]> andersk Git - openssh.git/blob - scp.c
e5332972c2bcd82d866bdc04ee9e590b4aa0642e
[openssh.git] / scp.c
1 /* $OpenBSD: scp.c,v 1.142 2006/05/17 12:43:34 markus 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 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
96
97 void bwlimit(int);
98
99 /* Struct for addargs */
100 arglist args;
101
102 /* Bandwidth limit */
103 off_t limit_rate = 0;
104
105 /* Name of current file being transferred. */
106 char *curfile;
107
108 /* This is set to non-zero to enable verbose mode. */
109 int verbose_mode = 0;
110
111 /* This is set to zero if the progressmeter is not desired. */
112 int showprogress = 1;
113
114 /* This is the program to execute for the secured connection. ("ssh" or -S) */
115 char *ssh_program = _PATH_SSH_PROGRAM;
116
117 /* This is used to store the pid of ssh_program */
118 pid_t do_cmd_pid = -1;
119
120 static void
121 killchild(int signo)
122 {
123         if (do_cmd_pid > 1) {
124                 kill(do_cmd_pid, signo ? signo : SIGTERM);
125                 waitpid(do_cmd_pid, NULL, 0);
126         }
127
128         if (signo)
129                 _exit(1);
130         exit(1);
131 }
132
133 static int
134 do_local_cmd(arglist *a)
135 {
136         u_int i;
137         int status;
138         pid_t pid;
139
140         if (a->num == 0)
141                 fatal("do_local_cmd: no arguments");
142
143         if (verbose_mode) {
144                 fprintf(stderr, "Executing:");
145                 for (i = 0; i < a->num; i++)
146                         fprintf(stderr, " %s", a->list[i]);
147                 fprintf(stderr, "\n");
148         }
149         if ((pid = fork()) == -1)
150                 fatal("do_local_cmd: fork: %s", strerror(errno));
151
152         if (pid == 0) {
153                 execvp(a->list[0], a->list);
154                 perror(a->list[0]);
155                 exit(1);
156         }
157
158         do_cmd_pid = pid;
159         signal(SIGTERM, killchild);
160         signal(SIGINT, killchild);
161         signal(SIGHUP, killchild);
162
163         while (waitpid(pid, &status, 0) == -1)
164                 if (errno != EINTR)
165                         fatal("do_local_cmd: waitpid: %s", strerror(errno));
166
167         do_cmd_pid = -1;
168
169         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
170                 return (-1);
171
172         return (0);
173 }
174
175 /*
176  * This function executes the given command as the specified user on the
177  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
178  * assigns the input and output file descriptors on success.
179  */
180
181 int
182 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
183 {
184         int pin[2], pout[2], reserved[2];
185
186         if (verbose_mode)
187                 fprintf(stderr,
188                     "Executing: program %s host %s, user %s, command %s\n",
189                     ssh_program, host,
190                     remuser ? remuser : "(unspecified)", cmd);
191
192         /*
193          * Reserve two descriptors so that the real pipes won't get
194          * descriptors 0 and 1 because that will screw up dup2 below.
195          */
196         if (pipe(reserved) < 0)
197                 fatal("pipe: %s", strerror(errno));
198
199         /* Create a socket pair for communicating with ssh. */
200         if (pipe(pin) < 0)
201                 fatal("pipe: %s", strerror(errno));
202         if (pipe(pout) < 0)
203                 fatal("pipe: %s", strerror(errno));
204
205         /* Free the reserved descriptors. */
206         close(reserved[0]);
207         close(reserved[1]);
208
209         /* Fork a child to execute the command on the remote host using ssh. */
210         do_cmd_pid = fork();
211         if (do_cmd_pid == 0) {
212                 /* Child. */
213                 close(pin[1]);
214                 close(pout[0]);
215                 dup2(pin[0], 0);
216                 dup2(pout[1], 1);
217                 close(pin[0]);
218                 close(pout[1]);
219
220                 replacearg(&args, 0, "%s", ssh_program);
221                 if (remuser != NULL)
222                         addargs(&args, "-l%s", remuser);
223                 addargs(&args, "%s", host);
224                 addargs(&args, "%s", cmd);
225
226                 execvp(ssh_program, args.list);
227                 perror(ssh_program);
228                 exit(1);
229         } else if (do_cmd_pid == -1) {
230                 fatal("fork: %s", strerror(errno));
231         }
232         /* Parent.  Close the other side, and return the local side. */
233         close(pin[0]);
234         *fdout = pin[1];
235         close(pout[1]);
236         *fdin = pout[0];
237         signal(SIGTERM, killchild);
238         signal(SIGINT, killchild);
239         signal(SIGHUP, killchild);
240         return 0;
241 }
242
243 typedef struct {
244         size_t cnt;
245         char *buf;
246 } BUF;
247
248 BUF *allocbuf(BUF *, int, int);
249 void lostconn(int);
250 int okname(char *);
251 void run_err(const char *,...);
252 void verifydir(char *);
253
254 struct passwd *pwd;
255 uid_t userid;
256 int errs, remin, remout;
257 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
258
259 #define CMDNEEDS        64
260 char cmd[CMDNEEDS];             /* must hold "rcp -r -p -d\0" */
261
262 int response(void);
263 void rsource(char *, struct stat *);
264 void sink(int, char *[]);
265 void source(int, char *[]);
266 void tolocal(int, char *[]);
267 void toremote(char *, int, char *[]);
268 void usage(void);
269
270 int
271 main(int argc, char **argv)
272 {
273         int ch, fflag, tflag, status;
274         double speed;
275         char *targ, *endp;
276         extern char *optarg;
277         extern int optind;
278
279         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
280         sanitise_stdfd();
281
282         __progname = ssh_get_progname(argv[0]);
283
284         memset(&args, '\0', sizeof(args));
285         args.list = NULL;
286         addargs(&args, "%s", ssh_program);
287         addargs(&args, "-x");
288         addargs(&args, "-oForwardAgent no");
289         addargs(&args, "-oPermitLocalCommand no");
290         addargs(&args, "-oClearAllForwardings yes");
291
292         fflag = tflag = 0;
293         while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q1246S:o:F:")) != -1)
294                 switch (ch) {
295                 /* User-visible flags. */
296                 case '1':
297                 case '2':
298                 case '4':
299                 case '6':
300                 case 'C':
301                         addargs(&args, "-%c", ch);
302                         break;
303                 case 'o':
304                 case 'c':
305                 case 'i':
306                 case 'F':
307                         addargs(&args, "-%c%s", ch, optarg);
308                         break;
309                 case 'P':
310                         addargs(&args, "-p%s", optarg);
311                         break;
312                 case 'B':
313                         addargs(&args, "-oBatchmode yes");
314                         break;
315                 case 'l':
316                         speed = strtod(optarg, &endp);
317                         if (speed <= 0 || *endp != '\0')
318                                 usage();
319                         limit_rate = speed * 1024;
320                         break;
321                 case 'p':
322                         pflag = 1;
323                         break;
324                 case 'r':
325                         iamrecursive = 1;
326                         break;
327                 case 'S':
328                         ssh_program = xstrdup(optarg);
329                         break;
330                 case 'v':
331                         addargs(&args, "-v");
332                         verbose_mode = 1;
333                         break;
334                 case 'q':
335                         addargs(&args, "-q");
336                         showprogress = 0;
337                         break;
338
339                 /* Server options. */
340                 case 'd':
341                         targetshouldbedirectory = 1;
342                         break;
343                 case 'f':       /* "from" */
344                         iamremote = 1;
345                         fflag = 1;
346                         break;
347                 case 't':       /* "to" */
348                         iamremote = 1;
349                         tflag = 1;
350 #ifdef HAVE_CYGWIN
351                         setmode(0, O_BINARY);
352 #endif
353                         break;
354                 default:
355                         usage();
356                 }
357         argc -= optind;
358         argv += optind;
359
360         if ((pwd = getpwuid(userid = getuid())) == NULL)
361                 fatal("unknown user %u", (u_int) userid);
362
363         if (!isatty(STDERR_FILENO))
364                 showprogress = 0;
365
366         remin = STDIN_FILENO;
367         remout = STDOUT_FILENO;
368
369         if (fflag) {
370                 /* Follow "protocol", send data. */
371                 (void) response();
372                 source(argc, argv);
373                 exit(errs != 0);
374         }
375         if (tflag) {
376                 /* Receive data. */
377                 sink(argc, argv);
378                 exit(errs != 0);
379         }
380         if (argc < 2)
381                 usage();
382         if (argc > 2)
383                 targetshouldbedirectory = 1;
384
385         remin = remout = -1;
386         do_cmd_pid = -1;
387         /* Command to be executed on remote system using "ssh". */
388         (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
389             verbose_mode ? " -v" : "",
390             iamrecursive ? " -r" : "", pflag ? " -p" : "",
391             targetshouldbedirectory ? " -d" : "");
392
393         (void) signal(SIGPIPE, lostconn);
394
395         if ((targ = colon(argv[argc - 1])))     /* Dest is remote host. */
396                 toremote(targ, argc, argv);
397         else {
398                 if (targetshouldbedirectory)
399                         verifydir(argv[argc - 1]);
400                 tolocal(argc, argv);    /* Dest is local host. */
401         }
402         /*
403          * Finally check the exit status of the ssh process, if one was forked
404          * and no error has occured yet
405          */
406         if (do_cmd_pid != -1 && errs == 0) {
407                 if (remin != -1)
408                     (void) close(remin);
409                 if (remout != -1)
410                     (void) close(remout);
411                 if (waitpid(do_cmd_pid, &status, 0) == -1)
412                         errs = 1;
413                 else {
414                         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
415                                 errs = 1;
416                 }
417         }
418         exit(errs != 0);
419 }
420
421 void
422 toremote(char *targ, int argc, char **argv)
423 {
424         char *bp, *host, *src, *suser, *thost, *tuser, *arg;
425         arglist alist;
426         int i;
427
428         memset(&alist, '\0', sizeof(alist));
429         alist.list = NULL;
430
431         *targ++ = 0;
432         if (*targ == 0)
433                 targ = ".";
434
435         arg = xstrdup(argv[argc - 1]);
436         if ((thost = strrchr(arg, '@'))) {
437                 /* user@host */
438                 *thost++ = 0;
439                 tuser = arg;
440                 if (*tuser == '\0')
441                         tuser = NULL;
442         } else {
443                 thost = arg;
444                 tuser = NULL;
445         }
446
447         if (tuser != NULL && !okname(tuser)) {
448                 xfree(arg);
449                 return;
450         }
451
452         for (i = 0; i < argc - 1; i++) {
453                 src = colon(argv[i]);
454                 if (src) {      /* remote to remote */
455                         freeargs(&alist);
456                         addargs(&alist, "%s", ssh_program);
457                         if (verbose_mode)
458                                 addargs(&alist, "-v");
459                         addargs(&alist, "-x");
460                         addargs(&alist, "-oClearAllForwardings yes");
461                         addargs(&alist, "-n");
462
463                         *src++ = 0;
464                         if (*src == 0)
465                                 src = ".";
466                         host = strrchr(argv[i], '@');
467
468                         if (host) {
469                                 *host++ = 0;
470                                 host = cleanhostname(host);
471                                 suser = argv[i];
472                                 if (*suser == '\0')
473                                         suser = pwd->pw_name;
474                                 else if (!okname(suser))
475                                         continue;
476                                 addargs(&alist, "-l");
477                                 addargs(&alist, "%s", suser);
478                         } else {
479                                 host = cleanhostname(argv[i]);
480                         }
481                         addargs(&alist, "%s", host);
482                         addargs(&alist, "%s", cmd);
483                         addargs(&alist, "%s", src);
484                         addargs(&alist, "%s%s%s:%s",
485                             tuser ? tuser : "", tuser ? "@" : "",
486                             thost, targ);
487                         if (do_local_cmd(&alist) != 0)
488                                 errs = 1;
489                 } else {        /* local to remote */
490                         if (remin == -1) {
491                                 xasprintf(&bp, "%s -t %s", cmd, targ);
492                                 host = cleanhostname(thost);
493                                 if (do_cmd(host, tuser, bp, &remin,
494                                     &remout) < 0)
495                                         exit(1);
496                                 if (response() < 0)
497                                         exit(1);
498                                 (void) xfree(bp);
499                         }
500                         source(1, argv + i);
501                 }
502         }
503         xfree(arg);
504 }
505
506 void
507 tolocal(int argc, char **argv)
508 {
509         char *bp, *host, *src, *suser;
510         arglist alist;
511         int i;
512
513         memset(&alist, '\0', sizeof(alist));
514         alist.list = NULL;
515
516         for (i = 0; i < argc - 1; i++) {
517                 if (!(src = colon(argv[i]))) {  /* Local to local. */
518                         freeargs(&alist);
519                         addargs(&alist, "%s", _PATH_CP);
520                         if (iamrecursive)
521                                 addargs(&alist, "-r");
522                         if (pflag)
523                                 addargs(&alist, "-p");
524                         addargs(&alist, "%s", argv[i]);
525                         addargs(&alist, "%s", argv[argc-1]);
526                         if (do_local_cmd(&alist))
527                                 ++errs;
528                         continue;
529                 }
530                 *src++ = 0;
531                 if (*src == 0)
532                         src = ".";
533                 if ((host = strrchr(argv[i], '@')) == NULL) {
534                         host = argv[i];
535                         suser = NULL;
536                 } else {
537                         *host++ = 0;
538                         suser = argv[i];
539                         if (*suser == '\0')
540                                 suser = pwd->pw_name;
541                 }
542                 host = cleanhostname(host);
543                 xasprintf(&bp, "%s -f %s", cmd, src);
544                 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
545                         (void) xfree(bp);
546                         ++errs;
547                         continue;
548                 }
549                 xfree(bp);
550                 sink(1, argv + argc - 1);
551                 (void) close(remin);
552                 remin = remout = -1;
553         }
554 }
555
556 void
557 source(int argc, char **argv)
558 {
559         struct stat stb;
560         static BUF buffer;
561         BUF *bp;
562         off_t i, amt, statbytes;
563         size_t result;
564         int fd = -1, haderr, indx;
565         char *last, *name, buf[2048];
566         int len;
567
568         for (indx = 0; indx < argc; ++indx) {
569                 name = argv[indx];
570                 statbytes = 0;
571                 len = strlen(name);
572                 while (len > 1 && name[len-1] == '/')
573                         name[--len] = '\0';
574                 if (strchr(name, '\n') != NULL) {
575                         run_err("%s: skipping, filename contains a newline",
576                             name);
577                         goto next;
578                 }
579                 if ((fd = open(name, O_RDONLY, 0)) < 0)
580                         goto syserr;
581                 if (fstat(fd, &stb) < 0) {
582 syserr:                 run_err("%s: %s", name, strerror(errno));
583                         goto next;
584                 }
585                 switch (stb.st_mode & S_IFMT) {
586                 case S_IFREG:
587                         break;
588                 case S_IFDIR:
589                         if (iamrecursive) {
590                                 rsource(name, &stb);
591                                 goto next;
592                         }
593                         /* FALLTHROUGH */
594                 default:
595                         run_err("%s: not a regular file", name);
596                         goto next;
597                 }
598                 if ((last = strrchr(name, '/')) == NULL)
599                         last = name;
600                 else
601                         ++last;
602                 curfile = last;
603                 if (pflag) {
604                         /*
605                          * Make it compatible with possible future
606                          * versions expecting microseconds.
607                          */
608                         (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
609                             (u_long) stb.st_mtime,
610                             (u_long) stb.st_atime);
611                         (void) atomicio(vwrite, remout, buf, strlen(buf));
612                         if (response() < 0)
613                                 goto next;
614                 }
615 #define FILEMODEMASK    (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
616                 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
617                     (u_int) (stb.st_mode & FILEMODEMASK),
618                     (long long)stb.st_size, last);
619                 if (verbose_mode) {
620                         fprintf(stderr, "Sending file modes: %s", buf);
621                 }
622                 (void) atomicio(vwrite, remout, buf, strlen(buf));
623                 if (response() < 0)
624                         goto next;
625                 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) {
626 next:                   if (fd != -1) {
627                                 (void) close(fd);
628                                 fd = -1;
629                         }
630                         continue;
631                 }
632                 if (showprogress)
633                         start_progress_meter(curfile, stb.st_size, &statbytes);
634                 /* Keep writing after an error so that we stay sync'd up. */
635                 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
636                         amt = bp->cnt;
637                         if (i + amt > stb.st_size)
638                                 amt = stb.st_size - i;
639                         if (!haderr) {
640                                 result = atomicio(read, fd, bp->buf, amt);
641                                 if (result != amt)
642                                         haderr = errno;
643                         }
644                         if (haderr)
645                                 (void) atomicio(vwrite, remout, bp->buf, amt);
646                         else {
647                                 result = atomicio(vwrite, remout, bp->buf, amt);
648                                 if (result != amt)
649                                         haderr = errno;
650                                 statbytes += result;
651                         }
652                         if (limit_rate)
653                                 bwlimit(amt);
654                 }
655                 if (showprogress)
656                         stop_progress_meter();
657
658                 if (fd != -1) {
659                         if (close(fd) < 0 && !haderr)
660                                 haderr = errno;
661                         fd = -1;
662                 }
663                 if (!haderr)
664                         (void) atomicio(vwrite, remout, "", 1);
665                 else
666                         run_err("%s: %s", name, strerror(haderr));
667                 (void) response();
668         }
669 }
670
671 void
672 rsource(char *name, struct stat *statp)
673 {
674         DIR *dirp;
675         struct dirent *dp;
676         char *last, *vect[1], path[1100];
677
678         if (!(dirp = opendir(name))) {
679                 run_err("%s: %s", name, strerror(errno));
680                 return;
681         }
682         last = strrchr(name, '/');
683         if (last == 0)
684                 last = name;
685         else
686                 last++;
687         if (pflag) {
688                 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
689                     (u_long) statp->st_mtime,
690                     (u_long) statp->st_atime);
691                 (void) atomicio(vwrite, remout, path, strlen(path));
692                 if (response() < 0) {
693                         closedir(dirp);
694                         return;
695                 }
696         }
697         (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
698             (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
699         if (verbose_mode)
700                 fprintf(stderr, "Entering directory: %s", path);
701         (void) atomicio(vwrite, remout, path, strlen(path));
702         if (response() < 0) {
703                 closedir(dirp);
704                 return;
705         }
706         while ((dp = readdir(dirp)) != NULL) {
707                 if (dp->d_ino == 0)
708                         continue;
709                 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
710                         continue;
711                 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
712                         run_err("%s/%s: name too long", name, dp->d_name);
713                         continue;
714                 }
715                 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
716                 vect[0] = path;
717                 source(1, vect);
718         }
719         (void) closedir(dirp);
720         (void) atomicio(vwrite, remout, "E\n", 2);
721         (void) response();
722 }
723
724 void
725 bwlimit(int amount)
726 {
727         static struct timeval bwstart, bwend;
728         static int lamt, thresh = 16384;
729         u_int64_t waitlen;
730         struct timespec ts, rm;
731
732         if (!timerisset(&bwstart)) {
733                 gettimeofday(&bwstart, NULL);
734                 return;
735         }
736
737         lamt += amount;
738         if (lamt < thresh)
739                 return;
740
741         gettimeofday(&bwend, NULL);
742         timersub(&bwend, &bwstart, &bwend);
743         if (!timerisset(&bwend))
744                 return;
745
746         lamt *= 8;
747         waitlen = (double)1000000L * lamt / limit_rate;
748
749         bwstart.tv_sec = waitlen / 1000000L;
750         bwstart.tv_usec = waitlen % 1000000L;
751
752         if (timercmp(&bwstart, &bwend, >)) {
753                 timersub(&bwstart, &bwend, &bwend);
754
755                 /* Adjust the wait time */
756                 if (bwend.tv_sec) {
757                         thresh /= 2;
758                         if (thresh < 2048)
759                                 thresh = 2048;
760                 } else if (bwend.tv_usec < 100) {
761                         thresh *= 2;
762                         if (thresh > 32768)
763                                 thresh = 32768;
764                 }
765
766                 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
767                 while (nanosleep(&ts, &rm) == -1) {
768                         if (errno != EINTR)
769                                 break;
770                         ts = rm;
771                 }
772         }
773
774         lamt = 0;
775         gettimeofday(&bwstart, NULL);
776 }
777
778 void
779 sink(int argc, char **argv)
780 {
781         static BUF buffer;
782         struct stat stb;
783         enum {
784                 YES, NO, DISPLAYED
785         } wrerr;
786         BUF *bp;
787         off_t i;
788         size_t j, count;
789         int amt, exists, first, ofd;
790         mode_t mode, omode, mask;
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 1.481564 seconds and 3 git commands to generate.