]> andersk Git - openssh.git/blame - scp.c
- stevesk@cvs.openbsd.org 2002/12/04 04:36:47
[openssh.git] / scp.c
CommitLineData
8efc0c15 1/*
bcbf86ec 2 * scp - secure remote copy. This is basically patched BSD rcp which
3 * uses ssh to do the data transfer (instead of using rcmd).
6ae2364d 4 *
bcbf86ec 5 * NOTE: This version should NOT be suid root. (This uses ssh to
6 * do the transfer and ssh has the necessary privileges.)
6ae2364d 7 *
5260325f 8 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
6ae2364d 9 *
bcbf86ec 10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
15 */
16/*
f3c7c613 17 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
18 * Copyright (c) 1999 Aaron Campbell. All rights reserved.
bcbf86ec 19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
22 * are met:
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
30 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
31 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
32 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
33 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
34 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
38 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 */
8efc0c15 40
41/*
2e73a022 42 * Parts from:
43 *
8efc0c15 44 * Copyright (c) 1983, 1990, 1992, 1993, 1995
45 * The Regents of the University of California. All rights reserved.
46 *
47 * Redistribution and use in source and binary forms, with or without
48 * modification, are permitted provided that the following conditions
49 * are met:
50 * 1. Redistributions of source code must retain the above copyright
51 * notice, this list of conditions and the following disclaimer.
52 * 2. Redistributions in binary form must reproduce the above copyright
53 * notice, this list of conditions and the following disclaimer in the
54 * documentation and/or other materials provided with the distribution.
55 * 3. All advertising materials mentioning features or use of this software
56 * must display the following acknowledgement:
57 * This product includes software developed by the University of
58 * California, Berkeley and its contributors.
59 * 4. Neither the name of the University nor the names of its contributors
60 * may be used to endorse or promote products derived from this software
61 * without specific prior written permission.
62 *
63 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
64 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
67 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
68 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
69 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
70 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
72 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * SUCH DAMAGE.
74 *
8efc0c15 75 */
76
77#include "includes.h"
15748b4d 78RCSID("$OpenBSD: scp.c,v 1.94 2002/11/27 17:53:35 markus Exp $");
8efc0c15 79
8efc0c15 80#include "xmalloc.h"
42f11eb2 81#include "atomicio.h"
82#include "pathnames.h"
83#include "log.h"
36a358ca 84#include "misc.h"
8efc0c15 85
260d427b 86#ifdef HAVE___PROGNAME
87extern char *__progname;
88#else
89char *__progname;
90#endif
91
8efc0c15 92/* For progressmeter() -- number of seconds before xfer considered "stalled" */
93#define STALLTIME 5
cddb9003 94/* alarm() interval for updating progress meter */
95#define PROGRESSTIME 1
8efc0c15 96
97/* Visual statistics about files as they are transferred. */
98void progressmeter(int);
99
100/* Returns width of the terminal (for progress meter calculations). */
101int getttywidth(void);
2e73a022 102int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc);
8efc0c15 103
8a624ebf 104/* Struct for addargs */
105arglist args;
94ec8c6b 106
8efc0c15 107/* Time a transfer started. */
108static struct timeval start;
109
110/* Number of bytes of current file transferred so far. */
ba917921 111volatile off_t statbytes;
8efc0c15 112
113/* Total size of current file. */
b4ad3727 114off_t totalbytes = 0;
8efc0c15 115
116/* Name of current file being transferred. */
117char *curfile;
118
119/* This is set to non-zero to enable verbose mode. */
5260325f 120int verbose_mode = 0;
8efc0c15 121
8efc0c15 122/* This is set to zero if the progressmeter is not desired. */
123int showprogress = 1;
124
2e73a022 125/* This is the program to execute for the secured connection. ("ssh" or -S) */
42f11eb2 126char *ssh_program = _PATH_SSH_PROGRAM;
2e73a022 127
252d1a24 128/* This is used to store the pid of ssh_program */
129pid_t do_cmd_pid;
130
aa3378df 131/*
132 * This function executes the given command as the specified user on the
133 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
134 * assigns the input and output file descriptors on success.
135 */
8efc0c15 136
6ae2364d 137int
2e73a022 138do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
8efc0c15 139{
5260325f 140 int pin[2], pout[2], reserved[2];
141
142 if (verbose_mode)
0b2988ca 143 fprintf(stderr,
144 "Executing: program %s host %s, user %s, command %s\n",
145 ssh_program, host,
146 remuser ? remuser : "(unspecified)", cmd);
5260325f 147
aa3378df 148 /*
149 * Reserve two descriptors so that the real pipes won't get
150 * descriptors 0 and 1 because that will screw up dup2 below.
151 */
5260325f 152 pipe(reserved);
153
154 /* Create a socket pair for communicating with ssh. */
155 if (pipe(pin) < 0)
156 fatal("pipe: %s", strerror(errno));
157 if (pipe(pout) < 0)
158 fatal("pipe: %s", strerror(errno));
159
160 /* Free the reserved descriptors. */
161 close(reserved[0]);
162 close(reserved[1]);
163
164 /* For a child to execute the command on the remote host using ssh. */
252d1a24 165 do_cmd_pid = fork();
166 if (do_cmd_pid == 0) {
5260325f 167 /* Child. */
168 close(pin[1]);
169 close(pout[0]);
170 dup2(pin[0], 0);
171 dup2(pout[1], 1);
172 close(pin[0]);
173 close(pout[1]);
174
94ec8c6b 175 args.list[0] = ssh_program;
176 if (remuser != NULL)
8a624ebf 177 addargs(&args, "-l%s", remuser);
178 addargs(&args, "%s", host);
179 addargs(&args, "%s", cmd);
5260325f 180
94ec8c6b 181 execvp(ssh_program, args.list);
2e73a022 182 perror(ssh_program);
5260325f 183 exit(1);
252d1a24 184 } else if (do_cmd_pid == -1) {
185 fatal("fork: %s", strerror(errno));
8efc0c15 186 }
5260325f 187 /* Parent. Close the other side, and return the local side. */
188 close(pin[0]);
189 *fdout = pin[1];
190 close(pout[1]);
191 *fdin = pout[0];
192 return 0;
8efc0c15 193}
194
8efc0c15 195typedef struct {
196 int cnt;
197 char *buf;
198} BUF;
199
5260325f 200BUF *allocbuf(BUF *, int, int);
5260325f 201void lostconn(int);
202void nospace(void);
203int okname(char *);
204void run_err(const char *,...);
205void verifydir(char *);
8efc0c15 206
8efc0c15 207struct passwd *pwd;
5260325f 208uid_t userid;
8efc0c15 209int errs, remin, remout;
210int pflag, iamremote, iamrecursive, targetshouldbedirectory;
211
212#define CMDNEEDS 64
213char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
214
5260325f 215int response(void);
216void rsource(char *, struct stat *);
217void sink(int, char *[]);
218void source(int, char *[]);
219void tolocal(int, char *[]);
220void toremote(char *, int, char *[]);
221void usage(void);
8efc0c15 222
223int
224main(argc, argv)
225 int argc;
226 char *argv[];
227{
252d1a24 228 int ch, fflag, tflag, status;
8efc0c15 229 char *targ;
230 extern char *optarg;
231 extern int optind;
232
260d427b 233 __progname = get_progname(argv[0]);
234
94ec8c6b 235 args.list = NULL;
7203d6bb 236 addargs(&args, "ssh"); /* overwritten with ssh_program */
8a624ebf 237 addargs(&args, "-x");
3a222388 238 addargs(&args, "-oForwardAgent no");
e1c5bfaf 239 addargs(&args, "-oClearAllForwardings yes");
94ec8c6b 240
8efc0c15 241 fflag = tflag = 0;
f1278af7 242 while ((ch = getopt(argc, argv, "dfprtvBCc:i:P:q46S:o:F:")) != -1)
5260325f 243 switch (ch) {
244 /* User-visible flags. */
48e671d5 245 case '4':
48e671d5 246 case '6':
94ec8c6b 247 case 'C':
8a624ebf 248 addargs(&args, "-%c", ch);
48e671d5 249 break;
94ec8c6b 250 case 'o':
251 case 'c':
252 case 'i':
f1278af7 253 case 'F':
8a624ebf 254 addargs(&args, "-%c%s", ch, optarg);
8efc0c15 255 break;
256 case 'P':
8a624ebf 257 addargs(&args, "-p%s", optarg);
94ec8c6b 258 break;
259 case 'B':
8a624ebf 260 addargs(&args, "-oBatchmode yes");
94ec8c6b 261 break;
262 case 'p':
263 pflag = 1;
5260325f 264 break;
8efc0c15 265 case 'r':
266 iamrecursive = 1;
267 break;
2e73a022 268 case 'S':
94ec8c6b 269 ssh_program = xstrdup(optarg);
270 break;
271 case 'v':
4fc334a2 272 addargs(&args, "-v");
94ec8c6b 273 verbose_mode = 1;
274 break;
275 case 'q':
276 showprogress = 0;
2e73a022 277 break;
278
5260325f 279 /* Server options. */
8efc0c15 280 case 'd':
281 targetshouldbedirectory = 1;
282 break;
5260325f 283 case 'f': /* "from" */
8efc0c15 284 iamremote = 1;
285 fflag = 1;
286 break;
5260325f 287 case 't': /* "to" */
8efc0c15 288 iamremote = 1;
289 tflag = 1;
fe56c12b 290#ifdef HAVE_CYGWIN
291 setmode(0, O_BINARY);
292#endif
8efc0c15 293 break;
8efc0c15 294 default:
295 usage();
296 }
297 argc -= optind;
298 argv += optind;
299
300 if ((pwd = getpwuid(userid = getuid())) == NULL)
5260325f 301 fatal("unknown user %d", (int) userid);
8efc0c15 302
5260325f 303 if (!isatty(STDERR_FILENO))
8efc0c15 304 showprogress = 0;
305
306 remin = STDIN_FILENO;
307 remout = STDOUT_FILENO;
308
2b87da3b 309 if (fflag) {
5260325f 310 /* Follow "protocol", send data. */
311 (void) response();
8efc0c15 312 source(argc, argv);
313 exit(errs != 0);
314 }
5260325f 315 if (tflag) {
316 /* Receive data. */
8efc0c15 317 sink(argc, argv);
318 exit(errs != 0);
319 }
8efc0c15 320 if (argc < 2)
321 usage();
322 if (argc > 2)
323 targetshouldbedirectory = 1;
324
325 remin = remout = -1;
252d1a24 326 do_cmd_pid = -1;
8efc0c15 327 /* Command to be executed on remote system using "ssh". */
0ed28836 328 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
329 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 }
252d1a24 342 /*
343 * Finally check the exit status of the ssh process, if one was forked
344 * and no error has occured yet
345 */
346 if (do_cmd_pid != -1 && errs == 0) {
347 if (remin != -1)
348 (void) close(remin);
349 if (remout != -1)
350 (void) close(remout);
351 if (waitpid(do_cmd_pid, &status, 0) == -1)
352 errs = 1;
353 else {
354 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
355 errs = 1;
356 }
357 }
8efc0c15 358 exit(errs != 0);
359}
360
361void
362toremote(targ, argc, argv)
363 char *targ, *argv[];
364 int argc;
365{
366 int i, len;
367 char *bp, *host, *src, *suser, *thost, *tuser;
368
369 *targ++ = 0;
370 if (*targ == 0)
371 targ = ".";
372
15748b4d 373 if ((thost = strrchr(argv[argc - 1], '@'))) {
8efc0c15 374 /* user@host */
375 *thost++ = 0;
376 tuser = argv[argc - 1];
377 if (*tuser == '\0')
378 tuser = NULL;
379 else if (!okname(tuser))
380 exit(1);
381 } else {
382 thost = argv[argc - 1];
383 tuser = NULL;
384 }
385
386 for (i = 0; i < argc - 1; i++) {
387 src = colon(argv[i]);
5260325f 388 if (src) { /* remote to remote */
e1c5bfaf 389 static char *ssh_options =
61eb812e 390 "-x -o'ClearAllForwardings yes'";
8efc0c15 391 *src++ = 0;
392 if (*src == 0)
393 src = ".";
15748b4d 394 host = strrchr(argv[i], '@');
2e73a022 395 len = strlen(ssh_program) + strlen(argv[i]) +
396 strlen(src) + (tuser ? strlen(tuser) : 0) +
e1c5bfaf 397 strlen(thost) + strlen(targ) +
398 strlen(ssh_options) + CMDNEEDS + 20;
5260325f 399 bp = xmalloc(len);
8efc0c15 400 if (host) {
401 *host++ = 0;
48e671d5 402 host = cleanhostname(host);
8efc0c15 403 suser = argv[i];
404 if (*suser == '\0')
405 suser = pwd->pw_name;
406 else if (!okname(suser))
407 continue;
0ed28836 408 snprintf(bp, len,
e1c5bfaf 409 "%s%s %s -n "
0ed28836 410 "-l %s %s %s %s '%s%s%s:%s'",
71c0d06a 411 ssh_program, verbose_mode ? " -v" : "",
e1c5bfaf 412 ssh_options, suser, host, cmd, src,
71c0d06a 413 tuser ? tuser : "", tuser ? "@" : "",
414 thost, targ);
48e671d5 415 } else {
416 host = cleanhostname(argv[i]);
0ed28836 417 snprintf(bp, len,
e1c5bfaf 418 "exec %s%s %s -n %s "
0ed28836 419 "%s %s '%s%s%s:%s'",
71c0d06a 420 ssh_program, verbose_mode ? " -v" : "",
e1c5bfaf 421 ssh_options, host, cmd, src,
71c0d06a 422 tuser ? tuser : "", tuser ? "@" : "",
423 thost, targ);
48e671d5 424 }
5260325f 425 if (verbose_mode)
426 fprintf(stderr, "Executing: %s\n", bp);
427 (void) system(bp);
428 (void) xfree(bp);
429 } else { /* local to remote */
8efc0c15 430 if (remin == -1) {
431 len = strlen(targ) + CMDNEEDS + 20;
5260325f 432 bp = xmalloc(len);
0ed28836 433 (void) snprintf(bp, len, "%s -t %s", cmd, targ);
48e671d5 434 host = cleanhostname(thost);
2e73a022 435 if (do_cmd(host, tuser, bp, &remin,
436 &remout, argc) < 0)
5260325f 437 exit(1);
8efc0c15 438 if (response() < 0)
439 exit(1);
5260325f 440 (void) xfree(bp);
8efc0c15 441 }
5260325f 442 source(1, argv + i);
8efc0c15 443 }
444 }
445}
446
447void
448tolocal(argc, argv)
449 int argc;
450 char *argv[];
451{
452 int i, len;
453 char *bp, *host, *src, *suser;
454
455 for (i = 0; i < argc - 1; i++) {
5260325f 456 if (!(src = colon(argv[i]))) { /* Local to local. */
8efc0c15 457 len = strlen(_PATH_CP) + strlen(argv[i]) +
2e73a022 458 strlen(argv[argc - 1]) + 20;
8efc0c15 459 bp = xmalloc(len);
0ed28836 460 (void) snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
2e73a022 461 iamrecursive ? " -r" : "", pflag ? " -p" : "",
462 argv[i], argv[argc - 1]);
5260325f 463 if (verbose_mode)
464 fprintf(stderr, "Executing: %s\n", bp);
8efc0c15 465 if (system(bp))
466 ++errs;
5260325f 467 (void) xfree(bp);
8efc0c15 468 continue;
469 }
470 *src++ = 0;
471 if (*src == 0)
472 src = ".";
15748b4d 473 if ((host = strrchr(argv[i], '@')) == NULL) {
8efc0c15 474 host = argv[i];
475 suser = NULL;
476 } else {
477 *host++ = 0;
478 suser = argv[i];
479 if (*suser == '\0')
480 suser = pwd->pw_name;
481 else if (!okname(suser))
482 continue;
483 }
48e671d5 484 host = cleanhostname(host);
8efc0c15 485 len = strlen(src) + CMDNEEDS + 20;
5260325f 486 bp = xmalloc(len);
0ed28836 487 (void) snprintf(bp, len, "%s -f %s", cmd, src);
2e73a022 488 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
5260325f 489 (void) xfree(bp);
490 ++errs;
491 continue;
8efc0c15 492 }
5260325f 493 xfree(bp);
8efc0c15 494 sink(1, argv + argc - 1);
5260325f 495 (void) close(remin);
8efc0c15 496 remin = remout = -1;
497 }
498}
499
500void
501source(argc, argv)
502 int argc;
503 char *argv[];
504{
505 struct stat stb;
506 static BUF buffer;
507 BUF *bp;
ba917921 508 off_t i, amt, result;
509 int fd, haderr, indx;
8efc0c15 510 char *last, *name, buf[2048];
0fc791ba 511 int len;
8efc0c15 512
513 for (indx = 0; indx < argc; ++indx) {
5260325f 514 name = argv[indx];
8efc0c15 515 statbytes = 0;
0fc791ba 516 len = strlen(name);
517 while (len > 1 && name[len-1] == '/')
518 name[--len] = '\0';
5720c10e 519 if (strchr(name, '\n') != NULL) {
520 run_err("%s: skipping, filename contains a newline",
521 name);
522 goto next;
523 }
8efc0c15 524 if ((fd = open(name, O_RDONLY, 0)) < 0)
525 goto syserr;
526 if (fstat(fd, &stb) < 0) {
527syserr: run_err("%s: %s", name, strerror(errno));
528 goto next;
529 }
530 switch (stb.st_mode & S_IFMT) {
531 case S_IFREG:
532 break;
533 case S_IFDIR:
534 if (iamrecursive) {
535 rsource(name, &stb);
536 goto next;
537 }
538 /* FALLTHROUGH */
539 default:
540 run_err("%s: not a regular file", name);
541 goto next;
542 }
543 if ((last = strrchr(name, '/')) == NULL)
544 last = name;
545 else
546 ++last;
547 curfile = last;
548 if (pflag) {
549 /*
550 * Make it compatible with possible future
551 * versions expecting microseconds.
552 */
0ed28836 553 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
1e3b8b07 554 (u_long) stb.st_mtime,
555 (u_long) stb.st_atime);
3189621b 556 (void) atomicio(write, remout, buf, strlen(buf));
8efc0c15 557 if (response() < 0)
558 goto next;
559 }
560#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
30eac028 561#ifdef HAVE_LONG_LONG_INT
bf1d27bd 562 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1e3b8b07 563 (u_int) (stb.st_mode & FILEMODEMASK),
20a11d35 564 (long long)stb.st_size, last);
f8f230bf 565#else
566 /* XXX: Handle integer overflow? */
d1581d5f 567 snprintf(buf, sizeof buf, "C%04o %lu %s\n",
f8f230bf 568 (u_int) (stb.st_mode & FILEMODEMASK),
d1581d5f 569 (u_long) stb.st_size, last);
f8f230bf 570#endif
5260325f 571 if (verbose_mode) {
572 fprintf(stderr, "Sending file modes: %s", buf);
5260325f 573 }
3189621b 574 (void) atomicio(write, remout, buf, strlen(buf));
8efc0c15 575 if (response() < 0)
576 goto next;
577 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
5260325f 578next: (void) close(fd);
8efc0c15 579 continue;
580 }
8efc0c15 581 if (showprogress) {
582 totalbytes = stb.st_size;
583 progressmeter(-1);
584 }
8efc0c15 585 /* Keep writing after an error so that we stay sync'd up. */
586 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
587 amt = bp->cnt;
588 if (i + amt > stb.st_size)
589 amt = stb.st_size - i;
590 if (!haderr) {
1d1ffb87 591 result = atomicio(read, fd, bp->buf, amt);
8efc0c15 592 if (result != amt)
593 haderr = result >= 0 ? EIO : errno;
594 }
595 if (haderr)
3189621b 596 (void) atomicio(write, remout, bp->buf, amt);
8efc0c15 597 else {
68227e6d 598 result = atomicio(write, remout, bp->buf, amt);
8efc0c15 599 if (result != amt)
600 haderr = result >= 0 ? EIO : errno;
601 statbytes += result;
602 }
603 }
5260325f 604 if (showprogress)
8efc0c15 605 progressmeter(1);
606
607 if (close(fd) < 0 && !haderr)
608 haderr = errno;
609 if (!haderr)
3189621b 610 (void) atomicio(write, remout, "", 1);
8efc0c15 611 else
612 run_err("%s: %s", name, strerror(haderr));
5260325f 613 (void) response();
8efc0c15 614 }
615}
616
617void
618rsource(name, statp)
619 char *name;
620 struct stat *statp;
621{
622 DIR *dirp;
623 struct dirent *dp;
624 char *last, *vect[1], path[1100];
625
626 if (!(dirp = opendir(name))) {
627 run_err("%s: %s", name, strerror(errno));
628 return;
629 }
630 last = strrchr(name, '/');
631 if (last == 0)
632 last = name;
633 else
634 last++;
635 if (pflag) {
0ed28836 636 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
1e3b8b07 637 (u_long) statp->st_mtime,
638 (u_long) statp->st_atime);
3189621b 639 (void) atomicio(write, remout, path, strlen(path));
8efc0c15 640 if (response() < 0) {
641 closedir(dirp);
642 return;
643 }
644 }
0ed28836 645 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1e3b8b07 646 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
5260325f 647 if (verbose_mode)
648 fprintf(stderr, "Entering directory: %s", path);
3189621b 649 (void) atomicio(write, remout, path, strlen(path));
8efc0c15 650 if (response() < 0) {
651 closedir(dirp);
652 return;
653 }
e5ff6ecf 654 while ((dp = readdir(dirp)) != NULL) {
8efc0c15 655 if (dp->d_ino == 0)
656 continue;
657 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
658 continue;
659 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
660 run_err("%s/%s: name too long", name, dp->d_name);
661 continue;
662 }
0ed28836 663 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
8efc0c15 664 vect[0] = path;
665 source(1, vect);
666 }
5260325f 667 (void) closedir(dirp);
3189621b 668 (void) atomicio(write, remout, "E\n", 2);
5260325f 669 (void) response();
8efc0c15 670}
671
672void
673sink(argc, argv)
674 int argc;
675 char *argv[];
676{
677 static BUF buffer;
678 struct stat stb;
5260325f 679 enum {
680 YES, NO, DISPLAYED
681 } wrerr;
8efc0c15 682 BUF *bp;
683 off_t i, j;
684 int amt, count, exists, first, mask, mode, ofd, omode;
14a9a859 685 off_t size;
686 int setimes, targisdir, wrerrno = 0;
8efc0c15 687 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
188adeb2 688 struct timeval tv[2];
8efc0c15 689
36967a16 690#define atime tv[0]
691#define mtime tv[1]
cb220a93 692#define SCREWUP(str) do { why = str; goto screwup; } while (0)
8efc0c15 693
694 setimes = targisdir = 0;
695 mask = umask(0);
696 if (!pflag)
5260325f 697 (void) umask(mask);
8efc0c15 698 if (argc != 1) {
699 run_err("ambiguous target");
700 exit(1);
701 }
702 targ = *argv;
703 if (targetshouldbedirectory)
704 verifydir(targ);
5260325f 705
3189621b 706 (void) atomicio(write, remout, "", 1);
8efc0c15 707 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
708 targisdir = 1;
709 for (first = 1;; first = 0) {
710 cp = buf;
1d1ffb87 711 if (atomicio(read, remin, cp, 1) <= 0)
8efc0c15 712 return;
713 if (*cp++ == '\n')
714 SCREWUP("unexpected <newline>");
715 do {
1d1ffb87 716 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 717 SCREWUP("lost connection");
718 *cp++ = ch;
719 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
720 *cp = 0;
721
722 if (buf[0] == '\01' || buf[0] == '\02') {
723 if (iamremote == 0)
3189621b 724 (void) atomicio(write, STDERR_FILENO,
71c0d06a 725 buf + 1, strlen(buf + 1));
8efc0c15 726 if (buf[0] == '\02')
727 exit(1);
728 ++errs;
729 continue;
730 }
731 if (buf[0] == 'E') {
3189621b 732 (void) atomicio(write, remout, "", 1);
8efc0c15 733 return;
734 }
8efc0c15 735 if (ch == '\n')
736 *--cp = 0;
737
8efc0c15 738 cp = buf;
739 if (*cp == 'T') {
740 setimes++;
741 cp++;
36967a16 742 mtime.tv_sec = strtol(cp, &cp, 10);
743 if (!cp || *cp++ != ' ')
8efc0c15 744 SCREWUP("mtime.sec not delimited");
36967a16 745 mtime.tv_usec = strtol(cp, &cp, 10);
746 if (!cp || *cp++ != ' ')
8efc0c15 747 SCREWUP("mtime.usec not delimited");
36967a16 748 atime.tv_sec = strtol(cp, &cp, 10);
749 if (!cp || *cp++ != ' ')
8efc0c15 750 SCREWUP("atime.sec not delimited");
36967a16 751 atime.tv_usec = strtol(cp, &cp, 10);
752 if (!cp || *cp++ != '\0')
8efc0c15 753 SCREWUP("atime.usec not delimited");
3189621b 754 (void) atomicio(write, remout, "", 1);
8efc0c15 755 continue;
756 }
757 if (*cp != 'C' && *cp != 'D') {
758 /*
759 * Check for the case "rcp remote:foo\* local:bar".
760 * In this case, the line "No match." can be returned
761 * by the shell before the rcp command on the remote is
762 * executed so the ^Aerror_message convention isn't
763 * followed.
764 */
765 if (first) {
766 run_err("%s", cp);
767 exit(1);
768 }
769 SCREWUP("expected control record");
770 }
771 mode = 0;
772 for (++cp; cp < buf + 5; cp++) {
773 if (*cp < '0' || *cp > '7')
774 SCREWUP("bad mode");
775 mode = (mode << 3) | (*cp - '0');
776 }
777 if (*cp++ != ' ')
778 SCREWUP("mode not delimited");
779
e5ff6ecf 780 for (size = 0; isdigit(*cp);)
8efc0c15 781 size = size * 10 + (*cp++ - '0');
782 if (*cp++ != ' ')
783 SCREWUP("size not delimited");
784 if (targisdir) {
785 static char *namebuf;
786 static int cursize;
787 size_t need;
788
789 need = strlen(targ) + strlen(cp) + 250;
0ed28836 790 if (need > cursize) {
791 if (namebuf)
792 xfree(namebuf);
5260325f 793 namebuf = xmalloc(need);
0ed28836 794 cursize = need;
795 }
796 (void) snprintf(namebuf, need, "%s%s%s", targ,
39f9599a 797 strcmp(targ, "/") ? "/" : "", cp);
8efc0c15 798 np = namebuf;
799 } else
800 np = targ;
801 curfile = cp;
802 exists = stat(np, &stb) == 0;
803 if (buf[0] == 'D') {
804 int mod_flag = pflag;
805 if (exists) {
806 if (!S_ISDIR(stb.st_mode)) {
807 errno = ENOTDIR;
808 goto bad;
809 }
810 if (pflag)
5260325f 811 (void) chmod(np, mode);
8efc0c15 812 } else {
5260325f 813 /* Handle copying from a read-only
814 directory */
8efc0c15 815 mod_flag = 1;
816 if (mkdir(np, mode | S_IRWXU) < 0)
817 goto bad;
818 }
5c470997 819 vect[0] = xstrdup(np);
8efc0c15 820 sink(1, vect);
821 if (setimes) {
822 setimes = 0;
e68225b2 823 if (utimes(vect[0], tv) < 0)
5260325f 824 run_err("%s: set times: %s",
e68225b2 825 vect[0], strerror(errno));
8efc0c15 826 }
827 if (mod_flag)
e68225b2 828 (void) chmod(vect[0], mode);
829 if (vect[0])
830 xfree(vect[0]);
8efc0c15 831 continue;
832 }
833 omode = mode;
834 mode |= S_IWRITE;
3e4fc5f9 835 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
8efc0c15 836bad: run_err("%s: %s", np, strerror(errno));
837 continue;
838 }
3189621b 839 (void) atomicio(write, remout, "", 1);
8efc0c15 840 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
5260325f 841 (void) close(ofd);
8efc0c15 842 continue;
843 }
844 cp = bp->buf;
845 wrerr = NO;
846
847 if (showprogress) {
848 totalbytes = size;
849 progressmeter(-1);
850 }
851 statbytes = 0;
852 for (count = i = 0; i < size; i += 4096) {
853 amt = 4096;
854 if (i + amt > size)
855 amt = size - i;
856 count += amt;
857 do {
a22aff1f 858 j = read(remin, cp, amt);
0b2988ca 859 if (j == -1 && (errno == EINTR ||
860 errno == EAGAIN)) {
a22aff1f 861 continue;
862 } else if (j <= 0) {
8efc0c15 863 run_err("%s", j ? strerror(errno) :
e5ff6ecf 864 "dropped connection");
8efc0c15 865 exit(1);
866 }
867 amt -= j;
868 cp += j;
5260325f 869 statbytes += j;
8efc0c15 870 } while (amt > 0);
871 if (count == bp->cnt) {
872 /* Keep reading so we stay sync'd up. */
873 if (wrerr == NO) {
1d1ffb87 874 j = atomicio(write, ofd, bp->buf, count);
8efc0c15 875 if (j != count) {
876 wrerr = YES;
5260325f 877 wrerrno = j >= 0 ? EIO : errno;
8efc0c15 878 }
879 }
880 count = 0;
881 cp = bp->buf;
882 }
883 }
884 if (showprogress)
885 progressmeter(1);
886 if (count != 0 && wrerr == NO &&
1d1ffb87 887 (j = atomicio(write, ofd, bp->buf, count)) != count) {
8efc0c15 888 wrerr = YES;
5260325f 889 wrerrno = j >= 0 ? EIO : errno;
8efc0c15 890 }
8efc0c15 891 if (ftruncate(ofd, size)) {
892 run_err("%s: truncate: %s", np, strerror(errno));
893 wrerr = DISPLAYED;
894 }
8efc0c15 895 if (pflag) {
896 if (exists || omode != mode)
77bb0bca 897#ifdef HAVE_FCHMOD
8efc0c15 898 if (fchmod(ofd, omode))
77bb0bca 899#else /* HAVE_FCHMOD */
900 if (chmod(np, omode))
901#endif /* HAVE_FCHMOD */
8efc0c15 902 run_err("%s: set mode: %s",
e5ff6ecf 903 np, strerror(errno));
8efc0c15 904 } else {
905 if (!exists && omode != mode)
77bb0bca 906#ifdef HAVE_FCHMOD
8efc0c15 907 if (fchmod(ofd, omode & ~mask))
77bb0bca 908#else /* HAVE_FCHMOD */
909 if (chmod(np, omode & ~mask))
910#endif /* HAVE_FCHMOD */
8efc0c15 911 run_err("%s: set mode: %s",
e5ff6ecf 912 np, strerror(errno));
8efc0c15 913 }
704b1659 914 if (close(ofd) == -1) {
915 wrerr = YES;
916 wrerrno = errno;
917 }
5260325f 918 (void) response();
8efc0c15 919 if (setimes && wrerr == NO) {
920 setimes = 0;
188adeb2 921 if (utimes(np, tv) < 0) {
8efc0c15 922 run_err("%s: set times: %s",
e5ff6ecf 923 np, strerror(errno));
8efc0c15 924 wrerr = DISPLAYED;
925 }
926 }
5260325f 927 switch (wrerr) {
8efc0c15 928 case YES:
929 run_err("%s: %s", np, strerror(wrerrno));
930 break;
931 case NO:
3189621b 932 (void) atomicio(write, remout, "", 1);
8efc0c15 933 break;
934 case DISPLAYED:
935 break;
936 }
937 }
938screwup:
939 run_err("protocol error: %s", why);
940 exit(1);
941}
942
943int
d5bb9418 944response(void)
8efc0c15 945{
946 char ch, *cp, resp, rbuf[2048];
947
1d1ffb87 948 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
8efc0c15 949 lostconn(0);
950
951 cp = rbuf;
5260325f 952 switch (resp) {
953 case 0: /* ok */
8efc0c15 954 return (0);
955 default:
956 *cp++ = resp;
957 /* FALLTHROUGH */
5260325f 958 case 1: /* error, followed by error msg */
959 case 2: /* fatal error, "" */
8efc0c15 960 do {
1d1ffb87 961 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 962 lostconn(0);
963 *cp++ = ch;
964 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
965
966 if (!iamremote)
3189621b 967 (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
8efc0c15 968 ++errs;
969 if (resp == 1)
970 return (-1);
971 exit(1);
972 }
973 /* NOTREACHED */
974}
975
976void
d5bb9418 977usage(void)
8efc0c15 978{
f1278af7 979 (void) fprintf(stderr,
3015d321 980 "usage: scp [-pqrvBC46] [-F config] [-S program] [-P port]\n"
981 " [-c cipher] [-i identity] [-o option]\n"
982 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
8efc0c15 983 exit(1);
984}
985
986void
5260325f 987run_err(const char *fmt,...)
8efc0c15 988{
989 static FILE *fp;
990 va_list ap;
8efc0c15 991
992 ++errs;
993 if (fp == NULL && !(fp = fdopen(remout, "w")))
994 return;
5260325f 995 (void) fprintf(fp, "%c", 0x01);
996 (void) fprintf(fp, "scp: ");
b92964b7 997 va_start(ap, fmt);
5260325f 998 (void) vfprintf(fp, fmt, ap);
b92964b7 999 va_end(ap);
5260325f 1000 (void) fprintf(fp, "\n");
1001 (void) fflush(fp);
1002
1003 if (!iamremote) {
b92964b7 1004 va_start(ap, fmt);
5260325f 1005 vfprintf(stderr, fmt, ap);
b92964b7 1006 va_end(ap);
5260325f 1007 fprintf(stderr, "\n");
1008 }
8efc0c15 1009}
1010
8efc0c15 1011void
1012verifydir(cp)
1013 char *cp;
1014{
1015 struct stat stb;
1016
1017 if (!stat(cp, &stb)) {
1018 if (S_ISDIR(stb.st_mode))
1019 return;
1020 errno = ENOTDIR;
1021 }
1022 run_err("%s: %s", cp, strerror(errno));
1023 exit(1);
1024}
1025
1026int
1027okname(cp0)
1028 char *cp0;
1029{
1030 int c;
1031 char *cp;
1032
1033 cp = cp0;
1034 do {
cb220a93 1035 c = (int)*cp;
8efc0c15 1036 if (c & 0200)
1037 goto bad;
731c1541 1038 if (!isalpha(c) && !isdigit(c) &&
15748b4d 1039 c != '@' && c != '_' && c != '-' && c != '.' && c != '+')
8efc0c15 1040 goto bad;
1041 } while (*++cp);
1042 return (1);
1043
c8d54615 1044bad: fprintf(stderr, "%s: invalid user name\n", cp0);
8efc0c15 1045 return (0);
1046}
1047
1048BUF *
1049allocbuf(bp, fd, blksize)
1050 BUF *bp;
1051 int fd, blksize;
1052{
1053 size_t size;
98a7c37b 1054#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
8efc0c15 1055 struct stat stb;
1056
1057 if (fstat(fd, &stb) < 0) {
1058 run_err("fstat: %s", strerror(errno));
1059 return (0);
1060 }
5260325f 1061 if (stb.st_blksize == 0)
1062 size = blksize;
1063 else
1064 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
2e73a022 1065 stb.st_blksize;
98a7c37b 1066#else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2b87da3b 1067 size = blksize;
98a7c37b 1068#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
8efc0c15 1069 if (bp->cnt >= size)
1070 return (bp);
5260325f 1071 if (bp->buf == NULL)
1072 bp->buf = xmalloc(size);
1073 else
1074 bp->buf = xrealloc(bp->buf, size);
46660a9e 1075 memset(bp->buf, 0, size);
8efc0c15 1076 bp->cnt = size;
1077 return (bp);
1078}
1079
1080void
1081lostconn(signo)
1082 int signo;
1083{
1084 if (!iamremote)
08c260ea 1085 write(STDERR_FILENO, "lost connection\n", 16);
1086 if (signo)
1087 _exit(1);
1088 else
1089 exit(1);
8efc0c15 1090}
1091
396c147e 1092static void
610cd5c6 1093updateprogressmeter(int ignore)
8efc0c15 1094{
1095 int save_errno = errno;
1096
1097 progressmeter(0);
cddb9003 1098 signal(SIGALRM, updateprogressmeter);
1099 alarm(PROGRESSTIME);
8efc0c15 1100 errno = save_errno;
1101}
1102
396c147e 1103static int
5ca51e19 1104foregroundproc(void)
2bd61362 1105{
1106 static pid_t pgrp = -1;
1107 int ctty_pgrp;
1108
1109 if (pgrp == -1)
1110 pgrp = getpgrp();
1111
63fe0529 1112#ifdef HAVE_TCGETPGRP
3c62e7eb 1113 return ((ctty_pgrp = tcgetpgrp(STDOUT_FILENO)) != -1 &&
1114 ctty_pgrp == pgrp);
1115#else
5260325f 1116 return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1117 ctty_pgrp == pgrp));
3c62e7eb 1118#endif
2bd61362 1119}
1120
8efc0c15 1121void
1122progressmeter(int flag)
1123{
1124 static const char prefixes[] = " KMGTP";
1125 static struct timeval lastupdate;
1126 static off_t lastsize;
1127 struct timeval now, td, wait;
1128 off_t cursize, abbrevsize;
1129 double elapsed;
b6573a35 1130 int ratio, barlength, i, remaining;
ca7e8e1e 1131 char buf[512];
8efc0c15 1132
1133 if (flag == -1) {
5260325f 1134 (void) gettimeofday(&start, (struct timezone *) 0);
8efc0c15 1135 lastupdate = start;
1136 lastsize = 0;
5260325f 1137 }
2bd61362 1138 if (foregroundproc() == 0)
1139 return;
1140
5260325f 1141 (void) gettimeofday(&now, (struct timezone *) 0);
8efc0c15 1142 cursize = statbytes;
b4ad3727 1143 if (totalbytes != 0) {
aa3378df 1144 ratio = 100.0 * cursize / totalbytes;
8efc0c15 1145 ratio = MAX(ratio, 0);
1146 ratio = MIN(ratio, 100);
5260325f 1147 } else
8efc0c15 1148 ratio = 100;
1149
5260325f 1150 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
8efc0c15 1151
1152 barlength = getttywidth() - 51;
1153 if (barlength > 0) {
1154 i = barlength * ratio / 100;
1155 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
ca7e8e1e 1156 "|%.*s%*s|", i,
1157 "*******************************************************"
1158 "*******************************************************"
1159 "*******************************************************"
1160 "*******************************************************"
1161 "*******************************************************"
1162 "*******************************************************"
1163 "*******************************************************",
1164 barlength - i, "");
8efc0c15 1165 }
8efc0c15 1166 i = 0;
1167 abbrevsize = cursize;
1168 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1169 i++;
1170 abbrevsize >>= 10;
1171 }
6a416424 1172 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5lu %c%c ",
2c92c680 1173 (unsigned long) abbrevsize, prefixes[i],
1174 prefixes[i] == ' ' ? ' ' : 'B');
8efc0c15 1175
1176 timersub(&now, &lastupdate, &wait);
1177 if (cursize > lastsize) {
1178 lastupdate = now;
1179 lastsize = cursize;
1180 if (wait.tv_sec >= STALLTIME) {
1181 start.tv_sec += wait.tv_sec;
1182 start.tv_usec += wait.tv_usec;
1183 }
1184 wait.tv_sec = 0;
1185 }
8efc0c15 1186 timersub(&now, &start, &td);
1187 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1188
71c0d06a 1189 if (flag != 1 &&
1190 (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes)) {
8efc0c15 1191 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
71c0d06a 1192 " --:-- ETA");
8efc0c15 1193 } else if (wait.tv_sec >= STALLTIME) {
1194 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
71c0d06a 1195 " - stalled -");
8efc0c15 1196 } else {
d6f24e45 1197 if (flag != 1)
71c0d06a 1198 remaining = (int)(totalbytes / (statbytes / elapsed) -
1199 elapsed);
d6f24e45 1200 else
1201 remaining = elapsed;
1202
5068f573 1203 i = remaining / 3600;
8efc0c15 1204 if (i)
1205 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2e73a022 1206 "%2d:", i);
8efc0c15 1207 else
1208 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2e73a022 1209 " ");
8efc0c15 1210 i = remaining % 3600;
1211 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2e73a022 1212 "%02d:%02d%s", i / 60, i % 60,
1213 (flag != 1) ? " ETA" : " ");
8efc0c15 1214 }
1215 atomicio(write, fileno(stdout), buf, strlen(buf));
1216
1217 if (flag == -1) {
36a358ca 1218 mysignal(SIGALRM, updateprogressmeter);
cddb9003 1219 alarm(PROGRESSTIME);
8efc0c15 1220 } else if (flag == 1) {
cddb9003 1221 alarm(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}
This page took 1.505454 seconds and 5 git commands to generate.