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