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