]> andersk Git - gssapi-openssh.git/blame - openssh/scp.c
Initial revision
[gssapi-openssh.git] / openssh / scp.c
CommitLineData
3c0ef626 1/*
2 * scp - secure remote copy. This is basically patched BSD rcp which
3 * uses ssh to do the data transfer (instead of using rcmd).
4 *
5 * NOTE: This version should NOT be suid root. (This uses ssh to
6 * do the transfer and ssh has the necessary privileges.)
7 *
8 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
9 *
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 */
40
41/*
42 * Parts from:
43 *
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.
473db5ab 55 * 3. Neither the name of the University nor the names of its contributors
3c0ef626 56 * may be used to endorse or promote products derived from this software
57 * without specific prior written permission.
58 *
59 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
70 *
71 */
72
73#include "includes.h"
473db5ab 74RCSID("$OpenBSD: scp.c,v 1.125 2005/07/27 10:39:03 dtucker Exp $");
3c0ef626 75
76#include "xmalloc.h"
77#include "atomicio.h"
78#include "pathnames.h"
79#include "log.h"
80#include "misc.h"
473db5ab 81#include "progressmeter.h"
3c0ef626 82
3c0ef626 83extern char *__progname;
3c0ef626 84
473db5ab 85void bwlimit(int);
3c0ef626 86
87/* Struct for addargs */
88arglist args;
89
473db5ab 90/* Bandwidth limit */
91off_t limit_rate = 0;
3c0ef626 92
93/* Name of current file being transferred. */
94char *curfile;
95
96/* This is set to non-zero to enable verbose mode. */
97int verbose_mode = 0;
98
99/* This is set to zero if the progressmeter is not desired. */
100int showprogress = 1;
101
102/* This is the program to execute for the secured connection. ("ssh" or -S) */
103char *ssh_program = _PATH_SSH_PROGRAM;
104
473db5ab 105/* This is used to store the pid of ssh_program */
106pid_t do_cmd_pid = -1;
107
108static void
109killchild(int signo)
110{
111 if (do_cmd_pid > 1) {
112 kill(do_cmd_pid, signo ? signo : SIGTERM);
113 waitpid(do_cmd_pid, NULL, 0);
114 }
115
116 if (signo)
117 _exit(1);
118 exit(1);
119}
120
3c0ef626 121/*
122 * This function executes the given command as the specified user on the
123 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
124 * assigns the input and output file descriptors on success.
125 */
126
127int
128do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
129{
130 int pin[2], pout[2], reserved[2];
131
132 if (verbose_mode)
133 fprintf(stderr,
134 "Executing: program %s host %s, user %s, command %s\n",
135 ssh_program, host,
136 remuser ? remuser : "(unspecified)", cmd);
137
138 /*
139 * Reserve two descriptors so that the real pipes won't get
140 * descriptors 0 and 1 because that will screw up dup2 below.
141 */
142 pipe(reserved);
143
144 /* Create a socket pair for communicating with ssh. */
145 if (pipe(pin) < 0)
146 fatal("pipe: %s", strerror(errno));
147 if (pipe(pout) < 0)
148 fatal("pipe: %s", strerror(errno));
149
150 /* Free the reserved descriptors. */
151 close(reserved[0]);
152 close(reserved[1]);
153
473db5ab 154 /* Fork a child to execute the command on the remote host using ssh. */
155 do_cmd_pid = fork();
156 if (do_cmd_pid == 0) {
3c0ef626 157 /* Child. */
158 close(pin[1]);
159 close(pout[0]);
160 dup2(pin[0], 0);
161 dup2(pout[1], 1);
162 close(pin[0]);
163 close(pout[1]);
164
165 args.list[0] = ssh_program;
166 if (remuser != NULL)
167 addargs(&args, "-l%s", remuser);
168 addargs(&args, "%s", host);
169 addargs(&args, "%s", cmd);
170
171 execvp(ssh_program, args.list);
172 perror(ssh_program);
173 exit(1);
473db5ab 174 } else if (do_cmd_pid == -1) {
175 fatal("fork: %s", strerror(errno));
3c0ef626 176 }
177 /* Parent. Close the other side, and return the local side. */
178 close(pin[0]);
179 *fdout = pin[1];
180 close(pout[1]);
181 *fdin = pout[0];
473db5ab 182 signal(SIGTERM, killchild);
183 signal(SIGINT, killchild);
184 signal(SIGHUP, killchild);
3c0ef626 185 return 0;
186}
187
188typedef struct {
473db5ab 189 size_t cnt;
3c0ef626 190 char *buf;
191} BUF;
192
193BUF *allocbuf(BUF *, int, int);
194void lostconn(int);
195void nospace(void);
196int okname(char *);
197void run_err(const char *,...);
198void verifydir(char *);
199
200struct passwd *pwd;
201uid_t userid;
202int errs, remin, remout;
203int pflag, iamremote, iamrecursive, targetshouldbedirectory;
204
205#define CMDNEEDS 64
206char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
207
208int response(void);
209void rsource(char *, struct stat *);
210void sink(int, char *[]);
211void source(int, char *[]);
212void tolocal(int, char *[]);
213void toremote(char *, int, char *[]);
214void usage(void);
215
216int
473db5ab 217main(int argc, char **argv)
3c0ef626 218{
473db5ab 219 int ch, fflag, tflag, status;
220 double speed;
221 char *targ, *endp;
3c0ef626 222 extern char *optarg;
223 extern int optind;
224
473db5ab 225 __progname = ssh_get_progname(argv[0]);
3c0ef626 226
227 args.list = NULL;
473db5ab 228 addargs(&args, "ssh"); /* overwritten with ssh_program */
3c0ef626 229 addargs(&args, "-x");
230 addargs(&args, "-oForwardAgent no");
3c0ef626 231 addargs(&args, "-oClearAllForwardings yes");
232
233 fflag = tflag = 0;
473db5ab 234 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246zS:o:F:w:")) != -1)
3c0ef626 235 switch (ch) {
236 /* User-visible flags. */
473db5ab 237 case '1':
238 case '2':
3c0ef626 239 case '4':
240 case '6':
241 case 'C':
473db5ab 242 case 'z':
3c0ef626 243 addargs(&args, "-%c", ch);
244 break;
245 case 'o':
246 case 'c':
247 case 'i':
248 case 'F':
249 addargs(&args, "-%c%s", ch, optarg);
250 break;
251 case 'P':
252 addargs(&args, "-p%s", optarg);
253 break;
254 case 'B':
255 addargs(&args, "-oBatchmode yes");
256 break;
473db5ab 257 case 'l':
258 speed = strtod(optarg, &endp);
259 if (speed <= 0 || *endp != '\0')
260 usage();
261 limit_rate = speed * 1024;
262 break;
3c0ef626 263 case 'p':
264 pflag = 1;
265 break;
266 case 'r':
267 iamrecursive = 1;
268 break;
269 case 'S':
270 ssh_program = xstrdup(optarg);
271 break;
272 case 'v':
273 addargs(&args, "-v");
274 verbose_mode = 1;
275 break;
276 case 'q':
473db5ab 277 addargs(&args, "-q");
3c0ef626 278 showprogress = 0;
279 break;
280
281 /* Server options. */
282 case 'd':
283 targetshouldbedirectory = 1;
284 break;
285 case 'f': /* "from" */
286 iamremote = 1;
287 fflag = 1;
288 break;
289 case 't': /* "to" */
290 iamremote = 1;
291 tflag = 1;
292#ifdef HAVE_CYGWIN
293 setmode(0, O_BINARY);
294#endif
295 break;
473db5ab 296 case 'w':
297 addargs(&args, "-w%s", optarg);
298 break;
3c0ef626 299 default:
300 usage();
301 }
302 argc -= optind;
303 argv += optind;
304
305 if ((pwd = getpwuid(userid = getuid())) == NULL)
473db5ab 306 fatal("unknown user %u", (u_int) userid);
3c0ef626 307
308 if (!isatty(STDERR_FILENO))
309 showprogress = 0;
310
311 remin = STDIN_FILENO;
312 remout = STDOUT_FILENO;
313
314 if (fflag) {
315 /* Follow "protocol", send data. */
316 (void) response();
317 source(argc, argv);
318 exit(errs != 0);
319 }
320 if (tflag) {
321 /* Receive data. */
322 sink(argc, argv);
323 exit(errs != 0);
324 }
325 if (argc < 2)
326 usage();
327 if (argc > 2)
328 targetshouldbedirectory = 1;
329
330 remin = remout = -1;
473db5ab 331 do_cmd_pid = -1;
3c0ef626 332 /* Command to be executed on remote system using "ssh". */
333 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
334 verbose_mode ? " -v" : "",
335 iamrecursive ? " -r" : "", pflag ? " -p" : "",
336 targetshouldbedirectory ? " -d" : "");
337
338 (void) signal(SIGPIPE, lostconn);
339
340 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
341 toremote(targ, argc, argv);
342 else {
343 tolocal(argc, argv); /* Dest is local host. */
344 if (targetshouldbedirectory)
345 verifydir(argv[argc - 1]);
346 }
473db5ab 347 /*
348 * Finally check the exit status of the ssh process, if one was forked
349 * and no error has occured yet
350 */
351 if (do_cmd_pid != -1 && errs == 0) {
352 if (remin != -1)
353 (void) close(remin);
354 if (remout != -1)
355 (void) close(remout);
356 if (waitpid(do_cmd_pid, &status, 0) == -1)
357 errs = 1;
358 else {
359 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
360 errs = 1;
361 }
362 }
3c0ef626 363 exit(errs != 0);
364}
365
366void
473db5ab 367toremote(char *targ, int argc, char **argv)
3c0ef626 368{
369 int i, len;
473db5ab 370 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
3c0ef626 371
372 *targ++ = 0;
373 if (*targ == 0)
374 targ = ".";
375
473db5ab 376 arg = xstrdup(argv[argc - 1]);
377 if ((thost = strrchr(arg, '@'))) {
3c0ef626 378 /* user@host */
379 *thost++ = 0;
473db5ab 380 tuser = arg;
3c0ef626 381 if (*tuser == '\0')
382 tuser = NULL;
3c0ef626 383 } else {
473db5ab 384 thost = arg;
3c0ef626 385 tuser = NULL;
386 }
387
388 for (i = 0; i < argc - 1; i++) {
389 src = colon(argv[i]);
390 if (src) { /* remote to remote */
391 static char *ssh_options =
473db5ab 392 "-x -o'ClearAllForwardings yes'";
3c0ef626 393 *src++ = 0;
394 if (*src == 0)
395 src = ".";
473db5ab 396 host = strrchr(argv[i], '@');
3c0ef626 397 len = strlen(ssh_program) + strlen(argv[i]) +
398 strlen(src) + (tuser ? strlen(tuser) : 0) +
399 strlen(thost) + strlen(targ) +
400 strlen(ssh_options) + CMDNEEDS + 20;
401 bp = xmalloc(len);
402 if (host) {
403 *host++ = 0;
404 host = cleanhostname(host);
405 suser = argv[i];
406 if (*suser == '\0')
407 suser = pwd->pw_name;
473db5ab 408 else if (!okname(suser)) {
409 xfree(bp);
3c0ef626 410 continue;
473db5ab 411 }
412 if (tuser && !okname(tuser)) {
413 xfree(bp);
414 continue;
415 }
3c0ef626 416 snprintf(bp, len,
417 "%s%s %s -n "
418 "-l %s %s %s %s '%s%s%s:%s'",
419 ssh_program, verbose_mode ? " -v" : "",
420 ssh_options, suser, host, cmd, src,
421 tuser ? tuser : "", tuser ? "@" : "",
422 thost, targ);
423 } else {
424 host = cleanhostname(argv[i]);
425 snprintf(bp, len,
426 "exec %s%s %s -n %s "
427 "%s %s '%s%s%s:%s'",
428 ssh_program, verbose_mode ? " -v" : "",
429 ssh_options, host, cmd, src,
430 tuser ? tuser : "", tuser ? "@" : "",
431 thost, targ);
432 }
433 if (verbose_mode)
434 fprintf(stderr, "Executing: %s\n", bp);
473db5ab 435 if (system(bp) != 0)
436 errs = 1;
3c0ef626 437 (void) xfree(bp);
438 } else { /* local to remote */
439 if (remin == -1) {
440 len = strlen(targ) + CMDNEEDS + 20;
441 bp = xmalloc(len);
442 (void) snprintf(bp, len, "%s -t %s", cmd, targ);
443 host = cleanhostname(thost);
444 if (do_cmd(host, tuser, bp, &remin,
445 &remout, argc) < 0)
446 exit(1);
447 if (response() < 0)
448 exit(1);
449 (void) xfree(bp);
450 }
451 source(1, argv + i);
452 }
453 }
454}
455
456void
473db5ab 457tolocal(int argc, char **argv)
3c0ef626 458{
459 int i, len;
460 char *bp, *host, *src, *suser;
461
462 for (i = 0; i < argc - 1; i++) {
463 if (!(src = colon(argv[i]))) { /* Local to local. */
464 len = strlen(_PATH_CP) + strlen(argv[i]) +
465 strlen(argv[argc - 1]) + 20;
466 bp = xmalloc(len);
467 (void) snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP,
468 iamrecursive ? " -r" : "", pflag ? " -p" : "",
469 argv[i], argv[argc - 1]);
470 if (verbose_mode)
471 fprintf(stderr, "Executing: %s\n", bp);
472 if (system(bp))
473 ++errs;
474 (void) xfree(bp);
475 continue;
476 }
477 *src++ = 0;
478 if (*src == 0)
479 src = ".";
473db5ab 480 if ((host = strrchr(argv[i], '@')) == NULL) {
3c0ef626 481 host = argv[i];
482 suser = NULL;
483 } else {
484 *host++ = 0;
485 suser = argv[i];
486 if (*suser == '\0')
487 suser = pwd->pw_name;
3c0ef626 488 }
489 host = cleanhostname(host);
490 len = strlen(src) + CMDNEEDS + 20;
491 bp = xmalloc(len);
492 (void) snprintf(bp, len, "%s -f %s", cmd, src);
493 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
494 (void) xfree(bp);
495 ++errs;
496 continue;
497 }
498 xfree(bp);
499 sink(1, argv + argc - 1);
500 (void) close(remin);
501 remin = remout = -1;
502 }
503}
504
505void
473db5ab 506source(int argc, char **argv)
3c0ef626 507{
508 struct stat stb;
509 static BUF buffer;
510 BUF *bp;
473db5ab 511 off_t i, amt, statbytes;
512 size_t result;
513 int fd = -1, haderr, indx;
514 char *last, *name, buf[16384];
3c0ef626 515 int len;
516
517 for (indx = 0; indx < argc; ++indx) {
518 name = argv[indx];
519 statbytes = 0;
520 len = strlen(name);
521 while (len > 1 && name[len-1] == '/')
522 name[--len] = '\0';
523 if (strchr(name, '\n') != NULL) {
524 run_err("%s: skipping, filename contains a newline",
525 name);
526 goto next;
527 }
528 if ((fd = open(name, O_RDONLY, 0)) < 0)
529 goto syserr;
530 if (fstat(fd, &stb) < 0) {
531syserr: run_err("%s: %s", name, strerror(errno));
532 goto next;
533 }
534 switch (stb.st_mode & S_IFMT) {
535 case S_IFREG:
536 break;
537 case S_IFDIR:
538 if (iamrecursive) {
539 rsource(name, &stb);
540 goto next;
541 }
542 /* FALLTHROUGH */
543 default:
544 run_err("%s: not a regular file", name);
545 goto next;
546 }
547 if ((last = strrchr(name, '/')) == NULL)
548 last = name;
549 else
550 ++last;
551 curfile = last;
552 if (pflag) {
553 /*
554 * Make it compatible with possible future
555 * versions expecting microseconds.
556 */
557 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
558 (u_long) stb.st_mtime,
559 (u_long) stb.st_atime);
473db5ab 560 (void) atomicio(vwrite, remout, buf, strlen(buf));
3c0ef626 561 if (response() < 0)
562 goto next;
563 }
564#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
3c0ef626 565 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
566 (u_int) (stb.st_mode & FILEMODEMASK),
473db5ab 567 (int64_t)stb.st_size, last);
3c0ef626 568 if (verbose_mode) {
569 fprintf(stderr, "Sending file modes: %s", buf);
3c0ef626 570 }
473db5ab 571 (void) atomicio(vwrite, remout, buf, strlen(buf));
3c0ef626 572 if (response() < 0)
573 goto next;
473db5ab 574 /* this change decreases the number of read/write syscalls*/
575 /* when scp acts as data source. this is the critical change*/
576 /* buf can actually remain at 2k but increasing both to 16k*/
577 /* seemed to make sense*/
578 if ((bp = allocbuf(&buffer, fd, sizeof(buf))) == NULL) {
3c0ef626 579next: (void) close(fd);
580 continue;
581 }
473db5ab 582 if (showprogress)
583 start_progress_meter(curfile, stb.st_size, &statbytes);
3c0ef626 584 /* Keep writing after an error so that we stay sync'd up. */
585 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
586 amt = bp->cnt;
587 if (i + amt > stb.st_size)
588 amt = stb.st_size - i;
589 if (!haderr) {
590 result = atomicio(read, fd, bp->buf, amt);
591 if (result != amt)
473db5ab 592 haderr = errno;
3c0ef626 593 }
594 if (haderr)
473db5ab 595 (void) atomicio(vwrite, remout, bp->buf, amt);
3c0ef626 596 else {
473db5ab 597 result = atomicio(vwrite, remout, bp->buf, amt);
3c0ef626 598 if (result != amt)
473db5ab 599 haderr = errno;
3c0ef626 600 statbytes += result;
601 }
473db5ab 602 if (limit_rate)
603 bwlimit(amt);
3c0ef626 604 }
605 if (showprogress)
473db5ab 606 stop_progress_meter();
3c0ef626 607
608 if (close(fd) < 0 && !haderr)
609 haderr = errno;
610 if (!haderr)
473db5ab 611 (void) atomicio(vwrite, remout, "", 1);
3c0ef626 612 else
613 run_err("%s: %s", name, strerror(haderr));
614 (void) response();
615 }
616}
617
618void
473db5ab 619rsource(char *name, struct stat *statp)
3c0ef626 620{
621 DIR *dirp;
622 struct dirent *dp;
623 char *last, *vect[1], path[1100];
624
625 if (!(dirp = opendir(name))) {
626 run_err("%s: %s", name, strerror(errno));
627 return;
628 }
629 last = strrchr(name, '/');
630 if (last == 0)
631 last = name;
632 else
633 last++;
634 if (pflag) {
635 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
636 (u_long) statp->st_mtime,
637 (u_long) statp->st_atime);
473db5ab 638 (void) atomicio(vwrite, remout, path, strlen(path));
3c0ef626 639 if (response() < 0) {
640 closedir(dirp);
641 return;
642 }
643 }
644 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
645 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
646 if (verbose_mode)
647 fprintf(stderr, "Entering directory: %s", path);
473db5ab 648 (void) atomicio(vwrite, remout, path, strlen(path));
3c0ef626 649 if (response() < 0) {
650 closedir(dirp);
651 return;
652 }
653 while ((dp = readdir(dirp)) != NULL) {
654 if (dp->d_ino == 0)
655 continue;
656 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
657 continue;
658 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
659 run_err("%s/%s: name too long", name, dp->d_name);
660 continue;
661 }
662 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
663 vect[0] = path;
664 source(1, vect);
665 }
666 (void) closedir(dirp);
473db5ab 667 (void) atomicio(vwrite, remout, "E\n", 2);
3c0ef626 668 (void) response();
669}
670
671void
473db5ab 672bwlimit(int amount)
673{
674 static struct timeval bwstart, bwend;
675 static int lamt, thresh = 16384;
676 u_int64_t waitlen;
677 struct timespec ts, rm;
678
679 if (!timerisset(&bwstart)) {
680 gettimeofday(&bwstart, NULL);
681 return;
682 }
683
684 lamt += amount;
685 if (lamt < thresh)
686 return;
687
688 gettimeofday(&bwend, NULL);
689 timersub(&bwend, &bwstart, &bwend);
690 if (!timerisset(&bwend))
691 return;
692
693 lamt *= 8;
694 waitlen = (double)1000000L * lamt / limit_rate;
695
696 bwstart.tv_sec = waitlen / 1000000L;
697 bwstart.tv_usec = waitlen % 1000000L;
698
699 if (timercmp(&bwstart, &bwend, >)) {
700 timersub(&bwstart, &bwend, &bwend);
701
702 /* Adjust the wait time */
703 if (bwend.tv_sec) {
704 thresh /= 2;
705 if (thresh < 2048)
706 thresh = 2048;
707 } else if (bwend.tv_usec < 100) {
708 thresh *= 2;
709 if (thresh > 32768)
710 thresh = 32768;
711 }
712
713 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
714 while (nanosleep(&ts, &rm) == -1) {
715 if (errno != EINTR)
716 break;
717 ts = rm;
718 }
719 }
720
721 lamt = 0;
722 gettimeofday(&bwstart, NULL);
723}
724
725void
726sink(int argc, char **argv)
3c0ef626 727{
728 static BUF buffer;
729 struct stat stb;
730 enum {
731 YES, NO, DISPLAYED
732 } wrerr;
733 BUF *bp;
473db5ab 734 off_t i;
735 size_t j, count;
736 int amt, exists, first, mask, mode, ofd, omode;
737 off_t size, statbytes;
3c0ef626 738 int setimes, targisdir, wrerrno = 0;
473db5ab 739 char ch, *cp, *np, *targ, *why, *vect[1], buf[16384];
3c0ef626 740 struct timeval tv[2];
741
742#define atime tv[0]
743#define mtime tv[1]
473db5ab 744#define SCREWUP(str) { why = str; goto screwup; }
3c0ef626 745
746 setimes = targisdir = 0;
747 mask = umask(0);
748 if (!pflag)
749 (void) umask(mask);
750 if (argc != 1) {
751 run_err("ambiguous target");
752 exit(1);
753 }
754 targ = *argv;
755 if (targetshouldbedirectory)
756 verifydir(targ);
757
473db5ab 758 (void) atomicio(vwrite, remout, "", 1);
3c0ef626 759 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
760 targisdir = 1;
761 for (first = 1;; first = 0) {
762 cp = buf;
473db5ab 763 if (atomicio(read, remin, cp, 1) != 1)
3c0ef626 764 return;
765 if (*cp++ == '\n')
766 SCREWUP("unexpected <newline>");
767 do {
768 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
769 SCREWUP("lost connection");
770 *cp++ = ch;
771 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
772 *cp = 0;
473db5ab 773 if (verbose_mode)
774 fprintf(stderr, "Sink: %s", buf);
3c0ef626 775
776 if (buf[0] == '\01' || buf[0] == '\02') {
777 if (iamremote == 0)
473db5ab 778 (void) atomicio(vwrite, STDERR_FILENO,
3c0ef626 779 buf + 1, strlen(buf + 1));
780 if (buf[0] == '\02')
781 exit(1);
782 ++errs;
783 continue;
784 }
785 if (buf[0] == 'E') {
473db5ab 786 (void) atomicio(vwrite, remout, "", 1);
3c0ef626 787 return;
788 }
789 if (ch == '\n')
790 *--cp = 0;
791
792 cp = buf;
793 if (*cp == 'T') {
794 setimes++;
795 cp++;
796 mtime.tv_sec = strtol(cp, &cp, 10);
797 if (!cp || *cp++ != ' ')
798 SCREWUP("mtime.sec not delimited");
799 mtime.tv_usec = strtol(cp, &cp, 10);
800 if (!cp || *cp++ != ' ')
801 SCREWUP("mtime.usec not delimited");
802 atime.tv_sec = strtol(cp, &cp, 10);
803 if (!cp || *cp++ != ' ')
804 SCREWUP("atime.sec not delimited");
805 atime.tv_usec = strtol(cp, &cp, 10);
806 if (!cp || *cp++ != '\0')
807 SCREWUP("atime.usec not delimited");
473db5ab 808 (void) atomicio(vwrite, remout, "", 1);
3c0ef626 809 continue;
810 }
811 if (*cp != 'C' && *cp != 'D') {
812 /*
813 * Check for the case "rcp remote:foo\* local:bar".
814 * In this case, the line "No match." can be returned
815 * by the shell before the rcp command on the remote is
816 * executed so the ^Aerror_message convention isn't
817 * followed.
818 */
819 if (first) {
820 run_err("%s", cp);
821 exit(1);
822 }
823 SCREWUP("expected control record");
824 }
825 mode = 0;
826 for (++cp; cp < buf + 5; cp++) {
827 if (*cp < '0' || *cp > '7')
828 SCREWUP("bad mode");
829 mode = (mode << 3) | (*cp - '0');
830 }
831 if (*cp++ != ' ')
832 SCREWUP("mode not delimited");
833
834 for (size = 0; isdigit(*cp);)
835 size = size * 10 + (*cp++ - '0');
836 if (*cp++ != ' ')
837 SCREWUP("size not delimited");
473db5ab 838 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
839 run_err("error: unexpected filename: %s", cp);
840 exit(1);
841 }
3c0ef626 842 if (targisdir) {
843 static char *namebuf;
473db5ab 844 static size_t cursize;
3c0ef626 845 size_t need;
846
847 need = strlen(targ) + strlen(cp) + 250;
848 if (need > cursize) {
849 if (namebuf)
850 xfree(namebuf);
851 namebuf = xmalloc(need);
852 cursize = need;
853 }
854 (void) snprintf(namebuf, need, "%s%s%s", targ,
473db5ab 855 strcmp(targ, "/") ? "/" : "", cp);
3c0ef626 856 np = namebuf;
857 } else
858 np = targ;
859 curfile = cp;
860 exists = stat(np, &stb) == 0;
861 if (buf[0] == 'D') {
862 int mod_flag = pflag;
473db5ab 863 if (!iamrecursive)
864 SCREWUP("received directory without -r");
3c0ef626 865 if (exists) {
866 if (!S_ISDIR(stb.st_mode)) {
867 errno = ENOTDIR;
868 goto bad;
869 }
870 if (pflag)
871 (void) chmod(np, mode);
872 } else {
873 /* Handle copying from a read-only
874 directory */
875 mod_flag = 1;
876 if (mkdir(np, mode | S_IRWXU) < 0)
877 goto bad;
878 }
879 vect[0] = xstrdup(np);
880 sink(1, vect);
881 if (setimes) {
882 setimes = 0;
883 if (utimes(vect[0], tv) < 0)
884 run_err("%s: set times: %s",
885 vect[0], strerror(errno));
886 }
887 if (mod_flag)
888 (void) chmod(vect[0], mode);
889 if (vect[0])
890 xfree(vect[0]);
891 continue;
892 }
893 omode = mode;
894 mode |= S_IWRITE;
895 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
896bad: run_err("%s: %s", np, strerror(errno));
897 continue;
898 }
473db5ab 899 (void) atomicio(vwrite, remout, "", 1);
900 if ((bp = allocbuf(&buffer, ofd, sizeof(buf))) == NULL) {
3c0ef626 901 (void) close(ofd);
902 continue;
903 }
904 cp = bp->buf;
905 wrerr = NO;
906
3c0ef626 907 statbytes = 0;
473db5ab 908 if (showprogress)
909 start_progress_meter(curfile, size, &statbytes);
910 for (count = i = 0; i < size; i += sizeof(buf)) {
911 amt = sizeof(buf);
3c0ef626 912 if (i + amt > size)
913 amt = size - i;
914 count += amt;
915 do {
473db5ab 916 j = atomicio(read, remin, cp, amt);
917 if (j == 0) {
3c0ef626 918 run_err("%s", j ? strerror(errno) :
919 "dropped connection");
920 exit(1);
921 }
922 amt -= j;
923 cp += j;
924 statbytes += j;
925 } while (amt > 0);
473db5ab 926
927 if (limit_rate)
928 bwlimit(sizeof(buf));
929
3c0ef626 930 if (count == bp->cnt) {
931 /* Keep reading so we stay sync'd up. */
932 if (wrerr == NO) {
473db5ab 933 if (atomicio(vwrite, ofd, bp->buf,
934 count) != count) {
3c0ef626 935 wrerr = YES;
473db5ab 936 wrerrno = errno;
3c0ef626 937 }
938 }
939 count = 0;
940 cp = bp->buf;
941 }
942 }
943 if (showprogress)
473db5ab 944 stop_progress_meter();
3c0ef626 945 if (count != 0 && wrerr == NO &&
473db5ab 946 atomicio(vwrite, ofd, bp->buf, count) != count) {
3c0ef626 947 wrerr = YES;
473db5ab 948 wrerrno = errno;
3c0ef626 949 }
473db5ab 950 if (wrerr == NO && ftruncate(ofd, size) != 0) {
3c0ef626 951 run_err("%s: truncate: %s", np, strerror(errno));
952 wrerr = DISPLAYED;
953 }
954 if (pflag) {
955 if (exists || omode != mode)
956#ifdef HAVE_FCHMOD
473db5ab 957 if (fchmod(ofd, omode)) {
3c0ef626 958#else /* HAVE_FCHMOD */
473db5ab 959 if (chmod(np, omode)) {
3c0ef626 960#endif /* HAVE_FCHMOD */
961 run_err("%s: set mode: %s",
962 np, strerror(errno));
473db5ab 963 wrerr = DISPLAYED;
964 }
3c0ef626 965 } else {
966 if (!exists && omode != mode)
967#ifdef HAVE_FCHMOD
473db5ab 968 if (fchmod(ofd, omode & ~mask)) {
3c0ef626 969#else /* HAVE_FCHMOD */
473db5ab 970 if (chmod(np, omode & ~mask)) {
3c0ef626 971#endif /* HAVE_FCHMOD */
972 run_err("%s: set mode: %s",
973 np, strerror(errno));
473db5ab 974 wrerr = DISPLAYED;
975 }
3c0ef626 976 }
977 if (close(ofd) == -1) {
978 wrerr = YES;
979 wrerrno = errno;
980 }
981 (void) response();
982 if (setimes && wrerr == NO) {
983 setimes = 0;
984 if (utimes(np, tv) < 0) {
985 run_err("%s: set times: %s",
986 np, strerror(errno));
987 wrerr = DISPLAYED;
988 }
989 }
990 switch (wrerr) {
991 case YES:
992 run_err("%s: %s", np, strerror(wrerrno));
993 break;
994 case NO:
473db5ab 995 (void) atomicio(vwrite, remout, "", 1);
3c0ef626 996 break;
997 case DISPLAYED:
998 break;
999 }
1000 }
1001screwup:
1002 run_err("protocol error: %s", why);
1003 exit(1);
1004}
1005
1006int
473db5ab 1007response(void)
3c0ef626 1008{
1009 char ch, *cp, resp, rbuf[2048];
1010
1011 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1012 lostconn(0);
1013
1014 cp = rbuf;
1015 switch (resp) {
1016 case 0: /* ok */
1017 return (0);
1018 default:
1019 *cp++ = resp;
1020 /* FALLTHROUGH */
1021 case 1: /* error, followed by error msg */
1022 case 2: /* fatal error, "" */
1023 do {
1024 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1025 lostconn(0);
1026 *cp++ = ch;
1027 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1028
1029 if (!iamremote)
473db5ab 1030 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
3c0ef626 1031 ++errs;
1032 if (resp == 1)
1033 return (-1);
1034 exit(1);
1035 }
1036 /* NOTREACHED */
1037}
1038
1039void
473db5ab 1040usage(void)
3c0ef626 1041{
1042 (void) fprintf(stderr,
473db5ab 1043 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1044 " [-l limit] [-o ssh_option] [-P port] [-w buffer size] [-S program]\n"
1045 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
3c0ef626 1046 exit(1);
1047}
1048
1049void
1050run_err(const char *fmt,...)
1051{
1052 static FILE *fp;
1053 va_list ap;
1054
1055 ++errs;
1056 if (fp == NULL && !(fp = fdopen(remout, "w")))
1057 return;
1058 (void) fprintf(fp, "%c", 0x01);
1059 (void) fprintf(fp, "scp: ");
1060 va_start(ap, fmt);
1061 (void) vfprintf(fp, fmt, ap);
1062 va_end(ap);
1063 (void) fprintf(fp, "\n");
1064 (void) fflush(fp);
1065
1066 if (!iamremote) {
1067 va_start(ap, fmt);
1068 vfprintf(stderr, fmt, ap);
1069 va_end(ap);
1070 fprintf(stderr, "\n");
1071 }
1072}
1073
1074void
473db5ab 1075verifydir(char *cp)
3c0ef626 1076{
1077 struct stat stb;
1078
1079 if (!stat(cp, &stb)) {
1080 if (S_ISDIR(stb.st_mode))
1081 return;
1082 errno = ENOTDIR;
1083 }
1084 run_err("%s: %s", cp, strerror(errno));
473db5ab 1085 killchild(0);
3c0ef626 1086}
1087
1088int
473db5ab 1089okname(char *cp0)
3c0ef626 1090{
1091 int c;
1092 char *cp;
1093
1094 cp = cp0;
1095 do {
1096 c = (int)*cp;
1097 if (c & 0200)
1098 goto bad;
473db5ab 1099 if (!isalpha(c) && !isdigit(c)) {
1100 switch (c) {
1101 case '\'':
1102 case '"':
1103 case '`':
1104 case ' ':
1105 case '#':
1106 goto bad;
1107 default:
1108 break;
1109 }
1110 }
3c0ef626 1111 } while (*++cp);
1112 return (1);
1113
1114bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1115 return (0);
1116}
1117
1118BUF *
473db5ab 1119allocbuf(BUF *bp, int fd, int blksize)
3c0ef626 1120{
1121 size_t size;
1122#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1123 struct stat stb;
1124
1125 if (fstat(fd, &stb) < 0) {
1126 run_err("fstat: %s", strerror(errno));
1127 return (0);
1128 }
473db5ab 1129 size = roundup(stb.st_blksize, blksize);
1130 if (size == 0)
3c0ef626 1131 size = blksize;
3c0ef626 1132#else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1133 size = blksize;
1134#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1135 if (bp->cnt >= size)
1136 return (bp);
1137 if (bp->buf == NULL)
1138 bp->buf = xmalloc(size);
1139 else
1140 bp->buf = xrealloc(bp->buf, size);
1141 memset(bp->buf, 0, size);
1142 bp->cnt = size;
1143 return (bp);
1144}
1145
1146void
473db5ab 1147lostconn(int signo)
3c0ef626 1148{
1149 if (!iamremote)
1150 write(STDERR_FILENO, "lost connection\n", 16);
1151 if (signo)
1152 _exit(1);
1153 else
1154 exit(1);
1155}
This page took 0.232535 seconds and 5 git commands to generate.