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