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