1 /* $OpenBSD: scp.c,v 1.166 2010/07/01 13:06:59 millert 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 #include <sys/param.h>
78 #ifdef HAVE_SYS_STAT_H
79 # include <sys/stat.h>
84 # ifdef HAVE_SYS_POLL_H
85 # include <sys/poll.h>
88 #ifdef HAVE_SYS_TIME_H
89 # include <sys/time.h>
106 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H)
111 #include "atomicio.h"
112 #include "pathnames.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);
125 /* Struct for addargs */
128 /* Bandwidth limit */
129 off_t limit_rate = 0;
131 /* Name of current file being transferred. */
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;
149 if (do_cmd_pid > 1) {
150 kill(do_cmd_pid, signo ? signo : SIGTERM);
151 waitpid(do_cmd_pid, NULL, 0);
164 if (do_cmd_pid > 1) {
165 kill(do_cmd_pid, signo);
166 while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
169 kill(getpid(), SIGSTOP);
174 do_local_cmd(arglist *a)
181 fatal("do_local_cmd: no arguments");
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));
193 execvp(a->list[0], a->list);
199 signal(SIGTERM, killchild);
200 signal(SIGINT, killchild);
201 signal(SIGHUP, killchild);
203 while (waitpid(pid, &status, 0) == -1)
205 fatal("do_local_cmd: waitpid: %s", strerror(errno));
209 if (!WIFEXITED(status) || WEXITSTATUS(status) != 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];
228 "Executing: program %s host %s, user %s, command %s\n",
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. */
241 fatal("pipe: %s", strerror(errno));
243 fatal("pipe: %s", strerror(errno));
245 /* Free the reserved descriptors. */
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. */
255 if (do_cmd_pid == 0) {
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);
276 } else if (do_cmd_pid == -1) {
277 fatal("fork: %s", strerror(errno));
279 /* Parent. Close the other side, and return the local side. */
284 signal(SIGTERM, killchild);
285 signal(SIGINT, killchild);
286 signal(SIGHUP, killchild);
295 BUF *allocbuf(BUF *, int, int);
298 void run_err(const char *,...);
299 void verifydir(char *);
303 int errs, remin, remout;
304 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
307 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
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 size_t scpio(ssize_t (*)(int, void *, size_t), int, void *, size_t, off_t *);
319 main(int argc, char **argv)
321 int ch, fflag, tflag, status, n;
323 char *targ, *endp, **newargv;
327 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
330 /* Copy argv, because we modify it */
331 newargv = xcalloc(MAX(argc + 1, 1), sizeof(*newargv));
332 for (n = 0; n < argc; n++)
333 newargv[n] = xstrdup(argv[n]);
336 __progname = ssh_get_progname(argv[0]);
338 memset(&args, '\0', sizeof(args));
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");
347 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
349 /* User-visible flags. */
355 addargs(&args, "-%c", ch);
361 addargs(&args, "-%c", ch);
362 addargs(&args, "%s", optarg);
365 addargs(&args, "-p");
366 addargs(&args, "%s", optarg);
369 addargs(&args, "-oBatchmode yes");
372 speed = strtod(optarg, &endp);
373 if (speed <= 0 || *endp != '\0')
375 limit_rate = speed * 1024;
384 ssh_program = xstrdup(optarg);
387 addargs(&args, "-v");
391 addargs(&args, "-q");
395 /* Server options. */
397 targetshouldbedirectory = 1;
399 case 'f': /* "from" */
407 setmode(0, O_BINARY);
416 if ((pwd = getpwuid(userid = getuid())) == NULL)
417 fatal("unknown user %u", (u_int) userid);
419 if (!isatty(STDOUT_FILENO))
422 remin = STDIN_FILENO;
423 remout = STDOUT_FILENO;
426 /* Follow "protocol", send data. */
439 targetshouldbedirectory = 1;
443 /* Command to be executed on remote system using "ssh". */
444 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
445 verbose_mode ? " -v" : "",
446 iamrecursive ? " -r" : "", pflag ? " -p" : "",
447 targetshouldbedirectory ? " -d" : "");
449 (void) signal(SIGPIPE, lostconn);
451 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
452 toremote(targ, argc, argv);
454 if (targetshouldbedirectory)
455 verifydir(argv[argc - 1]);
456 tolocal(argc, argv); /* Dest is local host. */
459 * Finally check the exit status of the ssh process, if one was forked
460 * and no error has occurred yet
462 if (do_cmd_pid != -1 && errs == 0) {
466 (void) close(remout);
467 if (waitpid(do_cmd_pid, &status, 0) == -1)
470 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
478 * atomicio-like wrapper that also applies bandwidth limits and updates
479 * the progressmeter counter.
482 scpio(ssize_t (*f)(int, void *, size_t), int fd, void *_p, size_t l, off_t *c)
484 u_char *p = (u_char *)_p;
490 pfd.events = f == read ? POLLIN : POLLOUT;
491 for (offset = 0; offset < l;) {
492 r = f(fd, p + offset, l - offset);
500 if (errno == EAGAIN || errno == EWOULDBLOCK) {
501 (void)poll(&pfd, 1, -1); /* Ignore errors */
515 toremote(char *targ, int argc, char **argv)
517 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
521 memset(&alist, '\0', sizeof(alist));
528 arg = xstrdup(argv[argc - 1]);
529 if ((thost = strrchr(arg, '@'))) {
540 if (tuser != NULL && !okname(tuser)) {
545 for (i = 0; i < argc - 1; i++) {
546 src = colon(argv[i]);
547 if (src) { /* remote to remote */
549 addargs(&alist, "%s", ssh_program);
551 addargs(&alist, "-v");
552 addargs(&alist, "-x");
553 addargs(&alist, "-oClearAllForwardings yes");
554 addargs(&alist, "-n");
559 host = strrchr(argv[i], '@');
563 host = cleanhostname(host);
566 suser = pwd->pw_name;
567 else if (!okname(suser))
569 addargs(&alist, "-l");
570 addargs(&alist, "%s", suser);
572 host = cleanhostname(argv[i]);
574 addargs(&alist, "--");
575 addargs(&alist, "%s", host);
576 addargs(&alist, "%s", cmd);
577 addargs(&alist, "%s", src);
578 addargs(&alist, "%s%s%s:%s",
579 tuser ? tuser : "", tuser ? "@" : "",
581 if (do_local_cmd(&alist) != 0)
583 } else { /* local to remote */
585 xasprintf(&bp, "%s -t -- %s", cmd, targ);
586 host = cleanhostname(thost);
587 if (do_cmd(host, tuser, bp, &remin,
601 tolocal(int argc, char **argv)
603 char *bp, *host, *src, *suser;
607 memset(&alist, '\0', sizeof(alist));
610 for (i = 0; i < argc - 1; i++) {
611 if (!(src = colon(argv[i]))) { /* Local to local. */
613 addargs(&alist, "%s", _PATH_CP);
615 addargs(&alist, "-r");
617 addargs(&alist, "-p");
618 addargs(&alist, "--");
619 addargs(&alist, "%s", argv[i]);
620 addargs(&alist, "%s", argv[argc-1]);
621 if (do_local_cmd(&alist))
628 if ((host = strrchr(argv[i], '@')) == NULL) {
635 suser = pwd->pw_name;
637 host = cleanhostname(host);
638 xasprintf(&bp, "%s -f -- %s", cmd, src);
639 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
645 sink(1, argv + argc - 1);
652 source(int argc, char **argv)
659 int fd = -1, haderr, indx;
660 char *last, *name, buf[16384], encname[MAXPATHLEN];
663 for (indx = 0; indx < argc; ++indx) {
667 while (len > 1 && name[len-1] == '/')
669 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
671 if (strchr(name, '\n') != NULL) {
672 strnvis(encname, name, sizeof(encname), VIS_NL);
675 if (fstat(fd, &stb) < 0) {
676 syserr: run_err("%s: %s", name, strerror(errno));
679 if (stb.st_size < 0) {
680 run_err("%s: %s", name, "Negative file size");
684 switch (stb.st_mode & S_IFMT) {
694 run_err("%s: not a regular file", name);
697 if ((last = strrchr(name, '/')) == NULL)
704 * Make it compatible with possible future
705 * versions expecting microseconds.
707 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
708 (u_long) (stb.st_mtime < 0 ? 0 : stb.st_mtime),
709 (u_long) (stb.st_atime < 0 ? 0 : stb.st_atime));
711 fprintf(stderr, "File mtime %ld atime %ld\n",
712 (long)stb.st_mtime, (long)stb.st_atime);
713 fprintf(stderr, "Sending file timestamps: %s",
716 (void) atomicio(vwrite, remout, buf, strlen(buf));
720 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
721 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
722 (u_int) (stb.st_mode & FILEMODEMASK),
723 (long long)stb.st_size, last);
725 fprintf(stderr, "Sending file modes: %s", buf);
727 (void) atomicio(vwrite, remout, buf, strlen(buf));
730 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
731 next: if (fd != -1) {
738 start_progress_meter(curfile, stb.st_size, &statbytes);
739 set_nonblock(remout);
740 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
742 if (i + (off_t)amt > stb.st_size)
743 amt = stb.st_size - i;
745 if (atomicio(read, fd, bp->buf, amt) != amt)
748 /* Keep writing after error to retain sync */
750 (void)atomicio(vwrite, remout, bp->buf, amt);
753 if (scpio(vwrite, remout, bp->buf, amt,
757 unset_nonblock(remout);
759 stop_progress_meter();
762 if (close(fd) < 0 && !haderr)
767 (void) atomicio(vwrite, remout, "", 1);
769 run_err("%s: %s", name, strerror(haderr));
775 rsource(char *name, struct stat *statp)
779 char *last, *vect[1], path[1100];
781 if (!(dirp = opendir(name))) {
782 run_err("%s: %s", name, strerror(errno));
785 last = strrchr(name, '/');
791 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
792 (u_long) statp->st_mtime,
793 (u_long) statp->st_atime);
794 (void) atomicio(vwrite, remout, path, strlen(path));
795 if (response() < 0) {
800 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
801 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
803 fprintf(stderr, "Entering directory: %s", path);
804 (void) atomicio(vwrite, remout, path, strlen(path));
805 if (response() < 0) {
809 while ((dp = readdir(dirp)) != NULL) {
812 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
814 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
815 run_err("%s/%s: name too long", name, dp->d_name);
818 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
822 (void) closedir(dirp);
823 (void) atomicio(vwrite, remout, "E\n", 2);
830 static struct timeval bwstart, bwend;
831 static int lamt, thresh = 16384;
833 struct timespec ts, rm;
835 if (!timerisset(&bwstart)) {
836 gettimeofday(&bwstart, NULL);
844 gettimeofday(&bwend, NULL);
845 timersub(&bwend, &bwstart, &bwend);
846 if (!timerisset(&bwend))
850 waitlen = (double)1000000L * lamt / limit_rate;
852 bwstart.tv_sec = waitlen / 1000000L;
853 bwstart.tv_usec = waitlen % 1000000L;
855 if (timercmp(&bwstart, &bwend, >)) {
856 timersub(&bwstart, &bwend, &bwend);
858 /* Adjust the wait time */
863 } else if (bwend.tv_usec < 10000) {
865 if (thresh > COPY_BUFLEN * 4)
866 thresh = COPY_BUFLEN * 4;
869 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
870 while (nanosleep(&ts, &rm) == -1) {
878 gettimeofday(&bwstart, NULL);
882 sink(int argc, char **argv)
892 int amt, exists, first, ofd;
893 mode_t mode, omode, mask;
894 off_t size, statbytes;
895 int setimes, targisdir, wrerrno = 0;
896 char ch, *cp, *np, *targ, *why, *vect[1], buf[16384];
897 struct timeval tv[2];
901 #define SCREWUP(str) { why = str; goto screwup; }
903 setimes = targisdir = 0;
908 run_err("ambiguous target");
912 if (targetshouldbedirectory)
915 (void) atomicio(vwrite, remout, "", 1);
916 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
918 for (first = 1;; first = 0) {
920 if (atomicio(read, remin, cp, 1) != 1)
923 SCREWUP("unexpected <newline>");
925 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
926 SCREWUP("lost connection");
928 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
931 fprintf(stderr, "Sink: %s", buf);
933 if (buf[0] == '\01' || buf[0] == '\02') {
935 (void) atomicio(vwrite, STDERR_FILENO,
936 buf + 1, strlen(buf + 1));
943 (void) atomicio(vwrite, remout, "", 1);
953 mtime.tv_sec = strtol(cp, &cp, 10);
954 if (!cp || *cp++ != ' ')
955 SCREWUP("mtime.sec not delimited");
956 mtime.tv_usec = strtol(cp, &cp, 10);
957 if (!cp || *cp++ != ' ')
958 SCREWUP("mtime.usec not delimited");
959 atime.tv_sec = strtol(cp, &cp, 10);
960 if (!cp || *cp++ != ' ')
961 SCREWUP("atime.sec not delimited");
962 atime.tv_usec = strtol(cp, &cp, 10);
963 if (!cp || *cp++ != '\0')
964 SCREWUP("atime.usec not delimited");
965 (void) atomicio(vwrite, remout, "", 1);
968 if (*cp != 'C' && *cp != 'D') {
970 * Check for the case "rcp remote:foo\* local:bar".
971 * In this case, the line "No match." can be returned
972 * by the shell before the rcp command on the remote is
973 * executed so the ^Aerror_message convention isn't
980 SCREWUP("expected control record");
983 for (++cp; cp < buf + 5; cp++) {
984 if (*cp < '0' || *cp > '7')
986 mode = (mode << 3) | (*cp - '0');
989 SCREWUP("mode not delimited");
991 for (size = 0; isdigit(*cp);)
992 size = size * 10 + (*cp++ - '0');
994 SCREWUP("size not delimited");
995 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
996 run_err("error: unexpected filename: %s", cp);
1000 static char *namebuf;
1001 static size_t cursize;
1004 need = strlen(targ) + strlen(cp) + 250;
1005 if (need > cursize) {
1008 namebuf = xmalloc(need);
1011 (void) snprintf(namebuf, need, "%s%s%s", targ,
1012 strcmp(targ, "/") ? "/" : "", cp);
1017 exists = stat(np, &stb) == 0;
1018 if (buf[0] == 'D') {
1019 int mod_flag = pflag;
1021 SCREWUP("received directory without -r");
1023 if (!S_ISDIR(stb.st_mode)) {
1028 (void) chmod(np, mode);
1030 /* Handle copying from a read-only
1033 if (mkdir(np, mode | S_IRWXU) < 0)
1036 vect[0] = xstrdup(np);
1040 if (utimes(vect[0], tv) < 0)
1041 run_err("%s: set times: %s",
1042 vect[0], strerror(errno));
1045 (void) chmod(vect[0], mode);
1052 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1053 bad: run_err("%s: %s", np, strerror(errno));
1056 (void) atomicio(vwrite, remout, "", 1);
1057 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1066 start_progress_meter(curfile, size, &statbytes);
1067 set_nonblock(remin);
1068 for (count = i = 0; i < size; i += bp->cnt) {
1074 j = scpio(read, remin, cp, amt, &statbytes);
1076 run_err("%s", j != EPIPE ?
1078 "dropped connection");
1085 if (count == bp->cnt) {
1086 /* Keep reading so we stay sync'd up. */
1088 if (atomicio(vwrite, ofd, bp->buf,
1098 unset_nonblock(remin);
1100 stop_progress_meter();
1101 if (count != 0 && wrerr == NO &&
1102 atomicio(vwrite, ofd, bp->buf, count) != count) {
1106 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1107 ftruncate(ofd, size) != 0) {
1108 run_err("%s: truncate: %s", np, strerror(errno));
1112 if (exists || omode != mode)
1114 if (fchmod(ofd, omode)) {
1115 #else /* HAVE_FCHMOD */
1116 if (chmod(np, omode)) {
1117 #endif /* HAVE_FCHMOD */
1118 run_err("%s: set mode: %s",
1119 np, strerror(errno));
1123 if (!exists && omode != mode)
1125 if (fchmod(ofd, omode & ~mask)) {
1126 #else /* HAVE_FCHMOD */
1127 if (chmod(np, omode & ~mask)) {
1128 #endif /* HAVE_FCHMOD */
1129 run_err("%s: set mode: %s",
1130 np, strerror(errno));
1134 if (close(ofd) == -1) {
1139 if (setimes && wrerr == NO) {
1141 if (utimes(np, tv) < 0) {
1142 run_err("%s: set times: %s",
1143 np, strerror(errno));
1149 run_err("%s: %s", np, strerror(wrerrno));
1152 (void) atomicio(vwrite, remout, "", 1);
1159 run_err("protocol error: %s", why);
1166 char ch, *cp, resp, rbuf[2048];
1168 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1178 case 1: /* error, followed by error msg */
1179 case 2: /* fatal error, "" */
1181 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1184 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1187 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1199 (void) fprintf(stderr,
1200 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1201 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1202 " [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1207 run_err(const char *fmt,...)
1213 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1214 (void) fprintf(fp, "%c", 0x01);
1215 (void) fprintf(fp, "scp: ");
1217 (void) vfprintf(fp, fmt, ap);
1219 (void) fprintf(fp, "\n");
1225 vfprintf(stderr, fmt, ap);
1227 fprintf(stderr, "\n");
1236 if (!stat(cp, &stb)) {
1237 if (S_ISDIR(stb.st_mode))
1241 run_err("%s: %s", cp, strerror(errno));
1256 if (!isalpha(c) && !isdigit(c)) {
1271 bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1276 allocbuf(BUF *bp, int fd, int blksize)
1279 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1282 if (fstat(fd, &stb) < 0) {
1283 run_err("fstat: %s", strerror(errno));
1286 size = roundup(stb.st_blksize, blksize);
1289 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1291 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1292 if (bp->cnt >= size)
1294 if (bp->buf == NULL)
1295 bp->buf = xmalloc(size);
1297 bp->buf = xrealloc(bp->buf, 1, size);
1298 memset(bp->buf, 0, size);
1307 write(STDERR_FILENO, "lost connection\n", 16);