xref: /original-bsd/lib/libcompat/4.3/rexec.c (revision 1eec400c)
1 #ifndef lint
2 static char sccsid[] = "@(#)rexec.c	4.3 82/04/01";
3 #endif
4 
5 #include <stdio.h>
6 #include <sys/types.h>
7 #include <sys/socket.h>
8 #include <net/in.h>
9 #include <errno.h>
10 
11 extern	errno;
12 char	*index(), *sprintf();
13 int	rexecoptions;
14 char	*getpass(), *getlogin();
15 
16 rexec(ahost, rport, name, pass, cmd, fd2p)
17 	char **ahost;
18 	int rport;
19 	char *name, *pass, *cmd;
20 	int *fd2p;
21 {
22 	int s, addr, timo = 1;
23 	struct sockaddr_in sin, sin2, from;
24 	char c;
25 	short port;
26 
27 	addr = rhost(ahost);
28 	if (addr == -1) {
29 		fprintf(stderr, "%s: unknown host\n", *ahost);
30 		return (-1);
31 	}
32 	ruserpass(*ahost, &name, &pass);
33 retry:
34 	sin.sin_family = AF_INET;
35 	sin.sin_port = 0;
36 	sin.sin_addr.s_addr = 0;
37 	s = socket(SOCK_STREAM, 0, &sin, rexecoptions|SO_KEEPALIVE);
38 	if (s < 0)
39 		return (-1);
40 	sin.sin_addr.s_addr = addr;
41 	sin.sin_port = rport;
42 #if vax
43 	sin.sin_port =
44 	    ((sin.sin_port << 8) & 0xff00) | ((sin.sin_port >> 8) & 0x00ff);
45 #endif
46 	if (connect(s, &sin) < 0) {
47 		if (errno == ECONNREFUSED && timo <= 16) {
48 			(void) close(s);
49 			sleep(timo);
50 			timo *= 2;
51 			goto retry;
52 		}
53 		perror(*ahost);
54 		return (-1);
55 	}
56 	if (fd2p == 0) {
57 		(void) write(s, "", 1);
58 		port = 0;
59 	} else {
60 		char num[8];
61 		int s2;
62 
63 		sin.sin_family = AF_INET;
64 		sin.sin_port = 0;
65 		sin.sin_addr.s_addr = 0;
66 		s2 = socket(SOCK_STREAM, 0, &sin, rexecoptions|SO_ACCEPTCONN);
67 
68 		if (s2 < 0) {
69 			(void) close(s);
70 			return (-1);
71 		}
72 		socketaddr(s2, &sin2);
73 		port = sin2.sin_port;
74 #if vax
75 		port = ((port << 8) & 0xff00) | ((port >> 8) & 0x00ff);
76 #endif
77 		(void) sprintf(num, "%d", port);
78 		(void) write(s, num, strlen(num)+1);
79 		if (accept(s2, &from) < 0) {
80 			perror("accept");
81 			goto bad;
82 		}
83 		*fd2p = s2;
84 	}
85 	(void) write(s, name, strlen(name) + 1);
86 	/* should public key encypt the password here */
87 	(void) write(s, pass, strlen(pass) + 1);
88 	(void) write(s, cmd, strlen(cmd) + 1);
89 	if (read(s, &c, 1) != 1) {
90 		perror(*ahost);
91 		goto bad;
92 	}
93 	if (c != 0) {
94 		while (read(s, &c, 1) == 1) {
95 			(void) write(2, &c, 1);
96 			if (c == '\n')
97 				break;
98 		}
99 		goto bad;
100 	}
101 	return (s);
102 bad:
103 	if (port)
104 		(void) close(*fd2p);
105 	(void) close(s);
106 	return (-1);
107 }
108