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