]> andersk Git - openssh.git/blame - scp.c
- deraadt@cvs.openbsd.org 2001/02/04 16:56:23
[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"
6a416424 78RCSID("$OpenBSD: scp.c,v 1.53 2001/02/04 23:56:22 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". */
5260325f 329 (void) sprintf(cmd, "scp%s%s%s%s", verbose_mode ? " -v" : "",
2e73a022 330 iamrecursive ? " -r" : "", pflag ? " -p" : "",
331 targetshouldbedirectory ? " -d" : "");
8efc0c15 332
5260325f 333 (void) signal(SIGPIPE, lostconn);
8efc0c15 334
335 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
336 toremote(targ, argc, argv);
337 else {
5260325f 338 tolocal(argc, argv); /* Dest is local host. */
8efc0c15 339 if (targetshouldbedirectory)
340 verifydir(argv[argc - 1]);
341 }
342 exit(errs != 0);
343}
344
48e671d5 345char *
346cleanhostname(host)
347 char *host;
348{
349 if (*host == '[' && host[strlen(host) - 1] == ']') {
350 host[strlen(host) - 1] = '\0';
351 return (host + 1);
352 } else
353 return host;
354}
355
8efc0c15 356void
357toremote(targ, argc, argv)
358 char *targ, *argv[];
359 int argc;
360{
361 int i, len;
362 char *bp, *host, *src, *suser, *thost, *tuser;
363
364 *targ++ = 0;
365 if (*targ == 0)
366 targ = ".";
367
368 if ((thost = strchr(argv[argc - 1], '@'))) {
369 /* user@host */
370 *thost++ = 0;
371 tuser = argv[argc - 1];
372 if (*tuser == '\0')
373 tuser = NULL;
374 else if (!okname(tuser))
375 exit(1);
376 } else {
377 thost = argv[argc - 1];
378 tuser = NULL;
379 }
380
381 for (i = 0; i < argc - 1; i++) {
382 src = colon(argv[i]);
5260325f 383 if (src) { /* remote to remote */
8efc0c15 384 *src++ = 0;
385 if (*src == 0)
386 src = ".";
387 host = strchr(argv[i], '@');
2e73a022 388 len = strlen(ssh_program) + strlen(argv[i]) +
389 strlen(src) + (tuser ? strlen(tuser) : 0) +
390 strlen(thost) + strlen(targ) + CMDNEEDS + 32;
5260325f 391 bp = xmalloc(len);
8efc0c15 392 if (host) {
393 *host++ = 0;
48e671d5 394 host = cleanhostname(host);
8efc0c15 395 suser = argv[i];
396 if (*suser == '\0')
397 suser = pwd->pw_name;
398 else if (!okname(suser))
399 continue;
71c0d06a 400 sprintf(bp,
2e73a022 401 "%s%s -x -o'FallBackToRsh no' -n -l %s %s %s %s '%s%s%s:%s'",
71c0d06a 402 ssh_program, verbose_mode ? " -v" : "",
403 suser, host, cmd, src,
404 tuser ? tuser : "", tuser ? "@" : "",
405 thost, targ);
48e671d5 406 } else {
407 host = cleanhostname(argv[i]);
71c0d06a 408 sprintf(bp,
2e73a022 409 "exec %s%s -x -o'FallBackToRsh no' -n %s %s %s '%s%s%s:%s'",
71c0d06a 410 ssh_program, verbose_mode ? " -v" : "",
411 host, cmd, src,
412 tuser ? tuser : "", tuser ? "@" : "",
413 thost, targ);
48e671d5 414 }
5260325f 415 if (verbose_mode)
416 fprintf(stderr, "Executing: %s\n", bp);
417 (void) system(bp);
418 (void) xfree(bp);
419 } else { /* local to remote */
8efc0c15 420 if (remin == -1) {
421 len = strlen(targ) + CMDNEEDS + 20;
5260325f 422 bp = xmalloc(len);
423 (void) sprintf(bp, "%s -t %s", cmd, targ);
48e671d5 424 host = cleanhostname(thost);
2e73a022 425 if (do_cmd(host, tuser, bp, &remin,
426 &remout, argc) < 0)
5260325f 427 exit(1);
8efc0c15 428 if (response() < 0)
429 exit(1);
5260325f 430 (void) xfree(bp);
8efc0c15 431 }
5260325f 432 source(1, argv + i);
8efc0c15 433 }
434 }
435}
436
437void
438tolocal(argc, argv)
439 int argc;
440 char *argv[];
441{
442 int i, len;
443 char *bp, *host, *src, *suser;
444
445 for (i = 0; i < argc - 1; i++) {
5260325f 446 if (!(src = colon(argv[i]))) { /* Local to local. */
8efc0c15 447 len = strlen(_PATH_CP) + strlen(argv[i]) +
2e73a022 448 strlen(argv[argc - 1]) + 20;
8efc0c15 449 bp = xmalloc(len);
5260325f 450 (void) sprintf(bp, "exec %s%s%s %s %s", _PATH_CP,
2e73a022 451 iamrecursive ? " -r" : "", pflag ? " -p" : "",
452 argv[i], argv[argc - 1]);
5260325f 453 if (verbose_mode)
454 fprintf(stderr, "Executing: %s\n", bp);
8efc0c15 455 if (system(bp))
456 ++errs;
5260325f 457 (void) xfree(bp);
8efc0c15 458 continue;
459 }
460 *src++ = 0;
461 if (*src == 0)
462 src = ".";
463 if ((host = strchr(argv[i], '@')) == NULL) {
464 host = argv[i];
465 suser = NULL;
466 } else {
467 *host++ = 0;
468 suser = argv[i];
469 if (*suser == '\0')
470 suser = pwd->pw_name;
471 else if (!okname(suser))
472 continue;
473 }
48e671d5 474 host = cleanhostname(host);
8efc0c15 475 len = strlen(src) + CMDNEEDS + 20;
5260325f 476 bp = xmalloc(len);
477 (void) sprintf(bp, "%s -f %s", cmd, src);
2e73a022 478 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
5260325f 479 (void) xfree(bp);
480 ++errs;
481 continue;
8efc0c15 482 }
5260325f 483 xfree(bp);
8efc0c15 484 sink(1, argv + argc - 1);
5260325f 485 (void) close(remin);
8efc0c15 486 remin = remout = -1;
487 }
488}
489
490void
491source(argc, argv)
492 int argc;
493 char *argv[];
494{
495 struct stat stb;
496 static BUF buffer;
497 BUF *bp;
498 off_t i;
499 int amt, fd, haderr, indx, result;
500 char *last, *name, buf[2048];
501
502 for (indx = 0; indx < argc; ++indx) {
5260325f 503 name = argv[indx];
8efc0c15 504 statbytes = 0;
505 if ((fd = open(name, O_RDONLY, 0)) < 0)
506 goto syserr;
507 if (fstat(fd, &stb) < 0) {
508syserr: run_err("%s: %s", name, strerror(errno));
509 goto next;
510 }
511 switch (stb.st_mode & S_IFMT) {
512 case S_IFREG:
513 break;
514 case S_IFDIR:
515 if (iamrecursive) {
516 rsource(name, &stb);
517 goto next;
518 }
519 /* FALLTHROUGH */
520 default:
521 run_err("%s: not a regular file", name);
522 goto next;
523 }
524 if ((last = strrchr(name, '/')) == NULL)
525 last = name;
526 else
527 ++last;
528 curfile = last;
529 if (pflag) {
530 /*
531 * Make it compatible with possible future
532 * versions expecting microseconds.
533 */
5260325f 534 (void) sprintf(buf, "T%lu 0 %lu 0\n",
1e3b8b07 535 (u_long) stb.st_mtime,
536 (u_long) stb.st_atime);
3189621b 537 (void) atomicio(write, remout, buf, strlen(buf));
8efc0c15 538 if (response() < 0)
539 goto next;
540 }
541#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
71c0d06a 542 sprintf(buf, "C%04o %lu %s\n",
1e3b8b07 543 (u_int) (stb.st_mode & FILEMODEMASK),
544 (u_long) stb.st_size, last);
5260325f 545 if (verbose_mode) {
546 fprintf(stderr, "Sending file modes: %s", buf);
547 fflush(stderr);
548 }
3189621b 549 (void) atomicio(write, remout, buf, strlen(buf));
8efc0c15 550 if (response() < 0)
551 goto next;
552 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
5260325f 553next: (void) close(fd);
8efc0c15 554 continue;
555 }
8efc0c15 556 if (showprogress) {
557 totalbytes = stb.st_size;
558 progressmeter(-1);
559 }
8efc0c15 560 /* Keep writing after an error so that we stay sync'd up. */
561 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
562 amt = bp->cnt;
563 if (i + amt > stb.st_size)
564 amt = stb.st_size - i;
565 if (!haderr) {
1d1ffb87 566 result = atomicio(read, fd, bp->buf, amt);
8efc0c15 567 if (result != amt)
568 haderr = result >= 0 ? EIO : errno;
569 }
570 if (haderr)
3189621b 571 (void) atomicio(write, remout, bp->buf, amt);
8efc0c15 572 else {
68227e6d 573 result = atomicio(write, remout, bp->buf, amt);
8efc0c15 574 if (result != amt)
575 haderr = result >= 0 ? EIO : errno;
576 statbytes += result;
577 }
578 }
5260325f 579 if (showprogress)
8efc0c15 580 progressmeter(1);
581
582 if (close(fd) < 0 && !haderr)
583 haderr = errno;
584 if (!haderr)
3189621b 585 (void) atomicio(write, remout, "", 1);
8efc0c15 586 else
587 run_err("%s: %s", name, strerror(haderr));
5260325f 588 (void) response();
8efc0c15 589 }
590}
591
592void
593rsource(name, statp)
594 char *name;
595 struct stat *statp;
596{
597 DIR *dirp;
598 struct dirent *dp;
599 char *last, *vect[1], path[1100];
600
601 if (!(dirp = opendir(name))) {
602 run_err("%s: %s", name, strerror(errno));
603 return;
604 }
605 last = strrchr(name, '/');
606 if (last == 0)
607 last = name;
608 else
609 last++;
610 if (pflag) {
5260325f 611 (void) sprintf(path, "T%lu 0 %lu 0\n",
1e3b8b07 612 (u_long) statp->st_mtime,
613 (u_long) statp->st_atime);
3189621b 614 (void) atomicio(write, remout, path, strlen(path));
8efc0c15 615 if (response() < 0) {
616 closedir(dirp);
617 return;
618 }
619 }
5260325f 620 (void) sprintf(path, "D%04o %d %.1024s\n",
1e3b8b07 621 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
5260325f 622 if (verbose_mode)
623 fprintf(stderr, "Entering directory: %s", path);
3189621b 624 (void) atomicio(write, remout, path, strlen(path));
8efc0c15 625 if (response() < 0) {
626 closedir(dirp);
627 return;
628 }
629 while ((dp = readdir(dirp))) {
630 if (dp->d_ino == 0)
631 continue;
632 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
633 continue;
634 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
635 run_err("%s/%s: name too long", name, dp->d_name);
636 continue;
637 }
5260325f 638 (void) sprintf(path, "%s/%s", name, dp->d_name);
8efc0c15 639 vect[0] = path;
640 source(1, vect);
641 }
5260325f 642 (void) closedir(dirp);
3189621b 643 (void) atomicio(write, remout, "E\n", 2);
5260325f 644 (void) response();
8efc0c15 645}
646
647void
648sink(argc, argv)
649 int argc;
650 char *argv[];
651{
652 static BUF buffer;
653 struct stat stb;
5260325f 654 enum {
655 YES, NO, DISPLAYED
656 } wrerr;
8efc0c15 657 BUF *bp;
658 off_t i, j;
659 int amt, count, exists, first, mask, mode, ofd, omode;
14a9a859 660 off_t size;
661 int setimes, targisdir, wrerrno = 0;
8efc0c15 662 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
5260325f 663 int dummy_usec;
188adeb2 664 struct timeval tv[2];
8efc0c15 665
666#define SCREWUP(str) { why = str; goto screwup; }
667
668 setimes = targisdir = 0;
669 mask = umask(0);
670 if (!pflag)
5260325f 671 (void) umask(mask);
8efc0c15 672 if (argc != 1) {
673 run_err("ambiguous target");
674 exit(1);
675 }
676 targ = *argv;
677 if (targetshouldbedirectory)
678 verifydir(targ);
5260325f 679
3189621b 680 (void) atomicio(write, remout, "", 1);
8efc0c15 681 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
682 targisdir = 1;
683 for (first = 1;; first = 0) {
684 cp = buf;
1d1ffb87 685 if (atomicio(read, remin, cp, 1) <= 0)
8efc0c15 686 return;
687 if (*cp++ == '\n')
688 SCREWUP("unexpected <newline>");
689 do {
1d1ffb87 690 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 691 SCREWUP("lost connection");
692 *cp++ = ch;
693 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
694 *cp = 0;
695
696 if (buf[0] == '\01' || buf[0] == '\02') {
697 if (iamremote == 0)
3189621b 698 (void) atomicio(write, STDERR_FILENO,
71c0d06a 699 buf + 1, strlen(buf + 1));
8efc0c15 700 if (buf[0] == '\02')
701 exit(1);
702 ++errs;
703 continue;
704 }
705 if (buf[0] == 'E') {
3189621b 706 (void) atomicio(write, remout, "", 1);
8efc0c15 707 return;
708 }
8efc0c15 709 if (ch == '\n')
710 *--cp = 0;
711
712#define getnum(t) (t) = 0; \
713 while (*cp >= '0' && *cp <= '9') (t) = (t) * 10 + (*cp++ - '0');
714 cp = buf;
715 if (*cp == 'T') {
716 setimes++;
717 cp++;
188adeb2 718 getnum(tv[1].tv_sec);
8efc0c15 719 if (*cp++ != ' ')
720 SCREWUP("mtime.sec not delimited");
721 getnum(dummy_usec);
188adeb2 722 tv[1].tv_usec = 0;
8efc0c15 723 if (*cp++ != ' ')
724 SCREWUP("mtime.usec not delimited");
188adeb2 725 getnum(tv[0].tv_sec);
8efc0c15 726 if (*cp++ != ' ')
727 SCREWUP("atime.sec not delimited");
728 getnum(dummy_usec);
188adeb2 729 tv[0].tv_usec = 0;
8efc0c15 730 if (*cp++ != '\0')
731 SCREWUP("atime.usec not delimited");
3189621b 732 (void) atomicio(write, remout, "", 1);
8efc0c15 733 continue;
734 }
735 if (*cp != 'C' && *cp != 'D') {
736 /*
737 * Check for the case "rcp remote:foo\* local:bar".
738 * In this case, the line "No match." can be returned
739 * by the shell before the rcp command on the remote is
740 * executed so the ^Aerror_message convention isn't
741 * followed.
742 */
743 if (first) {
744 run_err("%s", cp);
745 exit(1);
746 }
747 SCREWUP("expected control record");
748 }
749 mode = 0;
750 for (++cp; cp < buf + 5; cp++) {
751 if (*cp < '0' || *cp > '7')
752 SCREWUP("bad mode");
753 mode = (mode << 3) | (*cp - '0');
754 }
755 if (*cp++ != ' ')
756 SCREWUP("mode not delimited");
757
5260325f 758 for (size = 0; *cp >= '0' && *cp <= '9';)
8efc0c15 759 size = size * 10 + (*cp++ - '0');
760 if (*cp++ != ' ')
761 SCREWUP("size not delimited");
762 if (targisdir) {
763 static char *namebuf;
764 static int cursize;
765 size_t need;
766
767 need = strlen(targ) + strlen(cp) + 250;
768 if (need > cursize)
5260325f 769 namebuf = xmalloc(need);
770 (void) sprintf(namebuf, "%s%s%s", targ,
2e73a022 771 *targ ? "/" : "", cp);
8efc0c15 772 np = namebuf;
773 } else
774 np = targ;
775 curfile = cp;
776 exists = stat(np, &stb) == 0;
777 if (buf[0] == 'D') {
778 int mod_flag = pflag;
779 if (exists) {
780 if (!S_ISDIR(stb.st_mode)) {
781 errno = ENOTDIR;
782 goto bad;
783 }
784 if (pflag)
5260325f 785 (void) chmod(np, mode);
8efc0c15 786 } else {
5260325f 787 /* Handle copying from a read-only
788 directory */
8efc0c15 789 mod_flag = 1;
790 if (mkdir(np, mode | S_IRWXU) < 0)
791 goto bad;
792 }
793 vect[0] = np;
794 sink(1, vect);
795 if (setimes) {
796 setimes = 0;
188adeb2 797 if (utimes(np, tv) < 0)
5260325f 798 run_err("%s: set times: %s",
799 np, strerror(errno));
8efc0c15 800 }
801 if (mod_flag)
5260325f 802 (void) chmod(np, mode);
8efc0c15 803 continue;
804 }
805 omode = mode;
806 mode |= S_IWRITE;
5260325f 807 if ((ofd = open(np, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
8efc0c15 808bad: run_err("%s: %s", np, strerror(errno));
809 continue;
810 }
3189621b 811 (void) atomicio(write, remout, "", 1);
8efc0c15 812 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
5260325f 813 (void) close(ofd);
8efc0c15 814 continue;
815 }
816 cp = bp->buf;
817 wrerr = NO;
818
819 if (showprogress) {
820 totalbytes = size;
821 progressmeter(-1);
822 }
823 statbytes = 0;
824 for (count = i = 0; i < size; i += 4096) {
825 amt = 4096;
826 if (i + amt > size)
827 amt = size - i;
828 count += amt;
829 do {
a22aff1f 830 j = read(remin, cp, amt);
831 if (j == -1 && (errno == EINTR || errno == EAGAIN)) {
832 continue;
833 } else if (j <= 0) {
8efc0c15 834 run_err("%s", j ? strerror(errno) :
5260325f 835 "dropped connection");
8efc0c15 836 exit(1);
837 }
838 amt -= j;
839 cp += j;
5260325f 840 statbytes += j;
8efc0c15 841 } while (amt > 0);
842 if (count == bp->cnt) {
843 /* Keep reading so we stay sync'd up. */
844 if (wrerr == NO) {
1d1ffb87 845 j = atomicio(write, ofd, bp->buf, count);
8efc0c15 846 if (j != count) {
847 wrerr = YES;
5260325f 848 wrerrno = j >= 0 ? EIO : errno;
8efc0c15 849 }
850 }
851 count = 0;
852 cp = bp->buf;
853 }
854 }
855 if (showprogress)
856 progressmeter(1);
857 if (count != 0 && wrerr == NO &&
1d1ffb87 858 (j = atomicio(write, ofd, bp->buf, count)) != count) {
8efc0c15 859 wrerr = YES;
5260325f 860 wrerrno = j >= 0 ? EIO : errno;
8efc0c15 861 }
862#if 0
863 if (ftruncate(ofd, size)) {
864 run_err("%s: truncate: %s", np, strerror(errno));
865 wrerr = DISPLAYED;
866 }
867#endif
868 if (pflag) {
869 if (exists || omode != mode)
77bb0bca 870#ifdef HAVE_FCHMOD
8efc0c15 871 if (fchmod(ofd, omode))
77bb0bca 872#else /* HAVE_FCHMOD */
873 if (chmod(np, omode))
874#endif /* HAVE_FCHMOD */
8efc0c15 875 run_err("%s: set mode: %s",
5260325f 876 np, strerror(errno));
8efc0c15 877 } else {
878 if (!exists && omode != mode)
77bb0bca 879#ifdef HAVE_FCHMOD
8efc0c15 880 if (fchmod(ofd, omode & ~mask))
77bb0bca 881#else /* HAVE_FCHMOD */
882 if (chmod(np, omode & ~mask))
883#endif /* HAVE_FCHMOD */
8efc0c15 884 run_err("%s: set mode: %s",
5260325f 885 np, strerror(errno));
8efc0c15 886 }
704b1659 887 if (close(ofd) == -1) {
888 wrerr = YES;
889 wrerrno = errno;
890 }
5260325f 891 (void) response();
8efc0c15 892 if (setimes && wrerr == NO) {
893 setimes = 0;
188adeb2 894 if (utimes(np, tv) < 0) {
8efc0c15 895 run_err("%s: set times: %s",
5260325f 896 np, strerror(errno));
8efc0c15 897 wrerr = DISPLAYED;
898 }
899 }
5260325f 900 switch (wrerr) {
8efc0c15 901 case YES:
902 run_err("%s: %s", np, strerror(wrerrno));
903 break;
904 case NO:
3189621b 905 (void) atomicio(write, remout, "", 1);
8efc0c15 906 break;
907 case DISPLAYED:
908 break;
909 }
910 }
911screwup:
912 run_err("protocol error: %s", why);
913 exit(1);
914}
915
916int
917response()
918{
919 char ch, *cp, resp, rbuf[2048];
920
1d1ffb87 921 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
8efc0c15 922 lostconn(0);
923
924 cp = rbuf;
5260325f 925 switch (resp) {
926 case 0: /* ok */
8efc0c15 927 return (0);
928 default:
929 *cp++ = resp;
930 /* FALLTHROUGH */
5260325f 931 case 1: /* error, followed by error msg */
932 case 2: /* fatal error, "" */
8efc0c15 933 do {
1d1ffb87 934 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 935 lostconn(0);
936 *cp++ = ch;
937 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
938
939 if (!iamremote)
3189621b 940 (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
8efc0c15 941 ++errs;
942 if (resp == 1)
943 return (-1);
944 exit(1);
945 }
946 /* NOTREACHED */
947}
948
949void
950usage()
951{
2e73a022 952 (void) fprintf(stderr, "usage: scp "
953 "[-pqrvC46] [-S ssh] [-P port] [-c cipher] [-i identity] f1 f2; or:\n"
954 " scp [options] f1 ... fn directory\n");
8efc0c15 955 exit(1);
956}
957
958void
5260325f 959run_err(const char *fmt,...)
8efc0c15 960{
961 static FILE *fp;
962 va_list ap;
8efc0c15 963
964 ++errs;
965 if (fp == NULL && !(fp = fdopen(remout, "w")))
966 return;
5260325f 967 (void) fprintf(fp, "%c", 0x01);
968 (void) fprintf(fp, "scp: ");
b92964b7 969 va_start(ap, fmt);
5260325f 970 (void) vfprintf(fp, fmt, ap);
b92964b7 971 va_end(ap);
5260325f 972 (void) fprintf(fp, "\n");
973 (void) fflush(fp);
974
975 if (!iamremote) {
b92964b7 976 va_start(ap, fmt);
5260325f 977 vfprintf(stderr, fmt, ap);
b92964b7 978 va_end(ap);
5260325f 979 fprintf(stderr, "\n");
980 }
8efc0c15 981}
982
8efc0c15 983char *
984colon(cp)
985 char *cp;
986{
48e671d5 987 int flag = 0;
988
8efc0c15 989 if (*cp == ':') /* Leading colon is part of file name. */
990 return (0);
48e671d5 991 if (*cp == '[')
992 flag = 1;
8efc0c15 993
994 for (; *cp; ++cp) {
48e671d5 995 if (*cp == '@' && *(cp+1) == '[')
996 flag = 1;
997 if (*cp == ']' && *(cp+1) == ':' && flag)
998 return (cp+1);
999 if (*cp == ':' && !flag)
8efc0c15 1000 return (cp);
1001 if (*cp == '/')
1002 return (0);
1003 }
1004 return (0);
1005}
1006
1007void
1008verifydir(cp)
1009 char *cp;
1010{
1011 struct stat stb;
1012
1013 if (!stat(cp, &stb)) {
1014 if (S_ISDIR(stb.st_mode))
1015 return;
1016 errno = ENOTDIR;
1017 }
1018 run_err("%s: %s", cp, strerror(errno));
1019 exit(1);
1020}
1021
1022int
1023okname(cp0)
1024 char *cp0;
1025{
1026 int c;
1027 char *cp;
1028
1029 cp = cp0;
1030 do {
1031 c = *cp;
1032 if (c & 0200)
1033 goto bad;
731c1541 1034 if (!isalpha(c) && !isdigit(c) &&
1035 c != '_' && c != '-' && c != '.' && c != '+')
8efc0c15 1036 goto bad;
1037 } while (*++cp);
1038 return (1);
1039
c8d54615 1040bad: fprintf(stderr, "%s: invalid user name\n", cp0);
8efc0c15 1041 return (0);
1042}
1043
1044BUF *
1045allocbuf(bp, fd, blksize)
1046 BUF *bp;
1047 int fd, blksize;
1048{
1049 size_t size;
77bb0bca 1050#ifdef HAVE_ST_BLKSIZE
8efc0c15 1051 struct stat stb;
1052
1053 if (fstat(fd, &stb) < 0) {
1054 run_err("fstat: %s", strerror(errno));
1055 return (0);
1056 }
5260325f 1057 if (stb.st_blksize == 0)
1058 size = blksize;
1059 else
1060 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
2e73a022 1061 stb.st_blksize;
77bb0bca 1062#else /* HAVE_ST_BLKSIZE */
2b87da3b 1063 size = blksize;
77bb0bca 1064#endif /* HAVE_ST_BLKSIZE */
8efc0c15 1065 if (bp->cnt >= size)
1066 return (bp);
5260325f 1067 if (bp->buf == NULL)
1068 bp->buf = xmalloc(size);
1069 else
1070 bp->buf = xrealloc(bp->buf, size);
8efc0c15 1071 bp->cnt = size;
1072 return (bp);
1073}
1074
1075void
1076lostconn(signo)
1077 int signo;
1078{
1079 if (!iamremote)
1080 fprintf(stderr, "lost connection\n");
1081 exit(1);
1082}
1083
8efc0c15 1084
1085void
1086alarmtimer(int wait)
1087{
5260325f 1088 struct itimerval itv;
8efc0c15 1089
5260325f 1090 itv.it_value.tv_sec = wait;
1091 itv.it_value.tv_usec = 0;
1092 itv.it_interval = itv.it_value;
1093 setitimer(ITIMER_REAL, &itv, NULL);
8efc0c15 1094}
1095
1096void
610cd5c6 1097updateprogressmeter(int ignore)
8efc0c15 1098{
1099 int save_errno = errno;
1100
1101 progressmeter(0);
1102 errno = save_errno;
1103}
1104
2bd61362 1105int
1106foregroundproc()
1107{
1108 static pid_t pgrp = -1;
1109 int ctty_pgrp;
1110
1111 if (pgrp == -1)
1112 pgrp = getpgrp();
1113
63fe0529 1114#ifdef HAVE_TCGETPGRP
3c62e7eb 1115 return ((ctty_pgrp = tcgetpgrp(STDOUT_FILENO)) != -1 &&
1116 ctty_pgrp == pgrp);
1117#else
5260325f 1118 return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1119 ctty_pgrp == pgrp));
3c62e7eb 1120#endif
2bd61362 1121}
1122
8efc0c15 1123void
1124progressmeter(int flag)
1125{
1126 static const char prefixes[] = " KMGTP";
1127 static struct timeval lastupdate;
1128 static off_t lastsize;
1129 struct timeval now, td, wait;
1130 off_t cursize, abbrevsize;
1131 double elapsed;
b6573a35 1132 int ratio, barlength, i, remaining;
8efc0c15 1133 char buf[256];
1134
1135 if (flag == -1) {
5260325f 1136 (void) gettimeofday(&start, (struct timezone *) 0);
8efc0c15 1137 lastupdate = start;
1138 lastsize = 0;
5260325f 1139 }
2bd61362 1140 if (foregroundproc() == 0)
1141 return;
1142
5260325f 1143 (void) gettimeofday(&now, (struct timezone *) 0);
8efc0c15 1144 cursize = statbytes;
b4ad3727 1145 if (totalbytes != 0) {
aa3378df 1146 ratio = 100.0 * cursize / totalbytes;
8efc0c15 1147 ratio = MAX(ratio, 0);
1148 ratio = MIN(ratio, 100);
5260325f 1149 } else
8efc0c15 1150 ratio = 100;
1151
5260325f 1152 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
8efc0c15 1153
1154 barlength = getttywidth() - 51;
a4070484 1155 barlength = (barlength <= MAX_BARLENGTH)?barlength:MAX_BARLENGTH;
8efc0c15 1156 if (barlength > 0) {
1157 i = barlength * ratio / 100;
1158 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
a4070484 1159 "|%.*s%*s|", i, BAR, barlength - i, "");
8efc0c15 1160 }
8efc0c15 1161 i = 0;
1162 abbrevsize = cursize;
1163 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1164 i++;
1165 abbrevsize >>= 10;
1166 }
6a416424 1167 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5lu %c%c ",
1168 (unsigned long) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' : 'B');
8efc0c15 1169
1170 timersub(&now, &lastupdate, &wait);
1171 if (cursize > lastsize) {
1172 lastupdate = now;
1173 lastsize = cursize;
1174 if (wait.tv_sec >= STALLTIME) {
1175 start.tv_sec += wait.tv_sec;
1176 start.tv_usec += wait.tv_usec;
1177 }
1178 wait.tv_sec = 0;
1179 }
8efc0c15 1180 timersub(&now, &start, &td);
1181 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1182
71c0d06a 1183 if (flag != 1 &&
1184 (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes)) {
8efc0c15 1185 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
71c0d06a 1186 " --:-- ETA");
8efc0c15 1187 } else if (wait.tv_sec >= STALLTIME) {
1188 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
71c0d06a 1189 " - stalled -");
8efc0c15 1190 } else {
d6f24e45 1191 if (flag != 1)
71c0d06a 1192 remaining = (int)(totalbytes / (statbytes / elapsed) -
1193 elapsed);
d6f24e45 1194 else
1195 remaining = elapsed;
1196
5068f573 1197 i = remaining / 3600;
8efc0c15 1198 if (i)
1199 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2e73a022 1200 "%2d:", i);
8efc0c15 1201 else
1202 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2e73a022 1203 " ");
8efc0c15 1204 i = remaining % 3600;
1205 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2e73a022 1206 "%02d:%02d%s", i / 60, i % 60,
1207 (flag != 1) ? " ETA" : " ");
8efc0c15 1208 }
1209 atomicio(write, fileno(stdout), buf, strlen(buf));
1210
1211 if (flag == -1) {
68227e6d 1212 struct sigaction sa;
1213 sa.sa_handler = updateprogressmeter;
84a770d1 1214 sigemptyset((sigset_t *)&sa.sa_mask);
c04f75f1 1215#ifdef SA_RESTART
68227e6d 1216 sa.sa_flags = SA_RESTART;
c04f75f1 1217#endif
68227e6d 1218 sigaction(SIGALRM, &sa, NULL);
8efc0c15 1219 alarmtimer(1);
1220 } else if (flag == 1) {
1221 alarmtimer(0);
3189621b 1222 atomicio(write, fileno(stdout), "\n", 1);
8efc0c15 1223 statbytes = 0;
1224 }
1225}
1226
1227int
1228getttywidth(void)
1229{
1230 struct winsize winsize;
1231
1232 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
5260325f 1233 return (winsize.ws_col ? winsize.ws_col : 80);
8efc0c15 1234 else
5260325f 1235 return (80);
8efc0c15 1236}
94ec8c6b 1237
1238void
1239addargs(char *fmt, ...)
1240{
1241 va_list ap;
1242 char buf[1024];
1243
1244 va_start(ap, fmt);
1245 vsnprintf(buf, sizeof(buf), fmt, ap);
1246 va_end(ap);
1247
1248 if (args.list == NULL) {
1249 args.nalloc = 32;
1250 args.num = 0;
1251 args.list = xmalloc(args.nalloc * sizeof(char *));
1252 } else if (args.num+2 >= args.nalloc) {
1253 args.nalloc *= 2;
1254 args.list = xrealloc(args.list, args.nalloc * sizeof(char *));
1255 }
1256 args.list[args.num++] = xstrdup(buf);
1257 args.list[args.num] = NULL;
1258}
This page took 2.048589 seconds and 5 git commands to generate.