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