xref: /original-bsd/usr.bin/uucp/libacu/bsdtcp.c (revision c3e32dec)
1 /*-
2  * Copyright (c) 1985, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * %sccs.include.proprietary.c%
6  */
7 
8 #ifndef lint
9 static char sccsid[] = "@(#)bsdtcp.c	8.1 (Berkeley) 06/06/93";
10 #endif /* not lint */
11 
12 #include "condevs.h"
13 #include <netdb.h>
14 #include <sys/socket.h>
15 #include <netinet/in.h>
16 
17 /*
18  *	bsdtcpopn -- make a tcp connection
19  *
20  *	return codes:
21  *		>0 - file number - ok
22  *		FAIL - failed
23  */
24 
25 bsdtcpopn(flds)
26 register char *flds[];
27 {
28 	struct servent *sp;
29 	struct hostent *hp;
30 	struct	sockaddr_in hisctladdr;
31 	int s = -1, port;
32 	extern int errno;
33 	extern const char *const sys_errlist[];
34 
35 	sp = getservbyname(flds[F_CLASS], "tcp");
36 	if (sp == NULL) {
37 		port = htons(atoi(flds[F_CLASS]));
38 		if (port == 0) {
39 			logent(_FAILED, "UNKNOWN PORT NUMBER");
40 			return CF_SYSTEM;
41 		}
42 	} else
43 		port = sp->s_port;
44 	DEBUG(4, "bsdtcpopn host %s, ", flds[F_PHONE]);
45 	DEBUG(4, "port %d\n", ntohs(port));
46 	if (setjmp(Sjbuf)) {
47 		bsdtcpcls(s);
48 		logent("tcpopen", "TIMEOUT");
49 		return CF_DIAL;
50 	}
51 
52 	bzero((char *)&hisctladdr, sizeof (hisctladdr));
53 	hp = gethostbyname(flds[F_PHONE]);
54 	if (hp == NULL) {
55 		logent("tcpopen","UNKNOWN HOST");
56 		return CF_DIAL;
57 	}
58 	signal(SIGALRM, alarmtr);
59 	alarm(MAXMSGTIME*2);
60 	hisctladdr.sin_family = hp->h_addrtype;
61 #ifdef BSD2_9
62 	s = socket(SOCK_STREAM, 0, &hisctladdr, 0);
63 #else BSD4_2
64 	s = socket(hp->h_addrtype, SOCK_STREAM, 0);
65 #endif BSD4_2
66 	if (s < 0)
67 		goto bad;
68 #ifndef BSD2_9
69 	if (bind(s, (struct sockaddr *)&hisctladdr, sizeof (hisctladdr)) < 0)
70 		goto bad;
71 #endif BSD2_9
72 	bcopy(hp->h_addr, (char *)&hisctladdr.sin_addr, hp->h_length);
73 	hisctladdr.sin_port = port;
74 #ifdef BSD2_9
75 	if (connect(s, (char *)&hisctladdr) < 0)
76 #else BSD4_2
77 	if (connect(s, (struct sockaddr *)&hisctladdr, sizeof (hisctladdr)) < 0)
78 #endif BSD4_2
79 		goto bad;
80 	alarm(0);
81 	CU_end = bsdtcpcls;
82 	return s;
83 bad:
84 	alarm(0);
85 	bsdtcpcls(s);
86 	DEBUG(5, "tcpopen failed: errno %d\n", errno);
87 	logent(sys_errlist[errno], _FAILED);
88 	return CF_DIAL;
89 }
90 
91 /*
92  * bsdtcpcls -- close tcp connection
93  */
94 bsdtcpcls(fd)
95 register int fd;
96 {
97 	DEBUG(4, "TCP CLOSE called\n", 0);
98 	if (fd > 0) {
99 		close(fd);
100 		DEBUG(4, "closed fd %d\n", fd);
101 	}
102 }
103