bugfix for a memory-reuse bug spost and whom
[mmh] / uip / spost.c
1 /*
2 ** spost.c -- feed messages to sendmail
3 **
4 ** This is a simpler, faster, replacement for "post" for use
5 ** when "sendmail" is the transport system.
6 **
7 ** This code is Copyright (c) 2002, by the authors of nmh.  See the
8 ** COPYRIGHT file in the root directory of the nmh distribution for
9 ** complete copyright information.
10 */
11
12 #include <h/mh.h>
13 #include <signal.h>
14 #include <h/addrsbr.h>
15 #include <h/aliasbr.h>
16 #include <h/dropsbr.h>
17 #include <h/tws.h>
18 #include <h/utils.h>
19 #include <unistd.h>
20 #include <locale.h>
21 #include <sysexits.h>
22
23 #define MAX_SM_FIELD 1476  /* < largest hdr field sendmail will accept */
24
25 static struct swit switches[] = {
26 #define VERBSW  0
27         { "verbose", 0 },
28 #define NVERBSW  1
29         { "noverbose", 2 },
30 #define VERSIONSW  2
31         { "Version", 0 },
32 #define HELPSW  3
33         { "help", 0 },
34 #define DEBUGSW  4
35         { "debug", -5 },
36 #define DISTSW  5
37         { "dist", -4 },  /* interface from dist */
38         { NULL, 0 }
39 };
40
41
42 /* flags for headers->flags */
43 #define HNOP  0x0000  /* just used to keep .set around */
44 #define HBAD  0x0001  /* bad header - don't let it through */
45 #define HADR  0x0002  /* header has an address field */
46 #define HSUB  0x0004  /* Subject: header */
47 #define HTRY  0x0008  /* try to send to addrs on header */
48 #define HBCC  0x0010  /* don't output this header */
49 #define HFCC  0x0020  /* FCC: type header */
50 #define HIGN  0x0040  /* ignore this header */
51
52 /* flags for headers->set */
53 #define MFRM  0x0001  /* we've seen a From: */
54 #define MDAT  0x0002  /* we've seen a Date: */
55 #define MRFM  0x0004  /* we've seen a Resent-From: */
56 #define MVIS  0x0008  /* we've seen sighted addrs */
57 #define MINV  0x0010  /* we've seen blind addrs */
58 #define MRDT  0x0020  /* we've seen a Resent-Date: */
59 #define MFMM  0x0040  /* The Mail is From a Alternative-Mailbox Addresse */
60
61 struct headers {
62         char *value;
63         unsigned int flags;
64         unsigned int set;
65 };
66
67 static struct headers NHeaders[] = {
68         { "Return-Path", HBAD, 0 },
69         { "Received", HBAD, 0 },
70         { "Reply-To", HADR, 0 },
71         { "From", HADR, MFRM },
72         { "Sender", HADR|HBAD, 0 },
73         { "Date", HNOP, MDAT },
74         { "Subject", HSUB, 0 },
75         { "To", HADR|HTRY, MVIS },
76         { "Cc", HADR|HTRY, MVIS },
77         { "Bcc", HADR|HTRY|HBCC, MINV },
78         { "Message-Id", HBAD, 0 },
79         { "Fcc", HFCC, 0 },
80         { "Envelope-From", HIGN, 0 },
81         { NULL, 0, 0 }
82 };
83
84 static struct headers RHeaders[] = {
85         { "Resent-Reply-To",   HADR, 0 },
86         { "Resent-From", HADR, MRFM },
87         { "Resent-Sender", HADR|HBAD, 0 },
88         { "Resent-Date", HNOP, MRDT },
89         { "Resent-Subject", HSUB, 0 },
90         { "Resent-To", HADR|HTRY, MVIS },
91         { "Resent-Cc", HADR|HTRY, MVIS },
92         { "Resent-Bcc", HADR|HTRY|HBCC, MINV },
93         { "Resent-Message-Id", HBAD, 0 },
94         { "Resent-Fcc", HFCC, 0 },
95         { "Reply-To", HADR, 0 },
96         { "Fcc", HIGN, 0 },
97         { "Envelope-From", HIGN, 0 },
98         { NULL, 0, 0 }
99 };
100
101
102 static int badmsg = 0;
103 static int verbose = 0;
104 static int debug = 0;
105 static int aliasflg = 0;  /* if going to process aliases */
106
107 static unsigned msgflags = 0;  /* what we've seen */
108
109 static enum {
110         normal, resent
111 } msgstate = normal;
112
113 static char *tmpfil;
114
115 static char *subject = NULL;  /* the subject field for BCC'ing */
116 static char fccs[BUFSIZ] = "";
117 struct mailname *bccs = NULL;  /* list of the bcc recipients */
118
119 static struct headers *hdrtab;  /* table for the message we're doing */
120 static FILE *out;  /* output (temp) file */
121
122 /*
123 ** static prototypes
124 */
125 static void putfmt(char *, char *, FILE *);
126 static void finish_headers(FILE *);
127 static int get_header(char *, struct headers *);
128 static void putadr(char *, struct mailname *);
129 static int putone(char *, int, int);
130 static void process_fcc(char *);
131 static void fcc(char *, char *);
132 static void process_bccs(char *);
133
134
135 int
136 main(int argc, char **argv)
137 {
138         int state, compnum;
139         char *cp, *msg = NULL, **argp, **arguments;
140         char *sargv[16], buf[BUFSIZ], name[NAMESZ];
141         FILE *in;
142
143         setlocale(LC_ALL, "");
144         invo_name = mhbasename(argv[0]);
145
146         context_read();
147
148         arguments = getarguments(invo_name, argc, argv, 0);
149         argp = arguments;
150
151         while ((cp = *argp++)) {
152                 if (*cp == '-') {
153                         switch (smatch(++cp, switches)) {
154                         case AMBIGSW:
155                                 ambigsw(cp, switches);
156                                 exit(EX_USAGE);
157                         case UNKWNSW:
158                                 adios(EX_USAGE, NULL, "-%s unknown", cp);
159
160                         case HELPSW:
161                                 snprintf(buf, sizeof(buf),
162                                                 "%s [switches] file",
163                                                 invo_name);
164                                 print_help(buf, switches, 1);
165                                 exit(argc == 2 ? EX_OK : EX_USAGE);
166                         case VERSIONSW:
167                                 print_version(invo_name);
168                                 exit(argc == 2 ? EX_OK : EX_USAGE);
169
170                         case DEBUGSW:
171                                 debug++;
172                                 continue;
173
174                         case DISTSW:
175                                 msgstate = resent;
176                                 continue;
177
178                         case VERBSW:
179                                 verbose++;
180                                 continue;
181                         case NVERBSW:
182                                 verbose = 0;
183                                 continue;
184                         }
185                 }
186                 if (msg)
187                         adios(EX_USAGE, NULL, "only one message at a time!");
188                 else
189                         msg = cp;
190         }
191
192         if (!msg)
193                 adios(EX_USAGE, NULL, "usage: %s [switches] file", invo_name);
194
195         if ((in = fopen(msg, "r")) == NULL)
196                 adios(EX_IOERR, msg, "unable to open");
197
198         if (debug) {
199                 verbose++;
200                 out = stdout;
201         } else {
202                 tmpfil = getcpy(m_mktemp2("/tmp/", invo_name, NULL, &out));
203         }
204
205         /* check for "Aliasfile:" profile entry */
206         if ((cp = context_find("Aliasfile"))) {
207                 char *dp, **ap; 
208
209                 aliasflg = 1;
210                 for (ap=brkstring(dp=getcpy(cp), " ", "\n"); ap && *ap;
211                                 ap++) {
212                         if ((state = alias(etcpath(*ap))) != AK_OK) {
213                                 adios(EX_IOERR, NULL, "aliasing error in file %s: %s",
214                                                 *ap, akerror(state));
215                         }
216                 }
217         }
218
219
220         hdrtab = (msgstate == normal) ? NHeaders : RHeaders;
221
222         for (compnum = 1, state = FLD;;) {
223                 switch (state = m_getfld(state, name, buf, sizeof(buf), in)) {
224                 case FLD:
225                         compnum++;
226                         putfmt(name, buf, out);
227                         continue;
228
229                 case FLDPLUS:
230                         compnum++;
231                         cp = getcpy(buf);
232                         while (state == FLDPLUS) {
233                                 state = m_getfld(state, name, buf,
234                                                 sizeof(buf), in);
235                                 cp = add(buf, cp);
236                         }
237                         putfmt(name, cp, out);
238                         free(cp);
239                         continue;
240
241                 case BODY:
242                         finish_headers(out);
243                         fprintf(out, "\n%s", buf);
244                         while (state == BODY) {
245                                 state = m_getfld(state, name, buf,
246                                                 sizeof(buf), in);
247                                 fputs(buf, out);
248                         }
249                         break;
250
251                 case FILEEOF:
252                         finish_headers(out);
253                         break;
254
255                 case LENERR:
256                 case FMTERR:
257                         adios(EX_DATAERR, NULL, "message format error in component #%d",
258                                         compnum);
259
260                 default:
261                         adios(EX_SOFTWARE, NULL, "getfld() returned %d", state);
262                 }
263                 break;
264         }
265         fclose(in);
266
267         if (debug) {
268                 /* stop here */
269                 exit(EX_OK);
270         }
271
272         fclose(out);
273
274         /* process Fcc */
275         if (*fccs) {
276                 fcc(tmpfil, fccs);
277         }
278
279         if (bccs) {
280                 process_bccs(tmpfil);
281                 if (!(msgflags & MVIS)) {
282                         /* only Bcc rcpts: we're finished here */
283                         unlink(tmpfil);
284                         exit(EX_OK);
285                 }
286         }
287
288         /*
289         ** re-open the temp file, unlink it and exec sendmail, giving it
290         ** the msg temp file as std in.
291         */
292         if (!freopen(tmpfil, "r", stdin)) {
293                 adios(EX_IOERR, tmpfil, "can't reopen for sendmail");
294         }
295         unlink(tmpfil);
296
297         argp = sargv;
298         *argp++ = "send-mail";
299         *argp++ = "-m";  /* send to me too */
300         *argp++ = "-t";  /* read msg for recipients */
301         *argp++ = "-i";  /* don't stop on "." */
302         if (verbose) {
303                 *argp++ = "-v";
304         }
305         *argp = NULL;
306         execv(sendmail, sargv);
307         adios(EX_OSERR, sendmail, "can't exec");
308         return -1;
309 }
310
311
312 /* DRAFT GENERATION */
313
314 static void
315 putfmt(char *name, char *str, FILE *out)
316 {
317         int i;
318         char *cp;
319         struct headers *hdr;
320
321         /* remove leading whitespace */
322         while (*str==' ' || *str=='\t') {
323                 str++;
324         }
325
326         if ((i = get_header(name, hdrtab)) == NOTOK) {
327                 /* no header we would care for */
328                 if (mh_strcasecmp(name, attach_hdr)!=0 &&
329                                 mh_strcasecmp(name, sign_hdr)!=0 &&
330                                 mh_strcasecmp(name, enc_hdr)!=0) {
331                         /* push it through */
332                         fprintf(out, "%s: %s", name, str);
333                 }
334                 return;
335         }
336         /* it's one of the interesting headers */
337         hdr = &hdrtab[i];
338
339         if (hdr->flags & HIGN || strcmp(str, "\n")==0) {
340                 return;
341         }
342
343         if (hdr->flags & HBAD) {
344                 advise(NULL, "illegal header line -- %s:", name);
345                 badmsg++;
346                 return;
347         }
348
349         msgflags |= hdr->set;
350
351         if (hdr->flags & HFCC) {
352                 process_fcc(str);
353                 return;
354         }
355
356         if (hdr->flags & HBCC) {
357                 struct mailname *mp = NULL;
358
359                 /* Create list of Bcc addrs. */
360                 while ((cp = getname(str))) {
361                         mp = getm(cp, NULL, 0, AD_HOST, NULL);
362                         mp->m_next = bccs;  /* push */
363                         bccs = mp;
364                 }
365                 return;
366         }
367
368         if (aliasflg && hdr->flags & HTRY) {
369                 /*
370                 ** This header contains address(es) that we have to do
371                 ** alias expansion on.  Because of the saved state in
372                 ** getname we have to put all the addresses into a list.
373                 **/
374                 struct mailname *f = NULL;
375                 struct mailname *mp = NULL;
376
377                 while ((cp = getname(str))) {
378                         mp = getm(cp, NULL, 0, AD_HOST, NULL);
379                         if (!f) {
380                                 f = mp;
381                                 mp->m_next = mp;
382                         } else {
383                                 mp->m_next = f->m_next;
384                                 f->m_next = mp;
385                                 f = mp;
386                         }
387                 }
388                 f = mp->m_next;
389                 mp->m_next = NULL;
390                 /* Now munch on the list, possibly expanding aliases */
391                 putadr(name, f);
392                 return;
393         }
394
395         /*
396         ** The author(s) of spost decided that alias substitution wasn't
397         ** necessary for the non-HTRY headers.  Unfortunately, one of
398         ** those headers is "From:", and having alias substitution work on
399         ** that is extremely useful for someone with a lot of POP3 email
400         ** accounts or aliases.  post supports aliasing of "From:"...
401         **
402         ** Since "From:"-processing is incompletely implemented in this
403         ** unsupported and undocumented spost backend, I'm not going
404         ** to take the time to implement my new draft-From:-based email
405         ** address masquerading.  If I do ever implement it here, I'd almost
406         ** certainly want to implement "From:" line alias processing as well.
407         ** -- Dan Harkless <dan-nmh@dilvish.speed.net>
408         */
409         /*
410         ** Although there is no masquerading anymore in mmh, we might want
411         ** to have aliasing of From: addresses. Think about it.
412         ** -- meillo@marmaro.de  2012-02
413         */
414
415         if (hdr->set & MFRM) {
416
417                 struct mailname *mp = NULL;
418
419                 /* This is need because the addresse parser hold global state */
420                 ismymbox(NULL);
421
422                 while ((cp = getname(str)) != NULL) {
423                         mp = getm(cp, NULL, 0, AD_NAME, NULL);
424                         if (ismymbox(mp)) {
425                                 msgflags |= MFMM;
426                         }
427                 }
428         }
429
430         if (hdr->flags & HSUB) {
431                 subject = getcpy(str);
432         }
433         fprintf(out, "%s: %s", name, str);
434 }
435
436
437 /*
438 ** Add yet missing headers.
439 */
440 static void
441 finish_headers(FILE *out)
442 {
443         char *cp;
444         char from[BUFSIZ];  /* my network address */
445         char signature[BUFSIZ];  /* my signature */
446         char *resentstr = (msgstate == resent) ? "Resent-" : "";
447
448         if (!(msgflags & MDAT)) {
449                 fprintf(out, "%sDate: %s\n", resentstr, dtimenow());
450         }
451
452         if ((cp = context_find("Default-From")) != NULL) {
453                 snprintf(signature, sizeof(signature), "%s", cp);
454         } else {
455                 snprintf(from, sizeof(from), "%s@%s", getusername(), LocalName());
456                 if ((cp = getfullname()) && *cp) {
457                         snprintf(signature, sizeof(signature), "%s <%s>", cp, from);
458                 } else {
459                         snprintf(signature, sizeof(signature), "%s", from);
460                 }
461         }
462         if (!(msgflags & MFRM)) {
463                 fprintf(out, "%sFrom: %s\n", resentstr, signature);
464         } else {
465                 /*
466                 ** Add a Sender: header because the From: header could
467                 ** be fake or contain multiple addresses.
468                 */
469                 if (!(msgflags & MFMM)) {
470                         fprintf(out, "%sSender: %s\n", resentstr, signature);
471                 }
472         }
473         if (!(msgflags & MVIS)) {
474                 fprintf(out, "%sBcc: undisclosed-recipients:;\n", resentstr);
475         }
476         if (badmsg) {
477                 unlink(tmpfil);
478                 adios(EX_DATAERR, NULL, "re-format message and try again");
479         }
480 }
481
482
483 /*
484 ** Return index of the requested header in the table, or NOTOK if missing.
485 */
486 static int
487 get_header(char *header, struct headers *table)
488 {
489         struct headers *h;
490
491         for (h=table; h->value; h++) {
492                 if (mh_strcasecmp(header, h->value)==0) {
493                         return (h - table);
494                 }
495         }
496
497         return NOTOK;
498 }
499
500
501 /*
502 ** output the address list for header "name".  The address list
503 ** is a linked list of mailname structs.  "nl" points to the head
504 ** of the list.  Alias substitution should be done on nl.
505 */
506 static void
507 putadr(char *name, struct mailname *nl)
508 {
509         struct mailname *mp, *mp2;
510         int linepos;
511         char *cp;
512         int namelen;
513
514         fprintf(out, "%s: ", name);
515         namelen = strlen(name) + 2;
516         linepos = namelen;
517
518         for (mp = nl; mp; ) {
519                 if (linepos > MAX_SM_FIELD) {
520                         fprintf(out, "\n%s: ", name);
521                         linepos = namelen;
522                 }
523                 if (mp->m_nohost) {
524                         /* a local name - see if it's an alias */
525                         cp = akvalue(mp->m_mbox);
526                         if (cp == mp->m_mbox) {
527                                 /* wasn't an alias - use what the user typed */
528                                 linepos = putone(mp->m_text, linepos, namelen);
529                         } else {
530                                 /* an alias - expand it */
531                                 while ((cp = getname(cp))) {
532                                         if (linepos > MAX_SM_FIELD) {
533                                                 fprintf(out, "\n%s: ", name);
534                                                 linepos = namelen;
535                                         }
536                                         mp2 = getm(cp, NULL, 0, AD_HOST, NULL);
537                                         if (akvisible()) {
538                                                 mp2->m_pers = getcpy(mp->m_mbox);
539                                                 linepos = putone(adrformat(mp2), linepos, namelen);
540                                         } else {
541                                                 linepos = putone(mp2->m_text,
542                                                                 linepos,
543                                                                 namelen);
544                                         }
545                                         mnfree(mp2);
546                                 }
547                         }
548                 } else {
549                         /* not a local name - use what the user typed */
550                         linepos = putone(mp->m_text, linepos, namelen);
551                 }
552                 mp2 = mp;
553                 mp = mp->m_next;
554                 mnfree(mp2);
555         }
556         putc('\n', out);
557 }
558
559 static int
560 putone(char *adr, int pos, int indent)
561 {
562         register int len;
563         static int linepos;
564
565         len = strlen(adr);
566         if (pos == indent)
567                 linepos = pos;
568         else if (linepos+len > OUTPUTLINELEN) {
569                 fprintf(out, ",\n%*s", indent, "");
570                 linepos = indent;
571                 pos += indent + 2;
572         } else {
573                 fputs(", ", out);
574                 linepos += 2;
575                 pos += 2;
576         }
577         fputs(adr, out);
578
579         linepos += len;
580         return (pos+len);
581 }
582
583
584 static void
585 process_fcc(char *str)
586 {
587         char *cp, *pp;
588         int state = 0;
589
590         if (strlen(str)+strlen(fccs) > sizeof fccs /2) {
591                 adios(EX_DATAERR, NULL, "Too much Fcc data");
592         }
593         /* todo: better have three states: SEPARATOR, PLUS, WORD */
594         for (cp=pp=str; *cp; cp++) {
595                 switch (*cp) {
596                 case ' ':
597                 case '\t':
598                 case '\n':
599                 case ',':
600                         if (state != 0) {
601                                 state = 0;
602                                 *cp = '\0';
603                                 if (*pp=='+' || *pp=='@') {
604                                         strcat(fccs, " ");
605                                 } else {
606                                         strcat(fccs, " +");
607                                 }
608                                 strcat(fccs, pp);
609                         }
610                         break;
611                 default:
612                         if (state == 0) {
613                                 state = 1;
614                                 pp = cp;
615                         }
616                         break;
617                 }
618         }
619 }
620
621
622 static void
623 fcc(char *file, char *folders)
624 {
625         int status;
626         char cmd[BUFSIZ];
627
628         if (verbose) {
629                 printf("%sFcc: %s\n", msgstate == resent ? "Resent-" : "",
630                                 folders);
631                 fflush(stdout);
632         }
633         if (100+strlen(file)+strlen(folders) > sizeof cmd) {
634                 adios(EX_DATAERR, NULL, "Too much Fcc data");
635         }
636         /* hack: read from /dev/null and refile(1) won't question us */
637         snprintf(cmd, sizeof cmd, "</dev/null refile -link -file '%s' %s",
638                         file, folders);
639         status = system(cmd);
640         if (status == -1) {
641                 fprintf(stderr, "Skipped %sFcc %s: unable to system().\n",
642                                 msgstate == resent ? "Resent-" : "", folders);
643         } else if (status != 0) {
644                 fprintf(stderr, "%sFcc %s: Problems occured.\n",
645                                 msgstate == resent ? "Resent-" : "", folders);
646         }
647 }
648
649
650 /* BCC GENERATION */
651
652 static void
653 process_bccs(char *origmsg)
654 {
655         char *bccdraft = NULL;
656         struct mailname *mp = NULL;
657         FILE *out = NULL;
658
659         for (mp=bccs; mp; mp=mp->m_next) {
660                 bccdraft = getcpy(m_mktemp2("/tmp/", invo_name, NULL, &out));
661                 fprintf(out, "To: %s\n", mp->m_text);
662                 fprintf(out, "Subject: [BCC] %s", subject ? subject : "");
663                 fprintf(out, "%s: %s\n", attach_hdr, origmsg);
664                 fprintf(out, "------------\n");
665                 fclose(out);
666
667                 if (execprogl("send", "send", bccdraft, (char *)NULL) != 0) {
668                         admonish(invo_name, "Problems to send Bcc to %s",
669                                         mp->m_text);
670                         unlink(bccdraft);
671                 }
672         }
673 }