Merge from vendor branch FILE:
[dragonfly.git] / contrib / sendmail / src / main.c
1 /*
2  * Copyright (c) 1998-2003 Sendmail, Inc. and its suppliers.
3  *      All rights reserved.
4  * Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.
5  * Copyright (c) 1988, 1993
6  *      The Regents of the University of California.  All rights reserved.
7  *
8  * By using this file, you agree to the terms and conditions set
9  * forth in the LICENSE file which can be found at the top level of
10  * the sendmail distribution.
11  *
12  * $DragonFly: src/contrib/sendmail/src/Attic/main.c,v 1.3 2003/12/22 04:04:23 drhodus Exp $
13  */
14
15 #define _DEFINE
16 #include <sendmail.h>
17 #include <sm/xtrap.h>
18 #include <sm/signal.h>
19
20 #ifndef lint
21 SM_UNUSED(static char copyright[]) =
22 "@(#) Copyright (c) 1998-2001 Sendmail, Inc. and its suppliers.\n\
23         All rights reserved.\n\
24      Copyright (c) 1983, 1995-1997 Eric P. Allman.  All rights reserved.\n\
25      Copyright (c) 1988, 1993\n\
26         The Regents of the University of California.  All rights reserved.\n";
27 #endif /* ! lint */
28
29 SM_RCSID("@(#)$Id: main.c,v 8.887.2.27 2003/08/04 17:23:37 ca Exp $")
30
31
32 #if NETINET || NETINET6
33 # include <arpa/inet.h>
34 #endif /* NETINET || NETINET6 */
35
36 /* for getcfname() */
37 #include <sendmail/pathnames.h>
38
39 static SM_DEBUG_T
40 DebugNoPRestart = SM_DEBUG_INITIALIZER("no_persistent_restart",
41         "@(#)$Debug: no_persistent_restart - don't restart, log only $");
42
43 static void     dump_class __P((STAB *, int));
44 static void     obsolete __P((char **));
45 static void     testmodeline __P((char *, ENVELOPE *));
46 static char     *getextenv __P((const char *));
47 static void     sm_printoptions __P((char **));
48 static SIGFUNC_DECL     intindebug __P((int));
49 static SIGFUNC_DECL     sighup __P((int));
50 static SIGFUNC_DECL     sigpipe __P((int));
51 static SIGFUNC_DECL     sigterm __P((int));
52 #ifdef SIGUSR1
53 static SIGFUNC_DECL     sigusr1 __P((int));
54 #endif /* SIGUSR1 */
55
56 /*
57 **  SENDMAIL -- Post mail to a set of destinations.
58 **
59 **      This is the basic mail router.  All user mail programs should
60 **      call this routine to actually deliver mail.  Sendmail in
61 **      turn calls a bunch of mail servers that do the real work of
62 **      delivering the mail.
63 **
64 **      Sendmail is driven by settings read in from /etc/mail/sendmail.cf
65 **      (read by readcf.c).
66 **
67 **      Usage:
68 **              /usr/lib/sendmail [flags] addr ...
69 **
70 **              See the associated documentation for details.
71 **
72 **      Authors:
73 **              Eric Allman, UCB/INGRES (until 10/81).
74 **                           Britton-Lee, Inc., purveyors of fine
75 **                              database computers (11/81 - 10/88).
76 **                           International Computer Science Institute
77 **                              (11/88 - 9/89).
78 **                           UCB/Mammoth Project (10/89 - 7/95).
79 **                           InReference, Inc. (8/95 - 1/97).
80 **                           Sendmail, Inc. (1/98 - present).
81 **              The support of my employers is gratefully acknowledged.
82 **                      Few of them (Britton-Lee in particular) have had
83 **                      anything to gain from my involvement in this project.
84 **
85 **              Gregory Neil Shapiro,
86 **                      Worcester Polytechnic Institute (until 3/98).
87 **                      Sendmail, Inc. (3/98 - present).
88 **
89 **              Claus Assmann,
90 **                      Sendmail, Inc. (12/98 - present).
91 */
92
93 char            *FullName;      /* sender's full name */
94 ENVELOPE        BlankEnvelope;  /* a "blank" envelope */
95 static ENVELOPE MainEnvelope;   /* the envelope around the basic letter */
96 ADDRESS         NullAddress =   /* a null address */
97                 { "", "", NULL, "" };
98 char            *CommandLineArgs;       /* command line args for pid file */
99 bool            Warn_Q_option = false;  /* warn about Q option use */
100 static int      MissingFds = 0; /* bit map of fds missing on startup */
101 char            *Mbdb = "pw";   /* mailbox database defaults to /etc/passwd */
102
103 #ifdef NGROUPS_MAX
104 GIDSET_T        InitialGidSet[NGROUPS_MAX];
105 #endif /* NGROUPS_MAX */
106
107 #define MAXCONFIGLEVEL  10      /* highest config version level known */
108
109 #if SASL
110 static sasl_callback_t srvcallbacks[] =
111 {
112         {       SASL_CB_VERIFYFILE,     &safesaslfile,  NULL    },
113         {       SASL_CB_PROXY_POLICY,   &proxy_policy,  NULL    },
114         {       SASL_CB_LIST_END,       NULL,           NULL    }
115 };
116 #endif /* SASL */
117
118 unsigned int    SubmitMode;
119 int             SyslogPrefixLen; /* estimated length of syslog prefix */
120 #define PIDLEN          6       /* pid length for computing SyslogPrefixLen */
121 #ifndef SL_FUDGE
122 # define SL_FUDGE       10      /* fudge offset for SyslogPrefixLen */
123 #endif /* ! SL_FUDGE */
124 #define SLDLL           8       /* est. length of default syslog label */
125
126
127 /* Some options are dangerous to allow users to use in non-submit mode */
128 #define CHECK_AGAINST_OPMODE(cmd)                                       \
129 {                                                                       \
130         if (extraprivs &&                                               \
131             OpMode != MD_DELIVER && OpMode != MD_SMTP &&                \
132             OpMode != MD_ARPAFTP &&                                     \
133             OpMode != MD_VERIFY && OpMode != MD_TEST)                   \
134         {                                                               \
135                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,          \
136                                      "WARNING: Ignoring submission mode -%c option (not in submission mode)\n", \
137                        (cmd));                                          \
138                 break;                                                  \
139         }                                                               \
140         if (extraprivs && queuerun)                                     \
141         {                                                               \
142                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,          \
143                                      "WARNING: Ignoring submission mode -%c option with -q\n", \
144                        (cmd));                                          \
145                 break;                                                  \
146         }                                                               \
147 }
148
149 int
150 main(argc, argv, envp)
151         int argc;
152         char **argv;
153         char **envp;
154 {
155         register char *p;
156         char **av;
157         extern char Version[];
158         char *ep, *from;
159         STAB *st;
160         register int i;
161         int j;
162         int dp;
163         int fill_errno;
164         int qgrp = NOQGRP;              /* queue group to process */
165         bool safecf = true;
166         BITMAP256 *p_flags = NULL;      /* daemon flags */
167         bool warn_C_flag = false;
168         bool auth = true;               /* whether to set e_auth_param */
169         char warn_f_flag = '\0';
170         bool run_in_foreground = false; /* -bD mode */
171         bool queuerun = false, debug = false;
172         struct passwd *pw;
173         struct hostent *hp;
174         char *nullserver = NULL;
175         char *authinfo = NULL;
176         char *sysloglabel = NULL;       /* label for syslog */
177         char *conffile = NULL;          /* name of .cf file */
178         char *queuegroup = NULL;        /* queue group to process */
179 #if _FFR_QUARANTINE
180         char *quarantining = NULL;      /* quarantine queue items? */
181 #endif /* _FFR_QUARANTINE */
182         bool extraprivs;
183         bool forged, negate;
184         bool queuepersistent = false;   /* queue runner process runs forever */
185         bool foregroundqueue = false;   /* queue run in foreground */
186         bool save_val;                  /* to save some bool var. */
187         int cftype;                     /* which cf file to use? */
188         static time_t starttime = 0;    /* when was process started */
189         struct stat traf_st;            /* for TrafficLog FIFO check */
190         char buf[MAXLINE];
191         char jbuf[MAXHOSTNAMELEN];      /* holds MyHostName */
192         static char rnamebuf[MAXNAME];  /* holds RealUserName */
193         char *emptyenviron[1];
194 #if STARTTLS
195         bool tls_ok;
196 #endif /* STARTTLS */
197         QUEUE_CHAR *new;
198         ENVELOPE *e;
199         extern int DtableSize;
200         extern int optind;
201         extern int opterr;
202         extern char *optarg;
203         extern char **environ;
204 #if SASL
205         extern void sm_sasl_init __P((void));
206 #endif /* SASL */
207
208 #if USE_ENVIRON
209         envp = environ;
210 #endif /* USE_ENVIRON */
211
212         /* turn off profiling */
213         SM_PROF(0);
214
215         /* install default exception handler */
216         sm_exc_newthread(fatal_error);
217
218         /* set the default in/out channel so errors reported to screen */
219         InChannel = smioin;
220         OutChannel = smioout;
221
222         /*
223         **  Check to see if we reentered.
224         **      This would normally happen if e_putheader or e_putbody
225         **      were NULL when invoked.
226         */
227
228         if (starttime != 0)
229         {
230                 syserr("main: reentered!");
231                 abort();
232         }
233         starttime = curtime();
234
235         /* avoid null pointer dereferences */
236         TermEscape.te_rv_on = TermEscape.te_rv_off = "";
237
238         RealUid = getuid();
239         RealGid = getgid();
240
241         /* Check if sendmail is running with extra privs */
242         extraprivs = (RealUid != 0 &&
243                       (geteuid() != getuid() || getegid() != getgid()));
244
245         CurrentPid = getpid();
246
247         /* get whatever .cf file is right for the opmode */
248         cftype = SM_GET_RIGHT_CF;
249
250         /* in 4.4BSD, the table can be huge; impose a reasonable limit */
251         DtableSize = getdtsize();
252         if (DtableSize > 256)
253                 DtableSize = 256;
254
255         /*
256         **  Be sure we have enough file descriptors.
257         **      But also be sure that 0, 1, & 2 are open.
258         */
259
260         /* reset errno and fill_errno; the latter is used way down below */
261         errno = fill_errno = 0;
262         fill_fd(STDIN_FILENO, NULL);
263         if (errno != 0)
264                 fill_errno = errno;
265         fill_fd(STDOUT_FILENO, NULL);
266         if (errno != 0)
267                 fill_errno = errno;
268         fill_fd(STDERR_FILENO, NULL);
269         if (errno != 0)
270                 fill_errno = errno;
271
272         i = DtableSize;
273         while (--i > 0)
274         {
275                 if (i != STDIN_FILENO && i != STDOUT_FILENO &&
276                     i != STDERR_FILENO)
277                         (void) close(i);
278         }
279         errno = 0;
280
281 #if LOG
282 # ifndef SM_LOG_STR
283 #  define SM_LOG_STR    "sendmail"
284 # endif /* ! SM_LOG_STR */
285 #  ifdef LOG_MAIL
286         openlog(SM_LOG_STR, LOG_PID, LOG_MAIL);
287 #  else /* LOG_MAIL */
288         openlog(SM_LOG_STR, LOG_PID);
289 #  endif /* LOG_MAIL */
290 #endif /* LOG */
291
292         /*
293         **  Seed the random number generator.
294         **  Used for queue file names, picking a queue directory, and
295         **  MX randomization.
296         */
297
298         seed_random();
299
300         /* do machine-dependent initializations */
301         init_md(argc, argv);
302
303
304         SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL;
305
306         /* reset status from syserr() calls for missing file descriptors */
307         Errors = 0;
308         ExitStat = EX_OK;
309
310         SubmitMode = SUBMIT_UNKNOWN;
311 #if XDEBUG
312         checkfd012("after openlog");
313 #endif /* XDEBUG */
314
315         tTsetup(tTdvect, sizeof tTdvect, "0-99.1,*_trace_*.1");
316
317 #ifdef NGROUPS_MAX
318         /* save initial group set for future checks */
319         i = getgroups(NGROUPS_MAX, InitialGidSet);
320         if (i <= 0)
321         {
322                 InitialGidSet[0] = (GID_T) -1;
323                 i = 0;
324         }
325         while (i < NGROUPS_MAX)
326                 InitialGidSet[i++] = InitialGidSet[0];
327 #endif /* NGROUPS_MAX */
328
329         /* drop group id privileges (RunAsUser not yet set) */
330         dp = drop_privileges(false);
331         setstat(dp);
332
333 #ifdef SIGUSR1
334         /* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
335         if (!extraprivs)
336         {
337                 /* arrange to dump state on user-1 signal */
338                 (void) sm_signal(SIGUSR1, sigusr1);
339         }
340         else
341         {
342                 /* ignore user-1 signal */
343                 (void) sm_signal(SIGUSR1, SIG_IGN);
344         }
345 #endif /* SIGUSR1 */
346
347         /* initialize for setproctitle */
348         initsetproctitle(argc, argv, envp);
349
350         /* Handle any non-getoptable constructions. */
351         obsolete(argv);
352
353         /*
354         **  Do a quick prescan of the argument list.
355         */
356
357
358         /* find initial opMode */
359         OpMode = MD_DELIVER;
360         av = argv;
361         p = strrchr(*av, '/');
362         if (p++ == NULL)
363                 p = *av;
364         if (strcmp(p, "newaliases") == 0)
365                 OpMode = MD_INITALIAS;
366         else if (strcmp(p, "mailq") == 0)
367                 OpMode = MD_PRINT;
368         else if (strcmp(p, "smtpd") == 0)
369                 OpMode = MD_DAEMON;
370         else if (strcmp(p, "hoststat") == 0)
371                 OpMode = MD_HOSTSTAT;
372         else if (strcmp(p, "purgestat") == 0)
373                 OpMode = MD_PURGESTAT;
374
375 #if _FFR_QUARANTINE
376 # if defined(__osf__) || defined(_AIX3)
377 #  define OPTIONS       "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:xQ:"
378 # endif /* defined(__osf__) || defined(_AIX3) */
379 # if defined(sony_news)
380 #  define OPTIONS       "A:B:b:C:cd:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:q:R:r:sTtV:vX:Q:"
381 # endif /* defined(sony_news) */
382 # ifndef OPTIONS
383 #  define OPTIONS       "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:Q:"
384 # endif /* ! OPTIONS */
385 #else /* _FFR_QUARANTINE */
386 # if defined(__osf__) || defined(_AIX3)
387 #  define OPTIONS       "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:x"
388 # endif /* defined(__osf__) || defined(_AIX3) */
389 # if defined(sony_news)
390 #  define OPTIONS       "A:B:b:C:cd:E:e:F:f:Gh:IiJ:L:M:mN:nO:o:p:q:R:r:sTtV:vX:"
391 # endif /* defined(sony_news) */
392 # ifndef OPTIONS
393 #  define OPTIONS       "A:B:b:C:cd:e:F:f:Gh:IiL:M:mN:nO:o:p:q:R:r:sTtV:vX:"
394 # endif /* ! OPTIONS */
395 #endif /* _FFR_QUARANTINE */
396
397         /* Set to 0 to allow -b; need to check optarg before using it! */
398         opterr = 0;
399         while ((j = getopt(argc, argv, OPTIONS)) != -1)
400         {
401                 switch (j)
402                 {
403                   case 'b':     /* operations mode */
404                         j = (optarg == NULL) ? ' ' : *optarg;
405                         switch (j)
406                         {
407                           case MD_DAEMON:
408                           case MD_FGDAEMON:
409                           case MD_SMTP:
410                           case MD_INITALIAS:
411                           case MD_DELIVER:
412                           case MD_VERIFY:
413                           case MD_TEST:
414                           case MD_PRINT:
415                           case MD_PRINTNQE:
416                           case MD_HOSTSTAT:
417                           case MD_PURGESTAT:
418                           case MD_ARPAFTP:
419                                 OpMode = j;
420                                 break;
421
422                           case MD_FREEZE:
423                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
424                                                      "Frozen configurations unsupported\n");
425                                 return EX_USAGE;
426
427                           default:
428                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
429                                                      "Invalid operation mode %c\n",
430                                                      j);
431                                 return EX_USAGE;
432                         }
433                         break;
434
435                   case 'd':
436                         debug = true;
437                         tTflag(optarg);
438                         (void) sm_io_setvbuf(smioout, SM_TIME_DEFAULT,
439                                              (char *) NULL, SM_IO_NBF,
440                                              SM_IO_BUFSIZ);
441                         break;
442
443                   case 'G':     /* relay (gateway) submission */
444                         SubmitMode = SUBMIT_MTA;
445                         break;
446
447                   case 'L':
448                         if (optarg == NULL)
449                         {
450                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
451                                                      "option requires an argument -- '%c'",
452                                                      (char) j);
453                                 return EX_USAGE;
454                         }
455                         j = SM_MIN(strlen(optarg), 24) + 1;
456                         sysloglabel = xalloc(j);
457                         (void) sm_strlcpy(sysloglabel, optarg, j);
458                         SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) +
459                                           SL_FUDGE + j;
460                         break;
461
462 #if _FFR_QUARANTINE
463                   case 'Q':
464 #endif /* _FFR_QUARANTINE */
465                   case 'q':
466                         /* just check if it is there */
467                         queuerun = true;
468                         break;
469                 }
470         }
471         opterr = 1;
472
473         /* Don't leak queue information via debug flags */
474         if (extraprivs && queuerun && debug)
475         {
476                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
477                                      "WARNING: Can not use -d with -q.  Disabling debugging.\n");
478                 sm_debug_setfile(NULL);
479                 (void) memset(tTdvect, '\0', sizeof tTdvect);
480         }
481
482 #if LOG
483         if (sysloglabel != NULL)
484         {
485                 /* Sanitize the string */
486                 for (p = sysloglabel; *p != '\0'; p++)
487                 {
488                         if (!isascii(*p) || !isprint(*p) || *p == '%')
489                                 *p = '*';
490                 }
491                 closelog();
492 #  ifdef LOG_MAIL
493                 openlog(sysloglabel, LOG_PID, LOG_MAIL);
494 #  else /* LOG_MAIL */
495                 openlog(sysloglabel, LOG_PID);
496 #  endif /* LOG_MAIL */
497         }
498 #endif /* LOG */
499
500         /* set up the blank envelope */
501         BlankEnvelope.e_puthdr = putheader;
502         BlankEnvelope.e_putbody = putbody;
503         BlankEnvelope.e_xfp = NULL;
504         STRUCTCOPY(NullAddress, BlankEnvelope.e_from);
505         CurEnv = &BlankEnvelope;
506         STRUCTCOPY(NullAddress, MainEnvelope.e_from);
507
508         /*
509         **  Set default values for variables.
510         **      These cannot be in initialized data space.
511         */
512
513         setdefaults(&BlankEnvelope);
514         initmacros(&BlankEnvelope);
515
516         /* reset macro */
517         set_op_mode(OpMode);
518
519         pw = sm_getpwuid(RealUid);
520         if (pw != NULL)
521                 (void) sm_strlcpy(rnamebuf, pw->pw_name, sizeof rnamebuf);
522         else
523                 (void) sm_snprintf(rnamebuf, sizeof rnamebuf, "Unknown UID %d",
524                                    (int) RealUid);
525
526         RealUserName = rnamebuf;
527
528         if (tTd(0, 101))
529         {
530                 sm_dprintf("Version %s\n", Version);
531                 finis(false, true, EX_OK);
532                 /* NOTREACHED */
533         }
534
535         /*
536         **  if running non-set-user-ID binary as non-root, pretend
537         **  we are the RunAsUid
538         */
539
540         if (RealUid != 0 && geteuid() == RealUid)
541         {
542                 if (tTd(47, 1))
543                         sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
544                                    (int) RealUid);
545                 RunAsUid = RealUid;
546         }
547         else if (geteuid() != 0)
548                 RunAsUid = geteuid();
549
550         EffGid = getegid();
551         if (RealUid != 0 && EffGid == RealGid)
552                 RunAsGid = RealGid;
553
554         if (tTd(47, 5))
555         {
556                 sm_dprintf("main: e/ruid = %d/%d e/rgid = %d/%d\n",
557                            (int) geteuid(), (int) getuid(),
558                            (int) getegid(), (int) getgid());
559                 sm_dprintf("main: RunAsUser = %d:%d\n",
560                            (int) RunAsUid, (int) RunAsGid);
561         }
562
563         /* save command line arguments */
564         j = 0;
565         for (av = argv; *av != NULL; )
566                 j += strlen(*av++) + 1;
567         SaveArgv = (char **) xalloc(sizeof (char *) * (argc + 1));
568         CommandLineArgs = xalloc(j);
569         p = CommandLineArgs;
570         for (av = argv, i = 0; *av != NULL; )
571         {
572                 int h;
573
574                 SaveArgv[i++] = newstr(*av);
575                 if (av != argv)
576                         *p++ = ' ';
577                 (void) sm_strlcpy(p, *av++, j);
578                 h = strlen(p);
579                 p += h;
580                 j -= h + 1;
581         }
582         SaveArgv[i] = NULL;
583
584         if (tTd(0, 1))
585         {
586                 extern char *CompileOptions[];
587
588                 sm_dprintf("Version %s\n Compiled with:", Version);
589                 sm_printoptions(CompileOptions);
590         }
591         if (tTd(0, 10))
592         {
593                 extern char *OsCompileOptions[];
594
595                 sm_dprintf("    OS Defines:");
596                 sm_printoptions(OsCompileOptions);
597 #ifdef _PATH_UNIX
598                 sm_dprintf("Kernel symbols:\t%s\n", _PATH_UNIX);
599 #endif /* _PATH_UNIX */
600
601                 sm_dprintf("     Conf file:\t%s (default for MSP)\n",
602                            getcfname(OpMode, SubmitMode, SM_GET_SUBMIT_CF,
603                                      conffile));
604                 sm_dprintf("     Conf file:\t%s (default for MTA)\n",
605                            getcfname(OpMode, SubmitMode, SM_GET_SENDMAIL_CF,
606                                      conffile));
607                 sm_dprintf("      Pid file:\t%s (default)\n", PidFile);
608         }
609
610         if (tTd(0, 12))
611         {
612                 extern char *SmCompileOptions[];
613
614                 sm_dprintf(" libsm Defines:");
615                 sm_printoptions(SmCompileOptions);
616         }
617
618         if (tTd(0, 13))
619         {
620                 extern char *FFRCompileOptions[];
621
622                 sm_dprintf("   FFR Defines:");
623                 sm_printoptions(FFRCompileOptions);
624         }
625
626         /* clear sendmail's environment */
627         ExternalEnviron = environ;
628         emptyenviron[0] = NULL;
629         environ = emptyenviron;
630
631         /*
632         **  restore any original TZ setting until TimeZoneSpec has been
633         **  determined - or early log messages may get bogus time stamps
634         */
635
636         if ((p = getextenv("TZ")) != NULL)
637         {
638                 char *tz;
639                 int tzlen;
640
641                 /* XXX check for reasonable length? */
642                 tzlen = strlen(p) + 4;
643                 tz = xalloc(tzlen);
644                 (void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p);
645
646                 /* XXX check return code? */
647                 (void) putenv(tz);
648         }
649
650         /* prime the child environment */
651         setuserenv("AGENT", "sendmail");
652
653         (void) sm_signal(SIGPIPE, SIG_IGN);
654         OldUmask = umask(022);
655         FullName = getextenv("NAME");
656         if (FullName != NULL)
657                 FullName = newstr(FullName);
658
659         /*
660         **  Initialize name server if it is going to be used.
661         */
662
663 #if NAMED_BIND
664         if (!bitset(RES_INIT, _res.options))
665                 (void) res_init();
666         if (tTd(8, 8))
667                 _res.options |= RES_DEBUG;
668         else
669                 _res.options &= ~RES_DEBUG;
670 # ifdef RES_NOALIASES
671         if (bitset(RES_NOALIASES, _res.options))
672                 ResNoAliases = true;
673         _res.options |= RES_NOALIASES;
674 # endif /* RES_NOALIASES */
675         TimeOuts.res_retry[RES_TO_DEFAULT] = _res.retry;
676         TimeOuts.res_retry[RES_TO_FIRST] = _res.retry;
677         TimeOuts.res_retry[RES_TO_NORMAL] = _res.retry;
678         TimeOuts.res_retrans[RES_TO_DEFAULT] = _res.retrans;
679         TimeOuts.res_retrans[RES_TO_FIRST] = _res.retrans;
680         TimeOuts.res_retrans[RES_TO_NORMAL] = _res.retrans;
681 #endif /* NAMED_BIND */
682
683         errno = 0;
684         from = NULL;
685
686         /* initialize some macros, etc. */
687         init_vendor_macros(&BlankEnvelope);
688
689         /* version */
690         macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version);
691
692         /* hostname */
693         hp = myhostname(jbuf, sizeof jbuf);
694         if (jbuf[0] != '\0')
695         {
696                 struct utsname utsname;
697
698                 if (tTd(0, 4))
699                         sm_dprintf("Canonical name: %s\n", jbuf);
700                 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'w', jbuf);
701                 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'j', jbuf);
702                 setclass('w', jbuf);
703
704                 p = strchr(jbuf, '.');
705                 if (p != NULL)
706                 {
707                         if (p[1] != '\0')
708                         {
709                                 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm',
710                                           &p[1]);
711                         }
712                         while (p != NULL && strchr(&p[1], '.') != NULL)
713                         {
714                                 *p = '\0';
715                                 if (tTd(0, 4))
716                                         sm_dprintf("\ta.k.a.: %s\n", jbuf);
717                                 setclass('w', jbuf);
718                                 *p++ = '.';
719                                 p = strchr(p, '.');
720                         }
721                 }
722
723                 if (uname(&utsname) >= 0)
724                         p = utsname.nodename;
725                 else
726                 {
727                         if (tTd(0, 22))
728                                 sm_dprintf("uname failed (%s)\n",
729                                            sm_errstring(errno));
730                         makelower(jbuf);
731                         p = jbuf;
732                 }
733                 if (tTd(0, 4))
734                         sm_dprintf(" UUCP nodename: %s\n", p);
735                 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'k', p);
736                 setclass('k', p);
737                 setclass('w', p);
738         }
739         if (hp != NULL)
740         {
741                 for (av = hp->h_aliases; av != NULL && *av != NULL; av++)
742                 {
743                         if (tTd(0, 4))
744                                 sm_dprintf("\ta.k.a.: %s\n", *av);
745                         setclass('w', *av);
746                 }
747 #if NETINET || NETINET6
748                 for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++)
749                 {
750 # if NETINET6
751                         char *addr;
752                         char buf6[INET6_ADDRSTRLEN];
753                         struct in6_addr ia6;
754 # endif /* NETINET6 */
755 # if NETINET
756                         struct in_addr ia;
757 # endif /* NETINET */
758                         char ipbuf[103];
759
760                         ipbuf[0] = '\0';
761                         switch (hp->h_addrtype)
762                         {
763 # if NETINET
764                           case AF_INET:
765                                 if (hp->h_length != INADDRSZ)
766                                         break;
767
768                                 memmove(&ia, hp->h_addr_list[i], INADDRSZ);
769                                 (void) sm_snprintf(ipbuf, sizeof ipbuf,
770                                                    "[%.100s]", inet_ntoa(ia));
771                                 break;
772 # endif /* NETINET */
773
774 # if NETINET6
775                           case AF_INET6:
776                                 if (hp->h_length != IN6ADDRSZ)
777                                         break;
778
779                                 memmove(&ia6, hp->h_addr_list[i], IN6ADDRSZ);
780                                 addr = anynet_ntop(&ia6, buf6, sizeof buf6);
781                                 if (addr != NULL)
782                                         (void) sm_snprintf(ipbuf, sizeof ipbuf,
783                                                            "[%.100s]", addr);
784                                 break;
785 # endif /* NETINET6 */
786                         }
787                         if (ipbuf[0] == '\0')
788                                 break;
789
790                         if (tTd(0, 4))
791                                 sm_dprintf("\ta.k.a.: %s\n", ipbuf);
792                         setclass('w', ipbuf);
793                 }
794 #endif /* NETINET || NETINET6 */
795 #if NETINET6
796                 freehostent(hp);
797                 hp = NULL;
798 #endif /* NETINET6 */
799         }
800
801         /* current time */
802         macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL));
803
804         /* current load average */
805         sm_getla();
806
807         QueueLimitRecipient = (QUEUE_CHAR *) NULL;
808         QueueLimitSender = (QUEUE_CHAR *) NULL;
809         QueueLimitId = (QUEUE_CHAR *) NULL;
810 #if _FFR_QUARANTINE
811         QueueLimitQuarantine = (QUEUE_CHAR *) NULL;
812 #endif /* _FFR_QUARANTINE */
813
814         /*
815         **  Crack argv.
816         */
817
818         optind = 1;
819         while ((j = getopt(argc, argv, OPTIONS)) != -1)
820         {
821                 switch (j)
822                 {
823                   case 'b':     /* operations mode */
824                         /* already done */
825                         break;
826
827                   case 'A':     /* use Alternate sendmail/submit.cf */
828                         cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF
829                                                   : SM_GET_SENDMAIL_CF;
830                         break;
831
832                   case 'B':     /* body type */
833                         CHECK_AGAINST_OPMODE(j);
834                         BlankEnvelope.e_bodytype = newstr(optarg);
835                         break;
836
837                   case 'C':     /* select configuration file (already done) */
838                         if (RealUid != 0)
839                                 warn_C_flag = true;
840                         conffile = newstr(optarg);
841                         dp = drop_privileges(true);
842                         setstat(dp);
843                         safecf = false;
844                         break;
845
846                   case 'd':     /* debugging */
847                         /* already done */
848                         break;
849
850                   case 'f':     /* from address */
851                   case 'r':     /* obsolete -f flag */
852                         CHECK_AGAINST_OPMODE(j);
853                         if (from != NULL)
854                         {
855                                 usrerr("More than one \"from\" person");
856                                 ExitStat = EX_USAGE;
857                                 break;
858                         }
859                         if (optarg[0] == '\0')
860                                 from = newstr("<>");
861                         else
862                                 from = newstr(denlstring(optarg, true, true));
863                         if (strcmp(RealUserName, from) != 0)
864                                 warn_f_flag = j;
865                         break;
866
867                   case 'F':     /* set full name */
868                         CHECK_AGAINST_OPMODE(j);
869                         FullName = newstr(optarg);
870                         break;
871
872                   case 'G':     /* relay (gateway) submission */
873                         /* already set */
874                         CHECK_AGAINST_OPMODE(j);
875                         break;
876
877                   case 'h':     /* hop count */
878                         CHECK_AGAINST_OPMODE(j);
879                         BlankEnvelope.e_hopcount = (short) strtol(optarg, &ep,
880                                                                   10);
881                         (void) sm_snprintf(buf, sizeof buf, "%d",
882                                            BlankEnvelope.e_hopcount);
883                         macdefine(&BlankEnvelope.e_macro, A_TEMP, 'c', buf);
884
885                         if (*ep)
886                         {
887                                 usrerr("Bad hop count (%s)", optarg);
888                                 ExitStat = EX_USAGE;
889                         }
890                         break;
891
892                   case 'L':     /* program label */
893                         /* already set */
894                         break;
895
896                   case 'n':     /* don't alias */
897                         CHECK_AGAINST_OPMODE(j);
898                         NoAlias = true;
899                         break;
900
901                   case 'N':     /* delivery status notifications */
902                         CHECK_AGAINST_OPMODE(j);
903                         DefaultNotify |= QHASNOTIFY;
904                         macdefine(&BlankEnvelope.e_macro, A_TEMP,
905                                 macid("{dsn_notify}"), optarg);
906                         if (sm_strcasecmp(optarg, "never") == 0)
907                                 break;
908                         for (p = optarg; p != NULL; optarg = p)
909                         {
910                                 p = strchr(p, ',');
911                                 if (p != NULL)
912                                         *p++ = '\0';
913                                 if (sm_strcasecmp(optarg, "success") == 0)
914                                         DefaultNotify |= QPINGONSUCCESS;
915                                 else if (sm_strcasecmp(optarg, "failure") == 0)
916                                         DefaultNotify |= QPINGONFAILURE;
917                                 else if (sm_strcasecmp(optarg, "delay") == 0)
918                                         DefaultNotify |= QPINGONDELAY;
919                                 else
920                                 {
921                                         usrerr("Invalid -N argument");
922                                         ExitStat = EX_USAGE;
923                                 }
924                         }
925                         break;
926
927                   case 'o':     /* set option */
928                         setoption(*optarg, optarg + 1, false, true,
929                                   &BlankEnvelope);
930                         break;
931
932                   case 'O':     /* set option (long form) */
933                         setoption(' ', optarg, false, true, &BlankEnvelope);
934                         break;
935
936                   case 'p':     /* set protocol */
937                         CHECK_AGAINST_OPMODE(j);
938                         p = strchr(optarg, ':');
939                         if (p != NULL)
940                         {
941                                 *p++ = '\0';
942                                 if (*p != '\0')
943                                 {
944                                         i = strlen(p) + 1;
945                                         ep = sm_malloc_x(i);
946                                         cleanstrcpy(ep, p, i);
947                                         macdefine(&BlankEnvelope.e_macro,
948                                                   A_HEAP, 's', ep);
949                                 }
950                         }
951                         if (*optarg != '\0')
952                         {
953                                 i = strlen(optarg) + 1;
954                                 ep = sm_malloc_x(i);
955                                 cleanstrcpy(ep, optarg, i);
956                                 macdefine(&BlankEnvelope.e_macro, A_HEAP,
957                                           'r', ep);
958                         }
959                         break;
960
961 #if _FFR_QUARANTINE
962                   case 'Q':     /* change quarantining on queued items */
963                         /* sanity check */
964                         if (OpMode != MD_DELIVER &&
965                             OpMode != MD_QUEUERUN)
966                         {
967                                 usrerr("Can not use -Q with -b%c", OpMode);
968                                 ExitStat = EX_USAGE;
969                                 break;
970                         }
971
972                         if (OpMode == MD_DELIVER)
973                                 set_op_mode(MD_QUEUERUN);
974
975                         FullName = NULL;
976
977                         quarantining = newstr(optarg);
978                         break;
979 #endif /* _FFR_QUARANTINE */
980
981                   case 'q':     /* run queue files at intervals */
982                         /* sanity check */
983                         if (OpMode != MD_DELIVER &&
984                             OpMode != MD_DAEMON &&
985                             OpMode != MD_FGDAEMON &&
986                             OpMode != MD_PRINT &&
987                             OpMode != MD_PRINTNQE &&
988                             OpMode != MD_QUEUERUN)
989                         {
990                                 usrerr("Can not use -q with -b%c", OpMode);
991                                 ExitStat = EX_USAGE;
992                                 break;
993                         }
994
995                         /* don't override -bd, -bD or -bp */
996                         if (OpMode == MD_DELIVER)
997                                 set_op_mode(MD_QUEUERUN);
998
999                         FullName = NULL;
1000                         negate = optarg[0] == '!';
1001                         if (negate)
1002                         {
1003                                 /* negate meaning of pattern match */
1004                                 optarg++; /* skip '!' for next switch */
1005                         }
1006
1007                         switch (optarg[0])
1008                         {
1009                           case 'G': /* Limit by queue group name */
1010                                 if (negate)
1011                                 {
1012                                         usrerr("Can not use -q!G");
1013                                         ExitStat = EX_USAGE;
1014                                         break;
1015                                 }
1016                                 if (queuegroup != NULL)
1017                                 {
1018                                         usrerr("Can not use multiple -qG options");
1019                                         ExitStat = EX_USAGE;
1020                                         break;
1021                                 }
1022                                 queuegroup = newstr(&optarg[1]);
1023                                 break;
1024
1025                           case 'I': /* Limit by ID */
1026                                 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1027                                 new->queue_match = newstr(&optarg[1]);
1028                                 new->queue_negate = negate;
1029                                 new->queue_next = QueueLimitId;
1030                                 QueueLimitId = new;
1031                                 break;
1032
1033                           case 'R': /* Limit by recipient */
1034                                 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1035                                 new->queue_match = newstr(&optarg[1]);
1036                                 new->queue_negate = negate;
1037                                 new->queue_next = QueueLimitRecipient;
1038                                 QueueLimitRecipient = new;
1039                                 break;
1040
1041                           case 'S': /* Limit by sender */
1042                                 new = (QUEUE_CHAR *) xalloc(sizeof *new);
1043                                 new->queue_match = newstr(&optarg[1]);
1044                                 new->queue_negate = negate;
1045                                 new->queue_next = QueueLimitSender;
1046                                 QueueLimitSender = new;
1047                                 break;
1048
1049                           case 'f': /* foreground queue run */
1050                                 foregroundqueue  = true;
1051                                 break;
1052
1053 #if _FFR_QUARANTINE
1054                           case 'Q': /* Limit by quarantine message */
1055                                 if (optarg[1] != '\0')
1056                                 {
1057                                         new = (QUEUE_CHAR *) xalloc(sizeof *new);
1058                                         new->queue_match = newstr(&optarg[1]);
1059                                         new->queue_negate = negate;
1060                                         new->queue_next = QueueLimitQuarantine;
1061                                         QueueLimitQuarantine = new;
1062                                 }
1063                                 QueueMode = QM_QUARANTINE;
1064                                 break;
1065
1066                           case 'L': /* act on lost items */
1067                                 QueueMode = QM_LOST;
1068                                 break;
1069 #endif /* _FFR_QUARANTINE */
1070
1071                           case 'p': /* Persistent queue */
1072                                 queuepersistent = true;
1073                                 if (QueueIntvl == 0)
1074                                         QueueIntvl = 1;
1075                                 if (optarg[1] == '\0')
1076                                         break;
1077                                 ++optarg;
1078                                 /* FALLTHROUGH */
1079
1080                           default:
1081                                 i = Errors;
1082                                 QueueIntvl = convtime(optarg, 'm');
1083                                 if (QueueIntvl < 0)
1084                                 {
1085                                         usrerr("Invalid -q value");
1086                                         ExitStat = EX_USAGE;
1087                                 }
1088
1089                                 /* check for bad conversion */
1090                                 if (i < Errors)
1091                                         ExitStat = EX_USAGE;
1092                                 break;
1093                         }
1094                         break;
1095
1096                   case 'R':     /* DSN RET: what to return */
1097                         CHECK_AGAINST_OPMODE(j);
1098                         if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags))
1099                         {
1100                                 usrerr("Duplicate -R flag");
1101                                 ExitStat = EX_USAGE;
1102                                 break;
1103                         }
1104                         BlankEnvelope.e_flags |= EF_RET_PARAM;
1105                         if (sm_strcasecmp(optarg, "hdrs") == 0)
1106                                 BlankEnvelope.e_flags |= EF_NO_BODY_RETN;
1107                         else if (sm_strcasecmp(optarg, "full") != 0)
1108                         {
1109                                 usrerr("Invalid -R value");
1110                                 ExitStat = EX_USAGE;
1111                         }
1112                         macdefine(&BlankEnvelope.e_macro, A_TEMP,
1113                                   macid("{dsn_ret}"), optarg);
1114                         break;
1115
1116                   case 't':     /* read recipients from message */
1117                         CHECK_AGAINST_OPMODE(j);
1118                         GrabTo = true;
1119                         break;
1120
1121                   case 'V':     /* DSN ENVID: set "original" envelope id */
1122                         CHECK_AGAINST_OPMODE(j);
1123                         if (!xtextok(optarg))
1124                         {
1125                                 usrerr("Invalid syntax in -V flag");
1126                                 ExitStat = EX_USAGE;
1127                         }
1128                         else
1129                         {
1130                                 BlankEnvelope.e_envid = newstr(optarg);
1131                                 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1132                                           macid("{dsn_envid}"), optarg);
1133                         }
1134                         break;
1135
1136                   case 'X':     /* traffic log file */
1137                         dp = drop_privileges(true);
1138                         setstat(dp);
1139                         if (stat(optarg, &traf_st) == 0 &&
1140                             S_ISFIFO(traf_st.st_mode))
1141                                 TrafficLogFile = sm_io_open(SmFtStdio,
1142                                                             SM_TIME_DEFAULT,
1143                                                             optarg,
1144                                                             SM_IO_WRONLY, NULL);
1145                         else
1146                                 TrafficLogFile = sm_io_open(SmFtStdio,
1147                                                             SM_TIME_DEFAULT,
1148                                                             optarg,
1149                                                             SM_IO_APPEND, NULL);
1150                         if (TrafficLogFile == NULL)
1151                         {
1152                                 syserr("cannot open %s", optarg);
1153                                 ExitStat = EX_CANTCREAT;
1154                                 break;
1155                         }
1156                         (void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT,
1157                                              NULL, SM_IO_LBF, 0);
1158                         break;
1159
1160                         /* compatibility flags */
1161                   case 'c':     /* connect to non-local mailers */
1162                   case 'i':     /* don't let dot stop me */
1163                   case 'm':     /* send to me too */
1164                   case 'T':     /* set timeout interval */
1165                   case 'v':     /* give blow-by-blow description */
1166                         setoption(j, "T", false, true, &BlankEnvelope);
1167                         break;
1168
1169                   case 'e':     /* error message disposition */
1170                   case 'M':     /* define macro */
1171                         setoption(j, optarg, false, true, &BlankEnvelope);
1172                         break;
1173
1174                   case 's':     /* save From lines in headers */
1175                         setoption('f', "T", false, true, &BlankEnvelope);
1176                         break;
1177
1178 #ifdef DBM
1179                   case 'I':     /* initialize alias DBM file */
1180                         set_op_mode(MD_INITALIAS);
1181                         break;
1182 #endif /* DBM */
1183
1184 #if defined(__osf__) || defined(_AIX3)
1185                   case 'x':     /* random flag that OSF/1 & AIX mailx passes */
1186                         break;
1187 #endif /* defined(__osf__) || defined(_AIX3) */
1188 #if defined(sony_news)
1189                   case 'E':
1190                   case 'J':     /* ignore flags for Japanese code conversion
1191                                    implemented on Sony NEWS */
1192                         break;
1193 #endif /* defined(sony_news) */
1194
1195                   default:
1196                         finis(true, true, EX_USAGE);
1197                         /* NOTREACHED */
1198                         break;
1199                 }
1200         }
1201
1202         /* if we've had errors so far, exit now */
1203         if ((ExitStat != EX_OK && OpMode != MD_TEST) ||
1204             ExitStat == EX_OSERR)
1205         {
1206                 finis(false, true, ExitStat);
1207                 /* NOTREACHED */
1208         }
1209
1210         if (bitset(SUBMIT_MTA, SubmitMode))
1211         {
1212                 /* If set daemon_flags on command line, don't reset it */
1213                 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1214                         macdefine(&BlankEnvelope.e_macro, A_PERM,
1215                                   macid("{daemon_flags}"), "CC f");
1216         }
1217         else if (OpMode == MD_DELIVER || OpMode == MD_SMTP)
1218         {
1219                 SubmitMode = SUBMIT_MSA;
1220
1221                 /* If set daemon_flags on command line, don't reset it */
1222                 if (macvalue(macid("{daemon_flags}"), &BlankEnvelope) == NULL)
1223                         macdefine(&BlankEnvelope.e_macro, A_PERM,
1224                                   macid("{daemon_flags}"), "c u");
1225         }
1226
1227         /*
1228         **  Do basic initialization.
1229         **      Read system control file.
1230         **      Extract special fields for local use.
1231         */
1232
1233 #if XDEBUG
1234         checkfd012("before readcf");
1235 #endif /* XDEBUG */
1236         vendor_pre_defaults(&BlankEnvelope);
1237
1238         readcf(getcfname(OpMode, SubmitMode, cftype, conffile),
1239                          safecf, &BlankEnvelope);
1240 #if !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_)
1241         ConfigFileRead = true;
1242 #endif /* !defined(_USE_SUN_NSSWITCH_) && !defined(_USE_DEC_SVC_CONF_) */
1243         vendor_post_defaults(&BlankEnvelope);
1244
1245         /* now we can complain about missing fds */
1246         if (MissingFds != 0 && LogLevel > 8)
1247         {
1248                 char mbuf[MAXLINE];
1249
1250                 mbuf[0] = '\0';
1251                 if (bitset(1 << STDIN_FILENO, MissingFds))
1252                         (void) sm_strlcat(mbuf, ", stdin", sizeof mbuf);
1253                 if (bitset(1 << STDOUT_FILENO, MissingFds))
1254                         (void) sm_strlcat(mbuf, ", stdout", sizeof mbuf);
1255                 if (bitset(1 << STDERR_FILENO, MissingFds))
1256                         (void) sm_strlcat(mbuf, ", stderr", sizeof mbuf);
1257
1258                 /* Notice: fill_errno is from high above: fill_fd() */
1259                 sm_syslog(LOG_WARNING, NOQID,
1260                           "File descriptors missing on startup: %s; %s",
1261                           &mbuf[2], sm_errstring(fill_errno));
1262         }
1263
1264         /* Remove the ability for a normal user to send signals */
1265         if (RealUid != 0 && RealUid != geteuid())
1266         {
1267                 uid_t new_uid = geteuid();
1268
1269 #if HASSETREUID
1270                 /*
1271                 **  Since we can differentiate between uid and euid,
1272                 **  make the uid a different user so the real user
1273                 **  can't send signals.  However, it doesn't need to be
1274                 **  root (euid has root).
1275                 */
1276
1277                 if (new_uid == 0)
1278                         new_uid = DefUid;
1279                 if (tTd(47, 5))
1280                         sm_dprintf("Changing real uid to %d\n", (int) new_uid);
1281                 if (setreuid(new_uid, geteuid()) < 0)
1282                 {
1283                         syserr("main: setreuid(%d, %d) failed",
1284                                (int) new_uid, (int) geteuid());
1285                         finis(false, true, EX_OSERR);
1286                         /* NOTREACHED */
1287                 }
1288                 if (tTd(47, 10))
1289                         sm_dprintf("Now running as e/ruid %d:%d\n",
1290                                    (int) geteuid(), (int) getuid());
1291 #else /* HASSETREUID */
1292                 /*
1293                 **  Have to change both effective and real so need to
1294                 **  change them both to effective to keep privs.
1295                 */
1296
1297                 if (tTd(47, 5))
1298                         sm_dprintf("Changing uid to %d\n", (int) new_uid);
1299                 if (setuid(new_uid) < 0)
1300                 {
1301                         syserr("main: setuid(%d) failed", (int) new_uid);
1302                         finis(false, true, EX_OSERR);
1303                         /* NOTREACHED */
1304                 }
1305                 if (tTd(47, 10))
1306                         sm_dprintf("Now running as e/ruid %d:%d\n",
1307                                    (int) geteuid(), (int) getuid());
1308 #endif /* HASSETREUID */
1309         }
1310
1311 #if NAMED_BIND
1312         if (FallBackMX != NULL)
1313                 (void) getfallbackmxrr(FallBackMX);
1314 #endif /* NAMED_BIND */
1315
1316         if (SuperSafe == SAFE_INTERACTIVE && CurEnv->e_sendmode != SM_DELIVER)
1317         {
1318                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1319                                      "WARNING: SuperSafe=interactive should only be used with\n         DeliveryMode=interactive\n");
1320         }
1321
1322         if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON))
1323         {
1324                 usrerr("Mail submission program cannot be used as daemon");
1325                 finis(false, true, EX_USAGE);
1326         }
1327
1328         if (OpMode == MD_DELIVER || OpMode == MD_SMTP ||
1329             OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP ||
1330             OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)
1331                 makeworkgroups();
1332
1333         /* set up the basic signal handlers */
1334         if (sm_signal(SIGINT, SIG_IGN) != SIG_IGN)
1335                 (void) sm_signal(SIGINT, intsig);
1336         (void) sm_signal(SIGTERM, intsig);
1337
1338         /* Enforce use of local time (null string overrides this) */
1339         if (TimeZoneSpec == NULL)
1340                 unsetenv("TZ");
1341         else if (TimeZoneSpec[0] != '\0')
1342                 setuserenv("TZ", TimeZoneSpec);
1343         else
1344                 setuserenv("TZ", NULL);
1345         tzset();
1346
1347         /* initialize mailbox database */
1348         i = sm_mbdb_initialize(Mbdb);
1349         if (i != EX_OK)
1350         {
1351                 usrerr("Can't initialize mailbox database \"%s\": %s",
1352                        Mbdb, sm_strexit(i));
1353                 ExitStat = i;
1354         }
1355
1356         /* avoid denial-of-service attacks */
1357         resetlimits();
1358
1359         if (OpMode == MD_TEST)
1360         {
1361                 /* can't be done after readcf if RunAs* is used */
1362                 dp = drop_privileges(true);
1363                 if (dp != EX_OK)
1364                 {
1365                         finis(false, true, dp);
1366                         /* NOTREACHED */
1367                 }
1368         }
1369         else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON)
1370         {
1371                 /* drop privileges -- daemon mode done after socket/bind */
1372                 dp = drop_privileges(false);
1373                 setstat(dp);
1374                 if (dp == EX_OK && UseMSP && (geteuid() == 0 || getuid() == 0))
1375                 {
1376                         usrerr("Mail submission program must have RunAsUser set to non root user");
1377                         finis(false, true, EX_CONFIG);
1378                         /* NOTREACHED */
1379                 }
1380         }
1381
1382 #if NAMED_BIND
1383         _res.retry = TimeOuts.res_retry[RES_TO_DEFAULT];
1384         _res.retrans = TimeOuts.res_retrans[RES_TO_DEFAULT];
1385 #endif /* NAMED_BIND */
1386
1387         /*
1388         **  Find our real host name for future logging.
1389         */
1390
1391         authinfo = getauthinfo(STDIN_FILENO, &forged);
1392         macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
1393
1394         /* suppress error printing if errors mailed back or whatever */
1395         if (BlankEnvelope.e_errormode != EM_PRINT)
1396                 HoldErrs = true;
1397
1398         /* set up the $=m class now, after .cf has a chance to redefine $m */
1399         expand("\201m", jbuf, sizeof jbuf, &BlankEnvelope);
1400         if (jbuf[0] != '\0')
1401                 setclass('m', jbuf);
1402
1403         /* probe interfaces and locate any additional names */
1404         if (DontProbeInterfaces != DPI_PROBENONE)
1405                 load_if_names();
1406
1407         if (tTd(0, 10))
1408         {
1409                 char pidpath[MAXPATHLEN];
1410
1411                 /* Now we know which .cf file we use */
1412                 sm_dprintf("     Conf file:\t%s (selected)\n",
1413                            getcfname(OpMode, SubmitMode, cftype, conffile));
1414                 expand(PidFile, pidpath, sizeof pidpath, &BlankEnvelope);
1415                 sm_dprintf("      Pid file:\t%s (selected)\n", pidpath);
1416         }
1417
1418         if (tTd(0, 1))
1419         {
1420                 sm_dprintf("\n============ SYSTEM IDENTITY (after readcf) ============");
1421                 sm_dprintf("\n      (short domain name) $w = ");
1422                 xputs(macvalue('w', &BlankEnvelope));
1423                 sm_dprintf("\n  (canonical domain name) $j = ");
1424                 xputs(macvalue('j', &BlankEnvelope));
1425                 sm_dprintf("\n         (subdomain name) $m = ");
1426                 xputs(macvalue('m', &BlankEnvelope));
1427                 sm_dprintf("\n              (node name) $k = ");
1428                 xputs(macvalue('k', &BlankEnvelope));
1429                 sm_dprintf("\n========================================================\n\n");
1430         }
1431
1432         /*
1433         **  Do more command line checking -- these are things that
1434         **  have to modify the results of reading the config file.
1435         */
1436
1437         /* process authorization warnings from command line */
1438         if (warn_C_flag)
1439                 auth_warning(&BlankEnvelope, "Processed by %s with -C %s",
1440                              RealUserName, conffile);
1441         if (Warn_Q_option && !wordinclass(RealUserName, 't'))
1442                 auth_warning(&BlankEnvelope, "Processed from queue %s",
1443                              QueueDir);
1444         if (sysloglabel != NULL && !wordinclass(RealUserName, 't') &&
1445             RealUid != 0 && RealUid != TrustedUid && LogLevel > 1)
1446                 sm_syslog(LOG_WARNING, NOQID, "user %d changed syslog label",
1447                           (int) RealUid);
1448
1449         /* check body type for legality */
1450         i = check_bodytype(BlankEnvelope.e_bodytype);
1451         if (i == BODYTYPE_ILLEGAL)
1452         {
1453                 usrerr("Illegal body type %s", BlankEnvelope.e_bodytype);
1454                 BlankEnvelope.e_bodytype = NULL;
1455         }
1456         else if (i != BODYTYPE_NONE)
1457                 SevenBitInput = (i == BODYTYPE_7BIT);
1458
1459         /* tweak default DSN notifications */
1460         if (DefaultNotify == 0)
1461                 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
1462
1463         /* be sure we don't pick up bogus HOSTALIASES environment variable */
1464         if (OpMode == MD_QUEUERUN && RealUid != 0)
1465                 (void) unsetenv("HOSTALIASES");
1466
1467         /* check for sane configuration level */
1468         if (ConfigLevel > MAXCONFIGLEVEL)
1469         {
1470                 syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1471                        ConfigLevel, Version, MAXCONFIGLEVEL);
1472         }
1473
1474         /* need MCI cache to have persistence */
1475         if (HostStatDir != NULL && MaxMciCache == 0)
1476         {
1477                 HostStatDir = NULL;
1478                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1479                                      "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1480         }
1481
1482         /* need HostStatusDir in order to have SingleThreadDelivery */
1483         if (SingleThreadDelivery && HostStatDir == NULL)
1484         {
1485                 SingleThreadDelivery = false;
1486                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1487                                      "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1488         }
1489
1490         /* check for permissions */
1491         if (RealUid != 0 &&
1492             RealUid != TrustedUid)
1493         {
1494                 char *action = NULL;
1495
1496                 switch (OpMode)
1497                 {
1498                   case MD_QUEUERUN:
1499 #if _FFR_QUARANTINE
1500                         if (quarantining != NULL)
1501                                 action = "quarantine jobs";
1502                         else
1503 #endif /* _FFR_QUARANTINE */
1504                         /* Normal users can do a single queue run */
1505                         if (QueueIntvl == 0)
1506                                 break;
1507
1508                         /* but not persistent queue runners */
1509                         if (action == NULL)
1510                                 action = "start a queue runner daemon";
1511                         /* FALLTHROUGH */
1512
1513                   case MD_PURGESTAT:
1514                         if (action == NULL)
1515                                 action = "purge host status";
1516                         /* FALLTHROUGH */
1517
1518                   case MD_DAEMON:
1519                   case MD_FGDAEMON:
1520                         if (action == NULL)
1521                                 action = "run daemon";
1522
1523                         if (tTd(65, 1))
1524                                 sm_dprintf("Deny user %d attempt to %s\n",
1525                                            (int) RealUid, action);
1526
1527                         if (LogLevel > 1)
1528                                 sm_syslog(LOG_ALERT, NOQID,
1529                                           "user %d attempted to %s",
1530                                           (int) RealUid, action);
1531                         HoldErrs = false;
1532                         usrerr("Permission denied (real uid not trusted)");
1533                         finis(false, true, EX_USAGE);
1534                         /* NOTREACHED */
1535                         break;
1536
1537                   case MD_VERIFY:
1538                         if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags))
1539                         {
1540                                 /*
1541                                 **  If -bv and RestrictExpand,
1542                                 **  drop privs to prevent normal
1543                                 **  users from reading private
1544                                 **  aliases/forwards/:include:s
1545                                 */
1546
1547                                 if (tTd(65, 1))
1548                                         sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1549                                                    (int) RealUid);
1550
1551                                 dp = drop_privileges(true);
1552
1553                                 /* Fake address safety */
1554                                 if (tTd(65, 1))
1555                                         sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1556                                 setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail);
1557
1558                                 if (dp != EX_OK)
1559                                 {
1560                                         if (tTd(65, 1))
1561                                                 sm_dprintf("Failed to drop privs for user %d attempt to expand, exiting\n",
1562                                                            (int) RealUid);
1563                                         CurEnv->e_id = NULL;
1564                                         finis(true, true, dp);
1565                                         /* NOTREACHED */
1566                                 }
1567                         }
1568                         break;
1569
1570                   case MD_TEST:
1571                   case MD_PRINT:
1572                   case MD_PRINTNQE:
1573                   case MD_FREEZE:
1574                   case MD_HOSTSTAT:
1575                         /* Nothing special to check */
1576                         break;
1577
1578                   case MD_INITALIAS:
1579                         if (!wordinclass(RealUserName, 't'))
1580                         {
1581                                 if (tTd(65, 1))
1582                                         sm_dprintf("Deny user %d attempt to rebuild the alias map\n",
1583                                                    (int) RealUid);
1584                                 if (LogLevel > 1)
1585                                         sm_syslog(LOG_ALERT, NOQID,
1586                                                   "user %d attempted to rebuild the alias map",
1587                                                   (int) RealUid);
1588                                 HoldErrs = false;
1589                                 usrerr("Permission denied (real uid not trusted)");
1590                                 finis(false, true, EX_USAGE);
1591                                 /* NOTREACHED */
1592                         }
1593                         if (UseMSP)
1594                         {
1595                                 HoldErrs = false;
1596                                 usrerr("User %d cannot rebuild aliases in mail submission program",
1597                                        (int) RealUid);
1598                                 finis(false, true, EX_USAGE);
1599                                 /* NOTREACHED */
1600                         }
1601                         /* FALLTHROUGH */
1602
1603                   default:
1604                         if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) &&
1605                             Verbose != 0)
1606                         {
1607                                 /*
1608                                 **  If -v and RestrictExpand, reset
1609                                 **  Verbose to prevent normal users
1610                                 **  from seeing the expansion of
1611                                 **  aliases/forwards/:include:s
1612                                 */
1613
1614                                 if (tTd(65, 1))
1615                                         sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1616                                                    (int) RealUid);
1617                                 Verbose = 0;
1618                         }
1619                         break;
1620                 }
1621         }
1622
1623         if (MeToo)
1624                 BlankEnvelope.e_flags |= EF_METOO;
1625
1626         switch (OpMode)
1627         {
1628           case MD_TEST:
1629                 /* don't have persistent host status in test mode */
1630                 HostStatDir = NULL;
1631                 if (Verbose == 0)
1632                         Verbose = 2;
1633                 BlankEnvelope.e_errormode = EM_PRINT;
1634                 HoldErrs = false;
1635                 break;
1636
1637           case MD_VERIFY:
1638                 BlankEnvelope.e_errormode = EM_PRINT;
1639                 HoldErrs = false;
1640                 /* arrange to exit cleanly on hangup signal */
1641                 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1642                         (void) sm_signal(SIGHUP, intsig);
1643                 if (geteuid() != 0)
1644                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1645                                              "Notice: -bv may give misleading output for non-privileged user\n");
1646                 break;
1647
1648           case MD_FGDAEMON:
1649                 run_in_foreground = true;
1650                 set_op_mode(MD_DAEMON);
1651                 /* FALLTHROUGH */
1652
1653           case MD_DAEMON:
1654                 vendor_daemon_setup(&BlankEnvelope);
1655
1656                 /* remove things that don't make sense in daemon mode */
1657                 FullName = NULL;
1658                 GrabTo = false;
1659
1660                 /* arrange to restart on hangup signal */
1661                 if (SaveArgv[0] == NULL || SaveArgv[0][0] != '/')
1662                         sm_syslog(LOG_WARNING, NOQID,
1663                                   "daemon invoked without full pathname; kill -1 won't work");
1664                 break;
1665
1666           case MD_INITALIAS:
1667                 Verbose = 2;
1668                 BlankEnvelope.e_errormode = EM_PRINT;
1669                 HoldErrs = false;
1670                 /* FALLTHROUGH */
1671
1672           default:
1673                 /* arrange to exit cleanly on hangup signal */
1674                 if (sm_signal(SIGHUP, SIG_IGN) == (sigfunc_t) SIG_DFL)
1675                         (void) sm_signal(SIGHUP, intsig);
1676                 break;
1677         }
1678
1679         /* special considerations for FullName */
1680         if (FullName != NULL)
1681         {
1682                 char *full = NULL;
1683
1684                 /* full names can't have newlines */
1685                 if (strchr(FullName, '\n') != NULL)
1686                 {
1687                         full = newstr(denlstring(FullName, true, true));
1688                         FullName = full;
1689                 }
1690
1691                 /* check for characters that may have to be quoted */
1692                 if (!rfc822_string(FullName))
1693                 {
1694                         /*
1695                         **  Quote a full name with special characters
1696                         **  as a comment so crackaddr() doesn't destroy
1697                         **  the name portion of the address.
1698                         */
1699
1700                         FullName = addquotes(FullName, NULL);
1701                         if (full != NULL)
1702                                 sm_free(full);  /* XXX */
1703                 }
1704         }
1705
1706         /* do heuristic mode adjustment */
1707         if (Verbose)
1708         {
1709                 /* turn off noconnect option */
1710                 setoption('c', "F", true, false, &BlankEnvelope);
1711
1712                 /* turn on interactive delivery */
1713                 setoption('d', "", true, false, &BlankEnvelope);
1714         }
1715
1716 #ifdef VENDOR_CODE
1717         /* check for vendor mismatch */
1718         if (VendorCode != VENDOR_CODE)
1719         {
1720                 message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1721                         getvendor(VENDOR_CODE), getvendor(VendorCode));
1722         }
1723 #endif /* VENDOR_CODE */
1724
1725         /* check for out of date configuration level */
1726         if (ConfigLevel < MAXCONFIGLEVEL)
1727         {
1728                 message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1729                         Version, MAXCONFIGLEVEL, ConfigLevel);
1730         }
1731
1732         if (ConfigLevel < 3)
1733                 UseErrorsTo = true;
1734
1735         /* set options that were previous macros */
1736         if (SmtpGreeting == NULL)
1737         {
1738                 if (ConfigLevel < 7 &&
1739                     (p = macvalue('e', &BlankEnvelope)) != NULL)
1740                         SmtpGreeting = newstr(p);
1741                 else
1742                         SmtpGreeting = "\201j Sendmail \201v ready at \201b";
1743         }
1744         if (UnixFromLine == NULL)
1745         {
1746                 if (ConfigLevel < 7 &&
1747                     (p = macvalue('l', &BlankEnvelope)) != NULL)
1748                         UnixFromLine = newstr(p);
1749                 else
1750                         UnixFromLine = "From \201g  \201d";
1751         }
1752         SmtpError[0] = '\0';
1753
1754         /* our name for SMTP codes */
1755         expand("\201j", jbuf, sizeof jbuf, &BlankEnvelope);
1756         if (jbuf[0] == '\0')
1757                 PSTRSET(MyHostName, "localhost");
1758         else
1759                 PSTRSET(MyHostName, jbuf);
1760         if (strchr(MyHostName, '.') == NULL)
1761                 message("WARNING: local host name (%s) is not qualified; fix $j in config file",
1762                         MyHostName);
1763
1764         /* make certain that this name is part of the $=w class */
1765         setclass('w', MyHostName);
1766
1767         /* fill in the structure of the *default* queue */
1768         st = stab("mqueue", ST_QUEUE, ST_FIND);
1769         if (st == NULL)
1770                 syserr("No default queue (mqueue) defined");
1771         else
1772                 set_def_queueval(st->s_quegrp, true);
1773
1774         /* the indices of built-in mailers */
1775         st = stab("local", ST_MAILER, ST_FIND);
1776         if (st != NULL)
1777                 LocalMailer = st->s_mailer;
1778         else if (OpMode != MD_TEST || !warn_C_flag)
1779                 syserr("No local mailer defined");
1780
1781         st = stab("prog", ST_MAILER, ST_FIND);
1782         if (st == NULL)
1783                 syserr("No prog mailer defined");
1784         else
1785         {
1786                 ProgMailer = st->s_mailer;
1787                 clrbitn(M_MUSER, ProgMailer->m_flags);
1788         }
1789
1790         st = stab("*file*", ST_MAILER, ST_FIND);
1791         if (st == NULL)
1792                 syserr("No *file* mailer defined");
1793         else
1794         {
1795                 FileMailer = st->s_mailer;
1796                 clrbitn(M_MUSER, FileMailer->m_flags);
1797         }
1798
1799         st = stab("*include*", ST_MAILER, ST_FIND);
1800         if (st == NULL)
1801                 syserr("No *include* mailer defined");
1802         else
1803                 InclMailer = st->s_mailer;
1804
1805         if (ConfigLevel < 6)
1806         {
1807                 /* heuristic tweaking of local mailer for back compat */
1808                 if (LocalMailer != NULL)
1809                 {
1810                         setbitn(M_ALIASABLE, LocalMailer->m_flags);
1811                         setbitn(M_HASPWENT, LocalMailer->m_flags);
1812                         setbitn(M_TRYRULESET5, LocalMailer->m_flags);
1813                         setbitn(M_CHECKINCLUDE, LocalMailer->m_flags);
1814                         setbitn(M_CHECKPROG, LocalMailer->m_flags);
1815                         setbitn(M_CHECKFILE, LocalMailer->m_flags);
1816                         setbitn(M_CHECKUDB, LocalMailer->m_flags);
1817                 }
1818                 if (ProgMailer != NULL)
1819                         setbitn(M_RUNASRCPT, ProgMailer->m_flags);
1820                 if (FileMailer != NULL)
1821                         setbitn(M_RUNASRCPT, FileMailer->m_flags);
1822         }
1823         if (ConfigLevel < 7)
1824         {
1825                 if (LocalMailer != NULL)
1826                         setbitn(M_VRFY250, LocalMailer->m_flags);
1827                 if (ProgMailer != NULL)
1828                         setbitn(M_VRFY250, ProgMailer->m_flags);
1829                 if (FileMailer != NULL)
1830                         setbitn(M_VRFY250, FileMailer->m_flags);
1831         }
1832
1833         /* MIME Content-Types that cannot be transfer encoded */
1834         setclass('n', "multipart/signed");
1835
1836         /* MIME message/xxx subtypes that can be treated as messages */
1837         setclass('s', "rfc822");
1838
1839         /* MIME Content-Transfer-Encodings that can be encoded */
1840         setclass('e', "7bit");
1841         setclass('e', "8bit");
1842         setclass('e', "binary");
1843
1844 #ifdef USE_B_CLASS
1845         /* MIME Content-Types that should be treated as binary */
1846         setclass('b', "image");
1847         setclass('b', "audio");
1848         setclass('b', "video");
1849         setclass('b', "application/octet-stream");
1850 #endif /* USE_B_CLASS */
1851
1852         /* MIME headers which have fields to check for overflow */
1853         setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1854         setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1855
1856         /* MIME headers to check for length overflow */
1857         setclass(macid("{checkMIMETextHeaders}"), "content-description");
1858
1859         /* MIME headers to check for overflow and rebalance */
1860         setclass(macid("{checkMIMEHeaders}"), "content-disposition");
1861         setclass(macid("{checkMIMEHeaders}"), "content-id");
1862         setclass(macid("{checkMIMEHeaders}"), "content-transfer-encoding");
1863         setclass(macid("{checkMIMEHeaders}"), "content-type");
1864         setclass(macid("{checkMIMEHeaders}"), "mime-version");
1865
1866         /* Macros to save in the queue file -- don't remove any */
1867         setclass(macid("{persistentMacros}"), "r");
1868         setclass(macid("{persistentMacros}"), "s");
1869         setclass(macid("{persistentMacros}"), "_");
1870         setclass(macid("{persistentMacros}"), "{if_addr}");
1871         setclass(macid("{persistentMacros}"), "{daemon_flags}");
1872
1873         /* operate in queue directory */
1874         if (QueueDir == NULL || *QueueDir == '\0')
1875         {
1876                 if (OpMode != MD_TEST)
1877                 {
1878                         syserr("QueueDirectory (Q) option must be set");
1879                         ExitStat = EX_CONFIG;
1880                 }
1881         }
1882         else
1883         {
1884                 if (OpMode != MD_TEST)
1885                         setup_queues(OpMode == MD_DAEMON);
1886         }
1887
1888         /* check host status directory for validity */
1889         if (HostStatDir != NULL && !path_is_dir(HostStatDir, false))
1890         {
1891                 /* cannot use this value */
1892                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1893                                      "Warning: Cannot use HostStatusDirectory = %s: %s\n",
1894                                      HostStatDir, sm_errstring(errno));
1895                 HostStatDir = NULL;
1896         }
1897
1898         if (OpMode == MD_QUEUERUN &&
1899             RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags))
1900         {
1901                 struct stat stbuf;
1902
1903                 /* check to see if we own the queue directory */
1904                 if (stat(".", &stbuf) < 0)
1905                         syserr("main: cannot stat %s", QueueDir);
1906                 if (stbuf.st_uid != RealUid)
1907                 {
1908                         /* nope, really a botch */
1909                         HoldErrs = false;
1910                         usrerr("You do not have permission to process the queue");
1911                         finis(false, true, EX_NOPERM);
1912                         /* NOTREACHED */
1913                 }
1914         }
1915
1916 #if MILTER
1917         /* sanity checks on milter filters */
1918         if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
1919         {
1920                 milter_config(InputFilterList, InputFilters, MAXFILTERS);
1921 # if _FFR_MILTER_PERDAEMON
1922                 setup_daemon_milters();
1923 # endif /* _FFR_MILTER_PERDAEMON */
1924         }
1925 #endif /* MILTER */
1926
1927         /* Convert queuegroup string to qgrp number */
1928         if (queuegroup != NULL)
1929         {
1930                 qgrp = name2qid(queuegroup);
1931                 if (qgrp == NOQGRP)
1932                 {
1933                         HoldErrs = false;
1934                         usrerr("Queue group %s unknown", queuegroup);
1935                         finis(false, true, ExitStat);
1936                         /* NOTREACHED */
1937                 }
1938         }
1939
1940         /* if we've had errors so far, exit now */
1941         if (ExitStat != EX_OK && OpMode != MD_TEST)
1942         {
1943                 finis(false, true, ExitStat);
1944                 /* NOTREACHED */
1945         }
1946
1947 #if SASL
1948         /* sendmail specific SASL initialization */
1949         sm_sasl_init();
1950 #endif /* SASL */
1951
1952 #if XDEBUG
1953         checkfd012("before main() initmaps");
1954 #endif /* XDEBUG */
1955
1956         /*
1957         **  Do operation-mode-dependent initialization.
1958         */
1959
1960         switch (OpMode)
1961         {
1962           case MD_PRINT:
1963                 /* print the queue */
1964                 HoldErrs = false;
1965                 dropenvelope(&BlankEnvelope, true, false);
1966                 (void) sm_signal(SIGPIPE, sigpipe);
1967                 if (qgrp != NOQGRP)
1968                 {
1969                         int j;
1970
1971                         /* Selecting a particular queue group to run */
1972                         for (j = 0; j < Queue[qgrp]->qg_numqueues; j++)
1973                         {
1974                                 if (StopRequest)
1975                                         stop_sendmail();
1976                                 (void) print_single_queue(qgrp, j);
1977                         }
1978                         finis(false, true, EX_OK);
1979                         /* NOTREACHED */
1980                 }
1981                 printqueue();
1982                 finis(false, true, EX_OK);
1983                 /* NOTREACHED */
1984                 break;
1985
1986           case MD_PRINTNQE:
1987                 /* print number of entries in queue */
1988                 dropenvelope(&BlankEnvelope, true, false);
1989                 (void) sm_signal(SIGPIPE, sigpipe);
1990                 printnqe(smioout, NULL);
1991                 finis(false, true, EX_OK);
1992                 /* NOTREACHED */
1993                 break;
1994
1995 #if _FFR_QUARANTINE
1996           case MD_QUEUERUN:
1997                 /* only handle quarantining here */
1998                 if (quarantining == NULL)
1999                         break;
2000
2001                 if (QueueMode != QM_QUARANTINE &&
2002                     QueueMode != QM_NORMAL)
2003                 {
2004                         HoldErrs = false;
2005                         usrerr("Can not use -Q with -q%c", QueueMode);
2006                         ExitStat = EX_USAGE;
2007                         finis(false, true, ExitStat);
2008                         /* NOTREACHED */
2009                 }
2010                 quarantine_queue(quarantining, qgrp);
2011                 finis(false, true, EX_OK);
2012                 break;
2013 #endif /* _FFR_QUARANTINE */
2014
2015           case MD_HOSTSTAT:
2016                 (void) sm_signal(SIGPIPE, sigpipe);
2017                 (void) mci_traverse_persistent(mci_print_persistent, NULL);
2018                 finis(false, true, EX_OK);
2019                 /* NOTREACHED */
2020                 break;
2021
2022           case MD_PURGESTAT:
2023                 (void) mci_traverse_persistent(mci_purge_persistent, NULL);
2024                 finis(false, true, EX_OK);
2025                 /* NOTREACHED */
2026                 break;
2027
2028           case MD_INITALIAS:
2029                 /* initialize maps */
2030                 initmaps();
2031                 finis(false, true, ExitStat);
2032                 /* NOTREACHED */
2033                 break;
2034
2035           case MD_SMTP:
2036           case MD_DAEMON:
2037                 /* reset DSN parameters */
2038                 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
2039                 macdefine(&BlankEnvelope.e_macro, A_PERM,
2040                           macid("{dsn_notify}"), NULL);
2041                 BlankEnvelope.e_envid = NULL;
2042                 macdefine(&BlankEnvelope.e_macro, A_PERM,
2043                           macid("{dsn_envid}"), NULL);
2044                 BlankEnvelope.e_flags &= ~(EF_RET_PARAM|EF_NO_BODY_RETN);
2045                 macdefine(&BlankEnvelope.e_macro, A_PERM,
2046                           macid("{dsn_ret}"), NULL);
2047
2048                 /* don't open maps for daemon -- done below in child */
2049                 break;
2050         }
2051
2052         if (tTd(0, 15))
2053         {
2054                 /* print configuration table (or at least part of it) */
2055                 if (tTd(0, 90))
2056                         printrules();
2057                 for (i = 0; i < MAXMAILERS; i++)
2058                 {
2059                         if (Mailer[i] != NULL)
2060                                 printmailer(Mailer[i]);
2061                 }
2062         }
2063
2064         /*
2065         **  Switch to the main envelope.
2066         */
2067
2068         CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope,
2069                              sm_rpool_new_x(NULL));
2070         MainEnvelope.e_flags = BlankEnvelope.e_flags;
2071
2072         /*
2073         **  If test mode, read addresses from stdin and process.
2074         */
2075
2076         if (OpMode == MD_TEST)
2077         {
2078                 if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL)))
2079                         Verbose = 2;
2080
2081                 if (Verbose)
2082                 {
2083                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2084                                      "ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
2085                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2086                                      "Enter <ruleset> <address>\n");
2087                 }
2088                 macdefine(&(MainEnvelope.e_macro), A_PERM,
2089                           macid("{addr_type}"), "e r");
2090                 for (;;)
2091                 {
2092                         SM_TRY
2093                         {
2094                                 (void) sm_signal(SIGINT, intindebug);
2095                                 (void) sm_releasesignal(SIGINT);
2096                                 if (Verbose == 2)
2097                                         (void) sm_io_fprintf(smioout,
2098                                                              SM_TIME_DEFAULT,
2099                                                              "> ");
2100                                 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
2101                                 if (sm_io_fgets(smioin, SM_TIME_DEFAULT, buf,
2102                                                 sizeof buf) == NULL)
2103                                         testmodeline("/quit", &MainEnvelope);
2104                                 p = strchr(buf, '\n');
2105                                 if (p != NULL)
2106                                         *p = '\0';
2107                                 if (Verbose < 2)
2108                                         (void) sm_io_fprintf(smioout,
2109                                                              SM_TIME_DEFAULT,
2110                                                              "> %s\n", buf);
2111                                 testmodeline(buf, &MainEnvelope);
2112                         }
2113                         SM_EXCEPT(exc, "[!F]*")
2114                         {
2115                                 /*
2116                                 **  8.10 just prints \n on interrupt.
2117                                 **  I'm printing the exception here in case
2118                                 **  sendmail is extended to raise additional
2119                                 **  exceptions in this context.
2120                                 */
2121
2122                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2123                                                      "\n");
2124                                 sm_exc_print(exc, smioout);
2125                         }
2126                         SM_END_TRY
2127                 }
2128         }
2129
2130 #if STARTTLS
2131         tls_ok = true;
2132         if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER)
2133         {
2134                 /* check whether STARTTLS is turned off for the client */
2135                 if (chkclientmodifiers(D_NOTLS))
2136                         tls_ok = false;
2137         }
2138         else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON ||
2139                  OpMode == MD_SMTP)
2140         {
2141                 /* check whether STARTTLS is turned off for the server */
2142                 if (chkdaemonmodifiers(D_NOTLS))
2143                         tls_ok = false;
2144         }
2145         else    /* other modes don't need STARTTLS */
2146                 tls_ok = false;
2147
2148         if (tls_ok)
2149         {
2150                 /* basic TLS initialization */
2151                 tls_ok = init_tls_library();
2152         }
2153
2154         if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER))
2155         {
2156                 /* disable TLS for client */
2157                 setclttls(false);
2158         }
2159 #endif /* STARTTLS */
2160
2161         /*
2162         **  If collecting stuff from the queue, go start doing that.
2163         */
2164
2165         if (OpMode == MD_QUEUERUN && QueueIntvl == 0)
2166         {
2167                 pid_t pid = -1;
2168
2169 #if STARTTLS
2170                 /* init TLS for client, ignore result for now */
2171                 (void) initclttls(tls_ok);
2172 #endif /* STARTTLS */
2173
2174                 /*
2175                 **  The parent process of the caller of runqueue() needs
2176                 **  to stay around for a possible SIGTERM. The SIGTERM will
2177                 **  tell this process that all of the queue runners children
2178                 **  need to be sent SIGTERM as well. At the same time, we
2179                 **  want to return control to the command line. So we do an
2180                 **  extra fork().
2181                 */
2182
2183                 if (Verbose || foregroundqueue || (pid = fork()) <= 0)
2184                 {
2185                         /*
2186                         **  If the fork() failed we should still try to do
2187                         **  the queue run. If it succeeded then the child
2188                         **  is going to start the run and wait for all
2189                         **  of the children to finish.
2190                         */
2191
2192                         if (pid == 0)
2193                         {
2194                                 /* Reset global flags */
2195                                 RestartRequest = NULL;
2196                                 ShutdownRequest = NULL;
2197                                 PendingSignal = 0;
2198
2199                                 /* disconnect from terminal */
2200                                 disconnect(2, CurEnv);
2201                         }
2202
2203                         CurrentPid = getpid();
2204                         if (qgrp != NOQGRP)
2205                         {
2206                                 int rwgflags = RWG_NONE;
2207
2208                                 /*
2209                                 **  To run a specific queue group mark it to
2210                                 **  be run, select the work group it's in and
2211                                 **  increment the work counter.
2212                                 */
2213
2214                                 for (i = 0; i < NumQueue && Queue[i] != NULL;
2215                                      i++)
2216                                         Queue[i]->qg_nextrun = (time_t) -1;
2217                                 Queue[qgrp]->qg_nextrun = 0;
2218                                 if (Verbose)
2219                                         rwgflags |= RWG_VERBOSE;
2220                                 if (queuepersistent)
2221                                         rwgflags |= RWG_PERSISTENT;
2222                                 rwgflags |= RWG_FORCE;
2223                                 (void) run_work_group(Queue[qgrp]->qg_wgrp,
2224                                                       rwgflags);
2225                         }
2226                         else
2227                                 (void) runqueue(false, Verbose,
2228                                                 queuepersistent, true);
2229
2230                         /* set the title to make it easier to find */
2231                         sm_setproctitle(true, CurEnv, "Queue control");
2232                         (void) sm_signal(SIGCHLD, SIG_DFL);
2233                         while (CurChildren > 0)
2234                         {
2235                                 int status;
2236                                 pid_t ret;
2237
2238                                 while ((ret = sm_wait(&status)) <= 0)
2239                                         continue;
2240
2241                                 /* Only drop when a child gives status */
2242                                 if (WIFSTOPPED(status))
2243                                         continue;
2244
2245                                 proc_list_drop(ret, status, NULL);
2246                         }
2247                 }
2248                 finis(true, true, ExitStat);
2249                 /* NOTREACHED */
2250         }
2251
2252 # if SASL
2253         if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2254         {
2255                 /* check whether AUTH is turned off for the server */
2256                 if (!chkdaemonmodifiers(D_NOAUTH) &&
2257                     (i = sasl_server_init(srvcallbacks, "Sendmail")) != SASL_OK)
2258                         syserr("!sasl_server_init failed! [%s]",
2259                                 sasl_errstring(i, NULL, NULL));
2260         }
2261 # endif /* SASL */
2262
2263         if (OpMode == MD_SMTP)
2264         {
2265                 proc_list_add(CurrentPid, "Sendmail SMTP Agent",
2266                               PROC_DAEMON, 0, -1);
2267
2268                 /* clean up background delivery children */
2269                 (void) sm_signal(SIGCHLD, reapchild);
2270         }
2271
2272         /*
2273         **  If a daemon, wait for a request.
2274         **      getrequests will always return in a child.
2275         **      If we should also be processing the queue, start
2276         **              doing it in background.
2277         **      We check for any errors that might have happened
2278         **              during startup.
2279         */
2280
2281         if (OpMode == MD_DAEMON || QueueIntvl > 0)
2282         {
2283                 char dtype[200];
2284
2285                 if (!run_in_foreground && !tTd(99, 100))
2286                 {
2287                         /* put us in background */
2288                         i = fork();
2289                         if (i < 0)
2290                                 syserr("daemon: cannot fork");
2291                         if (i != 0)
2292                         {
2293                                 finis(false, true, EX_OK);
2294                                 /* NOTREACHED */
2295                         }
2296
2297                         /*
2298                         **  Initialize exception stack and default exception
2299                         **  handler for child process.
2300                         */
2301
2302                         /* Reset global flags */
2303                         RestartRequest = NULL;
2304                         RestartWorkGroup = false;
2305                         ShutdownRequest = NULL;
2306                         PendingSignal = 0;
2307                         CurrentPid = getpid();
2308
2309                         sm_exc_newthread(fatal_error);
2310
2311                         /* disconnect from our controlling tty */
2312                         disconnect(2, &MainEnvelope);
2313                 }
2314
2315                 dtype[0] = '\0';
2316                 if (OpMode == MD_DAEMON)
2317                 {
2318                         (void) sm_strlcat(dtype, "+SMTP", sizeof dtype);
2319                         DaemonPid = CurrentPid;
2320                 }
2321                 if (QueueIntvl > 0)
2322                 {
2323                         (void) sm_strlcat2(dtype,
2324                                            queuepersistent
2325                                            ? "+persistent-queueing@"
2326                                            : "+queueing@",
2327                                            pintvl(QueueIntvl, true),
2328                                            sizeof dtype);
2329                 }
2330                 if (tTd(0, 1))
2331                         (void) sm_strlcat(dtype, "+debugging", sizeof dtype);
2332
2333                 sm_syslog(LOG_INFO, NOQID,
2334                           "starting daemon (%s): %s", Version, dtype + 1);
2335 #if XLA
2336                 xla_create_file();
2337 #endif /* XLA */
2338
2339                 /* save daemon type in a macro for possible PidFile use */
2340                 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2341                         macid("{daemon_info}"), dtype + 1);
2342
2343                 /* save queue interval in a macro for possible PidFile use */
2344                 macdefine(&MainEnvelope.e_macro, A_TEMP,
2345                         macid("{queue_interval}"), pintvl(QueueIntvl, true));
2346
2347                 /* workaround: can't seem to release the signal in the parent */
2348                 (void) sm_signal(SIGHUP, sighup);
2349                 (void) sm_releasesignal(SIGHUP);
2350                 (void) sm_signal(SIGTERM, sigterm);
2351
2352                 if (QueueIntvl > 0)
2353                 {
2354                         (void) runqueue(true, false, queuepersistent, true);
2355
2356                         /*
2357                         **  If queuepersistent but not in daemon mode then
2358                         **  we're going to do the queue runner monitoring here.
2359                         **  If in daemon mode then the monitoring will happen
2360                         **  elsewhere.
2361                         */
2362
2363                         if (OpMode != MD_DAEMON && queuepersistent)
2364                         {
2365                                 /* set the title to make it easier to find */
2366                                 sm_setproctitle(true, CurEnv, "Queue control");
2367                                 (void) sm_signal(SIGCHLD, SIG_DFL);
2368                                 while (CurChildren > 0)
2369                                 {
2370                                         int status;
2371                                         pid_t ret;
2372                                         int group;
2373
2374                                         CHECK_RESTART;
2375                                         while ((ret = sm_wait(&status)) <= 0)
2376                                                 continue;
2377
2378                                         if (WIFSTOPPED(status))
2379                                                 continue;
2380
2381                                         /* Probe only on a child status */
2382                                         proc_list_drop(ret, status, &group);
2383
2384                                         if (WIFSIGNALED(status))
2385                                         {
2386                                                 if (WCOREDUMP(status))
2387                                                 {
2388                                                         sm_syslog(LOG_ERR, NOQID,
2389                                                                   "persistent queue runner=%d core dumped, signal=%d",
2390                                                                   group, WTERMSIG(status));
2391
2392                                                         /* don't restart this */
2393                                                         mark_work_group_restart(
2394                                                                 group, -1);
2395                                                         continue;
2396                                                 }
2397
2398                                                 sm_syslog(LOG_ERR, NOQID,
2399                                                           "persistent queue runner=%d died, signal=%d",
2400                                                           group, WTERMSIG(status));
2401                                         }
2402
2403                                         /*
2404                                         **  When debugging active, don't
2405                                         **  restart the persistent queues.
2406                                         **  But do log this as info.
2407                                         */
2408
2409                                         if (sm_debug_active(&DebugNoPRestart,
2410                                                             1))
2411                                         {
2412                                                 sm_syslog(LOG_DEBUG, NOQID,
2413                                                           "persistent queue runner=%d, exited",
2414                                                           group);
2415                                                 mark_work_group_restart(group,
2416                                                                         -1);
2417                                         }
2418                                 }
2419                                 finis(true, true, ExitStat);
2420                                 /* NOTREACHED */
2421                         }
2422
2423                         if (OpMode != MD_DAEMON)
2424                         {
2425                                 char qtype[200];
2426
2427                                 /*
2428                                 **  Write the pid to file
2429                                 **  XXX Overwrites sendmail.pid
2430                                 */
2431
2432                                 log_sendmail_pid(&MainEnvelope);
2433
2434                                 /* set the title to make it easier to find */
2435                                 qtype[0] = '\0';
2436                                 (void) sm_strlcpyn(qtype, sizeof qtype, 4,
2437                                                    "Queue runner@",
2438                                                    pintvl(QueueIntvl, true),
2439                                                    " for ",
2440                                                    QueueDir);
2441                                 sm_setproctitle(true, CurEnv, qtype);
2442                                 for (;;)
2443                                 {
2444                                         (void) pause();
2445                                         CHECK_RESTART;
2446                                         if (doqueuerun())
2447                                                 (void) runqueue(true, false,
2448                                                                 false, false);
2449                                 }
2450                         }
2451                 }
2452                 dropenvelope(&MainEnvelope, true, false);
2453
2454 #if STARTTLS
2455                 /* init TLS for server, ignore result for now */
2456                 (void) initsrvtls(tls_ok);
2457 #endif /* STARTTLS */
2458
2459         nextreq:
2460                 p_flags = getrequests(&MainEnvelope);
2461
2462                 /* drop privileges */
2463                 (void) drop_privileges(false);
2464
2465                 /*
2466                 **  Get authentication data
2467                 **  Set _ macro in BlankEnvelope before calling newenvelope().
2468                 */
2469
2470                 authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2471                                                      NULL), &forged);
2472                 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
2473
2474                 /* at this point we are in a child: reset state */
2475                 sm_rpool_free(MainEnvelope.e_rpool);
2476                 (void) newenvelope(&MainEnvelope, &MainEnvelope,
2477                                    sm_rpool_new_x(NULL));
2478         }
2479
2480         if (LogLevel > 9)
2481         {
2482                 /* log connection information */
2483                 sm_syslog(LOG_INFO, NULL, "connect from %s", authinfo);
2484         }
2485
2486         /*
2487         **  If running SMTP protocol, start collecting and executing
2488         **  commands.  This will never return.
2489         */
2490
2491         if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2492         {
2493                 char pbuf[20];
2494
2495                 /*
2496                 **  Save some macros for check_* rulesets.
2497                 */
2498
2499                 if (forged)
2500                 {
2501                         char ipbuf[103];
2502
2503                         (void) sm_snprintf(ipbuf, sizeof ipbuf, "[%.100s]",
2504                                            anynet_ntoa(&RealHostAddr));
2505                         macdefine(&BlankEnvelope.e_macro, A_TEMP,
2506                                   macid("{client_name}"), ipbuf);
2507                 }
2508                 else
2509                         macdefine(&BlankEnvelope.e_macro, A_PERM,
2510                                   macid("{client_name}"), RealHostName);
2511                 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2512                           macid("{client_addr}"), anynet_ntoa(&RealHostAddr));
2513                 sm_getla();
2514
2515                 switch (RealHostAddr.sa.sa_family)
2516                 {
2517 #if NETINET
2518                   case AF_INET:
2519                         (void) sm_snprintf(pbuf, sizeof pbuf, "%d",
2520                                            RealHostAddr.sin.sin_port);
2521                         break;
2522 #endif /* NETINET */
2523 #if NETINET6
2524                   case AF_INET6:
2525                         (void) sm_snprintf(pbuf, sizeof pbuf, "%d",
2526                                            RealHostAddr.sin6.sin6_port);
2527                         break;
2528 #endif /* NETINET6 */
2529                   default:
2530                         (void) sm_snprintf(pbuf, sizeof pbuf, "0");
2531                         break;
2532                 }
2533                 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2534                         macid("{client_port}"), pbuf);
2535
2536                 if (OpMode == MD_DAEMON)
2537                 {
2538                         /* validate the connection */
2539                         HoldErrs = true;
2540                         nullserver = validate_connection(&RealHostAddr,
2541                                                          RealHostName,
2542                                                          &MainEnvelope);
2543                         HoldErrs = false;
2544                 }
2545                 else if (p_flags == NULL)
2546                 {
2547                         p_flags = (BITMAP256 *) xalloc(sizeof *p_flags);
2548                         clrbitmap(p_flags);
2549                 }
2550 #if STARTTLS
2551                 if (OpMode == MD_SMTP)
2552                         (void) initsrvtls(tls_ok);
2553 #endif /* STARTTLS */
2554
2555                 /* turn off profiling */
2556                 SM_PROF(1);
2557                 smtp(nullserver, *p_flags, &MainEnvelope);
2558
2559                 if (tTd(93, 100))
2560                 {
2561                         /* turn off profiling */
2562                         SM_PROF(0);
2563                         if (OpMode == MD_DAEMON)
2564                                 goto nextreq;
2565                 }
2566         }
2567
2568         sm_rpool_free(MainEnvelope.e_rpool);
2569         clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2570         if (OpMode == MD_VERIFY)
2571         {
2572                 set_delivery_mode(SM_VERIFY, &MainEnvelope);
2573                 PostMasterCopy = NULL;
2574         }
2575         else
2576         {
2577                 /* interactive -- all errors are global */
2578                 MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2579         }
2580
2581         /*
2582         **  Do basic system initialization and set the sender
2583         */
2584
2585         initsys(&MainEnvelope);
2586         macdefine(&MainEnvelope.e_macro, A_PERM, macid("{ntries}"), "0");
2587         macdefine(&MainEnvelope.e_macro, A_PERM, macid("{nrcpts}"), "0");
2588         setsender(from, &MainEnvelope, NULL, '\0', false);
2589         if (warn_f_flag != '\0' && !wordinclass(RealUserName, 't') &&
2590             (!bitnset(M_LOCALMAILER, MainEnvelope.e_from.q_mailer->m_flags) ||
2591              strcmp(MainEnvelope.e_from.q_user, RealUserName) != 0))
2592         {
2593                 auth_warning(&MainEnvelope, "%s set sender to %s using -%c",
2594                              RealUserName, from, warn_f_flag);
2595 #if SASL
2596                 auth = false;
2597 #endif /* SASL */
2598         }
2599         if (auth)
2600         {
2601                 char *fv;
2602
2603                 /* set the initial sender for AUTH= to $f@$j */
2604                 fv = macvalue('f', &MainEnvelope);
2605                 if (fv == NULL || *fv == '\0')
2606                         MainEnvelope.e_auth_param = NULL;
2607                 else
2608                 {
2609                         if (strchr(fv, '@') == NULL)
2610                         {
2611                                 i = strlen(fv) + strlen(macvalue('j',
2612                                                         &MainEnvelope)) + 2;
2613                                 p = sm_malloc_x(i);
2614                                 (void) sm_strlcpyn(p, i, 3, fv, "@",
2615                                                    macvalue('j',
2616                                                             &MainEnvelope));
2617                         }
2618                         else
2619                                 p = sm_strdup_x(fv);
2620                         MainEnvelope.e_auth_param = sm_rpool_strdup_x(MainEnvelope.e_rpool,
2621                                                                       xtextify(p, "="));
2622                         sm_free(p);  /* XXX */
2623                 }
2624         }
2625         if (macvalue('s', &MainEnvelope) == NULL)
2626                 macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2627
2628         av = argv + optind;
2629         if (*av == NULL && !GrabTo)
2630         {
2631                 MainEnvelope.e_to = NULL;
2632                 MainEnvelope.e_flags |= EF_GLOBALERRS;
2633                 HoldErrs = false;
2634                 SuperSafe = SAFE_NO;
2635                 usrerr("Recipient names must be specified");
2636
2637                 /* collect body for UUCP return */
2638                 if (OpMode != MD_VERIFY)
2639                         collect(InChannel, false, NULL, &MainEnvelope, true);
2640                 finis(true, true, EX_USAGE);
2641                 /* NOTREACHED */
2642         }
2643
2644         /*
2645         **  Scan argv and deliver the message to everyone.
2646         */
2647
2648         save_val = LogUsrErrs;
2649         LogUsrErrs = true;
2650         sendtoargv(av, &MainEnvelope);
2651         LogUsrErrs = save_val;
2652
2653         /* if we have had errors sofar, arrange a meaningful exit stat */
2654         if (Errors > 0 && ExitStat == EX_OK)
2655                 ExitStat = EX_USAGE;
2656
2657 #if _FFR_FIX_DASHT
2658         /*
2659         **  If using -t, force not sending to argv recipients, even
2660         **  if they are mentioned in the headers.
2661         */
2662
2663         if (GrabTo)
2664         {
2665                 ADDRESS *q;
2666
2667                 for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2668                         q->q_state = QS_REMOVED;
2669         }
2670 #endif /* _FFR_FIX_DASHT */
2671
2672         /*
2673         **  Read the input mail.
2674         */
2675
2676         MainEnvelope.e_to = NULL;
2677         if (OpMode != MD_VERIFY || GrabTo)
2678         {
2679                 int savederrors;
2680                 unsigned long savedflags;
2681
2682                 /*
2683                 **  workaround for compiler warning on Irix:
2684                 **  do not initialize variable in the definition, but
2685                 **  later on:
2686                 **  warning(1548): transfer of control bypasses
2687                 **  initialization of:
2688                 **  variable "savederrors" (declared at line 2570)
2689                 **  variable "savedflags" (declared at line 2571)
2690                 **  goto giveup;
2691                 */
2692
2693                 savederrors = Errors;
2694                 savedflags = MainEnvelope.e_flags & EF_FATALERRS;
2695                 MainEnvelope.e_flags |= EF_GLOBALERRS;
2696                 MainEnvelope.e_flags &= ~EF_FATALERRS;
2697                 Errors = 0;
2698                 buffer_errors();
2699                 collect(InChannel, false, NULL, &MainEnvelope, true);
2700
2701                 /* header checks failed */
2702                 if (Errors > 0)
2703                 {
2704   giveup:
2705                         if (!GrabTo)
2706                         {
2707                                 /* Log who the mail would have gone to */
2708                                 logundelrcpts(&MainEnvelope,
2709                                               MainEnvelope.e_message,
2710                                               8, false);
2711                         }
2712                         flush_errors(true);
2713                         finis(true, true, ExitStat);
2714                         /* NOTREACHED */
2715                         return -1;
2716                 }
2717
2718                 /* bail out if message too large */
2719                 if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2720                 {
2721                         finis(true, true, ExitStat != EX_OK ? ExitStat
2722                                                             : EX_DATAERR);
2723                         /* NOTREACHED */
2724                         return -1;
2725                 }
2726
2727                 /* set message size */
2728                 (void) sm_snprintf(buf, sizeof buf, "%ld",
2729                                    MainEnvelope.e_msgsize);
2730                 macdefine(&MainEnvelope.e_macro, A_TEMP,
2731                           macid("{msg_size}"), buf);
2732
2733                 Errors = savederrors;
2734                 MainEnvelope.e_flags |= savedflags;
2735         }
2736         errno = 0;
2737
2738         if (tTd(1, 1))
2739                 sm_dprintf("From person = \"%s\"\n",
2740                            MainEnvelope.e_from.q_paddr);
2741
2742 #if _FFR_QUARANTINE
2743         /* Check if quarantining stats should be updated */
2744         if (MainEnvelope.e_quarmsg != NULL)
2745                 markstats(&MainEnvelope, NULL, STATS_QUARANTINE);
2746 #endif /* _FFR_QUARANTINE */
2747
2748         /*
2749         **  Actually send everything.
2750         **      If verifying, just ack.
2751         */
2752
2753         if (Errors == 0)
2754         {
2755                 if (!split_by_recipient(&MainEnvelope) &&
2756                     bitset(EF_FATALERRS, MainEnvelope.e_flags))
2757                         goto giveup;
2758         }
2759
2760         /* make sure we deliver at least the first envelope */
2761         i = FastSplit > 0 ? 0 : -1;
2762         for (e = &MainEnvelope; e != NULL; e = e->e_sibling, i++)
2763         {
2764                 ENVELOPE *next;
2765
2766                 e->e_from.q_state = QS_SENDER;
2767                 if (tTd(1, 5))
2768                 {
2769                         sm_dprintf("main[%d]: QS_SENDER ", i);
2770                         printaddr(&e->e_from, false);
2771                 }
2772                 e->e_to = NULL;
2773                 sm_getla();
2774                 GrabTo = false;
2775 #if NAMED_BIND
2776                 _res.retry = TimeOuts.res_retry[RES_TO_FIRST];
2777                 _res.retrans = TimeOuts.res_retrans[RES_TO_FIRST];
2778 #endif /* NAMED_BIND */
2779                 next = e->e_sibling;
2780                 e->e_sibling = NULL;
2781
2782                 /* after FastSplit envelopes: queue up */
2783                 sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2784                 e->e_sibling = next;
2785         }
2786
2787         /*
2788         **  All done.
2789         **      Don't send return error message if in VERIFY mode.
2790         */
2791
2792         finis(true, true, ExitStat);
2793         /* NOTREACHED */
2794         return ExitStat;
2795 }
2796 /*
2797 **  STOP_SENDMAIL -- Stop the running program
2798 **
2799 **      Parameters:
2800 **              none.
2801 **
2802 **      Returns:
2803 **              none.
2804 **
2805 **      Side Effects:
2806 **              exits.
2807 */
2808
2809 void
2810 stop_sendmail()
2811 {
2812         /* reset uid for process accounting */
2813         endpwent();
2814         (void) setuid(RealUid);
2815         exit(EX_OK);
2816 }
2817 /*
2818 **  FINIS -- Clean up and exit.
2819 **
2820 **      Parameters:
2821 **              drop -- whether or not to drop CurEnv envelope
2822 **              cleanup -- call exit() or _exit()?
2823 **              exitstat -- exit status to use for exit() call
2824 **
2825 **      Returns:
2826 **              never
2827 **
2828 **      Side Effects:
2829 **              exits sendmail
2830 */
2831
2832 void
2833 finis(drop, cleanup, exitstat)
2834         bool drop;
2835         bool cleanup;
2836         volatile int exitstat;
2837 {
2838
2839         /* Still want to process new timeouts added below */
2840         sm_clear_events();
2841         (void) sm_releasesignal(SIGALRM);
2842
2843         if (tTd(2, 1))
2844         {
2845                 sm_dprintf("\n====finis: stat %d e_id=%s e_flags=",
2846                            exitstat,
2847                            CurEnv->e_id == NULL ? "NOQUEUE" : CurEnv->e_id);
2848                 printenvflags(CurEnv);
2849         }
2850         if (tTd(2, 9))
2851                 printopenfds(false);
2852
2853         SM_TRY
2854                 /*
2855                 **  Clean up.  This might raise E:mta.quickabort
2856                 */
2857
2858                 /* clean up temp files */
2859                 CurEnv->e_to = NULL;
2860                 if (drop)
2861                 {
2862                         if (CurEnv->e_id != NULL)
2863                         {
2864                                 dropenvelope(CurEnv, true, false);
2865                                 sm_rpool_free(CurEnv->e_rpool);
2866                                 CurEnv->e_rpool = NULL;
2867                         }
2868                         else
2869                                 poststats(StatFile);
2870                 }
2871
2872                 /* flush any cached connections */
2873                 mci_flush(true, NULL);
2874
2875                 /* close maps belonging to this pid */
2876                 closemaps(false);
2877
2878 #if USERDB
2879                 /* close UserDatabase */
2880                 _udbx_close();
2881 #endif /* USERDB */
2882
2883 #if SASL
2884                 stop_sasl_client();
2885 #endif /* SASL */
2886
2887 #if XLA
2888                 /* clean up extended load average stuff */
2889                 xla_all_end();
2890 #endif /* XLA */
2891
2892         SM_FINALLY
2893                 /*
2894                 **  And exit.
2895                 */
2896
2897                 if (LogLevel > 78)
2898                         sm_syslog(LOG_DEBUG, CurEnv->e_id, "finis, pid=%d",
2899                                   (int) CurrentPid);
2900                 if (exitstat == EX_TEMPFAIL ||
2901                     CurEnv->e_errormode == EM_BERKNET)
2902                         exitstat = EX_OK;
2903
2904                 /* XXX clean up queues and related data structures */
2905                 cleanup_queues();
2906 #if SM_CONF_SHM
2907                 cleanup_shm(DaemonPid == getpid());
2908 #endif /* SM_CONF_SHM */
2909
2910                 /* reset uid for process accounting */
2911                 endpwent();
2912                 sm_mbdb_terminate();
2913                 (void) setuid(RealUid);
2914 #if SM_HEAP_CHECK
2915                 /* dump the heap, if we are checking for memory leaks */
2916                 if (sm_debug_active(&SmHeapCheck, 2))
2917                         sm_heap_report(smioout,
2918                                        sm_debug_level(&SmHeapCheck) - 1);
2919 #endif /* SM_HEAP_CHECK */
2920                 if (sm_debug_active(&SmXtrapReport, 1))
2921                         sm_dprintf("xtrap count = %d\n", SmXtrapCount);
2922                 if (cleanup)
2923                         exit(exitstat);
2924                 else
2925                         _exit(exitstat);
2926         SM_END_TRY
2927 }
2928 /*
2929 **  INTINDEBUG -- signal handler for SIGINT in -bt mode
2930 **
2931 **      Parameters:
2932 **              sig -- incoming signal.
2933 **
2934 **      Returns:
2935 **              none.
2936 **
2937 **      Side Effects:
2938 **              longjmps back to test mode loop.
2939 **
2940 **      NOTE:   THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
2941 **              ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2942 **              DOING.
2943 */
2944
2945 /* Type of an exception generated on SIGINT during address test mode.  */
2946 static const SM_EXC_TYPE_T EtypeInterrupt =
2947 {
2948         SmExcTypeMagic,
2949         "S:mta.interrupt",
2950         "",
2951         sm_etype_printf,
2952         "interrupt",
2953 };
2954
2955 /* ARGSUSED */
2956 static SIGFUNC_DECL
2957 intindebug(sig)
2958         int sig;
2959 {
2960         int save_errno = errno;
2961
2962         FIX_SYSV_SIGNAL(sig, intindebug);
2963         errno = save_errno;
2964         CHECK_CRITICAL(sig);
2965         errno = save_errno;
2966         sm_exc_raisenew_x(&EtypeInterrupt);
2967         errno = save_errno;
2968         return SIGFUNC_RETURN;
2969 }
2970 /*
2971 **  SIGTERM -- SIGTERM handler for the daemon
2972 **
2973 **      Parameters:
2974 **              sig -- signal number.
2975 **
2976 **      Returns:
2977 **              none.
2978 **
2979 **      Side Effects:
2980 **              Sets ShutdownRequest which will hopefully trigger
2981 **              the daemon to exit.
2982 **
2983 **      NOTE:   THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
2984 **              ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2985 **              DOING.
2986 */
2987
2988 /* ARGSUSED */
2989 static SIGFUNC_DECL
2990 sigterm(sig)
2991         int sig;
2992 {
2993         int save_errno = errno;
2994
2995         FIX_SYSV_SIGNAL(sig, sigterm);
2996         ShutdownRequest = "signal";
2997         errno = save_errno;
2998         return SIGFUNC_RETURN;
2999 }
3000 /*
3001 **  SIGHUP -- handle a SIGHUP signal
3002 **
3003 **      Parameters:
3004 **              sig -- incoming signal.
3005 **
3006 **      Returns:
3007 **              none.
3008 **
3009 **      Side Effects:
3010 **              Sets RestartRequest which should cause the daemon
3011 **              to restart.
3012 **
3013 **      NOTE:   THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3014 **              ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3015 **              DOING.
3016 */
3017
3018 /* ARGSUSED */
3019 static SIGFUNC_DECL
3020 sighup(sig)
3021         int sig;
3022 {
3023         int save_errno = errno;
3024
3025         FIX_SYSV_SIGNAL(sig, sighup);
3026         RestartRequest = "signal";
3027         errno = save_errno;
3028         return SIGFUNC_RETURN;
3029 }
3030 /*
3031 **  SIGPIPE -- signal handler for SIGPIPE
3032 **
3033 **      Parameters:
3034 **              sig -- incoming signal.
3035 **
3036 **      Returns:
3037 **              none.
3038 **
3039 **      Side Effects:
3040 **              Sets StopRequest which should cause the mailq/hoststatus
3041 **              display to stop.
3042 **
3043 **      NOTE:   THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3044 **              ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3045 **              DOING.
3046 */
3047
3048 /* ARGSUSED */
3049 static SIGFUNC_DECL
3050 sigpipe(sig)
3051         int sig;
3052 {
3053         int save_errno = errno;
3054
3055         FIX_SYSV_SIGNAL(sig, sigpipe);
3056         StopRequest = true;
3057         errno = save_errno;
3058         return SIGFUNC_RETURN;
3059 }
3060 /*
3061 **  INTSIG -- clean up on interrupt
3062 **
3063 **      This just arranges to exit.  It pessimizes in that it
3064 **      may resend a message.
3065 **
3066 **      Parameters:
3067 **              none.
3068 **
3069 **      Returns:
3070 **              none.
3071 **
3072 **      Side Effects:
3073 **              Unlocks the current job.
3074 **
3075 **      NOTE:   THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3076 **              ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3077 **              DOING.
3078 **
3079 **              XXX: More work is needed for this signal handler.
3080 */
3081
3082 /* ARGSUSED */
3083 SIGFUNC_DECL
3084 intsig(sig)
3085         int sig;
3086 {
3087         bool drop = false;
3088         int save_errno = errno;
3089
3090         FIX_SYSV_SIGNAL(sig, intsig);
3091         errno = save_errno;
3092         CHECK_CRITICAL(sig);
3093         sm_allsignals(true);
3094
3095         if (sig != 0 && LogLevel > 79)
3096                 sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3097         FileName = NULL;
3098
3099         /* Clean-up on aborted stdin message submission */
3100         if (CurEnv->e_id != NULL &&
3101             (OpMode == MD_SMTP ||
3102              OpMode == MD_DELIVER ||
3103              OpMode == MD_ARPAFTP))
3104         {
3105                 register ADDRESS *q;
3106
3107                 /* don't return an error indication */
3108                 CurEnv->e_to = NULL;
3109                 CurEnv->e_flags &= ~EF_FATALERRS;
3110                 CurEnv->e_flags |= EF_CLRQUEUE;
3111
3112                 /*
3113                 **  Spin through the addresses and
3114                 **  mark them dead to prevent bounces
3115                 */
3116
3117                 for (q = CurEnv->e_sendqueue; q != NULL; q = q->q_next)
3118                         q->q_state = QS_DONTSEND;
3119
3120                 drop = true;
3121         }
3122         else if (OpMode != MD_TEST)
3123         {
3124                 unlockqueue(CurEnv);
3125         }
3126
3127         finis(drop, false, EX_OK);
3128         /* NOTREACHED */
3129 }
3130 /*
3131 **  DISCONNECT -- remove our connection with any foreground process
3132 **
3133 **      Parameters:
3134 **              droplev -- how "deeply" we should drop the line.
3135 **                      0 -- ignore signals, mail back errors, make sure
3136 **                           output goes to stdout.
3137 **                      1 -- also, make stdout go to /dev/null.
3138 **                      2 -- also, disconnect from controlling terminal
3139 **                           (only for daemon mode).
3140 **              e -- the current envelope.
3141 **
3142 **      Returns:
3143 **              none
3144 **
3145 **      Side Effects:
3146 **              Trys to insure that we are immune to vagaries of
3147 **              the controlling tty.
3148 */
3149
3150 void
3151 disconnect(droplev, e)
3152         int droplev;
3153         register ENVELOPE *e;
3154 {
3155         int fd;
3156
3157         if (tTd(52, 1))
3158                 sm_dprintf("disconnect: In %d Out %d, e=%p\n",
3159                            sm_io_getinfo(InChannel, SM_IO_WHAT_FD, NULL),
3160                            sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL), e);
3161         if (tTd(52, 100))
3162         {
3163                 sm_dprintf("don't\n");
3164                 return;
3165         }
3166         if (LogLevel > 93)
3167                 sm_syslog(LOG_DEBUG, e->e_id,
3168                           "disconnect level %d",
3169                           droplev);
3170
3171         /* be sure we don't get nasty signals */
3172         (void) sm_signal(SIGINT, SIG_IGN);
3173         (void) sm_signal(SIGQUIT, SIG_IGN);
3174
3175         /* we can't communicate with our caller, so.... */
3176         HoldErrs = true;
3177         CurEnv->e_errormode = EM_MAIL;
3178         Verbose = 0;
3179         DisConnected = true;
3180
3181         /* all input from /dev/null */
3182         if (InChannel != smioin)
3183         {
3184                 (void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3185                 InChannel = smioin;
3186         }
3187         if (sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3188                          SM_IO_RDONLY, NULL, smioin) == NULL)
3189                 sm_syslog(LOG_ERR, e->e_id,
3190                           "disconnect: sm_io_reopen(\"%s\") failed: %s",
3191                           SM_PATH_DEVNULL, sm_errstring(errno));
3192
3193         /*
3194         **  output to the transcript
3195         **      We also compare the fd numbers here since OutChannel
3196         **      might be a layer on top of smioout due to encryption
3197         **      (see sfsasl.c).
3198         */
3199
3200         if (OutChannel != smioout &&
3201             sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3202             sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3203         {
3204                 (void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3205                 OutChannel = smioout;
3206
3207 #if 0
3208                 /*
3209                 **  Has smioout been closed? Reopen it.
3210                 **      This shouldn't happen anymore, the code is here
3211                 **      just as a reminder.
3212                 */
3213
3214                 if (smioout->sm_magic == NULL &&
3215                     sm_io_reopen(SmFtStdio, SM_TIME_DEFAULT, SM_PATH_DEVNULL,
3216                                  SM_IO_WRONLY, NULL, smioout) == NULL)
3217                         sm_syslog(LOG_ERR, e->e_id,
3218                                   "disconnect: sm_io_reopen(\"%s\") failed: %s",
3219                                   SM_PATH_DEVNULL, sm_errstring(errno));
3220 #endif /* 0 */
3221         }
3222         if (droplev > 0)
3223         {
3224                 fd = open(SM_PATH_DEVNULL, O_WRONLY, 0666);
3225                 if (fd == -1)
3226                         sm_syslog(LOG_ERR, e->e_id,
3227                                   "disconnect: open(\"%s\") failed: %s",
3228                                   SM_PATH_DEVNULL, sm_errstring(errno));
3229                 (void) sm_io_flush(smioout, SM_TIME_DEFAULT);
3230                 (void) dup2(fd, STDOUT_FILENO);
3231                 (void) dup2(fd, STDERR_FILENO);
3232                 (void) close(fd);
3233         }
3234
3235         /* drop our controlling TTY completely if possible */
3236         if (droplev > 1)
3237         {
3238                 (void) setsid();
3239                 errno = 0;
3240         }
3241
3242 #if XDEBUG
3243         checkfd012("disconnect");
3244 #endif /* XDEBUG */
3245
3246         if (LogLevel > 71)
3247                 sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3248                           (int) CurrentPid);
3249
3250         errno = 0;
3251 }
3252
3253 static void
3254 obsolete(argv)
3255         char *argv[];
3256 {
3257         register char *ap;
3258         register char *op;
3259
3260         while ((ap = *++argv) != NULL)
3261         {
3262                 /* Return if "--" or not an option of any form. */
3263                 if (ap[0] != '-' || ap[1] == '-')
3264                         return;
3265
3266 #if _FFR_QUARANTINE
3267                 /* Don't allow users to use "-Q." or "-Q ." */
3268                 if ((ap[1] == 'Q' && ap[2] == '.') ||
3269                     (ap[1] == 'Q' && argv[1] != NULL &&
3270                      argv[1][0] == '.' && argv[1][1] == '\0'))
3271                 {
3272                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3273                                              "Can not use -Q.\n");
3274                         exit(EX_USAGE);
3275                 }
3276 #endif /* _FFR_QUARANTINE */
3277
3278                 /* skip over options that do have a value */
3279                 op = strchr(OPTIONS, ap[1]);
3280                 if (op != NULL && *++op == ':' && ap[2] == '\0' &&
3281                     ap[1] != 'd' &&
3282 #if defined(sony_news)
3283                     ap[1] != 'E' && ap[1] != 'J' &&
3284 #endif /* defined(sony_news) */
3285                     argv[1] != NULL && argv[1][0] != '-')
3286                 {
3287                         argv++;
3288                         continue;
3289                 }
3290
3291                 /* If -C doesn't have an argument, use sendmail.cf. */
3292 #define __DEFPATH       "sendmail.cf"
3293                 if (ap[1] == 'C' && ap[2] == '\0')
3294                 {
3295                         *argv = xalloc(sizeof(__DEFPATH) + 2);
3296                         (void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3297                                            "-C", __DEFPATH);
3298                 }
3299
3300                 /* If -q doesn't have an argument, run it once. */
3301                 if (ap[1] == 'q' && ap[2] == '\0')
3302                         *argv = "-q0";
3303
3304 #if _FFR_QUARANTINE
3305                 /* If -Q doesn't have an argument, disable quarantining */
3306                 if (ap[1] == 'Q' && ap[2] == '\0')
3307                         *argv = "-Q.";
3308 #endif /* _FFR_QUARANTINE */
3309
3310                 /* if -d doesn't have an argument, use 0-99.1 */
3311                 if (ap[1] == 'd' && ap[2] == '\0')
3312                         *argv = "-d0-99.1";
3313
3314 #if defined(sony_news)
3315                 /* if -E doesn't have an argument, use -EC */
3316                 if (ap[1] == 'E' && ap[2] == '\0')
3317                         *argv = "-EC";
3318
3319                 /* if -J doesn't have an argument, use -JJ */
3320                 if (ap[1] == 'J' && ap[2] == '\0')
3321                         *argv = "-JJ";
3322 #endif /* defined(sony_news) */
3323         }
3324 }
3325 /*
3326 **  AUTH_WARNING -- specify authorization warning
3327 **
3328 **      Parameters:
3329 **              e -- the current envelope.
3330 **              msg -- the text of the message.
3331 **              args -- arguments to the message.
3332 **
3333 **      Returns:
3334 **              none.
3335 */
3336
3337 void
3338 #ifdef __STDC__
3339 auth_warning(register ENVELOPE *e, const char *msg, ...)
3340 #else /* __STDC__ */
3341 auth_warning(e, msg, va_alist)
3342         register ENVELOPE *e;
3343         const char *msg;
3344         va_dcl
3345 #endif /* __STDC__ */
3346 {
3347         char buf[MAXLINE];
3348         SM_VA_LOCAL_DECL
3349
3350         if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3351         {
3352                 register char *p;
3353                 static char hostbuf[48];
3354
3355                 if (hostbuf[0] == '\0')
3356                 {
3357                         struct hostent *hp;
3358
3359                         hp = myhostname(hostbuf, sizeof hostbuf);
3360 #if NETINET6
3361                         if (hp != NULL)
3362                         {
3363                                 freehostent(hp);
3364                                 hp = NULL;
3365                         }
3366 #endif /* NETINET6 */
3367                 }
3368
3369                 (void) sm_strlcpyn(buf, sizeof buf, 2, hostbuf, ": ");
3370                 p = &buf[strlen(buf)];
3371                 SM_VA_START(ap, msg);
3372                 (void) sm_vsnprintf(p, SPACELEFT(buf, p), msg, ap);
3373                 SM_VA_END(ap);
3374                 addheader("X-Authentication-Warning", buf, 0, e);
3375                 if (LogLevel > 3)
3376                         sm_syslog(LOG_INFO, e->e_id,
3377                                   "Authentication-Warning: %.400s",
3378                                   buf);
3379         }
3380 }
3381 /*
3382 **  GETEXTENV -- get from external environment
3383 **
3384 **      Parameters:
3385 **              envar -- the name of the variable to retrieve
3386 **
3387 **      Returns:
3388 **              The value, if any.
3389 */
3390
3391 static char *
3392 getextenv(envar)
3393         const char *envar;
3394 {
3395         char **envp;
3396         int l;
3397
3398         l = strlen(envar);
3399         for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++)
3400         {
3401                 if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3402                         return &(*envp)[l + 1];
3403         }
3404         return NULL;
3405 }
3406 /*
3407 **  SETUSERENV -- set an environment in the propagated environment
3408 **
3409 **      Parameters:
3410 **              envar -- the name of the environment variable.
3411 **              value -- the value to which it should be set.  If
3412 **                      null, this is extracted from the incoming
3413 **                      environment.  If that is not set, the call
3414 **                      to setuserenv is ignored.
3415 **
3416 **      Returns:
3417 **              none.
3418 */
3419
3420 void
3421 setuserenv(envar, value)
3422         const char *envar;
3423         const char *value;
3424 {
3425         int i, l;
3426         char **evp = UserEnviron;
3427         char *p;
3428
3429         if (value == NULL)
3430         {
3431                 value = getextenv(envar);
3432                 if (value == NULL)
3433                         return;
3434         }
3435
3436         /* XXX enforce reasonable size? */
3437         i = strlen(envar) + 1;
3438         l = strlen(value) + i + 1;
3439         p = (char *) xalloc(l);
3440         (void) sm_strlcpyn(p, l, 3, envar, "=", value);
3441
3442         while (*evp != NULL && strncmp(*evp, p, i) != 0)
3443                 evp++;
3444         if (*evp != NULL)
3445         {
3446                 *evp++ = p;
3447         }
3448         else if (evp < &UserEnviron[MAXUSERENVIRON])
3449         {
3450                 *evp++ = p;
3451                 *evp = NULL;
3452         }
3453
3454         /* make sure it is in our environment as well */
3455         if (putenv(p) < 0)
3456                 syserr("setuserenv: putenv(%s) failed", p);
3457 }
3458 /*
3459 **  DUMPSTATE -- dump state
3460 **
3461 **      For debugging.
3462 */
3463
3464 void
3465 dumpstate(when)
3466         char *when;
3467 {
3468         register char *j = macvalue('j', CurEnv);
3469         int rs;
3470         extern int NextMacroId;
3471
3472         sm_syslog(LOG_DEBUG, CurEnv->e_id,
3473                   "--- dumping state on %s: $j = %s ---",
3474                   when,
3475                   j == NULL ? "<NULL>" : j);
3476         if (j != NULL)
3477         {
3478                 if (!wordinclass(j, 'w'))
3479                         sm_syslog(LOG_DEBUG, CurEnv->e_id,
3480                                   "*** $j not in $=w ***");
3481         }
3482         sm_syslog(LOG_DEBUG, CurEnv->e_id, "CurChildren = %d", CurChildren);
3483         sm_syslog(LOG_DEBUG, CurEnv->e_id, "NextMacroId = %d (Max %d)",
3484                   NextMacroId, MAXMACROID);
3485         sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- open file descriptors: ---");
3486         printopenfds(true);
3487         sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- connection cache: ---");
3488         mci_dump_all(true);
3489         rs = strtorwset("debug_dumpstate", NULL, ST_FIND);
3490         if (rs > 0)
3491         {
3492                 int status;
3493                 register char **pvp;
3494                 char *pv[MAXATOM + 1];
3495
3496                 pv[0] = NULL;
3497                 status = REWRITE(pv, rs, CurEnv);
3498                 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3499                           "--- ruleset debug_dumpstate returns stat %d, pv: ---",
3500                           status);
3501                 for (pvp = pv; *pvp != NULL; pvp++)
3502                         sm_syslog(LOG_DEBUG, CurEnv->e_id, "%s", *pvp);
3503         }
3504         sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3505 }
3506
3507 #ifdef SIGUSR1
3508 /*
3509 **  SIGUSR1 -- Signal a request to dump state.
3510 **
3511 **      Parameters:
3512 **              sig -- calling signal.
3513 **
3514 **      Returns:
3515 **              none.
3516 **
3517 **      NOTE:   THIS CAN BE CALLED FROM A SIGNAL HANDLER.  DO NOT ADD
3518 **              ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3519 **              DOING.
3520 **
3521 **              XXX: More work is needed for this signal handler.
3522 */
3523
3524 /* ARGSUSED */
3525 static SIGFUNC_DECL
3526 sigusr1(sig)
3527         int sig;
3528 {
3529         int save_errno = errno;
3530 # if SM_HEAP_CHECK
3531         extern void dumpstab __P((void));
3532 # endif /* SM_HEAP_CHECK */
3533
3534         FIX_SYSV_SIGNAL(sig, sigusr1);
3535         errno = save_errno;
3536         CHECK_CRITICAL(sig);
3537         dumpstate("user signal");
3538 # if SM_HEAP_CHECK
3539         dumpstab();
3540 # endif /* SM_HEAP_CHECK */
3541         errno = save_errno;
3542         return SIGFUNC_RETURN;
3543 }
3544 #endif /* SIGUSR1 */
3545
3546 /*
3547 **  DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3548 **
3549 **      Parameters:
3550 **              to_real_uid -- if set, drop to the real uid instead
3551 **                      of the RunAsUser.
3552 **
3553 **      Returns:
3554 **              EX_OSERR if the setuid failed.
3555 **              EX_OK otherwise.
3556 */
3557
3558 int
3559 drop_privileges(to_real_uid)
3560         bool to_real_uid;
3561 {
3562         int rval = EX_OK;
3563         GIDSET_T emptygidset[1];
3564
3565         if (tTd(47, 1))
3566                 sm_dprintf("drop_privileges(%d): Real[UG]id=%d:%d, get[ug]id=%d:%d, gete[ug]id=%d:%d, RunAs[UG]id=%d:%d\n",
3567                            (int) to_real_uid,
3568                            (int) RealUid, (int) RealGid,
3569                            (int) getuid(), (int) getgid(),
3570                            (int) geteuid(), (int) getegid(),
3571                            (int) RunAsUid, (int) RunAsGid);
3572
3573         if (to_real_uid)
3574         {
3575                 RunAsUserName = RealUserName;
3576                 RunAsUid = RealUid;
3577                 RunAsGid = RealGid;
3578                 EffGid = RunAsGid;
3579         }
3580
3581         /* make sure no one can grab open descriptors for secret files */
3582         endpwent();
3583         sm_mbdb_terminate();
3584
3585         /* reset group permissions; these can be set later */
3586         emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
3587
3588         /*
3589         **  Notice:  on some OS (Linux...) the setgroups() call causes
3590         **      a logfile entry if sendmail is not run by root.
3591         **      However, it is unclear (no POSIX standard) whether
3592         **      setgroups() can only succeed if executed by root.
3593         **      So for now we keep it as it is; if you want to change it, use
3594         **  if (geteuid() == 0 && setgroups(1, emptygidset) == -1)
3595         */
3596
3597         if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3598         {
3599                 syserr("drop_privileges: setgroups(1, %d) failed",
3600                        (int) emptygidset[0]);
3601                 rval = EX_OSERR;
3602         }
3603
3604         /* reset primary group id */
3605         if (to_real_uid)
3606         {
3607                 /*
3608                 **  Drop gid to real gid.
3609                 **  On some OS we must reset the effective[/real[/saved]] gid,
3610                 **  and then use setgid() to finally drop all group privileges.
3611                 **  Later on we check whether we can get back the
3612                 **  effective gid.
3613                 */
3614
3615 #if HASSETEGID
3616                 if (setegid(RunAsGid) < 0)
3617                 {
3618                         syserr("drop_privileges: setegid(%d) failed",
3619                                (int) RunAsGid);
3620                         rval = EX_OSERR;
3621                 }
3622 #else /* HASSETEGID */
3623 # if HASSETREGID
3624                 if (setregid(RunAsGid, RunAsGid) < 0)
3625                 {
3626                         syserr("drop_privileges: setregid(%d, %d) failed",
3627                                (int) RunAsGid, (int) RunAsGid);
3628                         rval = EX_OSERR;
3629                 }
3630 # else /* HASSETREGID */
3631 #  if HASSETRESGID
3632                 if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3633                 {
3634                         syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3635                                (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3636                         rval = EX_OSERR;
3637                 }
3638 #  endif /* HASSETRESGID */
3639 # endif /* HASSETREGID */
3640 #endif /* HASSETEGID */
3641         }
3642         if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3643         {
3644                 if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3645                 {
3646                         syserr("drop_privileges: setgid(%d) failed",
3647                                (int) RunAsGid);
3648                         rval = EX_OSERR;
3649                 }
3650                 errno = 0;
3651                 if (rval == EX_OK && getegid() != RunAsGid)
3652                 {
3653                         syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3654                                (int) getegid(), (int) RunAsGid);
3655                         rval = EX_OSERR;
3656                 }
3657         }
3658
3659         /* fiddle with uid */
3660         if (to_real_uid || RunAsUid != 0)
3661         {
3662                 uid_t euid;
3663
3664                 /*
3665                 **  Try to setuid(RunAsUid).
3666                 **  euid must be RunAsUid,
3667                 **  ruid must be RunAsUid unless (e|r)uid wasn't 0
3668                 **      and we didn't have to drop privileges to the real uid.
3669                 */
3670
3671                 if (setuid(RunAsUid) < 0 ||
3672                     geteuid() != RunAsUid ||
3673                     (getuid() != RunAsUid &&
3674                      (to_real_uid || geteuid() == 0 || getuid() == 0)))
3675                 {
3676 #if HASSETREUID
3677                         /*
3678                         **  if ruid != RunAsUid, euid == RunAsUid, then
3679                         **  try resetting just the real uid, then using
3680                         **  setuid() to drop the saved-uid as well.
3681                         */
3682
3683                         if (geteuid() == RunAsUid)
3684                         {
3685                                 if (setreuid(RunAsUid, -1) < 0)
3686                                 {
3687                                         syserr("drop_privileges: setreuid(%d, -1) failed",
3688                                                (int) RunAsUid);
3689                                         rval = EX_OSERR;
3690                                 }
3691                                 if (setuid(RunAsUid) < 0)
3692                                 {
3693                                         syserr("drop_privileges: second setuid(%d) attempt failed",
3694                                                (int) RunAsUid);
3695                                         rval = EX_OSERR;
3696                                 }
3697                         }
3698                         else
3699 #endif /* HASSETREUID */
3700                         {
3701                                 syserr("drop_privileges: setuid(%d) failed",
3702                                        (int) RunAsUid);
3703                                 rval = EX_OSERR;
3704                         }
3705                 }
3706                 euid = geteuid();
3707                 if (RunAsUid != 0 && setuid(0) == 0)
3708                 {
3709                         /*
3710                         **  Believe it or not, the Linux capability model
3711                         **  allows a non-root process to override setuid()
3712                         **  on a process running as root and prevent that
3713                         **  process from dropping privileges.
3714                         */
3715
3716                         syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3717                         rval = EX_OSERR;
3718                 }
3719                 else if (RunAsUid != euid && setuid(euid) == 0)
3720                 {
3721                         /*
3722                         **  Some operating systems will keep the saved-uid
3723                         **  if a non-root effective-uid calls setuid(real-uid)
3724                         **  making it possible to set it back again later.
3725                         */
3726
3727                         syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3728                         rval = EX_OSERR;
3729                 }
3730         }
3731
3732         if ((to_real_uid || RunAsGid != 0) &&
3733             rval == EX_OK && RunAsGid != EffGid &&
3734             getuid() != 0 && geteuid() != 0)
3735         {
3736                 errno = 0;
3737                 if (setgid(EffGid) == 0)
3738                 {
3739                         syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3740                                (int) EffGid);
3741                         rval = EX_OSERR;
3742                 }
3743         }
3744
3745         if (tTd(47, 5))
3746         {
3747                 sm_dprintf("drop_privileges: e/ruid = %d/%d e/rgid = %d/%d\n",
3748                            (int) geteuid(), (int) getuid(),
3749                            (int) getegid(), (int) getgid());
3750                 sm_dprintf("drop_privileges: RunAsUser = %d:%d\n",
3751                            (int) RunAsUid, (int) RunAsGid);
3752                 if (tTd(47, 10))
3753                         sm_dprintf("drop_privileges: rval = %d\n", rval);
3754         }
3755         return rval;
3756 }
3757 /*
3758 **  FILL_FD -- make sure a file descriptor has been properly allocated
3759 **
3760 **      Used to make sure that stdin/out/err are allocated on startup
3761 **
3762 **      Parameters:
3763 **              fd -- the file descriptor to be filled.
3764 **              where -- a string used for logging.  If NULL, this is
3765 **                      being called on startup, and logging should
3766 **                      not be done.
3767 **
3768 **      Returns:
3769 **              none
3770 **
3771 **      Side Effects:
3772 **              possibly changes MissingFds
3773 */
3774
3775 void
3776 fill_fd(fd, where)
3777         int fd;
3778         char *where;
3779 {
3780         int i;
3781         struct stat stbuf;
3782
3783         if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3784                 return;
3785
3786         if (where != NULL)
3787                 syserr("fill_fd: %s: fd %d not open", where, fd);
3788         else
3789                 MissingFds |= 1 << fd;
3790         i = open(SM_PATH_DEVNULL, fd == 0 ? O_RDONLY : O_WRONLY, 0666);
3791         if (i < 0)
3792         {
3793                 syserr("!fill_fd: %s: cannot open %s",
3794                        where == NULL ? "startup" : where, SM_PATH_DEVNULL);
3795         }
3796         if (fd != i)
3797         {
3798                 (void) dup2(i, fd);
3799                 (void) close(i);
3800         }
3801 }
3802 /*
3803 **  SM_PRINTOPTIONS -- print options
3804 **
3805 **      Parameters:
3806 **              options -- array of options.
3807 **
3808 **      Returns:
3809 **              none.
3810 */
3811
3812 static void
3813 sm_printoptions(options)
3814         char **options;
3815 {
3816         int ll;
3817         char **av;
3818
3819         av = options;
3820         ll = 7;
3821         while (*av != NULL)
3822         {
3823                 if (ll + strlen(*av) > 63)
3824                 {
3825                         sm_dprintf("\n");
3826                         ll = 0;
3827                 }
3828                 if (ll == 0)
3829                         sm_dprintf("\t\t");
3830                 else
3831                         sm_dprintf(" ");
3832                 sm_dprintf("%s", *av);
3833                 ll += strlen(*av++) + 1;
3834         }
3835         sm_dprintf("\n");
3836 }
3837 /*
3838 **  TESTMODELINE -- process a test mode input line
3839 **
3840 **      Parameters:
3841 **              line -- the input line.
3842 **              e -- the current environment.
3843 **      Syntax:
3844 **              #  a comment
3845 **              .X process X as a configuration line
3846 **              =X dump a configuration item (such as mailers)
3847 **              $X dump a macro or class
3848 **              /X try an activity
3849 **              X  normal process through rule set X
3850 */
3851
3852 static void
3853 testmodeline(line, e)
3854         char *line;
3855         ENVELOPE *e;
3856 {
3857         register char *p;
3858         char *q;
3859         auto char *delimptr;
3860         int mid;
3861         int i, rs;
3862         STAB *map;
3863         char **s;
3864         struct rewrite *rw;
3865         ADDRESS a;
3866         static int tryflags = RF_COPYNONE;
3867         char exbuf[MAXLINE];
3868         extern unsigned char TokTypeNoC[];
3869
3870         /* skip leading spaces */
3871         while (*line == ' ')
3872                 line++;
3873
3874         switch (line[0])
3875         {
3876           case '#':
3877           case '\0':
3878                 return;
3879
3880           case '?':
3881                 help("-bt", e);
3882                 return;
3883
3884           case '.':             /* config-style settings */
3885                 switch (line[1])
3886                 {
3887                   case 'D':
3888                         mid = macid_parse(&line[2], &delimptr);
3889                         if (mid == 0)
3890                                 return;
3891                         translate_dollars(delimptr);
3892                         macdefine(&e->e_macro, A_TEMP, mid, delimptr);
3893                         break;
3894
3895                   case 'C':
3896                         if (line[2] == '\0')    /* not to call syserr() */
3897                                 return;
3898
3899                         mid = macid_parse(&line[2], &delimptr);
3900                         if (mid == 0)
3901                                 return;
3902                         translate_dollars(delimptr);
3903                         expand(delimptr, exbuf, sizeof exbuf, e);
3904                         p = exbuf;
3905                         while (*p != '\0')
3906                         {
3907                                 register char *wd;
3908                                 char delim;
3909
3910                                 while (*p != '\0' && isascii(*p) && isspace(*p))
3911                                         p++;
3912                                 wd = p;
3913                                 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
3914                                         p++;
3915                                 delim = *p;
3916                                 *p = '\0';
3917                                 if (wd[0] != '\0')
3918                                         setclass(mid, wd);
3919                                 *p = delim;
3920                         }
3921                         break;
3922
3923                   case '\0':
3924                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3925                                              "Usage: .[DC]macro value(s)\n");
3926                         break;
3927
3928                   default:
3929                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3930                                              "Unknown \".\" command %s\n", line);
3931                         break;
3932                 }
3933                 return;
3934
3935           case '=':             /* config-style settings */
3936                 switch (line[1])
3937                 {
3938                   case 'S':             /* dump rule set */
3939                         rs = strtorwset(&line[2], NULL, ST_FIND);
3940                         if (rs < 0)
3941                         {
3942                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3943                                                      "Undefined ruleset %s\n", &line[2]);
3944                                 return;
3945                         }
3946                         rw = RewriteRules[rs];
3947                         if (rw == NULL)
3948                                 return;
3949                         do
3950                         {
3951                                 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3952                                                   'R');
3953                                 s = rw->r_lhs;
3954                                 while (*s != NULL)
3955                                 {
3956                                         xputs(*s++);
3957                                         (void) sm_io_putc(smioout,
3958                                                           SM_TIME_DEFAULT, ' ');
3959                                 }
3960                                 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3961                                                   '\t');
3962                                 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3963                                                   '\t');
3964                                 s = rw->r_rhs;
3965                                 while (*s != NULL)
3966                                 {
3967                                         xputs(*s++);
3968                                         (void) sm_io_putc(smioout,
3969                                                           SM_TIME_DEFAULT, ' ');
3970                                 }
3971                                 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3972                                                   '\n');
3973                         } while ((rw = rw->r_next) != NULL);
3974                         break;
3975
3976                   case 'M':
3977                         for (i = 0; i < MAXMAILERS; i++)
3978                         {
3979                                 if (Mailer[i] != NULL)
3980                                         printmailer(Mailer[i]);
3981                         }
3982                         break;
3983
3984                   case '\0':
3985                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3986                                              "Usage: =Sruleset or =M\n");
3987                         break;
3988
3989                   default:
3990                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3991                                              "Unknown \"=\" command %s\n", line);
3992                         break;
3993                 }
3994                 return;
3995
3996           case '-':             /* set command-line-like opts */
3997                 switch (line[1])
3998                 {
3999                   case 'd':
4000                         tTflag(&line[2]);
4001                         break;
4002
4003                   case '\0':
4004                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4005                                              "Usage: -d{debug arguments}\n");
4006                         break;
4007
4008                   default:
4009                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4010                                              "Unknown \"-\" command %s\n", line);
4011                         break;
4012                 }
4013                 return;
4014
4015           case '$':
4016                 if (line[1] == '=')
4017                 {
4018                         mid = macid(&line[2]);
4019                         if (mid != 0)
4020                                 stabapply(dump_class, mid);
4021                         return;
4022                 }
4023                 mid = macid(&line[1]);
4024                 if (mid == 0)
4025                         return;
4026                 p = macvalue(mid, e);
4027                 if (p == NULL)
4028                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4029                                              "Undefined\n");
4030                 else
4031                 {
4032                         xputs(p);
4033                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4034                                              "\n");
4035                 }
4036                 return;
4037
4038           case '/':             /* miscellaneous commands */
4039                 p = &line[strlen(line)];
4040                 while (--p >= line && isascii(*p) && isspace(*p))
4041                         *p = '\0';
4042                 p = strpbrk(line, " \t");
4043                 if (p != NULL)
4044                 {
4045                         while (isascii(*p) && isspace(*p))
4046                                 *p++ = '\0';
4047                 }
4048                 else
4049                         p = "";
4050                 if (line[1] == '\0')
4051                 {
4052                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4053                                              "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4054                         return;
4055                 }
4056                 if (sm_strcasecmp(&line[1], "quit") == 0)
4057                 {
4058                         CurEnv->e_id = NULL;
4059                         finis(true, true, ExitStat);
4060                         /* NOTREACHED */
4061                 }
4062                 if (sm_strcasecmp(&line[1], "mx") == 0)
4063                 {
4064 #if NAMED_BIND
4065                         /* look up MX records */
4066                         int nmx;
4067                         auto int rcode;
4068                         char *mxhosts[MAXMXHOSTS + 1];
4069
4070                         if (*p == '\0')
4071                         {
4072                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4073                                                      "Usage: /mx address\n");
4074                                 return;
4075                         }
4076                         nmx = getmxrr(p, mxhosts, NULL, false, &rcode, true,
4077                                       NULL);
4078                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4079                                              "getmxrr(%s) returns %d value(s):\n",
4080                                 p, nmx);
4081                         for (i = 0; i < nmx; i++)
4082                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4083                                                      "\t%s\n", mxhosts[i]);
4084 #else /* NAMED_BIND */
4085                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4086                                              "No MX code compiled in\n");
4087 #endif /* NAMED_BIND */
4088                 }
4089                 else if (sm_strcasecmp(&line[1], "canon") == 0)
4090                 {
4091                         char host[MAXHOSTNAMELEN];
4092
4093                         if (*p == '\0')
4094                         {
4095                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4096                                                      "Usage: /canon address\n");
4097                                 return;
4098                         }
4099                         else if (sm_strlcpy(host, p, sizeof host) >= sizeof host)
4100                         {
4101                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4102                                                      "Name too long\n");
4103                                 return;
4104                         }
4105                         (void) getcanonname(host, sizeof host, !HasWildcardMX,
4106                                             NULL);
4107                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4108                                              "getcanonname(%s) returns %s\n",
4109                                              p, host);
4110                 }
4111                 else if (sm_strcasecmp(&line[1], "map") == 0)
4112                 {
4113                         auto int rcode = EX_OK;
4114                         char *av[2];
4115
4116                         if (*p == '\0')
4117                         {
4118                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4119                                                      "Usage: /map mapname key\n");
4120                                 return;
4121                         }
4122                         for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q));                             q++)
4123                                 continue;
4124                         if (*q == '\0')
4125                         {
4126                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4127                                                      "No key specified\n");
4128                                 return;
4129                         }
4130                         *q++ = '\0';
4131                         map = stab(p, ST_MAP, ST_FIND);
4132                         if (map == NULL)
4133                         {
4134                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4135                                                      "Map named \"%s\" not found\n", p);
4136                                 return;
4137                         }
4138                         if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4139                             !openmap(&(map->s_map)))
4140                         {
4141                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4142                                                      "Map named \"%s\" not open\n", p);
4143                                 return;
4144                         }
4145                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4146                                              "map_lookup: %s (%s) ", p, q);
4147                         av[0] = q;
4148                         av[1] = NULL;
4149                         p = (*map->s_map.map_class->map_lookup)
4150                                         (&map->s_map, q, av, &rcode);
4151                         if (p == NULL)
4152                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4153                                                      "no match (%d)\n",
4154                                                      rcode);
4155                         else
4156                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4157                                                      "returns %s (%d)\n", p,
4158                                                      rcode);
4159                 }
4160                 else if (sm_strcasecmp(&line[1], "try") == 0)
4161                 {
4162                         MAILER *m;
4163                         STAB *st;
4164                         auto int rcode = EX_OK;
4165
4166                         q = strpbrk(p, " \t");
4167                         if (q != NULL)
4168                         {
4169                                 while (isascii(*q) && isspace(*q))
4170                                         *q++ = '\0';
4171                         }
4172                         if (q == NULL || *q == '\0')
4173                         {
4174                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4175                                                      "Usage: /try mailer address\n");
4176                                 return;
4177                         }
4178                         st = stab(p, ST_MAILER, ST_FIND);
4179                         if (st == NULL)
4180                         {
4181                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4182                                                      "Unknown mailer %s\n", p);
4183                                 return;
4184                         }
4185                         m = st->s_mailer;
4186                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4187                                              "Trying %s %s address %s for mailer %s\n",
4188                                      bitset(RF_HEADERADDR, tryflags) ? "header"
4189                                                         : "envelope",
4190                                      bitset(RF_SENDERADDR, tryflags) ? "sender"
4191                                                         : "recipient", q, p);
4192                         p = remotename(q, m, tryflags, &rcode, CurEnv);
4193                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4194                                              "Rcode = %d, addr = %s\n",
4195                                              rcode, p == NULL ? "<NULL>" : p);
4196                         e->e_to = NULL;
4197                 }
4198                 else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4199                 {
4200                         if (*p == '\0')
4201                         {
4202                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4203                                                      "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4204                                 return;
4205                         }
4206                         for (; *p != '\0'; p++)
4207                         {
4208                                 switch (*p)
4209                                 {
4210                                   case 'H':
4211                                   case 'h':
4212                                         tryflags |= RF_HEADERADDR;
4213                                         break;
4214
4215                                   case 'E':
4216                                   case 'e':
4217                                         tryflags &= ~RF_HEADERADDR;
4218                                         break;
4219
4220                                   case 'S':
4221                                   case 's':
4222                                         tryflags |= RF_SENDERADDR;
4223                                         break;
4224
4225                                   case 'R':
4226                                   case 'r':
4227                                         tryflags &= ~RF_SENDERADDR;
4228                                         break;
4229                                 }
4230                         }
4231                         exbuf[0] = bitset(RF_HEADERADDR, tryflags) ? 'h' : 'e';
4232                         exbuf[1] = ' ';
4233                         exbuf[2] = bitset(RF_SENDERADDR, tryflags) ? 's' : 'r';
4234                         exbuf[3] = '\0';
4235                         macdefine(&e->e_macro, A_TEMP,
4236                                 macid("{addr_type}"), exbuf);
4237                 }
4238                 else if (sm_strcasecmp(&line[1], "parse") == 0)
4239                 {
4240                         if (*p == '\0')
4241                         {
4242                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4243                                                      "Usage: /parse address\n");
4244                                 return;
4245                         }
4246                         q = crackaddr(p, e);
4247                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4248                                              "Cracked address = ");
4249                         xputs(q);
4250                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4251                                              "\nParsing %s %s address\n",
4252                                              bitset(RF_HEADERADDR, tryflags) ?
4253                                                         "header" : "envelope",
4254                                              bitset(RF_SENDERADDR, tryflags) ?
4255                                                         "sender" : "recipient");
4256                         if (parseaddr(p, &a, tryflags, '\0', NULL, e, true)
4257                             == NULL)
4258                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4259                                                      "Cannot parse\n");
4260                         else if (a.q_host != NULL && a.q_host[0] != '\0')
4261                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4262                                                      "mailer %s, host %s, user %s\n",
4263                                                      a.q_mailer->m_name,
4264                                                      a.q_host,
4265                                                      a.q_user);
4266                         else
4267                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4268                                                      "mailer %s, user %s\n",
4269                                                      a.q_mailer->m_name,
4270                                                      a.q_user);
4271                         e->e_to = NULL;
4272                 }
4273                 else
4274                 {
4275                         (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4276                                              "Unknown \"/\" command %s\n",
4277                                              line);
4278                 }
4279                 return;
4280         }
4281
4282         for (p = line; isascii(*p) && isspace(*p); p++)
4283                 continue;
4284         q = p;
4285         while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4286                 p++;
4287         if (*p == '\0')
4288         {
4289                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4290                                      "No address!\n");
4291                 return;
4292         }
4293         *p = '\0';
4294         if (invalidaddr(p + 1, NULL, true))
4295                 return;
4296         do
4297         {
4298                 register char **pvp;
4299                 char pvpbuf[PSBUFSIZE];
4300
4301                 pvp = prescan(++p, ',', pvpbuf, sizeof pvpbuf,
4302                               &delimptr, ConfigLevel >= 9 ? TokTypeNoC : NULL);
4303                 if (pvp == NULL)
4304                         continue;
4305                 p = q;
4306                 while (*p != '\0')
4307                 {
4308                         int status;
4309
4310                         rs = strtorwset(p, NULL, ST_FIND);
4311                         if (rs < 0)
4312                         {
4313                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4314                                                      "Undefined ruleset %s\n",
4315                                                      p);
4316                                 break;
4317                         }
4318                         status = REWRITE(pvp, rs, e);
4319                         if (status != EX_OK)
4320                                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4321                                                      "== Ruleset %s (%d) status %d\n",
4322                                                      p, rs, status);
4323                         while (*p != '\0' && *p++ != ',')
4324                                 continue;
4325                 }
4326         } while (*(p = delimptr) != '\0');
4327 }
4328
4329 static void
4330 dump_class(s, id)
4331         register STAB *s;
4332         int id;
4333 {
4334         if (s->s_symtype != ST_CLASS)
4335                 return;
4336         if (bitnset(bitidx(id), s->s_class))
4337                 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4338                                      "%s\n", s->s_name);
4339 }
4340
4341 /*
4342 **  An exception type used to create QuickAbort exceptions.
4343 **  This is my first cut at converting QuickAbort from longjmp to exceptions.
4344 **  These exceptions have a single integer argument, which is the argument
4345 **  to longjmp in the original code (either 1 or 2).  I don't know the
4346 **  significance of 1 vs 2: the calls to setjmp don't care.
4347 */
4348
4349 const SM_EXC_TYPE_T EtypeQuickAbort =
4350 {
4351         SmExcTypeMagic,
4352         "E:mta.quickabort",
4353         "i",
4354         sm_etype_printf,
4355         "quick abort %0",
4356 };