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