WARNS is set in usr.bin/Makefile.inc.
[dragonfly.git] / usr.bin / rdist / rshrcmd.c
blob39005b840df4fc54cf193504bd2f8610b68d6b20
2 /*
3 * This is an rcmd() replacement originally by
4 * Chris Siebenmann <cks@utcc.utoronto.ca>.
6 * $FreeBSD: src/usr.bin/rdist/rshrcmd.c,v 1.6 1999/08/28 01:05:08 peter Exp $
7 * $DragonFly: src/usr.bin/rdist/rshrcmd.c,v 1.3 2004/07/24 19:45:10 eirikn Exp $
8 */
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <sys/wait.h>
14 #include <netdb.h>
15 #include <signal.h>
17 #include "defs.h"
19 #if !defined(DIRECT_RCMD)
21 static char *
22 xbasename(char *s)
24 char *ret;
26 ret = strrchr(s, '/');
27 if (ret && ret[1])
28 return (ret + 1);
29 return s;
34 * This is a replacement rcmd() function that uses the rsh(1c)
35 * program in place of a direct rcmd() function call so as to
36 * avoid having to be root.
38 int
39 rshrcmd(char **ahost, u_short port, char *luser, char *ruser, char *cmd, int *fd2p)
41 int cpid, sp[2];
42 struct hostent *hp;
44 /* insure that we are indeed being used as we thought. */
45 if (fd2p != 0)
46 return -1;
47 /* validate remote hostname. */
48 hp = gethostbyname(*ahost);
49 if (hp == 0) {
50 error("%s: unknown host", *ahost);
51 return -1;
54 /* get a socketpair we'll use for stdin and stdout. */
55 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sp) < 0) {
56 error("socketpair(AF_UNIX, SOCK_STREAM, 0) failed: %s.",
57 strerror(errno));
58 return -1;
61 cpid = fork();
62 if (cpid < 0) {
63 error("fork failed: %s.", strerror(errno));
64 return -1; /* error. */
66 if (cpid == 0) {
67 /* child. we use sp[1] to be stdin/stdout, and close
68 sp[0]. */
69 close(sp[0]);
70 if (dup2(sp[1], 0) < 0 || dup2(0,1) < 0) {
71 error("dup2 failed: %s.", strerror(errno));
72 _exit(255);
74 /* fork again to lose parent. */
75 cpid = fork();
76 if (cpid < 0) {
77 error("fork to lose parent failed: %s.", strerror(errno));
78 _exit(255);
80 if (cpid > 0)
81 _exit(0);
82 /* in grandchild here. */
85 * If we are rdist'ing to "localhost" as the same user
86 * as we are, then avoid running remote shell for efficiency.
88 if (strcmp(*ahost, "localhost") == 0 &&
89 strcmp(luser, ruser) == 0) {
90 execlp(_PATH_BSHELL, xbasename(_PATH_BSHELL), "-c",
91 cmd, (char *) NULL);
92 error("execlp %s failed: %s.", _PATH_BSHELL, strerror(errno));
93 } else {
94 execlp(path_rsh, xbasename(path_rsh),
95 *ahost, "-l", ruser, cmd, (char *) NULL);
96 error("execlp %s failed: %s.", path_rsh,
97 strerror(errno));
99 _exit(255);
101 if (cpid > 0) {
102 /* parent. close sp[1], return sp[0]. */
103 close(sp[1]);
104 /* reap child. */
105 wait(0);
106 return sp[0];
108 /*NOTREACHED*/
109 return (-1);
112 #endif /* !DIRECT_RCMD */