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