]> andersk Git - openssh.git/blame - scp.c
- djm@cvs.openbsd.org 2003/11/21 11:57:03
[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"
aff51935 74RCSID("$OpenBSD: scp.c,v 1.112 2003/11/21 11:57:03 djm 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 */
eb180c2e 95off_t limitbw = 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();
eb180c2e 260 limitbw = 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 }
eb180c2e 592 if (limitbw)
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;
666 u_int64_t wait;
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;
eb180c2e 684 wait = (double)1000000L * lamt / limitbw;
6ea3c52a 685
686 bwstart.tv_sec = wait / 1000000L;
687 bwstart.tv_usec = wait % 1000000L;
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;
762
763 if (buf[0] == '\01' || buf[0] == '\02') {
764 if (iamremote == 0)
dc54438a 765 (void) atomicio(vwrite, STDERR_FILENO,
71c0d06a 766 buf + 1, strlen(buf + 1));
8efc0c15 767 if (buf[0] == '\02')
768 exit(1);
769 ++errs;
770 continue;
771 }
772 if (buf[0] == 'E') {
dc54438a 773 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 774 return;
775 }
8efc0c15 776 if (ch == '\n')
777 *--cp = 0;
778
8efc0c15 779 cp = buf;
780 if (*cp == 'T') {
781 setimes++;
782 cp++;
36967a16 783 mtime.tv_sec = strtol(cp, &cp, 10);
784 if (!cp || *cp++ != ' ')
8efc0c15 785 SCREWUP("mtime.sec not delimited");
36967a16 786 mtime.tv_usec = strtol(cp, &cp, 10);
787 if (!cp || *cp++ != ' ')
8efc0c15 788 SCREWUP("mtime.usec not delimited");
36967a16 789 atime.tv_sec = strtol(cp, &cp, 10);
790 if (!cp || *cp++ != ' ')
8efc0c15 791 SCREWUP("atime.sec not delimited");
36967a16 792 atime.tv_usec = strtol(cp, &cp, 10);
793 if (!cp || *cp++ != '\0')
8efc0c15 794 SCREWUP("atime.usec not delimited");
dc54438a 795 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 796 continue;
797 }
798 if (*cp != 'C' && *cp != 'D') {
799 /*
800 * Check for the case "rcp remote:foo\* local:bar".
801 * In this case, the line "No match." can be returned
802 * by the shell before the rcp command on the remote is
803 * executed so the ^Aerror_message convention isn't
804 * followed.
805 */
806 if (first) {
807 run_err("%s", cp);
808 exit(1);
809 }
810 SCREWUP("expected control record");
811 }
812 mode = 0;
813 for (++cp; cp < buf + 5; cp++) {
814 if (*cp < '0' || *cp > '7')
815 SCREWUP("bad mode");
816 mode = (mode << 3) | (*cp - '0');
817 }
818 if (*cp++ != ' ')
819 SCREWUP("mode not delimited");
820
e5ff6ecf 821 for (size = 0; isdigit(*cp);)
8efc0c15 822 size = size * 10 + (*cp++ - '0');
823 if (*cp++ != ' ')
824 SCREWUP("size not delimited");
825 if (targisdir) {
826 static char *namebuf;
827 static int cursize;
828 size_t need;
829
830 need = strlen(targ) + strlen(cp) + 250;
0ed28836 831 if (need > cursize) {
832 if (namebuf)
833 xfree(namebuf);
5260325f 834 namebuf = xmalloc(need);
0ed28836 835 cursize = need;
836 }
837 (void) snprintf(namebuf, need, "%s%s%s", targ,
39f9599a 838 strcmp(targ, "/") ? "/" : "", cp);
8efc0c15 839 np = namebuf;
840 } else
841 np = targ;
842 curfile = cp;
843 exists = stat(np, &stb) == 0;
844 if (buf[0] == 'D') {
845 int mod_flag = pflag;
846 if (exists) {
847 if (!S_ISDIR(stb.st_mode)) {
848 errno = ENOTDIR;
849 goto bad;
850 }
851 if (pflag)
5260325f 852 (void) chmod(np, mode);
8efc0c15 853 } else {
5260325f 854 /* Handle copying from a read-only
855 directory */
8efc0c15 856 mod_flag = 1;
857 if (mkdir(np, mode | S_IRWXU) < 0)
858 goto bad;
859 }
5c470997 860 vect[0] = xstrdup(np);
8efc0c15 861 sink(1, vect);
862 if (setimes) {
863 setimes = 0;
e68225b2 864 if (utimes(vect[0], tv) < 0)
5260325f 865 run_err("%s: set times: %s",
e68225b2 866 vect[0], strerror(errno));
8efc0c15 867 }
868 if (mod_flag)
e68225b2 869 (void) chmod(vect[0], mode);
870 if (vect[0])
871 xfree(vect[0]);
8efc0c15 872 continue;
873 }
874 omode = mode;
875 mode |= S_IWRITE;
3e4fc5f9 876 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
8efc0c15 877bad: run_err("%s: %s", np, strerror(errno));
878 continue;
879 }
dc54438a 880 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 881 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
5260325f 882 (void) close(ofd);
8efc0c15 883 continue;
884 }
885 cp = bp->buf;
886 wrerr = NO;
887
8efc0c15 888 statbytes = 0;
b65c3807 889 if (showprogress)
890 start_progress_meter(curfile, size, &statbytes);
8efc0c15 891 for (count = i = 0; i < size; i += 4096) {
892 amt = 4096;
893 if (i + amt > size)
894 amt = size - i;
895 count += amt;
896 do {
a22aff1f 897 j = read(remin, cp, amt);
0b2988ca 898 if (j == -1 && (errno == EINTR ||
899 errno == EAGAIN)) {
a22aff1f 900 continue;
901 } else if (j <= 0) {
8efc0c15 902 run_err("%s", j ? strerror(errno) :
e5ff6ecf 903 "dropped connection");
8efc0c15 904 exit(1);
905 }
906 amt -= j;
907 cp += j;
5260325f 908 statbytes += j;
8efc0c15 909 } while (amt > 0);
6ea3c52a 910
eb180c2e 911 if (limitbw)
6ea3c52a 912 bwlimit(4096);
913
8efc0c15 914 if (count == bp->cnt) {
915 /* Keep reading so we stay sync'd up. */
916 if (wrerr == NO) {
dc54438a 917 j = atomicio(vwrite, ofd, bp->buf, count);
8efc0c15 918 if (j != count) {
919 wrerr = YES;
5260325f 920 wrerrno = j >= 0 ? EIO : errno;
8efc0c15 921 }
922 }
923 count = 0;
924 cp = bp->buf;
925 }
926 }
927 if (showprogress)
b65c3807 928 stop_progress_meter();
8efc0c15 929 if (count != 0 && wrerr == NO &&
dc54438a 930 (j = atomicio(vwrite, ofd, bp->buf, count)) != count) {
8efc0c15 931 wrerr = YES;
5260325f 932 wrerrno = j >= 0 ? EIO : errno;
8efc0c15 933 }
25a6efd8 934 if (wrerr == NO && ftruncate(ofd, size) != 0) {
8efc0c15 935 run_err("%s: truncate: %s", np, strerror(errno));
936 wrerr = DISPLAYED;
937 }
8efc0c15 938 if (pflag) {
939 if (exists || omode != mode)
77bb0bca 940#ifdef HAVE_FCHMOD
8efc0c15 941 if (fchmod(ofd, omode))
77bb0bca 942#else /* HAVE_FCHMOD */
943 if (chmod(np, omode))
944#endif /* HAVE_FCHMOD */
8efc0c15 945 run_err("%s: set mode: %s",
e5ff6ecf 946 np, strerror(errno));
8efc0c15 947 } else {
948 if (!exists && omode != mode)
77bb0bca 949#ifdef HAVE_FCHMOD
8efc0c15 950 if (fchmod(ofd, omode & ~mask))
77bb0bca 951#else /* HAVE_FCHMOD */
952 if (chmod(np, omode & ~mask))
953#endif /* HAVE_FCHMOD */
8efc0c15 954 run_err("%s: set mode: %s",
e5ff6ecf 955 np, strerror(errno));
8efc0c15 956 }
704b1659 957 if (close(ofd) == -1) {
958 wrerr = YES;
959 wrerrno = errno;
960 }
5260325f 961 (void) response();
8efc0c15 962 if (setimes && wrerr == NO) {
963 setimes = 0;
188adeb2 964 if (utimes(np, tv) < 0) {
8efc0c15 965 run_err("%s: set times: %s",
e5ff6ecf 966 np, strerror(errno));
8efc0c15 967 wrerr = DISPLAYED;
968 }
969 }
5260325f 970 switch (wrerr) {
8efc0c15 971 case YES:
972 run_err("%s: %s", np, strerror(wrerrno));
973 break;
974 case NO:
dc54438a 975 (void) atomicio(vwrite, remout, "", 1);
8efc0c15 976 break;
977 case DISPLAYED:
978 break;
979 }
980 }
981screwup:
982 run_err("protocol error: %s", why);
983 exit(1);
984}
985
986int
d5bb9418 987response(void)
8efc0c15 988{
989 char ch, *cp, resp, rbuf[2048];
990
1d1ffb87 991 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
8efc0c15 992 lostconn(0);
993
994 cp = rbuf;
5260325f 995 switch (resp) {
996 case 0: /* ok */
8efc0c15 997 return (0);
998 default:
999 *cp++ = resp;
1000 /* FALLTHROUGH */
5260325f 1001 case 1: /* error, followed by error msg */
1002 case 2: /* fatal error, "" */
8efc0c15 1003 do {
1d1ffb87 1004 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
8efc0c15 1005 lostconn(0);
1006 *cp++ = ch;
1007 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1008
1009 if (!iamremote)
dc54438a 1010 (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
8efc0c15 1011 ++errs;
1012 if (resp == 1)
1013 return (-1);
1014 exit(1);
1015 }
1016 /* NOTREACHED */
1017}
1018
1019void
d5bb9418 1020usage(void)
8efc0c15 1021{
f1278af7 1022 (void) fprintf(stderr,
433e60ac 1023 "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1024 " [-l limit] [-o ssh_option] [-P port] [-S program]\n"
3015d321 1025 " [[user@]host1:]file1 [...] [[user@]host2:]file2\n");
8efc0c15 1026 exit(1);
1027}
1028
1029void
5260325f 1030run_err(const char *fmt,...)
8efc0c15 1031{
1032 static FILE *fp;
1033 va_list ap;
8efc0c15 1034
1035 ++errs;
1036 if (fp == NULL && !(fp = fdopen(remout, "w")))
1037 return;
5260325f 1038 (void) fprintf(fp, "%c", 0x01);
1039 (void) fprintf(fp, "scp: ");
b92964b7 1040 va_start(ap, fmt);
5260325f 1041 (void) vfprintf(fp, fmt, ap);
b92964b7 1042 va_end(ap);
5260325f 1043 (void) fprintf(fp, "\n");
1044 (void) fflush(fp);
1045
1046 if (!iamremote) {
b92964b7 1047 va_start(ap, fmt);
5260325f 1048 vfprintf(stderr, fmt, ap);
b92964b7 1049 va_end(ap);
5260325f 1050 fprintf(stderr, "\n");
1051 }
8efc0c15 1052}
1053
8efc0c15 1054void
cf3248b8 1055verifydir(char *cp)
8efc0c15 1056{
1057 struct stat stb;
1058
1059 if (!stat(cp, &stb)) {
1060 if (S_ISDIR(stb.st_mode))
1061 return;
1062 errno = ENOTDIR;
1063 }
1064 run_err("%s: %s", cp, strerror(errno));
1065 exit(1);
1066}
1067
1068int
cf3248b8 1069okname(char *cp0)
8efc0c15 1070{
1071 int c;
1072 char *cp;
1073
1074 cp = cp0;
1075 do {
cb220a93 1076 c = (int)*cp;
8efc0c15 1077 if (c & 0200)
1078 goto bad;
0ec7661a 1079 if (!isalpha(c) && !isdigit(c)) {
1080 switch (c) {
1081 case '\'':
1082 case '"':
1083 case '`':
1084 case ' ':
1085 case '#':
1086 goto bad;
1087 default:
1088 break;
1089 }
1090 }
8efc0c15 1091 } while (*++cp);
1092 return (1);
1093
c8d54615 1094bad: fprintf(stderr, "%s: invalid user name\n", cp0);
8efc0c15 1095 return (0);
1096}
1097
1098BUF *
cf3248b8 1099allocbuf(BUF *bp, int fd, int blksize)
8efc0c15 1100{
1101 size_t size;
98a7c37b 1102#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
8efc0c15 1103 struct stat stb;
1104
1105 if (fstat(fd, &stb) < 0) {
1106 run_err("fstat: %s", strerror(errno));
1107 return (0);
1108 }
a0a14bcd 1109 size = roundup(stb.st_blksize, blksize);
1110 if (size == 0)
5260325f 1111 size = blksize;
98a7c37b 1112#else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2b87da3b 1113 size = blksize;
98a7c37b 1114#endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
8efc0c15 1115 if (bp->cnt >= size)
1116 return (bp);
5260325f 1117 if (bp->buf == NULL)
1118 bp->buf = xmalloc(size);
1119 else
1120 bp->buf = xrealloc(bp->buf, size);
46660a9e 1121 memset(bp->buf, 0, size);
8efc0c15 1122 bp->cnt = size;
1123 return (bp);
1124}
1125
1126void
cf3248b8 1127lostconn(int signo)
8efc0c15 1128{
1129 if (!iamremote)
08c260ea 1130 write(STDERR_FILENO, "lost connection\n", 16);
1131 if (signo)
1132 _exit(1);
1133 else
1134 exit(1);
8efc0c15 1135}
This page took 4.621207 seconds and 5 git commands to generate.