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