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