526b5e4ecb857348f95d71602c33efb8b12cba17
[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         fprintf (out, "%s: %s", name, str);
713         return;
714     }
715
716     hdr = &hdrtab[i];
717     if (hdr->flags & HIGN) {
718         return;
719     }
720     if (hdr->flags & HBAD) {
721         advise (NULL, "illegal header line -- %s:", name);
722         badmsg++;
723         return;
724     }
725     msgflags |= (hdr->set & ~(MVIS | MINV));
726
727     if (hdr->flags & HSUB)
728         subject = subject ? add (str, add ("\t", subject)) : getcpy (str);
729     if (hdr->flags & HFCC) {
730         if ((cp = strrchr(str, '\n')))
731             *cp = 0;
732         for (cp = pp = str; (cp = strchr(pp, ',')); pp = cp) {
733             *cp++ = 0;
734             insert_fcc (hdr, pp);
735         }
736         insert_fcc (hdr, pp);
737         return;
738     }
739
740     if (!(hdr->flags & HADR)) {
741         fprintf (out, "%s: %s", name, str);
742         return;
743     }
744
745     tmpaddrs.m_next = NULL;
746     for (count = 0; (cp = getname (str)); count++)
747         if ((mp = getm (cp, NULL, 0, AD_HOST, NULL))) {
748             if (tmpaddrs.m_next)
749                 np->m_next = mp;
750             else
751                 tmpaddrs.m_next = mp;
752             np = mp;
753         }
754         else
755             if (hdr->flags & HTRY)
756                 badadr++;
757             else
758                 badmsg++;
759
760     if (count < 1) {
761         if (hdr->flags & HNIL)
762             fprintf (out, "%s: %s", name, str);
763         else {
764             /*
765              * Sender (or Resent-Sender) can have only one address
766              */
767             if ((msgstate == RESENT) ? (hdr->set & MRSN)
768                                         : (hdr->set & MSND)) {
769                 advise (NULL, "%s: field requires one address", name);
770                 badmsg++;
771             }
772 #ifdef notdef
773             advise (NULL, "%s: field requires at least one address", name);
774             badmsg++;
775 #endif /* notdef */
776         }
777         return;
778     }
779
780     if (count > 1 && (hdr->flags & HONE)) {
781         advise (NULL, "%s: field only permits one address", name);
782         badmsg++;
783         return;
784     }
785
786     nameoutput = linepos = 0;
787     snprintf (namep, sizeof(namep), "%s%s",
788                 (hdr->flags & HMNG) ? "Original-" : "", name);
789
790     for (grp = 0, mp = tmpaddrs.m_next; mp; mp = np)
791         if (mp->m_nohost) {     /* also used to test (hdr->flags & HTRY) */
792             /* The address doesn't include a host, so it might be an alias. */
793             pp = akvalue (mp->m_mbox);  /* do mh alias substitution */
794             qp = akvisible () ? mp->m_mbox : "";
795             np = mp;
796             if (np->m_gname)
797                 putgrp (namep, np->m_gname, out, hdr->flags);
798             while ((cp = getname (pp))) {
799                 if (!(mp = getm (cp, NULL, 0, AD_HOST, NULL))) {
800                     badadr++;
801                     continue;
802                 }
803
804                 /*
805                  * If it's a From: or Resent-From: header, save the address
806                  * for later possible use (as the envelope address for SMTP)
807                  */
808
809                 if ((msgstate == RESENT) ? (hdr->set & MRFM)
810                                                 : (hdr->set & MFRM)) {
811                     strncpy(from, auxformat(mp, 0), sizeof(from) - 1);
812                     from[sizeof(from) - 1] = '\0';
813                     fromcount = count;
814                 }
815
816                 /*
817                  * Also save the Sender: or Resent-Sender: header as well
818                  */
819
820                 if ((msgstate == RESENT) ? (hdr->set & MRSN)
821                                                 : (hdr->set & MSND)) {
822                     strncpy(sender, auxformat(mp, 0), sizeof(sender) - 1);
823                     sender[sizeof(sender) - 1] = '\0';
824                     seensender++;
825                 }
826
827                 /*
828                  * ALSO ... save Envelope-From
829                  */
830
831                 if (hdr->set & MEFM) {
832                     strncpy(efrom, auxformat(mp, 0), sizeof(efrom) - 1);
833                     efrom[sizeof(efrom) - 1] = '\0';
834                 }
835
836                 if (hdr->flags & HBCC)
837                     mp->m_bcc++;
838                 if (np->m_ingrp)
839                     mp->m_ingrp = np->m_ingrp;
840                 else
841                     if (mp->m_gname)
842                         putgrp (namep, mp->m_gname, out, hdr->flags);
843                 if (mp->m_ingrp)
844                     grp++;
845                 if (putadr (namep, qp, mp, out, hdr->flags))
846                     msgflags |= (hdr->set & (MVIS | MINV));
847                 else
848                     mnfree (mp);
849             }
850             mp = np;
851             np = np->m_next;
852             mnfree (mp);
853         }
854         else {
855             /* Address includes a host, so no alias substitution is needed. */
856
857             /*
858              * If it's a From: or Resent-From header, save the address
859              * for later possible use (as the envelope address for SMTP)
860              */
861
862             if ((msgstate == RESENT) ? (hdr->set & MRFM)
863                                             : (hdr->set & MFRM)) {
864                 strncpy(from, auxformat(mp, 0), sizeof(from) - 1);
865                 fromcount = count;
866             }
867
868             /*
869              * Also save the Sender: header as well
870              */
871
872             if ((msgstate == RESENT) ? (hdr->set & MRSN)
873                                             : (hdr->set & MSND)) {
874                 strncpy(sender, auxformat(mp, 0), sizeof(sender) - 1);
875                 sender[sizeof(sender) - 1] = '\0';
876                 seensender++;
877             }
878
879             /*
880              * ALSO ... save Envelope-From
881              */
882
883             if (hdr->set & MEFM) {
884                 strncpy(efrom, auxformat(mp, 0), sizeof(efrom) - 1);
885                 efrom[sizeof(efrom) - 1] = '\0';
886             }
887
888             if (hdr->flags & HBCC)
889                 mp->m_bcc++;
890             if (mp->m_gname)
891                 putgrp (namep, mp->m_gname, out, hdr->flags);
892             if (mp->m_ingrp)
893                 grp++;
894             keep = putadr (namep, "", mp, out, hdr->flags);
895             np = mp->m_next;
896             if (keep) {
897                 mp->m_next = NULL;
898                 msgflags |= (hdr->set & (MVIS | MINV));
899             }
900             else
901                 mnfree (mp);
902         }
903
904     /*
905      * If this is a From:/Resent-From: header, save the full thing for
906      * later in case we need it for use when constructing a Bcc draft message
907      */
908
909     if ((msgstate == RESENT) ? (hdr->set & MRFM) : (hdr->set & MFRM)) {
910         strncpy(fullfrom, str, sizeof(fullfrom));
911         fullfrom[sizeof(fullfrom) - 1] = 0;
912         /*
913          * Strip off any trailing newlines
914          */
915
916         while (strlen(fullfrom) > 0 && fullfrom[strlen(fullfrom) - 1] == '\n') {
917             fullfrom[strlen(fullfrom) - 1] = '\0';
918         }
919     }
920
921     if (grp > 0 && (hdr->flags & HNGR)) {
922         advise (NULL, "%s: field does not allow groups", name);
923         badmsg++;
924     }
925     if (linepos) {
926         putc ('\n', out);
927     }
928 }
929
930
931 static void
932 start_headers (void)
933 {
934     unsigned char  *cp;
935     char sigbuf[BUFSIZ];
936     struct mailname *mp;
937
938     myuid = getuid ();
939     mygid = getgid ();
940     time (&tclock);
941
942     /*
943      * Probably not necessary, but just in case ...
944      */
945
946     from[0] = '\0';
947     efrom[0] = '\0';
948     sender[0] = '\0';
949     fullfrom[0] = '\0';
950
951     if ((cp = getfullname ()) && *cp) {
952         strncpy (sigbuf, cp, sizeof(sigbuf));
953         snprintf (signature, sizeof(signature), "%s <%s>",
954                 sigbuf, getlocaladdr());
955         if ((cp = getname (signature)) == NULL)
956             adios (NULL, "getname () failed -- you lose extraordinarily big");
957         if ((mp = getm (cp, NULL, 0, AD_HOST, NULL)) == NULL)
958             adios (NULL, "bad signature '%s'", sigbuf);
959         mnfree (mp);
960         while (getname (""))
961             continue;
962     } else {
963         strncpy (signature, getlocaladdr(), sizeof(signature));
964     }
965 }
966
967
968 /*
969  * Now that we've outputted the header fields in the draft
970  * message, we will now output any remaining header fields
971  * that we need to add/create.
972  */
973
974 static void
975 finish_headers (FILE *out)
976 {
977     switch (msgstate) {
978         case NORMAL: 
979             if (!(msgflags & MFRM)) {
980                 /*
981                  * A From: header is now required in the draft.
982                  */
983                 advise (NULL, "message has no From: header");
984                 advise (NULL, "See default components files for examples");
985                 badmsg++;
986                 break;
987             }
988
989             if (fromcount > 1 && (seensender == 0 && !(msgflags & MEFM))) {
990                 advise (NULL, "A Sender: or Envelope-From: header is required "
991                         "with multiple\nFrom: addresses");
992                 badmsg++;
993                 break;
994             }
995
996             if (whomsw)
997                 break;
998
999             fprintf (out, "Date: %s\n", dtime (&tclock, 0));
1000             if (msgid)
1001                 fprintf (out, "Message-ID: %s\n", message_id (tclock, 0));
1002             /*
1003              * If we have multiple From: addresses, make sure we have an
1004              * Sender: header.  If we don't have one, then generate one
1005              * from Envelope-From: (which in this case, cannot be blank)
1006              */
1007
1008             if (fromcount > 1 && seensender == 0) {
1009                 if (efrom[0] == '\0') {
1010                     advise (NULL, "Envelope-From cannot be blank when there "
1011                             "is multiple From: addresses\nand no Sender: "
1012                             "header");
1013                     badmsg++;
1014                 } else {
1015                     fprintf (out, "Sender: %s\n", efrom);
1016                 }
1017             }
1018
1019             if (!(msgflags & MVIS))
1020                 fprintf (out, "Bcc: Blind Distribution List: ;\n");
1021             break;
1022
1023         case RESENT: 
1024             if (!(msgflags & MDAT)) {
1025                 advise (NULL, "message has no Date: header");
1026                 badmsg++;
1027             }
1028             if (!(msgflags & MFRM)) {
1029                 advise (NULL, "message has no From: header");
1030                 badmsg++;
1031             }
1032             if (!(msgflags & MRFM)) {
1033                 advise (NULL, "message has no Resent-From: header");
1034                 advise (NULL, "See default components files for examples");
1035                 badmsg++;
1036                 break;
1037             }
1038             if (fromcount > 1 && (seensender == 0 && !(msgflags & MEFM))) {
1039                 advise (NULL, "A Resent-Sender: or Envelope-From: header is "
1040                         "required with multiple\nResent-From: addresses");
1041                 badmsg++;
1042                 break;
1043             }
1044
1045             if (whomsw)
1046                 break;
1047
1048             fprintf (out, "Resent-Date: %s\n", dtime (&tclock, 0));
1049             if (msgid)
1050                 fprintf (out, "Resent-Message-ID: %s\n",
1051                          message_id (tclock, 0));
1052             /*
1053              * If we have multiple Resent-From: addresses, make sure we have an
1054              * Resent-Sender: header.  If we don't have one, then generate one
1055              * from Envelope-From (which in this case, cannot be blank)
1056              */
1057
1058             if (fromcount > 1 && seensender == 0) {
1059                 if (efrom[0] == '\0') {
1060                     advise (NULL, "Envelope-From cannot be blank when there "
1061                             "is multiple Resent-From: addresses and no "
1062                             "Resent-Sender: header");
1063                     badmsg++;
1064                 } else {
1065                     fprintf (out, "Resent-Sender: %s\n", efrom);
1066                 }
1067             }
1068
1069             if (!(msgflags & MVIS))
1070                 fprintf (out, "Resent-Bcc: Blind Re-Distribution List: ;\n");
1071             break;
1072     }
1073
1074     if (badmsg)
1075         adios (NULL, "re-format message and try again");
1076     if (!recipients)
1077         adios (NULL, "no addressees");
1078 }
1079
1080
1081 static int
1082 get_header (char *header, struct headers *table)
1083 {
1084     struct headers *h;
1085
1086     for (h = table; h->value; h++)
1087         if (!mh_strcasecmp (header, h->value))
1088             return (h - table);
1089
1090     return NOTOK;
1091 }
1092
1093
1094 static int
1095 putadr (char *name, char *aka, struct mailname *mp, FILE *out, unsigned int flags)
1096 {
1097     int len;
1098     char *cp;
1099     char buffer[BUFSIZ];
1100
1101     if (mp->m_mbox == NULL || ((flags & HTRY) && !insert (mp)))
1102         return 0;
1103     if (sm_mts != MTS_SENDMAIL_PIPE &&
1104         ((flags & (HBCC | HDCC | HEFM)) || mp->m_ingrp))
1105         return 1;
1106
1107     if (!nameoutput) {
1108         fprintf (out, "%s: ", name);
1109         linepos += (nameoutput = strlen (name) + 2);
1110     }
1111
1112     if (*aka && mp->m_type != UUCPHOST && !mp->m_pers)
1113         mp->m_pers = getcpy (aka);
1114     if (format) {
1115         if (mp->m_gname) {
1116             snprintf (buffer, sizeof(buffer), "%s;", mp->m_gname);
1117             cp = buffer;
1118         } else {
1119             cp = adrformat (mp);
1120         }
1121     } else {
1122         cp = mp->m_text;
1123     }
1124     len = strlen (cp);
1125
1126     if (linepos != nameoutput) {
1127         if (len + linepos + 2 > outputlinelen)
1128             fprintf (out, ",\n%*s", linepos = nameoutput, "");
1129         else {
1130             fputs (", ", out);
1131             linepos += 2;
1132         }
1133     }
1134
1135     fputs (cp, out);
1136     linepos += len;
1137
1138     return (flags & HTRY);
1139 }
1140
1141
1142 static void
1143 putgrp (char *name, char *group, FILE *out, unsigned int flags)
1144 {
1145     int len;
1146     char *cp;
1147
1148     if (sm_mts != MTS_SENDMAIL_PIPE && (flags & HBCC))
1149         return;
1150
1151     if (!nameoutput) {
1152         fprintf (out, "%s: ", name);
1153         linepos += (nameoutput = strlen (name) + 2);
1154     }
1155
1156     cp = concat (group, ";", NULL);
1157     len = strlen (cp);
1158
1159     if (linepos > nameoutput) {
1160         if (len + linepos + 2 > outputlinelen) {
1161             fprintf (out, ",\n%*s", nameoutput, "");
1162             linepos = nameoutput;
1163         }
1164         else {
1165             fputs (", ", out);
1166             linepos += 2;
1167         }
1168     }
1169
1170     fputs (cp, out);
1171     linepos += len;
1172 }
1173
1174
1175 static int
1176 insert (struct mailname *np)
1177 {
1178     struct mailname *mp;
1179
1180     if (np->m_mbox == NULL)
1181         return 0;
1182
1183     for (mp = np->m_type == LOCALHOST ? &localaddrs
1184             : np->m_type == UUCPHOST ? &uuaddrs
1185             : &netaddrs;
1186             mp->m_next;
1187             mp = mp->m_next)
1188         if (!mh_strcasecmp (np->m_host, mp->m_next->m_host)
1189                 && !mh_strcasecmp (np->m_mbox, mp->m_next->m_mbox)
1190                 && np->m_bcc == mp->m_next->m_bcc)
1191             return 0;
1192
1193     mp->m_next = np;
1194     recipients++;
1195     return 1;
1196 }
1197
1198
1199 static void
1200 pl (void)
1201 {
1202     int i;
1203     struct mailname *mp;
1204
1205     printf ("-------\n\t-- Addresses --\nlocal:\t");
1206     for (mp = localaddrs.m_next; mp; mp = mp->m_next)
1207         printf ("%s%s%s", mp->m_mbox,
1208                 mp->m_bcc ? "[BCC]" : "",
1209                 mp->m_next ? ",\n\t" : "");
1210
1211     printf ("\nnet:\t");
1212     for (mp = netaddrs.m_next; mp; mp = mp->m_next)
1213         printf ("%s%s@%s%s%s", mp->m_path ? mp->m_path : "",
1214                 mp->m_mbox, mp->m_host,
1215                 mp->m_bcc ? "[BCC]" : "",
1216                 mp->m_next ? ",\n\t" : "");
1217
1218     printf ("\nuucp:\t");
1219     for (mp = uuaddrs.m_next; mp; mp = mp->m_next)
1220         printf ("%s!%s%s%s", mp->m_host, mp->m_mbox,
1221                 mp->m_bcc ? "[BCC]" : "",
1222                 mp->m_next ? ",\n\t" : "");
1223
1224     printf ("\n\t-- Folder Copies --\nfcc:\t");
1225     for (i = 0; i < fccind; i++)
1226         printf ("%s%s", fccfold[i], i + 1 < fccind ? ",\n\t" : "");
1227     printf ("\n");
1228 }
1229
1230
1231 static void
1232 anno (void)
1233 {
1234     struct mailname *mp;
1235
1236     for (mp = localaddrs.m_next; mp; mp = mp->m_next)
1237         if (annoaux (mp) == NOTOK)
1238             goto oops;
1239
1240     for (mp = netaddrs.m_next; mp; mp = mp->m_next)
1241         if (annoaux (mp) == NOTOK)
1242             goto oops;
1243
1244     for (mp = uuaddrs.m_next; mp; mp = mp->m_next)
1245         if (annoaux (mp) == NOTOK)
1246             break;
1247
1248 oops: ;
1249     close (pfd);
1250     pfd = NOTOK;
1251 }
1252
1253
1254 static int
1255 annoaux (struct mailname *mp)
1256 {
1257     int i;
1258     char buffer[BUFSIZ];
1259
1260     snprintf (buffer, sizeof(buffer), "%s\n", adrformat (mp));
1261     i = strlen (buffer);
1262
1263     return (write (pfd, buffer, i) == i ? OK : NOTOK);
1264 }
1265
1266
1267 static void
1268 insert_fcc (struct headers *hdr, unsigned char *pp)
1269 {
1270     unsigned char *cp;
1271
1272     for (cp = pp; isspace (*cp); cp++)
1273         continue;
1274     for (pp += strlen (pp) - 1; pp > cp && isspace (*pp); pp--)
1275         continue;
1276     if (pp >= cp)
1277         *++pp = 0;
1278     if (*cp == 0)
1279         return;
1280
1281     if (fccind >= FCCS)
1282         adios (NULL, "too many %ss", hdr->value);
1283     fccfold[fccind++] = getcpy (cp);
1284 }
1285
1286 /*
1287  * BCC GENERATION
1288  */
1289
1290 static void
1291 make_bcc_file (int dashstuff)
1292 {
1293     int fd, i;
1294     pid_t child_id;
1295     char *vec[6];
1296     FILE *out;
1297     char *tfile = NULL;
1298
1299     tfile = m_mktemp2(NULL, "bccs", NULL, &out);
1300     if (tfile == NULL) adios("bcc", "unable to create temporary file");
1301     strncpy (bccfil, tfile, sizeof(bccfil));
1302
1303     fprintf (out, "From: %s\n", fullfrom);
1304     fprintf (out, "Date: %s\n", dtime (&tclock, 0));
1305     if (msgid)
1306         fprintf (out, "Message-ID: %s\n", message_id (tclock, 0));
1307     if (subject)
1308         fprintf (out, "Subject: %s", subject);
1309     fprintf (out, "BCC:\n");
1310
1311     /*
1312      * Use MIME encapsulation for Bcc messages
1313      */
1314     if (mime) {
1315         char *cp;
1316
1317         /*
1318          * Check if any lines in the message clash with the
1319          * prefix for the MIME multipart separator.  If there
1320          * is a clash, increment one of the letters in the
1321          * prefix and check again.
1322          */
1323         if ((cp = strchr(prefix, 'a')) == NULL)
1324             adios (NULL, "lost prefix start");
1325         while (find_prefix () == NOTOK) {
1326             if (*cp < 'z')
1327                 (*cp)++;
1328             else
1329                 if (*++cp == 0)
1330                     adios (NULL, "can't find a unique delimiter string");
1331                 else
1332                     (*cp)++;
1333         }
1334
1335         fprintf (out, "%s: %s\n%s: multipart/digest; boundary=\"",
1336                  VRSN_FIELD, VRSN_VALUE, TYPE_FIELD);
1337         fprintf (out, "%s\"\n\n--%s\n\n", prefix, prefix);
1338     } else {
1339         fprintf (out, "\n------- Blind-Carbon-Copy\n\n");
1340     }
1341
1342     fflush (out);
1343
1344     /*
1345      * Do mhl filtering of Bcc messages instead
1346      * of MIME encapsulation.
1347      */
1348     if (filter != NULL) {
1349         vec[0] = r1bindex (mhlproc, '/');
1350
1351         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
1352             sleep (5);
1353         switch (child_id) {
1354             case NOTOK: 
1355                 adios ("fork", "unable to");
1356
1357             case OK: 
1358                 dup2 (fileno (out), 1);
1359
1360                 i = 1;
1361                 vec[i++] = "-forward";
1362                 vec[i++] = "-form";
1363                 vec[i++] = filter;
1364                 vec[i++] = tmpfil;
1365
1366                 /* was the flag -[no]dashstuffing specified? */
1367                 if (dashstuff > 0)
1368                     vec[i++] = "-dashstuffing";
1369                 else if (dashstuff < 0)
1370                     vec[i++] = "-nodashstuffing";
1371                 vec[i] = NULL;
1372
1373                 execvp (mhlproc, vec);
1374                 fprintf (stderr, "unable to exec ");
1375                 perror (mhlproc);
1376                 _exit (-1);
1377
1378             default: 
1379                 pidXwait (child_id, mhlproc);
1380                 break;
1381         }
1382     } else {
1383         if ((fd = open (tmpfil, O_RDONLY)) == NOTOK)
1384             adios (tmpfil, "unable to re-open");
1385
1386         /*
1387          * If using MIME encapsulation, or if the -nodashstuffing
1388          * flag was given, then just copy message.  Else do
1389          * RFC934 quoting (dashstuffing).
1390          */
1391         if (mime || dashstuff < 0)
1392             cpydata (fd, fileno (out), tmpfil, bccfil);
1393         else
1394             cpydgst (fd, fileno (out), tmpfil, bccfil);
1395         close (fd);
1396     }
1397
1398     fseek (out, 0L, SEEK_END);
1399     if (mime)
1400         fprintf (out, "\n--%s--\n", prefix);
1401     else
1402         fprintf (out, "\n------- End of Blind-Carbon-Copy\n");
1403     fclose (out);
1404 }
1405
1406
1407 /*
1408  * Scan message to check if any lines clash with
1409  * the prefix of the MIME multipart separator.
1410  */
1411
1412 static int
1413 find_prefix (void)
1414 {
1415     int result = OK;
1416     unsigned char buffer[BUFSIZ];
1417     FILE *in;
1418
1419     if ((in = fopen (tmpfil, "r")) == NULL)
1420         adios (tmpfil, "unable to re-open");
1421
1422     while (fgets (buffer, sizeof(buffer) - 1, in))
1423         if (buffer[0] == '-' && buffer[1] == '-') {
1424             unsigned char *cp;
1425
1426             for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1427                 if (!isspace (*cp))
1428                     break;
1429             *++cp = '\0';
1430             if (strcmp (buffer + 2, prefix) == 0) {
1431                 result = NOTOK;
1432                 break;
1433             }
1434         }
1435
1436     fclose (in);
1437     return result;
1438 }
1439
1440
1441 #define plural(x) (x == 1 ? "" : "s")
1442
1443 static void
1444 chkadr (void)
1445 {
1446     if (badadr && unkadr)
1447         die (NULL, "%d address%s unparsable, %d addressee%s undeliverable",
1448                 badadr, plural (badadr), unkadr, plural (badadr));
1449     if (badadr)
1450         die (NULL, "%d address%s unparsable", badadr, plural (badadr));
1451     if (unkadr)
1452         die (NULL, "%d addressee%s undeliverable", unkadr, plural (unkadr));
1453 }
1454
1455
1456 static void
1457 do_addresses (int bccque, int talk)
1458 {
1459     int retval;
1460     int state;
1461     struct mailname *lp;
1462
1463     state = 0;
1464     for (lp = localaddrs.m_next; lp; lp = lp->m_next)
1465         if (lp->m_bcc ? bccque : !bccque) {
1466             if (talk && !state)
1467                 printf ("  -- Local Recipients --\n");
1468             do_an_address (lp, talk);
1469             state++;
1470         }
1471
1472     state = 0;
1473     for (lp = uuaddrs.m_next; lp; lp = lp->m_next)
1474         if (lp->m_bcc ? bccque : !bccque) {
1475             if (talk && !state)
1476                 printf ("  -- UUCP Recipients --\n");
1477             do_an_address (lp, talk);
1478             state++;
1479         }
1480
1481     state = 0;
1482     for (lp = netaddrs.m_next; lp; lp = lp->m_next)
1483         if (lp->m_bcc ? bccque : !bccque) {
1484             if (talk && !state)
1485                 printf ("  -- Network Recipients --\n");
1486             do_an_address (lp, talk);
1487             state++;
1488         }
1489
1490     chkadr ();
1491
1492     if (rp_isbad (retval = sm_waend ()))
1493         die (NULL, "problem ending addresses; %s", rp_string (retval));
1494 }
1495
1496
1497 /*
1498  * MTS-SPECIFIC INTERACTION
1499  */
1500
1501
1502 /*
1503  * SENDMAIL/SMTP routines
1504  */
1505
1506 static void
1507 post (char *file, int bccque, int talk, char *envelope)
1508 {
1509     int fd;
1510     int retval, i;
1511     pid_t child_id;
1512
1513     if (verbose) {
1514         if (msgflags & MINV)
1515             printf (" -- Posting for %s Recipients --\n",
1516                     bccque ? "Blind" : "Sighted");
1517         else
1518             printf (" -- Posting for All Recipients --\n");
1519     }
1520
1521     sigon ();
1522
1523     if (sm_mts == MTS_SENDMAIL_PIPE) {
1524         char *sargv[16], **argp;
1525
1526         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
1527             sleep (5);
1528         switch (child_id) {
1529             case NOTOK: 
1530                 adios ("fork", "unable to");
1531
1532             case OK:
1533                 if (freopen( file, "r", stdin) == NULL) {
1534                     adios (file, "can't reopen for sendmail");
1535                 }
1536
1537                 argp = sargv;
1538                 *argp++ = "sendmail";
1539                 *argp++ = "-t"; /* read msg for recipients */
1540                 *argp++ = "-i"; /* don't stop on "." */
1541                 if (whomsw)
1542                     *argp++ = "-bv";
1543                 if (snoop)
1544                     *argp++ = "-v";
1545                 *argp = NULL;
1546
1547                 execv (sendmail, sargv);
1548                 adios (sendmail, "can't exec");
1549
1550             default: 
1551                 pidXwait (child_id, NULL);
1552                 break;
1553         }
1554     } else {
1555         if (rp_isbad (retval = sm_init (clientsw, serversw, port, watch,
1556                                         verbose, snoop, queued, sasl,
1557                                         saslssf, saslmech, user, tls))  ||
1558             rp_isbad (retval = sm_winit (envelope)))
1559             die (NULL, "problem initializing server; %s", rp_string (retval));
1560
1561         do_addresses (bccque, talk && verbose);
1562         if ((fd = open (file, O_RDONLY)) == NOTOK)
1563           die (file, "unable to re-open");
1564         do_text (file, fd);
1565         close (fd);
1566         fflush (stdout);
1567
1568         sm_end (!(msgflags & MINV) || bccque ? OK : DONE);
1569         sigoff ();
1570
1571         if (verbose) {
1572             if (msgflags & MINV)
1573                 printf (" -- %s Recipient Copies Posted --\n",
1574                         bccque ? "Blind" : "Sighted");
1575             else
1576                 printf (" -- Recipient Copies Posted --\n");
1577         }
1578
1579         fflush (stdout);
1580     }
1581 }
1582
1583
1584 /* Address Verification */
1585
1586 static void
1587 verify_all_addresses (int talk, char *envelope)
1588 {
1589     int retval;
1590     struct mailname *lp;
1591
1592     sigon ();
1593
1594     if (!whomsw || checksw)
1595         if (rp_isbad (retval = sm_init (clientsw, serversw, port, watch,
1596                                         verbose, snoop, queued, sasl,
1597                                         saslssf, saslmech, user, tls))
1598                 || rp_isbad (retval = sm_winit (envelope)))
1599             die (NULL, "problem initializing server; %s", rp_string (retval));
1600
1601     if (talk && !whomsw)
1602         printf (" -- Address Verification --\n");
1603     if (talk && localaddrs.m_next)
1604         printf ("  -- Local Recipients --\n");
1605     for (lp = localaddrs.m_next; lp; lp = lp->m_next)
1606         do_an_address (lp, talk);
1607
1608     if (talk && uuaddrs.m_next)
1609         printf ("  -- UUCP Recipients --\n");
1610     for (lp = uuaddrs.m_next; lp; lp = lp->m_next)
1611         do_an_address (lp, talk);
1612
1613     if (talk && netaddrs.m_next)
1614         printf ("  -- Network Recipients --\n");
1615     for (lp = netaddrs.m_next; lp; lp = lp->m_next)
1616         do_an_address (lp, talk);
1617
1618     chkadr ();
1619     if (talk && !whomsw)
1620         printf (" -- Address Verification Successful --\n");
1621
1622     if (!whomsw || checksw)
1623         sm_end (DONE);
1624
1625     fflush (stdout);
1626     sigoff ();
1627 }
1628
1629
1630 static void
1631 do_an_address (struct mailname *lp, int talk)
1632 {
1633     int retval;
1634     char *mbox, *host;
1635     char addr[BUFSIZ];
1636
1637     switch (lp->m_type) {
1638         case LOCALHOST: 
1639             mbox = lp->m_mbox;
1640             host = lp->m_host;
1641             strncpy (addr, mbox, sizeof(addr));
1642             break;
1643
1644         case UUCPHOST: 
1645             mbox = auxformat (lp, 0);
1646             host = NULL;
1647             snprintf (addr, sizeof(addr), "%s!%s", lp->m_host, lp->m_mbox);
1648             break;
1649
1650         default:                /* let SendMail decide if the host is bad  */
1651             mbox = lp->m_mbox;
1652             host = lp->m_host;
1653             snprintf (addr, sizeof(addr), "%s at %s", mbox, host);
1654             break;
1655     }
1656
1657     if (talk)
1658         printf ("  %s%s", addr, whomsw && lp->m_bcc ? "[BCC]" : "");
1659
1660     if (whomsw && !checksw) {
1661         putchar ('\n');
1662         return;
1663     }
1664     if (talk)
1665         printf (": ");
1666     fflush (stdout);
1667
1668     switch (retval = sm_wadr (mbox, host,
1669                          lp->m_type != UUCPHOST ? lp->m_path : NULL)) {
1670         case RP_OK: 
1671             if (talk)
1672                 printf ("address ok\n");
1673             break;
1674
1675         case RP_NO: 
1676         case RP_USER: 
1677             if (!talk)
1678                 fprintf (stderr, "  %s: ", addr);
1679             fprintf (talk ? stdout : stderr, "loses; %s\n",
1680                         rp_string (retval));
1681             unkadr++;
1682             break;
1683
1684         default: 
1685             if (!talk)
1686                 fprintf (stderr, "  %s: ", addr);
1687             die (NULL, "unexpected response; %s", rp_string (retval));
1688     }
1689
1690     fflush (stdout);
1691 }
1692
1693
1694 static void
1695 do_text (char *file, int fd)
1696 {
1697     int retval, state;
1698     char buf[BUFSIZ];
1699
1700     lseek (fd, (off_t) 0, SEEK_SET);
1701
1702     while ((state = read (fd, buf, sizeof(buf))) > 0) {
1703         if (rp_isbad (retval = sm_wtxt (buf, state)))
1704             die (NULL, "problem writing text; %s\n", rp_string (retval));
1705     }
1706
1707     if (state == NOTOK)
1708         die (file, "problem reading from");
1709
1710     switch (retval = sm_wtend ()) {
1711         case RP_OK: 
1712             break;
1713
1714         case RP_NO: 
1715         case RP_NDEL: 
1716             die (NULL, "posting failed; %s", rp_string (retval));
1717
1718         default: 
1719             die (NULL, "unexpected response; %s", rp_string (retval));
1720     }
1721 }
1722
1723
1724 /*
1725  * SIGNAL HANDLING
1726  */
1727
1728 static void
1729 sigser (int i)
1730 {
1731     NMH_UNUSED (i);
1732
1733     unlink (tmpfil);
1734     if (msgflags & MINV)
1735         unlink (bccfil);
1736
1737     if (!whomsw || checksw)
1738         sm_end (NOTOK);
1739
1740     done (1);
1741 }
1742
1743
1744 static void
1745 sigon (void)
1746 {
1747     if (debug)
1748         return;
1749
1750     hstat = SIGNAL2 (SIGHUP, sigser);
1751     istat = SIGNAL2 (SIGINT, sigser);
1752     qstat = SIGNAL2 (SIGQUIT, sigser);
1753     tstat = SIGNAL2 (SIGTERM, sigser);
1754 }
1755
1756
1757 static void
1758 sigoff (void)
1759 {
1760     if (debug)
1761         return;
1762
1763     SIGNAL (SIGHUP, hstat);
1764     SIGNAL (SIGINT, istat);
1765     SIGNAL (SIGQUIT, qstat);
1766     SIGNAL (SIGTERM, tstat);
1767 }
1768
1769 /*
1770  * FCC INTERACTION
1771  */
1772
1773 static void
1774 p_refile (char *file)
1775 {
1776     int i;
1777
1778     if (fccind == 0)
1779         return;
1780
1781     if (verbose)
1782         printf (" -- Filing Folder Copies --\n");
1783     for (i = 0; i < fccind; i++)
1784         fcc (file, fccfold[i]);
1785     if (verbose)
1786         printf (" -- Folder Copies Filed --\n");
1787 }
1788
1789
1790 /*
1791  * Call the `fileproc' to add the file to the folder.
1792  */
1793
1794 static void
1795 fcc (char *file, char *folder)
1796 {
1797     pid_t child_id;
1798     int i, status;
1799     char fold[BUFSIZ];
1800
1801     if (verbose)
1802         printf ("  %sFcc %s: ", msgstate == RESENT ? "Resent-" : "", folder);
1803     fflush (stdout);
1804
1805     for (i = 0; (child_id = fork ()) == NOTOK && i < 5; i++)
1806         sleep (5);
1807
1808     switch (child_id) {
1809         case NOTOK: 
1810             if (!verbose)
1811                 fprintf (stderr, "  %sFcc %s: ",
1812                         msgstate == RESENT ? "Resent-" : "", folder);
1813             fprintf (verbose ? stdout : stderr, "no forks, so not ok\n");
1814             break;
1815
1816         case OK: 
1817             /* see if we need to add `+' */
1818             snprintf (fold, sizeof(fold), "%s%s",
1819                     *folder == '+' || *folder == '@' ? "" : "+", folder);
1820
1821             /* now exec the fileproc */
1822             execlp (fileproc, r1bindex (fileproc, '/'),
1823                     "-link", "-file", file, fold, NULL);
1824             _exit (-1);
1825
1826         default: 
1827             if ((status = pidwait (child_id, OK))) {
1828                 if (!verbose)
1829                     fprintf (stderr, "  %sFcc %s: ",
1830                             msgstate == RESENT ? "Resent-" : "", folder);
1831                 pidstatus (status, verbose ? stdout : stderr, NULL);
1832             } else {
1833                 if (verbose)
1834                     printf ("folder ok\n");
1835             }
1836     }
1837
1838     fflush (stdout);
1839 }
1840
1841 /*
1842  * TERMINATION
1843  */
1844
1845 static void
1846 die (char *what, char *fmt, ...)
1847 {
1848     va_list ap;
1849
1850     unlink (tmpfil);
1851     if (msgflags & MINV)
1852         unlink (bccfil);
1853
1854     if (!whomsw || checksw)
1855         sm_end (NOTOK);
1856
1857     va_start(ap, fmt);
1858     advertise (what, NULL, fmt, ap);
1859     va_end(ap);
1860     done (1);
1861 }