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