Removed personal flavor for ISI.
[mmh] / uip / repl.c
1 /*
2 ** repl.c -- reply to a message
3 **
4 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
5 ** COPYRIGHT file in the root directory of the nmh distribution for
6 ** complete copyright information.
7 */
8
9 #include <h/mh.h>
10 #include <h/utils.h>
11 #include <h/addrsbr.h>
12 #include <h/fmt_scan.h>
13 #include <sys/file.h>  /* L_SET */
14 #include <errno.h>
15
16
17 static struct swit switches[] = {
18 #define GROUPSW  0
19         { "group", 0 },
20 #define NGROUPSW  1
21         { "nogroup", 0 },
22 #define ANNOSW  2
23         { "annotate", 0 },
24 #define NANNOSW  3
25         { "noannotate", 0 },
26 #define CCSW  4
27         { "cc all|to|cc|me", 0 },
28 #define NCCSW  5
29         { "nocc type", 0 },
30 #define EDITRSW  6
31         { "editor editor", 0 },
32 #define NEDITSW  7
33         { "noedit", 0 },
34 #define FILTSW  8
35         { "filter filterfile", 0 },
36 #define NFILTSW  9
37         { "nofilter", 0 },
38 #define FORMSW  10
39         { "form formfile", 0 },
40 #define MIMESW  11
41         { "mime", 0 },
42 #define NMIMESW  12
43         { "nomime", 0 },
44 #define QURYSW  13
45         { "query", 0 },
46 #define NQURYSW  14
47         { "noquery", 0 },
48 #define WHATSW  15
49         { "whatnowproc program", 0 },
50 #define NWHATSW  16
51         { "nowhatnowproc", 0 },
52 #define VERSIONSW  17
53         { "version", 0 },
54 #define HELPSW  18
55         { "help", 0 },
56 #define FILESW  19
57         { "file file", 4 },  /* interface from msh */
58
59 #ifdef MHE
60 #define BILDSW  20
61         { "build", 5 },  /* interface from mhe */
62 #endif
63
64         { NULL, 0 }
65 };
66
67 static struct swit ccswitches[] = {
68 #define CTOSW  0
69         { "to", 0 },
70 #define CCCSW  1
71         { "cc", 0 },
72 #define CMESW  2
73         { "me", 0 },
74 #define CALSW  3
75         { "all", 0 },
76         { NULL, 0 }
77 };
78
79 /*
80 ** Buffer size for content part of header fields.
81 ** We want this to be large enough so that we don't
82 ** do a lot of extra FLDPLUS calls on m_getfld but
83 ** small enough so that we don't snarf the entire
84 ** message body when we're not going to use any of it.
85 */
86 #define SBUFSIZ 256
87
88 static short ccto = -1;
89 static short cccc = -1;
90 static short ccme = -1;
91 static short querysw = 0;
92
93 static short groupreply = 0;  /* Is this a group reply? */
94
95 static int mime = 0;  /* include original as MIME part */
96 static char *form   = NULL;  /* form (components) file */
97 static char *filter = NULL;  /* message filter file */
98
99 static int dftype=0;
100
101 static char *badaddrs = NULL;
102 static char *dfhost = NULL;
103
104 static struct mailname mq = { NULL };
105
106 static struct format *fmt;
107
108 static int ncomps = 0;  /* # of interesting components */
109 static char **compbuffers = NULL;  /* buffers for component text */
110 static struct comp **used_buf = NULL;  /* stack for comp that use buffers */
111
112 static int dat[5];  /* aux. data for format routine */
113
114 static char *addrcomps[] = {
115         "from",
116         "sender",
117         "reply-to",
118         "to",
119         "cc",
120         "bcc",
121         "resent-from",
122         "resent-sender",
123         "resent-reply-to",
124         "resent-to",
125         "resent-cc",
126         "resent-bcc",
127         NULL
128 };
129
130 /*
131 ** static prototypes
132 */
133 static void docc(char *, int);
134 static int insert(struct mailname *);
135 static void replfilter(FILE *, FILE *, char *);
136 static void replout(FILE *, char *, char *, struct msgs *, int,
137                 char *, char *);
138
139
140 int
141 main(int argc, char **argv)
142 {
143         int anot = 0;
144         int nedit = 0, nwhat = 0;
145         char *cp, *cwd, *maildir, *file = NULL;
146         char *folder = NULL, *msg = NULL;
147         char *ed = NULL, drft[BUFSIZ], buf[BUFSIZ];
148         char **argp, **arguments;
149         struct msgs *mp = NULL;
150         FILE *in;
151
152 #ifdef MHE
153         int buildsw = 0;
154 #endif /* MHE */
155
156         filter = getcpy(etcpath(mhlreply));
157
158 #ifdef LOCALE
159         setlocale(LC_ALL, "");
160 #endif
161         invo_name = mhbasename(argv[0]);
162
163         /* read user profile/context */
164         context_read();
165
166         arguments = getarguments(invo_name, argc, argv, 1);
167         argp = arguments;
168
169         while ((cp = *argp++)) {
170                 if (*cp == '-') {
171                         switch (smatch(++cp, switches)) {
172                         case AMBIGSW:
173                                 ambigsw(cp, switches);
174                                 done(1);
175                         case UNKWNSW:
176                                 adios(NULL, "-%s unknown", cp);
177
178                         case HELPSW:
179                                 snprintf(buf, sizeof(buf), "%s: [+folder] [msg] [switches]", invo_name);
180                                 print_help(buf, switches, 1);
181                                 done(0);
182                         case VERSIONSW:
183                                 print_version(invo_name);
184                                 done(1);
185
186                         case GROUPSW:
187                                 groupreply++;
188                                 continue;
189                         case NGROUPSW:
190                                 groupreply = 0;
191                                 continue;
192
193                         case ANNOSW:
194                                 anot++;
195                                 continue;
196                         case NANNOSW:
197                                 anot = 0;
198                                 continue;
199
200                         case CCSW:
201                                 if (!(cp = *argp++) || *cp == '-')
202                                         adios(NULL, "missing argument to %s",
203                                                         argp[-2]);
204                                 docc(cp, 1);
205                                 continue;
206                         case NCCSW:
207                                 if (!(cp = *argp++) || *cp == '-')
208                                         adios(NULL, "missing argument to %s",
209                                                         argp[-2]);
210                                 docc(cp, 0);
211                                 continue;
212
213                         case EDITRSW:
214                                 if (!(ed = *argp++) || *ed == '-')
215                                         adios(NULL, "missing argument to %s",
216                                                         argp[-2]);
217                                 nedit = 0;
218                                 continue;
219                         case NEDITSW:
220                                 nedit++;
221                                 continue;
222
223                         case WHATSW:
224                                 if (!(whatnowproc = *argp++) ||
225                                                 *whatnowproc == '-')
226                                         adios(NULL, "missing argument to %s",
227                                                         argp[-2]);
228                                 nwhat = 0;
229                                 continue;
230 #ifdef MHE
231                         case BILDSW:
232                                 buildsw++;  /* fall... */
233 #endif /* MHE */
234                         case NWHATSW:
235                                 nwhat++;
236                                 continue;
237
238                         case FILESW:
239                                 if (file)
240                                         adios(NULL, "only one file at a time!");
241                                 if (!(cp = *argp++) || *cp == '-')
242                                         adios(NULL, "missing argument to %s",
243                                                         argp[-2]);
244                                 file = getcpy(expanddir(cp));
245                                 continue;
246                         case FORMSW:
247                                 if (!(form = *argp++) || *form == '-')
248                                         adios(NULL, "missing argument to %s",
249                                                         argp[-2]);
250                                 continue;
251
252                         case FILTSW:
253                                 if (!(cp = *argp++) || *cp == '-')
254                                         adios(NULL, "missing argument to %s",
255                                                         argp[-2]);
256                                 filter = getcpy(etcpath(cp));
257                                 continue;
258                         case NFILTSW:
259                                 filter = NULL;
260                                 continue;
261
262                         case MIMESW:
263                                 mime++;
264                                 continue;
265                         case NMIMESW:
266                                 mime = 0;
267                                 continue;
268
269                         case QURYSW:
270                                 querysw++;
271                                 continue;
272                         case NQURYSW:
273                                 querysw = 0;
274                                 continue;
275
276                         }
277                 }
278                 if (*cp == '+' || *cp == '@') {
279                         if (folder)
280                                 adios(NULL, "only one folder at a time!");
281                         else
282                                 folder = getcpy(expandfol(cp));
283                 } else {
284                         if (msg)
285                                 adios(NULL, "only one message at a time!");
286                         else
287                                 msg = cp;
288                 }
289         }
290
291         if (ccto == -1)
292                 ccto = groupreply;
293         if (cccc == -1)
294                 cccc = groupreply;
295         if (ccme == -1)
296                 ccme = groupreply;
297
298         cwd = getcpy(pwd());
299
300         if (file && (msg || folder))
301                 adios(NULL, "can't mix files and folders/msgs");
302
303 #ifdef MHE
304         strncpy(drft, buildsw ? toabsdir("reply")
305                 : m_draft(seq_beyond), sizeof(drft));
306 #else
307         strncpy(drft, m_draft(seq_beyond), sizeof(drft));
308 #endif /* MHE */
309
310         if (file) {
311                 /*
312                 ** We are replying to a file.
313                 */
314                 anot = 0;  /* we don't want to annotate a file */
315         } else {
316                 /*
317                 ** We are replying to a message.
318                 */
319                 if (!msg)
320                         msg = seq_cur;
321                 if (!folder)
322                         folder = getcurfol();
323                 maildir = toabsdir(folder);
324
325                 if (chdir(maildir) == NOTOK)
326                         adios(maildir, "unable to change directory to");
327
328                 /* read folder and create message structure */
329                 if (!(mp = folder_read(folder)))
330                         adios(NULL, "unable to read folder %s", folder);
331
332                 /* check for empty folder */
333                 if (mp->nummsg == 0)
334                         adios(NULL, "no messages in %s", folder);
335
336                 /* parse the message range/sequence/name and set SELECTED */
337                 if (!m_convert(mp, msg))
338                         done(1);
339                 seq_setprev(mp);  /* set the previous-sequence */
340
341                 if (mp->numsel > 1)
342                         adios(NULL, "only one message at a time!");
343
344                 context_replace(curfolder, folder); /* update current folder */
345                 seq_setcur(mp, mp->lowsel);  /* update current message  */
346                 seq_save(mp);  /* synchronize sequences   */
347                 context_save();  /* save the context file   */
348         }
349
350         msg = file ? file : getcpy(m_name(mp->lowsel));
351
352         if ((in = fopen(msg, "r")) == NULL)
353                 adios(msg, "unable to open");
354
355         /* find form (components) file */
356         if (!form) {
357                 if (groupreply)
358                         form = etcpath(replgroupcomps);
359                 else
360                         form = etcpath(replcomps);
361         }
362
363         replout(in, msg, drft, mp, mime, form, filter);
364         fclose(in);
365
366         if (nwhat)
367                 done(0);
368         what_now(ed, nedit, NOUSE, drft, msg, 0, mp, anot ? "Replied" : NULL,
369                         cwd);
370         done(1);
371         return 1;
372 }
373
374 static void
375 docc(char *cp, int ccflag)
376 {
377         switch (smatch(cp, ccswitches)) {
378         case AMBIGSW:
379                 ambigsw(cp, ccswitches);
380                 done(1);
381         case UNKWNSW:
382                 adios(NULL, "-%scc %s unknown", ccflag ? "" : "no", cp);
383
384         case CTOSW:
385                 ccto = ccflag;
386                 break;
387
388         case CCCSW:
389                 cccc = ccflag;
390                 break;
391
392         case CMESW:
393                 ccme = ccflag;
394                 break;
395
396         case CALSW:
397                 ccto = cccc = ccme = ccflag;
398                 break;
399         }
400 }
401
402
403
404
405 static void
406 replout(FILE *inb, char *msg, char *drft, struct msgs *mp,
407         int mime, char *form, char *filter)
408 {
409         register int state, i;
410         register struct comp *cptr;
411         register char *tmpbuf;
412         register char **nxtbuf;
413         register char **ap;
414         register struct comp **savecomp;
415         int char_read = 0, format_len, mask;
416         char name[NAMESZ], *scanl;
417         unsigned char *cp;
418         FILE *out;
419
420         mask = umask(~m_gmprot());
421         if ((out = fopen(drft, "w")) == NULL)
422                 adios(drft, "unable to create");
423
424         umask(mask);
425
426         /* get new format string */
427         cp = new_fs(form, NULL);
428         format_len = strlen(cp);
429
430         /* compile format string */
431         ncomps = fmt_compile(cp, &fmt) + 1;
432
433         if (!(nxtbuf = compbuffers = (char **)
434                         calloc((size_t) ncomps, sizeof(char *))))
435                 adios(NULL, "unable to allocate component buffers");
436         if (!(savecomp = used_buf = (struct comp **)
437                         calloc((size_t) (ncomps+1), sizeof(struct comp *))))
438                 adios(NULL, "unable to allocate component buffer stack");
439         savecomp += ncomps + 1;
440         *--savecomp = NULL;  /* point at zero'd end minus 1 */
441
442         for (i = ncomps; i--; )
443                 *nxtbuf++ = mh_xmalloc(SBUFSIZ);
444
445         nxtbuf = compbuffers;  /* point at start */
446         tmpbuf = *nxtbuf++;
447
448         for (ap = addrcomps; *ap; ap++) {
449                 FINDCOMP(cptr, *ap);
450                 if (cptr)
451                         cptr->c_type |= CT_ADDR;
452         }
453
454         /*
455         ** ignore any components killed by command line switches
456         */
457         if (!ccto) {
458                 FINDCOMP(cptr, "to");
459                 if (cptr)
460                         cptr->c_name = "";
461         }
462         if (!cccc) {
463                 FINDCOMP(cptr, "cc");
464                 if (cptr)
465                         cptr->c_name = "";
466         }
467         if ((cp = getenv("USER"))) {
468                 FINDCOMP(cptr, "user");
469                 if (cptr)
470                         cptr->c_text = getcpy(cp);
471         }
472         if (!ccme)
473                 ismymbox(NULL);
474
475         /*
476         ** pick any interesting stuff out of msg "inb"
477         */
478         for (state = FLD;;) {
479                 state = m_getfld(state, name, tmpbuf, SBUFSIZ, inb);
480                 switch (state) {
481                 case FLD:
482                 case FLDPLUS:
483                         /*
484                         ** if we're interested in this component, save
485                         ** a pointer to the component text, then start
486                         ** using our next free buffer as the component
487                         ** temp buffer (buffer switching saves an extra
488                         ** copy of the component text).
489                         */
490                         if ((cptr = wantcomp[CHASH(name)]))
491                                 do {
492                                         if (!mh_strcasecmp(name, cptr->c_name)) {
493                                                 char_read += msg_count;
494                                                 if (! cptr->c_text) {
495                                                         i = strlen(cptr->c_text = tmpbuf) - 1;
496                                                         if (tmpbuf[i] == '\n')
497                                                                 tmpbuf[i] = '\0';
498                                                         *--savecomp = cptr;
499                                                         tmpbuf = *nxtbuf++;
500                                                 } else {
501                                                         i = strlen(cp = cptr->c_text) - 1;
502                                                         if (cp[i] == '\n') {
503                                                                 if (cptr->c_type & CT_ADDR) {
504                                                                         cp[i] = '\0';
505                                                                         cp = add(",\n\t", cp);
506                                                                 } else {
507                                                                         cp = add("\t", cp);
508                                                                 }
509                                                         }
510                                                         cptr->c_text = add(tmpbuf, cp);
511                                                 }
512                                                 while (state == FLDPLUS) {
513                                                         state = m_getfld(state, name, tmpbuf,
514                                                                                           SBUFSIZ, inb);
515                                                         cptr->c_text = add(tmpbuf, cptr->c_text);
516                                                         char_read += msg_count;
517                                                 }
518                                                 break;
519                                         }
520                                 } while ((cptr = cptr->c_next));
521
522                         while (state == FLDPLUS)
523                                 state = m_getfld(state, name, tmpbuf,
524                                                 SBUFSIZ, inb);
525                         break;
526
527                 case LENERR:
528                 case FMTERR:
529                 case BODY:
530                 case FILEEOF:
531                         goto finished;
532
533                 default:
534                         adios(NULL, "m_getfld() returned %d", state);
535                 }
536         }
537
538         /*
539         ** format and output the header lines.
540         */
541 finished:
542
543         /*
544         ** if there's a "Subject" component, strip any "Re:"s off it
545         */
546         FINDCOMP(cptr, "subject")
547         if (cptr && (cp = cptr->c_text)) {
548                 register char *sp = cp;
549
550                 for (;;) {
551                         while (isspace(*cp))
552                                 cp++;
553                         if(uprf(cp, "re:"))
554                                 cp += 3;
555                         else
556                                 break;
557                         sp = cp;
558                 }
559                 if (sp != cptr->c_text) {
560                         cp = cptr->c_text;
561                         cptr->c_text = getcpy(sp);
562                         free(cp);
563                 }
564         }
565         i = format_len + char_read + 256;
566         scanl = mh_xmalloc((size_t) i + 2);
567         dat[0] = 0;
568         dat[1] = 0;
569         dat[2] = 0;
570         dat[3] = OUTPUTLINELEN;
571         dat[4] = 0;
572         fmt_scan(fmt, scanl, i, dat);
573         fputs(scanl, out);
574         if (badaddrs) {
575                 fputs("\nrepl: bad addresses:\n", out);
576                 fputs( badaddrs, out);
577         }
578
579         /* Check if we should filter the message */
580         if (filter) {
581                 fflush(out);
582                 if (ferror(out))
583                         adios(drft, "error writing");
584
585                 replfilter(inb, out, filter);
586         }
587
588         fflush(out);
589         if (ferror(out))
590                 adios(drft, "error writing");
591         fclose(out);
592
593         if (mime && mp) {
594                 /* add an attachment header */
595                 char buffer[BUFSIZ];
596
597                 snprintf(buffer, sizeof buffer, "anno -append -nodate '%s' "
598                                 "-comp '%s' -text '+%s %s'",
599                                 drft,
600                                 attach_hdr, mp->foldpath, m_name(mp->lowsel));
601                 if (system(buffer) != 0) {
602                         advise(NULL, "unable to add attachment header");
603                 }
604         }
605
606         /* return dynamically allocated buffers */
607         free(scanl);
608         for (nxtbuf = compbuffers, i = ncomps; (cptr = *savecomp++);
609                         nxtbuf++, i--)
610                 free(cptr->c_text);  /* if not nxtbuf, nxtbuf already freed */
611         while ( i-- > 0)
612                 free(*nxtbuf++);  /* free unused nxtbufs */
613         free((char *) compbuffers);
614         free((char *) used_buf);
615 }
616
617 static char *buf;  /* our current working buffer */
618 static char *bufend;  /* end of working buffer */
619 static char *last_dst;  /* buf ptr at end of last call */
620 static unsigned int bufsiz=0;  /* current size of buf */
621
622 #define BUFINCR 512  /* how much to expand buf when if fills */
623
624 #define CPY(s) { cp = (s); while ((*dst++ = *cp++)) ; --dst; }
625
626 /*
627 ** check if there's enough room in buf for str.
628 ** add more mem if needed
629 */
630 #define CHECKMEM(str) \
631         if ((len = strlen(str)) >= bufend - dst) {\
632                 int i = dst - buf;\
633                 int n = last_dst - buf;\
634                 bufsiz += ((dst + len - bufend) / BUFINCR + 1) * BUFINCR;\
635                 buf = mh_xrealloc(buf, bufsiz);\
636                 dst = buf + i;\
637                 last_dst = buf + n;\
638                 bufend = buf + bufsiz;\
639         }
640
641
642 /*
643 ** fmt_scan will call this routine if the user includes the function
644 ** "(formataddr {component})" in a format string.  "orig" is the
645 ** original contents of the string register.  "str" is the address
646 ** string to be formatted and concatenated onto orig.  This routine
647 ** returns a pointer to the concatenated address string.
648 **
649 ** We try to not do a lot of malloc/copy/free's (which is why we
650 ** don't call "getcpy") but still place no upper limit on the
651 ** length of the result string.
652 **
653 ** This routine is an override for the equally named one in sbr/fmt_addr.c.
654 ** Don't delete it!
655 */
656 char *
657 formataddr(char *orig, char *str)
658 {
659         register int len;
660         char baddr[BUFSIZ], error[BUFSIZ];
661         register int isgroup;
662         register char *dst;
663         register char *cp;
664         register char *sp;
665         register struct mailname *mp = NULL;
666
667         /* if we don't have a buffer yet, get one */
668         if (bufsiz == 0) {
669                 buf = mh_xmalloc(BUFINCR);
670                 last_dst = buf;  /* XXX */
671                 bufsiz = BUFINCR - 6;  /* leave some slop */
672                 bufend = buf + bufsiz;
673         }
674         /*
675         ** If "orig" points to our buffer we can just pick up where we
676         ** left off.  Otherwise we have to copy orig into our buffer.
677         */
678         if (orig == buf)
679                 dst = last_dst;
680         else if (!orig || !*orig) {
681                 dst = buf;
682                 *dst = '\0';
683         } else {
684                 dst = last_dst;  /* XXX */
685                 CHECKMEM(orig);
686                 CPY(orig);
687         }
688
689         /* concatenate all the new addresses onto 'buf' */
690         for (isgroup = 0; (cp = getname(str)); ) {
691                 if ((mp = getm(cp, dfhost, dftype, AD_NAME, error)) == NULL) {
692                         snprintf(baddr, sizeof(baddr), "\t%s -- %s\n",
693                                         cp, error);
694                         badaddrs = add(baddr, badaddrs);
695                         continue;
696                 }
697                 if (isgroup && (mp->m_gname || !mp->m_ingrp)) {
698                         *dst++ = ';';
699                         isgroup = 0;
700                 }
701                 if (insert(mp)) {
702                         /* if we get here we're going to add an address */
703                         if (dst != buf) {
704                                 *dst++ = ',';
705                                 *dst++ = ' ';
706                         }
707                         if (mp->m_gname) {
708                                 CHECKMEM(mp->m_gname);
709                                 CPY(mp->m_gname);
710                                 isgroup++;
711                         }
712                         sp = adrformat(mp);
713                         CHECKMEM(sp);
714                         CPY(sp);
715                 }
716         }
717
718         if (isgroup)
719                 *dst++ = ';';
720
721         *dst = '\0';
722         last_dst = dst;
723         return (buf);
724 }
725
726
727 static int
728 insert(struct mailname *np)
729 {
730         char buffer[BUFSIZ];
731         register struct mailname *mp;
732
733         if (np->m_mbox == NULL)
734                 return 0;
735
736         for (mp = &mq; mp->m_next; mp = mp->m_next) {
737                 if (!mh_strcasecmp(np->m_host, mp->m_next->m_host) &&
738                                 !mh_strcasecmp(np->m_mbox, mp->m_next->m_mbox))
739                         return 0;
740         }
741         if (!ccme && ismymbox(np))
742                 return 0;
743
744         if (querysw) {
745                 snprintf(buffer, sizeof(buffer), "Reply to %s? ",
746                                 adrformat(np));
747                 if (!gans(buffer, anoyes))
748                         return 0;
749         }
750         mp->m_next = np;
751         return 1;
752 }
753
754
755 /*
756 ** Call mhl
757 **
758 ** This function expects that argument out has been fflushed by the caller.
759 */
760 static void
761 replfilter(FILE *in, FILE *out, char *filter)
762 {
763         int pid, n;
764         char *errstr;
765
766         if (filter == NULL)
767                 return;
768
769         if (access(filter, R_OK) == NOTOK)
770                 adios(filter, "unable to read");
771
772         rewind(in);
773         lseek(fileno(in), (off_t) 0, SEEK_SET);
774
775         switch (pid = fork()) {
776         case NOTOK:
777                 adios("fork", "unable to");
778
779         case OK:
780                 dup2(fileno(in), fileno(stdin));
781                 dup2(fileno(out), fileno(stdout));
782                 for (n=3; n<OPEN_MAX; n++) {
783                         close(n);
784                 }
785
786                 execlp("mhl", "mhl", "-form", filter, NULL);
787                 errstr = strerror(errno);
788                 write(2, "unable to exec mhl: ", 20);
789                 write(2, errstr, strlen(errstr));
790                 write(2, "\n", 1);
791                 _exit(-1);
792
793         default:
794                 if (pidXwait(pid, "mhl"))
795                         done(1);
796                 fseek(out, 0L, SEEK_END);
797                 break;
798         }
799 }