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