- djm@cvs.openbsd.org 2010/12/04 00:18:01
[openssh-git.git] / scp.c
blob774e602f2f2675a8dec2c384b093b1adb1e634a8
1 /* $OpenBSD: scp.c,v 1.168 2010/11/26 05:52:49 djm Exp $ */
2 /*
3 * scp - secure remote copy. This is basically patched BSD rcp which
4 * uses ssh to do the data transfer (instead of using rcmd).
6 * NOTE: This version should NOT be suid root. (This uses ssh to
7 * do the transfer and ssh has the necessary privileges.)
9 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
18 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
19 * Copyright (c) 1999 Aaron Campbell. All rights reserved.
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
23 * are met:
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43 * Parts from:
45 * Copyright (c) 1983, 1990, 1992, 1993, 1995
46 * The Regents of the University of California. All rights reserved.
48 * Redistribution and use in source and binary forms, with or without
49 * modification, are permitted provided that the following conditions
50 * are met:
51 * 1. Redistributions of source code must retain the above copyright
52 * notice, this list of conditions and the following disclaimer.
53 * 2. Redistributions in binary form must reproduce the above copyright
54 * notice, this list of conditions and the following disclaimer in the
55 * documentation and/or other materials provided with the distribution.
56 * 3. Neither the name of the University nor the names of its contributors
57 * may be used to endorse or promote products derived from this software
58 * without specific prior written permission.
60 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 * SUCH DAMAGE.
74 #include "includes.h"
76 #include <sys/types.h>
77 #include <sys/param.h>
78 #ifdef HAVE_SYS_STAT_H
79 # include <sys/stat.h>
80 #endif
81 #ifdef HAVE_POLL_H
82 #include <poll.h>
83 #else
84 # ifdef HAVE_SYS_POLL_H
85 # include <sys/poll.h>
86 # endif
87 #endif
88 #ifdef HAVE_SYS_TIME_H
89 # include <sys/time.h>
90 #endif
91 #include <sys/wait.h>
92 #include <sys/uio.h>
94 #include <ctype.h>
95 #include <dirent.h>
96 #include <errno.h>
97 #include <fcntl.h>
98 #include <pwd.h>
99 #include <signal.h>
100 #include <stdarg.h>
101 #include <stdio.h>
102 #include <stdlib.h>
103 #include <string.h>
104 #include <time.h>
105 #include <unistd.h>
106 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H)
107 #include <vis.h>
108 #endif
110 #include "xmalloc.h"
111 #include "atomicio.h"
112 #include "pathnames.h"
113 #include "log.h"
114 #include "misc.h"
115 #include "progressmeter.h"
117 extern char *__progname;
119 #define COPY_BUFLEN 16384
121 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
123 /* Struct for addargs */
124 arglist args;
125 arglist remote_remote_args;
127 /* Bandwidth limit */
128 long long limit_kbps = 0;
129 struct bwlimit bwlimit;
131 /* Name of current file being transferred. */
132 char *curfile;
134 /* This is set to non-zero to enable verbose mode. */
135 int verbose_mode = 0;
137 /* This is set to zero if the progressmeter is not desired. */
138 int showprogress = 1;
140 /* This is the program to execute for the secured connection. ("ssh" or -S) */
141 char *ssh_program = _PATH_SSH_PROGRAM;
143 /* This is used to store the pid of ssh_program */
144 pid_t do_cmd_pid = -1;
146 static void
147 killchild(int signo)
149 if (do_cmd_pid > 1) {
150 kill(do_cmd_pid, signo ? signo : SIGTERM);
151 waitpid(do_cmd_pid, NULL, 0);
154 if (signo)
155 _exit(1);
156 exit(1);
159 static void
160 suspchild(int signo)
162 int status;
164 if (do_cmd_pid > 1) {
165 kill(do_cmd_pid, signo);
166 while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
167 errno == EINTR)
169 kill(getpid(), SIGSTOP);
173 static int
174 do_local_cmd(arglist *a)
176 u_int i;
177 int status;
178 pid_t pid;
180 if (a->num == 0)
181 fatal("do_local_cmd: no arguments");
183 if (verbose_mode) {
184 fprintf(stderr, "Executing:");
185 for (i = 0; i < a->num; i++)
186 fprintf(stderr, " %s", a->list[i]);
187 fprintf(stderr, "\n");
189 if ((pid = fork()) == -1)
190 fatal("do_local_cmd: fork: %s", strerror(errno));
192 if (pid == 0) {
193 execvp(a->list[0], a->list);
194 perror(a->list[0]);
195 exit(1);
198 do_cmd_pid = pid;
199 signal(SIGTERM, killchild);
200 signal(SIGINT, killchild);
201 signal(SIGHUP, killchild);
203 while (waitpid(pid, &status, 0) == -1)
204 if (errno != EINTR)
205 fatal("do_local_cmd: waitpid: %s", strerror(errno));
207 do_cmd_pid = -1;
209 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
210 return (-1);
212 return (0);
216 * This function executes the given command as the specified user on the
217 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
218 * assigns the input and output file descriptors on success.
222 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
224 int pin[2], pout[2], reserved[2];
226 if (verbose_mode)
227 fprintf(stderr,
228 "Executing: program %s host %s, user %s, command %s\n",
229 ssh_program, host,
230 remuser ? remuser : "(unspecified)", cmd);
233 * Reserve two descriptors so that the real pipes won't get
234 * descriptors 0 and 1 because that will screw up dup2 below.
236 if (pipe(reserved) < 0)
237 fatal("pipe: %s", strerror(errno));
239 /* Create a socket pair for communicating with ssh. */
240 if (pipe(pin) < 0)
241 fatal("pipe: %s", strerror(errno));
242 if (pipe(pout) < 0)
243 fatal("pipe: %s", strerror(errno));
245 /* Free the reserved descriptors. */
246 close(reserved[0]);
247 close(reserved[1]);
249 signal(SIGTSTP, suspchild);
250 signal(SIGTTIN, suspchild);
251 signal(SIGTTOU, suspchild);
253 /* Fork a child to execute the command on the remote host using ssh. */
254 do_cmd_pid = fork();
255 if (do_cmd_pid == 0) {
256 /* Child. */
257 close(pin[1]);
258 close(pout[0]);
259 dup2(pin[0], 0);
260 dup2(pout[1], 1);
261 close(pin[0]);
262 close(pout[1]);
264 replacearg(&args, 0, "%s", ssh_program);
265 if (remuser != NULL) {
266 addargs(&args, "-l");
267 addargs(&args, "%s", remuser);
269 addargs(&args, "--");
270 addargs(&args, "%s", host);
271 addargs(&args, "%s", cmd);
273 execvp(ssh_program, args.list);
274 perror(ssh_program);
275 exit(1);
276 } else if (do_cmd_pid == -1) {
277 fatal("fork: %s", strerror(errno));
279 /* Parent. Close the other side, and return the local side. */
280 close(pin[0]);
281 *fdout = pin[1];
282 close(pout[1]);
283 *fdin = pout[0];
284 signal(SIGTERM, killchild);
285 signal(SIGINT, killchild);
286 signal(SIGHUP, killchild);
287 return 0;
290 typedef struct {
291 size_t cnt;
292 char *buf;
293 } BUF;
295 BUF *allocbuf(BUF *, int, int);
296 void lostconn(int);
297 int okname(char *);
298 void run_err(const char *,...);
299 void verifydir(char *);
301 struct passwd *pwd;
302 uid_t userid;
303 int errs, remin, remout;
304 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
306 #define CMDNEEDS 64
307 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
309 int response(void);
310 void rsource(char *, struct stat *);
311 void sink(int, char *[]);
312 void source(int, char *[]);
313 void tolocal(int, char *[]);
314 void toremote(char *, int, char *[]);
315 void usage(void);
318 main(int argc, char **argv)
320 int ch, fflag, tflag, status, n;
321 char *targ, **newargv;
322 const char *errstr;
323 extern char *optarg;
324 extern int optind;
326 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
327 sanitise_stdfd();
329 /* Copy argv, because we modify it */
330 newargv = xcalloc(MAX(argc + 1, 1), sizeof(*newargv));
331 for (n = 0; n < argc; n++)
332 newargv[n] = xstrdup(argv[n]);
333 argv = newargv;
335 __progname = ssh_get_progname(argv[0]);
337 memset(&args, '\0', sizeof(args));
338 memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
339 args.list = remote_remote_args.list = NULL;
340 addargs(&args, "%s", ssh_program);
341 addargs(&args, "-x");
342 addargs(&args, "-oForwardAgent=no");
343 addargs(&args, "-oPermitLocalCommand=no");
344 addargs(&args, "-oClearAllForwardings=yes");
346 fflag = tflag = 0;
347 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
348 switch (ch) {
349 /* User-visible flags. */
350 case '1':
351 case '2':
352 case '4':
353 case '6':
354 case 'C':
355 addargs(&args, "-%c", ch);
356 addargs(&remote_remote_args, "-%c", ch);
357 break;
358 case 'o':
359 case 'c':
360 case 'i':
361 case 'F':
362 addargs(&remote_remote_args, "-%c", ch);
363 addargs(&remote_remote_args, "%s", optarg);
364 addargs(&args, "-%c", ch);
365 addargs(&args, "%s", optarg);
366 break;
367 case 'P':
368 addargs(&remote_remote_args, "-p");
369 addargs(&remote_remote_args, "%s", optarg);
370 addargs(&args, "-p");
371 addargs(&args, "%s", optarg);
372 break;
373 case 'B':
374 addargs(&remote_remote_args, "-oBatchmode=yes");
375 addargs(&args, "-oBatchmode=yes");
376 break;
377 case 'l':
378 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
379 &errstr);
380 if (errstr != NULL)
381 usage();
382 limit_kbps *= 1024; /* kbps */
383 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
384 break;
385 case 'p':
386 pflag = 1;
387 break;
388 case 'r':
389 iamrecursive = 1;
390 break;
391 case 'S':
392 ssh_program = xstrdup(optarg);
393 break;
394 case 'v':
395 addargs(&args, "-v");
396 addargs(&remote_remote_args, "-v");
397 verbose_mode = 1;
398 break;
399 case 'q':
400 addargs(&args, "-q");
401 addargs(&remote_remote_args, "-q");
402 showprogress = 0;
403 break;
405 /* Server options. */
406 case 'd':
407 targetshouldbedirectory = 1;
408 break;
409 case 'f': /* "from" */
410 iamremote = 1;
411 fflag = 1;
412 break;
413 case 't': /* "to" */
414 iamremote = 1;
415 tflag = 1;
416 #ifdef HAVE_CYGWIN
417 setmode(0, O_BINARY);
418 #endif
419 break;
420 default:
421 usage();
423 argc -= optind;
424 argv += optind;
426 if ((pwd = getpwuid(userid = getuid())) == NULL)
427 fatal("unknown user %u", (u_int) userid);
429 if (!isatty(STDOUT_FILENO))
430 showprogress = 0;
432 remin = STDIN_FILENO;
433 remout = STDOUT_FILENO;
435 if (fflag) {
436 /* Follow "protocol", send data. */
437 (void) response();
438 source(argc, argv);
439 exit(errs != 0);
441 if (tflag) {
442 /* Receive data. */
443 sink(argc, argv);
444 exit(errs != 0);
446 if (argc < 2)
447 usage();
448 if (argc > 2)
449 targetshouldbedirectory = 1;
451 remin = remout = -1;
452 do_cmd_pid = -1;
453 /* Command to be executed on remote system using "ssh". */
454 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
455 verbose_mode ? " -v" : "",
456 iamrecursive ? " -r" : "", pflag ? " -p" : "",
457 targetshouldbedirectory ? " -d" : "");
459 (void) signal(SIGPIPE, lostconn);
461 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
462 toremote(targ, argc, argv);
463 else {
464 if (targetshouldbedirectory)
465 verifydir(argv[argc - 1]);
466 tolocal(argc, argv); /* Dest is local host. */
469 * Finally check the exit status of the ssh process, if one was forked
470 * and no error has occurred yet
472 if (do_cmd_pid != -1 && errs == 0) {
473 if (remin != -1)
474 (void) close(remin);
475 if (remout != -1)
476 (void) close(remout);
477 if (waitpid(do_cmd_pid, &status, 0) == -1)
478 errs = 1;
479 else {
480 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
481 errs = 1;
484 exit(errs != 0);
487 /* Callback from atomicio6 to update progress meter and limit bandwidth */
488 static int
489 scpio(void *_cnt, size_t s)
491 off_t *cnt = (off_t *)_cnt;
493 *cnt += s;
494 if (limit_kbps > 0)
495 bandwidth_limit(&bwlimit, s);
496 return 0;
499 void
500 toremote(char *targ, int argc, char **argv)
502 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
503 arglist alist;
504 int i;
505 u_int j;
507 memset(&alist, '\0', sizeof(alist));
508 alist.list = NULL;
510 *targ++ = 0;
511 if (*targ == 0)
512 targ = ".";
514 arg = xstrdup(argv[argc - 1]);
515 if ((thost = strrchr(arg, '@'))) {
516 /* user@host */
517 *thost++ = 0;
518 tuser = arg;
519 if (*tuser == '\0')
520 tuser = NULL;
521 } else {
522 thost = arg;
523 tuser = NULL;
526 if (tuser != NULL && !okname(tuser)) {
527 xfree(arg);
528 return;
531 for (i = 0; i < argc - 1; i++) {
532 src = colon(argv[i]);
533 if (src) { /* remote to remote */
534 freeargs(&alist);
535 addargs(&alist, "%s", ssh_program);
536 addargs(&alist, "-x");
537 addargs(&alist, "-oClearAllForwardings=yes");
538 addargs(&alist, "-n");
539 for (j = 0; j < remote_remote_args.num; j++) {
540 addargs(&alist, "%s",
541 remote_remote_args.list[j]);
543 *src++ = 0;
544 if (*src == 0)
545 src = ".";
546 host = strrchr(argv[i], '@');
548 if (host) {
549 *host++ = 0;
550 host = cleanhostname(host);
551 suser = argv[i];
552 if (*suser == '\0')
553 suser = pwd->pw_name;
554 else if (!okname(suser))
555 continue;
556 addargs(&alist, "-l");
557 addargs(&alist, "%s", suser);
558 } else {
559 host = cleanhostname(argv[i]);
561 addargs(&alist, "--");
562 addargs(&alist, "%s", host);
563 addargs(&alist, "%s", cmd);
564 addargs(&alist, "%s", src);
565 addargs(&alist, "%s%s%s:%s",
566 tuser ? tuser : "", tuser ? "@" : "",
567 thost, targ);
568 if (do_local_cmd(&alist) != 0)
569 errs = 1;
570 } else { /* local to remote */
571 if (remin == -1) {
572 xasprintf(&bp, "%s -t -- %s", cmd, targ);
573 host = cleanhostname(thost);
574 if (do_cmd(host, tuser, bp, &remin,
575 &remout) < 0)
576 exit(1);
577 if (response() < 0)
578 exit(1);
579 (void) xfree(bp);
581 source(1, argv + i);
584 xfree(arg);
587 void
588 tolocal(int argc, char **argv)
590 char *bp, *host, *src, *suser;
591 arglist alist;
592 int i;
594 memset(&alist, '\0', sizeof(alist));
595 alist.list = NULL;
597 for (i = 0; i < argc - 1; i++) {
598 if (!(src = colon(argv[i]))) { /* Local to local. */
599 freeargs(&alist);
600 addargs(&alist, "%s", _PATH_CP);
601 if (iamrecursive)
602 addargs(&alist, "-r");
603 if (pflag)
604 addargs(&alist, "-p");
605 addargs(&alist, "--");
606 addargs(&alist, "%s", argv[i]);
607 addargs(&alist, "%s", argv[argc-1]);
608 if (do_local_cmd(&alist))
609 ++errs;
610 continue;
612 *src++ = 0;
613 if (*src == 0)
614 src = ".";
615 if ((host = strrchr(argv[i], '@')) == NULL) {
616 host = argv[i];
617 suser = NULL;
618 } else {
619 *host++ = 0;
620 suser = argv[i];
621 if (*suser == '\0')
622 suser = pwd->pw_name;
624 host = cleanhostname(host);
625 xasprintf(&bp, "%s -f -- %s", cmd, src);
626 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
627 (void) xfree(bp);
628 ++errs;
629 continue;
631 xfree(bp);
632 sink(1, argv + argc - 1);
633 (void) close(remin);
634 remin = remout = -1;
638 void
639 source(int argc, char **argv)
641 struct stat stb;
642 static BUF buffer;
643 BUF *bp;
644 off_t i, statbytes;
645 size_t amt;
646 int fd = -1, haderr, indx;
647 char *last, *name, buf[2048], encname[MAXPATHLEN];
648 int len;
650 for (indx = 0; indx < argc; ++indx) {
651 name = argv[indx];
652 statbytes = 0;
653 len = strlen(name);
654 while (len > 1 && name[len-1] == '/')
655 name[--len] = '\0';
656 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
657 goto syserr;
658 if (strchr(name, '\n') != NULL) {
659 strnvis(encname, name, sizeof(encname), VIS_NL);
660 name = encname;
662 if (fstat(fd, &stb) < 0) {
663 syserr: run_err("%s: %s", name, strerror(errno));
664 goto next;
666 if (stb.st_size < 0) {
667 run_err("%s: %s", name, "Negative file size");
668 goto next;
670 unset_nonblock(fd);
671 switch (stb.st_mode & S_IFMT) {
672 case S_IFREG:
673 break;
674 case S_IFDIR:
675 if (iamrecursive) {
676 rsource(name, &stb);
677 goto next;
679 /* FALLTHROUGH */
680 default:
681 run_err("%s: not a regular file", name);
682 goto next;
684 if ((last = strrchr(name, '/')) == NULL)
685 last = name;
686 else
687 ++last;
688 curfile = last;
689 if (pflag) {
691 * Make it compatible with possible future
692 * versions expecting microseconds.
694 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
695 (u_long) (stb.st_mtime < 0 ? 0 : stb.st_mtime),
696 (u_long) (stb.st_atime < 0 ? 0 : stb.st_atime));
697 if (verbose_mode) {
698 fprintf(stderr, "File mtime %ld atime %ld\n",
699 (long)stb.st_mtime, (long)stb.st_atime);
700 fprintf(stderr, "Sending file timestamps: %s",
701 buf);
703 (void) atomicio(vwrite, remout, buf, strlen(buf));
704 if (response() < 0)
705 goto next;
707 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
708 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
709 (u_int) (stb.st_mode & FILEMODEMASK),
710 (long long)stb.st_size, last);
711 if (verbose_mode) {
712 fprintf(stderr, "Sending file modes: %s", buf);
714 (void) atomicio(vwrite, remout, buf, strlen(buf));
715 if (response() < 0)
716 goto next;
717 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
718 next: if (fd != -1) {
719 (void) close(fd);
720 fd = -1;
722 continue;
724 if (showprogress)
725 start_progress_meter(curfile, stb.st_size, &statbytes);
726 set_nonblock(remout);
727 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
728 amt = bp->cnt;
729 if (i + (off_t)amt > stb.st_size)
730 amt = stb.st_size - i;
731 if (!haderr) {
732 if (atomicio(read, fd, bp->buf, amt) != amt)
733 haderr = errno;
735 /* Keep writing after error to retain sync */
736 if (haderr) {
737 (void)atomicio(vwrite, remout, bp->buf, amt);
738 continue;
740 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
741 &statbytes) != amt)
742 haderr = errno;
744 unset_nonblock(remout);
745 if (showprogress)
746 stop_progress_meter();
748 if (fd != -1) {
749 if (close(fd) < 0 && !haderr)
750 haderr = errno;
751 fd = -1;
753 if (!haderr)
754 (void) atomicio(vwrite, remout, "", 1);
755 else
756 run_err("%s: %s", name, strerror(haderr));
757 (void) response();
761 void
762 rsource(char *name, struct stat *statp)
764 DIR *dirp;
765 struct dirent *dp;
766 char *last, *vect[1], path[1100];
768 if (!(dirp = opendir(name))) {
769 run_err("%s: %s", name, strerror(errno));
770 return;
772 last = strrchr(name, '/');
773 if (last == 0)
774 last = name;
775 else
776 last++;
777 if (pflag) {
778 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
779 (u_long) statp->st_mtime,
780 (u_long) statp->st_atime);
781 (void) atomicio(vwrite, remout, path, strlen(path));
782 if (response() < 0) {
783 closedir(dirp);
784 return;
787 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
788 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
789 if (verbose_mode)
790 fprintf(stderr, "Entering directory: %s", path);
791 (void) atomicio(vwrite, remout, path, strlen(path));
792 if (response() < 0) {
793 closedir(dirp);
794 return;
796 while ((dp = readdir(dirp)) != NULL) {
797 if (dp->d_ino == 0)
798 continue;
799 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
800 continue;
801 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
802 run_err("%s/%s: name too long", name, dp->d_name);
803 continue;
805 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
806 vect[0] = path;
807 source(1, vect);
809 (void) closedir(dirp);
810 (void) atomicio(vwrite, remout, "E\n", 2);
811 (void) response();
814 void
815 sink(int argc, char **argv)
817 static BUF buffer;
818 struct stat stb;
819 enum {
820 YES, NO, DISPLAYED
821 } wrerr;
822 BUF *bp;
823 off_t i;
824 size_t j, count;
825 int amt, exists, first, ofd;
826 mode_t mode, omode, mask;
827 off_t size, statbytes;
828 int setimes, targisdir, wrerrno = 0;
829 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
830 struct timeval tv[2];
832 #define atime tv[0]
833 #define mtime tv[1]
834 #define SCREWUP(str) { why = str; goto screwup; }
836 setimes = targisdir = 0;
837 mask = umask(0);
838 if (!pflag)
839 (void) umask(mask);
840 if (argc != 1) {
841 run_err("ambiguous target");
842 exit(1);
844 targ = *argv;
845 if (targetshouldbedirectory)
846 verifydir(targ);
848 (void) atomicio(vwrite, remout, "", 1);
849 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
850 targisdir = 1;
851 for (first = 1;; first = 0) {
852 cp = buf;
853 if (atomicio(read, remin, cp, 1) != 1)
854 return;
855 if (*cp++ == '\n')
856 SCREWUP("unexpected <newline>");
857 do {
858 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
859 SCREWUP("lost connection");
860 *cp++ = ch;
861 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
862 *cp = 0;
863 if (verbose_mode)
864 fprintf(stderr, "Sink: %s", buf);
866 if (buf[0] == '\01' || buf[0] == '\02') {
867 if (iamremote == 0)
868 (void) atomicio(vwrite, STDERR_FILENO,
869 buf + 1, strlen(buf + 1));
870 if (buf[0] == '\02')
871 exit(1);
872 ++errs;
873 continue;
875 if (buf[0] == 'E') {
876 (void) atomicio(vwrite, remout, "", 1);
877 return;
879 if (ch == '\n')
880 *--cp = 0;
882 cp = buf;
883 if (*cp == 'T') {
884 setimes++;
885 cp++;
886 mtime.tv_sec = strtol(cp, &cp, 10);
887 if (!cp || *cp++ != ' ')
888 SCREWUP("mtime.sec not delimited");
889 mtime.tv_usec = strtol(cp, &cp, 10);
890 if (!cp || *cp++ != ' ')
891 SCREWUP("mtime.usec not delimited");
892 atime.tv_sec = strtol(cp, &cp, 10);
893 if (!cp || *cp++ != ' ')
894 SCREWUP("atime.sec not delimited");
895 atime.tv_usec = strtol(cp, &cp, 10);
896 if (!cp || *cp++ != '\0')
897 SCREWUP("atime.usec not delimited");
898 (void) atomicio(vwrite, remout, "", 1);
899 continue;
901 if (*cp != 'C' && *cp != 'D') {
903 * Check for the case "rcp remote:foo\* local:bar".
904 * In this case, the line "No match." can be returned
905 * by the shell before the rcp command on the remote is
906 * executed so the ^Aerror_message convention isn't
907 * followed.
909 if (first) {
910 run_err("%s", cp);
911 exit(1);
913 SCREWUP("expected control record");
915 mode = 0;
916 for (++cp; cp < buf + 5; cp++) {
917 if (*cp < '0' || *cp > '7')
918 SCREWUP("bad mode");
919 mode = (mode << 3) | (*cp - '0');
921 if (*cp++ != ' ')
922 SCREWUP("mode not delimited");
924 for (size = 0; isdigit(*cp);)
925 size = size * 10 + (*cp++ - '0');
926 if (*cp++ != ' ')
927 SCREWUP("size not delimited");
928 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
929 run_err("error: unexpected filename: %s", cp);
930 exit(1);
932 if (targisdir) {
933 static char *namebuf;
934 static size_t cursize;
935 size_t need;
937 need = strlen(targ) + strlen(cp) + 250;
938 if (need > cursize) {
939 if (namebuf)
940 xfree(namebuf);
941 namebuf = xmalloc(need);
942 cursize = need;
944 (void) snprintf(namebuf, need, "%s%s%s", targ,
945 strcmp(targ, "/") ? "/" : "", cp);
946 np = namebuf;
947 } else
948 np = targ;
949 curfile = cp;
950 exists = stat(np, &stb) == 0;
951 if (buf[0] == 'D') {
952 int mod_flag = pflag;
953 if (!iamrecursive)
954 SCREWUP("received directory without -r");
955 if (exists) {
956 if (!S_ISDIR(stb.st_mode)) {
957 errno = ENOTDIR;
958 goto bad;
960 if (pflag)
961 (void) chmod(np, mode);
962 } else {
963 /* Handle copying from a read-only
964 directory */
965 mod_flag = 1;
966 if (mkdir(np, mode | S_IRWXU) < 0)
967 goto bad;
969 vect[0] = xstrdup(np);
970 sink(1, vect);
971 if (setimes) {
972 setimes = 0;
973 if (utimes(vect[0], tv) < 0)
974 run_err("%s: set times: %s",
975 vect[0], strerror(errno));
977 if (mod_flag)
978 (void) chmod(vect[0], mode);
979 if (vect[0])
980 xfree(vect[0]);
981 continue;
983 omode = mode;
984 mode |= S_IWRITE;
985 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
986 bad: run_err("%s: %s", np, strerror(errno));
987 continue;
989 (void) atomicio(vwrite, remout, "", 1);
990 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
991 (void) close(ofd);
992 continue;
994 cp = bp->buf;
995 wrerr = NO;
997 statbytes = 0;
998 if (showprogress)
999 start_progress_meter(curfile, size, &statbytes);
1000 set_nonblock(remin);
1001 for (count = i = 0; i < size; i += bp->cnt) {
1002 amt = bp->cnt;
1003 if (i + amt > size)
1004 amt = size - i;
1005 count += amt;
1006 do {
1007 j = atomicio6(read, remin, cp, amt,
1008 scpio, &statbytes);
1009 if (j == 0) {
1010 run_err("%s", j != EPIPE ?
1011 strerror(errno) :
1012 "dropped connection");
1013 exit(1);
1015 amt -= j;
1016 cp += j;
1017 } while (amt > 0);
1019 if (count == bp->cnt) {
1020 /* Keep reading so we stay sync'd up. */
1021 if (wrerr == NO) {
1022 if (atomicio(vwrite, ofd, bp->buf,
1023 count) != count) {
1024 wrerr = YES;
1025 wrerrno = errno;
1028 count = 0;
1029 cp = bp->buf;
1032 unset_nonblock(remin);
1033 if (showprogress)
1034 stop_progress_meter();
1035 if (count != 0 && wrerr == NO &&
1036 atomicio(vwrite, ofd, bp->buf, count) != count) {
1037 wrerr = YES;
1038 wrerrno = errno;
1040 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1041 ftruncate(ofd, size) != 0) {
1042 run_err("%s: truncate: %s", np, strerror(errno));
1043 wrerr = DISPLAYED;
1045 if (pflag) {
1046 if (exists || omode != mode)
1047 #ifdef HAVE_FCHMOD
1048 if (fchmod(ofd, omode)) {
1049 #else /* HAVE_FCHMOD */
1050 if (chmod(np, omode)) {
1051 #endif /* HAVE_FCHMOD */
1052 run_err("%s: set mode: %s",
1053 np, strerror(errno));
1054 wrerr = DISPLAYED;
1056 } else {
1057 if (!exists && omode != mode)
1058 #ifdef HAVE_FCHMOD
1059 if (fchmod(ofd, omode & ~mask)) {
1060 #else /* HAVE_FCHMOD */
1061 if (chmod(np, omode & ~mask)) {
1062 #endif /* HAVE_FCHMOD */
1063 run_err("%s: set mode: %s",
1064 np, strerror(errno));
1065 wrerr = DISPLAYED;
1068 if (close(ofd) == -1) {
1069 wrerr = YES;
1070 wrerrno = errno;
1072 (void) response();
1073 if (setimes && wrerr == NO) {
1074 setimes = 0;
1075 if (utimes(np, tv) < 0) {
1076 run_err("%s: set times: %s",
1077 np, strerror(errno));
1078 wrerr = DISPLAYED;
1081 switch (wrerr) {
1082 case YES:
1083 run_err("%s: %s", np, strerror(wrerrno));
1084 break;
1085 case NO:
1086 (void) atomicio(vwrite, remout, "", 1);
1087 break;
1088 case DISPLAYED:
1089 break;
1092 screwup:
1093 run_err("protocol error: %s", why);
1094 exit(1);
1098 response(void)
1100 char ch, *cp, resp, rbuf[2048];
1102 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1103 lostconn(0);
1105 cp = rbuf;
1106 switch (resp) {
1107 case 0: /* ok */
1108 return (0);
1109 default:
1110 *cp++ = resp;
1111 /* FALLTHROUGH */
1112 case 1: /* error, followed by error msg */
1113 case 2: /* fatal error, "" */
1114 do {
1115 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1116 lostconn(0);
1117 *cp++ = ch;
1118 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1120 if (!iamremote)
1121 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1122 ++errs;
1123 if (resp == 1)
1124 return (-1);
1125 exit(1);
1127 /* NOTREACHED */
1130 void
1131 usage(void)
1133 (void) fprintf(stderr,
1134 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1135 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1136 " [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1137 exit(1);
1140 void
1141 run_err(const char *fmt,...)
1143 static FILE *fp;
1144 va_list ap;
1146 ++errs;
1147 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1148 (void) fprintf(fp, "%c", 0x01);
1149 (void) fprintf(fp, "scp: ");
1150 va_start(ap, fmt);
1151 (void) vfprintf(fp, fmt, ap);
1152 va_end(ap);
1153 (void) fprintf(fp, "\n");
1154 (void) fflush(fp);
1157 if (!iamremote) {
1158 va_start(ap, fmt);
1159 vfprintf(stderr, fmt, ap);
1160 va_end(ap);
1161 fprintf(stderr, "\n");
1165 void
1166 verifydir(char *cp)
1168 struct stat stb;
1170 if (!stat(cp, &stb)) {
1171 if (S_ISDIR(stb.st_mode))
1172 return;
1173 errno = ENOTDIR;
1175 run_err("%s: %s", cp, strerror(errno));
1176 killchild(0);
1180 okname(char *cp0)
1182 int c;
1183 char *cp;
1185 cp = cp0;
1186 do {
1187 c = (int)*cp;
1188 if (c & 0200)
1189 goto bad;
1190 if (!isalpha(c) && !isdigit(c)) {
1191 switch (c) {
1192 case '\'':
1193 case '"':
1194 case '`':
1195 case ' ':
1196 case '#':
1197 goto bad;
1198 default:
1199 break;
1202 } while (*++cp);
1203 return (1);
1205 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1206 return (0);
1209 BUF *
1210 allocbuf(BUF *bp, int fd, int blksize)
1212 size_t size;
1213 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1214 struct stat stb;
1216 if (fstat(fd, &stb) < 0) {
1217 run_err("fstat: %s", strerror(errno));
1218 return (0);
1220 size = roundup(stb.st_blksize, blksize);
1221 if (size == 0)
1222 size = blksize;
1223 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1224 size = blksize;
1225 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1226 if (bp->cnt >= size)
1227 return (bp);
1228 if (bp->buf == NULL)
1229 bp->buf = xmalloc(size);
1230 else
1231 bp->buf = xrealloc(bp->buf, 1, size);
1232 memset(bp->buf, 0, size);
1233 bp->cnt = size;
1234 return (bp);
1237 void
1238 lostconn(int signo)
1240 if (!iamremote)
1241 write(STDERR_FILENO, "lost connection\n", 16);
1242 if (signo)
1243 _exit(1);
1244 else
1245 exit(1);