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