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