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