]> 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"
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;
a7213e65 281 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246zS:o:F:w:")) != -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;
a7213e65 343 case 'w':
344 addargs(&args, "-w%s", optarg);
345 break;
3c0ef626 346 default:
347 usage();
348 }
349 argc -= optind;
350 argv += optind;
351
352 if ((pwd = getpwuid(userid = getuid())) == NULL)
473db5ab 353 fatal("unknown user %u", (u_int) userid);
3c0ef626 354
355 if (!isatty(STDERR_FILENO))
356 showprogress = 0;
357
358 remin = STDIN_FILENO;
359 remout = STDOUT_FILENO;
360
361 if (fflag) {
362 /* Follow "protocol", send data. */
363 (void) response();
364 source(argc, argv);
365 exit(errs != 0);
366 }
367 if (tflag) {
368 /* Receive data. */
369 sink(argc, argv);
370 exit(errs != 0);
371 }
372 if (argc < 2)
373 usage();
374 if (argc > 2)
375 targetshouldbedirectory = 1;
376
377 remin = remout = -1;
473db5ab 378 do_cmd_pid = -1;
3c0ef626 379 /* Command to be executed on remote system using "ssh". */
380 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
381 verbose_mode ? " -v" : "",
382 iamrecursive ? " -r" : "", pflag ? " -p" : "",
383 targetshouldbedirectory ? " -d" : "");
384
385 (void) signal(SIGPIPE, lostconn);
386
387 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
388 toremote(targ, argc, argv);
389 else {
3c0ef626 390 if (targetshouldbedirectory)
391 verifydir(argv[argc - 1]);
08822d99 392 tolocal(argc, argv); /* Dest is local host. */
3c0ef626 393 }
473db5ab 394 /*
395 * Finally check the exit status of the ssh process, if one was forked
396 * and no error has occured yet
397 */
398 if (do_cmd_pid != -1 && errs == 0) {
399 if (remin != -1)
400 (void) close(remin);
401 if (remout != -1)
402 (void) close(remout);
403 if (waitpid(do_cmd_pid, &status, 0) == -1)
404 errs = 1;
405 else {
406 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
407 errs = 1;
408 }
409 }
3c0ef626 410 exit(errs != 0);
411}
412
413void
473db5ab 414toremote(char *targ, int argc, char **argv)
3c0ef626 415{
416 int i, len;
473db5ab 417 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
08822d99 418 arglist alist;
419
420 memset(&alist, '\0', sizeof(alist));
421 alist.list = NULL;
3c0ef626 422
423 *targ++ = 0;
424 if (*targ == 0)
425 targ = ".";
426
473db5ab 427 arg = xstrdup(argv[argc - 1]);
428 if ((thost = strrchr(arg, '@'))) {
3c0ef626 429 /* user@host */
430 *thost++ = 0;
473db5ab 431 tuser = arg;
3c0ef626 432 if (*tuser == '\0')
433 tuser = NULL;
3c0ef626 434 } else {
473db5ab 435 thost = arg;
3c0ef626 436 tuser = NULL;
437 }
438
08822d99 439 if (tuser != NULL && !okname(tuser)) {
440 xfree(arg);
441 return;
442 }
443
3c0ef626 444 for (i = 0; i < argc - 1; i++) {
445 src = colon(argv[i]);
446 if (src) { /* remote to remote */
08822d99 447 freeargs(&alist);
448 addargs(&alist, "%s", ssh_program);
449 if (verbose_mode)
450 addargs(&alist, "-v");
451 addargs(&alist, "-x");
452 addargs(&alist, "-oClearAllForwardings yes");
453 addargs(&alist, "-n");
454
3c0ef626 455 *src++ = 0;
456 if (*src == 0)
457 src = ".";
473db5ab 458 host = strrchr(argv[i], '@');
08822d99 459
3c0ef626 460 if (host) {
461 *host++ = 0;
462 host = cleanhostname(host);
463 suser = argv[i];
464 if (*suser == '\0')
465 suser = pwd->pw_name;
08822d99 466 else if (!okname(suser))
3c0ef626 467 continue;
08822d99 468 addargs(&alist, "-l");
469 addargs(&alist, "%s", suser);
3c0ef626 470 } else {
471 host = cleanhostname(argv[i]);
3c0ef626 472 }
08822d99 473 addargs(&alist, "%s", host);
474 addargs(&alist, "%s", cmd);
475 addargs(&alist, "%s", src);
476 addargs(&alist, "%s%s%s:%s",
477 tuser ? tuser : "", tuser ? "@" : "",
478 thost, targ);
479 if (do_local_cmd(&alist) != 0)
473db5ab 480 errs = 1;
3c0ef626 481 } else { /* local to remote */
482 if (remin == -1) {
483 len = strlen(targ) + CMDNEEDS + 20;
484 bp = xmalloc(len);
485 (void) snprintf(bp, len, "%s -t %s", cmd, targ);
486 host = cleanhostname(thost);
487 if (do_cmd(host, tuser, bp, &remin,
488 &remout, argc) < 0)
489 exit(1);
490 if (response() < 0)
491 exit(1);
492 (void) xfree(bp);
493 }
494 source(1, argv + i);
495 }
496 }
497}
498
499void
473db5ab 500tolocal(int argc, char **argv)
3c0ef626 501{
502 int i, len;
503 char *bp, *host, *src, *suser;
08822d99 504 arglist alist;
505
506 memset(&alist, '\0', sizeof(alist));
507 alist.list = NULL;
3c0ef626 508
509 for (i = 0; i < argc - 1; i++) {
510 if (!(src = colon(argv[i]))) { /* Local to local. */
08822d99 511 freeargs(&alist);
512 addargs(&alist, "%s", _PATH_CP);
513 if (iamrecursive)
514 addargs(&alist, "-r");
515 if (pflag)
516 addargs(&alist, "-p");
517 addargs(&alist, "%s", argv[i]);
518 addargs(&alist, "%s", argv[argc-1]);
519 if (do_local_cmd(&alist))
3c0ef626 520 ++errs;
3c0ef626 521 continue;
522 }
523 *src++ = 0;
524 if (*src == 0)
525 src = ".";
473db5ab 526 if ((host = strrchr(argv[i], '@')) == NULL) {
3c0ef626 527 host = argv[i];
528 suser = NULL;
529 } else {
530 *host++ = 0;
531 suser = argv[i];
532 if (*suser == '\0')
533 suser = pwd->pw_name;
3c0ef626 534 }
535 host = cleanhostname(host);
536 len = strlen(src) + CMDNEEDS + 20;
537 bp = xmalloc(len);
538 (void) snprintf(bp, len, "%s -f %s", cmd, src);
539 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
540 (void) xfree(bp);
541 ++errs;
542 continue;
543 }
544 xfree(bp);
545 sink(1, argv + argc - 1);
546 (void) close(remin);
547 remin = remout = -1;
548 }
549}
550
551void
473db5ab 552source(int argc, char **argv)
3c0ef626 553{
554 struct stat stb;
555 static BUF buffer;
556 BUF *bp;
473db5ab 557 off_t i, amt, statbytes;
558 size_t result;
559 int fd = -1, haderr, indx;
560 char *last, *name, buf[16384];
3c0ef626 561 int len;
562
563 for (indx = 0; indx < argc; ++indx) {
564 name = argv[indx];
565 statbytes = 0;
566 len = strlen(name);
567 while (len > 1 && name[len-1] == '/')
568 name[--len] = '\0';
569 if (strchr(name, '\n') != NULL) {
570 run_err("%s: skipping, filename contains a newline",
571 name);
572 goto next;
573 }
574 if ((fd = open(name, O_RDONLY, 0)) < 0)
575 goto syserr;
576 if (fstat(fd, &stb) < 0) {
577syserr: run_err("%s: %s", name, strerror(errno));
578 goto next;
579 }
580 switch (stb.st_mode & S_IFMT) {
581 case S_IFREG:
582 break;
583 case S_IFDIR:
584 if (iamrecursive) {
585 rsource(name, &stb);
586 goto next;
587 }
588 /* FALLTHROUGH */
589 default:
590 run_err("%s: not a regular file", name);
591 goto next;
592 }
593 if ((last = strrchr(name, '/')) == NULL)
594 last = name;
595 else
596 ++last;
597 curfile = last;
598 if (pflag) {
599 /*
600 * Make it compatible with possible future
601 * versions expecting microseconds.
602 */
603 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
604 (u_long) stb.st_mtime,
605 (u_long) stb.st_atime);
473db5ab 606 (void) atomicio(vwrite, remout, buf, strlen(buf));
3c0ef626 607 if (response() < 0)
608 goto next;
609 }
610#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
3c0ef626 611 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
612 (u_int) (stb.st_mode & FILEMODEMASK),
08822d99 613 (long long)stb.st_size, last);
3c0ef626 614 if (verbose_mode) {
615 fprintf(stderr, "Sending file modes: %s", buf);
3c0ef626 616 }
473db5ab 617 (void) atomicio(vwrite, remout, buf, strlen(buf));
3c0ef626 618 if (response() < 0)
619 goto next;
473db5ab 620 if ((bp = allocbuf(&buffer, fd, sizeof(buf))) == NULL) {
08822d99 621next: if (fd != -1) {
622 (void) close(fd);
623 fd = -1;
624 }
3c0ef626 625 continue;
626 }
473db5ab 627 if (showprogress)
628 start_progress_meter(curfile, stb.st_size, &statbytes);
3c0ef626 629 /* Keep writing after an error so that we stay sync'd up. */
630 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
631 amt = bp->cnt;
632 if (i + amt > stb.st_size)
633 amt = stb.st_size - i;
634 if (!haderr) {
635 result = atomicio(read, fd, bp->buf, amt);
636 if (result != amt)
473db5ab 637 haderr = errno;
3c0ef626 638 }
639 if (haderr)
473db5ab 640 (void) atomicio(vwrite, remout, bp->buf, amt);
3c0ef626 641 else {
473db5ab 642 result = atomicio(vwrite, remout, bp->buf, amt);
3c0ef626 643 if (result != amt)
473db5ab 644 haderr = errno;
3c0ef626 645 statbytes += result;
646 }
473db5ab 647 if (limit_rate)
648 bwlimit(amt);
3c0ef626 649 }
650 if (showprogress)
473db5ab 651 stop_progress_meter();
3c0ef626 652
08822d99 653 if (fd != -1) {
654 if (close(fd) < 0 && !haderr)
655 haderr = errno;
656 fd = -1;
657 }
3c0ef626 658 if (!haderr)
473db5ab 659 (void) atomicio(vwrite, remout, "", 1);
3c0ef626 660 else
661 run_err("%s: %s", name, strerror(haderr));
662 (void) response();
663 }
664}
665
666void
473db5ab 667rsource(char *name, struct stat *statp)
3c0ef626 668{
669 DIR *dirp;
670 struct dirent *dp;
671 char *last, *vect[1], path[1100];
672
673 if (!(dirp = opendir(name))) {
674 run_err("%s: %s", name, strerror(errno));
675 return;
676 }
677 last = strrchr(name, '/');
678 if (last == 0)
679 last = name;
680 else
681 last++;
682 if (pflag) {
683 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
684 (u_long) statp->st_mtime,
685 (u_long) statp->st_atime);
473db5ab 686 (void) atomicio(vwrite, remout, path, strlen(path));
3c0ef626 687 if (response() < 0) {
688 closedir(dirp);
689 return;
690 }
691 }
692 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
693 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
694 if (verbose_mode)
695 fprintf(stderr, "Entering directory: %s", path);
473db5ab 696 (void) atomicio(vwrite, remout, path, strlen(path));
3c0ef626 697 if (response() < 0) {
698 closedir(dirp);
699 return;
700 }
701 while ((dp = readdir(dirp)) != NULL) {
702 if (dp->d_ino == 0)
703 continue;
704 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
705 continue;
706 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
707 run_err("%s/%s: name too long", name, dp->d_name);
708 continue;
709 }
710 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
711 vect[0] = path;
712 source(1, vect);
713 }
714 (void) closedir(dirp);
473db5ab 715 (void) atomicio(vwrite, remout, "E\n", 2);
3c0ef626 716 (void) response();
717}
718
719void
473db5ab 720bwlimit(int amount)
721{
722 static struct timeval bwstart, bwend;
723 static int lamt, thresh = 16384;
724 u_int64_t waitlen;
725 struct timespec ts, rm;
726
727 if (!timerisset(&bwstart)) {
728 gettimeofday(&bwstart, NULL);
729 return;
730 }
731
732 lamt += amount;
733 if (lamt < thresh)
734 return;
735
736 gettimeofday(&bwend, NULL);
737 timersub(&bwend, &bwstart, &bwend);
738 if (!timerisset(&bwend))
739 return;
740
741 lamt *= 8;
742 waitlen = (double)1000000L * lamt / limit_rate;
743
744 bwstart.tv_sec = waitlen / 1000000L;
745 bwstart.tv_usec = waitlen % 1000000L;
746
747 if (timercmp(&bwstart, &bwend, >)) {
748 timersub(&bwstart, &bwend, &bwend);
749
750 /* Adjust the wait time */
751 if (bwend.tv_sec) {
752 thresh /= 2;
753 if (thresh < 2048)
754 thresh = 2048;
755 } else if (bwend.tv_usec < 100) {
756 thresh *= 2;
757 if (thresh > 32768)
758 thresh = 32768;
759 }
760
761 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
762 while (nanosleep(&ts, &rm) == -1) {
763 if (errno != EINTR)
764 break;
765 ts = rm;
766 }
767 }
768
769 lamt = 0;
770 gettimeofday(&bwstart, NULL);
771}
772
773void
774sink(int argc, char **argv)
3c0ef626 775{
776 static BUF buffer;
777 struct stat stb;
778 enum {
779 YES, NO, DISPLAYED
780 } wrerr;
781 BUF *bp;
473db5ab 782 off_t i;
783 size_t j, count;
784 int amt, exists, first, mask, mode, ofd, omode;
785 off_t size, statbytes;
3c0ef626 786 int setimes, targisdir, wrerrno = 0;
473db5ab 787 char ch, *cp, *np, *targ, *why, *vect[1], buf[16384];
3c0ef626 788 struct timeval tv[2];
789
790#define atime tv[0]
791#define mtime tv[1]
473db5ab 792#define SCREWUP(str) { why = str; goto screwup; }
3c0ef626 793
794 setimes = targisdir = 0;
795 mask = umask(0);
796 if (!pflag)
797 (void) umask(mask);
798 if (argc != 1) {
799 run_err("ambiguous target");
800 exit(1);
801 }
802 targ = *argv;
803 if (targetshouldbedirectory)
804 verifydir(targ);
805
473db5ab 806 (void) atomicio(vwrite, remout, "", 1);
3c0ef626 807 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
808 targisdir = 1;
809 for (first = 1;; first = 0) {
810 cp = buf;
473db5ab 811 if (atomicio(read, remin, cp, 1) != 1)
3c0ef626 812 return;
813 if (*cp++ == '\n')
814 SCREWUP("unexpected <newline>");
815 do {
816 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
817 SCREWUP("lost connection");
818 *cp++ = ch;
819 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
820 *cp = 0;
473db5ab 821 if (verbose_mode)
822 fprintf(stderr, "Sink: %s", buf);
3c0ef626 823
824 if (buf[0] == '\01' || buf[0] == '\02') {
825 if (iamremote == 0)
473db5ab 826 (void) atomicio(vwrite, STDERR_FILENO,
3c0ef626 827 buf + 1, strlen(buf + 1));
828 if (buf[0] == '\02')
829 exit(1);
830 ++errs;
831 continue;
832 }
833 if (buf[0] == 'E') {
473db5ab 834 (void) atomicio(vwrite, remout, "", 1);
3c0ef626 835 return;
836 }
837 if (ch == '\n')
838 *--cp = 0;
839
840 cp = buf;
841 if (*cp == 'T') {
842 setimes++;
843 cp++;
844 mtime.tv_sec = strtol(cp, &cp, 10);
845 if (!cp || *cp++ != ' ')
846 SCREWUP("mtime.sec not delimited");
847 mtime.tv_usec = strtol(cp, &cp, 10);
848 if (!cp || *cp++ != ' ')
849 SCREWUP("mtime.usec not delimited");
850 atime.tv_sec = strtol(cp, &cp, 10);
851 if (!cp || *cp++ != ' ')
852 SCREWUP("atime.sec not delimited");
853 atime.tv_usec = strtol(cp, &cp, 10);
854 if (!cp || *cp++ != '\0')
855 SCREWUP("atime.usec not delimited");
473db5ab 856 (void) atomicio(vwrite, remout, "", 1);
3c0ef626 857 continue;
858 }
859 if (*cp != 'C' && *cp != 'D') {
860 /*
861 * Check for the case "rcp remote:foo\* local:bar".
862 * In this case, the line "No match." can be returned
863 * by the shell before the rcp command on the remote is
864 * executed so the ^Aerror_message convention isn't
865 * followed.
866 */
867 if (first) {
868 run_err("%s", cp);
869 exit(1);
870 }
871 SCREWUP("expected control record");
872 }
873 mode = 0;
874 for (++cp; cp < buf + 5; cp++) {
875 if (*cp < '0' || *cp > '7')
876 SCREWUP("bad mode");
877 mode = (mode << 3) | (*cp - '0');
878 }
879 if (*cp++ != ' ')
880 SCREWUP("mode not delimited");
881
882 for (size = 0; isdigit(*cp);)
883 size = size * 10 + (*cp++ - '0');
884 if (*cp++ != ' ')
885 SCREWUP("size not delimited");
473db5ab 886 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
887 run_err("error: unexpected filename: %s", cp);
888 exit(1);
889 }
3c0ef626 890 if (targisdir) {
891 static char *namebuf;
473db5ab 892 static size_t cursize;
3c0ef626 893 size_t need;
894
895 need = strlen(targ) + strlen(cp) + 250;
896 if (need > cursize) {
897 if (namebuf)
898 xfree(namebuf);
899 namebuf = xmalloc(need);
900 cursize = need;
901 }
902 (void) snprintf(namebuf, need, "%s%s%s", targ,
473db5ab 903 strcmp(targ, "/") ? "/" : "", cp);
3c0ef626 904 np = namebuf;
905 } else
906 np = targ;
907 curfile = cp;
908 exists = stat(np, &stb) == 0;
909 if (buf[0] == 'D') {
910 int mod_flag = pflag;
473db5ab 911 if (!iamrecursive)
912 SCREWUP("received directory without -r");
3c0ef626 913 if (exists) {
914 if (!S_ISDIR(stb.st_mode)) {
915 errno = ENOTDIR;
916 goto bad;
917 }
918 if (pflag)
919 (void) chmod(np, mode);
920 } else {
921 /* Handle copying from a read-only
922 directory */
923 mod_flag = 1;
924 if (mkdir(np, mode | S_IRWXU) < 0)
925 goto bad;
926 }
927 vect[0] = xstrdup(np);
928 sink(1, vect);
929 if (setimes) {
930 setimes = 0;
931 if (utimes(vect[0], tv) < 0)
932 run_err("%s: set times: %s",
933 vect[0], strerror(errno));
934 }
935 if (mod_flag)
936 (void) chmod(vect[0], mode);
937 if (vect[0])
938 xfree(vect[0]);
939 continue;
940 }
941 omode = mode;
942 mode |= S_IWRITE;
943 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
944bad: run_err("%s: %s", np, strerror(errno));
945 continue;
946 }
473db5ab 947 (void) atomicio(vwrite, remout, "", 1);
948 if ((bp = allocbuf(&buffer, ofd, sizeof(buf))) == NULL) {
3c0ef626 949 (void) close(ofd);
950 continue;
951 }
952 cp = bp->buf;
953 wrerr = NO;
954
3c0ef626 955 statbytes = 0;
473db5ab 956 if (showprogress)
957 start_progress_meter(curfile, size, &statbytes);
958 for (count = i = 0; i < size; i += sizeof(buf)) {
959 amt = sizeof(buf);
3c0ef626 960 if (i + amt > size)
961 amt = size - i;
962 count += amt;
963 do {
473db5ab 964 j = atomicio(read, remin, cp, amt);
965 if (j == 0) {
3c0ef626 966 run_err("%s", j ? strerror(errno) :
967 "dropped connection");
968 exit(1);
969 }
970 amt -= j;
971 cp += j;
972 statbytes += j;
973 } while (amt > 0);
473db5ab 974
975 if (limit_rate)
976 bwlimit(sizeof(buf));
977
3c0ef626 978 if (count == bp->cnt) {
979 /* Keep reading so we stay sync'd up. */
980 if (wrerr == NO) {
473db5ab 981 if (atomicio(vwrite, ofd, bp->buf,
982 count) != count) {
3c0ef626 983 wrerr = YES;
473db5ab 984 wrerrno = errno;
3c0ef626 985 }
986 }
987 count = 0;
988 cp = bp->buf;
989 }
990 }
991 if (showprogress)
473db5ab 992 stop_progress_meter();
3c0ef626 993 if (count != 0 && wrerr == NO &&
473db5ab 994 atomicio(vwrite, ofd, bp->buf, count) != count) {
3c0ef626 995 wrerr = YES;
473db5ab 996 wrerrno = errno;
3c0ef626 997 }
473db5ab 998 if (wrerr == NO && ftruncate(ofd, size) != 0) {
3c0ef626 999 run_err("%s: truncate: %s", np, strerror(errno));
1000 wrerr = DISPLAYED;
1001 }
1002 if (pflag) {
1003 if (exists || omode != mode)
1004#ifdef HAVE_FCHMOD
473db5ab 1005 if (fchmod(ofd, omode)) {
3c0ef626 1006#else /* HAVE_FCHMOD */
473db5ab 1007 if (chmod(np, omode)) {
3c0ef626 1008#endif /* HAVE_FCHMOD */
1009 run_err("%s: set mode: %s",
1010 np, strerror(errno));
473db5ab 1011 wrerr = DISPLAYED;
1012 }
3c0ef626 1013 } else {
1014 if (!exists && omode != mode)
1015#ifdef HAVE_FCHMOD
473db5ab 1016 if (fchmod(ofd, omode & ~mask)) {
3c0ef626 1017#else /* HAVE_FCHMOD */
473db5ab 1018 if (chmod(np, omode & ~mask)) {
3c0ef626 1019#endif /* HAVE_FCHMOD */
1020 run_err("%s: set mode: %s",
1021 np, strerror(errno));
473db5ab 1022 wrerr = DISPLAYED;
1023 }
3c0ef626 1024 }
1025 if (close(ofd) == -1) {
1026 wrerr = YES;
1027 wrerrno = errno;
1028 }
1029 (void) response();
1030 if (setimes && wrerr == NO) {
1031 setimes = 0;
1032 if (utimes(np, tv) < 0) {
1033 run_err("%s: set times: %s",
1034 np, strerror(errno));
1035 wrerr = DISPLAYED;
1036 }
1037 }
1038 switch (wrerr) {
1039 case YES:
1040 run_err("%s: %s", np, strerror(wrerrno));
1041 break;
1042 case NO:
473db5ab 1043 (void) atomicio(vwrite, remout, "", 1);
3c0ef626 1044 break;
1045 case DISPLAYED:
1046 break;
1047 }
1048 }
1049screwup:
1050 run_err("protocol error: %s", why);
1051 exit(1);
1052}
1053
1054int
473db5ab 1055response(void)
3c0ef626 1056{
1057 char ch, *cp, resp, rbuf[2048];
1058
1059 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1060 lostconn(0);
1061
1062 cp = rbuf;
1063 switch (resp) {
1064 case 0: /* ok */
1065 return (0);
1066 default:
1067 *cp++ = resp;
1068 /* FALLTHROUGH */
1069 case 1: /* error, followed by error msg */
1070 case 2: /* fatal error, "" */
1071 do {
1072 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1073 lostconn(0);
1074 *cp++ = ch;
1075 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1076
1077 if (!iamremote)
473db5ab 1078 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
3c0ef626 1079 ++errs;
1080 if (resp == 1)
1081 return (-1);
1082 exit(1);
1083 }
1084 /* NOTREACHED */
1085}
1086
1087void
473db5ab 1088usage(void)
3c0ef626 1089{
1090 (void) fprintf(stderr,
473db5ab 1091 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
a7213e65 1092 " [-l limit] [-o ssh_option] [-P port] [-w buffer size] [-S program]\n"
473db5ab 1093 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
3c0ef626 1094 exit(1);
1095}
1096
1097void
1098run_err(const char *fmt,...)
1099{
1100 static FILE *fp;
1101 va_list ap;
1102
1103 ++errs;
1104 if (fp == NULL && !(fp = fdopen(remout, "w")))
1105 return;
1106 (void) fprintf(fp, "%c", 0x01);
1107 (void) fprintf(fp, "scp: ");
1108 va_start(ap, fmt);
1109 (void) vfprintf(fp, fmt, ap);
1110 va_end(ap);
1111 (void) fprintf(fp, "\n");
1112 (void) fflush(fp);
1113
1114 if (!iamremote) {
1115 va_start(ap, fmt);
1116 vfprintf(stderr, fmt, ap);
1117 va_end(ap);
1118 fprintf(stderr, "\n");
1119 }
1120}
1121
1122void
473db5ab 1123verifydir(char *cp)
3c0ef626 1124{
1125 struct stat stb;
1126
1127 if (!stat(cp, &stb)) {
1128 if (S_ISDIR(stb.st_mode))
1129 return;
1130 errno = ENOTDIR;
1131 }
1132 run_err("%s: %s", cp, strerror(errno));
473db5ab 1133 killchild(0);
3c0ef626 1134}
1135
1136int
473db5ab 1137okname(char *cp0)
3c0ef626 1138{
1139 int c;
1140 char *cp;
1141
1142 cp = cp0;
1143 do {
1144 c = (int)*cp;
1145 if (c & 0200)
1146 goto bad;
473db5ab 1147 if (!isalpha(c) && !isdigit(c)) {
1148 switch (c) {
1149 case '\'':
1150 case '"':
1151 case '`':
1152 case ' ':
1153 case '#':
1154 goto bad;
1155 default:
1156 break;
1157 }
1158 }
3c0ef626 1159 } while (*++cp);
1160 return (1);
1161
1162bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1163 return (0);
1164}
1165
1166BUF *
473db5ab 1167allocbuf(BUF *bp, int fd, int blksize)
3c0ef626 1168{
1169 size_t size;
1170#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1171 struct stat stb;
1172
1173 if (fstat(fd, &stb) < 0) {
1174 run_err("fstat: %s", strerror(errno));
1175 return (0);
1176 }
473db5ab 1177 size = roundup(stb.st_blksize, blksize);
1178 if (size == 0)
3c0ef626 1179 size = blksize;
3c0ef626 1180#else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1181 size = blksize;
1182#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1183 if (bp->cnt >= size)
1184 return (bp);
1185 if (bp->buf == NULL)
1186 bp->buf = xmalloc(size);
1187 else
1188 bp->buf = xrealloc(bp->buf, size);
1189 memset(bp->buf, 0, size);
1190 bp->cnt = size;
1191 return (bp);
1192}
1193
1194void
473db5ab 1195lostconn(int signo)
3c0ef626 1196{
1197 if (!iamremote)
1198 write(STDERR_FILENO, "lost connection\n", 16);
1199 if (signo)
1200 _exit(1);
1201 else
1202 exit(1);
1203}
This page took 1.543172 seconds and 5 git commands to generate.