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