]> andersk Git - openssh.git/blame - scp.c
- stevesk@cvs.openbsd.org 2006/02/20 16:36:15
[openssh.git] / scp.c
CommitLineData
8efc0c15 1/*
bcbf86ec 2 * scp - secure remote copy. This is basically patched BSD rcp which
3 * uses ssh to do the data transfer (instead of using rcmd).
6ae2364d 4 *
bcbf86ec 5 * NOTE: This version should NOT be suid root. (This uses ssh to
6 * do the transfer and ssh has the necessary privileges.)
6ae2364d 7 *
5260325f 8 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
6ae2364d 9 *
bcbf86ec 10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
15 */
16/*
f3c7c613 17 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
18 * Copyright (c) 1999 Aaron Campbell. All rights reserved.
bcbf86ec 19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
22 * are met:
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 */
8efc0c15 40
41/*
2e73a022 42 * Parts from:
43 *
8efc0c15 44 * Copyright (c) 1983, 1990, 1992, 1993, 1995
45 * The Regents of the University of California. All rights reserved.
46 *
47 * Redistribution and use in source and binary forms, with or without
48 * modification, are permitted provided that the following conditions
49 * are met:
50 * 1. Redistributions of source code must retain the above copyright
51 * notice, this list of conditions and the following disclaimer.
52 * 2. Redistributions in binary form must reproduce the above copyright
53 * notice, this list of conditions and the following disclaimer in the
54 * documentation and/or other materials provided with the distribution.
d981089c 55 * 3. Neither the name of the University nor the names of its contributors
8efc0c15 56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
70 *
8efc0c15 71 */
72
73#include "includes.h"
aa2eae64 74RCSID("$OpenBSD: scp.c,v 1.132 2006/02/10 01:44:26 stevesk Exp $");
75
76#include <sys/types.h>
77#include <sys/wait.h>
68e39d38 78
79#include <dirent.h>
8efc0c15 80
8efc0c15 81#include "xmalloc.h"
42f11eb2 82#include "atomicio.h"
83#include "pathnames.h"
84#include "log.h"
36a358ca 85#include "misc.h"
b65c3807 86#include "progressmeter.h"
8efc0c15 87
260d427b 88extern char *__progname;
260d427b 89
6ea3c52a 90void bwlimit(int);
91
8a624ebf 92/* Struct for addargs */
93arglist args;
94ec8c6b 94
6ea3c52a 95/* Bandwidth limit */
10adbb52 96off_t limit_rate = 0;
6ea3c52a 97
8efc0c15 98/* Name of current file being transferred. */
99char *curfile;
100
101/* This is set to non-zero to enable verbose mode. */
5260325f 102int verbose_mode = 0;
8efc0c15 103
8efc0c15 104/* This is set to zero if the progressmeter is not desired. */
105int showprogress = 1;
106
2e73a022 107/* This is the program to execute for the secured connection. ("ssh" or -S) */
42f11eb2 108char *ssh_program = _PATH_SSH_PROGRAM;
2e73a022 109
252d1a24 110/* This is used to store the pid of ssh_program */
0f764b2f 111pid_t do_cmd_pid = -1;
112
113static void
114killchild(int signo)
115{
3c03ad3f 116 if (do_cmd_pid > 1) {
8f4ab41b 117 kill(do_cmd_pid, signo ? signo : SIGTERM);
3c03ad3f 118 waitpid(do_cmd_pid, NULL, 0);
119 }
0f764b2f 120
8f4ab41b 121 if (signo)
122 _exit(1);
123 exit(1);
0f764b2f 124}
252d1a24 125
4116f5c0 126static int
127do_local_cmd(arglist *a)
128{
129 u_int i;
130 int status;
131 pid_t pid;
132
133 if (a->num == 0)
134 fatal("do_local_cmd: no arguments");
135
136 if (verbose_mode) {
137 fprintf(stderr, "Executing:");
138 for (i = 0; i < a->num; i++)
139 fprintf(stderr, " %s", a->list[i]);
140 fprintf(stderr, "\n");
141 }
142 if ((pid = fork()) == -1)
143 fatal("do_local_cmd: fork: %s", strerror(errno));
144
145 if (pid == 0) {
146 execvp(a->list[0], a->list);
147 perror(a->list[0]);
148 exit(1);
149 }
150
151 do_cmd_pid = pid;
152 signal(SIGTERM, killchild);
153 signal(SIGINT, killchild);
154 signal(SIGHUP, killchild);
155
156 while (waitpid(pid, &status, 0) == -1)
157 if (errno != EINTR)
158 fatal("do_local_cmd: waitpid: %s", strerror(errno));
159
160 do_cmd_pid = -1;
161
162 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
163 return (-1);
164
165 return (0);
166}
167
aa3378df 168/*
169 * This function executes the given command as the specified user on the
170 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
171 * assigns the input and output file descriptors on success.
172 */
8efc0c15 173
6ae2364d 174int
2e73a022 175do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
8efc0c15 176{
5260325f 177 int pin[2], pout[2], reserved[2];
178
179 if (verbose_mode)
0b2988ca 180 fprintf(stderr,
181 "Executing: program %s host %s, user %s, command %s\n",
182 ssh_program, host,
183 remuser ? remuser : "(unspecified)", cmd);
5260325f 184
aa3378df 185 /*
186 * Reserve two descriptors so that the real pipes won't get
187 * descriptors 0 and 1 because that will screw up dup2 below.
188 */
5260325f 189 pipe(reserved);
190
191 /* Create a socket pair for communicating with ssh. */
192 if (pipe(pin) < 0)
193 fatal("pipe: %s", strerror(errno));
194 if (pipe(pout) < 0)
195 fatal("pipe: %s", strerror(errno));
196
197 /* Free the reserved descriptors. */
198 close(reserved[0]);
199 close(reserved[1]);
200
1fb23629 201 /* Fork a child to execute the command on the remote host using ssh. */
252d1a24 202 do_cmd_pid = fork();
203 if (do_cmd_pid == 0) {
5260325f 204 /* Child. */
205 close(pin[1]);
206 close(pout[0]);
207 dup2(pin[0], 0);
208 dup2(pout[1], 1);
209 close(pin[0]);
210 close(pout[1]);
211
4116f5c0 212 replacearg(&args, 0, "%s", ssh_program);
94ec8c6b 213 if (remuser != NULL)
8a624ebf 214 addargs(&args, "-l%s", remuser);
215 addargs(&args, "%s", host);
216 addargs(&args, "%s", cmd);
5260325f 217
94ec8c6b 218 execvp(ssh_program, args.list);
2e73a022 219 perror(ssh_program);
5260325f 220 exit(1);
252d1a24 221 } else if (do_cmd_pid == -1) {
222 fatal("fork: %s", strerror(errno));
8efc0c15 223 }
5260325f 224 /* Parent. Close the other side, and return the local side. */
225 close(pin[0]);
226 *fdout = pin[1];
227 close(pout[1]);
228 *fdin = pout[0];
0f764b2f 229 signal(SIGTERM, killchild);
230 signal(SIGINT, killchild);
231 signal(SIGHUP, killchild);
5260325f 232 return 0;
8efc0c15 233}
234
8efc0c15 235typedef struct {
2ceb8101 236 size_t cnt;
8efc0c15 237 char *buf;
238} BUF;
239
5260325f 240BUF *allocbuf(BUF *, int, int);
5260325f 241void lostconn(int);
242void nospace(void);
243int okname(char *);
244void run_err(const char *,...);
245void verifydir(char *);
8efc0c15 246
8efc0c15 247struct passwd *pwd;
5260325f 248uid_t userid;
8efc0c15 249int errs, remin, remout;
250int pflag, iamremote, iamrecursive, targetshouldbedirectory;
251
252#define CMDNEEDS 64
253char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
254
5260325f 255int response(void);
256void rsource(char *, struct stat *);
257void sink(int, char *[]);
258void source(int, char *[]);
259void tolocal(int, char *[]);
260void toremote(char *, int, char *[]);
261void usage(void);
8efc0c15 262
263int
cf3248b8 264main(int argc, char **argv)
8efc0c15 265{
252d1a24 266 int ch, fflag, tflag, status;
6ea3c52a 267 double speed;
268 char *targ, *endp;
8efc0c15 269 extern char *optarg;
270 extern int optind;
271
fd6168c1 272 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
273 sanitise_stdfd();
274
fda04d7d 275 __progname = ssh_get_progname(argv[0]);
260d427b 276
4116f5c0 277 memset(&args, '\0', sizeof(args));
94ec8c6b 278 args.list = NULL;
4116f5c0 279 addargs(&args, "%s", ssh_program);
8a624ebf 280 addargs(&args, "-x");
3a222388 281 addargs(&args, "-oForwardAgent no");
d20f3c9e 282 addargs(&args, "-oPermitLocalCommand no");
e1c5bfaf 283 addargs(&args, "-oClearAllForwardings yes");
94ec8c6b 284
8efc0c15 285 fflag = tflag = 0;
e6b15f23 286 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
5260325f 287 switch (ch) {
288 /* User-visible flags. */
e6b15f23 289 case '1':
290 case '2':
48e671d5 291 case '4':
48e671d5 292 case '6':
94ec8c6b 293 case 'C':
8a624ebf 294 addargs(&args, "-%c", ch);
48e671d5 295 break;
94ec8c6b 296 case 'o':
297 case 'c':
298 case 'i':
f1278af7 299 case 'F':
8a624ebf 300 addargs(&args, "-%c%s", ch, optarg);
8efc0c15 301 break;
302 case 'P':
8a624ebf 303 addargs(&args, "-p%s", optarg);
94ec8c6b 304 break;
305 case 'B':
8a624ebf 306 addargs(&args, "-oBatchmode yes");
94ec8c6b 307 break;
6ea3c52a 308 case 'l':
309 speed = strtod(optarg, &endp);
310 if (speed <= 0 || *endp != '\0')
311 usage();
10adbb52 312 limit_rate = speed * 1024;
6ea3c52a 313 break;
94ec8c6b 314 case 'p':
315 pflag = 1;
5260325f 316 break;
8efc0c15 317 case 'r':
318 iamrecursive = 1;
319 break;
2e73a022 320 case 'S':
94ec8c6b 321 ssh_program = xstrdup(optarg);
322 break;
323 case 'v':
4fc334a2 324 addargs(&args, "-v");
94ec8c6b 325 verbose_mode = 1;
326 break;
327 case 'q':
15c8e3fd 328 addargs(&args, "-q");
94ec8c6b 329 showprogress = 0;
2e73a022 330 break;
331
5260325f 332 /* Server options. */
8efc0c15 333 case 'd':
334 targetshouldbedirectory = 1;
335 break;
5260325f 336 case 'f': /* "from" */
8efc0c15 337 iamremote = 1;
338 fflag = 1;
339 break;
5260325f 340 case 't': /* "to" */
8efc0c15 341 iamremote = 1;
342 tflag = 1;
fe56c12b 343#ifdef HAVE_CYGWIN
344 setmode(0, O_BINARY);
345#endif
8efc0c15 346 break;
8efc0c15 347 default:
348 usage();
349 }
350 argc -= optind;
351 argv += optind;
352
353 if ((pwd = getpwuid(userid = getuid())) == NULL)
261bd618 354 fatal("unknown user %u", (u_int) userid);
8efc0c15 355
5260325f 356 if (!isatty(STDERR_FILENO))
8efc0c15 357 showprogress = 0;
358
359 remin = STDIN_FILENO;
360 remout = STDOUT_FILENO;
361
2b87da3b 362 if (fflag) {
5260325f 363 /* Follow "protocol", send data. */
364 (void) response();
8efc0c15 365 source(argc, argv);
366 exit(errs != 0);
367 }
5260325f 368 if (tflag) {
369 /* Receive data. */
8efc0c15 370 sink(argc, argv);
371 exit(errs != 0);
372 }
8efc0c15 373 if (argc < 2)
374 usage();
375 if (argc > 2)
376 targetshouldbedirectory = 1;
377
378 remin = remout = -1;
252d1a24 379 do_cmd_pid = -1;
8efc0c15 380 /* Command to be executed on remote system using "ssh". */
0ed28836 381 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
382 verbose_mode ? " -v" : "",
2e73a022 383 iamrecursive ? " -r" : "", pflag ? " -p" : "",
384 targetshouldbedirectory ? " -d" : "");
8efc0c15 385
5260325f 386 (void) signal(SIGPIPE, lostconn);
8efc0c15 387
388 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
389 toremote(targ, argc, argv);
390 else {
8efc0c15 391 if (targetshouldbedirectory)
392 verifydir(argv[argc - 1]);
16e8ab10 393 tolocal(argc, argv); /* Dest is local host. */
8efc0c15 394 }
252d1a24 395 /*
396 * Finally check the exit status of the ssh process, if one was forked
397 * and no error has occured yet
398 */
399 if (do_cmd_pid != -1 && errs == 0) {
400 if (remin != -1)
401 (void) close(remin);
402 if (remout != -1)
403 (void) close(remout);
404 if (waitpid(do_cmd_pid, &status, 0) == -1)
405 errs = 1;
406 else {
407 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
408 errs = 1;
409 }
410 }
8efc0c15 411 exit(errs != 0);
412}
413
414void
cf3248b8 415toremote(char *targ, int argc, char **argv)
8efc0c15 416{
417 int i, len;
99dfaccc 418 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
4116f5c0 419 arglist alist;
420
421 memset(&alist, '\0', sizeof(alist));
422 alist.list = NULL;
8efc0c15 423
424 *targ++ = 0;
425 if (*targ == 0)
426 targ = ".";
427
ae0d2f42 428 arg = xstrdup(argv[argc - 1]);
99dfaccc 429 if ((thost = strrchr(arg, '@'))) {
8efc0c15 430 /* user@host */
431 *thost++ = 0;
99dfaccc 432 tuser = arg;
8efc0c15 433 if (*tuser == '\0')
434 tuser = NULL;
8efc0c15 435 } else {
99dfaccc 436 thost = arg;
8efc0c15 437 tuser = NULL;
438 }
439
4116f5c0 440 if (tuser != NULL && !okname(tuser)) {
441 xfree(arg);
442 return;
443 }
444
8efc0c15 445 for (i = 0; i < argc - 1; i++) {
446 src = colon(argv[i]);
5260325f 447 if (src) { /* remote to remote */
4116f5c0 448 freeargs(&alist);
449 addargs(&alist, "%s", ssh_program);
450 if (verbose_mode)
451 addargs(&alist, "-v");
452 addargs(&alist, "-x");
453 addargs(&alist, "-oClearAllForwardings yes");
454 addargs(&alist, "-n");
455
8efc0c15 456 *src++ = 0;
457 if (*src == 0)
458 src = ".";
15748b4d 459 host = strrchr(argv[i], '@');
4116f5c0 460
8efc0c15 461 if (host) {
462 *host++ = 0;
48e671d5 463 host = cleanhostname(host);
8efc0c15 464 suser = argv[i];
465 if (*suser == '\0')
466 suser = pwd->pw_name;
4116f5c0 467 else if (!okname(suser))
0ec7661a 468 continue;
4116f5c0 469 addargs(&alist, "-l");
470 addargs(&alist, "%s", suser);
48e671d5 471 } else {
472 host = cleanhostname(argv[i]);
48e671d5 473 }
4116f5c0 474 addargs(&alist, "%s", host);
475 addargs(&alist, "%s", cmd);
476 addargs(&alist, "%s", src);
477 addargs(&alist, "%s%s%s:%s",
478 tuser ? tuser : "", tuser ? "@" : "",
479 thost, targ);
480 if (do_local_cmd(&alist) != 0)
815a8407 481 errs = 1;
5260325f 482 } else { /* local to remote */
8efc0c15 483 if (remin == -1) {
484 len = strlen(targ) + CMDNEEDS + 20;
5260325f 485 bp = xmalloc(len);
0ed28836 486 (void) snprintf(bp, len, "%s -t %s", cmd, targ);
48e671d5 487 host = cleanhostname(thost);
2e73a022 488 if (do_cmd(host, tuser, bp, &remin,
489 &remout, argc) < 0)
5260325f 490 exit(1);
8efc0c15 491 if (response() < 0)
492 exit(1);
5260325f 493 (void) xfree(bp);
8efc0c15 494 }
5260325f 495 source(1, argv + i);
8efc0c15 496 }
497 }
498}
499
500void
cf3248b8 501tolocal(int argc, char **argv)
8efc0c15 502{
503 int i, len;
504 char *bp, *host, *src, *suser;
4116f5c0 505 arglist alist;
506
507 memset(&alist, '\0', sizeof(alist));
508 alist.list = NULL;
8efc0c15 509
510 for (i = 0; i < argc - 1; i++) {
5260325f 511 if (!(src = colon(argv[i]))) { /* Local to local. */
4116f5c0 512 freeargs(&alist);
513 addargs(&alist, "%s", _PATH_CP);
514 if (iamrecursive)
515 addargs(&alist, "-r");
516 if (pflag)
517 addargs(&alist, "-p");
518 addargs(&alist, "%s", argv[i]);
519 addargs(&alist, "%s", argv[argc-1]);
520 if (do_local_cmd(&alist))
8efc0c15 521 ++errs;
8efc0c15 522 continue;
523 }
524 *src++ = 0;
525 if (*src == 0)
526 src = ".";
15748b4d 527 if ((host = strrchr(argv[i], '@')) == NULL) {
8efc0c15 528 host = argv[i];
529 suser = NULL;
530 } else {
531 *host++ = 0;
532 suser = argv[i];
533 if (*suser == '\0')
534 suser = pwd->pw_name;
8efc0c15 535 }
48e671d5 536 host = cleanhostname(host);
8efc0c15 537 len = strlen(src) + CMDNEEDS + 20;
5260325f 538 bp = xmalloc(len);
0ed28836 539 (void) snprintf(bp, len, "%s -f %s", cmd, src);
2e73a022 540 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
5260325f 541 (void) xfree(bp);
542 ++errs;
543 continue;
8efc0c15 544 }
5260325f 545 xfree(bp);
8efc0c15 546 sink(1, argv + argc - 1);
5260325f 547 (void) close(remin);
8efc0c15 548 remin = remout = -1;
549 }
550}
551
552void
cf3248b8 553source(int argc, char **argv)
8efc0c15 554{
555 struct stat stb;
556 static BUF buffer;
557 BUF *bp;
05624c18 558 off_t i, amt, statbytes;
559 size_t result;
a056dfa2 560 int fd = -1, haderr, indx;
8efc0c15 561 char *last, *name, buf[2048];
0fc791ba 562 int len;
8efc0c15 563
564 for (indx = 0; indx < argc; ++indx) {
5260325f 565 name = argv[indx];
8efc0c15 566 statbytes = 0;
0fc791ba 567 len = strlen(name);
568 while (len > 1 && name[len-1] == '/')
569 name[--len] = '\0';
5720c10e 570 if (strchr(name, '\n') != NULL) {
571 run_err("%s: skipping, filename contains a newline",
572 name);
573 goto next;
574 }
8efc0c15 575 if ((fd = open(name, O_RDONLY, 0)) < 0)
576 goto syserr;
577 if (fstat(fd, &stb) < 0) {
578syserr: run_err("%s: %s", name, strerror(errno));
579 goto next;
580 }
581 switch (stb.st_mode & S_IFMT) {
582 case S_IFREG:
583 break;
584 case S_IFDIR:
585 if (iamrecursive) {
586 rsource(name, &stb);
587 goto next;
588 }
589 /* FALLTHROUGH */
590 default:
591 run_err("%s: not a regular file", name);
592 goto next;
593 }
594 if ((last = strrchr(name, '/')) == NULL)
595 last = name;
596 else
597 ++last;
598 curfile = last;
599 if (pflag) {
600 /*
601 * Make it compatible with possible future
602 * versions expecting microseconds.
603 */
0ed28836 604 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
1e3b8b07 605 (u_long) stb.st_mtime,
606 (u_long) stb.st_atime);
dc54438a 607 (void) atomicio(vwrite, remout, buf, strlen(buf));
8efc0c15 608 if (response() < 0)
609 goto next;
610 }
611#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
bf1d27bd 612 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1e3b8b07 613 (u_int) (stb.st_mode & FILEMODEMASK),
419094c6 614 (long long)stb.st_size, last);
5260325f 615 if (verbose_mode) {
616 fprintf(stderr, "Sending file modes: %s", buf);
5260325f 617 }
dc54438a 618 (void) atomicio(vwrite, remout, buf, strlen(buf));
8efc0c15 619 if (response() < 0)
620 goto next;
621 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
29accf74 622next: if (fd != -1) {
623 (void) close(fd);
624 fd = -1;
625 }
8efc0c15 626 continue;
627 }
b65c3807 628 if (showprogress)
629 start_progress_meter(curfile, stb.st_size, &statbytes);
8efc0c15 630 /* Keep writing after an error so that we stay sync'd up. */
631 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
632 amt = bp->cnt;
633 if (i + amt > stb.st_size)
634 amt = stb.st_size - i;
635 if (!haderr) {
1d1ffb87 636 result = atomicio(read, fd, bp->buf, amt);
8efc0c15 637 if (result != amt)
05624c18 638 haderr = errno;
8efc0c15 639 }
640 if (haderr)
dc54438a 641 (void) atomicio(vwrite, remout, bp->buf, amt);
8efc0c15 642 else {
dc54438a 643 result = atomicio(vwrite, remout, bp->buf, amt);
8efc0c15 644 if (result != amt)
05624c18 645 haderr = errno;
8efc0c15 646 statbytes += result;
647 }
10adbb52 648 if (limit_rate)
6ea3c52a 649 bwlimit(amt);
8efc0c15 650 }
5260325f 651 if (showprogress)
b65c3807 652 stop_progress_meter();
8efc0c15 653
29accf74 654 if (fd != -1) {
655 if (close(fd) < 0 && !haderr)
656 haderr = errno;
657 fd = -1;
658 }
8efc0c15 659 if (!haderr)
dc54438a 660 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 661 else
662 run_err("%s: %s", name, strerror(haderr));
5260325f 663 (void) response();
8efc0c15 664 }
665}
666
667void
cf3248b8 668rsource(char *name, struct stat *statp)
8efc0c15 669{
670 DIR *dirp;
671 struct dirent *dp;
672 char *last, *vect[1], path[1100];
673
674 if (!(dirp = opendir(name))) {
675 run_err("%s: %s", name, strerror(errno));
676 return;
677 }
678 last = strrchr(name, '/');
679 if (last == 0)
680 last = name;
681 else
682 last++;
683 if (pflag) {
0ed28836 684 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
1e3b8b07 685 (u_long) statp->st_mtime,
686 (u_long) statp->st_atime);
dc54438a 687 (void) atomicio(vwrite, remout, path, strlen(path));
8efc0c15 688 if (response() < 0) {
689 closedir(dirp);
690 return;
691 }
692 }
0ed28836 693 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1e3b8b07 694 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
5260325f 695 if (verbose_mode)
696 fprintf(stderr, "Entering directory: %s", path);
dc54438a 697 (void) atomicio(vwrite, remout, path, strlen(path));
8efc0c15 698 if (response() < 0) {
699 closedir(dirp);
700 return;
701 }
e5ff6ecf 702 while ((dp = readdir(dirp)) != NULL) {
8efc0c15 703 if (dp->d_ino == 0)
704 continue;
705 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
706 continue;
707 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
708 run_err("%s/%s: name too long", name, dp->d_name);
709 continue;
710 }
0ed28836 711 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
8efc0c15 712 vect[0] = path;
713 source(1, vect);
714 }
5260325f 715 (void) closedir(dirp);
dc54438a 716 (void) atomicio(vwrite, remout, "E\n", 2);
5260325f 717 (void) response();
8efc0c15 718}
719
6ea3c52a 720void
721bwlimit(int amount)
722{
723 static struct timeval bwstart, bwend;
724 static int lamt, thresh = 16384;
ca75d7de 725 u_int64_t waitlen;
6ea3c52a 726 struct timespec ts, rm;
727
728 if (!timerisset(&bwstart)) {
729 gettimeofday(&bwstart, NULL);
730 return;
731 }
732
733 lamt += amount;
734 if (lamt < thresh)
735 return;
736
737 gettimeofday(&bwend, NULL);
738 timersub(&bwend, &bwstart, &bwend);
739 if (!timerisset(&bwend))
740 return;
741
742 lamt *= 8;
ca75d7de 743 waitlen = (double)1000000L * lamt / limit_rate;
6ea3c52a 744
ca75d7de 745 bwstart.tv_sec = waitlen / 1000000L;
746 bwstart.tv_usec = waitlen % 1000000L;
6ea3c52a 747
748 if (timercmp(&bwstart, &bwend, >)) {
749 timersub(&bwstart, &bwend, &bwend);
750
751 /* Adjust the wait time */
752 if (bwend.tv_sec) {
753 thresh /= 2;
754 if (thresh < 2048)
755 thresh = 2048;
756 } else if (bwend.tv_usec < 100) {
757 thresh *= 2;
758 if (thresh > 32768)
759 thresh = 32768;
760 }
761
762 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
763 while (nanosleep(&ts, &rm) == -1) {
764 if (errno != EINTR)
765 break;
766 ts = rm;
767 }
768 }
769
770 lamt = 0;
771 gettimeofday(&bwstart, NULL);
772}
773
8efc0c15 774void
cf3248b8 775sink(int argc, char **argv)
8efc0c15 776{
777 static BUF buffer;
778 struct stat stb;
5260325f 779 enum {
780 YES, NO, DISPLAYED
781 } wrerr;
8efc0c15 782 BUF *bp;
05624c18 783 off_t i;
2ceb8101 784 size_t j, count;
785 int amt, exists, first, mask, mode, ofd, omode;
b65c3807 786 off_t size, statbytes;
14a9a859 787 int setimes, targisdir, wrerrno = 0;
8efc0c15 788 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
188adeb2 789 struct timeval tv[2];
8efc0c15 790
36967a16 791#define atime tv[0]
792#define mtime tv[1]
007607ab 793#define SCREWUP(str) { why = str; goto screwup; }
8efc0c15 794
795 setimes = targisdir = 0;
796 mask = umask(0);
797 if (!pflag)
5260325f 798 (void) umask(mask);
8efc0c15 799 if (argc != 1) {
800 run_err("ambiguous target");
801 exit(1);
802 }
803 targ = *argv;
804 if (targetshouldbedirectory)
805 verifydir(targ);
5260325f 806
dc54438a 807 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 808 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
809 targisdir = 1;
810 for (first = 1;; first = 0) {
811 cp = buf;
05624c18 812 if (atomicio(read, remin, cp, 1) != 1)
8efc0c15 813 return;
814 if (*cp++ == '\n')
815 SCREWUP("unexpected <newline>");
816 do {
1d1ffb87 817 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 818 SCREWUP("lost connection");
819 *cp++ = ch;
820 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
821 *cp = 0;
f09aa22c 822 if (verbose_mode)
823 fprintf(stderr, "Sink: %s", buf);
8efc0c15 824
825 if (buf[0] == '\01' || buf[0] == '\02') {
826 if (iamremote == 0)
dc54438a 827 (void) atomicio(vwrite, STDERR_FILENO,
71c0d06a 828 buf + 1, strlen(buf + 1));
8efc0c15 829 if (buf[0] == '\02')
830 exit(1);
831 ++errs;
832 continue;
833 }
834 if (buf[0] == 'E') {
dc54438a 835 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 836 return;
837 }
8efc0c15 838 if (ch == '\n')
839 *--cp = 0;
840
8efc0c15 841 cp = buf;
842 if (*cp == 'T') {
843 setimes++;
844 cp++;
36967a16 845 mtime.tv_sec = strtol(cp, &cp, 10);
846 if (!cp || *cp++ != ' ')
8efc0c15 847 SCREWUP("mtime.sec not delimited");
36967a16 848 mtime.tv_usec = strtol(cp, &cp, 10);
849 if (!cp || *cp++ != ' ')
8efc0c15 850 SCREWUP("mtime.usec not delimited");
36967a16 851 atime.tv_sec = strtol(cp, &cp, 10);
852 if (!cp || *cp++ != ' ')
8efc0c15 853 SCREWUP("atime.sec not delimited");
36967a16 854 atime.tv_usec = strtol(cp, &cp, 10);
855 if (!cp || *cp++ != '\0')
8efc0c15 856 SCREWUP("atime.usec not delimited");
dc54438a 857 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 858 continue;
859 }
860 if (*cp != 'C' && *cp != 'D') {
861 /*
862 * Check for the case "rcp remote:foo\* local:bar".
863 * In this case, the line "No match." can be returned
864 * by the shell before the rcp command on the remote is
865 * executed so the ^Aerror_message convention isn't
866 * followed.
867 */
868 if (first) {
869 run_err("%s", cp);
870 exit(1);
871 }
872 SCREWUP("expected control record");
873 }
874 mode = 0;
875 for (++cp; cp < buf + 5; cp++) {
876 if (*cp < '0' || *cp > '7')
877 SCREWUP("bad mode");
878 mode = (mode << 3) | (*cp - '0');
879 }
880 if (*cp++ != ' ')
881 SCREWUP("mode not delimited");
882
e5ff6ecf 883 for (size = 0; isdigit(*cp);)
8efc0c15 884 size = size * 10 + (*cp++ - '0');
885 if (*cp++ != ' ')
886 SCREWUP("size not delimited");
f09aa22c 887 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
888 run_err("error: unexpected filename: %s", cp);
889 exit(1);
890 }
8efc0c15 891 if (targisdir) {
892 static char *namebuf;
2ceb8101 893 static size_t cursize;
8efc0c15 894 size_t need;
895
896 need = strlen(targ) + strlen(cp) + 250;
0ed28836 897 if (need > cursize) {
898 if (namebuf)
899 xfree(namebuf);
5260325f 900 namebuf = xmalloc(need);
0ed28836 901 cursize = need;
902 }
903 (void) snprintf(namebuf, need, "%s%s%s", targ,
39f9599a 904 strcmp(targ, "/") ? "/" : "", cp);
8efc0c15 905 np = namebuf;
906 } else
907 np = targ;
908 curfile = cp;
909 exists = stat(np, &stb) == 0;
910 if (buf[0] == 'D') {
911 int mod_flag = pflag;
f09aa22c 912 if (!iamrecursive)
913 SCREWUP("received directory without -r");
8efc0c15 914 if (exists) {
915 if (!S_ISDIR(stb.st_mode)) {
916 errno = ENOTDIR;
917 goto bad;
918 }
919 if (pflag)
5260325f 920 (void) chmod(np, mode);
8efc0c15 921 } else {
5260325f 922 /* Handle copying from a read-only
923 directory */
8efc0c15 924 mod_flag = 1;
925 if (mkdir(np, mode | S_IRWXU) < 0)
926 goto bad;
927 }
5c470997 928 vect[0] = xstrdup(np);
8efc0c15 929 sink(1, vect);
930 if (setimes) {
931 setimes = 0;
e68225b2 932 if (utimes(vect[0], tv) < 0)
5260325f 933 run_err("%s: set times: %s",
e68225b2 934 vect[0], strerror(errno));
8efc0c15 935 }
936 if (mod_flag)
e68225b2 937 (void) chmod(vect[0], mode);
938 if (vect[0])
939 xfree(vect[0]);
8efc0c15 940 continue;
941 }
942 omode = mode;
943 mode |= S_IWRITE;
3e4fc5f9 944 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
8efc0c15 945bad: run_err("%s: %s", np, strerror(errno));
946 continue;
947 }
dc54438a 948 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 949 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
5260325f 950 (void) close(ofd);
8efc0c15 951 continue;
952 }
953 cp = bp->buf;
954 wrerr = NO;
955
8efc0c15 956 statbytes = 0;
b65c3807 957 if (showprogress)
958 start_progress_meter(curfile, size, &statbytes);
8efc0c15 959 for (count = i = 0; i < size; i += 4096) {
960 amt = 4096;
961 if (i + amt > size)
962 amt = size - i;
963 count += amt;
964 do {
f581b6e8 965 j = atomicio(read, remin, cp, amt);
05624c18 966 if (j == 0) {
8efc0c15 967 run_err("%s", j ? strerror(errno) :
e5ff6ecf 968 "dropped connection");
8efc0c15 969 exit(1);
970 }
971 amt -= j;
972 cp += j;
5260325f 973 statbytes += j;
8efc0c15 974 } while (amt > 0);
b6453d99 975
10adbb52 976 if (limit_rate)
6ea3c52a 977 bwlimit(4096);
978
8efc0c15 979 if (count == bp->cnt) {
980 /* Keep reading so we stay sync'd up. */
981 if (wrerr == NO) {
05624c18 982 if (atomicio(vwrite, ofd, bp->buf,
983 count) != count) {
8efc0c15 984 wrerr = YES;
05624c18 985 wrerrno = errno;
8efc0c15 986 }
987 }
988 count = 0;
989 cp = bp->buf;
990 }
991 }
992 if (showprogress)
b65c3807 993 stop_progress_meter();
8efc0c15 994 if (count != 0 && wrerr == NO &&
05624c18 995 atomicio(vwrite, ofd, bp->buf, count) != count) {
8efc0c15 996 wrerr = YES;
05624c18 997 wrerrno = errno;
8efc0c15 998 }
25a6efd8 999 if (wrerr == NO && ftruncate(ofd, size) != 0) {
8efc0c15 1000 run_err("%s: truncate: %s", np, strerror(errno));
1001 wrerr = DISPLAYED;
1002 }
8efc0c15 1003 if (pflag) {
1004 if (exists || omode != mode)
77bb0bca 1005#ifdef HAVE_FCHMOD
7e693c81 1006 if (fchmod(ofd, omode)) {
77bb0bca 1007#else /* HAVE_FCHMOD */
7e693c81 1008 if (chmod(np, omode)) {
77bb0bca 1009#endif /* HAVE_FCHMOD */
8efc0c15 1010 run_err("%s: set mode: %s",
e5ff6ecf 1011 np, strerror(errno));
7e693c81 1012 wrerr = DISPLAYED;
1013 }
8efc0c15 1014 } else {
1015 if (!exists && omode != mode)
77bb0bca 1016#ifdef HAVE_FCHMOD
7e693c81 1017 if (fchmod(ofd, omode & ~mask)) {
77bb0bca 1018#else /* HAVE_FCHMOD */
7e693c81 1019 if (chmod(np, omode & ~mask)) {
77bb0bca 1020#endif /* HAVE_FCHMOD */
8efc0c15 1021 run_err("%s: set mode: %s",
e5ff6ecf 1022 np, strerror(errno));
7e693c81 1023 wrerr = DISPLAYED;
1024 }
8efc0c15 1025 }
704b1659 1026 if (close(ofd) == -1) {
1027 wrerr = YES;
1028 wrerrno = errno;
1029 }
5260325f 1030 (void) response();
8efc0c15 1031 if (setimes && wrerr == NO) {
1032 setimes = 0;
188adeb2 1033 if (utimes(np, tv) < 0) {
8efc0c15 1034 run_err("%s: set times: %s",
e5ff6ecf 1035 np, strerror(errno));
8efc0c15 1036 wrerr = DISPLAYED;
1037 }
1038 }
5260325f 1039 switch (wrerr) {
8efc0c15 1040 case YES:
1041 run_err("%s: %s", np, strerror(wrerrno));
1042 break;
1043 case NO:
dc54438a 1044 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 1045 break;
1046 case DISPLAYED:
1047 break;
1048 }
1049 }
1050screwup:
1051 run_err("protocol error: %s", why);
1052 exit(1);
1053}
1054
1055int
d5bb9418 1056response(void)
8efc0c15 1057{
1058 char ch, *cp, resp, rbuf[2048];
1059
1d1ffb87 1060 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
8efc0c15 1061 lostconn(0);
1062
1063 cp = rbuf;
5260325f 1064 switch (resp) {
1065 case 0: /* ok */
8efc0c15 1066 return (0);
1067 default:
1068 *cp++ = resp;
1069 /* FALLTHROUGH */
5260325f 1070 case 1: /* error, followed by error msg */
1071 case 2: /* fatal error, "" */
8efc0c15 1072 do {
1d1ffb87 1073 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 1074 lostconn(0);
1075 *cp++ = ch;
1076 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1077
1078 if (!iamremote)
dc54438a 1079 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
8efc0c15 1080 ++errs;
1081 if (resp == 1)
1082 return (-1);
1083 exit(1);
1084 }
1085 /* NOTREACHED */
1086}
1087
1088void
d5bb9418 1089usage(void)
8efc0c15 1090{
f1278af7 1091 (void) fprintf(stderr,
433e60ac 1092 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1093 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
3015d321 1094 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
8efc0c15 1095 exit(1);
1096}
1097
1098void
5260325f 1099run_err(const char *fmt,...)
8efc0c15 1100{
1101 static FILE *fp;
1102 va_list ap;
8efc0c15 1103
1104 ++errs;
1105 if (fp == NULL && !(fp = fdopen(remout, "w")))
1106 return;
5260325f 1107 (void) fprintf(fp, "%c", 0x01);
1108 (void) fprintf(fp, "scp: ");
b92964b7 1109 va_start(ap, fmt);
5260325f 1110 (void) vfprintf(fp, fmt, ap);
b92964b7 1111 va_end(ap);
5260325f 1112 (void) fprintf(fp, "\n");
1113 (void) fflush(fp);
1114
1115 if (!iamremote) {
b92964b7 1116 va_start(ap, fmt);
5260325f 1117 vfprintf(stderr, fmt, ap);
b92964b7 1118 va_end(ap);
5260325f 1119 fprintf(stderr, "\n");
1120 }
8efc0c15 1121}
1122
8efc0c15 1123void
cf3248b8 1124verifydir(char *cp)
8efc0c15 1125{
1126 struct stat stb;
1127
1128 if (!stat(cp, &stb)) {
1129 if (S_ISDIR(stb.st_mode))
1130 return;
1131 errno = ENOTDIR;
1132 }
1133 run_err("%s: %s", cp, strerror(errno));
8f4ab41b 1134 killchild(0);
8efc0c15 1135}
1136
1137int
cf3248b8 1138okname(char *cp0)
8efc0c15 1139{
1140 int c;
1141 char *cp;
1142
1143 cp = cp0;
1144 do {
cb220a93 1145 c = (int)*cp;
8efc0c15 1146 if (c & 0200)
1147 goto bad;
0ec7661a 1148 if (!isalpha(c) && !isdigit(c)) {
1149 switch (c) {
1150 case '\'':
1151 case '"':
1152 case '`':
1153 case ' ':
1154 case '#':
1155 goto bad;
1156 default:
1157 break;
1158 }
1159 }
8efc0c15 1160 } while (*++cp);
1161 return (1);
1162
c8d54615 1163bad: fprintf(stderr, "%s: invalid user name\n", cp0);
8efc0c15 1164 return (0);
1165}
1166
1167BUF *
cf3248b8 1168allocbuf(BUF *bp, int fd, int blksize)
8efc0c15 1169{
1170 size_t size;
98a7c37b 1171#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
8efc0c15 1172 struct stat stb;
1173
1174 if (fstat(fd, &stb) < 0) {
1175 run_err("fstat: %s", strerror(errno));
1176 return (0);
1177 }
a0a14bcd 1178 size = roundup(stb.st_blksize, blksize);
1179 if (size == 0)
5260325f 1180 size = blksize;
98a7c37b 1181#else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2b87da3b 1182 size = blksize;
98a7c37b 1183#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
8efc0c15 1184 if (bp->cnt >= size)
1185 return (bp);
5260325f 1186 if (bp->buf == NULL)
1187 bp->buf = xmalloc(size);
1188 else
1189 bp->buf = xrealloc(bp->buf, size);
46660a9e 1190 memset(bp->buf, 0, size);
8efc0c15 1191 bp->cnt = size;
1192 return (bp);
1193}
1194
1195void
cf3248b8 1196lostconn(int signo)
8efc0c15 1197{
1198 if (!iamremote)
08c260ea 1199 write(STDERR_FILENO, "lost connection\n", 16);
1200 if (signo)
1201 _exit(1);
1202 else
1203 exit(1);
8efc0c15 1204}
This page took 1.595385 seconds and 5 git commands to generate.