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