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