Update zoneinfo database.
[dragonfly/netmp.git] / contrib / sendmail / src / main.c
blob612ec0ae2335c79a72578b0e258b50ac3ab09612
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.
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.
12 * $DragonFly: src/contrib/sendmail/src/Attic/main.c,v 1.3 2003/12/22 04:04:23 drhodus Exp $
15 #define _DEFINE
16 #include <sendmail.h>
17 #include <sm/xtrap.h>
18 #include <sm/signal.h>
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 */
29 SM_RCSID("@(#)$Id: main.c,v 8.887.2.27 2003/08/04 17:23:37 ca Exp $")
32 #if NETINET || NETINET6
33 # include <arpa/inet.h>
34 #endif /* NETINET || NETINET6 */
36 /* for getcfname() */
37 #include <sendmail/pathnames.h>
39 static SM_DEBUG_T
40 DebugNoPRestart = SM_DEBUG_INITIALIZER("no_persistent_restart",
41 "@(#)$Debug: no_persistent_restart - don't restart, log only $");
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 */
57 ** SENDMAIL -- Post mail to a set of destinations.
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.
64 ** Sendmail is driven by settings read in from /etc/mail/sendmail.cf
65 ** (read by readcf.c).
67 ** Usage:
68 ** /usr/lib/sendmail [flags] addr ...
70 ** See the associated documentation for details.
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.
85 ** Gregory Neil Shapiro,
86 ** Worcester Polytechnic Institute (until 3/98).
87 ** Sendmail, Inc. (3/98 - present).
89 ** Claus Assmann,
90 ** Sendmail, Inc. (12/98 - present).
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 */
103 #ifdef NGROUPS_MAX
104 GIDSET_T InitialGidSet[NGROUPS_MAX];
105 #endif /* NGROUPS_MAX */
107 #define MAXCONFIGLEVEL 10 /* highest config version level known */
109 #if SASL
110 static sasl_callback_t srvcallbacks[] =
112 { SASL_CB_VERIFYFILE, &safesaslfile, NULL },
113 { SASL_CB_PROXY_POLICY, &proxy_policy, NULL },
114 { SASL_CB_LIST_END, NULL, NULL }
116 #endif /* SASL */
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 */
127 /* Some options are dangerous to allow users to use in non-submit mode */
128 #define CHECK_AGAINST_OPMODE(cmd) \
130 if (extraprivs && \
131 OpMode != MD_DELIVER && OpMode != MD_SMTP && \
132 OpMode != MD_ARPAFTP && \
133 OpMode != MD_VERIFY && OpMode != MD_TEST) \
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; \
140 if (extraprivs && queuerun) \
142 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, \
143 "WARNING: Ignoring submission mode -%c option with -q\n", \
144 (cmd)); \
145 break; \
150 main(argc, argv, envp)
151 int argc;
152 char **argv;
153 char **envp;
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 */
208 #if USE_ENVIRON
209 envp = environ;
210 #endif /* USE_ENVIRON */
212 /* turn off profiling */
213 SM_PROF(0);
215 /* install default exception handler */
216 sm_exc_newthread(fatal_error);
218 /* set the default in/out channel so errors reported to screen */
219 InChannel = smioin;
220 OutChannel = smioout;
223 ** Check to see if we reentered.
224 ** This would normally happen if e_putheader or e_putbody
225 ** were NULL when invoked.
228 if (starttime != 0)
230 syserr("main: reentered!");
231 abort();
233 starttime = curtime();
235 /* avoid null pointer dereferences */
236 TermEscape.te_rv_on = TermEscape.te_rv_off = "";
238 RealUid = getuid();
239 RealGid = getgid();
241 /* Check if sendmail is running with extra privs */
242 extraprivs = (RealUid != 0 &&
243 (geteuid() != getuid() || getegid() != getgid()));
245 CurrentPid = getpid();
247 /* get whatever .cf file is right for the opmode */
248 cftype = SM_GET_RIGHT_CF;
250 /* in 4.4BSD, the table can be huge; impose a reasonable limit */
251 DtableSize = getdtsize();
252 if (DtableSize > 256)
253 DtableSize = 256;
256 ** Be sure we have enough file descriptors.
257 ** But also be sure that 0, 1, & 2 are open.
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;
272 i = DtableSize;
273 while (--i > 0)
275 if (i != STDIN_FILENO && i != STDOUT_FILENO &&
276 i != STDERR_FILENO)
277 (void) close(i);
279 errno = 0;
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 */
293 ** Seed the random number generator.
294 ** Used for queue file names, picking a queue directory, and
295 ** MX randomization.
298 seed_random();
300 /* do machine-dependent initializations */
301 init_md(argc, argv);
304 SyslogPrefixLen = PIDLEN + (MAXQFNAME - 3) + SL_FUDGE + SLDLL;
306 /* reset status from syserr() calls for missing file descriptors */
307 Errors = 0;
308 ExitStat = EX_OK;
310 SubmitMode = SUBMIT_UNKNOWN;
311 #if XDEBUG
312 checkfd012("after openlog");
313 #endif /* XDEBUG */
315 tTsetup(tTdvect, sizeof tTdvect, "0-99.1,*_trace_*.1");
317 #ifdef NGROUPS_MAX
318 /* save initial group set for future checks */
319 i = getgroups(NGROUPS_MAX, InitialGidSet);
320 if (i <= 0)
322 InitialGidSet[0] = (GID_T) -1;
323 i = 0;
325 while (i < NGROUPS_MAX)
326 InitialGidSet[i++] = InitialGidSet[0];
327 #endif /* NGROUPS_MAX */
329 /* drop group id privileges (RunAsUser not yet set) */
330 dp = drop_privileges(false);
331 setstat(dp);
333 #ifdef SIGUSR1
334 /* Only allow root (or non-set-*-ID binaries) to use SIGUSR1 */
335 if (!extraprivs)
337 /* arrange to dump state on user-1 signal */
338 (void) sm_signal(SIGUSR1, sigusr1);
340 else
342 /* ignore user-1 signal */
343 (void) sm_signal(SIGUSR1, SIG_IGN);
345 #endif /* SIGUSR1 */
347 /* initialize for setproctitle */
348 initsetproctitle(argc, argv, envp);
350 /* Handle any non-getoptable constructions. */
351 obsolete(argv);
354 ** Do a quick prescan of the argument list.
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;
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 */
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)
401 switch (j)
403 case 'b': /* operations mode */
404 j = (optarg == NULL) ? ' ' : *optarg;
405 switch (j)
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;
422 case MD_FREEZE:
423 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
424 "Frozen configurations unsupported\n");
425 return EX_USAGE;
427 default:
428 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
429 "Invalid operation mode %c\n",
431 return EX_USAGE;
433 break;
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;
443 case 'G': /* relay (gateway) submission */
444 SubmitMode = SUBMIT_MTA;
445 break;
447 case 'L':
448 if (optarg == NULL)
450 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
451 "option requires an argument -- '%c'",
452 (char) j);
453 return EX_USAGE;
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;
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;
471 opterr = 1;
473 /* Don't leak queue information via debug flags */
474 if (extraprivs && queuerun && debug)
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);
482 #if LOG
483 if (sysloglabel != NULL)
485 /* Sanitize the string */
486 for (p = sysloglabel; *p != '\0'; p++)
488 if (!isascii(*p) || !isprint(*p) || *p == '%')
489 *p = '*';
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 */
498 #endif /* LOG */
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);
509 ** Set default values for variables.
510 ** These cannot be in initialized data space.
513 setdefaults(&BlankEnvelope);
514 initmacros(&BlankEnvelope);
516 /* reset macro */
517 set_op_mode(OpMode);
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);
526 RealUserName = rnamebuf;
528 if (tTd(0, 101))
530 sm_dprintf("Version %s\n", Version);
531 finis(false, true, EX_OK);
532 /* NOTREACHED */
536 ** if running non-set-user-ID binary as non-root, pretend
537 ** we are the RunAsUid
540 if (RealUid != 0 && geteuid() == RealUid)
542 if (tTd(47, 1))
543 sm_dprintf("Non-set-user-ID binary: RunAsUid = RealUid = %d\n",
544 (int) RealUid);
545 RunAsUid = RealUid;
547 else if (geteuid() != 0)
548 RunAsUid = geteuid();
550 EffGid = getegid();
551 if (RealUid != 0 && EffGid == RealGid)
552 RunAsGid = RealGid;
554 if (tTd(47, 5))
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);
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; )
572 int h;
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;
582 SaveArgv[i] = NULL;
584 if (tTd(0, 1))
586 extern char *CompileOptions[];
588 sm_dprintf("Version %s\n Compiled with:", Version);
589 sm_printoptions(CompileOptions);
591 if (tTd(0, 10))
593 extern char *OsCompileOptions[];
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 */
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);
610 if (tTd(0, 12))
612 extern char *SmCompileOptions[];
614 sm_dprintf(" libsm Defines:");
615 sm_printoptions(SmCompileOptions);
618 if (tTd(0, 13))
620 extern char *FFRCompileOptions[];
622 sm_dprintf(" FFR Defines:");
623 sm_printoptions(FFRCompileOptions);
626 /* clear sendmail's environment */
627 ExternalEnviron = environ;
628 emptyenviron[0] = NULL;
629 environ = emptyenviron;
632 ** restore any original TZ setting until TimeZoneSpec has been
633 ** determined - or early log messages may get bogus time stamps
636 if ((p = getextenv("TZ")) != NULL)
638 char *tz;
639 int tzlen;
641 /* XXX check for reasonable length? */
642 tzlen = strlen(p) + 4;
643 tz = xalloc(tzlen);
644 (void) sm_strlcpyn(tz, tzlen, 2, "TZ=", p);
646 /* XXX check return code? */
647 (void) putenv(tz);
650 /* prime the child environment */
651 setuserenv("AGENT", "sendmail");
653 (void) sm_signal(SIGPIPE, SIG_IGN);
654 OldUmask = umask(022);
655 FullName = getextenv("NAME");
656 if (FullName != NULL)
657 FullName = newstr(FullName);
660 ** Initialize name server if it is going to be used.
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 */
683 errno = 0;
684 from = NULL;
686 /* initialize some macros, etc. */
687 init_vendor_macros(&BlankEnvelope);
689 /* version */
690 macdefine(&BlankEnvelope.e_macro, A_PERM, 'v', Version);
692 /* hostname */
693 hp = myhostname(jbuf, sizeof jbuf);
694 if (jbuf[0] != '\0')
696 struct utsname utsname;
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);
704 p = strchr(jbuf, '.');
705 if (p != NULL)
707 if (p[1] != '\0')
709 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'm',
710 &p[1]);
712 while (p != NULL && strchr(&p[1], '.') != NULL)
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, '.');
723 if (uname(&utsname) >= 0)
724 p = utsname.nodename;
725 else
727 if (tTd(0, 22))
728 sm_dprintf("uname failed (%s)\n",
729 sm_errstring(errno));
730 makelower(jbuf);
731 p = jbuf;
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);
739 if (hp != NULL)
741 for (av = hp->h_aliases; av != NULL && *av != NULL; av++)
743 if (tTd(0, 4))
744 sm_dprintf("\ta.k.a.: %s\n", *av);
745 setclass('w', *av);
747 #if NETINET || NETINET6
748 for (i = 0; i >= 0 && hp->h_addr_list[i] != NULL; i++)
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];
760 ipbuf[0] = '\0';
761 switch (hp->h_addrtype)
763 # if NETINET
764 case AF_INET:
765 if (hp->h_length != INADDRSZ)
766 break;
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 */
774 # if NETINET6
775 case AF_INET6:
776 if (hp->h_length != IN6ADDRSZ)
777 break;
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 */
787 if (ipbuf[0] == '\0')
788 break;
790 if (tTd(0, 4))
791 sm_dprintf("\ta.k.a.: %s\n", ipbuf);
792 setclass('w', ipbuf);
794 #endif /* NETINET || NETINET6 */
795 #if NETINET6
796 freehostent(hp);
797 hp = NULL;
798 #endif /* NETINET6 */
801 /* current time */
802 macdefine(&BlankEnvelope.e_macro, A_TEMP, 'b', arpadate((char *) NULL));
804 /* current load average */
805 sm_getla();
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 */
815 ** Crack argv.
818 optind = 1;
819 while ((j = getopt(argc, argv, OPTIONS)) != -1)
821 switch (j)
823 case 'b': /* operations mode */
824 /* already done */
825 break;
827 case 'A': /* use Alternate sendmail/submit.cf */
828 cftype = optarg[0] == 'c' ? SM_GET_SUBMIT_CF
829 : SM_GET_SENDMAIL_CF;
830 break;
832 case 'B': /* body type */
833 CHECK_AGAINST_OPMODE(j);
834 BlankEnvelope.e_bodytype = newstr(optarg);
835 break;
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;
846 case 'd': /* debugging */
847 /* already done */
848 break;
850 case 'f': /* from address */
851 case 'r': /* obsolete -f flag */
852 CHECK_AGAINST_OPMODE(j);
853 if (from != NULL)
855 usrerr("More than one \"from\" person");
856 ExitStat = EX_USAGE;
857 break;
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;
867 case 'F': /* set full name */
868 CHECK_AGAINST_OPMODE(j);
869 FullName = newstr(optarg);
870 break;
872 case 'G': /* relay (gateway) submission */
873 /* already set */
874 CHECK_AGAINST_OPMODE(j);
875 break;
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);
885 if (*ep)
887 usrerr("Bad hop count (%s)", optarg);
888 ExitStat = EX_USAGE;
890 break;
892 case 'L': /* program label */
893 /* already set */
894 break;
896 case 'n': /* don't alias */
897 CHECK_AGAINST_OPMODE(j);
898 NoAlias = true;
899 break;
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)
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
921 usrerr("Invalid -N argument");
922 ExitStat = EX_USAGE;
925 break;
927 case 'o': /* set option */
928 setoption(*optarg, optarg + 1, false, true,
929 &BlankEnvelope);
930 break;
932 case 'O': /* set option (long form) */
933 setoption(' ', optarg, false, true, &BlankEnvelope);
934 break;
936 case 'p': /* set protocol */
937 CHECK_AGAINST_OPMODE(j);
938 p = strchr(optarg, ':');
939 if (p != NULL)
941 *p++ = '\0';
942 if (*p != '\0')
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);
951 if (*optarg != '\0')
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);
959 break;
961 #if _FFR_QUARANTINE
962 case 'Q': /* change quarantining on queued items */
963 /* sanity check */
964 if (OpMode != MD_DELIVER &&
965 OpMode != MD_QUEUERUN)
967 usrerr("Can not use -Q with -b%c", OpMode);
968 ExitStat = EX_USAGE;
969 break;
972 if (OpMode == MD_DELIVER)
973 set_op_mode(MD_QUEUERUN);
975 FullName = NULL;
977 quarantining = newstr(optarg);
978 break;
979 #endif /* _FFR_QUARANTINE */
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)
990 usrerr("Can not use -q with -b%c", OpMode);
991 ExitStat = EX_USAGE;
992 break;
995 /* don't override -bd, -bD or -bp */
996 if (OpMode == MD_DELIVER)
997 set_op_mode(MD_QUEUERUN);
999 FullName = NULL;
1000 negate = optarg[0] == '!';
1001 if (negate)
1003 /* negate meaning of pattern match */
1004 optarg++; /* skip '!' for next switch */
1007 switch (optarg[0])
1009 case 'G': /* Limit by queue group name */
1010 if (negate)
1012 usrerr("Can not use -q!G");
1013 ExitStat = EX_USAGE;
1014 break;
1016 if (queuegroup != NULL)
1018 usrerr("Can not use multiple -qG options");
1019 ExitStat = EX_USAGE;
1020 break;
1022 queuegroup = newstr(&optarg[1]);
1023 break;
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;
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;
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;
1049 case 'f': /* foreground queue run */
1050 foregroundqueue = true;
1051 break;
1053 #if _FFR_QUARANTINE
1054 case 'Q': /* Limit by quarantine message */
1055 if (optarg[1] != '\0')
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;
1063 QueueMode = QM_QUARANTINE;
1064 break;
1066 case 'L': /* act on lost items */
1067 QueueMode = QM_LOST;
1068 break;
1069 #endif /* _FFR_QUARANTINE */
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 */
1080 default:
1081 i = Errors;
1082 QueueIntvl = convtime(optarg, 'm');
1083 if (QueueIntvl < 0)
1085 usrerr("Invalid -q value");
1086 ExitStat = EX_USAGE;
1089 /* check for bad conversion */
1090 if (i < Errors)
1091 ExitStat = EX_USAGE;
1092 break;
1094 break;
1096 case 'R': /* DSN RET: what to return */
1097 CHECK_AGAINST_OPMODE(j);
1098 if (bitset(EF_RET_PARAM, BlankEnvelope.e_flags))
1100 usrerr("Duplicate -R flag");
1101 ExitStat = EX_USAGE;
1102 break;
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)
1109 usrerr("Invalid -R value");
1110 ExitStat = EX_USAGE;
1112 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1113 macid("{dsn_ret}"), optarg);
1114 break;
1116 case 't': /* read recipients from message */
1117 CHECK_AGAINST_OPMODE(j);
1118 GrabTo = true;
1119 break;
1121 case 'V': /* DSN ENVID: set "original" envelope id */
1122 CHECK_AGAINST_OPMODE(j);
1123 if (!xtextok(optarg))
1125 usrerr("Invalid syntax in -V flag");
1126 ExitStat = EX_USAGE;
1128 else
1130 BlankEnvelope.e_envid = newstr(optarg);
1131 macdefine(&BlankEnvelope.e_macro, A_TEMP,
1132 macid("{dsn_envid}"), optarg);
1134 break;
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)
1152 syserr("cannot open %s", optarg);
1153 ExitStat = EX_CANTCREAT;
1154 break;
1156 (void) sm_io_setvbuf(TrafficLogFile, SM_TIME_DEFAULT,
1157 NULL, SM_IO_LBF, 0);
1158 break;
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;
1169 case 'e': /* error message disposition */
1170 case 'M': /* define macro */
1171 setoption(j, optarg, false, true, &BlankEnvelope);
1172 break;
1174 case 's': /* save From lines in headers */
1175 setoption('f', "T", false, true, &BlankEnvelope);
1176 break;
1178 #ifdef DBM
1179 case 'I': /* initialize alias DBM file */
1180 set_op_mode(MD_INITALIAS);
1181 break;
1182 #endif /* DBM */
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) */
1195 default:
1196 finis(true, true, EX_USAGE);
1197 /* NOTREACHED */
1198 break;
1202 /* if we've had errors so far, exit now */
1203 if ((ExitStat != EX_OK && OpMode != MD_TEST) ||
1204 ExitStat == EX_OSERR)
1206 finis(false, true, ExitStat);
1207 /* NOTREACHED */
1210 if (bitset(SUBMIT_MTA, SubmitMode))
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");
1217 else if (OpMode == MD_DELIVER || OpMode == MD_SMTP)
1219 SubmitMode = SUBMIT_MSA;
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");
1228 ** Do basic initialization.
1229 ** Read system control file.
1230 ** Extract special fields for local use.
1233 #if XDEBUG
1234 checkfd012("before readcf");
1235 #endif /* XDEBUG */
1236 vendor_pre_defaults(&BlankEnvelope);
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);
1245 /* now we can complain about missing fds */
1246 if (MissingFds != 0 && LogLevel > 8)
1248 char mbuf[MAXLINE];
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);
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));
1264 /* Remove the ability for a normal user to send signals */
1265 if (RealUid != 0 && RealUid != geteuid())
1267 uid_t new_uid = geteuid();
1269 #if HASSETREUID
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).
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)
1283 syserr("main: setreuid(%d, %d) failed",
1284 (int) new_uid, (int) geteuid());
1285 finis(false, true, EX_OSERR);
1286 /* NOTREACHED */
1288 if (tTd(47, 10))
1289 sm_dprintf("Now running as e/ruid %d:%d\n",
1290 (int) geteuid(), (int) getuid());
1291 #else /* HASSETREUID */
1293 ** Have to change both effective and real so need to
1294 ** change them both to effective to keep privs.
1297 if (tTd(47, 5))
1298 sm_dprintf("Changing uid to %d\n", (int) new_uid);
1299 if (setuid(new_uid) < 0)
1301 syserr("main: setuid(%d) failed", (int) new_uid);
1302 finis(false, true, EX_OSERR);
1303 /* NOTREACHED */
1305 if (tTd(47, 10))
1306 sm_dprintf("Now running as e/ruid %d:%d\n",
1307 (int) geteuid(), (int) getuid());
1308 #endif /* HASSETREUID */
1311 #if NAMED_BIND
1312 if (FallBackMX != NULL)
1313 (void) getfallbackmxrr(FallBackMX);
1314 #endif /* NAMED_BIND */
1316 if (SuperSafe == SAFE_INTERACTIVE && CurEnv->e_sendmode != SM_DELIVER)
1318 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1319 "WARNING: SuperSafe=interactive should only be used with\n DeliveryMode=interactive\n");
1322 if (UseMSP && (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON))
1324 usrerr("Mail submission program cannot be used as daemon");
1325 finis(false, true, EX_USAGE);
1328 if (OpMode == MD_DELIVER || OpMode == MD_SMTP ||
1329 OpMode == MD_QUEUERUN || OpMode == MD_ARPAFTP ||
1330 OpMode == MD_DAEMON || OpMode == MD_FGDAEMON)
1331 makeworkgroups();
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);
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();
1347 /* initialize mailbox database */
1348 i = sm_mbdb_initialize(Mbdb);
1349 if (i != EX_OK)
1351 usrerr("Can't initialize mailbox database \"%s\": %s",
1352 Mbdb, sm_strexit(i));
1353 ExitStat = i;
1356 /* avoid denial-of-service attacks */
1357 resetlimits();
1359 if (OpMode == MD_TEST)
1361 /* can't be done after readcf if RunAs* is used */
1362 dp = drop_privileges(true);
1363 if (dp != EX_OK)
1365 finis(false, true, dp);
1366 /* NOTREACHED */
1369 else if (OpMode != MD_DAEMON && OpMode != MD_FGDAEMON)
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))
1376 usrerr("Mail submission program must have RunAsUser set to non root user");
1377 finis(false, true, EX_CONFIG);
1378 /* NOTREACHED */
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 */
1388 ** Find our real host name for future logging.
1391 authinfo = getauthinfo(STDIN_FILENO, &forged);
1392 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
1394 /* suppress error printing if errors mailed back or whatever */
1395 if (BlankEnvelope.e_errormode != EM_PRINT)
1396 HoldErrs = true;
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);
1403 /* probe interfaces and locate any additional names */
1404 if (DontProbeInterfaces != DPI_PROBENONE)
1405 load_if_names();
1407 if (tTd(0, 10))
1409 char pidpath[MAXPATHLEN];
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);
1418 if (tTd(0, 1))
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");
1433 ** Do more command line checking -- these are things that
1434 ** have to modify the results of reading the config file.
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);
1449 /* check body type for legality */
1450 i = check_bodytype(BlankEnvelope.e_bodytype);
1451 if (i == BODYTYPE_ILLEGAL)
1453 usrerr("Illegal body type %s", BlankEnvelope.e_bodytype);
1454 BlankEnvelope.e_bodytype = NULL;
1456 else if (i != BODYTYPE_NONE)
1457 SevenBitInput = (i == BODYTYPE_7BIT);
1459 /* tweak default DSN notifications */
1460 if (DefaultNotify == 0)
1461 DefaultNotify = QPINGONFAILURE|QPINGONDELAY;
1463 /* be sure we don't pick up bogus HOSTALIASES environment variable */
1464 if (OpMode == MD_QUEUERUN && RealUid != 0)
1465 (void) unsetenv("HOSTALIASES");
1467 /* check for sane configuration level */
1468 if (ConfigLevel > MAXCONFIGLEVEL)
1470 syserr("Warning: .cf version level (%d) exceeds sendmail version %s functionality (%d)",
1471 ConfigLevel, Version, MAXCONFIGLEVEL);
1474 /* need MCI cache to have persistence */
1475 if (HostStatDir != NULL && MaxMciCache == 0)
1477 HostStatDir = NULL;
1478 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1479 "Warning: HostStatusDirectory disabled with ConnectionCacheSize = 0\n");
1482 /* need HostStatusDir in order to have SingleThreadDelivery */
1483 if (SingleThreadDelivery && HostStatDir == NULL)
1485 SingleThreadDelivery = false;
1486 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1487 "Warning: HostStatusDirectory required for SingleThreadDelivery\n");
1490 /* check for permissions */
1491 if (RealUid != 0 &&
1492 RealUid != TrustedUid)
1494 char *action = NULL;
1496 switch (OpMode)
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;
1508 /* but not persistent queue runners */
1509 if (action == NULL)
1510 action = "start a queue runner daemon";
1511 /* FALLTHROUGH */
1513 case MD_PURGESTAT:
1514 if (action == NULL)
1515 action = "purge host status";
1516 /* FALLTHROUGH */
1518 case MD_DAEMON:
1519 case MD_FGDAEMON:
1520 if (action == NULL)
1521 action = "run daemon";
1523 if (tTd(65, 1))
1524 sm_dprintf("Deny user %d attempt to %s\n",
1525 (int) RealUid, action);
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;
1537 case MD_VERIFY:
1538 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags))
1541 ** If -bv and RestrictExpand,
1542 ** drop privs to prevent normal
1543 ** users from reading private
1544 ** aliases/forwards/:include:s
1547 if (tTd(65, 1))
1548 sm_dprintf("Drop privs for user %d attempt to expand (RestrictExpand)\n",
1549 (int) RealUid);
1551 dp = drop_privileges(true);
1553 /* Fake address safety */
1554 if (tTd(65, 1))
1555 sm_dprintf("Faking DontBlameSendmail=NonRootSafeAddr\n");
1556 setbitn(DBS_NONROOTSAFEADDR, DontBlameSendmail);
1558 if (dp != EX_OK)
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 */
1568 break;
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;
1578 case MD_INITALIAS:
1579 if (!wordinclass(RealUserName, 't'))
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 */
1593 if (UseMSP)
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 */
1601 /* FALLTHROUGH */
1603 default:
1604 if (bitset(PRIV_RESTRICTEXPAND, PrivacyFlags) &&
1605 Verbose != 0)
1608 ** If -v and RestrictExpand, reset
1609 ** Verbose to prevent normal users
1610 ** from seeing the expansion of
1611 ** aliases/forwards/:include:s
1614 if (tTd(65, 1))
1615 sm_dprintf("Dropping verbosity for user %d (RestrictExpand)\n",
1616 (int) RealUid);
1617 Verbose = 0;
1619 break;
1623 if (MeToo)
1624 BlankEnvelope.e_flags |= EF_METOO;
1626 switch (OpMode)
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;
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;
1648 case MD_FGDAEMON:
1649 run_in_foreground = true;
1650 set_op_mode(MD_DAEMON);
1651 /* FALLTHROUGH */
1653 case MD_DAEMON:
1654 vendor_daemon_setup(&BlankEnvelope);
1656 /* remove things that don't make sense in daemon mode */
1657 FullName = NULL;
1658 GrabTo = false;
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;
1666 case MD_INITALIAS:
1667 Verbose = 2;
1668 BlankEnvelope.e_errormode = EM_PRINT;
1669 HoldErrs = false;
1670 /* FALLTHROUGH */
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;
1679 /* special considerations for FullName */
1680 if (FullName != NULL)
1682 char *full = NULL;
1684 /* full names can't have newlines */
1685 if (strchr(FullName, '\n') != NULL)
1687 full = newstr(denlstring(FullName, true, true));
1688 FullName = full;
1691 /* check for characters that may have to be quoted */
1692 if (!rfc822_string(FullName))
1695 ** Quote a full name with special characters
1696 ** as a comment so crackaddr() doesn't destroy
1697 ** the name portion of the address.
1700 FullName = addquotes(FullName, NULL);
1701 if (full != NULL)
1702 sm_free(full); /* XXX */
1706 /* do heuristic mode adjustment */
1707 if (Verbose)
1709 /* turn off noconnect option */
1710 setoption('c', "F", true, false, &BlankEnvelope);
1712 /* turn on interactive delivery */
1713 setoption('d', "", true, false, &BlankEnvelope);
1716 #ifdef VENDOR_CODE
1717 /* check for vendor mismatch */
1718 if (VendorCode != VENDOR_CODE)
1720 message("Warning: .cf file vendor code mismatch: sendmail expects vendor %s, .cf file vendor is %s",
1721 getvendor(VENDOR_CODE), getvendor(VendorCode));
1723 #endif /* VENDOR_CODE */
1725 /* check for out of date configuration level */
1726 if (ConfigLevel < MAXCONFIGLEVEL)
1728 message("Warning: .cf file is out of date: sendmail %s supports version %d, .cf file is version %d",
1729 Version, MAXCONFIGLEVEL, ConfigLevel);
1732 if (ConfigLevel < 3)
1733 UseErrorsTo = true;
1735 /* set options that were previous macros */
1736 if (SmtpGreeting == NULL)
1738 if (ConfigLevel < 7 &&
1739 (p = macvalue('e', &BlankEnvelope)) != NULL)
1740 SmtpGreeting = newstr(p);
1741 else
1742 SmtpGreeting = "\201j Sendmail \201v ready at \201b";
1744 if (UnixFromLine == NULL)
1746 if (ConfigLevel < 7 &&
1747 (p = macvalue('l', &BlankEnvelope)) != NULL)
1748 UnixFromLine = newstr(p);
1749 else
1750 UnixFromLine = "From \201g \201d";
1752 SmtpError[0] = '\0';
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);
1764 /* make certain that this name is part of the $=w class */
1765 setclass('w', MyHostName);
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);
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");
1781 st = stab("prog", ST_MAILER, ST_FIND);
1782 if (st == NULL)
1783 syserr("No prog mailer defined");
1784 else
1786 ProgMailer = st->s_mailer;
1787 clrbitn(M_MUSER, ProgMailer->m_flags);
1790 st = stab("*file*", ST_MAILER, ST_FIND);
1791 if (st == NULL)
1792 syserr("No *file* mailer defined");
1793 else
1795 FileMailer = st->s_mailer;
1796 clrbitn(M_MUSER, FileMailer->m_flags);
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;
1805 if (ConfigLevel < 6)
1807 /* heuristic tweaking of local mailer for back compat */
1808 if (LocalMailer != NULL)
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);
1818 if (ProgMailer != NULL)
1819 setbitn(M_RUNASRCPT, ProgMailer->m_flags);
1820 if (FileMailer != NULL)
1821 setbitn(M_RUNASRCPT, FileMailer->m_flags);
1823 if (ConfigLevel < 7)
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);
1833 /* MIME Content-Types that cannot be transfer encoded */
1834 setclass('n', "multipart/signed");
1836 /* MIME message/xxx subtypes that can be treated as messages */
1837 setclass('s', "rfc822");
1839 /* MIME Content-Transfer-Encodings that can be encoded */
1840 setclass('e', "7bit");
1841 setclass('e', "8bit");
1842 setclass('e', "binary");
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 */
1852 /* MIME headers which have fields to check for overflow */
1853 setclass(macid("{checkMIMEFieldHeaders}"), "content-disposition");
1854 setclass(macid("{checkMIMEFieldHeaders}"), "content-type");
1856 /* MIME headers to check for length overflow */
1857 setclass(macid("{checkMIMETextHeaders}"), "content-description");
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");
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}");
1873 /* operate in queue directory */
1874 if (QueueDir == NULL || *QueueDir == '\0')
1876 if (OpMode != MD_TEST)
1878 syserr("QueueDirectory (Q) option must be set");
1879 ExitStat = EX_CONFIG;
1882 else
1884 if (OpMode != MD_TEST)
1885 setup_queues(OpMode == MD_DAEMON);
1888 /* check host status directory for validity */
1889 if (HostStatDir != NULL && !path_is_dir(HostStatDir, false))
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;
1898 if (OpMode == MD_QUEUERUN &&
1899 RealUid != 0 && bitset(PRIV_RESTRICTQRUN, PrivacyFlags))
1901 struct stat stbuf;
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)
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 */
1916 #if MILTER
1917 /* sanity checks on milter filters */
1918 if (OpMode == MD_DAEMON || OpMode == MD_SMTP)
1920 milter_config(InputFilterList, InputFilters, MAXFILTERS);
1921 # if _FFR_MILTER_PERDAEMON
1922 setup_daemon_milters();
1923 # endif /* _FFR_MILTER_PERDAEMON */
1925 #endif /* MILTER */
1927 /* Convert queuegroup string to qgrp number */
1928 if (queuegroup != NULL)
1930 qgrp = name2qid(queuegroup);
1931 if (qgrp == NOQGRP)
1933 HoldErrs = false;
1934 usrerr("Queue group %s unknown", queuegroup);
1935 finis(false, true, ExitStat);
1936 /* NOTREACHED */
1940 /* if we've had errors so far, exit now */
1941 if (ExitStat != EX_OK && OpMode != MD_TEST)
1943 finis(false, true, ExitStat);
1944 /* NOTREACHED */
1947 #if SASL
1948 /* sendmail specific SASL initialization */
1949 sm_sasl_init();
1950 #endif /* SASL */
1952 #if XDEBUG
1953 checkfd012("before main() initmaps");
1954 #endif /* XDEBUG */
1957 ** Do operation-mode-dependent initialization.
1960 switch (OpMode)
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)
1969 int j;
1971 /* Selecting a particular queue group to run */
1972 for (j = 0; j < Queue[qgrp]->qg_numqueues; j++)
1974 if (StopRequest)
1975 stop_sendmail();
1976 (void) print_single_queue(qgrp, j);
1978 finis(false, true, EX_OK);
1979 /* NOTREACHED */
1981 printqueue();
1982 finis(false, true, EX_OK);
1983 /* NOTREACHED */
1984 break;
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;
1995 #if _FFR_QUARANTINE
1996 case MD_QUEUERUN:
1997 /* only handle quarantining here */
1998 if (quarantining == NULL)
1999 break;
2001 if (QueueMode != QM_QUARANTINE &&
2002 QueueMode != QM_NORMAL)
2004 HoldErrs = false;
2005 usrerr("Can not use -Q with -q%c", QueueMode);
2006 ExitStat = EX_USAGE;
2007 finis(false, true, ExitStat);
2008 /* NOTREACHED */
2010 quarantine_queue(quarantining, qgrp);
2011 finis(false, true, EX_OK);
2012 break;
2013 #endif /* _FFR_QUARANTINE */
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;
2022 case MD_PURGESTAT:
2023 (void) mci_traverse_persistent(mci_purge_persistent, NULL);
2024 finis(false, true, EX_OK);
2025 /* NOTREACHED */
2026 break;
2028 case MD_INITALIAS:
2029 /* initialize maps */
2030 initmaps();
2031 finis(false, true, ExitStat);
2032 /* NOTREACHED */
2033 break;
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);
2048 /* don't open maps for daemon -- done below in child */
2049 break;
2052 if (tTd(0, 15))
2054 /* print configuration table (or at least part of it) */
2055 if (tTd(0, 90))
2056 printrules();
2057 for (i = 0; i < MAXMAILERS; i++)
2059 if (Mailer[i] != NULL)
2060 printmailer(Mailer[i]);
2065 ** Switch to the main envelope.
2068 CurEnv = newenvelope(&MainEnvelope, &BlankEnvelope,
2069 sm_rpool_new_x(NULL));
2070 MainEnvelope.e_flags = BlankEnvelope.e_flags;
2073 ** If test mode, read addresses from stdin and process.
2076 if (OpMode == MD_TEST)
2078 if (isatty(sm_io_getinfo(smioin, SM_IO_WHAT_FD, NULL)))
2079 Verbose = 2;
2081 if (Verbose)
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");
2088 macdefine(&(MainEnvelope.e_macro), A_PERM,
2089 macid("{addr_type}"), "e r");
2090 for (;;)
2092 SM_TRY
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);
2113 SM_EXCEPT(exc, "[!F]*")
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.
2122 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
2123 "\n");
2124 sm_exc_print(exc, smioout);
2126 SM_END_TRY
2130 #if STARTTLS
2131 tls_ok = true;
2132 if (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER)
2134 /* check whether STARTTLS is turned off for the client */
2135 if (chkclientmodifiers(D_NOTLS))
2136 tls_ok = false;
2138 else if (OpMode == MD_DAEMON || OpMode == MD_FGDAEMON ||
2139 OpMode == MD_SMTP)
2141 /* check whether STARTTLS is turned off for the server */
2142 if (chkdaemonmodifiers(D_NOTLS))
2143 tls_ok = false;
2145 else /* other modes don't need STARTTLS */
2146 tls_ok = false;
2148 if (tls_ok)
2150 /* basic TLS initialization */
2151 tls_ok = init_tls_library();
2154 if (!tls_ok && (OpMode == MD_QUEUERUN || OpMode == MD_DELIVER))
2156 /* disable TLS for client */
2157 setclttls(false);
2159 #endif /* STARTTLS */
2162 ** If collecting stuff from the queue, go start doing that.
2165 if (OpMode == MD_QUEUERUN && QueueIntvl == 0)
2167 pid_t pid = -1;
2169 #if STARTTLS
2170 /* init TLS for client, ignore result for now */
2171 (void) initclttls(tls_ok);
2172 #endif /* STARTTLS */
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().
2183 if (Verbose || foregroundqueue || (pid = fork()) <= 0)
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.
2192 if (pid == 0)
2194 /* Reset global flags */
2195 RestartRequest = NULL;
2196 ShutdownRequest = NULL;
2197 PendingSignal = 0;
2199 /* disconnect from terminal */
2200 disconnect(2, CurEnv);
2203 CurrentPid = getpid();
2204 if (qgrp != NOQGRP)
2206 int rwgflags = RWG_NONE;
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.
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);
2226 else
2227 (void) runqueue(false, Verbose,
2228 queuepersistent, true);
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)
2235 int status;
2236 pid_t ret;
2238 while ((ret = sm_wait(&status)) <= 0)
2239 continue;
2241 /* Only drop when a child gives status */
2242 if (WIFSTOPPED(status))
2243 continue;
2245 proc_list_drop(ret, status, NULL);
2248 finis(true, true, ExitStat);
2249 /* NOTREACHED */
2252 # if SASL
2253 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
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));
2261 # endif /* SASL */
2263 if (OpMode == MD_SMTP)
2265 proc_list_add(CurrentPid, "Sendmail SMTP Agent",
2266 PROC_DAEMON, 0, -1);
2268 /* clean up background delivery children */
2269 (void) sm_signal(SIGCHLD, reapchild);
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.
2281 if (OpMode == MD_DAEMON || QueueIntvl > 0)
2283 char dtype[200];
2285 if (!run_in_foreground && !tTd(99, 100))
2287 /* put us in background */
2288 i = fork();
2289 if (i < 0)
2290 syserr("daemon: cannot fork");
2291 if (i != 0)
2293 finis(false, true, EX_OK);
2294 /* NOTREACHED */
2298 ** Initialize exception stack and default exception
2299 ** handler for child process.
2302 /* Reset global flags */
2303 RestartRequest = NULL;
2304 RestartWorkGroup = false;
2305 ShutdownRequest = NULL;
2306 PendingSignal = 0;
2307 CurrentPid = getpid();
2309 sm_exc_newthread(fatal_error);
2311 /* disconnect from our controlling tty */
2312 disconnect(2, &MainEnvelope);
2315 dtype[0] = '\0';
2316 if (OpMode == MD_DAEMON)
2318 (void) sm_strlcat(dtype, "+SMTP", sizeof dtype);
2319 DaemonPid = CurrentPid;
2321 if (QueueIntvl > 0)
2323 (void) sm_strlcat2(dtype,
2324 queuepersistent
2325 ? "+persistent-queueing@"
2326 : "+queueing@",
2327 pintvl(QueueIntvl, true),
2328 sizeof dtype);
2330 if (tTd(0, 1))
2331 (void) sm_strlcat(dtype, "+debugging", sizeof dtype);
2333 sm_syslog(LOG_INFO, NOQID,
2334 "starting daemon (%s): %s", Version, dtype + 1);
2335 #if XLA
2336 xla_create_file();
2337 #endif /* XLA */
2339 /* save daemon type in a macro for possible PidFile use */
2340 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2341 macid("{daemon_info}"), dtype + 1);
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));
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);
2352 if (QueueIntvl > 0)
2354 (void) runqueue(true, false, queuepersistent, true);
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.
2363 if (OpMode != MD_DAEMON && queuepersistent)
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)
2370 int status;
2371 pid_t ret;
2372 int group;
2374 CHECK_RESTART;
2375 while ((ret = sm_wait(&status)) <= 0)
2376 continue;
2378 if (WIFSTOPPED(status))
2379 continue;
2381 /* Probe only on a child status */
2382 proc_list_drop(ret, status, &group);
2384 if (WIFSIGNALED(status))
2386 if (WCOREDUMP(status))
2388 sm_syslog(LOG_ERR, NOQID,
2389 "persistent queue runner=%d core dumped, signal=%d",
2390 group, WTERMSIG(status));
2392 /* don't restart this */
2393 mark_work_group_restart(
2394 group, -1);
2395 continue;
2398 sm_syslog(LOG_ERR, NOQID,
2399 "persistent queue runner=%d died, signal=%d",
2400 group, WTERMSIG(status));
2404 ** When debugging active, don't
2405 ** restart the persistent queues.
2406 ** But do log this as info.
2409 if (sm_debug_active(&DebugNoPRestart,
2412 sm_syslog(LOG_DEBUG, NOQID,
2413 "persistent queue runner=%d, exited",
2414 group);
2415 mark_work_group_restart(group,
2416 -1);
2419 finis(true, true, ExitStat);
2420 /* NOTREACHED */
2423 if (OpMode != MD_DAEMON)
2425 char qtype[200];
2428 ** Write the pid to file
2429 ** XXX Overwrites sendmail.pid
2432 log_sendmail_pid(&MainEnvelope);
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 (;;)
2444 (void) pause();
2445 CHECK_RESTART;
2446 if (doqueuerun())
2447 (void) runqueue(true, false,
2448 false, false);
2452 dropenvelope(&MainEnvelope, true, false);
2454 #if STARTTLS
2455 /* init TLS for server, ignore result for now */
2456 (void) initsrvtls(tls_ok);
2457 #endif /* STARTTLS */
2459 nextreq:
2460 p_flags = getrequests(&MainEnvelope);
2462 /* drop privileges */
2463 (void) drop_privileges(false);
2466 ** Get authentication data
2467 ** Set _ macro in BlankEnvelope before calling newenvelope().
2470 authinfo = getauthinfo(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
2471 NULL), &forged);
2472 macdefine(&BlankEnvelope.e_macro, A_TEMP, '_', authinfo);
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));
2480 if (LogLevel > 9)
2482 /* log connection information */
2483 sm_syslog(LOG_INFO, NULL, "connect from %s", authinfo);
2487 ** If running SMTP protocol, start collecting and executing
2488 ** commands. This will never return.
2491 if (OpMode == MD_SMTP || OpMode == MD_DAEMON)
2493 char pbuf[20];
2496 ** Save some macros for check_* rulesets.
2499 if (forged)
2501 char ipbuf[103];
2503 (void) sm_snprintf(ipbuf, sizeof ipbuf, "[%.100s]",
2504 anynet_ntoa(&RealHostAddr));
2505 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2506 macid("{client_name}"), ipbuf);
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();
2515 switch (RealHostAddr.sa.sa_family)
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;
2533 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2534 macid("{client_port}"), pbuf);
2536 if (OpMode == MD_DAEMON)
2538 /* validate the connection */
2539 HoldErrs = true;
2540 nullserver = validate_connection(&RealHostAddr,
2541 RealHostName,
2542 &MainEnvelope);
2543 HoldErrs = false;
2545 else if (p_flags == NULL)
2547 p_flags = (BITMAP256 *) xalloc(sizeof *p_flags);
2548 clrbitmap(p_flags);
2550 #if STARTTLS
2551 if (OpMode == MD_SMTP)
2552 (void) initsrvtls(tls_ok);
2553 #endif /* STARTTLS */
2555 /* turn off profiling */
2556 SM_PROF(1);
2557 smtp(nullserver, *p_flags, &MainEnvelope);
2559 if (tTd(93, 100))
2561 /* turn off profiling */
2562 SM_PROF(0);
2563 if (OpMode == MD_DAEMON)
2564 goto nextreq;
2568 sm_rpool_free(MainEnvelope.e_rpool);
2569 clearenvelope(&MainEnvelope, false, sm_rpool_new_x(NULL));
2570 if (OpMode == MD_VERIFY)
2572 set_delivery_mode(SM_VERIFY, &MainEnvelope);
2573 PostMasterCopy = NULL;
2575 else
2577 /* interactive -- all errors are global */
2578 MainEnvelope.e_flags |= EF_GLOBALERRS|EF_LOGSENDER;
2582 ** Do basic system initialization and set the sender
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))
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 */
2599 if (auth)
2601 char *fv;
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
2609 if (strchr(fv, '@') == NULL)
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));
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 */
2625 if (macvalue('s', &MainEnvelope) == NULL)
2626 macdefine(&MainEnvelope.e_macro, A_PERM, 's', RealHostName);
2628 av = argv + optind;
2629 if (*av == NULL && !GrabTo)
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");
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 */
2645 ** Scan argv and deliver the message to everyone.
2648 save_val = LogUsrErrs;
2649 LogUsrErrs = true;
2650 sendtoargv(av, &MainEnvelope);
2651 LogUsrErrs = save_val;
2653 /* if we have had errors sofar, arrange a meaningful exit stat */
2654 if (Errors > 0 && ExitStat == EX_OK)
2655 ExitStat = EX_USAGE;
2657 #if _FFR_FIX_DASHT
2659 ** If using -t, force not sending to argv recipients, even
2660 ** if they are mentioned in the headers.
2663 if (GrabTo)
2665 ADDRESS *q;
2667 for (q = MainEnvelope.e_sendqueue; q != NULL; q = q->q_next)
2668 q->q_state = QS_REMOVED;
2670 #endif /* _FFR_FIX_DASHT */
2673 ** Read the input mail.
2676 MainEnvelope.e_to = NULL;
2677 if (OpMode != MD_VERIFY || GrabTo)
2679 int savederrors;
2680 unsigned long savedflags;
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;
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);
2701 /* header checks failed */
2702 if (Errors > 0)
2704 giveup:
2705 if (!GrabTo)
2707 /* Log who the mail would have gone to */
2708 logundelrcpts(&MainEnvelope,
2709 MainEnvelope.e_message,
2710 8, false);
2712 flush_errors(true);
2713 finis(true, true, ExitStat);
2714 /* NOTREACHED */
2715 return -1;
2718 /* bail out if message too large */
2719 if (bitset(EF_CLRQUEUE, MainEnvelope.e_flags))
2721 finis(true, true, ExitStat != EX_OK ? ExitStat
2722 : EX_DATAERR);
2723 /* NOTREACHED */
2724 return -1;
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);
2733 Errors = savederrors;
2734 MainEnvelope.e_flags |= savedflags;
2736 errno = 0;
2738 if (tTd(1, 1))
2739 sm_dprintf("From person = \"%s\"\n",
2740 MainEnvelope.e_from.q_paddr);
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 */
2749 ** Actually send everything.
2750 ** If verifying, just ack.
2753 if (Errors == 0)
2755 if (!split_by_recipient(&MainEnvelope) &&
2756 bitset(EF_FATALERRS, MainEnvelope.e_flags))
2757 goto giveup;
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++)
2764 ENVELOPE *next;
2766 e->e_from.q_state = QS_SENDER;
2767 if (tTd(1, 5))
2769 sm_dprintf("main[%d]: QS_SENDER ", i);
2770 printaddr(&e->e_from, false);
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;
2782 /* after FastSplit envelopes: queue up */
2783 sendall(e, i >= FastSplit ? SM_QUEUE : SM_DEFAULT);
2784 e->e_sibling = next;
2788 ** All done.
2789 ** Don't send return error message if in VERIFY mode.
2792 finis(true, true, ExitStat);
2793 /* NOTREACHED */
2794 return ExitStat;
2797 ** STOP_SENDMAIL -- Stop the running program
2799 ** Parameters:
2800 ** none.
2802 ** Returns:
2803 ** none.
2805 ** Side Effects:
2806 ** exits.
2809 void
2810 stop_sendmail()
2812 /* reset uid for process accounting */
2813 endpwent();
2814 (void) setuid(RealUid);
2815 exit(EX_OK);
2818 ** FINIS -- Clean up and exit.
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
2825 ** Returns:
2826 ** never
2828 ** Side Effects:
2829 ** exits sendmail
2832 void
2833 finis(drop, cleanup, exitstat)
2834 bool drop;
2835 bool cleanup;
2836 volatile int exitstat;
2839 /* Still want to process new timeouts added below */
2840 sm_clear_events();
2841 (void) sm_releasesignal(SIGALRM);
2843 if (tTd(2, 1))
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);
2850 if (tTd(2, 9))
2851 printopenfds(false);
2853 SM_TRY
2855 ** Clean up. This might raise E:mta.quickabort
2858 /* clean up temp files */
2859 CurEnv->e_to = NULL;
2860 if (drop)
2862 if (CurEnv->e_id != NULL)
2864 dropenvelope(CurEnv, true, false);
2865 sm_rpool_free(CurEnv->e_rpool);
2866 CurEnv->e_rpool = NULL;
2868 else
2869 poststats(StatFile);
2872 /* flush any cached connections */
2873 mci_flush(true, NULL);
2875 /* close maps belonging to this pid */
2876 closemaps(false);
2878 #if USERDB
2879 /* close UserDatabase */
2880 _udbx_close();
2881 #endif /* USERDB */
2883 #if SASL
2884 stop_sasl_client();
2885 #endif /* SASL */
2887 #if XLA
2888 /* clean up extended load average stuff */
2889 xla_all_end();
2890 #endif /* XLA */
2892 SM_FINALLY
2894 ** And exit.
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;
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 */
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
2929 ** INTINDEBUG -- signal handler for SIGINT in -bt mode
2931 ** Parameters:
2932 ** sig -- incoming signal.
2934 ** Returns:
2935 ** none.
2937 ** Side Effects:
2938 ** longjmps back to test mode loop.
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.
2945 /* Type of an exception generated on SIGINT during address test mode. */
2946 static const SM_EXC_TYPE_T EtypeInterrupt =
2948 SmExcTypeMagic,
2949 "S:mta.interrupt",
2951 sm_etype_printf,
2952 "interrupt",
2955 /* ARGSUSED */
2956 static SIGFUNC_DECL
2957 intindebug(sig)
2958 int sig;
2960 int save_errno = errno;
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;
2971 ** SIGTERM -- SIGTERM handler for the daemon
2973 ** Parameters:
2974 ** sig -- signal number.
2976 ** Returns:
2977 ** none.
2979 ** Side Effects:
2980 ** Sets ShutdownRequest which will hopefully trigger
2981 ** the daemon to exit.
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.
2988 /* ARGSUSED */
2989 static SIGFUNC_DECL
2990 sigterm(sig)
2991 int sig;
2993 int save_errno = errno;
2995 FIX_SYSV_SIGNAL(sig, sigterm);
2996 ShutdownRequest = "signal";
2997 errno = save_errno;
2998 return SIGFUNC_RETURN;
3001 ** SIGHUP -- handle a SIGHUP signal
3003 ** Parameters:
3004 ** sig -- incoming signal.
3006 ** Returns:
3007 ** none.
3009 ** Side Effects:
3010 ** Sets RestartRequest which should cause the daemon
3011 ** to restart.
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.
3018 /* ARGSUSED */
3019 static SIGFUNC_DECL
3020 sighup(sig)
3021 int sig;
3023 int save_errno = errno;
3025 FIX_SYSV_SIGNAL(sig, sighup);
3026 RestartRequest = "signal";
3027 errno = save_errno;
3028 return SIGFUNC_RETURN;
3031 ** SIGPIPE -- signal handler for SIGPIPE
3033 ** Parameters:
3034 ** sig -- incoming signal.
3036 ** Returns:
3037 ** none.
3039 ** Side Effects:
3040 ** Sets StopRequest which should cause the mailq/hoststatus
3041 ** display to stop.
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.
3048 /* ARGSUSED */
3049 static SIGFUNC_DECL
3050 sigpipe(sig)
3051 int sig;
3053 int save_errno = errno;
3055 FIX_SYSV_SIGNAL(sig, sigpipe);
3056 StopRequest = true;
3057 errno = save_errno;
3058 return SIGFUNC_RETURN;
3061 ** INTSIG -- clean up on interrupt
3063 ** This just arranges to exit. It pessimizes in that it
3064 ** may resend a message.
3066 ** Parameters:
3067 ** none.
3069 ** Returns:
3070 ** none.
3072 ** Side Effects:
3073 ** Unlocks the current job.
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.
3079 ** XXX: More work is needed for this signal handler.
3082 /* ARGSUSED */
3083 SIGFUNC_DECL
3084 intsig(sig)
3085 int sig;
3087 bool drop = false;
3088 int save_errno = errno;
3090 FIX_SYSV_SIGNAL(sig, intsig);
3091 errno = save_errno;
3092 CHECK_CRITICAL(sig);
3093 sm_allsignals(true);
3095 if (sig != 0 && LogLevel > 79)
3096 sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt");
3097 FileName = NULL;
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))
3105 register ADDRESS *q;
3107 /* don't return an error indication */
3108 CurEnv->e_to = NULL;
3109 CurEnv->e_flags &= ~EF_FATALERRS;
3110 CurEnv->e_flags |= EF_CLRQUEUE;
3113 ** Spin through the addresses and
3114 ** mark them dead to prevent bounces
3117 for (q = CurEnv->e_sendqueue; q != NULL; q = q->q_next)
3118 q->q_state = QS_DONTSEND;
3120 drop = true;
3122 else if (OpMode != MD_TEST)
3124 unlockqueue(CurEnv);
3127 finis(drop, false, EX_OK);
3128 /* NOTREACHED */
3131 ** DISCONNECT -- remove our connection with any foreground process
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.
3142 ** Returns:
3143 ** none
3145 ** Side Effects:
3146 ** Trys to insure that we are immune to vagaries of
3147 ** the controlling tty.
3150 void
3151 disconnect(droplev, e)
3152 int droplev;
3153 register ENVELOPE *e;
3155 int fd;
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))
3163 sm_dprintf("don't\n");
3164 return;
3166 if (LogLevel > 93)
3167 sm_syslog(LOG_DEBUG, e->e_id,
3168 "disconnect level %d",
3169 droplev);
3171 /* be sure we don't get nasty signals */
3172 (void) sm_signal(SIGINT, SIG_IGN);
3173 (void) sm_signal(SIGQUIT, SIG_IGN);
3175 /* we can't communicate with our caller, so.... */
3176 HoldErrs = true;
3177 CurEnv->e_errormode = EM_MAIL;
3178 Verbose = 0;
3179 DisConnected = true;
3181 /* all input from /dev/null */
3182 if (InChannel != smioin)
3184 (void) sm_io_close(InChannel, SM_TIME_DEFAULT);
3185 InChannel = smioin;
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));
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).
3200 if (OutChannel != smioout &&
3201 sm_io_getinfo(OutChannel, SM_IO_WHAT_FD, NULL) !=
3202 sm_io_getinfo(smioout, SM_IO_WHAT_FD, NULL))
3204 (void) sm_io_close(OutChannel, SM_TIME_DEFAULT);
3205 OutChannel = smioout;
3207 #if 0
3209 ** Has smioout been closed? Reopen it.
3210 ** This shouldn't happen anymore, the code is here
3211 ** just as a reminder.
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 */
3222 if (droplev > 0)
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);
3235 /* drop our controlling TTY completely if possible */
3236 if (droplev > 1)
3238 (void) setsid();
3239 errno = 0;
3242 #if XDEBUG
3243 checkfd012("disconnect");
3244 #endif /* XDEBUG */
3246 if (LogLevel > 71)
3247 sm_syslog(LOG_DEBUG, e->e_id, "in background, pid=%d",
3248 (int) CurrentPid);
3250 errno = 0;
3253 static void
3254 obsolete(argv)
3255 char *argv[];
3257 register char *ap;
3258 register char *op;
3260 while ((ap = *++argv) != NULL)
3262 /* Return if "--" or not an option of any form. */
3263 if (ap[0] != '-' || ap[1] == '-')
3264 return;
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'))
3272 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3273 "Can not use -Q.\n");
3274 exit(EX_USAGE);
3276 #endif /* _FFR_QUARANTINE */
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] != '-')
3287 argv++;
3288 continue;
3291 /* If -C doesn't have an argument, use sendmail.cf. */
3292 #define __DEFPATH "sendmail.cf"
3293 if (ap[1] == 'C' && ap[2] == '\0')
3295 *argv = xalloc(sizeof(__DEFPATH) + 2);
3296 (void) sm_strlcpyn(argv[0], sizeof(__DEFPATH) + 2, 2,
3297 "-C", __DEFPATH);
3300 /* If -q doesn't have an argument, run it once. */
3301 if (ap[1] == 'q' && ap[2] == '\0')
3302 *argv = "-q0";
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 */
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";
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";
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) */
3326 ** AUTH_WARNING -- specify authorization warning
3328 ** Parameters:
3329 ** e -- the current envelope.
3330 ** msg -- the text of the message.
3331 ** args -- arguments to the message.
3333 ** Returns:
3334 ** none.
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__ */
3347 char buf[MAXLINE];
3348 SM_VA_LOCAL_DECL
3350 if (bitset(PRIV_AUTHWARNINGS, PrivacyFlags))
3352 register char *p;
3353 static char hostbuf[48];
3355 if (hostbuf[0] == '\0')
3357 struct hostent *hp;
3359 hp = myhostname(hostbuf, sizeof hostbuf);
3360 #if NETINET6
3361 if (hp != NULL)
3363 freehostent(hp);
3364 hp = NULL;
3366 #endif /* NETINET6 */
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);
3382 ** GETEXTENV -- get from external environment
3384 ** Parameters:
3385 ** envar -- the name of the variable to retrieve
3387 ** Returns:
3388 ** The value, if any.
3391 static char *
3392 getextenv(envar)
3393 const char *envar;
3395 char **envp;
3396 int l;
3398 l = strlen(envar);
3399 for (envp = ExternalEnviron; envp != NULL && *envp != NULL; envp++)
3401 if (strncmp(*envp, envar, l) == 0 && (*envp)[l] == '=')
3402 return &(*envp)[l + 1];
3404 return NULL;
3407 ** SETUSERENV -- set an environment in the propagated environment
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.
3416 ** Returns:
3417 ** none.
3420 void
3421 setuserenv(envar, value)
3422 const char *envar;
3423 const char *value;
3425 int i, l;
3426 char **evp = UserEnviron;
3427 char *p;
3429 if (value == NULL)
3431 value = getextenv(envar);
3432 if (value == NULL)
3433 return;
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);
3442 while (*evp != NULL && strncmp(*evp, p, i) != 0)
3443 evp++;
3444 if (*evp != NULL)
3446 *evp++ = p;
3448 else if (evp < &UserEnviron[MAXUSERENVIRON])
3450 *evp++ = p;
3451 *evp = NULL;
3454 /* make sure it is in our environment as well */
3455 if (putenv(p) < 0)
3456 syserr("setuserenv: putenv(%s) failed", p);
3459 ** DUMPSTATE -- dump state
3461 ** For debugging.
3464 void
3465 dumpstate(when)
3466 char *when;
3468 register char *j = macvalue('j', CurEnv);
3469 int rs;
3470 extern int NextMacroId;
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)
3478 if (!wordinclass(j, 'w'))
3479 sm_syslog(LOG_DEBUG, CurEnv->e_id,
3480 "*** $j not in $=w ***");
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)
3492 int status;
3493 register char **pvp;
3494 char *pv[MAXATOM + 1];
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);
3504 sm_syslog(LOG_DEBUG, CurEnv->e_id, "--- end of state dump ---");
3507 #ifdef SIGUSR1
3509 ** SIGUSR1 -- Signal a request to dump state.
3511 ** Parameters:
3512 ** sig -- calling signal.
3514 ** Returns:
3515 ** none.
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.
3521 ** XXX: More work is needed for this signal handler.
3524 /* ARGSUSED */
3525 static SIGFUNC_DECL
3526 sigusr1(sig)
3527 int sig;
3529 int save_errno = errno;
3530 # if SM_HEAP_CHECK
3531 extern void dumpstab __P((void));
3532 # endif /* SM_HEAP_CHECK */
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;
3544 #endif /* SIGUSR1 */
3547 ** DROP_PRIVILEGES -- reduce privileges to those of the RunAsUser option
3549 ** Parameters:
3550 ** to_real_uid -- if set, drop to the real uid instead
3551 ** of the RunAsUser.
3553 ** Returns:
3554 ** EX_OSERR if the setuid failed.
3555 ** EX_OK otherwise.
3559 drop_privileges(to_real_uid)
3560 bool to_real_uid;
3562 int rval = EX_OK;
3563 GIDSET_T emptygidset[1];
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);
3573 if (to_real_uid)
3575 RunAsUserName = RealUserName;
3576 RunAsUid = RealUid;
3577 RunAsGid = RealGid;
3578 EffGid = RunAsGid;
3581 /* make sure no one can grab open descriptors for secret files */
3582 endpwent();
3583 sm_mbdb_terminate();
3585 /* reset group permissions; these can be set later */
3586 emptygidset[0] = (to_real_uid || RunAsGid != 0) ? RunAsGid : getegid();
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)
3597 if (setgroups(1, emptygidset) == -1 && geteuid() == 0)
3599 syserr("drop_privileges: setgroups(1, %d) failed",
3600 (int) emptygidset[0]);
3601 rval = EX_OSERR;
3604 /* reset primary group id */
3605 if (to_real_uid)
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.
3615 #if HASSETEGID
3616 if (setegid(RunAsGid) < 0)
3618 syserr("drop_privileges: setegid(%d) failed",
3619 (int) RunAsGid);
3620 rval = EX_OSERR;
3622 #else /* HASSETEGID */
3623 # if HASSETREGID
3624 if (setregid(RunAsGid, RunAsGid) < 0)
3626 syserr("drop_privileges: setregid(%d, %d) failed",
3627 (int) RunAsGid, (int) RunAsGid);
3628 rval = EX_OSERR;
3630 # else /* HASSETREGID */
3631 # if HASSETRESGID
3632 if (setresgid(RunAsGid, RunAsGid, RunAsGid) < 0)
3634 syserr("drop_privileges: setresgid(%d, %d, %d) failed",
3635 (int) RunAsGid, (int) RunAsGid, (int) RunAsGid);
3636 rval = EX_OSERR;
3638 # endif /* HASSETRESGID */
3639 # endif /* HASSETREGID */
3640 #endif /* HASSETEGID */
3642 if (rval == EX_OK && (to_real_uid || RunAsGid != 0))
3644 if (setgid(RunAsGid) < 0 && (!UseMSP || getegid() != RunAsGid))
3646 syserr("drop_privileges: setgid(%d) failed",
3647 (int) RunAsGid);
3648 rval = EX_OSERR;
3650 errno = 0;
3651 if (rval == EX_OK && getegid() != RunAsGid)
3653 syserr("drop_privileges: Unable to set effective gid=%d to RunAsGid=%d",
3654 (int) getegid(), (int) RunAsGid);
3655 rval = EX_OSERR;
3659 /* fiddle with uid */
3660 if (to_real_uid || RunAsUid != 0)
3662 uid_t euid;
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.
3671 if (setuid(RunAsUid) < 0 ||
3672 geteuid() != RunAsUid ||
3673 (getuid() != RunAsUid &&
3674 (to_real_uid || geteuid() == 0 || getuid() == 0)))
3676 #if HASSETREUID
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.
3683 if (geteuid() == RunAsUid)
3685 if (setreuid(RunAsUid, -1) < 0)
3687 syserr("drop_privileges: setreuid(%d, -1) failed",
3688 (int) RunAsUid);
3689 rval = EX_OSERR;
3691 if (setuid(RunAsUid) < 0)
3693 syserr("drop_privileges: second setuid(%d) attempt failed",
3694 (int) RunAsUid);
3695 rval = EX_OSERR;
3698 else
3699 #endif /* HASSETREUID */
3701 syserr("drop_privileges: setuid(%d) failed",
3702 (int) RunAsUid);
3703 rval = EX_OSERR;
3706 euid = geteuid();
3707 if (RunAsUid != 0 && setuid(0) == 0)
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.
3716 syserr("drop_privileges: setuid(0) succeeded (when it should not)");
3717 rval = EX_OSERR;
3719 else if (RunAsUid != euid && setuid(euid) == 0)
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.
3727 syserr("drop_privileges: Unable to drop non-root set-user-ID privileges");
3728 rval = EX_OSERR;
3732 if ((to_real_uid || RunAsGid != 0) &&
3733 rval == EX_OK && RunAsGid != EffGid &&
3734 getuid() != 0 && geteuid() != 0)
3736 errno = 0;
3737 if (setgid(EffGid) == 0)
3739 syserr("drop_privileges: setgid(%d) succeeded (when it should not)",
3740 (int) EffGid);
3741 rval = EX_OSERR;
3745 if (tTd(47, 5))
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);
3755 return rval;
3758 ** FILL_FD -- make sure a file descriptor has been properly allocated
3760 ** Used to make sure that stdin/out/err are allocated on startup
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.
3768 ** Returns:
3769 ** none
3771 ** Side Effects:
3772 ** possibly changes MissingFds
3775 void
3776 fill_fd(fd, where)
3777 int fd;
3778 char *where;
3780 int i;
3781 struct stat stbuf;
3783 if (fstat(fd, &stbuf) >= 0 || errno != EBADF)
3784 return;
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)
3793 syserr("!fill_fd: %s: cannot open %s",
3794 where == NULL ? "startup" : where, SM_PATH_DEVNULL);
3796 if (fd != i)
3798 (void) dup2(i, fd);
3799 (void) close(i);
3803 ** SM_PRINTOPTIONS -- print options
3805 ** Parameters:
3806 ** options -- array of options.
3808 ** Returns:
3809 ** none.
3812 static void
3813 sm_printoptions(options)
3814 char **options;
3816 int ll;
3817 char **av;
3819 av = options;
3820 ll = 7;
3821 while (*av != NULL)
3823 if (ll + strlen(*av) > 63)
3825 sm_dprintf("\n");
3826 ll = 0;
3828 if (ll == 0)
3829 sm_dprintf("\t\t");
3830 else
3831 sm_dprintf(" ");
3832 sm_dprintf("%s", *av);
3833 ll += strlen(*av++) + 1;
3835 sm_dprintf("\n");
3838 ** TESTMODELINE -- process a test mode input line
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
3852 static void
3853 testmodeline(line, e)
3854 char *line;
3855 ENVELOPE *e;
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[];
3870 /* skip leading spaces */
3871 while (*line == ' ')
3872 line++;
3874 switch (line[0])
3876 case '#':
3877 case '\0':
3878 return;
3880 case '?':
3881 help("-bt", e);
3882 return;
3884 case '.': /* config-style settings */
3885 switch (line[1])
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;
3895 case 'C':
3896 if (line[2] == '\0') /* not to call syserr() */
3897 return;
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')
3907 register char *wd;
3908 char delim;
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;
3921 break;
3923 case '\0':
3924 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3925 "Usage: .[DC]macro value(s)\n");
3926 break;
3928 default:
3929 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3930 "Unknown \".\" command %s\n", line);
3931 break;
3933 return;
3935 case '=': /* config-style settings */
3936 switch (line[1])
3938 case 'S': /* dump rule set */
3939 rs = strtorwset(&line[2], NULL, ST_FIND);
3940 if (rs < 0)
3942 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3943 "Undefined ruleset %s\n", &line[2]);
3944 return;
3946 rw = RewriteRules[rs];
3947 if (rw == NULL)
3948 return;
3951 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3952 'R');
3953 s = rw->r_lhs;
3954 while (*s != NULL)
3956 xputs(*s++);
3957 (void) sm_io_putc(smioout,
3958 SM_TIME_DEFAULT, ' ');
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)
3967 xputs(*s++);
3968 (void) sm_io_putc(smioout,
3969 SM_TIME_DEFAULT, ' ');
3971 (void) sm_io_putc(smioout, SM_TIME_DEFAULT,
3972 '\n');
3973 } while ((rw = rw->r_next) != NULL);
3974 break;
3976 case 'M':
3977 for (i = 0; i < MAXMAILERS; i++)
3979 if (Mailer[i] != NULL)
3980 printmailer(Mailer[i]);
3982 break;
3984 case '\0':
3985 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3986 "Usage: =Sruleset or =M\n");
3987 break;
3989 default:
3990 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
3991 "Unknown \"=\" command %s\n", line);
3992 break;
3994 return;
3996 case '-': /* set command-line-like opts */
3997 switch (line[1])
3999 case 'd':
4000 tTflag(&line[2]);
4001 break;
4003 case '\0':
4004 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4005 "Usage: -d{debug arguments}\n");
4006 break;
4008 default:
4009 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4010 "Unknown \"-\" command %s\n", line);
4011 break;
4013 return;
4015 case '$':
4016 if (line[1] == '=')
4018 mid = macid(&line[2]);
4019 if (mid != 0)
4020 stabapply(dump_class, mid);
4021 return;
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
4032 xputs(p);
4033 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4034 "\n");
4036 return;
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)
4045 while (isascii(*p) && isspace(*p))
4046 *p++ = '\0';
4048 else
4049 p = "";
4050 if (line[1] == '\0')
4052 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4053 "Usage: /[canon|map|mx|parse|try|tryflags]\n");
4054 return;
4056 if (sm_strcasecmp(&line[1], "quit") == 0)
4058 CurEnv->e_id = NULL;
4059 finis(true, true, ExitStat);
4060 /* NOTREACHED */
4062 if (sm_strcasecmp(&line[1], "mx") == 0)
4064 #if NAMED_BIND
4065 /* look up MX records */
4066 int nmx;
4067 auto int rcode;
4068 char *mxhosts[MAXMXHOSTS + 1];
4070 if (*p == '\0')
4072 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4073 "Usage: /mx address\n");
4074 return;
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 */
4089 else if (sm_strcasecmp(&line[1], "canon") == 0)
4091 char host[MAXHOSTNAMELEN];
4093 if (*p == '\0')
4095 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4096 "Usage: /canon address\n");
4097 return;
4099 else if (sm_strlcpy(host, p, sizeof host) >= sizeof host)
4101 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4102 "Name too long\n");
4103 return;
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);
4111 else if (sm_strcasecmp(&line[1], "map") == 0)
4113 auto int rcode = EX_OK;
4114 char *av[2];
4116 if (*p == '\0')
4118 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4119 "Usage: /map mapname key\n");
4120 return;
4122 for (q = p; *q != '\0' && !(isascii(*q) && isspace(*q)); q++)
4123 continue;
4124 if (*q == '\0')
4126 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4127 "No key specified\n");
4128 return;
4130 *q++ = '\0';
4131 map = stab(p, ST_MAP, ST_FIND);
4132 if (map == NULL)
4134 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4135 "Map named \"%s\" not found\n", p);
4136 return;
4138 if (!bitset(MF_OPEN, map->s_map.map_mflags) &&
4139 !openmap(&(map->s_map)))
4141 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4142 "Map named \"%s\" not open\n", p);
4143 return;
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);
4160 else if (sm_strcasecmp(&line[1], "try") == 0)
4162 MAILER *m;
4163 STAB *st;
4164 auto int rcode = EX_OK;
4166 q = strpbrk(p, " \t");
4167 if (q != NULL)
4169 while (isascii(*q) && isspace(*q))
4170 *q++ = '\0';
4172 if (q == NULL || *q == '\0')
4174 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4175 "Usage: /try mailer address\n");
4176 return;
4178 st = stab(p, ST_MAILER, ST_FIND);
4179 if (st == NULL)
4181 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4182 "Unknown mailer %s\n", p);
4183 return;
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;
4198 else if (sm_strcasecmp(&line[1], "tryflags") == 0)
4200 if (*p == '\0')
4202 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4203 "Usage: /tryflags [Hh|Ee][Ss|Rr]\n");
4204 return;
4206 for (; *p != '\0'; p++)
4208 switch (*p)
4210 case 'H':
4211 case 'h':
4212 tryflags |= RF_HEADERADDR;
4213 break;
4215 case 'E':
4216 case 'e':
4217 tryflags &= ~RF_HEADERADDR;
4218 break;
4220 case 'S':
4221 case 's':
4222 tryflags |= RF_SENDERADDR;
4223 break;
4225 case 'R':
4226 case 'r':
4227 tryflags &= ~RF_SENDERADDR;
4228 break;
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);
4238 else if (sm_strcasecmp(&line[1], "parse") == 0)
4240 if (*p == '\0')
4242 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4243 "Usage: /parse address\n");
4244 return;
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;
4273 else
4275 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4276 "Unknown \"/\" command %s\n",
4277 line);
4279 return;
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')
4289 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4290 "No address!\n");
4291 return;
4293 *p = '\0';
4294 if (invalidaddr(p + 1, NULL, true))
4295 return;
4298 register char **pvp;
4299 char pvpbuf[PSBUFSIZE];
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')
4308 int status;
4310 rs = strtorwset(p, NULL, ST_FIND);
4311 if (rs < 0)
4313 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
4314 "Undefined ruleset %s\n",
4316 break;
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;
4326 } while (*(p = delimptr) != '\0');
4329 static void
4330 dump_class(s, id)
4331 register STAB *s;
4332 int id;
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);
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.
4349 const SM_EXC_TYPE_T EtypeQuickAbort =
4351 SmExcTypeMagic,
4352 "E:mta.quickabort",
4353 "i",
4354 sm_etype_printf,
4355 "quick abort %0",