copy news from release branch
[heimdal.git] / appl / rcp / rcp.c
blob2ad8ff6077bd724bc6b0e8e596a1e0c5893d463e
1 /*
2 * Copyright (c) 1983, 1990, 1992, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
30 #include "rcp_locl.h"
31 #include <getarg.h>
33 #define RSH_PROGRAM "rsh"
35 struct passwd *pwd;
36 uid_t userid;
37 int errs, remin, remout;
38 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
39 int doencrypt, noencrypt;
40 int usebroken, usekrb4, usekrb5, forwardtkt;
41 char *port;
42 int eflag = 0;
44 #define CMDNEEDS 64
45 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
47 int response (void);
48 void rsource (char *, struct stat *);
49 void sink (int, char *[]);
50 void source (int, char *[]);
51 void tolocal (int, char *[]);
52 void toremote (char *, int, char *[]);
54 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
56 static int fflag, tflag;
58 static int version_flag, help_flag;
60 struct getargs args[] = {
61 { NULL, '4', arg_flag, &usekrb4, "use Kerberos 4 authentication", NULL },
62 { NULL, '5', arg_flag, &usekrb5, "use Kerberos 5 authentication", NULL },
63 { NULL, 'F', arg_flag, &forwardtkt, "forward credentials", NULL },
64 { NULL, 'K', arg_flag, &usebroken, "use BSD authentication",
65 NULL },
66 { NULL, 'P', arg_string, &port, "non-default port", "port" },
67 { NULL, 'p', arg_flag, &pflag, "preserve file permissions",
68 NULL },
69 { NULL, 'r', arg_flag, &iamrecursive, "recursive mode", NULL },
70 { NULL, 'x', arg_flag, &doencrypt, "use encryption", NULL },
71 { NULL, 'z', arg_flag, &noencrypt, "don't encrypt", NULL },
72 { NULL, 'd', arg_flag, &targetshouldbedirectory, NULL, NULL },
73 { NULL, 'e', arg_flag, &eflag, "passed to rsh", NULL },
74 { NULL, 'f', arg_flag, &fflag, NULL, NULL },
75 { NULL, 't', arg_flag, &tflag, NULL, NULL },
76 { "version", 0, arg_flag, &version_flag, NULL, NULL },
77 { "help", 0, arg_flag, &help_flag, NULL, NULL }
80 static void
81 usage (int ret)
83 arg_printusage (args,
84 sizeof(args) / sizeof(args[0]),
85 NULL,
86 "file1 file2|file... directory");
87 exit (ret);
90 int
91 main(int argc, char **argv)
93 char *targ;
94 int optind = 0;
96 setprogname(argv[0]);
97 if (getarg (args, sizeof(args) / sizeof(args[0]), argc, argv,
98 &optind))
99 usage (1);
100 if(help_flag)
101 usage(0);
102 if (version_flag) {
103 print_version (NULL);
104 return 0;
107 iamremote = (fflag || tflag);
109 argc -= optind;
110 argv += optind;
112 if ((pwd = getpwuid(userid = getuid())) == NULL)
113 errx(1, "unknown user %d", (int)userid);
115 remin = STDIN_FILENO; /* XXX */
116 remout = STDOUT_FILENO;
118 if (fflag) { /* Follow "protocol", send data. */
119 (void)response();
120 source(argc, argv);
121 exit(errs);
124 if (tflag) { /* Receive data. */
125 sink(argc, argv);
126 exit(errs);
129 if (argc < 2)
130 usage(1);
131 if (argc > 2)
132 targetshouldbedirectory = 1;
134 remin = remout = -1;
135 /* Command to be executed on remote system using "rsh". */
136 snprintf(cmd, sizeof(cmd),
137 "rcp%s%s%s", iamrecursive ? " -r" : "",
138 pflag ? " -p" : "", targetshouldbedirectory ? " -d" : "");
140 signal(SIGPIPE, lostconn);
142 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
143 toremote(targ, argc, argv);
144 else {
145 tolocal(argc, argv); /* Dest is local host. */
146 if (targetshouldbedirectory)
147 verifydir(argv[argc - 1]);
149 exit(errs);
152 void
153 toremote(char *targ, int argc, char **argv)
155 int i;
156 char *bp, *host, *src, *suser, *thost, *tuser;
158 *targ++ = 0;
159 if (*targ == 0)
160 targ = ".";
162 if ((thost = strchr(argv[argc - 1], '@')) != NULL) {
163 /* user@host */
164 *thost++ = 0;
165 tuser = argv[argc - 1];
166 if (*tuser == '\0')
167 tuser = NULL;
168 else if (!okname(tuser))
169 exit(1);
170 } else {
171 thost = argv[argc - 1];
172 tuser = NULL;
174 thost = unbracket(thost);
176 for (i = 0; i < argc - 1; i++) {
177 src = colon(argv[i]);
178 if (src) { /* remote to remote */
179 int ret;
180 *src++ = 0;
181 if (*src == 0)
182 src = ".";
183 host = strchr(argv[i], '@');
184 if (host) {
185 *host++ = '\0';
186 host = unbracket(host);
187 suser = argv[i];
188 if (*suser == '\0')
189 suser = pwd->pw_name;
190 else if (!okname(suser))
191 continue;
192 ret = asprintf(&bp,
193 "%s%s %s -l %s -n %s %s '%s%s%s:%s'",
194 _PATH_RSH, eflag ? " -e" : "",
195 host, suser, cmd, src,
196 tuser ? tuser : "", tuser ? "@" : "",
197 thost, targ);
198 } else {
199 host = unbracket(argv[i]);
200 ret = asprintf(&bp,
201 "exec %s%s %s -n %s %s '%s%s%s:%s'",
202 _PATH_RSH, eflag ? " -e" : "",
203 host, cmd, src,
204 tuser ? tuser : "", tuser ? "@" : "",
205 thost, targ);
207 if (ret == -1)
208 err (1, "malloc");
209 susystem(bp);
210 free(bp);
211 } else { /* local to remote */
212 if (remin == -1) {
213 if (asprintf(&bp, "%s -t %s", cmd, targ) == -1)
214 err (1, "malloc");
215 host = thost;
217 if (do_cmd(host, tuser, bp, &remin, &remout) < 0)
218 exit(1);
220 if (response() < 0)
221 exit(1);
222 free(bp);
224 source(1, argv+i);
229 void
230 tolocal(int argc, char **argv)
232 int i;
233 char *bp, *host, *src, *suser;
235 for (i = 0; i < argc - 1; i++) {
236 int ret;
238 if (!(src = colon(argv[i]))) { /* Local to local. */
239 ret = asprintf(&bp, "exec %s%s%s %s %s", _PATH_CP,
240 iamrecursive ? " -PR" : "", pflag ? " -p" : "",
241 argv[i], argv[argc - 1]);
242 if (ret == -1)
243 err (1, "malloc");
244 if (susystem(bp))
245 ++errs;
246 free(bp);
247 continue;
249 *src++ = 0;
250 if (*src == 0)
251 src = ".";
252 if ((host = strchr(argv[i], '@')) == NULL) {
253 host = argv[i];
254 suser = pwd->pw_name;
255 } else {
256 *host++ = 0;
257 suser = argv[i];
258 if (*suser == '\0')
259 suser = pwd->pw_name;
260 else if (!okname(suser))
261 continue;
263 ret = asprintf(&bp, "%s -f %s", cmd, src);
264 if (ret == -1)
265 err (1, "malloc");
266 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
267 free(bp);
268 ++errs;
269 continue;
271 free(bp);
272 sink(1, argv + argc - 1);
273 close(remin);
274 remin = remout = -1;
278 void
279 source(int argc, char **argv)
281 struct stat stb;
282 static BUF buffer;
283 BUF *bp;
284 off_t i;
285 off_t amt;
286 int fd, haderr, indx, result;
287 char *last, *name, buf[BUFSIZ];
289 for (indx = 0; indx < argc; ++indx) {
290 name = argv[indx];
291 if ((fd = open(name, O_RDONLY, 0)) < 0)
292 goto syserr;
293 if (fstat(fd, &stb)) {
294 syserr: run_err("%s: %s", name, strerror(errno));
295 goto next;
297 if (S_ISDIR(stb.st_mode) && iamrecursive) {
298 rsource(name, &stb);
299 goto next;
300 } else if (!S_ISREG(stb.st_mode)) {
301 run_err("%s: not a regular file", name);
302 goto next;
304 if ((last = strrchr(name, '/')) == NULL)
305 last = name;
306 else
307 ++last;
308 if (pflag) {
310 * Make it compatible with possible future
311 * versions expecting microseconds.
313 snprintf(buf, sizeof(buf), "T%ld 0 %ld 0\n",
314 (long)stb.st_mtime,
315 (long)stb.st_atime);
316 write(remout, buf, strlen(buf));
317 if (response() < 0)
318 goto next;
320 #undef MODEMASK
321 #define MODEMASK (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)
322 snprintf(buf, sizeof(buf), "C%04o %lu %s\n",
323 (unsigned int)(stb.st_mode & MODEMASK),
324 (unsigned long)stb.st_size,
325 last);
326 write(remout, buf, strlen(buf));
327 if (response() < 0)
328 goto next;
329 if ((bp = allocbuf(&buffer, fd, BUFSIZ)) == NULL) {
330 next: close(fd);
331 continue;
334 /* Keep writing after an error so that we stay sync'd up. */
335 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
336 amt = bp->cnt;
337 if (i + amt > stb.st_size)
338 amt = stb.st_size - i;
339 if (!haderr) {
340 result = read(fd, bp->buf, (size_t)amt);
341 if (result != amt)
342 haderr = result >= 0 ? EIO : errno;
344 if (haderr)
345 write(remout, bp->buf, amt);
346 else {
347 result = write(remout, bp->buf, (size_t)amt);
348 if (result != amt)
349 haderr = result >= 0 ? EIO : errno;
352 if (close(fd) && !haderr)
353 haderr = errno;
354 if (!haderr)
355 write(remout, "", 1);
356 else
357 run_err("%s: %s", name, strerror(haderr));
358 response();
362 void
363 rsource(char *name, struct stat *statp)
365 DIR *dirp;
366 struct dirent *dp;
367 char *last, *vect[1], path[MAXPATHLEN];
369 if (!(dirp = opendir(name))) {
370 run_err("%s: %s", name, strerror(errno));
371 return;
373 last = strrchr(name, '/');
374 if (last == 0)
375 last = name;
376 else
377 last++;
378 if (pflag) {
379 snprintf(path, sizeof(path), "T%ld 0 %ld 0\n",
380 (long)statp->st_mtime,
381 (long)statp->st_atime);
382 write(remout, path, strlen(path));
383 if (response() < 0) {
384 closedir(dirp);
385 return;
388 snprintf(path, sizeof(path),
389 "D%04o %d %s\n",
390 (unsigned int)(statp->st_mode & MODEMASK), 0, last);
391 write(remout, path, strlen(path));
392 if (response() < 0) {
393 closedir(dirp);
394 return;
396 while ((dp = readdir(dirp)) != NULL) {
397 if (dp->d_ino == 0)
398 continue;
399 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
400 continue;
401 if (strlen(name) + 1 + strlen(dp->d_name) >= MAXPATHLEN - 1) {
402 run_err("%s/%s: name too long", name, dp->d_name);
403 continue;
405 snprintf(path, sizeof(path), "%s/%s", name, dp->d_name);
406 vect[0] = path;
407 source(1, vect);
409 closedir(dirp);
410 write(remout, "E\n", 2);
411 response();
414 void
415 sink(int argc, char **argv)
417 static BUF buffer;
418 struct stat stb;
419 struct timeval tv[2];
420 enum { YES, NO, DISPLAYED } wrerr;
421 BUF *bp;
422 off_t i, j, size;
423 int amt, count, exists, first, mask, mode, ofd, omode;
424 int setimes, targisdir, wrerrno = 0;
425 char ch, *cp, *np, *targ, *why, *vect[1], buf[BUFSIZ];
427 #define atime tv[0]
428 #define mtime tv[1]
429 #define SCREWUP(str) { why = str; goto screwup; }
431 setimes = targisdir = 0;
432 mask = umask(0);
433 if (!pflag)
434 umask(mask);
435 if (argc != 1) {
436 run_err("ambiguous target");
437 exit(1);
439 targ = *argv;
440 if (targetshouldbedirectory)
441 verifydir(targ);
442 write(remout, "", 1);
443 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
444 targisdir = 1;
445 for (first = 1;; first = 0) {
446 cp = buf;
447 if (read(remin, cp, 1) <= 0)
448 return;
449 if (*cp++ == '\n')
450 SCREWUP("unexpected <newline>");
451 do {
452 if (read(remin, &ch, sizeof(ch)) != sizeof(ch))
453 SCREWUP("lost connection");
454 *cp++ = ch;
455 } while (cp < &buf[BUFSIZ - 1] && ch != '\n');
456 *cp = 0;
458 if (buf[0] == '\01' || buf[0] == '\02') {
459 if (iamremote == 0)
460 write(STDERR_FILENO,
461 buf + 1, strlen(buf + 1));
462 if (buf[0] == '\02')
463 exit(1);
464 ++errs;
465 continue;
467 if (buf[0] == 'E') {
468 write(remout, "", 1);
469 return;
472 if (ch == '\n')
473 *--cp = 0;
475 cp = buf;
476 if (*cp == 'T') {
477 setimes++;
478 cp++;
479 mtime.tv_sec = strtol(cp, &cp, 10);
480 if (!cp || *cp++ != ' ')
481 SCREWUP("mtime.sec not delimited");
482 mtime.tv_usec = strtol(cp, &cp, 10);
483 if (!cp || *cp++ != ' ')
484 SCREWUP("mtime.usec not delimited");
485 atime.tv_sec = strtol(cp, &cp, 10);
486 if (!cp || *cp++ != ' ')
487 SCREWUP("atime.sec not delimited");
488 atime.tv_usec = strtol(cp, &cp, 10);
489 if (!cp || *cp++ != '\0')
490 SCREWUP("atime.usec not delimited");
491 write(remout, "", 1);
492 continue;
494 if (*cp != 'C' && *cp != 'D') {
496 * Check for the case "rcp remote:foo\* local:bar".
497 * In this case, the line "No match." can be returned
498 * by the shell before the rcp command on the remote is
499 * executed so the ^Aerror_message convention isn't
500 * followed.
502 if (first) {
503 run_err("%s", cp);
504 exit(1);
506 SCREWUP("expected control record");
508 mode = 0;
509 for (++cp; cp < buf + 5; cp++) {
510 if (*cp < '0' || *cp > '7')
511 SCREWUP("bad mode");
512 mode = (mode << 3) | (*cp - '0');
514 if (*cp++ != ' ')
515 SCREWUP("mode not delimited");
517 for (size = 0; isdigit((unsigned char)*cp);)
518 size = size * 10 + (*cp++ - '0');
519 if (*cp++ != ' ')
520 SCREWUP("size not delimited");
521 if (targisdir) {
522 static char *namebuf;
523 static int cursize;
524 size_t need;
526 need = strlen(targ) + strlen(cp) + 250;
527 if (need > cursize) {
528 if (!(namebuf = malloc(need)))
529 run_err("%s", strerror(errno));
531 snprintf(namebuf, need, "%s%s%s", targ,
532 *targ ? "/" : "", cp);
533 np = namebuf;
534 } else
535 np = targ;
536 exists = stat(np, &stb) == 0;
537 if (buf[0] == 'D') {
538 int mod_flag = pflag;
539 if (exists) {
540 if (!S_ISDIR(stb.st_mode)) {
541 errno = ENOTDIR;
542 goto bad;
544 if (pflag)
545 chmod(np, mode);
546 } else {
547 /* Handle copying from a read-only directory */
548 mod_flag = 1;
549 if (mkdir(np, mode | S_IRWXU) < 0)
550 goto bad;
552 vect[0] = np;
553 sink(1, vect);
554 if (setimes) {
555 setimes = 0;
556 if (utimes(np, tv) < 0)
557 run_err("%s: set times: %s",
558 np, strerror(errno));
560 if (mod_flag)
561 chmod(np, mode);
562 continue;
564 omode = mode;
565 mode |= S_IWRITE;
566 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
567 bad: run_err("%s: %s", np, strerror(errno));
568 continue;
570 write(remout, "", 1);
571 if ((bp = allocbuf(&buffer, ofd, BUFSIZ)) == NULL) {
572 close(ofd);
573 continue;
575 cp = bp->buf;
576 wrerr = NO;
577 for (count = i = 0; i < size; i += BUFSIZ) {
578 amt = BUFSIZ;
579 if (i + amt > size)
580 amt = size - i;
581 count += amt;
582 if((j = net_read(remin, cp, amt)) != amt) {
583 run_err("%s", j ? strerror(errno) :
584 "dropped connection");
585 exit(1);
587 amt -= j;
588 cp += j;
589 if (count == bp->cnt) {
590 /* Keep reading so we stay sync'd up. */
591 if (wrerr == NO) {
592 j = write(ofd, bp->buf, (size_t)count);
593 if (j != count) {
594 wrerr = YES;
595 wrerrno = j >= 0 ? EIO : errno;
598 count = 0;
599 cp = bp->buf;
602 if (count != 0 && wrerr == NO &&
603 (j = write(ofd, bp->buf, (size_t)count)) != count) {
604 wrerr = YES;
605 wrerrno = j >= 0 ? EIO : errno;
607 if (ftruncate(ofd, size)) {
608 run_err("%s: truncate: %s", np, strerror(errno));
609 wrerr = DISPLAYED;
611 if (pflag) {
612 if (exists || omode != mode)
613 if (fchmod(ofd, omode))
614 run_err("%s: set mode: %s",
615 np, strerror(errno));
616 } else {
617 if (!exists && omode != mode)
618 if (fchmod(ofd, omode & ~mask))
619 run_err("%s: set mode: %s",
620 np, strerror(errno));
622 close(ofd);
623 response();
624 if (setimes && wrerr == NO) {
625 setimes = 0;
626 if (utimes(np, tv) < 0) {
627 run_err("%s: set times: %s",
628 np, strerror(errno));
629 wrerr = DISPLAYED;
632 switch(wrerr) {
633 case YES:
634 run_err("%s: %s", np, strerror(wrerrno));
635 break;
636 case NO:
637 write(remout, "", 1);
638 break;
639 case DISPLAYED:
640 break;
643 screwup:
644 run_err("protocol error: %s", why);
645 exit(1);
649 response(void)
651 char ch, *cp, resp, rbuf[BUFSIZ];
653 if (read(remin, &resp, sizeof(resp)) != sizeof(resp))
654 lostconn(0);
656 cp = rbuf;
657 switch(resp) {
658 case 0: /* ok */
659 return (0);
660 default:
661 *cp++ = resp;
662 /* FALLTHROUGH */
663 case 1: /* error, followed by error msg */
664 case 2: /* fatal error, "" */
665 do {
666 if (read(remin, &ch, sizeof(ch)) != sizeof(ch))
667 lostconn(0);
668 *cp++ = ch;
669 } while (cp < &rbuf[BUFSIZ] && ch != '\n');
671 if (!iamremote)
672 write(STDERR_FILENO, rbuf, cp - rbuf);
673 ++errs;
674 if (resp == 1)
675 return (-1);
676 exit(1);
678 /* NOTREACHED */
681 #include <stdarg.h>
683 void
684 run_err(const char *fmt, ...)
686 static FILE *fp;
687 va_list ap;
689 ++errs;
690 if (fp == NULL && !(fp = fdopen(remout, "w")))
691 return;
692 va_start(ap, fmt);
693 fprintf(fp, "%c", 0x01);
694 fprintf(fp, "rcp: ");
695 vfprintf(fp, fmt, ap);
696 fprintf(fp, "\n");
697 fflush(fp);
698 va_end(ap);
700 if (!iamremote) {
701 va_start(ap, fmt);
702 vwarnx(fmt, ap);
703 va_end(ap);
708 * This function executes the given command as the specified user on the
709 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
710 * assigns the input and output file descriptors on success.
712 * If it cannot create necessary pipes it exits with error message.
716 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
718 int pin[2], pout[2], reserved[2];
721 * Reserve two descriptors so that the real pipes won't get
722 * descriptors 0 and 1 because that will screw up dup2 below.
724 pipe(reserved);
726 /* Create a socket pair for communicating with rsh. */
727 if (pipe(pin) < 0) {
728 perror("pipe");
729 exit(255);
731 if (pipe(pout) < 0) {
732 perror("pipe");
733 exit(255);
736 /* Free the reserved descriptors. */
737 close(reserved[0]);
738 close(reserved[1]);
740 /* For a child to execute the command on the remote host using rsh. */
741 if (fork() == 0) {
742 char *args[100];
743 unsigned int i;
745 /* Child. */
746 close(pin[1]);
747 close(pout[0]);
748 dup2(pin[0], 0);
749 dup2(pout[1], 1);
750 close(pin[0]);
751 close(pout[1]);
753 i = 0;
754 args[i++] = RSH_PROGRAM;
755 if (usekrb4)
756 args[i++] = "-4";
757 if (usekrb5)
758 args[i++] = "-5";
759 if (usebroken)
760 args[i++] = "-K";
761 if (doencrypt)
762 args[i++] = "-x";
763 if (forwardtkt)
764 args[i++] = "-F";
765 if (noencrypt)
766 args[i++] = "-z";
767 if (port != NULL) {
768 args[i++] = "-p";
769 args[i++] = port;
771 if (eflag)
772 args[i++] = "-e";
773 if (remuser != NULL) {
774 args[i++] = "-l";
775 args[i++] = remuser;
777 args[i++] = host;
778 args[i++] = cmd;
779 args[i++] = NULL;
781 execvp(RSH_PROGRAM, args);
782 perror(RSH_PROGRAM);
783 exit(1);
785 /* Parent. Close the other side, and return the local side. */
786 close(pin[0]);
787 *fdout = pin[1];
788 close(pout[1]);
789 *fdin = pout[0];
790 return 0;