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