xref: /freebsd/crypto/openssh/scp.c (revision 8e28d84935f2f0ee081d44f9803f3052b960e50b)
1 /* $OpenBSD: scp.c,v 1.263 2025/03/28 06:04:07 dtucker Exp $ */
2 /*
3  * scp - secure remote copy.  This is basically patched BSD rcp which
4  * uses ssh to do the data transfer (instead of using rcmd).
5  *
6  * NOTE: This version should NOT be suid root.  (This uses ssh to
7  * do the transfer and ssh has the necessary privileges.)
8  *
9  * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
10  *
11  * As far as I am concerned, the code I have written for this software
12  * can be used freely for any purpose.  Any derived versions of this
13  * software must be clearly marked as such, and if the derived work is
14  * incompatible with the protocol description in the RFC file, it must be
15  * called by a name other than "ssh" or "Secure Shell".
16  */
17 /*
18  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
19  * Copyright (c) 1999 Aaron Campbell.  All rights reserved.
20  *
21  * Redistribution and use in source and binary forms, with or without
22  * modification, are permitted provided that the following conditions
23  * are met:
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  */
41 
42 /*
43  * Parts from:
44  *
45  * Copyright (c) 1983, 1990, 1992, 1993, 1995
46  *	The Regents of the University of California.  All rights reserved.
47  *
48  * Redistribution and use in source and binary forms, with or without
49  * modification, are permitted provided that the following conditions
50  * are met:
51  * 1. Redistributions of source code must retain the above copyright
52  *    notice, this list of conditions and the following disclaimer.
53  * 2. Redistributions in binary form must reproduce the above copyright
54  *    notice, this list of conditions and the following disclaimer in the
55  *    documentation and/or other materials provided with the distribution.
56  * 3. Neither the name of the University nor the names of its contributors
57  *    may be used to endorse or promote products derived from this software
58  *    without specific prior written permission.
59  *
60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70  * SUCH DAMAGE.
71  *
72  */
73 
74 #include "includes.h"
75 
76 #include <sys/types.h>
77 #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 #ifdef HAVE_FNMATCH_H
98 #include <fnmatch.h>
99 #endif
100 #ifdef USE_SYSTEM_GLOB
101 # include <glob.h>
102 #else
103 # include "openbsd-compat/glob.h"
104 #endif
105 #ifdef HAVE_LIBGEN_H
106 #include <libgen.h>
107 #endif
108 #include <limits.h>
109 #ifdef HAVE_UTIL_H
110 # include <util.h>
111 #endif
112 #include <locale.h>
113 #include <pwd.h>
114 #include <signal.h>
115 #include <stdarg.h>
116 #ifdef HAVE_STDINT_H
117 # include <stdint.h>
118 #endif
119 #include <stdio.h>
120 #include <stdlib.h>
121 #include <string.h>
122 #include <time.h>
123 #include <unistd.h>
124 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
125 #include <vis.h>
126 #endif
127 
128 #include "xmalloc.h"
129 #include "ssh.h"
130 #include "atomicio.h"
131 #include "pathnames.h"
132 #include "log.h"
133 #include "misc.h"
134 #include "progressmeter.h"
135 #include "utf8.h"
136 #include "sftp.h"
137 
138 #include "sftp-common.h"
139 #include "sftp-client.h"
140 
141 extern char *__progname;
142 
143 #define COPY_BUFLEN	16384
144 
145 int do_cmd(char *, char *, char *, int, int, char *, int *, int *, pid_t *);
146 int do_cmd2(char *, char *, int, char *, int, int);
147 
148 /* Struct for addargs */
149 arglist args;
150 arglist remote_remote_args;
151 
152 /* Bandwidth limit */
153 long long limit_kbps = 0;
154 struct bwlimit bwlimit;
155 
156 /* Name of current file being transferred. */
157 char *curfile;
158 
159 /* This is set to non-zero to enable verbose mode. */
160 int verbose_mode = 0;
161 LogLevel log_level = SYSLOG_LEVEL_INFO;
162 
163 /* This is set to zero if the progressmeter is not desired. */
164 int showprogress = 1;
165 
166 /*
167  * This is set to non-zero if remote-remote copy should be piped
168  * through this process.
169  */
170 int throughlocal = 1;
171 
172 /* Non-standard port to use for the ssh connection or -1. */
173 int sshport = -1;
174 
175 /* This is the program to execute for the secured connection. ("ssh" or -S) */
176 char *ssh_program = _PATH_SSH_PROGRAM;
177 
178 /* This is used to store the pid of ssh_program */
179 pid_t do_cmd_pid = -1;
180 pid_t do_cmd_pid2 = -1;
181 
182 /* SFTP copy parameters */
183 size_t sftp_copy_buflen;
184 size_t sftp_nrequests;
185 
186 /* Needed for sftp */
187 volatile sig_atomic_t interrupted = 0;
188 
189 int sftp_glob(struct sftp_conn *, const char *, int,
190     int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
191 
192 static void
killchild(int signo)193 killchild(int signo)
194 {
195 	if (do_cmd_pid > 1) {
196 		kill(do_cmd_pid, signo ? signo : SIGTERM);
197 		(void)waitpid(do_cmd_pid, NULL, 0);
198 	}
199 	if (do_cmd_pid2 > 1) {
200 		kill(do_cmd_pid2, signo ? signo : SIGTERM);
201 		(void)waitpid(do_cmd_pid2, NULL, 0);
202 	}
203 
204 	if (signo)
205 		_exit(1);
206 	exit(1);
207 }
208 
209 static void
suspone(int pid,int signo)210 suspone(int pid, int signo)
211 {
212 	int status;
213 
214 	if (pid > 1) {
215 		kill(pid, signo);
216 		while (waitpid(pid, &status, WUNTRACED) == -1 &&
217 		    errno == EINTR)
218 			;
219 	}
220 }
221 
222 static void
suspchild(int signo)223 suspchild(int signo)
224 {
225 	int save_errno = errno;
226 	suspone(do_cmd_pid, signo);
227 	suspone(do_cmd_pid2, signo);
228 	kill(getpid(), SIGSTOP);
229 	errno = save_errno;
230 }
231 
232 static int
do_local_cmd(arglist * a)233 do_local_cmd(arglist *a)
234 {
235 	u_int i;
236 	int status;
237 	pid_t pid;
238 
239 	if (a->num == 0)
240 		fatal("do_local_cmd: no arguments");
241 
242 	if (verbose_mode) {
243 		fprintf(stderr, "Executing:");
244 		for (i = 0; i < a->num; i++)
245 			fmprintf(stderr, " %s", a->list[i]);
246 		fprintf(stderr, "\n");
247 	}
248 	if ((pid = fork()) == -1)
249 		fatal("do_local_cmd: fork: %s", strerror(errno));
250 
251 	if (pid == 0) {
252 		execvp(a->list[0], a->list);
253 		perror(a->list[0]);
254 		exit(1);
255 	}
256 
257 	do_cmd_pid = pid;
258 	ssh_signal(SIGTERM, killchild);
259 	ssh_signal(SIGINT, killchild);
260 	ssh_signal(SIGHUP, killchild);
261 
262 	while (waitpid(pid, &status, 0) == -1)
263 		if (errno != EINTR)
264 			fatal("do_local_cmd: waitpid: %s", strerror(errno));
265 
266 	do_cmd_pid = -1;
267 
268 	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
269 		return (-1);
270 
271 	return (0);
272 }
273 
274 /*
275  * This function executes the given command as the specified user on the
276  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
277  * assigns the input and output file descriptors on success.
278  */
279 
280 int
do_cmd(char * program,char * host,char * remuser,int port,int subsystem,char * cmd,int * fdin,int * fdout,pid_t * pid)281 do_cmd(char *program, char *host, char *remuser, int port, int subsystem,
282     char *cmd, int *fdin, int *fdout, pid_t *pid)
283 {
284 #ifdef USE_PIPES
285 	int pin[2], pout[2];
286 #else
287 	int sv[2];
288 #endif
289 
290 	if (verbose_mode)
291 		fmprintf(stderr,
292 		    "Executing: program %s host %s, user %s, command %s\n",
293 		    program, host,
294 		    remuser ? remuser : "(unspecified)", cmd);
295 
296 	if (port == -1)
297 		port = sshport;
298 
299 #ifdef USE_PIPES
300 	if (pipe(pin) == -1 || pipe(pout) == -1)
301 		fatal("pipe: %s", strerror(errno));
302 #else
303 	/* Create a socket pair for communicating with ssh. */
304 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1)
305 		fatal("socketpair: %s", strerror(errno));
306 #endif
307 
308 	ssh_signal(SIGTSTP, suspchild);
309 	ssh_signal(SIGTTIN, suspchild);
310 	ssh_signal(SIGTTOU, suspchild);
311 
312 	/* Fork a child to execute the command on the remote host using ssh. */
313 	*pid = fork();
314 	switch (*pid) {
315 	case -1:
316 		fatal("fork: %s", strerror(errno));
317 	case 0:
318 		/* Child. */
319 #ifdef USE_PIPES
320 		if (dup2(pin[0], STDIN_FILENO) == -1 ||
321 		    dup2(pout[1], STDOUT_FILENO) == -1) {
322 			error("dup2: %s", strerror(errno));
323 			_exit(1);
324 		}
325 		close(pin[0]);
326 		close(pin[1]);
327 		close(pout[0]);
328 		close(pout[1]);
329 #else
330 		if (dup2(sv[0], STDIN_FILENO) == -1 ||
331 		    dup2(sv[0], STDOUT_FILENO) == -1) {
332 			error("dup2: %s", strerror(errno));
333 			_exit(1);
334 		}
335 		close(sv[0]);
336 		close(sv[1]);
337 #endif
338 		replacearg(&args, 0, "%s", program);
339 		if (port != -1) {
340 			addargs(&args, "-p");
341 			addargs(&args, "%d", port);
342 		}
343 		if (remuser != NULL) {
344 			addargs(&args, "-l");
345 			addargs(&args, "%s", remuser);
346 		}
347 		if (subsystem)
348 			addargs(&args, "-s");
349 		addargs(&args, "--");
350 		addargs(&args, "%s", host);
351 		addargs(&args, "%s", cmd);
352 
353 		execvp(program, args.list);
354 		perror(program);
355 		_exit(1);
356 	default:
357 		/* Parent.  Close the other side, and return the local side. */
358 #ifdef USE_PIPES
359 		close(pin[0]);
360 		close(pout[1]);
361 		*fdout = pin[1];
362 		*fdin = pout[0];
363 #else
364 		close(sv[0]);
365 		*fdin = sv[1];
366 		*fdout = sv[1];
367 #endif
368 		ssh_signal(SIGTERM, killchild);
369 		ssh_signal(SIGINT, killchild);
370 		ssh_signal(SIGHUP, killchild);
371 		return 0;
372 	}
373 }
374 
375 /*
376  * This function executes a command similar to do_cmd(), but expects the
377  * input and output descriptors to be setup by a previous call to do_cmd().
378  * This way the input and output of two commands can be connected.
379  */
380 int
do_cmd2(char * host,char * remuser,int port,char * cmd,int fdin,int fdout)381 do_cmd2(char *host, char *remuser, int port, char *cmd,
382     int fdin, int fdout)
383 {
384 	int status;
385 	pid_t pid;
386 
387 	if (verbose_mode)
388 		fmprintf(stderr,
389 		    "Executing: 2nd program %s host %s, user %s, command %s\n",
390 		    ssh_program, host,
391 		    remuser ? remuser : "(unspecified)", cmd);
392 
393 	if (port == -1)
394 		port = sshport;
395 
396 	/* Fork a child to execute the command on the remote host using ssh. */
397 	pid = fork();
398 	if (pid == 0) {
399 		if (dup2(fdin, 0) == -1)
400 			perror("dup2");
401 		if (dup2(fdout, 1) == -1)
402 			perror("dup2");
403 
404 		replacearg(&args, 0, "%s", ssh_program);
405 		if (port != -1) {
406 			addargs(&args, "-p");
407 			addargs(&args, "%d", port);
408 		}
409 		if (remuser != NULL) {
410 			addargs(&args, "-l");
411 			addargs(&args, "%s", remuser);
412 		}
413 		addargs(&args, "-oBatchMode=yes");
414 		addargs(&args, "--");
415 		addargs(&args, "%s", host);
416 		addargs(&args, "%s", cmd);
417 
418 		execvp(ssh_program, args.list);
419 		perror(ssh_program);
420 		exit(1);
421 	} else if (pid == -1) {
422 		fatal("fork: %s", strerror(errno));
423 	}
424 	while (waitpid(pid, &status, 0) == -1)
425 		if (errno != EINTR)
426 			fatal("do_cmd2: waitpid: %s", strerror(errno));
427 	return 0;
428 }
429 
430 typedef struct {
431 	size_t cnt;
432 	char *buf;
433 } BUF;
434 
435 BUF *allocbuf(BUF *, int, int);
436 void lostconn(int);
437 int okname(char *);
438 void run_err(const char *,...)
439     __attribute__((__format__ (printf, 1, 2)))
440     __attribute__((__nonnull__ (1)));
441 int note_err(const char *,...)
442     __attribute__((__format__ (printf, 1, 2)));
443 void verifydir(char *);
444 
445 struct passwd *pwd;
446 uid_t userid;
447 int errs, remin, remout, remin2, remout2;
448 int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
449 
450 #define	CMDNEEDS	64
451 char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
452 
453 enum scp_mode_e {
454 	MODE_SCP,
455 	MODE_SFTP
456 };
457 
458 int response(void);
459 void rsource(char *, struct stat *);
460 void sink(int, char *[], const char *);
461 void source(int, char *[]);
462 void tolocal(int, char *[], enum scp_mode_e, char *sftp_direct);
463 void toremote(int, char *[], enum scp_mode_e, char *sftp_direct);
464 void usage(void);
465 
466 void source_sftp(int, char *, char *, struct sftp_conn *);
467 void sink_sftp(int, char *, const char *, struct sftp_conn *);
468 void throughlocal_sftp(struct sftp_conn *, struct sftp_conn *,
469     char *, char *);
470 
471 int
main(int argc,char ** argv)472 main(int argc, char **argv)
473 {
474 	int ch, fflag, tflag, status, r, n;
475 	char **newargv, *argv0;
476 	const char *errstr;
477 	extern char *optarg;
478 	extern int optind;
479 	enum scp_mode_e mode = MODE_SFTP;
480 	char *sftp_direct = NULL;
481 	long long llv;
482 
483 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
484 	sanitise_stdfd();
485 
486 	msetlocale();
487 
488 	/* Copy argv, because we modify it */
489 	argv0 = argv[0];
490 	newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
491 	for (n = 0; n < argc; n++)
492 		newargv[n] = xstrdup(argv[n]);
493 	argv = newargv;
494 
495 	__progname = ssh_get_progname(argv[0]);
496 
497 	log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
498 
499 	memset(&args, '\0', sizeof(args));
500 	memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
501 	args.list = remote_remote_args.list = NULL;
502 	addargs(&args, "%s", ssh_program);
503 	addargs(&args, "-x");
504 	addargs(&args, "-oPermitLocalCommand=no");
505 	addargs(&args, "-oClearAllForwardings=yes");
506 	addargs(&args, "-oRemoteCommand=none");
507 	addargs(&args, "-oRequestTTY=no");
508 	addargs(&args, "-oControlMaster=no");
509 
510 	fflag = Tflag = tflag = 0;
511 	while ((ch = getopt(argc, argv,
512 	    "12346ABCTdfOpqRrstvD:F:J:M:P:S:c:i:l:o:X:")) != -1) {
513 		switch (ch) {
514 		/* User-visible flags. */
515 		case '1':
516 			fatal("SSH protocol v.1 is no longer supported");
517 			break;
518 		case '2':
519 			/* Ignored */
520 			break;
521 		case 'A':
522 		case '4':
523 		case '6':
524 		case 'C':
525 			addargs(&args, "-%c", ch);
526 			addargs(&remote_remote_args, "-%c", ch);
527 			break;
528 		case 'D':
529 			sftp_direct = optarg;
530 			break;
531 		case '3':
532 			throughlocal = 1;
533 			break;
534 		case 'R':
535 			throughlocal = 0;
536 			break;
537 		case 'o':
538 		case 'c':
539 		case 'i':
540 		case 'F':
541 		case 'J':
542 			addargs(&remote_remote_args, "-%c", ch);
543 			addargs(&remote_remote_args, "%s", optarg);
544 			addargs(&args, "-%c", ch);
545 			addargs(&args, "%s", optarg);
546 			break;
547 		case 'O':
548 			mode = MODE_SCP;
549 			break;
550 		case 's':
551 			mode = MODE_SFTP;
552 			break;
553 		case 'P':
554 			sshport = a2port(optarg);
555 			if (sshport <= 0)
556 				fatal("bad port \"%s\"\n", optarg);
557 			break;
558 		case 'B':
559 			addargs(&remote_remote_args, "-oBatchmode=yes");
560 			addargs(&args, "-oBatchmode=yes");
561 			break;
562 		case 'l':
563 			limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
564 			    &errstr);
565 			if (errstr != NULL)
566 				usage();
567 			limit_kbps *= 1024; /* kbps */
568 			bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
569 			break;
570 		case 'p':
571 			pflag = 1;
572 			break;
573 		case 'r':
574 			iamrecursive = 1;
575 			break;
576 		case 'S':
577 			ssh_program = xstrdup(optarg);
578 			break;
579 		case 'v':
580 			addargs(&args, "-v");
581 			addargs(&remote_remote_args, "-v");
582 			if (verbose_mode == 0)
583 				log_level = SYSLOG_LEVEL_DEBUG1;
584 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
585 				log_level++;
586 			verbose_mode = 1;
587 			break;
588 		case 'q':
589 			addargs(&args, "-q");
590 			addargs(&remote_remote_args, "-q");
591 			showprogress = 0;
592 			break;
593 		case 'X':
594 			/* Please keep in sync with sftp.c -X */
595 			if (strncmp(optarg, "buffer=", 7) == 0) {
596 				r = scan_scaled(optarg + 7, &llv);
597 				if (r == 0 && (llv <= 0 || llv > 256 * 1024)) {
598 					r = -1;
599 					errno = EINVAL;
600 				}
601 				if (r == -1) {
602 					fatal("Invalid buffer size \"%s\": %s",
603 					     optarg + 7, strerror(errno));
604 				}
605 				sftp_copy_buflen = (size_t)llv;
606 			} else if (strncmp(optarg, "nrequests=", 10) == 0) {
607 				llv = strtonum(optarg + 10, 1, 256 * 1024,
608 				    &errstr);
609 				if (errstr != NULL) {
610 					fatal("Invalid number of requests "
611 					    "\"%s\": %s", optarg + 10, errstr);
612 				}
613 				sftp_nrequests = (size_t)llv;
614 			} else {
615 				fatal("Invalid -X option");
616 			}
617 			break;
618 
619 		/* Server options. */
620 		case 'd':
621 			targetshouldbedirectory = 1;
622 			break;
623 		case 'f':	/* "from" */
624 			iamremote = 1;
625 			fflag = 1;
626 			break;
627 		case 't':	/* "to" */
628 			iamremote = 1;
629 			tflag = 1;
630 #ifdef HAVE_CYGWIN
631 			setmode(0, O_BINARY);
632 #endif
633 			break;
634 		case 'T':
635 			Tflag = 1;
636 			break;
637 		default:
638 			usage();
639 		}
640 	}
641 	argc -= optind;
642 	argv += optind;
643 
644 	log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
645 
646 	/* Do this last because we want the user to be able to override it */
647 	addargs(&args, "-oForwardAgent=no");
648 
649 	if (iamremote)
650 		mode = MODE_SCP;
651 
652 	if ((pwd = getpwuid(userid = getuid())) == NULL)
653 		fatal("unknown user %u", (u_int) userid);
654 
655 	if (!isatty(STDOUT_FILENO))
656 		showprogress = 0;
657 
658 	if (pflag) {
659 		/* Cannot pledge: -p allows setuid/setgid files... */
660 	} else {
661 		if (pledge("stdio rpath wpath cpath fattr tty proc exec",
662 		    NULL) == -1) {
663 			perror("pledge");
664 			exit(1);
665 		}
666 	}
667 
668 	remin = STDIN_FILENO;
669 	remout = STDOUT_FILENO;
670 
671 	if (fflag) {
672 		/* Follow "protocol", send data. */
673 		(void) response();
674 		source(argc, argv);
675 		exit(errs != 0);
676 	}
677 	if (tflag) {
678 		/* Receive data. */
679 		sink(argc, argv, NULL);
680 		exit(errs != 0);
681 	}
682 	if (argc < 2)
683 		usage();
684 	if (argc > 2)
685 		targetshouldbedirectory = 1;
686 
687 	remin = remout = -1;
688 	do_cmd_pid = -1;
689 	/* Command to be executed on remote system using "ssh". */
690 	(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
691 	    verbose_mode ? " -v" : "",
692 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
693 	    targetshouldbedirectory ? " -d" : "");
694 
695 	(void) ssh_signal(SIGPIPE, lostconn);
696 
697 	if (colon(argv[argc - 1]))	/* Dest is remote host. */
698 		toremote(argc, argv, mode, sftp_direct);
699 	else {
700 		if (targetshouldbedirectory)
701 			verifydir(argv[argc - 1]);
702 		tolocal(argc, argv, mode, sftp_direct);	/* Dest is local host. */
703 	}
704 	/*
705 	 * Finally check the exit status of the ssh process, if one was forked
706 	 * and no error has occurred yet
707 	 */
708 	if (do_cmd_pid != -1 && (mode == MODE_SFTP || errs == 0)) {
709 		if (remin != -1)
710 		    (void) close(remin);
711 		if (remout != -1)
712 		    (void) close(remout);
713 		if (waitpid(do_cmd_pid, &status, 0) == -1)
714 			errs = 1;
715 		else {
716 			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
717 				errs = 1;
718 		}
719 	}
720 	exit(errs != 0);
721 }
722 
723 /* Callback from atomicio6 to update progress meter and limit bandwidth */
724 static int
scpio(void * _cnt,size_t s)725 scpio(void *_cnt, size_t s)
726 {
727 	off_t *cnt = (off_t *)_cnt;
728 
729 	*cnt += s;
730 	refresh_progress_meter(0);
731 	if (limit_kbps > 0)
732 		bandwidth_limit(&bwlimit, s);
733 	return 0;
734 }
735 
736 static int
do_times(int fd,int verb,const struct stat * sb)737 do_times(int fd, int verb, const struct stat *sb)
738 {
739 	/* strlen(2^64) == 20; strlen(10^6) == 7 */
740 	char buf[(20 + 7 + 2) * 2 + 2];
741 
742 	(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
743 	    (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
744 	    (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
745 	if (verb) {
746 		fprintf(stderr, "File mtime %lld atime %lld\n",
747 		    (long long)sb->st_mtime, (long long)sb->st_atime);
748 		fprintf(stderr, "Sending file timestamps: %s", buf);
749 	}
750 	(void) atomicio(vwrite, fd, buf, strlen(buf));
751 	return (response());
752 }
753 
754 static int
parse_scp_uri(const char * uri,char ** userp,char ** hostp,int * portp,char ** pathp)755 parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
756     char **pathp)
757 {
758 	int r;
759 
760 	r = parse_uri("scp", uri, userp, hostp, portp, pathp);
761 	if (r == 0 && *pathp == NULL)
762 		*pathp = xstrdup(".");
763 	return r;
764 }
765 
766 /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
767 static int
append(char * cp,char *** ap,size_t * np)768 append(char *cp, char ***ap, size_t *np)
769 {
770 	char **tmp;
771 
772 	if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
773 		return -1;
774 	tmp[(*np)] = cp;
775 	(*np)++;
776 	*ap = tmp;
777 	return 0;
778 }
779 
780 /*
781  * Finds the start and end of the first brace pair in the pattern.
782  * returns 0 on success or -1 for invalid patterns.
783  */
784 static int
find_brace(const char * pattern,int * startp,int * endp)785 find_brace(const char *pattern, int *startp, int *endp)
786 {
787 	int i;
788 	int in_bracket, brace_level;
789 
790 	*startp = *endp = -1;
791 	in_bracket = brace_level = 0;
792 	for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
793 		switch (pattern[i]) {
794 		case '\\':
795 			/* skip next character */
796 			if (pattern[i + 1] != '\0')
797 				i++;
798 			break;
799 		case '[':
800 			in_bracket = 1;
801 			break;
802 		case ']':
803 			in_bracket = 0;
804 			break;
805 		case '{':
806 			if (in_bracket)
807 				break;
808 			if (pattern[i + 1] == '}') {
809 				/* Protect a single {}, for find(1), like csh */
810 				i++; /* skip */
811 				break;
812 			}
813 			if (*startp == -1)
814 				*startp = i;
815 			brace_level++;
816 			break;
817 		case '}':
818 			if (in_bracket)
819 				break;
820 			if (*startp < 0) {
821 				/* Unbalanced brace */
822 				return -1;
823 			}
824 			if (--brace_level <= 0)
825 				*endp = i;
826 			break;
827 		}
828 	}
829 	/* unbalanced brackets/braces */
830 	if (*endp < 0 && (*startp >= 0 || in_bracket))
831 		return -1;
832 	return 0;
833 }
834 
835 /*
836  * Assembles and records a successfully-expanded pattern, returns -1 on
837  * alloc failure.
838  */
839 static int
emit_expansion(const char * pattern,int brace_start,int brace_end,int sel_start,int sel_end,char *** patternsp,size_t * npatternsp)840 emit_expansion(const char *pattern, int brace_start, int brace_end,
841     int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
842 {
843 	char *cp;
844 	size_t pattern_len;
845 	int o = 0, tail_len;
846 
847 	if ((pattern_len = strlen(pattern)) == 0 || pattern_len >= INT_MAX)
848 		return -1;
849 
850 	tail_len = strlen(pattern + brace_end + 1);
851 	if ((cp = malloc(brace_start + (sel_end - sel_start) +
852 	    tail_len + 1)) == NULL)
853 		return -1;
854 
855 	/* Pattern before initial brace */
856 	if (brace_start > 0) {
857 		memcpy(cp, pattern, brace_start);
858 		o = brace_start;
859 	}
860 	/* Current braced selection */
861 	if (sel_end - sel_start > 0) {
862 		memcpy(cp + o, pattern + sel_start,
863 		    sel_end - sel_start);
864 		o += sel_end - sel_start;
865 	}
866 	/* Remainder of pattern after closing brace */
867 	if (tail_len > 0) {
868 		memcpy(cp + o, pattern + brace_end + 1, tail_len);
869 		o += tail_len;
870 	}
871 	cp[o] = '\0';
872 	if (append(cp, patternsp, npatternsp) != 0) {
873 		free(cp);
874 		return -1;
875 	}
876 	return 0;
877 }
878 
879 /*
880  * Expand the first encountered brace in pattern, appending the expanded
881  * patterns it yielded to the *patternsp array.
882  *
883  * Returns 0 on success or -1 on allocation failure.
884  *
885  * Signals whether expansion was performed via *expanded and whether
886  * pattern was invalid via *invalid.
887  */
888 static int
brace_expand_one(const char * pattern,char *** patternsp,size_t * npatternsp,int * expanded,int * invalid)889 brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
890     int *expanded, int *invalid)
891 {
892 	int i;
893 	int in_bracket, brace_start, brace_end, brace_level;
894 	int sel_start, sel_end;
895 
896 	*invalid = *expanded = 0;
897 
898 	if (find_brace(pattern, &brace_start, &brace_end) != 0) {
899 		*invalid = 1;
900 		return 0;
901 	} else if (brace_start == -1)
902 		return 0;
903 
904 	in_bracket = brace_level = 0;
905 	for (i = sel_start = brace_start + 1; i < brace_end; i++) {
906 		switch (pattern[i]) {
907 		case '{':
908 			if (in_bracket)
909 				break;
910 			brace_level++;
911 			break;
912 		case '}':
913 			if (in_bracket)
914 				break;
915 			brace_level--;
916 			break;
917 		case '[':
918 			in_bracket = 1;
919 			break;
920 		case ']':
921 			in_bracket = 0;
922 			break;
923 		case '\\':
924 			if (i < brace_end - 1)
925 				i++; /* skip */
926 			break;
927 		}
928 		if (pattern[i] == ',' || i == brace_end - 1) {
929 			if (in_bracket || brace_level > 0)
930 				continue;
931 			/* End of a selection, emit an expanded pattern */
932 
933 			/* Adjust end index for last selection */
934 			sel_end = (i == brace_end - 1) ? brace_end : i;
935 			if (emit_expansion(pattern, brace_start, brace_end,
936 			    sel_start, sel_end, patternsp, npatternsp) != 0)
937 				return -1;
938 			/* move on to the next selection */
939 			sel_start = i + 1;
940 			continue;
941 		}
942 	}
943 	if (in_bracket || brace_level > 0) {
944 		*invalid = 1;
945 		return 0;
946 	}
947 	/* success */
948 	*expanded = 1;
949 	return 0;
950 }
951 
952 /* Expand braces from pattern. Returns 0 on success, -1 on failure */
953 static int
brace_expand(const char * pattern,char *** patternsp,size_t * npatternsp)954 brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
955 {
956 	char *cp, *cp2, **active = NULL, **done = NULL;
957 	size_t i, nactive = 0, ndone = 0;
958 	int ret = -1, invalid = 0, expanded = 0;
959 
960 	*patternsp = NULL;
961 	*npatternsp = 0;
962 
963 	/* Start the worklist with the original pattern */
964 	if ((cp = strdup(pattern)) == NULL)
965 		return -1;
966 	if (append(cp, &active, &nactive) != 0) {
967 		free(cp);
968 		return -1;
969 	}
970 	while (nactive > 0) {
971 		cp = active[nactive - 1];
972 		nactive--;
973 		if (brace_expand_one(cp, &active, &nactive,
974 		    &expanded, &invalid) == -1) {
975 			free(cp);
976 			goto fail;
977 		}
978 		if (invalid)
979 			fatal_f("invalid brace pattern \"%s\"", cp);
980 		if (expanded) {
981 			/*
982 			 * Current entry expanded to new entries on the
983 			 * active list; discard the progenitor pattern.
984 			 */
985 			free(cp);
986 			continue;
987 		}
988 		/*
989 		 * Pattern did not expand; append the finename component to
990 		 * the completed list
991 		 */
992 		if ((cp2 = strrchr(cp, '/')) != NULL)
993 			*cp2++ = '\0';
994 		else
995 			cp2 = cp;
996 		if (append(xstrdup(cp2), &done, &ndone) != 0) {
997 			free(cp);
998 			goto fail;
999 		}
1000 		free(cp);
1001 	}
1002 	/* success */
1003 	*patternsp = done;
1004 	*npatternsp = ndone;
1005 	done = NULL;
1006 	ndone = 0;
1007 	ret = 0;
1008  fail:
1009 	for (i = 0; i < nactive; i++)
1010 		free(active[i]);
1011 	free(active);
1012 	for (i = 0; i < ndone; i++)
1013 		free(done[i]);
1014 	free(done);
1015 	return ret;
1016 }
1017 
1018 static struct sftp_conn *
do_sftp_connect(char * host,char * user,int port,char * sftp_direct,int * reminp,int * remoutp,int * pidp)1019 do_sftp_connect(char *host, char *user, int port, char *sftp_direct,
1020    int *reminp, int *remoutp, int *pidp)
1021 {
1022 	if (sftp_direct == NULL) {
1023 		if (do_cmd(ssh_program, host, user, port, 1, "sftp",
1024 		    reminp, remoutp, pidp) < 0)
1025 			return NULL;
1026 
1027 	} else {
1028 		freeargs(&args);
1029 		addargs(&args, "sftp-server");
1030 		if (do_cmd(sftp_direct, host, NULL, -1, 0, "sftp",
1031 		    reminp, remoutp, pidp) < 0)
1032 			return NULL;
1033 	}
1034 	return sftp_init(*reminp, *remoutp,
1035 	    sftp_copy_buflen, sftp_nrequests, limit_kbps);
1036 }
1037 
1038 void
toremote(int argc,char ** argv,enum scp_mode_e mode,char * sftp_direct)1039 toremote(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1040 {
1041 	char *suser = NULL, *host = NULL, *src = NULL;
1042 	char *bp, *tuser, *thost, *targ;
1043 	int sport = -1, tport = -1;
1044 	struct sftp_conn *conn = NULL, *conn2 = NULL;
1045 	arglist alist;
1046 	int i, r, status;
1047 	struct stat sb;
1048 	u_int j;
1049 
1050 	memset(&alist, '\0', sizeof(alist));
1051 	alist.list = NULL;
1052 
1053 	/* Parse target */
1054 	r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
1055 	if (r == -1) {
1056 		fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
1057 		++errs;
1058 		goto out;
1059 	}
1060 	if (r != 0) {
1061 		if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
1062 		    &targ) == -1) {
1063 			fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
1064 			++errs;
1065 			goto out;
1066 		}
1067 	}
1068 
1069 	/* Parse source files */
1070 	for (i = 0; i < argc - 1; i++) {
1071 		free(suser);
1072 		free(host);
1073 		free(src);
1074 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1075 		if (r == -1) {
1076 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1077 			++errs;
1078 			continue;
1079 		}
1080 		if (r != 0) {
1081 			parse_user_host_path(argv[i], &suser, &host, &src);
1082 		}
1083 		if (suser != NULL && !okname(suser)) {
1084 			++errs;
1085 			continue;
1086 		}
1087 		if (host && throughlocal) {	/* extended remote to remote */
1088 			if (mode == MODE_SFTP) {
1089 				if (remin == -1 || conn == NULL) {
1090 					/* Connect to dest now */
1091 					conn = do_sftp_connect(thost, tuser,
1092 					    tport, sftp_direct,
1093 					    &remin, &remout, &do_cmd_pid);
1094 					if (conn == NULL) {
1095 						fatal("Unable to open "
1096 						    "destination connection");
1097 					}
1098 					debug3_f("origin in %d out %d pid %ld",
1099 					    remin, remout, (long)do_cmd_pid);
1100 				}
1101 				/*
1102 				 * XXX remember suser/host/sport and only
1103 				 * reconnect if they change between arguments.
1104 				 * would save reconnections for cases like
1105 				 * scp -3 hosta:/foo hosta:/bar hostb:
1106 				 */
1107 				/* Connect to origin now */
1108 				conn2 = do_sftp_connect(host, suser,
1109 				    sport, sftp_direct,
1110 				    &remin2, &remout2, &do_cmd_pid2);
1111 				if (conn2 == NULL) {
1112 					fatal("Unable to open "
1113 					    "source connection");
1114 				}
1115 				debug3_f("destination in %d out %d pid %ld",
1116 				    remin2, remout2, (long)do_cmd_pid2);
1117 				throughlocal_sftp(conn2, conn, src, targ);
1118 				(void) close(remin2);
1119 				(void) close(remout2);
1120 				remin2 = remout2 = -1;
1121 				if (waitpid(do_cmd_pid2, &status, 0) == -1)
1122 					++errs;
1123 				else if (!WIFEXITED(status) ||
1124 				    WEXITSTATUS(status) != 0)
1125 					++errs;
1126 				do_cmd_pid2 = -1;
1127 				continue;
1128 			} else {
1129 				xasprintf(&bp, "%s -f %s%s", cmd,
1130 				    *src == '-' ? "-- " : "", src);
1131 				if (do_cmd(ssh_program, host, suser, sport, 0,
1132 				    bp, &remin, &remout, &do_cmd_pid) < 0)
1133 					exit(1);
1134 				free(bp);
1135 				xasprintf(&bp, "%s -t %s%s", cmd,
1136 				    *targ == '-' ? "-- " : "", targ);
1137 				if (do_cmd2(thost, tuser, tport, bp,
1138 				    remin, remout) < 0)
1139 					exit(1);
1140 				free(bp);
1141 				(void) close(remin);
1142 				(void) close(remout);
1143 				remin = remout = -1;
1144 			}
1145 		} else if (host) {	/* standard remote to remote */
1146 			/*
1147 			 * Second remote user is passed to first remote side
1148 			 * via scp command-line. Ensure it contains no obvious
1149 			 * shell characters.
1150 			 */
1151 			if (tuser != NULL && !okname(tuser)) {
1152 				++errs;
1153 				continue;
1154 			}
1155 			if (tport != -1 && tport != SSH_DEFAULT_PORT) {
1156 				/* This would require the remote support URIs */
1157 				fatal("target port not supported with two "
1158 				    "remote hosts and the -R option");
1159 			}
1160 
1161 			freeargs(&alist);
1162 			addargs(&alist, "%s", ssh_program);
1163 			addargs(&alist, "-x");
1164 			addargs(&alist, "-oClearAllForwardings=yes");
1165 			addargs(&alist, "-n");
1166 			for (j = 0; j < remote_remote_args.num; j++) {
1167 				addargs(&alist, "%s",
1168 				    remote_remote_args.list[j]);
1169 			}
1170 
1171 			if (sport != -1) {
1172 				addargs(&alist, "-p");
1173 				addargs(&alist, "%d", sport);
1174 			}
1175 			if (suser) {
1176 				addargs(&alist, "-l");
1177 				addargs(&alist, "%s", suser);
1178 			}
1179 			addargs(&alist, "--");
1180 			addargs(&alist, "%s", host);
1181 			addargs(&alist, "%s", cmd);
1182 			addargs(&alist, "%s", src);
1183 			addargs(&alist, "%s%s%s:%s",
1184 			    tuser ? tuser : "", tuser ? "@" : "",
1185 			    thost, targ);
1186 			if (do_local_cmd(&alist) != 0)
1187 				errs = 1;
1188 		} else {	/* local to remote */
1189 			if (mode == MODE_SFTP) {
1190 				/* no need to glob: already done by shell */
1191 				if (stat(argv[i], &sb) != 0) {
1192 					fatal("stat local \"%s\": %s", argv[i],
1193 					    strerror(errno));
1194 				}
1195 				if (remin == -1) {
1196 					/* Connect to remote now */
1197 					conn = do_sftp_connect(thost, tuser,
1198 					    tport, sftp_direct,
1199 					    &remin, &remout, &do_cmd_pid);
1200 					if (conn == NULL) {
1201 						fatal("Unable to open sftp "
1202 						    "connection");
1203 					}
1204 				}
1205 
1206 				/* The protocol */
1207 				source_sftp(1, argv[i], targ, conn);
1208 				continue;
1209 			}
1210 			/* SCP */
1211 			if (remin == -1) {
1212 				xasprintf(&bp, "%s -t %s%s", cmd,
1213 				    *targ == '-' ? "-- " : "", targ);
1214 				if (do_cmd(ssh_program, thost, tuser, tport, 0,
1215 				    bp, &remin, &remout, &do_cmd_pid) < 0)
1216 					exit(1);
1217 				if (response() < 0)
1218 					exit(1);
1219 				free(bp);
1220 			}
1221 			source(1, argv + i);
1222 		}
1223 	}
1224 out:
1225 	if (mode == MODE_SFTP)
1226 		free(conn);
1227 	free(tuser);
1228 	free(thost);
1229 	free(targ);
1230 	free(suser);
1231 	free(host);
1232 	free(src);
1233 }
1234 
1235 void
tolocal(int argc,char ** argv,enum scp_mode_e mode,char * sftp_direct)1236 tolocal(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1237 {
1238 	char *bp, *host = NULL, *src = NULL, *suser = NULL;
1239 	arglist alist;
1240 	struct sftp_conn *conn = NULL;
1241 	int i, r, sport = -1;
1242 
1243 	memset(&alist, '\0', sizeof(alist));
1244 	alist.list = NULL;
1245 
1246 	for (i = 0; i < argc - 1; i++) {
1247 		free(suser);
1248 		free(host);
1249 		free(src);
1250 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
1251 		if (r == -1) {
1252 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
1253 			++errs;
1254 			continue;
1255 		}
1256 		if (r != 0)
1257 			parse_user_host_path(argv[i], &suser, &host, &src);
1258 		if (suser != NULL && !okname(suser)) {
1259 			++errs;
1260 			continue;
1261 		}
1262 		if (!host) {	/* Local to local. */
1263 			freeargs(&alist);
1264 			addargs(&alist, "%s", _PATH_CP);
1265 			if (iamrecursive)
1266 				addargs(&alist, "-r");
1267 			if (pflag)
1268 				addargs(&alist, "-p");
1269 			addargs(&alist, "--");
1270 			addargs(&alist, "%s", argv[i]);
1271 			addargs(&alist, "%s", argv[argc-1]);
1272 			if (do_local_cmd(&alist))
1273 				++errs;
1274 			continue;
1275 		}
1276 		/* Remote to local. */
1277 		if (mode == MODE_SFTP) {
1278 			conn = do_sftp_connect(host, suser, sport,
1279 			    sftp_direct, &remin, &remout, &do_cmd_pid);
1280 			if (conn == NULL) {
1281 				error("sftp connection failed");
1282 				++errs;
1283 				continue;
1284 			}
1285 
1286 			/* The protocol */
1287 			sink_sftp(1, argv[argc - 1], src, conn);
1288 
1289 			free(conn);
1290 			(void) close(remin);
1291 			(void) close(remout);
1292 			remin = remout = -1;
1293 			continue;
1294 		}
1295 		/* SCP */
1296 		xasprintf(&bp, "%s -f %s%s",
1297 		    cmd, *src == '-' ? "-- " : "", src);
1298 		if (do_cmd(ssh_program, host, suser, sport, 0, bp,
1299 		    &remin, &remout, &do_cmd_pid) < 0) {
1300 			free(bp);
1301 			++errs;
1302 			continue;
1303 		}
1304 		free(bp);
1305 		sink(1, argv + argc - 1, src);
1306 		(void) close(remin);
1307 		remin = remout = -1;
1308 	}
1309 	free(suser);
1310 	free(host);
1311 	free(src);
1312 }
1313 
1314 /* Prepare remote path, handling ~ by assuming cwd is the homedir */
1315 static char *
prepare_remote_path(struct sftp_conn * conn,const char * path)1316 prepare_remote_path(struct sftp_conn *conn, const char *path)
1317 {
1318 	size_t nslash;
1319 
1320 	/* Handle ~ prefixed paths */
1321 	if (*path == '\0' || strcmp(path, "~") == 0)
1322 		return xstrdup(".");
1323 	if (*path != '~')
1324 		return xstrdup(path);
1325 	if (strncmp(path, "~/", 2) == 0) {
1326 		if ((nslash = strspn(path + 2, "/")) == strlen(path + 2))
1327 			return xstrdup(".");
1328 		return xstrdup(path + 2 + nslash);
1329 	}
1330 	if (sftp_can_expand_path(conn))
1331 		return sftp_expand_path(conn, path);
1332 	/* No protocol extension */
1333 	error("server expand-path extension is required "
1334 	    "for ~user paths in SFTP mode");
1335 	return NULL;
1336 }
1337 
1338 void
source_sftp(int argc,char * src,char * targ,struct sftp_conn * conn)1339 source_sftp(int argc, char *src, char *targ, struct sftp_conn *conn)
1340 {
1341 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
1342 	int src_is_dir, target_is_dir;
1343 	Attrib a;
1344 	struct stat st;
1345 
1346 	memset(&a, '\0', sizeof(a));
1347 	if (stat(src, &st) != 0)
1348 		fatal("stat local \"%s\": %s", src, strerror(errno));
1349 	src_is_dir = S_ISDIR(st.st_mode);
1350 	if ((filename = basename(src)) == NULL)
1351 		fatal("basename \"%s\": %s", src, strerror(errno));
1352 
1353 	/*
1354 	 * No need to glob here - the local shell already took care of
1355 	 * the expansions
1356 	 */
1357 	if ((target = prepare_remote_path(conn, targ)) == NULL)
1358 		cleanup_exit(255);
1359 	target_is_dir = sftp_remote_is_dir(conn, target);
1360 	if (targetshouldbedirectory && !target_is_dir) {
1361 		debug("target directory \"%s\" does not exist", target);
1362 		a.flags = SSH2_FILEXFER_ATTR_PERMISSIONS;
1363 		a.perm = st.st_mode | 0700; /* ensure writable */
1364 		if (sftp_mkdir(conn, target, &a, 1) != 0)
1365 			cleanup_exit(255); /* error already logged */
1366 		target_is_dir = 1;
1367 	}
1368 	if (target_is_dir)
1369 		abs_dst = sftp_path_append(target, filename);
1370 	else {
1371 		abs_dst = target;
1372 		target = NULL;
1373 	}
1374 	debug3_f("copying local %s to remote %s", src, abs_dst);
1375 
1376 	if (src_is_dir && iamrecursive) {
1377 		if (sftp_upload_dir(conn, src, abs_dst, pflag,
1378 		    SFTP_PROGRESS_ONLY, 0, 0, 1, 1) != 0) {
1379 			error("failed to upload directory %s to %s", src, targ);
1380 			errs = 1;
1381 		}
1382 	} else if (sftp_upload(conn, src, abs_dst, pflag, 0, 0, 1) != 0) {
1383 		error("failed to upload file %s to %s", src, targ);
1384 		errs = 1;
1385 	}
1386 
1387 	free(abs_dst);
1388 	free(target);
1389 }
1390 
1391 void
source(int argc,char ** argv)1392 source(int argc, char **argv)
1393 {
1394 	struct stat stb;
1395 	static BUF buffer;
1396 	BUF *bp;
1397 	off_t i, statbytes;
1398 	size_t amt, nr;
1399 	int fd = -1, haderr, indx;
1400 	char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
1401 	int len;
1402 
1403 	for (indx = 0; indx < argc; ++indx) {
1404 		name = argv[indx];
1405 		statbytes = 0;
1406 		len = strlen(name);
1407 		while (len > 1 && name[len-1] == '/')
1408 			name[--len] = '\0';
1409 		if ((fd = open(name, O_RDONLY|O_NONBLOCK)) == -1)
1410 			goto syserr;
1411 		if (strchr(name, '\n') != NULL) {
1412 			strnvis(encname, name, sizeof(encname), VIS_NL);
1413 			name = encname;
1414 		}
1415 		if (fstat(fd, &stb) == -1) {
1416 syserr:			run_err("%s: %s", name, strerror(errno));
1417 			goto next;
1418 		}
1419 		if (stb.st_size < 0) {
1420 			run_err("%s: %s", name, "Negative file size");
1421 			goto next;
1422 		}
1423 		unset_nonblock(fd);
1424 		switch (stb.st_mode & S_IFMT) {
1425 		case S_IFREG:
1426 			break;
1427 		case S_IFDIR:
1428 			if (iamrecursive) {
1429 				rsource(name, &stb);
1430 				goto next;
1431 			}
1432 			/* FALLTHROUGH */
1433 		default:
1434 			run_err("%s: not a regular file", name);
1435 			goto next;
1436 		}
1437 		if ((last = strrchr(name, '/')) == NULL)
1438 			last = name;
1439 		else
1440 			++last;
1441 		curfile = last;
1442 		if (pflag) {
1443 			if (do_times(remout, verbose_mode, &stb) < 0)
1444 				goto next;
1445 		}
1446 #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1447 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1448 		    (u_int) (stb.st_mode & FILEMODEMASK),
1449 		    (long long)stb.st_size, last);
1450 		if (verbose_mode)
1451 			fmprintf(stderr, "Sending file modes: %s", buf);
1452 		(void) atomicio(vwrite, remout, buf, strlen(buf));
1453 		if (response() < 0)
1454 			goto next;
1455 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1456 next:			if (fd != -1) {
1457 				(void) close(fd);
1458 				fd = -1;
1459 			}
1460 			continue;
1461 		}
1462 		if (showprogress)
1463 			start_progress_meter(curfile, stb.st_size, &statbytes);
1464 		set_nonblock(remout);
1465 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1466 			amt = bp->cnt;
1467 			if (i + (off_t)amt > stb.st_size)
1468 				amt = stb.st_size - i;
1469 			if (!haderr) {
1470 				if ((nr = atomicio(read, fd,
1471 				    bp->buf, amt)) != amt) {
1472 					haderr = errno;
1473 					memset(bp->buf + nr, 0, amt - nr);
1474 				}
1475 			}
1476 			/* Keep writing after error to retain sync */
1477 			if (haderr) {
1478 				(void)atomicio(vwrite, remout, bp->buf, amt);
1479 				memset(bp->buf, 0, amt);
1480 				continue;
1481 			}
1482 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1483 			    &statbytes) != amt)
1484 				haderr = errno;
1485 		}
1486 		unset_nonblock(remout);
1487 
1488 		if (fd != -1) {
1489 			if (close(fd) == -1 && !haderr)
1490 				haderr = errno;
1491 			fd = -1;
1492 		}
1493 		if (!haderr)
1494 			(void) atomicio(vwrite, remout, "", 1);
1495 		else
1496 			run_err("%s: %s", name, strerror(haderr));
1497 		(void) response();
1498 		if (showprogress)
1499 			stop_progress_meter();
1500 	}
1501 }
1502 
1503 void
rsource(char * name,struct stat * statp)1504 rsource(char *name, struct stat *statp)
1505 {
1506 	DIR *dirp;
1507 	struct dirent *dp;
1508 	char *last, *vect[1], path[PATH_MAX];
1509 
1510 	if (!(dirp = opendir(name))) {
1511 		run_err("%s: %s", name, strerror(errno));
1512 		return;
1513 	}
1514 	last = strrchr(name, '/');
1515 	if (last == NULL)
1516 		last = name;
1517 	else
1518 		last++;
1519 	if (pflag) {
1520 		if (do_times(remout, verbose_mode, statp) < 0) {
1521 			closedir(dirp);
1522 			return;
1523 		}
1524 	}
1525 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1526 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1527 	if (verbose_mode)
1528 		fmprintf(stderr, "Entering directory: %s", path);
1529 	(void) atomicio(vwrite, remout, path, strlen(path));
1530 	if (response() < 0) {
1531 		closedir(dirp);
1532 		return;
1533 	}
1534 	while ((dp = readdir(dirp)) != NULL) {
1535 		if (dp->d_ino == 0)
1536 			continue;
1537 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1538 			continue;
1539 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1540 			run_err("%s/%s: name too long", name, dp->d_name);
1541 			continue;
1542 		}
1543 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1544 		vect[0] = path;
1545 		source(1, vect);
1546 	}
1547 	(void) closedir(dirp);
1548 	(void) atomicio(vwrite, remout, "E\n", 2);
1549 	(void) response();
1550 }
1551 
1552 void
sink_sftp(int argc,char * dst,const char * src,struct sftp_conn * conn)1553 sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn)
1554 {
1555 	char *abs_src = NULL;
1556 	char *abs_dst = NULL;
1557 	glob_t g;
1558 	char *filename, *tmp = NULL;
1559 	int i, r, err = 0, dst_is_dir;
1560 	struct stat st;
1561 
1562 	memset(&g, 0, sizeof(g));
1563 
1564 	/*
1565 	 * Here, we need remote glob as SFTP can not depend on remote shell
1566 	 * expansions
1567 	 */
1568 	if ((abs_src = prepare_remote_path(conn, src)) == NULL) {
1569 		err = -1;
1570 		goto out;
1571 	}
1572 
1573 	debug3_f("copying remote %s to local %s", abs_src, dst);
1574 	if ((r = sftp_glob(conn, abs_src, GLOB_NOCHECK|GLOB_MARK,
1575 	    NULL, &g)) != 0) {
1576 		if (r == GLOB_NOSPACE)
1577 			error("%s: too many glob matches", src);
1578 		else
1579 			error("%s: %s", src, strerror(ENOENT));
1580 		err = -1;
1581 		goto out;
1582 	}
1583 
1584 	/* Did we actually get any matches back from the glob? */
1585 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
1586 		/*
1587 		 * If nothing matched but a path returned, then it's probably
1588 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
1589 		 * exists so we can give a nice error message early.
1590 		 */
1591 		if (sftp_stat(conn, g.gl_pathv[0], 1, NULL) != 0) {
1592 			error("%s: %s", src, strerror(ENOENT));
1593 			err = -1;
1594 			goto out;
1595 		}
1596 	}
1597 
1598 	if ((r = stat(dst, &st)) != 0)
1599 		debug2_f("stat local \"%s\": %s", dst, strerror(errno));
1600 	dst_is_dir = r == 0 && S_ISDIR(st.st_mode);
1601 
1602 	if (g.gl_matchc > 1 && !dst_is_dir) {
1603 		if (r == 0) {
1604 			error("Multiple files match pattern, but destination "
1605 			    "\"%s\" is not a directory", dst);
1606 			err = -1;
1607 			goto out;
1608 		}
1609 		debug2_f("creating destination \"%s\"", dst);
1610 		if (mkdir(dst, 0777) != 0) {
1611 			error("local mkdir \"%s\": %s", dst, strerror(errno));
1612 			err = -1;
1613 			goto out;
1614 		}
1615 		dst_is_dir = 1;
1616 	}
1617 
1618 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
1619 		tmp = xstrdup(g.gl_pathv[i]);
1620 		if ((filename = basename(tmp)) == NULL) {
1621 			error("basename %s: %s", tmp, strerror(errno));
1622 			err = -1;
1623 			goto out;
1624 		}
1625 
1626 		if (dst_is_dir)
1627 			abs_dst = sftp_path_append(dst, filename);
1628 		else
1629 			abs_dst = xstrdup(dst);
1630 
1631 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
1632 		if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
1633 			if (sftp_download_dir(conn, g.gl_pathv[i], abs_dst,
1634 			    NULL, pflag, SFTP_PROGRESS_ONLY, 0, 0, 1, 1) == -1)
1635 				err = -1;
1636 		} else {
1637 			if (sftp_download(conn, g.gl_pathv[i], abs_dst, NULL,
1638 			    pflag, 0, 0, 1) == -1)
1639 				err = -1;
1640 		}
1641 		free(abs_dst);
1642 		abs_dst = NULL;
1643 		free(tmp);
1644 		tmp = NULL;
1645 	}
1646 
1647 out:
1648 	free(abs_src);
1649 	free(tmp);
1650 	globfree(&g);
1651 	if (err == -1)
1652 		errs = 1;
1653 }
1654 
1655 
1656 #define TYPE_OVERFLOW(type, val) \
1657 	((sizeof(type) == 4 && (val) > INT32_MAX) || \
1658 	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
1659 	 (sizeof(type) != 4 && sizeof(type) != 8))
1660 
1661 void
sink(int argc,char ** argv,const char * src)1662 sink(int argc, char **argv, const char *src)
1663 {
1664 	static BUF buffer;
1665 	struct stat stb;
1666 	BUF *bp;
1667 	off_t i;
1668 	size_t j, count;
1669 	int amt, exists, first, ofd;
1670 	mode_t mode, omode, mask;
1671 	off_t size, statbytes;
1672 	unsigned long long ull;
1673 	int setimes, targisdir, wrerr;
1674 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1675 	char **patterns = NULL;
1676 	size_t n, npatterns = 0;
1677 	struct timeval tv[2];
1678 
1679 #define	atime	tv[0]
1680 #define	mtime	tv[1]
1681 #define	SCREWUP(str)	{ why = str; goto screwup; }
1682 
1683 	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
1684 		SCREWUP("Unexpected off_t/time_t size");
1685 
1686 	setimes = targisdir = 0;
1687 	mask = umask(0);
1688 	if (!pflag)
1689 		(void) umask(mask);
1690 	if (argc != 1) {
1691 		run_err("ambiguous target");
1692 		exit(1);
1693 	}
1694 	targ = *argv;
1695 	if (targetshouldbedirectory)
1696 		verifydir(targ);
1697 
1698 	(void) atomicio(vwrite, remout, "", 1);
1699 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1700 		targisdir = 1;
1701 	if (src != NULL && !iamrecursive && !Tflag) {
1702 		/*
1703 		 * Prepare to try to restrict incoming filenames to match
1704 		 * the requested destination file glob.
1705 		 */
1706 		if (brace_expand(src, &patterns, &npatterns) != 0)
1707 			fatal_f("could not expand pattern");
1708 	}
1709 	for (first = 1;; first = 0) {
1710 		cp = buf;
1711 		if (atomicio(read, remin, cp, 1) != 1)
1712 			goto done;
1713 		if (*cp++ == '\n')
1714 			SCREWUP("unexpected <newline>");
1715 		do {
1716 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1717 				SCREWUP("lost connection");
1718 			*cp++ = ch;
1719 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1720 		*cp = 0;
1721 		if (verbose_mode)
1722 			fmprintf(stderr, "Sink: %s", buf);
1723 
1724 		if (buf[0] == '\01' || buf[0] == '\02') {
1725 			if (iamremote == 0) {
1726 				(void) snmprintf(visbuf, sizeof(visbuf),
1727 				    NULL, "%s", buf + 1);
1728 				(void) atomicio(vwrite, STDERR_FILENO,
1729 				    visbuf, strlen(visbuf));
1730 			}
1731 			if (buf[0] == '\02')
1732 				exit(1);
1733 			++errs;
1734 			continue;
1735 		}
1736 		if (buf[0] == 'E') {
1737 			(void) atomicio(vwrite, remout, "", 1);
1738 			goto done;
1739 		}
1740 		if (ch == '\n')
1741 			*--cp = 0;
1742 
1743 		cp = buf;
1744 		if (*cp == 'T') {
1745 			setimes++;
1746 			cp++;
1747 			if (!isdigit((unsigned char)*cp))
1748 				SCREWUP("mtime.sec not present");
1749 			ull = strtoull(cp, &cp, 10);
1750 			if (!cp || *cp++ != ' ')
1751 				SCREWUP("mtime.sec not delimited");
1752 			if (TYPE_OVERFLOW(time_t, ull))
1753 				setimes = 0;	/* out of range */
1754 			mtime.tv_sec = ull;
1755 			mtime.tv_usec = strtol(cp, &cp, 10);
1756 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1757 			    mtime.tv_usec > 999999)
1758 				SCREWUP("mtime.usec not delimited");
1759 			if (!isdigit((unsigned char)*cp))
1760 				SCREWUP("atime.sec not present");
1761 			ull = strtoull(cp, &cp, 10);
1762 			if (!cp || *cp++ != ' ')
1763 				SCREWUP("atime.sec not delimited");
1764 			if (TYPE_OVERFLOW(time_t, ull))
1765 				setimes = 0;	/* out of range */
1766 			atime.tv_sec = ull;
1767 			atime.tv_usec = strtol(cp, &cp, 10);
1768 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1769 			    atime.tv_usec > 999999)
1770 				SCREWUP("atime.usec not delimited");
1771 			(void) atomicio(vwrite, remout, "", 1);
1772 			continue;
1773 		}
1774 		if (*cp != 'C' && *cp != 'D') {
1775 			/*
1776 			 * Check for the case "rcp remote:foo\* local:bar".
1777 			 * In this case, the line "No match." can be returned
1778 			 * by the shell before the rcp command on the remote is
1779 			 * executed so the ^Aerror_message convention isn't
1780 			 * followed.
1781 			 */
1782 			if (first) {
1783 				run_err("%s", cp);
1784 				exit(1);
1785 			}
1786 			SCREWUP("expected control record");
1787 		}
1788 		mode = 0;
1789 		for (++cp; cp < buf + 5; cp++) {
1790 			if (*cp < '0' || *cp > '7')
1791 				SCREWUP("bad mode");
1792 			mode = (mode << 3) | (*cp - '0');
1793 		}
1794 		if (!pflag)
1795 			mode &= ~mask;
1796 		if (*cp++ != ' ')
1797 			SCREWUP("mode not delimited");
1798 
1799 		if (!isdigit((unsigned char)*cp))
1800 			SCREWUP("size not present");
1801 		ull = strtoull(cp, &cp, 10);
1802 		if (!cp || *cp++ != ' ')
1803 			SCREWUP("size not delimited");
1804 		if (TYPE_OVERFLOW(off_t, ull))
1805 			SCREWUP("size out of range");
1806 		size = (off_t)ull;
1807 
1808 		if (*cp == '\0' || strchr(cp, '/') != NULL ||
1809 		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1810 			run_err("error: unexpected filename: %s", cp);
1811 			exit(1);
1812 		}
1813 		if (npatterns > 0) {
1814 			for (n = 0; n < npatterns; n++) {
1815 				if (strcmp(patterns[n], cp) == 0 ||
1816 				    fnmatch(patterns[n], cp, 0) == 0)
1817 					break;
1818 			}
1819 			if (n >= npatterns) {
1820 				debug2_f("incoming filename \"%s\" does not "
1821 				    "match any of %zu expected patterns", cp,
1822 				    npatterns);
1823 				for (n = 0; n < npatterns; n++) {
1824 					debug3_f("expected pattern %zu: \"%s\"",
1825 					    n, patterns[n]);
1826 				}
1827 				SCREWUP("filename does not match request");
1828 			}
1829 		}
1830 		if (targisdir) {
1831 			static char *namebuf;
1832 			static size_t cursize;
1833 			size_t need;
1834 
1835 			need = strlen(targ) + strlen(cp) + 250;
1836 			if (need > cursize) {
1837 				free(namebuf);
1838 				namebuf = xmalloc(need);
1839 				cursize = need;
1840 			}
1841 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1842 			    strcmp(targ, "/") ? "/" : "", cp);
1843 			np = namebuf;
1844 		} else
1845 			np = targ;
1846 		curfile = cp;
1847 		exists = stat(np, &stb) == 0;
1848 		if (buf[0] == 'D') {
1849 			int mod_flag = pflag;
1850 			if (!iamrecursive)
1851 				SCREWUP("received directory without -r");
1852 			if (exists) {
1853 				if (!S_ISDIR(stb.st_mode)) {
1854 					errno = ENOTDIR;
1855 					goto bad;
1856 				}
1857 				if (pflag)
1858 					(void) chmod(np, mode);
1859 			} else {
1860 				/* Handle copying from a read-only directory */
1861 				mod_flag = 1;
1862 				if (mkdir(np, mode | S_IRWXU) == -1)
1863 					goto bad;
1864 			}
1865 			vect[0] = xstrdup(np);
1866 			sink(1, vect, src);
1867 			if (setimes) {
1868 				setimes = 0;
1869 				(void) utimes(vect[0], tv);
1870 			}
1871 			if (mod_flag)
1872 				(void) chmod(vect[0], mode);
1873 			free(vect[0]);
1874 			continue;
1875 		}
1876 		omode = mode;
1877 		mode |= S_IWUSR;
1878 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1879 bad:			run_err("%s: %s", np, strerror(errno));
1880 			continue;
1881 		}
1882 		(void) atomicio(vwrite, remout, "", 1);
1883 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1884 			(void) close(ofd);
1885 			continue;
1886 		}
1887 		cp = bp->buf;
1888 		wrerr = 0;
1889 
1890 		/*
1891 		 * NB. do not use run_err() unless immediately followed by
1892 		 * exit() below as it may send a spurious reply that might
1893 		 * desyncronise us from the peer. Use note_err() instead.
1894 		 */
1895 		statbytes = 0;
1896 		if (showprogress)
1897 			start_progress_meter(curfile, size, &statbytes);
1898 		set_nonblock(remin);
1899 		for (count = i = 0; i < size; i += bp->cnt) {
1900 			amt = bp->cnt;
1901 			if (i + amt > size)
1902 				amt = size - i;
1903 			count += amt;
1904 			do {
1905 				j = atomicio6(read, remin, cp, amt,
1906 				    scpio, &statbytes);
1907 				if (j == 0) {
1908 					run_err("%s", j != EPIPE ?
1909 					    strerror(errno) :
1910 					    "dropped connection");
1911 					exit(1);
1912 				}
1913 				amt -= j;
1914 				cp += j;
1915 			} while (amt > 0);
1916 
1917 			if (count == bp->cnt) {
1918 				/* Keep reading so we stay sync'd up. */
1919 				if (!wrerr) {
1920 					if (atomicio(vwrite, ofd, bp->buf,
1921 					    count) != count) {
1922 						note_err("%s: %s", np,
1923 						    strerror(errno));
1924 						wrerr = 1;
1925 					}
1926 				}
1927 				count = 0;
1928 				cp = bp->buf;
1929 			}
1930 		}
1931 		unset_nonblock(remin);
1932 		if (count != 0 && !wrerr &&
1933 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
1934 			note_err("%s: %s", np, strerror(errno));
1935 			wrerr = 1;
1936 		}
1937 		if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
1938 		    ftruncate(ofd, size) != 0)
1939 			note_err("%s: truncate: %s", np, strerror(errno));
1940 		if (pflag) {
1941 			if (exists || omode != mode)
1942 #ifdef HAVE_FCHMOD
1943 				if (fchmod(ofd, omode)) {
1944 #else /* HAVE_FCHMOD */
1945 				if (chmod(np, omode)) {
1946 #endif /* HAVE_FCHMOD */
1947 					note_err("%s: set mode: %s",
1948 					    np, strerror(errno));
1949 				}
1950 		} else {
1951 			if (!exists && omode != mode)
1952 #ifdef HAVE_FCHMOD
1953 				if (fchmod(ofd, omode & ~mask)) {
1954 #else /* HAVE_FCHMOD */
1955 				if (chmod(np, omode & ~mask)) {
1956 #endif /* HAVE_FCHMOD */
1957 					note_err("%s: set mode: %s",
1958 					    np, strerror(errno));
1959 				}
1960 		}
1961 		if (close(ofd) == -1)
1962 			note_err("%s: close: %s", np, strerror(errno));
1963 		(void) response();
1964 		if (showprogress)
1965 			stop_progress_meter();
1966 		if (setimes && !wrerr) {
1967 			setimes = 0;
1968 			if (utimes(np, tv) == -1) {
1969 				note_err("%s: set times: %s",
1970 				    np, strerror(errno));
1971 			}
1972 		}
1973 		/* If no error was noted then signal success for this file */
1974 		if (note_err(NULL) == 0)
1975 			(void) atomicio(vwrite, remout, "", 1);
1976 	}
1977 done:
1978 	for (n = 0; n < npatterns; n++)
1979 		free(patterns[n]);
1980 	free(patterns);
1981 	return;
1982 screwup:
1983 	for (n = 0; n < npatterns; n++)
1984 		free(patterns[n]);
1985 	free(patterns);
1986 	run_err("protocol error: %s", why);
1987 	exit(1);
1988 }
1989 
1990 void
1991 throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
1992     char *src, char *targ)
1993 {
1994 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
1995 	char *abs_src = NULL, *tmp = NULL;
1996 	glob_t g;
1997 	int i, r, targetisdir, err = 0;
1998 
1999 	if ((filename = basename(src)) == NULL)
2000 		fatal("basename %s: %s", src, strerror(errno));
2001 
2002 	if ((abs_src = prepare_remote_path(from, src)) == NULL ||
2003 	    (target = prepare_remote_path(to, targ)) == NULL)
2004 		cleanup_exit(255);
2005 	memset(&g, 0, sizeof(g));
2006 
2007 	targetisdir = sftp_remote_is_dir(to, target);
2008 	if (!targetisdir && targetshouldbedirectory) {
2009 		error("%s: destination is not a directory", targ);
2010 		err = -1;
2011 		goto out;
2012 	}
2013 
2014 	debug3_f("copying remote %s to remote %s", abs_src, target);
2015 	if ((r = sftp_glob(from, abs_src, GLOB_NOCHECK|GLOB_MARK,
2016 	    NULL, &g)) != 0) {
2017 		if (r == GLOB_NOSPACE)
2018 			error("%s: too many glob matches", src);
2019 		else
2020 			error("%s: %s", src, strerror(ENOENT));
2021 		err = -1;
2022 		goto out;
2023 	}
2024 
2025 	/* Did we actually get any matches back from the glob? */
2026 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
2027 		/*
2028 		 * If nothing matched but a path returned, then it's probably
2029 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
2030 		 * exists so we can give a nice error message early.
2031 		 */
2032 		if (sftp_stat(from, g.gl_pathv[0], 1, NULL) != 0) {
2033 			error("%s: %s", src, strerror(ENOENT));
2034 			err = -1;
2035 			goto out;
2036 		}
2037 	}
2038 
2039 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
2040 		tmp = xstrdup(g.gl_pathv[i]);
2041 		if ((filename = basename(tmp)) == NULL) {
2042 			error("basename %s: %s", tmp, strerror(errno));
2043 			err = -1;
2044 			goto out;
2045 		}
2046 
2047 		if (targetisdir)
2048 			abs_dst = sftp_path_append(target, filename);
2049 		else
2050 			abs_dst = xstrdup(target);
2051 
2052 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
2053 		if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
2054 			if (sftp_crossload_dir(from, to, g.gl_pathv[i], abs_dst,
2055 			    NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
2056 				err = -1;
2057 		} else {
2058 			if (sftp_crossload(from, to, g.gl_pathv[i], abs_dst,
2059 			    NULL, pflag) == -1)
2060 				err = -1;
2061 		}
2062 		free(abs_dst);
2063 		abs_dst = NULL;
2064 		free(tmp);
2065 		tmp = NULL;
2066 	}
2067 
2068 out:
2069 	free(abs_src);
2070 	free(abs_dst);
2071 	free(target);
2072 	free(tmp);
2073 	globfree(&g);
2074 	if (err == -1)
2075 		errs = 1;
2076 }
2077 
2078 int
2079 response(void)
2080 {
2081 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
2082 
2083 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
2084 		lostconn(0);
2085 
2086 	cp = rbuf;
2087 	switch (resp) {
2088 	case 0:		/* ok */
2089 		return (0);
2090 	default:
2091 		*cp++ = resp;
2092 		/* FALLTHROUGH */
2093 	case 1:		/* error, followed by error msg */
2094 	case 2:		/* fatal error, "" */
2095 		do {
2096 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
2097 				lostconn(0);
2098 			*cp++ = ch;
2099 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
2100 
2101 		if (!iamremote) {
2102 			cp[-1] = '\0';
2103 			(void) snmprintf(visbuf, sizeof(visbuf),
2104 			    NULL, "%s\n", rbuf);
2105 			(void) atomicio(vwrite, STDERR_FILENO,
2106 			    visbuf, strlen(visbuf));
2107 		}
2108 		++errs;
2109 		if (resp == 1)
2110 			return (-1);
2111 		exit(1);
2112 	}
2113 	/* NOTREACHED */
2114 }
2115 
2116 void
2117 usage(void)
2118 {
2119 	(void) fprintf(stderr,
2120 	    "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
2121 	    "           [-i identity_file] [-J destination] [-l limit] [-o ssh_option]\n"
2122 	    "           [-P port] [-S program] [-X sftp_option] source ... target\n");
2123 	exit(1);
2124 }
2125 
2126 void
2127 run_err(const char *fmt,...)
2128 {
2129 	static FILE *fp;
2130 	va_list ap;
2131 
2132 	++errs;
2133 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
2134 		(void) fprintf(fp, "%c", 0x01);
2135 		(void) fprintf(fp, "scp: ");
2136 		va_start(ap, fmt);
2137 		(void) vfprintf(fp, fmt, ap);
2138 		va_end(ap);
2139 		(void) fprintf(fp, "\n");
2140 		(void) fflush(fp);
2141 	}
2142 
2143 	if (!iamremote) {
2144 		va_start(ap, fmt);
2145 		vfmprintf(stderr, fmt, ap);
2146 		va_end(ap);
2147 		fprintf(stderr, "\n");
2148 	}
2149 }
2150 
2151 /*
2152  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
2153  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
2154  * any active error at the end of the transfer.
2155  */
2156 int
2157 note_err(const char *fmt, ...)
2158 {
2159 	static char *emsg;
2160 	va_list ap;
2161 
2162 	/* Replay any previously-noted error */
2163 	if (fmt == NULL) {
2164 		if (emsg == NULL)
2165 			return 0;
2166 		run_err("%s", emsg);
2167 		free(emsg);
2168 		emsg = NULL;
2169 		return -1;
2170 	}
2171 
2172 	errs++;
2173 	/* Prefer first-noted error */
2174 	if (emsg != NULL)
2175 		return -1;
2176 
2177 	va_start(ap, fmt);
2178 	vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
2179 	va_end(ap);
2180 	return -1;
2181 }
2182 
2183 void
2184 verifydir(char *cp)
2185 {
2186 	struct stat stb;
2187 
2188 	if (!stat(cp, &stb)) {
2189 		if (S_ISDIR(stb.st_mode))
2190 			return;
2191 		errno = ENOTDIR;
2192 	}
2193 	run_err("%s: %s", cp, strerror(errno));
2194 	killchild(0);
2195 }
2196 
2197 int
2198 okname(char *cp0)
2199 {
2200 	int c;
2201 	char *cp;
2202 
2203 	cp = cp0;
2204 	do {
2205 		c = (int)*cp;
2206 		if (c & 0200)
2207 			goto bad;
2208 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
2209 			switch (c) {
2210 			case '\'':
2211 			case '"':
2212 			case '`':
2213 			case ' ':
2214 			case '#':
2215 				goto bad;
2216 			default:
2217 				break;
2218 			}
2219 		}
2220 	} while (*++cp);
2221 	return (1);
2222 
2223 bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
2224 	return (0);
2225 }
2226 
2227 BUF *
2228 allocbuf(BUF *bp, int fd, int blksize)
2229 {
2230 	size_t size;
2231 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2232 	struct stat stb;
2233 
2234 	if (fstat(fd, &stb) == -1) {
2235 		run_err("fstat: %s", strerror(errno));
2236 		return (0);
2237 	}
2238 	size = ROUNDUP(stb.st_blksize, blksize);
2239 	if (size == 0)
2240 		size = blksize;
2241 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2242 	size = blksize;
2243 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2244 	if (bp->cnt >= size)
2245 		return (bp);
2246 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
2247 	bp->cnt = size;
2248 	return (bp);
2249 }
2250 
2251 void
2252 lostconn(int signo)
2253 {
2254 	if (!iamremote)
2255 		(void)write(STDERR_FILENO, "lost connection\n", 16);
2256 	if (signo)
2257 		_exit(1);
2258 	else
2259 		exit(1);
2260 }
2261 
2262 void
2263 cleanup_exit(int i)
2264 {
2265 	if (remin > 0)
2266 		close(remin);
2267 	if (remout > 0)
2268 		close(remout);
2269 	if (remin2 > 0)
2270 		close(remin2);
2271 	if (remout2 > 0)
2272 		close(remout2);
2273 	if (do_cmd_pid > 0)
2274 		(void)waitpid(do_cmd_pid, NULL, 0);
2275 	if (do_cmd_pid2 > 0)
2276 		(void)waitpid(do_cmd_pid2, NULL, 0);
2277 	exit(i);
2278 }
2279