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