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