comparison scp.c @ 4:fe6bca95afa7

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