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