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