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