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