Added argument to fmt_scan() to specify the buffer size.
[mmh] / uip / replsbr.c
1
2 /*
3  * replsbr.c -- routines to help repl 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/utils.h>
14 #include <sys/file.h>           /* L_SET */
15 #include <errno.h>
16
17 extern short ccto;              /* from repl.c */
18 extern short cccc;
19 extern short ccme;
20 extern short querysw;
21
22 static int dftype=0;
23
24 static char *badaddrs = NULL;
25 static char *dfhost = NULL;
26
27 static struct mailname mq;
28 static int nodupcheck = 0;              /* If set, no check for duplicates */
29
30 /*
31  * Buffer size for content part of header fields.
32  * We want this to be large enough so that we don't
33  * do a lot of extra FLDPLUS calls on m_getfld but
34  * small enough so that we don't snarf the entire
35  * message body when we're not going to use any of it.
36  */
37 #define SBUFSIZ 256             
38
39 static struct format *fmt;
40
41 static int ncomps = 0;                  /* # of interesting components */
42 static char **compbuffers = NULL;       /* buffers for component text */
43 static struct comp **used_buf = NULL;   /* stack for comp that use buffers */
44
45 static int dat[5];                      /* aux. data for format routine */
46
47 static char *addrcomps[] = {
48     "from",
49     "sender",
50     "reply-to",
51     "to",
52     "cc",
53     "bcc",
54     "resent-from",
55     "resent-sender",
56     "resent-reply-to",
57     "resent-to",
58     "resent-cc",
59     "resent-bcc",
60     NULL
61 };
62
63 /*
64  * static prototypes
65  */
66 static int insert (struct mailname *);
67 static void replfilter (FILE *, FILE *, char *, int);
68
69
70 void
71 replout (FILE *inb, char *msg, char *drft, struct msgs *mp, int outputlinelen,
72         int mime, char *form, char *filter, char *fcc, int fmtproc)
73 {
74     register int state, i;
75     register struct comp *cptr;
76     register char *tmpbuf;
77     register char **nxtbuf;
78     register char **ap;
79     register struct comp **savecomp;
80     int char_read = 0, format_len, mask;
81     char name[NAMESZ], *scanl;
82     unsigned char *cp;
83     FILE *out;
84     NMH_UNUSED (msg);
85
86     mask = umask(~m_gmprot());
87     if ((out = fopen (drft, "w")) == NULL)
88         adios (drft, "unable to create");
89
90     umask(mask);
91
92     /* get new format string */
93     cp = new_fs (form, NULL, NULL);
94     format_len = strlen (cp);
95
96     /* compile format string */
97     ncomps = fmt_compile (cp, &fmt) + 1;
98
99     if (!(nxtbuf = compbuffers = (char **)
100             calloc((size_t) ncomps, sizeof(char *))))
101         adios (NULL, "unable to allocate component buffers");
102     if (!(savecomp = used_buf = (struct comp **)
103             calloc((size_t) (ncomps+1), sizeof(struct comp *))))
104         adios (NULL, "unable to allocate component buffer stack");
105     savecomp += ncomps + 1;
106     *--savecomp = NULL;         /* point at zero'd end minus 1 */
107
108     for (i = ncomps; i--; )
109         *nxtbuf++ = mh_xmalloc(SBUFSIZ);
110
111     nxtbuf = compbuffers;               /* point at start */
112     tmpbuf = *nxtbuf++;
113
114     for (ap = addrcomps; *ap; ap++) {
115         FINDCOMP (cptr, *ap);
116         if (cptr)
117             cptr->c_type |= CT_ADDR;
118     }
119
120     /*
121      * ignore any components killed by command line switches
122      */
123     if (!ccto) {
124         FINDCOMP (cptr, "to");
125         if (cptr)
126             cptr->c_name = "";
127     }
128     if (!cccc) {
129         FINDCOMP (cptr, "cc");
130         if (cptr)
131             cptr->c_name = "";
132     }
133     /* set up the "fcc" pseudo-component */
134     if (fcc) {
135         FINDCOMP (cptr, "fcc");
136         if (cptr)
137             cptr->c_text = getcpy (fcc);
138     }
139     if ((cp = getenv("USER"))) {
140         FINDCOMP (cptr, "user");
141         if (cptr)
142             cptr->c_text = getcpy(cp);
143     }
144     if (!ccme)
145         ismymbox (NULL);
146
147     /*
148      * pick any interesting stuff out of msg "inb"
149      */
150     for (state = FLD;;) {
151         state = m_getfld (state, name, tmpbuf, SBUFSIZ, inb);
152         switch (state) {
153             case FLD: 
154             case FLDPLUS: 
155                 /*
156                  * if we're interested in this component, save a pointer
157                  * to the component text, then start using our next free
158                  * buffer as the component temp buffer (buffer switching
159                  * saves an extra copy of the component text).
160                  */
161                 if ((cptr = wantcomp[CHASH(name)]))
162                     do {
163                         if (!mh_strcasecmp(name, cptr->c_name)) {
164                             char_read += msg_count;
165                             if (! cptr->c_text) {
166                                 cptr->c_text = tmpbuf;
167                                 *--savecomp = cptr;
168                                 tmpbuf = *nxtbuf++;
169                             } else {
170                                 i = strlen (cp = cptr->c_text) - 1;
171                                 if (cp[i] == '\n') {
172                                     if (cptr->c_type & CT_ADDR) {
173                                         cp[i] = '\0';
174                                         cp = add (",\n\t", cp);
175                                     } else {
176                                         cp = add ("\t", cp);
177                                     }
178                                 }
179                                 cptr->c_text = add (tmpbuf, cp);
180                             }
181                             while (state == FLDPLUS) {
182                                 state = m_getfld (state, name, tmpbuf,
183                                                   SBUFSIZ, inb);
184                                 cptr->c_text = add (tmpbuf, cptr->c_text);
185                                 char_read += msg_count;
186                             }
187                             break;
188                         }
189                     } while ((cptr = cptr->c_next));
190
191                 while (state == FLDPLUS)
192                     state = m_getfld (state, name, tmpbuf, SBUFSIZ, inb);
193                 break;
194
195             case LENERR: 
196             case FMTERR: 
197             case BODY: 
198             case FILEEOF:
199                 goto finished;
200
201             default: 
202                 adios (NULL, "m_getfld() returned %d", state);
203         }
204     }
205
206     /*
207      * format and output the header lines.
208      */
209 finished:
210
211     /*
212      * if there's a "Subject" component, strip any "Re:"s off it
213      */
214     FINDCOMP (cptr, "subject")
215     if (cptr && (cp = cptr->c_text)) {
216         register char *sp = cp;
217
218         for (;;) {
219             while (isspace(*cp))
220                 cp++;
221             if(uprf(cp, "re:"))
222                 cp += 3;
223             else
224                 break;
225             sp = cp;
226         }
227         if (sp != cptr->c_text) {
228             cp = cptr->c_text;
229             cptr->c_text = getcpy (sp);
230             free (cp);
231         }
232     }
233     i = format_len + char_read + 256;
234     scanl = mh_xmalloc ((size_t) i + 2);
235     dat[0] = 0;
236     dat[1] = 0;
237     dat[2] = 0;
238     dat[3] = outputlinelen;
239     dat[4] = 0;
240     fmt_scan (fmt, scanl, i + 1, i, dat);
241     fputs (scanl, out);
242     if (badaddrs) {
243         fputs ("\nrepl: bad addresses:\n", out);
244         fputs ( badaddrs, out);
245     }
246
247     /*
248      * Check if we should filter the message
249      * or add mhn directives
250      */
251     if (filter) {
252         fflush(out);
253         if (ferror (out))
254             adios (drft, "error writing");
255         
256         replfilter (inb, out, filter, fmtproc);
257     } else if (mime && mp) {
258             fprintf (out, "#forw [original message] +%s %s\n",
259                      mp->foldpath, m_name (mp->lowsel));
260     }
261
262     fflush(out);
263     if (ferror (out))
264         adios (drft, "error writing");
265     fclose (out);
266
267     /* return dynamically allocated buffers */
268     free (scanl);
269     for (nxtbuf = compbuffers, i = ncomps; (cptr = *savecomp++); nxtbuf++, i--)
270         free (cptr->c_text);    /* if not nxtbuf, nxtbuf already freed */
271     while ( i-- > 0)
272         free (*nxtbuf++);       /* free unused nxtbufs */
273     free ((char *) compbuffers);
274     free ((char *) used_buf);
275 }
276
277 static char *buf;               /* our current working buffer */
278 static char *bufend;            /* end of working buffer */
279 static char *last_dst;          /* buf ptr at end of last call */
280 static unsigned int bufsiz=0;   /* current size of buf */
281
282 #define BUFINCR 512             /* how much to expand buf when if fills */
283
284 #define CPY(s) { cp = (s); while ((*dst++ = *cp++)) ; --dst; }
285
286 /*
287  * check if there's enough room in buf for str.
288  * add more mem if needed
289  */
290 #define CHECKMEM(str) \
291             if ((len = strlen (str)) >= bufend - dst) {\
292                 int i = dst - buf;\
293                 int n = last_dst - buf;\
294                 bufsiz += ((dst + len - bufend) / BUFINCR + 1) * BUFINCR;\
295                 buf = mh_xrealloc (buf, bufsiz);\
296                 dst = buf + i;\
297                 last_dst = buf + n;\
298                 bufend = buf + bufsiz;\
299             }
300
301
302 /*
303  * fmt_scan will call this routine if the user includes the function
304  * "(formataddr {component})" in a format string.  "orig" is the
305  * original contents of the string register.  "str" is the address
306  * string to be formatted and concatenated onto orig.  This routine
307  * returns a pointer to the concatenated address string.
308  *
309  * We try to not do a lot of malloc/copy/free's (which is why we
310  * don't call "getcpy") but still place no upper limit on the
311  * length of the result string.
312  */
313 char *
314 formataddr (char *orig, char *str)
315 {
316     register int len;
317     char baddr[BUFSIZ], error[BUFSIZ];
318     register int isgroup;
319     register char *dst;
320     register char *cp;
321     register char *sp;
322     register struct mailname *mp = NULL;
323
324     /* if we don't have a buffer yet, get one */
325     if (bufsiz == 0) {
326         buf = mh_xmalloc (BUFINCR);
327         last_dst = buf;         /* XXX */
328         bufsiz = BUFINCR - 6;  /* leave some slop */
329         bufend = buf + bufsiz;
330     }
331     /*
332      * If "orig" points to our buffer we can just pick up where we
333      * left off.  Otherwise we have to copy orig into our buffer.
334      */
335     if (orig == buf)
336         dst = last_dst;
337     else if (!orig || !*orig) {
338         dst = buf;
339         *dst = '\0';
340     } else {
341         dst = last_dst;         /* XXX */
342         CHECKMEM (orig);
343         CPY (orig);
344     }
345
346     /* concatenate all the new addresses onto 'buf' */
347     for (isgroup = 0; (cp = getname (str)); ) {
348         if ((mp = getm (cp, dfhost, dftype, AD_NAME, error)) == NULL) {
349             snprintf (baddr, sizeof(baddr), "\t%s -- %s\n", cp, error);
350             badaddrs = add (baddr, badaddrs);
351             continue;
352         }
353         if (isgroup && (mp->m_gname || !mp->m_ingrp)) {
354             *dst++ = ';';
355             isgroup = 0;
356         }
357         if (insert (mp)) {
358             /* if we get here we're going to add an address */
359             if (dst != buf) {
360                 *dst++ = ',';
361                 *dst++ = ' ';
362             }
363             if (mp->m_gname) {
364                 CHECKMEM (mp->m_gname);
365                 CPY (mp->m_gname);
366                 isgroup++;
367             }
368             sp = adrformat (mp);
369             CHECKMEM (sp);
370             CPY (sp);
371         }
372     }
373
374     if (isgroup)
375         *dst++ = ';';
376
377     *dst = '\0';
378     last_dst = dst;
379     return (buf);
380 }
381
382
383 /*
384  * fmt_scan will call this routine if the user includes the function
385  * "(concataddr {component})" in a format string.  This behaves exactly
386  * like formataddr, except that it does NOT suppress duplicate addresses
387  * between calls.
388  *
389  * As an implementation detail: I thought about splitting out formataddr()
390  * into the generic part and duplicate-suppressing part, but the call to
391  * insert() was buried deep within a couple of loops and I didn't see a
392  * way to do it easily.  So instead we simply set a special flag to stop
393  * the duplicate check and call formataddr().
394  */
395 char *
396 concataddr(char *orig, char *str)
397 {
398     char *cp;
399
400     nodupcheck = 1;
401     cp = formataddr(orig, str);
402     nodupcheck = 0;
403     return cp;
404 }
405
406 static int
407 insert (struct mailname *np)
408 {
409     char buffer[BUFSIZ];
410     register struct mailname *mp;
411
412     if (nodupcheck)
413         return 1;
414
415     if (np->m_mbox == NULL)
416         return 0;
417
418     for (mp = &mq; mp->m_next; mp = mp->m_next) {
419         if (!mh_strcasecmp (np->m_host, mp->m_next->m_host)
420                 && !mh_strcasecmp (np->m_mbox, mp->m_next->m_mbox))
421             return 0;
422     }
423     if (!ccme && ismymbox (np))
424         return 0;
425
426     if (querysw) {
427         snprintf (buffer, sizeof(buffer), "Reply to %s? ", adrformat (np));
428         if (!gans (buffer, anoyes))
429         return 0;
430     }
431     mp->m_next = np;
432
433     return 1;
434 }
435
436
437 /*
438  * Call the mhlproc
439  *
440  * This function expects that argument out has been fflushed by the caller.
441  */
442
443 static void
444 replfilter (FILE *in, FILE *out, char *filter, int fmtproc)
445 {
446     int pid;
447     char *mhl;
448     char *errstr;
449     char *arglist[7];
450
451     if (filter == NULL)
452         return;
453
454     if (access (filter, R_OK) == NOTOK)
455         adios (filter, "unable to read");
456
457     mhl = r1bindex (mhlproc, '/');
458
459     rewind (in);
460     lseek (fileno(in), (off_t) 0, SEEK_SET);
461
462     switch (pid = vfork()) {
463         case NOTOK: 
464             adios ("fork", "unable to");
465
466         case OK: 
467             dup2 (fileno (in), fileno (stdin));
468             dup2 (fileno (out), fileno (stdout));
469             closefds (3);
470
471             arglist[0] = mhl;
472             arglist[1] = "-form";
473             arglist[2] = filter;
474             arglist[3] = "-noclear";
475
476             switch (fmtproc) {
477             case 1:
478                 arglist[4] = "-fmtproc";
479                 arglist[5] = formatproc;
480                 arglist[6] = NULL;
481                 break;
482             case 0:
483                 arglist[4] = "-nofmtproc";
484                 arglist[5] = NULL;
485                 break;
486             default:
487                 arglist[4] = NULL;
488             }
489
490             execvp (mhlproc, arglist);
491             errstr = strerror(errno);
492             write(2, "unable to exec ", 15);
493             write(2, mhlproc, strlen(mhlproc));
494             write(2, ": ", 2);
495             write(2, errstr, strlen(errstr));
496             write(2, "\n", 1);
497             _exit (-1);
498
499         default: 
500             if (pidXwait (pid, mhl))
501                 done (1);
502             fseek (out, 0L, SEEK_END);
503             break;
504     }
505 }