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