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