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