1 /* $OpenBSD: scp.c,v 1.195 2018/02/10 06:15:12 djm Exp $ */
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
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.
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
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
76 #include <sys/types.h>
77 #ifdef HAVE_SYS_STAT_H
78 # include <sys/stat.h>
83 # ifdef HAVE_SYS_POLL_H
84 # include <sys/poll.h>
87 #ifdef HAVE_SYS_TIME_H
88 # include <sys/time.h>
110 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
116 #include "atomicio.h"
117 #include "pathnames.h"
120 #include "progressmeter.h"
123 extern char *__progname;
125 #define COPY_BUFLEN 16384
127 int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout);
128 int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout);
130 /* Struct for addargs */
132 arglist remote_remote_args;
134 /* Bandwidth limit */
135 long long limit_kbps = 0;
136 struct bwlimit bwlimit;
138 /* Name of current file being transferred. */
141 /* This is set to non-zero to enable verbose mode. */
142 int verbose_mode = 0;
144 /* This is set to zero if the progressmeter is not desired. */
145 int showprogress = 1;
148 * This is set to non-zero if remote-remote copy should be piped
149 * through this process.
151 int throughlocal = 0;
153 /* Non-standard port to use for the ssh connection or -1. */
156 /* This is the program to execute for the secured connection. ("ssh" or -S) */
157 char *ssh_program = _PATH_SSH_PROGRAM;
159 /* This is used to store the pid of ssh_program */
160 pid_t do_cmd_pid = -1;
165 if (do_cmd_pid > 1) {
166 kill(do_cmd_pid, signo ? signo : SIGTERM);
167 waitpid(do_cmd_pid, NULL, 0);
180 if (do_cmd_pid > 1) {
181 kill(do_cmd_pid, signo);
182 while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
185 kill(getpid(), SIGSTOP);
190 do_local_cmd(arglist *a)
197 fatal("do_local_cmd: no arguments");
200 fprintf(stderr, "Executing:");
201 for (i = 0; i < a->num; i++)
202 fmprintf(stderr, " %s", a->list[i]);
203 fprintf(stderr, "\n");
205 if ((pid = fork()) == -1)
206 fatal("do_local_cmd: fork: %s", strerror(errno));
209 execvp(a->list[0], a->list);
215 signal(SIGTERM, killchild);
216 signal(SIGINT, killchild);
217 signal(SIGHUP, killchild);
219 while (waitpid(pid, &status, 0) == -1)
221 fatal("do_local_cmd: waitpid: %s", strerror(errno));
225 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
232 * This function executes the given command as the specified user on the
233 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
234 * assigns the input and output file descriptors on success.
238 do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout)
240 int pin[2], pout[2], reserved[2];
244 "Executing: program %s host %s, user %s, command %s\n",
246 remuser ? remuser : "(unspecified)", cmd);
252 * Reserve two descriptors so that the real pipes won't get
253 * descriptors 0 and 1 because that will screw up dup2 below.
255 if (pipe(reserved) < 0)
256 fatal("pipe: %s", strerror(errno));
258 /* Create a socket pair for communicating with ssh. */
260 fatal("pipe: %s", strerror(errno));
262 fatal("pipe: %s", strerror(errno));
264 /* Free the reserved descriptors. */
268 signal(SIGTSTP, suspchild);
269 signal(SIGTTIN, suspchild);
270 signal(SIGTTOU, suspchild);
272 /* Fork a child to execute the command on the remote host using ssh. */
274 if (do_cmd_pid == 0) {
283 replacearg(&args, 0, "%s", ssh_program);
285 addargs(&args, "-p");
286 addargs(&args, "%d", port);
288 if (remuser != NULL) {
289 addargs(&args, "-l");
290 addargs(&args, "%s", remuser);
292 addargs(&args, "--");
293 addargs(&args, "%s", host);
294 addargs(&args, "%s", cmd);
296 execvp(ssh_program, args.list);
299 } else if (do_cmd_pid == -1) {
300 fatal("fork: %s", strerror(errno));
302 /* Parent. Close the other side, and return the local side. */
307 signal(SIGTERM, killchild);
308 signal(SIGINT, killchild);
309 signal(SIGHUP, killchild);
314 * This functions executes a command simlar to do_cmd(), but expects the
315 * input and output descriptors to be setup by a previous call to do_cmd().
316 * This way the input and output of two commands can be connected.
319 do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout)
326 "Executing: 2nd program %s host %s, user %s, command %s\n",
328 remuser ? remuser : "(unspecified)", cmd);
333 /* Fork a child to execute the command on the remote host using ssh. */
339 replacearg(&args, 0, "%s", ssh_program);
341 addargs(&args, "-p");
342 addargs(&args, "%d", port);
344 if (remuser != NULL) {
345 addargs(&args, "-l");
346 addargs(&args, "%s", remuser);
348 addargs(&args, "--");
349 addargs(&args, "%s", host);
350 addargs(&args, "%s", cmd);
352 execvp(ssh_program, args.list);
355 } else if (pid == -1) {
356 fatal("fork: %s", strerror(errno));
358 while (waitpid(pid, &status, 0) == -1)
360 fatal("do_cmd2: waitpid: %s", strerror(errno));
369 BUF *allocbuf(BUF *, int, int);
372 void run_err(const char *,...);
373 void verifydir(char *);
377 int errs, remin, remout;
378 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
381 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
384 void rsource(char *, struct stat *);
385 void sink(int, char *[]);
386 void source(int, char *[]);
387 void tolocal(int, char *[]);
388 void toremote(int, char *[]);
392 main(int argc, char **argv)
394 int ch, fflag, tflag, status, n;
400 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
405 /* Copy argv, because we modify it */
406 newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
407 for (n = 0; n < argc; n++)
408 newargv[n] = xstrdup(argv[n]);
411 __progname = ssh_get_progname(argv[0]);
413 memset(&args, '\0', sizeof(args));
414 memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
415 args.list = remote_remote_args.list = NULL;
416 addargs(&args, "%s", ssh_program);
417 addargs(&args, "-x");
418 addargs(&args, "-oForwardAgent=no");
419 addargs(&args, "-oPermitLocalCommand=no");
420 addargs(&args, "-oClearAllForwardings=yes");
421 addargs(&args, "-oRemoteCommand=none");
422 addargs(&args, "-oRequestTTY=no");
425 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
427 /* User-visible flags. */
429 fatal("SSH protocol v.1 is no longer supported");
437 addargs(&args, "-%c", ch);
438 addargs(&remote_remote_args, "-%c", ch);
447 addargs(&remote_remote_args, "-%c", ch);
448 addargs(&remote_remote_args, "%s", optarg);
449 addargs(&args, "-%c", ch);
450 addargs(&args, "%s", optarg);
453 sshport = a2port(optarg);
455 fatal("bad port \"%s\"\n", optarg);
458 addargs(&remote_remote_args, "-oBatchmode=yes");
459 addargs(&args, "-oBatchmode=yes");
462 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
466 limit_kbps *= 1024; /* kbps */
467 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
476 ssh_program = xstrdup(optarg);
479 addargs(&args, "-v");
480 addargs(&remote_remote_args, "-v");
484 addargs(&args, "-q");
485 addargs(&remote_remote_args, "-q");
489 /* Server options. */
491 targetshouldbedirectory = 1;
493 case 'f': /* "from" */
501 setmode(0, O_BINARY);
510 if ((pwd = getpwuid(userid = getuid())) == NULL)
511 fatal("unknown user %u", (u_int) userid);
513 if (!isatty(STDOUT_FILENO))
517 /* Cannot pledge: -p allows setuid/setgid files... */
519 if (pledge("stdio rpath wpath cpath fattr tty proc exec",
526 remin = STDIN_FILENO;
527 remout = STDOUT_FILENO;
530 /* Follow "protocol", send data. */
543 targetshouldbedirectory = 1;
547 /* Command to be executed on remote system using "ssh". */
548 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
549 verbose_mode ? " -v" : "",
550 iamrecursive ? " -r" : "", pflag ? " -p" : "",
551 targetshouldbedirectory ? " -d" : "");
553 (void) signal(SIGPIPE, lostconn);
555 if (colon(argv[argc - 1])) /* Dest is remote host. */
556 toremote(argc, argv);
558 if (targetshouldbedirectory)
559 verifydir(argv[argc - 1]);
560 tolocal(argc, argv); /* Dest is local host. */
563 * Finally check the exit status of the ssh process, if one was forked
564 * and no error has occurred yet
566 if (do_cmd_pid != -1 && errs == 0) {
570 (void) close(remout);
571 if (waitpid(do_cmd_pid, &status, 0) == -1)
574 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
581 /* Callback from atomicio6 to update progress meter and limit bandwidth */
583 scpio(void *_cnt, size_t s)
585 off_t *cnt = (off_t *)_cnt;
589 bandwidth_limit(&bwlimit, s);
594 do_times(int fd, int verb, const struct stat *sb)
596 /* strlen(2^64) == 20; strlen(10^6) == 7 */
597 char buf[(20 + 7 + 2) * 2 + 2];
599 (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
600 (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
601 (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
603 fprintf(stderr, "File mtime %lld atime %lld\n",
604 (long long)sb->st_mtime, (long long)sb->st_atime);
605 fprintf(stderr, "Sending file timestamps: %s", buf);
607 (void) atomicio(vwrite, fd, buf, strlen(buf));
612 parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
617 r = parse_uri("scp", uri, userp, hostp, portp, pathp);
618 if (r == 0 && *pathp == NULL)
619 *pathp = xstrdup(".");
624 toremote(int argc, char **argv)
626 char *suser = NULL, *host = NULL, *src = NULL;
627 char *bp, *tuser, *thost, *targ;
628 int sport = -1, tport = -1;
633 memset(&alist, '\0', sizeof(alist));
637 r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
639 fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
644 if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
646 fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
651 if (tuser != NULL && !okname(tuser)) {
656 /* Parse source files */
657 for (i = 0; i < argc - 1; i++) {
661 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
663 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
668 parse_user_host_path(argv[i], &suser, &host, &src);
670 if (suser != NULL && !okname(suser)) {
674 if (host && throughlocal) { /* extended remote to remote */
675 xasprintf(&bp, "%s -f %s%s", cmd,
676 *src == '-' ? "-- " : "", src);
677 if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
680 xasprintf(&bp, "%s -t %s%s", cmd,
681 *targ == '-' ? "-- " : "", targ);
682 if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
686 (void) close(remout);
688 } else if (host) { /* standard remote to remote */
689 if (tport != -1 && tport != SSH_DEFAULT_PORT) {
690 /* This would require the remote support URIs */
691 fatal("target port not supported with two "
692 "remote hosts without the -3 option");
696 addargs(&alist, "%s", ssh_program);
697 addargs(&alist, "-x");
698 addargs(&alist, "-oClearAllForwardings=yes");
699 addargs(&alist, "-n");
700 for (j = 0; j < remote_remote_args.num; j++) {
701 addargs(&alist, "%s",
702 remote_remote_args.list[j]);
706 addargs(&alist, "-p");
707 addargs(&alist, "%d", sport);
710 addargs(&alist, "-l");
711 addargs(&alist, "%s", suser);
713 addargs(&alist, "--");
714 addargs(&alist, "%s", host);
715 addargs(&alist, "%s", cmd);
716 addargs(&alist, "%s", src);
717 addargs(&alist, "%s%s%s:%s",
718 tuser ? tuser : "", tuser ? "@" : "",
720 if (do_local_cmd(&alist) != 0)
722 } else { /* local to remote */
724 xasprintf(&bp, "%s -t %s%s", cmd,
725 *targ == '-' ? "-- " : "", targ);
726 if (do_cmd(thost, tuser, tport, bp, &remin,
746 tolocal(int argc, char **argv)
748 char *bp, *host = NULL, *src = NULL, *suser = NULL;
750 int i, r, sport = -1;
752 memset(&alist, '\0', sizeof(alist));
755 for (i = 0; i < argc - 1; i++) {
759 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
761 fmprintf(stderr, "%s: invalid uri\n", argv[i]);
766 parse_user_host_path(argv[i], &suser, &host, &src);
767 if (suser != NULL && !okname(suser)) {
771 if (!host) { /* Local to local. */
773 addargs(&alist, "%s", _PATH_CP);
775 addargs(&alist, "-r");
777 addargs(&alist, "-p");
778 addargs(&alist, "--");
779 addargs(&alist, "%s", argv[i]);
780 addargs(&alist, "%s", argv[argc-1]);
781 if (do_local_cmd(&alist))
785 /* Remote to local. */
786 xasprintf(&bp, "%s -f %s%s",
787 cmd, *src == '-' ? "-- " : "", src);
788 if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
794 sink(1, argv + argc - 1);
804 source(int argc, char **argv)
811 int fd = -1, haderr, indx;
812 char *last, *name, buf[2048], encname[PATH_MAX];
815 for (indx = 0; indx < argc; ++indx) {
819 while (len > 1 && name[len-1] == '/')
821 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
823 if (strchr(name, '\n') != NULL) {
824 strnvis(encname, name, sizeof(encname), VIS_NL);
827 if (fstat(fd, &stb) < 0) {
828 syserr: run_err("%s: %s", name, strerror(errno));
831 if (stb.st_size < 0) {
832 run_err("%s: %s", name, "Negative file size");
836 switch (stb.st_mode & S_IFMT) {
846 run_err("%s: not a regular file", name);
849 if ((last = strrchr(name, '/')) == NULL)
855 if (do_times(remout, verbose_mode, &stb) < 0)
858 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
859 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
860 (u_int) (stb.st_mode & FILEMODEMASK),
861 (long long)stb.st_size, last);
863 fmprintf(stderr, "Sending file modes: %s", buf);
864 (void) atomicio(vwrite, remout, buf, strlen(buf));
867 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
868 next: if (fd != -1) {
875 start_progress_meter(curfile, stb.st_size, &statbytes);
876 set_nonblock(remout);
877 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
879 if (i + (off_t)amt > stb.st_size)
880 amt = stb.st_size - i;
882 if ((nr = atomicio(read, fd,
883 bp->buf, amt)) != amt) {
885 memset(bp->buf + nr, 0, amt - nr);
888 /* Keep writing after error to retain sync */
890 (void)atomicio(vwrite, remout, bp->buf, amt);
891 memset(bp->buf, 0, amt);
894 if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
898 unset_nonblock(remout);
901 if (close(fd) < 0 && !haderr)
906 (void) atomicio(vwrite, remout, "", 1);
908 run_err("%s: %s", name, strerror(haderr));
911 stop_progress_meter();
916 rsource(char *name, struct stat *statp)
920 char *last, *vect[1], path[PATH_MAX];
922 if (!(dirp = opendir(name))) {
923 run_err("%s: %s", name, strerror(errno));
926 last = strrchr(name, '/');
932 if (do_times(remout, verbose_mode, statp) < 0) {
937 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
938 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
940 fmprintf(stderr, "Entering directory: %s", path);
941 (void) atomicio(vwrite, remout, path, strlen(path));
942 if (response() < 0) {
946 while ((dp = readdir(dirp)) != NULL) {
949 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
951 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
952 run_err("%s/%s: name too long", name, dp->d_name);
955 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
959 (void) closedir(dirp);
960 (void) atomicio(vwrite, remout, "E\n", 2);
964 #define TYPE_OVERFLOW(type, val) \
965 ((sizeof(type) == 4 && (val) > INT32_MAX) || \
966 (sizeof(type) == 8 && (val) > INT64_MAX) || \
967 (sizeof(type) != 4 && sizeof(type) != 8))
970 sink(int argc, char **argv)
980 int amt, exists, first, ofd;
981 mode_t mode, omode, mask;
982 off_t size, statbytes;
983 unsigned long long ull;
984 int setimes, targisdir, wrerrno = 0;
985 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
986 struct timeval tv[2];
990 #define SCREWUP(str) { why = str; goto screwup; }
992 if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
993 SCREWUP("Unexpected off_t/time_t size");
995 setimes = targisdir = 0;
1000 run_err("ambiguous target");
1004 if (targetshouldbedirectory)
1007 (void) atomicio(vwrite, remout, "", 1);
1008 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1010 for (first = 1;; first = 0) {
1012 if (atomicio(read, remin, cp, 1) != 1)
1015 SCREWUP("unexpected <newline>");
1017 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1018 SCREWUP("lost connection");
1020 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1023 fmprintf(stderr, "Sink: %s", buf);
1025 if (buf[0] == '\01' || buf[0] == '\02') {
1026 if (iamremote == 0) {
1027 (void) snmprintf(visbuf, sizeof(visbuf),
1028 NULL, "%s", buf + 1);
1029 (void) atomicio(vwrite, STDERR_FILENO,
1030 visbuf, strlen(visbuf));
1032 if (buf[0] == '\02')
1037 if (buf[0] == 'E') {
1038 (void) atomicio(vwrite, remout, "", 1);
1048 if (!isdigit((unsigned char)*cp))
1049 SCREWUP("mtime.sec not present");
1050 ull = strtoull(cp, &cp, 10);
1051 if (!cp || *cp++ != ' ')
1052 SCREWUP("mtime.sec not delimited");
1053 if (TYPE_OVERFLOW(time_t, ull))
1054 setimes = 0; /* out of range */
1056 mtime.tv_usec = strtol(cp, &cp, 10);
1057 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1058 mtime.tv_usec > 999999)
1059 SCREWUP("mtime.usec not delimited");
1060 if (!isdigit((unsigned char)*cp))
1061 SCREWUP("atime.sec not present");
1062 ull = strtoull(cp, &cp, 10);
1063 if (!cp || *cp++ != ' ')
1064 SCREWUP("atime.sec not delimited");
1065 if (TYPE_OVERFLOW(time_t, ull))
1066 setimes = 0; /* out of range */
1068 atime.tv_usec = strtol(cp, &cp, 10);
1069 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1070 atime.tv_usec > 999999)
1071 SCREWUP("atime.usec not delimited");
1072 (void) atomicio(vwrite, remout, "", 1);
1075 if (*cp != 'C' && *cp != 'D') {
1077 * Check for the case "rcp remote:foo\* local:bar".
1078 * In this case, the line "No match." can be returned
1079 * by the shell before the rcp command on the remote is
1080 * executed so the ^Aerror_message convention isn't
1087 SCREWUP("expected control record");
1090 for (++cp; cp < buf + 5; cp++) {
1091 if (*cp < '0' || *cp > '7')
1092 SCREWUP("bad mode");
1093 mode = (mode << 3) | (*cp - '0');
1096 SCREWUP("mode not delimited");
1098 if (!isdigit((unsigned char)*cp))
1099 SCREWUP("size not present");
1100 ull = strtoull(cp, &cp, 10);
1101 if (!cp || *cp++ != ' ')
1102 SCREWUP("size not delimited");
1103 if (TYPE_OVERFLOW(off_t, ull))
1104 SCREWUP("size out of range");
1107 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
1108 run_err("error: unexpected filename: %s", cp);
1112 static char *namebuf;
1113 static size_t cursize;
1116 need = strlen(targ) + strlen(cp) + 250;
1117 if (need > cursize) {
1119 namebuf = xmalloc(need);
1122 (void) snprintf(namebuf, need, "%s%s%s", targ,
1123 strcmp(targ, "/") ? "/" : "", cp);
1128 exists = stat(np, &stb) == 0;
1129 if (buf[0] == 'D') {
1130 int mod_flag = pflag;
1132 SCREWUP("received directory without -r");
1134 if (!S_ISDIR(stb.st_mode)) {
1139 (void) chmod(np, mode);
1141 /* Handle copying from a read-only
1144 if (mkdir(np, mode | S_IRWXU) < 0)
1147 vect[0] = xstrdup(np);
1151 if (utimes(vect[0], tv) < 0)
1152 run_err("%s: set times: %s",
1153 vect[0], strerror(errno));
1156 (void) chmod(vect[0], mode);
1162 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1163 bad: run_err("%s: %s", np, strerror(errno));
1166 (void) atomicio(vwrite, remout, "", 1);
1167 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1176 start_progress_meter(curfile, size, &statbytes);
1177 set_nonblock(remin);
1178 for (count = i = 0; i < size; i += bp->cnt) {
1184 j = atomicio6(read, remin, cp, amt,
1187 run_err("%s", j != EPIPE ?
1189 "dropped connection");
1196 if (count == bp->cnt) {
1197 /* Keep reading so we stay sync'd up. */
1199 if (atomicio(vwrite, ofd, bp->buf,
1209 unset_nonblock(remin);
1210 if (count != 0 && wrerr == NO &&
1211 atomicio(vwrite, ofd, bp->buf, count) != count) {
1215 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1216 ftruncate(ofd, size) != 0) {
1217 run_err("%s: truncate: %s", np, strerror(errno));
1221 if (exists || omode != mode)
1223 if (fchmod(ofd, omode)) {
1224 #else /* HAVE_FCHMOD */
1225 if (chmod(np, omode)) {
1226 #endif /* HAVE_FCHMOD */
1227 run_err("%s: set mode: %s",
1228 np, strerror(errno));
1232 if (!exists && omode != mode)
1234 if (fchmod(ofd, omode & ~mask)) {
1235 #else /* HAVE_FCHMOD */
1236 if (chmod(np, omode & ~mask)) {
1237 #endif /* HAVE_FCHMOD */
1238 run_err("%s: set mode: %s",
1239 np, strerror(errno));
1243 if (close(ofd) == -1) {
1249 stop_progress_meter();
1250 if (setimes && wrerr == NO) {
1252 if (utimes(np, tv) < 0) {
1253 run_err("%s: set times: %s",
1254 np, strerror(errno));
1260 run_err("%s: %s", np, strerror(wrerrno));
1263 (void) atomicio(vwrite, remout, "", 1);
1270 run_err("protocol error: %s", why);
1277 char ch, *cp, resp, rbuf[2048], visbuf[2048];
1279 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1289 case 1: /* error, followed by error msg */
1290 case 2: /* fatal error, "" */
1292 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1295 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1299 (void) snmprintf(visbuf, sizeof(visbuf),
1300 NULL, "%s\n", rbuf);
1301 (void) atomicio(vwrite, STDERR_FILENO,
1302 visbuf, strlen(visbuf));
1315 (void) fprintf(stderr,
1316 "usage: scp [-346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1317 " [-l limit] [-o ssh_option] [-P port] [-S program] source ... target\n");
1322 run_err(const char *fmt,...)
1328 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1329 (void) fprintf(fp, "%c", 0x01);
1330 (void) fprintf(fp, "scp: ");
1332 (void) vfprintf(fp, fmt, ap);
1334 (void) fprintf(fp, "\n");
1340 vfmprintf(stderr, fmt, ap);
1342 fprintf(stderr, "\n");
1351 if (!stat(cp, &stb)) {
1352 if (S_ISDIR(stb.st_mode))
1356 run_err("%s: %s", cp, strerror(errno));
1371 if (!isalpha(c) && !isdigit((unsigned char)c)) {
1386 bad: fmprintf(stderr, "%s: invalid user name\n", cp0);
1391 allocbuf(BUF *bp, int fd, int blksize)
1394 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1397 if (fstat(fd, &stb) < 0) {
1398 run_err("fstat: %s", strerror(errno));
1401 size = ROUNDUP(stb.st_blksize, blksize);
1404 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1406 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1407 if (bp->cnt >= size)
1409 bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
1418 (void)write(STDERR_FILENO, "lost connection\n", 16);