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