* uip/post.c, uip/spost.c: Move the uptolow macro from spost.c to post.c
[mmh] / uip / post.c
1
2 /*
3  * post.c -- enter messages into the mail transport system
4  *
5  * $Id$
6  *
7  * This code is Copyright (c) 2002, by the authors of nmh.  See the
8  * COPYRIGHT file in the root directory of the nmh distribution for
9  * complete copyright information.
10  */
11
12 #include <h/mh.h>
13 #include <fcntl.h>
14 #include <h/signals.h>
15 #include <h/addrsbr.h>
16 #include <h/aliasbr.h>
17 #include <h/dropsbr.h>
18 #include <h/mime.h>
19 #include <h/utils.h>
20
21 #include <h/tws.h>
22 #include <h/mts.h>
23
24 #include <errno.h>
25 #include <setjmp.h>
26 #include <signal.h>
27
28 #ifdef TIME_WITH_SYS_TIME
29 # include <sys/time.h>
30 # include <time.h>
31 #else
32 # ifdef TM_IN_SYS_TIME
33 #  include <sys/time.h>
34 # else
35 #  include <time.h>
36 # endif
37 #endif
38
39 #ifdef SMTPMTS
40 # include <mts/smtp/smtp.h>
41 #endif
42
43 #ifndef CYRUS_SASL
44 # define SASLminc(a) (a)
45 #else /* CYRUS_SASL */
46 # define SASLminc(a)  0
47 #endif /* CYRUS_SASL */
48
49 #define FCCS            10      /* max number of fccs allowed */
50
51 #define uptolow(c)      ((isalpha(c) && isupper (c)) ? tolower (c) : c)
52
53 /* In the following array of structures, the numeric second field of the
54    structures (minchars) is apparently used like this:
55
56    -# : Switch can be abbreviated to # characters; switch hidden in -help.
57    0  : Switch can't be abbreviated;               switch shown in -help.
58    #  : Switch can be abbreviated to # characters; switch shown in -help. */
59
60 static struct swit switches[] = {
61 #define ALIASW                    0
62     { "alias aliasfile", 0 },
63 #define CHKSW                     1
64     { "check", -5 },                    /* interface from whom */
65 #define NCHKSW                    2
66     { "nocheck", -7 },                  /* interface from whom */
67 #define DEBUGSW                   3
68     { "debug", -5 },
69 #define DISTSW                    4
70     { "dist", -4 },                     /* interface from dist */
71 #define FILTSW                    5
72     { "filter filterfile", 0 },
73 #define NFILTSW                   6
74     { "nofilter", 0 },
75 #define FRMTSW                    7
76     { "format", 0 },
77 #define NFRMTSW                   8
78     { "noformat", 0 },
79 #define LIBSW                     9
80     { "library directory", -7 },        /* interface from send, whom */
81 #define MIMESW                   10
82     { "mime", 0 },
83 #define NMIMESW                  11
84     { "nomime", 0 },
85 #define MSGDSW                   12
86     { "msgid", 0 },
87 #define NMSGDSW                  13
88     { "nomsgid", 0 },
89 #define VERBSW                   14
90     { "verbose", 0 },
91 #define NVERBSW                  15
92     { "noverbose", 0 },
93 #define WATCSW                   16
94     { "watch", 0 },
95 #define NWATCSW                  17
96     { "nowatch", 0 },
97 #define WHOMSW                   18
98     { "whom", -4 },                     /* interface from whom */
99 #define WIDTHSW                  19
100     { "width columns", 0 },
101 #define VERSIONSW                20
102     { "version", 0 },
103 #define HELPSW                   21
104     { "help", 0 },
105 #define BITSTUFFSW               22
106     { "dashstuffing", -12 },            /* should we dashstuff BCC messages? */
107 #define NBITSTUFFSW              23
108     { "nodashstuffing", -14 },
109 #define MAILSW                   24
110     { "mail", -4 },                     /* specify MAIL smtp mode */
111 #define SAMLSW                   25
112     { "saml", -4 },                     /* specify SAML smtp mode */
113 #define SENDSW                   26
114     { "send", -4 },                     /* specify SEND smtp mode */
115 #define SOMLSW                   27
116     { "soml", -4 },                     /* specify SOML smtp mode */
117 #define ANNOSW                   28
118     { "idanno number", -6 },            /* interface from send    */
119 #define DLVRSW                   29
120     { "deliver address-list", -7 },
121 #define CLIESW                   30
122     { "client host", -6 },
123 #define SERVSW                   31
124     { "server host", -6 },              /* specify alternate SMTP server */
125 #define SNOOPSW                  32
126     { "snoop", -5 },                    /* snoop the SMTP transaction */
127 #define FILLSW                   33
128     { "fill-in file", -7 },
129 #define FILLUSW                  34
130     { "fill-up", -7 },
131 #define PARTSW                   35
132     { "partno", -6 },
133 #define QUEUESW                  36
134     { "queued", -6 },
135 #define SASLSW                   37
136     { "sasl", SASLminc(-4) },
137 #define SASLMECHSW               38
138     { "saslmech", SASLminc(-5) },
139 #define USERSW                   39
140     { "user", SASLminc(-4) },
141     { NULL, 0 }
142 };
143
144
145 struct headers {
146     char *value;
147     unsigned int flags;
148     unsigned int set;
149 };
150
151 /*
152  * flags for headers->flags
153  */
154 #define HNOP  0x0000            /* just used to keep .set around          */
155 #define HBAD  0x0001            /* bad header - don't let it through      */
156 #define HADR  0x0002            /* header has an address field            */
157 #define HSUB  0x0004            /* Subject: header                        */
158 #define HTRY  0x0008            /* try to send to addrs on header         */
159 #define HBCC  0x0010            /* don't output this header               */
160 #define HMNG  0x0020            /* munge this header                      */
161 #define HNGR  0x0040            /* no groups allowed in this header       */
162 #define HFCC  0x0080            /* FCC: type header                       */
163 #define HNIL  0x0100            /* okay for this header not to have addrs */
164 #define HIGN  0x0200            /* ignore this header                     */
165 #define HDCC  0x0400            /* another undocumented feature           */
166
167 /*
168  * flags for headers->set
169  */
170 #define MFRM  0x0001            /* we've seen a From:        */
171 #define MDAT  0x0002            /* we've seen a Date:        */
172 #define MRFM  0x0004            /* we've seen a Resent-From: */
173 #define MVIS  0x0008            /* we've seen sighted addrs  */
174 #define MINV  0x0010            /* we've seen blind addrs    */
175
176
177 static struct headers NHeaders[] = {
178     { "Return-Path", HBAD,                0 },
179     { "Received",    HBAD,                0 },
180     { "Reply-To",    HADR|HNGR,           0 },
181     { "From",        HADR|HNGR,           MFRM },
182     { "Sender",      HADR|HBAD,           0 },
183     { "Date",        HBAD,                0 },
184     { "Subject",     HSUB,                0 },
185     { "To",          HADR|HTRY,           MVIS },
186     { "cc",          HADR|HTRY,           MVIS },
187     { "Bcc",         HADR|HTRY|HBCC|HNIL, MINV },
188     { "Dcc",         HADR|HTRY|HDCC|HNIL, MVIS },       /* sorta cc & bcc combined */
189     { "Message-ID",  HBAD,                0 },
190     { "Fcc",         HFCC,                0 },
191     { NULL,          0,                   0 }
192 };
193
194 static struct headers RHeaders[] = {
195     { "Resent-Reply-To",   HADR|HNGR,           0 },
196     { "Resent-From",       HADR|HNGR,           MRFM },
197     { "Resent-Sender",     HADR|HBAD,           0 },
198     { "Resent-Date",       HBAD,                0 },
199     { "Resent-Subject",    HSUB,                0 },
200     { "Resent-To",         HADR|HTRY,           MVIS },
201     { "Resent-cc",         HADR|HTRY,           MVIS },
202     { "Resent-Bcc",        HADR|HTRY|HBCC,      MINV },
203     { "Resent-Message-ID", HBAD,                0 },
204     { "Resent-Fcc",        HFCC,                0 },
205     { "Reply-To",          HADR,                0 },
206     { "From",              HADR|HNGR,           MFRM },
207     { "Sender",            HADR|HNGR,           0 },
208     { "Date",              HNOP,                MDAT },
209     { "To",                HADR|HNIL,           0 },
210     { "cc",                HADR|HNIL,           0 },
211     { "Bcc",               HADR|HTRY|HBCC|HNIL, 0 },
212     { "Fcc",               HIGN,                0 },
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 char *saslmech=NULL;     /* Force use of particular SASL mech     */
238 static char *user=NULL;         /* Authenticate as this user             */
239
240 static unsigned msgflags = 0;   /* what we've seen */
241
242 #define NORMAL 0
243 #define RESENT 1
244 static int msgstate = NORMAL;
245
246 static time_t tclock = 0;       /* the time we started (more or less) */
247
248 static SIGNAL_HANDLER hstat, istat, qstat, tstat;
249
250 static char tmpfil[BUFSIZ];
251 static char bccfil[BUFSIZ];
252
253 static char from[BUFSIZ];       /* my network address            */
254 static char signature[BUFSIZ];  /* my signature                  */
255 static char *filter = NULL;     /* the filter for BCC'ing        */
256 static char *subject = NULL;    /* the subject field for BCC'ing */
257 static char *fccfold[FCCS];     /* foldernames for FCC'ing       */
258
259 static struct headers  *hdrtab; /* table for the message we're doing */
260
261 static struct mailname localaddrs={NULL};       /* local addrs     */
262 static struct mailname netaddrs={NULL};         /* network addrs   */
263 static struct mailname uuaddrs={NULL};          /* uucp addrs      */
264 static struct mailname tmpaddrs={NULL};         /* temporary queue */
265
266 #ifdef SMTPMTS
267 static int snoop      = 0;
268 static int smtpmode   = S_MAIL;
269 static char *clientsw = NULL;
270 static char *serversw = NULL;
271
272 extern struct smtp sm_reply;
273 #endif /* SMTPMTS */
274
275 static char prefix[] = "----- =_aaaaaaaaaa";
276
277 static int fill_up = 0;
278 static char *fill_in = NULL;
279 static char *partno = NULL;
280 static int queued = 0;
281
282 extern boolean  draft_from_masquerading;  /* defined in mts.c */
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 *, char *);
298 static void make_bcc_file (int);
299 static void verify_all_addresses (int);
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);
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;
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 DLVRSW:
453                     if (!(cp = *argp++) || *cp == '-')
454                         adios (NULL, "missing argument to %s", argp[-2]);
455                     continue;
456
457 #ifndef SMTPMTS
458                 case CLIESW:
459                 case SERVSW:
460                     if (!(cp = *argp++) || *cp == '-')
461                         adios (NULL, "missing argument to %s", argp[-2]);
462                     continue;
463
464                 case SNOOPSW:
465                     continue;
466 #else /* SMTPMTS */
467                 case MAILSW:
468                     smtpmode = S_MAIL;
469                     continue;
470                 case SAMLSW:
471                     smtpmode = S_SAML;
472                     continue;
473                 case SOMLSW:
474                     smtpmode = S_SOML;
475                     continue;
476                 case SENDSW:
477                     smtpmode = S_SEND;
478                     continue;
479                 case CLIESW:
480                     if (!(clientsw = *argp++) || *clientsw == '-')
481                         adios (NULL, "missing argument to %s", argp[-2]);
482                     continue;
483                 case SERVSW:
484                     if (!(serversw = *argp++) || *serversw == '-')
485                         adios (NULL, "missing argument to %s", argp[-2]);
486                     continue;
487                 case SNOOPSW:
488                     snoop++;
489                     continue;
490 #endif /* SMTPMTS */
491
492                 case FILLSW:
493                     if (!(fill_in = *argp++) || *fill_in == '-')
494                         adios (NULL, "missing argument to %s", argp[-2]);
495                     continue;
496                 case FILLUSW:
497                     fill_up++;
498                     continue;
499                 case PARTSW:
500                     if (!(partno = *argp++) || *partno == '-')
501                         adios (NULL, "missing argument to %s", argp[-2]);
502                     continue;
503
504                 case QUEUESW:
505                     queued++;
506                     continue;
507                 
508                 case SASLSW:
509                     sasl++;
510                     continue;
511                 
512                 case SASLMECHSW:
513                     if (!(saslmech = *argp++) || *saslmech == '-')
514                         adios (NULL, "missing argument to %s", argp[-2]);
515                     continue;
516                 
517                 case USERSW:
518                     if (!(user = *argp++) || *user == '-')
519                         adios (NULL, "missing argument to %s", argp[-2]);
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 (fill_in ? fill_in : "/dev/null", "w")) == NULL)
547                 adios ("/dev/null", "unable to open");
548         } else {
549             strncpy (tmpfil, m_scratch ("", m_maildir (invo_name)),
550                 sizeof(tmpfil));
551             if ((out = fopen (tmpfil, "w")) == NULL) {
552                 strncpy (tmpfil, m_tmpfil (invo_name), sizeof(tmpfil));
553                 if ((out = fopen (tmpfil, "w")) == NULL)
554                     adios (tmpfil, "unable to create");
555             }
556             chmod (tmpfil, 0600);
557         }
558     }
559
560     hdrtab = msgstate == NORMAL ? NHeaders : RHeaders;
561
562     for (compnum = 1, state = FLD;;) {
563         switch (state = m_getfld (state, name, buf, sizeof(buf), in)) {
564             case FLD: 
565             case FLDEOF: 
566             case FLDPLUS: 
567                 compnum++;
568                 cp = add (buf, NULL);
569                 while (state == FLDPLUS) {
570                     state = m_getfld (state, name, buf, sizeof(buf), in);
571                     cp = add (buf, cp);
572                 }
573                 putfmt (name, cp, out);
574                 free (cp);
575                 if (state != FLDEOF)
576                     continue;
577                 finish_headers (out);
578                 break;
579
580             case BODY: 
581             case BODYEOF: 
582                 finish_headers (out);
583                 if (whomsw && !fill_in)
584                     break;
585                 fprintf (out, "\n%s", buf);
586                 while (state == BODY) {
587                     state = m_getfld (state, name, buf, sizeof(buf), in);
588                     fputs (buf, out);
589                 }
590                 break;
591
592             case FILEEOF: 
593                 finish_headers (out);
594                 break;
595
596             case LENERR: 
597             case FMTERR: 
598                 adios (NULL, "message format error in component #%d", compnum);
599
600             default: 
601                 adios (NULL, "getfld() returned %d", state);
602         }
603         break;
604     }
605
606     if (pfd != NOTOK)
607         anno ();
608     fclose (in);
609
610     if (debug) {
611         pl ();
612         done (0);
613     } else {
614         fclose (out);
615     }
616
617     /* If we are doing a "whom" check */
618     if (whomsw) {
619         if (!fill_up)
620             verify_all_addresses (1);
621         done (0);
622     }
623
624     if (msgflags & MINV) {
625         make_bcc_file (dashstuff);
626         if (msgflags & MVIS) {
627             verify_all_addresses (verbose);
628             post (tmpfil, 0, verbose);
629         }
630         post (bccfil, 1, verbose);
631         unlink (bccfil);
632     } else {
633         post (tmpfil, 0, isatty (1));
634     }
635
636     p_refile (tmpfil);
637     unlink (tmpfil);
638
639     if (verbose)
640         printf (partno ? "Partial Message #%s Processed\n" : "Message Processed\n",
641                 partno);
642     return done (0);
643 }
644
645
646 /*
647  * DRAFT GENERATION
648  */
649
650 static void
651 putfmt (char *name, char *str, FILE *out)
652 {
653     int count, grp, i, keep;
654     char *cp, *pp, *qp;
655     char namep[BUFSIZ];
656     struct mailname *mp, *np;
657     struct headers *hdr;
658
659     while (*str == ' ' || *str == '\t')
660         str++;
661
662     if (msgstate == NORMAL && uprf (name, "resent")) {
663         advise (NULL, "illegal header line -- %s:", name);
664         badmsg++;
665         return;
666     }
667
668     if ((i = get_header (name, hdrtab)) == NOTOK) {
669         fprintf (out, "%s: %s", name, str);
670         return;
671     }
672
673     hdr = &hdrtab[i];
674     if (hdr->flags & HIGN) {
675         if (fill_in)
676             fprintf (out, "%s: %s", name, str);
677         return;
678     }
679     if (hdr->flags & HBAD) {
680         if (fill_in)
681             fprintf (out, "%s: %s", name, str);
682         else {
683             advise (NULL, "illegal header line -- %s:", name);
684             badmsg++;
685         }
686         return;
687     }
688     msgflags |= (hdr->set & ~(MVIS | MINV));
689
690     if (hdr->flags & HSUB)
691         subject = subject ? add (str, add ("\t", subject)) : getcpy (str);
692     if (hdr->flags & HFCC) {
693         if (fill_in) {
694             fprintf (out, "%s: %s", name, str);
695             return;
696         }
697
698         if ((cp = strrchr(str, '\n')))
699             *cp = 0;
700         for (cp = pp = str; (cp = strchr(pp, ',')); pp = cp) {
701             *cp++ = 0;
702             insert_fcc (hdr, pp);
703         }
704         insert_fcc (hdr, pp);
705         return;
706     }
707
708     if (!(hdr->flags & HADR)) {
709         fprintf (out, "%s: %s", name, str);
710         return;
711     }
712
713     tmpaddrs.m_next = NULL;
714     for (count = 0; (cp = getname (str)); count++)
715         if ((mp = getm (cp, NULL, 0, AD_HOST, NULL))) {
716             if (tmpaddrs.m_next)
717                 np->m_next = mp;
718             else
719                 tmpaddrs.m_next = mp;
720             np = mp;
721         }
722         else
723             if (hdr->flags & HTRY)
724                 badadr++;
725             else
726                 badmsg++;
727
728     if (count < 1) {
729         if (hdr->flags & HNIL)
730             fprintf (out, "%s: %s", name, str);
731         else {
732 #ifdef notdef
733             advise (NULL, "%s: field requires at least one address", name);
734             badmsg++;
735 #endif /* notdef */
736         }
737         return;
738     }
739
740     nameoutput = linepos = 0;
741     snprintf (namep, sizeof(namep), "%s%s",
742                 !fill_in && (hdr->flags & HMNG) ? "Original-" : "", name);
743
744     for (grp = 0, mp = tmpaddrs.m_next; mp; mp = np)
745         if (mp->m_nohost) {     /* also used to test (hdr->flags & HTRY) */
746             /* The address doesn't include a host, so it might be an alias. */
747             pp = akvalue (mp->m_mbox);  /* do mh alias substitution */
748             qp = akvisible () ? mp->m_mbox : "";
749             np = mp;
750             if (np->m_gname)
751                 putgrp (namep, np->m_gname, out, hdr->flags);
752             while ((cp = getname (pp))) {
753                 if (!(mp = getm (cp, NULL, 0, AD_HOST, NULL))) {
754                     badadr++;
755                     continue;
756                 }
757
758                 if (draft_from_masquerading && ((msgstate == RESENT)
759                                                 ? (hdr->set & MRFM)
760                                                 : (hdr->set & MFRM)))
761                     /* The user manually specified a [Resent-]From: address in
762                        their draft and the "masquerade:" line in mts.conf
763                        doesn't contain "draft_from", so we'll set things up to
764                        use the actual email address embedded in the draft
765                        [Resent-]From: (after alias substitution, and without the
766                        GECOS full name or angle brackets) as the envelope
767                        From:. */
768                     strncpy(from, auxformat(mp, 0), sizeof(from) - 1);
769
770                 if (hdr->flags & HBCC)
771                     mp->m_bcc++;
772                 if (np->m_ingrp)
773                     mp->m_ingrp = np->m_ingrp;
774                 else
775                     if (mp->m_gname)
776                         putgrp (namep, mp->m_gname, out, hdr->flags);
777                 if (mp->m_ingrp)
778                     grp++;
779                 if (putadr (namep, qp, mp, out, hdr->flags))
780                     msgflags |= (hdr->set & (MVIS | MINV));
781                 else
782                     mnfree (mp);
783             }
784             mp = np;
785             np = np->m_next;
786             mnfree (mp);
787         }
788         else {
789             /* Address includes a host, so no alias substitution is needed. */
790             if (draft_from_masquerading && ((msgstate == RESENT)
791                                             ? (hdr->set & MRFM)
792                                             : (hdr->set & MFRM)))
793                 /* The user manually specified a [Resent-]From: address in
794                    their draft and the "masquerade:" line in mts.conf
795                    doesn't contain "draft_from", so we'll set things up to
796                    use the actual email address embedded in the draft
797                    [Resent-]From: (after alias substitution, and without the
798                    GECOS full name or angle brackets) as the envelope
799                    From:. */
800                 strncpy(from, auxformat(mp, 0), sizeof(from) - 1);
801
802             if (hdr->flags & HBCC)
803                 mp->m_bcc++;
804             if (mp->m_gname)
805                 putgrp (namep, mp->m_gname, out, hdr->flags);
806             if (mp->m_ingrp)
807                 grp++;
808             keep = putadr (namep, "", mp, out, hdr->flags);
809             np = mp->m_next;
810             if (keep) {
811                 mp->m_next = NULL;
812                 msgflags |= (hdr->set & (MVIS | MINV));
813             }
814             else
815                 mnfree (mp);
816         }
817
818     if (grp > 0 && (hdr->flags & HNGR)) {
819         advise (NULL, "%s: field does not allow groups", name);
820         badmsg++;
821     }
822     if (linepos) {
823         if (fill_in && grp > 0)
824             putc (';', out);
825         putc ('\n', out);
826     }
827 }
828
829
830 static void
831 start_headers (void)
832 {
833     char  *cp;
834     char myhost[BUFSIZ], sigbuf[BUFSIZ];
835     struct mailname *mp;
836
837     myuid = getuid ();
838     mygid = getgid ();
839     time (&tclock);
840
841     strncpy (from, adrsprintf (NULL, NULL), sizeof(from));
842     strncpy (myhost, LocalName (), sizeof(myhost));
843
844     for (cp = myhost; *cp; cp++)
845         *cp = uptolow (*cp);
846
847     if ((cp = getfullname ()) && *cp) {
848         strncpy (sigbuf, cp, sizeof(sigbuf));
849         snprintf (signature, sizeof(signature), "%s <%s>",
850                 sigbuf, adrsprintf (NULL, NULL));
851         if ((cp = getname (signature)) == NULL)
852             adios (NULL, "getname () failed -- you lose extraordinarily big");
853         if ((mp = getm (cp, NULL, 0, AD_HOST, NULL)) == NULL)
854             adios (NULL, "bad signature '%s'", sigbuf);
855         mnfree (mp);
856         while (getname (""))
857             continue;
858     } else {
859         strncpy (signature, adrsprintf (NULL, NULL), sizeof(signature));
860     }
861 }
862
863
864 /*
865  * Now that we've outputted the header fields in the draft
866  * message, we will now output any remaining header fields
867  * that we need to add/create.
868  */
869
870 static void
871 finish_headers (FILE *out)
872 {
873     switch (msgstate) {
874         case NORMAL: 
875             if (whomsw && !fill_up)
876                 break;
877
878             fprintf (out, "Date: %s\n", dtime (&tclock, 0));
879             if (msgid)
880                 fprintf (out, "Message-ID: <%d.%ld@%s>\n",
881                         (int) getpid (), (long) tclock, LocalName ());
882             if (msgflags & MFRM) {
883                 /* There was already a From: in the draft.  Don't add one. */
884                 if (!draft_from_masquerading)
885                     /* mts.conf didn't contain "masquerade:[...]draft_from[...]"
886                        so we'll reveal the user's actual account@thismachine
887                        address in a Sender: header (and use it as the envelope
888                        From: later). */
889                     fprintf (out, "Sender: %s\n", from);
890             }
891             else
892                 /* Construct a From: header. */
893                 fprintf (out, "From: %s\n", signature);
894             if (whomsw)
895                 break;
896
897             if (!(msgflags & MVIS))
898                 fprintf (out, "Bcc: Blind Distribution List: ;\n");
899             break;
900
901         case RESENT: 
902             if (!(msgflags & MDAT)) {
903                 advise (NULL, "message has no Date: header");
904                 badmsg++;
905             }
906             if (!(msgflags & MFRM)) {
907                 advise (NULL, "message has no From: header");
908                 badmsg++;
909             }
910             if (whomsw && !fill_up)
911                 break;
912
913             fprintf (out, "Resent-Date: %s\n", dtime (&tclock, 0));
914             if (msgid)
915                 fprintf (out, "Resent-Message-ID: <%d.%ld@%s>\n",
916                         (int) getpid (), (long) tclock, LocalName ());
917             if (msgflags & MRFM) {
918                 /* There was already a Resent-From: in draft.  Don't add one. */
919                 if (!draft_from_masquerading)
920                     /* mts.conf didn't contain "masquerade:[...]draft_from[...]"
921                        so we'll reveal the user's actual account@thismachine
922                        address in a Sender: header (and use it as the envelope
923                        From: later). */
924                     fprintf (out, "Resent-Sender: %s\n", from);
925             }
926             else
927                 /* Construct a Resent-From: header. */
928                 fprintf (out, "Resent-From: %s\n", signature);
929             if (whomsw)
930                 break;
931             if (!(msgflags & MVIS))
932                 fprintf (out, "Resent-Bcc: Blind Re-Distribution List: ;\n");
933             break;
934     }
935
936     if (badmsg)
937         adios (NULL, "re-format message and try again");
938     if (!recipients)
939         adios (NULL, "no addressees");
940 }
941
942
943 static int
944 get_header (char *header, struct headers *table)
945 {
946     struct headers *h;
947
948     for (h = table; h->value; h++)
949         if (!strcasecmp (header, h->value))
950             return (h - table);
951
952     return NOTOK;
953 }
954
955
956 static int
957 putadr (char *name, char *aka, struct mailname *mp, FILE *out, unsigned int flags)
958 {
959     int len;
960     char *cp;
961     char buffer[BUFSIZ];
962
963     if (mp->m_mbox == NULL || ((flags & HTRY) && !insert (mp)))
964         return 0;
965     if ((!fill_in && (flags & (HBCC | HDCC))) || mp->m_ingrp)
966         return 1;
967
968     if (!nameoutput) {
969         fprintf (out, "%s: ", name);
970         linepos += (nameoutput = strlen (name) + 2);
971     }
972
973     if (*aka && mp->m_type != UUCPHOST && !mp->m_pers)
974         mp->m_pers = getcpy (aka);
975     if (format) {
976         if (mp->m_gname && !fill_in) {
977             snprintf (buffer, sizeof(buffer), "%s;", mp->m_gname);
978             cp = buffer;
979         } else {
980             cp = adrformat (mp);
981         }
982     } else {
983         cp = mp->m_text;
984     }
985     len = strlen (cp);
986
987     if (linepos != nameoutput) {
988         if (len + linepos + 2 > outputlinelen)
989             fprintf (out, ",\n%*s", linepos = nameoutput, "");
990         else {
991             fputs (", ", out);
992             linepos += 2;
993         }
994     }
995
996     fputs (cp, out);
997     linepos += len;
998
999     return (flags & HTRY);
1000 }
1001
1002
1003 static void
1004 putgrp (char *name, char *group, FILE *out, unsigned int flags)
1005 {
1006     int len;
1007     char *cp;
1008
1009     if (!fill_in && (flags & HBCC))
1010         return;
1011
1012     if (!nameoutput) {
1013         fprintf (out, "%s: ", name);
1014         linepos += (nameoutput = strlen (name) + 2);
1015         if (fill_in)
1016             linepos -= strlen (group);
1017     }
1018
1019     cp = fill_in ? group : concat (group, ";", NULL);
1020     len = strlen (cp);
1021
1022     if (linepos > nameoutput) {
1023         if (len + linepos + 2 > outputlinelen) {
1024             fprintf (out, ",\n%*s", nameoutput, "");
1025             linepos = nameoutput;
1026         }
1027         else {
1028             fputs (", ", out);
1029             linepos += 2;
1030         }
1031     }
1032
1033     fputs (cp, out);
1034     linepos += len;
1035 }
1036
1037
1038 static int
1039 insert (struct mailname *np)
1040 {
1041     struct mailname *mp;
1042
1043     if (np->m_mbox == NULL)
1044         return 0;
1045
1046     for (mp = np->m_type == LOCALHOST ? &localaddrs
1047             : np->m_type == UUCPHOST ? &uuaddrs
1048             : &netaddrs;
1049             mp->m_next;
1050             mp = mp->m_next)
1051         if (!strcasecmp (np->m_host, mp->m_next->m_host)
1052                 && !strcasecmp (np->m_mbox, mp->m_next->m_mbox)
1053                 && np->m_bcc == mp->m_next->m_bcc)
1054             return 0;
1055
1056     mp->m_next = np;
1057     recipients++;
1058     return 1;
1059 }
1060
1061
1062 static void
1063 pl (void)
1064 {
1065     int i;
1066     struct mailname *mp;
1067
1068     printf ("-------\n\t-- Addresses --\nlocal:\t");
1069     for (mp = localaddrs.m_next; mp; mp = mp->m_next)
1070         printf ("%s%s%s", mp->m_mbox,
1071                 mp->m_bcc ? "[BCC]" : "",
1072                 mp->m_next ? ",\n\t" : "");
1073
1074     printf ("\nnet:\t");
1075     for (mp = netaddrs.m_next; mp; mp = mp->m_next)
1076         printf ("%s%s@%s%s%s", mp->m_path ? mp->m_path : "",
1077                 mp->m_mbox, mp->m_host,
1078                 mp->m_bcc ? "[BCC]" : "",
1079                 mp->m_next ? ",\n\t" : "");
1080
1081     printf ("\nuucp:\t");
1082     for (mp = uuaddrs.m_next; mp; mp = mp->m_next)
1083         printf ("%s!%s%s%s", mp->m_host, mp->m_mbox,
1084                 mp->m_bcc ? "[BCC]" : "",
1085                 mp->m_next ? ",\n\t" : "");
1086
1087     printf ("\n\t-- Folder Copies --\nfcc:\t");
1088     for (i = 0; i < fccind; i++)
1089         printf ("%s%s", fccfold[i], i + 1 < fccind ? ",\n\t" : "");
1090     printf ("\n");
1091 }
1092
1093
1094 static void
1095 anno (void)
1096 {
1097     struct mailname *mp;
1098
1099     for (mp = localaddrs.m_next; mp; mp = mp->m_next)
1100         if (annoaux (mp) == NOTOK)
1101             goto oops;
1102
1103     for (mp = netaddrs.m_next; mp; mp = mp->m_next)
1104         if (annoaux (mp) == NOTOK)
1105             goto oops;
1106
1107     for (mp = uuaddrs.m_next; mp; mp = mp->m_next)
1108         if (annoaux (mp) == NOTOK)
1109             break;
1110
1111 oops: ;
1112     close (pfd);
1113     pfd = NOTOK;
1114 }
1115
1116
1117 static int
1118 annoaux (struct mailname *mp)
1119 {
1120     int i;
1121     char buffer[BUFSIZ];
1122
1123     snprintf (buffer, sizeof(buffer), "%s\n", adrformat (mp));
1124     i = strlen (buffer);
1125
1126     return (write (pfd, buffer, i) == i ? OK : NOTOK);
1127 }
1128
1129
1130 static void
1131 insert_fcc (struct headers *hdr, char *pp)
1132 {
1133     char *cp;
1134
1135     for (cp = pp; isspace (*cp); cp++)
1136         continue;
1137     for (pp += strlen (pp) - 1; pp > cp && isspace (*pp); pp--)
1138         continue;
1139     if (pp >= cp)
1140         *++pp = 0;
1141     if (*cp == 0)
1142         return;
1143
1144     if (fccind >= FCCS)
1145         adios (NULL, "too many %ss", hdr->value);
1146     fccfold[fccind++] = getcpy (cp);
1147 }
1148
1149 /*
1150  * BCC GENERATION
1151  */
1152
1153 static void
1154 make_bcc_file (int dashstuff)
1155 {
1156     int fd, i;
1157     pid_t child_id;
1158     char *vec[6];
1159     FILE *out;
1160
1161     strncpy (bccfil, m_tmpfil ("bccs"), sizeof(bccfil));
1162     if ((out = fopen (bccfil, "w")) == NULL)
1163         adios (bccfil, "unable to create");
1164     chmod (bccfil, 0600);
1165
1166     fprintf (out, "Date: %s\n", dtime (&tclock, 0));
1167     if (msgid)
1168         fprintf (out, "Message-ID: <%d.%ld@%s>\n",
1169                 (int) getpid (), (long) tclock, LocalName ());
1170     fprintf (out, "From: %s\n", signature);
1171     if (subject)
1172         fprintf (out, "Subject: %s", subject);
1173     fprintf (out, "BCC:\n");
1174
1175     /*
1176      * Use MIME encapsulation for Bcc messages
1177      */
1178     if (mime) {
1179         char *cp;
1180
1181         /*
1182          * Check if any lines in the message clash with the
1183          * prefix for the MIME multipart separator.  If there
1184          * is a clash, increment one of the letters in the
1185          * prefix and check again.
1186          */
1187         if ((cp = strchr(prefix, 'a')) == NULL)
1188             adios (NULL, "lost prefix start");
1189         while (find_prefix () == NOTOK) {
1190             if (*cp < 'z')
1191                 (*cp)++;
1192             else
1193                 if (*++cp == 0)
1194                     adios (NULL, "can't find a unique delimiter string");
1195                 else
1196                     (*cp)++;
1197         }
1198
1199         fprintf (out, "%s: %s\n%s: multipart/digest; boundary=\"",
1200                  VRSN_FIELD, VRSN_VALUE, TYPE_FIELD);
1201         fprintf (out, "%s\"\n\n--%s\n\n", prefix, prefix);
1202     } else {
1203         fprintf (out, "\n------- Blind-Carbon-Copy\n\n");
1204     }
1205
1206     fflush (out);
1207
1208     /*
1209      * Do mhl filtering of Bcc messages instead
1210      * of MIME encapsulation.
1211      */
1212     if (filter != NULL) {
1213         vec[0] = r1bindex (mhlproc, '/');
1214
1215         for (i = 0; (child_id = fork()) == NOTOK && i < 5; i++)
1216             sleep (5);
1217         switch (child_id) {
1218             case NOTOK: 
1219                 adios ("fork", "unable to");
1220
1221             case OK: 
1222                 dup2 (fileno (out), 1);
1223
1224                 i = 1;
1225                 vec[i++] = "-forward";
1226                 vec[i++] = "-form";
1227                 vec[i++] = filter;
1228                 vec[i++] = tmpfil;
1229
1230                 /* was the flag -[no]dashstuffing specified? */
1231                 if (dashstuff > 0)
1232                     vec[i++] = "-dashstuffing";
1233                 else if (dashstuff < 0)
1234                     vec[i++] = "-nodashstuffing";
1235                 vec[i] = NULL;
1236
1237                 execvp (mhlproc, vec);
1238                 fprintf (stderr, "unable to exec ");
1239                 perror (mhlproc);
1240                 _exit (-1);
1241
1242             default: 
1243                 pidXwait (child_id, mhlproc);
1244                 break;
1245         }
1246     } else {
1247         if ((fd = open (tmpfil, O_RDONLY)) == NOTOK)
1248             adios (tmpfil, "unable to re-open");
1249
1250         /*
1251          * If using MIME encapsulation, or if the -nodashstuffing
1252          * flag was given, then just copy message.  Else do
1253          * RFC934 quoting (dashstuffing).
1254          */
1255         if (mime || dashstuff < 0)
1256             cpydata (fd, fileno (out), tmpfil, bccfil);
1257         else
1258             cpydgst (fd, fileno (out), tmpfil, bccfil);
1259         close (fd);
1260     }
1261
1262     fseek (out, 0L, SEEK_END);
1263     if (mime)
1264         fprintf (out, "\n--%s--\n", prefix);
1265     else
1266         fprintf (out, "\n------- End of Blind-Carbon-Copy\n");
1267     fclose (out);
1268 }
1269
1270
1271 /*
1272  * Scan message to check if any lines clash with
1273  * the prefix of the MIME multipart separator.
1274  */
1275
1276 static int
1277 find_prefix (void)
1278 {
1279     int len, result;
1280     char buffer[BUFSIZ];
1281     FILE *in;
1282
1283     if ((in = fopen (tmpfil, "r")) == NULL)
1284         adios (tmpfil, "unable to re-open");
1285
1286     len = strlen (prefix);
1287
1288     result = OK;
1289     while (fgets (buffer, sizeof(buffer) - 1, in))
1290         if (buffer[0] == '-' && buffer[1] == '-') {
1291             char *cp;
1292
1293             for (cp = buffer + strlen (buffer) - 1; cp >= buffer; cp--)
1294                 if (!isspace (*cp))
1295                     break;
1296             *++cp = '\0';
1297             if (strcmp (buffer + 2, prefix) == 0) {
1298                 result = NOTOK;
1299                 break;
1300             }
1301         }
1302
1303     fclose (in);
1304     return result;
1305 }
1306
1307
1308 #define plural(x) (x == 1 ? "" : "s")
1309
1310 static void
1311 chkadr (void)
1312 {
1313     if (badadr && unkadr)
1314         die (NULL, "%d address%s unparsable, %d addressee%s undeliverable",
1315                 badadr, plural (badadr), unkadr, plural (badadr));
1316     if (badadr)
1317         die (NULL, "%d address%s unparsable", badadr, plural (badadr));
1318     if (unkadr)
1319         die (NULL, "%d addressee%s undeliverable", unkadr, plural (unkadr));
1320 }
1321
1322
1323 static void
1324 do_addresses (int bccque, int talk)
1325 {
1326     int retval;
1327     int state;
1328     struct mailname *lp;
1329
1330     state = 0;
1331     for (lp = localaddrs.m_next; lp; lp = lp->m_next)
1332         if (lp->m_bcc ? bccque : !bccque) {
1333             if (talk && !state)
1334                 printf ("  -- Local Recipients --\n");
1335             do_an_address (lp, talk);
1336             state++;
1337         }
1338
1339     state = 0;
1340     for (lp = uuaddrs.m_next; lp; lp = lp->m_next)
1341         if (lp->m_bcc ? bccque : !bccque) {
1342             if (talk && !state)
1343                 printf ("  -- UUCP Recipients --\n");
1344             do_an_address (lp, talk);
1345             state++;
1346         }
1347
1348     state = 0;
1349     for (lp = netaddrs.m_next; lp; lp = lp->m_next)
1350         if (lp->m_bcc ? bccque : !bccque) {
1351             if (talk && !state)
1352                 printf ("  -- Network Recipients --\n");
1353             do_an_address (lp, talk);
1354             state++;
1355         }
1356
1357     chkadr ();
1358
1359 #ifdef SMTPMTS
1360     if (rp_isbad (retval = sm_waend ()))
1361         die (NULL, "problem ending addresses; %s", rp_string (retval));
1362 #endif /* SMTPMTS */
1363 }
1364
1365
1366 /*
1367  * MTS-SPECIFIC INTERACTION
1368  */
1369
1370
1371 /*
1372  * SENDMAIL/SMTP routines
1373  */
1374
1375 #ifdef SMTPMTS
1376
1377 static void
1378 post (char *file, int bccque, int talk)
1379 {
1380     int fd, onex;
1381     int retval;
1382
1383     onex = !(msgflags & MINV) || bccque;
1384     if (verbose) {
1385         if (msgflags & MINV)
1386             printf (" -- Posting for %s Recipients --\n",
1387                     bccque ? "Blind" : "Sighted");
1388         else
1389             printf (" -- Posting for All Recipients --\n");
1390     }
1391
1392     sigon ();
1393
1394     if (rp_isbad (retval = sm_init (clientsw, serversw, watch, verbose,
1395                                     snoop, onex, queued, sasl, saslmech,
1396                                     user))
1397             || rp_isbad (retval = sm_winit (smtpmode, from)))
1398         die (NULL, "problem initializing server; %s", rp_string (retval));
1399
1400     do_addresses (bccque, talk && verbose);
1401     if ((fd = open (file, O_RDONLY)) == NOTOK)
1402         die (file, "unable to re-open");
1403     do_text (file, fd);
1404     close (fd);
1405     fflush (stdout);
1406
1407     sm_end (onex ? OK : DONE);
1408     sigoff ();
1409
1410     if (verbose) {
1411         if (msgflags & MINV)
1412             printf (" -- %s Recipient Copies Posted --\n",
1413                     bccque ? "Blind" : "Sighted");
1414         else
1415             printf (" -- Recipient Copies Posted --\n");
1416     }
1417
1418     fflush (stdout);
1419 }
1420
1421
1422 /* Address Verification */
1423
1424 static void
1425 verify_all_addresses (int talk)
1426 {
1427     int retval;
1428     struct mailname *lp;
1429
1430     sigon ();
1431
1432     if (!whomsw || checksw)
1433         if (rp_isbad (retval = sm_init (clientsw, serversw, watch, verbose, snoop, 0,
1434                                         queued, sasl, saslmech, user))
1435                 || rp_isbad (retval = sm_winit (smtpmode, from)))
1436             die (NULL, "problem initializing server; %s", rp_string (retval));
1437
1438     if (talk && !whomsw)
1439         printf (" -- Address Verification --\n");
1440     if (talk && localaddrs.m_next)
1441         printf ("  -- Local Recipients --\n");
1442     for (lp = localaddrs.m_next; lp; lp = lp->m_next)
1443         do_an_address (lp, talk);
1444
1445     if (talk && uuaddrs.m_next)
1446         printf ("  -- UUCP Recipients --\n");
1447     for (lp = uuaddrs.m_next; lp; lp = lp->m_next)
1448         do_an_address (lp, talk);
1449
1450     if (talk && netaddrs.m_next)
1451         printf ("  -- Network Recipients --\n");
1452     for (lp = netaddrs.m_next; lp; lp = lp->m_next)
1453         do_an_address (lp, talk);
1454
1455     chkadr ();
1456     if (talk && !whomsw)
1457         printf (" -- Address Verification Successful --\n");
1458
1459     if (!whomsw || checksw)
1460         sm_end (DONE);
1461
1462     fflush (stdout);
1463     sigoff ();
1464 }
1465
1466
1467 static void
1468 do_an_address (struct mailname *lp, int talk)
1469 {
1470     int retval;
1471     char *mbox, *host;
1472     char addr[BUFSIZ];
1473
1474     switch (lp->m_type) {
1475         case LOCALHOST: 
1476             mbox = lp->m_mbox;
1477             host = lp->m_host;
1478             strncpy (addr, mbox, sizeof(addr));
1479             break;
1480
1481         case UUCPHOST: 
1482             mbox = auxformat (lp, 0);
1483             host = NULL;
1484             snprintf (addr, sizeof(addr), "%s!%s", lp->m_host, lp->m_mbox);
1485             break;
1486
1487         default:                /* let SendMail decide if the host is bad  */
1488             mbox = lp->m_mbox;
1489             host = lp->m_host;
1490             snprintf (addr, sizeof(addr), "%s at %s", mbox, host);
1491             break;
1492     }
1493
1494     if (talk)
1495         printf ("  %s%s", addr, whomsw && lp->m_bcc ? "[BCC]" : "");
1496
1497     if (whomsw && !checksw) {
1498         putchar ('\n');
1499         return;
1500     }
1501     if (talk)
1502         printf (": ");
1503     fflush (stdout);
1504
1505     switch (retval = sm_wadr (mbox, host,
1506                          lp->m_type != UUCPHOST ? lp->m_path : NULL)) {
1507         case RP_OK: 
1508             if (talk)
1509                 printf ("address ok\n");
1510             break;
1511
1512         case RP_NO: 
1513         case RP_USER: 
1514             if (!talk)
1515                 fprintf (stderr, "  %s: ", addr);
1516             fprintf (talk ? stdout : stderr, "loses; %s\n",
1517                         rp_string (retval));
1518             unkadr++;
1519             break;
1520
1521         default: 
1522             if (!talk)
1523                 fprintf (stderr, "  %s: ", addr);
1524             die (NULL, "unexpected response; %s", rp_string (retval));
1525     }
1526
1527     fflush (stdout);
1528 }
1529
1530
1531 static void
1532 do_text (char *file, int fd)
1533 {
1534     int retval, state;
1535     char buf[BUFSIZ];
1536
1537     lseek (fd, (off_t) 0, SEEK_SET);
1538
1539     while ((state = read (fd, buf, sizeof(buf))) > 0) {
1540         if (rp_isbad (retval = sm_wtxt (buf, state)))
1541             die (NULL, "problem writing text; %s\n", rp_string (retval));
1542     }
1543
1544     if (state == NOTOK)
1545         die (file, "problem reading from");
1546
1547     switch (retval = sm_wtend ()) {
1548         case RP_OK: 
1549             break;
1550
1551         case RP_NO: 
1552         case RP_NDEL: 
1553             die (NULL, "posting failed; %s", rp_string (retval));
1554
1555         default: 
1556             die (NULL, "unexpected response; %s", rp_string (retval));
1557     }
1558 }
1559
1560 #endif /* SMTPMTS */
1561
1562
1563 /*
1564  * SIGNAL HANDLING
1565  */
1566
1567 static RETSIGTYPE
1568 sigser (int i)
1569 {
1570 #ifndef RELIABLE_SIGNALS
1571     SIGNAL (i, SIG_IGN);
1572 #endif
1573
1574     unlink (tmpfil);
1575     if (msgflags & MINV)
1576         unlink (bccfil);
1577
1578 #ifdef SMTPMTS
1579     if (!whomsw || checksw)
1580         sm_end (NOTOK);
1581 #endif /* SMTPMTS */
1582
1583     done (1);
1584 }
1585
1586
1587 static void
1588 sigon (void)
1589 {
1590     if (debug)
1591         return;
1592
1593     hstat = SIGNAL2 (SIGHUP, sigser);
1594     istat = SIGNAL2 (SIGINT, sigser);
1595     qstat = SIGNAL2 (SIGQUIT, sigser);
1596     tstat = SIGNAL2 (SIGTERM, sigser);
1597 }
1598
1599
1600 static void
1601 sigoff (void)
1602 {
1603     if (debug)
1604         return;
1605
1606     SIGNAL (SIGHUP, hstat);
1607     SIGNAL (SIGINT, istat);
1608     SIGNAL (SIGQUIT, qstat);
1609     SIGNAL (SIGTERM, tstat);
1610 }
1611
1612 /*
1613  * FCC INTERACTION
1614  */
1615
1616 static void
1617 p_refile (char *file)
1618 {
1619     int i;
1620
1621     if (fccind == 0)
1622         return;
1623
1624     if (verbose)
1625         printf (" -- Filing Folder Copies --\n");
1626     for (i = 0; i < fccind; i++)
1627         fcc (file, fccfold[i]);
1628     if (verbose)
1629         printf (" -- Folder Copies Filed --\n");
1630 }
1631
1632
1633 /*
1634  * Call the `fileproc' to add the file to the folder.
1635  */
1636
1637 static void
1638 fcc (char *file, char *folder)
1639 {
1640     pid_t child_id;
1641     int i, status;
1642     char fold[BUFSIZ];
1643
1644     if (verbose)
1645         printf ("  %sFcc %s: ", msgstate == RESENT ? "Resent-" : "", folder);
1646     fflush (stdout);
1647
1648     for (i = 0; (child_id = fork ()) == NOTOK && i < 5; i++)
1649         sleep (5);
1650
1651     switch (child_id) {
1652         case NOTOK: 
1653             if (!verbose)
1654                 fprintf (stderr, "  %sFcc %s: ",
1655                         msgstate == RESENT ? "Resent-" : "", folder);
1656             fprintf (verbose ? stdout : stderr, "no forks, so not ok\n");
1657             break;
1658
1659         case OK: 
1660             /* see if we need to add `+' */
1661             snprintf (fold, sizeof(fold), "%s%s",
1662                     *folder == '+' || *folder == '@' ? "" : "+", folder);
1663
1664             /* now exec the fileproc */
1665             execlp (fileproc, r1bindex (fileproc, '/'),
1666                     "-link", "-file", file, fold, NULL);
1667             _exit (-1);
1668
1669         default: 
1670             if ((status = pidwait (child_id, OK))) {
1671                 if (!verbose)
1672                     fprintf (stderr, "  %sFcc %s: ",
1673                             msgstate == RESENT ? "Resent-" : "", folder);
1674                 pidstatus (status, verbose ? stdout : stderr, NULL);
1675             } else {
1676                 if (verbose)
1677                     printf ("folder ok\n");
1678             }
1679     }
1680
1681     fflush (stdout);
1682 }
1683
1684 /*
1685  * TERMINATION
1686  */
1687
1688 static void
1689 die (char *what, char *fmt, ...)
1690 {
1691     va_list ap;
1692
1693     unlink (tmpfil);
1694     if (msgflags & MINV)
1695         unlink (bccfil);
1696
1697 #ifdef SMTPMTS
1698     if (!whomsw || checksw)
1699         sm_end (NOTOK);
1700 #endif /* SMTPMTS */
1701
1702     va_start(ap, fmt);
1703     advertise (what, NULL, fmt, ap);
1704     va_end(ap);
1705     done (1);
1706 }