2 * Copyright (c) 1983, 1990, 1992, 1993
3 * The Regents of the University of California. All rights reserved.
4 * Copyright (c) 2002 Networks Associates Technology, Inc.
7 * Portions of this software were developed for the FreeBSD Project by
8 * ThinkSec AS and NAI Labs, the Security Research Division of Network
9 * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035
10 * ("CBOSS"), as part of the DARPA CHATS research program.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#) Copyright (c) 1983, 1990, 1992, 1993 The Regents of the University of California. All rights reserved.
37 * @(#)rcp.c 8.2 (Berkeley) 4/2/94
38 * $FreeBSD: src/bin/rcp/rcp.c,v 1.26.2.6 2004/09/16 12:16:10 delphij Exp $
41 #include <sys/param.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
68 #include <openssl/des.h>
72 char dst_realm_buf[REALM_SZ];
73 char *dest_realm = NULL;
76 Key_schedule schedule;
77 extern char *krb_realmofhost();
80 #define OPTIONS "46dfKk:prtx"
82 #define OPTIONS "46dfKk:prt"
85 #define OPTIONS "46dfprt"
92 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
93 int family = PF_UNSPEC;
96 static char **argv_copy;
99 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
102 int kerberos(char **, char *, char *, char *);
103 void oldw(const char *, ...) __printflike(1, 2);
106 void rsource(char *, struct stat *);
107 void sink(int, char *[]);
108 void source(int, char *[]);
109 void tolocal(int, char *[]);
110 void toremote(char *, int, char *[]);
114 main(int argc, char *argv[])
117 int ch, fflag, i, tflag;
124 * Prepare for execing ourselves.
126 argc_copy = argc + 1;
127 argv_copy = malloc((argc_copy + 1) * sizeof(*argv_copy));
128 if (argv_copy == NULL)
130 argv_copy[0] = argv[0];
131 argv_copy[1] = __DECONST(char *, "-K");
132 for (i = 1; i < argc; ++i) {
133 argv_copy[i + 1] = strdup(argv[i]);
134 if (argv_copy[i + 1] == NULL)
135 errx(1, "strdup: out of memory");
137 argv_copy[argc + 1] = NULL;
140 while ((ch = getopt(argc, argv, OPTIONS)) != -1)
141 switch(ch) { /* User-visible flags. */
157 dest_realm = dst_realm_buf;
158 strncpy(dst_realm_buf, optarg, REALM_SZ - 1);
159 dst_realm_buf[REALM_SZ - 1] = '\0';
164 /* des_set_key(cred.session, schedule); */
174 /* Server options. */
176 targetshouldbedirectory = 1;
178 case 'f': /* "from" */
194 k = auth_getval("auth_list");
195 if (k && !strstr(k, "kerberos"))
199 shell = doencrypt ? __DECONST(char *, "ekshell") :
200 __DECONST(char *, "kshell");
202 shell = __DECONST(char *, "kshell");
204 if ((sp = getservbyname(shell, "tcp")) == NULL) {
206 oldw("can't get entry for %s/tcp service", shell);
207 sp = getservbyname(shell = "shell", "tcp");
210 shell = __DECONST(char *, "shell");
211 sp = getservbyname(shell, "tcp");
213 shell = __DECONST(char *, "shell");
214 sp = getservbyname(shell, "tcp");
217 errx(1, "%s/tcp: unknown service", shell);
220 if ((pwd = getpwuid(userid = getuid())) == NULL)
221 errx(1, "unknown user %d", (int)userid);
223 rem = STDIN_FILENO; /* XXX */
225 if (fflag) { /* Follow "protocol", send data. */
232 if (tflag) { /* Receive data. */
241 targetshouldbedirectory = 1;
244 /* Command to be executed on remote system using "rsh". */
246 snprintf(cmd, sizeof(cmd),
247 "rcp%s%s%s%s", iamrecursive ? " -r" : "",
249 (doencrypt && use_kerberos ? " -x" : ""),
253 pflag ? " -p" : "", targetshouldbedirectory ? " -d" : "");
255 snprintf(cmd, sizeof(cmd), "rcp%s%s%s",
256 iamrecursive ? " -r" : "", pflag ? " -p" : "",
257 targetshouldbedirectory ? " -d" : "");
260 signal(SIGPIPE, lostconn);
262 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
263 toremote(targ, argc, argv);
265 tolocal(argc, argv); /* Dest is local host. */
266 if (targetshouldbedirectory)
267 verifydir(argv[argc - 1]);
273 toremote(char *targ, int argc, char *argv[])
276 char *bp, *host, *src, *suser, *thost, *tuser;
280 targ = __DECONST(char *, ".");
282 if ((thost = strchr(argv[argc - 1], '@'))) {
285 tuser = argv[argc - 1];
288 else if (!okname(tuser))
291 thost = argv[argc - 1];
295 for (i = 0; i < argc - 1; i++) {
296 src = colon(argv[i]);
297 if (src) { /* remote to remote */
300 src = __DECONST(char *, ".");
301 host = strchr(argv[i], '@');
302 len = strlen(_PATH_RSH) + strlen(argv[i]) +
303 strlen(src) + (tuser ? strlen(tuser) : 0) +
304 strlen(thost) + strlen(targ) + CMDNEEDS + 20;
305 if (!(bp = malloc(len)))
311 suser = pwd->pw_name;
312 else if (!okname(suser)) {
317 "%s %s -l %s -n %s %s '%s%s%s:%s'",
318 _PATH_RSH, host, suser, cmd, src,
319 tuser ? tuser : "", tuser ? "@" : "",
323 "exec %s %s -n %s %s '%s%s%s:%s'",
324 _PATH_RSH, argv[i], cmd, src,
325 tuser ? tuser : "", tuser ? "@" : "",
327 susystem(bp, userid);
329 } else { /* local to remote */
331 len = strlen(targ) + CMDNEEDS + 20;
332 if (!(bp = malloc(len)))
334 snprintf(bp, len, "%s -t %s", cmd, targ);
338 rem = kerberos(&host, bp,
340 tuser ? tuser : pwd->pw_name);
343 rem = rcmd_af(&host, port,
345 tuser ? tuser : pwd->pw_name,
349 if (family == PF_INET) {
350 tos = IPTOS_THROUGHPUT;
351 if (setsockopt(rem, IPPROTO_IP, IP_TOS,
352 &tos, sizeof(int)) < 0)
353 warn("TOS (ignored)");
366 tolocal(int argc, char *argv[])
369 char *bp, *host, *src, *suser;
371 for (i = 0; i < argc - 1; i++) {
372 if (!(src = colon(argv[i]))) { /* Local to local. */
373 len = strlen(_PATH_CP) + strlen(argv[i]) +
374 strlen(argv[argc - 1]) + 20;
375 if (!(bp = malloc(len)))
377 snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
378 iamrecursive ? " -PR" : "", pflag ? " -p" : "",
379 argv[i], argv[argc - 1]);
380 if (susystem(bp, userid))
387 src = __DECONST(char *, ".");
388 if ((host = strchr(argv[i], '@')) == NULL) {
390 suser = pwd->pw_name;
395 suser = pwd->pw_name;
396 else if (!okname(suser)) {
401 len = strlen(src) + CMDNEEDS + 20;
402 if ((bp = malloc(len)) == NULL)
404 snprintf(bp, len, "%s -f %s", cmd, src);
408 kerberos(&host, bp, pwd->pw_name, suser) :
410 rcmd_af(&host, port, pwd->pw_name, suser, bp, 0,
418 if (family == PF_INET) {
419 tos = IPTOS_THROUGHPUT;
420 if (setsockopt(rem, IPPROTO_IP, IP_TOS, &tos,
422 warn("TOS (ignored)");
424 sink(1, argv + argc - 1);
432 source(int argc, char *argv[])
438 int amt, fd, haderr, indx, result;
439 char *last, *name, buf[BUFSIZ];
441 for (indx = 0; indx < argc; ++indx) {
443 if ((fd = open(name, O_RDONLY, 0)) < 0)
445 if (fstat(fd, &stb)) {
446 syserr: run_err("%s: %s", name, strerror(errno));
449 switch (stb.st_mode & S_IFMT) {
459 run_err("%s: not a regular file", name);
462 if ((last = strrchr(name, '/')) == NULL)
468 * Make it compatible with possible future
469 * versions expecting microseconds.
471 snprintf(buf, sizeof(buf), "T%ld 0 %ld 0\n",
472 (long)stb.st_mtimespec.tv_sec,
473 (long)stb.st_atimespec.tv_sec);
474 write(rem, buf, strlen(buf));
478 #define MODEMASK (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
479 snprintf(buf, sizeof(buf), "C%04o %jd %s\n",
480 stb.st_mode & MODEMASK, (intmax_t)stb.st_size, last);
481 write(rem, buf, strlen(buf));
484 if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
485 next: (void)close(fd);
489 /* Keep writing after an error so that we stay sync'd up. */
490 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
492 if (i + amt > stb.st_size)
493 amt = stb.st_size - i;
495 result = read(fd, bp->buf, amt);
497 haderr = result >= 0 ? EIO : errno;
500 write(rem, bp->buf, amt);
502 result = write(rem, bp->buf, amt);
504 haderr = result >= 0 ? EIO : errno;
507 if (close(fd) && !haderr)
512 run_err("%s: %s", name, strerror(haderr));
518 rsource(char *name, struct stat *statp)
522 char *last, *vect[1], path[PATH_MAX];
524 if (!(dirp = opendir(name))) {
525 run_err("%s: %s", name, strerror(errno));
528 last = strrchr(name, '/');
534 snprintf(path, sizeof(path), "T%ld 0 %ld 0\n",
535 (long)statp->st_mtimespec.tv_sec,
536 (long)statp->st_atimespec.tv_sec);
537 write(rem, path, strlen(path));
538 if (response() < 0) {
543 snprintf(path, sizeof(path),
544 "D%04o %d %s\n", statp->st_mode & MODEMASK, 0, last);
545 write(rem, path, strlen(path));
546 if (response() < 0) {
550 while ((dp = readdir(dirp))) {
553 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
555 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path)) {
556 run_err("%s/%s: name too long", name, dp->d_name);
559 snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
564 write(rem, "E\n", 2);
569 sink(int argc, char *argv[])
573 struct timeval tv[2];
574 enum { YES, NO, DISPLAYED } wrerr;
578 int amt, exists, first, mask, mode, ofd, omode;
579 int setimes, targisdir, wrerrno = 0;
580 char ch, *cp, *np, *targ, *why, *vect[1], buf[BUFSIZ], path[PATH_MAX];
584 #define SCREWUP(str) { why = __DECONST(char *, str); goto screwup; }
586 setimes = targisdir = 0;
591 run_err("ambiguous target");
595 if (targetshouldbedirectory)
598 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
600 for (first = 1;; first = 0) {
602 if (read(rem, cp, 1) <= 0)
605 SCREWUP("unexpected <newline>");
607 if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
608 SCREWUP("lost connection");
610 } while (cp < &buf[BUFSIZ - 1] && ch != '\n');
613 if (buf[0] == '\01' || buf[0] == '\02') {
616 buf + 1, strlen(buf + 1));
634 mtime.tv_sec = strtol(cp, &cp, 10);
635 if (!cp || *cp++ != ' ')
636 SCREWUP("mtime.sec not delimited");
637 mtime.tv_usec = strtol(cp, &cp, 10);
638 if (!cp || *cp++ != ' ')
639 SCREWUP("mtime.usec not delimited");
640 atime.tv_sec = strtol(cp, &cp, 10);
641 if (!cp || *cp++ != ' ')
642 SCREWUP("atime.sec not delimited");
643 atime.tv_usec = strtol(cp, &cp, 10);
644 if (!cp || *cp++ != '\0')
645 SCREWUP("atime.usec not delimited");
649 if (*cp != 'C' && *cp != 'D') {
651 * Check for the case "rcp remote:foo\* local:bar".
652 * In this case, the line "No match." can be returned
653 * by the shell before the rcp command on the remote is
654 * executed so the ^Aerror_message convention isn't
661 SCREWUP("expected control record");
664 for (++cp; cp < buf + 5; cp++) {
665 if (*cp < '0' || *cp > '7')
667 mode = (mode << 3) | (*cp - '0');
670 SCREWUP("mode not delimited");
672 for (size = 0; isdigit(*cp);)
673 size = size * 10 + (*cp++ - '0');
675 SCREWUP("size not delimited");
677 if (strlen(targ) + (*targ ? 1 : 0) + strlen(cp)
679 run_err("%s%s%s: name too long", targ,
680 *targ ? "/" : "", cp);
683 snprintf(path, sizeof(path), "%s%s%s", targ,
684 *targ ? "/" : "", cp);
688 exists = stat(np, &stb) == 0;
690 int mod_flag = pflag;
692 if (!S_ISDIR(stb.st_mode)) {
699 /* Handle copying from a read-only directory */
701 if (mkdir(np, mode | S_IRWXU) < 0)
708 if (utimes(np, tv) < 0)
709 run_err("%s: set times: %s",
710 np, strerror(errno));
718 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
719 bad: run_err("%s: %s", np, strerror(errno));
723 if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
729 for (count = i = 0; i < size; i += BUFSIZ) {
735 j = read(rem, cp, amt);
737 run_err("%s", j ? strerror(errno) :
738 "dropped connection");
744 if (count == bp->cnt) {
745 /* Keep reading so we stay sync'd up. */
747 j = write(ofd, bp->buf, count);
748 if (j != (off_t)count) {
750 wrerrno = j >= 0 ? EIO : errno;
757 if (count != 0 && wrerr == NO &&
758 (j = write(ofd, bp->buf, count)) != (off_t)count) {
760 wrerrno = j >= 0 ? EIO : errno;
762 if (ftruncate(ofd, size)) {
763 run_err("%s: truncate: %s", np, strerror(errno));
767 if (exists || omode != mode)
768 if (fchmod(ofd, omode))
769 run_err("%s: set mode: %s",
770 np, strerror(errno));
772 if (!exists && omode != mode)
773 if (fchmod(ofd, omode & ~mask))
774 run_err("%s: set mode: %s",
775 np, strerror(errno));
779 if (setimes && wrerr == NO) {
781 if (utimes(np, tv) < 0) {
782 run_err("%s: set times: %s",
783 np, strerror(errno));
789 run_err("%s: %s", np, strerror(wrerrno));
799 run_err("protocol error: %s", why);
805 kerberos(char **host, char *bp, char *locuser, char *user)
811 if (dest_realm == NULL)
812 dest_realm = krb_realmofhost(*host);
817 port, user, bp, 0, dest_realm, &cred, schedule) :
819 krcmd(host, port, user, bp, 0, dest_realm);
822 if (errno == ECONNREFUSED)
823 oldw("remote host doesn't support Kerberos");
824 else if (errno == ENOENT)
825 oldw("can't provide Kerberos authentication data");
826 execv(_PATH_RCP, argv_copy);
827 err(1, "execv: %s", _PATH_RCP);
833 "the -x option requires Kerberos authentication");
835 rem = rcmd_af(host, port, locuser, user, bp, 0, family);
839 #endif /* KERBEROS */
844 char ch, *cp, resp, rbuf[BUFSIZ];
846 if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
856 case 1: /* error, followed by error msg */
857 case 2: /* fatal error, "" */
859 if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
862 } while (cp < &rbuf[BUFSIZ] && ch != '\n');
865 write(STDERR_FILENO, rbuf, cp - rbuf);
879 fprintf(stderr, "%s\n%s\n",
880 "usage: rcp [-46Kpx] [-k realm] f1 f2",
881 " rcp [-46Kprx] [-k realm] f1 ... fn directory");
883 fprintf(stderr, "%s\n%s\n",
884 "usage: rcp [-46Kp] [-k realm] f1 f2",
885 " rcp [-46Kpr] [-k realm] f1 ... fn directory");
888 fprintf(stderr, "%s\n%s\n",
889 "usage: rcp [-46p] f1 f2",
890 " rcp [-46pr] f1 ... fn directory");
899 oldw(const char *fmt, ...)
903 fprintf(stderr, "rcp: ");
904 vfprintf(stderr, fmt, ap);
905 fprintf(stderr, ", using standard rcp\n");
911 run_err(const char *fmt, ...)
918 if (fp == NULL && !(fp = fdopen(rem, "w")))
920 fprintf(fp, "%c", 0x01);
921 fprintf(fp, "rcp: ");
922 vfprintf(fp, fmt, ap);