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