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 $")
19 #if defined(SOCK_STREAM) || defined(__GNU_LIBRARY__)
20 # define USE_SOCK_STREAM 1
23 #if defined(USE_SOCK_STREAM)
24 # if NETINET || NETINET6
25 # include <arpa/inet.h>
29 # define NO_DATA NO_ADDRESS
31 # endif /* NAMED_BIND */
32 #endif /* defined(USE_SOCK_STREAM) */
35 # include <openssl/rand.h>
38 # include "sm_resolve.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;
169 /* initialize data for function that generates queue ids */
171 for (idx = 0; idx < NDaemons; idx++)
173 Daemons[idx].d_port = setupdaemon(&(Daemons[idx].d_addr));
174 Daemons[idx].d_firsttime = true;
175 Daemons[idx].d_refuse_connections_until = (time_t) 0;
179 ** Try to actually open the connection.
184 for (idx = 0; idx < NDaemons; idx++)
186 sm_dprintf("getrequests: daemon %s: port %d\n",
188 ntohs(Daemons[idx].d_port));
192 /* get a socket for the SMTP connection */
193 for (idx = 0; idx < NDaemons; idx++)
194 Daemons[idx].d_socksize = opendaemonsocket(&Daemons[idx], true);
196 if (opencontrolsocket() < 0)
197 sm_syslog(LOG_WARNING, NOQID,
198 "daemon could not open control socket %s: %s",
199 ControlSocketName, sm_errstring(errno));
201 /* If there are any queue runners released reapchild() co-ord's */
202 (void) sm_signal(SIGCHLD, reapchild);
204 /* write the pid to file, command line args to syslog */
209 char jbuf[MAXHOSTNAMELEN];
211 expand("\201j", jbuf, sizeof(jbuf), e);
212 j_has_dot = strchr(jbuf, '.') != NULL;
216 /* Add parent process as first item */
217 proc_list_add(CurrentPid, "Sendmail daemon", PROC_DAEMON, 0, -1, NULL);
221 for (idx = 0; idx < NDaemons; idx++)
222 sm_dprintf("getrequests: daemon %s: socket %d\n",
224 Daemons[idx].d_socket);
230 auto SOCKADDR_LEN_T lotherend;
231 bool timedout = false;
232 bool control = false;
240 /* see if we are rejecting connections */
241 (void) sm_blocksignal(SIGALRM);
244 for (idx = 0; idx < NDaemons; idx++)
247 ** XXX do this call outside the loop?
248 ** no: refuse_connections may sleep().
252 if (now < Daemons[idx].d_refuse_connections_until)
254 if (bitnset(D_DISABLE, Daemons[idx].d_flags))
256 if (refuseconnections(e, idx, curdaemon == idx))
258 if (Daemons[idx].d_socket >= 0)
260 /* close socket so peer fails quickly */
261 (void) close(Daemons[idx].d_socket);
262 Daemons[idx].d_socket = -1;
265 /* refuse connections for next 15 seconds */
266 Daemons[idx].d_refuse_connections_until = now + 15;
268 else if (Daemons[idx].d_socket < 0 ||
269 Daemons[idx].d_firsttime)
271 if (!Daemons[idx].d_firsttime && LogLevel > 8)
272 sm_syslog(LOG_INFO, NOQID,
273 "accepting connections again for daemon %s",
274 Daemons[idx].d_name);
276 /* arrange to (re)open the socket if needed */
277 (void) opendaemonsocket(&Daemons[idx], false);
278 Daemons[idx].d_firsttime = false;
282 /* May have been sleeping above, check again */
285 getrequests_checkdiskspace(e);
288 /* check for disaster */
290 char jbuf[MAXHOSTNAMELEN];
292 expand("\201j", jbuf, sizeof(jbuf), e);
293 if (!wordinclass(jbuf, 'w'))
295 dumpstate("daemon lost $j");
296 sm_syslog(LOG_ALERT, NOQID,
297 "daemon process doesn't have $j in $=w; see syslog");
300 else if (j_has_dot && strchr(jbuf, '.') == NULL)
302 dumpstate("daemon $j lost dot");
303 sm_syslog(LOG_ALERT, NOQID,
304 "daemon process $j lost dot; see syslog");
312 ** Andrew Sun <asun@ieps-sun.ml.com> claims that this will
313 ** fix the SVr4 problem. But it seems to have gone away,
314 ** so is it worth doing this?
317 if (DaemonSocket >= 0 &&
318 SetNonBlocking(DaemonSocket, false) < 0)
321 (void) sm_releasesignal(SIGALRM);
325 bool setproc = false;
328 struct timeval timeout;
332 for (idx = 0; idx < NDaemons; idx++)
334 /* wait for a connection */
335 if (Daemons[idx].d_socket >= 0)
339 Daemons[idx].d_flags))
341 sm_setproctitle(true, e,
342 "accepting connections");
345 if (Daemons[idx].d_socket > highest)
346 highest = Daemons[idx].d_socket;
347 SM_FD_SET(Daemons[idx].d_socket,
353 if (ControlSocket >= 0)
355 if (ControlSocket > highest)
356 highest = ControlSocket;
357 SM_FD_SET(ControlSocket, &readfds);
364 t = select(highest + 1, FDSET_CAST &readfds,
365 NULL, NULL, &timeout);
367 /* Did someone signal while waiting? */
373 (void) runqueue(true, false, false, false);
374 #if _FFR_QUEUE_RUN_PARANOIA
378 #if _FFR_QUEUE_RUN_PARANOIA
379 else if (CheckQueueRunners > 0 && QueueIntvl > 0 &&
380 lastrun + QueueIntvl + CheckQueueRunners < now)
384 ** set lastrun unconditionally to avoid
385 ** calling checkqueuerunner() all the time.
386 ** That's also why we currently ignore the
387 ** result of the function call.
390 (void) checkqueuerunner();
393 #endif /* _FFR_QUEUE_RUN_PARANOIA */
404 /* look "round-robin" for an active socket */
405 if ((idx = olddaemon + 1) >= NDaemons)
407 for (i = 0; i < NDaemons; i++)
409 if (Daemons[idx].d_socket >= 0 &&
410 SM_FD_ISSET(Daemons[idx].d_socket,
413 lotherend = Daemons[idx].d_socksize;
414 memset(&RealHostAddr, '\0',
415 sizeof(RealHostAddr));
416 t = accept(Daemons[idx].d_socket,
417 (struct sockaddr *)&RealHostAddr,
421 ** If remote side closes before
422 ** accept() finishes, sockaddr
423 ** might not be fully filled in.
428 #ifdef BSD4_4_SOCKADDR
429 RealHostAddr.sa.sa_len == 0 ||
431 RealHostAddr.sa.sa_family != Daemons[idx].d_addr.sa.sa_family))
437 olddaemon = curdaemon = idx;
440 if (++idx >= NDaemons)
444 if (curdaemon == -1 && ControlSocket >= 0 &&
445 SM_FD_ISSET(ControlSocket, &readfds))
447 struct sockaddr_un sa_un;
449 lotherend = sizeof(sa_un);
450 memset(&sa_un, '\0', sizeof(sa_un));
451 t = accept(ControlSocket,
452 (struct sockaddr *)&sa_un,
456 ** If remote side closes before
457 ** accept() finishes, sockaddr
458 ** might not be fully filled in.
463 # ifdef BSD4_4_SOCKADDR
464 sa_un.sun_len == 0 ||
466 sa_un.sun_family != AF_UNIX))
478 /* No daemon to service */
482 if (t >= 0 || errno != EINTR)
491 (void) sm_blocksignal(SIGALRM);
496 /* let's ignore these temporary errors */
497 if (save_errno == EINTR
499 || save_errno == EAGAIN
502 || save_errno == ECONNABORTED
505 || save_errno == EWOULDBLOCK
510 syserr("getrequests: accept");
514 /* arrange to re-open socket next time around */
515 (void) close(Daemons[curdaemon].d_socket);
516 Daemons[curdaemon].d_socket = -1;
517 #if SO_REUSEADDR_IS_BROKEN
519 ** Give time for bound socket to be released.
520 ** This creates a denial-of-service if you can
521 ** force accept() to fail on affected systems.
524 Daemons[curdaemon].d_refuse_connections_until =
526 #endif /* SO_REUSEADDR_IS_BROKEN */
533 /* set some daemon related macros */
534 switch (Daemons[curdaemon].d_addr.sa.sa_family)
537 macdefine(&BlankEnvelope.e_macro, A_PERM,
538 macid("{daemon_family}"), "unspec");
542 macdefine(&BlankEnvelope.e_macro, A_PERM,
543 macid("{daemon_family}"), "local");
548 macdefine(&BlankEnvelope.e_macro, A_PERM,
549 macid("{daemon_family}"), "inet");
554 macdefine(&BlankEnvelope.e_macro, A_PERM,
555 macid("{daemon_family}"), "inet6");
560 macdefine(&BlankEnvelope.e_macro, A_PERM,
561 macid("{daemon_family}"), "iso");
566 macdefine(&BlankEnvelope.e_macro, A_PERM,
567 macid("{daemon_family}"), "ns");
572 macdefine(&BlankEnvelope.e_macro, A_PERM,
573 macid("{daemon_family}"), "x.25");
577 macdefine(&BlankEnvelope.e_macro, A_PERM,
578 macid("{daemon_name}"),
579 Daemons[curdaemon].d_name);
580 if (Daemons[curdaemon].d_mflags != NULL)
581 macdefine(&BlankEnvelope.e_macro, A_PERM,
582 macid("{daemon_flags}"),
583 Daemons[curdaemon].d_mflags);
585 macdefine(&BlankEnvelope.e_macro, A_PERM,
586 macid("{daemon_flags}"), "");
590 ** If connection rate is exceeded here, connection shall be
591 ** refused later by a new call after fork() by the
592 ** validate_connection() function. Closing the connection
593 ** at this point violates RFC 2821.
594 ** Do NOT remove this call, its side effects are needed.
597 connection_rate_check(&RealHostAddr, NULL);
600 ** Create a subprocess to process the mail.
604 sm_dprintf("getrequests: forking (fd = %d)\n", t);
607 ** Advance state of PRNG.
608 ** This is necessary because otherwise all child processes
609 ** will produce the same PRN sequence and hence the selection
610 ** of a queue directory (and other things, e.g., MX selection)
611 ** are not "really" random.
614 /* XXX get some better "random" data? */
616 RAND_seed((void *) &NextDiskSpaceCheck,
617 sizeof(NextDiskSpaceCheck));
618 RAND_seed((void *) &now, sizeof(now));
619 RAND_seed((void *) &seed, sizeof(seed));
622 #endif /* STARTTLS */
626 ** Update MX records for FallbackMX.
627 ** Let's hope this is fast otherwise we screw up the
631 if (FallbackMX != NULL)
632 (void) getfallbackmxrr(FallbackMX);
633 #endif /* NAMED_BIND */
637 /* don't fork, handle connection in this process */
639 pipefd[0] = pipefd[1] = -1;
644 ** Create a pipe to keep the child from writing to
645 ** the socket until after the parent has closed
646 ** it. Otherwise the parent may hang if the child
647 ** has closed it first.
650 if (pipe(pipefd) < 0)
651 pipefd[0] = pipefd[1] = -1;
653 (void) sm_blocksignal(SIGCHLD);
657 syserr("daemon: cannot fork");
660 (void) close(pipefd[0]);
661 (void) close(pipefd[1]);
663 (void) sm_releasesignal(SIGCHLD);
673 SM_FILE_T *inchannel, *outchannel = NULL;
676 ** CHILD -- return to caller.
677 ** Collect verified idea of sending host.
678 ** Verify calling user id if possible here.
681 /* Reset global flags */
682 RestartRequest = NULL;
683 RestartWorkGroup = false;
684 ShutdownRequest = NULL;
686 CurrentPid = getpid();
687 close_sendmail_pid();
689 (void) sm_releasesignal(SIGALRM);
690 (void) sm_releasesignal(SIGCHLD);
691 (void) sm_signal(SIGCHLD, SIG_DFL);
692 (void) sm_signal(SIGHUP, SIG_DFL);
693 (void) sm_signal(SIGTERM, intsig);
695 /* turn on profiling */
699 ** Initialize exception stack and default exception
700 ** handler for child process.
703 sm_exc_newthread(fatal_error);
707 macdefine(&BlankEnvelope.e_macro, A_TEMP,
708 macid("{daemon_addr}"),
709 anynet_ntoa(&Daemons[curdaemon].d_addr));
710 (void) sm_snprintf(status, sizeof(status), "%d",
711 ntohs(Daemons[curdaemon].d_port));
712 macdefine(&BlankEnvelope.e_macro, A_TEMP,
713 macid("{daemon_port}"), status);
716 for (idx = 0; idx < NDaemons; idx++)
718 if (Daemons[idx].d_socket >= 0)
719 (void) close(Daemons[idx].d_socket);
720 Daemons[idx].d_socket = -1;
724 /* Avoid SMTP daemon actions if control command */
727 /* Add control socket process */
728 proc_list_add(CurrentPid,
729 "console socket child",
730 PROC_CONTROL_CHILD, 0, -1, NULL);
736 /* clean up background delivery children */
737 (void) sm_signal(SIGCHLD, reapchild);
739 /* Add parent process as first child item */
740 proc_list_add(CurrentPid, "daemon child",
741 PROC_DAEMON_CHILD, 0, -1, NULL);
742 /* don't schedule queue runs if ETRN */
746 ** Hack: override global variables if
747 ** the corresponding DaemonPortOption
750 #if _FFR_SS_PER_DAEMON
751 if (Daemons[curdaemon].d_supersafe !=
753 SuperSafe = Daemons[curdaemon].
755 #endif /* _FFR_SS_PER_DAEMON */
756 if (Daemons[curdaemon].d_dm != DM_NOTSET)
758 Daemons[curdaemon].d_dm, e);
760 if (Daemons[curdaemon].d_refuseLA !=
762 RefuseLA = Daemons[curdaemon].
764 if (Daemons[curdaemon].d_queueLA != DPO_NOTSET)
765 QueueLA = Daemons[curdaemon].d_queueLA;
766 if (Daemons[curdaemon].d_delayLA != DPO_NOTSET)
767 DelayLA = Daemons[curdaemon].d_delayLA;
768 if (Daemons[curdaemon].d_maxchildren !=
770 MaxChildren = Daemons[curdaemon].
773 sm_setproctitle(true, e, "startup with %s",
774 anynet_ntoa(&RealHostAddr));
782 ** Wait for the parent to close the write end
783 ** of the pipe, which we will see as an EOF.
784 ** This guarantees that we won't write to the
785 ** socket until after the parent has closed
789 /* close the write end of the pipe */
790 (void) close(pipefd[1]);
792 /* we shouldn't be interrupted, but ... */
793 while (read(pipefd[0], &c, 1) < 0 &&
796 (void) close(pipefd[0]);
799 /* control socket processing */
802 control_command(t, e);
807 /* determine host name */
808 p = hostnamebyanyaddr(&RealHostAddr);
809 if (strlen(p) > MAXNAME) /* XXX - 1 ? */
811 RealHostName = newstr(p);
812 if (RealHostName[0] == '[')
814 macdefine(&BlankEnvelope.e_macro, A_PERM,
815 macid("{client_resolve}"),
816 h_errno == TRY_AGAIN ? "TEMP" : "FAIL");
820 macdefine(&BlankEnvelope.e_macro, A_PERM,
821 macid("{client_resolve}"), "OK");
823 sm_setproctitle(true, e, "startup with %s", p);
824 markstats(e, NULL, STATS_CONNECT);
826 if ((inchannel = sm_io_open(SmFtStdiofd,
832 (outchannel = sm_io_open(SmFtStdiofd,
838 syserr("cannot open SMTP server channel, fd=%d",
840 finis(false, true, EX_OK);
842 sm_io_automode(inchannel, outchannel);
844 InChannel = inchannel;
845 OutChannel = outchannel;
846 DisConnected = false;
849 t = xconnect(inchannel);
852 clrbitn(D_XCNCT, Daemons[curdaemon].d_flags);
853 clrbitn(D_XCNCT_M, Daemons[curdaemon].d_flags);
856 setbitn(t, Daemons[curdaemon].d_flags);
858 #endif /* _FFR_XCNCT */
861 if (!xla_host_ok(RealHostName))
863 message("421 4.4.5 Too many SMTP sessions for this host");
864 finis(false, true, EX_OK);
867 /* find out name for interface of connection */
868 if (getsockname(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
869 NULL), &sa.sa, &len) == 0)
871 p = hostnamebyanyaddr(&sa);
873 sm_dprintf("getreq: got name %s\n", p);
874 macdefine(&BlankEnvelope.e_macro, A_TEMP,
875 macid("{if_name}"), p);
878 ** Do this only if it is not the loopback
887 addr = anynet_ntoa(&sa);
888 (void) sm_snprintf(family,
890 "%d", sa.sa.sa_family);
891 macdefine(&BlankEnvelope.e_macro,
893 macid("{if_addr}"), addr);
894 macdefine(&BlankEnvelope.e_macro,
896 macid("{if_family}"), family);
898 sm_dprintf("getreq: got addr %s and family %s\n",
903 macdefine(&BlankEnvelope.e_macro,
905 macid("{if_addr}"), NULL);
906 macdefine(&BlankEnvelope.e_macro,
908 macid("{if_family}"), NULL);
914 sm_dprintf("getreq: getsockname failed\n");
915 macdefine(&BlankEnvelope.e_macro, A_PERM,
916 macid("{if_name}"), NULL);
917 macdefine(&BlankEnvelope.e_macro, A_PERM,
918 macid("{if_addr}"), NULL);
919 macdefine(&BlankEnvelope.e_macro, A_PERM,
920 macid("{if_family}"), NULL);
925 /* parent -- keep track of children */
928 (void) sm_snprintf(status, sizeof(status),
929 "control socket server child");
930 proc_list_add(pid, status, PROC_CONTROL, 0, -1, NULL);
934 (void) sm_snprintf(status, sizeof(status),
935 "SMTP server child for %s",
936 anynet_ntoa(&RealHostAddr));
937 proc_list_add(pid, status, PROC_DAEMON, 0, -1,
940 (void) sm_releasesignal(SIGCHLD);
942 /* close the read end of the synchronization pipe */
945 (void) close(pipefd[0]);
949 /* close the port so that others will hang (for a while) */
952 /* release the child by closing the read end of the sync pipe */
955 (void) close(pipefd[1]);
960 sm_dprintf("getreq: returning\n");
963 /* set the filters for this daemon */
964 if (Daemons[curdaemon].d_inputfilterlist != NULL)
968 Daemons[curdaemon].d_inputfilters[i] != NULL);
971 InputFilters[i] = Daemons[curdaemon].d_inputfilters[i];
974 InputFilters[i] = NULL;
977 return &Daemons[curdaemon].d_flags;
981 ** GETREQUESTS_CHECKDISKSPACE -- check available diskspace.
990 ** Modifies Daemon flags (D_ETRNONLY) if not enough disk space.
994 getrequests_checkdiskspace(e)
1002 if (now < NextDiskSpaceCheck)
1005 /* Check if there is available disk space in all queue groups. */
1006 if (!enoughdiskspace(0, NULL))
1008 for (idx = 0; idx < NDaemons; ++idx)
1010 if (bitnset(D_ETRNONLY, Daemons[idx].d_flags))
1013 /* log only if not logged before */
1017 sm_syslog(LOG_INFO, NOQID,
1018 "rejecting new messages: min free: %ld",
1020 sm_setproctitle(true, e,
1021 "rejecting new messages: min free: %ld",
1025 setbitn(D_ETRNONLY, Daemons[idx].d_flags);
1030 for (idx = 0; idx < NDaemons; ++idx)
1032 if (!bitnset(D_ETRNONLY, Daemons[idx].d_flags))
1035 /* log only if not logged before */
1039 sm_syslog(LOG_INFO, NOQID,
1040 "accepting new messages (again)");
1044 /* title will be set later */
1045 clrbitn(D_ETRNONLY, Daemons[idx].d_flags);
1049 /* only check disk space once a minute */
1050 NextDiskSpaceCheck = now + 60;
1054 ** OPENDAEMONSOCKET -- open SMTP socket
1056 ** Deals with setting all appropriate options.
1059 ** d -- the structure for the daemon to open.
1060 ** firsttime -- set if this is the initial open.
1063 ** Size in bytes of the daemon socket addr.
1066 ** Leaves DaemonSocket set to the open socket.
1067 ** Exits if the socket cannot be created.
1070 #define MAXOPENTRIES 10 /* maximum number of tries to open connection */
1073 opendaemonsocket(d, firsttime)
1079 SOCKADDR_LEN_T socksize = 0;
1084 sm_dprintf("opendaemonsocket(%s)\n", d->d_name);
1090 if (firsttime || d->d_socket < 0)
1093 if (d->d_addr.sa.sa_family == AF_UNIX)
1096 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_ROOTOK|SFF_EXECOK|SFF_CREAT;
1098 /* if not safe, don't use it */
1099 rval = safefile(d->d_addr.sunix.sun_path,
1102 S_IRUSR|S_IWUSR, NULL);
1106 syserr("opendaemonsocket: daemon %s: unsafe domain socket %s",
1108 d->d_addr.sunix.sun_path);
1112 /* Don't try to overtake an existing socket */
1113 (void) unlink(d->d_addr.sunix.sun_path);
1115 #endif /* NETUNIX */
1116 d->d_socket = socket(d->d_addr.sa.sa_family,
1118 if (d->d_socket < 0)
1121 syserr("opendaemonsocket: daemon %s: can't create server SMTP socket",
1124 if (bitnset(D_OPTIONAL, d->d_flags) &&
1125 (!transienterror(save_errno) ||
1126 ntries >= MAXOPENTRIES - 1))
1128 syserr("opendaemonsocket: daemon %s: optional socket disabled",
1130 setbitn(D_DISABLE, d->d_flags);
1136 sm_syslog(LOG_ALERT, NOQID,
1137 "daemon %s: problem creating SMTP socket",
1143 if (!SM_FD_OK_SELECT(d->d_socket))
1145 save_errno = EINVAL;
1146 syserr("opendaemonsocket: daemon %s: server SMTP socket (%d) too large",
1147 d->d_name, d->d_socket);
1151 /* turn on network debugging? */
1153 (void) setsockopt(d->d_socket, SOL_SOCKET,
1154 SO_DEBUG, (char *)&on,
1157 (void) setsockopt(d->d_socket, SOL_SOCKET,
1158 SO_REUSEADDR, (char *)&on, sizeof(on));
1159 (void) setsockopt(d->d_socket, SOL_SOCKET,
1160 SO_KEEPALIVE, (char *)&on, sizeof(on));
1163 if (d->d_tcprcvbufsize > 0)
1165 if (setsockopt(d->d_socket, SOL_SOCKET,
1167 (char *) &d->d_tcprcvbufsize,
1168 sizeof(d->d_tcprcvbufsize)) < 0)
1169 syserr("opendaemonsocket: daemon %s: setsockopt(SO_RCVBUF)", d->d_name);
1171 #endif /* SO_RCVBUF */
1173 if (d->d_tcpsndbufsize > 0)
1175 if (setsockopt(d->d_socket, SOL_SOCKET,
1177 (char *) &d->d_tcpsndbufsize,
1178 sizeof(d->d_tcpsndbufsize)) < 0)
1179 syserr("opendaemonsocket: daemon %s: setsockopt(SO_SNDBUF)", d->d_name);
1181 #endif /* SO_SNDBUF */
1183 if ((fdflags = fcntl(d->d_socket, F_GETFD, 0)) == -1 ||
1184 fcntl(d->d_socket, F_SETFD,
1185 fdflags | FD_CLOEXEC) == -1)
1188 syserr("opendaemonsocket: daemon %s: failed to %s close-on-exec flag: %s",
1190 fdflags == -1 ? "get" : "set",
1191 sm_errstring(save_errno));
1192 (void) close(d->d_socket);
1196 switch (d->d_addr.sa.sa_family)
1200 socksize = sizeof(d->d_addr.sunix);
1205 socksize = sizeof(d->d_addr.sin);
1211 socksize = sizeof(d->d_addr.sin6);
1217 socksize = sizeof(d->d_addr.siso);
1222 socksize = sizeof(d->d_addr);
1226 if (bind(d->d_socket, &d->d_addr.sa, socksize) < 0)
1228 /* probably another daemon already */
1230 syserr("opendaemonsocket: daemon %s: cannot bind",
1232 (void) close(d->d_socket);
1237 listen(d->d_socket, d->d_listenqueue) < 0)
1240 syserr("opendaemonsocket: daemon %s: cannot listen",
1242 (void) close(d->d_socket);
1246 } while (ntries++ < MAXOPENTRIES && transienterror(save_errno));
1247 syserr("!opendaemonsocket: daemon %s: server SMTP socket wedged: exiting",
1250 return -1; /* avoid compiler warning on IRIX */
1253 ** SETUPDAEMON -- setup socket for daemon
1256 ** daemonaddr -- socket for daemon
1259 ** port number on which daemon should run
1263 static unsigned short
1264 setupdaemon(daemonaddr)
1265 SOCKADDR *daemonaddr;
1267 unsigned short port;
1270 ** Set up the address for the mailer.
1273 if (daemonaddr->sa.sa_family == AF_UNSPEC)
1275 memset(daemonaddr, '\0', sizeof(*daemonaddr));
1277 daemonaddr->sa.sa_family = AF_INET;
1281 switch (daemonaddr->sa.sa_family)
1285 if (daemonaddr->sin.sin_addr.s_addr == 0)
1286 daemonaddr->sin.sin_addr.s_addr =
1287 LocalDaemon ? htonl(INADDR_LOOPBACK) : INADDR_ANY;
1288 port = daemonaddr->sin.sin_port;
1290 #endif /* NETINET */
1294 if (IN6_IS_ADDR_UNSPECIFIED(&daemonaddr->sin6.sin6_addr))
1295 daemonaddr->sin6.sin6_addr =
1296 (LocalDaemon && V6LoopbackAddrFound) ?
1297 in6addr_loopback : in6addr_any;
1298 port = daemonaddr->sin6.sin6_port;
1300 #endif /* NETINET6 */
1303 /* unknown protocol */
1309 #ifdef NO_GETSERVBYNAME
1311 #else /* NO_GETSERVBYNAME */
1313 register struct servent *sp;
1315 sp = getservbyname("smtp", "tcp");
1318 syserr("554 5.3.5 service \"smtp\" unknown");
1324 #endif /* NO_GETSERVBYNAME */
1327 switch (daemonaddr->sa.sa_family)
1331 daemonaddr->sin.sin_port = port;
1337 daemonaddr->sin6.sin6_port = port;
1342 /* unknown protocol */
1348 ** CLRDAEMON -- reset the daemon connection
1357 ** releases any resources used by the passive daemon.
1365 for (i = 0; i < NDaemons; i++)
1367 if (Daemons[i].d_socket >= 0)
1368 (void) close(Daemons[i].d_socket);
1369 Daemons[i].d_socket = -1;
1374 ** GETMODIFIERS -- get modifier flags
1377 ** v -- the modifiers (input text line).
1378 ** modifiers -- pointer to flag field to represent modifiers.
1381 ** (xallocat()ed) string representation of modifiers.
1384 ** fills in modifiers.
1388 getmodifiers(v, modifiers)
1390 BITMAP256 modifiers;
1393 char *h, *f, *flags;
1395 /* maximum length of flags: upper case Option -> "OO " */
1396 l = 3 * strlen(v) + 3;
1398 /* is someone joking? */
1399 if (l < 0 || l > 256)
1402 sm_syslog(LOG_ERR, NOQID,
1403 "getmodifiers too long, ignored");
1408 clrbitmap(modifiers);
1409 for (h = v; *h != '\0'; h++)
1411 if (isascii(*h) && !isspace(*h) && isprint(*h))
1413 setbitn(*h, modifiers);
1426 ** CHKDAEMONMODIFIERS -- check whether all daemons have set a flag.
1429 ** flag -- the flag to test.
1432 ** true iff all daemons have set flag.
1436 chkdaemonmodifiers(flag)
1441 for (i = 0; i < NDaemons; i++)
1442 if (!bitnset((char) flag, Daemons[i].d_flags))
1448 ** SETSOCKADDROPTIONS -- set options for SOCKADDR (daemon or client)
1451 ** p -- the options line.
1452 ** d -- the daemon structure to fill in.
1459 setsockaddroptions(p, d)
1470 if (d->d_addr.sa.sa_family == AF_UNSPEC)
1471 d->d_addr.sa.sa_family = AF_INET;
1473 #if _FFR_SS_PER_DAEMON
1474 d->d_supersafe = DPO_NOTSET;
1476 d->d_dm = DM_NOTSET;
1477 d->d_refuseLA = DPO_NOTSET;
1478 d->d_queueLA = DPO_NOTSET;
1479 d->d_delayLA = DPO_NOTSET;
1480 d->d_maxchildren = DPO_NOTSET;
1487 while (SM_ISSPACE(*p))
1498 while (isascii(*++v) && isspace(*v))
1503 case 'A': /* address */
1511 d->d_maxchildren = atoi(v);
1514 case 'D': /* DeliveryMode */
1527 syserr("554 5.3.5 Unknown delivery mode %c",
1533 case 'd': /* delayLA */
1534 d->d_delayLA = atoi(v);
1537 case 'F': /* address family */
1541 if (isascii(*v) && isdigit(*v))
1542 d->d_addr.sa.sa_family = atoi(v);
1544 else if (sm_strcasecmp(v, "unix") == 0 ||
1545 sm_strcasecmp(v, "local") == 0)
1546 d->d_addr.sa.sa_family = AF_UNIX;
1549 else if (sm_strcasecmp(v, "inet") == 0)
1550 d->d_addr.sa.sa_family = AF_INET;
1553 else if (sm_strcasecmp(v, "inet6") == 0)
1554 d->d_addr.sa.sa_family = AF_INET6;
1557 else if (sm_strcasecmp(v, "iso") == 0)
1558 d->d_addr.sa.sa_family = AF_ISO;
1561 else if (sm_strcasecmp(v, "ns") == 0)
1562 d->d_addr.sa.sa_family = AF_NS;
1565 else if (sm_strcasecmp(v, "x.25") == 0)
1566 d->d_addr.sa.sa_family = AF_CCITT;
1569 syserr("554 5.3.5 Unknown address family %s in Family=option",
1578 d->d_inputfilterlist = v;
1582 case 'L': /* listen queue size */
1586 d->d_listenqueue = atoi(v);
1589 case 'M': /* modifiers (flags) */
1593 d->d_mflags = getmodifiers(v, d->d_flags);
1596 case 'N': /* name */
1603 case 'P': /* port */
1611 d->d_queueLA = atoi(v);
1614 case 'R': /* receive buffer size */
1615 d->d_tcprcvbufsize = atoi(v);
1619 d->d_refuseLA = atoi(v);
1622 case 'S': /* send buffer size */
1626 d->d_tcpsndbufsize = atoi(v);
1629 #if _FFR_SS_PER_DAEMON
1630 case 'T': /* SuperSafe */
1631 if (tolower(*v) == 'i')
1632 d->d_supersafe = SAFE_INTERACTIVE;
1633 else if (tolower(*v) == 'p')
1635 d->d_supersafe = SAFE_REALLY_POSTMILTER;
1637 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1638 "Warning: SuperSafe=PostMilter requires Milter support (-DMILTER)\n");
1639 # endif /* MILTER */
1641 d->d_supersafe = atobool(v) ? SAFE_REALLY
1644 #endif /* _FFR_SS_PER_DAEMON */
1647 syserr("554 5.3.5 PortOptions parameter \"%s\" unknown",
1652 /* Check addr and port after finding family */
1655 switch (d->d_addr.sa.sa_family)
1659 if (strlen(addr) >= sizeof(d->d_addr.sunix.sun_path))
1661 errno = ENAMETOOLONG;
1662 syserr("setsockaddroptions: domain socket name too long: %s > %ld",
1664 (long) sizeof(d->d_addr.sunix.sun_path));
1668 /* file safety check done in opendaemonsocket() */
1669 (void) memset(&d->d_addr.sunix.sun_path, '\0',
1670 sizeof(d->d_addr.sunix.sun_path));
1671 (void) sm_strlcpy((char *)&d->d_addr.sunix.sun_path,
1673 sizeof(d->d_addr.sunix.sun_path));
1675 #endif /* NETUNIX */
1678 if (!isascii(*addr) || !isdigit(*addr) ||
1679 ((d->d_addr.sin.sin_addr.s_addr = inet_addr(addr))
1682 register struct hostent *hp;
1684 hp = sm_gethostbyname(addr, AF_INET);
1686 syserr("554 5.3.0 host \"%s\" unknown",
1690 while (*(hp->h_addr_list) != NULL &&
1691 hp->h_addrtype != AF_INET)
1693 if (*(hp->h_addr_list) == NULL)
1694 syserr("554 5.3.0 host \"%s\" unknown",
1697 memmove(&d->d_addr.sin.sin_addr,
1700 FREEHOSTENT(hp, NULL);
1704 #endif /* NETINET */
1708 if (anynet_pton(AF_INET6, addr,
1709 &d->d_addr.sin6.sin6_addr) != 1)
1711 register struct hostent *hp;
1713 hp = sm_gethostbyname(addr, AF_INET6);
1715 syserr("554 5.3.0 host \"%s\" unknown",
1719 while (*(hp->h_addr_list) != NULL &&
1720 hp->h_addrtype != AF_INET6)
1722 if (*(hp->h_addr_list) == NULL)
1723 syserr("554 5.3.0 host \"%s\" unknown",
1726 memmove(&d->d_addr.sin6.sin6_addr,
1729 FREEHOSTENT(hp, NULL);
1733 #endif /* NETINET6 */
1736 syserr("554 5.3.5 address= option unsupported for family %d",
1737 d->d_addr.sa.sa_family);
1744 switch (d->d_addr.sa.sa_family)
1748 if (isascii(*port) && isdigit(*port))
1749 d->d_addr.sin.sin_port = htons((unsigned short)
1750 atoi((const char *) port));
1753 # ifdef NO_GETSERVBYNAME
1754 syserr("554 5.3.5 invalid port number: %s",
1756 # else /* NO_GETSERVBYNAME */
1757 register struct servent *sp;
1759 sp = getservbyname(port, "tcp");
1761 syserr("554 5.3.5 service \"%s\" unknown",
1764 d->d_addr.sin.sin_port = sp->s_port;
1765 # endif /* NO_GETSERVBYNAME */
1768 #endif /* NETINET */
1772 if (isascii(*port) && isdigit(*port))
1773 d->d_addr.sin6.sin6_port = htons((unsigned short)
1777 # ifdef NO_GETSERVBYNAME
1778 syserr("554 5.3.5 invalid port number: %s",
1780 # else /* NO_GETSERVBYNAME */
1781 register struct servent *sp;
1783 sp = getservbyname(port, "tcp");
1785 syserr("554 5.3.5 service \"%s\" unknown",
1788 d->d_addr.sin6.sin6_port = sp->s_port;
1789 # endif /* NO_GETSERVBYNAME */
1792 #endif /* NETINET6 */
1796 /* assume two byte transport selector */
1797 if (isascii(*port) && isdigit(*port))
1798 portno = htons((unsigned short) atoi(port));
1801 # ifdef NO_GETSERVBYNAME
1802 syserr("554 5.3.5 invalid port number: %s",
1804 # else /* NO_GETSERVBYNAME */
1805 register struct servent *sp;
1807 sp = getservbyname(port, "tcp");
1809 syserr("554 5.3.5 service \"%s\" unknown",
1812 portno = sp->s_port;
1813 # endif /* NO_GETSERVBYNAME */
1815 memmove(TSEL(&d->d_addr.siso),
1816 (char *) &portno, 2);
1821 syserr("554 5.3.5 Port= option unsupported for family %d",
1822 d->d_addr.sa.sa_family);
1828 ** SETDAEMONOPTIONS -- set options for running the MTA daemon
1831 ** p -- the options line.
1834 ** true if successful, false otherwise.
1837 ** increments number of daemons.
1840 #define DEF_LISTENQUEUE 10
1848 static struct dflags DaemonFlags[] =
1850 { "AUTHREQ", D_AUTHREQ },
1851 { "BINDIF", D_BINDIF },
1852 { "CANONREQ", D_CANONREQ },
1853 { "IFNHELO", D_IFNHELO },
1854 { "FQMAIL", D_FQMAIL },
1855 { "FQRCPT", D_FQRCPT },
1856 { "SMTPS", D_SMTPS },
1857 { "UNQUALOK", D_UNQUALOK },
1858 { "NOAUTH", D_NOAUTH },
1859 { "NOCANON", D_NOCANON },
1860 { "NOETRN", D_NOETRN },
1861 { "NOTLS", D_NOTLS },
1862 { "ETRNONLY", D_ETRNONLY },
1863 { "OPTIONAL", D_OPTIONAL },
1864 { "DISABLE", D_DISABLE },
1865 { "ISSET", D_ISSET },
1873 register struct dflags *df;
1876 for (df = DaemonFlags; df->d_name != NULL; df++)
1878 if (!bitnset(df->d_flag, d->d_flags))
1881 sm_dprintf("<%s", df->d_name);
1883 sm_dprintf(",%s", df->d_name);
1894 if (NDaemons >= MAXDAEMONS)
1896 Daemons[NDaemons].d_socket = -1;
1897 Daemons[NDaemons].d_listenqueue = DEF_LISTENQUEUE;
1898 clrbitmap(Daemons[NDaemons].d_flags);
1899 setsockaddroptions(p, &Daemons[NDaemons]);
1902 if (Daemons[NDaemons].d_inputfilterlist != NULL)
1903 Daemons[NDaemons].d_inputfilterlist = newstr(Daemons[NDaemons].d_inputfilterlist);
1906 if (Daemons[NDaemons].d_name != NULL)
1907 Daemons[NDaemons].d_name = newstr(Daemons[NDaemons].d_name);
1912 (void) sm_snprintf(num, sizeof(num), "Daemon%d", NDaemons);
1913 Daemons[NDaemons].d_name = newstr(num);
1918 sm_dprintf("Daemon %s flags: ", Daemons[NDaemons].d_name);
1919 printdaemonflags(&Daemons[NDaemons]);
1926 ** INITDAEMON -- initialize daemon if not yet done.
1935 ** initializes structure for one daemon.
1943 Daemons[NDaemons].d_socket = -1;
1944 Daemons[NDaemons].d_listenqueue = DEF_LISTENQUEUE;
1945 Daemons[NDaemons].d_name = "Daemon0";
1950 ** SETCLIENTOPTIONS -- set options for running the client
1953 ** p -- the options line.
1959 static DAEMON_T ClientSettings[AF_MAX + 1];
1968 memset(&d, '\0', sizeof(d));
1969 setsockaddroptions(p, &d);
1971 /* grab what we need */
1972 family = d.d_addr.sa.sa_family;
1973 STRUCTCOPY(d, ClientSettings[family]);
1974 setbitn(D_ISSET, ClientSettings[family].d_flags); /* mark as set */
1975 if (d.d_name != NULL)
1976 ClientSettings[family].d_name = newstr(d.d_name);
1981 (void) sm_snprintf(num, sizeof(num), "Client%d", family);
1982 ClientSettings[family].d_name = newstr(num);
1986 ** ADDR_FAMILY -- determine address family from address
1989 ** addr -- the string representation of the address
1992 ** AF_INET, AF_INET6 or AF_UNSPEC
2007 if (inet_addr(addr) != INADDR_NONE)
2010 sm_dprintf("addr_family(%s): INET\n", addr);
2013 #endif /* NETINET */
2015 if (anynet_pton(AF_INET6, addr, &clt_addr.sin6.sin6_addr) == 1)
2018 sm_dprintf("addr_family(%s): INET6\n", addr);
2021 #endif /* NETINET6 */
2026 sm_dprintf("addr_family(%s): LOCAL\n", addr);
2029 #endif /* NETUNIX */
2031 sm_dprintf("addr_family(%s): UNSPEC\n", addr);
2036 ** CHKCLIENTMODIFIERS -- check whether all clients have set a flag.
2039 ** flag -- the flag to test.
2042 ** true iff all configured clients have set the flag.
2046 chkclientmodifiers(flag)
2053 for (i = 0; i < AF_MAX; i++)
2055 if (bitnset(D_ISSET, ClientSettings[i].d_flags))
2057 if (!bitnset((char) flag, ClientSettings[i].d_flags))
2067 ** SETUP_DAEMON_MILTERS -- Parse per-socket filters
2077 setup_daemon_milters()
2081 if (OpMode == MD_SMTP)
2083 /* no need to configure the daemons */
2087 for (idx = 0; idx < NDaemons; idx++)
2089 if (Daemons[idx].d_inputfilterlist != NULL)
2091 milter_config(Daemons[idx].d_inputfilterlist,
2092 Daemons[idx].d_inputfilters,
2099 ** MAKECONNECTION -- make a connection to an SMTP socket on a machine.
2102 ** host -- the name of the host.
2103 ** port -- the port number to connect to.
2104 ** mci -- a pointer to the mail connection information
2105 ** structure to be filled in.
2106 ** e -- the current envelope.
2107 ** enough -- time at which to stop further connection attempts.
2108 ** (0 means no limit)
2111 ** An exit code telling whether the connection could be
2112 ** made and if not why not.
2118 static jmp_buf CtxConnectTimeout;
2120 SOCKADDR CurHostAddr; /* address of current host */
2123 makeconnection(host, port, mci, e, enough
2129 volatile unsigned int port;
2134 unsigned long *ptlsa_flags;
2137 register volatile int addrno = 0;
2139 register struct hostent *volatile hp = (struct hostent *) NULL;
2143 volatile SOCKADDR_LEN_T addrlen;
2144 volatile bool firstconnect = true;
2145 SM_EVENT *volatile ev = NULL;
2147 volatile bool v6found = false;
2149 volatile int family = InetMode;
2151 volatile SOCKADDR_LEN_T socksize = 0;
2152 volatile bool clt_bind;
2155 extern ENVELOPE BlankEnvelope;
2157 unsigned long tlsa_flags;
2159 #if DANE && NETINET6
2160 struct hostent *volatile hs = (struct hostent *) NULL;
2162 # define hs ((struct hostent *) NULL)
2166 SM_REQUIRE(ptlsa_flags != NULL);
2167 tlsa_flags = *ptlsa_flags;
2168 *ptlsa_flags &= ~(TLSAFLALWAYS|TLSAFLSECURE);
2171 /* retranslate {daemon_flags} into bitmap */
2173 if ((p = macvalue(macid("{daemon_flags}"), e)) != NULL)
2175 for (; *p != '\0'; p++)
2177 if (!(SM_ISSPACE(*p)))
2178 setbitn(bitidx(*p), d_flags);
2187 /* Set up the address for outgoing connection. */
2188 if (bitnset(D_BINDIF, d_flags) &&
2189 (p = macvalue(macid("{if_addr}"), e)) != NULL &&
2193 char p6[INET6_ADDRSTRLEN];
2196 memset(&clt_addr, '\0', sizeof(clt_addr));
2198 /* infer the address family from the address itself */
2199 clt_addr.sa.sa_family = addr_family(p);
2200 switch (clt_addr.sa.sa_family)
2204 clt_addr.sin.sin_addr.s_addr = inet_addr(p);
2205 if (clt_addr.sin.sin_addr.s_addr != INADDR_NONE &&
2206 clt_addr.sin.sin_addr.s_addr !=
2207 htonl(INADDR_LOOPBACK))
2210 socksize = sizeof(struct sockaddr_in);
2213 #endif /* NETINET */
2217 if (inet_addr(p) != INADDR_NONE)
2218 (void) sm_snprintf(p6, sizeof(p6),
2219 "IPv6:::ffff:%s", p);
2221 (void) sm_strlcpy(p6, p, sizeof(p6));
2222 if (anynet_pton(AF_INET6, p6,
2223 &clt_addr.sin6.sin6_addr) == 1 &&
2224 !IN6_IS_ADDR_LOOPBACK(&clt_addr.sin6.sin6_addr))
2227 socksize = sizeof(struct sockaddr_in6);
2230 #endif /* NETINET6 */
2234 syserr("554 5.3.5 Address= option unsupported for family %d",
2235 clt_addr.sa.sa_family);
2240 family = clt_addr.sa.sa_family;
2243 /* D_BINDIF not set or not available, fallback to ClientPortOptions */
2246 STRUCTCOPY(ClientSettings[family].d_addr, clt_addr);
2247 switch (clt_addr.sa.sa_family)
2251 if (clt_addr.sin.sin_addr.s_addr == 0)
2252 clt_addr.sin.sin_addr.s_addr = LocalDaemon ?
2253 htonl(INADDR_LOOPBACK) : INADDR_ANY;
2256 if (clt_addr.sin.sin_port != 0)
2258 socksize = sizeof(struct sockaddr_in);
2260 #endif /* NETINET */
2263 if (IN6_IS_ADDR_UNSPECIFIED(&clt_addr.sin6.sin6_addr))
2264 clt_addr.sin6.sin6_addr =
2265 (LocalDaemon && V6LoopbackAddrFound) ?
2266 in6addr_loopback : in6addr_any;
2269 socksize = sizeof(struct sockaddr_in6);
2270 if (clt_addr.sin6.sin6_port != 0)
2273 #endif /* NETINET6 */
2276 socksize = sizeof(clt_addr.siso);
2286 ** Set up the address for the mailer.
2287 ** Accept "[a.b.c.d]" syntax for host name.
2292 memset(&CurHostAddr, '\0', sizeof(CurHostAddr));
2293 memset(&addr, '\0', sizeof(addr));
2294 SmtpPhase = mci->mci_phase = "initial connection";
2299 p = strchr(host, ']');
2303 unsigned long hid = INADDR_NONE;
2306 struct sockaddr_in6 hid6;
2311 memset(&hid6, '\0', sizeof(hid6));
2314 if (family == AF_INET &&
2315 (hid = inet_addr(&host[1])) != INADDR_NONE)
2317 addr.sin.sin_family = AF_INET;
2318 addr.sin.sin_addr.s_addr = hid;
2321 #endif /* NETINET */
2323 if (family == AF_INET6 &&
2324 anynet_pton(AF_INET6, &host[1],
2325 &hid6.sin6_addr) == 1)
2327 addr.sin6.sin6_family = AF_INET6;
2328 addr.sin6.sin6_addr = hid6.sin6_addr;
2331 #endif /* NETINET6 */
2333 /* try it as a host name (avoid MX lookup) */
2334 hp = sm_gethostbyname(&host[1], family);
2335 if (hp == NULL && p[-1] == '.')
2338 int oldopts = _res.options;
2340 _res.options &= ~(RES_DEFNAMES|RES_DNSRCH);
2341 #endif /* NAMED_BIND */
2343 hp = sm_gethostbyname(&host[1],
2347 _res.options = oldopts;
2357 extern char MsgBuf[];
2360 "553 Invalid numeric domain spec \"%s\"",
2362 mci_setstat(mci, EX_NOHOST, "5.1.2", MsgBuf);
2369 /* contortion to get around SGI cc complaints */
2371 p = &host[strlen(host) - 1];
2374 sm_dprintf("makeconnection: tlsa_flags=%lX, host=%s\n",
2376 if (DANEMODE(tlsa_flags) == DANE_SECURE
2385 rr = dns_lookup_int(host, C_IN, FAM2T_(family),
2386 0, 0, SM_RES_DNSSEC, 0, &err, &herr);
2389 ** Check for errors!
2390 ** If no ad: turn off TLSA.
2391 ** permail: use "normal" method?
2392 ** tempfail: delay or use "normal" method?
2395 if (rr != NULL && rr->dns_r_h.ad == 1)
2397 *ptlsa_flags |= DANE_SECURE;
2398 if ((TLSAFLTEMP & *ptlsa_flags) != 0)
2404 hp = dns2he(rr, family);
2410 /* other possible "tempfails"? */
2411 if (rr == NULL && h_errno == TRY_AGAIN)
2419 hp = sm_gethostbyname(host, family);
2420 if (hp == NULL && *p == '.')
2423 int oldopts = _res.options;
2425 _res.options &= ~(RES_DEFNAMES|RES_DNSRCH);
2428 hp = sm_gethostbyname(host, family);
2431 _res.options = oldopts;
2436 if (hp == NULL || hp->h_addr == NULL)
2439 /* check for name server timeouts */
2441 if (WorkAroundBrokenAAAA && family == AF_INET6 &&
2442 (h_errno == TRY_AGAIN || errno == ETIMEDOUT))
2445 ** An attempt with family AF_INET may
2446 ** succeed. By skipping the next section
2447 ** of code, we will try AF_INET before
2452 sm_dprintf("makeconnection: WorkAroundBrokenAAAA: Trying AF_INET lookup (AF_INET6 failed)\n");
2455 # endif /* NETINET6 */
2457 if (errno == ETIMEDOUT ||
2458 # if _FFR_GETHBN_ExFILE
2465 # endif /* _FFR_GETHBN_ExFILE */
2466 h_errno == TRY_AGAIN ||
2467 (errno == ECONNREFUSED && UseNameServer))
2470 mci_setstat(mci, EX_TEMPFAIL,
2476 #endif /* NAMED_BIND */
2479 ** Try v6 first, then fall back to v4.
2480 ** If we found a v6 address, but no v4
2481 ** addresses, then TEMPFAIL.
2484 if (family == AF_INET6)
2491 #endif /* NETINET6 */
2493 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2497 addr.sa.sa_family = hp->h_addrtype;
2498 switch (hp->h_addrtype)
2502 memmove(&addr.sin.sin_addr,
2506 #endif /* NETINET */
2510 memmove(&addr.sin6.sin6_addr,
2514 #endif /* NETINET6 */
2517 if (hp->h_length > sizeof(addr.sa.sa_data))
2519 syserr("makeconnection: long sa_data: family %d len %d",
2520 hp->h_addrtype, hp->h_length);
2521 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2525 memmove(addr.sa.sa_data, hp->h_addr, hp->h_length);
2533 ** Hack for testing.
2535 ** 10.1.1.12: see meta1.tns XREF IP address
2536 ** 8754: see common.sh XREF SNKPORT2
2539 if (tTd(77, 101) && hp->h_addrtype == AF_INET &&
2540 addr.sin.sin_addr.s_addr == inet_addr("10.1.1.12"))
2542 addr.sin.sin_addr.s_addr = inet_addr("127.0.0.1");
2544 sm_dprintf("hack host=%s addr=[%s].%d\n", host,
2545 anynet_ntoa(&addr), ntohs(port));
2550 ** Determine the port number.
2555 #ifdef NO_GETSERVBYNAME
2557 #else /* NO_GETSERVBYNAME */
2558 register struct servent *sp = getservbyname("smtp", "tcp");
2563 sm_syslog(LOG_ERR, NOQID,
2564 "makeconnection: service \"smtp\" unknown");
2569 #endif /* NO_GETSERVBYNAME */
2573 if (addr.sa.sa_family == AF_INET6 &&
2574 IN6_IS_ADDR_V4MAPPED(&addr.sin6.sin6_addr) &&
2575 ClientSettings[AF_INET].d_addr.sa.sa_family != 0)
2578 ** Ignore mapped IPv4 address since
2579 ** there is a ClientPortOptions setting
2585 #endif /* NETINET6 */
2587 switch (addr.sa.sa_family)
2591 addr.sin.sin_port = port;
2592 addrlen = sizeof(struct sockaddr_in);
2594 #endif /* NETINET */
2598 addr.sin6.sin6_port = port;
2599 addrlen = sizeof(struct sockaddr_in6);
2601 #endif /* NETINET6 */
2605 /* assume two byte transport selector */
2606 memmove(TSEL((struct sockaddr_iso *) &addr), (char *) &port, 2);
2607 addrlen = sizeof(struct sockaddr_iso);
2612 syserr("Can't connect to address family %d", addr.sa.sa_family);
2613 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2615 FREEHOSTENT(hp, hs);
2620 ** Try to actually open the connection.
2624 /* if too many connections, don't bother trying */
2625 if (!xla_noqueue_ok(host))
2627 FREEHOSTENT(hp, hs);
2633 # define OCC_CLOSE occ_close(e, mci, host, &addr)
2634 /* HACK!!!! just to see if this can work at all... */
2635 if (occ_exceeded(e, mci, host, &addr))
2637 FREEHOSTENT(hp, hs);
2638 sm_syslog(LOG_DEBUG, e->e_id,
2639 "stat=occ_exceeded, host=%s, addr=%s",
2640 host, anynet_ntoa(&addr));
2643 ** to get a more specific stat= message set errno
2644 ** or make up one in sm, see sm_errstring()
2647 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", "450 occ_exceeded"); /* check D.S.N */
2651 #else /* _FFR_OCC */
2653 #endif /* _FFR_OCC */
2658 sm_dprintf("makeconnection (%s [%s].%d (%d))\n",
2659 host, anynet_ntoa(&addr), ntohs(port),
2660 (int) addr.sa.sa_family);
2662 /* save for logging */
2666 if (bitnset(M_SECURE_PORT, mci->mci_mailer->m_flags))
2668 int rport = IPPORT_RESERVED - 1;
2670 s = rresvport(&rport);
2673 #endif /* HASRRESVPORT */
2675 s = socket(addr.sa.sa_family, SOCK_STREAM, 0);
2680 syserr("makeconnection: cannot create socket");
2684 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2685 FREEHOSTENT(hp, hs);
2692 if (ClientSettings[family].d_tcpsndbufsize > 0)
2694 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
2695 (char *) &ClientSettings[family].d_tcpsndbufsize,
2696 sizeof(ClientSettings[family].d_tcpsndbufsize)) < 0)
2697 syserr("makeconnection: setsockopt(SO_SNDBUF)");
2699 #endif /* SO_SNDBUF */
2701 if (ClientSettings[family].d_tcprcvbufsize > 0)
2703 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
2704 (char *) &ClientSettings[family].d_tcprcvbufsize,
2705 sizeof(ClientSettings[family].d_tcprcvbufsize)) < 0)
2706 syserr("makeconnection: setsockopt(SO_RCVBUF)");
2708 #endif /* SO_RCVBUF */
2711 sm_dprintf("makeconnection: fd=%d\n", s);
2713 /* turn on network debugging? */
2718 (void) setsockopt(s, SOL_SOCKET, SO_DEBUG,
2719 (char *)&on, sizeof(on));
2721 if (e->e_xfp != NULL) /* for debugging */
2722 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
2723 errno = 0; /* for debugging */
2729 switch (clt_addr.sa.sa_family)
2733 if (clt_addr.sin.sin_port != 0)
2734 (void) setsockopt(s, SOL_SOCKET,
2739 #endif /* NETINET */
2743 if (clt_addr.sin6.sin6_port != 0)
2744 (void) setsockopt(s, SOL_SOCKET,
2749 #endif /* NETINET6 */
2752 if (bind(s, &clt_addr.sa, socksize) < 0)
2757 syserr("makeconnection: cannot bind socket [%s]",
2758 anynet_ntoa(&clt_addr));
2759 FREEHOSTENT(hp, hs);
2767 ** Linux seems to hang in connect for 90 minutes (!!!).
2768 ** Time out the connect to avoid this problem.
2771 if (setjmp(CtxConnectTimeout) == 0)
2775 if (e->e_ntries <= 0 && TimeOuts.to_iconnect != 0)
2776 ev = sm_setevent(TimeOuts.to_iconnect,
2778 else if (TimeOuts.to_connect != 0)
2779 ev = sm_setevent(TimeOuts.to_connect,
2784 switch (ConnectOnlyTo.sa.sa_family)
2788 addr.sin.sin_addr.s_addr = ConnectOnlyTo.sin.sin_addr.s_addr;
2789 addr.sa.sa_family = ConnectOnlyTo.sa.sa_family;
2790 if (ConnectOnlyTo.sin.sin_port != 0)
2792 port = ConnectOnlyTo.sin.sin_port;
2793 addr.sin.sin_port = port;
2796 #endif /* NETINET */
2800 memmove(&addr.sin6.sin6_addr,
2801 &ConnectOnlyTo.sin6.sin6_addr,
2803 if (ConnectOnlyTo.sin6.sin6_port != 0)
2805 port = ConnectOnlyTo.sin6.sin6_port;
2806 addr.sin6.sin6_port = port;
2809 #endif /* NETINET6 */
2812 sm_dprintf("Connecting to [%s].%d...\n",
2813 anynet_ntoa(&addr), ntohs(port));
2815 i = connect(s, (struct sockaddr *) &addr, addrlen);
2825 /* couldn't connect.... figure out why */
2828 /* if running demand-dialed connection, try again */
2829 if (DialDelay > 0 && firstconnect &&
2830 bitnset(M_DIALDELAY, mci->mci_mailer->m_flags))
2833 sm_dprintf("Connect failed (%s); trying again...\n",
2834 sm_errstring(save_errno));
2835 firstconnect = false;
2836 (void) sleep(DialDelay);
2841 sm_syslog(LOG_INFO, e->e_id,
2842 "makeconnection (%s [%s].%d (%d)) failed: %s",
2843 host, anynet_ntoa(&addr), ntohs(port),
2844 (int) addr.sa.sa_family,
2845 sm_errstring(save_errno));
2849 #endif /* NETINET6 */
2850 if (hp != NULL && hp->h_addr_list[addrno] != NULL &&
2851 (enough == 0 || curtime() < enough))
2854 sm_dprintf("Connect failed (%s); trying new address....\n",
2855 sm_errstring(save_errno));
2856 switch (addr.sa.sa_family)
2860 memmove(&addr.sin.sin_addr,
2861 hp->h_addr_list[addrno++],
2864 #endif /* NETINET */
2868 memmove(&addr.sin6.sin6_addr,
2869 hp->h_addr_list[addrno++],
2872 #endif /* NETINET6 */
2875 memmove(addr.sa.sa_data,
2876 hp->h_addr_list[addrno++],
2885 if (family == AF_INET6)
2888 sm_dprintf("Connect failed (%s); retrying with AF_INET....\n",
2889 sm_errstring(save_errno));
2892 FREEHOSTENT(hp, hs);
2896 #endif /* NETINET6 */
2897 /* couldn't open connection */
2899 /* Don't clobber an already saved errno from v4retry */
2904 sm_dprintf("Connect failed (%s)\n",
2905 sm_errstring(save_errno));
2909 mci_setstat(mci, EX_TEMPFAIL, "4.4.1", NULL);
2910 FREEHOSTENT(hp, hs);
2916 FREEHOSTENT(hp, hs);
2918 /* connection ok, put it into canonical form */
2919 mci->mci_out = NULL;
2920 if ((mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2922 SM_IO_WRONLY_B, NULL)) == NULL ||
2924 (mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2926 SM_IO_RDONLY_B, NULL)) == NULL)
2929 syserr("cannot open SMTP client channel, fd=%d", s);
2930 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2931 if (mci->mci_out != NULL)
2932 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
2938 sm_io_automode(mci->mci_out, mci->mci_in);
2940 /* set {client_flags} */
2941 if (ClientSettings[addr.sa.sa_family].d_mflags != NULL)
2943 macdefine(&mci->mci_macro, A_PERM,
2944 macid("{client_flags}"),
2945 ClientSettings[addr.sa.sa_family].d_mflags);
2948 macdefine(&mci->mci_macro, A_PERM,
2949 macid("{client_flags}"), "");
2951 /* "add" {client_flags} to bitmap */
2952 if (bitnset(D_IFNHELO, ClientSettings[addr.sa.sa_family].d_flags))
2954 /* look for just this one flag */
2955 setbitn(D_IFNHELO, d_flags);
2958 /* find out name for Interface through which we connect */
2960 if (getsockname(s, &addr.sa, &len) == 0)
2964 if (!isloopback(addr))
2968 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2969 macid("{if_addr_out}"), anynet_ntoa(&addr));
2970 (void) sm_snprintf(familystr, sizeof(familystr), "%d",
2972 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2973 macid("{if_family_out}"), familystr);
2977 macdefine(&BlankEnvelope.e_macro, A_PERM,
2978 macid("{if_addr_out}"), NULL);
2979 macdefine(&BlankEnvelope.e_macro, A_PERM,
2980 macid("{if_family_out}"), NULL);
2983 name = hostnamebyanyaddr(&addr);
2984 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2985 macid("{if_name_out}"), name);
2988 /* log connection information */
2989 sm_syslog(LOG_INFO, e->e_id,
2990 "SMTP outgoing connect on %.40s", name);
2992 if (bitnset(D_IFNHELO, d_flags))
2994 if (name[0] != '[' && strchr(name, '.') != NULL)
2995 mci->mci_heloname = newstr(name);
3000 macdefine(&BlankEnvelope.e_macro, A_PERM,
3001 macid("{if_name_out}"), NULL);
3002 macdefine(&BlankEnvelope.e_macro, A_PERM,
3003 macid("{if_addr_out}"), NULL);
3004 macdefine(&BlankEnvelope.e_macro, A_PERM,
3005 macid("{if_family_out}"), NULL);
3008 /* Use the configured HeloName as appropriate */
3009 if (HeloName != NULL && HeloName[0] != '\0')
3011 SM_FREE(mci->mci_heloname);
3012 mci->mci_heloname = newstr(HeloName);
3015 mci_setstat(mci, EX_OK, NULL, NULL);
3020 connecttimeout(ignore)
3024 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3025 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3030 longjmp(CtxConnectTimeout, 1);
3033 ** MAKECONNECTION_DS -- make a connection to a domain socket.
3036 ** mux_path -- the path of the socket to connect to.
3037 ** mci -- a pointer to the mail connection information
3038 ** structure to be filled in.
3041 ** An exit code telling whether the connection could be
3042 ** made and if not why not.
3050 makeconnection_ds(mux_path, mci)
3055 int rval, save_errno;
3056 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_ROOTOK|SFF_EXECOK;
3057 struct sockaddr_un unix_addr;
3059 /* if not safe, don't connect */
3060 rval = safefile(mux_path, RunAsUid, RunAsGid, RunAsUserName,
3061 sff, S_IRUSR|S_IWUSR, NULL);
3065 syserr("makeconnection_ds: unsafe domain socket %s",
3067 mci_setstat(mci, EX_TEMPFAIL, "4.3.5", NULL);
3072 /* prepare address structure */
3073 memset(&unix_addr, '\0', sizeof(unix_addr));
3074 unix_addr.sun_family = AF_UNIX;
3076 if (strlen(mux_path) >= sizeof(unix_addr.sun_path))
3078 syserr("makeconnection_ds: domain socket name %s too long",
3081 /* XXX why TEMPFAIL but 5.x.y ? */
3082 mci_setstat(mci, EX_TEMPFAIL, "5.3.5", NULL);
3083 errno = ENAMETOOLONG;
3084 return EX_UNAVAILABLE;
3086 (void) sm_strlcpy(unix_addr.sun_path, mux_path,
3087 sizeof(unix_addr.sun_path));
3089 /* initialize domain socket */
3090 sock = socket(AF_UNIX, SOCK_STREAM, 0);
3094 syserr("makeconnection_ds: could not create domain socket %s",
3096 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
3101 /* connect to server */
3102 if (connect(sock, (struct sockaddr *) &unix_addr,
3103 sizeof(unix_addr)) == -1)
3106 syserr("Could not connect to socket %s", mux_path);
3107 mci_setstat(mci, EX_TEMPFAIL, "4.4.1", NULL);
3113 /* connection ok, put it into canonical form */
3114 mci->mci_out = NULL;
3115 if ((mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
3116 (void *) &sock, SM_IO_WRONLY_B, NULL))
3118 || (sock = dup(sock)) < 0 ||
3119 (mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
3120 (void *) &sock, SM_IO_RDONLY_B, NULL))
3124 syserr("cannot open SMTP client channel, fd=%d", sock);
3125 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
3126 if (mci->mci_out != NULL)
3127 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
3132 sm_io_automode(mci->mci_out, mci->mci_in);
3134 mci_setstat(mci, EX_OK, NULL, NULL);
3138 #endif /* NETUNIX */
3140 ** SHUTDOWN_DAEMON -- Performs a clean shutdown of the daemon
3149 ** closes control socket, exits.
3158 sm_allsignals(true);
3160 reason = ShutdownRequest;
3161 ShutdownRequest = NULL;
3165 sm_syslog(LOG_INFO, CurEnv->e_id, "stopping daemon, reason=%s",
3166 reason == NULL ? "implicit call" : reason);
3169 closecontrolsocket(true);
3174 for (i = 0; i < NDaemons; i++)
3176 if (Daemons[i].d_socket >= 0)
3178 (void) close(Daemons[i].d_socket);
3179 Daemons[i].d_socket = -1;
3182 /* Remove named sockets */
3183 if (Daemons[i].d_addr.sa.sa_family == AF_UNIX)
3186 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_MUSTOWN|SFF_EXECOK|SFF_CREAT;
3188 /* if not safe, don't use it */
3189 rval = safefile(Daemons[i].d_addr.sunix.sun_path,
3192 S_IRUSR|S_IWUSR, NULL);
3194 unlink(Daemons[i].d_addr.sunix.sun_path) < 0)
3196 sm_syslog(LOG_WARNING, NOQID,
3197 "Could not remove daemon %s socket: %s: %s",
3199 Daemons[i].d_addr.sunix.sun_path,
3200 sm_errstring(errno));
3203 #endif /* NETUNIX */
3207 finis(false, true, EX_OK);
3210 ** RESTART_DAEMON -- Performs a clean restart of the daemon
3219 ** restarts the daemon or exits if restart fails.
3222 /* Make a non-DFL/IGN signal a noop */
3223 #define SM_NOOP_SIGNAL(sig, old) \
3226 (old) = sm_signal((sig), sm_signal_noop); \
3227 if ((old) == SIG_IGN || (old) == SIG_DFL) \
3228 (void) sm_signal((sig), (old)); \
3237 sigfunc_t ignore, oalrm, ousr1;
3238 extern int DtableSize;
3240 /* clear the events to turn off SIGALRMs */
3242 sm_allsignals(true);
3244 reason = RestartRequest;
3245 RestartRequest = NULL;
3248 if (SaveArgv[0][0] != '/')
3251 sm_syslog(LOG_INFO, NOQID,
3252 "could not restart: need full path");
3253 finis(false, true, EX_OSFILE);
3257 sm_syslog(LOG_INFO, NOQID, "restarting %s due to %s",
3259 reason == NULL ? "implicit call" : reason);
3261 closecontrolsocket(true);
3263 cleanup_shm(DaemonPid == getpid());
3266 /* close locked pid file */
3267 close_sendmail_pid();
3270 ** Want to drop to the user who started the process in all cases
3271 ** *but* when running as "smmsp" for the clientmqueue queue run
3272 ** daemon. In that case, UseMSP will be true, RunAsUid should not
3273 ** be root, and RealUid should be either 0 or RunAsUid.
3276 drop = !(UseMSP && RunAsUid != 0 &&
3277 (RealUid == 0 || RealUid == RunAsUid));
3279 if (drop_privileges(drop) != EX_OK)
3282 sm_syslog(LOG_ALERT, NOQID,
3283 "could not drop privileges: %s",
3284 sm_errstring(errno));
3285 finis(false, true, EX_OSERR);
3289 sm_close_on_exec(STDERR_FILENO + 1, DtableSize);
3292 ** Need to allow signals before execve() to make them "harmless".
3293 ** However, the default action can be "terminate", so it isn't
3294 ** really harmless. Setting signals to IGN will cause them to be
3295 ** ignored in the new process to, so that isn't a good alternative.
3298 SM_NOOP_SIGNAL(SIGALRM, oalrm);
3299 SM_NOOP_SIGNAL(SIGCHLD, ignore);
3300 SM_NOOP_SIGNAL(SIGHUP, ignore);
3301 SM_NOOP_SIGNAL(SIGINT, ignore);
3302 SM_NOOP_SIGNAL(SIGPIPE, ignore);
3303 SM_NOOP_SIGNAL(SIGTERM, ignore);
3305 SM_NOOP_SIGNAL(SIGUSR1, ousr1);
3308 /* Turn back on signals */
3309 sm_allsignals(false);
3311 (void) execve(SaveArgv[0], (ARGV_T) SaveArgv, (ARGV_T) ExternalEnviron);
3314 /* block signals again and restore needed signals */
3315 sm_allsignals(true);
3317 /* For finis() events */
3318 (void) sm_signal(SIGALRM, oalrm);
3321 /* For debugging finis() */
3322 (void) sm_signal(SIGUSR1, ousr1);
3327 sm_syslog(LOG_ALERT, NOQID, "could not exec %s: %s",
3328 SaveArgv[0], sm_errstring(errno));
3329 finis(false, true, EX_OSFILE);
3333 ** MYHOSTNAME -- return the name of this host.
3336 ** hostbuf -- a place to return the name of this host.
3337 ** size -- the size of hostbuf.
3340 ** A list of aliases for this host.
3343 ** Adds numeric codes to $=w.
3347 myhostname(hostbuf, size)
3351 register struct hostent *hp;
3353 if (gethostname(hostbuf, size) < 0 || hostbuf[0] == '\0')
3354 (void) sm_strlcpy(hostbuf, "localhost", size);
3355 hp = sm_gethostbyname(hostbuf, InetMode);
3356 #if NETINET && NETINET6
3357 if (hp == NULL && InetMode == AF_INET6)
3360 ** It's possible that this IPv6 enabled machine doesn't
3361 ** actually have any IPv6 interfaces and, therefore, no
3362 ** IPv6 addresses. Fall back to AF_INET.
3365 hp = sm_gethostbyname(hostbuf, AF_INET);
3367 #endif /* NETINET && NETINET6 */
3370 if (strchr(hp->h_name, '.') != NULL || strchr(hostbuf, '.') == NULL)
3371 (void) cleanstrcpy(hostbuf, hp->h_name, size);
3374 if (strchr(hostbuf, '.') == NULL)
3378 domainname = ni_propval("/locations", NULL, "resolver",
3380 if (domainname != NULL &&
3381 strlen(domainname) + strlen(hostbuf) + 1 < size)
3382 (void) sm_strlcat2(hostbuf, ".", domainname, size);
3384 #endif /* NETINFO */
3387 ** If there is still no dot in the name, try looking for a
3391 if (strchr(hostbuf, '.') == NULL)
3395 for (ha = hp->h_aliases; ha != NULL && *ha != NULL; ha++)
3397 if (strchr(*ha, '.') != NULL)
3399 (void) cleanstrcpy(hostbuf, *ha, size - 1);
3400 hostbuf[size - 1] = '\0';
3407 ** If _still_ no dot, wait for a while and try again -- it is
3408 ** possible that some service is starting up. This can result
3409 ** in excessive delays if the system is badly configured, but
3410 ** there really isn't a way around that, particularly given that
3411 ** the config file hasn't been read at this point.
3412 ** All in all, a bit of a mess.
3415 if (strchr(hostbuf, '.') == NULL &&
3416 getcanonname(hostbuf, size, true, NULL) == HOST_NOTFOUND)
3418 sm_syslog(LocalDaemon ? LOG_WARNING : LOG_CRIT, NOQID,
3419 "My unqualified host name (%s) unknown; sleeping for retry",
3421 message("My unqualified host name (%s) unknown; sleeping for retry",
3424 if (getcanonname(hostbuf, size, true, NULL) == HOST_NOTFOUND)
3426 sm_syslog(LocalDaemon ? LOG_WARNING : LOG_ALERT, NOQID,
3427 "unable to qualify my own domain name (%s) -- using short name",
3429 message("WARNING: unable to qualify my own domain name (%s) -- using short name",
3436 ** ADDRCMP -- compare two host addresses
3439 ** hp -- hostent structure for the first address
3440 ** ha -- actual first address
3441 ** sa -- second address
3444 ** 0 -- if ha and sa match
3445 ** else -- they don't match
3458 switch (sa->sa.sa_family)
3462 if (hp->h_addrtype == AF_INET)
3463 return memcmp(ha, (char *) &sa->sin.sin_addr, INADDRSZ);
3469 a = (unsigned char *) &sa->sin6.sin6_addr;
3471 /* Straight binary comparison */
3472 if (hp->h_addrtype == AF_INET6)
3473 return memcmp(ha, a, IN6ADDRSZ);
3475 /* If IPv4-mapped IPv6 address, compare the IPv4 section */
3476 if (hp->h_addrtype == AF_INET &&
3477 IN6_IS_ADDR_V4MAPPED(&sa->sin6.sin6_addr))
3478 return memcmp(a + IN6ADDRSZ - INADDRSZ, ha, INADDRSZ);
3480 #endif /* NETINET6 */
3485 ** GETAUTHINFO -- get the real host name associated with a file descriptor
3487 ** Uses RFC1413 protocol to try to get info from the other end.
3490 ** fd -- the descriptor
3491 ** may_be_forged -- an outage that is set to true if the
3492 ** forward lookup of RealHostName does not match
3493 ** RealHostAddr; set to false if they do match.
3496 ** The user@host information associated with this descriptor.
3499 static jmp_buf CtxAuthTimeout;
3506 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3507 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3512 longjmp(CtxAuthTimeout, 1);
3516 getauthinfo(fd, may_be_forged)
3518 bool *may_be_forged;
3520 unsigned short SM_NONVOLATILE port = 0;
3521 SOCKADDR_LEN_T falen;
3522 register char *volatile p = NULL;
3524 SOCKADDR_LEN_T lalen;
3525 #ifndef NO_GETSERVBYNAME
3526 register struct servent *sp;
3528 static unsigned short port4 = 0;
3531 static unsigned short port6 = 0;
3533 #endif /* ! NO_GETSERVBYNAME */
3540 char *ostype = NULL;
3542 char ibuf[MAXNAME + 1];
3543 static char hbuf[MAXNAME + MAXAUTHINFO + 11];
3545 *may_be_forged = true;
3546 falen = sizeof(RealHostAddr);
3547 if (isatty(fd) || (i = getpeername(fd, &RealHostAddr.sa, &falen)) < 0 ||
3548 falen <= 0 || RealHostAddr.sa.sa_family == 0)
3553 ** ENOTSOCK is OK: bail on anything else, but reset
3554 ** errno in this case, so a mis-report doesn't
3558 if (errno != ENOTSOCK)
3563 *may_be_forged = false;
3564 (void) sm_strlcpyn(hbuf, sizeof(hbuf), 2, RealUserName,
3567 sm_dprintf("getauthinfo: %s\n", hbuf);
3571 if (RealHostName == NULL)
3573 /* translate that to a host name */
3574 RealHostName = newstr(hostnamebyanyaddr(&RealHostAddr));
3575 if (strlen(RealHostName) > MAXNAME)
3576 RealHostName[MAXNAME] = '\0'; /* XXX - 1 ? */
3579 /* cross check RealHostName with forward DNS lookup */
3580 if (anynet_ntoa(&RealHostAddr)[0] == '[' ||
3581 RealHostName[0] == '[')
3582 *may_be_forged = false;
3587 family = RealHostAddr.sa.sa_family;
3588 #if NETINET6 && NEEDSGETIPNODE
3590 ** If RealHostAddr is an IPv6 connection with an
3591 ** IPv4-mapped address, we need RealHostName's IPv4
3592 ** address(es) for addrcmp() to compare against
3595 ** Actually, we only need to do this for systems
3596 ** which NEEDSGETIPNODE since the real getipnodebyname()
3597 ** already does V4MAPPED address via the AI_V4MAPPEDCFG
3598 ** flag. A better fix to this problem is to add this
3599 ** functionality to our stub getipnodebyname().
3602 if (family == AF_INET6 &&
3603 IN6_IS_ADDR_V4MAPPED(&RealHostAddr.sin6.sin6_addr))
3605 #endif /* NETINET6 && NEEDSGETIPNODE */
3607 /* try to match the reverse against the forward lookup */
3608 hp = sm_gethostbyname(RealHostName, family);
3611 for (ha = hp->h_addr_list; *ha != NULL; ha++)
3613 if (addrcmp(hp, *ha, &RealHostAddr) == 0)
3615 *may_be_forged = false;
3619 FREEHOSTENT(hp, NULL);
3623 if (TimeOuts.to_ident == 0)
3627 switch (RealHostAddr.sa.sa_family)
3631 if (getsockname(fd, &la.sa, &lalen) < 0 ||
3633 la.sa.sa_family != AF_INET)
3638 port = RealHostAddr.sin.sin_port;
3640 /* create ident query */
3641 (void) sm_snprintf(ibuf, sizeof(ibuf), "%d,%d\r\n",
3642 ntohs(RealHostAddr.sin.sin_port),
3643 ntohs(la.sin.sin_port));
3645 /* create local address */
3646 la.sin.sin_port = 0;
3648 /* create foreign address */
3649 # ifdef NO_GETSERVBYNAME
3650 RealHostAddr.sin.sin_port = htons(113);
3651 # else /* NO_GETSERVBYNAME */
3654 ** getservbyname() consumes about 5% of the time
3655 ** when receiving a small message (almost all of the time
3656 ** spent in this routine).
3657 ** Hence we store the port in a static variable
3658 ** to save this time.
3659 ** The portnumber shouldn't change very often...
3660 ** This code makes the assumption that the port number
3666 sp = getservbyname("auth", "tcp");
3672 RealHostAddr.sin.sin_port = port4;
3674 # endif /* NO_GETSERVBYNAME */
3675 #endif /* NETINET */
3679 if (getsockname(fd, &la.sa, &lalen) < 0 ||
3681 la.sa.sa_family != AF_INET6)
3686 port = RealHostAddr.sin6.sin6_port;
3688 /* create ident query */
3689 (void) sm_snprintf(ibuf, sizeof(ibuf), "%d,%d\r\n",
3690 ntohs(RealHostAddr.sin6.sin6_port),
3691 ntohs(la.sin6.sin6_port));
3693 /* create local address */
3694 la.sin6.sin6_port = 0;
3696 /* create foreign address */
3697 # ifdef NO_GETSERVBYNAME
3698 RealHostAddr.sin6.sin6_port = htons(113);
3699 # else /* NO_GETSERVBYNAME */
3702 sp = getservbyname("auth", "tcp");
3708 RealHostAddr.sin6.sin6_port = port6;
3710 # endif /* NO_GETSERVBYNAME */
3711 #endif /* NETINET6 */
3718 if (setjmp(CtxAuthTimeout) != 0)
3725 /* put a timeout around the whole thing */
3726 ev = sm_setevent(TimeOuts.to_ident, authtimeout, 0);
3728 /* connect to foreign IDENT server using same address as SMTP socket */
3729 s = socket(la.sa.sa_family, SOCK_STREAM, 0);
3735 if (bind(s, &la.sa, lalen) < 0 ||
3736 connect(s, &RealHostAddr.sa, lalen) < 0)
3740 sm_dprintf("getauthinfo: sent %s", ibuf);
3743 if (write(s, ibuf, strlen(ibuf)) < 0)
3748 nleft = sizeof(ibuf) - 1;
3749 while ((i = read(s, p, nleft)) > 0)
3756 if ((s = strchr(ibuf, '\n')) != NULL)
3770 if (i < 0 || p == &ibuf[0])
3773 if (p >= &ibuf[2] && *--p == '\n' && *--p == '\r')
3778 sm_dprintf("getauthinfo: got %s\n", ibuf);
3781 p = strchr(ibuf, ':');
3784 /* malformed response */
3787 while (isascii(*++p) && isspace(*p))
3789 if (sm_strncasecmp(p, "userid", 6) != 0)
3791 /* presumably an error string */
3795 while (SM_ISSPACE(*p))
3799 /* either useridxx or malformed response */
3803 /* p now points to the OSTYPE field */
3804 while (SM_ISSPACE(*p))
3810 /* malformed response */
3818 charset = strchr(ostype, ',');
3819 if (charset != NULL)
3823 /* 1413 says don't do this -- but it's broken otherwise */
3824 while (isascii(*++p) && isspace(*p))
3827 /* p now points to the authenticated name -- copy carefully */
3828 if (sm_strncasecmp(ostype, "other", 5) == 0 &&
3829 (ostype[5] == ' ' || ostype[5] == '\0'))
3831 (void) sm_strlcpy(hbuf, "IDENT:", sizeof(hbuf));
3832 cleanstrcpy(&hbuf[6], p, MAXAUTHINFO);
3835 cleanstrcpy(hbuf, p, MAXAUTHINFO);
3837 (void) sm_strlcpyn(&hbuf[len], sizeof(hbuf) - len, 2, "@",
3838 RealHostName == NULL ? "localhost" : RealHostName);
3846 /* put back the original incoming port */
3847 switch (RealHostAddr.sa.sa_family)
3852 RealHostAddr.sin.sin_port = port;
3854 #endif /* NETINET */
3859 RealHostAddr.sin6.sin6_port = port;
3861 #endif /* NETINET6 */
3864 if (RealHostName == NULL)
3867 sm_dprintf("getauthinfo: NULL\n");
3870 (void) sm_strlcpy(hbuf, RealHostName, sizeof(hbuf));
3874 # ifndef GET_IPOPT_DST
3875 # define GET_IPOPT_DST(dst) (dst)
3878 ** Extract IP source routing information.
3880 ** Format of output for a connection from site a through b
3882 ** loose: @site-c@site-b:site-a
3883 ** strict: !@site-c@site-b:site-a
3885 ** o - pointer within ipopt_list structure.
3886 ** q - pointer within ls/ss rr route data
3887 ** p - pointer to hbuf
3890 if (RealHostAddr.sa.sa_family == AF_INET)
3892 SOCKOPT_LEN_T ipoptlen;
3897 struct IPOPTION ipopt;
3899 ipoptlen = sizeof(ipopt);
3900 if (getsockopt(fd, IPPROTO_IP, IP_OPTIONS,
3901 (char *) &ipopt, &ipoptlen) < 0)
3905 o = (unsigned char *) ipopt.IP_LIST;
3906 while (o != NULL && o < (unsigned char *) &ipopt + ipoptlen)
3922 ** o[0] is the option type (loose/strict).
3923 ** o[1] is the length of this option,
3924 ** including option type and
3926 ** o[2] is the pointer into the route
3928 ** o[3] begins the route data.
3931 p = &hbuf[strlen(hbuf)];
3932 l = sizeof(hbuf) - (hbuf - p) - 6;
3933 (void) sm_snprintf(p, SPACELEFT(hbuf, p),
3935 *o == IPOPT_SSRR ? "!" : "",
3936 l > 240 ? 120 : l / 2,
3937 inet_ntoa(GET_IPOPT_DST(ipopt.IP_DST)));
3942 j = o[1] / sizeof(struct in_addr) - 1;
3944 /* q skips length and router pointer to data */
3946 for ( ; j >= 0; j--)
3948 struct in_addr addr;
3950 memcpy(&addr, q, sizeof(addr));
3951 (void) sm_snprintf(p,
3961 q += sizeof(struct in_addr);
3967 /* Skip over option */
3972 (void) sm_snprintf(p, SPACELEFT(hbuf, p), "]");
3977 #endif /* IP_SRCROUTE */
3978 if (RealHostName != NULL && RealHostName[0] != '[')
3980 p = &hbuf[strlen(hbuf)];
3981 (void) sm_snprintf(p, SPACELEFT(hbuf, p), " [%.100s]",
3982 anynet_ntoa(&RealHostAddr));
3986 p = &hbuf[strlen(hbuf)];
3987 (void) sm_strlcpy(p, " (may be forged)", SPACELEFT(hbuf, p));
3988 macdefine(&BlankEnvelope.e_macro, A_PERM,
3989 macid("{client_resolve}"), "FORGED");
3994 #endif /* IP_SRCROUTE */
3996 /* put back the original incoming port */
3997 switch (RealHostAddr.sa.sa_family)
4002 RealHostAddr.sin.sin_port = port;
4004 #endif /* NETINET */
4009 RealHostAddr.sin6.sin6_port = port;
4011 #endif /* NETINET6 */
4015 sm_dprintf("getauthinfo: %s\n", hbuf);
4019 ** HOST_MAP_LOOKUP -- turn a hostname into canonical form
4022 ** map -- a pointer to this map.
4023 ** name -- the (presumably unqualified) hostname.
4024 ** av -- unused -- for compatibility with other mapping
4026 ** statp -- an exit status (out parameter) -- set to
4027 ** EX_TEMPFAIL if the name server is unavailable.
4030 ** The mapping, if found.
4031 ** NULL if no mapping found.
4034 ** Looks up the host specified in hbuf. If it is not
4035 ** the canonical name for that host, return the canonical
4036 ** name (unless MF_MATCHONLY is set, which will cause the
4037 ** status only to be returned).
4041 host_map_lookup(map, name, av, statp)
4047 register struct hostent *hp;
4049 struct in_addr in_addr;
4052 struct in6_addr in6_addr;
4054 char *cp, *ans = NULL;
4058 time_t SM_NONVOLATILE retrans = 0;
4059 int SM_NONVOLATILE retry = 0;
4061 char hbuf[MAXNAME + 1];
4064 ** See if we have already looked up this name. If so, just
4065 ** return it (unless expired).
4069 s = stab(name, ST_NAMECANON, ST_ENTER);
4070 if (bitset(NCF_VALID, s->s_namecanon.nc_flags) &&
4071 s->s_namecanon.nc_exp >= now)
4074 sm_dprintf("host_map_lookup(%s) => CACHE %s\n",
4076 s->s_namecanon.nc_cname == NULL
4078 : s->s_namecanon.nc_cname);
4079 errno = s->s_namecanon.nc_errno;
4080 SM_SET_H_ERRNO(s->s_namecanon.nc_herrno);
4081 *statp = s->s_namecanon.nc_stat;
4082 if (*statp == EX_TEMPFAIL)
4084 CurEnv->e_status = "4.4.3";
4085 message("851 %s: Name server timeout",
4086 shortenstring(name, 33));
4088 if (*statp != EX_OK)
4090 if (s->s_namecanon.nc_cname == NULL)
4092 syserr("host_map_lookup(%s): bogus NULL cache entry, errno=%d, h_errno=%d",
4094 s->s_namecanon.nc_errno,
4095 s->s_namecanon.nc_herrno);
4098 if (bitset(NCF_SECURE, s->s_namecanon.nc_flags))
4099 map->map_mflags |= MF_SECURE;
4101 map->map_mflags &= ~MF_SECURE;
4102 if (bitset(MF_MATCHONLY, map->map_mflags))
4103 cp = map_rewrite(map, name, strlen(name), NULL);
4105 cp = map_rewrite(map,
4106 s->s_namecanon.nc_cname,
4107 strlen(s->s_namecanon.nc_cname),
4113 ** If we are running without a regular network connection (usually
4114 ** dial-on-demand) and we are just queueing, we want to avoid DNS
4115 ** lookups because those could try to connect to a server.
4118 if (CurEnv->e_sendmode == SM_DEFER &&
4119 bitset(MF_DEFER, map->map_mflags))
4122 sm_dprintf("host_map_lookup(%s) => DEFERRED\n", name);
4123 *statp = EX_TEMPFAIL;
4128 ** If first character is a bracket, then it is an address
4129 ** lookup. Address is copied into a temporary buffer to
4130 ** strip the brackets and to preserve name if address is
4135 sm_dprintf("host_map_lookup(%s) => ", name);
4137 if (map->map_timeout > 0)
4139 retrans = _res.retrans;
4140 _res.retrans = map->map_timeout;
4142 if (map->map_retry > 0)
4145 _res.retry = map->map_retry;
4147 #endif /* NAMED_BIND */
4149 /* set default TTL */
4150 s->s_namecanon.nc_exp = now + SM_DEFAULT_TTL;
4155 (void) sm_strlcpy(hbuf, name, sizeof(hbuf));
4157 r = getcanonname(hbuf, sizeof(hbuf) - 1, !HasWildcardMX, &ttl);
4158 if (r != HOST_NOTFOUND)
4162 s->s_namecanon.nc_exp = now + SM_MIN(ttl,
4165 if (HOST_SECURE == r)
4167 s->s_namecanon.nc_flags |= NCF_SECURE;
4168 map->map_mflags |= MF_SECURE;
4172 s->s_namecanon.nc_flags &= ~NCF_SECURE;
4173 map->map_mflags &= ~MF_SECURE;
4179 if ((cp = strchr(name, ']')) == NULL)
4182 sm_dprintf("FAILED\n");
4189 /* should this be considered secure? */
4190 map->map_mflags &= ~MF_SECURE;
4192 if ((in_addr.s_addr = inet_addr(&name[1])) != INADDR_NONE)
4193 hp = sm_gethostbyaddr((char *)&in_addr,
4195 #endif /* NETINET */
4198 anynet_pton(AF_INET6, &name[1], &in6_addr) == 1)
4199 hp = sm_gethostbyaddr((char *)&in6_addr,
4200 IN6ADDRSZ, AF_INET6);
4201 #endif /* NETINET6 */
4206 /* found a match -- copy out */
4207 ans = denlstring((char *) hp->h_name, true, true);
4209 if (ans == hp->h_name)
4211 static char n[MAXNAME + 1];
4213 /* hp->h_name is about to disappear */
4214 (void) sm_strlcpy(n, ans, sizeof(n));
4217 FREEHOSTENT(hp, NULL);
4218 #endif /* NETINET6 */
4222 if (map->map_timeout > 0)
4223 _res.retrans = retrans;
4224 if (map->map_retry > 0)
4226 #endif /* NAMED_BIND */
4228 s->s_namecanon.nc_flags |= NCF_VALID; /* will be soon */
4230 /* Found an answer */
4233 s->s_namecanon.nc_stat = *statp = EX_OK;
4234 if (s->s_namecanon.nc_cname != NULL)
4235 sm_free(s->s_namecanon.nc_cname);
4236 s->s_namecanon.nc_cname = sm_strdup_x(ans);
4237 if (bitset(MF_MATCHONLY, map->map_mflags))
4238 cp = map_rewrite(map, name, strlen(name), NULL);
4240 cp = map_rewrite(map, ans, strlen(ans), av);
4242 sm_dprintf("FOUND %s\n", ans);
4247 /* No match found */
4248 s->s_namecanon.nc_errno = errno;
4250 s->s_namecanon.nc_herrno = h_errno;
4252 sm_dprintf("FAIL (%d)\n", h_errno);
4258 CurEnv->e_status = "4.4.3";
4259 message("851 %s: Name server timeout",
4260 shortenstring(name, 33));
4262 *statp = EX_TEMPFAIL;
4265 case HOST_NOT_FOUND:
4271 *statp = EX_SOFTWARE;
4275 *statp = EX_UNAVAILABLE;
4278 #else /* NAMED_BIND */
4280 sm_dprintf("FAIL\n");
4282 #endif /* NAMED_BIND */
4283 s->s_namecanon.nc_stat = *statp;
4287 ** HOST_MAP_INIT -- initialize host class structures
4290 ** map -- a pointer to this map.
4291 ** args -- argument string.
4298 host_map_init(map, args)
4302 register char *p = args;
4306 while (SM_ISSPACE(*p))
4317 map->map_tapp = ++p;
4321 map->map_mflags |= MF_MATCHONLY;
4325 map->map_mflags |= MF_NODEFER;
4328 case 'S': /* only for consistency */
4329 map->map_spacesub = *++p;
4333 map->map_mflags |= MF_DEFER;
4340 while (isascii(*++p) && isspace(*p))
4345 map->map_timeout = convtime(p, 's');
4352 while (isascii(*++p) && isspace(*p))
4354 map->map_retry = atoi(p);
4357 while (*p != '\0' && !(SM_ISSPACE(*p)))
4362 if (map->map_app != NULL)
4363 map->map_app = newstr(map->map_app);
4364 if (map->map_tapp != NULL)
4365 map->map_tapp = newstr(map->map_tapp);
4371 ** ANYNET_NTOP -- convert an IPv6 network address to printable form.
4374 ** s6a -- a pointer to an in6_addr structure.
4375 ** dst -- buffer to store result in
4376 ** dst_len -- size of dst buffer
4379 ** A printable version of that structure.
4383 anynet_ntop(s6a, dst, dst_len)
4384 struct in6_addr *s6a;
4390 if (IN6_IS_ADDR_V4MAPPED(s6a))
4391 ap = (char *) inet_ntop(AF_INET,
4392 &s6a->s6_addr[IN6ADDRSZ - INADDRSZ],
4399 /* Save pointer to beginning of string */
4402 /* Add IPv6: protocol tag */
4403 sz = sm_strlcpy(dst, "IPv6:", dst_len);
4408 if (UseCompressedIPv6Addresses)
4409 ap = (char *) inet_ntop(AF_INET6, s6a, dst, dst_len);
4411 ap = sm_inet6_ntop(s6a, dst, dst_len);
4412 /* Restore pointer to beginning of string */
4420 ** ANYNET_PTON -- convert printed form to network address.
4422 ** Wrapper for inet_pton() which handles IPv6: labels.
4425 ** family -- address family
4427 ** dst -- destination address structure
4430 ** 1 if the address was valid
4431 ** 0 if the address wasn't parsable
4436 anynet_pton(family, src, dst)
4441 if (family == AF_INET6 && sm_strncasecmp(src, "IPv6:", 5) == 0)
4443 return inet_pton(family, src, dst);
4445 #endif /* NETINET6 */
4447 ** ANYNET_NTOA -- convert a network address to printable form.
4450 ** sap -- a pointer to a sockaddr structure.
4453 ** A printable version of that sockaddr.
4456 #ifdef USE_SOCK_STREAM
4459 # include <net/if_dl.h>
4464 register SOCKADDR *sap;
4469 static char buf[100];
4471 /* check for null/zero family */
4474 if (sap->sa.sa_family == 0)
4477 switch (sap->sa.sa_family)
4481 if (sap->sunix.sun_path[0] != '\0')
4482 (void) sm_snprintf(buf, sizeof(buf), "[UNIX: %.64s]",
4483 sap->sunix.sun_path);
4485 (void) sm_strlcpy(buf, "[UNIX: localhost]", sizeof(buf));
4487 # endif /* NETUNIX */
4491 return (char *) inet_ntoa(sap->sin.sin_addr);
4496 ap = anynet_ntop(&sap->sin6.sin6_addr, buf, sizeof(buf));
4500 # endif /* NETINET6 */
4504 (void) sm_snprintf(buf, sizeof(buf), "[LINK: %s]",
4505 link_ntoa((struct sockaddr_dl *) &sap->sa));
4507 # endif /* NETLINK */
4509 /* this case is needed when nothing is #defined */
4510 /* in order to keep the switch syntactically correct */
4514 /* unknown family -- just dump bytes */
4515 (void) sm_snprintf(buf, sizeof(buf), "Family %d: ", sap->sa.sa_family);
4516 bp = &buf[strlen(buf)];
4517 ap = sap->sa.sa_data;
4518 for (l = sizeof(sap->sa.sa_data); --l >= 0; )
4520 (void) sm_snprintf(bp, SPACELEFT(buf, bp), "%02x:",
4528 ** HOSTNAMEBYANYADDR -- return name of host based on address
4531 ** sap -- SOCKADDR pointer
4534 ** text representation of host name.
4541 hostnamebyanyaddr(sap)
4542 register SOCKADDR *sap;
4544 register struct hostent *hp;
4549 struct in6_addr in6_addr;
4550 # endif /* NETINET6 */
4553 /* shorten name server timeout to avoid higher level timeouts */
4554 saveretry = _res.retry;
4555 if (_res.retry * _res.retrans > 20)
4556 _res.retry = 20 / _res.retrans;
4557 if (_res.retry == 0)
4559 # endif /* NAMED_BIND */
4561 switch (sap->sa.sa_family)
4565 hp = sm_gethostbyaddr((char *) &sap->sin.sin_addr,
4568 # endif /* NETINET */
4572 hp = sm_gethostbyaddr((char *) &sap->sin6.sin6_addr,
4573 IN6ADDRSZ, AF_INET6);
4575 # endif /* NETINET6 */
4579 hp = sm_gethostbyaddr((char *) &sap->siso.siso_addr,
4580 sizeof(sap->siso.siso_addr), AF_ISO);
4582 # endif /* NETISO */
4588 # endif /* NETUNIX */
4591 hp = sm_gethostbyaddr(sap->sa.sa_data, sizeof(sap->sa.sa_data),
4597 _res.retry = saveretry;
4600 # if NETINET || NETINET6
4601 if (hp != NULL && hp->h_name[0] != '['
4603 && inet_pton(AF_INET6, hp->h_name, &in6_addr) != 1
4604 # endif /* NETINET6 */
4606 && inet_addr(hp->h_name) == INADDR_NONE
4612 name = denlstring((char *) hp->h_name, true, true);
4614 if (name == hp->h_name)
4616 static char n[MAXNAME + 1];
4618 /* Copy the string, hp->h_name is about to disappear */
4619 (void) sm_strlcpy(n, name, sizeof(n));
4622 FREEHOSTENT(hp, NULL);
4623 # endif /* NETINET6 */
4626 # endif /* NETINET || NETINET6 */
4628 FREEHOSTENT(hp, NULL);
4631 if (sap->sa.sa_family == AF_UNIX && sap->sunix.sun_path[0] == '\0')
4635 static char buf[203];
4637 (void) sm_snprintf(buf, sizeof(buf), "[%.200s]",
4642 #endif /* USE_SOCK_STREAM */