]> andersk Git - openssh.git/blame_incremental - scp.c
- (bal) Slight auth2-pam.c clean up.
[openssh.git] / scp.c
... / ...
CommitLineData
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.
55 * 3. All advertising materials mentioning features or use of this software
56 * must display the following acknowledgement:
57 * This product includes software developed by the University of
58 * California, Berkeley and its contributors.
59 * 4. Neither the name of the University nor the names of its contributors
60 * may be used to endorse or promote products derived from this software
61 * without specific prior written permission.
62 *
63 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
64 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
67 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
68 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
69 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
70 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
72 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * SUCH DAMAGE.
74 *
75 */
76
77#include "includes.h"
78RCSID("$OpenBSD: scp.c,v 1.49 2001/01/13 18:03:07 markus Exp $");
79
80#include "ssh.h"
81#include "xmalloc.h"
82
83#ifndef _PATH_CP
84#define _PATH_CP "cp"
85#endif
86
87#ifdef HAVE___PROGNAME
88extern char *__progname;
89#else
90char *__progname;
91#endif
92
93/* For progressmeter() -- number of seconds before xfer considered "stalled" */
94#define STALLTIME 5
95
96/* Progress meter bar */
97#define BAR \
98 "************************************************************"\
99 "************************************************************"\
100 "************************************************************"\
101 "************************************************************"
102#define MAX_BARLENGTH (sizeof(BAR) - 1)
103
104/* Visual statistics about files as they are transferred. */
105void progressmeter(int);
106
107/* Returns width of the terminal (for progress meter calculations). */
108int getttywidth(void);
109int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc);
110
111/* setup arguments for the call to ssh */
112void addargs(char *fmt, ...) __attribute__((format(printf, 1, 2)));
113
114/* Time a transfer started. */
115static struct timeval start;
116
117/* Number of bytes of current file transferred so far. */
118volatile u_long statbytes;
119
120/* Total size of current file. */
121off_t totalbytes = 0;
122
123/* Name of current file being transferred. */
124char *curfile;
125
126/* This is set to non-zero to enable verbose mode. */
127int verbose_mode = 0;
128
129/* This is set to zero if the progressmeter is not desired. */
130int showprogress = 1;
131
132/* This is the program to execute for the secured connection. ("ssh" or -S) */
133char *ssh_program = SSH_PROGRAM;
134
135/* This is the list of arguments that scp passes to ssh */
136struct {
137 char **list;
138 int num;
139 int nalloc;
140} args;
141
142/*
143 * This function executes the given command as the specified user on the
144 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This
145 * assigns the input and output file descriptors on success.
146 */
147
148int
149do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc)
150{
151 int pin[2], pout[2], reserved[2];
152
153 if (verbose_mode)
154 fprintf(stderr, "Executing: program %s host %s, user %s, command %s\n",
155 ssh_program, host, remuser ? remuser : "(unspecified)", cmd);
156
157 /*
158 * Reserve two descriptors so that the real pipes won't get
159 * descriptors 0 and 1 because that will screw up dup2 below.
160 */
161 pipe(reserved);
162
163 /* Create a socket pair for communicating with ssh. */
164 if (pipe(pin) < 0)
165 fatal("pipe: %s", strerror(errno));
166 if (pipe(pout) < 0)
167 fatal("pipe: %s", strerror(errno));
168
169 /* Free the reserved descriptors. */
170 close(reserved[0]);
171 close(reserved[1]);
172
173 /* For a child to execute the command on the remote host using ssh. */
174 if (fork() == 0) {
175 /* Child. */
176 close(pin[1]);
177 close(pout[0]);
178 dup2(pin[0], 0);
179 dup2(pout[1], 1);
180 close(pin[0]);
181 close(pout[1]);
182
183 args.list[0] = ssh_program;
184 if (remuser != NULL)
185 addargs("-l%s", remuser);
186 addargs("%s", host);
187 addargs("%s", cmd);
188
189 execvp(ssh_program, args.list);
190 perror(ssh_program);
191 exit(1);
192 }
193 /* Parent. Close the other side, and return the local side. */
194 close(pin[0]);
195 *fdout = pin[1];
196 close(pout[1]);
197 *fdin = pout[0];
198 return 0;
199}
200
201typedef struct {
202 int cnt;
203 char *buf;
204} BUF;
205
206extern int iamremote;
207
208BUF *allocbuf(BUF *, int, int);
209char *colon(char *);
210void lostconn(int);
211void nospace(void);
212int okname(char *);
213void run_err(const char *,...);
214void verifydir(char *);
215
216struct passwd *pwd;
217uid_t userid;
218int errs, remin, remout;
219int pflag, iamremote, iamrecursive, targetshouldbedirectory;
220
221#define CMDNEEDS 64
222char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */
223
224int response(void);
225void rsource(char *, struct stat *);
226void sink(int, char *[]);
227void source(int, char *[]);
228void tolocal(int, char *[]);
229void toremote(char *, int, char *[]);
230void usage(void);
231
232int
233main(argc, argv)
234 int argc;
235 char *argv[];
236{
237 int ch, fflag, tflag;
238 char *targ;
239 extern char *optarg;
240 extern int optind;
241
242 __progname = get_progname(argv[0]);
243
244 args.list = NULL;
245 addargs("ssh"); /* overwritten with ssh_program */
246 addargs("-x");
247 addargs("-oFallBackToRsh no");
248
249 fflag = tflag = 0;
250 while ((ch = getopt(argc, argv, "dfprtvBCc:i:P:q46S:o:")) != -1)
251 switch (ch) {
252 /* User-visible flags. */
253 case '4':
254 case '6':
255 case 'C':
256 addargs("-%c", ch);
257 break;
258 case 'o':
259 case 'c':
260 case 'i':
261 addargs("-%c%s", ch, optarg);
262 break;
263 case 'P':
264 addargs("-p%s", optarg);
265 break;
266 case 'B':
267 addargs("-oBatchmode yes");
268 break;
269 case 'p':
270 pflag = 1;
271 break;
272 case 'r':
273 iamrecursive = 1;
274 break;
275 case 'S':
276 ssh_program = xstrdup(optarg);
277 break;
278 case 'v':
279 verbose_mode = 1;
280 break;
281 case 'q':
282 showprogress = 0;
283 break;
284
285 /* Server options. */
286 case 'd':
287 targetshouldbedirectory = 1;
288 break;
289 case 'f': /* "from" */
290 iamremote = 1;
291 fflag = 1;
292 break;
293 case 't': /* "to" */
294 iamremote = 1;
295 tflag = 1;
296 break;
297 case '?':
298 default:
299 usage();
300 }
301 argc -= optind;
302 argv += optind;
303
304 if ((pwd = getpwuid(userid = getuid())) == NULL)
305 fatal("unknown user %d", (int) userid);
306
307 if (!isatty(STDERR_FILENO))
308 showprogress = 0;
309
310 remin = STDIN_FILENO;
311 remout = STDOUT_FILENO;
312
313 if (fflag) {
314 /* Follow "protocol", send data. */
315 (void) response();
316 source(argc, argv);
317 exit(errs != 0);
318 }
319 if (tflag) {
320 /* Receive data. */
321 sink(argc, argv);
322 exit(errs != 0);
323 }
324 if (argc < 2)
325 usage();
326 if (argc > 2)
327 targetshouldbedirectory = 1;
328
329 remin = remout = -1;
330 /* Command to be executed on remote system using "ssh". */
331 (void) sprintf(cmd, "scp%s%s%s%s", verbose_mode ? " -v" : "",
332 iamrecursive ? " -r" : "", pflag ? " -p" : "",
333 targetshouldbedirectory ? " -d" : "");
334
335 (void) signal(SIGPIPE, lostconn);
336
337 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */
338 toremote(targ, argc, argv);
339 else {
340 tolocal(argc, argv); /* Dest is local host. */
341 if (targetshouldbedirectory)
342 verifydir(argv[argc - 1]);
343 }
344 exit(errs != 0);
345}
346
347char *
348cleanhostname(host)
349 char *host;
350{
351 if (*host == '[' && host[strlen(host) - 1] == ']') {
352 host[strlen(host) - 1] = '\0';
353 return (host + 1);
354 } else
355 return host;
356}
357
358void
359toremote(targ, argc, argv)
360 char *targ, *argv[];
361 int argc;
362{
363 int i, len;
364 char *bp, *host, *src, *suser, *thost, *tuser;
365
366 *targ++ = 0;
367 if (*targ == 0)
368 targ = ".";
369
370 if ((thost = strchr(argv[argc - 1], '@'))) {
371 /* user@host */
372 *thost++ = 0;
373 tuser = argv[argc - 1];
374 if (*tuser == '\0')
375 tuser = NULL;
376 else if (!okname(tuser))
377 exit(1);
378 } else {
379 thost = argv[argc - 1];
380 tuser = NULL;
381 }
382
383 for (i = 0; i < argc - 1; i++) {
384 src = colon(argv[i]);
385 if (src) { /* remote to remote */
386 *src++ = 0;
387 if (*src == 0)
388 src = ".";
389 host = strchr(argv[i], '@');
390 len = strlen(ssh_program) + strlen(argv[i]) +
391 strlen(src) + (tuser ? strlen(tuser) : 0) +
392 strlen(thost) + strlen(targ) + CMDNEEDS + 32;
393 bp = xmalloc(len);
394 if (host) {
395 *host++ = 0;
396 host = cleanhostname(host);
397 suser = argv[i];
398 if (*suser == '\0')
399 suser = pwd->pw_name;
400 else if (!okname(suser))
401 continue;
402 sprintf(bp,
403 "%s%s -x -o'FallBackToRsh no' -n -l %s %s %s %s '%s%s%s:%s'",
404 ssh_program, verbose_mode ? " -v" : "",
405 suser, host, cmd, src,
406 tuser ? tuser : "", tuser ? "@" : "",
407 thost, targ);
408 } else {
409 host = cleanhostname(argv[i]);
410 sprintf(bp,
411 "exec %s%s -x -o'FallBackToRsh no' -n %s %s %s '%s%s%s:%s'",
412 ssh_program, verbose_mode ? " -v" : "",
413 host, cmd, src,
414 tuser ? tuser : "", tuser ? "@" : "",
415 thost, targ);
416 }
417 if (verbose_mode)
418 fprintf(stderr, "Executing: %s\n", bp);
419 (void) system(bp);
420 (void) xfree(bp);
421 } else { /* local to remote */
422 if (remin == -1) {
423 len = strlen(targ) + CMDNEEDS + 20;
424 bp = xmalloc(len);
425 (void) sprintf(bp, "%s -t %s", cmd, targ);
426 host = cleanhostname(thost);
427 if (do_cmd(host, tuser, bp, &remin,
428 &remout, argc) < 0)
429 exit(1);
430 if (response() < 0)
431 exit(1);
432 (void) xfree(bp);
433 }
434 source(1, argv + i);
435 }
436 }
437}
438
439void
440tolocal(argc, argv)
441 int argc;
442 char *argv[];
443{
444 int i, len;
445 char *bp, *host, *src, *suser;
446
447 for (i = 0; i < argc - 1; i++) {
448 if (!(src = colon(argv[i]))) { /* Local to local. */
449 len = strlen(_PATH_CP) + strlen(argv[i]) +
450 strlen(argv[argc - 1]) + 20;
451 bp = xmalloc(len);
452 (void) sprintf(bp, "exec %s%s%s %s %s", _PATH_CP,
453 iamrecursive ? " -r" : "", pflag ? " -p" : "",
454 argv[i], argv[argc - 1]);
455 if (verbose_mode)
456 fprintf(stderr, "Executing: %s\n", bp);
457 if (system(bp))
458 ++errs;
459 (void) xfree(bp);
460 continue;
461 }
462 *src++ = 0;
463 if (*src == 0)
464 src = ".";
465 if ((host = strchr(argv[i], '@')) == NULL) {
466 host = argv[i];
467 suser = NULL;
468 } else {
469 *host++ = 0;
470 suser = argv[i];
471 if (*suser == '\0')
472 suser = pwd->pw_name;
473 else if (!okname(suser))
474 continue;
475 }
476 host = cleanhostname(host);
477 len = strlen(src) + CMDNEEDS + 20;
478 bp = xmalloc(len);
479 (void) sprintf(bp, "%s -f %s", cmd, src);
480 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) {
481 (void) xfree(bp);
482 ++errs;
483 continue;
484 }
485 xfree(bp);
486 sink(1, argv + argc - 1);
487 (void) close(remin);
488 remin = remout = -1;
489 }
490}
491
492void
493source(argc, argv)
494 int argc;
495 char *argv[];
496{
497 struct stat stb;
498 static BUF buffer;
499 BUF *bp;
500 off_t i;
501 int amt, fd, haderr, indx, result;
502 char *last, *name, buf[2048];
503
504 for (indx = 0; indx < argc; ++indx) {
505 name = argv[indx];
506 statbytes = 0;
507 if ((fd = open(name, O_RDONLY, 0)) < 0)
508 goto syserr;
509 if (fstat(fd, &stb) < 0) {
510syserr: run_err("%s: %s", name, strerror(errno));
511 goto next;
512 }
513 switch (stb.st_mode & S_IFMT) {
514 case S_IFREG:
515 break;
516 case S_IFDIR:
517 if (iamrecursive) {
518 rsource(name, &stb);
519 goto next;
520 }
521 /* FALLTHROUGH */
522 default:
523 run_err("%s: not a regular file", name);
524 goto next;
525 }
526 if ((last = strrchr(name, '/')) == NULL)
527 last = name;
528 else
529 ++last;
530 curfile = last;
531 if (pflag) {
532 /*
533 * Make it compatible with possible future
534 * versions expecting microseconds.
535 */
536 (void) sprintf(buf, "T%lu 0 %lu 0\n",
537 (u_long) stb.st_mtime,
538 (u_long) stb.st_atime);
539 (void) atomicio(write, remout, buf, strlen(buf));
540 if (response() < 0)
541 goto next;
542 }
543#define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
544 sprintf(buf, "C%04o %lu %s\n",
545 (u_int) (stb.st_mode & FILEMODEMASK),
546 (u_long) stb.st_size, last);
547 if (verbose_mode) {
548 fprintf(stderr, "Sending file modes: %s", buf);
549 fflush(stderr);
550 }
551 (void) atomicio(write, remout, buf, strlen(buf));
552 if (response() < 0)
553 goto next;
554 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
555next: (void) close(fd);
556 continue;
557 }
558 if (showprogress) {
559 totalbytes = stb.st_size;
560 progressmeter(-1);
561 }
562 /* Keep writing after an error so that we stay sync'd up. */
563 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
564 amt = bp->cnt;
565 if (i + amt > stb.st_size)
566 amt = stb.st_size - i;
567 if (!haderr) {
568 result = atomicio(read, fd, bp->buf, amt);
569 if (result != amt)
570 haderr = result >= 0 ? EIO : errno;
571 }
572 if (haderr)
573 (void) atomicio(write, remout, bp->buf, amt);
574 else {
575 result = atomicio(write, remout, bp->buf, amt);
576 if (result != amt)
577 haderr = result >= 0 ? EIO : errno;
578 statbytes += result;
579 }
580 }
581 if (showprogress)
582 progressmeter(1);
583
584 if (close(fd) < 0 && !haderr)
585 haderr = errno;
586 if (!haderr)
587 (void) atomicio(write, remout, "", 1);
588 else
589 run_err("%s: %s", name, strerror(haderr));
590 (void) response();
591 }
592}
593
594void
595rsource(name, statp)
596 char *name;
597 struct stat *statp;
598{
599 DIR *dirp;
600 struct dirent *dp;
601 char *last, *vect[1], path[1100];
602
603 if (!(dirp = opendir(name))) {
604 run_err("%s: %s", name, strerror(errno));
605 return;
606 }
607 last = strrchr(name, '/');
608 if (last == 0)
609 last = name;
610 else
611 last++;
612 if (pflag) {
613 (void) sprintf(path, "T%lu 0 %lu 0\n",
614 (u_long) statp->st_mtime,
615 (u_long) statp->st_atime);
616 (void) atomicio(write, remout, path, strlen(path));
617 if (response() < 0) {
618 closedir(dirp);
619 return;
620 }
621 }
622 (void) sprintf(path, "D%04o %d %.1024s\n",
623 (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
624 if (verbose_mode)
625 fprintf(stderr, "Entering directory: %s", path);
626 (void) atomicio(write, remout, path, strlen(path));
627 if (response() < 0) {
628 closedir(dirp);
629 return;
630 }
631 while ((dp = readdir(dirp))) {
632 if (dp->d_ino == 0)
633 continue;
634 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
635 continue;
636 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
637 run_err("%s/%s: name too long", name, dp->d_name);
638 continue;
639 }
640 (void) sprintf(path, "%s/%s", name, dp->d_name);
641 vect[0] = path;
642 source(1, vect);
643 }
644 (void) closedir(dirp);
645 (void) atomicio(write, remout, "E\n", 2);
646 (void) response();
647}
648
649void
650sink(argc, argv)
651 int argc;
652 char *argv[];
653{
654 static BUF buffer;
655 struct stat stb;
656 enum {
657 YES, NO, DISPLAYED
658 } wrerr;
659 BUF *bp;
660 off_t i, j;
661 int amt, count, exists, first, mask, mode, ofd, omode;
662 off_t size;
663 int setimes, targisdir, wrerrno = 0;
664 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048];
665 int dummy_usec;
666 struct timeval tv[2];
667
668#define SCREWUP(str) { why = str; goto screwup; }
669
670 setimes = targisdir = 0;
671 mask = umask(0);
672 if (!pflag)
673 (void) umask(mask);
674 if (argc != 1) {
675 run_err("ambiguous target");
676 exit(1);
677 }
678 targ = *argv;
679 if (targetshouldbedirectory)
680 verifydir(targ);
681
682 (void) atomicio(write, remout, "", 1);
683 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
684 targisdir = 1;
685 for (first = 1;; first = 0) {
686 cp = buf;
687 if (atomicio(read, remin, cp, 1) <= 0)
688 return;
689 if (*cp++ == '\n')
690 SCREWUP("unexpected <newline>");
691 do {
692 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
693 SCREWUP("lost connection");
694 *cp++ = ch;
695 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
696 *cp = 0;
697
698 if (buf[0] == '\01' || buf[0] == '\02') {
699 if (iamremote == 0)
700 (void) atomicio(write, STDERR_FILENO,
701 buf + 1, strlen(buf + 1));
702 if (buf[0] == '\02')
703 exit(1);
704 ++errs;
705 continue;
706 }
707 if (buf[0] == 'E') {
708 (void) atomicio(write, remout, "", 1);
709 return;
710 }
711 if (ch == '\n')
712 *--cp = 0;
713
714#define getnum(t) (t) = 0; \
715 while (*cp >= '0' && *cp <= '9') (t) = (t) * 10 + (*cp++ - '0');
716 cp = buf;
717 if (*cp == 'T') {
718 setimes++;
719 cp++;
720 getnum(tv[1].tv_sec);
721 if (*cp++ != ' ')
722 SCREWUP("mtime.sec not delimited");
723 getnum(dummy_usec);
724 tv[1].tv_usec = 0;
725 if (*cp++ != ' ')
726 SCREWUP("mtime.usec not delimited");
727 getnum(tv[0].tv_sec);
728 if (*cp++ != ' ')
729 SCREWUP("atime.sec not delimited");
730 getnum(dummy_usec);
731 tv[0].tv_usec = 0;
732 if (*cp++ != '\0')
733 SCREWUP("atime.usec not delimited");
734 (void) atomicio(write, remout, "", 1);
735 continue;
736 }
737 if (*cp != 'C' && *cp != 'D') {
738 /*
739 * Check for the case "rcp remote:foo\* local:bar".
740 * In this case, the line "No match." can be returned
741 * by the shell before the rcp command on the remote is
742 * executed so the ^Aerror_message convention isn't
743 * followed.
744 */
745 if (first) {
746 run_err("%s", cp);
747 exit(1);
748 }
749 SCREWUP("expected control record");
750 }
751 mode = 0;
752 for (++cp; cp < buf + 5; cp++) {
753 if (*cp < '0' || *cp > '7')
754 SCREWUP("bad mode");
755 mode = (mode << 3) | (*cp - '0');
756 }
757 if (*cp++ != ' ')
758 SCREWUP("mode not delimited");
759
760 for (size = 0; *cp >= '0' && *cp <= '9';)
761 size = size * 10 + (*cp++ - '0');
762 if (*cp++ != ' ')
763 SCREWUP("size not delimited");
764 if (targisdir) {
765 static char *namebuf;
766 static int cursize;
767 size_t need;
768
769 need = strlen(targ) + strlen(cp) + 250;
770 if (need > cursize)
771 namebuf = xmalloc(need);
772 (void) sprintf(namebuf, "%s%s%s", targ,
773 *targ ? "/" : "", cp);
774 np = namebuf;
775 } else
776 np = targ;
777 curfile = cp;
778 exists = stat(np, &stb) == 0;
779 if (buf[0] == 'D') {
780 int mod_flag = pflag;
781 if (exists) {
782 if (!S_ISDIR(stb.st_mode)) {
783 errno = ENOTDIR;
784 goto bad;
785 }
786 if (pflag)
787 (void) chmod(np, mode);
788 } else {
789 /* Handle copying from a read-only
790 directory */
791 mod_flag = 1;
792 if (mkdir(np, mode | S_IRWXU) < 0)
793 goto bad;
794 }
795 vect[0] = np;
796 sink(1, vect);
797 if (setimes) {
798 setimes = 0;
799 if (utimes(np, tv) < 0)
800 run_err("%s: set times: %s",
801 np, strerror(errno));
802 }
803 if (mod_flag)
804 (void) chmod(np, mode);
805 continue;
806 }
807 omode = mode;
808 mode |= S_IWRITE;
809 if ((ofd = open(np, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
810bad: run_err("%s: %s", np, strerror(errno));
811 continue;
812 }
813 (void) atomicio(write, remout, "", 1);
814 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) {
815 (void) close(ofd);
816 continue;
817 }
818 cp = bp->buf;
819 wrerr = NO;
820
821 if (showprogress) {
822 totalbytes = size;
823 progressmeter(-1);
824 }
825 statbytes = 0;
826 for (count = i = 0; i < size; i += 4096) {
827 amt = 4096;
828 if (i + amt > size)
829 amt = size - i;
830 count += amt;
831 do {
832 j = read(remin, cp, amt);
833 if (j == -1 && (errno == EINTR || errno == EAGAIN)) {
834 continue;
835 } else if (j <= 0) {
836 run_err("%s", j ? strerror(errno) :
837 "dropped connection");
838 exit(1);
839 }
840 amt -= j;
841 cp += j;
842 statbytes += j;
843 } while (amt > 0);
844 if (count == bp->cnt) {
845 /* Keep reading so we stay sync'd up. */
846 if (wrerr == NO) {
847 j = atomicio(write, ofd, bp->buf, count);
848 if (j != count) {
849 wrerr = YES;
850 wrerrno = j >= 0 ? EIO : errno;
851 }
852 }
853 count = 0;
854 cp = bp->buf;
855 }
856 }
857 if (showprogress)
858 progressmeter(1);
859 if (count != 0 && wrerr == NO &&
860 (j = atomicio(write, ofd, bp->buf, count)) != count) {
861 wrerr = YES;
862 wrerrno = j >= 0 ? EIO : errno;
863 }
864#if 0
865 if (ftruncate(ofd, size)) {
866 run_err("%s: truncate: %s", np, strerror(errno));
867 wrerr = DISPLAYED;
868 }
869#endif
870 if (pflag) {
871 if (exists || omode != mode)
872#ifdef HAVE_FCHMOD
873 if (fchmod(ofd, omode))
874#else /* HAVE_FCHMOD */
875 if (chmod(np, omode))
876#endif /* HAVE_FCHMOD */
877 run_err("%s: set mode: %s",
878 np, strerror(errno));
879 } else {
880 if (!exists && omode != mode)
881#ifdef HAVE_FCHMOD
882 if (fchmod(ofd, omode & ~mask))
883#else /* HAVE_FCHMOD */
884 if (chmod(np, omode & ~mask))
885#endif /* HAVE_FCHMOD */
886 run_err("%s: set mode: %s",
887 np, strerror(errno));
888 }
889 if (close(ofd) == -1) {
890 wrerr = YES;
891 wrerrno = errno;
892 }
893 (void) response();
894 if (setimes && wrerr == NO) {
895 setimes = 0;
896 if (utimes(np, tv) < 0) {
897 run_err("%s: set times: %s",
898 np, strerror(errno));
899 wrerr = DISPLAYED;
900 }
901 }
902 switch (wrerr) {
903 case YES:
904 run_err("%s: %s", np, strerror(wrerrno));
905 break;
906 case NO:
907 (void) atomicio(write, remout, "", 1);
908 break;
909 case DISPLAYED:
910 break;
911 }
912 }
913screwup:
914 run_err("protocol error: %s", why);
915 exit(1);
916}
917
918int
919response()
920{
921 char ch, *cp, resp, rbuf[2048];
922
923 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
924 lostconn(0);
925
926 cp = rbuf;
927 switch (resp) {
928 case 0: /* ok */
929 return (0);
930 default:
931 *cp++ = resp;
932 /* FALLTHROUGH */
933 case 1: /* error, followed by error msg */
934 case 2: /* fatal error, "" */
935 do {
936 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
937 lostconn(0);
938 *cp++ = ch;
939 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
940
941 if (!iamremote)
942 (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf);
943 ++errs;
944 if (resp == 1)
945 return (-1);
946 exit(1);
947 }
948 /* NOTREACHED */
949}
950
951void
952usage()
953{
954 (void) fprintf(stderr, "usage: scp "
955 "[-pqrvC46] [-S ssh] [-P port] [-c cipher] [-i identity] f1 f2; or:\n"
956 " scp [options] f1 ... fn directory\n");
957 exit(1);
958}
959
960void
961run_err(const char *fmt,...)
962{
963 static FILE *fp;
964 va_list ap;
965
966 ++errs;
967 if (fp == NULL && !(fp = fdopen(remout, "w")))
968 return;
969 (void) fprintf(fp, "%c", 0x01);
970 (void) fprintf(fp, "scp: ");
971 va_start(ap, fmt);
972 (void) vfprintf(fp, fmt, ap);
973 va_end(ap);
974 (void) fprintf(fp, "\n");
975 (void) fflush(fp);
976
977 if (!iamremote) {
978 va_start(ap, fmt);
979 vfprintf(stderr, fmt, ap);
980 va_end(ap);
981 fprintf(stderr, "\n");
982 }
983}
984
985char *
986colon(cp)
987 char *cp;
988{
989 int flag = 0;
990
991 if (*cp == ':') /* Leading colon is part of file name. */
992 return (0);
993 if (*cp == '[')
994 flag = 1;
995
996 for (; *cp; ++cp) {
997 if (*cp == '@' && *(cp+1) == '[')
998 flag = 1;
999 if (*cp == ']' && *(cp+1) == ':' && flag)
1000 return (cp+1);
1001 if (*cp == ':' && !flag)
1002 return (cp);
1003 if (*cp == '/')
1004 return (0);
1005 }
1006 return (0);
1007}
1008
1009void
1010verifydir(cp)
1011 char *cp;
1012{
1013 struct stat stb;
1014
1015 if (!stat(cp, &stb)) {
1016 if (S_ISDIR(stb.st_mode))
1017 return;
1018 errno = ENOTDIR;
1019 }
1020 run_err("%s: %s", cp, strerror(errno));
1021 exit(1);
1022}
1023
1024int
1025okname(cp0)
1026 char *cp0;
1027{
1028 int c;
1029 char *cp;
1030
1031 cp = cp0;
1032 do {
1033 c = *cp;
1034 if (c & 0200)
1035 goto bad;
1036 if (!isalpha(c) && !isdigit(c) &&
1037 c != '_' && c != '-' && c != '.' && c != '+')
1038 goto bad;
1039 } while (*++cp);
1040 return (1);
1041
1042bad: fprintf(stderr, "%s: invalid user name\n", cp0);
1043 return (0);
1044}
1045
1046BUF *
1047allocbuf(bp, fd, blksize)
1048 BUF *bp;
1049 int fd, blksize;
1050{
1051 size_t size;
1052#ifdef HAVE_ST_BLKSIZE
1053 struct stat stb;
1054
1055 if (fstat(fd, &stb) < 0) {
1056 run_err("fstat: %s", strerror(errno));
1057 return (0);
1058 }
1059 if (stb.st_blksize == 0)
1060 size = blksize;
1061 else
1062 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) %
1063 stb.st_blksize;
1064#else /* HAVE_ST_BLKSIZE */
1065 size = blksize;
1066#endif /* HAVE_ST_BLKSIZE */
1067 if (bp->cnt >= size)
1068 return (bp);
1069 if (bp->buf == NULL)
1070 bp->buf = xmalloc(size);
1071 else
1072 bp->buf = xrealloc(bp->buf, size);
1073 bp->cnt = size;
1074 return (bp);
1075}
1076
1077void
1078lostconn(signo)
1079 int signo;
1080{
1081 if (!iamremote)
1082 fprintf(stderr, "lost connection\n");
1083 exit(1);
1084}
1085
1086
1087void
1088alarmtimer(int wait)
1089{
1090 struct itimerval itv;
1091
1092 itv.it_value.tv_sec = wait;
1093 itv.it_value.tv_usec = 0;
1094 itv.it_interval = itv.it_value;
1095 setitimer(ITIMER_REAL, &itv, NULL);
1096}
1097
1098void
1099updateprogressmeter(int ignore)
1100{
1101 int save_errno = errno;
1102
1103 progressmeter(0);
1104 errno = save_errno;
1105}
1106
1107int
1108foregroundproc()
1109{
1110 static pid_t pgrp = -1;
1111 int ctty_pgrp;
1112
1113 if (pgrp == -1)
1114 pgrp = getpgrp();
1115
1116#ifdef HAVE_CYGWIN
1117 /*
1118 * Cygwin only supports tcgetpgrp() for getting the controlling tty
1119 * currently.
1120 */
1121 return ((ctty_pgrp = tcgetpgrp(STDOUT_FILENO)) != -1 &&
1122 ctty_pgrp == pgrp);
1123#else
1124 return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 &&
1125 ctty_pgrp == pgrp));
1126#endif
1127}
1128
1129void
1130progressmeter(int flag)
1131{
1132 static const char prefixes[] = " KMGTP";
1133 static struct timeval lastupdate;
1134 static off_t lastsize;
1135 struct timeval now, td, wait;
1136 off_t cursize, abbrevsize;
1137 double elapsed;
1138 int ratio, barlength, i, remaining;
1139 char buf[256];
1140
1141 if (flag == -1) {
1142 (void) gettimeofday(&start, (struct timezone *) 0);
1143 lastupdate = start;
1144 lastsize = 0;
1145 }
1146 if (foregroundproc() == 0)
1147 return;
1148
1149 (void) gettimeofday(&now, (struct timezone *) 0);
1150 cursize = statbytes;
1151 if (totalbytes != 0) {
1152 ratio = 100.0 * cursize / totalbytes;
1153 ratio = MAX(ratio, 0);
1154 ratio = MIN(ratio, 100);
1155 } else
1156 ratio = 100;
1157
1158 snprintf(buf, sizeof(buf), "\r%-20.20s %3d%% ", curfile, ratio);
1159
1160 barlength = getttywidth() - 51;
1161 barlength = (barlength <= MAX_BARLENGTH)?barlength:MAX_BARLENGTH;
1162 if (barlength > 0) {
1163 i = barlength * ratio / 100;
1164 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1165 "|%.*s%*s|", i, BAR, barlength - i, "");
1166 }
1167 i = 0;
1168 abbrevsize = cursize;
1169 while (abbrevsize >= 100000 && i < sizeof(prefixes)) {
1170 i++;
1171 abbrevsize >>= 10;
1172 }
1173 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " %5d %c%c ",
1174 (int) abbrevsize, prefixes[i], prefixes[i] == ' ' ? ' ' : 'B');
1175
1176 timersub(&now, &lastupdate, &wait);
1177 if (cursize > lastsize) {
1178 lastupdate = now;
1179 lastsize = cursize;
1180 if (wait.tv_sec >= STALLTIME) {
1181 start.tv_sec += wait.tv_sec;
1182 start.tv_usec += wait.tv_usec;
1183 }
1184 wait.tv_sec = 0;
1185 }
1186 timersub(&now, &start, &td);
1187 elapsed = td.tv_sec + (td.tv_usec / 1000000.0);
1188
1189 if (flag != 1 &&
1190 (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes)) {
1191 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1192 " --:-- ETA");
1193 } else if (wait.tv_sec >= STALLTIME) {
1194 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1195 " - stalled -");
1196 } else {
1197 if (flag != 1)
1198 remaining = (int)(totalbytes / (statbytes / elapsed) -
1199 elapsed);
1200 else
1201 remaining = elapsed;
1202
1203 i = remaining / 3600;
1204 if (i)
1205 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1206 "%2d:", i);
1207 else
1208 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1209 " ");
1210 i = remaining % 3600;
1211 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1212 "%02d:%02d%s", i / 60, i % 60,
1213 (flag != 1) ? " ETA" : " ");
1214 }
1215 atomicio(write, fileno(stdout), buf, strlen(buf));
1216
1217 if (flag == -1) {
1218 struct sigaction sa;
1219 sa.sa_handler = updateprogressmeter;
1220 sigemptyset((sigset_t *)&sa.sa_mask);
1221#ifdef SA_RESTART
1222 sa.sa_flags = SA_RESTART;
1223#endif
1224 sigaction(SIGALRM, &sa, NULL);
1225 alarmtimer(1);
1226 } else if (flag == 1) {
1227 alarmtimer(0);
1228 atomicio(write, fileno(stdout), "\n", 1);
1229 statbytes = 0;
1230 }
1231}
1232
1233int
1234getttywidth(void)
1235{
1236 struct winsize winsize;
1237
1238 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1)
1239 return (winsize.ws_col ? winsize.ws_col : 80);
1240 else
1241 return (80);
1242}
1243
1244void
1245addargs(char *fmt, ...)
1246{
1247 va_list ap;
1248 char buf[1024];
1249
1250 va_start(ap, fmt);
1251 vsnprintf(buf, sizeof(buf), fmt, ap);
1252 va_end(ap);
1253
1254 if (args.list == NULL) {
1255 args.nalloc = 32;
1256 args.num = 0;
1257 args.list = xmalloc(args.nalloc * sizeof(char *));
1258 } else if (args.num+2 >= args.nalloc) {
1259 args.nalloc *= 2;
1260 args.list = xrealloc(args.list, args.nalloc * sizeof(char *));
1261 }
1262 args.list[args.num++] = xstrdup(buf);
1263 args.list[args.num] = NULL;
1264}
This page took 0.048838 seconds and 5 git commands to generate.