53ae86a72538b71b30764bdec435315988c0e6f8
[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 #include <errno.h>
23
24 #define MAX_SM_FIELD 1476  /* < largest hdr field sendmail will accept */
25
26 static struct swit switches[] = {
27 #define VERBSW  0
28         { "verbose", 0 },
29 #define NVERBSW  1
30         { "noverbose", 2 },
31 #define VERSIONSW  2
32         { "Version", 0 },
33 #define HELPSW  3
34         { "help", 0 },
35 #define DEBUGSW  4
36         { "debug", -5 },
37 #define DISTSW  5
38         { "dist", -4 },  /* interface from dist */
39         { NULL, 0 }
40 };
41
42
43 /* flags for headers->flags */
44 #define HNOP  0x0000  /* just used to keep .set around */
45 #define HBAD  0x0001  /* bad header - don't let it through */
46 #define HADR  0x0002  /* header has an address field */
47 #define HSUB  0x0004  /* Subject: header */
48 #define HTRY  0x0008  /* try to send to addrs on header */
49 #define HBCC  0x0010  /* don't output this header */
50 #define HFCC  0x0020  /* FCC: type header */
51 #define HIGN  0x0040  /* ignore this header */
52 #define HDCC  0x0080  /* DCC: type header */
53
54 /* flags for headers->set */
55 #define MFRM  0x0001  /* we've seen a From: */
56 #define MDAT  0x0002  /* we've seen a Date: */
57 #define MRFM  0x0004  /* we've seen a Resent-From: */
58 #define MVIS  0x0008  /* we've seen sighted addrs */
59 #define MINV  0x0010  /* we've seen blind addrs */
60 #define MRDT  0x0020  /* we've seen a Resent-Date: */
61 #define MFMM  0x0040  /* The Mail is From a Alternative-Mailbox Addresse */
62
63 struct headers {
64         char *value;
65         unsigned int flags;
66         unsigned int set;
67 };
68
69 static struct headers NHeaders[] = {
70         { "Return-Path", HBAD, 0 },
71         { "Received", HBAD, 0 },
72         { "Reply-To", HADR, 0 },
73         { "From", HADR, MFRM },
74         { "Sender", HADR|HBAD, 0 },
75         { "Date", HNOP, MDAT },
76         { "Subject", HSUB, 0 },
77         { "To", HADR|HTRY, MVIS },
78         { "Cc", HADR|HTRY, MVIS },
79         { "Dcc", HADR|HTRY|HDCC, MINV },
80         { "Bcc", HADR|HTRY|HBCC, MINV },
81         { "Message-Id", HBAD, 0 },
82         { "Fcc", HFCC, 0 },
83         { "Envelope-From", HIGN, 0 },
84         { NULL, 0, 0 }
85 };
86
87 static struct headers RHeaders[] = {
88         { "Resent-Reply-To",   HADR, 0 },
89         { "Resent-From", HADR, MRFM },
90         { "Resent-Sender", HADR|HBAD, 0 },
91         { "Resent-Date", HNOP, MRDT },
92         { "Resent-Subject", HSUB, 0 },
93         { "Resent-To", HADR|HTRY, MVIS },
94         { "Resent-Cc", HADR|HTRY, MVIS },
95         { "Resent-Dcc", HADR|HTRY|HDCC, MINV },
96         { "Resent-Bcc", HADR|HTRY|HBCC, MINV },
97         { "Resent-Message-Id", HBAD, 0 },
98         { "Resent-Fcc", HFCC, 0 },
99         { "Reply-To", HADR, 0 },
100         { "Fcc", HIGN, 0 },
101         { "Envelope-From", HIGN, 0 },
102         { NULL, 0, 0 }
103 };
104
105
106 static int badmsg = 0;
107 static int verbose = 0;
108 static int debug = 0;
109 static int aliasflg = 0;  /* if going to process aliases */
110
111 static unsigned msgflags = 0;  /* what we've seen */
112
113 static enum {
114         normal, resent
115 } msgstate = normal;
116
117 static char *tmpfil;
118
119 static char *subject = NULL;  /* the subject field for BCC'ing */
120 static struct mailname *from = NULL;  /* the from field for BCC'ing */
121 static char fccs[BUFSIZ] = "";
122 struct mailname *bccs = NULL;  /* list of the bcc recipients */
123 struct mailname *recipients = NULL;  /* list of the recipients */
124 size_t recipientsc = 0;
125 struct mailname *sender = NULL;
126
127 static struct headers *hdrtab;  /* table for the message we're doing */
128 static FILE *out;  /* output (temp) file */
129
130 /*
131 ** static prototypes
132 */
133 static void putfmt(char *, char *, FILE *);
134 static void finish_headers(FILE *);
135 static int get_header(char *, struct headers *);
136 static void putadr(char *, struct mailname *);
137 static int putone(char *, int, int);
138 static void process_fcc(char *);
139 static void fcc(char *, char *);
140 static void process_bccs(char *);
141 static size_t do_aliasing(struct mailname *, struct mailname **);
142
143
144 int
145 main(int argc, char **argv)
146 {
147         enum state state;
148         struct field f = {{0}};
149         int compnum;
150         char *cp, *msg = NULL, **argp, **arguments;
151         char **sargv, buf[BUFSIZ];
152         FILE *in;
153
154         setlocale(LC_ALL, "");
155         invo_name = mhbasename(argv[0]);
156
157         context_read();
158
159         arguments = getarguments(invo_name, argc, argv, 0);
160         argp = arguments;
161
162         while ((cp = *argp++)) {
163                 if (*cp == '-') {
164                         switch (smatch(++cp, switches)) {
165                         case AMBIGSW:
166                                 ambigsw(cp, switches);
167                                 exit(EX_USAGE);
168                         case UNKWNSW:
169                                 adios(EX_USAGE, NULL, "-%s unknown", cp);
170
171                         case HELPSW:
172                                 snprintf(buf, sizeof(buf),
173                                                 "%s [switches] file",
174                                                 invo_name);
175                                 print_help(buf, switches, 1);
176                                 exit(argc == 2 ? EX_OK : EX_USAGE);
177                         case VERSIONSW:
178                                 print_version(invo_name);
179                                 exit(argc == 2 ? EX_OK : EX_USAGE);
180
181                         case DEBUGSW:
182                                 debug++;
183                                 continue;
184
185                         case DISTSW:
186                                 msgstate = resent;
187                                 continue;
188
189                         case VERBSW:
190                                 verbose++;
191                                 continue;
192                         case NVERBSW:
193                                 verbose = 0;
194                                 continue;
195                         }
196                 }
197                 if (msg) {
198                         adios(EX_USAGE, NULL, "only one message at a time!");
199                 } else {
200                         msg = cp;
201                 }
202         }
203
204         if (!msg) {
205                 adios(EX_USAGE, NULL, "usage: %s [switches] file", invo_name);
206         }
207
208         if ((in = fopen(msg, "r")) == NULL) {
209                 adios(EX_IOERR, msg, "unable to open");
210         }
211
212         if (debug) {
213                 verbose++;
214                 out = stdout;
215         } else {
216                 tmpfil = mh_xstrdup(m_mktemp2("/tmp/", invo_name, NULL, &out));
217         }
218
219         /* check for "Aliasfile:" profile entry */
220         if ((cp = context_find("Aliasfile"))) {
221                 char *dp, **ap; 
222
223                 aliasflg = 1;
224                 for (ap=brkstring(dp=mh_xstrdup(cp), " ", "\n"); ap && *ap;
225                                 ap++) {
226                         if ((state = alias(etcpath(*ap))) != AK_OK) {
227                                 adios(EX_IOERR, NULL, "aliasing error in file %s: %s",
228                                                 *ap, akerror(state));
229                         }
230                 }
231         }
232
233
234         hdrtab = (msgstate == normal) ? NHeaders : RHeaders;
235
236         for (compnum = 1, state = FLD2;;) {
237                 switch (state = m_getfld2(state, &f, in)) {
238                 case FLD2:
239                         compnum++;
240                         putfmt(f.name, f.value, out);
241                         continue;
242
243                 case BODY2:
244                         finish_headers(out);
245                         fprintf(out, "\n%s", f.value);
246                         while ((state = m_getfld2(state, &f, in)) == BODY2) {
247                                 fputs(f.value, out);
248                         }
249                         break;
250
251                 case FILEEOF2:
252                         finish_headers(out);
253                         break;
254
255                 case LENERR2:
256                 case FMTERR2:
257                 case IOERR2:
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                 struct mailname *i = recipients;
270                 /* stop here */
271                 puts("----EOM----");
272                 while (i) {
273                         fputs(i->m_mbox, stdout);
274                         if (i->m_host) {
275                                 fputs("@", stdout);
276                                 fputs(i->m_host, stdout);
277                         }
278                         fputs("\n", stdout);
279                         i = i->m_next;
280                         mnfree(recipients);
281                         recipients = i;
282                 }
283                 exit(EX_OK);
284         }
285
286         fclose(out);
287
288         /* process Fcc */
289         if (*fccs) {
290                 fcc(tmpfil, fccs);
291         }
292
293         if (bccs) {
294                 process_bccs(tmpfil);
295                 if (!(msgflags & MVIS)) {
296                         /* only Bcc rcpts: we're finished here */
297                         unlink(tmpfil);
298                         exit(EX_OK);
299                 }
300         }
301
302         /*
303         ** re-open the temp file, unlink it and exec sendmail, giving it
304         ** the msg temp file as std in.
305         */
306         if (!freopen(tmpfil, "r", stdin)) {
307                 adios(EX_IOERR, tmpfil, "can't reopen for sendmail");
308         }
309         unlink(tmpfil);
310
311         if (recipientsc == 0) {
312                 adios(EX_DATAERR, NULL, "message has no recipients");
313         }
314
315         sargv = mh_xcalloc(recipientsc + 4, sizeof(char **));
316
317         argp = sargv;
318         *argp++ = "send-mail";
319         *argp++ = "-i";  /* don't stop on "." */
320         if (verbose) {
321                 *argp++ = "-v";
322         }
323
324         while (recipients != NULL) {
325                 cp = mh_xstrdup(recipients->m_mbox);
326                 if (recipients->m_host) {
327                         cp = add("@", cp);
328                         cp = add(recipients->m_host, cp);
329                 }
330                 *argp++ = cp;
331                 cp = NULL;
332                 recipients = recipients->m_next;
333         }
334         *argp = NULL;
335         execvp(sendmail, sargv);
336
337         if (errno == E2BIG) {
338                 adios(EX_DATAERR, sendmail, "too much arguments, probably to much recipients");
339         }
340
341         adios(EX_OSERR, sendmail, "can't exec");
342         return -1;
343 }
344
345
346 /* DRAFT GENERATION */
347
348 static void
349 putfmt(char *name, char *str, FILE *out)
350 {
351         int i;
352         struct headers *hdr;
353         struct mailname addr_start, *addr_end;
354         size_t addrc = 0;
355         ssize_t ret;
356
357         addr_end = &addr_start;
358         addr_end->m_next = NULL;
359
360         /* remove leading whitespace */
361         while (*str==' ' || *str=='\t') {
362                 str++;
363         }
364
365         if ((i = get_header(name, hdrtab)) == NOTOK) {
366                 /* no header we would care for */
367                 if (mh_strcasecmp(name, attach_hdr)==0) {
368                         return;
369                 }
370                 if (mh_strcasecmp(name, sign_hdr)==0) {
371                         return;
372                 }
373                 if (mh_strcasecmp(name, enc_hdr)==0) {
374                         return;
375                 }
376                 /* push it through */
377                 fprintf(out, "%s: %s", name, str);
378                 return;
379         }
380         /* it's one of the interesting headers */
381         hdr = &hdrtab[i];
382
383         if (hdr->flags & HIGN || strcmp(str, "\n")==0) {
384                 return;
385         }
386
387         if (hdr->flags & HBAD) {
388                 advise(NULL, "illegal header line -- %s:", name);
389                 badmsg++;
390                 return;
391         }
392
393         msgflags |= hdr->set;
394
395         if (hdr->flags & HFCC) {
396                 process_fcc(str);
397                 return;
398         }
399
400         if (hdr->flags & HSUB) {
401                 subject = mh_xstrdup(str);
402         }
403
404         if (!(hdr->flags & HADR)) {
405                 fprintf(out, "%s: %s", name, str);
406                 return;
407         }
408
409         if ((ret = getmboxes(str, &addr_end)) < 0) {
410                 adios(EX_DATAERR, NULL, "can't parse address: %s", str);
411         }
412
413         addrc += ret;
414
415         if (aliasflg) {
416                 addrc += do_aliasing(&addr_start, &addr_end);
417         }
418
419         if (hdr->flags & HBCC) {
420                 addr_end->m_next = bccs;
421                 bccs = addr_start.m_next;
422                 return;
423         }
424
425         if (hdr->set & MFRM) {
426                 struct mailname *mp = NULL;
427                 struct mailname *my = NULL;
428
429                 /* needed because the address parser holds global state */
430                 ismymbox(NULL);
431
432                 for (mp = addr_start.m_next; mp; mp = mp->m_next) {
433                         if (ismymbox(mp)) {
434                                 msgflags |= MFMM;
435                                 if (my == NULL) {
436                                         from = my = mp;
437                                 }
438                         }
439                 }
440
441                 if (addrc > 1) {
442                         sender = my;
443                 }
444         }
445
446         if (!(hdr->flags & HDCC)) {
447                 putadr(name, addr_start.m_next);
448         }
449
450         if (hdr->flags & HTRY) {
451                 addr_end->m_next = recipients;
452                 recipients = addr_start.m_next;
453                 recipientsc += i;
454         }
455 }
456
457
458 /*
459 ** Add yet missing headers.
460 */
461 static void
462 finish_headers(FILE *out)
463 {
464         char *cp;
465         char from[BUFSIZ];  /* my network address */
466         char signature[BUFSIZ];  /* my signature */
467         char *resentstr = (msgstate == resent) ? "Resent-" : "";
468
469         if (!(msgflags & MDAT)) {
470                 fprintf(out, "%sDate: %s\n", resentstr, dtimenow());
471         }
472
473         if (sender != NULL) {
474                 snprintf(signature, sizeof(signature), "%s", sender->m_text);
475         } else if ((cp = context_find("Default-From")) != NULL) {
476                 snprintf(signature, sizeof(signature), "%s", cp);
477         } else {
478                 snprintf(from, sizeof(from), "%s@%s", getusername(), LocalName());
479                 if ((cp = getfullname()) && *cp) {
480                         snprintf(signature, sizeof(signature), "%s <%s>", cp, from);
481                 } else {
482                         snprintf(signature, sizeof(signature), "%s", from);
483                 }
484         }
485         if (!(msgflags & MFRM)) {
486                 fprintf(out, "%sFrom: %s\n", resentstr, signature);
487         } else {
488                 /*
489                 ** Add a Sender: header because the From: header could
490                 ** be fake or contain multiple addresses.
491                 */
492                 if (!(msgflags & MFMM) || sender != NULL) {
493                         fprintf(out, "%sSender: %s\n", resentstr, signature);
494                 }
495         }
496         if (!(msgflags & MVIS)) {
497                 fprintf(out, "%sBcc: undisclosed-recipients:;\n", resentstr);
498         }
499         if (badmsg) {
500                 unlink(tmpfil);
501                 adios(EX_DATAERR, NULL, "re-format message and try again");
502         }
503 }
504
505
506 /*
507 ** Return index of the requested header in the table, or NOTOK if missing.
508 */
509 static int
510 get_header(char *header, struct headers *table)
511 {
512         struct headers *h;
513
514         for (h=table; h->value; h++) {
515                 if (mh_strcasecmp(header, h->value)==0) {
516                         return (h - table);
517                 }
518         }
519         return NOTOK;
520 }
521
522
523 /*
524 ** output the address list for header "name".  The address list
525 ** is a linked list of mailname structs.  "nl" points to the head
526 ** of the list.  Alias substitution should be done on nl.
527 */
528 static void
529 putadr(char *name, struct mailname *nl)
530 {
531         struct mailname *mp;
532         char *cp;
533         int linepos;
534         int namelen;
535
536         fprintf(out, "%s: ", name);
537         namelen = strlen(name) + 2;
538         linepos = namelen;
539
540         for (mp = nl; mp; ) {
541                 if (linepos > MAX_SM_FIELD) {
542                         fprintf(out, "\n%s: ", name);
543                         linepos = namelen;
544                 }
545                 if (mp->m_ingrp) {
546                         if (mp->m_gname != NULL) {
547                                 cp = mh_xstrdup(mp->m_gname);
548                                 cp = add(";", cp);
549                                 linepos = putone(cp, linepos, namelen);
550                                 mh_free0(&cp);
551                                 cp = NULL;
552                         }
553                 } else {
554                         linepos = putone(mp->m_text, linepos, namelen);
555                 }
556                 mp = mp->m_next;
557         }
558         putc('\n', out);
559 }
560
561 static int
562 putone(char *adr, int pos, int indent)
563 {
564         int len;
565         static int linepos;
566
567         len = strlen(adr);
568         if (pos == indent) {
569                 linepos = pos;
570         } else if (linepos+len > OUTPUTLINELEN) {
571                 fprintf(out, ",\n%*s", indent, "");
572                 linepos = indent;
573                 pos += indent + 2;
574         } else {
575                 fputs(", ", out);
576                 linepos += 2;
577                 pos += 2;
578         }
579         fputs(adr, out);
580
581         linepos += len;
582         return (pos+len);
583 }
584
585
586 static void
587 process_fcc(char *str)
588 {
589         char *cp, *pp;
590         int state = 0;
591
592         if (strlen(str)+strlen(fccs) > sizeof fccs /2) {
593                 adios(EX_DATAERR, NULL, "Too much Fcc data");
594         }
595         /* todo: better have three states: SEPARATOR, PLUS, WORD */
596         for (cp=pp=str; *cp; cp++) {
597                 switch (*cp) {
598                 case ' ':
599                 case '\t':
600                 case '\n':
601                 case ',':
602                         if (state != 0) {
603                                 state = 0;
604                                 *cp = '\0';
605                                 if (*pp=='+' || *pp=='@') {
606                                         strcat(fccs, " ");
607                                 } else {
608                                         strcat(fccs, " +");
609                                 }
610                                 strcat(fccs, pp);
611                         }
612                         break;
613                 default:
614                         if (state == 0) {
615                                 state = 1;
616                                 pp = cp;
617                         }
618                         break;
619                 }
620         }
621 }
622
623
624 static void
625 fcc(char *file, char *folders)
626 {
627         int status;
628         char cmd[BUFSIZ];
629
630         if (verbose) {
631                 printf("%sFcc: %s\n", msgstate == resent ? "Resent-" : "",
632                                 folders);
633                 fflush(stdout);
634         }
635         if (100+strlen(file)+strlen(folders) > sizeof cmd) {
636                 adios(EX_DATAERR, NULL, "Too much Fcc data");
637         }
638         /* hack: read from /dev/null and refile(1) won't question us */
639         snprintf(cmd, sizeof cmd, "</dev/null refile -link -file '%s' %s",
640                         file, folders);
641         status = system(cmd);
642         if (status == -1) {
643                 fprintf(stderr, "Skipped %sFcc %s: unable to system().\n",
644                                 msgstate == resent ? "Resent-" : "", folders);
645         } else if (status != 0) {
646                 fprintf(stderr, "%sFcc %s: Problems occurred.\n",
647                                 msgstate == resent ? "Resent-" : "", folders);
648         }
649 }
650
651
652 /* BCC GENERATION */
653
654 static void
655 process_bccs(char *origmsg)
656 {
657         char *bccdraft = NULL;
658         struct mailname *mp = NULL;
659         FILE *out = NULL;
660
661         for (mp=bccs; mp; mp=mp->m_next) {
662                 bccdraft = mh_xstrdup(m_mktemp2("/tmp/", invo_name, NULL, &out));
663                 fprintf(out, "To: %s\n", mp->m_text);
664                 if (from) {
665                         fprintf(out, "From: %s\n", from->m_text);
666                 }
667                 fprintf(out, "Subject: [BCC] %s", subject ? subject : "");
668                 fprintf(out, "%s: %s\n", attach_hdr, origmsg);
669                 fprintf(out, "------------\n");
670                 fclose(out);
671
672                 if (execprogl("send", "send", bccdraft, (char *)NULL) != 0) {
673                         admonish(invo_name, "Problems to send Bcc to %s",
674                                         mp->m_text);
675                         unlink(bccdraft);
676                 }
677         }
678 }
679
680 /*
681  * Do aliasing on a mailname linked list
682  * Begin at start->m_next
683  * End if m_next == NULL
684  * **end is set to the new end.
685  * Return the number of new mainames in the list
686  */
687
688 static size_t
689 do_aliasing(struct mailname *start, struct mailname **end)
690 {
691         struct mailname *prev, *cur;
692         char *cp;
693         size_t i = 0;
694         ssize_t e;
695
696         prev = start;
697         cur = prev->m_next;
698
699         while (cur != NULL) {
700                 if (cur->m_nohost) {
701                         cp = akvalue(cur->m_mbox);
702                         if (strcmp(cp, cur->m_mbox) != 0) {
703                                 prev->m_next = cur->m_next;
704                                 if ((e = getmboxes(cp, &prev)) < 0) {
705                                         goto error;
706                                 }
707                                 i += e;
708                                 i -= 1;
709                                 mnfree(cur);
710                         } else {
711                                 prev = cur;
712                         }
713                 } else {
714                         prev = cur;
715                 }
716                 cur = prev->m_next;
717         }
718         *end = prev;
719         return i;
720 error:
721         adios(EX_CONFIG, NULL, "can't parse alias %s: %s", cur->m_mbox, cp);
722         return 0; /* not reached */
723 }