Home | History | Annotate | Line # | Download | only in dist
scp.c revision 1.45
      1 /*	$NetBSD: scp.c,v 1.45 2026/04/08 18:58:41 christos Exp $	*/
      2 /* $OpenBSD: scp.c,v 1.273 2026/04/02 07:42:16 djm 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 (at) iki.fi>, Tatu Ylonen <ylo (at) 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.45 2026/04/08 18:58:41 christos Exp $");
     78 
     79 #include <sys/param.h>	/* roundup MAX */
     80 #include <sys/types.h>
     81 #include <sys/stat.h>
     82 #include <sys/time.h>
     83 #include <sys/wait.h>
     84 #include <sys/uio.h>
     85 
     86 #include <ctype.h>
     87 #include <dirent.h>
     88 #include <errno.h>
     89 #include <fcntl.h>
     90 #include <fnmatch.h>
     91 #include <glob.h>
     92 #include <libgen.h>
     93 #include <locale.h>
     94 #include <poll.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
    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
    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
    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
    218 do_local_cmd(arglist *a)
    219 {
    220 	char *cp;
    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 		cp = argv_assemble(a->num, a->list);
    229 		fmprintf(stderr, "Executing: %s\n", cp);
    230 		free(cp);
    231 	}
    232 	if ((pid = fork()) == -1)
    233 		fatal("do_local_cmd: fork: %s", strerror(errno));
    234 
    235 	if (pid == 0) {
    236 		execvp(a->list[0], a->list);
    237 		perror(a->list[0]);
    238 		exit(1);
    239 	}
    240 
    241 	do_cmd_pid = pid;
    242 	ssh_signal(SIGTERM, killchild);
    243 	ssh_signal(SIGINT, killchild);
    244 	ssh_signal(SIGHUP, killchild);
    245 
    246 	while (waitpid(pid, &status, 0) == -1)
    247 		if (errno != EINTR)
    248 			fatal("do_local_cmd: waitpid: %s", strerror(errno));
    249 
    250 	do_cmd_pid = -1;
    251 
    252 	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
    253 		return (-1);
    254 
    255 	return (0);
    256 }
    257 
    258 /*
    259  * This function executes the given command as the specified user on the
    260  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
    261  * assigns the input and output file descriptors on success.
    262  */
    263 
    264 int
    265 do_cmd(const char *program, const char *host, const char *remuser, int port, int subsystem,
    266     const char *cmd, int *fdin, int *fdout, pid_t *pid)
    267 {
    268 	int sv[2];
    269 
    270 	if (verbose_mode)
    271 		fmprintf(stderr,
    272 		    "Executing: program %s host %s, user %s, command %s\n",
    273 		    program, host,
    274 		    remuser ? remuser : "(unspecified)", cmd);
    275 
    276 	if (port == -1)
    277 		port = sshport;
    278 
    279 	/* Create a socket pair for communicating with ssh. */
    280 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1)
    281 		fatal("socketpair: %s", strerror(errno));
    282 
    283 	ssh_signal(SIGTSTP, suspchild);
    284 	ssh_signal(SIGTTIN, suspchild);
    285 	ssh_signal(SIGTTOU, suspchild);
    286 
    287 	/* Fork a child to execute the command on the remote host using ssh. */
    288 	*pid = fork();
    289 	switch (*pid) {
    290 	case -1:
    291 		fatal("fork: %s", strerror(errno));
    292 	case 0:
    293 		/* Child. */
    294 		if (dup2(sv[0], STDIN_FILENO) == -1 ||
    295 		    dup2(sv[0], STDOUT_FILENO) == -1) {
    296 			perror("dup2");
    297 			_exit(1);
    298 		}
    299 		close(sv[0]);
    300 		close(sv[1]);
    301 		replacearg(&args, 0, "%s", program);
    302 		if (port != -1) {
    303 			addargs(&args, "-p");
    304 			addargs(&args, "%d", port);
    305 		}
    306 		if (remuser != NULL) {
    307 			addargs(&args, "-l");
    308 			addargs(&args, "%s", remuser);
    309 		}
    310 		if (subsystem)
    311 			addargs(&args, "-s");
    312 		addargs(&args, "--");
    313 		addargs(&args, "%s", host);
    314 		addargs(&args, "%s", cmd);
    315 
    316 		execvp(program, args.list);
    317 		perror(program);
    318 		_exit(1);
    319 	default:
    320 		/* Parent.  Close the other side, and return the local side. */
    321 		close(sv[0]);
    322 		*fdin = sv[1];
    323 		*fdout = sv[1];
    324 		ssh_signal(SIGTERM, killchild);
    325 		ssh_signal(SIGINT, killchild);
    326 		ssh_signal(SIGHUP, killchild);
    327 		return 0;
    328 	}
    329 }
    330 
    331 /*
    332  * This function executes a command similar to do_cmd(), but expects the
    333  * input and output descriptors to be setup by a previous call to do_cmd().
    334  * This way the input and output of two commands can be connected.
    335  */
    336 int
    337 do_cmd2(char *host, char *remuser, int port, char *cmd,
    338     int fdin, int fdout)
    339 {
    340 	int status;
    341 	pid_t pid;
    342 
    343 	if (verbose_mode)
    344 		fmprintf(stderr,
    345 		    "Executing: 2nd program %s host %s, user %s, command %s\n",
    346 		    ssh_program, host,
    347 		    remuser ? remuser : "(unspecified)", cmd);
    348 
    349 	if (port == -1)
    350 		port = sshport;
    351 
    352 	/* Fork a child to execute the command on the remote host using ssh. */
    353 	pid = fork();
    354 	if (pid == 0) {
    355 		if (dup2(fdin, 0) == -1)
    356 			perror("dup2");
    357 		if (dup2(fdout, 1) == -1)
    358 			perror("dup2");
    359 
    360 		replacearg(&args, 0, "%s", ssh_program);
    361 		if (port != -1) {
    362 			addargs(&args, "-p");
    363 			addargs(&args, "%d", port);
    364 		}
    365 		if (remuser != NULL) {
    366 			addargs(&args, "-l");
    367 			addargs(&args, "%s", remuser);
    368 		}
    369 		addargs(&args, "-oBatchMode=yes");
    370 		addargs(&args, "--");
    371 		addargs(&args, "%s", host);
    372 		addargs(&args, "%s", cmd);
    373 
    374 		execvp(ssh_program, args.list);
    375 		perror(ssh_program);
    376 		exit(1);
    377 	} else if (pid == -1) {
    378 		fatal("fork: %s", strerror(errno));
    379 	}
    380 	while (waitpid(pid, &status, 0) == -1)
    381 		if (errno != EINTR)
    382 			fatal("do_cmd2: waitpid: %s", strerror(errno));
    383 	return 0;
    384 }
    385 
    386 typedef struct {
    387 	size_t cnt;
    388 	char *buf;
    389 } BUF;
    390 
    391 BUF *allocbuf(BUF *, int, int);
    392 __dead static void lostconn(int);
    393 int okname(char *);
    394 void run_err(const char *,...)
    395     __attribute__((__format__ (printf, 1, 2)))
    396     __attribute__((__nonnull__ (1)));
    397 int note_err(const char *,...)
    398     __attribute__((__format__ (printf, 1, 2)));
    399 void verifydir(char *);
    400 
    401 struct passwd *pwd;
    402 uid_t userid;
    403 int errs, remin, remout, remin2, remout2;
    404 int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
    405 
    406 #define	CMDNEEDS	64
    407 char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
    408 
    409 enum scp_mode_e {
    410 	MODE_SCP,
    411 	MODE_SFTP
    412 };
    413 
    414 int response(void);
    415 void rsource(char *, struct stat *);
    416 void sink(int, char *[], const char *);
    417 void source(int, char *[]);
    418 static void tolocal(int, char *[], enum scp_mode_e, char *sftp_direct);
    419 static void toremote(int, char *[], enum scp_mode_e, char *sftp_direct);
    420 __dead static void usage(void);
    421 
    422 void source_sftp(int, char *, char *, struct sftp_conn *);
    423 void sink_sftp(int, char *, const char *, struct sftp_conn *);
    424 void throughlocal_sftp(struct sftp_conn *, struct sftp_conn *,
    425     char *, char *);
    426 
    427 int
    428 main(int argc, char **argv)
    429 {
    430 	int ch, fflag, tflag, status, r, n;
    431 	char **newargv, *argv0;
    432 	const char *errstr;
    433 	extern char *optarg;
    434 	extern int optind;
    435 	enum scp_mode_e mode = MODE_SFTP;
    436 	char *sftp_direct = NULL;
    437 	long long llv;
    438 
    439 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
    440 	sanitise_stdfd();
    441 
    442 	setlocale(LC_CTYPE, "");
    443 
    444 	/* Copy argv, because we modify it */
    445 	argv0 = argv[0];
    446 	newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
    447 	for (n = 0; n < argc; n++)
    448 		newargv[n] = xstrdup(argv[n]);
    449 	argv = newargv;
    450 
    451 	log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
    452 
    453 	memset(&args, '\0', sizeof(args));
    454 	memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
    455 	args.list = remote_remote_args.list = NULL;
    456 	addargs(&args, "%s", ssh_program);
    457 	addargs(&args, "-x");
    458 	addargs(&args, "-oPermitLocalCommand=no");
    459 	addargs(&args, "-oClearAllForwardings=yes");
    460 	addargs(&args, "-oRemoteCommand=none");
    461 	addargs(&args, "-oRequestTTY=no");
    462 	addargs(&args, "-oControlMaster=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
    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
    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
    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
    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
    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
    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
    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
    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 filename 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 *
    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
    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 || conn == NULL) {
   1043 					/* Connect to dest now */
   1044 					sftp_free(conn);
   1045 					conn = do_sftp_connect(thost, tuser,
   1046 					    tport, sftp_direct,
   1047 					    &remin, &remout, &do_cmd_pid);
   1048 					if (conn == NULL) {
   1049 						fatal("Unable to open "
   1050 						    "destination connection");
   1051 					}
   1052 					debug3_f("origin in %d out %d pid %ld",
   1053 					    remin, remout, (long)do_cmd_pid);
   1054 				}
   1055 				/*
   1056 				 * XXX remember suser/host/sport and only
   1057 				 * reconnect if they change between arguments.
   1058 				 * would save reconnections for cases like
   1059 				 * scp -3 hosta:/foo hosta:/bar hostb:
   1060 				 */
   1061 				/* Connect to origin now */
   1062 				sftp_free(conn2);
   1063 				conn2 = do_sftp_connect(host, suser,
   1064 				    sport, sftp_direct,
   1065 				    &remin2, &remout2, &do_cmd_pid2);
   1066 				if (conn2 == NULL) {
   1067 					fatal("Unable to open "
   1068 					    "source connection");
   1069 				}
   1070 				debug3_f("destination in %d out %d pid %ld",
   1071 				    remin2, remout2, (long)do_cmd_pid2);
   1072 				throughlocal_sftp(conn2, conn, src, targ);
   1073 				(void) close(remin2);
   1074 				(void) close(remout2);
   1075 				remin2 = remout2 = -1;
   1076 				if (waitpid(do_cmd_pid2, &status, 0) == -1)
   1077 					++errs;
   1078 				else if (!WIFEXITED(status) ||
   1079 				    WEXITSTATUS(status) != 0)
   1080 					++errs;
   1081 				do_cmd_pid2 = -1;
   1082 				continue;
   1083 			} else {
   1084 				xasprintf(&bp, "%s -f %s%s", cmd,
   1085 				    *src == '-' ? "-- " : "", src);
   1086 				if (do_cmd(ssh_program, host, suser, sport, 0,
   1087 				    bp, &remin, &remout, &do_cmd_pid) < 0)
   1088 					exit(1);
   1089 				free(bp);
   1090 				xasprintf(&bp, "%s -t %s%s", cmd,
   1091 				    *targ == '-' ? "-- " : "", targ);
   1092 				if (do_cmd2(thost, tuser, tport, bp,
   1093 				    remin, remout) < 0)
   1094 					exit(1);
   1095 				free(bp);
   1096 				(void) close(remin);
   1097 				(void) close(remout);
   1098 				remin = remout = -1;
   1099 			}
   1100 		} else if (host) {	/* standard remote to remote */
   1101 			/*
   1102 			 * Second remote user is passed to first remote side
   1103 			 * via scp command-line. Ensure it contains no obvious
   1104 			 * shell characters.
   1105 			 */
   1106 			if (tuser != NULL && !okname(tuser)) {
   1107 				++errs;
   1108 				continue;
   1109 			}
   1110 			if (tport != -1 && tport != SSH_DEFAULT_PORT) {
   1111 				/* This would require the remote support URIs */
   1112 				fatal("target port not supported with two "
   1113 				    "remote hosts and the -R option");
   1114 			}
   1115 
   1116 			freeargs(&alist);
   1117 			addargs(&alist, "%s", ssh_program);
   1118 			addargs(&alist, "-x");
   1119 			addargs(&alist, "-oClearAllForwardings=yes");
   1120 			addargs(&alist, "-n");
   1121 			for (j = 0; j < remote_remote_args.num; j++) {
   1122 				addargs(&alist, "%s",
   1123 				    remote_remote_args.list[j]);
   1124 			}
   1125 
   1126 			if (sport != -1) {
   1127 				addargs(&alist, "-p");
   1128 				addargs(&alist, "%d", sport);
   1129 			}
   1130 			if (suser) {
   1131 				addargs(&alist, "-l");
   1132 				addargs(&alist, "%s", suser);
   1133 			}
   1134 			addargs(&alist, "--");
   1135 			addargs(&alist, "%s", host);
   1136 			addargs(&alist, "%s", cmd);
   1137 			addargs(&alist, "%s", src);
   1138 			addargs(&alist, "%s%s%s:%s",
   1139 			    tuser ? tuser : "", tuser ? "@" : "",
   1140 			    thost, targ);
   1141 			if (do_local_cmd(&alist) != 0)
   1142 				errs = 1;
   1143 		} else {	/* local to remote */
   1144 			if (mode == MODE_SFTP) {
   1145 				/* no need to glob: already done by shell */
   1146 				if (stat(argv[i], &sb) != 0) {
   1147 					fatal("stat local \"%s\": %s", argv[i],
   1148 					    strerror(errno));
   1149 				}
   1150 				if (remin == -1) {
   1151 					/* Connect to remote now */
   1152 					sftp_free(conn);
   1153 					conn = do_sftp_connect(thost, tuser,
   1154 					    tport, sftp_direct,
   1155 					    &remin, &remout, &do_cmd_pid);
   1156 					if (conn == NULL) {
   1157 						fatal("Unable to open sftp "
   1158 						    "connection");
   1159 					}
   1160 				}
   1161 
   1162 				/* The protocol */
   1163 				source_sftp(1, argv[i], targ, conn);
   1164 				continue;
   1165 			}
   1166 			/* SCP */
   1167 			if (remin == -1) {
   1168 				xasprintf(&bp, "%s -t %s%s", cmd,
   1169 				    *targ == '-' ? "-- " : "", targ);
   1170 				if (do_cmd(ssh_program, thost, tuser, tport, 0,
   1171 				    bp, &remin, &remout, &do_cmd_pid) < 0)
   1172 					exit(1);
   1173 				if (response() < 0)
   1174 					exit(1);
   1175 				free(bp);
   1176 			}
   1177 			source(1, argv + i);
   1178 		}
   1179 	}
   1180 out:
   1181 	freeargs(&alist);
   1182 	free(tuser);
   1183 	free(thost);
   1184 	free(targ);
   1185 	free(suser);
   1186 	free(host);
   1187 	free(src);
   1188 	sftp_free(conn);
   1189 	sftp_free(conn2);
   1190 }
   1191 
   1192 static void
   1193 tolocal(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
   1194 {
   1195 	char *bp, *host = NULL, *suser = NULL, *src = NULL;
   1196 	arglist alist;
   1197 	struct sftp_conn *conn = NULL;
   1198 	int i, r, sport = -1;
   1199 
   1200 	memset(&alist, '\0', sizeof(alist));
   1201 	alist.list = NULL;
   1202 
   1203 	for (i = 0; i < argc - 1; i++) {
   1204 		free(suser);
   1205 		free(host);
   1206 		free(src);
   1207 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
   1208 		if (r == -1) {
   1209 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
   1210 			++errs;
   1211 			continue;
   1212 		}
   1213 		if (r != 0)
   1214 			parse_user_host_path(argv[i], &suser, &host, &src);
   1215 		if (suser != NULL && !okname(suser)) {
   1216 			++errs;
   1217 			continue;
   1218 		}
   1219 		if (!host) {	/* Local to local. */
   1220 			freeargs(&alist);
   1221 			addargs(&alist, "%s", _PATH_CP);
   1222 			if (iamrecursive)
   1223 				addargs(&alist, "-r");
   1224 			if (pflag)
   1225 				addargs(&alist, "-p");
   1226 			addargs(&alist, "--");
   1227 			addargs(&alist, "%s", argv[i]);
   1228 			addargs(&alist, "%s", argv[argc-1]);
   1229 			if (do_local_cmd(&alist))
   1230 				++errs;
   1231 			continue;
   1232 		}
   1233 		/* Remote to local. */
   1234 		if (mode == MODE_SFTP) {
   1235 			sftp_free(conn);
   1236 			conn = do_sftp_connect(host, suser, sport,
   1237 			    sftp_direct, &remin, &remout, &do_cmd_pid);
   1238 			if (conn == NULL) {
   1239 				error("sftp connection failed");
   1240 				++errs;
   1241 				continue;
   1242 			}
   1243 
   1244 			/* The protocol */
   1245 			sink_sftp(1, argv[argc - 1], src, conn);
   1246 
   1247 			(void) close(remin);
   1248 			(void) close(remout);
   1249 			remin = remout = -1;
   1250 			continue;
   1251 		}
   1252 		/* SCP */
   1253 		xasprintf(&bp, "%s -f %s%s",
   1254 		    cmd, *src == '-' ? "-- " : "", src);
   1255 		if (do_cmd(ssh_program, host, suser, sport, 0, bp,
   1256 		    &remin, &remout, &do_cmd_pid) < 0) {
   1257 			free(bp);
   1258 			++errs;
   1259 			continue;
   1260 		}
   1261 		free(bp);
   1262 		sink(1, argv + argc - 1, src);
   1263 		(void) close(remin);
   1264 		remin = remout = -1;
   1265 	}
   1266 	freeargs(&alist);
   1267 	free(suser);
   1268 	free(host);
   1269 	free(src);
   1270 	sftp_free(conn);
   1271 }
   1272 
   1273 /* Prepare remote path, handling ~ by assuming cwd is the homedir */
   1274 static char *
   1275 prepare_remote_path(struct sftp_conn *conn, const char *path)
   1276 {
   1277 	size_t nslash;
   1278 
   1279 	/* Handle ~ prefixed paths */
   1280 	if (*path == '\0' || strcmp(path, "~") == 0)
   1281 		return xstrdup(".");
   1282 	if (*path != '~')
   1283 		return xstrdup(path);
   1284 	if (strncmp(path, "~/", 2) == 0) {
   1285 		if ((nslash = strspn(path + 2, "/")) == strlen(path + 2))
   1286 			return xstrdup(".");
   1287 		return xstrdup(path + 2 + nslash);
   1288 	}
   1289 	if (sftp_can_expand_path(conn))
   1290 		return sftp_expand_path(conn, path);
   1291 	/* No protocol extension */
   1292 	error("server expand-path extension is required "
   1293 	    "for ~user paths in SFTP mode");
   1294 	return NULL;
   1295 }
   1296 
   1297 void
   1298 source_sftp(int argc, char *src, char *targ, struct sftp_conn *conn)
   1299 {
   1300 	char *target = NULL, *abs_dst = NULL;
   1301 	const char *filename = NULL;
   1302 	int src_is_dir, target_is_dir;
   1303 	Attrib a;
   1304 	struct stat st;
   1305 
   1306 	memset(&a, '\0', sizeof(a));
   1307 	if (stat(src, &st) != 0)
   1308 		fatal("stat local \"%s\": %s", src, strerror(errno));
   1309 	src_is_dir = S_ISDIR(st.st_mode);
   1310 	if ((filename = basename(src)) == NULL)
   1311 		fatal("basename \"%s\": %s", src, strerror(errno));
   1312 
   1313 	/* Special handling for source of '..' */
   1314 	if (strcmp(filename, "..") == 0)
   1315 		filename = "."; /* Upload to dest, not dest/.. */
   1316 
   1317 	/*
   1318 	 * No need to glob here - the local shell already took care of
   1319 	 * the expansions
   1320 	 */
   1321 	if ((target = prepare_remote_path(conn, targ)) == NULL)
   1322 		cleanup_exit(255);
   1323 	target_is_dir = sftp_remote_is_dir(conn, target);
   1324 	if (targetshouldbedirectory && !target_is_dir) {
   1325 		debug("target directory \"%s\" does not exist", target);
   1326 		a.flags = SSH2_FILEXFER_ATTR_PERMISSIONS;
   1327 		a.perm = st.st_mode | 0700; /* ensure writable */
   1328 		if (sftp_mkdir(conn, target, &a, 1) != 0)
   1329 			cleanup_exit(255); /* error already logged */
   1330 		target_is_dir = 1;
   1331 	}
   1332 	if (target_is_dir)
   1333 		abs_dst = sftp_path_append(target, filename);
   1334 	else {
   1335 		abs_dst = target;
   1336 		target = NULL;
   1337 	}
   1338 	debug3_f("copying local %s to remote %s", src, abs_dst);
   1339 
   1340 	if (src_is_dir && iamrecursive) {
   1341 		if (sftp_upload_dir(conn, src, abs_dst, pflag,
   1342 		    SFTP_PROGRESS_ONLY, 0, 0, 1, 1) != 0) {
   1343 			error("failed to upload directory %s to %s", src, targ);
   1344 			errs = 1;
   1345 		}
   1346 	} else if (sftp_upload(conn, src, abs_dst, pflag, 0, 0, 1) != 0) {
   1347 		error("failed to upload file %s to %s", src, targ);
   1348 		errs = 1;
   1349 	}
   1350 
   1351 	free(abs_dst);
   1352 	free(target);
   1353 }
   1354 
   1355 void
   1356 source(int argc, char **argv)
   1357 {
   1358 	struct stat stb;
   1359 	static BUF buffer;
   1360 	BUF *bp;
   1361 	off_t i, statbytes;
   1362 	size_t amt, nr;
   1363 	int fd = -1, haderr, indx;
   1364 	char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
   1365 	int len;
   1366 
   1367 	for (indx = 0; indx < argc; ++indx) {
   1368 		fd = -1;
   1369 		name = argv[indx];
   1370 		statbytes = 0;
   1371 		len = strlen(name);
   1372 		while (len > 1 && name[len-1] == '/')
   1373 			name[--len] = '\0';
   1374 		if ((fd = open(name, O_RDONLY|O_NONBLOCK)) == -1)
   1375 			goto syserr;
   1376 		if (strchr(name, '\n') != NULL) {
   1377 			strvisx(encname, name, len, VIS_NL);
   1378 			name = encname;
   1379 		}
   1380 		if (fstat(fd, &stb) == -1) {
   1381 syserr:			run_err("%s: %s", name, strerror(errno));
   1382 			goto next;
   1383 		}
   1384 		if (stb.st_size < 0) {
   1385 			run_err("%s: %s", name, "Negative file size");
   1386 			goto next;
   1387 		}
   1388 		unset_nonblock(fd);
   1389 		switch (stb.st_mode & S_IFMT) {
   1390 		case S_IFREG:
   1391 			break;
   1392 		case S_IFDIR:
   1393 			if (iamrecursive) {
   1394 				rsource(name, &stb);
   1395 				goto next;
   1396 			}
   1397 			/* FALLTHROUGH */
   1398 		default:
   1399 			run_err("%s: not a regular file", name);
   1400 			goto next;
   1401 		}
   1402 		if ((last = strrchr(name, '/')) == NULL)
   1403 			last = name;
   1404 		else
   1405 			++last;
   1406 		curfile = last;
   1407 		if (pflag) {
   1408 			if (do_times(remout, verbose_mode, &stb) < 0)
   1409 				goto next;
   1410 		}
   1411 #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
   1412 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
   1413 		    (u_int) (stb.st_mode & FILEMODEMASK),
   1414 		    (long long)stb.st_size, last);
   1415 		if (verbose_mode)
   1416 			fmprintf(stderr, "Sending file modes: %s", buf);
   1417 		(void) atomicio(vwrite, remout, buf, strlen(buf));
   1418 		if (response() < 0)
   1419 			goto next;
   1420 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
   1421 next:			if (fd != -1) {
   1422 				(void) close(fd);
   1423 				fd = -1;
   1424 			}
   1425 			continue;
   1426 		}
   1427 		if (showprogress)
   1428 			start_progress_meter(curfile, stb.st_size, &statbytes);
   1429 		set_nonblock(remout);
   1430 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
   1431 			amt = bp->cnt;
   1432 			if (i + (off_t)amt > stb.st_size)
   1433 				amt = stb.st_size - i;
   1434 			if (!haderr) {
   1435 				if ((nr = atomicio(read, fd,
   1436 				    bp->buf, amt)) != amt) {
   1437 					haderr = errno;
   1438 					memset(bp->buf + nr, 0, amt - nr);
   1439 				}
   1440 			}
   1441 			/* Keep writing after error to retain sync */
   1442 			if (haderr) {
   1443 				(void)atomicio(vwrite, remout, bp->buf, amt);
   1444 				memset(bp->buf, 0, amt);
   1445 				continue;
   1446 			}
   1447 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
   1448 			    &statbytes) != amt)
   1449 				haderr = errno;
   1450 		}
   1451 		unset_nonblock(remout);
   1452 
   1453 		if (fd != -1) {
   1454 			if (close(fd) == -1 && !haderr)
   1455 				haderr = errno;
   1456 			fd = -1;
   1457 		}
   1458 		if (!haderr)
   1459 			(void) atomicio(vwrite, remout, empty, 1);
   1460 		else
   1461 			run_err("%s: %s", name, strerror(haderr));
   1462 		(void) response();
   1463 		if (showprogress)
   1464 			stop_progress_meter();
   1465 	}
   1466 }
   1467 
   1468 void
   1469 rsource(char *name, struct stat *statp)
   1470 {
   1471 	DIR *dirp;
   1472 	struct dirent *dp;
   1473 	char *last, *vect[1], path[PATH_MAX + 20];
   1474 
   1475 	if (!(dirp = opendir(name))) {
   1476 		run_err("%s: %s", name, strerror(errno));
   1477 		return;
   1478 	}
   1479 	last = strrchr(name, '/');
   1480 	if (last == NULL)
   1481 		last = name;
   1482 	else
   1483 		last++;
   1484 	if (pflag) {
   1485 		if (do_times(remout, verbose_mode, statp) < 0) {
   1486 			closedir(dirp);
   1487 			return;
   1488 		}
   1489 	}
   1490 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
   1491 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
   1492 	if (verbose_mode)
   1493 		fmprintf(stderr, "Entering directory: %s", path);
   1494 	(void) atomicio(vwrite, remout, path, strlen(path));
   1495 	if (response() < 0) {
   1496 		closedir(dirp);
   1497 		return;
   1498 	}
   1499 	while ((dp = readdir(dirp)) != NULL) {
   1500 		if (dp->d_ino == 0)
   1501 			continue;
   1502 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
   1503 			continue;
   1504 		if ((size_t)snprintf(path, sizeof path, "%s/%s",
   1505 		    name, dp->d_name) >= sizeof path) {
   1506 			run_err("%s/%s: name too long", name, dp->d_name);
   1507 			continue;
   1508 		}
   1509 		vect[0] = path;
   1510 		source(1, vect);
   1511 	}
   1512 	(void) closedir(dirp);
   1513 	(void) atomicio(vwrite, remout, __UNCONST("E\n"), 2);
   1514 	(void) response();
   1515 }
   1516 
   1517 void
   1518 sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn)
   1519 {
   1520 	char *abs_src = NULL;
   1521 	char *abs_dst = NULL;
   1522 	glob_t g;
   1523 	const char *filename;
   1524 	char *tmp = NULL;
   1525 	int i, r, err = 0, dst_is_dir;
   1526 	struct stat st;
   1527 
   1528 	memset(&g, 0, sizeof(g));
   1529 
   1530 	/*
   1531 	 * Here, we need remote glob as SFTP can not depend on remote shell
   1532 	 * expansions
   1533 	 */
   1534 	if ((abs_src = prepare_remote_path(conn, src)) == NULL) {
   1535 		err = -1;
   1536 		goto out;
   1537 	}
   1538 
   1539 	debug3_f("copying remote %s to local %s", abs_src, dst);
   1540 	if ((r = sftp_glob(conn, abs_src, GLOB_NOCHECK|GLOB_MARK,
   1541 	    NULL, &g)) != 0) {
   1542 		if (r == GLOB_NOSPACE)
   1543 			error("%s: too many glob matches", src);
   1544 		else
   1545 			error("%s: %s", src, strerror(ENOENT));
   1546 		err = -1;
   1547 		goto out;
   1548 	}
   1549 
   1550 	/* Did we actually get any matches back from the glob? */
   1551 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != NULL) {
   1552 		/*
   1553 		 * If nothing matched but a path returned, then it's probably
   1554 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
   1555 		 * exists so we can give a nice error message early.
   1556 		 */
   1557 		if (sftp_stat(conn, g.gl_pathv[0], 1, NULL) != 0) {
   1558 			error("%s: %s", src, strerror(ENOENT));
   1559 			err = -1;
   1560 			goto out;
   1561 		}
   1562 	}
   1563 
   1564 	if ((r = stat(dst, &st)) != 0)
   1565 		debug2_f("stat local \"%s\": %s", dst, strerror(errno));
   1566 	dst_is_dir = r == 0 && S_ISDIR(st.st_mode);
   1567 
   1568 	if (g.gl_matchc > 1 && !dst_is_dir) {
   1569 		if (r == 0) {
   1570 			error("Multiple files match pattern, but destination "
   1571 			    "\"%s\" is not a directory", dst);
   1572 			err = -1;
   1573 			goto out;
   1574 		}
   1575 		debug2_f("creating destination \"%s\"", dst);
   1576 		if (mkdir(dst, 0777) != 0) {
   1577 			error("local mkdir \"%s\": %s", dst, strerror(errno));
   1578 			err = -1;
   1579 			goto out;
   1580 		}
   1581 		dst_is_dir = 1;
   1582 	}
   1583 
   1584 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
   1585 		tmp = xstrdup(g.gl_pathv[i]);
   1586 		if ((filename = basename(tmp)) == NULL) {
   1587 			error("basename %s: %s", tmp, strerror(errno));
   1588 			err = -1;
   1589 			goto out;
   1590 		}
   1591 
   1592 		/* Special handling for destination of '..' */
   1593 		if (strcmp(filename, "..") == 0)
   1594 			filename = "."; /* Download to dest, not dest/.. */
   1595 
   1596 		if (dst_is_dir)
   1597 			abs_dst = sftp_path_append(dst, filename);
   1598 		else
   1599 			abs_dst = xstrdup(dst);
   1600 
   1601 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
   1602 		if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
   1603 			if (sftp_download_dir(conn, g.gl_pathv[i], abs_dst,
   1604 			    NULL, pflag, SFTP_PROGRESS_ONLY, 0, 0, 1, 1) == -1)
   1605 				err = -1;
   1606 		} else {
   1607 			if (sftp_download(conn, g.gl_pathv[i], abs_dst, NULL,
   1608 			    pflag, 0, 0, 1) == -1)
   1609 				err = -1;
   1610 		}
   1611 		free(abs_dst);
   1612 		abs_dst = NULL;
   1613 		free(tmp);
   1614 		tmp = NULL;
   1615 	}
   1616 
   1617 out:
   1618 	free(abs_src);
   1619 	free(tmp);
   1620 	globfree(&g);
   1621 	if (err == -1)
   1622 		errs = 1;
   1623 }
   1624 
   1625 
   1626 #define TYPE_OVERFLOW(type, val) \
   1627 	((sizeof(type) == 4 && (val) > INT32_MAX) || \
   1628 	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
   1629 	 (sizeof(type) != 4 && sizeof(type) != 8))
   1630 
   1631 void
   1632 sink(int argc, char **argv, const char *src)
   1633 {
   1634 	static BUF buffer;
   1635 	struct stat stb;
   1636 	BUF *bp;
   1637 	off_t i;
   1638 	size_t j, count;
   1639 	int amt, exists, first, ofd;
   1640 	mode_t mode, omode, mask;
   1641 	off_t size, statbytes;
   1642 	unsigned long long ull;
   1643 	int setimes, targisdir, wrerr;
   1644 	char ch, *cp, *np, *targ, *vect[1], buf[2048], visbuf[2048];
   1645 	const char *why;
   1646 	char **patterns = NULL;
   1647 	size_t n, npatterns = 0;
   1648 	struct timeval tv[2];
   1649 
   1650 #define	atime	tv[0]
   1651 #define	mtime	tv[1]
   1652 #define	SCREWUP(str)	{ why = str; goto screwup; }
   1653 
   1654 	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
   1655 		SCREWUP("Unexpected off_t/time_t size");
   1656 
   1657 	setimes = targisdir = 0;
   1658 	mask = umask(0);
   1659 	if (!pflag) {
   1660 		mask |= 07000;
   1661 		(void) umask(mask);
   1662 	}
   1663 	if (argc != 1) {
   1664 		run_err("ambiguous target");
   1665 		exit(1);
   1666 	}
   1667 	targ = *argv;
   1668 	if (targetshouldbedirectory)
   1669 		verifydir(targ);
   1670 
   1671 	(void) atomicio(vwrite, remout, empty, 1);
   1672 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
   1673 		targisdir = 1;
   1674 	if (src != NULL && !iamrecursive && !Tflag) {
   1675 		/*
   1676 		 * Prepare to try to restrict incoming filenames to match
   1677 		 * the requested destination file glob.
   1678 		 */
   1679 		if (brace_expand(src, &patterns, &npatterns) != 0)
   1680 			fatal_f("could not expand pattern");
   1681 	}
   1682 	for (first = 1;; first = 0) {
   1683 		cp = buf;
   1684 		if (atomicio(read, remin, cp, 1) != 1)
   1685 			goto done;
   1686 		if (*cp++ == '\n')
   1687 			SCREWUP("unexpected <newline>");
   1688 		do {
   1689 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
   1690 				SCREWUP("lost connection");
   1691 			*cp++ = ch;
   1692 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
   1693 		*cp = 0;
   1694 		if (verbose_mode)
   1695 			fmprintf(stderr, "Sink: %s", buf);
   1696 
   1697 		if (buf[0] == '\01' || buf[0] == '\02') {
   1698 			if (iamremote == 0) {
   1699 				(void) snmprintf(visbuf, sizeof(visbuf),
   1700 				    NULL, "%s", buf + 1);
   1701 				(void) atomicio(vwrite, STDERR_FILENO,
   1702 				    visbuf, strlen(visbuf));
   1703 			}
   1704 			if (buf[0] == '\02')
   1705 				exit(1);
   1706 			++errs;
   1707 			continue;
   1708 		}
   1709 		if (buf[0] == 'E') {
   1710 			(void) atomicio(vwrite, remout, __UNCONST(""), 1);
   1711 			goto done;
   1712 		}
   1713 		if (ch == '\n')
   1714 			*--cp = 0;
   1715 
   1716 		cp = buf;
   1717 		if (*cp == 'T') {
   1718 			setimes++;
   1719 			cp++;
   1720 			if (!isdigit((unsigned char)*cp))
   1721 				SCREWUP("mtime.sec not present");
   1722 			ull = strtoull(cp, &cp, 10);
   1723 			if (!cp || *cp++ != ' ')
   1724 				SCREWUP("mtime.sec not delimited");
   1725 			if (TYPE_OVERFLOW(time_t, ull))
   1726 				setimes = 0;	/* out of range */
   1727 			mtime.tv_sec = ull;
   1728 			mtime.tv_usec = strtol(cp, &cp, 10);
   1729 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
   1730 			    mtime.tv_usec > 999999)
   1731 				SCREWUP("mtime.usec not delimited");
   1732 			if (!isdigit((unsigned char)*cp))
   1733 				SCREWUP("atime.sec not present");
   1734 			ull = strtoull(cp, &cp, 10);
   1735 			if (!cp || *cp++ != ' ')
   1736 				SCREWUP("atime.sec not delimited");
   1737 			if (TYPE_OVERFLOW(time_t, ull))
   1738 				setimes = 0;	/* out of range */
   1739 			atime.tv_sec = ull;
   1740 			atime.tv_usec = strtol(cp, &cp, 10);
   1741 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
   1742 			    atime.tv_usec > 999999)
   1743 				SCREWUP("atime.usec not delimited");
   1744 			(void) atomicio(vwrite, remout, empty, 1);
   1745 			continue;
   1746 		}
   1747 		if (*cp != 'C' && *cp != 'D') {
   1748 			/*
   1749 			 * Check for the case "rcp remote:foo\* local:bar".
   1750 			 * In this case, the line "No match." can be returned
   1751 			 * by the shell before the rcp command on the remote is
   1752 			 * executed so the ^Aerror_message convention isn't
   1753 			 * followed.
   1754 			 */
   1755 			if (first) {
   1756 				run_err("%s", cp);
   1757 				exit(1);
   1758 			}
   1759 			SCREWUP("expected control record");
   1760 		}
   1761 		mode = 0;
   1762 		for (++cp; cp < buf + 5; cp++) {
   1763 			if (*cp < '0' || *cp > '7')
   1764 				SCREWUP("bad mode");
   1765 			mode = (mode << 3) | (*cp - '0');
   1766 		}
   1767 		if (!pflag)
   1768 			mode &= ~mask;
   1769 		if (*cp++ != ' ')
   1770 			SCREWUP("mode not delimited");
   1771 
   1772 		if (!isdigit((unsigned char)*cp))
   1773 			SCREWUP("size not present");
   1774 		ull = strtoull(cp, &cp, 10);
   1775 		if (!cp || *cp++ != ' ')
   1776 			SCREWUP("size not delimited");
   1777 		if (TYPE_OVERFLOW(off_t, ull))
   1778 			SCREWUP("size out of range");
   1779 		size = (off_t)ull;
   1780 
   1781 		if (*cp == '\0' || strchr(cp, '/') != NULL ||
   1782 		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
   1783 			run_err("error: unexpected filename: %s", cp);
   1784 			exit(1);
   1785 		}
   1786 		if (npatterns > 0) {
   1787 			for (n = 0; n < npatterns; n++) {
   1788 				if (strcmp(patterns[n], cp) == 0 ||
   1789 				    fnmatch(patterns[n], cp, 0) == 0)
   1790 					break;
   1791 			}
   1792 			if (n >= npatterns) {
   1793 				debug2_f("incoming filename \"%s\" does not "
   1794 				    "match any of %zu expected patterns", cp,
   1795 				    npatterns);
   1796 				for (n = 0; n < npatterns; n++) {
   1797 					debug3_f("expected pattern %zu: \"%s\"",
   1798 					    n, patterns[n]);
   1799 				}
   1800 				SCREWUP("filename does not match request");
   1801 			}
   1802 		}
   1803 		if (targisdir) {
   1804 			static char *namebuf;
   1805 			static size_t cursize;
   1806 			size_t need;
   1807 
   1808 			need = strlen(targ) + strlen(cp) + 250;
   1809 			if (need > cursize) {
   1810 				free(namebuf);
   1811 				namebuf = xmalloc(need);
   1812 				cursize = need;
   1813 			}
   1814 			(void) snprintf(namebuf, need, "%s%s%s", targ,
   1815 			    strcmp(targ, "/") ? "/" : "", cp);
   1816 			np = namebuf;
   1817 		} else
   1818 			np = targ;
   1819 		curfile = cp;
   1820 		exists = stat(np, &stb) == 0;
   1821 		if (buf[0] == 'D') {
   1822 			int mod_flag = pflag;
   1823 			if (!iamrecursive)
   1824 				SCREWUP("received directory without -r");
   1825 			if (exists) {
   1826 				if (!S_ISDIR(stb.st_mode)) {
   1827 					errno = ENOTDIR;
   1828 					goto bad;
   1829 				}
   1830 				if (pflag)
   1831 					(void) chmod(np, mode);
   1832 			} else {
   1833 				/* Handle copying from a read-only directory */
   1834 				mod_flag = 1;
   1835 				if (mkdir(np, mode | S_IRWXU) == -1)
   1836 					goto bad;
   1837 			}
   1838 			vect[0] = xstrdup(np);
   1839 			sink(1, vect, src);
   1840 			if (setimes) {
   1841 				setimes = 0;
   1842 				(void) utimes(vect[0], tv);
   1843 			}
   1844 			if (mod_flag)
   1845 				(void) chmod(vect[0], mode);
   1846 			free(vect[0]);
   1847 			continue;
   1848 		}
   1849 		omode = mode;
   1850 		mode |= S_IWUSR;
   1851 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
   1852 bad:			run_err("%s: %s", np, strerror(errno));
   1853 			continue;
   1854 		}
   1855 		(void) atomicio(vwrite, remout, empty, 1);
   1856 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
   1857 			(void) close(ofd);
   1858 			continue;
   1859 		}
   1860 		cp = bp->buf;
   1861 		wrerr = 0;
   1862 
   1863 		/*
   1864 		 * NB. do not use run_err() unless immediately followed by
   1865 		 * exit() below as it may send a spurious reply that might
   1866 		 * desynchronise us from the peer. Use note_err() instead.
   1867 		 */
   1868 		statbytes = 0;
   1869 		if (showprogress)
   1870 			start_progress_meter(curfile, size, &statbytes);
   1871 		set_nonblock(remin);
   1872 		for (count = i = 0; i < size; i += bp->cnt) {
   1873 			amt = bp->cnt;
   1874 			if (i + amt > size)
   1875 				amt = size - i;
   1876 			count += amt;
   1877 			do {
   1878 				j = atomicio6(read, remin, cp, amt,
   1879 				    scpio, &statbytes);
   1880 				if (j == 0) {
   1881 					run_err("%s", j != EPIPE ?
   1882 					    strerror(errno) :
   1883 					    "dropped connection");
   1884 					exit(1);
   1885 				}
   1886 				amt -= j;
   1887 				cp += j;
   1888 			} while (amt > 0);
   1889 
   1890 			if (count == bp->cnt) {
   1891 				/* Keep reading so we stay sync'd up. */
   1892 				if (!wrerr) {
   1893 					if (atomicio(vwrite, ofd, bp->buf,
   1894 					    count) != count) {
   1895 						note_err("%s: %s", np,
   1896 						    strerror(errno));
   1897 						wrerr = 1;
   1898 					}
   1899 				}
   1900 				count = 0;
   1901 				cp = bp->buf;
   1902 			}
   1903 		}
   1904 		unset_nonblock(remin);
   1905 		if (count != 0 && !wrerr &&
   1906 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
   1907 			note_err("%s: %s", np, strerror(errno));
   1908 			wrerr = 1;
   1909 		}
   1910 		if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
   1911 		    ftruncate(ofd, size) != 0)
   1912 			note_err("%s: truncate: %s", np, strerror(errno));
   1913 		if (pflag) {
   1914 			if (exists || omode != mode)
   1915 				if (fchmod(ofd, omode)) {
   1916 					note_err("%s: set mode: %s",
   1917 					    np, strerror(errno));
   1918 				}
   1919 		} else {
   1920 			if (!exists && omode != mode)
   1921 				if (fchmod(ofd, omode & ~mask)) {
   1922 					note_err("%s: set mode: %s",
   1923 					    np, strerror(errno));
   1924 				}
   1925 		}
   1926 		if (close(ofd) == -1)
   1927 			note_err("%s: close: %s", np, strerror(errno));
   1928 		(void) response();
   1929 		if (showprogress)
   1930 			stop_progress_meter();
   1931 		if (setimes && !wrerr) {
   1932 			setimes = 0;
   1933 			if (utimes(np, tv) == -1) {
   1934 				note_err("%s: set times: %s",
   1935 				    np, strerror(errno));
   1936 			}
   1937 		}
   1938 		/* If no error was noted then signal success for this file */
   1939 		if (note_err(NULL) == 0)
   1940 			(void) atomicio(vwrite, remout, __UNCONST(""), 1);
   1941 	}
   1942 done:
   1943 	for (n = 0; n < npatterns; n++)
   1944 		free(patterns[n]);
   1945 	free(patterns);
   1946 	return;
   1947 screwup:
   1948 	for (n = 0; n < npatterns; n++)
   1949 		free(patterns[n]);
   1950 	free(patterns);
   1951 	run_err("protocol error: %s", why);
   1952 	exit(1);
   1953 }
   1954 
   1955 void
   1956 throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
   1957     char *src, char *targ)
   1958 {
   1959 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
   1960 	char *abs_src = NULL, *tmp = NULL;
   1961 	glob_t g;
   1962 	int i, r, targetisdir, err = 0;
   1963 
   1964 	if ((filename = basename(src)) == NULL)
   1965 		fatal("basename %s: %s", src, strerror(errno));
   1966 
   1967 	if ((abs_src = prepare_remote_path(from, src)) == NULL ||
   1968 	    (target = prepare_remote_path(to, targ)) == NULL)
   1969 		cleanup_exit(255);
   1970 	memset(&g, 0, sizeof(g));
   1971 
   1972 	targetisdir = sftp_remote_is_dir(to, target);
   1973 	if (!targetisdir && targetshouldbedirectory) {
   1974 		error("%s: destination is not a directory", targ);
   1975 		err = -1;
   1976 		goto out;
   1977 	}
   1978 
   1979 	debug3_f("copying remote %s to remote %s", abs_src, target);
   1980 	if ((r = sftp_glob(from, abs_src, GLOB_NOCHECK|GLOB_MARK,
   1981 	    NULL, &g)) != 0) {
   1982 		if (r == GLOB_NOSPACE)
   1983 			error("%s: too many glob matches", src);
   1984 		else
   1985 			error("%s: %s", src, strerror(ENOENT));
   1986 		err = -1;
   1987 		goto out;
   1988 	}
   1989 
   1990 	/* Did we actually get any matches back from the glob? */
   1991 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != NULL) {
   1992 		/*
   1993 		 * If nothing matched but a path returned, then it's probably
   1994 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
   1995 		 * exists so we can give a nice error message early.
   1996 		 */
   1997 		if (sftp_stat(from, g.gl_pathv[0], 1, NULL) != 0) {
   1998 			error("%s: %s", src, strerror(ENOENT));
   1999 			err = -1;
   2000 			goto out;
   2001 		}
   2002 	}
   2003 
   2004 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
   2005 		tmp = xstrdup(g.gl_pathv[i]);
   2006 		if ((filename = basename(tmp)) == NULL) {
   2007 			error("basename %s: %s", tmp, strerror(errno));
   2008 			err = -1;
   2009 			goto out;
   2010 		}
   2011 
   2012 		if (targetisdir)
   2013 			abs_dst = sftp_path_append(target, filename);
   2014 		else
   2015 			abs_dst = xstrdup(target);
   2016 
   2017 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
   2018 		if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
   2019 			if (sftp_crossload_dir(from, to, g.gl_pathv[i], abs_dst,
   2020 			    NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
   2021 				err = -1;
   2022 		} else {
   2023 			if (sftp_crossload(from, to, g.gl_pathv[i], abs_dst,
   2024 			    NULL, pflag) == -1)
   2025 				err = -1;
   2026 		}
   2027 		free(abs_dst);
   2028 		abs_dst = NULL;
   2029 		free(tmp);
   2030 		tmp = NULL;
   2031 	}
   2032 
   2033 out:
   2034 	free(abs_src);
   2035 	free(abs_dst);
   2036 	free(target);
   2037 	free(tmp);
   2038 	globfree(&g);
   2039 	if (err == -1)
   2040 		errs = 1;
   2041 }
   2042 
   2043 int
   2044 response(void)
   2045 {
   2046 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
   2047 
   2048 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
   2049 		lostconn(0);
   2050 
   2051 	cp = rbuf;
   2052 	switch (resp) {
   2053 	case 0:		/* ok */
   2054 		return (0);
   2055 	default:
   2056 		*cp++ = resp;
   2057 		/* FALLTHROUGH */
   2058 	case 1:		/* error, followed by error msg */
   2059 	case 2:		/* fatal error, "" */
   2060 		do {
   2061 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
   2062 				lostconn(0);
   2063 			*cp++ = ch;
   2064 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
   2065 
   2066 		if (!iamremote) {
   2067 			cp[-1] = '\0';
   2068 			(void) snmprintf(visbuf, sizeof(visbuf),
   2069 			    NULL, "%s\n", rbuf);
   2070 			(void) atomicio(vwrite, STDERR_FILENO,
   2071 			    visbuf, strlen(visbuf));
   2072 		}
   2073 		++errs;
   2074 		if (resp == 1)
   2075 			return (-1);
   2076 		exit(1);
   2077 	}
   2078 	/* NOTREACHED */
   2079 }
   2080 
   2081 static void
   2082 usage(void)
   2083 {
   2084 	(void) fprintf(stderr,
   2085 	    "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
   2086 	    "           [-i identity_file] [-J destination] [-l limit] [-o ssh_option]\n"
   2087 	    "           [-P port] [-S program] [-X sftp_option] source ... target\n");
   2088 	exit(1);
   2089 }
   2090 
   2091 void
   2092 run_err(const char *fmt,...)
   2093 {
   2094 	static FILE *fp;
   2095 	va_list ap;
   2096 
   2097 	++errs;
   2098 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
   2099 		(void) fprintf(fp, "%c", 0x01);
   2100 		(void) fprintf(fp, "scp: ");
   2101 		va_start(ap, fmt);
   2102 		(void) vfprintf(fp, fmt, ap);
   2103 		va_end(ap);
   2104 		(void) fprintf(fp, "\n");
   2105 		(void) fflush(fp);
   2106 	}
   2107 
   2108 	if (!iamremote) {
   2109 		va_start(ap, fmt);
   2110 		vfmprintf(stderr, fmt, ap);
   2111 		va_end(ap);
   2112 		fprintf(stderr, "\n");
   2113 	}
   2114 }
   2115 
   2116 /*
   2117  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
   2118  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
   2119  * any active error at the end of the transfer.
   2120  */
   2121 int
   2122 note_err(const char *fmt, ...)
   2123 {
   2124 	static char *emsg;
   2125 	va_list ap;
   2126 
   2127 	/* Replay any previously-noted error */
   2128 	if (fmt == NULL) {
   2129 		if (emsg == NULL)
   2130 			return 0;
   2131 		run_err("%s", emsg);
   2132 		free(emsg);
   2133 		emsg = NULL;
   2134 		return -1;
   2135 	}
   2136 
   2137 	errs++;
   2138 	/* Prefer first-noted error */
   2139 	if (emsg != NULL)
   2140 		return -1;
   2141 
   2142 	va_start(ap, fmt);
   2143 	vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
   2144 	va_end(ap);
   2145 	return -1;
   2146 }
   2147 
   2148 void
   2149 verifydir(char *cp)
   2150 {
   2151 	struct stat stb;
   2152 
   2153 	if (!stat(cp, &stb)) {
   2154 		if (S_ISDIR(stb.st_mode))
   2155 			return;
   2156 		errno = ENOTDIR;
   2157 	}
   2158 	run_err("%s: %s", cp, strerror(errno));
   2159 	killchild(0);
   2160 }
   2161 
   2162 int
   2163 okname(char *cp0)
   2164 {
   2165 	int c;
   2166 	char *cp;
   2167 
   2168 	cp = cp0;
   2169 	do {
   2170 		c = (int)*cp;
   2171 		if (c & 0200)
   2172 			goto bad;
   2173 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
   2174 			switch (c) {
   2175 			case '\'':
   2176 			case '"':
   2177 			case '`':
   2178 			case ' ':
   2179 			case '#':
   2180 				goto bad;
   2181 			default:
   2182 				break;
   2183 			}
   2184 		}
   2185 	} while (*++cp);
   2186 	return (1);
   2187 
   2188 bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
   2189 	return (0);
   2190 }
   2191 
   2192 BUF *
   2193 allocbuf(BUF *bp, int fd, int blksize)
   2194 {
   2195 	size_t size;
   2196 	struct stat stb;
   2197 
   2198 	if (fstat(fd, &stb) == -1) {
   2199 		run_err("fstat: %s", strerror(errno));
   2200 		return (NULL);
   2201 	}
   2202 	size = ROUNDUP(stb.st_blksize, blksize);
   2203 	if (size == 0)
   2204 		size = blksize;
   2205 	if (bp->cnt >= size)
   2206 		return (bp);
   2207 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
   2208 	bp->cnt = size;
   2209 	return (bp);
   2210 }
   2211 
   2212 static void
   2213 lostconn(int signo)
   2214 {
   2215 	if (!iamremote)
   2216 		(void)write(STDERR_FILENO, "lost connection\n", 16);
   2217 	if (signo)
   2218 		_exit(1);
   2219 	else
   2220 		exit(1);
   2221 }
   2222 
   2223 void
   2224 cleanup_exit(int i)
   2225 {
   2226 	if (remin > 0)
   2227 		close(remin);
   2228 	if (remout > 0)
   2229 		close(remout);
   2230 	if (remin2 > 0)
   2231 		close(remin2);
   2232 	if (remout2 > 0)
   2233 		close(remout2);
   2234 	if (do_cmd_pid > 0)
   2235 		(void)waitpid(do_cmd_pid, NULL, 0);
   2236 	if (do_cmd_pid2 > 0)
   2237 		(void)waitpid(do_cmd_pid2, NULL, 0);
   2238 	exit(i);
   2239 }
   2240