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