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