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