OSDN Git Service

Fix the segmentation fault of ssh, and configure scp to make it work properly
[android-x86/external-openssh.git] / scp.c
1 /* $OpenBSD: scp.c,v 1.187 2016/09/12 01:22:38 deraadt Exp $ */
2 /*
3  * scp - secure remote copy.  This is basically patched BSD rcp which
4  * uses ssh to do the data transfer (instead of using rcmd).
5  *
6  * NOTE: This version should NOT be suid root.  (This uses ssh to
7  * do the transfer and ssh has the necessary privileges.)
8  *
9  * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
10  *
11  * As far as I am concerned, the code I have written for this software
12  * can be used freely for any purpose.  Any derived versions of this
13  * software must be clearly marked as such, and if the derived work is
14  * incompatible with the protocol description in the RFC file, it must be
15  * called by a name other than "ssh" or "Secure Shell".
16  */
17 /*
18  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
19  * Copyright (c) 1999 Aaron Campbell.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41
42 /*
43  * Parts from:
44  *
45  * Copyright (c) 1983, 1990, 1992, 1993, 1995
46  *      The Regents of the University of California.  All rights reserved.
47  *
48  * Redistribution and use in source and binary forms, with or without
49  * modification, are permitted provided that the following conditions
50  * are met:
51  * 1. Redistributions of source code must retain the above copyright
52  *    notice, this list of conditions and the following disclaimer.
53  * 2. Redistributions in binary form must reproduce the above copyright
54  *    notice, this list of conditions and the following disclaimer in the
55  *    documentation and/or other materials provided with the distribution.
56  * 3. Neither the name of the University nor the names of its contributors
57  *    may be used to endorse or promote products derived from this software
58  *    without specific prior written permission.
59  *
60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70  * SUCH DAMAGE.
71  *
72  */
73
74 #include "includes.h"
75
76 #include <sys/types.h>
77 #ifdef HAVE_SYS_STAT_H
78 # include <sys/stat.h>
79 #endif
80 #ifdef HAVE_POLL_H
81 #include <poll.h>
82 #else
83 # ifdef HAVE_SYS_POLL_H
84 #  include <sys/poll.h>
85 # endif
86 #endif
87 #ifdef HAVE_SYS_TIME_H
88 # include <sys/time.h>
89 #endif
90 #include <sys/wait.h>
91 #include <sys/uio.h>
92
93 #include <ctype.h>
94 #include <dirent.h>
95 #include <errno.h>
96 #include <fcntl.h>
97 #include <limits.h>
98 #include <locale.h>
99 #include <pwd.h>
100 #include <signal.h>
101 #include <stdarg.h>
102 #include <stdio.h>
103 #include <stdlib.h>
104 #include <string.h>
105 #include <time.h>
106 #include <unistd.h>
107 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
108 #include <vis.h>
109 #endif
110
111 #include "xmalloc.h"
112 #include "atomicio.h"
113 #include "pathnames.h"
114 #include "log.h"
115 #include "misc.h"
116 #include "progressmeter.h"
117 #include "utf8.h"
118
119 extern char *__progname;
120
121 #define COPY_BUFLEN     16384
122
123 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
124 int do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout);
125
126 /* Struct for addargs */
127 arglist args;
128 arglist remote_remote_args;
129
130 /* Bandwidth limit */
131 long long limit_kbps = 0;
132 struct bwlimit bwlimit;
133
134 /* Name of current file being transferred. */
135 char *curfile;
136
137 /* This is set to non-zero to enable verbose mode. */
138 int verbose_mode = 0;
139
140 /* This is set to zero if the progressmeter is not desired. */
141 int showprogress = 1;
142
143 /*
144  * This is set to non-zero if remote-remote copy should be piped
145  * through this process.
146  */
147 int throughlocal = 0;
148
149 /* This is the program to execute for the secured connection. ("ssh" or -S) */
150 char *ssh_program = _PATH_SSH_PROGRAM;
151
152 /* This is used to store the pid of ssh_program */
153 pid_t do_cmd_pid = -1;
154
155 static void
156 killchild(int signo)
157 {
158         if (do_cmd_pid > 1) {
159                 kill(do_cmd_pid, signo ? signo : SIGTERM);
160                 waitpid(do_cmd_pid, NULL, 0);
161         }
162
163         if (signo)
164                 _exit(1);
165         exit(1);
166 }
167
168 static void
169 suspchild(int signo)
170 {
171         int status;
172
173         if (do_cmd_pid > 1) {
174                 kill(do_cmd_pid, signo);
175                 while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
176                     errno == EINTR)
177                         ;
178                 kill(getpid(), SIGSTOP);
179         }
180 }
181
182 static int
183 do_local_cmd(arglist *a)
184 {
185         u_int i;
186         int status;
187         pid_t pid;
188
189         if (a->num == 0)
190                 fatal("do_local_cmd: no arguments");
191
192         if (verbose_mode) {
193                 fprintf(stderr, "Executing:");
194                 for (i = 0; i < a->num; i++)
195                         fmprintf(stderr, " %s", a->list[i]);
196                 fprintf(stderr, "\n");
197         }
198         if ((pid = fork()) == -1)
199                 fatal("do_local_cmd: fork: %s", strerror(errno));
200
201         if (pid == 0) {
202                 execvp(a->list[0], a->list);
203                 perror(a->list[0]);
204                 exit(1);
205         }
206
207         do_cmd_pid = pid;
208         signal(SIGTERM, killchild);
209         signal(SIGINT, killchild);
210         signal(SIGHUP, killchild);
211
212         while (waitpid(pid, &status, 0) == -1)
213                 if (errno != EINTR)
214                         fatal("do_local_cmd: waitpid: %s", strerror(errno));
215
216         do_cmd_pid = -1;
217
218         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
219                 return (-1);
220
221         return (0);
222 }
223
224 /*
225  * This function executes the given command as the specified user on the
226  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
227  * assigns the input and output file descriptors on success.
228  */
229
230 int
231 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
232 {
233         int pin[2], pout[2], reserved[2];
234
235         if (verbose_mode)
236                 fmprintf(stderr,
237                     "Executing: program %s host %s, user %s, command %s\n",
238                     ssh_program, host,
239                     remuser ? remuser : "(unspecified)", cmd);
240
241         /*
242          * Reserve two descriptors so that the real pipes won't get
243          * descriptors 0 and 1 because that will screw up dup2 below.
244          */
245         if (pipe(reserved) < 0)
246                 fatal("pipe: %s", strerror(errno));
247
248         /* Create a socket pair for communicating with ssh. */
249         if (pipe(pin) < 0)
250                 fatal("pipe: %s", strerror(errno));
251         if (pipe(pout) < 0)
252                 fatal("pipe: %s", strerror(errno));
253
254         /* Free the reserved descriptors. */
255         close(reserved[0]);
256         close(reserved[1]);
257
258         signal(SIGTSTP, suspchild);
259         signal(SIGTTIN, suspchild);
260         signal(SIGTTOU, suspchild);
261
262         /* Fork a child to execute the command on the remote host using ssh. */
263         do_cmd_pid = fork();
264         if (do_cmd_pid == 0) {
265                 /* Child. */
266                 close(pin[1]);
267                 close(pout[0]);
268                 dup2(pin[0], 0);
269                 dup2(pout[1], 1);
270                 close(pin[0]);
271                 close(pout[1]);
272
273                 replacearg(&args, 0, "%s", ssh_program);
274                 if (remuser != NULL) {
275                         addargs(&args, "-l");
276                         addargs(&args, "%s", remuser);
277                 }
278                 addargs(&args, "--");
279                 addargs(&args, "%s", host);
280                 addargs(&args, "%s", cmd);
281
282                 execvp(ssh_program, args.list);
283                 perror(ssh_program);
284                 exit(1);
285         } else if (do_cmd_pid == -1) {
286                 fatal("fork: %s", strerror(errno));
287         }
288         /* Parent.  Close the other side, and return the local side. */
289         close(pin[0]);
290         *fdout = pin[1];
291         close(pout[1]);
292         *fdin = pout[0];
293         signal(SIGTERM, killchild);
294         signal(SIGINT, killchild);
295         signal(SIGHUP, killchild);
296         return 0;
297 }
298
299 /*
300  * This functions executes a command simlar to do_cmd(), but expects the
301  * input and output descriptors to be setup by a previous call to do_cmd().
302  * This way the input and output of two commands can be connected.
303  */
304 int
305 do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout)
306 {
307         pid_t pid;
308         int status;
309
310         if (verbose_mode)
311                 fmprintf(stderr,
312                     "Executing: 2nd program %s host %s, user %s, command %s\n",
313                     ssh_program, host,
314                     remuser ? remuser : "(unspecified)", cmd);
315
316         /* Fork a child to execute the command on the remote host using ssh. */
317         pid = fork();
318         if (pid == 0) {
319                 dup2(fdin, 0);
320                 dup2(fdout, 1);
321
322                 replacearg(&args, 0, "%s", ssh_program);
323                 if (remuser != NULL) {
324                         addargs(&args, "-l");
325                         addargs(&args, "%s", remuser);
326                 }
327                 addargs(&args, "--");
328                 addargs(&args, "%s", host);
329                 addargs(&args, "%s", cmd);
330
331                 execvp(ssh_program, args.list);
332                 perror(ssh_program);
333                 exit(1);
334         } else if (pid == -1) {
335                 fatal("fork: %s", strerror(errno));
336         }
337         while (waitpid(pid, &status, 0) == -1)
338                 if (errno != EINTR)
339                         fatal("do_cmd2: waitpid: %s", strerror(errno));
340         return 0;
341 }
342
343 typedef struct {
344         size_t cnt;
345         char *buf;
346 } BUF;
347
348 BUF *allocbuf(BUF *, int, int);
349 void lostconn(int);
350 int okname(char *);
351 void run_err(const char *,...);
352 void verifydir(char *);
353
354 struct passwd *pwd;
355 uid_t userid;
356 int errs, remin, remout;
357 int pflag, iamremote, iamrecursive, targetshouldbedirectory;
358
359 #define CMDNEEDS        64
360 char cmd[CMDNEEDS];             /* must hold "rcp -r -p -d\0" */
361
362 int response(void);
363 void rsource(char *, struct stat *);
364 void sink(int, char *[]);
365 void source(int, char *[]);
366 void tolocal(int, char *[]);
367 void toremote(char *, int, char *[]);
368 void usage(void);
369
370 int
371 main(int argc, char **argv)
372 {
373         int ch, fflag, tflag, status, n;
374         char *targ, **newargv;
375         const char *errstr;
376         extern char *optarg;
377         extern int optind;
378
379         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
380         sanitise_stdfd();
381
382         msetlocale();
383
384         /* Copy argv, because we modify it */
385         newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
386         for (n = 0; n < argc; n++)
387                 newargv[n] = xstrdup(argv[n]);
388         argv = newargv;
389
390         __progname = ssh_get_progname(argv[0]);
391
392         memset(&args, '\0', sizeof(args));
393         memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
394         args.list = remote_remote_args.list = NULL;
395         addargs(&args, "%s", ssh_program);
396         addargs(&args, "-x");
397         addargs(&args, "-oForwardAgent=no");
398         addargs(&args, "-oPermitLocalCommand=no");
399         addargs(&args, "-oClearAllForwardings=yes");
400
401         fflag = tflag = 0;
402         while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
403                 switch (ch) {
404                 /* User-visible flags. */
405                 case '1':
406                 case '2':
407                 case '4':
408                 case '6':
409                 case 'C':
410                         addargs(&args, "-%c", ch);
411                         addargs(&remote_remote_args, "-%c", ch);
412                         break;
413                 case '3':
414                         throughlocal = 1;
415                         break;
416                 case 'o':
417                 case 'c':
418                 case 'i':
419                 case 'F':
420                         addargs(&remote_remote_args, "-%c", ch);
421                         addargs(&remote_remote_args, "%s", optarg);
422                         addargs(&args, "-%c", ch);
423                         addargs(&args, "%s", optarg);
424                         break;
425                 case 'P':
426                         addargs(&remote_remote_args, "-p");
427                         addargs(&remote_remote_args, "%s", optarg);
428                         addargs(&args, "-p");
429                         addargs(&args, "%s", optarg);
430                         break;
431                 case 'B':
432                         addargs(&remote_remote_args, "-oBatchmode=yes");
433                         addargs(&args, "-oBatchmode=yes");
434                         break;
435                 case 'l':
436                         limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
437                             &errstr);
438                         if (errstr != NULL)
439                                 usage();
440                         limit_kbps *= 1024; /* kbps */
441                         bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
442                         break;
443                 case 'p':
444                         pflag = 1;
445                         break;
446                 case 'r':
447                         iamrecursive = 1;
448                         break;
449                 case 'S':
450                         ssh_program = xstrdup(optarg);
451                         break;
452                 case 'v':
453                         addargs(&args, "-v");
454                         addargs(&remote_remote_args, "-v");
455                         verbose_mode = 1;
456                         break;
457                 case 'q':
458                         addargs(&args, "-q");
459                         addargs(&remote_remote_args, "-q");
460                         showprogress = 0;
461                         break;
462
463                 /* Server options. */
464                 case 'd':
465                         targetshouldbedirectory = 1;
466                         break;
467                 case 'f':       /* "from" */
468                         iamremote = 1;
469                         fflag = 1;
470                         break;
471                 case 't':       /* "to" */
472                         iamremote = 1;
473                         tflag = 1;
474 #ifdef HAVE_CYGWIN
475                         setmode(0, O_BINARY);
476 #endif
477                         break;
478                 default:
479                         usage();
480                 }
481         argc -= optind;
482         argv += optind;
483
484         if ((pwd = getpwuid(userid = getuid())) == NULL)
485                 fatal("unknown user %u", (u_int) userid);
486
487         if (!isatty(STDOUT_FILENO))
488                 showprogress = 0;
489
490         if (pflag) {
491                 /* Cannot pledge: -p allows setuid/setgid files... */
492         } else {
493                 if (pledge("stdio rpath wpath cpath fattr tty proc exec",
494                     NULL) == -1) {
495                         perror("pledge");
496                         exit(1);
497                 }
498         }
499
500         remin = STDIN_FILENO;
501         remout = STDOUT_FILENO;
502
503         if (fflag) {
504                 /* Follow "protocol", send data. */
505                 (void) response();
506                 source(argc, argv);
507                 exit(errs != 0);
508         }
509         if (tflag) {
510                 /* Receive data. */
511                 sink(argc, argv);
512                 exit(errs != 0);
513         }
514         if (argc < 2)
515                 usage();
516         if (argc > 2)
517                 targetshouldbedirectory = 1;
518
519         remin = remout = -1;
520         do_cmd_pid = -1;
521         /* Command to be executed on remote system using "ssh". */
522         (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
523             verbose_mode ? " -v" : "",
524             iamrecursive ? " -r" : "", pflag ? " -p" : "",
525             targetshouldbedirectory ? " -d" : "");
526
527         (void) signal(SIGPIPE, lostconn);
528
529         if ((targ = colon(argv[argc - 1])))     /* Dest is remote host. */
530                 toremote(targ, argc, argv);
531         else {
532                 if (targetshouldbedirectory)
533                         verifydir(argv[argc - 1]);
534                 tolocal(argc, argv);    /* Dest is local host. */
535         }
536         /*
537          * Finally check the exit status of the ssh process, if one was forked
538          * and no error has occurred yet
539          */
540         if (do_cmd_pid != -1 && errs == 0) {
541                 if (remin != -1)
542                     (void) close(remin);
543                 if (remout != -1)
544                     (void) close(remout);
545                 if (waitpid(do_cmd_pid, &status, 0) == -1)
546                         errs = 1;
547                 else {
548                         if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
549                                 errs = 1;
550                 }
551         }
552         exit(errs != 0);
553 }
554
555 /* Callback from atomicio6 to update progress meter and limit bandwidth */
556 static int
557 scpio(void *_cnt, size_t s)
558 {
559         off_t *cnt = (off_t *)_cnt;
560
561         *cnt += s;
562         if (limit_kbps > 0)
563                 bandwidth_limit(&bwlimit, s);
564         return 0;
565 }
566
567 static int
568 do_times(int fd, int verb, const struct stat *sb)
569 {
570         /* strlen(2^64) == 20; strlen(10^6) == 7 */
571         char buf[(20 + 7 + 2) * 2 + 2];
572
573         (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
574             (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
575             (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
576         if (verb) {
577                 fprintf(stderr, "File mtime %lld atime %lld\n",
578                     (long long)sb->st_mtime, (long long)sb->st_atime);
579                 fprintf(stderr, "Sending file timestamps: %s", buf);
580         }
581         (void) atomicio(vwrite, fd, buf, strlen(buf));
582         return (response());
583 }
584
585 void
586 toremote(char *targ, int argc, char **argv)
587 {
588         char *bp, *host, *src, *suser, *thost, *tuser, *arg;
589         arglist alist;
590         int i;
591         u_int j;
592
593         memset(&alist, '\0', sizeof(alist));
594         alist.list = NULL;
595
596         *targ++ = 0;
597         if (*targ == 0)
598                 targ = ".";
599
600         arg = xstrdup(argv[argc - 1]);
601         if ((thost = strrchr(arg, '@'))) {
602                 /* user@host */
603                 *thost++ = 0;
604                 tuser = arg;
605                 if (*tuser == '\0')
606                         tuser = NULL;
607         } else {
608                 thost = arg;
609                 tuser = NULL;
610         }
611
612         if (tuser != NULL && !okname(tuser)) {
613                 free(arg);
614                 return;
615         }
616
617         for (i = 0; i < argc - 1; i++) {
618                 src = colon(argv[i]);
619                 if (src && throughlocal) {      /* extended remote to remote */
620                         *src++ = 0;
621                         if (*src == 0)
622                                 src = ".";
623                         host = strrchr(argv[i], '@');
624                         if (host) {
625                                 *host++ = 0;
626                                 host = cleanhostname(host);
627                                 suser = argv[i];
628                                 if (*suser == '\0')
629                                         suser = pwd->pw_name;
630                                 else if (!okname(suser))
631                                         continue;
632                         } else {
633                                 host = cleanhostname(argv[i]);
634                                 suser = NULL;
635                         }
636                         xasprintf(&bp, "%s -f %s%s", cmd,
637                             *src == '-' ? "-- " : "", src);
638                         if (do_cmd(host, suser, bp, &remin, &remout) < 0)
639                                 exit(1);
640                         free(bp);
641                         host = cleanhostname(thost);
642                         xasprintf(&bp, "%s -t %s%s", cmd,
643                             *targ == '-' ? "-- " : "", targ);
644                         if (do_cmd2(host, tuser, bp, remin, remout) < 0)
645                                 exit(1);
646                         free(bp);
647                         (void) close(remin);
648                         (void) close(remout);
649                         remin = remout = -1;
650                 } else if (src) {       /* standard remote to remote */
651                         freeargs(&alist);
652                         addargs(&alist, "%s", ssh_program);
653                         addargs(&alist, "-x");
654                         addargs(&alist, "-oClearAllForwardings=yes");
655                         addargs(&alist, "-n");
656                         for (j = 0; j < remote_remote_args.num; j++) {
657                                 addargs(&alist, "%s",
658                                     remote_remote_args.list[j]);
659                         }
660                         *src++ = 0;
661                         if (*src == 0)
662                                 src = ".";
663                         host = strrchr(argv[i], '@');
664
665                         if (host) {
666                                 *host++ = 0;
667                                 host = cleanhostname(host);
668                                 suser = argv[i];
669                                 if (*suser == '\0')
670                                         suser = pwd->pw_name;
671                                 else if (!okname(suser))
672                                         continue;
673                                 addargs(&alist, "-l");
674                                 addargs(&alist, "%s", suser);
675                         } else {
676                                 host = cleanhostname(argv[i]);
677                         }
678                         addargs(&alist, "--");
679                         addargs(&alist, "%s", host);
680                         addargs(&alist, "%s", cmd);
681                         addargs(&alist, "%s", src);
682                         addargs(&alist, "%s%s%s:%s",
683                             tuser ? tuser : "", tuser ? "@" : "",
684                             thost, targ);
685                         if (do_local_cmd(&alist) != 0)
686                                 errs = 1;
687                 } else {        /* local to remote */
688                         if (remin == -1) {
689                                 xasprintf(&bp, "%s -t %s%s", cmd,
690                                     *targ == '-' ? "-- " : "", targ);
691                                 host = cleanhostname(thost);
692                                 if (do_cmd(host, tuser, bp, &remin,
693                                     &remout) < 0)
694                                         exit(1);
695                                 if (response() < 0)
696                                         exit(1);
697                                 free(bp);
698                         }
699                         source(1, argv + i);
700                 }
701         }
702         free(arg);
703 }
704
705 void
706 tolocal(int argc, char **argv)
707 {
708         char *bp, *host, *src, *suser;
709         arglist alist;
710         int i;
711
712         memset(&alist, '\0', sizeof(alist));
713         alist.list = NULL;
714
715         for (i = 0; i < argc - 1; i++) {
716                 if (!(src = colon(argv[i]))) {  /* Local to local. */
717                         freeargs(&alist);
718                         addargs(&alist, "%s", _PATH_CP);
719                         if (iamrecursive)
720                                 addargs(&alist, "-r");
721                         if (pflag)
722                                 addargs(&alist, "-p");
723                         addargs(&alist, "--");
724                         addargs(&alist, "%s", argv[i]);
725                         addargs(&alist, "%s", argv[argc-1]);
726                         if (do_local_cmd(&alist))
727                                 ++errs;
728                         continue;
729                 }
730                 *src++ = 0;
731                 if (*src == 0)
732                         src = ".";
733                 if ((host = strrchr(argv[i], '@')) == NULL) {
734                         host = argv[i];
735                         suser = NULL;
736                 } else {
737                         *host++ = 0;
738                         suser = argv[i];
739                         if (*suser == '\0')
740                                 suser = pwd->pw_name;
741                 }
742                 host = cleanhostname(host);
743                 xasprintf(&bp, "%s -f %s%s",
744                     cmd, *src == '-' ? "-- " : "", src);
745                 if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
746                         free(bp);
747                         ++errs;
748                         continue;
749                 }
750                 free(bp);
751                 sink(1, argv + argc - 1);
752                 (void) close(remin);
753                 remin = remout = -1;
754         }
755 }
756
757 void
758 source(int argc, char **argv)
759 {
760         struct stat stb;
761         static BUF buffer;
762         BUF *bp;
763         off_t i, statbytes;
764         size_t amt, nr;
765         int fd = -1, haderr, indx;
766         char *last, *name, buf[2048], encname[PATH_MAX];
767         int len;
768
769         for (indx = 0; indx < argc; ++indx) {
770                 name = argv[indx];
771                 statbytes = 0;
772                 len = strlen(name);
773                 while (len > 1 && name[len-1] == '/')
774                         name[--len] = '\0';
775                 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
776                         goto syserr;
777                 if (strchr(name, '\n') != NULL) {
778                         strnvis(encname, name, sizeof(encname), VIS_NL);
779                         name = encname;
780                 }
781                 if (fstat(fd, &stb) < 0) {
782 syserr:                 run_err("%s: %s", name, strerror(errno));
783                         goto next;
784                 }
785                 if (stb.st_size < 0) {
786                         run_err("%s: %s", name, "Negative file size");
787                         goto next;
788                 }
789                 unset_nonblock(fd);
790                 switch (stb.st_mode & S_IFMT) {
791                 case S_IFREG:
792                         break;
793                 case S_IFDIR:
794                         if (iamrecursive) {
795                                 rsource(name, &stb);
796                                 goto next;
797                         }
798                         /* FALLTHROUGH */
799                 default:
800                         run_err("%s: not a regular file", name);
801                         goto next;
802                 }
803                 if ((last = strrchr(name, '/')) == NULL)
804                         last = name;
805                 else
806                         ++last;
807                 curfile = last;
808                 if (pflag) {
809                         if (do_times(remout, verbose_mode, &stb) < 0)
810                                 goto next;
811                 }
812 #define FILEMODEMASK    (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
813                 snprintf(buf, sizeof buf, "C%04o %lld %s\n",
814                     (u_int) (stb.st_mode & FILEMODEMASK),
815                     (long long)stb.st_size, last);
816                 if (verbose_mode)
817                         fmprintf(stderr, "Sending file modes: %s", buf);
818                 (void) atomicio(vwrite, remout, buf, strlen(buf));
819                 if (response() < 0)
820                         goto next;
821                 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
822 next:                   if (fd != -1) {
823                                 (void) close(fd);
824                                 fd = -1;
825                         }
826                         continue;
827                 }
828                 if (showprogress)
829                         start_progress_meter(curfile, stb.st_size, &statbytes);
830                 set_nonblock(remout);
831                 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
832                         amt = bp->cnt;
833                         if (i + (off_t)amt > stb.st_size)
834                                 amt = stb.st_size - i;
835                         if (!haderr) {
836                                 if ((nr = atomicio(read, fd,
837                                     bp->buf, amt)) != amt) {
838                                         haderr = errno;
839                                         memset(bp->buf + nr, 0, amt - nr);
840                                 }
841                         }
842                         /* Keep writing after error to retain sync */
843                         if (haderr) {
844                                 (void)atomicio(vwrite, remout, bp->buf, amt);
845                                 memset(bp->buf, 0, amt);
846                                 continue;
847                         }
848                         if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
849                             &statbytes) != amt)
850                                 haderr = errno;
851                 }
852                 unset_nonblock(remout);
853
854                 if (fd != -1) {
855                         if (close(fd) < 0 && !haderr)
856                                 haderr = errno;
857                         fd = -1;
858                 }
859                 if (!haderr)
860                         (void) atomicio(vwrite, remout, "", 1);
861                 else
862                         run_err("%s: %s", name, strerror(haderr));
863                 (void) response();
864                 if (showprogress)
865                         stop_progress_meter();
866         }
867 }
868
869 void
870 rsource(char *name, struct stat *statp)
871 {
872         DIR *dirp;
873         struct dirent *dp;
874         char *last, *vect[1], path[PATH_MAX];
875
876         if (!(dirp = opendir(name))) {
877                 run_err("%s: %s", name, strerror(errno));
878                 return;
879         }
880         last = strrchr(name, '/');
881         if (last == NULL)
882                 last = name;
883         else
884                 last++;
885         if (pflag) {
886                 if (do_times(remout, verbose_mode, statp) < 0) {
887                         closedir(dirp);
888                         return;
889                 }
890         }
891         (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
892             (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
893         if (verbose_mode)
894                 fmprintf(stderr, "Entering directory: %s", path);
895         (void) atomicio(vwrite, remout, path, strlen(path));
896         if (response() < 0) {
897                 closedir(dirp);
898                 return;
899         }
900         while ((dp = readdir(dirp)) != NULL) {
901                 if (dp->d_ino == 0)
902                         continue;
903                 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
904                         continue;
905                 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
906                         run_err("%s/%s: name too long", name, dp->d_name);
907                         continue;
908                 }
909                 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
910                 vect[0] = path;
911                 source(1, vect);
912         }
913         (void) closedir(dirp);
914         (void) atomicio(vwrite, remout, "E\n", 2);
915         (void) response();
916 }
917
918 void
919 sink(int argc, char **argv)
920 {
921         static BUF buffer;
922         struct stat stb;
923         enum {
924                 YES, NO, DISPLAYED
925         } wrerr;
926         BUF *bp;
927         off_t i;
928         size_t j, count;
929         int amt, exists, first, ofd;
930         mode_t mode, omode, mask;
931         off_t size, statbytes;
932         unsigned long long ull;
933         int setimes, targisdir, wrerrno = 0;
934         char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
935         struct timeval tv[2];
936
937 #define atime   tv[0]
938 #define mtime   tv[1]
939 #define SCREWUP(str)    { why = str; goto screwup; }
940
941         setimes = targisdir = 0;
942         mask = umask(0);
943         if (!pflag)
944                 (void) umask(mask);
945         if (argc != 1) {
946                 run_err("ambiguous target");
947                 exit(1);
948         }
949         targ = *argv;
950         if (targetshouldbedirectory)
951                 verifydir(targ);
952
953         (void) atomicio(vwrite, remout, "", 1);
954         if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
955                 targisdir = 1;
956         for (first = 1;; first = 0) {
957                 cp = buf;
958                 if (atomicio(read, remin, cp, 1) != 1)
959                         return;
960                 if (*cp++ == '\n')
961                         SCREWUP("unexpected <newline>");
962                 do {
963                         if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
964                                 SCREWUP("lost connection");
965                         *cp++ = ch;
966                 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
967                 *cp = 0;
968                 if (verbose_mode)
969                         fmprintf(stderr, "Sink: %s", buf);
970
971                 if (buf[0] == '\01' || buf[0] == '\02') {
972                         if (iamremote == 0) {
973                                 (void) snmprintf(visbuf, sizeof(visbuf),
974                                     NULL, "%s", buf + 1);
975                                 (void) atomicio(vwrite, STDERR_FILENO,
976                                     visbuf, strlen(visbuf));
977                         }
978                         if (buf[0] == '\02')
979                                 exit(1);
980                         ++errs;
981                         continue;
982                 }
983                 if (buf[0] == 'E') {
984                         (void) atomicio(vwrite, remout, "", 1);
985                         return;
986                 }
987                 if (ch == '\n')
988                         *--cp = 0;
989
990                 cp = buf;
991                 if (*cp == 'T') {
992                         setimes++;
993                         cp++;
994                         if (!isdigit((unsigned char)*cp))
995                                 SCREWUP("mtime.sec not present");
996                         ull = strtoull(cp, &cp, 10);
997                         if (!cp || *cp++ != ' ')
998                                 SCREWUP("mtime.sec not delimited");
999                         if ((time_t)ull < 0 ||
1000                             (unsigned long long)(time_t)ull != ull)
1001                                 setimes = 0;    /* out of range */
1002                         mtime.tv_sec = ull;
1003                         mtime.tv_usec = strtol(cp, &cp, 10);
1004                         if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1005                             mtime.tv_usec > 999999)
1006                                 SCREWUP("mtime.usec not delimited");
1007                         if (!isdigit((unsigned char)*cp))
1008                                 SCREWUP("atime.sec not present");
1009                         ull = strtoull(cp, &cp, 10);
1010                         if (!cp || *cp++ != ' ')
1011                                 SCREWUP("atime.sec not delimited");
1012                         if ((time_t)ull < 0 ||
1013                             (unsigned long long)(time_t)ull != ull)
1014                                 setimes = 0;    /* out of range */
1015                         atime.tv_sec = ull;
1016                         atime.tv_usec = strtol(cp, &cp, 10);
1017                         if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1018                             atime.tv_usec > 999999)
1019                                 SCREWUP("atime.usec not delimited");
1020                         (void) atomicio(vwrite, remout, "", 1);
1021                         continue;
1022                 }
1023                 if (*cp != 'C' && *cp != 'D') {
1024                         /*
1025                          * Check for the case "rcp remote:foo\* local:bar".
1026                          * In this case, the line "No match." can be returned
1027                          * by the shell before the rcp command on the remote is
1028                          * executed so the ^Aerror_message convention isn't
1029                          * followed.
1030                          */
1031                         if (first) {
1032                                 run_err("%s", cp);
1033                                 exit(1);
1034                         }
1035                         SCREWUP("expected control record");
1036                 }
1037                 mode = 0;
1038                 for (++cp; cp < buf + 5; cp++) {
1039                         if (*cp < '0' || *cp > '7')
1040                                 SCREWUP("bad mode");
1041                         mode = (mode << 3) | (*cp - '0');
1042                 }
1043                 if (*cp++ != ' ')
1044                         SCREWUP("mode not delimited");
1045
1046                 for (size = 0; isdigit((unsigned char)*cp);)
1047                         size = size * 10 + (*cp++ - '0');
1048                 if (*cp++ != ' ')
1049                         SCREWUP("size not delimited");
1050                 if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
1051                         run_err("error: unexpected filename: %s", cp);
1052                         exit(1);
1053                 }
1054                 if (targisdir) {
1055                         static char *namebuf;
1056                         static size_t cursize;
1057                         size_t need;
1058
1059                         need = strlen(targ) + strlen(cp) + 250;
1060                         if (need > cursize) {
1061                                 free(namebuf);
1062                                 namebuf = xmalloc(need);
1063                                 cursize = need;
1064                         }
1065                         (void) snprintf(namebuf, need, "%s%s%s", targ,
1066                             strcmp(targ, "/") ? "/" : "", cp);
1067                         np = namebuf;
1068                 } else
1069                         np = targ;
1070                 curfile = cp;
1071                 exists = stat(np, &stb) == 0;
1072                 if (buf[0] == 'D') {
1073                         int mod_flag = pflag;
1074                         if (!iamrecursive)
1075                                 SCREWUP("received directory without -r");
1076                         if (exists) {
1077                                 if (!S_ISDIR(stb.st_mode)) {
1078                                         errno = ENOTDIR;
1079                                         goto bad;
1080                                 }
1081                                 if (pflag)
1082                                         (void) chmod(np, mode);
1083                         } else {
1084                                 /* Handle copying from a read-only
1085                                    directory */
1086                                 mod_flag = 1;
1087                                 if (mkdir(np, mode | S_IRWXU) < 0)
1088                                         goto bad;
1089                         }
1090                         vect[0] = xstrdup(np);
1091                         sink(1, vect);
1092                         if (setimes) {
1093                                 setimes = 0;
1094                                 if (utimes(vect[0], tv) < 0)
1095                                         run_err("%s: set times: %s",
1096                                             vect[0], strerror(errno));
1097                         }
1098                         if (mod_flag)
1099                                 (void) chmod(vect[0], mode);
1100                         free(vect[0]);
1101                         continue;
1102                 }
1103                 omode = mode;
1104                 mode |= S_IWUSR;
1105                 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1106 bad:                    run_err("%s: %s", np, strerror(errno));
1107                         continue;
1108                 }
1109                 (void) atomicio(vwrite, remout, "", 1);
1110                 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1111                         (void) close(ofd);
1112                         continue;
1113                 }
1114                 cp = bp->buf;
1115                 wrerr = NO;
1116
1117                 statbytes = 0;
1118                 if (showprogress)
1119                         start_progress_meter(curfile, size, &statbytes);
1120                 set_nonblock(remin);
1121                 for (count = i = 0; i < size; i += bp->cnt) {
1122                         amt = bp->cnt;
1123                         if (i + amt > size)
1124                                 amt = size - i;
1125                         count += amt;
1126                         do {
1127                                 j = atomicio6(read, remin, cp, amt,
1128                                     scpio, &statbytes);
1129                                 if (j == 0) {
1130                                         run_err("%s", j != EPIPE ?
1131                                             strerror(errno) :
1132                                             "dropped connection");
1133                                         exit(1);
1134                                 }
1135                                 amt -= j;
1136                                 cp += j;
1137                         } while (amt > 0);
1138
1139                         if (count == bp->cnt) {
1140                                 /* Keep reading so we stay sync'd up. */
1141                                 if (wrerr == NO) {
1142                                         if (atomicio(vwrite, ofd, bp->buf,
1143                                             count) != count) {
1144                                                 wrerr = YES;
1145                                                 wrerrno = errno;
1146                                         }
1147                                 }
1148                                 count = 0;
1149                                 cp = bp->buf;
1150                         }
1151                 }
1152                 unset_nonblock(remin);
1153                 if (count != 0 && wrerr == NO &&
1154                     atomicio(vwrite, ofd, bp->buf, count) != count) {
1155                         wrerr = YES;
1156                         wrerrno = errno;
1157                 }
1158                 if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1159                     ftruncate(ofd, size) != 0) {
1160                         run_err("%s: truncate: %s", np, strerror(errno));
1161                         wrerr = DISPLAYED;
1162                 }
1163                 if (pflag) {
1164                         if (exists || omode != mode)
1165 #ifdef HAVE_FCHMOD
1166                                 if (fchmod(ofd, omode)) {
1167 #else /* HAVE_FCHMOD */
1168                                 if (chmod(np, omode)) {
1169 #endif /* HAVE_FCHMOD */
1170                                         run_err("%s: set mode: %s",
1171                                             np, strerror(errno));
1172                                         wrerr = DISPLAYED;
1173                                 }
1174                 } else {
1175                         if (!exists && omode != mode)
1176 #ifdef HAVE_FCHMOD
1177                                 if (fchmod(ofd, omode & ~mask)) {
1178 #else /* HAVE_FCHMOD */
1179                                 if (chmod(np, omode & ~mask)) {
1180 #endif /* HAVE_FCHMOD */
1181                                         run_err("%s: set mode: %s",
1182                                             np, strerror(errno));
1183                                         wrerr = DISPLAYED;
1184                                 }
1185                 }
1186                 if (close(ofd) == -1) {
1187                         wrerr = YES;
1188                         wrerrno = errno;
1189                 }
1190                 (void) response();
1191                 if (showprogress)
1192                         stop_progress_meter();
1193                 if (setimes && wrerr == NO) {
1194                         setimes = 0;
1195                         if (utimes(np, tv) < 0) {
1196                                 run_err("%s: set times: %s",
1197                                     np, strerror(errno));
1198                                 wrerr = DISPLAYED;
1199                         }
1200                 }
1201                 switch (wrerr) {
1202                 case YES:
1203                         run_err("%s: %s", np, strerror(wrerrno));
1204                         break;
1205                 case NO:
1206                         (void) atomicio(vwrite, remout, "", 1);
1207                         break;
1208                 case DISPLAYED:
1209                         break;
1210                 }
1211         }
1212 screwup:
1213         run_err("protocol error: %s", why);
1214         exit(1);
1215 }
1216
1217 int
1218 response(void)
1219 {
1220         char ch, *cp, resp, rbuf[2048], visbuf[2048];
1221
1222         if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1223                 lostconn(0);
1224
1225         cp = rbuf;
1226         switch (resp) {
1227         case 0:         /* ok */
1228                 return (0);
1229         default:
1230                 *cp++ = resp;
1231                 /* FALLTHROUGH */
1232         case 1:         /* error, followed by error msg */
1233         case 2:         /* fatal error, "" */
1234                 do {
1235                         if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1236                                 lostconn(0);
1237                         *cp++ = ch;
1238                 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1239
1240                 if (!iamremote) {
1241                         cp[-1] = '\0';
1242                         (void) snmprintf(visbuf, sizeof(visbuf),
1243                             NULL, "%s\n", rbuf);
1244                         (void) atomicio(vwrite, STDERR_FILENO,
1245                             visbuf, strlen(visbuf));
1246                 }
1247                 ++errs;
1248                 if (resp == 1)
1249                         return (-1);
1250                 exit(1);
1251         }
1252         /* NOTREACHED */
1253 }
1254
1255 void
1256 usage(void)
1257 {
1258         (void) fprintf(stderr,
1259             "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1260             "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
1261             "           [[user@]host1:]file1 ... [[user@]host2:]file2\n");
1262         exit(1);
1263 }
1264
1265 void
1266 run_err(const char *fmt,...)
1267 {
1268         static FILE *fp;
1269         va_list ap;
1270
1271         ++errs;
1272         if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1273                 (void) fprintf(fp, "%c", 0x01);
1274                 (void) fprintf(fp, "scp: ");
1275                 va_start(ap, fmt);
1276                 (void) vfprintf(fp, fmt, ap);
1277                 va_end(ap);
1278                 (void) fprintf(fp, "\n");
1279                 (void) fflush(fp);
1280         }
1281
1282         if (!iamremote) {
1283                 va_start(ap, fmt);
1284                 vfmprintf(stderr, fmt, ap);
1285                 va_end(ap);
1286                 fprintf(stderr, "\n");
1287         }
1288 }
1289
1290 void
1291 verifydir(char *cp)
1292 {
1293         struct stat stb;
1294
1295         if (!stat(cp, &stb)) {
1296                 if (S_ISDIR(stb.st_mode))
1297                         return;
1298                 errno = ENOTDIR;
1299         }
1300         run_err("%s: %s", cp, strerror(errno));
1301         killchild(0);
1302 }
1303
1304 int
1305 okname(char *cp0)
1306 {
1307         int c;
1308         char *cp;
1309
1310         cp = cp0;
1311         do {
1312                 c = (int)*cp;
1313                 if (c & 0200)
1314                         goto bad;
1315                 if (!isalpha(c) && !isdigit((unsigned char)c)) {
1316                         switch (c) {
1317                         case '\'':
1318                         case '"':
1319                         case '`':
1320                         case ' ':
1321                         case '#':
1322                                 goto bad;
1323                         default:
1324                                 break;
1325                         }
1326                 }
1327         } while (*++cp);
1328         return (1);
1329
1330 bad:    fmprintf(stderr, "%s: invalid user name\n", cp0);
1331         return (0);
1332 }
1333
1334 BUF *
1335 allocbuf(BUF *bp, int fd, int blksize)
1336 {
1337         size_t size;
1338 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1339         struct stat stb;
1340
1341         if (fstat(fd, &stb) < 0) {
1342                 run_err("fstat: %s", strerror(errno));
1343                 return (0);
1344         }
1345         size = ROUNDUP(stb.st_blksize, blksize);
1346         if (size == 0)
1347                 size = blksize;
1348 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1349         size = blksize;
1350 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1351         if (bp->cnt >= size)
1352                 return (bp);
1353         if (bp->buf == NULL)
1354                 bp->buf = xmalloc(size);
1355         else
1356                 bp->buf = xreallocarray(bp->buf, 1, size);
1357         memset(bp->buf, 0, size);
1358         bp->cnt = size;
1359         return (bp);
1360 }
1361
1362 void
1363 lostconn(int signo)
1364 {
1365         if (!iamremote)
1366                 (void)write(STDERR_FILENO, "lost connection\n", 16);
1367         if (signo)
1368                 _exit(1);
1369         else
1370                 exit(1);
1371 }