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