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
21 #endif /* defined(SOCK_STREAM) || defined(__GNU_LIBRARY__) */
23 #if defined(USE_SOCK_STREAM)
24 # if NETINET || NETINET6
25 # include <arpa/inet.h>
26 # endif /* NETINET || NETINET6 */
29 # define NO_DATA NO_ADDRESS
30 # endif /* ! NO_DATA */
31 # endif /* NAMED_BIND */
32 #endif /* defined(USE_SOCK_STREAM) */
35 # include <openssl/rand.h>
40 #if IP_SRCROUTE && NETINET
41 # include <netinet/in_systm.h>
42 # include <netinet/ip.h>
44 # include <netinet/in.h>
46 # define IPOPTION ip_opts
47 # define IP_LIST ip_opts
48 # define IP_DST ip_dst
49 # endif /* ! IPOPTION */
51 # include <netinet/ip_var.h>
53 # define IPOPTION ipoption
54 # define IP_LIST ipopt_list
55 # define IP_DST ipopt_dst
56 # endif /* ! IPOPTION */
57 # endif /* HAS_IN_H */
58 #endif /* IP_SRCROUTE && NETINET */
65 static void connecttimeout __P((int));
66 static int opendaemonsocket __P((DAEMON_T *, bool));
67 static unsigned short setupdaemon __P((SOCKADDR *));
68 static void getrequests_checkdiskspace __P((ENVELOPE *e));
69 static void setsockaddroptions __P((char *, DAEMON_T *));
70 static void printdaemonflags __P((DAEMON_T *));
71 static int addr_family __P((char *));
72 static int addrcmp __P((struct hostent *, char *, SOCKADDR *));
73 static void authtimeout __P((int));
76 ** DAEMON.C -- routines to use when running as a daemon.
78 ** This entire file is highly dependent on the 4.2 BSD
79 ** interprocess communication primitives. No attempt has
80 ** been made to make this file portable to Version 7,
81 ** Version 6, MPX files, etc. If you should try such a
82 ** thing yourself, I recommend chucking the entire file
83 ** and starting from scratch. Basic semantics are:
86 ** Opens a port and initiates a connection.
87 ** Returns in a child. Must set InChannel and
88 ** OutChannel appropriately.
90 ** Close any open files associated with getting
91 ** the connection; this is used when running the queue,
92 ** etc., to avoid having extra file descriptors during
93 ** the queue run and to avoid confusing the network
94 ** code (if it cares).
95 ** makeconnection(host, port, mci, e, enough)
96 ** Make a connection to the named host on the given
97 ** port. Returns zero on success, else an exit status
98 ** describing the error.
99 ** host_map_lookup(map, hbuf, avp, pstat)
100 ** Convert the entry in hbuf into a canonical form.
103 static int NDaemons = 0; /* actual number of daemons */
105 static time_t NextDiskSpaceCheck = 0;
108 ** GETREQUESTS -- open mail IPC port and get requests.
111 ** e -- the current envelope.
117 ** Waits until some interesting activity occurs. When
118 ** it does, a child is created to process it, and the
119 ** parent waits for completion. Return from this
120 ** routine is always in the child. The file pointers
121 ** "InChannel" and "OutChannel" should be set to point
122 ** to the communication channel.
123 ** May restart persistent queue runners if they have ended
132 int idx, curdaemon = -1;
133 int i, olddaemon = 0;
137 char status[MAXLINE];
139 SOCKADDR_LEN_T len = sizeof(sa);
140 #if _FFR_QUEUE_RUN_PARANOIA
142 #endif /* _FFR_QUEUE_RUN_PARANOIA */
144 extern int ControlSocket;
145 # endif /* NETUNIX */
146 extern ENVELOPE BlankEnvelope;
149 /* initialize data for function that generates queue ids */
151 for (idx = 0; idx < NDaemons; idx++)
153 Daemons[idx].d_port = setupdaemon(&(Daemons[idx].d_addr));
154 Daemons[idx].d_firsttime = true;
155 Daemons[idx].d_refuse_connections_until = (time_t) 0;
159 ** Try to actually open the connection.
164 for (idx = 0; idx < NDaemons; idx++)
166 sm_dprintf("getrequests: daemon %s: port %d\n",
168 ntohs(Daemons[idx].d_port));
172 /* get a socket for the SMTP connection */
173 for (idx = 0; idx < NDaemons; idx++)
174 Daemons[idx].d_socksize = opendaemonsocket(&Daemons[idx], true);
176 if (opencontrolsocket() < 0)
177 sm_syslog(LOG_WARNING, NOQID,
178 "daemon could not open control socket %s: %s",
179 ControlSocketName, sm_errstring(errno));
181 /* If there are any queue runners released reapchild() co-ord's */
182 (void) sm_signal(SIGCHLD, reapchild);
184 /* write the pid to file, command line args to syslog */
189 char jbuf[MAXHOSTNAMELEN];
191 expand("\201j", jbuf, sizeof(jbuf), e);
192 j_has_dot = strchr(jbuf, '.') != NULL;
196 /* Add parent process as first item */
197 proc_list_add(CurrentPid, "Sendmail daemon", PROC_DAEMON, 0, -1, NULL);
201 for (idx = 0; idx < NDaemons; idx++)
202 sm_dprintf("getrequests: daemon %s: socket %d\n",
204 Daemons[idx].d_socket);
210 auto SOCKADDR_LEN_T lotherend;
211 bool timedout = false;
212 bool control = false;
218 #endif /* STARTTLS */
220 /* see if we are rejecting connections */
221 (void) sm_blocksignal(SIGALRM);
224 for (idx = 0; idx < NDaemons; idx++)
227 ** XXX do this call outside the loop?
228 ** no: refuse_connections may sleep().
232 if (now < Daemons[idx].d_refuse_connections_until)
234 if (bitnset(D_DISABLE, Daemons[idx].d_flags))
236 if (refuseconnections(e, idx, curdaemon == idx))
238 if (Daemons[idx].d_socket >= 0)
240 /* close socket so peer fails quickly */
241 (void) close(Daemons[idx].d_socket);
242 Daemons[idx].d_socket = -1;
245 /* refuse connections for next 15 seconds */
246 Daemons[idx].d_refuse_connections_until = now + 15;
248 else if (Daemons[idx].d_socket < 0 ||
249 Daemons[idx].d_firsttime)
251 if (!Daemons[idx].d_firsttime && LogLevel > 8)
252 sm_syslog(LOG_INFO, NOQID,
253 "accepting connections again for daemon %s",
254 Daemons[idx].d_name);
256 /* arrange to (re)open the socket if needed */
257 (void) opendaemonsocket(&Daemons[idx], false);
258 Daemons[idx].d_firsttime = false;
262 /* May have been sleeping above, check again */
265 getrequests_checkdiskspace(e);
268 /* check for disaster */
270 char jbuf[MAXHOSTNAMELEN];
272 expand("\201j", jbuf, sizeof(jbuf), e);
273 if (!wordinclass(jbuf, 'w'))
275 dumpstate("daemon lost $j");
276 sm_syslog(LOG_ALERT, NOQID,
277 "daemon process doesn't have $j in $=w; see syslog");
280 else if (j_has_dot && strchr(jbuf, '.') == NULL)
282 dumpstate("daemon $j lost dot");
283 sm_syslog(LOG_ALERT, NOQID,
284 "daemon process $j lost dot; see syslog");
292 ** Andrew Sun <asun@ieps-sun.ml.com> claims that this will
293 ** fix the SVr4 problem. But it seems to have gone away,
294 ** so is it worth doing this?
297 if (DaemonSocket >= 0 &&
298 SetNonBlocking(DaemonSocket, false) < 0)
301 (void) sm_releasesignal(SIGALRM);
305 bool setproc = false;
308 struct timeval timeout;
312 for (idx = 0; idx < NDaemons; idx++)
314 /* wait for a connection */
315 if (Daemons[idx].d_socket >= 0)
319 Daemons[idx].d_flags))
321 sm_setproctitle(true, e,
322 "accepting connections");
325 if (Daemons[idx].d_socket > highest)
326 highest = Daemons[idx].d_socket;
327 SM_FD_SET(Daemons[idx].d_socket,
333 if (ControlSocket >= 0)
335 if (ControlSocket > highest)
336 highest = ControlSocket;
337 SM_FD_SET(ControlSocket, &readfds);
344 t = select(highest + 1, FDSET_CAST &readfds,
345 NULL, NULL, &timeout);
347 /* Did someone signal while waiting? */
353 (void) runqueue(true, false, false, false);
354 #if _FFR_QUEUE_RUN_PARANOIA
356 #endif /* _FFR_QUEUE_RUN_PARANOIA */
358 #if _FFR_QUEUE_RUN_PARANOIA
359 else if (CheckQueueRunners > 0 && QueueIntvl > 0 &&
360 lastrun + QueueIntvl + CheckQueueRunners < now)
364 ** set lastrun unconditionally to avoid
365 ** calling checkqueuerunner() all the time.
366 ** That's also why we currently ignore the
367 ** result of the function call.
370 (void) checkqueuerunner();
373 #endif /* _FFR_QUEUE_RUN_PARANOIA */
384 /* look "round-robin" for an active socket */
385 if ((idx = olddaemon + 1) >= NDaemons)
387 for (i = 0; i < NDaemons; i++)
389 if (Daemons[idx].d_socket >= 0 &&
390 SM_FD_ISSET(Daemons[idx].d_socket,
393 lotherend = Daemons[idx].d_socksize;
394 memset(&RealHostAddr, '\0',
395 sizeof(RealHostAddr));
396 t = accept(Daemons[idx].d_socket,
397 (struct sockaddr *)&RealHostAddr,
401 ** If remote side closes before
402 ** accept() finishes, sockaddr
403 ** might not be fully filled in.
408 # ifdef BSD4_4_SOCKADDR
409 RealHostAddr.sa.sa_len == 0 ||
410 # endif /* BSD4_4_SOCKADDR */
411 RealHostAddr.sa.sa_family != Daemons[idx].d_addr.sa.sa_family))
417 olddaemon = curdaemon = idx;
420 if (++idx >= NDaemons)
424 if (curdaemon == -1 && ControlSocket >= 0 &&
425 SM_FD_ISSET(ControlSocket, &readfds))
427 struct sockaddr_un sa_un;
429 lotherend = sizeof(sa_un);
430 memset(&sa_un, '\0', sizeof(sa_un));
431 t = accept(ControlSocket,
432 (struct sockaddr *)&sa_un,
436 ** If remote side closes before
437 ** accept() finishes, sockaddr
438 ** might not be fully filled in.
443 # ifdef BSD4_4_SOCKADDR
444 sa_un.sun_len == 0 ||
445 # endif /* BSD4_4_SOCKADDR */
446 sa_un.sun_family != AF_UNIX))
458 /* No daemon to service */
462 if (t >= 0 || errno != EINTR)
471 (void) sm_blocksignal(SIGALRM);
476 /* let's ignore these temporary errors */
477 if (save_errno == EINTR
479 || save_errno == EAGAIN
482 || save_errno == ECONNABORTED
483 #endif /* ECONNABORTED */
485 || save_errno == EWOULDBLOCK
486 #endif /* EWOULDBLOCK */
490 syserr("getrequests: accept");
494 /* arrange to re-open socket next time around */
495 (void) close(Daemons[curdaemon].d_socket);
496 Daemons[curdaemon].d_socket = -1;
497 #if SO_REUSEADDR_IS_BROKEN
499 ** Give time for bound socket to be released.
500 ** This creates a denial-of-service if you can
501 ** force accept() to fail on affected systems.
504 Daemons[curdaemon].d_refuse_connections_until =
506 #endif /* SO_REUSEADDR_IS_BROKEN */
513 /* set some daemon related macros */
514 switch (Daemons[curdaemon].d_addr.sa.sa_family)
517 macdefine(&BlankEnvelope.e_macro, A_PERM,
518 macid("{daemon_family}"), "unspec");
522 macdefine(&BlankEnvelope.e_macro, A_PERM,
523 macid("{daemon_family}"), "local");
528 macdefine(&BlankEnvelope.e_macro, A_PERM,
529 macid("{daemon_family}"), "inet");
534 macdefine(&BlankEnvelope.e_macro, A_PERM,
535 macid("{daemon_family}"), "inet6");
537 #endif /* NETINET6 */
540 macdefine(&BlankEnvelope.e_macro, A_PERM,
541 macid("{daemon_family}"), "iso");
546 macdefine(&BlankEnvelope.e_macro, A_PERM,
547 macid("{daemon_family}"), "ns");
552 macdefine(&BlankEnvelope.e_macro, A_PERM,
553 macid("{daemon_family}"), "x.25");
557 macdefine(&BlankEnvelope.e_macro, A_PERM,
558 macid("{daemon_name}"),
559 Daemons[curdaemon].d_name);
560 if (Daemons[curdaemon].d_mflags != NULL)
561 macdefine(&BlankEnvelope.e_macro, A_PERM,
562 macid("{daemon_flags}"),
563 Daemons[curdaemon].d_mflags);
565 macdefine(&BlankEnvelope.e_macro, A_PERM,
566 macid("{daemon_flags}"), "");
570 ** If connection rate is exceeded here, connection shall be
571 ** refused later by a new call after fork() by the
572 ** validate_connection() function. Closing the connection
573 ** at this point violates RFC 2821.
574 ** Do NOT remove this call, its side effects are needed.
577 connection_rate_check(&RealHostAddr, NULL);
580 ** Create a subprocess to process the mail.
584 sm_dprintf("getrequests: forking (fd = %d)\n", t);
587 ** Advance state of PRNG.
588 ** This is necessary because otherwise all child processes
589 ** will produce the same PRN sequence and hence the selection
590 ** of a queue directory (and other things, e.g., MX selection)
591 ** are not "really" random.
594 /* XXX get some better "random" data? */
596 RAND_seed((void *) &NextDiskSpaceCheck,
597 sizeof(NextDiskSpaceCheck));
598 RAND_seed((void *) &now, sizeof(now));
599 RAND_seed((void *) &seed, sizeof(seed));
602 #endif /* STARTTLS */
606 ** Update MX records for FallbackMX.
607 ** Let's hope this is fast otherwise we screw up the
611 if (FallbackMX != NULL)
612 (void) getfallbackmxrr(FallbackMX);
613 #endif /* NAMED_BIND */
617 /* don't fork, handle connection in this process */
619 pipefd[0] = pipefd[1] = -1;
624 ** Create a pipe to keep the child from writing to
625 ** the socket until after the parent has closed
626 ** it. Otherwise the parent may hang if the child
627 ** has closed it first.
630 if (pipe(pipefd) < 0)
631 pipefd[0] = pipefd[1] = -1;
633 (void) sm_blocksignal(SIGCHLD);
637 syserr("daemon: cannot fork");
640 (void) close(pipefd[0]);
641 (void) close(pipefd[1]);
643 (void) sm_releasesignal(SIGCHLD);
653 SM_FILE_T *inchannel, *outchannel = NULL;
656 ** CHILD -- return to caller.
657 ** Collect verified idea of sending host.
658 ** Verify calling user id if possible here.
661 /* Reset global flags */
662 RestartRequest = NULL;
663 RestartWorkGroup = false;
664 ShutdownRequest = NULL;
666 CurrentPid = getpid();
667 close_sendmail_pid();
669 (void) sm_releasesignal(SIGALRM);
670 (void) sm_releasesignal(SIGCHLD);
671 (void) sm_signal(SIGCHLD, SIG_DFL);
672 (void) sm_signal(SIGHUP, SIG_DFL);
673 (void) sm_signal(SIGTERM, intsig);
675 /* turn on profiling */
679 ** Initialize exception stack and default exception
680 ** handler for child process.
683 sm_exc_newthread(fatal_error);
687 macdefine(&BlankEnvelope.e_macro, A_TEMP,
688 macid("{daemon_addr}"),
689 anynet_ntoa(&Daemons[curdaemon].d_addr));
690 (void) sm_snprintf(status, sizeof(status), "%d",
691 ntohs(Daemons[curdaemon].d_port));
692 macdefine(&BlankEnvelope.e_macro, A_TEMP,
693 macid("{daemon_port}"), status);
696 for (idx = 0; idx < NDaemons; idx++)
698 if (Daemons[idx].d_socket >= 0)
699 (void) close(Daemons[idx].d_socket);
700 Daemons[idx].d_socket = -1;
704 /* Avoid SMTP daemon actions if control command */
707 /* Add control socket process */
708 proc_list_add(CurrentPid,
709 "console socket child",
710 PROC_CONTROL_CHILD, 0, -1, NULL);
716 /* clean up background delivery children */
717 (void) sm_signal(SIGCHLD, reapchild);
719 /* Add parent process as first child item */
720 proc_list_add(CurrentPid, "daemon child",
721 PROC_DAEMON_CHILD, 0, -1, NULL);
722 /* don't schedule queue runs if ETRN */
726 ** Hack: override global variables if
727 ** the corresponding DaemonPortOption
730 #if _FFR_SS_PER_DAEMON
731 if (Daemons[curdaemon].d_supersafe !=
733 SuperSafe = Daemons[curdaemon].
735 #endif /* _FFR_SS_PER_DAEMON */
736 if (Daemons[curdaemon].d_dm != DM_NOTSET)
738 Daemons[curdaemon].d_dm, e);
740 if (Daemons[curdaemon].d_refuseLA !=
742 RefuseLA = Daemons[curdaemon].
744 if (Daemons[curdaemon].d_queueLA != DPO_NOTSET)
745 QueueLA = Daemons[curdaemon].d_queueLA;
746 if (Daemons[curdaemon].d_delayLA != DPO_NOTSET)
747 DelayLA = Daemons[curdaemon].d_delayLA;
748 if (Daemons[curdaemon].d_maxchildren !=
750 MaxChildren = Daemons[curdaemon].
753 sm_setproctitle(true, e, "startup with %s",
754 anynet_ntoa(&RealHostAddr));
762 ** Wait for the parent to close the write end
763 ** of the pipe, which we will see as an EOF.
764 ** This guarantees that we won't write to the
765 ** socket until after the parent has closed
769 /* close the write end of the pipe */
770 (void) close(pipefd[1]);
772 /* we shouldn't be interrupted, but ... */
773 while (read(pipefd[0], &c, 1) < 0 &&
776 (void) close(pipefd[0]);
779 /* control socket processing */
782 control_command(t, e);
787 /* determine host name */
788 p = hostnamebyanyaddr(&RealHostAddr);
789 if (strlen(p) > MAXNAME) /* XXX - 1 ? */
791 RealHostName = newstr(p);
792 if (RealHostName[0] == '[')
794 macdefine(&BlankEnvelope.e_macro, A_PERM,
795 macid("{client_resolve}"),
796 h_errno == TRY_AGAIN ? "TEMP" : "FAIL");
800 macdefine(&BlankEnvelope.e_macro, A_PERM,
801 macid("{client_resolve}"), "OK");
803 sm_setproctitle(true, e, "startup with %s", p);
804 markstats(e, NULL, STATS_CONNECT);
806 if ((inchannel = sm_io_open(SmFtStdiofd,
812 (outchannel = sm_io_open(SmFtStdiofd,
818 syserr("cannot open SMTP server channel, fd=%d",
820 finis(false, true, EX_OK);
822 sm_io_automode(inchannel, outchannel);
824 InChannel = inchannel;
825 OutChannel = outchannel;
826 DisConnected = false;
829 t = xconnect(inchannel);
832 clrbitn(D_XCNCT, Daemons[curdaemon].d_flags);
833 clrbitn(D_XCNCT_M, Daemons[curdaemon].d_flags);
836 setbitn(t, Daemons[curdaemon].d_flags);
838 #endif /* _FFR_XCNCT */
841 if (!xla_host_ok(RealHostName))
843 message("421 4.4.5 Too many SMTP sessions for this host");
844 finis(false, true, EX_OK);
847 /* find out name for interface of connection */
848 if (getsockname(sm_io_getinfo(InChannel, SM_IO_WHAT_FD,
849 NULL), &sa.sa, &len) == 0)
851 p = hostnamebyanyaddr(&sa);
853 sm_dprintf("getreq: got name %s\n", p);
854 macdefine(&BlankEnvelope.e_macro, A_TEMP,
855 macid("{if_name}"), p);
858 ** Do this only if it is not the loopback
867 addr = anynet_ntoa(&sa);
868 (void) sm_snprintf(family,
870 "%d", sa.sa.sa_family);
871 macdefine(&BlankEnvelope.e_macro,
873 macid("{if_addr}"), addr);
874 macdefine(&BlankEnvelope.e_macro,
876 macid("{if_family}"), family);
878 sm_dprintf("getreq: got addr %s and family %s\n",
883 macdefine(&BlankEnvelope.e_macro,
885 macid("{if_addr}"), NULL);
886 macdefine(&BlankEnvelope.e_macro,
888 macid("{if_family}"), NULL);
894 sm_dprintf("getreq: getsockname failed\n");
895 macdefine(&BlankEnvelope.e_macro, A_PERM,
896 macid("{if_name}"), NULL);
897 macdefine(&BlankEnvelope.e_macro, A_PERM,
898 macid("{if_addr}"), NULL);
899 macdefine(&BlankEnvelope.e_macro, A_PERM,
900 macid("{if_family}"), NULL);
905 /* parent -- keep track of children */
908 (void) sm_snprintf(status, sizeof(status),
909 "control socket server child");
910 proc_list_add(pid, status, PROC_CONTROL, 0, -1, NULL);
914 (void) sm_snprintf(status, sizeof(status),
915 "SMTP server child for %s",
916 anynet_ntoa(&RealHostAddr));
917 proc_list_add(pid, status, PROC_DAEMON, 0, -1,
920 (void) sm_releasesignal(SIGCHLD);
922 /* close the read end of the synchronization pipe */
925 (void) close(pipefd[0]);
929 /* close the port so that others will hang (for a while) */
932 /* release the child by closing the read end of the sync pipe */
935 (void) close(pipefd[1]);
940 sm_dprintf("getreq: returning\n");
943 /* set the filters for this daemon */
944 if (Daemons[curdaemon].d_inputfilterlist != NULL)
948 Daemons[curdaemon].d_inputfilters[i] != NULL);
951 InputFilters[i] = Daemons[curdaemon].d_inputfilters[i];
954 InputFilters[i] = NULL;
957 return &Daemons[curdaemon].d_flags;
961 ** GETREQUESTS_CHECKDISKSPACE -- check available diskspace.
970 ** Modifies Daemon flags (D_ETRNONLY) if not enough disk space.
974 getrequests_checkdiskspace(e)
982 if (now < NextDiskSpaceCheck)
985 /* Check if there is available disk space in all queue groups. */
986 if (!enoughdiskspace(0, NULL))
988 for (idx = 0; idx < NDaemons; ++idx)
990 if (bitnset(D_ETRNONLY, Daemons[idx].d_flags))
993 /* log only if not logged before */
997 sm_syslog(LOG_INFO, NOQID,
998 "rejecting new messages: min free: %ld",
1000 sm_setproctitle(true, e,
1001 "rejecting new messages: min free: %ld",
1005 setbitn(D_ETRNONLY, Daemons[idx].d_flags);
1010 for (idx = 0; idx < NDaemons; ++idx)
1012 if (!bitnset(D_ETRNONLY, Daemons[idx].d_flags))
1015 /* log only if not logged before */
1019 sm_syslog(LOG_INFO, NOQID,
1020 "accepting new messages (again)");
1024 /* title will be set later */
1025 clrbitn(D_ETRNONLY, Daemons[idx].d_flags);
1029 /* only check disk space once a minute */
1030 NextDiskSpaceCheck = now + 60;
1034 ** OPENDAEMONSOCKET -- open SMTP socket
1036 ** Deals with setting all appropriate options.
1039 ** d -- the structure for the daemon to open.
1040 ** firsttime -- set if this is the initial open.
1043 ** Size in bytes of the daemon socket addr.
1046 ** Leaves DaemonSocket set to the open socket.
1047 ** Exits if the socket cannot be created.
1050 #define MAXOPENTRIES 10 /* maximum number of tries to open connection */
1053 opendaemonsocket(d, firsttime)
1059 SOCKADDR_LEN_T socksize = 0;
1064 sm_dprintf("opendaemonsocket(%s)\n", d->d_name);
1070 if (firsttime || d->d_socket < 0)
1073 if (d->d_addr.sa.sa_family == AF_UNIX)
1076 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_ROOTOK|SFF_EXECOK|SFF_CREAT;
1078 /* if not safe, don't use it */
1079 rval = safefile(d->d_addr.sunix.sun_path,
1082 S_IRUSR|S_IWUSR, NULL);
1086 syserr("opendaemonsocket: daemon %s: unsafe domain socket %s",
1088 d->d_addr.sunix.sun_path);
1092 /* Don't try to overtake an existing socket */
1093 (void) unlink(d->d_addr.sunix.sun_path);
1095 #endif /* NETUNIX */
1096 d->d_socket = socket(d->d_addr.sa.sa_family,
1098 if (d->d_socket < 0)
1101 syserr("opendaemonsocket: daemon %s: can't create server SMTP socket",
1104 if (bitnset(D_OPTIONAL, d->d_flags) &&
1105 (!transienterror(save_errno) ||
1106 ntries >= MAXOPENTRIES - 1))
1108 syserr("opendaemonsocket: daemon %s: optional socket disabled",
1110 setbitn(D_DISABLE, d->d_flags);
1116 sm_syslog(LOG_ALERT, NOQID,
1117 "daemon %s: problem creating SMTP socket",
1123 if (!SM_FD_OK_SELECT(d->d_socket))
1125 save_errno = EINVAL;
1126 syserr("opendaemonsocket: daemon %s: server SMTP socket (%d) too large",
1127 d->d_name, d->d_socket);
1131 /* turn on network debugging? */
1133 (void) setsockopt(d->d_socket, SOL_SOCKET,
1134 SO_DEBUG, (char *)&on,
1137 (void) setsockopt(d->d_socket, SOL_SOCKET,
1138 SO_REUSEADDR, (char *)&on, sizeof(on));
1139 (void) setsockopt(d->d_socket, SOL_SOCKET,
1140 SO_KEEPALIVE, (char *)&on, sizeof(on));
1143 if (d->d_tcprcvbufsize > 0)
1145 if (setsockopt(d->d_socket, SOL_SOCKET,
1147 (char *) &d->d_tcprcvbufsize,
1148 sizeof(d->d_tcprcvbufsize)) < 0)
1149 syserr("opendaemonsocket: daemon %s: setsockopt(SO_RCVBUF)", d->d_name);
1151 #endif /* SO_RCVBUF */
1153 if (d->d_tcpsndbufsize > 0)
1155 if (setsockopt(d->d_socket, SOL_SOCKET,
1157 (char *) &d->d_tcpsndbufsize,
1158 sizeof(d->d_tcpsndbufsize)) < 0)
1159 syserr("opendaemonsocket: daemon %s: setsockopt(SO_SNDBUF)", d->d_name);
1161 #endif /* SO_SNDBUF */
1163 if ((fdflags = fcntl(d->d_socket, F_GETFD, 0)) == -1 ||
1164 fcntl(d->d_socket, F_SETFD,
1165 fdflags | FD_CLOEXEC) == -1)
1168 syserr("opendaemonsocket: daemon %s: failed to %s close-on-exec flag: %s",
1170 fdflags == -1 ? "get" : "set",
1171 sm_errstring(save_errno));
1172 (void) close(d->d_socket);
1176 switch (d->d_addr.sa.sa_family)
1180 socksize = sizeof(d->d_addr.sunix);
1182 #endif /* NETUNIX */
1185 socksize = sizeof(d->d_addr.sin);
1187 #endif /* NETINET */
1191 socksize = sizeof(d->d_addr.sin6);
1193 #endif /* NETINET6 */
1197 socksize = sizeof(d->d_addr.siso);
1202 socksize = sizeof(d->d_addr);
1206 if (bind(d->d_socket, &d->d_addr.sa, socksize) < 0)
1208 /* probably another daemon already */
1210 syserr("opendaemonsocket: daemon %s: cannot bind",
1212 (void) close(d->d_socket);
1217 listen(d->d_socket, d->d_listenqueue) < 0)
1220 syserr("opendaemonsocket: daemon %s: cannot listen",
1222 (void) close(d->d_socket);
1226 } while (ntries++ < MAXOPENTRIES && transienterror(save_errno));
1227 syserr("!opendaemonsocket: daemon %s: server SMTP socket wedged: exiting",
1230 return -1; /* avoid compiler warning on IRIX */
1233 ** SETUPDAEMON -- setup socket for daemon
1236 ** daemonaddr -- socket for daemon
1239 ** port number on which daemon should run
1243 static unsigned short
1244 setupdaemon(daemonaddr)
1245 SOCKADDR *daemonaddr;
1247 unsigned short port;
1250 ** Set up the address for the mailer.
1253 if (daemonaddr->sa.sa_family == AF_UNSPEC)
1255 memset(daemonaddr, '\0', sizeof(*daemonaddr));
1257 daemonaddr->sa.sa_family = AF_INET;
1258 #endif /* NETINET */
1261 switch (daemonaddr->sa.sa_family)
1265 if (daemonaddr->sin.sin_addr.s_addr == 0)
1266 daemonaddr->sin.sin_addr.s_addr =
1267 LocalDaemon ? htonl(INADDR_LOOPBACK) : INADDR_ANY;
1268 port = daemonaddr->sin.sin_port;
1270 #endif /* NETINET */
1274 if (IN6_IS_ADDR_UNSPECIFIED(&daemonaddr->sin6.sin6_addr))
1275 daemonaddr->sin6.sin6_addr =
1276 (LocalDaemon && V6LoopbackAddrFound) ?
1277 in6addr_loopback : in6addr_any;
1278 port = daemonaddr->sin6.sin6_port;
1280 #endif /* NETINET6 */
1283 /* unknown protocol */
1289 #ifdef NO_GETSERVBYNAME
1291 #else /* NO_GETSERVBYNAME */
1293 register struct servent *sp;
1295 sp = getservbyname("smtp", "tcp");
1298 syserr("554 5.3.5 service \"smtp\" unknown");
1304 #endif /* NO_GETSERVBYNAME */
1307 switch (daemonaddr->sa.sa_family)
1311 daemonaddr->sin.sin_port = port;
1313 #endif /* NETINET */
1317 daemonaddr->sin6.sin6_port = port;
1319 #endif /* NETINET6 */
1322 /* unknown protocol */
1328 ** CLRDAEMON -- reset the daemon connection
1337 ** releases any resources used by the passive daemon.
1345 for (i = 0; i < NDaemons; i++)
1347 if (Daemons[i].d_socket >= 0)
1348 (void) close(Daemons[i].d_socket);
1349 Daemons[i].d_socket = -1;
1354 ** GETMODIFIERS -- get modifier flags
1357 ** v -- the modifiers (input text line).
1358 ** modifiers -- pointer to flag field to represent modifiers.
1361 ** (xallocat()ed) string representation of modifiers.
1364 ** fills in modifiers.
1368 getmodifiers(v, modifiers)
1370 BITMAP256 modifiers;
1373 char *h, *f, *flags;
1375 /* maximum length of flags: upper case Option -> "OO " */
1376 l = 3 * strlen(v) + 3;
1378 /* is someone joking? */
1379 if (l < 0 || l > 256)
1382 sm_syslog(LOG_ERR, NOQID,
1383 "getmodifiers too long, ignored");
1388 clrbitmap(modifiers);
1389 for (h = v; *h != '\0'; h++)
1391 if (isascii(*h) && !isspace(*h) && isprint(*h))
1393 setbitn(*h, modifiers);
1406 ** CHKDAEMONMODIFIERS -- check whether all daemons have set a flag.
1409 ** flag -- the flag to test.
1412 ** true iff all daemons have set flag.
1416 chkdaemonmodifiers(flag)
1421 for (i = 0; i < NDaemons; i++)
1422 if (!bitnset((char) flag, Daemons[i].d_flags))
1428 ** SETSOCKADDROPTIONS -- set options for SOCKADDR (daemon or client)
1431 ** p -- the options line.
1432 ** d -- the daemon structure to fill in.
1439 setsockaddroptions(p, d)
1450 if (d->d_addr.sa.sa_family == AF_UNSPEC)
1451 d->d_addr.sa.sa_family = AF_INET;
1452 #endif /* NETINET */
1453 #if _FFR_SS_PER_DAEMON
1454 d->d_supersafe = DPO_NOTSET;
1455 #endif /* _FFR_SS_PER_DAEMON */
1456 d->d_dm = DM_NOTSET;
1457 d->d_refuseLA = DPO_NOTSET;
1458 d->d_queueLA = DPO_NOTSET;
1459 d->d_delayLA = DPO_NOTSET;
1460 d->d_maxchildren = DPO_NOTSET;
1467 while (isascii(*p) && isspace(*p))
1478 while (isascii(*++v) && isspace(*v))
1483 case 'A': /* address */
1486 #endif /* !_FFR_DPO_CS */
1491 d->d_maxchildren = atoi(v);
1494 case 'D': /* DeliveryMode */
1503 #endif /* _FFR_PROXY */
1507 syserr("554 5.3.5 Unknown delivery mode %c",
1513 case 'd': /* delayLA */
1514 d->d_delayLA = atoi(v);
1517 case 'F': /* address family */
1520 #endif /* !_FFR_DPO_CS */
1521 if (isascii(*v) && isdigit(*v))
1522 d->d_addr.sa.sa_family = atoi(v);
1524 else if (sm_strcasecmp(v, "unix") == 0 ||
1525 sm_strcasecmp(v, "local") == 0)
1526 d->d_addr.sa.sa_family = AF_UNIX;
1527 #endif /* NETUNIX */
1529 else if (sm_strcasecmp(v, "inet") == 0)
1530 d->d_addr.sa.sa_family = AF_INET;
1531 #endif /* NETINET */
1533 else if (sm_strcasecmp(v, "inet6") == 0)
1534 d->d_addr.sa.sa_family = AF_INET6;
1535 #endif /* NETINET6 */
1537 else if (sm_strcasecmp(v, "iso") == 0)
1538 d->d_addr.sa.sa_family = AF_ISO;
1541 else if (sm_strcasecmp(v, "ns") == 0)
1542 d->d_addr.sa.sa_family = AF_NS;
1545 else if (sm_strcasecmp(v, "x.25") == 0)
1546 d->d_addr.sa.sa_family = AF_CCITT;
1549 syserr("554 5.3.5 Unknown address family %s in Family=option",
1557 # endif /* !_FFR_DPO_CS */
1558 d->d_inputfilterlist = v;
1562 case 'L': /* listen queue size */
1565 #endif /* !_FFR_DPO_CS */
1566 d->d_listenqueue = atoi(v);
1569 case 'M': /* modifiers (flags) */
1572 #endif /* !_FFR_DPO_CS */
1573 d->d_mflags = getmodifiers(v, d->d_flags);
1576 case 'N': /* name */
1579 #endif /* !_FFR_DPO_CS */
1583 case 'P': /* port */
1586 #endif /* !_FFR_DPO_CS */
1591 d->d_queueLA = atoi(v);
1594 case 'R': /* receive buffer size */
1595 d->d_tcprcvbufsize = atoi(v);
1599 d->d_refuseLA = atoi(v);
1602 case 'S': /* send buffer size */
1605 #endif /* !_FFR_DPO_CS */
1606 d->d_tcpsndbufsize = atoi(v);
1609 #if _FFR_SS_PER_DAEMON
1610 case 'T': /* SuperSafe */
1611 if (tolower(*v) == 'i')
1612 d->d_supersafe = SAFE_INTERACTIVE;
1613 else if (tolower(*v) == 'p')
1615 d->d_supersafe = SAFE_REALLY_POSTMILTER;
1617 (void) sm_io_fprintf(smioout, SM_TIME_DEFAULT,
1618 "Warning: SuperSafe=PostMilter requires Milter support (-DMILTER)\n");
1619 # endif /* MILTER */
1621 d->d_supersafe = atobool(v) ? SAFE_REALLY
1624 #endif /* _FFR_SS_PER_DAEMON */
1627 syserr("554 5.3.5 PortOptions parameter \"%s\" unknown",
1632 /* Check addr and port after finding family */
1635 switch (d->d_addr.sa.sa_family)
1639 if (strlen(addr) >= sizeof(d->d_addr.sunix.sun_path))
1641 errno = ENAMETOOLONG;
1642 syserr("setsockaddroptions: domain socket name too long: %s > %ld",
1644 (long) sizeof(d->d_addr.sunix.sun_path));
1648 /* file safety check done in opendaemonsocket() */
1649 (void) memset(&d->d_addr.sunix.sun_path, '\0',
1650 sizeof(d->d_addr.sunix.sun_path));
1651 (void) sm_strlcpy((char *)&d->d_addr.sunix.sun_path,
1653 sizeof(d->d_addr.sunix.sun_path));
1655 #endif /* NETUNIX */
1658 if (!isascii(*addr) || !isdigit(*addr) ||
1659 ((d->d_addr.sin.sin_addr.s_addr = inet_addr(addr))
1662 register struct hostent *hp;
1664 hp = sm_gethostbyname(addr, AF_INET);
1666 syserr("554 5.3.0 host \"%s\" unknown",
1670 while (*(hp->h_addr_list) != NULL &&
1671 hp->h_addrtype != AF_INET)
1673 if (*(hp->h_addr_list) == NULL)
1674 syserr("554 5.3.0 host \"%s\" unknown",
1677 memmove(&d->d_addr.sin.sin_addr,
1683 # endif /* NETINET6 */
1687 #endif /* NETINET */
1691 if (anynet_pton(AF_INET6, addr,
1692 &d->d_addr.sin6.sin6_addr) != 1)
1694 register struct hostent *hp;
1696 hp = sm_gethostbyname(addr, AF_INET6);
1698 syserr("554 5.3.0 host \"%s\" unknown",
1702 while (*(hp->h_addr_list) != NULL &&
1703 hp->h_addrtype != AF_INET6)
1705 if (*(hp->h_addr_list) == NULL)
1706 syserr("554 5.3.0 host \"%s\" unknown",
1709 memmove(&d->d_addr.sin6.sin6_addr,
1717 #endif /* NETINET6 */
1720 syserr("554 5.3.5 address= option unsupported for family %d",
1721 d->d_addr.sa.sa_family);
1728 switch (d->d_addr.sa.sa_family)
1732 if (isascii(*port) && isdigit(*port))
1733 d->d_addr.sin.sin_port = htons((unsigned short)
1734 atoi((const char *) port));
1737 # ifdef NO_GETSERVBYNAME
1738 syserr("554 5.3.5 invalid port number: %s",
1740 # else /* NO_GETSERVBYNAME */
1741 register struct servent *sp;
1743 sp = getservbyname(port, "tcp");
1745 syserr("554 5.3.5 service \"%s\" unknown",
1748 d->d_addr.sin.sin_port = sp->s_port;
1749 # endif /* NO_GETSERVBYNAME */
1752 #endif /* NETINET */
1756 if (isascii(*port) && isdigit(*port))
1757 d->d_addr.sin6.sin6_port = htons((unsigned short)
1761 # ifdef NO_GETSERVBYNAME
1762 syserr("554 5.3.5 invalid port number: %s",
1764 # else /* NO_GETSERVBYNAME */
1765 register struct servent *sp;
1767 sp = getservbyname(port, "tcp");
1769 syserr("554 5.3.5 service \"%s\" unknown",
1772 d->d_addr.sin6.sin6_port = sp->s_port;
1773 # endif /* NO_GETSERVBYNAME */
1776 #endif /* NETINET6 */
1780 /* assume two byte transport selector */
1781 if (isascii(*port) && isdigit(*port))
1782 portno = htons((unsigned short) atoi(port));
1785 # ifdef NO_GETSERVBYNAME
1786 syserr("554 5.3.5 invalid port number: %s",
1788 # else /* NO_GETSERVBYNAME */
1789 register struct servent *sp;
1791 sp = getservbyname(port, "tcp");
1793 syserr("554 5.3.5 service \"%s\" unknown",
1796 portno = sp->s_port;
1797 # endif /* NO_GETSERVBYNAME */
1799 memmove(TSEL(&d->d_addr.siso),
1800 (char *) &portno, 2);
1805 syserr("554 5.3.5 Port= option unsupported for family %d",
1806 d->d_addr.sa.sa_family);
1812 ** SETDAEMONOPTIONS -- set options for running the MTA daemon
1815 ** p -- the options line.
1818 ** true if successful, false otherwise.
1821 ** increments number of daemons.
1824 #define DEF_LISTENQUEUE 10
1832 static struct dflags DaemonFlags[] =
1834 { "AUTHREQ", D_AUTHREQ },
1835 { "BINDIF", D_BINDIF },
1836 { "CANONREQ", D_CANONREQ },
1837 { "IFNHELO", D_IFNHELO },
1838 { "FQMAIL", D_FQMAIL },
1839 { "FQRCPT", D_FQRCPT },
1840 { "SMTPS", D_SMTPS },
1841 { "UNQUALOK", D_UNQUALOK },
1842 { "NOAUTH", D_NOAUTH },
1843 { "NOCANON", D_NOCANON },
1844 { "NOETRN", D_NOETRN },
1845 { "NOTLS", D_NOTLS },
1846 { "ETRNONLY", D_ETRNONLY },
1847 { "OPTIONAL", D_OPTIONAL },
1848 { "DISABLE", D_DISABLE },
1849 { "ISSET", D_ISSET },
1857 register struct dflags *df;
1860 for (df = DaemonFlags; df->d_name != NULL; df++)
1862 if (!bitnset(df->d_flag, d->d_flags))
1865 sm_dprintf("<%s", df->d_name);
1867 sm_dprintf(",%s", df->d_name);
1878 if (NDaemons >= MAXDAEMONS)
1880 Daemons[NDaemons].d_socket = -1;
1881 Daemons[NDaemons].d_listenqueue = DEF_LISTENQUEUE;
1882 clrbitmap(Daemons[NDaemons].d_flags);
1883 setsockaddroptions(p, &Daemons[NDaemons]);
1886 if (Daemons[NDaemons].d_inputfilterlist != NULL)
1887 Daemons[NDaemons].d_inputfilterlist = newstr(Daemons[NDaemons].d_inputfilterlist);
1890 if (Daemons[NDaemons].d_name != NULL)
1891 Daemons[NDaemons].d_name = newstr(Daemons[NDaemons].d_name);
1896 (void) sm_snprintf(num, sizeof(num), "Daemon%d", NDaemons);
1897 Daemons[NDaemons].d_name = newstr(num);
1902 sm_dprintf("Daemon %s flags: ", Daemons[NDaemons].d_name);
1903 printdaemonflags(&Daemons[NDaemons]);
1910 ** INITDAEMON -- initialize daemon if not yet done.
1919 ** initializes structure for one daemon.
1927 Daemons[NDaemons].d_socket = -1;
1928 Daemons[NDaemons].d_listenqueue = DEF_LISTENQUEUE;
1929 Daemons[NDaemons].d_name = "Daemon0";
1934 ** SETCLIENTOPTIONS -- set options for running the client
1937 ** p -- the options line.
1943 static DAEMON_T ClientSettings[AF_MAX + 1];
1952 memset(&d, '\0', sizeof(d));
1953 setsockaddroptions(p, &d);
1955 /* grab what we need */
1956 family = d.d_addr.sa.sa_family;
1957 STRUCTCOPY(d, ClientSettings[family]);
1958 setbitn(D_ISSET, ClientSettings[family].d_flags); /* mark as set */
1959 if (d.d_name != NULL)
1960 ClientSettings[family].d_name = newstr(d.d_name);
1965 (void) sm_snprintf(num, sizeof(num), "Client%d", family);
1966 ClientSettings[family].d_name = newstr(num);
1970 ** ADDR_FAMILY -- determine address family from address
1973 ** addr -- the string representation of the address
1976 ** AF_INET, AF_INET6 or AF_UNSPEC
1988 #endif /* NETINET6 */
1991 if (inet_addr(addr) != INADDR_NONE)
1994 sm_dprintf("addr_family(%s): INET\n", addr);
1997 #endif /* NETINET */
1999 if (anynet_pton(AF_INET6, addr, &clt_addr.sin6.sin6_addr) == 1)
2002 sm_dprintf("addr_family(%s): INET6\n", addr);
2005 #endif /* NETINET6 */
2010 sm_dprintf("addr_family(%s): LOCAL\n", addr);
2013 #endif /* NETUNIX */
2015 sm_dprintf("addr_family(%s): UNSPEC\n", addr);
2020 ** CHKCLIENTMODIFIERS -- check whether all clients have set a flag.
2023 ** flag -- the flag to test.
2026 ** true iff all configured clients have set the flag.
2030 chkclientmodifiers(flag)
2037 for (i = 0; i < AF_MAX; i++)
2039 if (bitnset(D_ISSET, ClientSettings[i].d_flags))
2041 if (!bitnset((char) flag, ClientSettings[i].d_flags))
2051 ** SETUP_DAEMON_MILTERS -- Parse per-socket filters
2061 setup_daemon_milters()
2065 if (OpMode == MD_SMTP)
2067 /* no need to configure the daemons */
2071 for (idx = 0; idx < NDaemons; idx++)
2073 if (Daemons[idx].d_inputfilterlist != NULL)
2075 milter_config(Daemons[idx].d_inputfilterlist,
2076 Daemons[idx].d_inputfilters,
2083 ** MAKECONNECTION -- make a connection to an SMTP socket on a machine.
2086 ** host -- the name of the host.
2087 ** port -- the port number to connect to.
2088 ** mci -- a pointer to the mail connection information
2089 ** structure to be filled in.
2090 ** e -- the current envelope.
2091 ** enough -- time at which to stop further connection attempts.
2092 ** (0 means no limit)
2095 ** An exit code telling whether the connection could be
2096 ** made and if not why not.
2102 static jmp_buf CtxConnectTimeout;
2104 SOCKADDR CurHostAddr; /* address of current host */
2107 makeconnection(host, port, mci, e, enough)
2109 volatile unsigned int port;
2114 register volatile int addrno = 0;
2116 register struct hostent *volatile hp = (struct hostent *) NULL;
2120 volatile SOCKADDR_LEN_T addrlen;
2121 volatile bool firstconnect = true;
2122 SM_EVENT *volatile ev = NULL;
2124 volatile bool v6found = false;
2125 #endif /* NETINET6 */
2126 volatile int family = InetMode;
2128 volatile SOCKADDR_LEN_T socksize = 0;
2129 volatile bool clt_bind;
2132 extern ENVELOPE BlankEnvelope;
2134 /* retranslate {daemon_flags} into bitmap */
2136 if ((p = macvalue(macid("{daemon_flags}"), e)) != NULL)
2138 for (; *p != '\0'; p++)
2140 if (!(isascii(*p) && isspace(*p)))
2141 setbitn(bitidx(*p), d_flags);
2147 #endif /* NETINET6 */
2150 /* Set up the address for outgoing connection. */
2151 if (bitnset(D_BINDIF, d_flags) &&
2152 (p = macvalue(macid("{if_addr}"), e)) != NULL &&
2156 char p6[INET6_ADDRSTRLEN];
2157 #endif /* NETINET6 */
2159 memset(&clt_addr, '\0', sizeof(clt_addr));
2161 /* infer the address family from the address itself */
2162 clt_addr.sa.sa_family = addr_family(p);
2163 switch (clt_addr.sa.sa_family)
2167 clt_addr.sin.sin_addr.s_addr = inet_addr(p);
2168 if (clt_addr.sin.sin_addr.s_addr != INADDR_NONE &&
2169 clt_addr.sin.sin_addr.s_addr !=
2170 htonl(INADDR_LOOPBACK))
2173 socksize = sizeof(struct sockaddr_in);
2176 #endif /* NETINET */
2180 if (inet_addr(p) != INADDR_NONE)
2181 (void) sm_snprintf(p6, sizeof(p6),
2182 "IPv6:::ffff:%s", p);
2184 (void) sm_strlcpy(p6, p, sizeof(p6));
2185 if (anynet_pton(AF_INET6, p6,
2186 &clt_addr.sin6.sin6_addr) == 1 &&
2187 !IN6_IS_ADDR_LOOPBACK(&clt_addr.sin6.sin6_addr))
2190 socksize = sizeof(struct sockaddr_in6);
2193 #endif /* NETINET6 */
2197 syserr("554 5.3.5 Address= option unsupported for family %d",
2198 clt_addr.sa.sa_family);
2203 family = clt_addr.sa.sa_family;
2206 /* D_BINDIF not set or not available, fallback to ClientPortOptions */
2209 STRUCTCOPY(ClientSettings[family].d_addr, clt_addr);
2210 switch (clt_addr.sa.sa_family)
2214 if (clt_addr.sin.sin_addr.s_addr == 0)
2215 clt_addr.sin.sin_addr.s_addr = LocalDaemon ?
2216 htonl(INADDR_LOOPBACK) : INADDR_ANY;
2219 if (clt_addr.sin.sin_port != 0)
2221 socksize = sizeof(struct sockaddr_in);
2223 #endif /* NETINET */
2226 if (IN6_IS_ADDR_UNSPECIFIED(&clt_addr.sin6.sin6_addr))
2227 clt_addr.sin6.sin6_addr =
2228 (LocalDaemon && V6LoopbackAddrFound) ?
2229 in6addr_loopback : in6addr_any;
2232 socksize = sizeof(struct sockaddr_in6);
2233 if (clt_addr.sin6.sin6_port != 0)
2236 #endif /* NETINET6 */
2239 socksize = sizeof(clt_addr.siso);
2249 ** Set up the address for the mailer.
2250 ** Accept "[a.b.c.d]" syntax for host name.
2255 memset(&CurHostAddr, '\0', sizeof(CurHostAddr));
2256 memset(&addr, '\0', sizeof(addr));
2257 SmtpPhase = mci->mci_phase = "initial connection";
2262 p = strchr(host, ']');
2266 unsigned long hid = INADDR_NONE;
2267 #endif /* NETINET */
2269 struct sockaddr_in6 hid6;
2270 #endif /* NETINET6 */
2274 memset(&hid6, '\0', sizeof(hid6));
2275 #endif /* NETINET6 */
2277 if (family == AF_INET &&
2278 (hid = inet_addr(&host[1])) != INADDR_NONE)
2280 addr.sin.sin_family = AF_INET;
2281 addr.sin.sin_addr.s_addr = hid;
2284 #endif /* NETINET */
2286 if (family == AF_INET6 &&
2287 anynet_pton(AF_INET6, &host[1],
2288 &hid6.sin6_addr) == 1)
2290 addr.sin6.sin6_family = AF_INET6;
2291 addr.sin6.sin6_addr = hid6.sin6_addr;
2294 #endif /* NETINET6 */
2296 /* try it as a host name (avoid MX lookup) */
2297 hp = sm_gethostbyname(&host[1], family);
2298 if (hp == NULL && p[-1] == '.')
2301 int oldopts = _res.options;
2303 _res.options &= ~(RES_DEFNAMES|RES_DNSRCH);
2304 #endif /* NAMED_BIND */
2306 hp = sm_gethostbyname(&host[1],
2310 _res.options = oldopts;
2311 #endif /* NAMED_BIND */
2320 extern char MsgBuf[];
2323 "553 Invalid numeric domain spec \"%s\"",
2325 mci_setstat(mci, EX_NOHOST, "5.1.2", MsgBuf);
2332 /* contortion to get around SGI cc complaints */
2334 p = &host[strlen(host) - 1];
2335 hp = sm_gethostbyname(host, family);
2336 if (hp == NULL && *p == '.')
2339 int oldopts = _res.options;
2341 _res.options &= ~(RES_DEFNAMES|RES_DNSRCH);
2342 #endif /* NAMED_BIND */
2344 hp = sm_gethostbyname(host, family);
2347 _res.options = oldopts;
2348 #endif /* NAMED_BIND */
2352 if (hp == NULL || hp->h_addr == NULL)
2355 /* check for name server timeouts */
2357 if (WorkAroundBrokenAAAA && family == AF_INET6 &&
2358 (h_errno == TRY_AGAIN || errno == ETIMEDOUT))
2361 ** An attempt with family AF_INET may
2362 ** succeed. By skipping the next section
2363 ** of code, we will try AF_INET before
2368 sm_dprintf("makeconnection: WorkAroundBrokenAAAA: Trying AF_INET lookup (AF_INET6 failed)\n");
2371 # endif /* NETINET6 */
2373 if (errno == ETIMEDOUT ||
2374 # if _FFR_GETHBN_ExFILE
2377 # endif /* EMFILE */
2380 # endif /* ENFILE */
2381 # endif /* _FFR_GETHBN_ExFILE */
2382 h_errno == TRY_AGAIN ||
2383 (errno == ECONNREFUSED && UseNameServer))
2386 mci_setstat(mci, EX_TEMPFAIL,
2392 #endif /* NAMED_BIND */
2395 ** Try v6 first, then fall back to v4.
2396 ** If we found a v6 address, but no v4
2397 ** addresses, then TEMPFAIL.
2400 if (family == AF_INET6)
2407 #endif /* NETINET6 */
2409 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2413 addr.sa.sa_family = hp->h_addrtype;
2414 switch (hp->h_addrtype)
2418 memmove(&addr.sin.sin_addr,
2422 #endif /* NETINET */
2426 memmove(&addr.sin6.sin6_addr,
2430 #endif /* NETINET6 */
2433 if (hp->h_length > sizeof(addr.sa.sa_data))
2435 syserr("makeconnection: long sa_data: family %d len %d",
2436 hp->h_addrtype, hp->h_length);
2437 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2441 memmove(addr.sa.sa_data, hp->h_addr, hp->h_length);
2448 ** Determine the port number.
2453 #ifdef NO_GETSERVBYNAME
2455 #else /* NO_GETSERVBYNAME */
2456 register struct servent *sp = getservbyname("smtp", "tcp");
2461 sm_syslog(LOG_ERR, NOQID,
2462 "makeconnection: service \"smtp\" unknown");
2467 #endif /* NO_GETSERVBYNAME */
2471 if (addr.sa.sa_family == AF_INET6 &&
2472 IN6_IS_ADDR_V4MAPPED(&addr.sin6.sin6_addr) &&
2473 ClientSettings[AF_INET].d_addr.sa.sa_family != 0)
2476 ** Ignore mapped IPv4 address since
2477 ** there is a ClientPortOptions setting
2483 #endif /* NETINET6 */
2485 switch (addr.sa.sa_family)
2489 addr.sin.sin_port = port;
2490 addrlen = sizeof(struct sockaddr_in);
2492 #endif /* NETINET */
2496 addr.sin6.sin6_port = port;
2497 addrlen = sizeof(struct sockaddr_in6);
2499 #endif /* NETINET6 */
2503 /* assume two byte transport selector */
2504 memmove(TSEL((struct sockaddr_iso *) &addr), (char *) &port, 2);
2505 addrlen = sizeof(struct sockaddr_iso);
2510 syserr("Can't connect to address family %d", addr.sa.sa_family);
2511 mci_setstat(mci, EX_NOHOST, "5.1.2", NULL);
2516 #endif /* NETINET6 */
2521 ** Try to actually open the connection.
2525 /* if too many connections, don't bother trying */
2526 if (!xla_noqueue_ok(host))
2531 # endif /* NETINET6 */
2539 sm_dprintf("makeconnection (%s [%s].%d (%d))\n",
2540 host, anynet_ntoa(&addr), ntohs(port),
2541 (int) addr.sa.sa_family);
2543 /* save for logging */
2547 if (bitnset(M_SECURE_PORT, mci->mci_mailer->m_flags))
2549 int rport = IPPORT_RESERVED - 1;
2551 s = rresvport(&rport);
2554 #endif /* HASRRESVPORT */
2556 s = socket(addr.sa.sa_family, SOCK_STREAM, 0);
2561 syserr("makeconnection: cannot create socket");
2565 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2569 #endif /* NETINET6 */
2575 if (ClientSettings[family].d_tcpsndbufsize > 0)
2577 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
2578 (char *) &ClientSettings[family].d_tcpsndbufsize,
2579 sizeof(ClientSettings[family].d_tcpsndbufsize)) < 0)
2580 syserr("makeconnection: setsockopt(SO_SNDBUF)");
2582 #endif /* SO_SNDBUF */
2584 if (ClientSettings[family].d_tcprcvbufsize > 0)
2586 if (setsockopt(s, SOL_SOCKET, SO_RCVBUF,
2587 (char *) &ClientSettings[family].d_tcprcvbufsize,
2588 sizeof(ClientSettings[family].d_tcprcvbufsize)) < 0)
2589 syserr("makeconnection: setsockopt(SO_RCVBUF)");
2591 #endif /* SO_RCVBUF */
2594 sm_dprintf("makeconnection: fd=%d\n", s);
2596 /* turn on network debugging? */
2601 (void) setsockopt(s, SOL_SOCKET, SO_DEBUG,
2602 (char *)&on, sizeof(on));
2604 if (e->e_xfp != NULL) /* for debugging */
2605 (void) sm_io_flush(e->e_xfp, SM_TIME_DEFAULT);
2606 errno = 0; /* for debugging */
2612 switch (clt_addr.sa.sa_family)
2616 if (clt_addr.sin.sin_port != 0)
2617 (void) setsockopt(s, SOL_SOCKET,
2622 #endif /* NETINET */
2626 if (clt_addr.sin6.sin6_port != 0)
2627 (void) setsockopt(s, SOL_SOCKET,
2632 #endif /* NETINET6 */
2635 if (bind(s, &clt_addr.sa, socksize) < 0)
2640 syserr("makeconnection: cannot bind socket [%s]",
2641 anynet_ntoa(&clt_addr));
2645 #endif /* NETINET6 */
2652 ** Linux seems to hang in connect for 90 minutes (!!!).
2653 ** Time out the connect to avoid this problem.
2656 if (setjmp(CtxConnectTimeout) == 0)
2660 if (e->e_ntries <= 0 && TimeOuts.to_iconnect != 0)
2661 ev = sm_setevent(TimeOuts.to_iconnect,
2663 else if (TimeOuts.to_connect != 0)
2664 ev = sm_setevent(TimeOuts.to_connect,
2669 switch (ConnectOnlyTo.sa.sa_family)
2673 addr.sin.sin_addr.s_addr = ConnectOnlyTo.sin.sin_addr.s_addr;
2674 addr.sa.sa_family = ConnectOnlyTo.sa.sa_family;
2676 #endif /* NETINET */
2680 memmove(&addr.sin6.sin6_addr,
2681 &ConnectOnlyTo.sin6.sin6_addr,
2684 #endif /* NETINET6 */
2687 sm_dprintf("Connecting to [%s]...\n", anynet_ntoa(&addr));
2688 i = connect(s, (struct sockaddr *) &addr, addrlen);
2698 /* couldn't connect.... figure out why */
2701 /* if running demand-dialed connection, try again */
2702 if (DialDelay > 0 && firstconnect &&
2703 bitnset(M_DIALDELAY, mci->mci_mailer->m_flags))
2706 sm_dprintf("Connect failed (%s); trying again...\n",
2707 sm_errstring(save_errno));
2708 firstconnect = false;
2709 (void) sleep(DialDelay);
2714 sm_syslog(LOG_INFO, e->e_id,
2715 "makeconnection (%s [%s]) failed: %s",
2716 host, anynet_ntoa(&addr),
2717 sm_errstring(save_errno));
2721 #endif /* NETINET6 */
2722 if (hp != NULL && hp->h_addr_list[addrno] != NULL &&
2723 (enough == 0 || curtime() < enough))
2726 sm_dprintf("Connect failed (%s); trying new address....\n",
2727 sm_errstring(save_errno));
2728 switch (addr.sa.sa_family)
2732 memmove(&addr.sin.sin_addr,
2733 hp->h_addr_list[addrno++],
2736 #endif /* NETINET */
2740 memmove(&addr.sin6.sin6_addr,
2741 hp->h_addr_list[addrno++],
2744 #endif /* NETINET6 */
2747 memmove(addr.sa.sa_data,
2748 hp->h_addr_list[addrno++],
2757 if (family == AF_INET6)
2760 sm_dprintf("Connect failed (%s); retrying with AF_INET....\n",
2761 sm_errstring(save_errno));
2772 #endif /* NETINET6 */
2773 /* couldn't open connection */
2775 /* Don't clobber an already saved errno from v4retry */
2777 #endif /* NETINET6 */
2780 sm_dprintf("Connect failed (%s)\n",
2781 sm_errstring(save_errno));
2785 mci_setstat(mci, EX_TEMPFAIL, "4.4.1", NULL);
2789 #endif /* NETINET6 */
2800 #endif /* NETINET6 */
2802 /* connection ok, put it into canonical form */
2803 mci->mci_out = NULL;
2804 if ((mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2806 SM_IO_WRONLY_B, NULL)) == NULL ||
2808 (mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2810 SM_IO_RDONLY_B, NULL)) == NULL)
2813 syserr("cannot open SMTP client channel, fd=%d", s);
2814 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2815 if (mci->mci_out != NULL)
2816 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
2821 sm_io_automode(mci->mci_out, mci->mci_in);
2823 /* set {client_flags} */
2824 if (ClientSettings[addr.sa.sa_family].d_mflags != NULL)
2826 macdefine(&mci->mci_macro, A_PERM,
2827 macid("{client_flags}"),
2828 ClientSettings[addr.sa.sa_family].d_mflags);
2831 macdefine(&mci->mci_macro, A_PERM,
2832 macid("{client_flags}"), "");
2834 /* "add" {client_flags} to bitmap */
2835 if (bitnset(D_IFNHELO, ClientSettings[addr.sa.sa_family].d_flags))
2837 /* look for just this one flag */
2838 setbitn(D_IFNHELO, d_flags);
2841 /* find out name for Interface through which we connect */
2843 if (getsockname(s, &addr.sa, &len) == 0)
2848 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2849 macid("{if_addr_out}"), anynet_ntoa(&addr));
2850 (void) sm_snprintf(family, sizeof(family), "%d",
2852 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2853 macid("{if_family_out}"), family);
2855 name = hostnamebyanyaddr(&addr);
2856 macdefine(&BlankEnvelope.e_macro, A_TEMP,
2857 macid("{if_name_out}"), name);
2860 /* log connection information */
2861 sm_syslog(LOG_INFO, e->e_id,
2862 "SMTP outgoing connect on %.40s", name);
2864 if (bitnset(D_IFNHELO, d_flags))
2866 if (name[0] != '[' && strchr(name, '.') != NULL)
2867 mci->mci_heloname = newstr(name);
2872 macdefine(&BlankEnvelope.e_macro, A_PERM,
2873 macid("{if_name_out}"), NULL);
2874 macdefine(&BlankEnvelope.e_macro, A_PERM,
2875 macid("{if_addr_out}"), NULL);
2876 macdefine(&BlankEnvelope.e_macro, A_PERM,
2877 macid("{if_family_out}"), NULL);
2880 /* Use the configured HeloName as appropriate */
2881 if (HeloName != NULL && HeloName[0] != '\0')
2883 SM_FREE_CLR(mci->mci_heloname);
2884 mci->mci_heloname = newstr(HeloName);
2887 mci_setstat(mci, EX_OK, NULL, NULL);
2892 connecttimeout(ignore)
2896 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
2897 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
2902 longjmp(CtxConnectTimeout, 1);
2905 ** MAKECONNECTION_DS -- make a connection to a domain socket.
2908 ** mux_path -- the path of the socket to connect to.
2909 ** mci -- a pointer to the mail connection information
2910 ** structure to be filled in.
2913 ** An exit code telling whether the connection could be
2914 ** made and if not why not.
2922 makeconnection_ds(mux_path, mci)
2927 int rval, save_errno;
2928 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_ROOTOK|SFF_EXECOK;
2929 struct sockaddr_un unix_addr;
2931 /* if not safe, don't connect */
2932 rval = safefile(mux_path, RunAsUid, RunAsGid, RunAsUserName,
2933 sff, S_IRUSR|S_IWUSR, NULL);
2937 syserr("makeconnection_ds: unsafe domain socket %s",
2939 mci_setstat(mci, EX_TEMPFAIL, "4.3.5", NULL);
2944 /* prepare address structure */
2945 memset(&unix_addr, '\0', sizeof(unix_addr));
2946 unix_addr.sun_family = AF_UNIX;
2948 if (strlen(mux_path) >= sizeof(unix_addr.sun_path))
2950 syserr("makeconnection_ds: domain socket name %s too long",
2953 /* XXX why TEMPFAIL but 5.x.y ? */
2954 mci_setstat(mci, EX_TEMPFAIL, "5.3.5", NULL);
2955 errno = ENAMETOOLONG;
2956 return EX_UNAVAILABLE;
2958 (void) sm_strlcpy(unix_addr.sun_path, mux_path,
2959 sizeof(unix_addr.sun_path));
2961 /* initialize domain socket */
2962 sock = socket(AF_UNIX, SOCK_STREAM, 0);
2966 syserr("makeconnection_ds: could not create domain socket %s",
2968 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2973 /* connect to server */
2974 if (connect(sock, (struct sockaddr *) &unix_addr,
2975 sizeof(unix_addr)) == -1)
2978 syserr("Could not connect to socket %s", mux_path);
2979 mci_setstat(mci, EX_TEMPFAIL, "4.4.1", NULL);
2985 /* connection ok, put it into canonical form */
2986 mci->mci_out = NULL;
2987 if ((mci->mci_out = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2988 (void *) &sock, SM_IO_WRONLY_B, NULL))
2990 || (sock = dup(sock)) < 0 ||
2991 (mci->mci_in = sm_io_open(SmFtStdiofd, SM_TIME_DEFAULT,
2992 (void *) &sock, SM_IO_RDONLY_B, NULL))
2996 syserr("cannot open SMTP client channel, fd=%d", sock);
2997 mci_setstat(mci, EX_TEMPFAIL, "4.4.5", NULL);
2998 if (mci->mci_out != NULL)
2999 (void) sm_io_close(mci->mci_out, SM_TIME_DEFAULT);
3004 sm_io_automode(mci->mci_out, mci->mci_in);
3006 mci_setstat(mci, EX_OK, NULL, NULL);
3010 #endif /* NETUNIX */
3012 ** SHUTDOWN_DAEMON -- Performs a clean shutdown of the daemon
3021 ** closes control socket, exits.
3030 sm_allsignals(true);
3032 reason = ShutdownRequest;
3033 ShutdownRequest = NULL;
3037 sm_syslog(LOG_INFO, CurEnv->e_id, "stopping daemon, reason=%s",
3038 reason == NULL ? "implicit call" : reason);
3041 closecontrolsocket(true);
3046 for (i = 0; i < NDaemons; i++)
3048 if (Daemons[i].d_socket >= 0)
3050 (void) close(Daemons[i].d_socket);
3051 Daemons[i].d_socket = -1;
3054 /* Remove named sockets */
3055 if (Daemons[i].d_addr.sa.sa_family == AF_UNIX)
3058 long sff = SFF_SAFEDIRPATH|SFF_OPENASROOT|SFF_NOLINK|SFF_MUSTOWN|SFF_EXECOK|SFF_CREAT;
3060 /* if not safe, don't use it */
3061 rval = safefile(Daemons[i].d_addr.sunix.sun_path,
3064 S_IRUSR|S_IWUSR, NULL);
3066 unlink(Daemons[i].d_addr.sunix.sun_path) < 0)
3068 sm_syslog(LOG_WARNING, NOQID,
3069 "Could not remove daemon %s socket: %s: %s",
3071 Daemons[i].d_addr.sunix.sun_path,
3072 sm_errstring(errno));
3075 #endif /* NETUNIX */
3079 finis(false, true, EX_OK);
3082 ** RESTART_DAEMON -- Performs a clean restart of the daemon
3091 ** restarts the daemon or exits if restart fails.
3094 /* Make a non-DFL/IGN signal a noop */
3095 #define SM_NOOP_SIGNAL(sig, old) \
3098 (old) = sm_signal((sig), sm_signal_noop); \
3099 if ((old) == SIG_IGN || (old) == SIG_DFL) \
3100 (void) sm_signal((sig), (old)); \
3109 sigfunc_t ignore, oalrm, ousr1;
3110 extern int DtableSize;
3112 /* clear the events to turn off SIGALRMs */
3114 sm_allsignals(true);
3116 reason = RestartRequest;
3117 RestartRequest = NULL;
3120 if (SaveArgv[0][0] != '/')
3123 sm_syslog(LOG_INFO, NOQID,
3124 "could not restart: need full path");
3125 finis(false, true, EX_OSFILE);
3129 sm_syslog(LOG_INFO, NOQID, "restarting %s due to %s",
3131 reason == NULL ? "implicit call" : reason);
3133 closecontrolsocket(true);
3135 cleanup_shm(DaemonPid == getpid());
3136 #endif /* SM_CONF_SHM */
3138 /* close locked pid file */
3139 close_sendmail_pid();
3142 ** Want to drop to the user who started the process in all cases
3143 ** *but* when running as "smmsp" for the clientmqueue queue run
3144 ** daemon. In that case, UseMSP will be true, RunAsUid should not
3145 ** be root, and RealUid should be either 0 or RunAsUid.
3148 drop = !(UseMSP && RunAsUid != 0 &&
3149 (RealUid == 0 || RealUid == RunAsUid));
3151 if (drop_privileges(drop) != EX_OK)
3154 sm_syslog(LOG_ALERT, NOQID,
3155 "could not drop privileges: %s",
3156 sm_errstring(errno));
3157 finis(false, true, EX_OSERR);
3161 sm_close_on_exec(STDERR_FILENO + 1, DtableSize);
3164 ** Need to allow signals before execve() to make them "harmless".
3165 ** However, the default action can be "terminate", so it isn't
3166 ** really harmless. Setting signals to IGN will cause them to be
3167 ** ignored in the new process to, so that isn't a good alternative.
3170 SM_NOOP_SIGNAL(SIGALRM, oalrm);
3171 SM_NOOP_SIGNAL(SIGCHLD, ignore);
3172 SM_NOOP_SIGNAL(SIGHUP, ignore);
3173 SM_NOOP_SIGNAL(SIGINT, ignore);
3174 SM_NOOP_SIGNAL(SIGPIPE, ignore);
3175 SM_NOOP_SIGNAL(SIGTERM, ignore);
3177 SM_NOOP_SIGNAL(SIGUSR1, ousr1);
3178 #endif /* SIGUSR1 */
3180 /* Turn back on signals */
3181 sm_allsignals(false);
3183 (void) execve(SaveArgv[0], (ARGV_T) SaveArgv, (ARGV_T) ExternalEnviron);
3186 /* block signals again and restore needed signals */
3187 sm_allsignals(true);
3189 /* For finis() events */
3190 (void) sm_signal(SIGALRM, oalrm);
3193 /* For debugging finis() */
3194 (void) sm_signal(SIGUSR1, ousr1);
3195 #endif /* SIGUSR1 */
3199 sm_syslog(LOG_ALERT, NOQID, "could not exec %s: %s",
3200 SaveArgv[0], sm_errstring(errno));
3201 finis(false, true, EX_OSFILE);
3205 ** MYHOSTNAME -- return the name of this host.
3208 ** hostbuf -- a place to return the name of this host.
3209 ** size -- the size of hostbuf.
3212 ** A list of aliases for this host.
3215 ** Adds numeric codes to $=w.
3219 myhostname(hostbuf, size)
3223 register struct hostent *hp;
3225 if (gethostname(hostbuf, size) < 0 || hostbuf[0] == '\0')
3226 (void) sm_strlcpy(hostbuf, "localhost", size);
3227 hp = sm_gethostbyname(hostbuf, InetMode);
3228 #if NETINET && NETINET6
3229 if (hp == NULL && InetMode == AF_INET6)
3232 ** It's possible that this IPv6 enabled machine doesn't
3233 ** actually have any IPv6 interfaces and, therefore, no
3234 ** IPv6 addresses. Fall back to AF_INET.
3237 hp = sm_gethostbyname(hostbuf, AF_INET);
3239 #endif /* NETINET && NETINET6 */
3242 if (strchr(hp->h_name, '.') != NULL || strchr(hostbuf, '.') == NULL)
3243 (void) cleanstrcpy(hostbuf, hp->h_name, size);
3246 if (strchr(hostbuf, '.') == NULL)
3250 domainname = ni_propval("/locations", NULL, "resolver",
3252 if (domainname != NULL &&
3253 strlen(domainname) + strlen(hostbuf) + 1 < size)
3254 (void) sm_strlcat2(hostbuf, ".", domainname, size);
3256 #endif /* NETINFO */
3259 ** If there is still no dot in the name, try looking for a
3263 if (strchr(hostbuf, '.') == NULL)
3267 for (ha = hp->h_aliases; ha != NULL && *ha != NULL; ha++)
3269 if (strchr(*ha, '.') != NULL)
3271 (void) cleanstrcpy(hostbuf, *ha, size - 1);
3272 hostbuf[size - 1] = '\0';
3279 ** If _still_ no dot, wait for a while and try again -- it is
3280 ** possible that some service is starting up. This can result
3281 ** in excessive delays if the system is badly configured, but
3282 ** there really isn't a way around that, particularly given that
3283 ** the config file hasn't been read at this point.
3284 ** All in all, a bit of a mess.
3287 if (strchr(hostbuf, '.') == NULL &&
3288 !getcanonname(hostbuf, size, true, NULL))
3290 sm_syslog(LocalDaemon ? LOG_WARNING : LOG_CRIT, NOQID,
3291 "My unqualified host name (%s) unknown; sleeping for retry",
3293 message("My unqualified host name (%s) unknown; sleeping for retry",
3296 if (!getcanonname(hostbuf, size, true, NULL))
3298 sm_syslog(LocalDaemon ? LOG_WARNING : LOG_ALERT, NOQID,
3299 "unable to qualify my own domain name (%s) -- using short name",
3301 message("WARNING: unable to qualify my own domain name (%s) -- using short name",
3308 ** ADDRCMP -- compare two host addresses
3311 ** hp -- hostent structure for the first address
3312 ** ha -- actual first address
3313 ** sa -- second address
3316 ** 0 -- if ha and sa match
3317 ** else -- they don't match
3328 #endif /* NETINET6 */
3330 switch (sa->sa.sa_family)
3334 if (hp->h_addrtype == AF_INET)
3335 return memcmp(ha, (char *) &sa->sin.sin_addr, INADDRSZ);
3337 #endif /* NETINET */
3341 a = (unsigned char *) &sa->sin6.sin6_addr;
3343 /* Straight binary comparison */
3344 if (hp->h_addrtype == AF_INET6)
3345 return memcmp(ha, a, IN6ADDRSZ);
3347 /* If IPv4-mapped IPv6 address, compare the IPv4 section */
3348 if (hp->h_addrtype == AF_INET &&
3349 IN6_IS_ADDR_V4MAPPED(&sa->sin6.sin6_addr))
3350 return memcmp(a + IN6ADDRSZ - INADDRSZ, ha, INADDRSZ);
3352 #endif /* NETINET6 */
3357 ** GETAUTHINFO -- get the real host name associated with a file descriptor
3359 ** Uses RFC1413 protocol to try to get info from the other end.
3362 ** fd -- the descriptor
3363 ** may_be_forged -- an outage that is set to true if the
3364 ** forward lookup of RealHostName does not match
3365 ** RealHostAddr; set to false if they do match.
3368 ** The user@host information associated with this descriptor.
3371 static jmp_buf CtxAuthTimeout;
3378 ** NOTE: THIS CAN BE CALLED FROM A SIGNAL HANDLER. DO NOT ADD
3379 ** ANYTHING TO THIS ROUTINE UNLESS YOU KNOW WHAT YOU ARE
3384 longjmp(CtxAuthTimeout, 1);
3388 getauthinfo(fd, may_be_forged)
3390 bool *may_be_forged;
3392 unsigned short SM_NONVOLATILE port = 0;
3393 SOCKADDR_LEN_T falen;
3394 register char *volatile p = NULL;
3396 SOCKADDR_LEN_T lalen;
3397 #ifndef NO_GETSERVBYNAME
3398 register struct servent *sp;
3400 static unsigned short port4 = 0;
3401 # endif /* NETINET */
3403 static unsigned short port6 = 0;
3404 # endif /* NETINET6 */
3405 #endif /* ! NO_GETSERVBYNAME */
3412 char *ostype = NULL;
3414 char ibuf[MAXNAME + 1];
3415 static char hbuf[MAXNAME + MAXAUTHINFO + 11];
3417 *may_be_forged = true;
3418 falen = sizeof(RealHostAddr);
3419 if (isatty(fd) || (i = getpeername(fd, &RealHostAddr.sa, &falen)) < 0 ||
3420 falen <= 0 || RealHostAddr.sa.sa_family == 0)
3425 ** ENOTSOCK is OK: bail on anything else, but reset
3426 ** errno in this case, so a mis-report doesn't
3430 if (errno != ENOTSOCK)
3435 *may_be_forged = false;
3436 (void) sm_strlcpyn(hbuf, sizeof(hbuf), 2, RealUserName,
3439 sm_dprintf("getauthinfo: %s\n", hbuf);
3443 if (RealHostName == NULL)
3445 /* translate that to a host name */
3446 RealHostName = newstr(hostnamebyanyaddr(&RealHostAddr));
3447 if (strlen(RealHostName) > MAXNAME)
3448 RealHostName[MAXNAME] = '\0'; /* XXX - 1 ? */
3451 /* cross check RealHostName with forward DNS lookup */
3452 if (anynet_ntoa(&RealHostAddr)[0] == '[' ||
3453 RealHostName[0] == '[')
3454 *may_be_forged = false;
3459 family = RealHostAddr.sa.sa_family;
3460 #if NETINET6 && NEEDSGETIPNODE
3462 ** If RealHostAddr is an IPv6 connection with an
3463 ** IPv4-mapped address, we need RealHostName's IPv4
3464 ** address(es) for addrcmp() to compare against
3467 ** Actually, we only need to do this for systems
3468 ** which NEEDSGETIPNODE since the real getipnodebyname()
3469 ** already does V4MAPPED address via the AI_V4MAPPEDCFG
3470 ** flag. A better fix to this problem is to add this
3471 ** functionality to our stub getipnodebyname().
3474 if (family == AF_INET6 &&
3475 IN6_IS_ADDR_V4MAPPED(&RealHostAddr.sin6.sin6_addr))
3477 #endif /* NETINET6 && NEEDSGETIPNODE */
3479 /* try to match the reverse against the forward lookup */
3480 hp = sm_gethostbyname(RealHostName, family);
3483 for (ha = hp->h_addr_list; *ha != NULL; ha++)
3485 if (addrcmp(hp, *ha, &RealHostAddr) == 0)
3487 *may_be_forged = false;
3494 #endif /* NETINET6 */
3498 if (TimeOuts.to_ident == 0)
3502 switch (RealHostAddr.sa.sa_family)
3506 if (getsockname(fd, &la.sa, &lalen) < 0 ||
3508 la.sa.sa_family != AF_INET)
3513 port = RealHostAddr.sin.sin_port;
3515 /* create ident query */
3516 (void) sm_snprintf(ibuf, sizeof(ibuf), "%d,%d\r\n",
3517 ntohs(RealHostAddr.sin.sin_port),
3518 ntohs(la.sin.sin_port));
3520 /* create local address */
3521 la.sin.sin_port = 0;
3523 /* create foreign address */
3524 # ifdef NO_GETSERVBYNAME
3525 RealHostAddr.sin.sin_port = htons(113);
3526 # else /* NO_GETSERVBYNAME */
3529 ** getservbyname() consumes about 5% of the time
3530 ** when receiving a small message (almost all of the time
3531 ** spent in this routine).
3532 ** Hence we store the port in a static variable
3533 ** to save this time.
3534 ** The portnumber shouldn't change very often...
3535 ** This code makes the assumption that the port number
3541 sp = getservbyname("auth", "tcp");
3547 RealHostAddr.sin.sin_port = port4;
3549 # endif /* NO_GETSERVBYNAME */
3550 #endif /* NETINET */
3554 if (getsockname(fd, &la.sa, &lalen) < 0 ||
3556 la.sa.sa_family != AF_INET6)
3561 port = RealHostAddr.sin6.sin6_port;
3563 /* create ident query */
3564 (void) sm_snprintf(ibuf, sizeof(ibuf), "%d,%d\r\n",
3565 ntohs(RealHostAddr.sin6.sin6_port),
3566 ntohs(la.sin6.sin6_port));
3568 /* create local address */
3569 la.sin6.sin6_port = 0;
3571 /* create foreign address */
3572 # ifdef NO_GETSERVBYNAME
3573 RealHostAddr.sin6.sin6_port = htons(113);
3574 # else /* NO_GETSERVBYNAME */
3577 sp = getservbyname("auth", "tcp");
3583 RealHostAddr.sin6.sin6_port = port6;
3585 # endif /* NO_GETSERVBYNAME */
3586 #endif /* NETINET6 */
3593 if (setjmp(CtxAuthTimeout) != 0)
3600 /* put a timeout around the whole thing */
3601 ev = sm_setevent(TimeOuts.to_ident, authtimeout, 0);
3603 /* connect to foreign IDENT server using same address as SMTP socket */
3604 s = socket(la.sa.sa_family, SOCK_STREAM, 0);
3610 if (bind(s, &la.sa, lalen) < 0 ||
3611 connect(s, &RealHostAddr.sa, lalen) < 0)
3615 sm_dprintf("getauthinfo: sent %s", ibuf);
3618 if (write(s, ibuf, strlen(ibuf)) < 0)
3623 nleft = sizeof(ibuf) - 1;
3624 while ((i = read(s, p, nleft)) > 0)
3631 if ((s = strchr(ibuf, '\n')) != NULL)
3645 if (i < 0 || p == &ibuf[0])
3648 if (p >= &ibuf[2] && *--p == '\n' && *--p == '\r')
3653 sm_dprintf("getauthinfo: got %s\n", ibuf);
3656 p = strchr(ibuf, ':');
3659 /* malformed response */
3662 while (isascii(*++p) && isspace(*p))
3664 if (sm_strncasecmp(p, "userid", 6) != 0)
3666 /* presumably an error string */
3670 while (isascii(*p) && isspace(*p))
3674 /* either useridxx or malformed response */
3678 /* p now points to the OSTYPE field */
3679 while (isascii(*p) && isspace(*p))
3685 /* malformed response */
3693 charset = strchr(ostype, ',');
3694 if (charset != NULL)
3698 /* 1413 says don't do this -- but it's broken otherwise */
3699 while (isascii(*++p) && isspace(*p))
3702 /* p now points to the authenticated name -- copy carefully */
3703 if (sm_strncasecmp(ostype, "other", 5) == 0 &&
3704 (ostype[5] == ' ' || ostype[5] == '\0'))
3706 (void) sm_strlcpy(hbuf, "IDENT:", sizeof(hbuf));
3707 cleanstrcpy(&hbuf[6], p, MAXAUTHINFO);
3710 cleanstrcpy(hbuf, p, MAXAUTHINFO);
3712 (void) sm_strlcpyn(&hbuf[len], sizeof(hbuf) - len, 2, "@",
3713 RealHostName == NULL ? "localhost" : RealHostName);
3721 /* put back the original incoming port */
3722 switch (RealHostAddr.sa.sa_family)
3727 RealHostAddr.sin.sin_port = port;
3729 #endif /* NETINET */
3734 RealHostAddr.sin6.sin6_port = port;
3736 #endif /* NETINET6 */
3739 if (RealHostName == NULL)
3742 sm_dprintf("getauthinfo: NULL\n");
3745 (void) sm_strlcpy(hbuf, RealHostName, sizeof(hbuf));
3749 # ifndef GET_IPOPT_DST
3750 # define GET_IPOPT_DST(dst) (dst)
3751 # endif /* ! GET_IPOPT_DST */
3753 ** Extract IP source routing information.
3755 ** Format of output for a connection from site a through b
3757 ** loose: @site-c@site-b:site-a
3758 ** strict: !@site-c@site-b:site-a
3760 ** o - pointer within ipopt_list structure.
3761 ** q - pointer within ls/ss rr route data
3762 ** p - pointer to hbuf
3765 if (RealHostAddr.sa.sa_family == AF_INET)
3767 SOCKOPT_LEN_T ipoptlen;
3772 struct IPOPTION ipopt;
3774 ipoptlen = sizeof(ipopt);
3775 if (getsockopt(fd, IPPROTO_IP, IP_OPTIONS,
3776 (char *) &ipopt, &ipoptlen) < 0)
3780 o = (unsigned char *) ipopt.IP_LIST;
3781 while (o != NULL && o < (unsigned char *) &ipopt + ipoptlen)
3797 ** o[0] is the option type (loose/strict).
3798 ** o[1] is the length of this option,
3799 ** including option type and
3801 ** o[2] is the pointer into the route
3803 ** o[3] begins the route data.
3806 p = &hbuf[strlen(hbuf)];
3807 l = sizeof(hbuf) - (hbuf - p) - 6;
3808 (void) sm_snprintf(p, SPACELEFT(hbuf, p),
3810 *o == IPOPT_SSRR ? "!" : "",
3811 l > 240 ? 120 : l / 2,
3812 inet_ntoa(GET_IPOPT_DST(ipopt.IP_DST)));
3817 j = o[1] / sizeof(struct in_addr) - 1;
3819 /* q skips length and router pointer to data */
3821 for ( ; j >= 0; j--)
3823 struct in_addr addr;
3825 memcpy(&addr, q, sizeof(addr));
3826 (void) sm_snprintf(p,
3836 q += sizeof(struct in_addr);
3842 /* Skip over option */
3847 (void) sm_snprintf(p, SPACELEFT(hbuf, p), "]");
3852 #endif /* IP_SRCROUTE */
3853 if (RealHostName != NULL && RealHostName[0] != '[')
3855 p = &hbuf[strlen(hbuf)];
3856 (void) sm_snprintf(p, SPACELEFT(hbuf, p), " [%.100s]",
3857 anynet_ntoa(&RealHostAddr));
3861 p = &hbuf[strlen(hbuf)];
3862 (void) sm_strlcpy(p, " (may be forged)", SPACELEFT(hbuf, p));
3863 macdefine(&BlankEnvelope.e_macro, A_PERM,
3864 macid("{client_resolve}"), "FORGED");
3869 #endif /* IP_SRCROUTE */
3871 /* put back the original incoming port */
3872 switch (RealHostAddr.sa.sa_family)
3877 RealHostAddr.sin.sin_port = port;
3879 #endif /* NETINET */
3884 RealHostAddr.sin6.sin6_port = port;
3886 #endif /* NETINET6 */
3890 sm_dprintf("getauthinfo: %s\n", hbuf);
3894 ** HOST_MAP_LOOKUP -- turn a hostname into canonical form
3897 ** map -- a pointer to this map.
3898 ** name -- the (presumably unqualified) hostname.
3899 ** av -- unused -- for compatibility with other mapping
3901 ** statp -- an exit status (out parameter) -- set to
3902 ** EX_TEMPFAIL if the name server is unavailable.
3905 ** The mapping, if found.
3906 ** NULL if no mapping found.
3909 ** Looks up the host specified in hbuf. If it is not
3910 ** the canonical name for that host, return the canonical
3911 ** name (unless MF_MATCHONLY is set, which will cause the
3912 ** status only to be returned).
3916 host_map_lookup(map, name, av, statp)
3922 register struct hostent *hp;
3924 struct in_addr in_addr;
3925 #endif /* NETINET */
3927 struct in6_addr in6_addr;
3928 #endif /* NETINET6 */
3929 char *cp, *ans = NULL;
3933 time_t SM_NONVOLATILE retrans = 0;
3934 int SM_NONVOLATILE retry = 0;
3935 #endif /* NAMED_BIND */
3936 char hbuf[MAXNAME + 1];
3939 ** See if we have already looked up this name. If so, just
3940 ** return it (unless expired).
3944 s = stab(name, ST_NAMECANON, ST_ENTER);
3945 if (bitset(NCF_VALID, s->s_namecanon.nc_flags) &&
3946 s->s_namecanon.nc_exp >= now)
3949 sm_dprintf("host_map_lookup(%s) => CACHE %s\n",
3951 s->s_namecanon.nc_cname == NULL
3953 : s->s_namecanon.nc_cname);
3954 errno = s->s_namecanon.nc_errno;
3955 SM_SET_H_ERRNO(s->s_namecanon.nc_herrno);
3956 *statp = s->s_namecanon.nc_stat;
3957 if (*statp == EX_TEMPFAIL)
3959 CurEnv->e_status = "4.4.3";
3960 message("851 %s: Name server timeout",
3961 shortenstring(name, 33));
3963 if (*statp != EX_OK)
3965 if (s->s_namecanon.nc_cname == NULL)
3967 syserr("host_map_lookup(%s): bogus NULL cache entry, errno=%d, h_errno=%d",
3969 s->s_namecanon.nc_errno,
3970 s->s_namecanon.nc_herrno);
3973 if (bitset(MF_MATCHONLY, map->map_mflags))
3974 cp = map_rewrite(map, name, strlen(name), NULL);
3976 cp = map_rewrite(map,
3977 s->s_namecanon.nc_cname,
3978 strlen(s->s_namecanon.nc_cname),
3984 ** If we are running without a regular network connection (usually
3985 ** dial-on-demand) and we are just queueing, we want to avoid DNS
3986 ** lookups because those could try to connect to a server.
3989 if (CurEnv->e_sendmode == SM_DEFER &&
3990 bitset(MF_DEFER, map->map_mflags))
3993 sm_dprintf("host_map_lookup(%s) => DEFERRED\n", name);
3994 *statp = EX_TEMPFAIL;
3999 ** If first character is a bracket, then it is an address
4000 ** lookup. Address is copied into a temporary buffer to
4001 ** strip the brackets and to preserve name if address is
4006 sm_dprintf("host_map_lookup(%s) => ", name);
4008 if (map->map_timeout > 0)
4010 retrans = _res.retrans;
4011 _res.retrans = map->map_timeout;
4013 if (map->map_retry > 0)
4016 _res.retry = map->map_retry;
4018 #endif /* NAMED_BIND */
4020 /* set default TTL */
4021 s->s_namecanon.nc_exp = now + SM_DEFAULT_TTL;
4026 (void) sm_strlcpy(hbuf, name, sizeof(hbuf));
4027 if (getcanonname(hbuf, sizeof(hbuf) - 1, !HasWildcardMX, &ttl))
4031 s->s_namecanon.nc_exp = now + SM_MIN(ttl,
4037 if ((cp = strchr(name, ']')) == NULL)
4040 sm_dprintf("FAILED\n");
4047 if ((in_addr.s_addr = inet_addr(&name[1])) != INADDR_NONE)
4048 hp = sm_gethostbyaddr((char *)&in_addr,
4050 #endif /* NETINET */
4053 anynet_pton(AF_INET6, &name[1], &in6_addr) == 1)
4054 hp = sm_gethostbyaddr((char *)&in6_addr,
4055 IN6ADDRSZ, AF_INET6);
4056 #endif /* NETINET6 */
4061 /* found a match -- copy out */
4062 ans = denlstring((char *) hp->h_name, true, true);
4064 if (ans == hp->h_name)
4066 static char n[MAXNAME + 1];
4068 /* hp->h_name is about to disappear */
4069 (void) sm_strlcpy(n, ans, sizeof(n));
4074 #endif /* NETINET6 */
4078 if (map->map_timeout > 0)
4079 _res.retrans = retrans;
4080 if (map->map_retry > 0)
4082 #endif /* NAMED_BIND */
4084 s->s_namecanon.nc_flags |= NCF_VALID; /* will be soon */
4086 /* Found an answer */
4089 s->s_namecanon.nc_stat = *statp = EX_OK;
4090 if (s->s_namecanon.nc_cname != NULL)
4091 sm_free(s->s_namecanon.nc_cname);
4092 s->s_namecanon.nc_cname = sm_strdup_x(ans);
4093 if (bitset(MF_MATCHONLY, map->map_mflags))
4094 cp = map_rewrite(map, name, strlen(name), NULL);
4096 cp = map_rewrite(map, ans, strlen(ans), av);
4098 sm_dprintf("FOUND %s\n", ans);
4103 /* No match found */
4104 s->s_namecanon.nc_errno = errno;
4106 s->s_namecanon.nc_herrno = h_errno;
4108 sm_dprintf("FAIL (%d)\n", h_errno);
4114 CurEnv->e_status = "4.4.3";
4115 message("851 %s: Name server timeout",
4116 shortenstring(name, 33));
4118 *statp = EX_TEMPFAIL;
4121 case HOST_NOT_FOUND:
4127 *statp = EX_SOFTWARE;
4131 *statp = EX_UNAVAILABLE;
4134 #else /* NAMED_BIND */
4136 sm_dprintf("FAIL\n");
4138 #endif /* NAMED_BIND */
4139 s->s_namecanon.nc_stat = *statp;
4143 ** HOST_MAP_INIT -- initialize host class structures
4146 ** map -- a pointer to this map.
4147 ** args -- argument string.
4154 host_map_init(map, args)
4158 register char *p = args;
4162 while (isascii(*p) && isspace(*p))
4173 map->map_tapp = ++p;
4177 map->map_mflags |= MF_MATCHONLY;
4181 map->map_mflags |= MF_NODEFER;
4184 case 'S': /* only for consistency */
4185 map->map_spacesub = *++p;
4189 map->map_mflags |= MF_DEFER;
4196 while (isascii(*++p) && isspace(*p))
4201 map->map_timeout = convtime(p, 's');
4208 while (isascii(*++p) && isspace(*p))
4210 map->map_retry = atoi(p);
4213 while (*p != '\0' && !(isascii(*p) && isspace(*p)))
4218 if (map->map_app != NULL)
4219 map->map_app = newstr(map->map_app);
4220 if (map->map_tapp != NULL)
4221 map->map_tapp = newstr(map->map_tapp);
4227 ** ANYNET_NTOP -- convert an IPv6 network address to printable form.
4230 ** s6a -- a pointer to an in6_addr structure.
4231 ** dst -- buffer to store result in
4232 ** dst_len -- size of dst buffer
4235 ** A printable version of that structure.
4239 anynet_ntop(s6a, dst, dst_len)
4240 struct in6_addr *s6a;
4246 if (IN6_IS_ADDR_V4MAPPED(s6a))
4247 ap = (char *) inet_ntop(AF_INET,
4248 &s6a->s6_addr[IN6ADDRSZ - INADDRSZ],
4255 /* Save pointer to beginning of string */
4258 /* Add IPv6: protocol tag */
4259 sz = sm_strlcpy(dst, "IPv6:", dst_len);
4264 if (UseCompressedIPv6Addresses)
4265 ap = (char *) inet_ntop(AF_INET6, s6a, dst, dst_len);
4267 ap = sm_inet6_ntop(s6a, dst, dst_len);
4268 /* Restore pointer to beginning of string */
4276 ** ANYNET_PTON -- convert printed form to network address.
4278 ** Wrapper for inet_pton() which handles IPv6: labels.
4281 ** family -- address family
4283 ** dst -- destination address structure
4286 ** 1 if the address was valid
4287 ** 0 if the address wasn't parseable
4292 anynet_pton(family, src, dst)
4297 if (family == AF_INET6 && sm_strncasecmp(src, "IPv6:", 5) == 0)
4299 return inet_pton(family, src, dst);
4301 #endif /* NETINET6 */
4303 ** ANYNET_NTOA -- convert a network address to printable form.
4306 ** sap -- a pointer to a sockaddr structure.
4309 ** A printable version of that sockaddr.
4312 #ifdef USE_SOCK_STREAM
4315 # include <net/if_dl.h>
4316 # endif /* NETLINK */
4320 register SOCKADDR *sap;
4325 static char buf[100];
4327 /* check for null/zero family */
4330 if (sap->sa.sa_family == 0)
4333 switch (sap->sa.sa_family)
4337 if (sap->sunix.sun_path[0] != '\0')
4338 (void) sm_snprintf(buf, sizeof(buf), "[UNIX: %.64s]",
4339 sap->sunix.sun_path);
4341 (void) sm_strlcpy(buf, "[UNIX: localhost]", sizeof(buf));
4343 # endif /* NETUNIX */
4347 return (char *) inet_ntoa(sap->sin.sin_addr);
4348 # endif /* NETINET */
4352 ap = anynet_ntop(&sap->sin6.sin6_addr, buf, sizeof(buf));
4356 # endif /* NETINET6 */
4360 (void) sm_snprintf(buf, sizeof(buf), "[LINK: %s]",
4361 link_ntoa((struct sockaddr_dl *) &sap->sa));
4363 # endif /* NETLINK */
4365 /* this case is needed when nothing is #defined */
4366 /* in order to keep the switch syntactically correct */
4370 /* unknown family -- just dump bytes */
4371 (void) sm_snprintf(buf, sizeof(buf), "Family %d: ", sap->sa.sa_family);
4372 bp = &buf[strlen(buf)];
4373 ap = sap->sa.sa_data;
4374 for (l = sizeof(sap->sa.sa_data); --l >= 0; )
4376 (void) sm_snprintf(bp, SPACELEFT(buf, bp), "%02x:",
4384 ** HOSTNAMEBYANYADDR -- return name of host based on address
4387 ** sap -- SOCKADDR pointer
4390 ** text representation of host name.
4397 hostnamebyanyaddr(sap)
4398 register SOCKADDR *sap;
4400 register struct hostent *hp;
4403 # endif /* NAMED_BIND */
4405 struct in6_addr in6_addr;
4406 # endif /* NETINET6 */
4409 /* shorten name server timeout to avoid higher level timeouts */
4410 saveretry = _res.retry;
4411 if (_res.retry * _res.retrans > 20)
4412 _res.retry = 20 / _res.retrans;
4413 if (_res.retry == 0)
4415 # endif /* NAMED_BIND */
4417 switch (sap->sa.sa_family)
4421 hp = sm_gethostbyaddr((char *) &sap->sin.sin_addr,
4424 # endif /* NETINET */
4428 hp = sm_gethostbyaddr((char *) &sap->sin6.sin6_addr,
4429 IN6ADDRSZ, AF_INET6);
4431 # endif /* NETINET6 */
4435 hp = sm_gethostbyaddr((char *) &sap->siso.siso_addr,
4436 sizeof(sap->siso.siso_addr), AF_ISO);
4438 # endif /* NETISO */
4444 # endif /* NETUNIX */
4447 hp = sm_gethostbyaddr(sap->sa.sa_data, sizeof(sap->sa.sa_data),
4453 _res.retry = saveretry;
4454 # endif /* NAMED_BIND */
4456 # if NETINET || NETINET6
4457 if (hp != NULL && hp->h_name[0] != '['
4459 && inet_pton(AF_INET6, hp->h_name, &in6_addr) != 1
4460 # endif /* NETINET6 */
4462 && inet_addr(hp->h_name) == INADDR_NONE
4463 # endif /* NETINET */
4468 name = denlstring((char *) hp->h_name, true, true);
4470 if (name == hp->h_name)
4472 static char n[MAXNAME + 1];
4474 /* Copy the string, hp->h_name is about to disappear */
4475 (void) sm_strlcpy(n, name, sizeof(n));
4479 # endif /* NETINET6 */
4482 # endif /* NETINET || NETINET6 */
4490 # endif /* NETINET6 */
4493 if (sap->sa.sa_family == AF_UNIX && sap->sunix.sun_path[0] == '\0')
4495 # endif /* NETUNIX */
4497 static char buf[203];
4499 (void) sm_snprintf(buf, sizeof(buf), "[%.200s]",
4504 #endif /* USE_SOCK_STREAM */