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