04dc21528d1af0aa77b8f104023f984cf46545e8
[mmh] / uip / scansbr.c
1
2 /*
3  * scansbr.c -- routines to help scan along...
4  *
5  * This code is Copyright (c) 2002, by the authors of nmh.  See the
6  * COPYRIGHT file in the root directory of the nmh distribution for
7  * complete copyright information.
8  */
9
10 #include <h/mh.h>
11 #include <h/addrsbr.h>
12 #include <h/fmt_scan.h>
13 #include <h/scansbr.h>
14 #include <h/tws.h>
15 #include <h/utils.h>
16
17 #ifdef _FSTDIO
18 # define _ptr _p                /* Gag    */
19 # define _cnt _w                /* Wretch */
20 #endif
21
22 #ifdef SCO_5_STDIO
23 # define _ptr  __ptr
24 # define _cnt  __cnt
25 # define _base __base
26 # define _filbuf(fp)  ((fp)->__cnt = 0, __filbuf(fp))
27 #endif
28
29 #define MAXSCANL 256            /* longest possible scan line */
30
31 /*
32  * Buffer size for content part of header fields.  We want this
33  * to be large enough so that we don't do a lot of extra FLDPLUS
34  * calls on m_getfld but small enough so that we don't snarf
35  * the entire message body when we're only going to display 30
36  * characters of it.
37  */
38 #define SBUFSIZ 512
39
40 static struct format *fmt;
41 #ifdef JLR
42 static struct format *fmt_top;
43 #endif /* JLR */
44
45 static struct comp *datecomp;           /* pntr to "date" comp             */
46 static struct comp *bodycomp;           /* pntr to "body" pseudo-comp      *
47                                          * (if referenced)                 */
48 static int ncomps = 0;                  /* # of interesting components     */
49 static char **compbuffers = 0;          /* buffers for component text      */
50 static struct comp **used_buf = 0;      /* stack for comp that use buffers */
51
52 static int dat[5];                      /* aux. data for format routine    */
53
54 char *scanl = 0;                        /* text of most recent scanline    */
55
56 #define DIEWRERR() adios (scnmsg, "write error on")
57
58 #define FPUTS(buf) {\
59                 if (mh_fputs(buf,scnout) == EOF)\
60                     DIEWRERR();\
61                 }
62
63 /*
64  * prototypes
65  */
66 int sc_width (void);                    /* from termsbr.c */
67 static int mh_fputs(char *, FILE *);
68
69 #ifdef MULTIBYTE_SUPPORT
70 #define SCAN_CHARWIDTH MB_CUR_MAX
71 #else
72 #define SCAN_CHARWIDTH 1
73 #endif
74
75 int
76 scan (FILE *inb, int innum, int outnum, char *nfs, int width, int curflg,
77       int unseen, char *folder, long size, int noisy)
78 {
79     int i, compnum, encrypted, state;
80     unsigned char *cp, *tmpbuf;
81     char **nxtbuf;
82     char *saved_c_text = NULL;
83     struct comp *cptr;
84     struct comp **savecomp;
85     char *scnmsg = NULL;
86     FILE *scnout = NULL;
87     char name[NAMESZ];
88     static int rlwidth, slwidth;
89
90 #ifdef RPATHS
91     char returnpath[BUFSIZ];
92     char deliverydate[BUFSIZ];
93 #endif
94
95     /* first-time only initialization */
96     if (!scanl) {
97         if (width == 0) {
98             if ((width = sc_width ()) < WIDTH/2)
99                 width = WIDTH/2;
100             else if (width > MAXSCANL)
101                 width = MAXSCANL;
102         }
103         dat[3] = slwidth = width;
104         scanl = (char *) mh_xmalloc((size_t) SCAN_CHARWIDTH * (slwidth + 2) );
105         if (outnum)
106             umask(~m_gmprot());
107
108         /* Compile format string */
109         ncomps = fmt_compile (nfs, &fmt) + 1;
110
111 #ifdef JLR
112         fmt_top = fmt;
113 #endif  /* JLR */
114         FINDCOMP(bodycomp, "body");
115         FINDCOMP(datecomp, "date");
116         FINDCOMP(cptr, "folder");
117         if (cptr && folder)
118             cptr->c_text = folder;
119         FINDCOMP(cptr, "encrypted");
120         if (!cptr)
121             if ((cptr = (struct comp *) calloc (1, sizeof(*cptr)))) {
122                 cptr->c_name = "encrypted";
123                 cptr->c_next = wantcomp[i = CHASH (cptr->c_name)];
124                 wantcomp[i] = cptr;
125                 ncomps++;
126         }
127         FINDCOMP (cptr, "dtimenow");
128         if (cptr)
129             cptr->c_text = getcpy(dtimenow (0));
130         nxtbuf = compbuffers = (char **) calloc((size_t) ncomps, sizeof(char *));
131         if (nxtbuf == NULL)
132             adios (NULL, "unable to allocate component buffers");
133         used_buf = (struct comp **) calloc((size_t) (ncomps+1),
134             sizeof(struct comp *));
135         if (used_buf == NULL)
136             adios (NULL, "unable to allocate component buffer stack");
137         used_buf += ncomps+1; *--used_buf = 0;
138         rlwidth = bodycomp && (width > SBUFSIZ) ? width : SBUFSIZ;
139         for (i = ncomps; i--; )
140             *nxtbuf++ = mh_xmalloc(rlwidth);
141     }
142
143     /*
144      * each-message initialization
145      */
146     nxtbuf = compbuffers;
147     savecomp = used_buf;
148     tmpbuf = *nxtbuf++;
149     dat[0] = innum ? innum : outnum;
150     dat[1] = curflg;
151     dat[4] = unseen;
152
153     /*
154      * Get the first field.  If the message is non-empty
155      * and we're doing an "inc", open the output file.
156      */
157     if ((state = m_getfld (FLD, name, tmpbuf, rlwidth, inb)) == FILEEOF) {
158         if (ferror(inb)) {
159             advise("read", "unable to"); /* "read error" */
160             return SCNFAT;
161         } else {
162             return SCNEOF;
163         }
164     }
165
166     if (outnum) {
167         if (outnum > 0) {
168             scnmsg = m_name (outnum);
169             if (*scnmsg == '?')         /* msg num out of range */
170                 return SCNNUM;
171         } else {
172             scnmsg = "/dev/null";
173         }
174         if ((scnout = fopen (scnmsg, "w")) == NULL)
175             adios (scnmsg, "unable to write");
176 #ifdef RPATHS
177         /*
178          * Add the Return-Path and Delivery-Date
179          * header fields to message.
180          */
181         if (get_returnpath (returnpath, sizeof(returnpath),
182                 deliverydate, sizeof(deliverydate))) {
183             FPUTS ("Return-Path: ");
184             FPUTS (returnpath);
185             FPUTS ("Delivery-Date: ");
186             FPUTS (deliverydate);
187         }
188 #endif /* RPATHS */
189     }
190
191     /* scan - main loop */
192     for (compnum = 1; ; state = m_getfld (state, name, tmpbuf, rlwidth, inb)) {
193         switch (state) {
194             case FLD: 
195             case FLDPLUS: 
196                 compnum++;
197                 if (outnum) {
198                     FPUTS (name);
199                     if ( putc (':', scnout) == EOF) DIEWRERR();
200                     FPUTS (tmpbuf);
201                 }
202                 /*
203                  * if we're interested in this component, save a pointer
204                  * to the component text, then start using our next free
205                  * buffer as the component temp buffer (buffer switching
206                  * saves an extra copy of the component text).
207                  */
208                 if ((cptr = wantcomp[CHASH(name)])) {
209                     do {
210                         if (!mh_strcasecmp(name, cptr->c_name)) {
211                             if (! cptr->c_text) {
212                                 cptr->c_text = tmpbuf;
213                                 for (cp = tmpbuf + strlen (tmpbuf) - 1; 
214                                         cp >= tmpbuf; cp--)
215                                     if (isspace (*cp))
216                                         *cp = 0;
217                                     else
218                                         break;
219                                 *--savecomp = cptr;
220                                 tmpbuf = *nxtbuf++;
221                             }
222                             break;
223                         }
224                     } while ((cptr = cptr->c_next));
225                 }
226
227                 while (state == FLDPLUS) {
228                     state = m_getfld (state, name, tmpbuf, rlwidth, inb);
229                     if (outnum)
230                         FPUTS (tmpbuf);
231                 }
232                 break;
233
234             case BODY: 
235                 compnum = -1;
236                 if (! outnum) {
237                     state = FILEEOF; /* stop now if scan cmd */
238                     goto finished;
239                 }
240                 if (putc ('\n', scnout) == EOF) DIEWRERR();
241                 FPUTS (tmpbuf);
242                 /*
243                  * performance hack: some people like to run "inc" on
244                  * things like net.sources or large digests.  We do a
245                  * copy directly into the output buffer rather than
246                  * going through an intermediate buffer.
247                  *
248                  * We need the amount of data m_getfld found & don't
249                  * want to do a strlen on the long buffer so there's
250                  * a hack in m_getfld to save the amount of data it
251                  * returned in the global "msg_count".
252                  */
253 body:;
254                 while (state == BODY) {
255 #ifdef LINUX_STDIO
256                     if (scnout->_IO_write_ptr == scnout->_IO_write_end) {
257 #elif defined(__DragonFly__)
258                     if (((struct __FILE_public *)scnout)->_w <= 0) {
259 #else
260                     if (scnout->_cnt <= 0) {
261 #endif
262                         if (fflush(scnout) == EOF)
263                             DIEWRERR ();
264                     }
265 #ifdef LINUX_STDIO
266                     state = m_getfld(state, name, scnout->_IO_write_ptr,
267                         (long)scnout->_IO_write_ptr-(long)scnout->_IO_write_end , inb);
268                     scnout->_IO_write_ptr += msg_count;
269 #elif defined(__DragonFly__)
270                     state = m_getfld( state, name, ((struct __FILE_public *)scnout)->_p, -(((struct __FILE_public *)scnout)->_w), inb );
271                     ((struct __FILE_public *)scnout)->_w -= msg_count;
272                     ((struct __FILE_public *)scnout)->_p += msg_count;
273 #else
274                     state = m_getfld( state, name, scnout->_ptr, -(scnout->_cnt), inb );
275                     scnout->_cnt -= msg_count;
276                     scnout->_ptr += msg_count;
277 #endif
278                 }
279                 goto finished;
280
281             case LENERR: 
282             case FMTERR: 
283                 fprintf (stderr, 
284                         innum ? "??Format error (message %d) in "
285                               : "??Format error in ",
286                         outnum ? outnum : innum);
287                 fprintf (stderr, "component %d\n", compnum);
288
289                 if (outnum) {
290                     FPUTS ("\n\nBAD MSG:\n");
291                     FPUTS (name);
292                     if (putc ('\n', scnout) == EOF) DIEWRERR();
293                     state = BODY;
294                     goto body;
295                 }
296                 /* fall through */
297
298             case FILEEOF:
299                 goto finished;
300
301             default: 
302                 adios (NULL, "getfld() returned %d", state);
303         }
304     }
305
306     /*
307      * format and output the scan line.
308      */
309 finished:
310     if (ferror(inb)) {
311         advise("read", "unable to"); /* "read error" */
312         return SCNFAT;
313     }
314
315     /* Save and restore buffer so we don't trash our dynamic pool! */
316     if (bodycomp) {
317         saved_c_text = bodycomp->c_text;
318         bodycomp->c_text = tmpbuf;
319     }
320
321     if (size)
322         dat[2] = size;
323     else if (outnum > 0)
324     {
325         dat[2] = ftell(scnout);
326         if (dat[2] == EOF) DIEWRERR();
327     }
328
329     if ((datecomp && !datecomp->c_text) || (!size && !outnum)) {
330         struct stat st;
331
332         fstat (fileno(inb), &st);
333         if (!size && !outnum)
334             dat[2] = st.st_size;
335         if (datecomp) {
336             if (! datecomp->c_text) {
337                 if (datecomp->c_tws == NULL)
338                     datecomp->c_tws = (struct tws *)
339                         calloc((size_t) 1, sizeof(*datecomp->c_tws));
340                 if (datecomp->c_tws == NULL)
341                     adios (NULL, "unable to allocate tws buffer");
342                 *datecomp->c_tws = *dlocaltime ((time_t *) &st.st_mtime);
343                 datecomp->c_flags |= CF_DATEFAB|CF_TRUE;
344             } else {
345                 datecomp->c_flags &= ~CF_DATEFAB;
346             }
347         }
348     }
349
350     fmt_scan (fmt, scanl, slwidth, dat);
351
352 #if 0
353     fmt = fmt_scan (fmt, scanl, slwidth, dat);
354     if (!fmt)
355         fmt = fmt_top;          /* reset for old format files */
356 #endif
357
358     if (bodycomp)
359         bodycomp->c_text = saved_c_text;
360
361     if (noisy)
362         fputs (scanl, stdout);
363
364     FINDCOMP (cptr, "encrypted");
365     encrypted = cptr && cptr->c_text;
366
367     /* return dynamically allocated buffers to pool */
368     while ((cptr = *savecomp++)) {
369         *--nxtbuf = cptr->c_text;
370         cptr->c_text = NULL;
371     }
372     *--nxtbuf = tmpbuf;
373
374     if (outnum && (ferror(scnout) || fclose (scnout) == EOF))
375         DIEWRERR();
376
377     return (state != FILEEOF ? SCNERR : encrypted ? SCNENC : SCNMSG);
378 }
379
380
381 /*
382  * Cheat:  we are loaded with adrparse, which wants a routine called
383  * OfficialName().  We call adrparse:getm() with the correct arguments
384  * to prevent OfficialName() from being called.  Hence, the following
385  * is to keep the loader happy.
386  */
387 char *
388 OfficialName (char *name)
389 {
390     return name;
391 }
392
393
394 static int
395 mh_fputs(char *s, FILE *stream)
396 {
397     char c;
398
399     while ((c = *s++)) 
400         if (putc (c,stream) == EOF )
401             return(EOF);
402     return (0);
403 }
404