7515f1169f8b34e8ad2a127dc434fc94f4635bf2
[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                                 }
171                                 cptr->c_text = add (tmpbuf, cp);
172                             }
173                             while (state == FLDPLUS) {
174                                 state = m_getfld (state, name, tmpbuf,
175                                                   SBUFSIZ, inb);
176                                 cptr->c_text = add (tmpbuf, cptr->c_text);
177                                 char_read += msg_count;
178                             }
179                             break;
180                         }
181                     } while ((cptr = cptr->c_next));
182
183                 while (state == FLDPLUS)
184                     state = m_getfld (state, name, tmpbuf, SBUFSIZ, inb);
185                 break;
186
187             case LENERR: 
188             case FMTERR: 
189             case BODY: 
190             case FILEEOF:
191                 goto finished;
192
193             default: 
194                 adios (NULL, "m_getfld() returned %d", state);
195         }
196     }
197
198     /*
199      * format and output the header lines.
200      */
201 finished:
202
203     /*
204      * if there's a "Subject" component, strip any "Re:"s off it
205      */
206     FINDCOMP (cptr, "subject")
207     if (cptr && (cp = cptr->c_text)) {
208         register char *sp = cp;
209
210         for (;;) {
211             while (isspace(*cp))
212                 cp++;
213             if(uprf(cp, "re:"))
214                 cp += 3;
215             else
216                 break;
217             sp = cp;
218         }
219         if (sp != cptr->c_text) {
220             cp = cptr->c_text;
221             cptr->c_text = getcpy (sp);
222             free (cp);
223         }
224     }
225     i = format_len + char_read + 256;
226     scanl = malloc ((size_t) i + 2);
227     dat[0] = 0;
228     dat[1] = 0;
229     dat[2] = 0;
230     dat[3] = outputlinelen;
231     dat[4] = 0;
232     fmt_scan (fmt, scanl, i, dat);
233     fputs (scanl, out);
234     if (badaddrs) {
235         fputs ("\nrepl: bad addresses:\n", out);
236         fputs ( badaddrs, out);
237     }
238
239     /*
240      * Check if we should filter the message
241      * or add mhn directives
242      */
243     if (filter) {
244         replfilter (inb, out, filter);
245     } else if (mime && mp) {
246             fprintf (out, "#forw [original message] +%s %s\n",
247                      mp->foldpath, m_name (mp->lowsel));
248     }
249
250     if (ferror (out))
251         adios (drft, "error writing");
252     fclose (out);
253
254     /* return dynamically allocated buffers */
255     free (scanl);
256     for (nxtbuf = compbuffers, i = ncomps; (cptr = *savecomp++); nxtbuf++, i--)
257         free (cptr->c_text);    /* if not nxtbuf, nxtbuf already freed */
258     while ( i-- > 0)
259         free (*nxtbuf++);       /* free unused nxtbufs */
260     free ((char *) compbuffers);
261     free ((char *) used_buf);
262 }
263
264 static char *buf;               /* our current working buffer */
265 static char *bufend;            /* end of working buffer */
266 static char *last_dst;          /* buf ptr at end of last call */
267 static unsigned int bufsiz=0;   /* current size of buf */
268
269 #define BUFINCR 512             /* how much to expand buf when if fills */
270
271 #define CPY(s) { cp = (s); while ((*dst++ = *cp++)) ; --dst; }
272
273 /*
274  * check if there's enough room in buf for str.
275  * add more mem if needed
276  */
277 #define CHECKMEM(str) \
278             if ((len = strlen (str)) >= bufend - dst) {\
279                 int i = dst - buf;\
280                 int n = last_dst - buf;\
281                 bufsiz += ((dst + len - bufend) / BUFINCR + 1) * BUFINCR;\
282                 buf = realloc (buf, bufsiz);\
283                 dst = buf + i;\
284                 last_dst = buf + n;\
285                 if (! buf)\
286                     adios (NULL, "formataddr: couldn't get buffer space");\
287                 bufend = buf + bufsiz;\
288             }
289
290
291 /*
292  * fmt_scan will call this routine if the user includes the function
293  * "(formataddr {component})" in a format string.  "orig" is the
294  * original contents of the string register.  "str" is the address
295  * string to be formatted and concatenated onto orig.  This routine
296  * returns a pointer to the concatenated address string.
297  *
298  * We try to not do a lot of malloc/copy/free's (which is why we
299  * don't call "getcpy") but still place no upper limit on the
300  * length of the result string.
301  */
302 char *
303 formataddr (char *orig, char *str)
304 {
305     register int len;
306     char baddr[BUFSIZ], error[BUFSIZ];
307     register int isgroup;
308     register char *dst;
309     register char *cp;
310     register char *sp;
311     register struct mailname *mp = NULL;
312
313     /* if we don't have a buffer yet, get one */
314     if (bufsiz == 0) {
315         buf = malloc (BUFINCR);
316         if (! buf)
317             adios (NULL, "formataddr: couldn't allocate buffer space");
318         last_dst = buf;         /* XXX */
319         bufsiz = BUFINCR - 6;  /* leave some slop */
320         bufend = buf + bufsiz;
321     }
322     /*
323      * If "orig" points to our buffer we can just pick up where we
324      * left off.  Otherwise we have to copy orig into our buffer.
325      */
326     if (orig == buf)
327         dst = last_dst;
328     else if (!orig || !*orig) {
329         dst = buf;
330         *dst = '\0';
331     } else {
332         dst = last_dst;         /* XXX */
333         CHECKMEM (orig);
334         CPY (orig);
335     }
336
337     /* concatenate all the new addresses onto 'buf' */
338     for (isgroup = 0; (cp = getname (str)); ) {
339         if ((mp = getm (cp, dfhost, dftype, AD_NAME, error)) == NULL) {
340             snprintf (baddr, sizeof(baddr), "\t%s -- %s\n", cp, error);
341             badaddrs = add (baddr, badaddrs);
342             continue;
343         }
344         if (isgroup && (mp->m_gname || !mp->m_ingrp)) {
345             *dst++ = ';';
346             isgroup = 0;
347         }
348         if (insert (mp)) {
349             /* if we get here we're going to add an address */
350             if (dst != buf) {
351                 *dst++ = ',';
352                 *dst++ = ' ';
353             }
354             if (mp->m_gname) {
355                 CHECKMEM (mp->m_gname);
356                 CPY (mp->m_gname);
357                 isgroup++;
358             }
359             sp = adrformat (mp);
360             CHECKMEM (sp);
361             CPY (sp);
362         }
363     }
364
365     if (isgroup)
366         *dst++ = ';';
367
368     *dst = '\0';
369     last_dst = dst;
370     return (buf);
371 }
372
373
374 static int
375 insert (struct mailname *np)
376 {
377     char buffer[BUFSIZ];
378     register struct mailname *mp;
379
380     if (np->m_mbox == NULL)
381         return 0;
382
383     for (mp = &mq; mp->m_next; mp = mp->m_next) {
384         if (!strcasecmp (np->m_host, mp->m_next->m_host)
385                 && !strcasecmp (np->m_mbox, mp->m_next->m_mbox))
386             return 0;
387     }
388     if (!ccme && ismymbox (np))
389         return 0;
390
391     if (querysw) {
392         snprintf (buffer, sizeof(buffer), "Reply to %s? ", adrformat (np));
393         if (!gans (buffer, anoyes))
394         return 0;
395     }
396     mp->m_next = np;
397
398 #ifdef ISI
399     if (ismymbox (np))
400         ccme = 0;
401 #endif
402
403     return 1;
404 }
405
406
407 /*
408  * Call the mhlproc
409  */
410
411 static void
412 replfilter (FILE *in, FILE *out, char *filter)
413 {
414     int pid;
415     char *mhl;
416
417     if (filter == NULL)
418         return;
419
420     if (access (filter, R_OK) == NOTOK)
421         adios (filter, "unable to read");
422
423     mhl = r1bindex (mhlproc, '/');
424
425     rewind (in);
426     lseek (fileno(in), (off_t) 0, SEEK_SET);
427     fflush (out);
428
429     switch (pid = vfork ()) {
430         case NOTOK: 
431             adios ("fork", "unable to");
432
433         case OK: 
434             dup2 (fileno (in), fileno (stdin));
435             dup2 (fileno (out), fileno (stdout));
436             closefds (3);
437
438             execlp (mhlproc, mhl, "-form", filter, "-noclear", NULL);
439             fprintf (stderr, "unable to exec ");
440             perror (mhlproc);
441             _exit (-1);
442
443         default: 
444             if (pidXwait (pid, mhl))
445                 done (1);
446             fseek (out, 0L, SEEK_END);
447             break;
448     }
449 }