]> andersk Git - openssh.git/blame - scp.c
- (tim) [buildpkg.sh.in] Some systems have really limited nawk (OpenServer).
[openssh.git] / scp.c
CommitLineData
31652869 1/* $OpenBSD: scp.c,v 1.155 2006/08/03 03:34:42 deraadt Exp $ */
8efc0c15 2/*
bcbf86ec 3 * scp - secure remote copy. This is basically patched BSD rcp which
4 * uses ssh to do the data transfer (instead of using rcmd).
6ae2364d 5 *
bcbf86ec 6 * NOTE: This version should NOT be suid root. (This uses ssh to
7 * do the transfer and ssh has the necessary privileges.)
6ae2364d 8 *
5260325f 9 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
6ae2364d 10 *
bcbf86ec 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/*
f3c7c613 18 * Copyright (c) 1999 Theo de Raadt. All rights reserved.
19 * Copyright (c) 1999 Aaron Campbell. All rights reserved.
bcbf86ec 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 */
8efc0c15 41
42/*
2e73a022 43 * Parts from:
44 *
8efc0c15 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.
d981089c 56 * 3. Neither the name of the University nor the names of its contributors
8efc0c15 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 *
8efc0c15 72 */
73
74#include "includes.h"
aa2eae64 75
76#include <sys/types.h>
536c14e8 77#include <sys/param.h>
4095f623 78#ifdef HAVE_SYS_STAT_H
79# include <sys/stat.h>
80#endif
e264ac72 81#ifdef HAVE_SYS_TIME_H
82# include <sys/time.h>
83#endif
aa2eae64 84#include <sys/wait.h>
31652869 85#include <sys/uio.h>
68e39d38 86
b6438382 87#include <ctype.h>
68e39d38 88#include <dirent.h>
028094f4 89#include <errno.h>
d3221cca 90#include <fcntl.h>
b1842393 91#include <pwd.h>
ada68823 92#include <signal.h>
4c72fcfd 93#include <stdarg.h>
cf851879 94#include <stdio.h>
ffa517a8 95#include <stdlib.h>
00146caa 96#include <string.h>
b0f6943a 97#include <time.h>
5188ba17 98#include <unistd.h>
8efc0c15 99
8efc0c15 100#include "xmalloc.h"
42f11eb2 101#include "atomicio.h"
102#include "pathnames.h"
103#include "log.h"
36a358ca 104#include "misc.h"
b65c3807 105#include "progressmeter.h"
8efc0c15 106
260d427b 107extern char *__progname;
260d427b 108
ac93e676 109int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
110
6ea3c52a 111void bwlimit(int);
112
8a624ebf 113/* Struct for addargs */
114arglist args;
94ec8c6b 115
6ea3c52a 116/* Bandwidth limit */
10adbb52 117off_t limit_rate = 0;
6ea3c52a 118
8efc0c15 119/* Name of current file being transferred. */
120char *curfile;
121
122/* This is set to non-zero to enable verbose mode. */
5260325f 123int verbose_mode = 0;
8efc0c15 124
8efc0c15 125/* This is set to zero if the progressmeter is not desired. */
126int showprogress = 1;
127
2e73a022 128/* This is the program to execute for the secured connection. ("ssh" or -S) */
42f11eb2 129char *ssh_program = _PATH_SSH_PROGRAM;
2e73a022 130
252d1a24 131/* This is used to store the pid of ssh_program */
0f764b2f 132pid_t do_cmd_pid = -1;
133
134static void
135killchild(int signo)
136{
3c03ad3f 137 if (do_cmd_pid > 1) {
8f4ab41b 138 kill(do_cmd_pid, signo ? signo : SIGTERM);
3c03ad3f 139 waitpid(do_cmd_pid, NULL, 0);
140 }
0f764b2f 141
8f4ab41b 142 if (signo)
143 _exit(1);
144 exit(1);
0f764b2f 145}
252d1a24 146
4116f5c0 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
aa3378df 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 */
8efc0c15 194
6ae2364d 195int
ac93e676 196do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
8efc0c15 197{
5260325f 198 int pin[2], pout[2], reserved[2];
199
200 if (verbose_mode)
0b2988ca 201 fprintf(stderr,
202 "Executing: program %s host %s, user %s, command %s\n",
203 ssh_program, host,
204 remuser ? remuser : "(unspecified)", cmd);
5260325f 205
aa3378df 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 */
2b8dc5e3 210 if (pipe(reserved) < 0)
211 fatal("pipe: %s", strerror(errno));
5260325f 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
1fb23629 223 /* Fork a child to execute the command on the remote host using ssh. */
252d1a24 224 do_cmd_pid = fork();
225 if (do_cmd_pid == 0) {
5260325f 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
4116f5c0 234 replacearg(&args, 0, "%s", ssh_program);
94ec8c6b 235 if (remuser != NULL)
8a624ebf 236 addargs(&args, "-l%s", remuser);
237 addargs(&args, "%s", host);
238 addargs(&args, "%s", cmd);
5260325f 239
94ec8c6b 240 execvp(ssh_program, args.list);
2e73a022 241 perror(ssh_program);
5260325f 242 exit(1);
252d1a24 243 } else if (do_cmd_pid == -1) {
244 fatal("fork: %s", strerror(errno));
8efc0c15 245 }
5260325f 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];
0f764b2f 251 signal(SIGTERM, killchild);
252 signal(SIGINT, killchild);
253 signal(SIGHUP, killchild);
5260325f 254 return 0;
8efc0c15 255}
256
8efc0c15 257typedef struct {
2ceb8101 258 size_t cnt;
8efc0c15 259 char *buf;
260} BUF;
261
5260325f 262BUF *allocbuf(BUF *, int, int);
5260325f 263void lostconn(int);
5260325f 264int okname(char *);
265void run_err(const char *,...);
266void verifydir(char *);
8efc0c15 267
8efc0c15 268struct passwd *pwd;
5260325f 269uid_t userid;
8efc0c15 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
5260325f 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);
8efc0c15 283
284int
cf3248b8 285main(int argc, char **argv)
8efc0c15 286{
1879b184 287 int ch, fflag, tflag, status, n;
6ea3c52a 288 double speed;
1879b184 289 char *targ, *endp, **newargv;
8efc0c15 290 extern char *optarg;
291 extern int optind;
292
fd6168c1 293 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
294 sanitise_stdfd();
295
1879b184 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
fda04d7d 302 __progname = ssh_get_progname(argv[0]);
260d427b 303
4116f5c0 304 memset(&args, '\0', sizeof(args));
94ec8c6b 305 args.list = NULL;
4116f5c0 306 addargs(&args, "%s", ssh_program);
8a624ebf 307 addargs(&args, "-x");
3a222388 308 addargs(&args, "-oForwardAgent no");
d20f3c9e 309 addargs(&args, "-oPermitLocalCommand no");
e1c5bfaf 310 addargs(&args, "-oClearAllForwardings yes");
94ec8c6b 311
8efc0c15 312 fflag = tflag = 0;
e6b15f23 313 while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
5260325f 314 switch (ch) {
315 /* User-visible flags. */
e6b15f23 316 case '1':
317 case '2':
48e671d5 318 case '4':
48e671d5 319 case '6':
94ec8c6b 320 case 'C':
8a624ebf 321 addargs(&args, "-%c", ch);
48e671d5 322 break;
94ec8c6b 323 case 'o':
324 case 'c':
325 case 'i':
f1278af7 326 case 'F':
8a624ebf 327 addargs(&args, "-%c%s", ch, optarg);
8efc0c15 328 break;
329 case 'P':
8a624ebf 330 addargs(&args, "-p%s", optarg);
94ec8c6b 331 break;
332 case 'B':
8a624ebf 333 addargs(&args, "-oBatchmode yes");
94ec8c6b 334 break;
6ea3c52a 335 case 'l':
336 speed = strtod(optarg, &endp);
337 if (speed <= 0 || *endp != '\0')
338 usage();
10adbb52 339 limit_rate = speed * 1024;
6ea3c52a 340 break;
94ec8c6b 341 case 'p':
342 pflag = 1;
5260325f 343 break;
8efc0c15 344 case 'r':
345 iamrecursive = 1;
346 break;
2e73a022 347 case 'S':
94ec8c6b 348 ssh_program = xstrdup(optarg);
349 break;
350 case 'v':
4fc334a2 351 addargs(&args, "-v");
94ec8c6b 352 verbose_mode = 1;
353 break;
354 case 'q':
15c8e3fd 355 addargs(&args, "-q");
94ec8c6b 356 showprogress = 0;
2e73a022 357 break;
358
5260325f 359 /* Server options. */
8efc0c15 360 case 'd':
361 targetshouldbedirectory = 1;
362 break;
5260325f 363 case 'f': /* "from" */
8efc0c15 364 iamremote = 1;
365 fflag = 1;
366 break;
5260325f 367 case 't': /* "to" */
8efc0c15 368 iamremote = 1;
369 tflag = 1;
fe56c12b 370#ifdef HAVE_CYGWIN
371 setmode(0, O_BINARY);
372#endif
8efc0c15 373 break;
8efc0c15 374 default:
375 usage();
376 }
377 argc -= optind;
378 argv += optind;
379
380 if ((pwd = getpwuid(userid = getuid())) == NULL)
261bd618 381 fatal("unknown user %u", (u_int) userid);
8efc0c15 382
5260325f 383 if (!isatty(STDERR_FILENO))
8efc0c15 384 showprogress = 0;
385
386 remin = STDIN_FILENO;
387 remout = STDOUT_FILENO;
388
2b87da3b 389 if (fflag) {
5260325f 390 /* Follow "protocol", send data. */
391 (void) response();
8efc0c15 392 source(argc, argv);
393 exit(errs != 0);
394 }
5260325f 395 if (tflag) {
396 /* Receive data. */
8efc0c15 397 sink(argc, argv);
398 exit(errs != 0);
399 }
8efc0c15 400 if (argc < 2)
401 usage();
402 if (argc > 2)
403 targetshouldbedirectory = 1;
404
405 remin = remout = -1;
252d1a24 406 do_cmd_pid = -1;
8efc0c15 407 /* Command to be executed on remote system using "ssh". */
0ed28836 408 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
409 verbose_mode ? " -v" : "",
2e73a022 410 iamrecursive ? " -r" : "", pflag ? " -p" : "",
411 targetshouldbedirectory ? " -d" : "");
8efc0c15 412
5260325f 413 (void) signal(SIGPIPE, lostconn);
8efc0c15 414
415 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
416 toremote(targ, argc, argv);
417 else {
8efc0c15 418 if (targetshouldbedirectory)
419 verifydir(argv[argc - 1]);
16e8ab10 420 tolocal(argc, argv); /* Dest is local host. */
8efc0c15 421 }
252d1a24 422 /*
423 * Finally check the exit status of the ssh process, if one was forked
424 * and no error has occured yet
425 */
426 if (do_cmd_pid != -1 && errs == 0) {
427 if (remin != -1)
428 (void) close(remin);
429 if (remout != -1)
430 (void) close(remout);
431 if (waitpid(do_cmd_pid, &status, 0) == -1)
432 errs = 1;
433 else {
434 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
435 errs = 1;
436 }
437 }
8efc0c15 438 exit(errs != 0);
439}
440
441void
cf3248b8 442toremote(char *targ, int argc, char **argv)
8efc0c15 443{
99dfaccc 444 char *bp, *host, *src, *suser, *thost, *tuser, *arg;
4116f5c0 445 arglist alist;
ac93e676 446 int i;
4116f5c0 447
448 memset(&alist, '\0', sizeof(alist));
449 alist.list = NULL;
8efc0c15 450
451 *targ++ = 0;
452 if (*targ == 0)
453 targ = ".";
454
ae0d2f42 455 arg = xstrdup(argv[argc - 1]);
99dfaccc 456 if ((thost = strrchr(arg, '@'))) {
8efc0c15 457 /* user@host */
458 *thost++ = 0;
99dfaccc 459 tuser = arg;
8efc0c15 460 if (*tuser == '\0')
461 tuser = NULL;
8efc0c15 462 } else {
99dfaccc 463 thost = arg;
8efc0c15 464 tuser = NULL;
465 }
466
4116f5c0 467 if (tuser != NULL && !okname(tuser)) {
468 xfree(arg);
469 return;
470 }
471
8efc0c15 472 for (i = 0; i < argc - 1; i++) {
473 src = colon(argv[i]);
5260325f 474 if (src) { /* remote to remote */
4116f5c0 475 freeargs(&alist);
476 addargs(&alist, "%s", ssh_program);
477 if (verbose_mode)
478 addargs(&alist, "-v");
479 addargs(&alist, "-x");
480 addargs(&alist, "-oClearAllForwardings yes");
481 addargs(&alist, "-n");
482
8efc0c15 483 *src++ = 0;
484 if (*src == 0)
485 src = ".";
15748b4d 486 host = strrchr(argv[i], '@');
4116f5c0 487
8efc0c15 488 if (host) {
489 *host++ = 0;
48e671d5 490 host = cleanhostname(host);
8efc0c15 491 suser = argv[i];
492 if (*suser == '\0')
493 suser = pwd->pw_name;
4116f5c0 494 else if (!okname(suser))
0ec7661a 495 continue;
4116f5c0 496 addargs(&alist, "-l");
497 addargs(&alist, "%s", suser);
48e671d5 498 } else {
499 host = cleanhostname(argv[i]);
48e671d5 500 }
4116f5c0 501 addargs(&alist, "%s", host);
502 addargs(&alist, "%s", cmd);
503 addargs(&alist, "%s", src);
504 addargs(&alist, "%s%s%s:%s",
505 tuser ? tuser : "", tuser ? "@" : "",
506 thost, targ);
507 if (do_local_cmd(&alist) != 0)
815a8407 508 errs = 1;
5260325f 509 } else { /* local to remote */
8efc0c15 510 if (remin == -1) {
c0a8e7bb 511 xasprintf(&bp, "%s -t %s", cmd, targ);
48e671d5 512 host = cleanhostname(thost);
2e73a022 513 if (do_cmd(host, tuser, bp, &remin,
ac93e676 514 &remout) < 0)
5260325f 515 exit(1);
8efc0c15 516 if (response() < 0)
517 exit(1);
5260325f 518 (void) xfree(bp);
8efc0c15 519 }
5260325f 520 source(1, argv + i);
8efc0c15 521 }
522 }
2b8dc5e3 523 xfree(arg);
8efc0c15 524}
525
526void
cf3248b8 527tolocal(int argc, char **argv)
8efc0c15 528{
8efc0c15 529 char *bp, *host, *src, *suser;
4116f5c0 530 arglist alist;
ac93e676 531 int i;
4116f5c0 532
533 memset(&alist, '\0', sizeof(alist));
534 alist.list = NULL;
8efc0c15 535
536 for (i = 0; i < argc - 1; i++) {
5260325f 537 if (!(src = colon(argv[i]))) { /* Local to local. */
4116f5c0 538 freeargs(&alist);
539 addargs(&alist, "%s", _PATH_CP);
540 if (iamrecursive)
541 addargs(&alist, "-r");
542 if (pflag)
543 addargs(&alist, "-p");
544 addargs(&alist, "%s", argv[i]);
545 addargs(&alist, "%s", argv[argc-1]);
546 if (do_local_cmd(&alist))
8efc0c15 547 ++errs;
8efc0c15 548 continue;
549 }
550 *src++ = 0;
551 if (*src == 0)
552 src = ".";
15748b4d 553 if ((host = strrchr(argv[i], '@')) == NULL) {
8efc0c15 554 host = argv[i];
555 suser = NULL;
556 } else {
557 *host++ = 0;
558 suser = argv[i];
559 if (*suser == '\0')
560 suser = pwd->pw_name;
8efc0c15 561 }
48e671d5 562 host = cleanhostname(host);
c0a8e7bb 563 xasprintf(&bp, "%s -f %s", cmd, src);
ac93e676 564 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
5260325f 565 (void) xfree(bp);
566 ++errs;
567 continue;
8efc0c15 568 }
5260325f 569 xfree(bp);
8efc0c15 570 sink(1, argv + argc - 1);
5260325f 571 (void) close(remin);
8efc0c15 572 remin = remout = -1;
573 }
574}
575
576void
cf3248b8 577source(int argc, char **argv)
8efc0c15 578{
579 struct stat stb;
580 static BUF buffer;
581 BUF *bp;
05624c18 582 off_t i, amt, statbytes;
583 size_t result;
a056dfa2 584 int fd = -1, haderr, indx;
8efc0c15 585 char *last, *name, buf[2048];
0fc791ba 586 int len;
8efc0c15 587
588 for (indx = 0; indx < argc; ++indx) {
5260325f 589 name = argv[indx];
8efc0c15 590 statbytes = 0;
0fc791ba 591 len = strlen(name);
592 while (len > 1 && name[len-1] == '/')
593 name[--len] = '\0';
5720c10e 594 if (strchr(name, '\n') != NULL) {
595 run_err("%s: skipping, filename contains a newline",
596 name);
597 goto next;
598 }
8efc0c15 599 if ((fd = open(name, O_RDONLY, 0)) < 0)
600 goto syserr;
601 if (fstat(fd, &stb) < 0) {
602syserr: run_err("%s: %s", name, strerror(errno));
603 goto next;
604 }
605 switch (stb.st_mode & S_IFMT) {
606 case S_IFREG:
607 break;
608 case S_IFDIR:
609 if (iamrecursive) {
610 rsource(name, &stb);
611 goto next;
612 }
613 /* FALLTHROUGH */
614 default:
615 run_err("%s: not a regular file", name);
616 goto next;
617 }
618 if ((last = strrchr(name, '/')) == NULL)
619 last = name;
620 else
621 ++last;
622 curfile = last;
623 if (pflag) {
624 /*
625 * Make it compatible with possible future
626 * versions expecting microseconds.
627 */
0ed28836 628 (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
1e3b8b07 629 (u_long) stb.st_mtime,
630 (u_long) stb.st_atime);
dc54438a 631 (void) atomicio(vwrite, remout, buf, strlen(buf));
8efc0c15 632 if (response() < 0)
633 goto next;
634 }
635#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
bf1d27bd 636 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1e3b8b07 637 (u_int) (stb.st_mode & FILEMODEMASK),
419094c6 638 (long long)stb.st_size, last);
5260325f 639 if (verbose_mode) {
640 fprintf(stderr, "Sending file modes: %s", buf);
5260325f 641 }
dc54438a 642 (void) atomicio(vwrite, remout, buf, strlen(buf));
8efc0c15 643 if (response() < 0)
644 goto next;
645 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
29accf74 646next: if (fd != -1) {
647 (void) close(fd);
648 fd = -1;
649 }
8efc0c15 650 continue;
651 }
b65c3807 652 if (showprogress)
653 start_progress_meter(curfile, stb.st_size, &statbytes);
8efc0c15 654 /* Keep writing after an error so that we stay sync'd up. */
655 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
656 amt = bp->cnt;
657 if (i + amt > stb.st_size)
658 amt = stb.st_size - i;
659 if (!haderr) {
1d1ffb87 660 result = atomicio(read, fd, bp->buf, amt);
8efc0c15 661 if (result != amt)
05624c18 662 haderr = errno;
8efc0c15 663 }
664 if (haderr)
dc54438a 665 (void) atomicio(vwrite, remout, bp->buf, amt);
8efc0c15 666 else {
dc54438a 667 result = atomicio(vwrite, remout, bp->buf, amt);
8efc0c15 668 if (result != amt)
05624c18 669 haderr = errno;
8efc0c15 670 statbytes += result;
671 }
10adbb52 672 if (limit_rate)
6ea3c52a 673 bwlimit(amt);
8efc0c15 674 }
5260325f 675 if (showprogress)
b65c3807 676 stop_progress_meter();
8efc0c15 677
29accf74 678 if (fd != -1) {
679 if (close(fd) < 0 && !haderr)
680 haderr = errno;
681 fd = -1;
682 }
8efc0c15 683 if (!haderr)
dc54438a 684 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 685 else
686 run_err("%s: %s", name, strerror(haderr));
5260325f 687 (void) response();
8efc0c15 688 }
689}
690
691void
cf3248b8 692rsource(char *name, struct stat *statp)
8efc0c15 693{
694 DIR *dirp;
695 struct dirent *dp;
696 char *last, *vect[1], path[1100];
697
698 if (!(dirp = opendir(name))) {
699 run_err("%s: %s", name, strerror(errno));
700 return;
701 }
702 last = strrchr(name, '/');
703 if (last == 0)
704 last = name;
705 else
706 last++;
707 if (pflag) {
0ed28836 708 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
1e3b8b07 709 (u_long) statp->st_mtime,
710 (u_long) statp->st_atime);
dc54438a 711 (void) atomicio(vwrite, remout, path, strlen(path));
8efc0c15 712 if (response() < 0) {
713 closedir(dirp);
714 return;
715 }
716 }
0ed28836 717 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1e3b8b07 718 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
5260325f 719 if (verbose_mode)
720 fprintf(stderr, "Entering directory: %s", path);
dc54438a 721 (void) atomicio(vwrite, remout, path, strlen(path));
8efc0c15 722 if (response() < 0) {
723 closedir(dirp);
724 return;
725 }
e5ff6ecf 726 while ((dp = readdir(dirp)) != NULL) {
8efc0c15 727 if (dp->d_ino == 0)
728 continue;
729 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
730 continue;
731 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
732 run_err("%s/%s: name too long", name, dp->d_name);
733 continue;
734 }
0ed28836 735 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
8efc0c15 736 vect[0] = path;
737 source(1, vect);
738 }
5260325f 739 (void) closedir(dirp);
dc54438a 740 (void) atomicio(vwrite, remout, "E\n", 2);
5260325f 741 (void) response();
8efc0c15 742}
743
6ea3c52a 744void
745bwlimit(int amount)
746{
747 static struct timeval bwstart, bwend;
748 static int lamt, thresh = 16384;
ca75d7de 749 u_int64_t waitlen;
6ea3c52a 750 struct timespec ts, rm;
751
752 if (!timerisset(&bwstart)) {
753 gettimeofday(&bwstart, NULL);
754 return;
755 }
756
757 lamt += amount;
758 if (lamt < thresh)
759 return;
760
761 gettimeofday(&bwend, NULL);
762 timersub(&bwend, &bwstart, &bwend);
763 if (!timerisset(&bwend))
764 return;
765
766 lamt *= 8;
ca75d7de 767 waitlen = (double)1000000L * lamt / limit_rate;
6ea3c52a 768
ca75d7de 769 bwstart.tv_sec = waitlen / 1000000L;
770 bwstart.tv_usec = waitlen % 1000000L;
6ea3c52a 771
772 if (timercmp(&bwstart, &bwend, >)) {
773 timersub(&bwstart, &bwend, &bwend);
774
775 /* Adjust the wait time */
776 if (bwend.tv_sec) {
777 thresh /= 2;
778 if (thresh < 2048)
779 thresh = 2048;
780 } else if (bwend.tv_usec < 100) {
781 thresh *= 2;
782 if (thresh > 32768)
783 thresh = 32768;
784 }
785
786 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
787 while (nanosleep(&ts, &rm) == -1) {
788 if (errno != EINTR)
789 break;
790 ts = rm;
791 }
792 }
793
794 lamt = 0;
795 gettimeofday(&bwstart, NULL);
796}
797
8efc0c15 798void
cf3248b8 799sink(int argc, char **argv)
8efc0c15 800{
801 static BUF buffer;
802 struct stat stb;
5260325f 803 enum {
804 YES, NO, DISPLAYED
805 } wrerr;
8efc0c15 806 BUF *bp;
05624c18 807 off_t i;
2ceb8101 808 size_t j, count;
ac93e676 809 int amt, exists, first, ofd;
810 mode_t mode, omode, mask;
b65c3807 811 off_t size, statbytes;
14a9a859 812 int setimes, targisdir, wrerrno = 0;
8efc0c15 813 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
188adeb2 814 struct timeval tv[2];
8efc0c15 815
36967a16 816#define atime tv[0]
817#define mtime tv[1]
007607ab 818#define SCREWUP(str) { why = str; goto screwup; }
8efc0c15 819
820 setimes = targisdir = 0;
821 mask = umask(0);
822 if (!pflag)
5260325f 823 (void) umask(mask);
8efc0c15 824 if (argc != 1) {
825 run_err("ambiguous target");
826 exit(1);
827 }
828 targ = *argv;
829 if (targetshouldbedirectory)
830 verifydir(targ);
5260325f 831
dc54438a 832 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 833 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
834 targisdir = 1;
835 for (first = 1;; first = 0) {
836 cp = buf;
05624c18 837 if (atomicio(read, remin, cp, 1) != 1)
8efc0c15 838 return;
839 if (*cp++ == '\n')
840 SCREWUP("unexpected <newline>");
841 do {
1d1ffb87 842 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 843 SCREWUP("lost connection");
844 *cp++ = ch;
845 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
846 *cp = 0;
f09aa22c 847 if (verbose_mode)
848 fprintf(stderr, "Sink: %s", buf);
8efc0c15 849
850 if (buf[0] == '\01' || buf[0] == '\02') {
851 if (iamremote == 0)
dc54438a 852 (void) atomicio(vwrite, STDERR_FILENO,
71c0d06a 853 buf + 1, strlen(buf + 1));
8efc0c15 854 if (buf[0] == '\02')
855 exit(1);
856 ++errs;
857 continue;
858 }
859 if (buf[0] == 'E') {
dc54438a 860 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 861 return;
862 }
8efc0c15 863 if (ch == '\n')
864 *--cp = 0;
865
8efc0c15 866 cp = buf;
867 if (*cp == 'T') {
868 setimes++;
869 cp++;
36967a16 870 mtime.tv_sec = strtol(cp, &cp, 10);
871 if (!cp || *cp++ != ' ')
8efc0c15 872 SCREWUP("mtime.sec not delimited");
36967a16 873 mtime.tv_usec = strtol(cp, &cp, 10);
874 if (!cp || *cp++ != ' ')
8efc0c15 875 SCREWUP("mtime.usec not delimited");
36967a16 876 atime.tv_sec = strtol(cp, &cp, 10);
877 if (!cp || *cp++ != ' ')
8efc0c15 878 SCREWUP("atime.sec not delimited");
36967a16 879 atime.tv_usec = strtol(cp, &cp, 10);
880 if (!cp || *cp++ != '\0')
8efc0c15 881 SCREWUP("atime.usec not delimited");
dc54438a 882 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 883 continue;
884 }
885 if (*cp != 'C' && *cp != 'D') {
886 /*
887 * Check for the case "rcp remote:foo\* local:bar".
888 * In this case, the line "No match." can be returned
889 * by the shell before the rcp command on the remote is
890 * executed so the ^Aerror_message convention isn't
891 * followed.
892 */
893 if (first) {
894 run_err("%s", cp);
895 exit(1);
896 }
897 SCREWUP("expected control record");
898 }
899 mode = 0;
900 for (++cp; cp < buf + 5; cp++) {
901 if (*cp < '0' || *cp > '7')
902 SCREWUP("bad mode");
903 mode = (mode << 3) | (*cp - '0');
904 }
905 if (*cp++ != ' ')
906 SCREWUP("mode not delimited");
907
e5ff6ecf 908 for (size = 0; isdigit(*cp);)
8efc0c15 909 size = size * 10 + (*cp++ - '0');
910 if (*cp++ != ' ')
911 SCREWUP("size not delimited");
f09aa22c 912 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
913 run_err("error: unexpected filename: %s", cp);
914 exit(1);
915 }
8efc0c15 916 if (targisdir) {
917 static char *namebuf;
2ceb8101 918 static size_t cursize;
8efc0c15 919 size_t need;
920
921 need = strlen(targ) + strlen(cp) + 250;
0ed28836 922 if (need > cursize) {
923 if (namebuf)
924 xfree(namebuf);
5260325f 925 namebuf = xmalloc(need);
0ed28836 926 cursize = need;
927 }
928 (void) snprintf(namebuf, need, "%s%s%s", targ,
39f9599a 929 strcmp(targ, "/") ? "/" : "", cp);
8efc0c15 930 np = namebuf;
931 } else
932 np = targ;
933 curfile = cp;
934 exists = stat(np, &stb) == 0;
935 if (buf[0] == 'D') {
936 int mod_flag = pflag;
f09aa22c 937 if (!iamrecursive)
938 SCREWUP("received directory without -r");
8efc0c15 939 if (exists) {
940 if (!S_ISDIR(stb.st_mode)) {
941 errno = ENOTDIR;
942 goto bad;
943 }
944 if (pflag)
5260325f 945 (void) chmod(np, mode);
8efc0c15 946 } else {
5260325f 947 /* Handle copying from a read-only
948 directory */
8efc0c15 949 mod_flag = 1;
950 if (mkdir(np, mode | S_IRWXU) < 0)
951 goto bad;
952 }
5c470997 953 vect[0] = xstrdup(np);
8efc0c15 954 sink(1, vect);
955 if (setimes) {
956 setimes = 0;
e68225b2 957 if (utimes(vect[0], tv) < 0)
5260325f 958 run_err("%s: set times: %s",
e68225b2 959 vect[0], strerror(errno));
8efc0c15 960 }
961 if (mod_flag)
e68225b2 962 (void) chmod(vect[0], mode);
963 if (vect[0])
964 xfree(vect[0]);
8efc0c15 965 continue;
966 }
967 omode = mode;
968 mode |= S_IWRITE;
3e4fc5f9 969 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
8efc0c15 970bad: run_err("%s: %s", np, strerror(errno));
971 continue;
972 }
dc54438a 973 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 974 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
5260325f 975 (void) close(ofd);
8efc0c15 976 continue;
977 }
978 cp = bp->buf;
979 wrerr = NO;
980
8efc0c15 981 statbytes = 0;
b65c3807 982 if (showprogress)
983 start_progress_meter(curfile, size, &statbytes);
8efc0c15 984 for (count = i = 0; i < size; i += 4096) {
985 amt = 4096;
986 if (i + amt > size)
987 amt = size - i;
988 count += amt;
989 do {
f581b6e8 990 j = atomicio(read, remin, cp, amt);
05624c18 991 if (j == 0) {
8efc0c15 992 run_err("%s", j ? strerror(errno) :
e5ff6ecf 993 "dropped connection");
8efc0c15 994 exit(1);
995 }
996 amt -= j;
997 cp += j;
5260325f 998 statbytes += j;
8efc0c15 999 } while (amt > 0);
b6453d99 1000
10adbb52 1001 if (limit_rate)
6ea3c52a 1002 bwlimit(4096);
1003
8efc0c15 1004 if (count == bp->cnt) {
1005 /* Keep reading so we stay sync'd up. */
1006 if (wrerr == NO) {
05624c18 1007 if (atomicio(vwrite, ofd, bp->buf,
1008 count) != count) {
8efc0c15 1009 wrerr = YES;
05624c18 1010 wrerrno = errno;
8efc0c15 1011 }
1012 }
1013 count = 0;
1014 cp = bp->buf;
1015 }
1016 }
1017 if (showprogress)
b65c3807 1018 stop_progress_meter();
8efc0c15 1019 if (count != 0 && wrerr == NO &&
05624c18 1020 atomicio(vwrite, ofd, bp->buf, count) != count) {
8efc0c15 1021 wrerr = YES;
05624c18 1022 wrerrno = errno;
8efc0c15 1023 }
25a6efd8 1024 if (wrerr == NO && ftruncate(ofd, size) != 0) {
8efc0c15 1025 run_err("%s: truncate: %s", np, strerror(errno));
1026 wrerr = DISPLAYED;
1027 }
8efc0c15 1028 if (pflag) {
1029 if (exists || omode != mode)
77bb0bca 1030#ifdef HAVE_FCHMOD
7e693c81 1031 if (fchmod(ofd, omode)) {
77bb0bca 1032#else /* HAVE_FCHMOD */
7e693c81 1033 if (chmod(np, omode)) {
77bb0bca 1034#endif /* HAVE_FCHMOD */
8efc0c15 1035 run_err("%s: set mode: %s",
e5ff6ecf 1036 np, strerror(errno));
7e693c81 1037 wrerr = DISPLAYED;
1038 }
8efc0c15 1039 } else {
1040 if (!exists && omode != mode)
77bb0bca 1041#ifdef HAVE_FCHMOD
7e693c81 1042 if (fchmod(ofd, omode & ~mask)) {
77bb0bca 1043#else /* HAVE_FCHMOD */
7e693c81 1044 if (chmod(np, omode & ~mask)) {
77bb0bca 1045#endif /* HAVE_FCHMOD */
8efc0c15 1046 run_err("%s: set mode: %s",
e5ff6ecf 1047 np, strerror(errno));
7e693c81 1048 wrerr = DISPLAYED;
1049 }
8efc0c15 1050 }
704b1659 1051 if (close(ofd) == -1) {
1052 wrerr = YES;
1053 wrerrno = errno;
1054 }
5260325f 1055 (void) response();
8efc0c15 1056 if (setimes && wrerr == NO) {
1057 setimes = 0;
188adeb2 1058 if (utimes(np, tv) < 0) {
8efc0c15 1059 run_err("%s: set times: %s",
e5ff6ecf 1060 np, strerror(errno));
8efc0c15 1061 wrerr = DISPLAYED;
1062 }
1063 }
5260325f 1064 switch (wrerr) {
8efc0c15 1065 case YES:
1066 run_err("%s: %s", np, strerror(wrerrno));
1067 break;
1068 case NO:
dc54438a 1069 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 1070 break;
1071 case DISPLAYED:
1072 break;
1073 }
1074 }
1075screwup:
1076 run_err("protocol error: %s", why);
1077 exit(1);
1078}
1079
1080int
d5bb9418 1081response(void)
8efc0c15 1082{
1083 char ch, *cp, resp, rbuf[2048];
1084
1d1ffb87 1085 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
8efc0c15 1086 lostconn(0);
1087
1088 cp = rbuf;
5260325f 1089 switch (resp) {
1090 case 0: /* ok */
8efc0c15 1091 return (0);
1092 default:
1093 *cp++ = resp;
1094 /* FALLTHROUGH */
5260325f 1095 case 1: /* error, followed by error msg */
1096 case 2: /* fatal error, "" */
8efc0c15 1097 do {
1d1ffb87 1098 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 1099 lostconn(0);
1100 *cp++ = ch;
1101 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1102
1103 if (!iamremote)
dc54438a 1104 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
8efc0c15 1105 ++errs;
1106 if (resp == 1)
1107 return (-1);
1108 exit(1);
1109 }
1110 /* NOTREACHED */
1111}
1112
1113void
d5bb9418 1114usage(void)
8efc0c15 1115{
f1278af7 1116 (void) fprintf(stderr,
433e60ac 1117 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1118 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
3015d321 1119 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
8efc0c15 1120 exit(1);
1121}
1122
1123void
5260325f 1124run_err(const char *fmt,...)
8efc0c15 1125{
1126 static FILE *fp;
1127 va_list ap;
8efc0c15 1128
1129 ++errs;
d6157b67 1130 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1131 (void) fprintf(fp, "%c", 0x01);
1132 (void) fprintf(fp, "scp: ");
1133 va_start(ap, fmt);
1134 (void) vfprintf(fp, fmt, ap);
1135 va_end(ap);
1136 (void) fprintf(fp, "\n");
1137 (void) fflush(fp);
1138 }
5260325f 1139
1140 if (!iamremote) {
b92964b7 1141 va_start(ap, fmt);
5260325f 1142 vfprintf(stderr, fmt, ap);
b92964b7 1143 va_end(ap);
5260325f 1144 fprintf(stderr, "\n");
1145 }
8efc0c15 1146}
1147
8efc0c15 1148void
cf3248b8 1149verifydir(char *cp)
8efc0c15 1150{
1151 struct stat stb;
1152
1153 if (!stat(cp, &stb)) {
1154 if (S_ISDIR(stb.st_mode))
1155 return;
1156 errno = ENOTDIR;
1157 }
1158 run_err("%s: %s", cp, strerror(errno));
8f4ab41b 1159 killchild(0);
8efc0c15 1160}
1161
1162int
cf3248b8 1163okname(char *cp0)
8efc0c15 1164{
1165 int c;
1166 char *cp;
1167
1168 cp = cp0;
1169 do {
cb220a93 1170 c = (int)*cp;
8efc0c15 1171 if (c & 0200)
1172 goto bad;
0ec7661a 1173 if (!isalpha(c) && !isdigit(c)) {
1174 switch (c) {
1175 case '\'':
1176 case '"':
1177 case '`':
1178 case ' ':
1179 case '#':
1180 goto bad;
1181 default:
1182 break;
1183 }
1184 }
8efc0c15 1185 } while (*++cp);
1186 return (1);
1187
c8d54615 1188bad: fprintf(stderr, "%s: invalid user name\n", cp0);
8efc0c15 1189 return (0);
1190}
1191
1192BUF *
cf3248b8 1193allocbuf(BUF *bp, int fd, int blksize)
8efc0c15 1194{
1195 size_t size;
98a7c37b 1196#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
8efc0c15 1197 struct stat stb;
1198
1199 if (fstat(fd, &stb) < 0) {
1200 run_err("fstat: %s", strerror(errno));
1201 return (0);
1202 }
a0a14bcd 1203 size = roundup(stb.st_blksize, blksize);
1204 if (size == 0)
5260325f 1205 size = blksize;
98a7c37b 1206#else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2b87da3b 1207 size = blksize;
98a7c37b 1208#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
8efc0c15 1209 if (bp->cnt >= size)
1210 return (bp);
5260325f 1211 if (bp->buf == NULL)
1212 bp->buf = xmalloc(size);
1213 else
c5d10563 1214 bp->buf = xrealloc(bp->buf, 1, size);
46660a9e 1215 memset(bp->buf, 0, size);
8efc0c15 1216 bp->cnt = size;
1217 return (bp);
1218}
1219
1220void
cf3248b8 1221lostconn(int signo)
8efc0c15 1222{
1223 if (!iamremote)
08c260ea 1224 write(STDERR_FILENO, "lost connection\n", 16);
1225 if (signo)
1226 _exit(1);
1227 else
1228 exit(1);
8efc0c15 1229}
This page took 0.487708 seconds and 5 git commands to generate.