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