Don't allow blind aliases with sendmail/pipe mts. Before this change,
[mmh] / uip / post.c
1
2 /*
3  * post.c -- enter messages into the mail transport system
4  *
5  * This code is Copyright (c) 2002, by the authors of nmh.  See the
6  * COPYRIGHT file in the root directory of the nmh distribution for
7  * complete copyright information.
8  */
9
10 #include <h/mh.h>
11 #include <fcntl.h>
12 #include <h/signals.h>
13 #include <h/addrsbr.h>
14 #include <h/aliasbr.h>
15 #include <h/dropsbr.h>
16 #include <h/mime.h>
17 #include <h/utils.h>
18
19 #include <h/tws.h>
20 #include <h/mts.h>
21
22 #include <errno.h>
23 #include <signal.h>
24
25 #ifdef HAVE_SYS_TIME_H
26 # include <sys/time.h>
27 #endif
28 #include <time.h>
29
30 #include <mts/smtp/smtp.h>
31
32 #ifndef CYRUS_SASL
33 # define SASLminc(a) (a)
34 #else /* CYRUS_SASL */
35 # define SASLminc(a)  0
36 #endif /* CYRUS_SASL */
37
38 #ifndef TLS_SUPPORT
39 # define TLSminc(a)  (a)
40 #else /* TLS_SUPPORT */
41 # define TLSminc(a)   0
42 #endif /* TLS_SUPPORT */
43
44 #define FCCS            10      /* max number of fccs allowed */
45
46 /* In the following array of structures, the numeric second field of the
47    structures (minchars) is apparently used like this:
48
49    -# : Switch can be abbreviated to # characters; switch hidden in -help.
50    0  : Switch can't be abbreviated;               switch shown in -help.
51    #  : Switch can be abbreviated to # characters; switch shown in -help. */
52
53 static struct swit switches[] = {
54 #define ALIASW                    0
55     { "alias aliasfile", 0 },
56 #define CHKSW                     1
57     { "check", -5 },                    /* interface from whom */
58 #define NCHKSW                    2
59     { "nocheck", -7 },                  /* interface from whom */
60 #define DEBUGSW                   3
61     { "debug", -5 },
62 #define DISTSW                    4
63     { "dist", -4 },                     /* interface from dist */
64 #define FILTSW                    5
65     { "filter filterfile", 0 },
66 #define NFILTSW                   6
67     { "nofilter", 0 },
68 #define FRMTSW                    7
69     { "format", 0 },
70 #define NFRMTSW                   8
71     { "noformat", 0 },
72 #define LIBSW                     9
73     { "library directory", -7 },        /* interface from send, whom */
74 #define MIMESW                   10
75     { "mime", 0 },
76 #define NMIMESW                  11
77     { "nomime", 0 },
78 #define MSGDSW                   12
79     { "msgid", 0 },
80 #define NMSGDSW                  13
81     { "nomsgid", 0 },
82 #define VERBSW                   14
83     { "verbose", 0 },
84 #define NVERBSW                  15
85     { "noverbose", 0 },
86 #define WATCSW                   16
87     { "watch", 0 },
88 #define NWATCSW                  17
89     { "nowatch", 0 },
90 #define WHOMSW                   18
91     { "whom", -4 },                     /* interface from whom */
92 #define WIDTHSW                  19
93     { "width columns", 0 },
94 #define VERSIONSW                20
95     { "version", 0 },
96 #define HELPSW                   21
97     { "help", 0 },
98 #define BITSTUFFSW               22
99     { "dashstuffing", -12 },            /* should we dashstuff BCC messages? */
100 #define NBITSTUFFSW              23
101     { "nodashstuffing", -14 },
102 #define ANNOSW                   24
103     { "idanno number", -6 },            /* interface from send    */
104 #define CLIESW                   25
105     { "client host", -6 },
106 #define SERVSW                   26
107     { "server host", 6 },               /* specify alternate SMTP server */
108 #define SNOOPSW                  27
109     { "snoop", -5 },                    /* snoop the SMTP transaction */
110 #define PARTSW                   28
111     { "partno", -6 },
112 #define QUEUESW                  29
113     { "queued", -6 },
114 #define SASLSW                   30
115     { "sasl", SASLminc(-4) },
116 #define NOSASLSW                 31
117     { "nosasl", SASLminc(-6) },
118 #define SASLMXSSFSW              32
119     { "saslmaxssf", SASLminc(-10) },
120 #define SASLMECHSW               33
121     { "saslmech", SASLminc(-5) },
122 #define USERSW                   34
123     { "user", SASLminc(-4) },
124 #define PORTSW                   35
125     { "port server port name/number", 4 },
126 #define TLSSW                    36
127     { "tls", TLSminc(-3) },
128 #define NTLSSW                   37
129     { "notls", TLSminc(-5) },
130 #define FILEPROCSW               38
131     { "fileproc", -4 },
132 #define MHLPROCSW                39
133     { "mhlproc", -3 },
134 #define MTSSW                    40
135     { "mts smtp|sendmail/smtp|sendmail/pipe", 2 },
136 #define MESSAGEIDSW              41
137     { "messageid localname|random", 2 },
138     { NULL, 0 }
139 };
140
141
142 struct headers {
143     char *value;
144     unsigned int flags;
145     unsigned int set;
146 };
147
148 /*
149  * flags for headers->flags
150  */
151 #define HNOP  0x0000    /* just used to keep .set around                      */
152 #define HBAD  0x0001    /* bad header - don't let it through                  */
153 #define HADR  0x0002    /* header has an address field                        */
154 #define HSUB  0x0004    /* Subject: header                                    */
155 #define HTRY  0x0008    /* try to send to addrs on header                     */
156 #define HBCC  0x0010    /* don't output this header, unless MTS_SENDMAIL_PIPE */
157 #define HMNG  0x0020    /* munge this header                                  */
158 #define HNGR  0x0040    /* no groups allowed in this header                   */
159 #define HFCC  0x0080    /* FCC: type header                                   */
160 #define HNIL  0x0100    /* okay for this header not to have addrs             */
161 #define HIGN  0x0200    /* ignore this header                                 */
162 #define HDCC  0x0400    /* another undocumented feature                       */
163 #define HONE  0x0800    /* Only (zero or) one address allowed                 */
164 #define HEFM  0x1000    /* Envelope-From: header                              */
165
166 /*
167  * flags for headers->set
168  */
169 #define MFRM  0x0001    /* we've seen a From:        */
170 #define MDAT  0x0002    /* we've seen a Date:        */
171 #define MRFM  0x0004    /* we've seen a Resent-From: */
172 #define MVIS  0x0008    /* we've seen sighted addrs  */
173 #define MINV  0x0010    /* we've seen blind addrs    */
174 #define MSND  0x0020    /* we've seen a Sender:      */
175 #define MRSN  0x0040    /* We've seen a Resent-Sendr:*/
176 #define MEFM  0x0080    /* We've seen Envelope-From: */
177
178
179 static struct headers NHeaders[] = {
180     { "Return-Path",   HBAD,                0 },
181     { "Received",      HBAD,                0 },
182     { "Reply-To",      HADR|HNGR,           0 },
183     { "From",          HADR|HNGR,           MFRM },
184     { "Sender",        HADR|HNGR|HONE,      MSND },
185     { "Date",          HBAD,                0 },
186     { "Subject",       HSUB,                0 },
187     { "To",            HADR|HTRY,           MVIS },
188     { "cc",            HADR|HTRY,           MVIS },
189     { "Bcc",           HADR|HTRY|HBCC|HNIL, MINV },
190     { "Dcc",           HADR|HTRY|HDCC|HNIL, MVIS },     /* sorta cc & bcc combined */
191     { "Message-ID",    HBAD,                0 },
192     { "Fcc",           HFCC,                0 },
193     { "Envelope-From", HADR|HONE|HEFM,      MEFM },
194     { NULL,            0,                   0 }
195 };
196
197 static struct headers RHeaders[] = {
198     { "Resent-Reply-To",   HADR|HNGR,           0 },
199     { "Resent-From",       HADR|HNGR,           MRFM },
200     { "Resent-Sender",     HADR|HNGR,           MRSN },
201     { "Resent-Date",       HBAD,                0 },
202     { "Resent-Subject",    HSUB,                0 },
203     { "Resent-To",         HADR|HTRY,           MVIS },
204     { "Resent-cc",         HADR|HTRY,           MVIS },
205     { "Resent-Bcc",        HADR|HTRY|HBCC,      MINV },
206     { "Resent-Message-ID", HBAD,                0 },
207     { "Resent-Fcc",        HFCC,                0 },
208     { "Reply-To",          HADR,                0 },
209     { "From",              HADR|HNGR,           MFRM },
210     { "Sender",            HADR|HNGR,           MSND },
211     { "Date",              HNOP,                MDAT },
212     { "To",                HADR|HNIL,           0 },
213     { "cc",                HADR|HNIL,           0 },
214     { "Bcc",               HADR|HTRY|HBCC|HNIL, 0 },
215     { "Fcc",               HIGN,                0 },
216     { "Envelope-From",     HADR|HONE|HEFM,      MEFM },
217     { NULL,                0,                   0 }
218 };
219
220 static short fccind = 0;        /* index into fccfold[] */
221 static short outputlinelen = OUTPUTLINELEN;
222
223 static int pfd = NOTOK;         /* fd to write annotation list to        */
224 static uid_t myuid= -1;         /* my user id                            */
225 static gid_t mygid= -1;         /* my group id                           */
226 static int recipients = 0;      /* how many people will get a copy       */
227 static int unkadr = 0;          /* how many of those were unknown        */
228 static int badadr = 0;          /* number of bad addrs                   */
229 static int badmsg = 0;          /* message has bad semantics             */
230 static int verbose = 0;         /* spell it out                          */
231 static int format = 1;          /* format addresses                      */
232 static int mime = 0;            /* use MIME-style encapsulations for Bcc */
233 static int msgid = 0;           /* add msgid                             */
234 static int debug = 0;           /* debugging post                        */
235 static int watch = 0;           /* watch the delivery process            */
236 static int whomsw = 0;          /* we are whom not post                  */
237 static int checksw = 0;         /* whom -check                           */
238 static int linepos=0;           /* putadr()'s position on the line       */
239 static int nameoutput=0;        /* putadr() has output header name       */
240 static int sasl=0;              /* Use SASL auth for SMTP                */
241 static int saslssf=-1;          /* Our maximum SSF for SASL              */
242 static char *saslmech=NULL;     /* Force use of particular SASL mech     */
243 static char *user=NULL;         /* Authenticate as this user             */
244 static char *port="smtp";       /* Name of server port for SMTP          */
245 static int tls=0;               /* Use TLS for encryption                */
246 static int fromcount=0;         /* Count of addresses on From: header    */
247 static int seensender=0;        /* Have we seen a Sender: header?        */
248
249 static unsigned msgflags = 0;   /* what we've seen */
250
251 #define NORMAL 0
252 #define RESENT 1
253 static int msgstate = NORMAL;
254
255 static time_t tclock = 0;       /* the time we started (more or less) */
256
257 static SIGNAL_HANDLER hstat, istat, qstat, tstat;
258
259 static char tmpfil[BUFSIZ];
260 static char bccfil[BUFSIZ];
261
262 static char from[BUFSIZ];       /* my network address            */
263 static char sender[BUFSIZ];     /* my Sender: header             */
264 static char efrom[BUFSIZ];      /* my Envelope-From: header      */
265 static char fullfrom[BUFSIZ];   /* full contents of From header  */
266 static char signature[BUFSIZ];  /* my signature                  */
267 static char *filter = NULL;     /* the filter for BCC'ing        */
268 static char *subject = NULL;    /* the subject field for BCC'ing */
269 static char *fccfold[FCCS];     /* foldernames for FCC'ing       */
270
271 static struct headers  *hdrtab; /* table for the message we're doing */
272
273 static struct mailname localaddrs;              /* local addrs     */
274 static struct mailname netaddrs;                /* network addrs   */
275 static struct mailname uuaddrs;                 /* uucp addrs      */
276 static struct mailname tmpaddrs;                /* temporary queue */
277
278 static int snoop      = 0;
279 static char *clientsw = NULL;
280 static char *serversw = NULL;
281
282 extern struct smtp sm_reply;
283
284 static char prefix[] = "----- =_aaaaaaaaaa";
285
286 static char *partno = NULL;
287 static int queued = 0;
288
289 /*
290  * static prototypes
291  */
292 static void putfmt (char *, char *, FILE *);
293 static void start_headers (void);
294 static void finish_headers (FILE *);
295 static int get_header (char *, struct headers *);
296 static int putadr (char *, char *, struct mailname *, FILE *, unsigned int);
297 static void putgrp (char *, char *, FILE *, unsigned int);
298 static int insert (struct mailname *);
299 static void pl (void);
300 static void anno (void);
301 static int annoaux (struct mailname *);
302 static void insert_fcc (struct headers *, unsigned char *);
303 static void make_bcc_file (int);
304 static void verify_all_addresses (int, char *);
305 static void chkadr (void);
306 static void sigon (void);
307 static void sigoff (void);
308 static void p_refile (char *);
309 static void fcc (char *, char *);
310 static void die (char *, char *, ...);
311 static void post (char *, int, int, char *);
312 static void do_text (char *file, int fd);
313 static void do_an_address (struct mailname *, int);
314 static void do_addresses (int, int);
315 static int find_prefix (void);
316
317
318 int
319 main (int argc, char **argv)
320 {
321     int state, compnum, dashstuff = 0;
322     char *cp, *msg = NULL, **argp, **arguments, *envelope;
323     char buf[BUFSIZ], name[NAMESZ];
324     FILE *in, *out;
325
326 #ifdef LOCALE
327     setlocale(LC_ALL, "");
328 #endif
329     invo_name = r1bindex (argv[0], '/');
330
331     /* foil search of user profile/context */
332     if (context_foil (NULL) == -1)
333         done (1);
334
335     mts_init (invo_name);
336     arguments = getarguments (invo_name, argc, argv, 0);
337     argp = arguments;
338
339     while ((cp = *argp++)) {
340         if (*cp == '-') {
341             switch (smatch (++cp, switches)) {
342                 case AMBIGSW: 
343                     ambigsw (cp, switches);
344                     done (1);
345                 case UNKWNSW: 
346                     adios (NULL, "-%s unknown", cp);
347
348                 case HELPSW: 
349                     snprintf (buf, sizeof(buf), "%s [switches] file", invo_name);
350                     print_help (buf, switches, 0);
351                     done (0);
352                 case VERSIONSW:
353                     print_version(invo_name);
354                     done (0);
355
356                 case LIBSW:
357                     if (!(cp = *argp++) || *cp == '-')
358                         adios (NULL, "missing argument to %s", argp[-2]);
359                     /* create a minimal context */
360                     if (context_foil (cp) == -1)
361                         done (1);
362                     continue;
363
364                 case ALIASW: 
365                     if (!(cp = *argp++) || *cp == '-')
366                         adios (NULL, "missing argument to %s", argp[-2]);
367                     if ((state = alias (cp)) != AK_OK)
368                         adios (NULL, "aliasing error in %s - %s",
369                                 cp, akerror (state));
370                     continue;
371
372                 case CHKSW: 
373                     checksw++;
374                     continue;
375                 case NCHKSW: 
376                     checksw = 0;
377                     continue;
378
379                 case DEBUGSW: 
380                     debug++;
381                     continue;
382
383                 case DISTSW:
384                     msgstate = RESENT;
385                     continue;
386
387                 case FILTSW:
388                     if (!(filter = *argp++) || *filter == '-')
389                         adios (NULL, "missing argument to %s", argp[-2]);
390                     mime = 0;
391                     continue;
392                 case NFILTSW:
393                     filter = NULL;
394                     continue;
395                 
396                 case FRMTSW: 
397                     format++;
398                     continue;
399                 case NFRMTSW: 
400                     format = 0;
401                     continue;
402
403                 case BITSTUFFSW:
404                     dashstuff = 1;
405                     continue;
406                 case NBITSTUFFSW:
407                     dashstuff = -1;
408                     continue;
409
410                 case MIMESW:
411                     mime++;
412                     filter = NULL;
413                     continue;
414                 case NMIMESW: 
415                     mime = 0;
416                     continue;
417
418                 case MSGDSW: 
419                     msgid++;
420                     continue;
421                 case NMSGDSW: 
422                     msgid = 0;
423                     continue;
424
425                 case VERBSW: 
426                     verbose++;
427                     continue;
428                 case NVERBSW: 
429                     verbose = 0;
430                     continue;
431
432                 case WATCSW: 
433                     watch++;
434                     continue;
435                 case NWATCSW: 
436                     watch = 0;
437                     continue;
438
439                 case WHOMSW: 
440                     whomsw++;
441                     continue;
442
443                 case WIDTHSW: 
444                     if (!(cp = *argp++) || *cp == '-')
445                         adios (NULL, "missing argument to %s", argp[-2]);
446                     if ((outputlinelen = atoi (cp)) < 10)
447                         adios (NULL, "impossible width %d", outputlinelen);
448                     continue;
449
450                 case ANNOSW: 
451                     if (!(cp = *argp++) || *cp == '-')
452                         adios (NULL, "missing argument to %s", argp[-2]);
453                     if ((pfd = atoi (cp)) <= 2)
454                         adios (NULL, "bad argument %s %s", argp[-2], cp);
455                     continue;
456
457                 case CLIESW:
458                     if (!(clientsw = *argp++) || *clientsw == '-')
459                         adios (NULL, "missing argument to %s", argp[-2]);
460                     continue;
461                 case SERVSW:
462                     if (!(serversw = *argp++) || *serversw == '-')
463                         adios (NULL, "missing argument to %s", argp[-2]);
464                     continue;
465                 case SNOOPSW:
466                     snoop++;
467                     continue;
468
469                 case PARTSW:
470                     if (!(partno = *argp++) || *partno == '-')
471                         adios (NULL, "missing argument to %s", argp[-2]);
472                     continue;
473
474                 case QUEUESW:
475                     queued++;
476                     continue;
477                 
478                 case SASLSW:
479                     sasl++;
480                     continue;
481
482                 case NOSASLSW:
483                     sasl = 0;
484                     continue;
485
486                 case SASLMXSSFSW:
487                     if (!(cp = *argp++) || *cp == '-')
488                         adios (NULL, "missing argument to %s", argp[-2]);
489                     saslssf = atoi(cp);
490                     continue;
491                 
492                 case SASLMECHSW:
493                     if (!(saslmech = *argp++) || *saslmech == '-')
494                         adios (NULL, "missing argument to %s", argp[-2]);
495                     continue;
496                 
497                 case USERSW:
498                     if (!(user = *argp++) || *user == '-')
499                         adios (NULL, "missing argument to %s", argp[-2]);
500                     continue;
501
502                 case PORTSW:
503                     if (!(port = *argp++) || *port == '-')
504                         adios (NULL, "missing argument to %s", argp[-2]);
505                     continue;
506
507                 case TLSSW:
508                     tls++;
509                     continue;
510
511                 case NTLSSW:
512                     tls = 0;
513                     continue;
514
515                 case FILEPROCSW:
516                     if (!(cp = *argp++) || *cp == '-')
517                         adios (NULL, "missing argument to %s", argp[-2]);
518                     fileproc = cp;
519                     continue;
520
521                 case MHLPROCSW:
522                     if (!(cp = *argp++) || *cp == '-')
523                         adios (NULL, "missing argument to %s", argp[-2]);
524                     mhlproc = cp;
525                     continue;
526
527                 case MTSSW:
528                     if (!(cp = *argp++) || *cp == '-')
529                         adios (NULL, "missing argument to %s", argp[-2]);
530                     save_mts_method (cp);
531                     continue;
532
533                 case MESSAGEIDSW:
534                     if (!(cp = *argp++) || *cp == '-')
535                         adios (NULL, "missing argument to %s", argp[-2]);
536                     if (save_message_id_style (cp) != 0)
537                         adios (NULL, "unsupported messageid \"%s\"", cp);
538                     continue;
539             }
540         }
541         if (msg)
542             adios (NULL, "only one message at a time!");
543         else
544             msg = cp;
545     }
546
547     alias (AliasFile);
548
549     if (!msg)
550         adios (NULL, "usage: %s [switches] file", invo_name);
551
552     if (outputlinelen < 10)
553         adios (NULL, "impossible width %d", outputlinelen);
554
555     if ((in = fopen (msg, "r")) == NULL)
556         adios (msg, "unable to open");
557
558     start_headers ();
559     if (debug) {
560         verbose++;
561         discard (out = stdout); /* XXX: reference discard() to help loader */
562     } else {
563         if (whomsw) {
564             if ((out = fopen ("/dev/null", "w")) == NULL)
565                 adios ("/dev/null", "unable to open");
566         } else {
567             char *cp = m_mktemp(m_maildir(invo_name), NULL, &out);
568             if (cp == NULL) {
569                 cp = m_mktemp2(NULL, invo_name, NULL, &out);
570                 if (cp == NULL) {
571                     adios ("post", "unable to create temporary file");
572                 }
573             }
574             strncpy(tmpfil, cp, sizeof(tmpfil));
575             chmod (tmpfil, 0600);
576         }
577     }
578
579     hdrtab = msgstate == NORMAL ? NHeaders : RHeaders;
580
581     for (compnum = 1, state = FLD;;) {
582         switch (state = m_getfld (state, name, buf, sizeof(buf), in)) {
583             case FLD: 
584             case FLDEOF: 
585             case FLDPLUS: 
586                 compnum++;
587                 cp = add (buf, NULL);
588                 while (state == FLDPLUS) {
589                     state = m_getfld (state, name, buf, sizeof(buf), in);
590                     cp = add (buf, cp);
591                 }
592                 putfmt (name, cp, out);
593                 free (cp);
594                 if (state != FLDEOF)
595                     continue;
596                 finish_headers (out);
597                 break;
598
599             case BODY: 
600             case BODYEOF: 
601                 finish_headers (out);
602                 if (whomsw)
603                     break;
604                 fprintf (out, "\n%s", buf);
605                 while (state == BODY) {
606                     state = m_getfld (state, name, buf, sizeof(buf), in);
607                     fputs (buf, out);
608                 }
609                 break;
610
611             case FILEEOF: 
612                 finish_headers (out);
613                 break;
614
615             case LENERR: 
616             case FMTERR: 
617                 adios (NULL, "message format error in component #%d", compnum);
618
619             default: 
620                 adios (NULL, "getfld() returned %d", state);
621         }
622         break;
623     }
624
625     if (pfd != NOTOK)
626         anno ();
627     fclose (in);
628
629     if (debug) {
630         pl ();
631         done (0);
632     } else {
633         fclose (out);
634     }
635
636     /*
637      * Here's how we decide which address to use as the envelope-from
638      * address for SMTP.
639      *
640      * - If we were given an Envelope-From header, use that.
641      * - If we were given a Sender: address, use that.
642      * - Otherwise, use the address on the From: line
643      */
644
645     if (msgflags & MEFM) {
646         envelope = efrom;
647     } else if (seensender) {
648         envelope = sender;
649     } else {
650         envelope = from;
651     }
652
653     /* If we are doing a "whom" check */
654     if (whomsw) {
655         /* This won't work with MTS_SENDMAIL_PIPE. */
656         verify_all_addresses (1, envelope);
657         done (0);
658     }
659
660     if (msgflags & MINV) {
661         make_bcc_file (dashstuff);
662         if (msgflags & MVIS) {
663             if (sm_mts != MTS_SENDMAIL_PIPE) {
664                 /* It would be nice to have support to call
665                    verify_all_addresses with MTS_SENDMAIL_PIPE, but
666                    that might require running sendmail as root.  Note
667                    that spost didn't verify addresses. */
668                 verify_all_addresses (verbose, envelope);
669             }
670             post (tmpfil, 0, verbose, envelope);
671         }
672         post (bccfil, 1, verbose, envelope);
673         unlink (bccfil);
674     } else {
675         post (tmpfil, 0, isatty (1), envelope);
676     }
677
678     p_refile (tmpfil);
679     unlink (tmpfil);
680
681     if (verbose)
682         printf (partno ? "Partial Message #%s Processed\n" : "Message Processed\n",
683                 partno);
684     done (0);
685     return 1;
686 }
687
688
689 /*
690  * DRAFT GENERATION
691  */
692
693 static void
694 putfmt (char *name, char *str, FILE *out)
695 {
696     int count, grp, i, keep;
697     char *cp, *pp, *qp;
698     char namep[BUFSIZ];
699     struct mailname *mp = NULL, *np = NULL;
700     struct headers *hdr;
701
702     while (*str == ' ' || *str == '\t')
703         str++;
704
705     if (msgstate == NORMAL && uprf (name, "resent")) {
706         advise (NULL, "illegal header line -- %s:", name);
707         badmsg++;
708         return;
709     }
710
711     if ((i = get_header (name, hdrtab)) == NOTOK) {
712         if (strncasecmp (name, "nmh-", 4)) {
713             fprintf (out, "%s: %s", name, str);
714         } else {
715             /* Filter out all Nmh-* headers, because Norm asked.  They
716                should never have reached this point.  Warn about any
717                that are non-empty. */
718             if (strcmp (str, "\n")) {
719                 char *newline = strchr (str, '\n');
720                 if (newline) *newline = '\0';
721                 if (! whomsw) {
722                     advise (NULL, "ignoring header line -- %s: %s", name, str);
723                 }
724             }
725         }
726
727         return;
728     }
729
730     hdr = &hdrtab[i];
731     if (hdr->flags & HIGN) {
732         return;
733     }
734     if (hdr->flags & HBAD) {
735         advise (NULL, "illegal header line -- %s:", name);
736         badmsg++;
737         return;
738     }
739     msgflags |= (hdr->set & ~(MVIS | MINV));
740
741     if (hdr->flags & HSUB)
742         subject = subject ? add (str, add ("\t", subject)) : getcpy (str);
743     if (hdr->flags & HFCC) {
744         if ((cp = strrchr(str, '\n')))
745             *cp = 0;
746         for (cp = pp = str; (cp = strchr(pp, ',')); pp = cp) {
747             *cp++ = 0;
748             insert_fcc (hdr, pp);
749         }
750         insert_fcc (hdr, pp);
751         return;
752     }
753
754     if (!(hdr->flags & HADR)) {
755         fprintf (out, "%s: %s", name, str);
756         return;
757     }
758
759     tmpaddrs.m_next = NULL;
760     for (count = 0; (cp = getname (str)); count++)
761         if ((mp = getm (cp, NULL, 0, AD_HOST, NULL))) {
762             if (tmpaddrs.m_next)
763                 np->m_next = mp;
764             else
765                 tmpaddrs.m_next = mp;
766             np = mp;
767         }
768         else
769             if (hdr->flags & HTRY)
770                 badadr++;
771             else
772                 badmsg++;
773
774     if (count < 1) {
775         if (hdr->flags & HNIL)
776             fprintf (out, "%s: %s", name, str);
777         else {
778             /*
779              * Sender (or Resent-Sender) can have only one address
780              */
781             if ((msgstate == RESENT) ? (hdr->set & MRSN)
782                                         : (hdr->set & MSND)) {
783                 advise (NULL, "%s: field requires one address", name);
784                 badmsg++;
785             }
786 #ifdef notdef
787             advise (NULL, "%s: field requires at least one address", name);
788             badmsg++;
789 #endif /* notdef */
790         }
791         return;
792     }
793
794     if (count > 1 && (hdr->flags & HONE)) {
795         advise (NULL, "%s: field only permits one address", name);
796         badmsg++;
797         return;
798     }
799
800     nameoutput = linepos = 0;
801     snprintf (namep, sizeof(namep), "%s%s",
802                 (hdr->flags & HMNG) ? "Original-" : "", name);
803
804     for (grp = 0, mp = tmpaddrs.m_next; mp; mp = np)
805         if (mp->m_nohost) {     /* also used to test (hdr->flags & HTRY) */
806             /* The address doesn't include a host, so it might be an alias. */
807             pp = akvalue (mp->m_mbox);  /* do mh alias substitution */
808             qp = akvisible () ? mp->m_mbox : "";
809             np = mp;
810             if (np->m_gname)
811                 putgrp (namep, np->m_gname, out, hdr->flags);
812             while ((cp = getname (pp))) {
813                 if (!(mp = getm (cp, NULL, 0, AD_HOST, NULL))) {
814                     badadr++;
815                     continue;
816                 }
817
818                 /*
819                  * If it's a From: or Resent-From: header, save the address
820                  * for later possible use (as the envelope address for SMTP)
821                  */
822
823                 if ((msgstate == RESENT) ? (hdr->set & MRFM)
824                                                 : (hdr->set & MFRM)) {
825                     strncpy(from, auxformat(mp, 0), sizeof(from) - 1);
826                     from[sizeof(from) - 1] = '\0';
827                     fromcount = count;
828                 }
829
830                 /*
831                  * Also save the Sender: or Resent-Sender: header as well
832                  */
833
834                 if ((msgstate == RESENT) ? (hdr->set & MRSN)
835                                                 : (hdr->set & MSND)) {
836                     strncpy(sender, auxformat(mp, 0), sizeof(sender) - 1);
837                     sender[sizeof(sender) - 1] = '\0';
838                     seensender++;
839                 }
840
841                 /*
842                  * ALSO ... save Envelope-From
843                  */
844
845                 if (hdr->set & MEFM) {
846                     strncpy(efrom, auxformat(mp, 0), sizeof(efrom) - 1);
847                     efrom[sizeof(efrom) - 1] = '\0';
848                 }
849
850                 if (hdr->flags & HBCC)
851                     mp->m_bcc++;
852                 if (np->m_ingrp)
853                     mp->m_ingrp = np->m_ingrp;
854                 else
855                     if (mp->m_gname)
856                         putgrp (namep, mp->m_gname, out, hdr->flags);
857                 if (mp->m_ingrp) {
858                     if (sm_mts == MTS_SENDMAIL_PIPE) {
859                         /* Catch this before sendmail chokes with:
860                            "553 List:; syntax illegal for recipient
861                             addresses".
862                            If we wanted to, we could expand out blind
863                            aliases and put them in Bcc:, but then
864                            they'd have the Blind-Carbon-Copy
865                            indication. */
866                         adios (NULL,
867                                "blind aliases not compatible with"
868                                " sendmail/pipe");
869                     }
870
871                     grp++;
872                 }
873                 if (putadr (namep, qp, mp, out, hdr->flags))
874                     msgflags |= (hdr->set & (MVIS | MINV));
875                 else
876                     mnfree (mp);
877             }
878             mp = np;
879             np = np->m_next;
880             mnfree (mp);
881         }
882         else {
883             /* Address includes a host, so no alias substitution is needed. */
884
885             /*
886              * If it's a From: or Resent-From header, save the address
887              * for later possible use (as the envelope address for SMTP)
888              */
889
890             if ((msgstate == RESENT) ? (hdr->set & MRFM)
891                                             : (hdr->set & MFRM)) {
892                 strncpy(from, auxformat(mp, 0), sizeof(from) - 1);
893                 fromcount = count;
894             }
895
896             /*
897              * Also save the Sender: header as well
898              */
899
900             if ((msgstate == RESENT) ? (hdr->set & MRSN)
901                                             : (hdr->set & MSND)) {
902                 strncpy(sender, auxformat(mp, 0), sizeof(sender) - 1);
903                 sender[sizeof(sender) - 1] = '\0';
904                 seensender++;
905             }
906
907             /*
908              * ALSO ... save Envelope-From
909              */
910
911             if (hdr->set & MEFM) {
912                 strncpy(efrom, auxformat(mp, 0), sizeof(efrom) - 1);
913                 efrom[sizeof(efrom) - 1] = '\0';
914             }
915
916             if (hdr->flags & HBCC)
917                 mp->m_bcc++;
918             if (mp->m_gname)
919                 putgrp (namep, mp->m_gname, out, hdr->flags);
920             if (mp->m_ingrp)
921                 grp++;
922             keep = putadr (namep, "", mp, out, hdr->flags);
923             np = mp->m_next;
924             if (keep) {
925                 mp->m_next = NULL;
926                 msgflags |= (hdr->set & (MVIS | MINV));
927             }
928             else
929                 mnfree (mp);
930         }
931
932     /*
933      * If this is a From:/Resent-From: header, save the full thing for
934      * later in case we need it for use when constructing a Bcc draft message
935      */
936
937     if ((msgstate == RESENT) ? (hdr->set & MRFM) : (hdr->set & MFRM)) {
938         strncpy(fullfrom, str, sizeof(fullfrom));
939         fullfrom[sizeof(fullfrom) - 1] = 0;
940         /*
941          * Strip off any trailing newlines
942          */
943
944         while (strlen(fullfrom) > 0 && fullfrom[strlen(fullfrom) - 1] == '\n') {
945             fullfrom[strlen(fullfrom) - 1] = '\0';
946         }
947     }
948
949     if (grp > 0 && (hdr->flags & HNGR)) {
950         advise (NULL, "%s: field does not allow groups", name);
951         badmsg++;
952     }
953     if (linepos) {
954         putc ('\n', out);
955     }
956 }
957
958
959 static void
960 start_headers (void)
961 {
962     unsigned char  *cp;
963     char sigbuf[BUFSIZ];
964     struct mailname *mp;
965
966     myuid = getuid ();
967     mygid = getgid ();
968     time (&tclock);
969
970     /*
971      * Probably not necessary, but just in case ...
972      */
973
974     from[0] = '\0';
975     efrom[0] = '\0';
976     sender[0] = '\0';
977     fullfrom[0] = '\0';
978
979     if ((cp = getfullname ()) && *cp) {
980         strncpy (sigbuf, cp, sizeof(sigbuf));
981         snprintf (signature, sizeof(signature), "%s <%s>",
982                 sigbuf, getlocaladdr());
983         if ((cp = getname (signature)) == NULL)
984             adios (NULL, "getname () failed -- you lose extraordinarily big");
985         if ((mp = getm (cp, NULL, 0, AD_HOST, NULL)) == NULL)
986             adios (NULL, "bad signature '%s'", sigbuf);
987         mnfree (mp);
988         while (getname (""))
989             continue;
990     } else {
991         strncpy (signature, getlocaladdr(), sizeof(signature));
992     }
993 }
994
995
996 /*
997  * Now that we've outputted the header fields in the draft
998  * message, we will now output any remaining header fields
999  * that we need to add/create.
1000  */
1001
1002 static void
1003 finish_headers (FILE *out)
1004 {
1005     switch (msgstate) {
1006         case NORMAL: 
1007             if (!(msgflags & MFRM)) {
1008                 /*
1009                  * A From: header is now required in the draft.
1010                  */
1011                 advise (NULL, "message has no From: header");
1012                 advise (NULL, "See default components files for examples");
1013                 badmsg++;
1014                 break;
1015             }
1016
1017             if (fromcount > 1 && (seensender == 0 && !(msgflags & MEFM))) {
1018                 advise (NULL, "A Sender: or Envelope-From: header is required "
1019                         "with multiple\nFrom: addresses");
1020                 badmsg++;
1021                 break;
1022             }
1023
1024             if (whomsw)
1025                 break;
1026
1027             fprintf (out, "Date: %s\n", dtime (&tclock, 0));
1028             if (msgid)
1029                 fprintf (out, "Message-ID: %s\n", message_id (tclock, 0));
1030             /*
1031              * If we have multiple From: addresses, make sure we have an
1032              * Sender: header.  If we don't have one, then generate one
1033              * from Envelope-From: (which in this case, cannot be blank)
1034              */
1035
1036             if (fromcount > 1 && seensender == 0) {
1037                 if (efrom[0] == '\0') {
1038                     advise (NULL, "Envelope-From cannot be blank when there "
1039                             "is multiple From: addresses\nand no Sender: "
1040                             "header");
1041                     badmsg++;
1042                 } else {
1043                     fprintf (out, "Sender: %s\n", efrom);
1044                 }
1045             }
1046
1047             if (!(msgflags & MVIS))
1048                 fprintf (out, "Bcc: Blind Distribution List: ;\n");
1049             break;
1050
1051         case RESENT: 
1052             if (!(msgflags & MDAT)) {
1053                 advise (NULL, "message has no Date: header");
1054                 badmsg++;
1055             }
1056             if (!(msgflags & MFRM)) {
1057                 advise (NULL, "message has no From: header");
1058                 badmsg++;
1059             }
1060             if (!(msgflags & MRFM)) {
1061                 advise (NULL, "message has no Resent-From: header");
1062                 advise (NULL, "See default components files for examples");
1063                 badmsg++;
1064                 break;
1065             }
1066             if (fromcount > 1 && (seensender == 0 && !(msgflags & MEFM))) {
1067                 advise (NULL, "A Resent-Sender: or Envelope-From: header is "
1068                         "required with multiple\nResent-From: addresses");
1069                 badmsg++;
1070                 break;
1071             }
1072
1073             if (whomsw)
1074                 break;
1075
1076             fprintf (out, "Resent-Date: %s\n", dtime (&tclock, 0));
1077             if (msgid)
1078                 fprintf (out, "Resent-Message-ID: %s\n",
1079                          message_id (tclock, 0));
1080             /*
1081              * If we have multiple Resent-From: addresses, make sure we have an
1082              * Resent-Sender: header.  If we don't have one, then generate one
1083              * from Envelope-From (which in this case, cannot be blank)
1084              */
1085
1086             if (fromcount > 1 && seensender == 0) {
1087                 if (efrom[0] == '\0') {
1088                     advise (NULL, "Envelope-From cannot be blank when there "
1089                             "is multiple Resent-From: addresses and no "
1090                             "Resent-Sender: header");
1091                     badmsg++;
1092                 } else {
1093                     fprintf (out, "Resent-Sender: %s\n", efrom);
1094                 }
1095             }
1096
1097             if (!(msgflags & MVIS))
1098                 fprintf (out, "Resent-Bcc: Blind Re-Distribution List: ;\n");
1099             break;
1100     }
1101
1102     if (badmsg)
1103         adios (NULL, "re-format message and try again");
1104     if (!recipients)
1105         adios (NULL, "no addressees");
1106 }
1107
1108
1109 static int
1110 get_header (char *header, struct headers *table)
1111 {
1112     struct headers *h;
1113
1114     for (h = table; h->value; h++)
1115         if (!mh_strcasecmp (header, h->value))
1116             return (h - table);
1117
1118     return NOTOK;
1119 }
1120
1121
1122 static int
1123 putadr (char *name, char *aka, struct mailname *mp, FILE *out, unsigned int flags)
1124 {
1125     int len;
1126     char *cp;
1127     char buffer[BUFSIZ];
1128
1129     if (mp->m_mbox == NULL || ((flags & HTRY) && !insert (mp)))
1130         return 0;
1131     if (sm_mts != MTS_SENDMAIL_PIPE &&
1132         ((flags & (HBCC | HDCC | HEFM)) || mp->m_ingrp))
1133         return 1;
1134
1135     if (!nameoutput) {
1136         fprintf (out, "%s: ", name);
1137         linepos += (nameoutput = strlen (name) + 2);
1138     }
1139
1140     if (*aka && mp->m_type != UUCPHOST && !mp->m_pers)
1141         mp->m_pers = getcpy (aka);
1142     if (format) {
1143         if (mp->m_gname) {
1144             snprintf (buffer, sizeof(buffer), "%s;", mp->m_gname);
1145             cp = buffer;
1146         } else {
1147             cp = adrformat (mp);
1148         }
1149     } else {
1150         cp = mp->m_text;
1151     }
1152     len = strlen (cp);
1153
1154     if (linepos != nameoutput) {
1155         if (len + linepos + 2 > outputlinelen)
1156             fprintf (out, ",\n%*s", linepos = nameoutput, "");
1157         else {
1158             fputs (", ", out);
1159             linepos += 2;
1160         }
1161     }
1162
1163     fputs (cp, out);
1164     linepos += len;
1165
1166     return (flags & HTRY);
1167 }
1168
1169
1170 static void
1171 putgrp (char *name, char *group, FILE *out, unsigned int flags)
1172 {
1173     int len;
1174     char *cp;
1175
1176     if (sm_mts != MTS_SENDMAIL_PIPE && (flags & HBCC))
1177         return;
1178
1179     if (!nameoutput) {
1180         fprintf (out, "%s: ", name);
1181         linepos += (nameoutput = strlen (name) + 2);
1182     }
1183
1184     cp = concat (group, ";", NULL);
1185     len = strlen (cp);
1186
1187     if (linepos > nameoutput) {
1188         if (len + linepos + 2 > outputlinelen) {
1189             fprintf (out, ",\n%*s", nameoutput, "");
1190             linepos = nameoutput;
1191         }
1192         else {
1193             fputs (", ", out);
1194             linepos += 2;
1195         }
1196     }
1197
1198     fputs (cp, out);
1199     linepos += len;
1200 }
1201
1202
1203 static int
1204 insert (struct mailname *np)
1205 {
1206     struct mailname *mp;
1207
1208     if (np->m_mbox == NULL)
1209         return 0;
1210
1211     for (mp = np->m_type == LOCALHOST ? &localaddrs
1212             : np->m_type == UUCPHOST ? &uuaddrs
1213             : &netaddrs;
1214             mp->m_next;
1215             mp = mp->m_next)
1216         if (!mh_strcasecmp (np->m_host, mp->m_next->m_host)
1217                 && !mh_strcasecmp (np->m_mbox, mp->m_next->m_mbox)
1218                 && np->m_bcc == mp->m_next->m_bcc)
1219             return 0;
1220
1221     mp->m_next = np;
1222     recipients++;
1223     return 1;
1224 }
1225
1226
1227 static void
1228 pl (void)
1229 {
1230     int i;
1231     struct mailname *mp;
1232
1233     printf ("-------\n\t-- Addresses --\nlocal:\t");
1234     for (mp = localaddrs.m_next; mp; mp = mp->m_next)
1235         printf ("%s%s%s", mp->m_mbox,
1236                 mp->m_bcc ? "[BCC]" : "",
1237                 mp->m_next ? ",\n\t" : "");
1238
1239     printf ("\nnet:\t");
1240     for (mp = netaddrs.m_next; mp; mp = mp->m_next)
1241         printf ("%s%s@%s%s%s", mp->m_path ? mp->m_path : "",
1242                 mp->m_mbox, mp->m_host,
1243                 mp->m_bcc ? "[BCC]" : "",
1244                 mp->m_next ? ",\n\t" : "");
1245
1246     printf ("\nuucp:\t");
1247     for (mp = uuaddrs.m_next; mp; mp = mp->m_next)
1248         printf ("%s!%s%s%s", mp->m_host, mp->m_mbox,
1249                 mp->m_bcc ? "[BCC]" : "",
1250                 mp->m_next ? ",\n\t" : "");
1251
1252     printf ("\n\t-- Folder Copies --\nfcc:\t");
1253     for (i = 0; i < fccind; i++)
1254         printf ("%s%s", fccfold[i], i + 1 < fccind ? ",\n\t" : "");
1255     printf ("\n");
1256 }
1257
1258
1259 static void
1260 anno (void)
1261 {
1262     struct mailname *mp;
1263
1264     for (mp = localaddrs.m_next; mp; mp = mp->m_next)
1265         if (annoaux (mp) == NOTOK)
1266             goto oops;
1267
1268     for (mp = netaddrs.m_next; mp; mp = mp->m_next)
1269         if (annoaux (mp) == NOTOK)
1270             goto oops;
1271
1272     for (mp = uuaddrs.m_next; mp; mp = mp->m_next)
1273         if (annoaux (mp) == NOTOK)
1274             break;
1275
1276 oops: ;
1277     close (pfd);
1278     pfd = NOTOK;
1279 }
1280
1281
1282 static int
1283 annoaux (struct mailname *mp)
1284 {
1285     int i;
1286     char buffer[BUFSIZ];
1287
1288     snprintf (buffer, sizeof(buffer), "%s\n", adrformat (mp));
1289     i = strlen (buffer);
1290
1291     return (write (pfd, buffer, i) == i ? OK : NOTOK);
1292 }
1293
1294
1295 static void
1296 insert_fcc (struct headers *hdr, unsigned char *pp)
1297 {
1298     unsigned char *cp;
1299
1300     for (cp = pp; isspace (*cp); cp++)
1301         continue;
1302     for (pp += strlen (pp) - 1; pp > cp && isspace (*pp); pp--)
1303         continue;
1304     if (pp >= cp)
1305         *++pp = 0;
1306     if (*cp == 0)
1307         return;
1308
1309     if (fccind >= FCCS)
1310         adios (NULL, "too many %ss", hdr->value);
1311     fccfold[fccind++] = getcpy (cp);
1312 }
1313
1314 /*
1315  * BCC GENERATION
1316  */
1317
1318 static void
1319 make_bcc_file (int dashstuff)
1320 {
1321     int fd, i;
1322     pid_t child_id;
1323     char *vec[6];
1324     FILE *out;
1325     char *tfile = NULL;
1326
1327     tfile = m_mktemp2(NULL, "bccs", NULL, &out);
1328     if (tfile == NULL) adios("bcc", "unable to create temporary file");
1329     strncpy (bccfil, tfile, sizeof(bccfil));
1330
1331     fprintf (out, "From: %s\n", fullfrom);
1332     fprintf (out, "Date: %s\n", dtime (&tclock, 0));
1333     if (msgid)
1334         fprintf (out, "Message-ID: %s\n", message_id (tclock, 0));
1335     if (subject)
1336         fprintf (out, "Subject: %s", subject);
1337     fprintf (out, "BCC:\n");
1338
1339     /*
1340      * Use MIME encapsulation for Bcc messages
1341      */
1342     if (mime) {
1343         char *cp;
1344
1345         /*
1346          * Check if any lines in the message clash with the
1347          * prefix for the MIME multipart separator.  If there
1348          * is a clash, increment one of the letters in the
1349          * prefix and check again.
1350          */
1351         if ((cp = strchr(prefix, 'a')) == NULL)
1352             adios (NULL, "lost prefix start");
1353         while (find_prefix () == NOTOK) {
1354             if (*cp < 'z')
1355                 (*cp)++;
1356             else
1357                 if (*++cp == 0)
1358                     adios (NULL, "can't find a unique delimiter string");
1359                 else
1360                     (*cp)++;
1361         }
1362
1363         fprintf (out, "%s: %s\n%s: multipart/digest; boundary=\"",
1364                  VRSN_FIELD, VRSN_VALUE, TYPE_FIELD);
1365         fprintf (out, "%s\"\n\n--%s\n\n", prefix, prefix);
1366     } else {
1367         fprintf (out, "\n------- Blind-Carbon-Copy\n\n");
1368     }
1369
1370     fflush (out);
1371
1372     /*
1373      * Do mhl filtering of Bcc messages instead
1374      * of MIME encapsulation.
1375      */
1376     if (filter != NULL) {
1377         vec[0] = r1bindex (mhlproc, '/');
1378
1379         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
1380             sleep (5);
1381         switch (child_id) {
1382             case NOTOK: 
1383                 adios ("fork", "unable to");
1384
1385             case OK: 
1386                 dup2 (fileno (out), 1);
1387
1388                 i = 1;
1389                 vec[i++] = "-forward";
1390                 vec[i++] = "-form";
1391                 vec[i++] = filter;
1392                 vec[i++] = tmpfil;
1393
1394                 /* was the flag -[no]dashstuffing specified? */
1395                 if (dashstuff > 0)
1396                     vec[i++] = "-dashstuffing";
1397                 else if (dashstuff < 0)
1398                     vec[i++] = "-nodashstuffing";
1399                 vec[i] = NULL;
1400
1401                 execvp (mhlproc, vec);
1402                 fprintf (stderr, "unable to exec ");
1403                 perror (mhlproc);
1404                 _exit (-1);
1405
1406             default: 
1407                 pidXwait (child_id, mhlproc);
1408                 break;
1409         }
1410     } else {
1411         if ((fd = open (tmpfil, O_RDONLY)) == NOTOK)
1412             adios (tmpfil, "unable to re-open");
1413
1414         /*
1415          * If using MIME encapsulation, or if the -nodashstuffing
1416          * flag was given, then just copy message.  Else do
1417          * RFC934 quoting (dashstuffing).
1418          */
1419         if (mime || dashstuff < 0)
1420             cpydata (fd, fileno (out), tmpfil, bccfil);
1421         else
1422             cpydgst (fd, fileno (out), tmpfil, bccfil);
1423         close (fd);
1424     }
1425
1426     fseek (out, 0L, SEEK_END);
1427     if (mime)
1428         fprintf (out, "\n--%s--\n", prefix);
1429     else
1430         fprintf (out, "\n------- End of Blind-Carbon-Copy\n");
1431     fclose (out);
1432 }
1433
1434
1435 /*
1436  * Scan message to check if any lines clash with
1437  * the prefix of the MIME multipart separator.
1438  */
1439
1440 static int
1441 find_prefix (void)
1442 {
1443     int result = OK;
1444     unsigned char buffer[BUFSIZ];
1445     FILE *in;
1446
1447     if ((in = fopen (tmpfil, "r")) == NULL)
1448         adios (tmpfil, "unable to re-open");
1449
1450     while (fgets (buffer, sizeof(buffer) - 1, in))
1451         if (buffer[0] == '-' && buffer[1] == '-') {
1452             unsigned char *cp;
1453
1454             for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1455                 if (!isspace (*cp))
1456                     break;
1457             *++cp = '\0';
1458             if (strcmp (buffer + 2, prefix) == 0) {
1459                 result = NOTOK;
1460                 break;
1461             }
1462         }
1463
1464     fclose (in);
1465     return result;
1466 }
1467
1468
1469 #define plural(x) (x == 1 ? "" : "s")
1470
1471 static void
1472 chkadr (void)
1473 {
1474     if (badadr && unkadr)
1475         die (NULL, "%d address%s unparsable, %d addressee%s undeliverable",
1476                 badadr, plural (badadr), unkadr, plural (badadr));
1477     if (badadr)
1478         die (NULL, "%d address%s unparsable", badadr, plural (badadr));
1479     if (unkadr)
1480         die (NULL, "%d addressee%s undeliverable", unkadr, plural (unkadr));
1481 }
1482
1483
1484 static void
1485 do_addresses (int bccque, int talk)
1486 {
1487     int retval;
1488     int state;
1489     struct mailname *lp;
1490
1491     state = 0;
1492     for (lp = localaddrs.m_next; lp; lp = lp->m_next)
1493         if (lp->m_bcc ? bccque : !bccque) {
1494             if (talk && !state)
1495                 printf ("  -- Local Recipients --\n");
1496             do_an_address (lp, talk);
1497             state++;
1498         }
1499
1500     state = 0;
1501     for (lp = uuaddrs.m_next; lp; lp = lp->m_next)
1502         if (lp->m_bcc ? bccque : !bccque) {
1503             if (talk && !state)
1504                 printf ("  -- UUCP Recipients --\n");
1505             do_an_address (lp, talk);
1506             state++;
1507         }
1508
1509     state = 0;
1510     for (lp = netaddrs.m_next; lp; lp = lp->m_next)
1511         if (lp->m_bcc ? bccque : !bccque) {
1512             if (talk && !state)
1513                 printf ("  -- Network Recipients --\n");
1514             do_an_address (lp, talk);
1515             state++;
1516         }
1517
1518     chkadr ();
1519
1520     if (rp_isbad (retval = sm_waend ()))
1521         die (NULL, "problem ending addresses; %s", rp_string (retval));
1522 }
1523
1524
1525 /*
1526  * MTS-SPECIFIC INTERACTION
1527  */
1528
1529
1530 /*
1531  * SENDMAIL/SMTP routines
1532  */
1533
1534 static void
1535 post (char *file, int bccque, int talk, char *envelope)
1536 {
1537     int fd;
1538     int retval, i;
1539     pid_t child_id;
1540
1541     if (verbose) {
1542         if (msgflags & MINV)
1543             printf (" -- Posting for %s Recipients --\n",
1544                     bccque ? "Blind" : "Sighted");
1545         else
1546             printf (" -- Posting for All Recipients --\n");
1547     }
1548
1549     sigon ();
1550
1551     if (sm_mts == MTS_SENDMAIL_PIPE) {
1552         char *sargv[16], **argp;
1553
1554         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
1555             sleep (5);
1556         switch (child_id) {
1557             case NOTOK: 
1558                 adios ("fork", "unable to");
1559
1560             case OK:
1561                 if (freopen( file, "r", stdin) == NULL) {
1562                     adios (file, "can't reopen for sendmail");
1563                 }
1564
1565                 argp = sargv;
1566                 *argp++ = "sendmail";
1567                 *argp++ = "-t"; /* read msg for recipients */
1568                 *argp++ = "-i"; /* don't stop on "." */
1569                 if (whomsw)
1570                     *argp++ = "-bv";
1571                 if (snoop)
1572                     *argp++ = "-v";
1573                 *argp = NULL;
1574
1575                 execv (sendmail, sargv);
1576                 adios (sendmail, "can't exec");
1577
1578             default: 
1579                 pidXwait (child_id, NULL);
1580                 break;
1581         }
1582     } else {
1583         if (rp_isbad (retval = sm_init (clientsw, serversw, port, watch,
1584                                         verbose, snoop, queued, sasl,
1585                                         saslssf, saslmech, user, tls))  ||
1586             rp_isbad (retval = sm_winit (envelope)))
1587             die (NULL, "problem initializing server; %s", rp_string (retval));
1588
1589         do_addresses (bccque, talk && verbose);
1590         if ((fd = open (file, O_RDONLY)) == NOTOK)
1591           die (file, "unable to re-open");
1592         do_text (file, fd);
1593         close (fd);
1594         fflush (stdout);
1595
1596         sm_end (!(msgflags & MINV) || bccque ? OK : DONE);
1597         sigoff ();
1598
1599         if (verbose) {
1600             if (msgflags & MINV)
1601                 printf (" -- %s Recipient Copies Posted --\n",
1602                         bccque ? "Blind" : "Sighted");
1603             else
1604                 printf (" -- Recipient Copies Posted --\n");
1605         }
1606
1607         fflush (stdout);
1608     }
1609 }
1610
1611
1612 /* Address Verification */
1613
1614 static void
1615 verify_all_addresses (int talk, char *envelope)
1616 {
1617     int retval;
1618     struct mailname *lp;
1619
1620     sigon ();
1621
1622     if (!whomsw || checksw)
1623         if (rp_isbad (retval = sm_init (clientsw, serversw, port, watch,
1624                                         verbose, snoop, queued, sasl,
1625                                         saslssf, saslmech, user, tls))
1626                 || rp_isbad (retval = sm_winit (envelope)))
1627             die (NULL, "problem initializing server; %s", rp_string (retval));
1628
1629     if (talk && !whomsw)
1630         printf (" -- Address Verification --\n");
1631     if (talk && localaddrs.m_next)
1632         printf ("  -- Local Recipients --\n");
1633     for (lp = localaddrs.m_next; lp; lp = lp->m_next)
1634         do_an_address (lp, talk);
1635
1636     if (talk && uuaddrs.m_next)
1637         printf ("  -- UUCP Recipients --\n");
1638     for (lp = uuaddrs.m_next; lp; lp = lp->m_next)
1639         do_an_address (lp, talk);
1640
1641     if (talk && netaddrs.m_next)
1642         printf ("  -- Network Recipients --\n");
1643     for (lp = netaddrs.m_next; lp; lp = lp->m_next)
1644         do_an_address (lp, talk);
1645
1646     chkadr ();
1647     if (talk && !whomsw)
1648         printf (" -- Address Verification Successful --\n");
1649
1650     if (!whomsw || checksw)
1651         sm_end (DONE);
1652
1653     fflush (stdout);
1654     sigoff ();
1655 }
1656
1657
1658 static void
1659 do_an_address (struct mailname *lp, int talk)
1660 {
1661     int retval;
1662     char *mbox, *host;
1663     char addr[BUFSIZ];
1664
1665     switch (lp->m_type) {
1666         case LOCALHOST: 
1667             mbox = lp->m_mbox;
1668             host = lp->m_host;
1669             strncpy (addr, mbox, sizeof(addr));
1670             break;
1671
1672         case UUCPHOST: 
1673             mbox = auxformat (lp, 0);
1674             host = NULL;
1675             snprintf (addr, sizeof(addr), "%s!%s", lp->m_host, lp->m_mbox);
1676             break;
1677
1678         default:                /* let SendMail decide if the host is bad  */
1679             mbox = lp->m_mbox;
1680             host = lp->m_host;
1681             snprintf (addr, sizeof(addr), "%s at %s", mbox, host);
1682             break;
1683     }
1684
1685     if (talk)
1686         printf ("  %s%s", addr, whomsw && lp->m_bcc ? "[BCC]" : "");
1687
1688     if (whomsw && !checksw) {
1689         putchar ('\n');
1690         return;
1691     }
1692     if (talk)
1693         printf (": ");
1694     fflush (stdout);
1695
1696     switch (retval = sm_wadr (mbox, host,
1697                          lp->m_type != UUCPHOST ? lp->m_path : NULL)) {
1698         case RP_OK: 
1699             if (talk)
1700                 printf ("address ok\n");
1701             break;
1702
1703         case RP_NO: 
1704         case RP_USER: 
1705             if (!talk)
1706                 fprintf (stderr, "  %s: ", addr);
1707             fprintf (talk ? stdout : stderr, "loses; %s\n",
1708                         rp_string (retval));
1709             unkadr++;
1710             break;
1711
1712         default: 
1713             if (!talk)
1714                 fprintf (stderr, "  %s: ", addr);
1715             die (NULL, "unexpected response; %s", rp_string (retval));
1716     }
1717
1718     fflush (stdout);
1719 }
1720
1721
1722 static void
1723 do_text (char *file, int fd)
1724 {
1725     int retval, state;
1726     char buf[BUFSIZ];
1727
1728     lseek (fd, (off_t) 0, SEEK_SET);
1729
1730     while ((state = read (fd, buf, sizeof(buf))) > 0) {
1731         if (rp_isbad (retval = sm_wtxt (buf, state)))
1732             die (NULL, "problem writing text; %s\n", rp_string (retval));
1733     }
1734
1735     if (state == NOTOK)
1736         die (file, "problem reading from");
1737
1738     switch (retval = sm_wtend ()) {
1739         case RP_OK: 
1740             break;
1741
1742         case RP_NO: 
1743         case RP_NDEL: 
1744             die (NULL, "posting failed; %s", rp_string (retval));
1745
1746         default: 
1747             die (NULL, "unexpected response; %s", rp_string (retval));
1748     }
1749 }
1750
1751
1752 /*
1753  * SIGNAL HANDLING
1754  */
1755
1756 static void
1757 sigser (int i)
1758 {
1759     NMH_UNUSED (i);
1760
1761     unlink (tmpfil);
1762     if (msgflags & MINV)
1763         unlink (bccfil);
1764
1765     if (!whomsw || checksw)
1766         sm_end (NOTOK);
1767
1768     done (1);
1769 }
1770
1771
1772 static void
1773 sigon (void)
1774 {
1775     if (debug)
1776         return;
1777
1778     hstat = SIGNAL2 (SIGHUP, sigser);
1779     istat = SIGNAL2 (SIGINT, sigser);
1780     qstat = SIGNAL2 (SIGQUIT, sigser);
1781     tstat = SIGNAL2 (SIGTERM, sigser);
1782 }
1783
1784
1785 static void
1786 sigoff (void)
1787 {
1788     if (debug)
1789         return;
1790
1791     SIGNAL (SIGHUP, hstat);
1792     SIGNAL (SIGINT, istat);
1793     SIGNAL (SIGQUIT, qstat);
1794     SIGNAL (SIGTERM, tstat);
1795 }
1796
1797 /*
1798  * FCC INTERACTION
1799  */
1800
1801 static void
1802 p_refile (char *file)
1803 {
1804     int i;
1805
1806     if (fccind == 0)
1807         return;
1808
1809     if (verbose)
1810         printf (" -- Filing Folder Copies --\n");
1811     for (i = 0; i < fccind; i++)
1812         fcc (file, fccfold[i]);
1813     if (verbose)
1814         printf (" -- Folder Copies Filed --\n");
1815 }
1816
1817
1818 /*
1819  * Call the `fileproc' to add the file to the folder.
1820  */
1821
1822 static void
1823 fcc (char *file, char *folder)
1824 {
1825     pid_t child_id;
1826     int i, status;
1827     char fold[BUFSIZ];
1828
1829     if (verbose)
1830         printf ("  %sFcc %s: ", msgstate == RESENT ? "Resent-" : "", folder);
1831     fflush (stdout);
1832
1833     for (i = 0; (child_id = fork ()) == NOTOK && i < 5; i++)
1834         sleep (5);
1835
1836     switch (child_id) {
1837         case NOTOK: 
1838             if (!verbose)
1839                 fprintf (stderr, "  %sFcc %s: ",
1840                         msgstate == RESENT ? "Resent-" : "", folder);
1841             fprintf (verbose ? stdout : stderr, "no forks, so not ok\n");
1842             break;
1843
1844         case OK: 
1845             /* see if we need to add `+' */
1846             snprintf (fold, sizeof(fold), "%s%s",
1847                     *folder == '+' || *folder == '@' ? "" : "+", folder);
1848
1849             /* now exec the fileproc */
1850             execlp (fileproc, r1bindex (fileproc, '/'),
1851                     "-link", "-file", file, fold, NULL);
1852             _exit (-1);
1853
1854         default: 
1855             if ((status = pidwait (child_id, OK))) {
1856                 if (!verbose)
1857                     fprintf (stderr, "  %sFcc %s: ",
1858                             msgstate == RESENT ? "Resent-" : "", folder);
1859                 pidstatus (status, verbose ? stdout : stderr, NULL);
1860             } else {
1861                 if (verbose)
1862                     printf ("folder ok\n");
1863             }
1864     }
1865
1866     fflush (stdout);
1867 }
1868
1869 /*
1870  * TERMINATION
1871  */
1872
1873 static void
1874 die (char *what, char *fmt, ...)
1875 {
1876     va_list ap;
1877
1878     unlink (tmpfil);
1879     if (msgflags & MINV)
1880         unlink (bccfil);
1881
1882     if (!whomsw || checksw)
1883         sm_end (NOTOK);
1884
1885     va_start(ap, fmt);
1886     advertise (what, NULL, fmt, ap);
1887     va_end(ap);
1888     done (1);
1889 }