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 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by the University of
23 * California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * @(#) Copyright (c) 1983, 1990, 1992, 1993 The Regents of the University of California. All rights reserved.
41 * @(#)rcp.c 8.2 (Berkeley) 4/2/94
42 * $FreeBSD: src/bin/rcp/rcp.c,v 1.26.2.6 2004/09/16 12:16:10 delphij Exp $
45 #include <sys/cdefs.h>
46 #include <sys/param.h>
49 #include <sys/socket.h>
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h>
52 #include <netinet/ip.h>
73 #include <openssl/des.h>
77 char dst_realm_buf[REALM_SZ];
78 char *dest_realm = NULL;
81 Key_schedule schedule;
82 extern char *krb_realmofhost();
85 #define OPTIONS "46dfKk:prtx"
87 #define OPTIONS "46dfKk:prt"
90 #define OPTIONS "46dfprt"
97 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
98 int family = PF_UNSPEC;
100 static int argc_copy;
101 static char **argv_copy;
104 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
107 int kerberos(char **, char *, char *, char *);
108 void oldw(const char *, ...) __printflike(1, 2);
111 void rsource(char *, struct stat *);
112 void sink(int, char *[]);
113 void source(int, char *[]);
114 void tolocal(int, char *[]);
115 void toremote(char *, int, char *[]);
119 main(int argc, char *argv[])
122 int ch, fflag, i, tflag;
129 * Prepare for execing ourselves.
131 argc_copy = argc + 1;
132 argv_copy = malloc((argc_copy + 1) * sizeof(*argv_copy));
133 if (argv_copy == NULL)
135 argv_copy[0] = argv[0];
136 argv_copy[1] = __DECONST(char *, "-K");
137 for (i = 1; i < argc; ++i) {
138 argv_copy[i + 1] = strdup(argv[i]);
139 if (argv_copy[i + 1] == NULL)
140 errx(1, "strdup: out of memory");
142 argv_copy[argc + 1] = NULL;
145 while ((ch = getopt(argc, argv, OPTIONS)) != -1)
146 switch(ch) { /* User-visible flags. */
162 dest_realm = dst_realm_buf;
163 strncpy(dst_realm_buf, optarg, REALM_SZ - 1);
164 dst_realm_buf[REALM_SZ - 1] = '\0';
169 /* des_set_key(cred.session, schedule); */
179 /* Server options. */
181 targetshouldbedirectory = 1;
183 case 'f': /* "from" */
199 k = auth_getval("auth_list");
200 if (k && !strstr(k, "kerberos"))
204 shell = doencrypt ? __DECONST(char *, "ekshell") :
205 __DECONST(char *, "kshell");
207 shell = __DECONST(char *, "kshell");
209 if ((sp = getservbyname(shell, "tcp")) == NULL) {
211 oldw("can't get entry for %s/tcp service", shell);
212 sp = getservbyname(shell = "shell", "tcp");
215 shell = __DECONST(char *, "shell");
216 sp = getservbyname(shell, "tcp");
218 shell = __DECONST(char *, "shell");
219 sp = getservbyname(shell, "tcp");
222 errx(1, "%s/tcp: unknown service", shell);
225 if ((pwd = getpwuid(userid = getuid())) == NULL)
226 errx(1, "unknown user %d", (int)userid);
228 rem = STDIN_FILENO; /* XXX */
230 if (fflag) { /* Follow "protocol", send data. */
237 if (tflag) { /* Receive data. */
246 targetshouldbedirectory = 1;
249 /* Command to be executed on remote system using "rsh". */
251 snprintf(cmd, sizeof(cmd),
252 "rcp%s%s%s%s", iamrecursive ? " -r" : "",
254 (doencrypt && use_kerberos ? " -x" : ""),
258 pflag ? " -p" : "", targetshouldbedirectory ? " -d" : "");
260 snprintf(cmd, sizeof(cmd), "rcp%s%s%s",
261 iamrecursive ? " -r" : "", pflag ? " -p" : "",
262 targetshouldbedirectory ? " -d" : "");
265 signal(SIGPIPE, lostconn);
267 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
268 toremote(targ, argc, argv);
270 tolocal(argc, argv); /* Dest is local host. */
271 if (targetshouldbedirectory)
272 verifydir(argv[argc - 1]);
278 toremote(char *targ, int argc, char *argv[])
281 char *bp, *host, *src, *suser, *thost, *tuser;
285 targ = __DECONST(char *, ".");
287 if ((thost = strchr(argv[argc - 1], '@'))) {
290 tuser = argv[argc - 1];
293 else if (!okname(tuser))
296 thost = argv[argc - 1];
300 for (i = 0; i < argc - 1; i++) {
301 src = colon(argv[i]);
302 if (src) { /* remote to remote */
305 src = __DECONST(char *, ".");
306 host = strchr(argv[i], '@');
307 len = strlen(_PATH_RSH) + strlen(argv[i]) +
308 strlen(src) + (tuser ? strlen(tuser) : 0) +
309 strlen(thost) + strlen(targ) + CMDNEEDS + 20;
310 if (!(bp = malloc(len)))
316 suser = pwd->pw_name;
317 else if (!okname(suser)) {
322 "%s %s -l %s -n %s %s '%s%s%s:%s'",
323 _PATH_RSH, host, suser, cmd, src,
324 tuser ? tuser : "", tuser ? "@" : "",
328 "exec %s %s -n %s %s '%s%s%s:%s'",
329 _PATH_RSH, argv[i], cmd, src,
330 tuser ? tuser : "", tuser ? "@" : "",
332 susystem(bp, userid);
334 } else { /* local to remote */
336 len = strlen(targ) + CMDNEEDS + 20;
337 if (!(bp = malloc(len)))
339 snprintf(bp, len, "%s -t %s", cmd, targ);
343 rem = kerberos(&host, bp,
345 tuser ? tuser : pwd->pw_name);
348 rem = rcmd_af(&host, port,
350 tuser ? tuser : pwd->pw_name,
354 if (family == PF_INET) {
355 tos = IPTOS_THROUGHPUT;
356 if (setsockopt(rem, IPPROTO_IP, IP_TOS,
357 &tos, sizeof(int)) < 0)
358 warn("TOS (ignored)");
371 tolocal(int argc, char *argv[])
374 char *bp, *host, *src, *suser;
376 for (i = 0; i < argc - 1; i++) {
377 if (!(src = colon(argv[i]))) { /* Local to local. */
378 len = strlen(_PATH_CP) + strlen(argv[i]) +
379 strlen(argv[argc - 1]) + 20;
380 if (!(bp = malloc(len)))
382 snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
383 iamrecursive ? " -PR" : "", pflag ? " -p" : "",
384 argv[i], argv[argc - 1]);
385 if (susystem(bp, userid))
392 src = __DECONST(char *, ".");
393 if ((host = strchr(argv[i], '@')) == NULL) {
395 suser = pwd->pw_name;
400 suser = pwd->pw_name;
401 else if (!okname(suser)) {
406 len = strlen(src) + CMDNEEDS + 20;
407 if ((bp = malloc(len)) == NULL)
409 snprintf(bp, len, "%s -f %s", cmd, src);
413 kerberos(&host, bp, pwd->pw_name, suser) :
415 rcmd_af(&host, port, pwd->pw_name, suser, bp, 0,
423 if (family == PF_INET) {
424 tos = IPTOS_THROUGHPUT;
425 if (setsockopt(rem, IPPROTO_IP, IP_TOS, &tos,
427 warn("TOS (ignored)");
429 sink(1, argv + argc - 1);
437 source(int argc, char *argv[])
443 int amt, fd, haderr, indx, result;
444 char *last, *name, buf[BUFSIZ];
446 for (indx = 0; indx < argc; ++indx) {
448 if ((fd = open(name, O_RDONLY, 0)) < 0)
450 if (fstat(fd, &stb)) {
451 syserr: run_err("%s: %s", name, strerror(errno));
454 switch (stb.st_mode & S_IFMT) {
464 run_err("%s: not a regular file", name);
467 if ((last = strrchr(name, '/')) == NULL)
473 * Make it compatible with possible future
474 * versions expecting microseconds.
476 snprintf(buf, sizeof(buf), "T%ld 0 %ld 0\n",
477 (long)stb.st_mtimespec.tv_sec,
478 (long)stb.st_atimespec.tv_sec);
479 write(rem, buf, strlen(buf));
483 #define MODEMASK (S_ISUID|S_ISGID|S_ISTXT|S_IRWXU|S_IRWXG|S_IRWXO)
484 snprintf(buf, sizeof(buf), "C%04o %jd %s\n",
485 stb.st_mode & MODEMASK, (intmax_t)stb.st_size, last);
486 write(rem, buf, strlen(buf));
489 if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
490 next: (void)close(fd);
494 /* Keep writing after an error so that we stay sync'd up. */
495 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
497 if (i + amt > stb.st_size)
498 amt = stb.st_size - i;
500 result = read(fd, bp->buf, amt);
502 haderr = result >= 0 ? EIO : errno;
505 write(rem, bp->buf, amt);
507 result = write(rem, bp->buf, amt);
509 haderr = result >= 0 ? EIO : errno;
512 if (close(fd) && !haderr)
517 run_err("%s: %s", name, strerror(haderr));
523 rsource(char *name, struct stat *statp)
527 char *last, *vect[1], path[PATH_MAX];
529 if (!(dirp = opendir(name))) {
530 run_err("%s: %s", name, strerror(errno));
533 last = strrchr(name, '/');
539 snprintf(path, sizeof(path), "T%ld 0 %ld 0\n",
540 (long)statp->st_mtimespec.tv_sec,
541 (long)statp->st_atimespec.tv_sec);
542 write(rem, path, strlen(path));
543 if (response() < 0) {
548 snprintf(path, sizeof(path),
549 "D%04o %d %s\n", statp->st_mode & MODEMASK, 0, last);
550 write(rem, path, strlen(path));
551 if (response() < 0) {
555 while ((dp = readdir(dirp))) {
558 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
560 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path)) {
561 run_err("%s/%s: name too long", name, dp->d_name);
564 snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
569 write(rem, "E\n", 2);
574 sink(int argc, char *argv[])
578 struct timeval tv[2];
579 enum { YES, NO, DISPLAYED } wrerr;
583 int amt, exists, first, mask, mode, ofd, omode;
584 int setimes, targisdir, wrerrno = 0;
585 char ch, *cp, *np, *targ, *why, *vect[1], buf[BUFSIZ], path[PATH_MAX];
589 #define SCREWUP(str) { why = __DECONST(char *, str); goto screwup; }
591 setimes = targisdir = 0;
596 run_err("ambiguous target");
600 if (targetshouldbedirectory)
603 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
605 for (first = 1;; first = 0) {
607 if (read(rem, cp, 1) <= 0)
610 SCREWUP("unexpected <newline>");
612 if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
613 SCREWUP("lost connection");
615 } while (cp < &buf[BUFSIZ - 1] && ch != '\n');
618 if (buf[0] == '\01' || buf[0] == '\02') {
621 buf + 1, strlen(buf + 1));
639 mtime.tv_sec = strtol(cp, &cp, 10);
640 if (!cp || *cp++ != ' ')
641 SCREWUP("mtime.sec not delimited");
642 mtime.tv_usec = strtol(cp, &cp, 10);
643 if (!cp || *cp++ != ' ')
644 SCREWUP("mtime.usec not delimited");
645 atime.tv_sec = strtol(cp, &cp, 10);
646 if (!cp || *cp++ != ' ')
647 SCREWUP("atime.sec not delimited");
648 atime.tv_usec = strtol(cp, &cp, 10);
649 if (!cp || *cp++ != '\0')
650 SCREWUP("atime.usec not delimited");
654 if (*cp != 'C' && *cp != 'D') {
656 * Check for the case "rcp remote:foo\* local:bar".
657 * In this case, the line "No match." can be returned
658 * by the shell before the rcp command on the remote is
659 * executed so the ^Aerror_message convention isn't
666 SCREWUP("expected control record");
669 for (++cp; cp < buf + 5; cp++) {
670 if (*cp < '0' || *cp > '7')
672 mode = (mode << 3) | (*cp - '0');
675 SCREWUP("mode not delimited");
677 for (size = 0; isdigit(*cp);)
678 size = size * 10 + (*cp++ - '0');
680 SCREWUP("size not delimited");
682 if (strlen(targ) + (*targ ? 1 : 0) + strlen(cp)
684 run_err("%s%s%s: name too long", targ,
685 *targ ? "/" : "", cp);
688 snprintf(path, sizeof(path), "%s%s%s", targ,
689 *targ ? "/" : "", cp);
693 exists = stat(np, &stb) == 0;
695 int mod_flag = pflag;
697 if (!S_ISDIR(stb.st_mode)) {
704 /* Handle copying from a read-only directory */
706 if (mkdir(np, mode | S_IRWXU) < 0)
713 if (utimes(np, tv) < 0)
714 run_err("%s: set times: %s",
715 np, strerror(errno));
723 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
724 bad: run_err("%s: %s", np, strerror(errno));
728 if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
734 for (count = i = 0; i < size; i += BUFSIZ) {
740 j = read(rem, cp, amt);
742 run_err("%s", j ? strerror(errno) :
743 "dropped connection");
749 if (count == bp->cnt) {
750 /* Keep reading so we stay sync'd up. */
752 j = write(ofd, bp->buf, count);
753 if (j != (off_t)count) {
755 wrerrno = j >= 0 ? EIO : errno;
762 if (count != 0 && wrerr == NO &&
763 (j = write(ofd, bp->buf, count)) != (off_t)count) {
765 wrerrno = j >= 0 ? EIO : errno;
767 if (ftruncate(ofd, size)) {
768 run_err("%s: truncate: %s", np, strerror(errno));
772 if (exists || omode != mode)
773 if (fchmod(ofd, omode))
774 run_err("%s: set mode: %s",
775 np, strerror(errno));
777 if (!exists && omode != mode)
778 if (fchmod(ofd, omode & ~mask))
779 run_err("%s: set mode: %s",
780 np, strerror(errno));
784 if (setimes && wrerr == NO) {
786 if (utimes(np, tv) < 0) {
787 run_err("%s: set times: %s",
788 np, strerror(errno));
794 run_err("%s: %s", np, strerror(wrerrno));
804 run_err("protocol error: %s", why);
810 kerberos(char **host, char *bp, char *locuser, char *user)
816 if (dest_realm == NULL)
817 dest_realm = krb_realmofhost(*host);
822 port, user, bp, 0, dest_realm, &cred, schedule) :
824 krcmd(host, port, user, bp, 0, dest_realm);
827 if (errno == ECONNREFUSED)
828 oldw("remote host doesn't support Kerberos");
829 else if (errno == ENOENT)
830 oldw("can't provide Kerberos authentication data");
831 execv(_PATH_RCP, argv_copy);
832 err(1, "execv: %s", _PATH_RCP);
838 "the -x option requires Kerberos authentication");
840 rem = rcmd_af(host, port, locuser, user, bp, 0, family);
844 #endif /* KERBEROS */
849 char ch, *cp, resp, rbuf[BUFSIZ];
851 if (read(rem, &resp, sizeof(resp)) != sizeof(resp))
861 case 1: /* error, followed by error msg */
862 case 2: /* fatal error, "" */
864 if (read(rem, &ch, sizeof(ch)) != sizeof(ch))
867 } while (cp < &rbuf[BUFSIZ] && ch != '\n');
870 write(STDERR_FILENO, rbuf, cp - rbuf);
884 fprintf(stderr, "%s\n%s\n",
885 "usage: rcp [-46Kpx] [-k realm] f1 f2",
886 " rcp [-46Kprx] [-k realm] f1 ... fn directory");
888 fprintf(stderr, "%s\n%s\n",
889 "usage: rcp [-46Kp] [-k realm] f1 f2",
890 " rcp [-46Kpr] [-k realm] f1 ... fn directory");
893 fprintf(stderr, "%s\n%s\n",
894 "usage: rcp [-46p] f1 f2",
895 " rcp [-46pr] f1 ... fn directory");
904 oldw(const char *fmt, ...)
908 fprintf(stderr, "rcp: ");
909 vfprintf(stderr, fmt, ap);
910 fprintf(stderr, ", using standard rcp\n");
916 run_err(const char *fmt, ...)
923 if (fp == NULL && !(fp = fdopen(rem, "w")))
925 fprintf(fp, "%c", 0x01);
926 fprintf(fp, "rcp: ");
927 vfprintf(fp, fmt, ap);