]> andersk Git - gssapi-openssh.git/blob - openssh/scp.c
merged OPENSSH_5_2P1_GSSAPI_20090225 to GPT-branch
[gssapi-openssh.git] / openssh / scp.c
1 /* $OpenBSD: scp.c,v 1.164 2008/10/10 04:55:16 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_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 occurred 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 || errno == EWOULDBLOCK) {
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, statbytes;
635         size_t amt;
636         int fd = -1, haderr, indx;
637         char *last, *name, buf[16384], encname[MAXPATHLEN];
638         int len;
639
640         for (indx = 0; indx < argc; ++indx) {
641                 name = argv[indx];
642                 statbytes = 0;
643                 len = strlen(name);
644                 while (len > 1 && name[len-1] == '/')
645                         name[--len] = '\0';
646                 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
647                         goto syserr;
648                 if (strchr(name, '\n') != NULL) {
649                         strnvis(encname, name, sizeof(encname), VIS_NL);
650                         name = encname;
651                 }
652                 if (fstat(fd, &stb) < 0) {
653 syserr:                 run_err("%s: %s", name, strerror(errno));
654                         goto next;
655                 }
656                 if (stb.st_size < 0) {
657                         run_err("%s: %s", name, "Negative file size");
658                         goto next;
659                 }
660                 unset_nonblock(fd);
661                 switch (stb.st_mode & S_IFMT) {
662                 case S_IFREG:
663                         break;
664                 case S_IFDIR:
665                         if (iamrecursive) {
666                                 rsource(name, &stb);
667                                 goto next;
668                         }
669                         /* FALLTHROUGH */
670                 default:
671                         run_err("%s: not a regular file", name);
672                         goto next;
673                 }
674                 if ((last = strrchr(name, '/')) == NULL)
675                         last = name;
676                 else
677                         ++last;
678                 curfile = last;
679                 if (pflag) {
680                         /*
681                          * Make it compatible with possible future
682                          * versions expecting microseconds.
683                          */
684                         (void) snprintf(buf, sizeof buf, "T%lu 0 %lu 0\n",
685                             (u_long) (stb.st_mtime < 0 ? 0 : stb.st_mtime),
686                             (u_long) (stb.st_atime < 0 ? 0 : stb.st_atime));
687                         if (verbose_mode) {
688                                 fprintf(stderr, "File mtime %ld atime %ld\n",
689                                     (long)stb.st_mtime, (long)stb.st_atime);
690                                 fprintf(stderr, "Sending file timestamps: %s",
691                                     buf);
692                         }
693                         (void) atomicio(vwrite, remout, buf, strlen(buf));
694                         if (response() < 0)
695                                 goto next;
696                 }
697 #define FILEMODEMASK    (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
698                 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
699                     (u_int) (stb.st_mode & FILEMODEMASK),
700                     (long long)stb.st_size, last);
701                 if (verbose_mode) {
702                         fprintf(stderr, "Sending file modes: %s", buf);
703                 }
704                 (void) atomicio(vwrite, remout, buf, strlen(buf));
705                 if (response() < 0)
706                         goto next;
707                 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
708 next:                   if (fd != -1) {
709                                 (void) close(fd);
710                                 fd = -1;
711                         }
712                         continue;
713                 }
714                 if (showprogress)
715                         start_progress_meter(curfile, stb.st_size, &statbytes);
716                 set_nonblock(remout);
717                 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
718                         amt = bp->cnt;
719                         if (i + (off_t)amt > stb.st_size)
720                                 amt = stb.st_size - i;
721                         if (!haderr) {
722                                 if (atomicio(read, fd, bp->buf, amt) != amt)
723                                         haderr = errno;
724                         }
725                         /* Keep writing after error to retain sync */
726                         if (haderr) {
727                                 (void)atomicio(vwrite, remout, bp->buf, amt);
728                                 continue;
729                         }
730                         if (scpio(vwrite, remout, bp->buf, amt,
731                             &statbytes) != amt)
732                                 haderr = errno;
733                 }
734                 unset_nonblock(remout);
735                 if (showprogress)
736                         stop_progress_meter();
737
738                 if (fd != -1) {
739                         if (close(fd) < 0 && !haderr)
740                                 haderr = errno;
741                         fd = -1;
742                 }
743                 if (!haderr)
744                         (void) atomicio(vwrite, remout, "", 1);
745                 else
746                         run_err("%s: %s", name, strerror(haderr));
747                 (void) response();
748         }
749 }
750
751 void
752 rsource(char *name, struct stat *statp)
753 {
754         DIR *dirp;
755         struct dirent *dp;
756         char *last, *vect[1], path[1100];
757
758         if (!(dirp = opendir(name))) {
759                 run_err("%s: %s", name, strerror(errno));
760                 return;
761         }
762         last = strrchr(name, '/');
763         if (last == 0)
764                 last = name;
765         else
766                 last++;
767         if (pflag) {
768                 (void) snprintf(path, sizeof(path), "T%lu 0 %lu 0\n",
769                     (u_long) statp->st_mtime,
770                     (u_long) statp->st_atime);
771                 (void) atomicio(vwrite, remout, path, strlen(path));
772                 if (response() < 0) {
773                         closedir(dirp);
774                         return;
775                 }
776         }
777         (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
778             (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
779         if (verbose_mode)
780                 fprintf(stderr, "Entering directory: %s", path);
781         (void) atomicio(vwrite, remout, path, strlen(path));
782         if (response() < 0) {
783                 closedir(dirp);
784                 return;
785         }
786         while ((dp = readdir(dirp)) != NULL) {
787                 if (dp->d_ino == 0)
788                         continue;
789                 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
790                         continue;
791                 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
792                         run_err("%s/%s: name too long", name, dp->d_name);
793                         continue;
794                 }
795                 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
796                 vect[0] = path;
797                 source(1, vect);
798         }
799         (void) closedir(dirp);
800         (void) atomicio(vwrite, remout, "E\n", 2);
801         (void) response();
802 }
803
804 void
805 bwlimit(int amount)
806 {
807         static struct timeval bwstart, bwend;
808         static int lamt, thresh = 16384;
809         u_int64_t waitlen;
810         struct timespec ts, rm;
811
812         if (!timerisset(&bwstart)) {
813                 gettimeofday(&bwstart, NULL);
814                 return;
815         }
816
817         lamt += amount;
818         if (lamt < thresh)
819                 return;
820
821         gettimeofday(&bwend, NULL);
822         timersub(&bwend, &bwstart, &bwend);
823         if (!timerisset(&bwend))
824                 return;
825
826         lamt *= 8;
827         waitlen = (double)1000000L * lamt / limit_rate;
828
829         bwstart.tv_sec = waitlen / 1000000L;
830         bwstart.tv_usec = waitlen % 1000000L;
831
832         if (timercmp(&bwstart, &bwend, >)) {
833                 timersub(&bwstart, &bwend, &bwend);
834
835                 /* Adjust the wait time */
836                 if (bwend.tv_sec) {
837                         thresh /= 2;
838                         if (thresh < 2048)
839                                 thresh = 2048;
840                 } else if (bwend.tv_usec < 10000) {
841                         thresh *= 2;
842                         if (thresh > COPY_BUFLEN * 4)
843                                 thresh = COPY_BUFLEN * 4;
844                 }
845
846                 TIMEVAL_TO_TIMESPEC(&bwend, &ts);
847                 while (nanosleep(&ts, &rm) == -1) {
848                         if (errno != EINTR)
849                                 break;
850                         ts = rm;
851                 }
852         }
853
854         lamt = 0;
855         gettimeofday(&bwstart, NULL);
856 }
857
858 void
859 sink(int argc, char **argv)
860 {
861         static BUF buffer;
862         struct stat stb;
863         enum {
864                 YES, NO, DISPLAYED
865         } wrerr;
866         BUF *bp;
867         off_t i;
868         size_t j, count;
869         int amt, exists, first, ofd;
870         mode_t mode, omode, mask;
871         off_t size, statbytes;
872         int setimes, targisdir, wrerrno = 0;
873         char ch, *cp, *np, *targ, *why, *vect[1], buf[16384];
874         struct timeval tv[2];
875
876 #define atime   tv[0]
877 #define mtime   tv[1]
878 #define SCREWUP(str)    { why = str; goto screwup; }
879
880         setimes = targisdir = 0;
881         mask = umask(0);
882         if (!pflag)
883                 (void) umask(mask);
884         if (argc != 1) {
885                 run_err("ambiguous target");
886                 exit(1);
887         }
888         targ = *argv;
889         if (targetshouldbedirectory)
890                 verifydir(targ);
891
892         (void) atomicio(vwrite, remout, "", 1);
893         if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
894                 targisdir = 1;
895         for (first = 1;; first = 0) {
896                 cp = buf;
897                 if (atomicio(read, remin, cp, 1) != 1)
898                         return;
899                 if (*cp++ == '\n')
900                         SCREWUP("unexpected <newline>");
901                 do {
902                         if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
903                                 SCREWUP("lost connection");
904                         *cp++ = ch;
905                 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
906                 *cp = 0;
907                 if (verbose_mode)
908                         fprintf(stderr, "Sink: %s", buf);
909
910                 if (buf[0] == '\01' || buf[0] == '\02') {
911                         if (iamremote == 0)
912                                 (void) atomicio(vwrite, STDERR_FILENO,
913                                     buf + 1, strlen(buf + 1));
914                         if (buf[0] == '\02')
915                                 exit(1);
916                         ++errs;
917                         continue;
918                 }
919                 if (buf[0] == 'E') {
920                         (void) atomicio(vwrite, remout, "", 1);
921                         return;
922                 }
923                 if (ch == '\n')
924                         *--cp = 0;
925
926                 cp = buf;
927                 if (*cp == 'T') {
928                         setimes++;
929                         cp++;
930                         mtime.tv_sec = strtol(cp, &cp, 10);
931                         if (!cp || *cp++ != ' ')
932                                 SCREWUP("mtime.sec not delimited");
933                         mtime.tv_usec = strtol(cp, &cp, 10);
934                         if (!cp || *cp++ != ' ')
935                                 SCREWUP("mtime.usec not delimited");
936                         atime.tv_sec = strtol(cp, &cp, 10);
937                         if (!cp || *cp++ != ' ')
938                                 SCREWUP("atime.sec not delimited");
939                         atime.tv_usec = strtol(cp, &cp, 10);
940                         if (!cp || *cp++ != '\0')
941                                 SCREWUP("atime.usec not delimited");
942                         (void) atomicio(vwrite, remout, "", 1);
943                         continue;
944                 }
945                 if (*cp != 'C' && *cp != 'D') {
946                         /*
947                          * Check for the case "rcp remote:foo\* local:bar".
948                          * In this case, the line "No match." can be returned
949                          * by the shell before the rcp command on the remote is
950                          * executed so the ^Aerror_message convention isn't
951                          * followed.
952                          */
953                         if (first) {
954                                 run_err("%s", cp);
955                                 exit(1);
956                         }
957                         SCREWUP("expected control record");
958                 }
959                 mode = 0;
960                 for (++cp; cp < buf + 5; cp++) {
961                         if (*cp < '0' || *cp > '7')
962                                 SCREWUP("bad mode");
963                         mode = (mode << 3) | (*cp - '0');
964                 }
965                 if (*cp++ != ' ')
966                         SCREWUP("mode not delimited");
967
968                 for (size = 0; isdigit(*cp);)
969                         size = size * 10 + (*cp++ - '0');
970                 if (*cp++ != ' ')
971                         SCREWUP("size not delimited");
972                 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
973                         run_err("error: unexpected filename: %s", cp);
974                         exit(1);
975                 }
976                 if (targisdir) {
977                         static char *namebuf;
978                         static size_t cursize;
979                         size_t need;
980
981                         need = strlen(targ) + strlen(cp) + 250;
982                         if (need > cursize) {
983                                 if (namebuf)
984                                         xfree(namebuf);
985                                 namebuf = xmalloc(need);
986                                 cursize = need;
987                         }
988                         (void) snprintf(namebuf, need, "%s%s%s", targ,
989                             strcmp(targ, "/") ? "/" : "", cp);
990                         np = namebuf;
991                 } else
992                         np = targ;
993                 curfile = cp;
994                 exists = stat(np, &stb) == 0;
995                 if (buf[0] == 'D') {
996                         int mod_flag = pflag;
997                         if (!iamrecursive)
998                                 SCREWUP("received directory without -r");
999                         if (exists) {
1000                                 if (!S_ISDIR(stb.st_mode)) {
1001                                         errno = ENOTDIR;
1002                                         goto bad;
1003                                 }
1004                                 if (pflag)
1005                                         (void) chmod(np, mode);
1006                         } else {
1007                                 /* Handle copying from a read-only
1008                                    directory */
1009                                 mod_flag = 1;
1010                                 if (mkdir(np, mode | S_IRWXU) < 0)
1011                                         goto bad;
1012                         }
1013                         vect[0] = xstrdup(np);
1014                         sink(1, vect);
1015                         if (setimes) {
1016                                 setimes = 0;
1017                                 if (utimes(vect[0], tv) < 0)
1018                                         run_err("%s: set times: %s",
1019                                             vect[0], strerror(errno));
1020                         }
1021                         if (mod_flag)
1022                                 (void) chmod(vect[0], mode);
1023                         if (vect[0])
1024                                 xfree(vect[0]);
1025                         continue;
1026                 }
1027                 omode = mode;
1028                 mode |= S_IWRITE;
1029                 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1030 bad:                    run_err("%s: %s", np, strerror(errno));
1031                         continue;
1032                 }
1033                 (void) atomicio(vwrite, remout, "", 1);
1034                 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1035                         (void) close(ofd);
1036                         continue;
1037                 }
1038                 cp = bp->buf;
1039                 wrerr = NO;
1040
1041                 statbytes = 0;
1042                 if (showprogress)
1043                         start_progress_meter(curfile, size, &statbytes);
1044                 set_nonblock(remin);
1045                 for (count = i = 0; i < size; i += bp->cnt) {
1046                         amt = bp->cnt;
1047                         if (i + amt > size)
1048                                 amt = size - i;
1049                         count += amt;
1050                         do {
1051                                 j = scpio(read, remin, cp, amt, &statbytes);
1052                                 if (j == 0) {
1053                                         run_err("%s", j != EPIPE ?
1054                                             strerror(errno) :
1055                                             "dropped connection");
1056                                         exit(1);
1057                                 }
1058                                 amt -= j;
1059                                 cp += j;
1060                         } while (amt > 0);
1061
1062                         if (count == bp->cnt) {
1063                                 /* Keep reading so we stay sync'd up. */
1064                                 if (wrerr == NO) {
1065                                         if (atomicio(vwrite, ofd, bp->buf,
1066                                             count) != count) {
1067                                                 wrerr = YES;
1068                                                 wrerrno = errno;
1069                                         }
1070                                 }
1071                                 count = 0;
1072                                 cp = bp->buf;
1073                         }
1074                 }
1075                 unset_nonblock(remin);
1076                 if (showprogress)
1077                         stop_progress_meter();
1078                 if (count != 0 && wrerr == NO &&
1079                     atomicio(vwrite, ofd, bp->buf, count) != count) {
1080                         wrerr = YES;
1081                         wrerrno = errno;
1082                 }
1083                 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1084                     ftruncate(ofd, size) != 0) {
1085                         run_err("%s: truncate: %s", np, strerror(errno));
1086                         wrerr = DISPLAYED;
1087                 }
1088                 if (pflag) {
1089                         if (exists || omode != mode)
1090 #ifdef HAVE_FCHMOD
1091                                 if (fchmod(ofd, omode)) {
1092 #else /* HAVE_FCHMOD */
1093                                 if (chmod(np, omode)) {
1094 #endif /* HAVE_FCHMOD */
1095                                         run_err("%s: set mode: %s",
1096                                             np, strerror(errno));
1097                                         wrerr = DISPLAYED;
1098                                 }
1099                 } else {
1100                         if (!exists && omode != mode)
1101 #ifdef HAVE_FCHMOD
1102                                 if (fchmod(ofd, omode & ~mask)) {
1103 #else /* HAVE_FCHMOD */
1104                                 if (chmod(np, omode & ~mask)) {
1105 #endif /* HAVE_FCHMOD */
1106                                         run_err("%s: set mode: %s",
1107                                             np, strerror(errno));
1108                                         wrerr = DISPLAYED;
1109                                 }
1110                 }
1111                 if (close(ofd) == -1) {
1112                         wrerr = YES;
1113                         wrerrno = errno;
1114                 }
1115                 (void) response();
1116                 if (setimes && wrerr == NO) {
1117                         setimes = 0;
1118                         if (utimes(np, tv) < 0) {
1119                                 run_err("%s: set times: %s",
1120                                     np, strerror(errno));
1121                                 wrerr = DISPLAYED;
1122                         }
1123                 }
1124                 switch (wrerr) {
1125                 case YES:
1126                         run_err("%s: %s", np, strerror(wrerrno));
1127                         break;
1128                 case NO:
1129                         (void) atomicio(vwrite, remout, "", 1);
1130                         break;
1131                 case DISPLAYED:
1132                         break;
1133                 }
1134         }
1135 screwup:
1136         run_err("protocol error: %s", why);
1137         exit(1);
1138 }
1139
1140 int
1141 response(void)
1142 {
1143         char ch, *cp, resp, rbuf[2048];
1144
1145         if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1146                 lostconn(0);
1147
1148         cp = rbuf;
1149         switch (resp) {
1150         case 0:         /* ok */
1151                 return (0);
1152         default:
1153                 *cp++ = resp;
1154                 /* FALLTHROUGH */
1155         case 1:         /* error, followed by error msg */
1156         case 2:         /* fatal error, "" */
1157                 do {
1158                         if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1159                                 lostconn(0);
1160                         *cp++ = ch;
1161                 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1162
1163                 if (!iamremote)
1164                         (void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
1165                 ++errs;
1166                 if (resp == 1)
1167                         return (-1);
1168                 exit(1);
1169         }
1170         /* NOTREACHED */
1171 }
1172
1173 void
1174 usage(void)
1175 {
1176         (void) fprintf(stderr,
1177             "usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1178             "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1179             "           [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1180         exit(1);
1181 }
1182
1183 void
1184 run_err(const char *fmt,...)
1185 {
1186         static FILE *fp;
1187         va_list ap;
1188
1189         ++errs;
1190         if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1191                 (void) fprintf(fp, "%c", 0x01);
1192                 (void) fprintf(fp, "scp: ");
1193                 va_start(ap, fmt);
1194                 (void) vfprintf(fp, fmt, ap);
1195                 va_end(ap);
1196                 (void) fprintf(fp, "\n");
1197                 (void) fflush(fp);
1198         }
1199
1200         if (!iamremote) {
1201                 va_start(ap, fmt);
1202                 vfprintf(stderr, fmt, ap);
1203                 va_end(ap);
1204                 fprintf(stderr, "\n");
1205         }
1206 }
1207
1208 void
1209 verifydir(char *cp)
1210 {
1211         struct stat stb;
1212
1213         if (!stat(cp, &stb)) {
1214                 if (S_ISDIR(stb.st_mode))
1215                         return;
1216                 errno = ENOTDIR;
1217         }
1218         run_err("%s: %s", cp, strerror(errno));
1219         killchild(0);
1220 }
1221
1222 int
1223 okname(char *cp0)
1224 {
1225         int c;
1226         char *cp;
1227
1228         cp = cp0;
1229         do {
1230                 c = (int)*cp;
1231                 if (c & 0200)
1232                         goto bad;
1233                 if (!isalpha(c) && !isdigit(c)) {
1234                         switch (c) {
1235                         case '\'':
1236                         case '"':
1237                         case '`':
1238                         case ' ':
1239                         case '#':
1240                                 goto bad;
1241                         default:
1242                                 break;
1243                         }
1244                 }
1245         } while (*++cp);
1246         return (1);
1247
1248 bad:    fprintf(stderr, "%s: invalid user name\n", cp0);
1249         return (0);
1250 }
1251
1252 BUF *
1253 allocbuf(BUF *bp, int fd, int blksize)
1254 {
1255         size_t size;
1256 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1257         struct stat stb;
1258
1259         if (fstat(fd, &stb) < 0) {
1260                 run_err("fstat: %s", strerror(errno));
1261                 return (0);
1262         }
1263         size = roundup(stb.st_blksize, blksize);
1264         if (size == 0)
1265                 size = blksize;
1266 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1267         size = blksize;
1268 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1269         if (bp->cnt >= size)
1270                 return (bp);
1271         if (bp->buf == NULL)
1272                 bp->buf = xmalloc(size);
1273         else
1274                 bp->buf = xrealloc(bp->buf, 1, size);
1275         memset(bp->buf, 0, size);
1276         bp->cnt = size;
1277         return (bp);
1278 }
1279
1280 void
1281 lostconn(int signo)
1282 {
1283         if (!iamremote)
1284                 write(STDERR_FILENO, "lost connection\n", 16);
1285         if (signo)
1286                 _exit(1);
1287         else
1288                 exit(1);
1289 }
This page took 0.165994 seconds and 5 git commands to generate.