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