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