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