implement arpatounix; log more info; allow nested $?...$|...$.;
[unix-history] / usr / src / usr.sbin / sendmail / src / main.c
... / ...
CommitLineData
1/*
2 * Copyright (c) 1983 Eric P. Allman
3 * Copyright (c) 1988 Regents of the University of California.
4 * All rights reserved.
5 *
6 * %sccs.include.redist.c%
7 */
8
9#ifndef lint
10char copyright[] =
11"@(#) Copyright (c) 1988 Regents of the University of California.\n\
12 All rights reserved.\n";
13#endif /* not lint */
14
15#ifndef lint
16static char sccsid[] = "@(#)main.c 6.7 (Berkeley) %G%";
17#endif /* not lint */
18
19#define _DEFINE
20
21#include <unistd.h>
22#include <sys/file.h>
23#include <sys/stat.h>
24#include <signal.h>
25#include <sgtty.h>
26#include "sendmail.h"
27#include <arpa/nameser.h>
28#include <resolv.h>
29
30# ifdef lint
31char edata, end;
32# endif lint
33
34/*
35** SENDMAIL -- Post mail to a set of destinations.
36**
37** This is the basic mail router. All user mail programs should
38** call this routine to actually deliver mail. Sendmail in
39** turn calls a bunch of mail servers that do the real work of
40** delivering the mail.
41**
42** Sendmail is driven by tables read in from /usr/lib/sendmail.cf
43** (read by readcf.c). Some more static configuration info,
44** including some code that you may want to tailor for your
45** installation, is in conf.c. You may also want to touch
46** daemon.c (if you have some other IPC mechanism), acct.c
47** (to change your accounting), names.c (to adjust the name
48** server mechanism).
49**
50** Usage:
51** /usr/lib/sendmail [flags] addr ...
52**
53** See the associated documentation for details.
54**
55** Author:
56** Eric Allman, UCB/INGRES (until 10/81)
57** Britton-Lee, Inc., purveyors of fine
58** database computers (from 11/81)
59** Now back at UCB at the Mammoth project.
60** The support of the INGRES Project and Britton-Lee is
61** gratefully acknowledged. Britton-Lee in
62** particular had absolutely nothing to gain from
63** my involvement in this project.
64*/
65
66
67int NextMailer; /* "free" index into Mailer struct */
68char *FullName; /* sender's full name */
69ENVELOPE BlankEnvelope; /* a "blank" envelope */
70ENVELOPE MainEnvelope; /* the envelope around the basic letter */
71ADDRESS NullAddress = /* a null address */
72 { "", "", NULL, "" };
73
74/*
75** Pointers for setproctitle.
76** This allows "ps" listings to give more useful information.
77** These must be kept out of BSS for frozen configuration files
78** to work.
79*/
80
81# ifdef SETPROCTITLE
82char **Argv = NULL; /* pointer to argument vector */
83char *LastArgv = NULL; /* end of argv */
84# endif /* SETPROCTITLE */
85
86/*
87** The file in which to log raw recipient information.
88** This is logged before aliasing, forwarding, and so forth so we
89** can see how our addresses are being used. For example, this
90** would give us the names of aliases (instead of what they alias
91** to), the pre-MX hostnames, and so forth.
92**
93** This is specified on the command line, not in the config file,
94** and is therefore really only useful for logging SMTP RCPTs.
95*/
96
97char *RcptLogFile = NULL; /* file name */
98
99static void obsolete();
100
101#ifdef DAEMON
102#ifndef SMTP
103ERROR %%%% Cannot have daemon mode without SMTP %%%% ERROR
104#endif /* SMTP */
105#endif /* DAEMON */
106
107#define MAXCONFIGLEVEL 3 /* highest config version level known */
108
109main(argc, argv, envp)
110 int argc;
111 char **argv;
112 char **envp;
113{
114 register char *p;
115 register char *q;
116 char **av;
117 char *locname;
118 extern int finis();
119 extern char Version[];
120 char *ep, *from;
121 typedef int (*fnptr)();
122 STAB *st;
123 register int i;
124 int j;
125 bool readconfig = TRUE;
126 bool queuemode = FALSE; /* process queue requests */
127 bool nothaw;
128 bool safecf = TRUE;
129 static bool reenter = FALSE;
130 char *argv0 = argv[0];
131 char jbuf[MAXHOSTNAMELEN]; /* holds MyHostName */
132 extern int DtableSize;
133 extern int optind;
134 extern bool safefile();
135 extern time_t convtime();
136 extern putheader(), putbody();
137 extern ENVELOPE *newenvelope();
138 extern void intsig();
139 extern char **myhostname();
140 extern char *arpadate();
141 extern char *optarg;
142
143 /*
144 ** Check to see if we reentered.
145 ** This would normally happen if e_putheader or e_putbody
146 ** were NULL when invoked.
147 */
148
149 if (reenter)
150 {
151 syserr("main: reentered!");
152 abort();
153 }
154 reenter = TRUE;
155 extern ADDRESS *recipient();
156 bool canrename;
157
158#ifndef SYS5TZ
159 /* enforce use of kernel-supplied time zone information */
160 unsetenv("TZ");
161#endif
162
163 /* in 4.4BSD, the table can be huge; impose a reasonable limit */
164 DtableSize = getdtablesize();
165 if (DtableSize > 256)
166 DtableSize = 256;
167
168 /*
169 ** Be sure we have enough file descriptors.
170 ** But also be sure that 0, 1, & 2 are open.
171 */
172
173 i = open("/dev/null", O_RDWR);
174 while (i >= 0 && i < 2)
175 i = dup(i);
176
177 i = DtableSize;
178 while (--i > 0)
179 {
180 if (i != STDIN_FILENO && i != STDOUT_FILENO && i != STDERR_FILENO)
181 (void) close(i);
182 }
183 errno = 0;
184
185#ifdef LOG_MAIL
186 openlog("sendmail", LOG_PID, LOG_MAIL);
187#else
188 openlog("sendmail", LOG_PID);
189#endif
190
191 /*
192 ** Set default values for variables.
193 ** These cannot be in initialized data space.
194 */
195
196 setdefaults();
197
198 /* set up the blank envelope */
199 BlankEnvelope.e_puthdr = putheader;
200 BlankEnvelope.e_putbody = putbody;
201 BlankEnvelope.e_xfp = NULL;
202 STRUCTCOPY(NullAddress, BlankEnvelope.e_from);
203 STRUCTCOPY(BlankEnvelope, MainEnvelope);
204 CurEnv = &MainEnvelope;
205
206 /* Handle any non-getoptable constructions. */
207 obsolete(argv);
208
209 /*
210 ** Do a quick prescan of the argument list.
211 ** We do this to find out if we can potentially thaw the
212 ** configuration file. If not, we do the thaw now so that
213 ** the argument processing applies to this run rather than
214 ** to the run that froze the configuration.
215 */
216 nothaw = FALSE;
217#define OPTIONS "b:C:cd:eF:f:h:Iimno:p:q:R:r:sTtv"
218 while ((j = getopt(argc, argv, OPTIONS)) != EOF)
219 {
220 switch (j)
221 {
222 case 'b':
223 if (optarg[0] == 'z' && optarg[1] == '\0')
224 nothaw = TRUE;
225 break;
226
227 case 'C':
228 ConfFile = optarg;
229 (void) setgid(getrgid());
230 (void) setuid(getruid());
231 safecf = FALSE;
232 nothaw = TRUE;
233 break;
234
235 case 'd':
236 tTsetup(tTdvect, sizeof tTdvect, "0-99.1");
237 tTflag(optarg);
238 setbuf(stdout, (char *) NULL);
239 printf("Version %s\n", Version);
240 break;
241 }
242 }
243
244 InChannel = stdin;
245 OutChannel = stdout;
246
247 if (!nothaw)
248 readconfig = !thaw(FreezeFile, argv0);
249
250# ifdef SETPROCTITLE
251 /*
252 ** Save start and extent of argv for setproctitle.
253 */
254
255 Argv = argv;
256 if (--i > 0)
257 LastArgv = envp[i - 1] + strlen(envp[i - 1]);
258 else
259 LastArgv = argv[argc - 1] + strlen(argv[argc - 1]);
260# endif /* SETPROCTITLE */
261
262 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
263 (void) signal(SIGINT, intsig);
264 if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
265 (void) signal(SIGHUP, intsig);
266 (void) signal(SIGTERM, intsig);
267 (void) signal(SIGPIPE, SIG_IGN);
268 OldUmask = umask(0);
269 OpMode = MD_DELIVER;
270 MotherPid = getpid();
271 FullName = getenv("NAME");
272
273 errno = 0;
274 from = NULL;
275
276 if (readconfig)
277 {
278 /* initialize some macros, etc. */
279 initmacros();
280
281 /* hostname */
282 av = myhostname(jbuf, sizeof jbuf);
283 if (jbuf[0] != '\0')
284 {
285 extern char *strchr();
286
287 if (tTd(0, 4))
288 printf("canonical name: %s\n", jbuf);
289 p = newstr(jbuf);
290 define('w', p, CurEnv);
291
292 q = strchr(jbuf, '.');
293 if (q != NULL)
294 {
295 *q++ = '\0';
296 p = newstr(jbuf);
297 define('m', q, CurEnv);
298 }
299 setclass('w', p);
300 }
301 while (av != NULL && *av != NULL)
302 {
303 if (tTd(0, 4))
304 printf("\ta.k.a.: %s\n", *av);
305 setclass('w', *av++);
306 }
307
308 /* version */
309 define('v', Version, CurEnv);
310 }
311
312 /* current time */
313 define('b', arpadate((char *) NULL), CurEnv);
314
315 /*
316 ** Crack argv.
317 */
318
319 av = argv;
320 p = strrchr(*av, '/');
321 if (p++ == NULL)
322 p = *av;
323 if (strcmp(p, "newaliases") == 0)
324 OpMode = MD_INITALIAS;
325 else if (strcmp(p, "mailq") == 0)
326 OpMode = MD_PRINT;
327 else if (strcmp(p, "smtpd") == 0)
328 OpMode = MD_DAEMON;
329
330 optind = 1;
331 while ((j = getopt(argc, argv, OPTIONS)) != EOF)
332 {
333 switch (j)
334 {
335 case 'b': /* operations mode */
336 switch (j = *optarg)
337 {
338 case MD_DAEMON:
339# ifdef DAEMON
340 if (getuid() != 0) {
341 usrerr("Permission denied");
342 exit (EX_USAGE);
343 }
344 (void) unsetenv("HOSTALIASES");
345# else
346 usrerr("Daemon mode not implemented");
347 ExitStat = EX_USAGE;
348 break;
349# endif /* DAEMON */
350 case MD_SMTP:
351# ifndef SMTP
352 usrerr("I don't speak SMTP");
353 ExitStat = EX_USAGE;
354 break;
355# endif /* SMTP */
356 case MD_DELIVER:
357 case MD_VERIFY:
358 case MD_TEST:
359 case MD_INITALIAS:
360 case MD_PRINT:
361 case MD_FREEZE:
362 OpMode = j;
363 break;
364
365 default:
366 usrerr("Invalid operation mode %c", j);
367 ExitStat = EX_USAGE;
368 break;
369 }
370 break;
371
372 case 'C': /* select configuration file (already done) */
373 break;
374
375 case 'd': /* debugging -- redo in case frozen */
376 tTsetup(tTdvect, sizeof tTdvect, "0-99.1");
377 tTflag(optarg);
378 setbuf(stdout, (char *) NULL);
379 break;
380
381 case 'f': /* from address */
382 case 'r': /* obsolete -f flag */
383 if (from != NULL)
384 {
385 usrerr("More than one \"from\" person");
386 ExitStat = EX_USAGE;
387 break;
388 }
389 from = newstr(optarg);
390 break;
391
392 case 'F': /* set full name */
393 FullName = newstr(optarg);
394 break;
395
396 case 'h': /* hop count */
397 CurEnv->e_hopcount = strtol(optarg, &ep, 10);
398 if (*ep)
399 {
400 usrerr("Bad hop count (%s)", optarg);
401 ExitStat = EX_USAGE;
402 break;
403 }
404 break;
405
406 case 'n': /* don't alias */
407 NoAlias = TRUE;
408 break;
409
410 case 'o': /* set option */
411 setoption(*optarg, optarg + 1, FALSE, TRUE);
412 break;
413
414 case 'p': /* set protocol */
415 q = strchr(optarg, ':');
416 if (q != NULL)
417 *q++ = '\0';
418 if (*optarg != '\0')
419 define('r', newstr(optarg), CurEnv);
420 if (*q != '\0')
421 define('s', newstr(q), CurEnv);
422 break;
423
424 case 'q': /* run queue files at intervals */
425# ifdef QUEUE
426 if (getuid() != 0)
427 {
428 struct stat stbuf;
429
430 /* check to see if we own the queue directory */
431 if (stat(QueueDir, &stbuf) < 0)
432 syserr("main: cannot stat %s", QueueDir);
433 if (stbuf.st_uid != getuid())
434 {
435 /* nope, really a botch */
436 usrerr("Permission denied");
437 exit (EX_NOPERM);
438 }
439 }
440 (void) unsetenv("HOSTALIASES");
441 FullName = NULL;
442 queuemode = TRUE;
443 QueueIntvl = convtime(optarg);
444# else /* QUEUE */
445 usrerr("I don't know about queues");
446 ExitStat = EX_USAGE;
447# endif /* QUEUE */
448 break;
449
450 case 't': /* read recipients from message */
451 GrabTo = TRUE;
452 break;
453
454 /* compatibility flags */
455 case 'c': /* connect to non-local mailers */
456 case 'e': /* error message disposition */
457 case 'i': /* don't let dot stop me */
458 case 'm': /* send to me too */
459 case 'T': /* set timeout interval */
460 case 'v': /* give blow-by-blow description */
461 setoption(j, "T", FALSE, TRUE);
462 break;
463
464 case 's': /* save From lines in headers */
465 setoption('f', "T", FALSE, TRUE);
466 break;
467
468# ifdef DBM
469 case 'I': /* initialize alias DBM file */
470 OpMode = MD_INITALIAS;
471 break;
472# endif /* DBM */
473
474 case 'R': /* log raw recipient info */
475 RcptLogFile = newstr(optarg);
476 break;
477
478 default:
479 ExitStat = EX_USAGE;
480 finis();
481 break;
482 }
483 }
484 av += optind;
485
486#ifdef NAMED_BIND
487 if (tTd(8, 1))
488 _res.options |= RES_DEBUG;
489#endif
490
491 /*
492 ** Do basic initialization.
493 ** Read system control file.
494 ** Extract special fields for local use.
495 */
496
497 if (OpMode == MD_FREEZE || readconfig)
498 readcf(ConfFile, safecf, CurEnv);
499
500#ifdef SYS5TZ
501 /* Enforce use of local time (null string overrides this) */
502 if (TimeZoneSpec == NULL)
503 unsetenv("TZ");
504 else if (TimeZoneSpec[0] != '\0')
505 {
506 p = xalloc(strlen(TimeZoneSpec) + 4);
507 (void) strcpy(p, "TZ=");
508 (void) strcat(p, TimeZoneSpec);
509 putenv(p);
510 }
511#endif
512
513 if (ConfigLevel > MAXCONFIGLEVEL)
514 {
515 syserr("Warning: .cf version level (%d) exceeds program functionality (%d)",
516 ConfigLevel, MAXCONFIGLEVEL);
517 }
518 switch (OpMode)
519 {
520 case MD_FREEZE:
521 /* this is critical to avoid forgeries of the frozen config */
522 (void) setgid(getgid());
523 (void) setuid(getuid());
524
525 /* freeze the configuration */
526 freeze(FreezeFile);
527 exit(EX_OK);
528
529 case MD_INITALIAS:
530 Verbose = TRUE;
531 break;
532
533 case MD_DAEMON:
534 /* remove things that don't make sense in daemon mode */
535 FullName = NULL;
536 break;
537 }
538
539 /* do heuristic mode adjustment */
540 if (Verbose)
541 {
542 /* turn off noconnect option */
543 setoption('c', "F", TRUE, FALSE);
544
545 /* turn on interactive delivery */
546 setoption('d', "", TRUE, FALSE);
547 }
548
549 /* our name for SMTP codes */
550 expand("\001j", jbuf, &jbuf[sizeof jbuf - 1], CurEnv);
551 MyHostName = jbuf;
552
553 /* the indices of built-in mailers */
554 st = stab("local", ST_MAILER, ST_FIND);
555 if (st == NULL)
556 syserr("No local mailer defined");
557 else
558 LocalMailer = st->s_mailer;
559
560 st = stab("prog", ST_MAILER, ST_FIND);
561 if (st == NULL)
562 syserr("No prog mailer defined");
563 else
564 ProgMailer = st->s_mailer;
565
566 st = stab("*file*", ST_MAILER, ST_FIND);
567 if (st == NULL)
568 syserr("No *file* mailer defined");
569 else
570 FileMailer = st->s_mailer;
571
572 st = stab("*include*", ST_MAILER, ST_FIND);
573 if (st == NULL)
574 syserr("No *include* mailer defined");
575 else
576 InclMailer = st->s_mailer;
577
578
579 /* operate in queue directory */
580 if (chdir(QueueDir) < 0)
581 {
582 syserr("cannot chdir(%s)", QueueDir);
583 exit(EX_SOFTWARE);
584 }
585
586 /*
587 ** Do operation-mode-dependent initialization.
588 */
589
590 switch (OpMode)
591 {
592 case MD_PRINT:
593 /* print the queue */
594#ifdef QUEUE
595 dropenvelope(CurEnv);
596 printqueue();
597 exit(EX_OK);
598#else /* QUEUE */
599 usrerr("No queue to print");
600 finis();
601#endif /* QUEUE */
602
603 case MD_INITALIAS:
604 /* initialize alias database */
605 initaliases(AliasFile, TRUE, CurEnv);
606 exit(EX_OK);
607
608 case MD_DAEMON:
609 /* don't open alias database -- done in srvrsmtp */
610 break;
611
612 default:
613 /* open the alias database */
614 initaliases(AliasFile, FALSE, CurEnv);
615 break;
616 }
617
618 if (tTd(0, 15))
619 {
620 /* print configuration table (or at least part of it) */
621 printrules();
622 for (i = 0; i < MAXMAILERS; i++)
623 {
624 register struct mailer *m = Mailer[i];
625 int j;
626
627 if (m == NULL)
628 continue;
629 printf("mailer %d (%s): P=%s S=%d R=%d M=%ld F=", i, m->m_name,
630 m->m_mailer, m->m_s_rwset, m->m_r_rwset,
631 m->m_maxsize);
632 for (j = '\0'; j <= '\177'; j++)
633 if (bitnset(j, m->m_flags))
634 (void) putchar(j);
635 printf(" E=");
636 xputs(m->m_eol);
637 if (m->m_argv != NULL)
638 {
639 char **a = m->m_argv;
640
641 printf(" A=");
642 while (*a != NULL)
643 {
644 if (a != m->m_argv)
645 printf(" ");
646 xputs(*a++);
647 }
648 }
649 printf("\n");
650 }
651 }
652
653 /*
654 ** Switch to the main envelope.
655 */
656
657 CurEnv = newenvelope(&MainEnvelope);
658 MainEnvelope.e_flags = BlankEnvelope.e_flags;
659
660 /*
661 ** If test mode, read addresses from stdin and process.
662 */
663
664 if (OpMode == MD_TEST)
665 {
666 bool terminal = isatty(fileno(stdin));
667 char buf[MAXLINE];
668
669 if (terminal)
670 {
671 printf("ADDRESS TEST MODE (ruleset 3 NOT automatically invoked)\n");
672 printf("Enter <ruleset> <address>\n");
673 }
674 for (;;)
675 {
676 register char **pvp;
677 char *q;
678 extern char *DelimChar;
679 extern bool invalidaddr();
680
681 if (terminal)
682 printf("> ");
683 (void) fflush(stdout);
684 if (fgets(buf, sizeof buf, stdin) == NULL)
685 finis();
686 if (!terminal)
687 printf("> %s", buf);
688 if (buf[0] == '#')
689 continue;
690 for (p = buf; isspace(*p); p++)
691 continue;
692 q = p;
693 while (*p != '\0' && !isspace(*p))
694 p++;
695 if (*p == '\0')
696 {
697 printf("No address!\n");
698 continue;
699 }
700 *p = '\0';
701 if (invalidaddr(p + 1))
702 continue;
703 do
704 {
705 extern char **prescan();
706 char pvpbuf[PSBUFSIZE];
707
708 pvp = prescan(++p, ',', pvpbuf);
709 if (pvp == NULL)
710 continue;
711 p = q;
712 while (*p != '\0')
713 {
714 rewrite(pvp, atoi(p));
715 while (*p != '\0' && *p++ != ',')
716 continue;
717 }
718 } while (*(p = DelimChar) != '\0');
719 }
720 }
721
722# ifdef QUEUE
723 /*
724 ** If collecting stuff from the queue, go start doing that.
725 */
726
727 if (queuemode && OpMode != MD_DAEMON && QueueIntvl == 0)
728 {
729 runqueue(FALSE);
730 finis();
731 }
732# endif /* QUEUE */
733
734 /*
735 ** If a daemon, wait for a request.
736 ** getrequests will always return in a child.
737 ** If we should also be processing the queue, start
738 ** doing it in background.
739 ** We check for any errors that might have happened
740 ** during startup.
741 */
742
743 if (OpMode == MD_DAEMON || QueueIntvl != 0)
744 {
745 if (!tTd(0, 1))
746 {
747 /* put us in background */
748 i = fork();
749 if (i < 0)
750 syserr("daemon: cannot fork");
751 if (i != 0)
752 exit(0);
753
754 /* get our pid right */
755 MotherPid = getpid();
756
757 /* disconnect from our controlling tty */
758 disconnect(TRUE);
759 }
760
761# ifdef QUEUE
762 if (queuemode)
763 {
764 runqueue(TRUE);
765 if (OpMode != MD_DAEMON)
766 for (;;)
767 pause();
768 }
769# endif /* QUEUE */
770 dropenvelope(CurEnv);
771
772#ifdef DAEMON
773 getrequests();
774
775 /* at this point we are in a child: reset state */
776 OpMode = MD_SMTP;
777 (void) newenvelope(CurEnv);
778 openxscript(CurEnv);
779#endif /* DAEMON */
780 }
781
782# ifdef SMTP
783 /*
784 ** If running SMTP protocol, start collecting and executing
785 ** commands. This will never return.
786 */
787
788 if (OpMode == MD_SMTP)
789 smtp(CurEnv);
790# endif /* SMTP */
791
792 /*
793 ** Do basic system initialization and set the sender
794 */
795
796 initsys(CurEnv);
797 setsender(from, CurEnv);
798
799 if (*av == NULL && !GrabTo)
800 {
801 usrerr("Recipient names must be specified");
802
803 /* collect body for UUCP return */
804 if (OpMode != MD_VERIFY)
805 collect(FALSE, CurEnv);
806 finis();
807 }
808 if (OpMode == MD_VERIFY)
809 SendMode = SM_VERIFY;
810
811 /*
812 ** Scan argv and deliver the message to everyone.
813 */
814
815 sendtoargv(av, CurEnv);
816
817 /* if we have had errors sofar, arrange a meaningful exit stat */
818 if (Errors > 0 && ExitStat == EX_OK)
819 ExitStat = EX_USAGE;
820
821 /*
822 ** Read the input mail.
823 */
824
825 CurEnv->e_to = NULL;
826 if (OpMode != MD_VERIFY || GrabTo)
827 collect(FALSE, CurEnv);
828 errno = 0;
829
830 /* collect statistics */
831 if (OpMode != MD_VERIFY)
832 markstats(CurEnv, (ADDRESS *) NULL);
833
834 if (tTd(1, 1))
835 printf("From person = \"%s\"\n", CurEnv->e_from.q_paddr);
836
837 /*
838 ** Actually send everything.
839 ** If verifying, just ack.
840 */
841
842 CurEnv->e_from.q_flags |= QDONTSEND;
843 CurEnv->e_to = NULL;
844 sendall(CurEnv, SM_DEFAULT);
845
846 /*
847 ** All done.
848 */
849
850 finis();
851}
852\f/*
853** FINIS -- Clean up and exit.
854**
855** Parameters:
856** none
857**
858** Returns:
859** never
860**
861** Side Effects:
862** exits sendmail
863*/
864
865finis()
866{
867 if (tTd(2, 1))
868 printf("\n====finis: stat %d e_flags %o\n", ExitStat, CurEnv->e_flags);
869
870 /* clean up temp files */
871 CurEnv->e_to = NULL;
872 dropenvelope(CurEnv);
873
874 /* flush any cached connections */
875 mci_flush();
876
877 /* post statistics */
878 poststats(StatFile);
879
880 /* and exit */
881# ifdef LOG
882 if (LogLevel > 11)
883 syslog(LOG_DEBUG, "finis, pid=%d", getpid());
884# endif /* LOG */
885 if (ExitStat == EX_TEMPFAIL)
886 ExitStat = EX_OK;
887 exit(ExitStat);
888}
889\f/*
890** INTSIG -- clean up on interrupt
891**
892** This just arranges to exit. It pessimises in that it
893** may resend a message.
894**
895** Parameters:
896** none.
897**
898** Returns:
899** none.
900**
901** Side Effects:
902** Unlocks the current job.
903*/
904
905void
906intsig()
907{
908 FileName = NULL;
909 unlockqueue(CurEnv);
910 exit(EX_OK);
911}
912\f/*
913** INITMACROS -- initialize the macro system
914**
915** This just involves defining some macros that are actually
916** used internally as metasymbols to be themselves.
917**
918** Parameters:
919** none.
920**
921** Returns:
922** none.
923**
924** Side Effects:
925** initializes several macros to be themselves.
926*/
927
928struct metamac MetaMacros[] =
929{
930 /* LHS pattern matching characters */
931 '*', MATCHZANY, '+', MATCHANY, '-', MATCHONE,
932 '=', MATCHCLASS, '~', MATCHNCLASS,
933
934 /* these are RHS metasymbols */
935 '#', CANONNET, '@', CANONHOST, ':', CANONUSER,
936 '>', CALLSUBR,
937 '{', MATCHLOOKUP, '}', MATCHELOOKUP,
938
939 /* the conditional operations */
940 '?', CONDIF, '|', CONDELSE, '.', CONDFI,
941
942 /* and finally the hostname lookup characters */
943 '[', HOSTBEGIN, ']', HOSTEND,
944 '(', LOOKUPBEGIN, ')', LOOKUPEND,
945
946 '\0'
947};
948
949initmacros()
950{
951 register struct metamac *m;
952 char buf[5];
953 register int c;
954
955 for (m = MetaMacros; m->metaname != '\0'; m++)
956 {
957 buf[0] = m->metaval;
958 buf[1] = '\0';
959 define(m->metaname, newstr(buf), CurEnv);
960 }
961 buf[0] = MATCHREPL;
962 buf[2] = '\0';
963 for (c = '0'; c <= '9'; c++)
964 {
965 buf[1] = c;
966 define(c, newstr(buf), CurEnv);
967 }
968}
969\f/*
970** FREEZE -- freeze BSS & allocated memory
971**
972** This will be used to efficiently load the configuration file.
973**
974** Parameters:
975** freezefile -- the name of the file to freeze to.
976**
977** Returns:
978** none.
979**
980** Side Effects:
981** Writes BSS and malloc'ed memory to freezefile
982*/
983
984union frz
985{
986 char frzpad[BUFSIZ]; /* insure we are on a BUFSIZ boundary */
987 struct
988 {
989 time_t frzstamp; /* timestamp on this freeze */
990 char *frzbrk; /* the current break */
991 char *frzedata; /* address of edata */
992 char *frzend; /* address of end */
993 char frzver[252]; /* sendmail version */
994 } frzinfo;
995};
996
997freeze(freezefile)
998 char *freezefile;
999{
1000 int f;
1001 union frz fhdr;
1002 extern char edata, end;
1003 extern char *sbrk();
1004 extern char Version[];
1005
1006 if (freezefile == NULL)
1007 return;
1008
1009 /* try to open the freeze file */
1010 f = creat(freezefile, FileMode);
1011 if (f < 0)
1012 {
1013 syserr("Cannot freeze %s", freezefile);
1014 errno = 0;
1015 return;
1016 }
1017
1018 /* build the freeze header */
1019 fhdr.frzinfo.frzstamp = curtime();
1020 fhdr.frzinfo.frzbrk = sbrk(0);
1021 fhdr.frzinfo.frzedata = &edata;
1022 fhdr.frzinfo.frzend = &end;
1023 (void) strcpy(fhdr.frzinfo.frzver, Version);
1024
1025 /* write out the freeze header */
1026 if (write(f, (char *) &fhdr, sizeof fhdr) != sizeof fhdr ||
1027 write(f, (char *) &edata, (int) (fhdr.frzinfo.frzbrk - &edata)) !=
1028 (int) (fhdr.frzinfo.frzbrk - &edata))
1029 {
1030 syserr("Cannot freeze %s", freezefile);
1031 }
1032
1033 /* fine, clean up */
1034 (void) close(f);
1035}
1036\f/*
1037** THAW -- read in the frozen configuration file.
1038**
1039** Parameters:
1040** freezefile -- the name of the file to thaw from.
1041** binfile -- the name of the sendmail binary (ok to guess).
1042**
1043** Returns:
1044** TRUE if it successfully read the freeze file.
1045** FALSE otherwise.
1046**
1047** Side Effects:
1048** reads freezefile in to BSS area.
1049*/
1050
1051thaw(freezefile, binfile)
1052 char *freezefile;
1053 char *binfile;
1054{
1055 int f;
1056 register char *p;
1057 union frz fhdr;
1058 char hbuf[60];
1059 struct stat fst, sst;
1060 extern char edata, end;
1061 extern char Version[];
1062 extern caddr_t brk();
1063 extern char **myhostname();
1064 extern char *macvalue();
1065
1066 if (freezefile == NULL)
1067 return (FALSE);
1068
1069 /* open the freeze file */
1070 f = open(freezefile, 0);
1071 if (f < 0)
1072 {
1073 errno = 0;
1074 return (FALSE);
1075 }
1076
1077 if (fstat(f, &fst) < 0 || stat(ConfFile, &sst) < 0 ||
1078 fst.st_mtime < sst.st_mtime)
1079 {
1080 syslog(LOG_WARNING, "Freeze file older than config file");
1081 (void) close(f);
1082 return (FALSE);
1083 }
1084
1085 if (strchr(binfile, '/') != NULL && stat(binfile, &sst) == 0 &&
1086 fst.st_mtime < sst.st_mtime)
1087 {
1088 syslog(LOG_WARNING, "Freeze file older than binary file");
1089 (void) close(f);
1090 return (FALSE);
1091 }
1092
1093 /* read in the header */
1094 if (read(f, (char *) &fhdr, sizeof fhdr) < sizeof fhdr)
1095 {
1096 syslog(LOG_WARNING, "Cannot read frozen config file");
1097 (void) close(f);
1098 return (FALSE);
1099 }
1100 if (fhdr.frzinfo.frzedata != &edata ||
1101 fhdr.frzinfo.frzend != &end ||
1102 strcmp(fhdr.frzinfo.frzver, Version) != 0)
1103 {
1104 syslog(LOG_WARNING, "Wrong version of frozen config file");
1105 (void) close(f);
1106 return (FALSE);
1107 }
1108
1109 /* arrange to have enough space */
1110 if (brk(fhdr.frzinfo.frzbrk) == (caddr_t) -1)
1111 {
1112 syserr("Cannot break to %x", fhdr.frzinfo.frzbrk);
1113 (void) close(f);
1114 return (FALSE);
1115 }
1116
1117 /* now read in the freeze file */
1118 if (read(f, (char *) &edata, (int) (fhdr.frzinfo.frzbrk - &edata)) !=
1119 (int) (fhdr.frzinfo.frzbrk - &edata))
1120 {
1121 syserr("Cannot read frozen config file");
1122 /* oops! we have trashed memory..... */
1123 (void) write(2, "Cannot read freeze file\n", 24);
1124 _exit(EX_SOFTWARE);
1125 }
1126
1127 (void) close(f);
1128
1129 /* verify that the host name was correct on the freeze */
1130 (void) myhostname(hbuf, sizeof hbuf);
1131 p = macvalue('w', CurEnv);
1132 if (p == NULL)
1133 p = "";
1134 if (strcmp(hbuf, macvalue('w', CurEnv)) == 0)
1135 return (TRUE);
1136 syslog(LOG_WARNING, "Hostname changed since freeze (%s => %s)",
1137 p, hbuf);
1138 return (FALSE);
1139}
1140\f/*
1141** DISCONNECT -- remove our connection with any foreground process
1142**
1143** Parameters:
1144** fulldrop -- if set, we should also drop the controlling
1145** TTY if possible -- this should only be done when
1146** setting up the daemon since otherwise UUCP can
1147** leave us trying to open a dialin, and we will
1148** wait for the carrier.
1149**
1150** Returns:
1151** none
1152**
1153** Side Effects:
1154** Trys to insure that we are immune to vagaries of
1155** the controlling tty.
1156*/
1157
1158disconnect(fulldrop)
1159 bool fulldrop;
1160{
1161 int fd;
1162
1163 if (tTd(52, 1))
1164 printf("disconnect: In %d Out %d\n", fileno(InChannel),
1165 fileno(OutChannel));
1166 if (tTd(52, 5))
1167 {
1168 printf("don't\n");
1169 return;
1170 }
1171
1172 /* be sure we don't get nasty signals */
1173 (void) signal(SIGHUP, SIG_IGN);
1174 (void) signal(SIGINT, SIG_IGN);
1175 (void) signal(SIGQUIT, SIG_IGN);
1176
1177 /* we can't communicate with our caller, so.... */
1178 HoldErrs = TRUE;
1179 ErrorMode = EM_MAIL;
1180 Verbose = FALSE;
1181
1182 /* all input from /dev/null */
1183 if (InChannel != stdin)
1184 {
1185 (void) fclose(InChannel);
1186 InChannel = stdin;
1187 }
1188 (void) freopen("/dev/null", "r", stdin);
1189
1190 /* output to the transcript */
1191 if (OutChannel != stdout)
1192 {
1193 (void) fclose(OutChannel);
1194 OutChannel = stdout;
1195 }
1196 if (CurEnv->e_xfp == NULL)
1197 CurEnv->e_xfp = fopen("/dev/null", "w");
1198 (void) fflush(stdout);
1199 (void) close(1);
1200 (void) close(2);
1201 while ((fd = dup(fileno(CurEnv->e_xfp))) < 2 && fd > 0)
1202 continue;
1203
1204 /* drop our controlling TTY completely if possible */
1205 if (fulldrop)
1206 {
1207 (void) setsid();
1208#ifdef TIOCNOTTY
1209 fd = open("/dev/tty", 2);
1210 if (fd >= 0)
1211 {
1212 (void) ioctl(fd, (int) TIOCNOTTY, (char *) 0);
1213 (void) close(fd);
1214 }
1215 (void) setpgrp(0, 0);
1216#endif /* TIOCNOTTY */
1217 errno = 0;
1218 }
1219
1220# ifdef LOG
1221 if (LogLevel > 11)
1222 syslog(LOG_DEBUG, "in background, pid=%d", getpid());
1223# endif /* LOG */
1224
1225 errno = 0;
1226}
1227
1228static void
1229obsolete(argv)
1230 char *argv[];
1231{
1232 char *ap;
1233
1234 while (ap = *++argv)
1235 {
1236 /* Return if "--" or not an option of any form. */
1237 if (ap[0] != '-' || ap[1] == '-')
1238 return;
1239
1240 /* If -C doesn't have an argument, use sendmail.cf. */
1241#define __DEFPATH "sendmail.cf"
1242 if (ap[1] == 'C' && ap[2] == '\0' &&
1243 (argv[1] == NULL || argv[1][0] == '-'))
1244 {
1245 *argv = xalloc(sizeof(__DEFPATH) + 2);
1246 argv[0][0] = '-';
1247 argv[0][1] = 'C';
1248 (void)strcpy(&argv[0][2], __DEFPATH);
1249 }
1250
1251 /* If -q doesn't have an argument, run it once. */
1252 if (ap[1] == 'q' && ap[2] == '\0' &&
1253 (argv[1] == NULL || argv[1][0] == '-'))
1254 *argv = "-q0";
1255
1256 /* if -d doesn't have an argument, use 0-99.1 */
1257 if (ap[1] == 'd' && ap[2] == '\0' &&
1258 (argv[1] == NULL || argv[1][0] == '-'))
1259 *argv = "-d0-99.1";
1260 }
1261}