1 /*
2 * Copyright (c) 1983 Eric P. Allman
3 * Copyright (c) 1988, 1993
4 * The Regents of the University of California. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. All advertising materials mentioning features or use of this software
15 * must display the following acknowledgement:
16 * This product includes software developed by the University of
17 * California, Berkeley and its contributors.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35 #include <errno.h>
36 #include "sendmail.h"
37
38 #ifndef lint
39 #ifdef DAEMON
40 static char sccsid[] = "@(#)daemon.c 8.48 (Berkeley) 4/18/94 (with daemon mode)";
41 #else
42 static char sccsid[] = "@(#)daemon.c 8.48 (Berkeley) 4/18/94 (without daemon mode)";
43 #endif
44 #endif /* not lint */
45
46 #ifdef DAEMON
47
48 # include <netdb.h>
49 # include <arpa/inet.h>
50
51 #if NAMED_BIND
52 # include <arpa/nameser.h>
53 # include <resolv.h>
54 #endif
55
56 /*
57 ** DAEMON.C -- routines to use when running as a daemon.
58 **
59 ** This entire file is highly dependent on the 4.2 BSD
60 ** interprocess communication primitives. No attempt has
61 ** been made to make this file portable to Version 7,
62 ** Version 6, MPX files, etc. If you should try such a
63 ** thing yourself, I recommend chucking the entire file
64 ** and starting from scratch. Basic semantics are:
65 **
66 ** getrequests()
67 ** Opens a port and initiates a connection.
68 ** Returns in a child. Must set InChannel and
69 ** OutChannel appropriately.
70 ** clrdaemon()
71 ** Close any open files associated with getting
72 ** the connection; this is used when running the queue,
73 ** etc., to avoid having extra file descriptors during
74 ** the queue run and to avoid confusing the network
75 ** code (if it cares).
76 ** makeconnection(host, port, outfile, infile, usesecureport)
77 ** Make a connection to the named host on the given
78 ** port. Set *outfile and *infile to the files
79 ** appropriate for communication. Returns zero on
80 ** success, else an exit status describing the
81 ** error.
82 ** host_map_lookup(map, hbuf, avp, pstat)
83 ** Convert the entry in hbuf into a canonical form.
84 */
85 /*
86 ** GETREQUESTS -- open mail IPC port and get requests.
87 **
88 ** Parameters:
89 ** none.
90 **
91 ** Returns:
92 ** none.
93 **
94 ** Side Effects:
95 ** Waits until some interesting activity occurs. When
96 ** it does, a child is created to process it, and the
97 ** parent waits for completion. Return from this
98 ** routine is always in the child. The file pointers
99 ** "InChannel" and "OutChannel" should be set to point
100 ** to the communication channel.
101 */
102
103 int DaemonSocket = -1; /* fd describing socket */
104 SOCKADDR DaemonAddr; /* socket for incoming */
105 int ListenQueueSize = 10; /* size of listen queue */
106 int TcpRcvBufferSize = 0; /* size of TCP receive buffer */
107 int TcpSndBufferSize = 0; /* size of TCP send buffer */
108
getrequests()109 getrequests()
110 {
111 int t;
112 bool refusingconnections = TRUE;
113 FILE *pidf;
114 int socksize;
115 #ifdef XDEBUG
116 bool j_has_dot;
117 #endif
118 extern void reapchild();
119
120 /*
121 ** Set up the address for the mailer.
122 */
123
124 if (DaemonAddr.sin.sin_family == 0)
125 DaemonAddr.sin.sin_family = AF_INET;
126 if (DaemonAddr.sin.sin_addr.s_addr == 0)
127 DaemonAddr.sin.sin_addr.s_addr = INADDR_ANY;
128 if (DaemonAddr.sin.sin_port == 0)
129 {
130 register struct servent *sp;
131
132 sp = getservbyname("smtp", "tcp");
133 if (sp == NULL)
134 {
135 syserr("554 service \"smtp\" unknown");
136 DaemonAddr.sin.sin_port = htons(25);
137 }
138 else
139 DaemonAddr.sin.sin_port = sp->s_port;
140 }
141
142 /*
143 ** Try to actually open the connection.
144 */
145
146 if (tTd(15, 1))
147 printf("getrequests: port 0x%x\n", DaemonAddr.sin.sin_port);
148
149 /* get a socket for the SMTP connection */
150 socksize = opendaemonsocket(TRUE);
151
152 (void) setsignal(SIGCHLD, reapchild);
153
154 /* write the pid to the log file for posterity */
155 pidf = fopen(PidFile, "w");
156 if (pidf != NULL)
157 {
158 extern char *CommandLineArgs;
159
160 /* write the process id on line 1 */
161 fprintf(pidf, "%d\n", getpid());
162
163 /* line 2 contains all command line flags */
164 fprintf(pidf, "%s\n", CommandLineArgs);
165
166 /* flush and close */
167 fclose(pidf);
168 }
169
170 #ifdef XDEBUG
171 {
172 char jbuf[MAXHOSTNAMELEN];
173
174 expand("\201j", jbuf, &jbuf[sizeof jbuf - 1], CurEnv);
175 j_has_dot = strchr(jbuf, '.') != NULL;
176 }
177 #endif
178
179 if (tTd(15, 1))
180 printf("getrequests: %d\n", DaemonSocket);
181
182 for (;;)
183 {
184 register int pid;
185 auto int lotherend;
186 extern bool refuseconnections();
187
188 /* see if we are rejecting connections */
189 CurrentLA = getla();
190 if (refuseconnections())
191 {
192 if (DaemonSocket >= 0)
193 {
194 /* close socket so peer will fail quickly */
195 (void) close(DaemonSocket);
196 DaemonSocket = -1;
197 }
198 refusingconnections = TRUE;
199 setproctitle("rejecting connections: load average: %d",
200 CurrentLA);
201 sleep(15);
202 continue;
203 }
204
205 if (refusingconnections)
206 {
207 /* start listening again */
208 (void) opendaemonsocket(FALSE);
209 setproctitle("accepting connections");
210 refusingconnections = FALSE;
211 }
212
213 #ifdef XDEBUG
214 /* check for disaster */
215 {
216 register STAB *s;
217 char jbuf[MAXHOSTNAMELEN];
218
219 expand("\201j", jbuf, &jbuf[sizeof jbuf - 1], CurEnv);
220 if ((s = stab(jbuf, ST_CLASS, ST_FIND)) == NULL ||
221 !bitnset('w', s->s_class))
222 {
223 dumpstate("daemon lost $j");
224 syslog(LOG_ALERT, "daemon process doesn't have $j in $=w; see syslog");
225 abort();
226 }
227 else if (j_has_dot && strchr(jbuf, '.') == NULL)
228 {
229 dumpstate("daemon $j lost dot");
230 syslog(LOG_ALERT, "daemon process $j lost dot; see syslog");
231 abort();
232 }
233 }
234 #endif
235
236 /* wait for a connection */
237 do
238 {
239 errno = 0;
240 lotherend = socksize;
241 t = accept(DaemonSocket,
242 (struct sockaddr *)&RealHostAddr, &lotherend);
243 } while (t < 0 && errno == EINTR);
244 if (t < 0)
245 {
246 syserr("getrequests: accept");
247 sleep(5);
248 continue;
249 }
250
251 /*
252 ** Create a subprocess to process the mail.
253 */
254
255 if (tTd(15, 2))
256 printf("getrequests: forking (fd = %d)\n", t);
257
258 pid = fork();
259 if (pid < 0)
260 {
261 syserr("daemon: cannot fork");
262 sleep(10);
263 (void) close(t);
264 continue;
265 }
266
267 if (pid == 0)
268 {
269 char *p;
270 extern char *hostnamebyanyaddr();
271
272 /*
273 ** CHILD -- return to caller.
274 ** Collect verified idea of sending host.
275 ** Verify calling user id if possible here.
276 */
277
278 (void) setsignal(SIGCHLD, SIG_DFL);
279 DisConnected = FALSE;
280
281 setproctitle("startup with %s",
282 anynet_ntoa(&RealHostAddr));
283
284 /* determine host name */
285 p = hostnamebyanyaddr(&RealHostAddr);
286 RealHostName = newstr(p);
287 setproctitle("startup with %s", p);
288
289 #ifdef LOG
290 if (LogLevel > 11)
291 {
292 /* log connection information */
293 syslog(LOG_INFO, "connect from %s (%s)",
294 RealHostName, anynet_ntoa(&RealHostAddr));
295 }
296 #endif
297
298 (void) close(DaemonSocket);
299 if ((InChannel = fdopen(t, "r")) == NULL ||
300 (t = dup(t)) < 0 ||
301 (OutChannel = fdopen(t, "w")) == NULL)
302 {
303 syserr("cannot open SMTP server channel, fd=%d", t);
304 exit(0);
305 }
306
307 /* should we check for illegal connection here? XXX */
308 #ifdef XLA
309 if (!xla_host_ok(RealHostName))
310 {
311 message("421 Too many SMTP sessions for this host");
312 exit(0);
313 }
314 #endif
315
316 if (tTd(15, 2))
317 printf("getreq: returning\n");
318 return;
319 }
320
321 /* close the port so that others will hang (for a while) */
322 (void) close(t);
323 }
324 /*NOTREACHED*/
325 }
326 /*
327 ** OPENDAEMONSOCKET -- open the SMTP socket
328 **
329 ** Deals with setting all appropriate options. DaemonAddr must
330 ** be set up in advance.
331 **
332 ** Parameters:
333 ** firsttime -- set if this is the initial open.
334 **
335 ** Returns:
336 ** Size in bytes of the daemon socket addr.
337 **
338 ** Side Effects:
339 ** Leaves DaemonSocket set to the open socket.
340 ** Exits if the socket cannot be created.
341 */
342
343 #define MAXOPENTRIES 10 /* maximum number of tries to open connection */
344
345 int
opendaemonsocket(firsttime)346 opendaemonsocket(firsttime)
347 bool firsttime;
348 {
349 int on = 1;
350 int socksize;
351 int ntries = 0;
352 int saveerrno;
353
354 if (tTd(15, 2))
355 printf("opendaemonsocket()\n");
356
357 do
358 {
359 if (ntries > 0)
360 sleep(5);
361 if (firsttime || DaemonSocket < 0)
362 {
363 DaemonSocket = socket(DaemonAddr.sa.sa_family, SOCK_STREAM, 0);
364 if (DaemonSocket < 0)
365 {
366 /* probably another daemon already */
367 saveerrno = errno;
368 syserr("opendaemonsocket: can't create server SMTP socket");
369 severe:
370 # ifdef LOG
371 if (LogLevel > 0)
372 syslog(LOG_ALERT, "problem creating SMTP socket");
373 # endif /* LOG */
374 DaemonSocket = -1;
375 continue;
376 }
377
378 /* turn on network debugging? */
379 if (tTd(15, 101))
380 (void) setsockopt(DaemonSocket, SOL_SOCKET,
381 SO_DEBUG, (char *)&on,
382 sizeof on);
383
384 (void) setsockopt(DaemonSocket, SOL_SOCKET,
385 SO_REUSEADDR, (char *)&on, sizeof on);
386 (void) setsockopt(DaemonSocket, SOL_SOCKET,
387 SO_KEEPALIVE, (char *)&on, sizeof on);
388
389 #ifdef SO_RCVBUF
390 if (TcpRcvBufferSize > 0)
391 {
392 if (setsockopt(DaemonSocket, SOL_SOCKET,
393 SO_RCVBUF,
394 (char *) &TcpRcvBufferSize,
395 sizeof(TcpRcvBufferSize)) < 0)
396 syserr("getrequests: setsockopt(SO_RCVBUF)");
397 }
398 #endif
399
400 switch (DaemonAddr.sa.sa_family)
401 {
402 # ifdef NETINET
403 case AF_INET:
404 socksize = sizeof DaemonAddr.sin;
405 break;
406 # endif
407
408 # ifdef NETISO
409 case AF_ISO:
410 socksize = sizeof DaemonAddr.siso;
411 break;
412 # endif
413
414 default:
415 socksize = sizeof DaemonAddr;
416 break;
417 }
418
419 if (bind(DaemonSocket, &DaemonAddr.sa, socksize) < 0)
420 {
421 saveerrno = errno;
422 syserr("getrequests: cannot bind");
423 (void) close(DaemonSocket);
424 goto severe;
425 }
426 }
427 if (!firsttime && listen(DaemonSocket, ListenQueueSize) < 0)
428 {
429 saveerrno = errno;
430 syserr("getrequests: cannot listen");
431 (void) close(DaemonSocket);
432 goto severe;
433 }
434 return socksize;
435 } while (ntries++ < MAXOPENTRIES && transienterror(saveerrno));
436 finis();
437 }
438 /*
439 ** CLRDAEMON -- reset the daemon connection
440 **
441 ** Parameters:
442 ** none.
443 **
444 ** Returns:
445 ** none.
446 **
447 ** Side Effects:
448 ** releases any resources used by the passive daemon.
449 */
450
clrdaemon()451 clrdaemon()
452 {
453 if (DaemonSocket >= 0)
454 (void) close(DaemonSocket);
455 DaemonSocket = -1;
456 }
457 /*
458 ** SETDAEMONOPTIONS -- set options for running the daemon
459 **
460 ** Parameters:
461 ** p -- the options line.
462 **
463 ** Returns:
464 ** none.
465 */
466
setdaemonoptions(p)467 setdaemonoptions(p)
468 register char *p;
469 {
470 if (DaemonAddr.sa.sa_family == AF_UNSPEC)
471 DaemonAddr.sa.sa_family = AF_INET;
472
473 while (p != NULL)
474 {
475 register char *f;
476 register char *v;
477
478 while (isascii(*p) && isspace(*p))
479 p++;
480 if (*p == '\0')
481 break;
482 f = p;
483 p = strchr(p, ',');
484 if (p != NULL)
485 *p++ = '\0';
486 v = strchr(f, '=');
487 if (v == NULL)
488 continue;
489 while (isascii(*++v) && isspace(*v))
490 continue;
491
492 switch (*f)
493 {
494 case 'F': /* address family */
495 if (isascii(*v) && isdigit(*v))
496 DaemonAddr.sa.sa_family = atoi(v);
497 #ifdef NETINET
498 else if (strcasecmp(v, "inet") == 0)
499 DaemonAddr.sa.sa_family = AF_INET;
500 #endif
501 #ifdef NETISO
502 else if (strcasecmp(v, "iso") == 0)
503 DaemonAddr.sa.sa_family = AF_ISO;
504 #endif
505 #ifdef NETNS
506 else if (strcasecmp(v, "ns") == 0)
507 DaemonAddr.sa.sa_family = AF_NS;
508 #endif
509 #ifdef NETX25
510 else if (strcasecmp(v, "x.25") == 0)
511 DaemonAddr.sa.sa_family = AF_CCITT;
512 #endif
513 else
514 syserr("554 Unknown address family %s in Family=option", v);
515 break;
516
517 case 'A': /* address */
518 switch (DaemonAddr.sa.sa_family)
519 {
520 #ifdef NETINET
521 case AF_INET:
522 if (isascii(*v) && isdigit(*v))
523 DaemonAddr.sin.sin_addr.s_addr = inet_network(v);
524 else
525 {
526 register struct netent *np;
527
528 np = getnetbyname(v);
529 if (np == NULL)
530 syserr("554 network \"%s\" unknown", v);
531 else
532 DaemonAddr.sin.sin_addr.s_addr = np->n_net;
533 }
534 break;
535 #endif
536
537 default:
538 syserr("554 Address= option unsupported for family %d",
539 DaemonAddr.sa.sa_family);
540 break;
541 }
542 break;
543
544 case 'P': /* port */
545 switch (DaemonAddr.sa.sa_family)
546 {
547 short port;
548
549 #ifdef NETINET
550 case AF_INET:
551 if (isascii(*v) && isdigit(*v))
552 DaemonAddr.sin.sin_port = htons(atoi(v));
553 else
554 {
555 register struct servent *sp;
556
557 sp = getservbyname(v, "tcp");
558 if (sp == NULL)
559 syserr("554 service \"%s\" unknown", v);
560 else
561 DaemonAddr.sin.sin_port = sp->s_port;
562 }
563 break;
564 #endif
565
566 #ifdef NETISO
567 case AF_ISO:
568 /* assume two byte transport selector */
569 if (isascii(*v) && isdigit(*v))
570 port = htons(atoi(v));
571 else
572 {
573 register struct servent *sp;
574
575 sp = getservbyname(v, "tcp");
576 if (sp == NULL)
577 syserr("554 service \"%s\" unknown", v);
578 else
579 port = sp->s_port;
580 }
581 bcopy((char *) &port, TSEL(&DaemonAddr.siso), 2);
582 break;
583 #endif
584
585 default:
586 syserr("554 Port= option unsupported for family %d",
587 DaemonAddr.sa.sa_family);
588 break;
589 }
590 break;
591
592 case 'L': /* listen queue size */
593 ListenQueueSize = atoi(v);
594 break;
595
596 case 'S': /* send buffer size */
597 TcpSndBufferSize = atoi(v);
598 break;
599
600 case 'R': /* receive buffer size */
601 TcpRcvBufferSize = atoi(v);
602 break;
603 }
604 }
605 }
606 /*
607 ** MAKECONNECTION -- make a connection to an SMTP socket on another machine.
608 **
609 ** Parameters:
610 ** host -- the name of the host.
611 ** port -- the port number to connect to.
612 ** mci -- a pointer to the mail connection information
613 ** structure to be filled in.
614 ** usesecureport -- if set, use a low numbered (reserved)
615 ** port to provide some rudimentary authentication.
616 **
617 ** Returns:
618 ** An exit code telling whether the connection could be
619 ** made and if not why not.
620 **
621 ** Side Effects:
622 ** none.
623 */
624
625 SOCKADDR CurHostAddr; /* address of current host */
626
627 int
makeconnection(host,port,mci,usesecureport)628 makeconnection(host, port, mci, usesecureport)
629 char *host;
630 u_short port;
631 register MCI *mci;
632 bool usesecureport;
633 {
634 register int i, s;
635 register struct hostent *hp = (struct hostent *)NULL;
636 SOCKADDR addr;
637 int sav_errno;
638 int addrlen;
639 #if NAMED_BIND
640 extern int h_errno;
641 #endif
642
643 /*
644 ** Set up the address for the mailer.
645 ** Accept "[a.b.c.d]" syntax for host name.
646 */
647
648 #if NAMED_BIND
649 h_errno = 0;
650 #endif
651 errno = 0;
652 bzero(&CurHostAddr, sizeof CurHostAddr);
653 SmtpPhase = mci->mci_phase = "initial connection";
654 CurHostName = host;
655
656 if (host[0] == '[')
657 {
658 long hid;
659 register char *p = strchr(host, ']');
660
661 if (p != NULL)
662 {
663 *p = '\0';
664 #ifdef NETINET
665 hid = inet_addr(&host[1]);
666 if (hid == -1)
667 #endif
668 {
669 /* try it as a host name (avoid MX lookup) */
670 hp = gethostbyname(&host[1]);
671 if (hp == NULL && p[-1] == '.')
672 {
673 p[-1] = '\0';
674 hp = gethostbyname(&host[1]);
675 p[-1] = '.';
676 }
677 *p = ']';
678 goto gothostent;
679 }
680 *p = ']';
681 }
682 if (p == NULL)
683 {
684 usrerr("553 Invalid numeric domain spec \"%s\"", host);
685 return (EX_NOHOST);
686 }
687 #ifdef NETINET
688 addr.sin.sin_family = AF_INET; /*XXX*/
689 addr.sin.sin_addr.s_addr = hid;
690 #endif
691 }
692 else
693 {
694 register char *p = &host[strlen(host) - 1];
695
696 hp = gethostbyname(host);
697 if (hp == NULL && *p == '.')
698 {
699 *p = '\0';
700 hp = gethostbyname(host);
701 *p = '.';
702 }
703 gothostent:
704 if (hp == NULL)
705 {
706 #if NAMED_BIND
707 if (errno == ETIMEDOUT || h_errno == TRY_AGAIN)
708 return (EX_TEMPFAIL);
709
710 /* if name server is specified, assume temp fail */
711 if (errno == ECONNREFUSED && UseNameServer)
712 return (EX_TEMPFAIL);
713 #endif
714 return (EX_NOHOST);
715 }
716 addr.sa.sa_family = hp->h_addrtype;
717 switch (hp->h_addrtype)
718 {
719 #ifdef NETINET
720 case AF_INET:
721 bcopy(hp->h_addr,
722 &addr.sin.sin_addr,
723 sizeof addr.sin.sin_addr);
724 break;
725 #endif
726
727 default:
728 bcopy(hp->h_addr,
729 addr.sa.sa_data,
730 hp->h_length);
731 break;
732 }
733 i = 1;
734 }
735
736 /*
737 ** Determine the port number.
738 */
739
740 if (port != 0)
741 port = htons(port);
742 else
743 {
744 register struct servent *sp = getservbyname("smtp", "tcp");
745
746 if (sp == NULL)
747 {
748 syserr("554 makeconnection: service \"smtp\" unknown");
749 port = htons(25);
750 }
751 else
752 port = sp->s_port;
753 }
754
755 switch (addr.sa.sa_family)
756 {
757 #ifdef NETINET
758 case AF_INET:
759 addr.sin.sin_port = port;
760 addrlen = sizeof (struct sockaddr_in);
761 break;
762 #endif
763
764 #ifdef NETISO
765 case AF_ISO:
766 /* assume two byte transport selector */
767 bcopy((char *) &port, TSEL((struct sockaddr_iso *) &addr), 2);
768 addrlen = sizeof (struct sockaddr_iso);
769 break;
770 #endif
771
772 default:
773 syserr("Can't connect to address family %d", addr.sa.sa_family);
774 return (EX_NOHOST);
775 }
776
777 /*
778 ** Try to actually open the connection.
779 */
780
781 #ifdef XLA
782 /* if too many connections, don't bother trying */
783 if (!xla_noqueue_ok(host))
784 return EX_TEMPFAIL;
785 #endif
786
787 for (;;)
788 {
789 if (tTd(16, 1))
790 printf("makeconnection (%s [%s])\n",
791 host, anynet_ntoa(&addr));
792
793 /* save for logging */
794 CurHostAddr = addr;
795
796 if (usesecureport)
797 {
798 int rport = IPPORT_RESERVED - 1;
799
800 s = rresvport(&rport);
801 }
802 else
803 {
804 s = socket(AF_INET, SOCK_STREAM, 0);
805 }
806 if (s < 0)
807 {
808 sav_errno = errno;
809 syserr("makeconnection: no socket");
810 goto failure;
811 }
812
813 #ifdef SO_SNDBUF
814 if (TcpSndBufferSize > 0)
815 {
816 if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
817 (char *) &TcpSndBufferSize,
818 sizeof(TcpSndBufferSize)) < 0)
819 syserr("makeconnection: setsockopt(SO_SNDBUF)");
820 }
821 #endif
822
823 if (tTd(16, 1))
824 printf("makeconnection: fd=%d\n", s);
825
826 /* turn on network debugging? */
827 if (tTd(16, 101))
828 {
829 int on = 1;
830 (void) setsockopt(s, SOL_SOCKET, SO_DEBUG,
831 (char *)&on, sizeof on);
832 }
833 if (CurEnv->e_xfp != NULL)
834 (void) fflush(CurEnv->e_xfp); /* for debugging */
835 errno = 0; /* for debugging */
836 if (connect(s, (struct sockaddr *) &addr, addrlen) >= 0)
837 break;
838
839 /* couldn't connect.... figure out why */
840 sav_errno = errno;
841 (void) close(s);
842 if (hp && hp->h_addr_list[i])
843 {
844 if (tTd(16, 1))
845 printf("Connect failed (%s); trying new address....\n",
846 errstring(sav_errno));
847 switch (addr.sa.sa_family)
848 {
849 #ifdef NETINET
850 case AF_INET:
851 bcopy(hp->h_addr_list[i++],
852 &addr.sin.sin_addr,
853 sizeof addr.sin.sin_addr);
854 break;
855 #endif
856
857 default:
858 bcopy(hp->h_addr_list[i++],
859 addr.sa.sa_data,
860 hp->h_length);
861 break;
862 }
863 continue;
864 }
865
866 /* failure, decide if temporary or not */
867 failure:
868 #ifdef XLA
869 xla_host_end(host);
870 #endif
871 if (transienterror(sav_errno))
872 return EX_TEMPFAIL;
873 else
874 {
875 message("%s", errstring(sav_errno));
876 return (EX_UNAVAILABLE);
877 }
878 }
879
880 /* connection ok, put it into canonical form */
881 if ((mci->mci_out = fdopen(s, "w")) == NULL ||
882 (s = dup(s)) < 0 ||
883 (mci->mci_in = fdopen(s, "r")) == NULL)
884 {
885 syserr("cannot open SMTP client channel, fd=%d", s);
886 return EX_TEMPFAIL;
887 }
888
889 return (EX_OK);
890 }
891 /*
892 ** MYHOSTNAME -- return the name of this host.
893 **
894 ** Parameters:
895 ** hostbuf -- a place to return the name of this host.
896 ** size -- the size of hostbuf.
897 **
898 ** Returns:
899 ** A list of aliases for this host.
900 **
901 ** Side Effects:
902 ** Adds numeric codes to $=w.
903 */
904
905 char **
myhostname(hostbuf,size)906 myhostname(hostbuf, size)
907 char hostbuf[];
908 int size;
909 {
910 register struct hostent *hp;
911 extern struct hostent *gethostbyname();
912
913 if (gethostname(hostbuf, size) < 0)
914 {
915 (void) strcpy(hostbuf, "localhost");
916 }
917 hp = gethostbyname(hostbuf);
918 if (hp == NULL)
919 {
920 syserr("!My host name (%s) does not seem to exist!", hostbuf);
921 }
922 (void) strncpy(hostbuf, hp->h_name, size - 1);
923 hostbuf[size - 1] = '\0';
924
925 #if NAMED_BIND
926 /* if still no dot, try DNS directly (i.e., avoid NIS problems) */
927 if (strchr(hostbuf, '.') == NULL)
928 {
929 extern bool getcanonname();
930 extern int h_errno;
931
932 /* try twice in case name server not yet started up */
933 if (!getcanonname(hostbuf, size, TRUE) &&
934 UseNameServer &&
935 (h_errno != TRY_AGAIN ||
936 (sleep(30), !getcanonname(hostbuf, size, TRUE))))
937 {
938 errno = h_errno + E_DNSBASE;
939 syserr("!My host name (%s) not known to DNS",
940 hostbuf);
941 }
942 }
943 #endif
944
945 if (hp->h_addrtype == AF_INET && hp->h_length == 4)
946 {
947 register int i;
948
949 for (i = 0; hp->h_addr_list[i] != NULL; i++)
950 {
951 char ipbuf[100];
952
953 sprintf(ipbuf, "[%s]",
954 inet_ntoa(*((struct in_addr *) hp->h_addr_list[i])));
955 setclass('w', ipbuf);
956 }
957 }
958
959 return (hp->h_aliases);
960 }
961 /*
962 ** GETAUTHINFO -- get the real host name asociated with a file descriptor
963 **
964 ** Uses RFC1413 protocol to try to get info from the other end.
965 **
966 ** Parameters:
967 ** fd -- the descriptor
968 **
969 ** Returns:
970 ** The user@host information associated with this descriptor.
971 */
972
973 #if IDENTPROTO
974
975 static jmp_buf CtxAuthTimeout;
976
977 static
authtimeout()978 authtimeout()
979 {
980 longjmp(CtxAuthTimeout, 1);
981 }
982
983 #endif
984
985 char *
getauthinfo(fd)986 getauthinfo(fd)
987 int fd;
988 {
989 int falen;
990 register char *p;
991 #if IDENTPROTO
992 SOCKADDR la;
993 int lalen;
994 register struct servent *sp;
995 int s;
996 int i;
997 EVENT *ev;
998 #endif
999 static char hbuf[MAXNAME * 2 + 2];
1000 extern char *hostnamebyanyaddr();
1001 extern char RealUserName[]; /* main.c */
1002
1003 falen = sizeof RealHostAddr;
1004 if (getpeername(fd, &RealHostAddr.sa, &falen) < 0 || falen <= 0 ||
1005 RealHostAddr.sa.sa_family == 0)
1006 {
1007 (void) sprintf(hbuf, "%s@localhost", RealUserName);
1008 if (tTd(9, 1))
1009 printf("getauthinfo: %s\n", hbuf);
1010 return hbuf;
1011 }
1012
1013 if (RealHostName == NULL)
1014 {
1015 /* translate that to a host name */
1016 RealHostName = newstr(hostnamebyanyaddr(&RealHostAddr));
1017 }
1018
1019 #if IDENTPROTO
1020 if (TimeOuts.to_ident == 0)
1021 goto noident;
1022
1023 lalen = sizeof la;
1024 if (RealHostAddr.sa.sa_family != AF_INET ||
1025 getsockname(fd, &la.sa, &lalen) < 0 || lalen <= 0 ||
1026 la.sa.sa_family != AF_INET)
1027 {
1028 /* no ident info */
1029 goto noident;
1030 }
1031
1032 /* create ident query */
1033 (void) sprintf(hbuf, "%d,%d\r\n",
1034 ntohs(RealHostAddr.sin.sin_port), ntohs(la.sin.sin_port));
1035
1036 /* create local address */
1037 la.sin.sin_port = 0;
1038
1039 /* create foreign address */
1040 sp = getservbyname("auth", "tcp");
1041 if (sp != NULL)
1042 RealHostAddr.sin.sin_port = sp->s_port;
1043 else
1044 RealHostAddr.sin.sin_port = htons(113);
1045
1046 s = -1;
1047 if (setjmp(CtxAuthTimeout) != 0)
1048 {
1049 if (s >= 0)
1050 (void) close(s);
1051 goto noident;
1052 }
1053
1054 /* put a timeout around the whole thing */
1055 ev = setevent(TimeOuts.to_ident, authtimeout, 0);
1056
1057 /* connect to foreign IDENT server using same address as SMTP socket */
1058 s = socket(AF_INET, SOCK_STREAM, 0);
1059 if (s < 0)
1060 {
1061 clrevent(ev);
1062 goto noident;
1063 }
1064 if (bind(s, &la.sa, sizeof la.sin) < 0 ||
1065 connect(s, &RealHostAddr.sa, sizeof RealHostAddr.sin) < 0)
1066 {
1067 goto closeident;
1068 }
1069
1070 if (tTd(9, 10))
1071 printf("getauthinfo: sent %s", hbuf);
1072
1073 /* send query */
1074 if (write(s, hbuf, strlen(hbuf)) < 0)
1075 goto closeident;
1076
1077 /* get result */
1078 i = read(s, hbuf, sizeof hbuf);
1079 (void) close(s);
1080 clrevent(ev);
1081 if (i <= 0)
1082 goto noident;
1083 if (hbuf[--i] == '\n' && hbuf[--i] == '\r')
1084 i--;
1085 hbuf[++i] = '\0';
1086
1087 if (tTd(9, 3))
1088 printf("getauthinfo: got %s\n", hbuf);
1089
1090 /* parse result */
1091 p = strchr(hbuf, ':');
1092 if (p == NULL)
1093 {
1094 /* malformed response */
1095 goto noident;
1096 }
1097 while (isascii(*++p) && isspace(*p))
1098 continue;
1099 if (strncasecmp(p, "userid", 6) != 0)
1100 {
1101 /* presumably an error string */
1102 goto noident;
1103 }
1104 p += 6;
1105 while (isascii(*p) && isspace(*p))
1106 p++;
1107 if (*p++ != ':')
1108 {
1109 /* either useridxx or malformed response */
1110 goto noident;
1111 }
1112
1113 /* p now points to the OSTYPE field */
1114 p = strchr(p, ':');
1115 if (p == NULL)
1116 {
1117 /* malformed response */
1118 goto noident;
1119 }
1120
1121 /* 1413 says don't do this -- but it's broken otherwise */
1122 while (isascii(*++p) && isspace(*p))
1123 continue;
1124
1125 /* p now points to the authenticated name */
1126 (void) sprintf(hbuf, "%s@%s",
1127 p, RealHostName == NULL ? "localhost" : RealHostName);
1128 goto finish;
1129
1130 closeident:
1131 (void) close(s);
1132 clrevent(ev);
1133
1134 #endif /* IDENTPROTO */
1135
1136 noident:
1137 if (RealHostName == NULL)
1138 {
1139 if (tTd(9, 1))
1140 printf("getauthinfo: NULL\n");
1141 return NULL;
1142 }
1143 (void) strcpy(hbuf, RealHostName);
1144
1145 finish:
1146 if (RealHostName != NULL && RealHostName[0] != '[')
1147 {
1148 p = &hbuf[strlen(hbuf)];
1149 (void) sprintf(p, " [%s]", anynet_ntoa(&RealHostAddr));
1150 }
1151 if (tTd(9, 1))
1152 printf("getauthinfo: %s\n", hbuf);
1153 return hbuf;
1154 }
1155 /*
1156 ** HOST_MAP_LOOKUP -- turn a hostname into canonical form
1157 **
1158 ** Parameters:
1159 ** map -- a pointer to this map (unused).
1160 ** name -- the (presumably unqualified) hostname.
1161 ** av -- unused -- for compatibility with other mapping
1162 ** functions.
1163 ** statp -- an exit status (out parameter) -- set to
1164 ** EX_TEMPFAIL if the name server is unavailable.
1165 **
1166 ** Returns:
1167 ** The mapping, if found.
1168 ** NULL if no mapping found.
1169 **
1170 ** Side Effects:
1171 ** Looks up the host specified in hbuf. If it is not
1172 ** the canonical name for that host, return the canonical
1173 ** name.
1174 */
1175
1176 char *
host_map_lookup(map,name,av,statp)1177 host_map_lookup(map, name, av, statp)
1178 MAP *map;
1179 char *name;
1180 char **av;
1181 int *statp;
1182 {
1183 register struct hostent *hp;
1184 u_long in_addr;
1185 char *cp;
1186 int i;
1187 register STAB *s;
1188 char hbuf[MAXNAME];
1189 extern struct hostent *gethostbyaddr();
1190 #if NAMED_BIND
1191 extern int h_errno;
1192 #endif
1193
1194 /*
1195 ** See if we have already looked up this name. If so, just
1196 ** return it.
1197 */
1198
1199 s = stab(name, ST_NAMECANON, ST_ENTER);
1200 if (bitset(NCF_VALID, s->s_namecanon.nc_flags))
1201 {
1202 if (tTd(9, 1))
1203 printf("host_map_lookup(%s) => CACHE %s\n",
1204 name, s->s_namecanon.nc_cname);
1205 errno = s->s_namecanon.nc_errno;
1206 #if NAMED_BIND
1207 h_errno = s->s_namecanon.nc_herrno;
1208 #endif
1209 *statp = s->s_namecanon.nc_stat;
1210 if (CurEnv->e_message == NULL && *statp == EX_TEMPFAIL)
1211 {
1212 sprintf(hbuf, "%s: Name server timeout",
1213 shortenstring(name, 33));
1214 CurEnv->e_message = newstr(hbuf);
1215 }
1216 return s->s_namecanon.nc_cname;
1217 }
1218
1219 /*
1220 ** If first character is a bracket, then it is an address
1221 ** lookup. Address is copied into a temporary buffer to
1222 ** strip the brackets and to preserve name if address is
1223 ** unknown.
1224 */
1225
1226 if (*name != '[')
1227 {
1228 extern bool getcanonname();
1229
1230 if (tTd(9, 1))
1231 printf("host_map_lookup(%s) => ", name);
1232 s->s_namecanon.nc_flags |= NCF_VALID; /* will be soon */
1233 (void) strcpy(hbuf, name);
1234 if (getcanonname(hbuf, sizeof hbuf - 1, TRUE))
1235 {
1236 if (tTd(9, 1))
1237 printf("%s\n", hbuf);
1238 cp = map_rewrite(map, hbuf, strlen(hbuf), av);
1239 s->s_namecanon.nc_cname = newstr(cp);
1240 return cp;
1241 }
1242 else
1243 {
1244 register struct hostent *hp;
1245
1246 s->s_namecanon.nc_errno = errno;
1247 #if NAMED_BIND
1248 s->s_namecanon.nc_herrno = h_errno;
1249 if (tTd(9, 1))
1250 printf("FAIL (%d)\n", h_errno);
1251 switch (h_errno)
1252 {
1253 case TRY_AGAIN:
1254 if (UseNameServer)
1255 {
1256 sprintf(hbuf, "%s: Name server timeout",
1257 shortenstring(name, 33));
1258 message("%s", hbuf);
1259 if (CurEnv->e_message == NULL)
1260 CurEnv->e_message = newstr(hbuf);
1261 }
1262 *statp = EX_TEMPFAIL;
1263 break;
1264
1265 case HOST_NOT_FOUND:
1266 *statp = EX_NOHOST;
1267 break;
1268
1269 case NO_RECOVERY:
1270 *statp = EX_SOFTWARE;
1271 break;
1272
1273 default:
1274 *statp = EX_UNAVAILABLE;
1275 break;
1276 }
1277 #else
1278 if (tTd(9, 1))
1279 printf("FAIL\n");
1280 *statp = EX_NOHOST;
1281 #endif
1282 s->s_namecanon.nc_stat = *statp;
1283 if (*statp != EX_TEMPFAIL || UseNameServer)
1284 return NULL;
1285
1286 /*
1287 ** Try to look it up in /etc/hosts
1288 */
1289
1290 hp = gethostbyname(name);
1291 if (hp == NULL)
1292 {
1293 /* no dice there either */
1294 s->s_namecanon.nc_stat = *statp = EX_NOHOST;
1295 return NULL;
1296 }
1297
1298 s->s_namecanon.nc_stat = *statp = EX_OK;
1299 cp = map_rewrite(map, hp->h_name, strlen(hp->h_name), av);
1300 s->s_namecanon.nc_cname = newstr(cp);
1301 return cp;
1302 }
1303 }
1304 if ((cp = strchr(name, ']')) == NULL)
1305 return (NULL);
1306 *cp = '\0';
1307 in_addr = inet_addr(&name[1]);
1308
1309 /* nope -- ask the name server */
1310 hp = gethostbyaddr((char *)&in_addr, sizeof(struct in_addr), AF_INET);
1311 s->s_namecanon.nc_errno = errno;
1312 #if NAMED_BIND
1313 s->s_namecanon.nc_herrno = h_errno;
1314 #endif
1315 s->s_namecanon.nc_flags |= NCF_VALID; /* will be soon */
1316 if (hp == NULL)
1317 {
1318 s->s_namecanon.nc_stat = *statp = EX_NOHOST;
1319 return (NULL);
1320 }
1321
1322 /* found a match -- copy out */
1323 cp = map_rewrite(map, hp->h_name, strlen(hp->h_name), av);
1324 s->s_namecanon.nc_stat = *statp = EX_OK;
1325 s->s_namecanon.nc_cname = newstr(cp);
1326 return cp;
1327 }
1328 /*
1329 ** ANYNET_NTOA -- convert a network address to printable form.
1330 **
1331 ** Parameters:
1332 ** sap -- a pointer to a sockaddr structure.
1333 **
1334 ** Returns:
1335 ** A printable version of that sockaddr.
1336 */
1337
1338 char *
anynet_ntoa(sap)1339 anynet_ntoa(sap)
1340 register SOCKADDR *sap;
1341 {
1342 register char *bp;
1343 register char *ap;
1344 int l;
1345 static char buf[100];
1346
1347 /* check for null/zero family */
1348 if (sap == NULL)
1349 return "NULLADDR";
1350 if (sap->sa.sa_family == 0)
1351 return "0";
1352
1353 switch (sap->sa.sa_family)
1354 {
1355 #ifdef MAYBENEXTRELEASE /*** UNTESTED *** UNTESTED *** UNTESTED ***/
1356 #ifdef NETUNIX
1357 case AF_UNIX:
1358 if (sap->sunix.sun_path[0] != '\0')
1359 sprintf(buf, "[UNIX: %.64s]", sap->sunix.sun_path);
1360 else
1361 sprintf(buf, "[UNIX: localhost]");
1362 return buf;
1363 #endif
1364 #endif
1365
1366 #ifdef NETINET
1367 case AF_INET:
1368 return inet_ntoa(((struct sockaddr_in *) sap)->sin_addr);
1369 #endif
1370
1371 default:
1372 /* this case is only to ensure syntactic correctness */
1373 break;
1374 }
1375
1376 /* unknown family -- just dump bytes */
1377 (void) sprintf(buf, "Family %d: ", sap->sa.sa_family);
1378 bp = &buf[strlen(buf)];
1379 ap = sap->sa.sa_data;
1380 for (l = sizeof sap->sa.sa_data; --l >= 0; )
1381 {
1382 (void) sprintf(bp, "%02x:", *ap++ & 0377);
1383 bp += 3;
1384 }
1385 *--bp = '\0';
1386 return buf;
1387 }
1388 /*
1389 ** HOSTNAMEBYANYADDR -- return name of host based on address
1390 **
1391 ** Parameters:
1392 ** sap -- SOCKADDR pointer
1393 **
1394 ** Returns:
1395 ** text representation of host name.
1396 **
1397 ** Side Effects:
1398 ** none.
1399 */
1400
1401 char *
hostnamebyanyaddr(sap)1402 hostnamebyanyaddr(sap)
1403 register SOCKADDR *sap;
1404 {
1405 register struct hostent *hp;
1406 int saveretry;
1407
1408 #if NAMED_BIND
1409 /* shorten name server timeout to avoid higher level timeouts */
1410 saveretry = _res.retry;
1411 _res.retry = 3;
1412 #endif /* NAMED_BIND */
1413
1414 switch (sap->sa.sa_family)
1415 {
1416 #ifdef NETINET
1417 case AF_INET:
1418 hp = gethostbyaddr((char *) &sap->sin.sin_addr,
1419 sizeof sap->sin.sin_addr,
1420 AF_INET);
1421 break;
1422 #endif
1423
1424 #ifdef NETISO
1425 case AF_ISO:
1426 hp = gethostbyaddr((char *) &sap->siso.siso_addr,
1427 sizeof sap->siso.siso_addr,
1428 AF_ISO);
1429 break;
1430 #endif
1431
1432 #ifdef MAYBENEXTRELEASE /*** UNTESTED *** UNTESTED *** UNTESTED ***/
1433 case AF_UNIX:
1434 hp = NULL;
1435 break;
1436 #endif
1437
1438 default:
1439 hp = gethostbyaddr(sap->sa.sa_data,
1440 sizeof sap->sa.sa_data,
1441 sap->sa.sa_family);
1442 break;
1443 }
1444
1445 #if NAMED_BIND
1446 _res.retry = saveretry;
1447 #endif /* NAMED_BIND */
1448
1449 if (hp != NULL)
1450 return hp->h_name;
1451 else
1452 {
1453 /* produce a dotted quad */
1454 static char buf[512];
1455
1456 (void) sprintf(buf, "[%s]", anynet_ntoa(sap));
1457 return buf;
1458 }
1459 }
1460
1461 # else /* DAEMON */
1462 /* code for systems without sophisticated networking */
1463
1464 /*
1465 ** MYHOSTNAME -- stub version for case of no daemon code.
1466 **
1467 ** Can't convert to upper case here because might be a UUCP name.
1468 **
1469 ** Mark, you can change this to be anything you want......
1470 */
1471
1472 char **
myhostname(hostbuf,size)1473 myhostname(hostbuf, size)
1474 char hostbuf[];
1475 int size;
1476 {
1477 register FILE *f;
1478
1479 hostbuf[0] = '\0';
1480 f = fopen("/usr/include/whoami", "r");
1481 if (f != NULL)
1482 {
1483 (void) fgets(hostbuf, size, f);
1484 fixcrlf(hostbuf, TRUE);
1485 (void) fclose(f);
1486 }
1487 return (NULL);
1488 }
1489 /*
1490 ** GETAUTHINFO -- get the real host name asociated with a file descriptor
1491 **
1492 ** Parameters:
1493 ** fd -- the descriptor
1494 **
1495 ** Returns:
1496 ** The host name associated with this descriptor, if it can
1497 ** be determined.
1498 ** NULL otherwise.
1499 **
1500 ** Side Effects:
1501 ** none
1502 */
1503
1504 char *
getauthinfo(fd)1505 getauthinfo(fd)
1506 int fd;
1507 {
1508 return NULL;
1509 }
1510 /*
1511 ** MAPHOSTNAME -- turn a hostname into canonical form
1512 **
1513 ** Parameters:
1514 ** map -- a pointer to the database map.
1515 ** name -- a buffer containing a hostname.
1516 ** avp -- a pointer to a (cf file defined) argument vector.
1517 ** statp -- an exit status (out parameter).
1518 **
1519 ** Returns:
1520 ** mapped host name
1521 ** FALSE otherwise.
1522 **
1523 ** Side Effects:
1524 ** Looks up the host specified in name. If it is not
1525 ** the canonical name for that host, replace it with
1526 ** the canonical name. If the name is unknown, or it
1527 ** is already the canonical name, leave it unchanged.
1528 */
1529
1530 /*ARGSUSED*/
1531 char *
host_map_lookup(map,name,avp,statp)1532 host_map_lookup(map, name, avp, statp)
1533 MAP *map;
1534 char *name;
1535 char **avp;
1536 char *statp;
1537 {
1538 register struct hostent *hp;
1539
1540 hp = gethostbyname(name);
1541 if (hp != NULL)
1542 return hp->h_name;
1543 *statp = EX_NOHOST;
1544 return NULL;
1545 }
1546
1547 #endif /* DAEMON */
1548