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