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