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