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