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