2 * Copyright (c) 1998-2003 Sendmail, Inc. and its suppliers.
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.
16 SM_RCSID("@(#)$Id: daemon.c,v 8.613.2.17 2003/07/30 20:17:04 ca Exp $")
18 #if defined(SOCK_STREAM) || defined(__GNU_LIBRARY__)
19 # define USE_SOCK_STREAM 1
20 #endif /* defined(SOCK_STREAM) || defined(__GNU_LIBRARY__) */
22 #if defined(USE_SOCK_STREAM)
23 # if NETINET || NETINET6
24 # include <arpa/inet.h>
25 # endif /* NETINET || NETINET6 */
28 # define NO_DATA NO_ADDRESS
29 # endif /* ! NO_DATA */
30 # endif /* NAMED_BIND */
31 #endif /* defined(USE_SOCK_STREAM) */
34 # include <openssl/rand.h>
39 #if IP_SRCROUTE && NETINET
40 # include <netinet/in_systm.h>
41 # include <netinet/ip.h>
43 # include <netinet/in.h>
45 # define IPOPTION ip_opts
46 # define IP_LIST ip_opts
47 # define IP_DST ip_dst
48 # endif /* ! IPOPTION */
50 # include <netinet/ip_var.h>
52 # define IPOPTION ipoption
53 # define IP_LIST ipopt_list
54 # define IP_DST ipopt_dst
55 # endif /* ! IPOPTION */
56 # endif /* HAS_IN_H */
57 #endif /* IP_SRCROUTE && NETINET */
61 /* structure to describe a daemon or a client */
64 int d_socket; /* fd for socket */
65 SOCKADDR d_addr; /* socket for incoming */
66 unsigned short d_port; /* port number */
67 int d_listenqueue; /* size of listen queue */
68 int d_tcprcvbufsize; /* size of TCP receive buffer */
69 int d_tcpsndbufsize; /* size of TCP send buffer */
70 time_t d_refuse_connections_until;
73 BITMAP256 d_flags; /* flags; see sendmail.h */
74 char *d_mflags; /* flags for use in macro */
75 char *d_name; /* user-supplied name */
77 # if _FFR_MILTER_PERDAEMON
78 char *d_inputfilterlist;
79 struct milter *d_inputfilters[MAXFILTERS];
80 # endif /* _FFR_MILTER_PERDAEMON */
84 typedef struct daemon DAEMON_T;
86 static void connecttimeout __P((void));
87 static int opendaemonsocket __P((DAEMON_T *, bool));
88 static unsigned short setupdaemon __P((SOCKADDR *));
89 static void getrequests_checkdiskspace __P((ENVELOPE *e));
92 ** DAEMON.C -- routines to use when running as a daemon.
94 ** This entire file is highly dependent on the 4.2 BSD
95 ** interprocess communication primitives. No attempt has
96 ** been made to make this file portable to Version 7,
97 ** Version 6, MPX files, etc. If you should try such a
98 ** thing yourself, I recommend chucking the entire file
99 ** and starting from scratch. Basic semantics are:
102 ** Opens a port and initiates a connection.
103 ** Returns in a child. Must set InChannel and
104 ** OutChannel appropriately.
106 ** Close any open files associated with getting
107 ** the connection; this is used when running the queue,
108 ** etc., to avoid having extra file descriptors during
109 ** the queue run and to avoid confusing the network
110 ** code (if it cares).
111 ** makeconnection(host, port, mci, e, enough)
112 ** Make a connection to the named host on the given
113 ** port. Returns zero on success, else an exit status
114 ** describing the error.
115 ** host_map_lookup(map, hbuf, avp, pstat)
116 ** Convert the entry in hbuf into a canonical form.
119 static DAEMON_T Daemons[MAXDAEMONS];
120 static int NDaemons = 0; /* actual number of daemons */
122 static time_t NextDiskSpaceCheck = 0;
125 ** GETREQUESTS -- open mail IPC port and get requests.
128 ** e -- the current envelope.
134 ** Waits until some interesting activity occurs. When
135 ** it does, a child is created to process it, and the
136 ** parent waits for completion. Return from this
137 ** routine is always in the child. The file pointers
138 ** "InChannel" and "OutChannel" should be set to point
139 ** to the communication channel.
140 ** May restart persistent queue runners if they have ended
149 int idx, curdaemon = -1;
150 int i, olddaemon = 0;
154 char status[MAXLINE];
156 SOCKADDR_LEN_T len = sizeof sa;
157 #if _FFR_QUEUE_RUN_PARANOIA
159 #endif /* _FFR_QUEUE_RUN_PARANOIA */
161 extern int ControlSocket;
162 # endif /* NETUNIX */
163 extern ENVELOPE BlankEnvelope;
164 extern bool refuseconnections __P((char *, ENVELOPE *, int, bool));
167 for (idx = 0; idx < NDaemons; idx++)
169 Daemons[idx].d_port = setupdaemon(&(Daemons[idx].d_addr));
170 Daemons[idx].d_firsttime = true;
171 Daemons[idx].d_refuse_connections_until = (time_t) 0;
175 ** Try to actually open the connection.
180 for (idx = 0; idx < NDaemons; idx++)
182 sm_dprintf("getrequests: daemon %s: port %d\n",
184 ntohs(Daemons[idx].d_port));
188 /* get a socket for the SMTP connection */
189 for (idx = 0; idx < NDaemons; idx++)
190 Daemons[idx].d_socksize = opendaemonsocket(&Daemons[idx], true);
192 if (opencontrolsocket() < 0)
193 sm_syslog(LOG_WARNING, NOQID,
194 "daemon could not open control socket %s: %s",
195 ControlSocketName, sm_errstring(errno));
197 /* If there are any queue runners released reapchild() co-ord's */
198 (void) sm_signal(SIGCHLD, reapchild);
200 /* write the pid to file, command line args to syslog */
205 char jbuf[MAXHOSTNAMELEN];
207 expand("\201j", jbuf, sizeof jbuf, e);
208 j_has_dot = strchr(jbuf, '.') != NULL;
212 /* Add parent process as first item */
213 proc_list_add(CurrentPid, "Sendmail daemon", PROC_DAEMON, 0, -1);
217 for (idx = 0; idx < NDaemons; idx++)
218 sm_dprintf("getrequests: daemon %s: %d\n",
220 Daemons[idx].d_socket);
226 auto SOCKADDR_LEN_T lotherend;
227 bool timedout = false;
228 bool control = false;
234 #endif /* STARTTLS */
236 /* see if we are rejecting connections */
237 (void) sm_blocksignal(SIGALRM);
240 for (idx = 0; idx < NDaemons; idx++)
243 ** XXX do this call outside the loop?
244 ** no: refuse_connections may sleep().
248 if (now < Daemons[idx].d_refuse_connections_until)
250 if (bitnset(D_DISABLE, Daemons[idx].d_flags))
252 if (refuseconnections(Daemons[idx].d_name, e, idx,
255 if (Daemons[idx].d_socket >= 0)
257 /* close socket so peer fails quickly */
258 (void) close(Daemons[idx].d_socket);
259 Daemons[idx].d_socket = -1;
262 /* refuse connections for next 15 seconds */
263 Daemons[idx].d_refuse_connections_until = now + 15;
265 else if (Daemons[idx].d_socket < 0 ||
266 Daemons[idx].d_firsttime)
268 if (!Daemons[idx].d_firsttime && LogLevel > 8)
269 sm_syslog(LOG_INFO, NOQID,
270 "accepting connections again for daemon %s",
271 Daemons[idx].d_name);
273 /* arrange to (re)open the socket if needed */
274 (void) opendaemonsocket(&Daemons[idx], false);
275 Daemons[idx].d_firsttime = false;
279 /* May have been sleeping above, check again */
281 getrequests_checkdiskspace(e);
284 /* check for disaster */
286 char jbuf[MAXHOSTNAMELEN];
288 expand("\201j", jbuf, sizeof jbuf, e);
289 if (!wordinclass(jbuf, 'w'))
291 dumpstate("daemon lost $j");
292 sm_syslog(LOG_ALERT, NOQID,
293 "daemon process doesn't have $j in $=w; see syslog");
296 else if (j_has_dot && strchr(jbuf, '.') == NULL)
298 dumpstate("daemon $j lost dot");
299 sm_syslog(LOG_ALERT, NOQID,
300 "daemon process $j lost dot; see syslog");
308 ** Andrew Sun <asun@ieps-sun.ml.com> claims that this will
309 ** fix the SVr4 problem. But it seems to have gone away,
310 ** so is it worth doing this?
313 if (DaemonSocket >= 0 &&
314 SetNonBlocking(DaemonSocket, false) < 0)
317 (void) sm_releasesignal(SIGALRM);
321 bool setproc = false;
324 struct timeval timeout;
328 for (idx = 0; idx < NDaemons; idx++)
330 /* wait for a connection */
331 if (Daemons[idx].d_socket >= 0)
335 Daemons[idx].d_flags))
337 sm_setproctitle(true, e,
338 "accepting connections");
341 if (Daemons[idx].d_socket > highest)
342 highest = Daemons[idx].d_socket;
343 SM_FD_SET(Daemons[idx].d_socket,
349 if (ControlSocket >= 0)
351 if (ControlSocket > highest)
352 highest = ControlSocket;
353 SM_FD_SET(ControlSocket, &readfds);
360 t = select(highest + 1, FDSET_CAST &readfds,
361 NULL, NULL, &timeout);
363 /* Did someone signal while waiting? */
370 (void) runqueue(true, false, false, false);
371 #if _FFR_QUEUE_RUN_PARANOIA
373 #endif /* _FFR_QUEUE_RUN_PARANOIA */
375 #if _FFR_QUEUE_RUN_PARANOIA
376 else if (QueueIntvl > 0 &&
377 lastrun + QueueIntvl + 60 < now)
381 ** set lastrun unconditionally to avoid
382 ** calling checkqueuerunner() all the time.
383 ** That's also why we currently ignore the
384 ** result of the function call.
387 (void) checkqueuerunner();
390 #endif /* _FFR_QUEUE_RUN_PARANOIA */
401 /* look "round-robin" for an active socket */
402 if ((idx = olddaemon + 1) >= NDaemons)
404 for (i = 0; i < NDaemons; i++)
406 if (Daemons[idx].d_socket >= 0 &&
407 SM_FD_ISSET(Daemons[idx].d_socket,
410 lotherend = Daemons[idx].d_socksize;
411 memset(&RealHostAddr, '\0',
412 sizeof RealHostAddr);
413 t = accept(Daemons[idx].d_socket,
414 (struct sockaddr *)&RealHostAddr,
418 ** If remote side closes before
419 ** accept() finishes, sockaddr
420 ** might not be fully filled in.
425 # ifdef BSD4_4_SOCKADDR
426 RealHostAddr.sa.sa_len == 0 ||
427 # endif /* BSD4_4_SOCKADDR */
428 RealHostAddr.sa.sa_family != Daemons[idx].d_addr.sa.sa_family))
434 olddaemon = curdaemon = idx;
437 if (++idx >= NDaemons)
441 if (curdaemon == -1 && ControlSocket >= 0 &&
442 SM_FD_ISSET(ControlSocket, &readfds))
444 struct sockaddr_un sa_un;
446 lotherend = sizeof sa_un;
447 memset(&sa_un, '\0', sizeof sa_un);
448 t = accept(ControlSocket,
449 (struct sockaddr *)&sa_un,
453 ** If remote side closes before
454 ** accept() finishes, sockaddr
455 ** might not be fully filled in.
460 # ifdef BSD4_4_SOCKADDR
461 sa_un.sun_len == 0 ||
462 # endif /* BSD4_4_SOCKADDR */
463 sa_un.sun_family != AF_UNIX))
475 /* No daemon to service */
479 if (t >= 0 || errno != EINTR)
488 (void) sm_blocksignal(SIGALRM);
492 syserr("getrequests: accept");
494 /* arrange to re-open the socket next time around */
495 (void) close(Daemons[curdaemon].d_socket);
496 Daemons[curdaemon].d_socket = -1;
497 #if SO_REUSEADDR_IS_BROKEN
499 ** Give time for bound socket to be released.
500 ** This creates a denial-of-service if you can
501 ** force accept() to fail on affected systems.
504 Daemons[curdaemon].d_refuse_connections_until = curtime() + 15;
505 #endif /* SO_REUSEADDR_IS_BROKEN */
511 /* set some daemon related macros */
512 switch (Daemons[curdaemon].d_addr.sa.sa_family)
515 macdefine(&BlankEnvelope.e_macro, A_PERM,
516 macid("{daemon_family}"), "unspec");
518 #if _FFR_DAEMON_NETUNIX
521 macdefine(&BlankEnvelope.e_macro, A_PERM,
522 macid("{daemon_family}"), "local");
524 # endif /* NETUNIX */
525 #endif /* _FFR_DAEMON_NETUNIX */
528 macdefine(&BlankEnvelope.e_macro, A_PERM,
529 macid("{daemon_family}"), "inet");
534 macdefine(&BlankEnvelope.e_macro, A_PERM,
535 macid("{daemon_family}"), "inet6");
537 #endif /* NETINET6 */
540 macdefine(&BlankEnvelope.e_macro, A_PERM,
541 macid("{daemon_family}"), "iso");
546 macdefine(&BlankEnvelope.e_macro, A_PERM,
547 macid("{daemon_family}"), "ns");
552 macdefine(&BlankEnvelope.e_macro, A_PERM,
553 macid("{daemon_family}"), "x.25");
557 macdefine(&BlankEnvelope.e_macro, A_PERM,
558 macid("{daemon_name}"),
559 Daemons[curdaemon].d_name);
560 if (Daemons[curdaemon].d_mflags != NULL)
561 macdefine(&BlankEnvelope.e_macro, A_PERM,
562 macid("{daemon_flags}"),
563 Daemons[curdaemon].d_mflags);
565 macdefine(&BlankEnvelope.e_macro, A_PERM,
566 macid("{daemon_flags}"), "");
570 ** Create a subprocess to process the mail.
574 sm_dprintf("getrequests: forking (fd = %d)\n", t);
577 ** Advance state of PRNG.
578 ** This is necessary because otherwise all child processes
579 ** will produce the same PRN sequence and hence the selection
580 ** of a queue directory (and other things, e.g., MX selection)
581 ** are not "really" random.
584 /* XXX get some better "random" data? */
586 RAND_seed((void *) &NextDiskSpaceCheck,
587 sizeof NextDiskSpaceCheck);
588 RAND_seed((void *) &now, sizeof now);
589 RAND_seed((void *) &seed, sizeof seed);
592 #endif /* STARTTLS */
596 ** Update MX records for FallBackMX.
597 ** Let's hope this is fast otherwise we screw up the
601 if (FallBackMX != NULL)
602 (void) getfallbackmxrr(FallBackMX);
603 #endif /* NAMED_BIND */
607 /* don't fork, handle connection in this process */
609 pipefd[0] = pipefd[1] = -1;
614 ** Create a pipe to keep the child from writing to
615 ** the socket until after the parent has closed
616 ** it. Otherwise the parent may hang if the child
617 ** has closed it first.
620 if (pipe(pipefd) < 0)
621 pipefd[0] = pipefd[1] = -1;
623 (void) sm_blocksignal(SIGCHLD);
627 syserr("daemon: cannot fork");
630 (void) close(pipefd[0]);
631 (void) close(pipefd[1]);
633 (void) sm_releasesignal(SIGCHLD);
643 SM_FILE_T *inchannel, *outchannel = NULL;
646 ** CHILD -- return to caller.
647 ** Collect verified idea of sending host.
648 ** Verify calling user id if possible here.
651 /* Reset global flags */
652 RestartRequest = NULL;
653 RestartWorkGroup = false;
654 ShutdownRequest = NULL;
656 CurrentPid = getpid();
658 (void) sm_releasesignal(SIGALRM);
659 (void) sm_releasesignal(SIGCHLD);
660 (void) sm_signal(SIGCHLD, SIG_DFL);
661 (void) sm_signal(SIGHUP, SIG_DFL);
662 (void) sm_signal(SIGTERM, intsig);
664 /* turn on profiling */
668 ** Initialize exception stack and default exception
669 ** handler for child process.
672 sm_exc_newthread(fatal_error);
676 macdefine(&BlankEnvelope.e_macro, A_TEMP,
677 macid("{daemon_addr}"),
678 anynet_ntoa(&Daemons[curdaemon].d_addr));
679 (void) sm_snprintf(status, sizeof status, "%d",
680 ntohs(Daemons[curdaemon].d_port));
681 macdefine(&BlankEnvelope.e_macro, A_TEMP,
682 macid("{daemon_port}"), status);
685 for (idx = 0; idx < NDaemons; idx++)
687 if (Daemons[idx].d_socket >= 0)
688 (void) close(Daemons[idx].d_socket);
689 Daemons[idx].d_socket = -1;
693 /* Avoid SMTP daemon actions if control command */
696 /* Add control socket process */
697 proc_list_add(CurrentPid,
698 "console socket child",
699 PROC_CONTROL_CHILD, 0, -1);
705 /* clean up background delivery children */
706 (void) sm_signal(SIGCHLD, reapchild);
708 /* Add parent process as first child item */
709 proc_list_add(CurrentPid, "daemon child",
710 PROC_DAEMON_CHILD, 0, -1);
712 /* don't schedule queue runs if ETRN */
715 sm_setproctitle(true, e, "startup with %s",
716 anynet_ntoa(&RealHostAddr));
724 ** Wait for the parent to close the write end
725 ** of the pipe, which we will see as an EOF.
726 ** This guarantees that we won't write to the
727 ** socket until after the parent has closed
731 /* close the write end of the pipe */
732 (void) close(pipefd[1]);
734 /* we shouldn't be interrupted, but ... */
735 while (read(pipefd[0], &c, 1) < 0 &&
738 (void) close(pipefd[0]);
741 /* control socket processing */
744 control_command(t, e);
749 /* determine host name */
750 p = hostnamebyanyaddr(&RealHostAddr);
751 if (strlen(p) > MAXNAME) /* XXX - 1 ? */
753 RealHostName = newstr(p);
754 if (RealHostName[0] == '[')
756 macdefine(&BlankEnvelope.e_macro, A_PERM,
757 macid("{client_resolve}"),
758 h_errno == TRY_AGAIN ? "TEMP" : "FAIL");
761 macdefine(&BlankEnvelope.e_macro, A_PERM,
762 macid("{client_resolve}"), "OK");
763 sm_setproctitle(true, e, "startup with %s", p);
764 markstats(e, NULL, STATS_CONNECT);
766 if ((inchannel = sm_io_open(SmFtStdiofd,
772 (outchannel = sm_io_open(SmFtStdiofd,
778 syserr("cannot open SMTP server channel, fd=%d",
780 finis(false, true, EX_OK);
782 sm_io_automode(inchannel, outchannel);
784 InChannel = inchannel;
785 OutChannel = outchannel;
786 DisConnected = false;
789 if (!xla_host_ok(RealHostName))
791 message("421 4.4.5 Too many SMTP sessions for this host");
792 finis(false, true, EX_OK);
795 /* find out name for interface of connection */
796 if (getsockname(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
797 NULL), &sa.sa, &len) == 0)
799 p = hostnamebyanyaddr(&sa);
801 sm_dprintf("getreq: got name %s\n", p);
802 macdefine(&BlankEnvelope.e_macro, A_TEMP,
803 macid("{if_name}"), p);
806 ** Do this only if it is not the loopback
815 addr = anynet_ntoa(&sa);
816 (void) sm_snprintf(family,
818 "%d", sa.sa.sa_family);
819 macdefine(&BlankEnvelope.e_macro,
821 macid("{if_addr}"), addr);
822 macdefine(&BlankEnvelope.e_macro,
824 macid("{if_family}"), family);
826 sm_dprintf("getreq: got addr %s and family %s\n",
831 macdefine(&BlankEnvelope.e_macro,
833 macid("{if_addr}"), NULL);
834 macdefine(&BlankEnvelope.e_macro,
836 macid("{if_family}"), NULL);
842 sm_dprintf("getreq: getsockname failed\n");
843 macdefine(&BlankEnvelope.e_macro, A_PERM,
844 macid("{if_name}"), NULL);
845 macdefine(&BlankEnvelope.e_macro, A_PERM,
846 macid("{if_addr}"), NULL);
847 macdefine(&BlankEnvelope.e_macro, A_PERM,
848 macid("{if_family}"), NULL);
853 /* parent -- keep track of children */
856 (void) sm_snprintf(status, sizeof status,
857 "control socket server child");
858 proc_list_add(pid, status, PROC_CONTROL, 0, -1);
862 (void) sm_snprintf(status, sizeof status,
863 "SMTP server child for %s",
864 anynet_ntoa(&RealHostAddr));
865 proc_list_add(pid, status, PROC_DAEMON, 0, -1);
867 (void) sm_releasesignal(SIGCHLD);
869 /* close the read end of the synchronization pipe */
872 (void) close(pipefd[0]);
876 /* close the port so that others will hang (for a while) */
879 /* release the child by closing the read end of the sync pipe */
882 (void) close(pipefd[1]);
887 sm_dprintf("getreq: returning\n");
890 # if _FFR_MILTER_PERDAEMON
891 /* set the filters for this daemon */
892 if (Daemons[curdaemon].d_inputfilterlist != NULL)
896 Daemons[curdaemon].d_inputfilters[i] != NULL);
899 InputFilters[i] = Daemons[curdaemon].d_inputfilters[i];
902 InputFilters[i] = NULL;
904 # endif /* _FFR_MILTER_PERDAEMON */
906 return &Daemons[curdaemon].d_flags;
910 ** GETREQUESTS_CHECKDISKSPACE -- check available diskspace.
919 ** Modifies Daemon flags (D_ETRNONLY) if not enough disk space.
923 getrequests_checkdiskspace(e)
931 if (now < NextDiskSpaceCheck)
934 /* Check if there is available disk space in all queue groups. */
935 if (!enoughdiskspace(0, NULL))
937 for (idx = 0; idx < NDaemons; ++idx)
939 if (bitnset(D_ETRNONLY, Daemons[idx].d_flags))
942 /* log only if not logged before */
946 sm_syslog(LOG_INFO, NOQID,
947 "rejecting new messages: min free: %ld",
949 sm_setproctitle(true, e,
950 "rejecting new messages: min free: %ld",
954 setbitn(D_ETRNONLY, Daemons[idx].d_flags);
959 for (idx = 0; idx < NDaemons; ++idx)
961 if (!bitnset(D_ETRNONLY, Daemons[idx].d_flags))
964 /* log only if not logged before */
968 sm_syslog(LOG_INFO, NOQID,
969 "accepting new messages (again)");
973 /* title will be set later */
974 clrbitn(D_ETRNONLY, Daemons[idx].d_flags);
978 /* only check disk space once a minute */
979 NextDiskSpaceCheck = now + 60;
983 ** OPENDAEMONSOCKET -- open SMTP socket
985 ** Deals with setting all appropriate options.
988 ** d -- the structure for the daemon to open.
989 ** firsttime -- set if this is the initial open.
992 ** Size in bytes of the daemon socket addr.
995 ** Leaves DaemonSocket set to the open socket.
996 ** Exits if the socket cannot be created.
999 #define MAXOPENTRIES 10 /* maximum number of tries to open connection */
1002 opendaemonsocket(d, firsttime)
1008 SOCKADDR_LEN_T socksize = 0;
1013 sm_dprintf("opendaemonsocket(%s)\n", d->d_name);
1019 if (firsttime || d->d_socket < 0)
1021 #if _FFR_DAEMON_NETUNIX
1023 if (d->d_addr.sa.sa_family == AF_UNIX)
1026 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_ROOTOK|SFF_EXECOK|SFF_CREAT;
1028 /* if not safe, don't use it */
1029 rval = safefile(d->d_addr.sunix.sun_path,
1032 S_IRUSR|S_IWUSR, NULL);
1036 syserr("opendaemonsocket: daemon %s: unsafe domain socket %s",
1038 d->d_addr.sunix.sun_path);
1042 /* Don't try to overtake an existing socket */
1043 (void) unlink(d->d_addr.sunix.sun_path);
1045 # endif /* NETUNIX */
1046 #endif /* _FFR_DOMAIN_NETUNIX */
1047 d->d_socket = socket(d->d_addr.sa.sa_family,
1049 if (d->d_socket < 0)
1052 syserr("opendaemonsocket: daemon %s: can't create server SMTP socket",
1055 if (bitnset(D_OPTIONAL, d->d_flags) &&
1056 (!transienterror(save_errno) ||
1057 ntries >= MAXOPENTRIES - 1))
1059 syserr("opendaemonsocket: daemon %s: optional socket disabled",
1061 setbitn(D_DISABLE, d->d_flags);
1067 sm_syslog(LOG_ALERT, NOQID,
1068 "daemon %s: problem creating SMTP socket",
1074 if (SM_FD_SETSIZE > 0 && d->d_socket >= SM_FD_SETSIZE)
1076 save_errno = EINVAL;
1077 syserr("opendaemonsocket: daemon %s: server SMTP socket (%d) too large",
1078 d->d_name, d->d_socket);
1082 /* turn on network debugging? */
1084 (void) setsockopt(d->d_socket, SOL_SOCKET,
1085 SO_DEBUG, (char *)&on,
1088 (void) setsockopt(d->d_socket, SOL_SOCKET,
1089 SO_REUSEADDR, (char *)&on, sizeof on);
1090 (void) setsockopt(d->d_socket, SOL_SOCKET,
1091 SO_KEEPALIVE, (char *)&on, sizeof on);
1094 if (d->d_tcprcvbufsize > 0)
1096 if (setsockopt(d->d_socket, SOL_SOCKET,
1098 (char *) &d->d_tcprcvbufsize,
1099 sizeof(d->d_tcprcvbufsize)) < 0)
1100 syserr("opendaemonsocket: daemon %s: setsockopt(SO_RCVBUF)", d->d_name);
1102 #endif /* SO_RCVBUF */
1104 if (d->d_tcpsndbufsize > 0)
1106 if (setsockopt(d->d_socket, SOL_SOCKET,
1108 (char *) &d->d_tcpsndbufsize,
1109 sizeof(d->d_tcpsndbufsize)) < 0)
1110 syserr("opendaemonsocket: daemon %s: setsockopt(SO_SNDBUF)", d->d_name);
1112 #endif /* SO_SNDBUF */
1114 if ((fdflags = fcntl(d->d_socket, F_GETFD, 0)) == -1 ||
1115 fcntl(d->d_socket, F_SETFD,
1116 fdflags | FD_CLOEXEC) == -1)
1119 syserr("opendaemonsocket: daemon %s: failed to %s close-on-exec flag: %s",
1121 fdflags == -1 ? "get" : "set",
1122 sm_errstring(save_errno));
1123 (void) close(d->d_socket);
1127 switch (d->d_addr.sa.sa_family)
1129 #if _FFR_DAEMON_NETUNIX
1132 socksize = sizeof d->d_addr.sunix;
1134 # endif /* NETUNIX */
1135 #endif /* _FFR_DAEMON_NETUNIX */
1138 socksize = sizeof d->d_addr.sin;
1140 #endif /* NETINET */
1144 socksize = sizeof d->d_addr.sin6;
1146 #endif /* NETINET6 */
1150 socksize = sizeof d->d_addr.siso;
1155 socksize = sizeof d->d_addr;
1159 if (bind(d->d_socket, &d->d_addr.sa, socksize) < 0)
1161 /* probably another daemon already */
1163 syserr("opendaemonsocket: daemon %s: cannot bind",
1165 (void) close(d->d_socket);
1170 listen(d->d_socket, d->d_listenqueue) < 0)
1173 syserr("opendaemonsocket: daemon %s: cannot listen",
1175 (void) close(d->d_socket);
1179 } while (ntries++ < MAXOPENTRIES && transienterror(save_errno));
1180 syserr("!opendaemonsocket: daemon %s: server SMTP socket wedged: exiting",
1183 return -1; /* avoid compiler warning on IRIX */
1186 ** SETUPDAEMON -- setup socket for daemon
1189 ** daemonaddr -- socket for daemon
1192 ** port number on which daemon should run
1196 static unsigned short
1197 setupdaemon(daemonaddr)
1198 SOCKADDR *daemonaddr;
1200 unsigned short port;
1203 ** Set up the address for the mailer.
1206 if (daemonaddr->sa.sa_family == AF_UNSPEC)
1208 memset(daemonaddr, '\0', sizeof *daemonaddr);
1210 daemonaddr->sa.sa_family = AF_INET;
1211 #endif /* NETINET */
1214 switch (daemonaddr->sa.sa_family)
1218 if (daemonaddr->sin.sin_addr.s_addr == 0)
1219 daemonaddr->sin.sin_addr.s_addr = INADDR_ANY;
1220 port = daemonaddr->sin.sin_port;
1222 #endif /* NETINET */
1226 if (IN6_IS_ADDR_UNSPECIFIED(&daemonaddr->sin6.sin6_addr))
1227 daemonaddr->sin6.sin6_addr = in6addr_any;
1228 port = daemonaddr->sin6.sin6_port;
1230 #endif /* NETINET6 */
1233 /* unknown protocol */
1239 #ifdef NO_GETSERVBYNAME
1241 #else /* NO_GETSERVBYNAME */
1243 register struct servent *sp;
1245 sp = getservbyname("smtp", "tcp");
1248 syserr("554 5.3.5 service \"smtp\" unknown");
1254 #endif /* NO_GETSERVBYNAME */
1257 switch (daemonaddr->sa.sa_family)
1261 daemonaddr->sin.sin_port = port;
1263 #endif /* NETINET */
1267 daemonaddr->sin6.sin6_port = port;
1269 #endif /* NETINET6 */
1272 /* unknown protocol */
1278 ** CLRDAEMON -- reset the daemon connection
1287 ** releases any resources used by the passive daemon.
1295 for (i = 0; i < NDaemons; i++)
1297 if (Daemons[i].d_socket >= 0)
1298 (void) close(Daemons[i].d_socket);
1299 Daemons[i].d_socket = -1;
1304 ** GETMODIFIERS -- get modifier flags
1307 ** v -- the modifiers (input text line).
1308 ** modifiers -- pointer to flag field to represent modifiers.
1311 ** (xallocat()ed) string representation of modifiers.
1314 ** fills in modifiers.
1318 getmodifiers(v, modifiers)
1320 BITMAP256 modifiers;
1323 char *h, *f, *flags;
1325 /* maximum length of flags: upper case Option -> "OO " */
1326 l = 3 * strlen(v) + 3;
1328 /* is someone joking? */
1329 if (l < 0 || l > 256)
1332 sm_syslog(LOG_ERR, NOQID,
1333 "getmodifiers too long, ignored");
1338 clrbitmap(modifiers);
1339 for (h = v; *h != '\0'; h++)
1341 if (isascii(*h) && !isspace(*h) && isprint(*h))
1343 setbitn(*h, modifiers);
1356 ** CHKDAEMONMODIFIERS -- check whether all daemons have set a flag.
1359 ** flag -- the flag to test.
1362 ** true iff all daemons have set flag.
1366 chkdaemonmodifiers(flag)
1371 for (i = 0; i < NDaemons; i++)
1372 if (!bitnset((char) flag, Daemons[i].d_flags))
1378 ** SETSOCKADDROPTIONS -- set options for SOCKADDR (daemon or client)
1381 ** p -- the options line.
1382 ** d -- the daemon structure to fill in.
1389 setsockaddroptions(p, d)
1400 if (d->d_addr.sa.sa_family == AF_UNSPEC)
1401 d->d_addr.sa.sa_family = AF_INET;
1402 #endif /* NETINET */
1409 while (isascii(*p) && isspace(*p))
1420 while (isascii(*++v) && isspace(*v))
1422 if (isascii(*f) && islower(*f))
1427 case 'F': /* address family */
1428 if (isascii(*v) && isdigit(*v))
1429 d->d_addr.sa.sa_family = atoi(v);
1430 #if _FFR_DAEMON_NETUNIX
1432 else if (sm_strcasecmp(v, "unix") == 0 ||
1433 sm_strcasecmp(v, "local") == 0)
1434 d->d_addr.sa.sa_family = AF_UNIX;
1435 # endif /* NETUNIX */
1436 #endif /* _FFR_DAEMON_NETUNIX */
1438 else if (sm_strcasecmp(v, "inet") == 0)
1439 d->d_addr.sa.sa_family = AF_INET;
1440 #endif /* NETINET */
1442 else if (sm_strcasecmp(v, "inet6") == 0)
1443 d->d_addr.sa.sa_family = AF_INET6;
1444 #endif /* NETINET6 */
1446 else if (sm_strcasecmp(v, "iso") == 0)
1447 d->d_addr.sa.sa_family = AF_ISO;
1450 else if (sm_strcasecmp(v, "ns") == 0)
1451 d->d_addr.sa.sa_family = AF_NS;
1454 else if (sm_strcasecmp(v, "x.25") == 0)
1455 d->d_addr.sa.sa_family = AF_CCITT;
1458 syserr("554 5.3.5 Unknown address family %s in Family=option",
1462 case 'A': /* address */
1467 # if _FFR_MILTER_PERDAEMON
1469 d->d_inputfilterlist = v;
1471 # endif /* _FFR_MILTER_PERDAEMON */
1474 case 'P': /* port */
1478 case 'L': /* listen queue size */
1479 d->d_listenqueue = atoi(v);
1482 case 'M': /* modifiers (flags) */
1483 d->d_mflags = getmodifiers(v, d->d_flags);
1486 case 'S': /* send buffer size */
1487 d->d_tcpsndbufsize = atoi(v);
1490 case 'R': /* receive buffer size */
1491 d->d_tcprcvbufsize = atoi(v);
1494 case 'N': /* name */
1499 syserr("554 5.3.5 PortOptions parameter \"%s\" unknown",
1504 /* Check addr and port after finding family */
1507 switch (d->d_addr.sa.sa_family)
1509 #if _FFR_DAEMON_NETUNIX
1512 if (strlen(addr) >= sizeof(d->d_addr.sunix.sun_path))
1514 errno = ENAMETOOLONG;
1515 syserr("setsockaddroptions: domain socket name too long: %s > %d",
1516 addr, sizeof(d->d_addr.sunix.sun_path));
1520 /* file safety check done in opendaemonsocket() */
1521 (void) memset(&d->d_addr.sunix.sun_path, '\0',
1522 sizeof(d->d_addr.sunix.sun_path));
1523 (void) sm_strlcpy((char *)&d->d_addr.sunix.sun_path,
1525 sizeof(d->d_addr.sunix.sun_path));
1527 # endif /* NETUNIX */
1528 #endif /* _FFR_DAEMON_NETUNIX */
1531 if (!isascii(*addr) || !isdigit(*addr) ||
1532 ((d->d_addr.sin.sin_addr.s_addr = inet_addr(addr))
1535 register struct hostent *hp;
1537 hp = sm_gethostbyname(addr, AF_INET);
1539 syserr("554 5.3.0 host \"%s\" unknown",
1543 while (*(hp->h_addr_list) != NULL &&
1544 hp->h_addrtype != AF_INET)
1546 if (*(hp->h_addr_list) == NULL)
1547 syserr("554 5.3.0 host \"%s\" unknown",
1550 memmove(&d->d_addr.sin.sin_addr,
1556 # endif /* NETINET6 */
1560 #endif /* NETINET */
1564 if (anynet_pton(AF_INET6, addr,
1565 &d->d_addr.sin6.sin6_addr) != 1)
1567 register struct hostent *hp;
1569 hp = sm_gethostbyname(addr, AF_INET6);
1571 syserr("554 5.3.0 host \"%s\" unknown",
1575 while (*(hp->h_addr_list) != NULL &&
1576 hp->h_addrtype != AF_INET6)
1578 if (*(hp->h_addr_list) == NULL)
1579 syserr("554 5.3.0 host \"%s\" unknown",
1582 memmove(&d->d_addr.sin6.sin6_addr,
1590 #endif /* NETINET6 */
1593 syserr("554 5.3.5 address= option unsupported for family %d",
1594 d->d_addr.sa.sa_family);
1601 switch (d->d_addr.sa.sa_family)
1605 if (isascii(*port) && isdigit(*port))
1606 d->d_addr.sin.sin_port = htons((unsigned short)
1607 atoi((const char *) port));
1610 # ifdef NO_GETSERVBYNAME
1611 syserr("554 5.3.5 invalid port number: %s",
1613 # else /* NO_GETSERVBYNAME */
1614 register struct servent *sp;
1616 sp = getservbyname(port, "tcp");
1618 syserr("554 5.3.5 service \"%s\" unknown",
1621 d->d_addr.sin.sin_port = sp->s_port;
1622 # endif /* NO_GETSERVBYNAME */
1625 #endif /* NETINET */
1629 if (isascii(*port) && isdigit(*port))
1630 d->d_addr.sin6.sin6_port = htons((unsigned short)
1634 # ifdef NO_GETSERVBYNAME
1635 syserr("554 5.3.5 invalid port number: %s",
1637 # else /* NO_GETSERVBYNAME */
1638 register struct servent *sp;
1640 sp = getservbyname(port, "tcp");
1642 syserr("554 5.3.5 service \"%s\" unknown",
1645 d->d_addr.sin6.sin6_port = sp->s_port;
1646 # endif /* NO_GETSERVBYNAME */
1649 #endif /* NETINET6 */
1653 /* assume two byte transport selector */
1654 if (isascii(*port) && isdigit(*port))
1655 portno = htons((unsigned short) atoi(port));
1658 # ifdef NO_GETSERVBYNAME
1659 syserr("554 5.3.5 invalid port number: %s",
1661 # else /* NO_GETSERVBYNAME */
1662 register struct servent *sp;
1664 sp = getservbyname(port, "tcp");
1666 syserr("554 5.3.5 service \"%s\" unknown",
1669 portno = sp->s_port;
1670 # endif /* NO_GETSERVBYNAME */
1672 memmove(TSEL(&d->d_addr.siso),
1673 (char *) &portno, 2);
1678 syserr("554 5.3.5 Port= option unsupported for family %d",
1679 d->d_addr.sa.sa_family);
1685 ** SETDAEMONOPTIONS -- set options for running the MTA daemon
1688 ** p -- the options line.
1691 ** true if successful, false otherwise.
1694 ** increments number of daemons.
1697 #define DEF_LISTENQUEUE 10
1705 static struct dflags DaemonFlags[] =
1707 { "AUTHREQ", D_AUTHREQ },
1708 { "BINDIF", D_BINDIF },
1709 { "CANONREQ", D_CANONREQ },
1710 { "IFNHELO", D_IFNHELO },
1711 { "FQMAIL", D_FQMAIL },
1712 { "FQRCPT", D_FQRCPT },
1714 { "SMTPS", D_SMTPS },
1715 #endif /* _FFR_SMTP_SSL */
1716 { "UNQUALOK", D_UNQUALOK },
1717 { "NOAUTH", D_NOAUTH },
1718 { "NOCANON", D_NOCANON },
1719 { "NOETRN", D_NOETRN },
1720 { "NOTLS", D_NOTLS },
1721 { "ETRNONLY", D_ETRNONLY },
1722 { "OPTIONAL", D_OPTIONAL },
1723 { "DISABLE", D_DISABLE },
1724 { "ISSET", D_ISSET },
1732 register struct dflags *df;
1735 for (df = DaemonFlags; df->d_name != NULL; df++)
1737 if (!bitnset(df->d_flag, d->d_flags))
1740 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, "<%s",
1743 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, ",%s",
1748 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT, ">");
1755 if (NDaemons >= MAXDAEMONS)
1757 Daemons[NDaemons].d_socket = -1;
1758 Daemons[NDaemons].d_listenqueue = DEF_LISTENQUEUE;
1759 clrbitmap(Daemons[NDaemons].d_flags);
1760 setsockaddroptions(p, &Daemons[NDaemons]);
1763 # if _FFR_MILTER_PERDAEMON
1764 if (Daemons[NDaemons].d_inputfilterlist != NULL)
1765 Daemons[NDaemons].d_inputfilterlist = newstr(Daemons[NDaemons].d_inputfilterlist);
1766 # endif /* _FFR_MILTER_PERDAEMON */
1769 if (Daemons[NDaemons].d_name != NULL)
1770 Daemons[NDaemons].d_name = newstr(Daemons[NDaemons].d_name);
1775 (void) sm_snprintf(num, sizeof num, "Daemon%d", NDaemons);
1776 Daemons[NDaemons].d_name = newstr(num);
1781 sm_dprintf("Daemon %s flags: ", Daemons[NDaemons].d_name);
1782 printdaemonflags(&Daemons[NDaemons]);
1789 ** INITDAEMON -- initialize daemon if not yet done.
1798 ** initializes structure for one daemon.
1806 Daemons[NDaemons].d_socket = -1;
1807 Daemons[NDaemons].d_listenqueue = DEF_LISTENQUEUE;
1808 Daemons[NDaemons].d_name = "Daemon0";
1813 ** SETCLIENTOPTIONS -- set options for running the client
1816 ** p -- the options line.
1822 static DAEMON_T ClientSettings[AF_MAX + 1];
1831 memset(&d, '\0', sizeof d);
1832 setsockaddroptions(p, &d);
1834 /* grab what we need */
1835 family = d.d_addr.sa.sa_family;
1836 STRUCTCOPY(d, ClientSettings[family]);
1837 setbitn(D_ISSET, ClientSettings[family].d_flags); /* mark as set */
1838 if (d.d_name != NULL)
1839 ClientSettings[family].d_name = newstr(d.d_name);
1844 (void) sm_snprintf(num, sizeof num, "Client%d", family);
1845 ClientSettings[family].d_name = newstr(num);
1849 ** ADDR_FAMILY -- determine address family from address
1852 ** addr -- the string representation of the address
1855 ** AF_INET, AF_INET6 or AF_UNSPEC
1867 #endif /* NETINET6 */
1870 if (inet_addr(addr) != INADDR_NONE)
1873 sm_dprintf("addr_family(%s): INET\n", addr);
1876 #endif /* NETINET */
1878 if (anynet_pton(AF_INET6, addr, &clt_addr.sin6.sin6_addr) == 1)
1881 sm_dprintf("addr_family(%s): INET6\n", addr);
1884 #endif /* NETINET6 */
1885 #if _FFR_DAEMON_NETUNIX
1890 sm_dprintf("addr_family(%s): LOCAL\n", addr);
1893 # endif /* NETUNIX */
1894 #endif /* _FFR_DAEMON_NETUNIX */
1896 sm_dprintf("addr_family(%s): UNSPEC\n", addr);
1901 ** CHKCLIENTMODIFIERS -- check whether all clients have set a flag.
1904 ** flag -- the flag to test.
1907 ** true iff all configured clients have set the flag.
1911 chkclientmodifiers(flag)
1918 for (i = 0; i < AF_MAX; i++)
1920 if (bitnset(D_ISSET, ClientSettings[i].d_flags))
1922 if (!bitnset((char) flag, ClientSettings[i].d_flags))
1931 # if _FFR_MILTER_PERDAEMON
1933 ** SETUP_DAEMON_FILTERS -- Parse per-socket filters
1943 setup_daemon_milters()
1947 if (OpMode == MD_SMTP)
1949 /* no need to configure the daemons */
1953 for (idx = 0; idx < NDaemons; idx++)
1955 if (Daemons[idx].d_inputfilterlist != NULL)
1957 milter_config(Daemons[idx].d_inputfilterlist,
1958 Daemons[idx].d_inputfilters,
1963 # endif /* _FFR_MILTER_PERDAEMON */
1966 ** MAKECONNECTION -- make a connection to an SMTP socket on a machine.
1969 ** host -- the name of the host.
1970 ** port -- the port number to connect to.
1971 ** mci -- a pointer to the mail connection information
1972 ** structure to be filled in.
1973 ** e -- the current envelope.
1974 ** enough -- time at which to stop further connection attempts.
1975 ** (0 means no limit)
1978 ** An exit code telling whether the connection could be
1979 ** made and if not why not.
1985 static jmp_buf CtxConnectTimeout;
1987 SOCKADDR CurHostAddr; /* address of current host */
1990 makeconnection(host, port, mci, e, enough)
1992 volatile unsigned int port;
1997 register volatile int addrno = 0;
1999 register struct hostent *volatile hp = (struct hostent *) NULL;
2003 volatile SOCKADDR_LEN_T addrlen;
2004 volatile bool firstconnect;
2005 SM_EVENT *volatile ev = NULL;
2007 volatile bool v6found = false;
2008 #endif /* NETINET6 */
2009 volatile int family = InetMode;
2011 volatile SOCKADDR_LEN_T socksize = 0;
2012 volatile bool clt_bind;
2015 extern ENVELOPE BlankEnvelope;
2017 /* retranslate {daemon_flags} into bitmap */
2019 if ((p = macvalue(macid("{daemon_flags}"), e)) != NULL)
2021 for (; *p != '\0'; p++)
2023 if (!(isascii(*p) && isspace(*p)))
2024 setbitn(bitidx(*p), d_flags);
2030 #endif /* NETINET6 */
2033 /* Set up the address for outgoing connection. */
2034 if (bitnset(D_BINDIF, d_flags) &&
2035 (p = macvalue(macid("{if_addr}"), e)) != NULL &&
2039 char p6[INET6_ADDRSTRLEN];
2040 #endif /* NETINET6 */
2042 memset(&clt_addr, '\0', sizeof clt_addr);
2044 /* infer the address family from the address itself */
2045 clt_addr.sa.sa_family = addr_family(p);
2046 switch (clt_addr.sa.sa_family)
2050 clt_addr.sin.sin_addr.s_addr = inet_addr(p);
2051 if (clt_addr.sin.sin_addr.s_addr != INADDR_NONE &&
2052 clt_addr.sin.sin_addr.s_addr != INADDR_LOOPBACK)
2055 socksize = sizeof (struct sockaddr_in);
2058 #endif /* NETINET */
2062 if (inet_addr(p) != INADDR_NONE)
2063 (void) sm_snprintf(p6, sizeof p6,
2064 "IPv6:::ffff:%s", p);
2066 (void) sm_strlcpy(p6, p, sizeof p6);
2067 if (anynet_pton(AF_INET6, p6,
2068 &clt_addr.sin6.sin6_addr) == 1 &&
2069 !IN6_IS_ADDR_LOOPBACK(&clt_addr.sin6.sin6_addr))
2072 socksize = sizeof (struct sockaddr_in6);
2075 #endif /* NETINET6 */
2079 syserr("554 5.3.5 Address= option unsupported for family %d",
2080 clt_addr.sa.sa_family);
2085 family = clt_addr.sa.sa_family;
2088 /* D_BINDIF not set or not available, fallback to ClientPortOptions */
2091 STRUCTCOPY(ClientSettings[family].d_addr, clt_addr);
2092 switch (clt_addr.sa.sa_family)
2096 if (clt_addr.sin.sin_addr.s_addr == 0)
2097 clt_addr.sin.sin_addr.s_addr = INADDR_ANY;
2100 if (clt_addr.sin.sin_port != 0)
2102 socksize = sizeof (struct sockaddr_in);
2104 #endif /* NETINET */
2107 if (IN6_IS_ADDR_UNSPECIFIED(&clt_addr.sin6.sin6_addr))
2108 clt_addr.sin6.sin6_addr = in6addr_any;
2111 socksize = sizeof (struct sockaddr_in6);
2112 if (clt_addr.sin6.sin6_port != 0)
2115 #endif /* NETINET6 */
2118 socksize = sizeof clt_addr.siso;
2128 ** Set up the address for the mailer.
2129 ** Accept "[a.b.c.d]" syntax for host name.
2134 memset(&CurHostAddr, '\0', sizeof CurHostAddr);
2135 memset(&addr, '\0', sizeof addr);
2136 SmtpPhase = mci->mci_phase = "initial connection";
2141 p = strchr(host, ']');
2145 unsigned long hid = INADDR_NONE;
2146 #endif /* NETINET */
2148 struct sockaddr_in6 hid6;
2149 #endif /* NETINET6 */
2153 memset(&hid6, '\0', sizeof hid6);
2154 #endif /* NETINET6 */
2156 if (family == AF_INET &&
2157 (hid = inet_addr(&host[1])) != INADDR_NONE)
2159 addr.sin.sin_family = AF_INET;
2160 addr.sin.sin_addr.s_addr = hid;
2163 #endif /* NETINET */
2165 if (family == AF_INET6 &&
2166 anynet_pton(AF_INET6, &host[1],
2167 &hid6.sin6_addr) == 1)
2169 addr.sin6.sin6_family = AF_INET6;
2170 addr.sin6.sin6_addr = hid6.sin6_addr;
2173 #endif /* NETINET6 */
2175 /* try it as a host name (avoid MX lookup) */
2176 hp = sm_gethostbyname(&host[1], family);
2177 if (hp == NULL && p[-1] == '.')
2180 int oldopts = _res.options;
2182 _res.options &= ~(RES_DEFNAMES|RES_DNSRCH);
2183 #endif /* NAMED_BIND */
2185 hp = sm_gethostbyname(&host[1],
2189 _res.options = oldopts;
2190 #endif /* NAMED_BIND */
2199 extern char MsgBuf[];
2202 "553 Invalid numeric domain spec \"%s\"",
2204 mci_setstat(mci, EX_NOHOST, "5.1.2", MsgBuf);
2211 /* contortion to get around SGI cc complaints */
2213 p = &host[strlen(host) - 1];
2214 hp = sm_gethostbyname(host, family);
2215 if (hp == NULL && *p == '.')
2218 int oldopts = _res.options;
2220 _res.options &= ~(RES_DEFNAMES|RES_DNSRCH);
2221 #endif /* NAMED_BIND */
2223 hp = sm_gethostbyname(host, family);
2226 _res.options = oldopts;
2227 #endif /* NAMED_BIND */
2234 /* check for name server timeouts */
2236 if (WorkAroundBrokenAAAA && family == AF_INET6 &&
2240 ** An attempt with family AF_INET may
2241 ** succeed By skipping the next section
2242 ** of code, we will try AF_INET before
2247 sm_dprintf("makeconnection: WorkAroundBrokenAAAA: Trying AF_INET lookup (AF_INET6 failed)\n");
2250 # endif /* NETINET6 */
2252 if (errno == ETIMEDOUT ||
2253 h_errno == TRY_AGAIN ||
2254 (errno == ECONNREFUSED && UseNameServer))
2257 mci_setstat(mci, EX_TEMPFAIL,
2263 #endif /* NAMED_BIND */
2266 ** Try v6 first, then fall back to v4.
2267 ** If we found a v6 address, but no v4
2268 ** addresses, then TEMPFAIL.
2271 if (family == AF_INET6)
2278 #endif /* NETINET6 */
2280 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2284 addr.sa.sa_family = hp->h_addrtype;
2285 switch (hp->h_addrtype)
2289 memmove(&addr.sin.sin_addr,
2293 #endif /* NETINET */
2297 memmove(&addr.sin6.sin6_addr,
2301 #endif /* NETINET6 */
2304 if (hp->h_length > sizeof addr.sa.sa_data)
2306 syserr("makeconnection: long sa_data: family %d len %d",
2307 hp->h_addrtype, hp->h_length);
2308 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2312 memmove(addr.sa.sa_data, hp->h_addr, hp->h_length);
2319 ** Determine the port number.
2324 #ifdef NO_GETSERVBYNAME
2326 #else /* NO_GETSERVBYNAME */
2327 register struct servent *sp = getservbyname("smtp", "tcp");
2332 sm_syslog(LOG_ERR, NOQID,
2333 "makeconnection: service \"smtp\" unknown");
2338 #endif /* NO_GETSERVBYNAME */
2342 if (addr.sa.sa_family == AF_INET6 &&
2343 IN6_IS_ADDR_V4MAPPED(&addr.sin6.sin6_addr) &&
2344 ClientSettings[AF_INET].d_addr.sa.sa_family != 0)
2347 ** Ignore mapped IPv4 address since
2348 ** there is a ClientPortOptions setting
2354 #endif /* NETINET6 */
2356 switch (addr.sa.sa_family)
2360 addr.sin.sin_port = port;
2361 addrlen = sizeof (struct sockaddr_in);
2363 #endif /* NETINET */
2367 addr.sin6.sin6_port = port;
2368 addrlen = sizeof (struct sockaddr_in6);
2370 #endif /* NETINET6 */
2374 /* assume two byte transport selector */
2375 memmove(TSEL((struct sockaddr_iso *) &addr), (char *) &port, 2);
2376 addrlen = sizeof (struct sockaddr_iso);
2381 syserr("Can't connect to address family %d", addr.sa.sa_family);
2382 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2387 #endif /* NETINET6 */
2392 ** Try to actually open the connection.
2396 /* if too many connections, don't bother trying */
2397 if (!xla_noqueue_ok(host))
2402 # endif /* NETINET6 */
2407 firstconnect = true;
2411 sm_dprintf("makeconnection (%s [%s].%d (%d))\n",
2412 host, anynet_ntoa(&addr), ntohs(port),
2413 (int) addr.sa.sa_family);
2415 /* save for logging */
2419 if (bitnset(M_SECURE_PORT, mci->mci_mailer->m_flags))
2421 int rport = IPPORT_RESERVED - 1;
2423 s = rresvport(&rport);
2426 #endif /* HASRRESVPORT */
2428 s = socket(addr.sa.sa_family, SOCK_STREAM, 0);
2433 syserr("makeconnection: cannot create socket");
2437 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2441 #endif /* NETINET6 */
2447 if (ClientSettings[family].d_tcpsndbufsize > 0)
2449 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
2450 (char *) &ClientSettings[family].d_tcpsndbufsize,
2451 sizeof(ClientSettings[family].d_tcpsndbufsize)) < 0)
2452 syserr("makeconnection: setsockopt(SO_SNDBUF)");
2454 #endif /* SO_SNDBUF */
2456 if (ClientSettings[family].d_tcprcvbufsize > 0)
2458 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
2459 (char *) &ClientSettings[family].d_tcprcvbufsize,
2460 sizeof(ClientSettings[family].d_tcprcvbufsize)) < 0)
2461 syserr("makeconnection: setsockopt(SO_RCVBUF)");
2463 #endif /* SO_RCVBUF */
2466 sm_dprintf("makeconnection: fd=%d\n", s);
2468 /* turn on network debugging? */
2473 (void) setsockopt(s, SOL_SOCKET, SO_DEBUG,
2474 (char *)&on, sizeof on);
2476 if (e->e_xfp != NULL) /* for debugging */
2477 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
2478 errno = 0; /* for debugging */
2484 switch (clt_addr.sa.sa_family)
2488 if (clt_addr.sin.sin_port != 0)
2489 (void) setsockopt(s, SOL_SOCKET,
2494 #endif /* NETINET */
2498 if (clt_addr.sin6.sin6_port != 0)
2499 (void) setsockopt(s, SOL_SOCKET,
2504 #endif /* NETINET6 */
2507 if (bind(s, &clt_addr.sa, socksize) < 0)
2512 syserr("makeconnection: cannot bind socket [%s]",
2513 anynet_ntoa(&clt_addr));
2517 #endif /* NETINET6 */
2524 ** Linux seems to hang in connect for 90 minutes (!!!).
2525 ** Time out the connect to avoid this problem.
2528 if (setjmp(CtxConnectTimeout) == 0)
2532 if (e->e_ntries <= 0 && TimeOuts.to_iconnect != 0)
2533 ev = sm_setevent(TimeOuts.to_iconnect,
2535 else if (TimeOuts.to_connect != 0)
2536 ev = sm_setevent(TimeOuts.to_connect,
2541 switch (ConnectOnlyTo.sa.sa_family)
2545 addr.sin.sin_addr.s_addr = ConnectOnlyTo.sin.sin_addr.s_addr;
2547 #endif /* NETINET */
2551 memmove(&addr.sin6.sin6_addr,
2552 &ConnectOnlyTo.sin6.sin6_addr,
2555 #endif /* NETINET6 */
2557 i = connect(s, (struct sockaddr *) &addr, addrlen);
2567 /* couldn't connect.... figure out why */
2570 /* if running demand-dialed connection, try again */
2571 if (DialDelay > 0 && firstconnect &&
2572 bitnset(M_DIALDELAY, mci->mci_mailer->m_flags))
2575 sm_dprintf("Connect failed (%s); trying again...\n",
2576 sm_errstring(save_errno));
2577 firstconnect = false;
2578 (void) sleep(DialDelay);
2583 sm_syslog(LOG_INFO, e->e_id,
2584 "makeconnection (%s [%s]) failed: %s",
2585 host, anynet_ntoa(&addr),
2586 sm_errstring(save_errno));
2590 #endif /* NETINET6 */
2591 if (hp != NULL && hp->h_addr_list[addrno] != NULL &&
2592 (enough == 0 || curtime() < enough))
2595 sm_dprintf("Connect failed (%s); trying new address....\n",
2596 sm_errstring(save_errno));
2597 switch (addr.sa.sa_family)
2601 memmove(&addr.sin.sin_addr,
2602 hp->h_addr_list[addrno++],
2605 #endif /* NETINET */
2609 memmove(&addr.sin6.sin6_addr,
2610 hp->h_addr_list[addrno++],
2613 #endif /* NETINET6 */
2616 memmove(addr.sa.sa_data,
2617 hp->h_addr_list[addrno++],
2626 if (family == AF_INET6)
2629 sm_dprintf("Connect failed (%s); retrying with AF_INET....\n",
2630 sm_errstring(save_errno));
2641 #endif /* NETINET6 */
2642 /* couldn't open connection */
2644 /* Don't clobber an already saved errno from v4retry */
2646 #endif /* NETINET6 */
2649 sm_dprintf("Connect failed (%s)\n",
2650 sm_errstring(save_errno));
2654 mci_setstat(mci, EX_TEMPFAIL, "4.4.1", NULL);
2658 #endif /* NETINET6 */
2669 #endif /* NETINET6 */
2671 /* connection ok, put it into canonical form */
2672 mci->mci_out = NULL;
2673 if ((mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2675 SM_IO_WRONLY, NULL)) == NULL ||
2677 (mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2679 SM_IO_RDONLY, NULL)) == NULL)
2682 syserr("cannot open SMTP client channel, fd=%d", s);
2683 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2684 if (mci->mci_out != NULL)
2685 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
2690 sm_io_automode(mci->mci_out, mci->mci_in);
2692 /* set {client_flags} */
2693 if (ClientSettings[addr.sa.sa_family].d_mflags != NULL)
2695 macdefine(&mci->mci_macro, A_PERM,
2696 macid("{client_flags}"),
2697 ClientSettings[addr.sa.sa_family].d_mflags);
2700 macdefine(&mci->mci_macro, A_PERM,
2701 macid("{client_flags}"), "");
2703 /* "add" {client_flags} to bitmap */
2704 if (bitnset(D_IFNHELO, ClientSettings[addr.sa.sa_family].d_flags))
2706 /* look for just this one flag */
2707 setbitn(D_IFNHELO, d_flags);
2710 /* find out name for Interface through which we connect */
2712 if (getsockname(s, &addr.sa, &len) == 0)
2717 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2718 macid("{if_addr_out}"), anynet_ntoa(&addr));
2719 (void) sm_snprintf(family, sizeof(family), "%d",
2721 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2722 macid("{if_family_out}"), family);
2724 name = hostnamebyanyaddr(&addr);
2725 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2726 macid("{if_name_out}"), name);
2729 /* log connection information */
2730 sm_syslog(LOG_INFO, e->e_id,
2731 "SMTP outgoing connect on %.40s", name);
2733 if (bitnset(D_IFNHELO, d_flags))
2735 if (name[0] != '[' && strchr(name, '.') != NULL)
2736 mci->mci_heloname = newstr(name);
2741 macdefine(&BlankEnvelope.e_macro, A_PERM,
2742 macid("{if_name_out}"), NULL);
2743 macdefine(&BlankEnvelope.e_macro, A_PERM,
2744 macid("{if_addr_out}"), NULL);
2745 macdefine(&BlankEnvelope.e_macro, A_PERM,
2746 macid("{if_family_out}"), NULL);
2748 mci_setstat(mci, EX_OK, NULL, NULL);
2756 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2757 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2762 longjmp(CtxConnectTimeout, 1);
2765 ** MAKECONNECTION_DS -- make a connection to a domain socket.
2768 ** mux_path -- the path of the socket to connect to.
2769 ** mci -- a pointer to the mail connection information
2770 ** structure to be filled in.
2773 ** An exit code telling whether the connection could be
2774 ** made and if not why not.
2782 makeconnection_ds(mux_path, mci)
2787 int rval, save_errno;
2788 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_ROOTOK|SFF_EXECOK;
2789 struct sockaddr_un unix_addr;
2791 /* if not safe, don't connect */
2792 rval = safefile(mux_path, RunAsUid, RunAsGid, RunAsUserName,
2793 sff, S_IRUSR|S_IWUSR, NULL);
2797 syserr("makeconnection_ds: unsafe domain socket");
2798 mci_setstat(mci, EX_TEMPFAIL, "4.3.5", NULL);
2803 /* prepare address structure */
2804 memset(&unix_addr, '\0', sizeof unix_addr);
2805 unix_addr.sun_family = AF_UNIX;
2807 if (strlen(mux_path) >= sizeof unix_addr.sun_path)
2809 syserr("makeconnection_ds: domain socket name too long");
2811 /* XXX why TEMPFAIL but 5.x.y ? */
2812 mci_setstat(mci, EX_TEMPFAIL, "5.3.5", NULL);
2813 errno = ENAMETOOLONG;
2814 return EX_UNAVAILABLE;
2816 (void) sm_strlcpy(unix_addr.sun_path, mux_path,
2817 sizeof unix_addr.sun_path);
2819 /* initialize domain socket */
2820 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2824 syserr("makeconnection_ds: could not create domain socket");
2825 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2830 /* connect to server */
2831 if (connect(sock, (struct sockaddr *) &unix_addr,
2832 sizeof(unix_addr)) == -1)
2835 syserr("Could not connect to socket %s", mux_path);
2836 mci_setstat(mci, EX_TEMPFAIL, "4.4.1", NULL);
2842 /* connection ok, put it into canonical form */
2843 mci->mci_out = NULL;
2844 if ((mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2845 (void *) &sock, SM_IO_WRONLY, NULL))
2847 || (sock = dup(sock)) < 0 ||
2848 (mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2849 (void *) &sock, SM_IO_RDONLY, NULL))
2853 syserr("cannot open SMTP client channel, fd=%d", sock);
2854 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2855 if (mci->mci_out != NULL)
2856 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
2861 sm_io_automode(mci->mci_out, mci->mci_in);
2863 mci_setstat(mci, EX_OK, NULL, NULL);
2867 #endif /* NETUNIX */
2869 ** SHUTDOWN_DAEMON -- Performs a clean shutdown of the daemon
2878 ** closes control socket, exits.
2887 sm_allsignals(true);
2889 reason = ShutdownRequest;
2890 ShutdownRequest = NULL;
2894 sm_syslog(LOG_DEBUG, CurEnv->e_id, "interrupt (%s)",
2895 reason == NULL ? "implicit call" : reason);
2898 closecontrolsocket(true);
2903 for (i = 0; i < NDaemons; i++)
2905 if (Daemons[i].d_socket >= 0)
2907 (void) close(Daemons[i].d_socket);
2908 Daemons[i].d_socket = -1;
2910 #if _FFR_DAEMON_NETUNIX
2912 /* Remove named sockets */
2913 if (Daemons[i].d_addr.sa.sa_family == AF_UNIX)
2916 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_MUSTOWN|SFF_EXECOK|SFF_CREAT;
2918 /* if not safe, don't use it */
2919 rval = safefile(Daemons[i].d_addr.sunix.sun_path,
2922 S_IRUSR|S_IWUSR, NULL);
2924 unlink(Daemons[i].d_addr.sunix.sun_path) < 0)
2926 sm_syslog(LOG_WARNING, NOQID,
2927 "Could not remove daemon %s socket: %s: %s",
2929 Daemons[i].d_addr.sunix.sun_path,
2930 sm_errstring(errno));
2933 # endif /* NETUNIX */
2934 #endif /* _FFR_DAEMON_NETUNIX */
2938 finis(false, true, EX_OK);
2941 ** RESTART_DAEMON -- Performs a clean restart of the daemon
2950 ** restarts the daemon or exits if restart fails.
2953 /* Make a non-DFL/IGN signal a noop */
2954 #define SM_NOOP_SIGNAL(sig, old) \
2957 (old) = sm_signal((sig), sm_signal_noop); \
2958 if ((old) == SIG_IGN || (old) == SIG_DFL) \
2959 (void) sm_signal((sig), (old)); \
2969 sigfunc_t ignore, oalrm, ousr1;
2970 extern int DtableSize;
2972 /* clear the events to turn off SIGALRMs */
2974 sm_allsignals(true);
2976 reason = RestartRequest;
2977 RestartRequest = NULL;
2980 if (SaveArgv[0][0] != '/')
2983 sm_syslog(LOG_INFO, NOQID,
2984 "could not restart: need full path");
2985 finis(false, true, EX_OSFILE);
2989 sm_syslog(LOG_INFO, NOQID, "restarting %s due to %s",
2991 reason == NULL ? "implicit call" : reason);
2993 closecontrolsocket(true);
2995 cleanup_shm(DaemonPid == getpid());
2996 #endif /* SM_CONF_SHM */
2999 ** Want to drop to the user who started the process in all cases
3000 ** *but* when running as "smmsp" for the clientmqueue queue run
3001 ** daemon. In that case, UseMSP will be true, RunAsUid should not
3002 ** be root, and RealUid should be either 0 or RunAsUid.
3005 drop = !(UseMSP && RunAsUid != 0 &&
3006 (RealUid == 0 || RealUid == RunAsUid));
3008 if (drop_privileges(drop) != EX_OK)
3011 sm_syslog(LOG_ALERT, NOQID,
3012 "could not drop privileges: %s",
3013 sm_errstring(errno));
3014 finis(false, true, EX_OSERR);
3018 /* arrange for all the files to be closed */
3019 for (i = 3; i < DtableSize; i++)
3023 if ((j = fcntl(i, F_GETFD, 0)) != -1)
3024 (void) fcntl(i, F_SETFD, j | FD_CLOEXEC);
3028 ** Need to allow signals before execve() to make them "harmless".
3029 ** However, the default action can be "terminate", so it isn't
3030 ** really harmless. Setting signals to IGN will cause them to be
3031 ** ignored in the new process to, so that isn't a good alternative.
3034 SM_NOOP_SIGNAL(SIGALRM, oalrm);
3035 SM_NOOP_SIGNAL(SIGCHLD, ignore);
3036 SM_NOOP_SIGNAL(SIGHUP, ignore);
3037 SM_NOOP_SIGNAL(SIGINT, ignore);
3038 SM_NOOP_SIGNAL(SIGPIPE, ignore);
3039 SM_NOOP_SIGNAL(SIGTERM, ignore);
3041 SM_NOOP_SIGNAL(SIGUSR1, ousr1);
3042 #endif /* SIGUSR1 */
3044 /* Turn back on signals */
3045 sm_allsignals(false);
3047 (void) execve(SaveArgv[0], (ARGV_T) SaveArgv, (ARGV_T) ExternalEnviron);
3050 /* block signals again and restore needed signals */
3051 sm_allsignals(true);
3053 /* For finis() events */
3054 (void) sm_signal(SIGALRM, oalrm);
3057 /* For debugging finis() */
3058 (void) sm_signal(SIGUSR1, ousr1);
3059 #endif /* SIGUSR1 */
3063 sm_syslog(LOG_ALERT, NOQID, "could not exec %s: %s",
3064 SaveArgv[0], sm_errstring(errno));
3065 finis(false, true, EX_OSFILE);
3069 ** MYHOSTNAME -- return the name of this host.
3072 ** hostbuf -- a place to return the name of this host.
3073 ** size -- the size of hostbuf.
3076 ** A list of aliases for this host.
3079 ** Adds numeric codes to $=w.
3083 myhostname(hostbuf, size)
3087 register struct hostent *hp;
3089 if (gethostname(hostbuf, size) < 0 || hostbuf[0] == '\0')
3090 (void) sm_strlcpy(hostbuf, "localhost", size);
3091 hp = sm_gethostbyname(hostbuf, InetMode);
3092 #if NETINET && NETINET6
3093 if (hp == NULL && InetMode == AF_INET6)
3096 ** It's possible that this IPv6 enabled machine doesn't
3097 ** actually have any IPv6 interfaces and, therefore, no
3098 ** IPv6 addresses. Fall back to AF_INET.
3101 hp = sm_gethostbyname(hostbuf, AF_INET);
3103 #endif /* NETINET && NETINET6 */
3106 if (strchr(hp->h_name, '.') != NULL || strchr(hostbuf, '.') == NULL)
3107 (void) cleanstrcpy(hostbuf, hp->h_name, size);
3110 if (strchr(hostbuf, '.') == NULL)
3114 domainname = ni_propval("/locations", NULL, "resolver",
3116 if (domainname != NULL &&
3117 strlen(domainname) + strlen(hostbuf) + 1 < size)
3118 (void) sm_strlcat2(hostbuf, ".", domainname, size);
3120 #endif /* NETINFO */
3123 ** If there is still no dot in the name, try looking for a
3127 if (strchr(hostbuf, '.') == NULL)
3131 for (ha = hp->h_aliases; ha != NULL && *ha != NULL; ha++)
3133 if (strchr(*ha, '.') != NULL)
3135 (void) cleanstrcpy(hostbuf, *ha, size - 1);
3136 hostbuf[size - 1] = '\0';
3143 ** If _still_ no dot, wait for a while and try again -- it is
3144 ** possible that some service is starting up. This can result
3145 ** in excessive delays if the system is badly configured, but
3146 ** there really isn't a way around that, particularly given that
3147 ** the config file hasn't been read at this point.
3148 ** All in all, a bit of a mess.
3151 if (strchr(hostbuf, '.') == NULL &&
3152 !getcanonname(hostbuf, size, true, NULL))
3154 sm_syslog(LOG_CRIT, NOQID,
3155 "My unqualified host name (%s) unknown; sleeping for retry",
3157 message("My unqualified host name (%s) unknown; sleeping for retry",
3160 if (!getcanonname(hostbuf, size, true, NULL))
3162 sm_syslog(LOG_ALERT, NOQID,
3163 "unable to qualify my own domain name (%s) -- using short name",
3165 message("WARNING: unable to qualify my own domain name (%s) -- using short name",
3172 ** ADDRCMP -- compare two host addresses
3175 ** hp -- hostent structure for the first address
3176 ** ha -- actual first address
3177 ** sa -- second address
3180 ** 0 -- if ha and sa match
3181 ** else -- they don't match
3192 #endif /* NETINET6 */
3194 switch (sa->sa.sa_family)
3198 if (hp->h_addrtype == AF_INET)
3199 return memcmp(ha, (char *) &sa->sin.sin_addr, INADDRSZ);
3201 #endif /* NETINET */
3205 a = (unsigned char *) &sa->sin6.sin6_addr;
3207 /* Straight binary comparison */
3208 if (hp->h_addrtype == AF_INET6)
3209 return memcmp(ha, a, IN6ADDRSZ);
3211 /* If IPv4-mapped IPv6 address, compare the IPv4 section */
3212 if (hp->h_addrtype == AF_INET &&
3213 IN6_IS_ADDR_V4MAPPED(&sa->sin6.sin6_addr))
3214 return memcmp(a + IN6ADDRSZ - INADDRSZ, ha, INADDRSZ);
3216 #endif /* NETINET6 */
3221 ** GETAUTHINFO -- get the real host name associated with a file descriptor
3223 ** Uses RFC1413 protocol to try to get info from the other end.
3226 ** fd -- the descriptor
3227 ** may_be_forged -- an outage that is set to true if the
3228 ** forward lookup of RealHostName does not match
3229 ** RealHostAddr; set to false if they do match.
3232 ** The user@host information associated with this descriptor.
3235 static jmp_buf CtxAuthTimeout;
3241 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3242 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3247 longjmp(CtxAuthTimeout, 1);
3251 getauthinfo(fd, may_be_forged)
3253 bool *may_be_forged;
3255 unsigned short SM_NONVOLATILE port = 0;
3256 SOCKADDR_LEN_T falen;
3257 register char *volatile p = NULL;
3259 SOCKADDR_LEN_T lalen;
3260 #ifndef NO_GETSERVBYNAME
3261 register struct servent *sp;
3263 static unsigned short port4 = 0;
3264 # endif /* NETINET */
3266 static unsigned short port6 = 0;
3267 # endif /* NETINET6 */
3268 #endif /* ! NO_GETSERVBYNAME */
3275 char *ostype = NULL;
3277 char ibuf[MAXNAME + 1];
3278 static char hbuf[MAXNAME + MAXAUTHINFO + 11];
3280 *may_be_forged = false;
3281 falen = sizeof RealHostAddr;
3282 if (isatty(fd) || (i = getpeername(fd, &RealHostAddr.sa, &falen)) < 0 ||
3283 falen <= 0 || RealHostAddr.sa.sa_family == 0)
3288 ** ENOTSOCK is OK: bail on anything else, but reset
3289 ** errno in this case, so a mis-report doesn't
3293 if (errno != ENOTSOCK)
3297 (void) sm_strlcpyn(hbuf, sizeof hbuf, 2, RealUserName,
3300 sm_dprintf("getauthinfo: %s\n", hbuf);
3304 if (RealHostName == NULL)
3306 /* translate that to a host name */
3307 RealHostName = newstr(hostnamebyanyaddr(&RealHostAddr));
3308 if (strlen(RealHostName) > MAXNAME)
3309 RealHostName[MAXNAME] = '\0'; /* XXX - 1 ? */
3312 /* cross check RealHostName with forward DNS lookup */
3313 if (anynet_ntoa(&RealHostAddr)[0] != '[' &&
3314 RealHostName[0] != '[')
3318 family = RealHostAddr.sa.sa_family;
3319 #if NETINET6 && NEEDSGETIPNODE
3321 ** If RealHostAddr is an IPv6 connection with an
3322 ** IPv4-mapped address, we need RealHostName's IPv4
3323 ** address(es) for addrcmp() to compare against
3326 ** Actually, we only need to do this for systems
3327 ** which NEEDSGETIPNODE since the real getipnodebyname()
3328 ** already does V4MAPPED address via the AI_V4MAPPEDCFG
3329 ** flag. A better fix to this problem is to add this
3330 ** functionality to our stub getipnodebyname().
3333 if (family == AF_INET6 &&
3334 IN6_IS_ADDR_V4MAPPED(&RealHostAddr.sin6.sin6_addr))
3336 #endif /* NETINET6 && NEEDSGETIPNODE */
3338 /* try to match the reverse against the forward lookup */
3339 hp = sm_gethostbyname(RealHostName, family);
3342 *may_be_forged = true;
3346 for (ha = hp->h_addr_list; *ha != NULL; ha++)
3348 if (addrcmp(hp, *ha, &RealHostAddr) == 0)
3351 *may_be_forged = *ha == NULL;
3355 #endif /* NETINET6 */
3359 if (TimeOuts.to_ident == 0)
3363 switch (RealHostAddr.sa.sa_family)
3367 if (getsockname(fd, &la.sa, &lalen) < 0 ||
3369 la.sa.sa_family != AF_INET)
3374 port = RealHostAddr.sin.sin_port;
3376 /* create ident query */
3377 (void) sm_snprintf(ibuf, sizeof ibuf, "%d,%d\r\n",
3378 ntohs(RealHostAddr.sin.sin_port),
3379 ntohs(la.sin.sin_port));
3381 /* create local address */
3382 la.sin.sin_port = 0;
3384 /* create foreign address */
3385 # ifdef NO_GETSERVBYNAME
3386 RealHostAddr.sin.sin_port = htons(113);
3387 # else /* NO_GETSERVBYNAME */
3390 ** getservbyname() consumes about 5% of the time
3391 ** when receiving a small message (almost all of the time
3392 ** spent in this routine).
3393 ** Hence we store the port in a static variable
3394 ** to save this time.
3395 ** The portnumber shouldn't change very often...
3396 ** This code makes the assumption that the port number
3402 sp = getservbyname("auth", "tcp");
3408 RealHostAddr.sin.sin_port = port4;
3410 # endif /* NO_GETSERVBYNAME */
3411 #endif /* NETINET */
3415 if (getsockname(fd, &la.sa, &lalen) < 0 ||
3417 la.sa.sa_family != AF_INET6)
3422 port = RealHostAddr.sin6.sin6_port;
3424 /* create ident query */
3425 (void) sm_snprintf(ibuf, sizeof ibuf, "%d,%d\r\n",
3426 ntohs(RealHostAddr.sin6.sin6_port),
3427 ntohs(la.sin6.sin6_port));
3429 /* create local address */
3430 la.sin6.sin6_port = 0;
3432 /* create foreign address */
3433 # ifdef NO_GETSERVBYNAME
3434 RealHostAddr.sin6.sin6_port = htons(113);
3435 # else /* NO_GETSERVBYNAME */
3438 sp = getservbyname("auth", "tcp");
3444 RealHostAddr.sin6.sin6_port = port6;
3446 # endif /* NO_GETSERVBYNAME */
3447 #endif /* NETINET6 */
3454 if (setjmp(CtxAuthTimeout) != 0)
3461 /* put a timeout around the whole thing */
3462 ev = sm_setevent(TimeOuts.to_ident, authtimeout, 0);
3464 /* connect to foreign IDENT server using same address as SMTP socket */
3465 s = socket(la.sa.sa_family, SOCK_STREAM, 0);
3471 if (bind(s, &la.sa, lalen) < 0 ||
3472 connect(s, &RealHostAddr.sa, lalen) < 0)
3476 sm_dprintf("getauthinfo: sent %s", ibuf);
3479 if (write(s, ibuf, strlen(ibuf)) < 0)
3484 nleft = sizeof ibuf - 1;
3485 while ((i = read(s, p, nleft)) > 0)
3490 if (strchr(ibuf, '\n') != NULL || nleft <= 0)
3495 if (i < 0 || p == &ibuf[0])
3498 if (p >= &ibuf[2] && *--p == '\n' && *--p == '\r')
3503 sm_dprintf("getauthinfo: got %s\n", ibuf);
3506 p = strchr(ibuf, ':');
3509 /* malformed response */
3512 while (isascii(*++p) && isspace(*p))
3514 if (sm_strncasecmp(p, "userid", 6) != 0)
3516 /* presumably an error string */
3520 while (isascii(*p) && isspace(*p))
3524 /* either useridxx or malformed response */
3528 /* p now points to the OSTYPE field */
3529 while (isascii(*p) && isspace(*p))
3535 /* malformed response */
3543 charset = strchr(ostype, ',');
3544 if (charset != NULL)
3548 /* 1413 says don't do this -- but it's broken otherwise */
3549 while (isascii(*++p) && isspace(*p))
3552 /* p now points to the authenticated name -- copy carefully */
3553 if (sm_strncasecmp(ostype, "other", 5) == 0 &&
3554 (ostype[5] == ' ' || ostype[5] == '\0'))
3556 (void) sm_strlcpy(hbuf, "IDENT:", sizeof hbuf);
3557 cleanstrcpy(&hbuf[6], p, MAXAUTHINFO);
3560 cleanstrcpy(hbuf, p, MAXAUTHINFO);
3562 (void) sm_strlcpyn(&hbuf[len], sizeof hbuf - len, 2, "@",
3563 RealHostName == NULL ? "localhost" : RealHostName);
3571 /* put back the original incoming port */
3572 switch (RealHostAddr.sa.sa_family)
3577 RealHostAddr.sin.sin_port = port;
3579 #endif /* NETINET */
3584 RealHostAddr.sin6.sin6_port = port;
3586 #endif /* NETINET6 */
3589 if (RealHostName == NULL)
3592 sm_dprintf("getauthinfo: NULL\n");
3595 (void) sm_strlcpy(hbuf, RealHostName, sizeof hbuf);
3599 # ifndef GET_IPOPT_DST
3600 # define GET_IPOPT_DST(dst) (dst)
3601 # endif /* ! GET_IPOPT_DST */
3603 ** Extract IP source routing information.
3605 ** Format of output for a connection from site a through b
3607 ** loose: @site-c@site-b:site-a
3608 ** strict: !@site-c@site-b:site-a
3610 ** o - pointer within ipopt_list structure.
3611 ** q - pointer within ls/ss rr route data
3612 ** p - pointer to hbuf
3615 if (RealHostAddr.sa.sa_family == AF_INET)
3617 SOCKOPT_LEN_T ipoptlen;
3622 struct IPOPTION ipopt;
3624 ipoptlen = sizeof ipopt;
3625 if (getsockopt(fd, IPPROTO_IP, IP_OPTIONS,
3626 (char *) &ipopt, &ipoptlen) < 0)
3630 o = (unsigned char *) ipopt.IP_LIST;
3631 while (o != NULL && o < (unsigned char *) &ipopt + ipoptlen)
3647 ** o[0] is the option type (loose/strict).
3648 ** o[1] is the length of this option,
3649 ** including option type and
3651 ** o[2] is the pointer into the route
3653 ** o[3] begins the route data.
3656 p = &hbuf[strlen(hbuf)];
3657 l = sizeof hbuf - (hbuf - p) - 6;
3658 (void) sm_snprintf(p, SPACELEFT(hbuf, p),
3660 *o == IPOPT_SSRR ? "!" : "",
3661 l > 240 ? 120 : l / 2,
3662 inet_ntoa(GET_IPOPT_DST(ipopt.IP_DST)));
3667 j = o[1] / sizeof(struct in_addr) - 1;
3669 /* q skips length and router pointer to data */
3671 for ( ; j >= 0; j--)
3673 struct in_addr addr;
3675 memcpy(&addr, q, sizeof(addr));
3676 (void) sm_snprintf(p,
3686 q += sizeof(struct in_addr);
3692 /* Skip over option */
3697 (void) sm_snprintf(p, SPACELEFT(hbuf, p), "]");
3702 #endif /* IP_SRCROUTE */
3703 if (RealHostName != NULL && RealHostName[0] != '[')
3705 p = &hbuf[strlen(hbuf)];
3706 (void) sm_snprintf(p, SPACELEFT(hbuf, p), " [%.100s]",
3707 anynet_ntoa(&RealHostAddr));
3711 p = &hbuf[strlen(hbuf)];
3712 (void) sm_strlcpy(p, " (may be forged)", SPACELEFT(hbuf, p));
3713 macdefine(&BlankEnvelope.e_macro, A_PERM,
3714 macid("{client_resolve}"), "FORGED");
3719 #endif /* IP_SRCROUTE */
3721 /* put back the original incoming port */
3722 switch (RealHostAddr.sa.sa_family)
3727 RealHostAddr.sin.sin_port = port;
3729 #endif /* NETINET */
3734 RealHostAddr.sin6.sin6_port = port;
3736 #endif /* NETINET6 */
3740 sm_dprintf("getauthinfo: %s\n", hbuf);
3744 ** HOST_MAP_LOOKUP -- turn a hostname into canonical form
3747 ** map -- a pointer to this map.
3748 ** name -- the (presumably unqualified) hostname.
3749 ** av -- unused -- for compatibility with other mapping
3751 ** statp -- an exit status (out parameter) -- set to
3752 ** EX_TEMPFAIL if the name server is unavailable.
3755 ** The mapping, if found.
3756 ** NULL if no mapping found.
3759 ** Looks up the host specified in hbuf. If it is not
3760 ** the canonical name for that host, return the canonical
3761 ** name (unless MF_MATCHONLY is set, which will cause the
3762 ** status only to be returned).
3766 host_map_lookup(map, name, av, statp)
3772 register struct hostent *hp;
3774 struct in_addr in_addr;
3775 #endif /* NETINET */
3777 struct in6_addr in6_addr;
3778 #endif /* NETINET6 */
3779 char *cp, *ans = NULL;
3783 time_t SM_NONVOLATILE retrans = 0;
3784 int SM_NONVOLATILE retry = 0;
3785 #endif /* NAMED_BIND */
3786 char hbuf[MAXNAME + 1];
3789 ** See if we have already looked up this name. If so, just
3790 ** return it (unless expired).
3794 s = stab(name, ST_NAMECANON, ST_ENTER);
3795 if (bitset(NCF_VALID, s->s_namecanon.nc_flags) &&
3796 s->s_namecanon.nc_exp >= now)
3799 sm_dprintf("host_map_lookup(%s) => CACHE %s\n",
3801 s->s_namecanon.nc_cname == NULL
3803 : s->s_namecanon.nc_cname);
3804 errno = s->s_namecanon.nc_errno;
3805 SM_SET_H_ERRNO(s->s_namecanon.nc_herrno);
3806 *statp = s->s_namecanon.nc_stat;
3807 if (*statp == EX_TEMPFAIL)
3809 CurEnv->e_status = "4.4.3";
3810 message("851 %s: Name server timeout",
3811 shortenstring(name, 33));
3813 if (*statp != EX_OK)
3815 if (s->s_namecanon.nc_cname == NULL)
3817 syserr("host_map_lookup(%s): bogus NULL cache entry, errno = %d, h_errno = %d",
3819 s->s_namecanon.nc_errno,
3820 s->s_namecanon.nc_herrno);
3823 if (bitset(MF_MATCHONLY, map->map_mflags))
3824 cp = map_rewrite(map, name, strlen(name), NULL);
3826 cp = map_rewrite(map,
3827 s->s_namecanon.nc_cname,
3828 strlen(s->s_namecanon.nc_cname),
3834 ** If we are running without a regular network connection (usually
3835 ** dial-on-demand) and we are just queueing, we want to avoid DNS
3836 ** lookups because those could try to connect to a server.
3839 if (CurEnv->e_sendmode == SM_DEFER &&
3840 bitset(MF_DEFER, map->map_mflags))
3843 sm_dprintf("host_map_lookup(%s) => DEFERRED\n", name);
3844 *statp = EX_TEMPFAIL;
3849 ** If first character is a bracket, then it is an address
3850 ** lookup. Address is copied into a temporary buffer to
3851 ** strip the brackets and to preserve name if address is
3856 sm_dprintf("host_map_lookup(%s) => ", name);
3858 if (map->map_timeout > 0)
3860 retrans = _res.retrans;
3861 _res.retrans = map->map_timeout;
3863 if (map->map_retry > 0)
3866 _res.retry = map->map_retry;
3868 #endif /* NAMED_BIND */
3870 /* set default TTL */
3871 s->s_namecanon.nc_exp = now + SM_DEFAULT_TTL;
3876 (void) sm_strlcpy(hbuf, name, sizeof hbuf);
3877 if (getcanonname(hbuf, sizeof hbuf - 1, !HasWildcardMX, &ttl))
3881 s->s_namecanon.nc_exp = now + SM_MIN(ttl,
3887 if ((cp = strchr(name, ']')) == NULL)
3890 sm_dprintf("FAILED\n");
3897 if ((in_addr.s_addr = inet_addr(&name[1])) != INADDR_NONE)
3898 hp = sm_gethostbyaddr((char *)&in_addr,
3900 #endif /* NETINET */
3903 anynet_pton(AF_INET6, &name[1], &in6_addr) == 1)
3904 hp = sm_gethostbyaddr((char *)&in6_addr,
3905 IN6ADDRSZ, AF_INET6);
3906 #endif /* NETINET6 */
3911 /* found a match -- copy out */
3912 ans = denlstring((char *) hp->h_name, true, true);
3914 if (ans == hp->h_name)
3916 static char n[MAXNAME + 1];
3918 /* hp->h_name is about to disappear */
3919 (void) sm_strlcpy(n, ans, sizeof n);
3924 #endif /* NETINET6 */
3928 if (map->map_timeout > 0)
3929 _res.retrans = retrans;
3930 if (map->map_retry > 0)
3932 #endif /* NAMED_BIND */
3934 s->s_namecanon.nc_flags |= NCF_VALID; /* will be soon */
3936 /* Found an answer */
3939 s->s_namecanon.nc_stat = *statp = EX_OK;
3940 if (s->s_namecanon.nc_cname != NULL)
3941 sm_free(s->s_namecanon.nc_cname);
3942 s->s_namecanon.nc_cname = sm_strdup_x(ans);
3943 if (bitset(MF_MATCHONLY, map->map_mflags))
3944 cp = map_rewrite(map, name, strlen(name), NULL);
3946 cp = map_rewrite(map, ans, strlen(ans), av);
3948 sm_dprintf("FOUND %s\n", ans);
3953 /* No match found */
3954 s->s_namecanon.nc_errno = errno;
3956 s->s_namecanon.nc_herrno = h_errno;
3958 sm_dprintf("FAIL (%d)\n", h_errno);
3964 CurEnv->e_status = "4.4.3";
3965 message("851 %s: Name server timeout",
3966 shortenstring(name, 33));
3968 *statp = EX_TEMPFAIL;
3971 case HOST_NOT_FOUND:
3977 *statp = EX_SOFTWARE;
3981 *statp = EX_UNAVAILABLE;
3984 #else /* NAMED_BIND */
3986 sm_dprintf("FAIL\n");
3988 #endif /* NAMED_BIND */
3989 s->s_namecanon.nc_stat = *statp;
3993 ** HOST_MAP_INIT -- initialize host class structures
3996 ** map -- a pointer to this map.
3997 ** args -- argument string.
4004 host_map_init(map, args)
4008 register char *p = args;
4012 while (isascii(*p) && isspace(*p))
4023 map->map_tapp = ++p;
4027 map->map_mflags |= MF_MATCHONLY;
4031 map->map_mflags |= MF_NODEFER;
4034 case 'S': /* only for consistency */
4035 map->map_spacesub = *++p;
4039 map->map_mflags |= MF_DEFER;
4046 while (isascii(*++p) && isspace(*p))
4051 map->map_timeout = convtime(p, 's');
4058 while (isascii(*++p) && isspace(*p))
4060 map->map_retry = atoi(p);
4063 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4068 if (map->map_app != NULL)
4069 map->map_app = newstr(map->map_app);
4070 if (map->map_tapp != NULL)
4071 map->map_tapp = newstr(map->map_tapp);
4077 ** ANYNET_NTOP -- convert an IPv6 network address to printable form.
4080 ** s6a -- a pointer to an in6_addr structure.
4081 ** dst -- buffer to store result in
4082 ** dst_len -- size of dst buffer
4085 ** A printable version of that structure.
4089 anynet_ntop(s6a, dst, dst_len)
4090 struct in6_addr *s6a;
4096 if (IN6_IS_ADDR_V4MAPPED(s6a))
4097 ap = (char *) inet_ntop(AF_INET,
4098 &s6a->s6_addr[IN6ADDRSZ - INADDRSZ],
4105 /* Save pointer to beginning of string */
4108 /* Add IPv6: protocol tag */
4109 sz = sm_strlcpy(dst, "IPv6:", dst_len);
4114 ap = (char *) inet_ntop(AF_INET6, s6a, dst, dst_len);
4116 /* Restore pointer to beginning of string */
4124 ** ANYNET_PTON -- convert printed form to network address.
4126 ** Wrapper for inet_pton() which handles IPv6: labels.
4129 ** family -- address family
4131 ** dst -- destination address structure
4134 ** 1 if the address was valid
4135 ** 0 if the address wasn't parseable
4140 anynet_pton(family, src, dst)
4145 if (family == AF_INET6 && sm_strncasecmp(src, "IPv6:", 5) == 0)
4147 return inet_pton(family, src, dst);
4149 #endif /* NETINET6 */
4151 ** ANYNET_NTOA -- convert a network address to printable form.
4154 ** sap -- a pointer to a sockaddr structure.
4157 ** A printable version of that sockaddr.
4160 #ifdef USE_SOCK_STREAM
4163 # include <net/if_dl.h>
4164 # endif /* NETLINK */
4168 register SOCKADDR *sap;
4173 static char buf[100];
4175 /* check for null/zero family */
4178 if (sap->sa.sa_family == 0)
4181 switch (sap->sa.sa_family)
4185 if (sap->sunix.sun_path[0] != '\0')
4186 (void) sm_snprintf(buf, sizeof buf, "[UNIX: %.64s]",
4187 sap->sunix.sun_path);
4189 (void) sm_strlcpy(buf, "[UNIX: localhost]", sizeof buf);
4191 # endif /* NETUNIX */
4195 return (char *) inet_ntoa(sap->sin.sin_addr);
4196 # endif /* NETINET */
4200 ap = anynet_ntop(&sap->sin6.sin6_addr, buf, sizeof buf);
4204 # endif /* NETINET6 */
4208 (void) sm_snprintf(buf, sizeof buf, "[LINK: %s]",
4209 link_ntoa((struct sockaddr_dl *) &sap->sa));
4211 # endif /* NETLINK */
4213 /* this case is needed when nothing is #defined */
4214 /* in order to keep the switch syntactically correct */
4218 /* unknown family -- just dump bytes */
4219 (void) sm_snprintf(buf, sizeof buf, "Family %d: ", sap->sa.sa_family);
4220 bp = &buf[strlen(buf)];
4221 ap = sap->sa.sa_data;
4222 for (l = sizeof sap->sa.sa_data; --l >= 0; )
4224 (void) sm_snprintf(bp, SPACELEFT(buf, bp), "%02x:",
4232 ** HOSTNAMEBYANYADDR -- return name of host based on address
4235 ** sap -- SOCKADDR pointer
4238 ** text representation of host name.
4245 hostnamebyanyaddr(sap)
4246 register SOCKADDR *sap;
4248 register struct hostent *hp;
4251 # endif /* NAMED_BIND */
4253 struct in6_addr in6_addr;
4254 # endif /* NETINET6 */
4257 /* shorten name server timeout to avoid higher level timeouts */
4258 saveretry = _res.retry;
4259 if (_res.retry * _res.retrans > 20)
4260 _res.retry = 20 / _res.retrans;
4261 # endif /* NAMED_BIND */
4263 switch (sap->sa.sa_family)
4267 hp = sm_gethostbyaddr((char *) &sap->sin.sin_addr,
4270 # endif /* NETINET */
4274 hp = sm_gethostbyaddr((char *) &sap->sin6.sin6_addr,
4275 IN6ADDRSZ, AF_INET6);
4277 # endif /* NETINET6 */
4281 hp = sm_gethostbyaddr((char *) &sap->siso.siso_addr,
4282 sizeof sap->siso.siso_addr, AF_ISO);
4284 # endif /* NETISO */
4290 # endif /* NETUNIX */
4293 hp = sm_gethostbyaddr(sap->sa.sa_data, sizeof sap->sa.sa_data,
4299 _res.retry = saveretry;
4300 # endif /* NAMED_BIND */
4302 # if NETINET || NETINET6
4303 if (hp != NULL && hp->h_name[0] != '['
4305 && inet_pton(AF_INET6, hp->h_name, &in6_addr) != 1
4306 # endif /* NETINET6 */
4308 && inet_addr(hp->h_name) == INADDR_NONE
4309 # endif /* NETINET */
4314 name = denlstring((char *) hp->h_name, true, true);
4316 if (name == hp->h_name)
4318 static char n[MAXNAME + 1];
4320 /* Copy the string, hp->h_name is about to disappear */
4321 (void) sm_strlcpy(n, name, sizeof n);
4325 # endif /* NETINET6 */
4328 # endif /* NETINET || NETINET6 */
4336 # endif /* NETINET6 */
4339 if (sap->sa.sa_family == AF_UNIX && sap->sunix.sun_path[0] == '\0')
4341 # endif /* NETUNIX */
4343 static char buf[203];
4345 (void) sm_snprintf(buf, sizeof buf, "[%.200s]",
4350 #endif /* USE_SOCK_STREAM */