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