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