chiark / gitweb /
REORG remove old/ directory
[inn-innduct.git] / infile.c
1 /*
2  *  innduct
3  *  tailing reliable realtime streaming feeder for inn
4  *  infile.c - monitoring and handling of input files
5  *
6  *  Copyright (C) 2010 Ian Jackson <ijackson@chiark.greenend.org.uk>
7  * 
8  *  This program is free software: you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation, either version 3 of the License, or
11  *  (at your option) any later version.
12  * 
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  * 
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  *
21  *  (I believe that when you compile and link this as part of the inn2
22  *  build, with the Makefile runes I have provided, all the libraries
23  *  and files which end up included in innduct are licence-compatible
24  *  with GPLv3.  If not then please let me know.  -Ian Jackson.)
25  */
26
27 #include "innduct.h"
28
29 /*========== monitoring of input files ==========*/
30
31 static void feedfile_eof(InputFile *ipf) {
32   assert(ipf != main_input_file); /* promised by tailing_try_read */
33   inputfile_reading_stop(ipf);
34
35   if (ipf == flushing_input_file) {
36     assert(sms==sm_SEPARATED || sms==sm_DROPPING);
37     if (main_input_file) inputfile_reading_start(main_input_file);
38     statemc_check_flushing_done();
39   } else if (ipf == backlog_input_file) {
40     statemc_check_backlog_done();
41   } else {
42     abort(); /* supposed to wait rather than get EOF on main input file */
43   }
44 }
45
46 InputFile *open_input_file(const char *path) {
47   int fd= open(path, O_RDWR);
48   if (fd<0) {
49     if (errno==ENOENT) return 0;
50     sysdie("unable to open input file %s", path);
51   }
52   assert(fd>0);
53
54   InputFile *ipf= xmalloc(sizeof(*ipf) + strlen(path) + 1);
55   memset(ipf,0,sizeof(*ipf));
56
57   ipf->fd= fd;
58   ipf->autodefer= -1;
59   LIST_INIT(ipf->queue);
60   strcpy(ipf->path, path);
61
62   return ipf;
63 }
64
65 void close_input_file(InputFile *ipf) { /* does not free */
66   assert(!ipf->readable_callback); /* must have had ->on_cancel */
67   assert(!ipf->filemon); /* must have had inputfile_reading_stop */
68   assert(!ipf->rd); /* must have had inputfile_reading_stop */
69   assert(!ipf->inprogress); /* no dangling pointers pointing here */
70   xclose_perhaps(&ipf->fd, "input file ", ipf->path);
71 }
72
73
74 /*---------- dealing with articles read in the input file ----------*/
75
76 static void *feedfile_got_bad_data(InputFile *ipf, off_t offset,
77                                    const char *data, const char *how) {
78   warn("corrupted file: %s, offset %lu: %s: in %s",
79        ipf->path, (unsigned long)offset, how, sanitise(data,-1));
80   ipf->readcount_err++;
81   if (ipf->readcount_err > max_bad_data_initial +
82       (ipf->readcount_ok+ipf->readcount_blank) / max_bad_data_ratio)
83     crash("too much garbage in input file!  (%d errs, %d ok, %d blank)",
84           ipf->readcount_err, ipf->readcount_ok, ipf->readcount_blank);
85   return OOP_CONTINUE;
86 }
87
88 static void *feedfile_read_err(oop_source *lp, oop_read *rd,
89                                oop_rd_event ev, const char *errmsg,
90                                int errnoval, const char *data, size_t recsz,
91                                void *ipf_v) {
92   InputFile *ipf= ipf_v;
93   assert(ev == OOP_RD_SYSTEM);
94   errno= errnoval;
95   syscrash("error reading input file: %s, offset %lu",
96            ipf->path, (unsigned long)ipf->offset);
97 }
98
99 static void *feedfile_got_article(oop_source *lp, oop_read *rd,
100                                   oop_rd_event ev, const char *errmsg,
101                                   int errnoval, const char *data, size_t recsz,
102                                   void *ipf_v) {
103   InputFile *ipf= ipf_v;
104   Article *art;
105   char tokentextbuf[sizeof(TOKEN)*2+3];
106
107   if (!data) { feedfile_eof(ipf); return OOP_CONTINUE; }
108
109   off_t old_offset= ipf->offset;
110   ipf->offset += recsz + !!(ev == OOP_RD_OK);
111
112 #define X_BAD_DATA(m) return feedfile_got_bad_data(ipf,old_offset,data,m);
113
114   if (ev==OOP_RD_PARTREC)
115     feedfile_got_bad_data(ipf,old_offset,data,"missing final newline");
116     /* but process it anyway */
117
118   if (ipf->skippinglong) {
119     if (ev==OOP_RD_OK) ipf->skippinglong= 0; /* fine now */
120     return OOP_CONTINUE;
121   }
122   if (ev==OOP_RD_LONG) {
123     ipf->skippinglong= 1;
124     X_BAD_DATA("overly long line");
125   }
126
127   if (memchr(data,'\0',recsz)) X_BAD_DATA("nul byte");
128   if (!recsz) X_BAD_DATA("empty line");
129
130   if (data[0]==' ') {
131     if (strspn(data," ") != recsz) X_BAD_DATA("line partially blanked");
132     ipf->readcount_blank++;
133     return OOP_CONTINUE;
134   }
135
136   char *space= strchr(data,' ');
137   int tokenlen= space-data;
138   int midlen= (int)recsz-tokenlen-1;
139   if (midlen <= 2) X_BAD_DATA("no room for messageid");
140   if (space[1]!='<' || space[midlen]!='>') X_BAD_DATA("invalid messageid");
141
142   if (tokenlen != sizeof(TOKEN)*2+2) X_BAD_DATA("token wrong length");
143   memcpy(tokentextbuf, data, tokenlen);
144   tokentextbuf[tokenlen]= 0;
145   if (!IsToken(tokentextbuf)) X_BAD_DATA("token wrong syntax");
146
147   ipf->readcount_ok++;
148
149   art= xmalloc(sizeof(*art) - 1 + midlen + 1);
150   memset(art,0,sizeof(*art));
151   art->state= art_Unchecked;
152   art->midlen= midlen;
153   art->ipf= ipf;  ipf->inprogress++;
154   art->token= TextToToken(tokentextbuf);
155   art->offset= old_offset;
156   art->blanklen= recsz;
157   strcpy(art->messageid, space+1);
158
159   if (ipf->autodefer >= 0) {
160     article_autodefer(ipf, art);
161   } else {
162     LIST_ADDTAIL(ipf->queue, art);
163
164     if (ipf==backlog_input_file)
165       article_check_expired(art);
166   }
167
168   if (sms==sm_NORMAL && ipf==main_input_file &&
169       ipf->offset >= target_max_feedfile_size)
170     statemc_start_flush("feed file size");
171
172   check_assign_articles(); /* may destroy conn but that's OK */
173   check_reading_pause_resume(ipf);
174   return OOP_CONTINUE;
175 }
176
177 /*========== tailing input file ==========*/
178
179 static void *tailing_rable_call_time(oop_source *lp, struct timeval tv,
180                                      void *user) {
181   /* lifetime of ipf here is OK because destruction will cause
182    * on_cancel which will cancel this callback */
183   InputFile *ipf= user;
184
185   dbg("**TRACT** ipf=%p called",ipf);
186   if (!ipf->fake_readable) return OOP_CONTINUE;
187
188   /* we just keep calling readable until our caller (oop_rd)
189    * has called try_read, and try_read has found EOF so given EAGAIN */
190   dbg("**TRACT** ipf=%p reschedule",ipf);
191   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
192
193   return ipf->readable_callback(loop, &ipf->readable,
194                                 ipf->readable_callback_user);
195 }
196
197 static void tailing_on_cancel(struct oop_readable *rable) {
198   InputFile *ipf= (void*)rable;
199   dbg("**TOR** ipf=%p on_cancel",ipf);
200
201   if (ipf->filemon) filemon_stop(ipf);
202   dbg("**TRACT** ipf=%p cancel",ipf);
203   loop->cancel_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
204   ipf->readable_callback= 0;
205 }
206
207 void tailing_make_readable(InputFile *ipf) {
208   dbg("**TRACT** ipf=%p makereadable rcb=%p",ipf,
209       (void*)ipf?ipf->readable_callback:0);
210   if (!ipf || !ipf->readable_callback) /* so callers can be naive */
211     return;
212   ipf->fake_readable= 1;
213   loop->on_time(loop, OOP_TIME_NOW, tailing_rable_call_time, ipf);
214 }
215
216 static int tailing_on_readable(struct oop_readable *rable,
217                                 oop_readable_call *cb, void *user) {
218   InputFile *ipf= (void*)rable;
219   dbg("**TOR** ipf=%p on_readable",ipf);
220
221   tailing_on_cancel(rable);
222   ipf->readable_callback= cb;
223   ipf->readable_callback_user= user;
224   filemon_start(ipf);
225   tailing_make_readable(ipf);
226   return 0;
227 }
228
229 static ssize_t tailing_try_read(struct oop_readable *rable, void *buffer,
230                                 size_t length) {
231   InputFile *ipf= (void*)rable;
232   for (;;) {
233     ssize_t r= read(ipf->fd, buffer, length);
234     if (r==-1) {
235       if (errno==EINTR) continue;
236       ipf->fake_readable= 0;
237       return r;
238     }
239     if (!r) {
240       if (ipf==main_input_file) {
241         errno=EAGAIN;
242         ipf->fake_readable= 0;
243         return -1;
244       } else if (ipf==flushing_input_file) {
245         assert(ipf->rd);
246         assert(sms==sm_SEPARATED || sms==sm_DROPPING);
247       } else if (ipf==backlog_input_file) {
248         assert(ipf->rd);
249       } else {
250         abort();
251       }
252     }
253     dbg("**TOR** ipf=%p try_read r=%d",ipf,r);
254     return r;
255   }
256 }
257
258 /*---------- interface to start and stop an input file ----------*/
259
260 static const oop_rd_style feedfile_rdstyle= {
261   OOP_RD_DELIM_STRIP, '\n',
262   OOP_RD_NUL_PERMIT,
263   OOP_RD_SHORTREC_LONG,
264 };
265
266 void inputfile_reading_resume(InputFile *ipf) {
267   if (!ipf->rd) return;
268   if (!ipf->paused) return;
269
270   int r= oop_rd_read(ipf->rd, &feedfile_rdstyle, MAX_LINE_FEEDFILE,
271                      feedfile_got_article,ipf, feedfile_read_err, ipf);
272   if (r) syscrash("unable start reading feedfile %s",ipf->path);
273
274   ipf->paused= 0;
275 }
276
277 void inputfile_reading_pause(InputFile *ipf) {
278   if (!ipf->rd) return;
279   if (ipf->paused) return;
280   oop_rd_cancel(ipf->rd);
281   ipf->paused= 1;
282 }
283
284 void inputfile_reading_start(InputFile *ipf) {
285   assert(!ipf->rd);
286   ipf->readable.on_readable= tailing_on_readable;
287   ipf->readable.on_cancel=   tailing_on_cancel;
288   ipf->readable.try_read=    tailing_try_read;
289   ipf->readable.delete_tidy= 0; /* we never call oop_rd_delete_{tidy,kill} */
290   ipf->readable.delete_kill= 0;
291
292   ipf->readable_callback= 0;
293   ipf->readable_callback_user= 0;
294
295   ipf->rd= oop_rd_new(loop, &ipf->readable, 0,0);
296   assert(ipf->rd);
297
298   ipf->paused= 1;
299   inputfile_reading_resume(ipf);
300 }
301
302 void inputfile_reading_stop(InputFile *ipf) {
303   assert(ipf->rd);
304   inputfile_reading_pause(ipf);
305   oop_rd_delete(ipf->rd);
306   ipf->rd= 0;
307   assert(!ipf->filemon); /* we shouldn't be monitoring it now */
308 }
309
310 void filepoll(void) {
311   tailing_make_readable(main_input_file);
312   tailing_make_readable(flushing_input_file);
313 }
314
315 char *dbg_report_ipf(InputFile *ipf) {
316   if (!ipf) return xasprintf("none");
317
318   const char *slash= strrchr(ipf->path,'/');
319   const char *path= slash ? slash+1 : ipf->path;
320
321   return xasprintf("%p/%s:queue=%d,ip=%ld,autodef=%ld,off=%ld,fd=%d%s%s%s",
322                    ipf, path,
323                    ipf->queue.count, ipf->inprogress, ipf->autodefer,
324                    (long)ipf->offset, ipf->fd,
325                    ipf->rd ? "" : ",!rd",
326                    ipf->skippinglong ? "*skiplong" : "",
327                    ipf->rd && ipf->paused ? "*paused" : "");
328 }