]> andersk Git - openssh.git/blame - scp.c
Diff hunk which slipped thru
[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"
74fc9186 48RCSID("$OpenBSD: scp.c,v 1.32 2000/06/20 01:39:44 markus 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 }
5260325f 892 (void) close(ofd);
893 (void) response();
8efc0c15 894 if (setimes && wrerr == NO) {
895 setimes = 0;
896 if (utime(np, &ut) < 0) {
897 run_err("%s: set times: %s",
5260325f 898 np, strerror(errno));
8efc0c15 899 wrerr = DISPLAYED;
900 }
901 }
5260325f 902 switch (wrerr) {
8efc0c15 903 case YES:
904 run_err("%s: %s", np, strerror(wrerrno));
905 break;
906 case NO:
3189621b 907 (void) atomicio(write, remout, "", 1);
8efc0c15 908 break;
909 case DISPLAYED:
910 break;
911 }
912 }
913screwup:
914 run_err("protocol error: %s", why);
915 exit(1);
916}
917
918int
919response()
920{
921 char ch, *cp, resp, rbuf[2048];
922
1d1ffb87 923 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
8efc0c15 924 lostconn(0);
925
926 cp = rbuf;
5260325f 927 switch (resp) {
928 case 0: /* ok */
8efc0c15 929 return (0);
930 default:
931 *cp++ = resp;
932 /* FALLTHROUGH */
5260325f 933 case 1: /* error, followed by error msg */
934 case 2: /* fatal error, "" */
8efc0c15 935 do {
1d1ffb87 936 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 937 lostconn(0);
938 *cp++ = ch;
939 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
940
941 if (!iamremote)
3189621b 942 (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
8efc0c15 943 ++errs;
944 if (resp == 1)
945 return (-1);
946 exit(1);
947 }
948 /* NOTREACHED */
949}
950
951void
952usage()
953{
5260325f 954 (void) fprintf(stderr,
48e671d5 955 "usage: scp [-pqrvC46] [-P port] [-c cipher] [-i identity] f1 f2; or:\n scp [options] f1 ... fn directory\n");
8efc0c15 956 exit(1);
957}
958
959void
5260325f 960run_err(const char *fmt,...)
8efc0c15 961{
962 static FILE *fp;
963 va_list ap;
8efc0c15 964
965 ++errs;
966 if (fp == NULL && !(fp = fdopen(remout, "w")))
967 return;
5260325f 968 (void) fprintf(fp, "%c", 0x01);
969 (void) fprintf(fp, "scp: ");
b92964b7 970 va_start(ap, fmt);
5260325f 971 (void) vfprintf(fp, fmt, ap);
b92964b7 972 va_end(ap);
5260325f 973 (void) fprintf(fp, "\n");
974 (void) fflush(fp);
975
976 if (!iamremote) {
b92964b7 977 va_start(ap, fmt);
5260325f 978 vfprintf(stderr, fmt, ap);
b92964b7 979 va_end(ap);
5260325f 980 fprintf(stderr, "\n");
981 }
8efc0c15 982}
983
984/* Stuff below is from BSD rcp util.c. */
985
986/*-
987 * Copyright (c) 1992, 1993
988 * The Regents of the University of California. All rights reserved.
989 *
990 * Redistribution and use in source and binary forms, with or without
991 * modification, are permitted provided that the following conditions
992 * are met:
993 * 1. Redistributions of source code must retain the above copyright
994 * notice, this list of conditions and the following disclaimer.
995 * 2. Redistributions in binary form must reproduce the above copyright
996 * notice, this list of conditions and the following disclaimer in the
997 * documentation and/or other materials provided with the distribution.
998 * 3. All advertising materials mentioning features or use of this software
999 * must display the following acknowledgement:
1000 * This product includes software developed by the University of
1001 * California, Berkeley and its contributors.
1002 * 4. Neither the name of the University nor the names of its contributors
1003 * may be used to endorse or promote products derived from this software
1004 * without specific prior written permission.
1005 *
1006 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
1007 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1008 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1009 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
1010 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1011 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1012 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1013 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1014 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1015 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1016 * SUCH DAMAGE.
1017 *
74fc9186 1018 * $OpenBSD: scp.c,v 1.32 2000/06/20 01:39:44 markus Exp $
8efc0c15 1019 */
1020
1021char *
1022colon(cp)
1023 char *cp;
1024{
48e671d5 1025 int flag = 0;
1026
8efc0c15 1027 if (*cp == ':') /* Leading colon is part of file name. */
1028 return (0);
48e671d5 1029 if (*cp == '[')
1030 flag = 1;
8efc0c15 1031
1032 for (; *cp; ++cp) {
48e671d5 1033 if (*cp == '@' && *(cp+1) == '[')
1034 flag = 1;
1035 if (*cp == ']' && *(cp+1) == ':' && flag)
1036 return (cp+1);
1037 if (*cp == ':' && !flag)
8efc0c15 1038 return (cp);
1039 if (*cp == '/')
1040 return (0);
1041 }
1042 return (0);
1043}
1044
1045void
1046verifydir(cp)
1047 char *cp;
1048{
1049 struct stat stb;
1050
1051 if (!stat(cp, &stb)) {
1052 if (S_ISDIR(stb.st_mode))
1053 return;
1054 errno = ENOTDIR;
1055 }
1056 run_err("%s: %s", cp, strerror(errno));
1057 exit(1);
1058}
1059
1060int
1061okname(cp0)
1062 char *cp0;
1063{
1064 int c;
1065 char *cp;
1066
1067 cp = cp0;
1068 do {
1069 c = *cp;
1070 if (c & 0200)
1071 goto bad;
1072 if (!isalpha(c) && !isdigit(c) && c != '_' && c != '-')
1073 goto bad;
1074 } while (*++cp);
1075 return (1);
1076
c8d54615 1077bad: fprintf(stderr, "%s: invalid user name\n", cp0);
8efc0c15 1078 return (0);
1079}
1080
1081BUF *
1082allocbuf(bp, fd, blksize)
1083 BUF *bp;
1084 int fd, blksize;
1085{
1086 size_t size;
1087 struct stat stb;
1088
1089 if (fstat(fd, &stb) < 0) {
1090 run_err("fstat: %s", strerror(errno));
1091 return (0);
1092 }
5260325f 1093 if (stb.st_blksize == 0)
1094 size = blksize;
1095 else
1096 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1097 stb.st_blksize;
8efc0c15 1098 if (bp->cnt >= size)
1099 return (bp);
5260325f 1100 if (bp->buf == NULL)
1101 bp->buf = xmalloc(size);
1102 else
1103 bp->buf = xrealloc(bp->buf, size);
8efc0c15 1104 bp->cnt = size;
1105 return (bp);
1106}
1107
1108void
1109lostconn(signo)
1110 int signo;
1111{
1112 if (!iamremote)
1113 fprintf(stderr, "lost connection\n");
1114 exit(1);
1115}
1116
8efc0c15 1117
1118void
1119alarmtimer(int wait)
1120{
5260325f 1121 struct itimerval itv;
8efc0c15 1122
5260325f 1123 itv.it_value.tv_sec = wait;
1124 itv.it_value.tv_usec = 0;
1125 itv.it_interval = itv.it_value;
1126 setitimer(ITIMER_REAL, &itv, NULL);
8efc0c15 1127}
1128
1129void
610cd5c6 1130updateprogressmeter(int ignore)
8efc0c15 1131{
1132 int save_errno = errno;
1133
1134 progressmeter(0);
1135 errno = save_errno;
1136}
1137
2bd61362 1138int
1139foregroundproc()
1140{
1141 static pid_t pgrp = -1;
1142 int ctty_pgrp;
1143
1144 if (pgrp == -1)
1145 pgrp = getpgrp();
1146
5260325f 1147 return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1148 ctty_pgrp == pgrp));
2bd61362 1149}
1150
8efc0c15 1151void
1152progressmeter(int flag)
1153{
1154 static const char prefixes[] = " KMGTP";
1155 static struct timeval lastupdate;
1156 static off_t lastsize;
1157 struct timeval now, td, wait;
1158 off_t cursize, abbrevsize;
1159 double elapsed;
b6573a35 1160 int ratio, barlength, i, remaining;
8efc0c15 1161 char buf[256];
1162
1163 if (flag == -1) {
5260325f 1164 (void) gettimeofday(&start, (struct timezone *) 0);
8efc0c15 1165 lastupdate = start;
1166 lastsize = 0;
5260325f 1167 }
2bd61362 1168 if (foregroundproc() == 0)
1169 return;
1170
5260325f 1171 (void) gettimeofday(&now, (struct timezone *) 0);
8efc0c15 1172 cursize = statbytes;
b4ad3727 1173 if (totalbytes != 0) {
aa3378df 1174 ratio = 100.0 * cursize / totalbytes;
8efc0c15 1175 ratio = MAX(ratio, 0);
1176 ratio = MIN(ratio, 100);
5260325f 1177 } else
8efc0c15 1178 ratio = 100;
1179
5260325f 1180 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
8efc0c15 1181
1182 barlength = getttywidth() - 51;
a4070484 1183 barlength = (barlength <= MAX_BARLENGTH)?barlength:MAX_BARLENGTH;
8efc0c15 1184 if (barlength > 0) {
1185 i = barlength * ratio / 100;
1186 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
a4070484 1187 "|%.*s%*s|", i, BAR, barlength - i, "");
8efc0c15 1188 }
8efc0c15 1189 i = 0;
1190 abbrevsize = cursize;
1191 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1192 i++;
1193 abbrevsize >>= 10;
1194 }
68227e6d 1195 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5d %c%c ",
1196 (int) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' :
5260325f 1197 'B');
8efc0c15 1198
1199 timersub(&now, &lastupdate, &wait);
1200 if (cursize > lastsize) {
1201 lastupdate = now;
1202 lastsize = cursize;
1203 if (wait.tv_sec >= STALLTIME) {
1204 start.tv_sec += wait.tv_sec;
1205 start.tv_usec += wait.tv_usec;
1206 }
1207 wait.tv_sec = 0;
1208 }
8efc0c15 1209 timersub(&now, &start, &td);
1210 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1211
1212 if (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes) {
1213 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
5260325f 1214 " --:-- ETA");
8efc0c15 1215 } else if (wait.tv_sec >= STALLTIME) {
1216 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
5260325f 1217 " - stalled -");
8efc0c15 1218 } else {
d6f24e45 1219 if (flag != 1)
1220 remaining =
1221 (int)(totalbytes / (statbytes / elapsed) - elapsed);
1222 else
1223 remaining = elapsed;
1224
5068f573 1225 i = remaining / 3600;
8efc0c15 1226 if (i)
1227 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
5260325f 1228 "%2d:", i);
8efc0c15 1229 else
1230 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
5260325f 1231 " ");
8efc0c15 1232 i = remaining % 3600;
1233 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
d6f24e45 1234 "%02d:%02d%s", i / 60, i % 60,
1235 (flag != 1) ? " ETA" : " ");
8efc0c15 1236 }
1237 atomicio(write, fileno(stdout), buf, strlen(buf));
1238
1239 if (flag == -1) {
68227e6d 1240 struct sigaction sa;
1241 sa.sa_handler = updateprogressmeter;
1242 sigemptyset(&sa.sa_mask);
c04f75f1 1243#ifdef SA_RESTART
68227e6d 1244 sa.sa_flags = SA_RESTART;
c04f75f1 1245#endif
68227e6d 1246 sigaction(SIGALRM, &sa, NULL);
8efc0c15 1247 alarmtimer(1);
1248 } else if (flag == 1) {
1249 alarmtimer(0);
3189621b 1250 atomicio(write, fileno(stdout), "\n", 1);
8efc0c15 1251 statbytes = 0;
1252 }
1253}
1254
1255int
1256getttywidth(void)
1257{
1258 struct winsize winsize;
1259
1260 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
5260325f 1261 return (winsize.ws_col ? winsize.ws_col : 80);
8efc0c15 1262 else
5260325f 1263 return (80);
8efc0c15 1264}
This page took 0.261302 seconds and 5 git commands to generate.