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