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