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