2 * Copyright (c) 1998-2007, 2009, 2010 Proofpoint, 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.
17 SM_RCSID("@(#)$Id: daemon.c,v 8.698 2013-11-22 20:51:55 ca Exp $")
18 #include <sm/sendmail.h>
20 #if defined(SOCK_STREAM) || defined(__GNU_LIBRARY__)
21 # define USE_SOCK_STREAM 1
24 #if defined(USE_SOCK_STREAM)
25 # if NETINET || NETINET6
26 # include <arpa/inet.h>
31 # include <openssl/rand.h>
34 # include "sm_resolve.h"
39 # include <sm/notify.h>
43 # define FREEHOSTENT(h, s) \
46 if ((h) != (s) && (h) != NULL) \
53 # define FREEHOSTENT(h, s)
58 #if IP_SRCROUTE && NETINET
59 # include <netinet/in_systm.h>
60 # include <netinet/ip.h>
62 # include <netinet/in.h>
64 # define IPOPTION ip_opts
65 # define IP_LIST ip_opts
66 # define IP_DST ip_dst
67 # endif /* ! IPOPTION */
69 # include <netinet/ip_var.h>
71 # define IPOPTION ipoption
72 # define IP_LIST ipopt_list
73 # define IP_DST ipopt_dst
74 # endif /* ! IPOPTION */
75 # endif /* HAS_IN_H */
76 #endif /* IP_SRCROUTE && NETINET */
85 static void connecttimeout __P((int));
86 static int opendaemonsocket __P((DAEMON_T *, bool));
87 static unsigned short setupdaemon __P((SOCKADDR *));
88 static void getrequests_checkdiskspace __P((ENVELOPE *e));
89 static void setsockaddroptions __P((char *, DAEMON_T *));
90 static void printdaemonflags __P((DAEMON_T *));
91 static int addr_family __P((char *));
92 static int addrcmp __P((struct hostent *, char *, SOCKADDR *));
93 static void authtimeout __P((int));
96 ** DAEMON.C -- routines to use when running as a daemon.
98 ** This entire file is highly dependent on the 4.2 BSD
99 ** interprocess communication primitives. No attempt has
100 ** been made to make this file portable to Version 7,
101 ** Version 6, MPX files, etc. If you should try such a
102 ** thing yourself, I recommend chucking the entire file
103 ** and starting from scratch. Basic semantics are:
106 ** Opens a port and initiates a connection.
107 ** Returns in a child. Must set InChannel and
108 ** OutChannel appropriately.
110 ** Close any open files associated with getting
111 ** the connection; this is used when running the queue,
112 ** etc., to avoid having extra file descriptors during
113 ** the queue run and to avoid confusing the network
114 ** code (if it cares).
115 ** makeconnection(host, port, mci, e, enough)
116 ** Make a connection to the named host on the given
117 ** port. Returns zero on success, else an exit status
118 ** describing the error.
119 ** host_map_lookup(map, hbuf, avp, pstat)
120 ** Convert the entry in hbuf into a canonical form.
123 static int NDaemons = 0; /* actual number of daemons */
125 static time_t NextDiskSpaceCheck = 0;
128 ** GETREQUESTS -- open mail IPC port and get requests.
131 ** e -- the current envelope.
137 ** Waits until some interesting activity occurs. When
138 ** it does, a child is created to process it, and the
139 ** parent waits for completion. Return from this
140 ** routine is always in the child. The file pointers
141 ** "InChannel" and "OutChannel" should be set to point
142 ** to the communication channel.
143 ** May restart persistent queue runners if they have ended
152 int idx, curdaemon = -1;
153 int i, olddaemon = 0;
157 char status[MAXLINE];
159 SOCKADDR_LEN_T len = sizeof(sa);
160 #if _FFR_QUEUE_RUN_PARANOIA
164 extern int ControlSocket;
166 extern ENVELOPE BlankEnvelope;
168 /* initialize data for function that generates queue ids */
170 for (idx = 0; idx < NDaemons; idx++)
172 Daemons[idx].d_port = setupdaemon(&(Daemons[idx].d_addr));
173 Daemons[idx].d_firsttime = true;
174 Daemons[idx].d_refuse_connections_until = (time_t) 0;
178 ** Try to actually open the connection.
183 for (idx = 0; idx < NDaemons; idx++)
185 sm_dprintf("getrequests: daemon %s: port %d\n",
187 ntohs(Daemons[idx].d_port));
191 /* get a socket for the SMTP connection */
192 for (idx = 0; idx < NDaemons; idx++)
193 Daemons[idx].d_socksize = opendaemonsocket(&Daemons[idx], true);
195 if (opencontrolsocket() < 0)
196 sm_syslog(LOG_WARNING, NOQID,
197 "daemon could not open control socket %s: %s",
198 ControlSocketName, sm_errstring(errno));
200 /* If there are any queue runners released reapchild() co-ord's */
201 (void) sm_signal(SIGCHLD, reapchild);
203 /* write the pid to file, command line args to syslog */
208 char jbuf[MAXHOSTNAMELEN];
210 expand("\201j", jbuf, sizeof(jbuf), e);
211 j_has_dot = strchr(jbuf, '.') != NULL;
215 /* Add parent process as first item */
216 proc_list_add(CurrentPid, "Sendmail daemon", PROC_DAEMON, 0, -1, NULL);
220 for (idx = 0; idx < NDaemons; idx++)
221 sm_dprintf("getrequests: daemon %s: socket %d\n",
223 Daemons[idx].d_socket);
229 auto SOCKADDR_LEN_T lotherend;
230 bool timedout = false;
231 bool control = false;
239 /* see if we are rejecting connections */
240 (void) sm_blocksignal(SIGALRM);
243 for (idx = 0; idx < NDaemons; idx++)
246 ** XXX do this call outside the loop?
247 ** no: refuse_connections may sleep().
251 if (now < Daemons[idx].d_refuse_connections_until)
253 if (bitnset(D_DISABLE, Daemons[idx].d_flags))
255 if (refuseconnections(e, idx, curdaemon == idx))
257 if (Daemons[idx].d_socket >= 0)
259 /* close socket so peer fails quickly */
260 (void) close(Daemons[idx].d_socket);
261 Daemons[idx].d_socket = -1;
264 /* refuse connections for next 15 seconds */
265 Daemons[idx].d_refuse_connections_until = now + 15;
267 else if (Daemons[idx].d_socket < 0 ||
268 Daemons[idx].d_firsttime)
270 if (!Daemons[idx].d_firsttime && LogLevel > 8)
271 sm_syslog(LOG_INFO, NOQID,
272 "accepting connections again for daemon %s",
273 Daemons[idx].d_name);
275 /* arrange to (re)open the socket if needed */
276 (void) opendaemonsocket(&Daemons[idx], false);
277 Daemons[idx].d_firsttime = false;
281 /* May have been sleeping above, check again */
284 getrequests_checkdiskspace(e);
287 /* check for disaster */
289 char jbuf[MAXHOSTNAMELEN];
291 expand("\201j", jbuf, sizeof(jbuf), e);
292 if (!wordinclass(jbuf, 'w'))
294 dumpstate("daemon lost $j");
295 sm_syslog(LOG_ALERT, NOQID,
296 "daemon process doesn't have $j in $=w; see syslog");
299 else if (j_has_dot && strchr(jbuf, '.') == NULL)
301 dumpstate("daemon $j lost dot");
302 sm_syslog(LOG_ALERT, NOQID,
303 "daemon process $j lost dot; see syslog");
311 ** Andrew Sun <asun@ieps-sun.ml.com> claims that this will
312 ** fix the SVr4 problem. But it seems to have gone away,
313 ** so is it worth doing this?
316 if (DaemonSocket >= 0 &&
317 SetNonBlocking(DaemonSocket, false) < 0)
320 (void) sm_releasesignal(SIGALRM);
324 bool setproc = false;
327 struct timeval timeout;
331 for (idx = 0; idx < NDaemons; idx++)
333 /* wait for a connection */
334 if (Daemons[idx].d_socket >= 0)
338 Daemons[idx].d_flags))
340 sm_setproctitle(true, e,
341 "accepting connections");
344 if (Daemons[idx].d_socket > highest)
345 highest = Daemons[idx].d_socket;
346 SM_FD_SET(Daemons[idx].d_socket,
352 if (ControlSocket >= 0)
354 if (ControlSocket > highest)
355 highest = ControlSocket;
356 SM_FD_SET(ControlSocket, &readfds);
363 t = select(highest + 1, FDSET_CAST &readfds,
364 NULL, NULL, &timeout);
366 /* Did someone signal while waiting? */
372 (void) runqueue(true, false, false, false);
373 #if _FFR_QUEUE_RUN_PARANOIA
377 #if _FFR_QUEUE_RUN_PARANOIA
378 else if (CheckQueueRunners > 0 && QueueIntvl > 0 &&
379 lastrun + QueueIntvl + CheckQueueRunners < now)
383 ** set lastrun unconditionally to avoid
384 ** calling checkqueuerunner() all the time.
385 ** That's also why we currently ignore the
386 ** result of the function call.
389 (void) checkqueuerunner();
392 #endif /* _FFR_QUEUE_RUN_PARANOIA */
403 /* look "round-robin" for an active socket */
404 if ((idx = olddaemon + 1) >= NDaemons)
406 for (i = 0; i < NDaemons; i++)
408 if (Daemons[idx].d_socket >= 0 &&
409 SM_FD_ISSET(Daemons[idx].d_socket,
412 lotherend = Daemons[idx].d_socksize;
413 memset(&RealHostAddr, '\0',
414 sizeof(RealHostAddr));
415 t = accept(Daemons[idx].d_socket,
416 (struct sockaddr *)&RealHostAddr,
420 ** If remote side closes before
421 ** accept() finishes, sockaddr
422 ** might not be fully filled in.
427 #ifdef BSD4_4_SOCKADDR
428 RealHostAddr.sa.sa_len == 0 ||
430 RealHostAddr.sa.sa_family != Daemons[idx].d_addr.sa.sa_family))
436 olddaemon = curdaemon = idx;
439 if (++idx >= NDaemons)
443 if (curdaemon == -1 && ControlSocket >= 0 &&
444 SM_FD_ISSET(ControlSocket, &readfds))
446 struct sockaddr_un sa_un;
448 lotherend = sizeof(sa_un);
449 memset(&sa_un, '\0', sizeof(sa_un));
450 t = accept(ControlSocket,
451 (struct sockaddr *)&sa_un,
455 ** If remote side closes before
456 ** accept() finishes, sockaddr
457 ** might not be fully filled in.
462 # ifdef BSD4_4_SOCKADDR
463 sa_un.sun_len == 0 ||
465 sa_un.sun_family != AF_UNIX))
477 /* No daemon to service */
481 if (t >= 0 || errno != EINTR)
490 (void) sm_blocksignal(SIGALRM);
495 /* let's ignore these temporary errors */
496 if (save_errno == EINTR
498 || save_errno == EAGAIN
501 || save_errno == ECONNABORTED
504 || save_errno == EWOULDBLOCK
509 syserr("getrequests: accept");
513 /* arrange to re-open socket next time around */
514 (void) close(Daemons[curdaemon].d_socket);
515 Daemons[curdaemon].d_socket = -1;
516 #if SO_REUSEADDR_IS_BROKEN
518 ** Give time for bound socket to be released.
519 ** This creates a denial-of-service if you can
520 ** force accept() to fail on affected systems.
523 Daemons[curdaemon].d_refuse_connections_until =
525 #endif /* SO_REUSEADDR_IS_BROKEN */
532 /* set some daemon related macros */
533 switch (Daemons[curdaemon].d_addr.sa.sa_family)
536 macdefine(&BlankEnvelope.e_macro, A_PERM,
537 macid("{daemon_family}"), "unspec");
541 macdefine(&BlankEnvelope.e_macro, A_PERM,
542 macid("{daemon_family}"), "local");
547 macdefine(&BlankEnvelope.e_macro, A_PERM,
548 macid("{daemon_family}"), "inet");
553 macdefine(&BlankEnvelope.e_macro, A_PERM,
554 macid("{daemon_family}"), "inet6");
559 macdefine(&BlankEnvelope.e_macro, A_PERM,
560 macid("{daemon_family}"), "iso");
565 macdefine(&BlankEnvelope.e_macro, A_PERM,
566 macid("{daemon_family}"), "ns");
571 macdefine(&BlankEnvelope.e_macro, A_PERM,
572 macid("{daemon_family}"), "x.25");
576 macdefine(&BlankEnvelope.e_macro, A_PERM,
577 macid("{daemon_name}"),
578 Daemons[curdaemon].d_name);
579 if (Daemons[curdaemon].d_mflags != NULL)
580 macdefine(&BlankEnvelope.e_macro, A_PERM,
581 macid("{daemon_flags}"),
582 Daemons[curdaemon].d_mflags);
584 macdefine(&BlankEnvelope.e_macro, A_PERM,
585 macid("{daemon_flags}"), "");
589 ** If connection rate is exceeded here, connection shall be
590 ** refused later by a new call after fork() by the
591 ** validate_connection() function. Closing the connection
592 ** at this point violates RFC 2821.
593 ** Do NOT remove this call, its side effects are needed.
596 connection_rate_check(&RealHostAddr, NULL);
599 ** Create a subprocess to process the mail.
603 sm_dprintf("getrequests: forking (fd = %d)\n", t);
606 ** Advance state of PRNG.
607 ** This is necessary because otherwise all child processes
608 ** will produce the same PRN sequence and hence the selection
609 ** of a queue directory (and other things, e.g., MX selection)
610 ** are not "really" random.
613 /* XXX get some better "random" data? */
615 RAND_seed((void *) &NextDiskSpaceCheck,
616 sizeof(NextDiskSpaceCheck));
617 RAND_seed((void *) &now, sizeof(now));
618 RAND_seed((void *) &seed, sizeof(seed));
621 #endif /* STARTTLS */
625 ** Update MX records for FallbackMX.
626 ** Let's hope this is fast otherwise we screw up the
630 if (FallbackMX != NULL)
631 (void) getfallbackmxrr(FallbackMX);
632 #endif /* NAMED_BIND */
636 /* don't fork, handle connection in this process */
638 pipefd[0] = pipefd[1] = -1;
643 ** Create a pipe to keep the child from writing to
644 ** the socket until after the parent has closed
645 ** it. Otherwise the parent may hang if the child
646 ** has closed it first.
649 if (pipe(pipefd) < 0)
650 pipefd[0] = pipefd[1] = -1;
652 (void) sm_blocksignal(SIGCHLD);
656 syserr("daemon: cannot fork");
659 (void) close(pipefd[0]);
660 (void) close(pipefd[1]);
662 (void) sm_releasesignal(SIGCHLD);
672 SM_FILE_T *inchannel, *outchannel = NULL;
675 ** CHILD -- return to caller.
676 ** Collect verified idea of sending host.
677 ** Verify calling user id if possible here.
680 /* Reset global flags */
681 RestartRequest = NULL;
682 RestartWorkGroup = false;
683 ShutdownRequest = NULL;
685 CurrentPid = getpid();
686 close_sendmail_pid();
688 (void) sm_releasesignal(SIGALRM);
689 (void) sm_releasesignal(SIGCHLD);
690 (void) sm_signal(SIGCHLD, SIG_DFL);
691 (void) sm_signal(SIGHUP, SIG_DFL);
692 (void) sm_signal(SIGTERM, intsig);
694 /* turn on profiling */
698 if (SM_TRIGGER == e->e_sendmode)
700 i = sm_notify_start(false, 0);
702 syserr("sm_notify_start(false) failed=%d", i);
707 ** Initialize exception stack and default exception
708 ** handler for child process.
711 sm_exc_newthread(fatal_error);
715 macdefine(&BlankEnvelope.e_macro, A_TEMP,
716 macid("{daemon_addr}"),
717 anynet_ntoa(&Daemons[curdaemon].d_addr));
718 (void) sm_snprintf(status, sizeof(status), "%d",
719 ntohs(Daemons[curdaemon].d_port));
720 macdefine(&BlankEnvelope.e_macro, A_TEMP,
721 macid("{daemon_port}"), status);
724 for (idx = 0; idx < NDaemons; idx++)
726 if (Daemons[idx].d_socket >= 0)
727 (void) close(Daemons[idx].d_socket);
728 Daemons[idx].d_socket = -1;
732 /* Avoid SMTP daemon actions if control command */
735 /* Add control socket process */
736 proc_list_add(CurrentPid,
737 "console socket child",
738 PROC_CONTROL_CHILD, 0, -1, NULL);
744 /* clean up background delivery children */
745 (void) sm_signal(SIGCHLD, reapchild);
747 /* Add parent process as first child item */
748 proc_list_add(CurrentPid, "daemon child",
749 PROC_DAEMON_CHILD, 0, -1, NULL);
750 /* don't schedule queue runs if ETRN */
754 ** Hack: override global variables if
755 ** the corresponding DaemonPortOption
758 #if _FFR_SS_PER_DAEMON
759 if (Daemons[curdaemon].d_supersafe !=
761 SuperSafe = Daemons[curdaemon].
763 #endif /* _FFR_SS_PER_DAEMON */
764 if (Daemons[curdaemon].d_dm != DM_NOTSET)
766 Daemons[curdaemon].d_dm, e);
768 if (Daemons[curdaemon].d_refuseLA !=
770 RefuseLA = Daemons[curdaemon].
772 if (Daemons[curdaemon].d_queueLA != DPO_NOTSET)
773 QueueLA = Daemons[curdaemon].d_queueLA;
774 if (Daemons[curdaemon].d_delayLA != DPO_NOTSET)
775 DelayLA = Daemons[curdaemon].d_delayLA;
776 if (Daemons[curdaemon].d_maxchildren !=
778 MaxChildren = Daemons[curdaemon].
781 sm_setproctitle(true, e, "startup with %s",
782 anynet_ntoa(&RealHostAddr));
790 ** Wait for the parent to close the write end
791 ** of the pipe, which we will see as an EOF.
792 ** This guarantees that we won't write to the
793 ** socket until after the parent has closed
797 /* close the write end of the pipe */
798 (void) close(pipefd[1]);
800 /* we shouldn't be interrupted, but ... */
801 while (read(pipefd[0], &c, 1) < 0 &&
804 (void) close(pipefd[0]);
807 /* control socket processing */
810 control_command(t, e);
815 /* determine host name */
816 p = hostnamebyanyaddr(&RealHostAddr);
817 if (strlen(p) > MAXNAME) /* XXX - 1 ? */
819 RealHostName = newstr(p);
820 if (RealHostName[0] == '[')
822 macdefine(&BlankEnvelope.e_macro, A_PERM,
823 macid("{client_resolve}"),
824 h_errno == TRY_AGAIN ? "TEMP" : "FAIL");
828 macdefine(&BlankEnvelope.e_macro, A_PERM,
829 macid("{client_resolve}"), "OK");
831 sm_setproctitle(true, e, "startup with %s", p);
832 markstats(e, NULL, STATS_CONNECT);
834 if ((inchannel = sm_io_open(SmFtStdiofd,
840 (outchannel = sm_io_open(SmFtStdiofd,
846 syserr("cannot open SMTP server channel, fd=%d",
848 finis(false, true, EX_OK);
850 sm_io_automode(inchannel, outchannel);
852 InChannel = inchannel;
853 OutChannel = outchannel;
854 DisConnected = false;
857 t = xconnect(inchannel);
860 clrbitn(D_XCNCT, Daemons[curdaemon].d_flags);
861 clrbitn(D_XCNCT_M, Daemons[curdaemon].d_flags);
864 setbitn(t, Daemons[curdaemon].d_flags);
865 #endif /* _FFR_XCNCT */
868 if (!xla_host_ok(RealHostName))
870 message("421 4.4.5 Too many SMTP sessions for this host");
871 finis(false, true, EX_OK);
874 /* find out name for interface of connection */
875 if (getsockname(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
876 NULL), &sa.sa, &len) == 0)
878 p = hostnamebyanyaddr(&sa);
880 sm_dprintf("getreq: got name %s\n", p);
881 macdefine(&BlankEnvelope.e_macro, A_TEMP,
882 macid("{if_name}"), p);
885 ** Do this only if it is not the loopback
894 addr = anynet_ntoa(&sa);
895 (void) sm_snprintf(family,
897 "%d", sa.sa.sa_family);
898 macdefine(&BlankEnvelope.e_macro,
900 macid("{if_addr}"), addr);
901 macdefine(&BlankEnvelope.e_macro,
903 macid("{if_family}"), family);
905 sm_dprintf("getreq: got addr %s and family %s\n",
910 macdefine(&BlankEnvelope.e_macro,
912 macid("{if_addr}"), NULL);
913 macdefine(&BlankEnvelope.e_macro,
915 macid("{if_family}"), NULL);
921 sm_dprintf("getreq: getsockname failed\n");
922 macdefine(&BlankEnvelope.e_macro, A_PERM,
923 macid("{if_name}"), NULL);
924 macdefine(&BlankEnvelope.e_macro, A_PERM,
925 macid("{if_addr}"), NULL);
926 macdefine(&BlankEnvelope.e_macro, A_PERM,
927 macid("{if_family}"), NULL);
932 /* parent -- keep track of children */
935 (void) sm_snprintf(status, sizeof(status),
936 "control socket server child");
937 proc_list_add(pid, status, PROC_CONTROL, 0, -1, NULL);
941 (void) sm_snprintf(status, sizeof(status),
942 "SMTP server child for %s",
943 anynet_ntoa(&RealHostAddr));
944 proc_list_add(pid, status, PROC_DAEMON, 0, -1,
947 (void) sm_releasesignal(SIGCHLD);
949 /* close the read end of the synchronization pipe */
952 (void) close(pipefd[0]);
956 /* close the port so that others will hang (for a while) */
959 /* release the child by closing the read end of the sync pipe */
962 (void) close(pipefd[1]);
967 sm_dprintf("getrequests: returning\n");
970 /* set the filters for this daemon */
971 if (Daemons[curdaemon].d_inputfilterlist != NULL)
975 Daemons[curdaemon].d_inputfilters[i] != NULL);
978 InputFilters[i] = Daemons[curdaemon].d_inputfilters[i];
981 InputFilters[i] = NULL;
984 return &Daemons[curdaemon].d_flags;
988 ** GETREQUESTS_CHECKDISKSPACE -- check available diskspace.
997 ** Modifies Daemon flags (D_ETRNONLY) if not enough disk space.
1001 getrequests_checkdiskspace(e)
1004 bool logged = false;
1009 if (now < NextDiskSpaceCheck)
1012 /* Check if there is available disk space in all queue groups. */
1013 if (!enoughdiskspace(0, NULL))
1015 for (idx = 0; idx < NDaemons; ++idx)
1017 if (bitnset(D_ETRNONLY, Daemons[idx].d_flags))
1020 /* log only if not logged before */
1024 sm_syslog(LOG_INFO, NOQID,
1025 "rejecting new messages: min free: %ld",
1027 sm_setproctitle(true, e,
1028 "rejecting new messages: min free: %ld",
1032 setbitn(D_ETRNONLY, Daemons[idx].d_flags);
1037 for (idx = 0; idx < NDaemons; ++idx)
1039 if (!bitnset(D_ETRNONLY, Daemons[idx].d_flags))
1042 /* log only if not logged before */
1046 sm_syslog(LOG_INFO, NOQID,
1047 "accepting new messages (again)");
1051 /* title will be set later */
1052 clrbitn(D_ETRNONLY, Daemons[idx].d_flags);
1056 /* only check disk space once a minute */
1057 NextDiskSpaceCheck = now + 60;
1061 ** OPENDAEMONSOCKET -- open SMTP socket
1063 ** Deals with setting all appropriate options.
1066 ** d -- the structure for the daemon to open.
1067 ** firsttime -- set if this is the initial open.
1070 ** Size in bytes of the daemon socket addr.
1073 ** Leaves DaemonSocket set to the open socket.
1074 ** Exits if the socket cannot be created.
1077 #define MAXOPENTRIES 10 /* maximum number of tries to open connection */
1080 opendaemonsocket(d, firsttime)
1086 SOCKADDR_LEN_T socksize = 0;
1091 sm_dprintf("opendaemonsocket(%s)\n", d->d_name);
1097 if (firsttime || d->d_socket < 0)
1100 if (d->d_addr.sa.sa_family == AF_UNIX)
1103 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_ROOTOK|SFF_EXECOK|SFF_CREAT;
1105 /* if not safe, don't use it */
1106 rval = safefile(d->d_addr.sunix.sun_path,
1109 S_IRUSR|S_IWUSR, NULL);
1113 syserr("opendaemonsocket: daemon %s: unsafe domain socket %s",
1115 d->d_addr.sunix.sun_path);
1119 /* Don't try to overtake an existing socket */
1120 (void) unlink(d->d_addr.sunix.sun_path);
1122 #endif /* NETUNIX */
1123 d->d_socket = socket(d->d_addr.sa.sa_family,
1125 if (d->d_socket < 0)
1128 syserr("opendaemonsocket: daemon %s: can't create server SMTP socket",
1131 if (bitnset(D_OPTIONAL, d->d_flags) &&
1132 (!transienterror(save_errno) ||
1133 ntries >= MAXOPENTRIES - 1))
1135 syserr("opendaemonsocket: daemon %s: optional socket disabled",
1137 setbitn(D_DISABLE, d->d_flags);
1143 sm_syslog(LOG_ALERT, NOQID,
1144 "daemon %s: problem creating SMTP socket",
1150 if (!SM_FD_OK_SELECT(d->d_socket))
1152 save_errno = EINVAL;
1153 syserr("opendaemonsocket: daemon %s: server SMTP socket (%d) too large",
1154 d->d_name, d->d_socket);
1158 /* turn on network debugging? */
1160 (void) setsockopt(d->d_socket, SOL_SOCKET,
1161 SO_DEBUG, (char *)&on,
1164 (void) setsockopt(d->d_socket, SOL_SOCKET,
1165 SO_REUSEADDR, (char *)&on, sizeof(on));
1166 (void) setsockopt(d->d_socket, SOL_SOCKET,
1167 SO_KEEPALIVE, (char *)&on, sizeof(on));
1170 if (d->d_tcprcvbufsize > 0)
1172 if (setsockopt(d->d_socket, SOL_SOCKET,
1174 (char *) &d->d_tcprcvbufsize,
1175 sizeof(d->d_tcprcvbufsize)) < 0)
1176 syserr("opendaemonsocket: daemon %s: setsockopt(SO_RCVBUF)", d->d_name);
1178 #endif /* SO_RCVBUF */
1180 if (d->d_tcpsndbufsize > 0)
1182 if (setsockopt(d->d_socket, SOL_SOCKET,
1184 (char *) &d->d_tcpsndbufsize,
1185 sizeof(d->d_tcpsndbufsize)) < 0)
1186 syserr("opendaemonsocket: daemon %s: setsockopt(SO_SNDBUF)", d->d_name);
1188 #endif /* SO_SNDBUF */
1190 if ((fdflags = fcntl(d->d_socket, F_GETFD, 0)) == -1 ||
1191 fcntl(d->d_socket, F_SETFD,
1192 fdflags | FD_CLOEXEC) == -1)
1195 syserr("opendaemonsocket: daemon %s: failed to %s close-on-exec flag: %s",
1197 fdflags == -1 ? "get" : "set",
1198 sm_errstring(save_errno));
1199 (void) close(d->d_socket);
1203 switch (d->d_addr.sa.sa_family)
1207 socksize = sizeof(d->d_addr.sunix);
1212 socksize = sizeof(d->d_addr.sin);
1218 socksize = sizeof(d->d_addr.sin6);
1224 socksize = sizeof(d->d_addr.siso);
1229 socksize = sizeof(d->d_addr);
1233 if (bind(d->d_socket, &d->d_addr.sa, socksize) < 0)
1235 /* probably another daemon already */
1237 syserr("opendaemonsocket: daemon %s: cannot bind",
1239 (void) close(d->d_socket);
1244 listen(d->d_socket, d->d_listenqueue) < 0)
1247 syserr("opendaemonsocket: daemon %s: cannot listen",
1249 (void) close(d->d_socket);
1253 } while (ntries++ < MAXOPENTRIES && transienterror(save_errno));
1254 syserr("!opendaemonsocket: daemon %s: server SMTP socket wedged: exiting",
1257 return -1; /* avoid compiler warning on IRIX */
1260 ** SETUPDAEMON -- setup socket for daemon
1263 ** daemonaddr -- socket for daemon
1266 ** port number on which daemon should run
1270 static unsigned short
1271 setupdaemon(daemonaddr)
1272 SOCKADDR *daemonaddr;
1274 unsigned short port;
1277 ** Set up the address for the mailer.
1280 if (daemonaddr->sa.sa_family == AF_UNSPEC)
1282 memset(daemonaddr, '\0', sizeof(*daemonaddr));
1284 daemonaddr->sa.sa_family = AF_INET;
1288 switch (daemonaddr->sa.sa_family)
1292 if (daemonaddr->sin.sin_addr.s_addr == 0)
1293 daemonaddr->sin.sin_addr.s_addr =
1294 LocalDaemon ? htonl(INADDR_LOOPBACK) : INADDR_ANY;
1295 port = daemonaddr->sin.sin_port;
1297 #endif /* NETINET */
1301 if (IN6_IS_ADDR_UNSPECIFIED(&daemonaddr->sin6.sin6_addr))
1302 daemonaddr->sin6.sin6_addr =
1303 (LocalDaemon && V6LoopbackAddrFound) ?
1304 in6addr_loopback : in6addr_any;
1305 port = daemonaddr->sin6.sin6_port;
1307 #endif /* NETINET6 */
1310 /* unknown protocol */
1316 #ifdef NO_GETSERVBYNAME
1318 #else /* NO_GETSERVBYNAME */
1320 register struct servent *sp;
1322 sp = getservbyname("smtp", "tcp");
1325 syserr("554 5.3.5 service \"smtp\" unknown");
1331 #endif /* NO_GETSERVBYNAME */
1334 switch (daemonaddr->sa.sa_family)
1338 daemonaddr->sin.sin_port = port;
1344 daemonaddr->sin6.sin6_port = port;
1349 /* unknown protocol */
1355 ** CLRDAEMON -- reset the daemon connection
1364 ** releases any resources used by the passive daemon.
1372 for (i = 0; i < NDaemons; i++)
1374 if (Daemons[i].d_socket >= 0)
1375 (void) close(Daemons[i].d_socket);
1376 Daemons[i].d_socket = -1;
1381 ** GETMODIFIERS -- get modifier flags
1384 ** v -- the modifiers (input text line).
1385 ** modifiers -- pointer to flag field to represent modifiers.
1388 ** (xallocat()ed) string representation of modifiers.
1391 ** fills in modifiers.
1395 getmodifiers(v, modifiers)
1397 BITMAP256 modifiers;
1400 char *h, *f, *flags;
1402 /* maximum length of flags: upper case Option -> "OO " */
1403 l = 3 * strlen(v) + 3;
1405 /* is someone joking? */
1406 if (l < 0 || l > 256)
1409 sm_syslog(LOG_ERR, NOQID,
1410 "getmodifiers too long, ignored");
1415 clrbitmap(modifiers);
1416 for (h = v; *h != '\0'; h++)
1418 if (isascii(*h) && !isspace(*h) && isprint(*h))
1420 setbitn(*h, modifiers);
1433 ** CHKDAEMONMODIFIERS -- check whether all daemons have set a flag.
1436 ** flag -- the flag to test.
1439 ** true iff all daemons have set flag.
1443 chkdaemonmodifiers(flag)
1448 for (i = 0; i < NDaemons; i++)
1449 if (!bitnset((char) flag, Daemons[i].d_flags))
1455 ** SETSOCKADDROPTIONS -- set options for SOCKADDR (daemon or client)
1458 ** p -- the options line.
1459 ** d -- the daemon structure to fill in.
1466 setsockaddroptions(p, d)
1477 if (d->d_addr.sa.sa_family == AF_UNSPEC)
1478 d->d_addr.sa.sa_family = AF_INET;
1480 #if _FFR_SS_PER_DAEMON
1481 d->d_supersafe = DPO_NOTSET;
1483 d->d_dm = DM_NOTSET;
1484 d->d_refuseLA = DPO_NOTSET;
1485 d->d_queueLA = DPO_NOTSET;
1486 d->d_delayLA = DPO_NOTSET;
1487 d->d_maxchildren = DPO_NOTSET;
1494 while (SM_ISSPACE(*p))
1505 while (isascii(*++v) && isspace(*v))
1510 case 'A': /* address */
1518 d->d_maxchildren = atoi(v);
1521 case 'D': /* DeliveryMode */
1534 syserr("554 5.3.5 Unknown delivery mode %c",
1540 case 'd': /* delayLA */
1541 d->d_delayLA = atoi(v);
1544 case 'F': /* address family */
1548 if (isascii(*v) && isdigit(*v))
1549 d->d_addr.sa.sa_family = atoi(v);
1551 else if (SM_STRCASEEQ(v, "unix") ||
1552 SM_STRCASEEQ(v, "local"))
1553 d->d_addr.sa.sa_family = AF_UNIX;
1556 else if (SM_STRCASEEQ(v, "inet"))
1557 d->d_addr.sa.sa_family = AF_INET;
1560 else if (SM_STRCASEEQ(v, "inet6"))
1561 d->d_addr.sa.sa_family = AF_INET6;
1564 else if (SM_STRCASEEQ(v, "iso"))
1565 d->d_addr.sa.sa_family = AF_ISO;
1568 else if (SM_STRCASEEQ(v, "ns"))
1569 d->d_addr.sa.sa_family = AF_NS;
1572 else if (SM_STRCASEEQ(v, "x.25"))
1573 d->d_addr.sa.sa_family = AF_CCITT;
1576 syserr("554 5.3.5 Unknown address family %s in Family=option",
1585 d->d_inputfilterlist = v;
1589 case 'L': /* listen queue size */
1593 d->d_listenqueue = atoi(v);
1596 case 'M': /* modifiers (flags) */
1600 d->d_mflags = getmodifiers(v, d->d_flags);
1603 case 'N': /* name */
1610 case 'P': /* port */
1618 d->d_queueLA = atoi(v);
1621 case 'R': /* receive buffer size */
1622 d->d_tcprcvbufsize = atoi(v);
1626 d->d_refuseLA = atoi(v);
1629 case 'S': /* send buffer size */
1633 d->d_tcpsndbufsize = atoi(v);
1636 #if _FFR_SS_PER_DAEMON
1637 case 'T': /* SuperSafe */
1638 if (tolower(*v) == 'i')
1639 d->d_supersafe = SAFE_INTERACTIVE;
1640 else if (tolower(*v) == 'p')
1642 d->d_supersafe = SAFE_REALLY_POSTMILTER;
1644 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1645 "Warning: SuperSafe=PostMilter requires Milter support (-DMILTER)\n");
1646 # endif /* MILTER */
1648 d->d_supersafe = atobool(v) ? SAFE_REALLY
1651 #endif /* _FFR_SS_PER_DAEMON */
1654 syserr("554 5.3.5 PortOptions parameter \"%s\" unknown",
1659 /* Check addr and port after finding family */
1662 switch (d->d_addr.sa.sa_family)
1666 if (strlen(addr) >= sizeof(d->d_addr.sunix.sun_path))
1668 errno = ENAMETOOLONG;
1669 syserr("setsockaddroptions: domain socket name too long: %s > %ld",
1671 (long) sizeof(d->d_addr.sunix.sun_path));
1675 /* file safety check done in opendaemonsocket() */
1676 (void) memset(&d->d_addr.sunix.sun_path, '\0',
1677 sizeof(d->d_addr.sunix.sun_path));
1678 (void) sm_strlcpy((char *)&d->d_addr.sunix.sun_path,
1680 sizeof(d->d_addr.sunix.sun_path));
1682 #endif /* NETUNIX */
1685 if (!isascii(*addr) || !isdigit(*addr) ||
1686 ((d->d_addr.sin.sin_addr.s_addr = inet_addr(addr))
1689 register struct hostent *hp;
1691 hp = sm_gethostbyname(addr, AF_INET);
1693 syserr("554 5.3.0 host \"%s\" unknown",
1697 while (*(hp->h_addr_list) != NULL &&
1698 hp->h_addrtype != AF_INET)
1700 if (*(hp->h_addr_list) == NULL)
1701 syserr("554 5.3.0 host \"%s\" unknown",
1704 memmove(&d->d_addr.sin.sin_addr,
1707 FREEHOSTENT(hp, NULL);
1711 #endif /* NETINET */
1715 if (anynet_pton(AF_INET6, addr,
1716 &d->d_addr.sin6.sin6_addr) != 1)
1718 register struct hostent *hp;
1720 hp = sm_gethostbyname(addr, AF_INET6);
1722 syserr("554 5.3.0 host \"%s\" unknown",
1726 while (*(hp->h_addr_list) != NULL &&
1727 hp->h_addrtype != AF_INET6)
1729 if (*(hp->h_addr_list) == NULL)
1730 syserr("554 5.3.0 host \"%s\" unknown",
1733 memmove(&d->d_addr.sin6.sin6_addr,
1736 FREEHOSTENT(hp, NULL);
1740 #endif /* NETINET6 */
1743 syserr("554 5.3.5 address= option unsupported for family %d",
1744 d->d_addr.sa.sa_family);
1751 switch (d->d_addr.sa.sa_family)
1755 if (isascii(*port) && isdigit(*port))
1756 d->d_addr.sin.sin_port = htons((unsigned short)
1757 atoi((const char *) port));
1760 # ifdef NO_GETSERVBYNAME
1761 syserr("554 5.3.5 invalid port number: %s",
1763 # else /* NO_GETSERVBYNAME */
1764 register struct servent *sp;
1766 sp = getservbyname(port, "tcp");
1768 syserr("554 5.3.5 service \"%s\" unknown",
1771 d->d_addr.sin.sin_port = sp->s_port;
1772 # endif /* NO_GETSERVBYNAME */
1775 #endif /* NETINET */
1779 if (isascii(*port) && isdigit(*port))
1780 d->d_addr.sin6.sin6_port = htons((unsigned short)
1784 # ifdef NO_GETSERVBYNAME
1785 syserr("554 5.3.5 invalid port number: %s",
1787 # else /* NO_GETSERVBYNAME */
1788 register struct servent *sp;
1790 sp = getservbyname(port, "tcp");
1792 syserr("554 5.3.5 service \"%s\" unknown",
1795 d->d_addr.sin6.sin6_port = sp->s_port;
1796 # endif /* NO_GETSERVBYNAME */
1799 #endif /* NETINET6 */
1803 /* assume two byte transport selector */
1804 if (isascii(*port) && isdigit(*port))
1805 portno = htons((unsigned short) atoi(port));
1808 # ifdef NO_GETSERVBYNAME
1809 syserr("554 5.3.5 invalid port number: %s",
1811 # else /* NO_GETSERVBYNAME */
1812 register struct servent *sp;
1814 sp = getservbyname(port, "tcp");
1816 syserr("554 5.3.5 service \"%s\" unknown",
1819 portno = sp->s_port;
1820 # endif /* NO_GETSERVBYNAME */
1822 memmove(TSEL(&d->d_addr.siso),
1823 (char *) &portno, 2);
1828 syserr("554 5.3.5 Port= option unsupported for family %d",
1829 d->d_addr.sa.sa_family);
1835 ** SETDAEMONOPTIONS -- set options for running the MTA daemon
1838 ** p -- the options line.
1841 ** true if successful, false otherwise.
1844 ** increments number of daemons.
1847 #define DEF_LISTENQUEUE 10
1855 static struct dflags DaemonFlags[] =
1857 { "AUTHREQ", D_AUTHREQ },
1858 { "BINDIF", D_BINDIF },
1859 { "CANONREQ", D_CANONREQ },
1860 { "IFNHELO", D_IFNHELO },
1861 { "FQMAIL", D_FQMAIL },
1862 { "FQRCPT", D_FQRCPT },
1863 { "SMTPS", D_SMTPS },
1864 { "UNQUALOK", D_UNQUALOK },
1865 { "NOAUTH", D_NOAUTH },
1866 { "NOCANON", D_NOCANON },
1867 { "NODANE", D_NODANE },
1868 { "NOETRN", D_NOETRN },
1869 { "NOSTS", D_NOSTS },
1870 { "NOTLS", D_NOTLS },
1871 { "ETRNONLY", D_ETRNONLY },
1872 { "OPTIONAL", D_OPTIONAL },
1873 { "DISABLE", D_DISABLE },
1874 { "ISSET", D_ISSET },
1876 { "XCNCT", D_XCNCT },
1877 { "XCNCT_M", D_XCNCT_M },
1886 register struct dflags *df;
1889 for (df = DaemonFlags; df->d_name != NULL; df++)
1891 if (!bitnset(df->d_flag, d->d_flags))
1894 sm_dprintf("<%s", df->d_name);
1896 sm_dprintf(",%s", df->d_name);
1907 if (NDaemons >= MAXDAEMONS)
1909 Daemons[NDaemons].d_socket = -1;
1910 Daemons[NDaemons].d_listenqueue = DEF_LISTENQUEUE;
1911 clrbitmap(Daemons[NDaemons].d_flags);
1912 setsockaddroptions(p, &Daemons[NDaemons]);
1915 if (Daemons[NDaemons].d_inputfilterlist != NULL)
1916 Daemons[NDaemons].d_inputfilterlist = newstr(Daemons[NDaemons].d_inputfilterlist);
1919 if (Daemons[NDaemons].d_name != NULL)
1920 Daemons[NDaemons].d_name = newstr(Daemons[NDaemons].d_name);
1925 (void) sm_snprintf(num, sizeof(num), "Daemon%d", NDaemons);
1926 Daemons[NDaemons].d_name = newstr(num);
1931 sm_dprintf("Daemon %s flags: ", Daemons[NDaemons].d_name);
1932 printdaemonflags(&Daemons[NDaemons]);
1939 ** INITDAEMON -- initialize daemon if not yet done.
1948 ** initializes structure for one daemon.
1956 Daemons[NDaemons].d_socket = -1;
1957 Daemons[NDaemons].d_listenqueue = DEF_LISTENQUEUE;
1958 Daemons[NDaemons].d_name = "Daemon0";
1963 ** SETCLIENTOPTIONS -- set options for running the client
1966 ** p -- the options line.
1972 static DAEMON_T ClientSettings[AF_MAX + 1];
1981 memset(&d, '\0', sizeof(d));
1982 setsockaddroptions(p, &d);
1984 /* grab what we need */
1985 family = d.d_addr.sa.sa_family;
1986 STRUCTCOPY(d, ClientSettings[family]);
1987 setbitn(D_ISSET, ClientSettings[family].d_flags); /* mark as set */
1988 if (d.d_name != NULL)
1989 ClientSettings[family].d_name = newstr(d.d_name);
1994 (void) sm_snprintf(num, sizeof(num), "Client%d", family);
1995 ClientSettings[family].d_name = newstr(num);
1999 ** ADDR_FAMILY -- determine address family from address
2002 ** addr -- the string representation of the address
2005 ** AF_INET, AF_INET6 or AF_UNSPEC
2020 if (inet_addr(addr) != INADDR_NONE)
2023 sm_dprintf("addr_family(%s): INET\n", addr);
2026 #endif /* NETINET */
2028 if (anynet_pton(AF_INET6, addr, &clt_addr.sin6.sin6_addr) == 1)
2031 sm_dprintf("addr_family(%s): INET6\n", addr);
2034 #endif /* NETINET6 */
2039 sm_dprintf("addr_family(%s): LOCAL\n", addr);
2042 #endif /* NETUNIX */
2044 sm_dprintf("addr_family(%s): UNSPEC\n", addr);
2049 ** CHKCLIENTMODIFIERS -- check whether all clients have set a flag.
2052 ** flag -- the flag to test.
2055 ** true iff all configured clients have set the flag.
2059 chkclientmodifiers(flag)
2066 for (i = 0; i < AF_MAX; i++)
2068 if (bitnset(D_ISSET, ClientSettings[i].d_flags))
2070 if (!bitnset((char) flag, ClientSettings[i].d_flags))
2080 ** SETUP_DAEMON_MILTERS -- Parse per-socket filters
2090 setup_daemon_milters()
2094 if (OpMode == MD_SMTP)
2096 /* no need to configure the daemons */
2100 for (idx = 0; idx < NDaemons; idx++)
2102 if (Daemons[idx].d_inputfilterlist != NULL)
2104 milter_config(Daemons[idx].d_inputfilterlist,
2105 Daemons[idx].d_inputfilters,
2112 ** MAKECONNECTION -- make a connection to an SMTP socket on a machine.
2115 ** host -- the name of the host.
2116 ** port -- the port number to connect to.
2117 ** mci -- a pointer to the mail connection information
2118 ** structure to be filled in.
2119 ** e -- the current envelope.
2120 ** enough -- time at which to stop further connection attempts.
2121 ** (0 means no limit)
2124 ** An exit code telling whether the connection could be
2125 ** made and if not why not.
2131 static jmp_buf CtxConnectTimeout;
2133 SOCKADDR CurHostAddr; /* address of current host */
2136 makeconnection(host, port, mci, e, enough
2142 volatile unsigned int port;
2147 unsigned long *ptlsa_flags;
2150 register volatile int addrno = 0;
2152 register struct hostent *volatile hp = (struct hostent *) NULL;
2156 volatile SOCKADDR_LEN_T addrlen;
2157 volatile bool firstconnect = true;
2158 SM_EVENT *volatile ev = NULL;
2160 volatile bool v6found = false;
2162 volatile int family;
2164 volatile SOCKADDR_LEN_T socksize = 0;
2165 volatile bool clt_bind;
2168 extern ENVELOPE BlankEnvelope;
2170 unsigned long tlsa_flags;
2172 #if DANE && NETINET6
2173 struct hostent *volatile hs = (struct hostent *) NULL;
2175 # define hs ((struct hostent *) NULL)
2179 SM_REQUIRE(ptlsa_flags != NULL);
2180 tlsa_flags = *ptlsa_flags;
2181 *ptlsa_flags &= ~TLSAFLADIP;
2183 #if _FFR_M_ONLY_IPV4
2184 if (bitnset(M_ONLY_IPV4, mci->mci_mailer->m_flags))
2190 /* retranslate {daemon_flags} into bitmap */
2192 if ((p = macvalue(macid("{daemon_flags}"), e)) != NULL)
2194 for (; *p != '\0'; p++)
2196 if (!(SM_ISSPACE(*p)))
2197 setbitn(bitidx(*p), d_flags);
2206 /* Set up the address for outgoing connection. */
2207 if (bitnset(D_BINDIF, d_flags) &&
2208 (p = macvalue(macid("{if_addr}"), e)) != NULL &&
2212 char p6[INET6_ADDRSTRLEN];
2215 memset(&clt_addr, '\0', sizeof(clt_addr));
2217 /* infer the address family from the address itself */
2218 clt_addr.sa.sa_family = addr_family(p);
2219 switch (clt_addr.sa.sa_family)
2223 clt_addr.sin.sin_addr.s_addr = inet_addr(p);
2224 if (clt_addr.sin.sin_addr.s_addr != INADDR_NONE &&
2225 clt_addr.sin.sin_addr.s_addr !=
2226 htonl(INADDR_LOOPBACK))
2229 socksize = sizeof(struct sockaddr_in);
2232 #endif /* NETINET */
2236 if (inet_addr(p) != INADDR_NONE)
2237 (void) sm_snprintf(p6, sizeof(p6),
2238 "IPv6:::ffff:%s", p);
2240 (void) sm_strlcpy(p6, p, sizeof(p6));
2241 if (anynet_pton(AF_INET6, p6,
2242 &clt_addr.sin6.sin6_addr) == 1 &&
2243 !IN6_IS_ADDR_LOOPBACK(&clt_addr.sin6.sin6_addr))
2246 socksize = sizeof(struct sockaddr_in6);
2249 #endif /* NETINET6 */
2253 syserr("554 5.3.5 Address= option unsupported for family %d",
2254 clt_addr.sa.sa_family);
2259 family = clt_addr.sa.sa_family;
2262 /* D_BINDIF not set or not available, fallback to ClientPortOptions */
2265 STRUCTCOPY(ClientSettings[family].d_addr, clt_addr);
2266 switch (clt_addr.sa.sa_family)
2270 if (clt_addr.sin.sin_addr.s_addr == 0)
2271 clt_addr.sin.sin_addr.s_addr = LocalDaemon ?
2272 htonl(INADDR_LOOPBACK) : INADDR_ANY;
2275 if (clt_addr.sin.sin_port != 0)
2277 socksize = sizeof(struct sockaddr_in);
2279 #endif /* NETINET */
2282 if (IN6_IS_ADDR_UNSPECIFIED(&clt_addr.sin6.sin6_addr))
2283 clt_addr.sin6.sin6_addr =
2284 (LocalDaemon && V6LoopbackAddrFound) ?
2285 in6addr_loopback : in6addr_any;
2288 socksize = sizeof(struct sockaddr_in6);
2289 if (clt_addr.sin6.sin6_port != 0)
2292 #endif /* NETINET6 */
2295 socksize = sizeof(clt_addr.siso);
2305 ** Set up the address for the mailer.
2306 ** Accept "[a.b.c.d]" syntax for host name.
2311 memset(&CurHostAddr, '\0', sizeof(CurHostAddr));
2312 memset(&addr, '\0', sizeof(addr));
2313 SmtpPhase = mci->mci_phase = "initial connection";
2318 p = strchr(host, ']');
2322 unsigned long hid = INADDR_NONE;
2325 struct sockaddr_in6 hid6;
2330 memset(&hid6, '\0', sizeof(hid6));
2333 if (family == AF_INET &&
2334 (hid = inet_addr(&host[1])) != INADDR_NONE)
2336 addr.sin.sin_family = AF_INET;
2337 addr.sin.sin_addr.s_addr = hid;
2340 #endif /* NETINET */
2342 if (family == AF_INET6 &&
2343 anynet_pton(AF_INET6, &host[1],
2344 &hid6.sin6_addr) == 1)
2346 addr.sin6.sin6_family = AF_INET6;
2347 addr.sin6.sin6_addr = hid6.sin6_addr;
2350 #endif /* NETINET6 */
2352 /* try it as a host name (avoid MX lookup) */
2353 hp = sm_gethostbyname(&host[1], family);
2354 if (hp == NULL && p[-1] == '.')
2357 int oldopts = _res.options;
2359 _res.options &= ~(RES_DEFNAMES|RES_DNSRCH);
2360 #endif /* NAMED_BIND */
2362 hp = sm_gethostbyname(&host[1],
2366 _res.options = oldopts;
2376 extern char MsgBuf[];
2379 "553 Invalid numeric domain spec \"%s\"",
2381 mci_setstat(mci, EX_NOHOST, "5.1.2", MsgBuf);
2388 /* contortion to get around SGI cc complaints */
2390 p = &host[strlen(host) - 1];
2393 sm_dprintf("makeconnection: tlsa_flags=%#lx, host=%s\n",
2395 if (DANEMODE(tlsa_flags) == DANE_SECURE
2404 rr = dns_lookup_int(host, C_IN, FAM2T_(family),
2405 0, 0, SM_RES_DNSSEC, 0, &err, &herr);
2408 ** Check for errors!
2409 ** If no ad: turn off TLSA.
2410 ** permfail: use "normal" method?
2411 ** tempfail: delay or use "normal" method?
2414 if (rr != NULL && rr->dns_r_h.ad == 1)
2416 *ptlsa_flags |= TLSAFLADIP;
2417 if ((TLSAFLTEMP & *ptlsa_flags) != 0)
2426 hp = dns2he(rr, family);
2432 /* other possible "tempfails"? */
2433 if (rr == NULL && h_errno == TRY_AGAIN)
2441 hp = sm_gethostbyname(host, family);
2442 if (hp == NULL && *p == '.')
2445 int oldopts = _res.options;
2447 _res.options &= ~(RES_DEFNAMES|RES_DNSRCH);
2450 hp = sm_gethostbyname(host, family);
2453 _res.options = oldopts;
2458 if (hp == NULL || hp->h_addr == NULL)
2461 /* check for name server timeouts */
2463 if (WorkAroundBrokenAAAA && family == AF_INET6 &&
2464 (h_errno == TRY_AGAIN || errno == ETIMEDOUT))
2467 ** An attempt with family AF_INET may
2468 ** succeed. By skipping the next section
2469 ** of code, we will try AF_INET before
2474 sm_dprintf("makeconnection: WorkAroundBrokenAAAA: Trying AF_INET lookup (AF_INET6 failed)\n");
2477 # endif /* NETINET6 */
2478 /* "else" in #if code above */
2480 if (errno == ETIMEDOUT ||
2481 # if _FFR_GETHBN_ExFILE
2488 # endif /* _FFR_GETHBN_ExFILE */
2489 h_errno == TRY_AGAIN ||
2490 (errno == ECONNREFUSED && UseNameServer))
2493 mci_setstat(mci, EX_TEMPFAIL,
2499 #endif /* NAMED_BIND */
2502 ** Try v6 first, then fall back to v4.
2503 ** If we found a v6 address, but no v4
2504 ** addresses, then TEMPFAIL.
2507 if (family == AF_INET6)
2514 #endif /* NETINET6 */
2516 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2520 addr.sa.sa_family = hp->h_addrtype;
2521 switch (hp->h_addrtype)
2525 memmove(&addr.sin.sin_addr,
2529 #endif /* NETINET */
2533 memmove(&addr.sin6.sin6_addr,
2537 #endif /* NETINET6 */
2540 if (hp->h_length > sizeof(addr.sa.sa_data))
2542 syserr("makeconnection: long sa_data: family %d len %d",
2543 hp->h_addrtype, hp->h_length);
2544 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2548 memmove(addr.sa.sa_data, hp->h_addr, hp->h_length);
2556 ** Hack for testing.
2558 ** 10.1.1.12: see meta1.tns XREF IP address
2559 ** 8754: see common.sh XREF SNKPORT2
2562 if (tTd(77, 101) && hp != NULL && hp->h_addrtype == AF_INET &&
2563 addr.sin.sin_addr.s_addr == inet_addr("10.1.1.12"))
2565 addr.sin.sin_addr.s_addr = inet_addr("127.0.0.1");
2567 sm_dprintf("hack host=%s addr=[%s].%d\n", host,
2568 anynet_ntoa(&addr), ntohs(port));
2573 ** Determine the port number.
2578 #ifdef NO_GETSERVBYNAME
2579 # if _FFR_SMTPS_CLIENT
2580 if (bitnset(M_SMTPS_CLIENT, mci->mci_mailer->m_flags))
2583 # endif /* _FFR_SMTPS_CLIENT */
2585 #else /* NO_GETSERVBYNAME */
2586 register struct servent *sp;
2588 # if _FFR_SMTPS_CLIENT
2589 if (bitnset(M_SMTPS_CLIENT, mci->mci_mailer->m_flags))
2592 # endif /* _FFR_SMTPS_CLIENT */
2594 sp = getservbyname(p, "tcp");
2599 sm_syslog(LOG_ERR, NOQID,
2600 "makeconnection: service \"%s\" unknown", p);
2601 # if _FFR_SMTPS_CLIENT
2602 if (bitnset(M_SMTPS_CLIENT, mci->mci_mailer->m_flags))
2605 # endif /* _FFR_SMTPS_CLIENT */
2610 #endif /* NO_GETSERVBYNAME */
2614 if (addr.sa.sa_family == AF_INET6 &&
2615 IN6_IS_ADDR_V4MAPPED(&addr.sin6.sin6_addr) &&
2616 ClientSettings[AF_INET].d_addr.sa.sa_family != 0)
2619 ** Ignore mapped IPv4 address since
2620 ** there is a ClientPortOptions setting
2626 #endif /* NETINET6 */
2628 switch (addr.sa.sa_family)
2632 addr.sin.sin_port = port;
2633 addrlen = sizeof(struct sockaddr_in);
2635 #endif /* NETINET */
2639 addr.sin6.sin6_port = port;
2640 addrlen = sizeof(struct sockaddr_in6);
2642 #endif /* NETINET6 */
2646 /* assume two byte transport selector */
2647 memmove(TSEL((struct sockaddr_iso *) &addr), (char *) &port, 2);
2648 addrlen = sizeof(struct sockaddr_iso);
2653 syserr("Can't connect to address family %d", addr.sa.sa_family);
2654 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2656 FREEHOSTENT(hp, hs);
2661 ** Try to actually open the connection.
2665 /* if too many connections, don't bother trying */
2666 if (!xla_noqueue_ok(host))
2668 FREEHOSTENT(hp, hs);
2674 # define OCC_CLOSE occ_close(e, mci, host, &addr)
2675 /* HACK!!!! just to see if this can work at all... */
2676 if (occ_exceeded(e, mci, host, &addr))
2678 FREEHOSTENT(hp, hs);
2679 sm_syslog(LOG_DEBUG, e->e_id,
2680 "stat=occ_exceeded, host=%s, addr=%s",
2681 host, anynet_ntoa(&addr));
2684 ** to get a more specific stat= message set errno
2685 ** or make up one in sm, see sm_errstring()
2688 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", "450 occ_exceeded"); /* check D.S.N */
2692 #else /* _FFR_OCC */
2694 #endif /* _FFR_OCC */
2699 sm_dprintf("makeconnection (%s [%s].%d (%d))\n",
2700 host, anynet_ntoa(&addr), ntohs(port),
2701 (int) addr.sa.sa_family);
2703 /* save for logging */
2707 if (bitnset(M_SECURE_PORT, mci->mci_mailer->m_flags))
2709 int rport = IPPORT_RESERVED - 1;
2711 s = rresvport(&rport);
2714 #endif /* HASRRESVPORT */
2715 /* "else" in #if code above */
2717 s = socket(addr.sa.sa_family, SOCK_STREAM, 0);
2722 syserr("makeconnection: cannot create socket");
2726 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2727 FREEHOSTENT(hp, hs);
2734 if (ClientSettings[family].d_tcpsndbufsize > 0)
2736 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
2737 (char *) &ClientSettings[family].d_tcpsndbufsize,
2738 sizeof(ClientSettings[family].d_tcpsndbufsize)) < 0)
2739 syserr("makeconnection: setsockopt(SO_SNDBUF)");
2741 #endif /* SO_SNDBUF */
2743 if (ClientSettings[family].d_tcprcvbufsize > 0)
2745 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
2746 (char *) &ClientSettings[family].d_tcprcvbufsize,
2747 sizeof(ClientSettings[family].d_tcprcvbufsize)) < 0)
2748 syserr("makeconnection: setsockopt(SO_RCVBUF)");
2750 #endif /* SO_RCVBUF */
2753 sm_dprintf("makeconnection: fd=%d\n", s);
2755 /* turn on network debugging? */
2760 (void) setsockopt(s, SOL_SOCKET, SO_DEBUG,
2761 (char *)&on, sizeof(on));
2763 if (e->e_xfp != NULL) /* for debugging */
2764 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
2765 errno = 0; /* for debugging */
2771 switch (clt_addr.sa.sa_family)
2775 if (clt_addr.sin.sin_port != 0)
2776 (void) setsockopt(s, SOL_SOCKET,
2781 #endif /* NETINET */
2785 if (clt_addr.sin6.sin6_port != 0)
2786 (void) setsockopt(s, SOL_SOCKET,
2791 #endif /* NETINET6 */
2794 if (bind(s, &clt_addr.sa, socksize) < 0)
2799 syserr("makeconnection: cannot bind socket [%s]",
2800 anynet_ntoa(&clt_addr));
2801 FREEHOSTENT(hp, hs);
2809 ** Linux seems to hang in connect for 90 minutes (!!!).
2810 ** Time out the connect to avoid this problem.
2813 if (setjmp(CtxConnectTimeout) == 0)
2820 if (e->e_ntries <= 0 && TimeOuts.to_iconnect != 0)
2821 ev = sm_setevent(TimeOuts.to_iconnect,
2823 else if (TimeOuts.to_connect != 0)
2824 ev = sm_setevent(TimeOuts.to_connect,
2832 /* && AF_INET == addr.sin.sin_family */
2833 && ntohl(addr.sin.sin_addr.s_addr) >=
2834 ntohl(inet_addr("255.255.255.1"))
2835 && ntohl(addr.sin.sin_addr.s_addr) <=
2836 ntohl(inet_addr("255.255.255.255"))
2840 c_errno = ntohl(addr.sin.sin_addr.s_addr) -
2841 ntohl(inet_addr("255.255.255.0"));
2842 sm_dprintf("hack: fail connection=%d, ip=%#x, lower=%#x\n",
2844 , ntohl(addr.sin.sin_addr.s_addr)
2845 , ntohl(inet_addr("255.255.255.0")));
2848 #endif /* _FFR_TESTS */
2849 /* "else" in #if code above */
2851 switch (ConnectOnlyTo.sa.sa_family)
2855 addr.sin.sin_addr.s_addr = ConnectOnlyTo.sin.sin_addr.s_addr;
2856 addr.sa.sa_family = ConnectOnlyTo.sa.sa_family;
2857 if (ConnectOnlyTo.sin.sin_port != 0)
2859 port = ConnectOnlyTo.sin.sin_port;
2860 addr.sin.sin_port = port;
2863 #endif /* NETINET */
2867 memmove(&addr.sin6.sin6_addr,
2868 &ConnectOnlyTo.sin6.sin6_addr,
2870 if (ConnectOnlyTo.sin6.sin6_port != 0)
2872 port = ConnectOnlyTo.sin6.sin6_port;
2873 addr.sin6.sin6_port = port;
2876 #endif /* NETINET6 */
2879 sm_dprintf("Connecting to [%s].%d...\n",
2880 anynet_ntoa(&addr), ntohs(port));
2887 /* "else" in #if code above */
2888 i = connect(s, (struct sockaddr *) &addr, addrlen);
2898 /* couldn't connect.... figure out why */
2901 /* if running demand-dialed connection, try again */
2902 if (DialDelay > 0 && firstconnect &&
2903 bitnset(M_DIALDELAY, mci->mci_mailer->m_flags))
2906 sm_dprintf("Connect failed (%s); trying again...\n",
2907 sm_errstring(save_errno));
2908 firstconnect = false;
2909 (void) sleep(DialDelay);
2914 sm_syslog(LOG_INFO, e->e_id,
2915 "makeconnection (%s [%s].%d (%d)) failed: %s",
2916 host, anynet_ntoa(&addr), ntohs(port),
2917 (int) addr.sa.sa_family,
2918 sm_errstring(save_errno));
2922 #endif /* NETINET6 */
2923 if (hp != NULL && hp->h_addr_list[addrno] != NULL &&
2924 (enough == 0 || curtime() < enough))
2927 sm_dprintf("Connect failed (%s); trying new address....\n",
2928 sm_errstring(save_errno));
2929 switch (addr.sa.sa_family)
2933 memmove(&addr.sin.sin_addr,
2934 hp->h_addr_list[addrno++],
2937 #endif /* NETINET */
2941 memmove(&addr.sin6.sin6_addr,
2942 hp->h_addr_list[addrno++],
2945 #endif /* NETINET6 */
2948 memmove(addr.sa.sa_data,
2949 hp->h_addr_list[addrno++],
2958 if (family == AF_INET6)
2961 sm_dprintf("Connect failed (%s); retrying with AF_INET....\n",
2962 sm_errstring(save_errno));
2965 FREEHOSTENT(hp, hs);
2969 #endif /* NETINET6 */
2970 /* couldn't open connection */
2972 /* Don't clobber an already saved errno from v4retry */
2977 sm_dprintf("Connect failed (%s)\n",
2978 sm_errstring(save_errno));
2982 mci_setstat(mci, EX_TEMPFAIL, "4.4.1", NULL);
2983 FREEHOSTENT(hp, hs);
2989 FREEHOSTENT(hp, hs);
2991 /* connection ok, put it into canonical form */
2992 mci->mci_out = NULL;
2993 if ((mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2995 SM_IO_WRONLY_B, NULL)) == NULL ||
2997 (mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2999 SM_IO_RDONLY_B, NULL)) == NULL)
3002 syserr("cannot open SMTP client channel, fd=%d", s);
3003 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
3004 SM_CLOSE_FP(mci->mci_out);
3010 sm_io_automode(mci->mci_out, mci->mci_in);
3012 /* set {client_flags} */
3013 if (ClientSettings[addr.sa.sa_family].d_mflags != NULL)
3015 char flags[64]; /* XXX */
3018 ** For now just concatenate the flags as there is no
3022 p = macvalue(macid("{client_flags}"), e);
3024 if (!SM_IS_EMPTY(p))
3026 (void) sm_strlcpy(flags, p, sizeof(flags));
3027 (void) sm_strlcat(flags, " ", sizeof(flags));
3029 (void) sm_strlcat(flags,
3030 ClientSettings[addr.sa.sa_family].d_mflags,
3032 macdefine(&mci->mci_macro, A_PERM, macid("{client_flags}"),
3036 /* "add" {client_flags} to bitmap */
3037 if (bitnset(D_IFNHELO, ClientSettings[addr.sa.sa_family].d_flags))
3039 /* look for just this one flag */
3040 setbitn(D_IFNHELO, d_flags);
3043 /* find out name for Interface through which we connect */
3045 if (getsockname(s, &addr.sa, &len) == 0)
3049 if (!isloopback(addr))
3053 macdefine(&BlankEnvelope.e_macro, A_TEMP,
3054 macid("{if_addr_out}"), anynet_ntoa(&addr));
3055 (void) sm_snprintf(familystr, sizeof(familystr), "%d",
3057 macdefine(&BlankEnvelope.e_macro, A_TEMP,
3058 macid("{if_family_out}"), familystr);
3062 macdefine(&BlankEnvelope.e_macro, A_PERM,
3063 macid("{if_addr_out}"), NULL);
3064 macdefine(&BlankEnvelope.e_macro, A_PERM,
3065 macid("{if_family_out}"), NULL);
3068 name = hostnamebyanyaddr(&addr);
3069 macdefine(&BlankEnvelope.e_macro, A_TEMP,
3070 macid("{if_name_out}"), name);
3073 /* log connection information */
3074 sm_syslog(LOG_INFO, e->e_id,
3075 "SMTP outgoing connect on %.40s", name);
3077 if (bitnset(D_IFNHELO, d_flags))
3079 if (name[0] != '[' && strchr(name, '.') != NULL)
3080 mci->mci_heloname = newstr(name);
3085 macdefine(&BlankEnvelope.e_macro, A_PERM,
3086 macid("{if_name_out}"), NULL);
3087 macdefine(&BlankEnvelope.e_macro, A_PERM,
3088 macid("{if_addr_out}"), NULL);
3089 macdefine(&BlankEnvelope.e_macro, A_PERM,
3090 macid("{if_family_out}"), NULL);
3093 /* Use the configured HeloName as appropriate */
3094 if (HeloName != NULL && HeloName[0] != '\0')
3096 SM_FREE(mci->mci_heloname);
3097 mci->mci_heloname = newstr(HeloName);
3100 mci_setstat(mci, EX_OK, NULL, NULL);
3105 connecttimeout(ignore)
3109 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3110 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3115 longjmp(CtxConnectTimeout, 1);
3118 ** MAKECONNECTION_DS -- make a connection to a domain socket.
3121 ** mux_path -- the path of the socket to connect to.
3122 ** mci -- a pointer to the mail connection information
3123 ** structure to be filled in.
3126 ** An exit code telling whether the connection could be
3127 ** made and if not why not.
3135 makeconnection_ds(mux_path, mci)
3140 int rval, save_errno;
3141 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_ROOTOK|SFF_EXECOK;
3142 struct sockaddr_un unix_addr;
3144 /* if not safe, don't connect */
3145 rval = safefile(mux_path, RunAsUid, RunAsGid, RunAsUserName,
3146 sff, S_IRUSR|S_IWUSR, NULL);
3150 syserr("makeconnection_ds: unsafe domain socket %s",
3152 mci_setstat(mci, EX_TEMPFAIL, "4.3.5", NULL);
3157 /* prepare address structure */
3158 memset(&unix_addr, '\0', sizeof(unix_addr));
3159 unix_addr.sun_family = AF_UNIX;
3161 if (strlen(mux_path) >= sizeof(unix_addr.sun_path))
3163 syserr("makeconnection_ds: domain socket name %s too long",
3166 /* XXX why TEMPFAIL but 5.x.y ? */
3167 mci_setstat(mci, EX_TEMPFAIL, "5.3.5", NULL);
3168 errno = ENAMETOOLONG;
3169 return EX_UNAVAILABLE;
3171 (void) sm_strlcpy(unix_addr.sun_path, mux_path,
3172 sizeof(unix_addr.sun_path));
3174 /* initialize domain socket */
3175 sock = socket(AF_UNIX, SOCK_STREAM, 0);
3179 syserr("makeconnection_ds: could not create domain socket %s",
3181 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
3186 /* connect to server */
3187 if (connect(sock, (struct sockaddr *) &unix_addr,
3188 sizeof(unix_addr)) == -1)
3191 syserr("Could not connect to socket %s", mux_path);
3192 mci_setstat(mci, EX_TEMPFAIL, "4.4.1", NULL);
3198 /* connection ok, put it into canonical form */
3199 mci->mci_out = NULL;
3200 if ((mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
3201 (void *) &sock, SM_IO_WRONLY_B, NULL))
3203 || (sock = dup(sock)) < 0 ||
3204 (mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
3205 (void *) &sock, SM_IO_RDONLY_B, NULL))
3209 syserr("cannot open SMTP client channel, fd=%d", sock);
3210 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
3211 SM_CLOSE_FP(mci->mci_out);
3216 sm_io_automode(mci->mci_out, mci->mci_in);
3218 mci_setstat(mci, EX_OK, NULL, NULL);
3222 #endif /* NETUNIX */
3224 ** SHUTDOWN_DAEMON -- Performs a clean shutdown of the daemon
3233 ** closes control socket, exits.
3242 sm_allsignals(true);
3244 reason = ShutdownRequest;
3245 ShutdownRequest = NULL;
3249 sm_syslog(LOG_INFO, CurEnv->e_id, "stopping daemon, reason=%s",
3250 reason == NULL ? "implicit call" : reason);
3253 closecontrolsocket(true);
3258 for (i = 0; i < NDaemons; i++)
3260 if (Daemons[i].d_socket >= 0)
3262 (void) close(Daemons[i].d_socket);
3263 Daemons[i].d_socket = -1;
3266 /* Remove named sockets */
3267 if (Daemons[i].d_addr.sa.sa_family == AF_UNIX)
3270 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_MUSTOWN|SFF_EXECOK|SFF_CREAT;
3272 /* if not safe, don't use it */
3273 rval = safefile(Daemons[i].d_addr.sunix.sun_path,
3276 S_IRUSR|S_IWUSR, NULL);
3278 unlink(Daemons[i].d_addr.sunix.sun_path) < 0)
3280 sm_syslog(LOG_WARNING, NOQID,
3281 "Could not remove daemon %s socket: %s: %s",
3283 Daemons[i].d_addr.sunix.sun_path,
3284 sm_errstring(errno));
3287 #endif /* NETUNIX */
3291 finis(false, true, EX_OK);
3294 ** RESTART_DAEMON -- Performs a clean restart of the daemon
3303 ** restarts the daemon or exits if restart fails.
3306 /* Make a non-DFL/IGN signal a noop */
3307 #define SM_NOOP_SIGNAL(sig, old) \
3310 (old) = sm_signal((sig), sm_signal_noop); \
3311 if ((old) == SIG_IGN || (old) == SIG_DFL) \
3312 (void) sm_signal((sig), (old)); \
3321 sigfunc_t ignore, oalrm, ousr1;
3322 extern int DtableSize;
3324 /* clear the events to turn off SIGALRMs */
3326 sm_allsignals(true);
3328 reason = RestartRequest;
3329 RestartRequest = NULL;
3332 if (SaveArgv[0][0] != '/')
3335 sm_syslog(LOG_INFO, NOQID,
3336 "could not restart: need full path");
3337 finis(false, true, EX_OSFILE);
3341 sm_syslog(LOG_INFO, NOQID, "restarting %s due to %s",
3343 reason == NULL ? "implicit call" : reason);
3345 closecontrolsocket(true);
3347 cleanup_shm(DaemonPid == getpid());
3350 /* close locked pid file */
3351 close_sendmail_pid();
3354 ** Want to drop to the user who started the process in all cases
3355 ** *but* when running as "smmsp" for the clientmqueue queue run
3356 ** daemon. In that case, UseMSP will be true, RunAsUid should not
3357 ** be root, and RealUid should be either 0 or RunAsUid.
3360 drop = !(UseMSP && RunAsUid != 0 &&
3361 (RealUid == 0 || RealUid == RunAsUid));
3363 if (drop_privileges(drop) != EX_OK)
3366 sm_syslog(LOG_ALERT, NOQID,
3367 "could not drop privileges: %s",
3368 sm_errstring(errno));
3369 finis(false, true, EX_OSERR);
3373 sm_close_on_exec(STDERR_FILENO + 1, DtableSize);
3376 ** Need to allow signals before execve() to make them "harmless".
3377 ** However, the default action can be "terminate", so it isn't
3378 ** really harmless. Setting signals to IGN will cause them to be
3379 ** ignored in the new process to, so that isn't a good alternative.
3382 SM_NOOP_SIGNAL(SIGALRM, oalrm);
3383 SM_NOOP_SIGNAL(SIGCHLD, ignore);
3384 SM_NOOP_SIGNAL(SIGHUP, ignore);
3385 SM_NOOP_SIGNAL(SIGINT, ignore);
3386 SM_NOOP_SIGNAL(SIGPIPE, ignore);
3387 SM_NOOP_SIGNAL(SIGTERM, ignore);
3389 SM_NOOP_SIGNAL(SIGUSR1, ousr1);
3392 /* Turn back on signals */
3393 sm_allsignals(false);
3395 (void) execve(SaveArgv[0], (ARGV_T) SaveArgv, (ARGV_T) ExternalEnviron);
3398 /* block signals again and restore needed signals */
3399 sm_allsignals(true);
3401 /* For finis() events */
3402 (void) sm_signal(SIGALRM, oalrm);
3405 /* For debugging finis() */
3406 (void) sm_signal(SIGUSR1, ousr1);
3411 sm_syslog(LOG_ALERT, NOQID, "could not exec %s: %s",
3412 SaveArgv[0], sm_errstring(errno));
3413 finis(false, true, EX_OSFILE);
3417 ** MYHOSTNAME -- return the name of this host.
3420 ** hostbuf -- a place to return the name of this host.
3421 ** size -- the size of hostbuf.
3424 ** A list of aliases for this host.
3427 ** Adds numeric codes to $=w.
3431 myhostname(hostbuf, size)
3435 register struct hostent *hp;
3437 if (gethostname(hostbuf, size) < 0 || hostbuf[0] == '\0')
3438 (void) sm_strlcpy(hostbuf, "localhost", size);
3439 hp = sm_gethostbyname(hostbuf, InetMode);
3440 #if NETINET && NETINET6
3441 if (hp == NULL && InetMode == AF_INET6)
3444 ** It's possible that this IPv6 enabled machine doesn't
3445 ** actually have any IPv6 interfaces and, therefore, no
3446 ** IPv6 addresses. Fall back to AF_INET.
3449 hp = sm_gethostbyname(hostbuf, AF_INET);
3451 #endif /* NETINET && NETINET6 */
3454 if (strchr(hp->h_name, '.') != NULL || strchr(hostbuf, '.') == NULL)
3455 (void) cleanstrcpy(hostbuf, hp->h_name, size);
3458 if (strchr(hostbuf, '.') == NULL)
3462 domainname = ni_propval("/locations", NULL, "resolver",
3464 if (domainname != NULL &&
3465 strlen(domainname) + strlen(hostbuf) + 1 < size)
3466 (void) sm_strlcat2(hostbuf, ".", domainname, size);
3468 #endif /* NETINFO */
3471 ** If there is still no dot in the name, try looking for a
3475 if (strchr(hostbuf, '.') == NULL)
3479 for (ha = hp->h_aliases; ha != NULL && *ha != NULL; ha++)
3481 if (strchr(*ha, '.') != NULL)
3483 (void) cleanstrcpy(hostbuf, *ha, size - 1);
3484 hostbuf[size - 1] = '\0';
3491 ** If _still_ no dot, wait for a while and try again -- it is
3492 ** possible that some service is starting up. This can result
3493 ** in excessive delays if the system is badly configured, but
3494 ** there really isn't a way around that, particularly given that
3495 ** the config file hasn't been read at this point.
3496 ** All in all, a bit of a mess.
3499 if (strchr(hostbuf, '.') == NULL &&
3500 getcanonname(hostbuf, size, true, NULL) == HOST_NOTFOUND)
3502 sm_syslog(LocalDaemon ? LOG_WARNING : LOG_CRIT, NOQID,
3503 "My unqualified host name (%s) unknown; sleeping for retry",
3505 message("My unqualified host name (%s) unknown; sleeping for retry",
3508 if (getcanonname(hostbuf, size, true, NULL) == HOST_NOTFOUND)
3510 sm_syslog(LocalDaemon ? LOG_WARNING : LOG_ALERT, NOQID,
3511 "unable to qualify my own domain name (%s) -- using short name",
3513 message("WARNING: unable to qualify my own domain name (%s) -- using short name",
3520 ** ADDRCMP -- compare two host addresses
3523 ** hp -- hostent structure for the first address
3524 ** ha -- actual first address
3525 ** sa -- second address
3528 ** 0 -- if ha and sa match
3529 ** else -- they don't match
3542 switch (sa->sa.sa_family)
3546 if (hp->h_addrtype == AF_INET)
3547 return memcmp(ha, (char *) &sa->sin.sin_addr, INADDRSZ);
3553 a = (unsigned char *) &sa->sin6.sin6_addr;
3555 /* Straight binary comparison */
3556 if (hp->h_addrtype == AF_INET6)
3557 return memcmp(ha, a, IN6ADDRSZ);
3559 /* If IPv4-mapped IPv6 address, compare the IPv4 section */
3560 if (hp->h_addrtype == AF_INET &&
3561 IN6_IS_ADDR_V4MAPPED(&sa->sin6.sin6_addr))
3562 return memcmp(a + IN6ADDRSZ - INADDRSZ, ha, INADDRSZ);
3564 #endif /* NETINET6 */
3569 ** GETAUTHINFO -- get the real host name associated with a file descriptor
3571 ** Uses RFC1413 protocol to try to get info from the other end.
3574 ** fd -- the descriptor
3575 ** may_be_forged -- an outage that is set to true if the
3576 ** forward lookup of RealHostName does not match
3577 ** RealHostAddr; set to false if they do match.
3580 ** The user@host information associated with this descriptor.
3583 static jmp_buf CtxAuthTimeout;
3590 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3591 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3596 longjmp(CtxAuthTimeout, 1);
3600 getauthinfo(fd, may_be_forged)
3602 bool *may_be_forged;
3604 unsigned short SM_NONVOLATILE port = 0;
3605 SOCKADDR_LEN_T falen;
3606 register char *volatile p = NULL;
3608 SOCKADDR_LEN_T lalen;
3609 #ifndef NO_GETSERVBYNAME
3610 register struct servent *sp;
3612 static unsigned short port4 = 0;
3615 static unsigned short port6 = 0;
3617 #endif /* ! NO_GETSERVBYNAME */
3624 char *ostype = NULL;
3626 char ibuf[MAXNAME + 1]; /* EAI:ok? it's a hostname from OS */
3627 static char hbuf[MAXNAME + MAXAUTHINFO + 11]; /* EAI:ok? (as above)*/
3629 *may_be_forged = true;
3630 falen = sizeof(RealHostAddr);
3631 if (isatty(fd) || (i = getpeername(fd, &RealHostAddr.sa, &falen)) < 0 ||
3632 falen <= 0 || RealHostAddr.sa.sa_family == 0)
3637 ** ENOTSOCK is OK: bail on anything else, but reset
3638 ** errno in this case, so a mis-report doesn't
3642 if (errno != ENOTSOCK)
3647 *may_be_forged = false;
3648 (void) sm_strlcpyn(hbuf, sizeof(hbuf), 2, RealUserName,
3651 sm_dprintf("getauthinfo: %s\n", hbuf);
3655 if (RealHostName == NULL)
3657 /* translate that to a host name */
3658 RealHostName = newstr(hostnamebyanyaddr(&RealHostAddr));
3659 if (strlen(RealHostName) > MAXNAME)
3660 RealHostName[MAXNAME] = '\0'; /* XXX - 1 ? */
3663 /* cross check RealHostName with forward DNS lookup */
3664 if (anynet_ntoa(&RealHostAddr)[0] == '[' ||
3665 RealHostName[0] == '[')
3666 *may_be_forged = false;
3671 family = RealHostAddr.sa.sa_family;
3672 #if NETINET6 && NEEDSGETIPNODE
3674 ** If RealHostAddr is an IPv6 connection with an
3675 ** IPv4-mapped address, we need RealHostName's IPv4
3676 ** address(es) for addrcmp() to compare against
3679 ** Actually, we only need to do this for systems
3680 ** which NEEDSGETIPNODE since the real getipnodebyname()
3681 ** already does V4MAPPED address via the AI_V4MAPPEDCFG
3682 ** flag. A better fix to this problem is to add this
3683 ** functionality to our stub getipnodebyname().
3686 if (family == AF_INET6 &&
3687 IN6_IS_ADDR_V4MAPPED(&RealHostAddr.sin6.sin6_addr))
3689 #endif /* NETINET6 && NEEDSGETIPNODE */
3691 /* try to match the reverse against the forward lookup */
3692 hp = sm_gethostbyname(RealHostName, family);
3695 for (ha = hp->h_addr_list; *ha != NULL; ha++)
3697 if (addrcmp(hp, *ha, &RealHostAddr) == 0)
3699 *may_be_forged = false;
3703 FREEHOSTENT(hp, NULL);
3707 if (TimeOuts.to_ident == 0)
3711 switch (RealHostAddr.sa.sa_family)
3715 if (getsockname(fd, &la.sa, &lalen) < 0 ||
3717 la.sa.sa_family != AF_INET)
3722 port = RealHostAddr.sin.sin_port;
3724 /* create ident query */
3725 (void) sm_snprintf(ibuf, sizeof(ibuf), "%d,%d\r\n",
3726 ntohs(RealHostAddr.sin.sin_port),
3727 ntohs(la.sin.sin_port));
3729 /* create local address */
3730 la.sin.sin_port = 0;
3732 /* create foreign address */
3733 # ifdef NO_GETSERVBYNAME
3734 RealHostAddr.sin.sin_port = htons(113);
3735 # else /* NO_GETSERVBYNAME */
3738 ** getservbyname() consumes about 5% of the time
3739 ** when receiving a small message (almost all of the time
3740 ** spent in this routine).
3741 ** Hence we store the port in a static variable
3742 ** to save this time.
3743 ** The portnumber shouldn't change very often...
3744 ** This code makes the assumption that the port number
3750 sp = getservbyname("auth", "tcp");
3756 RealHostAddr.sin.sin_port = port4;
3758 # endif /* NO_GETSERVBYNAME */
3759 #endif /* NETINET */
3763 if (getsockname(fd, &la.sa, &lalen) < 0 ||
3765 la.sa.sa_family != AF_INET6)
3770 port = RealHostAddr.sin6.sin6_port;
3772 /* create ident query */
3773 (void) sm_snprintf(ibuf, sizeof(ibuf), "%d,%d\r\n",
3774 ntohs(RealHostAddr.sin6.sin6_port),
3775 ntohs(la.sin6.sin6_port));
3777 /* create local address */
3778 la.sin6.sin6_port = 0;
3780 /* create foreign address */
3781 # ifdef NO_GETSERVBYNAME
3782 RealHostAddr.sin6.sin6_port = htons(113);
3783 # else /* NO_GETSERVBYNAME */
3786 sp = getservbyname("auth", "tcp");
3792 RealHostAddr.sin6.sin6_port = port6;
3794 # endif /* NO_GETSERVBYNAME */
3795 #endif /* NETINET6 */
3802 if (setjmp(CtxAuthTimeout) != 0)
3809 /* put a timeout around the whole thing */
3810 ev = sm_setevent(TimeOuts.to_ident, authtimeout, 0);
3812 /* connect to foreign IDENT server using same address as SMTP socket */
3813 s = socket(la.sa.sa_family, SOCK_STREAM, 0);
3819 if (bind(s, &la.sa, lalen) < 0 ||
3820 connect(s, &RealHostAddr.sa, lalen) < 0)
3824 sm_dprintf("getauthinfo: sent %s", ibuf);
3827 if (write(s, ibuf, strlen(ibuf)) < 0)
3832 nleft = sizeof(ibuf) - 1;
3833 while ((i = read(s, p, nleft)) > 0)
3840 if ((s = strchr(ibuf, '\n')) != NULL)
3854 if (i < 0 || p == &ibuf[0])
3857 if (p >= &ibuf[2] && *--p == '\n' && *--p == '\r')
3862 sm_dprintf("getauthinfo: got %s\n", ibuf);
3865 p = strchr(ibuf, ':');
3868 /* malformed response */
3871 while (isascii(*++p) && isspace(*p))
3873 if (sm_strncasecmp(p, "userid", 6) != 0)
3875 /* presumably an error string */
3879 while (SM_ISSPACE(*p))
3883 /* either useridxx or malformed response */
3887 /* p now points to the OSTYPE field */
3888 while (SM_ISSPACE(*p))
3894 /* malformed response */
3902 charset = strchr(ostype, ',');
3903 if (charset != NULL)
3907 /* 1413 says don't do this -- but it's broken otherwise */
3908 while (isascii(*++p) && isspace(*p))
3911 /* p now points to the authenticated name -- copy carefully */
3912 if (sm_strncasecmp(ostype, "other", 5) == 0 &&
3913 (ostype[5] == ' ' || ostype[5] == '\0'))
3915 (void) sm_strlcpy(hbuf, "IDENT:", sizeof(hbuf));
3916 cleanstrcpy(&hbuf[6], p, MAXAUTHINFO);
3919 cleanstrcpy(hbuf, p, MAXAUTHINFO);
3921 (void) sm_strlcpyn(&hbuf[len], sizeof(hbuf) - len, 2, "@",
3922 RealHostName == NULL ? "localhost" : RealHostName);
3930 /* put back the original incoming port */
3931 switch (RealHostAddr.sa.sa_family)
3936 RealHostAddr.sin.sin_port = port;
3938 #endif /* NETINET */
3943 RealHostAddr.sin6.sin6_port = port;
3945 #endif /* NETINET6 */
3948 if (RealHostName == NULL)
3951 sm_dprintf("getauthinfo: NULL\n");
3954 (void) sm_strlcpy(hbuf, RealHostName, sizeof(hbuf));
3958 # ifndef GET_IPOPT_DST
3959 # define GET_IPOPT_DST(dst) (dst)
3962 ** Extract IP source routing information.
3964 ** Format of output for a connection from site a through b
3966 ** loose: @site-c@site-b:site-a
3967 ** strict: !@site-c@site-b:site-a
3969 ** o - pointer within ipopt_list structure.
3970 ** q - pointer within ls/ss rr route data
3971 ** p - pointer to hbuf
3974 if (RealHostAddr.sa.sa_family == AF_INET)
3976 SOCKOPT_LEN_T ipoptlen;
3981 struct IPOPTION ipopt;
3983 ipoptlen = sizeof(ipopt);
3984 if (getsockopt(fd, IPPROTO_IP, IP_OPTIONS,
3985 (char *) &ipopt, &ipoptlen) < 0)
3989 o = (unsigned char *) ipopt.IP_LIST;
3990 while (o != NULL && o < (unsigned char *) &ipopt + ipoptlen)
4006 ** o[0] is the option type (loose/strict).
4007 ** o[1] is the length of this option,
4008 ** including option type and
4010 ** o[2] is the pointer into the route
4012 ** o[3] begins the route data.
4015 p = &hbuf[strlen(hbuf)];
4016 l = sizeof(hbuf) - (hbuf - p) - 6;
4017 (void) sm_snprintf(p, SPACELEFT(hbuf, p),
4019 *o == IPOPT_SSRR ? "!" : "",
4020 l > 240 ? 120 : l / 2,
4021 inet_ntoa(GET_IPOPT_DST(ipopt.IP_DST)));
4026 j = o[1] / sizeof(struct in_addr) - 1;
4028 /* q skips length and router pointer to data */
4030 for ( ; j >= 0; j--)
4032 struct in_addr addr;
4034 memcpy(&addr, q, sizeof(addr));
4035 (void) sm_snprintf(p,
4045 q += sizeof(struct in_addr);
4051 /* Skip over option */
4056 (void) sm_snprintf(p, SPACELEFT(hbuf, p), "]");
4061 #endif /* IP_SRCROUTE */
4062 if (RealHostName != NULL && RealHostName[0] != '[')
4064 p = &hbuf[strlen(hbuf)];
4065 (void) sm_snprintf(p, SPACELEFT(hbuf, p), " [%.100s]",
4066 anynet_ntoa(&RealHostAddr));
4070 p = &hbuf[strlen(hbuf)];
4071 (void) sm_strlcpy(p, " (may be forged)", SPACELEFT(hbuf, p));
4072 macdefine(&BlankEnvelope.e_macro, A_PERM,
4073 macid("{client_resolve}"), "FORGED");
4078 #endif /* IP_SRCROUTE */
4080 /* put back the original incoming port */
4081 switch (RealHostAddr.sa.sa_family)
4086 RealHostAddr.sin.sin_port = port;
4088 #endif /* NETINET */
4093 RealHostAddr.sin6.sin6_port = port;
4095 #endif /* NETINET6 */
4099 sm_dprintf("getauthinfo: %s\n", hbuf);
4103 ** HOST_MAP_LOOKUP -- turn a hostname into canonical form
4106 ** map -- a pointer to this map.
4107 ** name -- the (presumably unqualified) hostname.
4108 ** av -- unused -- for compatibility with other mapping
4110 ** statp -- an exit status (out parameter) -- set to
4111 ** EX_TEMPFAIL if the name server is unavailable.
4114 ** The mapping, if found.
4115 ** NULL if no mapping found.
4118 ** Looks up the host specified in hbuf. If it is not
4119 ** the canonical name for that host, return the canonical
4120 ** name (unless MF_MATCHONLY is set, which will cause the
4121 ** status only to be returned).
4125 host_map_lookup(map, name, av, statp)
4131 register struct hostent *hp;
4133 struct in_addr in_addr;
4136 struct in6_addr in6_addr;
4138 char *cp, *ans = NULL;
4142 time_t SM_NONVOLATILE retrans = 0;
4143 int SM_NONVOLATILE retry = 0;
4145 char hbuf[MAXNAME + 1]; /* is (host)name in 'x' format? */
4148 ** See if we have already looked up this name. If so, just
4149 ** return it (unless expired).
4153 s = stab(name, ST_NAMECANON, ST_ENTER);
4154 if (bitset(NCF_VALID, s->s_namecanon.nc_flags) &&
4155 s->s_namecanon.nc_exp >= now)
4158 sm_dprintf("host_map_lookup(%s) => CACHE %s\n",
4160 s->s_namecanon.nc_cname == NULL
4162 : s->s_namecanon.nc_cname);
4163 errno = s->s_namecanon.nc_errno;
4164 SM_SET_H_ERRNO(s->s_namecanon.nc_herrno);
4165 *statp = s->s_namecanon.nc_stat;
4166 if (*statp == EX_TEMPFAIL)
4168 CurEnv->e_status = "4.4.3";
4169 message("851 %s: Name server timeout",
4170 shortenstring(name, 33));
4172 if (*statp != EX_OK)
4174 if (s->s_namecanon.nc_cname == NULL)
4176 syserr("host_map_lookup(%s): bogus NULL cache entry, errno=%d, h_errno=%d",
4178 s->s_namecanon.nc_errno,
4179 s->s_namecanon.nc_herrno);
4182 if (bitset(NCF_SECURE, s->s_namecanon.nc_flags))
4183 map->map_mflags |= MF_SECURE;
4185 map->map_mflags &= ~MF_SECURE;
4186 if (bitset(MF_MATCHONLY, map->map_mflags))
4187 cp = map_rewrite(map, name, strlen(name), NULL);
4189 cp = map_rewrite(map,
4190 s->s_namecanon.nc_cname,
4191 strlen(s->s_namecanon.nc_cname),
4197 ** If we are running without a regular network connection (usually
4198 ** dial-on-demand) and we are just queueing, we want to avoid DNS
4199 ** lookups because those could try to connect to a server.
4202 if (CurEnv->e_sendmode == SM_DEFER &&
4203 bitset(MF_DEFER, map->map_mflags))
4206 sm_dprintf("host_map_lookup(%s) => DEFERRED\n", name);
4207 *statp = EX_TEMPFAIL;
4212 ** If first character is a bracket, then it is an address
4213 ** lookup. Address is copied into a temporary buffer to
4214 ** strip the brackets and to preserve name if address is
4219 sm_dprintf("host_map_lookup(%s) => ", name);
4221 if (map->map_timeout > 0)
4223 retrans = _res.retrans;
4224 _res.retrans = map->map_timeout;
4226 if (map->map_retry > 0)
4229 _res.retry = map->map_retry;
4231 #endif /* NAMED_BIND */
4233 /* set default TTL */
4234 s->s_namecanon.nc_exp = now + SM_DEFAULT_TTL;
4241 utf8 = !str_is_print(name);
4244 (void) sm_strlcpy(hbuf, hn2alabel(name), sizeof(hbuf));
4246 /* if this is not a FQHN then do not restore it */
4247 utf8 = strchr(hbuf, '.') != NULL;
4250 #endif /* USE_EAI */
4251 /* "else" in #if code above */
4253 (void) sm_strlcpy(hbuf, name, sizeof(hbuf));
4256 r = getcanonname(hbuf, sizeof(hbuf) - 1, !HasWildcardMX, &ttl);
4257 if (r != HOST_NOTFOUND)
4261 ** Restore original. XXX Check if modified?
4262 ** If so, convert it via hn2ulabel()
4263 ** (not available yet)?
4267 (void) sm_strlcpy(hbuf, name, sizeof(hbuf));
4271 s->s_namecanon.nc_exp = now + SM_MIN(ttl,
4274 if (HOST_SECURE == r)
4276 s->s_namecanon.nc_flags |= NCF_SECURE;
4277 map->map_mflags |= MF_SECURE;
4281 s->s_namecanon.nc_flags &= ~NCF_SECURE;
4282 map->map_mflags &= ~MF_SECURE;
4288 if ((cp = strchr(name, ']')) == NULL)
4291 sm_dprintf("FAILED\n");
4298 /* should this be considered secure? */
4299 map->map_mflags &= ~MF_SECURE;
4301 if ((in_addr.s_addr = inet_addr(&name[1])) != INADDR_NONE)
4302 hp = sm_gethostbyaddr((char *)&in_addr,
4304 #endif /* NETINET */
4307 anynet_pton(AF_INET6, &name[1], &in6_addr) == 1)
4308 hp = sm_gethostbyaddr((char *)&in6_addr,
4309 IN6ADDRSZ, AF_INET6);
4310 #endif /* NETINET6 */
4315 /* found a match -- copy out */
4316 ans = denlstring((char *) hp->h_name, true, true);
4318 if (ans == hp->h_name)
4320 static char n[MAXNAME + 1]; /* EAI:ok */
4322 /* hp->h_name is about to disappear */
4323 (void) sm_strlcpy(n, ans, sizeof(n));
4326 FREEHOSTENT(hp, NULL);
4327 #endif /* NETINET6 */
4331 if (map->map_timeout > 0)
4332 _res.retrans = retrans;
4333 if (map->map_retry > 0)
4335 #endif /* NAMED_BIND */
4337 s->s_namecanon.nc_flags |= NCF_VALID; /* will be soon */
4339 /* Found an answer */
4342 s->s_namecanon.nc_stat = *statp = EX_OK;
4343 if (s->s_namecanon.nc_cname != NULL)
4344 sm_free(s->s_namecanon.nc_cname);
4345 s->s_namecanon.nc_cname = sm_strdup_x(ans);
4346 if (bitset(MF_MATCHONLY, map->map_mflags))
4347 cp = map_rewrite(map, name, strlen(name), NULL);
4349 cp = map_rewrite(map, ans, strlen(ans), av);
4351 sm_dprintf("FOUND %s\n", ans);
4355 /* No match found */
4356 s->s_namecanon.nc_errno = errno;
4358 s->s_namecanon.nc_herrno = h_errno;
4360 sm_dprintf("FAIL (%d)\n", h_errno);
4366 CurEnv->e_status = "4.4.3";
4367 message("851 %s: Name server timeout",
4368 shortenstring(name, 33));
4370 *statp = EX_TEMPFAIL;
4373 case HOST_NOT_FOUND:
4379 *statp = EX_SOFTWARE;
4383 *statp = EX_UNAVAILABLE;
4386 #else /* NAMED_BIND */
4388 sm_dprintf("FAIL\n");
4390 #endif /* NAMED_BIND */
4391 s->s_namecanon.nc_stat = *statp;
4395 ** HOST_MAP_INIT -- initialize host class structures
4398 ** map -- a pointer to this map.
4399 ** args -- argument string.
4406 host_map_init(map, args)
4410 register char *p = args;
4414 while (SM_ISSPACE(*p))
4425 map->map_tapp = ++p;
4429 map->map_mflags |= MF_MATCHONLY;
4433 map->map_mflags |= MF_NODEFER;
4436 case 'S': /* only for consistency */
4437 map->map_spacesub = *++p;
4441 map->map_mflags |= MF_DEFER;
4448 while (isascii(*++p) && isspace(*p))
4453 map->map_timeout = convtime(p, 's');
4460 while (isascii(*++p) && isspace(*p))
4462 map->map_retry = atoi(p);
4465 while (*p != '\0' && !(SM_ISSPACE(*p)))
4470 if (map->map_app != NULL)
4471 map->map_app = newstr(map->map_app);
4472 if (map->map_tapp != NULL)
4473 map->map_tapp = newstr(map->map_tapp);
4479 ** ANYNET_NTOP -- convert an IPv6 network address to printable form.
4482 ** s6a -- a pointer to an in6_addr structure.
4483 ** dst -- buffer to store result in
4484 ** dst_len -- size of dst buffer
4487 ** A printable version of that structure.
4491 anynet_ntop(s6a, dst, dst_len)
4492 struct in6_addr *s6a;
4498 if (IN6_IS_ADDR_V4MAPPED(s6a))
4499 ap = (char *) inet_ntop(AF_INET,
4500 &s6a->s6_addr[IN6ADDRSZ - INADDRSZ],
4507 /* Save pointer to beginning of string */
4510 /* Add IPv6: protocol tag */
4511 sz = sm_strlcpy(dst, "IPv6:", dst_len);
4516 if (UseCompressedIPv6Addresses)
4517 ap = (char *) inet_ntop(AF_INET6, s6a, dst, dst_len);
4519 ap = sm_inet6_ntop(s6a, dst, dst_len);
4520 /* Restore pointer to beginning of string */
4528 ** ANYNET_PTON -- convert printed form to network address.
4530 ** Wrapper for inet_pton() which handles IPv6: labels.
4533 ** family -- address family
4535 ** dst -- destination address structure
4538 ** 1 if the address was valid
4539 ** 0 if the address wasn't parsable
4544 anynet_pton(family, src, dst)
4549 if (family == AF_INET6 && sm_strncasecmp(src, "IPv6:", 5) == 0)
4551 return inet_pton(family, src, dst);
4553 #endif /* NETINET6 */
4555 ** ANYNET_NTOA -- convert a network address to printable form.
4558 ** sap -- a pointer to a sockaddr structure.
4561 ** A printable version of that sockaddr.
4564 #ifdef USE_SOCK_STREAM
4567 # include <net/if_dl.h>
4572 register SOCKADDR *sap;
4577 static char buf[100];
4579 /* check for null/zero family */
4582 if (sap->sa.sa_family == 0)
4585 switch (sap->sa.sa_family)
4589 if (sap->sunix.sun_path[0] != '\0')
4590 (void) sm_snprintf(buf, sizeof(buf), "[UNIX: %.64s]",
4591 sap->sunix.sun_path);
4593 (void) sm_strlcpy(buf, "[UNIX: localhost]", sizeof(buf));
4595 # endif /* NETUNIX */
4599 return (char *) inet_ntoa(sap->sin.sin_addr);
4604 ap = anynet_ntop(&sap->sin6.sin6_addr, buf, sizeof(buf));
4608 # endif /* NETINET6 */
4612 (void) sm_snprintf(buf, sizeof(buf), "[LINK: %s]",
4613 link_ntoa((struct sockaddr_dl *) &sap->sa));
4615 # endif /* NETLINK */
4617 /* this case is needed when nothing is #defined */
4618 /* in order to keep the switch syntactically correct */
4622 /* unknown family -- just dump bytes */
4623 (void) sm_snprintf(buf, sizeof(buf), "Family %d: ", sap->sa.sa_family);
4624 bp = &buf[strlen(buf)];
4625 ap = sap->sa.sa_data;
4626 for (l = sizeof(sap->sa.sa_data); --l >= 0 && SPACELEFT(buf, bp) > 3; )
4628 (void) sm_snprintf(bp, SPACELEFT(buf, bp), "%02x:",
4632 SM_ASSERT(bp > buf);
4633 SM_ASSERT(bp <= buf + sizeof(buf));
4638 ** HOSTNAMEBYANYADDR -- return name of host based on address
4641 ** sap -- SOCKADDR pointer
4644 ** text representation of host name.
4651 hostnamebyanyaddr(sap)
4652 register SOCKADDR *sap;
4654 register struct hostent *hp;
4659 struct in6_addr in6_addr;
4660 # endif /* NETINET6 */
4663 /* shorten name server timeout to avoid higher level timeouts */
4664 saveretry = _res.retry;
4665 if (_res.retry * _res.retrans > 20)
4666 _res.retry = 20 / _res.retrans;
4667 if (_res.retry == 0)
4669 # endif /* NAMED_BIND */
4671 switch (sap->sa.sa_family)
4675 hp = sm_gethostbyaddr((char *) &sap->sin.sin_addr,
4678 # endif /* NETINET */
4682 hp = sm_gethostbyaddr((char *) &sap->sin6.sin6_addr,
4683 IN6ADDRSZ, AF_INET6);
4685 # endif /* NETINET6 */
4689 hp = sm_gethostbyaddr((char *) &sap->siso.siso_addr,
4690 sizeof(sap->siso.siso_addr), AF_ISO);
4692 # endif /* NETISO */
4698 # endif /* NETUNIX */
4701 hp = sm_gethostbyaddr(sap->sa.sa_data, sizeof(sap->sa.sa_data),
4707 _res.retry = saveretry;
4710 # if NETINET || NETINET6
4711 if (hp != NULL && hp->h_name[0] != '['
4713 && inet_pton(AF_INET6, hp->h_name, &in6_addr) != 1
4714 # endif /* NETINET6 */
4716 && inet_addr(hp->h_name) == INADDR_NONE
4722 name = denlstring((char *) hp->h_name, true, true);
4724 if (name == hp->h_name)
4726 static char n[MAXNAME + 1]; /* EAI:ok */
4728 /* Copy the string, hp->h_name is about to disappear */
4729 (void) sm_strlcpy(n, name, sizeof(n));
4732 FREEHOSTENT(hp, NULL);
4733 # endif /* NETINET6 */
4736 # endif /* NETINET || NETINET6 */
4738 FREEHOSTENT(hp, NULL);
4741 if (sap->sa.sa_family == AF_UNIX && sap->sunix.sun_path[0] == '\0')
4745 static char buf[203];
4747 (void) sm_snprintf(buf, sizeof(buf), "[%.200s]",
4752 #endif /* USE_SOCK_STREAM */