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