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