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