xref: /freebsd/crypto/openssh/scp.c (revision 1323ec57)
11323ec57SEd Maste /* $OpenBSD: scp.c,v 1.245 2022/02/10 04:12:38 djm Exp $ */
2511b41d2SMark Murray /*
3b66f2d16SKris Kennaway  * scp - secure remote copy.  This is basically patched BSD rcp which
4b66f2d16SKris Kennaway  * uses ssh to do the data transfer (instead of using rcmd).
5511b41d2SMark Murray  *
6b66f2d16SKris Kennaway  * NOTE: This version should NOT be suid root.  (This uses ssh to
7b66f2d16SKris Kennaway  * do the transfer and ssh has the necessary privileges.)
8511b41d2SMark Murray  *
9511b41d2SMark Murray  * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
10511b41d2SMark Murray  *
11b66f2d16SKris Kennaway  * As far as I am concerned, the code I have written for this software
12b66f2d16SKris Kennaway  * can be used freely for any purpose.  Any derived versions of this
13b66f2d16SKris Kennaway  * software must be clearly marked as such, and if the derived work is
14b66f2d16SKris Kennaway  * incompatible with the protocol description in the RFC file, it must be
15b66f2d16SKris Kennaway  * called by a name other than "ssh" or "Secure Shell".
16b66f2d16SKris Kennaway  */
17b66f2d16SKris Kennaway /*
18b66f2d16SKris Kennaway  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
19b66f2d16SKris Kennaway  * Copyright (c) 1999 Aaron Campbell.  All rights reserved.
20b66f2d16SKris Kennaway  *
21b66f2d16SKris Kennaway  * Redistribution and use in source and binary forms, with or without
22b66f2d16SKris Kennaway  * modification, are permitted provided that the following conditions
23b66f2d16SKris Kennaway  * are met:
24b66f2d16SKris Kennaway  * 1. Redistributions of source code must retain the above copyright
25b66f2d16SKris Kennaway  *    notice, this list of conditions and the following disclaimer.
26b66f2d16SKris Kennaway  * 2. Redistributions in binary form must reproduce the above copyright
27b66f2d16SKris Kennaway  *    notice, this list of conditions and the following disclaimer in the
28b66f2d16SKris Kennaway  *    documentation and/or other materials provided with the distribution.
29b66f2d16SKris Kennaway  *
30b66f2d16SKris Kennaway  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31b66f2d16SKris Kennaway  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32b66f2d16SKris Kennaway  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33b66f2d16SKris Kennaway  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34b66f2d16SKris Kennaway  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35b66f2d16SKris Kennaway  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36b66f2d16SKris Kennaway  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37b66f2d16SKris Kennaway  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38b66f2d16SKris Kennaway  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39b66f2d16SKris Kennaway  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40511b41d2SMark Murray  */
41511b41d2SMark Murray 
42511b41d2SMark Murray /*
43b66f2d16SKris Kennaway  * Parts from:
44b66f2d16SKris Kennaway  *
45511b41d2SMark Murray  * Copyright (c) 1983, 1990, 1992, 1993, 1995
46511b41d2SMark Murray  *	The Regents of the University of California.  All rights reserved.
47511b41d2SMark Murray  *
48511b41d2SMark Murray  * Redistribution and use in source and binary forms, with or without
49511b41d2SMark Murray  * modification, are permitted provided that the following conditions
50511b41d2SMark Murray  * are met:
51511b41d2SMark Murray  * 1. Redistributions of source code must retain the above copyright
52511b41d2SMark Murray  *    notice, this list of conditions and the following disclaimer.
53511b41d2SMark Murray  * 2. Redistributions in binary form must reproduce the above copyright
54511b41d2SMark Murray  *    notice, this list of conditions and the following disclaimer in the
55511b41d2SMark Murray  *    documentation and/or other materials provided with the distribution.
56cf2b5f3bSDag-Erling Smørgrav  * 3. Neither the name of the University nor the names of its contributors
57511b41d2SMark Murray  *    may be used to endorse or promote products derived from this software
58511b41d2SMark Murray  *    without specific prior written permission.
59511b41d2SMark Murray  *
60511b41d2SMark Murray  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61511b41d2SMark Murray  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62511b41d2SMark Murray  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63511b41d2SMark Murray  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64511b41d2SMark Murray  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65511b41d2SMark Murray  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66511b41d2SMark Murray  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67511b41d2SMark Murray  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68511b41d2SMark Murray  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69511b41d2SMark Murray  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70511b41d2SMark Murray  * SUCH DAMAGE.
71511b41d2SMark Murray  *
72511b41d2SMark Murray  */
73511b41d2SMark Murray 
74511b41d2SMark Murray #include "includes.h"
75333ee039SDag-Erling Smørgrav 
76333ee039SDag-Erling Smørgrav #include <sys/types.h>
77333ee039SDag-Erling Smørgrav #ifdef HAVE_SYS_STAT_H
78333ee039SDag-Erling Smørgrav # include <sys/stat.h>
79333ee039SDag-Erling Smørgrav #endif
80d4af9e69SDag-Erling Smørgrav #ifdef HAVE_POLL_H
81d4af9e69SDag-Erling Smørgrav #include <poll.h>
82d4af9e69SDag-Erling Smørgrav #else
83d4af9e69SDag-Erling Smørgrav # ifdef HAVE_SYS_POLL_H
84d4af9e69SDag-Erling Smørgrav #  include <sys/poll.h>
85d4af9e69SDag-Erling Smørgrav # endif
86d4af9e69SDag-Erling Smørgrav #endif
87333ee039SDag-Erling Smørgrav #ifdef HAVE_SYS_TIME_H
88333ee039SDag-Erling Smørgrav # include <sys/time.h>
89333ee039SDag-Erling Smørgrav #endif
90333ee039SDag-Erling Smørgrav #include <sys/wait.h>
91333ee039SDag-Erling Smørgrav #include <sys/uio.h>
92333ee039SDag-Erling Smørgrav 
93333ee039SDag-Erling Smørgrav #include <ctype.h>
94333ee039SDag-Erling Smørgrav #include <dirent.h>
95333ee039SDag-Erling Smørgrav #include <errno.h>
96333ee039SDag-Erling Smørgrav #include <fcntl.h>
9719261079SEd Maste #ifdef HAVE_FNMATCH_H
98afde5170SEd Maste #include <fnmatch.h>
9919261079SEd Maste #endif
10019261079SEd Maste #ifdef USE_SYSTEM_GLOB
10119261079SEd Maste # include <glob.h>
10219261079SEd Maste #else
10319261079SEd Maste # include "openbsd-compat/glob.h"
10419261079SEd Maste #endif
10519261079SEd Maste #ifdef HAVE_LIBGEN_H
10619261079SEd Maste #include <libgen.h>
10719261079SEd Maste #endif
108bc5531deSDag-Erling Smørgrav #include <limits.h>
109076ad2f8SDag-Erling Smørgrav #include <locale.h>
110333ee039SDag-Erling Smørgrav #include <pwd.h>
111333ee039SDag-Erling Smørgrav #include <signal.h>
112333ee039SDag-Erling Smørgrav #include <stdarg.h>
1134f52dfbbSDag-Erling Smørgrav #ifdef HAVE_STDINT_H
1144f52dfbbSDag-Erling Smørgrav # include <stdint.h>
1154f52dfbbSDag-Erling Smørgrav #endif
116333ee039SDag-Erling Smørgrav #include <stdio.h>
117333ee039SDag-Erling Smørgrav #include <stdlib.h>
118333ee039SDag-Erling Smørgrav #include <string.h>
119333ee039SDag-Erling Smørgrav #include <time.h>
120333ee039SDag-Erling Smørgrav #include <unistd.h>
1216888a9beSDag-Erling Smørgrav #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
122d4af9e69SDag-Erling Smørgrav #include <vis.h>
123d4af9e69SDag-Erling Smørgrav #endif
124511b41d2SMark Murray 
125511b41d2SMark Murray #include "xmalloc.h"
12647dd1d1bSDag-Erling Smørgrav #include "ssh.h"
1271e8db6e2SBrian Feldman #include "atomicio.h"
1281e8db6e2SBrian Feldman #include "pathnames.h"
1291e8db6e2SBrian Feldman #include "log.h"
130ae1f160dSDag-Erling Smørgrav #include "misc.h"
131e73e9afaSDag-Erling Smørgrav #include "progressmeter.h"
132076ad2f8SDag-Erling Smørgrav #include "utf8.h"
1331323ec57SEd Maste #include "sftp.h"
134511b41d2SMark Murray 
13519261079SEd Maste #include "sftp-common.h"
13619261079SEd Maste #include "sftp-client.h"
13719261079SEd Maste 
13883d2307dSDag-Erling Smørgrav extern char *__progname;
13983d2307dSDag-Erling Smørgrav 
140d4af9e69SDag-Erling Smørgrav #define COPY_BUFLEN	16384
141d4af9e69SDag-Erling Smørgrav 
14219261079SEd Maste int do_cmd(char *, char *, char *, int, int, char *, int *, int *, pid_t *);
14319261079SEd Maste int do_cmd2(char *, char *, int, char *, int, int);
144511b41d2SMark Murray 
145ae1f160dSDag-Erling Smørgrav /* Struct for addargs */
146ae1f160dSDag-Erling Smørgrav arglist args;
1474a421b63SDag-Erling Smørgrav arglist remote_remote_args;
1485b9b2fafSBrian Feldman 
149e73e9afaSDag-Erling Smørgrav /* Bandwidth limit */
1504a421b63SDag-Erling Smørgrav long long limit_kbps = 0;
1514a421b63SDag-Erling Smørgrav struct bwlimit bwlimit;
152511b41d2SMark Murray 
153511b41d2SMark Murray /* Name of current file being transferred. */
154511b41d2SMark Murray char *curfile;
155511b41d2SMark Murray 
156511b41d2SMark Murray /* This is set to non-zero to enable verbose mode. */
157511b41d2SMark Murray int verbose_mode = 0;
15819261079SEd Maste LogLevel log_level = SYSLOG_LEVEL_INFO;
159511b41d2SMark Murray 
160511b41d2SMark Murray /* This is set to zero if the progressmeter is not desired. */
161511b41d2SMark Murray int showprogress = 1;
162511b41d2SMark Murray 
1634a421b63SDag-Erling Smørgrav /*
1644a421b63SDag-Erling Smørgrav  * This is set to non-zero if remote-remote copy should be piped
1654a421b63SDag-Erling Smørgrav  * through this process.
1664a421b63SDag-Erling Smørgrav  */
16719261079SEd Maste int throughlocal = 1;
1684a421b63SDag-Erling Smørgrav 
16947dd1d1bSDag-Erling Smørgrav /* Non-standard port to use for the ssh connection or -1. */
17047dd1d1bSDag-Erling Smørgrav int sshport = -1;
17147dd1d1bSDag-Erling Smørgrav 
172b66f2d16SKris Kennaway /* This is the program to execute for the secured connection. ("ssh" or -S) */
1731e8db6e2SBrian Feldman char *ssh_program = _PATH_SSH_PROGRAM;
174b66f2d16SKris Kennaway 
175e73e9afaSDag-Erling Smørgrav /* This is used to store the pid of ssh_program */
176cf2b5f3bSDag-Erling Smørgrav pid_t do_cmd_pid = -1;
17719261079SEd Maste pid_t do_cmd_pid2 = -1;
17819261079SEd Maste 
17919261079SEd Maste /* Needed for sftp */
18019261079SEd Maste volatile sig_atomic_t interrupted = 0;
18119261079SEd Maste 
18219261079SEd Maste int remote_glob(struct sftp_conn *, const char *, int,
18319261079SEd Maste     int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
184cf2b5f3bSDag-Erling Smørgrav 
185cf2b5f3bSDag-Erling Smørgrav static void
186cf2b5f3bSDag-Erling Smørgrav killchild(int signo)
187cf2b5f3bSDag-Erling Smørgrav {
188aa49c926SDag-Erling Smørgrav 	if (do_cmd_pid > 1) {
189d4ecd108SDag-Erling Smørgrav 		kill(do_cmd_pid, signo ? signo : SIGTERM);
190aa49c926SDag-Erling Smørgrav 		waitpid(do_cmd_pid, NULL, 0);
191aa49c926SDag-Erling Smørgrav 	}
19219261079SEd Maste 	if (do_cmd_pid2 > 1) {
19319261079SEd Maste 		kill(do_cmd_pid2, signo ? signo : SIGTERM);
19419261079SEd Maste 		waitpid(do_cmd_pid2, NULL, 0);
19519261079SEd Maste 	}
196cf2b5f3bSDag-Erling Smørgrav 
197d4ecd108SDag-Erling Smørgrav 	if (signo)
198cf2b5f3bSDag-Erling Smørgrav 		_exit(1);
199d4ecd108SDag-Erling Smørgrav 	exit(1);
200cf2b5f3bSDag-Erling Smørgrav }
201e73e9afaSDag-Erling Smørgrav 
202e2f6069cSDag-Erling Smørgrav static void
20319261079SEd Maste suspone(int pid, int signo)
204e2f6069cSDag-Erling Smørgrav {
205e2f6069cSDag-Erling Smørgrav 	int status;
206e2f6069cSDag-Erling Smørgrav 
20719261079SEd Maste 	if (pid > 1) {
20819261079SEd Maste 		kill(pid, signo);
20919261079SEd Maste 		while (waitpid(pid, &status, WUNTRACED) == -1 &&
210e2f6069cSDag-Erling Smørgrav 		    errno == EINTR)
211e2f6069cSDag-Erling Smørgrav 			;
212e2f6069cSDag-Erling Smørgrav 	}
213e2f6069cSDag-Erling Smørgrav }
214e2f6069cSDag-Erling Smørgrav 
21519261079SEd Maste static void
21619261079SEd Maste suspchild(int signo)
21719261079SEd Maste {
21819261079SEd Maste 	suspone(do_cmd_pid, signo);
21919261079SEd Maste 	suspone(do_cmd_pid2, signo);
22019261079SEd Maste 	kill(getpid(), SIGSTOP);
22119261079SEd Maste }
22219261079SEd Maste 
223b74df5b2SDag-Erling Smørgrav static int
224b74df5b2SDag-Erling Smørgrav do_local_cmd(arglist *a)
225b74df5b2SDag-Erling Smørgrav {
226b74df5b2SDag-Erling Smørgrav 	u_int i;
227b74df5b2SDag-Erling Smørgrav 	int status;
228b74df5b2SDag-Erling Smørgrav 	pid_t pid;
229b74df5b2SDag-Erling Smørgrav 
230b74df5b2SDag-Erling Smørgrav 	if (a->num == 0)
231b74df5b2SDag-Erling Smørgrav 		fatal("do_local_cmd: no arguments");
232b74df5b2SDag-Erling Smørgrav 
233b74df5b2SDag-Erling Smørgrav 	if (verbose_mode) {
234b74df5b2SDag-Erling Smørgrav 		fprintf(stderr, "Executing:");
235b74df5b2SDag-Erling Smørgrav 		for (i = 0; i < a->num; i++)
236076ad2f8SDag-Erling Smørgrav 			fmprintf(stderr, " %s", a->list[i]);
237b74df5b2SDag-Erling Smørgrav 		fprintf(stderr, "\n");
238b74df5b2SDag-Erling Smørgrav 	}
239b74df5b2SDag-Erling Smørgrav 	if ((pid = fork()) == -1)
240b74df5b2SDag-Erling Smørgrav 		fatal("do_local_cmd: fork: %s", strerror(errno));
241b74df5b2SDag-Erling Smørgrav 
242b74df5b2SDag-Erling Smørgrav 	if (pid == 0) {
243b74df5b2SDag-Erling Smørgrav 		execvp(a->list[0], a->list);
244b74df5b2SDag-Erling Smørgrav 		perror(a->list[0]);
245b74df5b2SDag-Erling Smørgrav 		exit(1);
246b74df5b2SDag-Erling Smørgrav 	}
247b74df5b2SDag-Erling Smørgrav 
248b74df5b2SDag-Erling Smørgrav 	do_cmd_pid = pid;
24919261079SEd Maste 	ssh_signal(SIGTERM, killchild);
25019261079SEd Maste 	ssh_signal(SIGINT, killchild);
25119261079SEd Maste 	ssh_signal(SIGHUP, killchild);
252b74df5b2SDag-Erling Smørgrav 
253b74df5b2SDag-Erling Smørgrav 	while (waitpid(pid, &status, 0) == -1)
254b74df5b2SDag-Erling Smørgrav 		if (errno != EINTR)
255b74df5b2SDag-Erling Smørgrav 			fatal("do_local_cmd: waitpid: %s", strerror(errno));
256b74df5b2SDag-Erling Smørgrav 
257b74df5b2SDag-Erling Smørgrav 	do_cmd_pid = -1;
258b74df5b2SDag-Erling Smørgrav 
259b74df5b2SDag-Erling Smørgrav 	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
260b74df5b2SDag-Erling Smørgrav 		return (-1);
261b74df5b2SDag-Erling Smørgrav 
262b74df5b2SDag-Erling Smørgrav 	return (0);
263b74df5b2SDag-Erling Smørgrav }
264b74df5b2SDag-Erling Smørgrav 
265511b41d2SMark Murray /*
266511b41d2SMark Murray  * This function executes the given command as the specified user on the
267511b41d2SMark Murray  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
268511b41d2SMark Murray  * assigns the input and output file descriptors on success.
269511b41d2SMark Murray  */
270511b41d2SMark Murray 
271511b41d2SMark Murray int
27219261079SEd Maste do_cmd(char *program, char *host, char *remuser, int port, int subsystem,
27319261079SEd Maste     char *cmd, int *fdin, int *fdout, pid_t *pid)
274511b41d2SMark Murray {
275511b41d2SMark Murray 	int pin[2], pout[2], reserved[2];
276511b41d2SMark Murray 
277511b41d2SMark Murray 	if (verbose_mode)
278076ad2f8SDag-Erling Smørgrav 		fmprintf(stderr,
279ae1f160dSDag-Erling Smørgrav 		    "Executing: program %s host %s, user %s, command %s\n",
28019261079SEd Maste 		    program, host,
281ae1f160dSDag-Erling Smørgrav 		    remuser ? remuser : "(unspecified)", cmd);
282511b41d2SMark Murray 
28347dd1d1bSDag-Erling Smørgrav 	if (port == -1)
28447dd1d1bSDag-Erling Smørgrav 		port = sshport;
28547dd1d1bSDag-Erling Smørgrav 
286511b41d2SMark Murray 	/*
287511b41d2SMark Murray 	 * Reserve two descriptors so that the real pipes won't get
288511b41d2SMark Murray 	 * descriptors 0 and 1 because that will screw up dup2 below.
289511b41d2SMark Murray 	 */
29019261079SEd Maste 	if (pipe(reserved) == -1)
291333ee039SDag-Erling Smørgrav 		fatal("pipe: %s", strerror(errno));
292511b41d2SMark Murray 
293511b41d2SMark Murray 	/* Create a socket pair for communicating with ssh. */
29419261079SEd Maste 	if (pipe(pin) == -1)
295511b41d2SMark Murray 		fatal("pipe: %s", strerror(errno));
29619261079SEd Maste 	if (pipe(pout) == -1)
297511b41d2SMark Murray 		fatal("pipe: %s", strerror(errno));
298511b41d2SMark Murray 
299511b41d2SMark Murray 	/* Free the reserved descriptors. */
300511b41d2SMark Murray 	close(reserved[0]);
301511b41d2SMark Murray 	close(reserved[1]);
302511b41d2SMark Murray 
30319261079SEd Maste 	ssh_signal(SIGTSTP, suspchild);
30419261079SEd Maste 	ssh_signal(SIGTTIN, suspchild);
30519261079SEd Maste 	ssh_signal(SIGTTOU, suspchild);
306e2f6069cSDag-Erling Smørgrav 
307cf2b5f3bSDag-Erling Smørgrav 	/* Fork a child to execute the command on the remote host using ssh. */
30819261079SEd Maste 	*pid = fork();
30919261079SEd Maste 	if (*pid == 0) {
310511b41d2SMark Murray 		/* Child. */
311511b41d2SMark Murray 		close(pin[1]);
312511b41d2SMark Murray 		close(pout[0]);
313511b41d2SMark Murray 		dup2(pin[0], 0);
314511b41d2SMark Murray 		dup2(pout[1], 1);
315511b41d2SMark Murray 		close(pin[0]);
316511b41d2SMark Murray 		close(pout[1]);
317511b41d2SMark Murray 
31819261079SEd Maste 		replacearg(&args, 0, "%s", program);
31947dd1d1bSDag-Erling Smørgrav 		if (port != -1) {
32047dd1d1bSDag-Erling Smørgrav 			addargs(&args, "-p");
32147dd1d1bSDag-Erling Smørgrav 			addargs(&args, "%d", port);
32247dd1d1bSDag-Erling Smørgrav 		}
323b15c8340SDag-Erling Smørgrav 		if (remuser != NULL) {
324b15c8340SDag-Erling Smørgrav 			addargs(&args, "-l");
325b15c8340SDag-Erling Smørgrav 			addargs(&args, "%s", remuser);
326b15c8340SDag-Erling Smørgrav 		}
32719261079SEd Maste 		if (subsystem)
32819261079SEd Maste 			addargs(&args, "-s");
329b15c8340SDag-Erling Smørgrav 		addargs(&args, "--");
330ae1f160dSDag-Erling Smørgrav 		addargs(&args, "%s", host);
331ae1f160dSDag-Erling Smørgrav 		addargs(&args, "%s", cmd);
332511b41d2SMark Murray 
33319261079SEd Maste 		execvp(program, args.list);
33419261079SEd Maste 		perror(program);
335511b41d2SMark Murray 		exit(1);
33619261079SEd Maste 	} else if (*pid == -1) {
337e73e9afaSDag-Erling Smørgrav 		fatal("fork: %s", strerror(errno));
338511b41d2SMark Murray 	}
339511b41d2SMark Murray 	/* Parent.  Close the other side, and return the local side. */
340511b41d2SMark Murray 	close(pin[0]);
341511b41d2SMark Murray 	*fdout = pin[1];
342511b41d2SMark Murray 	close(pout[1]);
343511b41d2SMark Murray 	*fdin = pout[0];
34419261079SEd Maste 	ssh_signal(SIGTERM, killchild);
34519261079SEd Maste 	ssh_signal(SIGINT, killchild);
34619261079SEd Maste 	ssh_signal(SIGHUP, killchild);
347511b41d2SMark Murray 	return 0;
348511b41d2SMark Murray }
349511b41d2SMark Murray 
3504a421b63SDag-Erling Smørgrav /*
351190cef3dSDag-Erling Smørgrav  * This function executes a command similar to do_cmd(), but expects the
3524a421b63SDag-Erling Smørgrav  * input and output descriptors to be setup by a previous call to do_cmd().
3534a421b63SDag-Erling Smørgrav  * This way the input and output of two commands can be connected.
3544a421b63SDag-Erling Smørgrav  */
3554a421b63SDag-Erling Smørgrav int
35619261079SEd Maste do_cmd2(char *host, char *remuser, int port, char *cmd,
35719261079SEd Maste     int fdin, int fdout)
3584a421b63SDag-Erling Smørgrav {
3594a421b63SDag-Erling Smørgrav 	int status;
36019261079SEd Maste 	pid_t pid;
3614a421b63SDag-Erling Smørgrav 
3624a421b63SDag-Erling Smørgrav 	if (verbose_mode)
363076ad2f8SDag-Erling Smørgrav 		fmprintf(stderr,
3644a421b63SDag-Erling Smørgrav 		    "Executing: 2nd program %s host %s, user %s, command %s\n",
3654a421b63SDag-Erling Smørgrav 		    ssh_program, host,
3664a421b63SDag-Erling Smørgrav 		    remuser ? remuser : "(unspecified)", cmd);
3674a421b63SDag-Erling Smørgrav 
36847dd1d1bSDag-Erling Smørgrav 	if (port == -1)
36947dd1d1bSDag-Erling Smørgrav 		port = sshport;
37047dd1d1bSDag-Erling Smørgrav 
3714a421b63SDag-Erling Smørgrav 	/* Fork a child to execute the command on the remote host using ssh. */
3724a421b63SDag-Erling Smørgrav 	pid = fork();
3734a421b63SDag-Erling Smørgrav 	if (pid == 0) {
3744a421b63SDag-Erling Smørgrav 		dup2(fdin, 0);
3754a421b63SDag-Erling Smørgrav 		dup2(fdout, 1);
3764a421b63SDag-Erling Smørgrav 
3774a421b63SDag-Erling Smørgrav 		replacearg(&args, 0, "%s", ssh_program);
37847dd1d1bSDag-Erling Smørgrav 		if (port != -1) {
37947dd1d1bSDag-Erling Smørgrav 			addargs(&args, "-p");
38047dd1d1bSDag-Erling Smørgrav 			addargs(&args, "%d", port);
38147dd1d1bSDag-Erling Smørgrav 		}
3824a421b63SDag-Erling Smørgrav 		if (remuser != NULL) {
3834a421b63SDag-Erling Smørgrav 			addargs(&args, "-l");
3844a421b63SDag-Erling Smørgrav 			addargs(&args, "%s", remuser);
3854a421b63SDag-Erling Smørgrav 		}
38619261079SEd Maste 		addargs(&args, "-oBatchMode=yes");
3874a421b63SDag-Erling Smørgrav 		addargs(&args, "--");
3884a421b63SDag-Erling Smørgrav 		addargs(&args, "%s", host);
3894a421b63SDag-Erling Smørgrav 		addargs(&args, "%s", cmd);
3904a421b63SDag-Erling Smørgrav 
3914a421b63SDag-Erling Smørgrav 		execvp(ssh_program, args.list);
3924a421b63SDag-Erling Smørgrav 		perror(ssh_program);
3934a421b63SDag-Erling Smørgrav 		exit(1);
3944a421b63SDag-Erling Smørgrav 	} else if (pid == -1) {
3954a421b63SDag-Erling Smørgrav 		fatal("fork: %s", strerror(errno));
3964a421b63SDag-Erling Smørgrav 	}
3974a421b63SDag-Erling Smørgrav 	while (waitpid(pid, &status, 0) == -1)
3984a421b63SDag-Erling Smørgrav 		if (errno != EINTR)
3994a421b63SDag-Erling Smørgrav 			fatal("do_cmd2: waitpid: %s", strerror(errno));
4004a421b63SDag-Erling Smørgrav 	return 0;
4014a421b63SDag-Erling Smørgrav }
4024a421b63SDag-Erling Smørgrav 
403511b41d2SMark Murray typedef struct {
404d4ecd108SDag-Erling Smørgrav 	size_t cnt;
405511b41d2SMark Murray 	char *buf;
406511b41d2SMark Murray } BUF;
407511b41d2SMark Murray 
408511b41d2SMark Murray BUF *allocbuf(BUF *, int, int);
409511b41d2SMark Murray void lostconn(int);
410511b41d2SMark Murray int okname(char *);
41119261079SEd Maste void run_err(const char *,...)
41219261079SEd Maste     __attribute__((__format__ (printf, 1, 2)))
41319261079SEd Maste     __attribute__((__nonnull__ (1)));
41419261079SEd Maste int note_err(const char *,...)
41519261079SEd Maste     __attribute__((__format__ (printf, 1, 2)));
416511b41d2SMark Murray void verifydir(char *);
417511b41d2SMark Murray 
418511b41d2SMark Murray struct passwd *pwd;
419511b41d2SMark Murray uid_t userid;
42019261079SEd Maste int errs, remin, remout, remin2, remout2;
421afde5170SEd Maste int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
422511b41d2SMark Murray 
423511b41d2SMark Murray #define	CMDNEEDS	64
424511b41d2SMark Murray char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
425511b41d2SMark Murray 
42619261079SEd Maste enum scp_mode_e {
42719261079SEd Maste 	MODE_SCP,
42819261079SEd Maste 	MODE_SFTP
42919261079SEd Maste };
43019261079SEd Maste 
431511b41d2SMark Murray int response(void);
432511b41d2SMark Murray void rsource(char *, struct stat *);
433afde5170SEd Maste void sink(int, char *[], const char *);
434511b41d2SMark Murray void source(int, char *[]);
43519261079SEd Maste void tolocal(int, char *[], enum scp_mode_e, char *sftp_direct);
43619261079SEd Maste void toremote(int, char *[], enum scp_mode_e, char *sftp_direct);
437511b41d2SMark Murray void usage(void);
438511b41d2SMark Murray 
43919261079SEd Maste void source_sftp(int, char *, char *, struct sftp_conn *);
44019261079SEd Maste void sink_sftp(int, char *, const char *, struct sftp_conn *);
44119261079SEd Maste void throughlocal_sftp(struct sftp_conn *, struct sftp_conn *,
44219261079SEd Maste     char *, char *);
44319261079SEd Maste 
444511b41d2SMark Murray int
445cf2b5f3bSDag-Erling Smørgrav main(int argc, char **argv)
446511b41d2SMark Murray {
447333ee039SDag-Erling Smørgrav 	int ch, fflag, tflag, status, n;
44819261079SEd Maste 	char **newargv, *argv0;
4494a421b63SDag-Erling Smørgrav 	const char *errstr;
450511b41d2SMark Murray 	extern char *optarg;
451511b41d2SMark Murray 	extern int optind;
45219261079SEd Maste 	enum scp_mode_e mode = MODE_SCP;
45319261079SEd Maste 	char *sftp_direct = NULL;
454511b41d2SMark Murray 
455b74df5b2SDag-Erling Smørgrav 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
456b74df5b2SDag-Erling Smørgrav 	sanitise_stdfd();
457b74df5b2SDag-Erling Smørgrav 
45819261079SEd Maste 	seed_rng();
45919261079SEd Maste 
460ca86bcf2SDag-Erling Smørgrav 	msetlocale();
461076ad2f8SDag-Erling Smørgrav 
462333ee039SDag-Erling Smørgrav 	/* Copy argv, because we modify it */
46319261079SEd Maste 	argv0 = argv[0];
464ca86bcf2SDag-Erling Smørgrav 	newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
465333ee039SDag-Erling Smørgrav 	for (n = 0; n < argc; n++)
466333ee039SDag-Erling Smørgrav 		newargv[n] = xstrdup(argv[n]);
467333ee039SDag-Erling Smørgrav 	argv = newargv;
468333ee039SDag-Erling Smørgrav 
469cf2b5f3bSDag-Erling Smørgrav 	__progname = ssh_get_progname(argv[0]);
47083d2307dSDag-Erling Smørgrav 
471e9e8876aSEd Maste 	log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
47219261079SEd Maste 
473b74df5b2SDag-Erling Smørgrav 	memset(&args, '\0', sizeof(args));
4744a421b63SDag-Erling Smørgrav 	memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
4754a421b63SDag-Erling Smørgrav 	args.list = remote_remote_args.list = NULL;
476b74df5b2SDag-Erling Smørgrav 	addargs(&args, "%s", ssh_program);
477ae1f160dSDag-Erling Smørgrav 	addargs(&args, "-x");
4784a421b63SDag-Erling Smørgrav 	addargs(&args, "-oPermitLocalCommand=no");
4794a421b63SDag-Erling Smørgrav 	addargs(&args, "-oClearAllForwardings=yes");
48047dd1d1bSDag-Erling Smørgrav 	addargs(&args, "-oRemoteCommand=none");
48147dd1d1bSDag-Erling Smørgrav 	addargs(&args, "-oRequestTTY=no");
4825b9b2fafSBrian Feldman 
483afde5170SEd Maste 	fflag = Tflag = tflag = 0;
484afde5170SEd Maste 	while ((ch = getopt(argc, argv,
48519261079SEd Maste 	    "12346ABCTdfOpqRrstvD:F:J:M:P:S:c:i:l:o:")) != -1) {
486511b41d2SMark Murray 		switch (ch) {
487511b41d2SMark Murray 		/* User-visible flags. */
488e73e9afaSDag-Erling Smørgrav 		case '1':
4894f52dfbbSDag-Erling Smørgrav 			fatal("SSH protocol v.1 is no longer supported");
4904f52dfbbSDag-Erling Smørgrav 			break;
491e73e9afaSDag-Erling Smørgrav 		case '2':
4924f52dfbbSDag-Erling Smørgrav 			/* Ignored */
4934f52dfbbSDag-Erling Smørgrav 			break;
49419261079SEd Maste 		case 'A':
495511b41d2SMark Murray 		case '4':
496511b41d2SMark Murray 		case '6':
4975b9b2fafSBrian Feldman 		case 'C':
498ae1f160dSDag-Erling Smørgrav 			addargs(&args, "-%c", ch);
4994a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "-%c", ch);
5004a421b63SDag-Erling Smørgrav 			break;
50119261079SEd Maste 		case 'D':
50219261079SEd Maste 			sftp_direct = optarg;
50319261079SEd Maste 			break;
5044a421b63SDag-Erling Smørgrav 		case '3':
5054a421b63SDag-Erling Smørgrav 			throughlocal = 1;
5065b9b2fafSBrian Feldman 			break;
50719261079SEd Maste 		case 'R':
50819261079SEd Maste 			throughlocal = 0;
50919261079SEd Maste 			break;
5105b9b2fafSBrian Feldman 		case 'o':
5115b9b2fafSBrian Feldman 		case 'c':
5125b9b2fafSBrian Feldman 		case 'i':
513ae1f160dSDag-Erling Smørgrav 		case 'F':
51419261079SEd Maste 		case 'J':
5154a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "-%c", ch);
5164a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "%s", optarg);
517b15c8340SDag-Erling Smørgrav 			addargs(&args, "-%c", ch);
518b15c8340SDag-Erling Smørgrav 			addargs(&args, "%s", optarg);
5195b9b2fafSBrian Feldman 			break;
52019261079SEd Maste 		case 'O':
52119261079SEd Maste 			mode = MODE_SCP;
52219261079SEd Maste 			break;
52319261079SEd Maste 		case 's':
52419261079SEd Maste 			mode = MODE_SFTP;
52519261079SEd Maste 			break;
5265b9b2fafSBrian Feldman 		case 'P':
52747dd1d1bSDag-Erling Smørgrav 			sshport = a2port(optarg);
52847dd1d1bSDag-Erling Smørgrav 			if (sshport <= 0)
52947dd1d1bSDag-Erling Smørgrav 				fatal("bad port \"%s\"\n", optarg);
5305b9b2fafSBrian Feldman 			break;
5315b9b2fafSBrian Feldman 		case 'B':
5324a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "-oBatchmode=yes");
5334a421b63SDag-Erling Smørgrav 			addargs(&args, "-oBatchmode=yes");
534511b41d2SMark Murray 			break;
535e73e9afaSDag-Erling Smørgrav 		case 'l':
5364a421b63SDag-Erling Smørgrav 			limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
5374a421b63SDag-Erling Smørgrav 			    &errstr);
5384a421b63SDag-Erling Smørgrav 			if (errstr != NULL)
539e73e9afaSDag-Erling Smørgrav 				usage();
5404a421b63SDag-Erling Smørgrav 			limit_kbps *= 1024; /* kbps */
5414a421b63SDag-Erling Smørgrav 			bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
542e73e9afaSDag-Erling Smørgrav 			break;
543511b41d2SMark Murray 		case 'p':
544511b41d2SMark Murray 			pflag = 1;
545511b41d2SMark Murray 			break;
546511b41d2SMark Murray 		case 'r':
547511b41d2SMark Murray 			iamrecursive = 1;
548511b41d2SMark Murray 			break;
549b66f2d16SKris Kennaway 		case 'S':
5505b9b2fafSBrian Feldman 			ssh_program = xstrdup(optarg);
5515b9b2fafSBrian Feldman 			break;
5525b9b2fafSBrian Feldman 		case 'v':
553ae1f160dSDag-Erling Smørgrav 			addargs(&args, "-v");
5544a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "-v");
55519261079SEd Maste 			if (verbose_mode == 0)
55619261079SEd Maste 				log_level = SYSLOG_LEVEL_DEBUG1;
55719261079SEd Maste 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
55819261079SEd Maste 				log_level++;
5595b9b2fafSBrian Feldman 			verbose_mode = 1;
5605b9b2fafSBrian Feldman 			break;
5615b9b2fafSBrian Feldman 		case 'q':
5621ec0d754SDag-Erling Smørgrav 			addargs(&args, "-q");
5634a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "-q");
5645b9b2fafSBrian Feldman 			showprogress = 0;
565b66f2d16SKris Kennaway 			break;
566b66f2d16SKris Kennaway 
567511b41d2SMark Murray 		/* Server options. */
568511b41d2SMark Murray 		case 'd':
569511b41d2SMark Murray 			targetshouldbedirectory = 1;
570511b41d2SMark Murray 			break;
571511b41d2SMark Murray 		case 'f':	/* "from" */
572511b41d2SMark Murray 			iamremote = 1;
573511b41d2SMark Murray 			fflag = 1;
574511b41d2SMark Murray 			break;
575511b41d2SMark Murray 		case 't':	/* "to" */
576511b41d2SMark Murray 			iamremote = 1;
577511b41d2SMark Murray 			tflag = 1;
57883d2307dSDag-Erling Smørgrav #ifdef HAVE_CYGWIN
57983d2307dSDag-Erling Smørgrav 			setmode(0, O_BINARY);
58083d2307dSDag-Erling Smørgrav #endif
581511b41d2SMark Murray 			break;
582afde5170SEd Maste 		case 'T':
583afde5170SEd Maste 			Tflag = 1;
584afde5170SEd Maste 			break;
585511b41d2SMark Murray 		default:
586511b41d2SMark Murray 			usage();
587511b41d2SMark Murray 		}
588afde5170SEd Maste 	}
589511b41d2SMark Murray 	argc -= optind;
590511b41d2SMark Murray 	argv += optind;
591511b41d2SMark Murray 
592e9e8876aSEd Maste 	log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
59319261079SEd Maste 
59419261079SEd Maste 	/* Do this last because we want the user to be able to override it */
59519261079SEd Maste 	addargs(&args, "-oForwardAgent=no");
59619261079SEd Maste 
59719261079SEd Maste 	if (iamremote)
59819261079SEd Maste 		mode = MODE_SCP;
59919261079SEd Maste 
600511b41d2SMark Murray 	if ((pwd = getpwuid(userid = getuid())) == NULL)
601cf2b5f3bSDag-Erling Smørgrav 		fatal("unknown user %u", (u_int) userid);
602511b41d2SMark Murray 
603d4af9e69SDag-Erling Smørgrav 	if (!isatty(STDOUT_FILENO))
604511b41d2SMark Murray 		showprogress = 0;
605511b41d2SMark Murray 
606acc1a9efSDag-Erling Smørgrav 	if (pflag) {
607acc1a9efSDag-Erling Smørgrav 		/* Cannot pledge: -p allows setuid/setgid files... */
608acc1a9efSDag-Erling Smørgrav 	} else {
609acc1a9efSDag-Erling Smørgrav 		if (pledge("stdio rpath wpath cpath fattr tty proc exec",
610acc1a9efSDag-Erling Smørgrav 		    NULL) == -1) {
611acc1a9efSDag-Erling Smørgrav 			perror("pledge");
612acc1a9efSDag-Erling Smørgrav 			exit(1);
613acc1a9efSDag-Erling Smørgrav 		}
614acc1a9efSDag-Erling Smørgrav 	}
615acc1a9efSDag-Erling Smørgrav 
616511b41d2SMark Murray 	remin = STDIN_FILENO;
617511b41d2SMark Murray 	remout = STDOUT_FILENO;
618511b41d2SMark Murray 
619511b41d2SMark Murray 	if (fflag) {
620511b41d2SMark Murray 		/* Follow "protocol", send data. */
621511b41d2SMark Murray 		(void) response();
622511b41d2SMark Murray 		source(argc, argv);
623511b41d2SMark Murray 		exit(errs != 0);
624511b41d2SMark Murray 	}
625511b41d2SMark Murray 	if (tflag) {
626511b41d2SMark Murray 		/* Receive data. */
627afde5170SEd Maste 		sink(argc, argv, NULL);
628511b41d2SMark Murray 		exit(errs != 0);
629511b41d2SMark Murray 	}
630511b41d2SMark Murray 	if (argc < 2)
631511b41d2SMark Murray 		usage();
632511b41d2SMark Murray 	if (argc > 2)
633511b41d2SMark Murray 		targetshouldbedirectory = 1;
634511b41d2SMark Murray 
635511b41d2SMark Murray 	remin = remout = -1;
636e73e9afaSDag-Erling Smørgrav 	do_cmd_pid = -1;
637511b41d2SMark Murray 	/* Command to be executed on remote system using "ssh". */
6381e8db6e2SBrian Feldman 	(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
6391e8db6e2SBrian Feldman 	    verbose_mode ? " -v" : "",
640511b41d2SMark Murray 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
641511b41d2SMark Murray 	    targetshouldbedirectory ? " -d" : "");
642511b41d2SMark Murray 
64319261079SEd Maste 	(void) ssh_signal(SIGPIPE, lostconn);
644511b41d2SMark Murray 
64547dd1d1bSDag-Erling Smørgrav 	if (colon(argv[argc - 1]))	/* Dest is remote host. */
64619261079SEd Maste 		toremote(argc, argv, mode, sftp_direct);
647511b41d2SMark Murray 	else {
648511b41d2SMark Murray 		if (targetshouldbedirectory)
649511b41d2SMark Murray 			verifydir(argv[argc - 1]);
65019261079SEd Maste 		tolocal(argc, argv, mode, sftp_direct);	/* Dest is local host. */
651511b41d2SMark Murray 	}
652e73e9afaSDag-Erling Smørgrav 	/*
653e73e9afaSDag-Erling Smørgrav 	 * Finally check the exit status of the ssh process, if one was forked
654cce7d346SDag-Erling Smørgrav 	 * and no error has occurred yet
655e73e9afaSDag-Erling Smørgrav 	 */
656e9e8876aSEd Maste 	if (do_cmd_pid != -1 && (mode == MODE_SFTP || errs == 0)) {
657e73e9afaSDag-Erling Smørgrav 		if (remin != -1)
658e73e9afaSDag-Erling Smørgrav 		    (void) close(remin);
659e73e9afaSDag-Erling Smørgrav 		if (remout != -1)
660e73e9afaSDag-Erling Smørgrav 		    (void) close(remout);
661e73e9afaSDag-Erling Smørgrav 		if (waitpid(do_cmd_pid, &status, 0) == -1)
662e73e9afaSDag-Erling Smørgrav 			errs = 1;
663e73e9afaSDag-Erling Smørgrav 		else {
664e73e9afaSDag-Erling Smørgrav 			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
665e73e9afaSDag-Erling Smørgrav 				errs = 1;
666e73e9afaSDag-Erling Smørgrav 		}
667e73e9afaSDag-Erling Smørgrav 	}
668511b41d2SMark Murray 	exit(errs != 0);
669511b41d2SMark Murray }
670511b41d2SMark Murray 
6714a421b63SDag-Erling Smørgrav /* Callback from atomicio6 to update progress meter and limit bandwidth */
6724a421b63SDag-Erling Smørgrav static int
6734a421b63SDag-Erling Smørgrav scpio(void *_cnt, size_t s)
674d4af9e69SDag-Erling Smørgrav {
6754a421b63SDag-Erling Smørgrav 	off_t *cnt = (off_t *)_cnt;
676d4af9e69SDag-Erling Smørgrav 
6774a421b63SDag-Erling Smørgrav 	*cnt += s;
67819261079SEd Maste 	refresh_progress_meter(0);
6794a421b63SDag-Erling Smørgrav 	if (limit_kbps > 0)
6804a421b63SDag-Erling Smørgrav 		bandwidth_limit(&bwlimit, s);
6814a421b63SDag-Erling Smørgrav 	return 0;
682d4af9e69SDag-Erling Smørgrav }
683d4af9e69SDag-Erling Smørgrav 
684e4a9863fSDag-Erling Smørgrav static int
685e4a9863fSDag-Erling Smørgrav do_times(int fd, int verb, const struct stat *sb)
686e4a9863fSDag-Erling Smørgrav {
687e4a9863fSDag-Erling Smørgrav 	/* strlen(2^64) == 20; strlen(10^6) == 7 */
688e4a9863fSDag-Erling Smørgrav 	char buf[(20 + 7 + 2) * 2 + 2];
689e4a9863fSDag-Erling Smørgrav 
690e4a9863fSDag-Erling Smørgrav 	(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
691e4a9863fSDag-Erling Smørgrav 	    (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
692e4a9863fSDag-Erling Smørgrav 	    (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
693e4a9863fSDag-Erling Smørgrav 	if (verb) {
694e4a9863fSDag-Erling Smørgrav 		fprintf(stderr, "File mtime %lld atime %lld\n",
695e4a9863fSDag-Erling Smørgrav 		    (long long)sb->st_mtime, (long long)sb->st_atime);
696e4a9863fSDag-Erling Smørgrav 		fprintf(stderr, "Sending file timestamps: %s", buf);
697e4a9863fSDag-Erling Smørgrav 	}
698e4a9863fSDag-Erling Smørgrav 	(void) atomicio(vwrite, fd, buf, strlen(buf));
699e4a9863fSDag-Erling Smørgrav 	return (response());
700e4a9863fSDag-Erling Smørgrav }
701e4a9863fSDag-Erling Smørgrav 
70247dd1d1bSDag-Erling Smørgrav static int
70347dd1d1bSDag-Erling Smørgrav parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
70447dd1d1bSDag-Erling Smørgrav     char **pathp)
705511b41d2SMark Murray {
70647dd1d1bSDag-Erling Smørgrav 	int r;
70747dd1d1bSDag-Erling Smørgrav 
70847dd1d1bSDag-Erling Smørgrav 	r = parse_uri("scp", uri, userp, hostp, portp, pathp);
70947dd1d1bSDag-Erling Smørgrav 	if (r == 0 && *pathp == NULL)
71047dd1d1bSDag-Erling Smørgrav 		*pathp = xstrdup(".");
71147dd1d1bSDag-Erling Smørgrav 	return r;
71247dd1d1bSDag-Erling Smørgrav }
71347dd1d1bSDag-Erling Smørgrav 
7140967215dSEd Maste /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
7150967215dSEd Maste static int
7160967215dSEd Maste append(char *cp, char ***ap, size_t *np)
7170967215dSEd Maste {
7180967215dSEd Maste 	char **tmp;
7190967215dSEd Maste 
7200967215dSEd Maste 	if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
7210967215dSEd Maste 		return -1;
7220967215dSEd Maste 	tmp[(*np)] = cp;
7230967215dSEd Maste 	(*np)++;
7240967215dSEd Maste 	*ap = tmp;
7250967215dSEd Maste 	return 0;
7260967215dSEd Maste }
7270967215dSEd Maste 
7280967215dSEd Maste /*
7290967215dSEd Maste  * Finds the start and end of the first brace pair in the pattern.
7300967215dSEd Maste  * returns 0 on success or -1 for invalid patterns.
7310967215dSEd Maste  */
7320967215dSEd Maste static int
7330967215dSEd Maste find_brace(const char *pattern, int *startp, int *endp)
7340967215dSEd Maste {
7350967215dSEd Maste 	int i;
7360967215dSEd Maste 	int in_bracket, brace_level;
7370967215dSEd Maste 
7380967215dSEd Maste 	*startp = *endp = -1;
7390967215dSEd Maste 	in_bracket = brace_level = 0;
7400967215dSEd Maste 	for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
7410967215dSEd Maste 		switch (pattern[i]) {
7420967215dSEd Maste 		case '\\':
7430967215dSEd Maste 			/* skip next character */
7440967215dSEd Maste 			if (pattern[i + 1] != '\0')
7450967215dSEd Maste 				i++;
7460967215dSEd Maste 			break;
7470967215dSEd Maste 		case '[':
7480967215dSEd Maste 			in_bracket = 1;
7490967215dSEd Maste 			break;
7500967215dSEd Maste 		case ']':
7510967215dSEd Maste 			in_bracket = 0;
7520967215dSEd Maste 			break;
7530967215dSEd Maste 		case '{':
7540967215dSEd Maste 			if (in_bracket)
7550967215dSEd Maste 				break;
7560967215dSEd Maste 			if (pattern[i + 1] == '}') {
7570967215dSEd Maste 				/* Protect a single {}, for find(1), like csh */
7580967215dSEd Maste 				i++; /* skip */
7590967215dSEd Maste 				break;
7600967215dSEd Maste 			}
7610967215dSEd Maste 			if (*startp == -1)
7620967215dSEd Maste 				*startp = i;
7630967215dSEd Maste 			brace_level++;
7640967215dSEd Maste 			break;
7650967215dSEd Maste 		case '}':
7660967215dSEd Maste 			if (in_bracket)
7670967215dSEd Maste 				break;
7680967215dSEd Maste 			if (*startp < 0) {
7690967215dSEd Maste 				/* Unbalanced brace */
7700967215dSEd Maste 				return -1;
7710967215dSEd Maste 			}
7720967215dSEd Maste 			if (--brace_level <= 0)
7730967215dSEd Maste 				*endp = i;
7740967215dSEd Maste 			break;
7750967215dSEd Maste 		}
7760967215dSEd Maste 	}
7770967215dSEd Maste 	/* unbalanced brackets/braces */
7780967215dSEd Maste 	if (*endp < 0 && (*startp >= 0 || in_bracket))
7790967215dSEd Maste 		return -1;
7800967215dSEd Maste 	return 0;
7810967215dSEd Maste }
7820967215dSEd Maste 
7830967215dSEd Maste /*
7840967215dSEd Maste  * Assembles and records a successfully-expanded pattern, returns -1 on
7850967215dSEd Maste  * alloc failure.
7860967215dSEd Maste  */
7870967215dSEd Maste static int
7880967215dSEd Maste emit_expansion(const char *pattern, int brace_start, int brace_end,
7890967215dSEd Maste     int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
7900967215dSEd Maste {
7910967215dSEd Maste 	char *cp;
7920967215dSEd Maste 	int o = 0, tail_len = strlen(pattern + brace_end + 1);
7930967215dSEd Maste 
7940967215dSEd Maste 	if ((cp = malloc(brace_start + (sel_end - sel_start) +
7950967215dSEd Maste 	    tail_len + 1)) == NULL)
7960967215dSEd Maste 		return -1;
7970967215dSEd Maste 
7980967215dSEd Maste 	/* Pattern before initial brace */
7990967215dSEd Maste 	if (brace_start > 0) {
8000967215dSEd Maste 		memcpy(cp, pattern, brace_start);
8010967215dSEd Maste 		o = brace_start;
8020967215dSEd Maste 	}
8030967215dSEd Maste 	/* Current braced selection */
8040967215dSEd Maste 	if (sel_end - sel_start > 0) {
8050967215dSEd Maste 		memcpy(cp + o, pattern + sel_start,
8060967215dSEd Maste 		    sel_end - sel_start);
8070967215dSEd Maste 		o += sel_end - sel_start;
8080967215dSEd Maste 	}
8090967215dSEd Maste 	/* Remainder of pattern after closing brace */
8100967215dSEd Maste 	if (tail_len > 0) {
8110967215dSEd Maste 		memcpy(cp + o, pattern + brace_end + 1, tail_len);
8120967215dSEd Maste 		o += tail_len;
8130967215dSEd Maste 	}
8140967215dSEd Maste 	cp[o] = '\0';
8150967215dSEd Maste 	if (append(cp, patternsp, npatternsp) != 0) {
8160967215dSEd Maste 		free(cp);
8170967215dSEd Maste 		return -1;
8180967215dSEd Maste 	}
8190967215dSEd Maste 	return 0;
8200967215dSEd Maste }
8210967215dSEd Maste 
8220967215dSEd Maste /*
8230967215dSEd Maste  * Expand the first encountered brace in pattern, appending the expanded
8240967215dSEd Maste  * patterns it yielded to the *patternsp array.
8250967215dSEd Maste  *
8260967215dSEd Maste  * Returns 0 on success or -1 on allocation failure.
8270967215dSEd Maste  *
8280967215dSEd Maste  * Signals whether expansion was performed via *expanded and whether
8290967215dSEd Maste  * pattern was invalid via *invalid.
8300967215dSEd Maste  */
8310967215dSEd Maste static int
8320967215dSEd Maste brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
8330967215dSEd Maste     int *expanded, int *invalid)
8340967215dSEd Maste {
8350967215dSEd Maste 	int i;
8360967215dSEd Maste 	int in_bracket, brace_start, brace_end, brace_level;
8370967215dSEd Maste 	int sel_start, sel_end;
8380967215dSEd Maste 
8390967215dSEd Maste 	*invalid = *expanded = 0;
8400967215dSEd Maste 
8410967215dSEd Maste 	if (find_brace(pattern, &brace_start, &brace_end) != 0) {
8420967215dSEd Maste 		*invalid = 1;
8430967215dSEd Maste 		return 0;
8440967215dSEd Maste 	} else if (brace_start == -1)
8450967215dSEd Maste 		return 0;
8460967215dSEd Maste 
8470967215dSEd Maste 	in_bracket = brace_level = 0;
8480967215dSEd Maste 	for (i = sel_start = brace_start + 1; i < brace_end; i++) {
8490967215dSEd Maste 		switch (pattern[i]) {
8500967215dSEd Maste 		case '{':
8510967215dSEd Maste 			if (in_bracket)
8520967215dSEd Maste 				break;
8530967215dSEd Maste 			brace_level++;
8540967215dSEd Maste 			break;
8550967215dSEd Maste 		case '}':
8560967215dSEd Maste 			if (in_bracket)
8570967215dSEd Maste 				break;
8580967215dSEd Maste 			brace_level--;
8590967215dSEd Maste 			break;
8600967215dSEd Maste 		case '[':
8610967215dSEd Maste 			in_bracket = 1;
8620967215dSEd Maste 			break;
8630967215dSEd Maste 		case ']':
8640967215dSEd Maste 			in_bracket = 0;
8650967215dSEd Maste 			break;
8660967215dSEd Maste 		case '\\':
8670967215dSEd Maste 			if (i < brace_end - 1)
8680967215dSEd Maste 				i++; /* skip */
8690967215dSEd Maste 			break;
8700967215dSEd Maste 		}
8710967215dSEd Maste 		if (pattern[i] == ',' || i == brace_end - 1) {
8720967215dSEd Maste 			if (in_bracket || brace_level > 0)
8730967215dSEd Maste 				continue;
8740967215dSEd Maste 			/* End of a selection, emit an expanded pattern */
8750967215dSEd Maste 
8760967215dSEd Maste 			/* Adjust end index for last selection */
8770967215dSEd Maste 			sel_end = (i == brace_end - 1) ? brace_end : i;
8780967215dSEd Maste 			if (emit_expansion(pattern, brace_start, brace_end,
8790967215dSEd Maste 			    sel_start, sel_end, patternsp, npatternsp) != 0)
8800967215dSEd Maste 				return -1;
8810967215dSEd Maste 			/* move on to the next selection */
8820967215dSEd Maste 			sel_start = i + 1;
8830967215dSEd Maste 			continue;
8840967215dSEd Maste 		}
8850967215dSEd Maste 	}
8860967215dSEd Maste 	if (in_bracket || brace_level > 0) {
8870967215dSEd Maste 		*invalid = 1;
8880967215dSEd Maste 		return 0;
8890967215dSEd Maste 	}
8900967215dSEd Maste 	/* success */
8910967215dSEd Maste 	*expanded = 1;
8920967215dSEd Maste 	return 0;
8930967215dSEd Maste }
8940967215dSEd Maste 
8950967215dSEd Maste /* Expand braces from pattern. Returns 0 on success, -1 on failure */
8960967215dSEd Maste static int
8970967215dSEd Maste brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
8980967215dSEd Maste {
8990967215dSEd Maste 	char *cp, *cp2, **active = NULL, **done = NULL;
9000967215dSEd Maste 	size_t i, nactive = 0, ndone = 0;
9010967215dSEd Maste 	int ret = -1, invalid = 0, expanded = 0;
9020967215dSEd Maste 
9030967215dSEd Maste 	*patternsp = NULL;
9040967215dSEd Maste 	*npatternsp = 0;
9050967215dSEd Maste 
9060967215dSEd Maste 	/* Start the worklist with the original pattern */
9070967215dSEd Maste 	if ((cp = strdup(pattern)) == NULL)
9080967215dSEd Maste 		return -1;
9090967215dSEd Maste 	if (append(cp, &active, &nactive) != 0) {
9100967215dSEd Maste 		free(cp);
9110967215dSEd Maste 		return -1;
9120967215dSEd Maste 	}
9130967215dSEd Maste 	while (nactive > 0) {
9140967215dSEd Maste 		cp = active[nactive - 1];
9150967215dSEd Maste 		nactive--;
9160967215dSEd Maste 		if (brace_expand_one(cp, &active, &nactive,
9170967215dSEd Maste 		    &expanded, &invalid) == -1) {
9180967215dSEd Maste 			free(cp);
9190967215dSEd Maste 			goto fail;
9200967215dSEd Maste 		}
9210967215dSEd Maste 		if (invalid)
92219261079SEd Maste 			fatal_f("invalid brace pattern \"%s\"", cp);
9230967215dSEd Maste 		if (expanded) {
9240967215dSEd Maste 			/*
9250967215dSEd Maste 			 * Current entry expanded to new entries on the
9260967215dSEd Maste 			 * active list; discard the progenitor pattern.
9270967215dSEd Maste 			 */
9280967215dSEd Maste 			free(cp);
9290967215dSEd Maste 			continue;
9300967215dSEd Maste 		}
9310967215dSEd Maste 		/*
9320967215dSEd Maste 		 * Pattern did not expand; append the finename component to
9330967215dSEd Maste 		 * the completed list
9340967215dSEd Maste 		 */
9350967215dSEd Maste 		if ((cp2 = strrchr(cp, '/')) != NULL)
9360967215dSEd Maste 			*cp2++ = '\0';
9370967215dSEd Maste 		else
9380967215dSEd Maste 			cp2 = cp;
9390967215dSEd Maste 		if (append(xstrdup(cp2), &done, &ndone) != 0) {
9400967215dSEd Maste 			free(cp);
9410967215dSEd Maste 			goto fail;
9420967215dSEd Maste 		}
9430967215dSEd Maste 		free(cp);
9440967215dSEd Maste 	}
9450967215dSEd Maste 	/* success */
9460967215dSEd Maste 	*patternsp = done;
9470967215dSEd Maste 	*npatternsp = ndone;
9480967215dSEd Maste 	done = NULL;
9490967215dSEd Maste 	ndone = 0;
9500967215dSEd Maste 	ret = 0;
9510967215dSEd Maste  fail:
9520967215dSEd Maste 	for (i = 0; i < nactive; i++)
9530967215dSEd Maste 		free(active[i]);
9540967215dSEd Maste 	free(active);
9550967215dSEd Maste 	for (i = 0; i < ndone; i++)
9560967215dSEd Maste 		free(done[i]);
9570967215dSEd Maste 	free(done);
9580967215dSEd Maste 	return ret;
9590967215dSEd Maste }
9600967215dSEd Maste 
96119261079SEd Maste static struct sftp_conn *
96219261079SEd Maste do_sftp_connect(char *host, char *user, int port, char *sftp_direct,
96319261079SEd Maste    int *reminp, int *remoutp, int *pidp)
96419261079SEd Maste {
96519261079SEd Maste 	if (sftp_direct == NULL) {
96619261079SEd Maste 		if (do_cmd(ssh_program, host, user, port, 1, "sftp",
96719261079SEd Maste 		    reminp, remoutp, pidp) < 0)
96819261079SEd Maste 			return NULL;
96919261079SEd Maste 
97019261079SEd Maste 	} else {
97119261079SEd Maste 		args.list = NULL;
97219261079SEd Maste 		addargs(&args, "sftp-server");
97319261079SEd Maste 		if (do_cmd(sftp_direct, host, NULL, -1, 0, "sftp",
97419261079SEd Maste 		    reminp, remoutp, pidp) < 0)
97519261079SEd Maste 			return NULL;
97619261079SEd Maste 	}
97719261079SEd Maste 	return do_init(*reminp, *remoutp, 32768, 64, limit_kbps);
97819261079SEd Maste }
97919261079SEd Maste 
98047dd1d1bSDag-Erling Smørgrav void
98119261079SEd Maste toremote(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
98247dd1d1bSDag-Erling Smørgrav {
98347dd1d1bSDag-Erling Smørgrav 	char *suser = NULL, *host = NULL, *src = NULL;
98447dd1d1bSDag-Erling Smørgrav 	char *bp, *tuser, *thost, *targ;
98547dd1d1bSDag-Erling Smørgrav 	int sport = -1, tport = -1;
98619261079SEd Maste 	struct sftp_conn *conn = NULL, *conn2 = NULL;
987b74df5b2SDag-Erling Smørgrav 	arglist alist;
98819261079SEd Maste 	int i, r, status;
9894a421b63SDag-Erling Smørgrav 	u_int j;
990b74df5b2SDag-Erling Smørgrav 
991b74df5b2SDag-Erling Smørgrav 	memset(&alist, '\0', sizeof(alist));
992b74df5b2SDag-Erling Smørgrav 	alist.list = NULL;
993511b41d2SMark Murray 
99447dd1d1bSDag-Erling Smørgrav 	/* Parse target */
99547dd1d1bSDag-Erling Smørgrav 	r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
99647dd1d1bSDag-Erling Smørgrav 	if (r == -1) {
99747dd1d1bSDag-Erling Smørgrav 		fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
99847dd1d1bSDag-Erling Smørgrav 		++errs;
99947dd1d1bSDag-Erling Smørgrav 		goto out;
1000511b41d2SMark Murray 	}
100147dd1d1bSDag-Erling Smørgrav 	if (r != 0) {
100247dd1d1bSDag-Erling Smørgrav 		if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
100347dd1d1bSDag-Erling Smørgrav 		    &targ) == -1) {
100447dd1d1bSDag-Erling Smørgrav 			fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
100547dd1d1bSDag-Erling Smørgrav 			++errs;
100647dd1d1bSDag-Erling Smørgrav 			goto out;
100747dd1d1bSDag-Erling Smørgrav 		}
100847dd1d1bSDag-Erling Smørgrav 	}
1009b74df5b2SDag-Erling Smørgrav 
101047dd1d1bSDag-Erling Smørgrav 	/* Parse source files */
1011511b41d2SMark Murray 	for (i = 0; i < argc - 1; i++) {
101247dd1d1bSDag-Erling Smørgrav 		free(suser);
101347dd1d1bSDag-Erling Smørgrav 		free(host);
101447dd1d1bSDag-Erling Smørgrav 		free(src);
101547dd1d1bSDag-Erling Smørgrav 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
101647dd1d1bSDag-Erling Smørgrav 		if (r == -1) {
101747dd1d1bSDag-Erling Smørgrav 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
101847dd1d1bSDag-Erling Smørgrav 			++errs;
10194a421b63SDag-Erling Smørgrav 			continue;
10204a421b63SDag-Erling Smørgrav 		}
102147dd1d1bSDag-Erling Smørgrav 		if (r != 0) {
102247dd1d1bSDag-Erling Smørgrav 			parse_user_host_path(argv[i], &suser, &host, &src);
102347dd1d1bSDag-Erling Smørgrav 		}
102447dd1d1bSDag-Erling Smørgrav 		if (suser != NULL && !okname(suser)) {
102547dd1d1bSDag-Erling Smørgrav 			++errs;
102647dd1d1bSDag-Erling Smørgrav 			continue;
102747dd1d1bSDag-Erling Smørgrav 		}
102847dd1d1bSDag-Erling Smørgrav 		if (host && throughlocal) {	/* extended remote to remote */
102919261079SEd Maste 			if (mode == MODE_SFTP) {
103019261079SEd Maste 				if (remin == -1) {
103119261079SEd Maste 					/* Connect to dest now */
103219261079SEd Maste 					conn = do_sftp_connect(thost, tuser,
103319261079SEd Maste 					    tport, sftp_direct,
103419261079SEd Maste 					    &remin, &remout, &do_cmd_pid);
103519261079SEd Maste 					if (conn == NULL) {
103619261079SEd Maste 						fatal("Unable to open "
103719261079SEd Maste 						    "destination connection");
103819261079SEd Maste 					}
103919261079SEd Maste 					debug3_f("origin in %d out %d pid %ld",
104019261079SEd Maste 					    remin, remout, (long)do_cmd_pid);
104119261079SEd Maste 				}
104219261079SEd Maste 				/*
104319261079SEd Maste 				 * XXX remember suser/host/sport and only
104419261079SEd Maste 				 * reconnect if they change between arguments.
104519261079SEd Maste 				 * would save reconnections for cases like
104619261079SEd Maste 				 * scp -3 hosta:/foo hosta:/bar hostb:
104719261079SEd Maste 				 */
104819261079SEd Maste 				/* Connect to origin now */
104919261079SEd Maste 				conn2 = do_sftp_connect(host, suser,
105019261079SEd Maste 				    sport, sftp_direct,
105119261079SEd Maste 				    &remin2, &remout2, &do_cmd_pid2);
105219261079SEd Maste 				if (conn2 == NULL) {
105319261079SEd Maste 					fatal("Unable to open "
105419261079SEd Maste 					    "source connection");
105519261079SEd Maste 				}
105619261079SEd Maste 				debug3_f("destination in %d out %d pid %ld",
105719261079SEd Maste 				    remin2, remout2, (long)do_cmd_pid2);
105819261079SEd Maste 				throughlocal_sftp(conn2, conn, src, targ);
105919261079SEd Maste 				(void) close(remin2);
106019261079SEd Maste 				(void) close(remout2);
106119261079SEd Maste 				remin2 = remout2 = -1;
106219261079SEd Maste 				if (waitpid(do_cmd_pid2, &status, 0) == -1)
106319261079SEd Maste 					++errs;
106419261079SEd Maste 				else if (!WIFEXITED(status) ||
106519261079SEd Maste 				    WEXITSTATUS(status) != 0)
106619261079SEd Maste 					++errs;
106719261079SEd Maste 				do_cmd_pid2 = -1;
106819261079SEd Maste 				continue;
106919261079SEd Maste 			} else {
1070462c32cbSDag-Erling Smørgrav 				xasprintf(&bp, "%s -f %s%s", cmd,
1071462c32cbSDag-Erling Smørgrav 				    *src == '-' ? "-- " : "", src);
107219261079SEd Maste 				if (do_cmd(ssh_program, host, suser, sport, 0,
107319261079SEd Maste 				    bp, &remin, &remout, &do_cmd_pid) < 0)
10744a421b63SDag-Erling Smørgrav 					exit(1);
1075e4a9863fSDag-Erling Smørgrav 				free(bp);
1076462c32cbSDag-Erling Smørgrav 				xasprintf(&bp, "%s -t %s%s", cmd,
1077462c32cbSDag-Erling Smørgrav 				    *targ == '-' ? "-- " : "", targ);
107819261079SEd Maste 				if (do_cmd2(thost, tuser, tport, bp,
107919261079SEd Maste 				    remin, remout) < 0)
10804a421b63SDag-Erling Smørgrav 					exit(1);
1081e4a9863fSDag-Erling Smørgrav 				free(bp);
10824a421b63SDag-Erling Smørgrav 				(void) close(remin);
10834a421b63SDag-Erling Smørgrav 				(void) close(remout);
10844a421b63SDag-Erling Smørgrav 				remin = remout = -1;
108519261079SEd Maste 			}
108647dd1d1bSDag-Erling Smørgrav 		} else if (host) {	/* standard remote to remote */
108719261079SEd Maste 			/*
108819261079SEd Maste 			 * Second remote user is passed to first remote side
108919261079SEd Maste 			 * via scp command-line. Ensure it contains no obvious
109019261079SEd Maste 			 * shell characters.
109119261079SEd Maste 			 */
109219261079SEd Maste 			if (tuser != NULL && !okname(tuser)) {
109319261079SEd Maste 				++errs;
109419261079SEd Maste 				continue;
109519261079SEd Maste 			}
109647dd1d1bSDag-Erling Smørgrav 			if (tport != -1 && tport != SSH_DEFAULT_PORT) {
109747dd1d1bSDag-Erling Smørgrav 				/* This would require the remote support URIs */
109847dd1d1bSDag-Erling Smørgrav 				fatal("target port not supported with two "
109919261079SEd Maste 				    "remote hosts and the -R option");
110047dd1d1bSDag-Erling Smørgrav 			}
110147dd1d1bSDag-Erling Smørgrav 
1102b74df5b2SDag-Erling Smørgrav 			freeargs(&alist);
1103b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", ssh_program);
1104b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "-x");
11054a421b63SDag-Erling Smørgrav 			addargs(&alist, "-oClearAllForwardings=yes");
1106b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "-n");
11074a421b63SDag-Erling Smørgrav 			for (j = 0; j < remote_remote_args.num; j++) {
11084a421b63SDag-Erling Smørgrav 				addargs(&alist, "%s",
11094a421b63SDag-Erling Smørgrav 				    remote_remote_args.list[j]);
11104a421b63SDag-Erling Smørgrav 			}
1111b74df5b2SDag-Erling Smørgrav 
111247dd1d1bSDag-Erling Smørgrav 			if (sport != -1) {
111347dd1d1bSDag-Erling Smørgrav 				addargs(&alist, "-p");
111447dd1d1bSDag-Erling Smørgrav 				addargs(&alist, "%d", sport);
111547dd1d1bSDag-Erling Smørgrav 			}
111647dd1d1bSDag-Erling Smørgrav 			if (suser) {
1117b74df5b2SDag-Erling Smørgrav 				addargs(&alist, "-l");
1118b74df5b2SDag-Erling Smørgrav 				addargs(&alist, "%s", suser);
1119b74df5b2SDag-Erling Smørgrav 			}
1120b15c8340SDag-Erling Smørgrav 			addargs(&alist, "--");
1121b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", host);
1122b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", cmd);
1123b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", src);
1124b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s%s%s:%s",
1125511b41d2SMark Murray 			    tuser ? tuser : "", tuser ? "@" : "",
1126511b41d2SMark Murray 			    thost, targ);
1127b74df5b2SDag-Erling Smørgrav 			if (do_local_cmd(&alist) != 0)
11281ec0d754SDag-Erling Smørgrav 				errs = 1;
1129511b41d2SMark Murray 		} else {	/* local to remote */
113019261079SEd Maste 			if (mode == MODE_SFTP) {
113119261079SEd Maste 				if (remin == -1) {
113219261079SEd Maste 					/* Connect to remote now */
113319261079SEd Maste 					conn = do_sftp_connect(thost, tuser,
113419261079SEd Maste 					    tport, sftp_direct,
113519261079SEd Maste 					    &remin, &remout, &do_cmd_pid);
113619261079SEd Maste 					if (conn == NULL) {
113719261079SEd Maste 						fatal("Unable to open sftp "
113819261079SEd Maste 						    "connection");
113919261079SEd Maste 					}
114019261079SEd Maste 				}
114119261079SEd Maste 
114219261079SEd Maste 				/* The protocol */
114319261079SEd Maste 				source_sftp(1, argv[i], targ, conn);
114419261079SEd Maste 				continue;
114519261079SEd Maste 			}
114619261079SEd Maste 			/* SCP */
1147511b41d2SMark Murray 			if (remin == -1) {
1148462c32cbSDag-Erling Smørgrav 				xasprintf(&bp, "%s -t %s%s", cmd,
1149462c32cbSDag-Erling Smørgrav 				    *targ == '-' ? "-- " : "", targ);
115019261079SEd Maste 				if (do_cmd(ssh_program, thost, tuser, tport, 0,
115119261079SEd Maste 				    bp, &remin, &remout, &do_cmd_pid) < 0)
1152511b41d2SMark Murray 					exit(1);
1153511b41d2SMark Murray 				if (response() < 0)
1154511b41d2SMark Murray 					exit(1);
1155e4a9863fSDag-Erling Smørgrav 				free(bp);
1156511b41d2SMark Murray 			}
1157511b41d2SMark Murray 			source(1, argv + i);
1158511b41d2SMark Murray 		}
1159511b41d2SMark Murray 	}
116047dd1d1bSDag-Erling Smørgrav out:
116119261079SEd Maste 	if (mode == MODE_SFTP)
116219261079SEd Maste 		free(conn);
116347dd1d1bSDag-Erling Smørgrav 	free(tuser);
116447dd1d1bSDag-Erling Smørgrav 	free(thost);
116547dd1d1bSDag-Erling Smørgrav 	free(targ);
116647dd1d1bSDag-Erling Smørgrav 	free(suser);
116747dd1d1bSDag-Erling Smørgrav 	free(host);
116847dd1d1bSDag-Erling Smørgrav 	free(src);
1169511b41d2SMark Murray }
1170511b41d2SMark Murray 
1171511b41d2SMark Murray void
117219261079SEd Maste tolocal(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1173511b41d2SMark Murray {
117447dd1d1bSDag-Erling Smørgrav 	char *bp, *host = NULL, *src = NULL, *suser = NULL;
1175b74df5b2SDag-Erling Smørgrav 	arglist alist;
117619261079SEd Maste 	struct sftp_conn *conn = NULL;
117747dd1d1bSDag-Erling Smørgrav 	int i, r, sport = -1;
1178b74df5b2SDag-Erling Smørgrav 
1179b74df5b2SDag-Erling Smørgrav 	memset(&alist, '\0', sizeof(alist));
1180b74df5b2SDag-Erling Smørgrav 	alist.list = NULL;
1181511b41d2SMark Murray 
1182511b41d2SMark Murray 	for (i = 0; i < argc - 1; i++) {
118347dd1d1bSDag-Erling Smørgrav 		free(suser);
118447dd1d1bSDag-Erling Smørgrav 		free(host);
118547dd1d1bSDag-Erling Smørgrav 		free(src);
118647dd1d1bSDag-Erling Smørgrav 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
118747dd1d1bSDag-Erling Smørgrav 		if (r == -1) {
118847dd1d1bSDag-Erling Smørgrav 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
118947dd1d1bSDag-Erling Smørgrav 			++errs;
119047dd1d1bSDag-Erling Smørgrav 			continue;
119147dd1d1bSDag-Erling Smørgrav 		}
119247dd1d1bSDag-Erling Smørgrav 		if (r != 0)
119347dd1d1bSDag-Erling Smørgrav 			parse_user_host_path(argv[i], &suser, &host, &src);
119447dd1d1bSDag-Erling Smørgrav 		if (suser != NULL && !okname(suser)) {
119547dd1d1bSDag-Erling Smørgrav 			++errs;
119647dd1d1bSDag-Erling Smørgrav 			continue;
119747dd1d1bSDag-Erling Smørgrav 		}
119847dd1d1bSDag-Erling Smørgrav 		if (!host) {	/* Local to local. */
1199b74df5b2SDag-Erling Smørgrav 			freeargs(&alist);
1200b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", _PATH_CP);
1201b74df5b2SDag-Erling Smørgrav 			if (iamrecursive)
1202b74df5b2SDag-Erling Smørgrav 				addargs(&alist, "-r");
1203b74df5b2SDag-Erling Smørgrav 			if (pflag)
1204b74df5b2SDag-Erling Smørgrav 				addargs(&alist, "-p");
1205b15c8340SDag-Erling Smørgrav 			addargs(&alist, "--");
1206b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", argv[i]);
1207b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", argv[argc-1]);
1208b74df5b2SDag-Erling Smørgrav 			if (do_local_cmd(&alist))
1209511b41d2SMark Murray 				++errs;
1210511b41d2SMark Murray 			continue;
1211511b41d2SMark Murray 		}
121247dd1d1bSDag-Erling Smørgrav 		/* Remote to local. */
121319261079SEd Maste 		if (mode == MODE_SFTP) {
121419261079SEd Maste 			conn = do_sftp_connect(host, suser, sport,
121519261079SEd Maste 			    sftp_direct, &remin, &remout, &do_cmd_pid);
121619261079SEd Maste 			if (conn == NULL) {
1217e9e8876aSEd Maste 				error("sftp connection failed");
121819261079SEd Maste 				++errs;
121919261079SEd Maste 				continue;
122019261079SEd Maste 			}
122119261079SEd Maste 
122219261079SEd Maste 			/* The protocol */
122319261079SEd Maste 			sink_sftp(1, argv[argc - 1], src, conn);
122419261079SEd Maste 
122519261079SEd Maste 			free(conn);
122619261079SEd Maste 			(void) close(remin);
122719261079SEd Maste 			(void) close(remout);
122819261079SEd Maste 			remin = remout = -1;
122919261079SEd Maste 			continue;
123019261079SEd Maste 		}
123119261079SEd Maste 		/* SCP */
1232462c32cbSDag-Erling Smørgrav 		xasprintf(&bp, "%s -f %s%s",
1233462c32cbSDag-Erling Smørgrav 		    cmd, *src == '-' ? "-- " : "", src);
123419261079SEd Maste 		if (do_cmd(ssh_program, host, suser, sport, 0, bp,
123519261079SEd Maste 		    &remin, &remout, &do_cmd_pid) < 0) {
1236e4a9863fSDag-Erling Smørgrav 			free(bp);
1237511b41d2SMark Murray 			++errs;
1238511b41d2SMark Murray 			continue;
1239511b41d2SMark Murray 		}
1240e4a9863fSDag-Erling Smørgrav 		free(bp);
1241afde5170SEd Maste 		sink(1, argv + argc - 1, src);
1242511b41d2SMark Murray 		(void) close(remin);
1243511b41d2SMark Murray 		remin = remout = -1;
1244511b41d2SMark Murray 	}
124547dd1d1bSDag-Erling Smørgrav 	free(suser);
124647dd1d1bSDag-Erling Smørgrav 	free(host);
124747dd1d1bSDag-Erling Smørgrav 	free(src);
1248511b41d2SMark Murray }
1249511b41d2SMark Murray 
125019261079SEd Maste /* Prepare remote path, handling ~ by assuming cwd is the homedir */
125119261079SEd Maste static char *
125219261079SEd Maste prepare_remote_path(struct sftp_conn *conn, const char *path)
125319261079SEd Maste {
12541323ec57SEd Maste 	size_t nslash;
12551323ec57SEd Maste 
125619261079SEd Maste 	/* Handle ~ prefixed paths */
125719261079SEd Maste 	if (*path == '\0' || strcmp(path, "~") == 0)
125819261079SEd Maste 		return xstrdup(".");
12591323ec57SEd Maste 	if (*path != '~')
12601323ec57SEd Maste 		return xstrdup(path);
12611323ec57SEd Maste 	if (strncmp(path, "~/", 2) == 0) {
12621323ec57SEd Maste 		if ((nslash = strspn(path + 2, "/")) == strlen(path + 2))
12631323ec57SEd Maste 			return xstrdup(".");
12641323ec57SEd Maste 		return xstrdup(path + 2 + nslash);
12651323ec57SEd Maste 	}
126619261079SEd Maste 	if (can_expand_path(conn))
126719261079SEd Maste 		return do_expand_path(conn, path);
126819261079SEd Maste 	/* No protocol extension */
1269e9e8876aSEd Maste 	error("server expand-path extension is required "
1270e9e8876aSEd Maste 	    "for ~user paths in SFTP mode");
127119261079SEd Maste 	return NULL;
127219261079SEd Maste }
127319261079SEd Maste 
127419261079SEd Maste void
127519261079SEd Maste source_sftp(int argc, char *src, char *targ, struct sftp_conn *conn)
127619261079SEd Maste {
127719261079SEd Maste 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
12781323ec57SEd Maste 	int src_is_dir, target_is_dir;
12791323ec57SEd Maste 	Attrib a;
12801323ec57SEd Maste 	struct stat st;
128119261079SEd Maste 
12821323ec57SEd Maste 	memset(&a, '\0', sizeof(a));
12831323ec57SEd Maste 	if (stat(src, &st) != 0)
12841323ec57SEd Maste 		fatal("stat local \"%s\": %s", src, strerror(errno));
12851323ec57SEd Maste 	src_is_dir = S_ISDIR(st.st_mode);
128619261079SEd Maste 	if ((filename = basename(src)) == NULL)
12871323ec57SEd Maste 		fatal("basename \"%s\": %s", src, strerror(errno));
128819261079SEd Maste 
128919261079SEd Maste 	/*
129019261079SEd Maste 	 * No need to glob here - the local shell already took care of
129119261079SEd Maste 	 * the expansions
129219261079SEd Maste 	 */
129319261079SEd Maste 	if ((target = prepare_remote_path(conn, targ)) == NULL)
129419261079SEd Maste 		cleanup_exit(255);
129519261079SEd Maste 	target_is_dir = remote_is_dir(conn, target);
129619261079SEd Maste 	if (targetshouldbedirectory && !target_is_dir) {
12971323ec57SEd Maste 		debug("target directory \"%s\" does not exist", target);
12981323ec57SEd Maste 		a.flags = SSH2_FILEXFER_ATTR_PERMISSIONS;
12991323ec57SEd Maste 		a.perm = st.st_mode | 0700; /* ensure writable */
13001323ec57SEd Maste 		if (do_mkdir(conn, target, &a, 1) != 0)
13011323ec57SEd Maste 			cleanup_exit(255); /* error already logged */
13021323ec57SEd Maste 		target_is_dir = 1;
130319261079SEd Maste 	}
130419261079SEd Maste 	if (target_is_dir)
130519261079SEd Maste 		abs_dst = path_append(target, filename);
130619261079SEd Maste 	else {
130719261079SEd Maste 		abs_dst = target;
130819261079SEd Maste 		target = NULL;
130919261079SEd Maste 	}
131019261079SEd Maste 	debug3_f("copying local %s to remote %s", src, abs_dst);
131119261079SEd Maste 
13121323ec57SEd Maste 	if (src_is_dir && iamrecursive) {
131319261079SEd Maste 		if (upload_dir(conn, src, abs_dst, pflag,
131419261079SEd Maste 		    SFTP_PROGRESS_ONLY, 0, 0, 1) != 0) {
13151323ec57SEd Maste 			error("failed to upload directory %s to %s", src, targ);
1316e9e8876aSEd Maste 			errs = 1;
131719261079SEd Maste 		}
1318e9e8876aSEd Maste 	} else if (do_upload(conn, src, abs_dst, pflag, 0, 0) != 0) {
13191323ec57SEd Maste 		error("failed to upload file %s to %s", src, targ);
1320e9e8876aSEd Maste 		errs = 1;
1321e9e8876aSEd Maste 	}
132219261079SEd Maste 
132319261079SEd Maste 	free(abs_dst);
132419261079SEd Maste 	free(target);
132519261079SEd Maste }
132619261079SEd Maste 
1327511b41d2SMark Murray void
1328cf2b5f3bSDag-Erling Smørgrav source(int argc, char **argv)
1329511b41d2SMark Murray {
1330511b41d2SMark Murray 	struct stat stb;
1331511b41d2SMark Murray 	static BUF buffer;
1332511b41d2SMark Murray 	BUF *bp;
1333d4af9e69SDag-Erling Smørgrav 	off_t i, statbytes;
1334a0ee8cc6SDag-Erling Smørgrav 	size_t amt, nr;
1335d4ecd108SDag-Erling Smørgrav 	int fd = -1, haderr, indx;
133619261079SEd Maste 	char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
13371e8db6e2SBrian Feldman 	int len;
1338511b41d2SMark Murray 
1339511b41d2SMark Murray 	for (indx = 0; indx < argc; ++indx) {
1340511b41d2SMark Murray 		name = argv[indx];
1341511b41d2SMark Murray 		statbytes = 0;
13421e8db6e2SBrian Feldman 		len = strlen(name);
13431e8db6e2SBrian Feldman 		while (len > 1 && name[len-1] == '/')
13441e8db6e2SBrian Feldman 			name[--len] = '\0';
13451323ec57SEd Maste 		if ((fd = open(name, O_RDONLY|O_NONBLOCK)) == -1)
1346511b41d2SMark Murray 			goto syserr;
1347d4af9e69SDag-Erling Smørgrav 		if (strchr(name, '\n') != NULL) {
1348d4af9e69SDag-Erling Smørgrav 			strnvis(encname, name, sizeof(encname), VIS_NL);
1349d4af9e69SDag-Erling Smørgrav 			name = encname;
1350d4af9e69SDag-Erling Smørgrav 		}
135119261079SEd Maste 		if (fstat(fd, &stb) == -1) {
1352511b41d2SMark Murray syserr:			run_err("%s: %s", name, strerror(errno));
1353511b41d2SMark Murray 			goto next;
1354511b41d2SMark Murray 		}
1355d4af9e69SDag-Erling Smørgrav 		if (stb.st_size < 0) {
1356d4af9e69SDag-Erling Smørgrav 			run_err("%s: %s", name, "Negative file size");
1357d4af9e69SDag-Erling Smørgrav 			goto next;
1358d4af9e69SDag-Erling Smørgrav 		}
1359d4af9e69SDag-Erling Smørgrav 		unset_nonblock(fd);
1360511b41d2SMark Murray 		switch (stb.st_mode & S_IFMT) {
1361511b41d2SMark Murray 		case S_IFREG:
1362511b41d2SMark Murray 			break;
1363511b41d2SMark Murray 		case S_IFDIR:
1364511b41d2SMark Murray 			if (iamrecursive) {
1365511b41d2SMark Murray 				rsource(name, &stb);
1366511b41d2SMark Murray 				goto next;
1367511b41d2SMark Murray 			}
1368511b41d2SMark Murray 			/* FALLTHROUGH */
1369511b41d2SMark Murray 		default:
1370511b41d2SMark Murray 			run_err("%s: not a regular file", name);
1371511b41d2SMark Murray 			goto next;
1372511b41d2SMark Murray 		}
1373511b41d2SMark Murray 		if ((last = strrchr(name, '/')) == NULL)
1374511b41d2SMark Murray 			last = name;
1375511b41d2SMark Murray 		else
1376511b41d2SMark Murray 			++last;
1377511b41d2SMark Murray 		curfile = last;
1378511b41d2SMark Murray 		if (pflag) {
1379e4a9863fSDag-Erling Smørgrav 			if (do_times(remout, verbose_mode, &stb) < 0)
1380511b41d2SMark Murray 				goto next;
1381511b41d2SMark Murray 		}
1382511b41d2SMark Murray #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
13831e8db6e2SBrian Feldman 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
13841e8db6e2SBrian Feldman 		    (u_int) (stb.st_mode & FILEMODEMASK),
1385b74df5b2SDag-Erling Smørgrav 		    (long long)stb.st_size, last);
1386076ad2f8SDag-Erling Smørgrav 		if (verbose_mode)
1387076ad2f8SDag-Erling Smørgrav 			fmprintf(stderr, "Sending file modes: %s", buf);
1388cf2b5f3bSDag-Erling Smørgrav 		(void) atomicio(vwrite, remout, buf, strlen(buf));
1389511b41d2SMark Murray 		if (response() < 0)
1390511b41d2SMark Murray 			goto next;
1391d4af9e69SDag-Erling Smørgrav 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1392b74df5b2SDag-Erling Smørgrav next:			if (fd != -1) {
1393b74df5b2SDag-Erling Smørgrav 				(void) close(fd);
1394b74df5b2SDag-Erling Smørgrav 				fd = -1;
1395b74df5b2SDag-Erling Smørgrav 			}
1396511b41d2SMark Murray 			continue;
1397511b41d2SMark Murray 		}
1398e73e9afaSDag-Erling Smørgrav 		if (showprogress)
1399e73e9afaSDag-Erling Smørgrav 			start_progress_meter(curfile, stb.st_size, &statbytes);
1400d4af9e69SDag-Erling Smørgrav 		set_nonblock(remout);
1401511b41d2SMark Murray 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1402511b41d2SMark Murray 			amt = bp->cnt;
1403d4af9e69SDag-Erling Smørgrav 			if (i + (off_t)amt > stb.st_size)
1404511b41d2SMark Murray 				amt = stb.st_size - i;
1405511b41d2SMark Murray 			if (!haderr) {
1406a0ee8cc6SDag-Erling Smørgrav 				if ((nr = atomicio(read, fd,
1407a0ee8cc6SDag-Erling Smørgrav 				    bp->buf, amt)) != amt) {
1408d4ecd108SDag-Erling Smørgrav 					haderr = errno;
1409a0ee8cc6SDag-Erling Smørgrav 					memset(bp->buf + nr, 0, amt - nr);
1410a0ee8cc6SDag-Erling Smørgrav 				}
1411511b41d2SMark Murray 			}
1412d4af9e69SDag-Erling Smørgrav 			/* Keep writing after error to retain sync */
1413d4af9e69SDag-Erling Smørgrav 			if (haderr) {
1414cf2b5f3bSDag-Erling Smørgrav 				(void)atomicio(vwrite, remout, bp->buf, amt);
1415a0ee8cc6SDag-Erling Smørgrav 				memset(bp->buf, 0, amt);
1416d4af9e69SDag-Erling Smørgrav 				continue;
1417d4af9e69SDag-Erling Smørgrav 			}
14184a421b63SDag-Erling Smørgrav 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1419d4af9e69SDag-Erling Smørgrav 			    &statbytes) != amt)
1420d4ecd108SDag-Erling Smørgrav 				haderr = errno;
1421511b41d2SMark Murray 		}
1422d4af9e69SDag-Erling Smørgrav 		unset_nonblock(remout);
1423511b41d2SMark Murray 
1424b74df5b2SDag-Erling Smørgrav 		if (fd != -1) {
142519261079SEd Maste 			if (close(fd) == -1 && !haderr)
1426511b41d2SMark Murray 				haderr = errno;
1427b74df5b2SDag-Erling Smørgrav 			fd = -1;
1428b74df5b2SDag-Erling Smørgrav 		}
1429511b41d2SMark Murray 		if (!haderr)
1430cf2b5f3bSDag-Erling Smørgrav 			(void) atomicio(vwrite, remout, "", 1);
1431511b41d2SMark Murray 		else
1432511b41d2SMark Murray 			run_err("%s: %s", name, strerror(haderr));
1433511b41d2SMark Murray 		(void) response();
1434076ad2f8SDag-Erling Smørgrav 		if (showprogress)
1435076ad2f8SDag-Erling Smørgrav 			stop_progress_meter();
1436511b41d2SMark Murray 	}
1437511b41d2SMark Murray }
1438511b41d2SMark Murray 
1439511b41d2SMark Murray void
1440cf2b5f3bSDag-Erling Smørgrav rsource(char *name, struct stat *statp)
1441511b41d2SMark Murray {
1442511b41d2SMark Murray 	DIR *dirp;
1443511b41d2SMark Murray 	struct dirent *dp;
1444bc5531deSDag-Erling Smørgrav 	char *last, *vect[1], path[PATH_MAX];
1445511b41d2SMark Murray 
1446511b41d2SMark Murray 	if (!(dirp = opendir(name))) {
1447511b41d2SMark Murray 		run_err("%s: %s", name, strerror(errno));
1448511b41d2SMark Murray 		return;
1449511b41d2SMark Murray 	}
1450511b41d2SMark Murray 	last = strrchr(name, '/');
1451acc1a9efSDag-Erling Smørgrav 	if (last == NULL)
1452511b41d2SMark Murray 		last = name;
1453511b41d2SMark Murray 	else
1454511b41d2SMark Murray 		last++;
1455511b41d2SMark Murray 	if (pflag) {
1456e4a9863fSDag-Erling Smørgrav 		if (do_times(remout, verbose_mode, statp) < 0) {
1457511b41d2SMark Murray 			closedir(dirp);
1458511b41d2SMark Murray 			return;
1459511b41d2SMark Murray 		}
1460511b41d2SMark Murray 	}
14611e8db6e2SBrian Feldman 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
14621e8db6e2SBrian Feldman 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1463511b41d2SMark Murray 	if (verbose_mode)
1464076ad2f8SDag-Erling Smørgrav 		fmprintf(stderr, "Entering directory: %s", path);
1465cf2b5f3bSDag-Erling Smørgrav 	(void) atomicio(vwrite, remout, path, strlen(path));
1466511b41d2SMark Murray 	if (response() < 0) {
1467511b41d2SMark Murray 		closedir(dirp);
1468511b41d2SMark Murray 		return;
1469511b41d2SMark Murray 	}
14701e8db6e2SBrian Feldman 	while ((dp = readdir(dirp)) != NULL) {
1471511b41d2SMark Murray 		if (dp->d_ino == 0)
1472511b41d2SMark Murray 			continue;
1473511b41d2SMark Murray 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1474511b41d2SMark Murray 			continue;
1475511b41d2SMark Murray 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1476511b41d2SMark Murray 			run_err("%s/%s: name too long", name, dp->d_name);
1477511b41d2SMark Murray 			continue;
1478511b41d2SMark Murray 		}
14791e8db6e2SBrian Feldman 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1480511b41d2SMark Murray 		vect[0] = path;
1481511b41d2SMark Murray 		source(1, vect);
1482511b41d2SMark Murray 	}
1483511b41d2SMark Murray 	(void) closedir(dirp);
1484cf2b5f3bSDag-Erling Smørgrav 	(void) atomicio(vwrite, remout, "E\n", 2);
1485511b41d2SMark Murray 	(void) response();
1486511b41d2SMark Murray }
1487511b41d2SMark Murray 
148819261079SEd Maste void
148919261079SEd Maste sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn)
149019261079SEd Maste {
149119261079SEd Maste 	char *abs_src = NULL;
149219261079SEd Maste 	char *abs_dst = NULL;
149319261079SEd Maste 	glob_t g;
149419261079SEd Maste 	char *filename, *tmp = NULL;
14951323ec57SEd Maste 	int i, r, err = 0, dst_is_dir;
14961323ec57SEd Maste 	struct stat st;
149719261079SEd Maste 
149819261079SEd Maste 	memset(&g, 0, sizeof(g));
14991323ec57SEd Maste 
150019261079SEd Maste 	/*
150119261079SEd Maste 	 * Here, we need remote glob as SFTP can not depend on remote shell
150219261079SEd Maste 	 * expansions
150319261079SEd Maste 	 */
150419261079SEd Maste 	if ((abs_src = prepare_remote_path(conn, src)) == NULL) {
150519261079SEd Maste 		err = -1;
150619261079SEd Maste 		goto out;
150719261079SEd Maste 	}
150819261079SEd Maste 
150919261079SEd Maste 	debug3_f("copying remote %s to local %s", abs_src, dst);
151019261079SEd Maste 	if ((r = remote_glob(conn, abs_src, GLOB_MARK, NULL, &g)) != 0) {
151119261079SEd Maste 		if (r == GLOB_NOSPACE)
15121323ec57SEd Maste 			error("%s: too many glob matches", src);
151319261079SEd Maste 		else
15141323ec57SEd Maste 			error("%s: %s", src, strerror(ENOENT));
151519261079SEd Maste 		err = -1;
151619261079SEd Maste 		goto out;
151719261079SEd Maste 	}
151819261079SEd Maste 
15191323ec57SEd Maste 	if ((r = stat(dst, &st)) != 0)
15201323ec57SEd Maste 		debug2_f("stat local \"%s\": %s", dst, strerror(errno));
15211323ec57SEd Maste 	dst_is_dir = r == 0 && S_ISDIR(st.st_mode);
15221323ec57SEd Maste 
15231323ec57SEd Maste 	if (g.gl_matchc > 1 && !dst_is_dir) {
15241323ec57SEd Maste 		if (r == 0) {
152519261079SEd Maste 			error("Multiple files match pattern, but destination "
152619261079SEd Maste 			    "\"%s\" is not a directory", dst);
152719261079SEd Maste 			err = -1;
152819261079SEd Maste 			goto out;
152919261079SEd Maste 		}
15301323ec57SEd Maste 		debug2_f("creating destination \"%s\"", dst);
15311323ec57SEd Maste 		if (mkdir(dst, 0777) != 0) {
15321323ec57SEd Maste 			error("local mkdir \"%s\": %s", dst, strerror(errno));
15331323ec57SEd Maste 			err = -1;
15341323ec57SEd Maste 			goto out;
15351323ec57SEd Maste 		}
15361323ec57SEd Maste 		dst_is_dir = 1;
15371323ec57SEd Maste 	}
153819261079SEd Maste 
153919261079SEd Maste 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
154019261079SEd Maste 		tmp = xstrdup(g.gl_pathv[i]);
154119261079SEd Maste 		if ((filename = basename(tmp)) == NULL) {
154219261079SEd Maste 			error("basename %s: %s", tmp, strerror(errno));
154319261079SEd Maste 			err = -1;
154419261079SEd Maste 			goto out;
154519261079SEd Maste 		}
154619261079SEd Maste 
15471323ec57SEd Maste 		if (dst_is_dir)
154819261079SEd Maste 			abs_dst = path_append(dst, filename);
154919261079SEd Maste 		else
155019261079SEd Maste 			abs_dst = xstrdup(dst);
155119261079SEd Maste 
155219261079SEd Maste 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
155319261079SEd Maste 		if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
155419261079SEd Maste 			if (download_dir(conn, g.gl_pathv[i], abs_dst, NULL,
155519261079SEd Maste 			    pflag, SFTP_PROGRESS_ONLY, 0, 0, 1) == -1)
155619261079SEd Maste 				err = -1;
155719261079SEd Maste 		} else {
155819261079SEd Maste 			if (do_download(conn, g.gl_pathv[i], abs_dst, NULL,
155919261079SEd Maste 			    pflag, 0, 0) == -1)
156019261079SEd Maste 				err = -1;
156119261079SEd Maste 		}
156219261079SEd Maste 		free(abs_dst);
156319261079SEd Maste 		abs_dst = NULL;
156419261079SEd Maste 		free(tmp);
156519261079SEd Maste 		tmp = NULL;
156619261079SEd Maste 	}
156719261079SEd Maste 
156819261079SEd Maste out:
156919261079SEd Maste 	free(abs_src);
157019261079SEd Maste 	free(tmp);
157119261079SEd Maste 	globfree(&g);
1572e9e8876aSEd Maste 	if (err == -1)
1573e9e8876aSEd Maste 		errs = 1;
157419261079SEd Maste }
157519261079SEd Maste 
157619261079SEd Maste 
15774f52dfbbSDag-Erling Smørgrav #define TYPE_OVERFLOW(type, val) \
15784f52dfbbSDag-Erling Smørgrav 	((sizeof(type) == 4 && (val) > INT32_MAX) || \
15794f52dfbbSDag-Erling Smørgrav 	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
15804f52dfbbSDag-Erling Smørgrav 	 (sizeof(type) != 4 && sizeof(type) != 8))
15814f52dfbbSDag-Erling Smørgrav 
1582511b41d2SMark Murray void
1583afde5170SEd Maste sink(int argc, char **argv, const char *src)
1584511b41d2SMark Murray {
1585511b41d2SMark Murray 	static BUF buffer;
1586511b41d2SMark Murray 	struct stat stb;
1587511b41d2SMark Murray 	BUF *bp;
1588d4ecd108SDag-Erling Smørgrav 	off_t i;
1589d4ecd108SDag-Erling Smørgrav 	size_t j, count;
1590333ee039SDag-Erling Smørgrav 	int amt, exists, first, ofd;
1591333ee039SDag-Erling Smørgrav 	mode_t mode, omode, mask;
1592e73e9afaSDag-Erling Smørgrav 	off_t size, statbytes;
1593e4a9863fSDag-Erling Smørgrav 	unsigned long long ull;
159419261079SEd Maste 	int setimes, targisdir, wrerr;
1595076ad2f8SDag-Erling Smørgrav 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
15960967215dSEd Maste 	char **patterns = NULL;
15970967215dSEd Maste 	size_t n, npatterns = 0;
15985b9b2fafSBrian Feldman 	struct timeval tv[2];
1599511b41d2SMark Murray 
16001e8db6e2SBrian Feldman #define	atime	tv[0]
16011e8db6e2SBrian Feldman #define	mtime	tv[1]
1602aa49c926SDag-Erling Smørgrav #define	SCREWUP(str)	{ why = str; goto screwup; }
1603511b41d2SMark Murray 
16044f52dfbbSDag-Erling Smørgrav 	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
16054f52dfbbSDag-Erling Smørgrav 		SCREWUP("Unexpected off_t/time_t size");
16064f52dfbbSDag-Erling Smørgrav 
1607511b41d2SMark Murray 	setimes = targisdir = 0;
1608511b41d2SMark Murray 	mask = umask(0);
1609511b41d2SMark Murray 	if (!pflag)
1610511b41d2SMark Murray 		(void) umask(mask);
1611511b41d2SMark Murray 	if (argc != 1) {
1612511b41d2SMark Murray 		run_err("ambiguous target");
1613511b41d2SMark Murray 		exit(1);
1614511b41d2SMark Murray 	}
1615511b41d2SMark Murray 	targ = *argv;
1616511b41d2SMark Murray 	if (targetshouldbedirectory)
1617511b41d2SMark Murray 		verifydir(targ);
1618511b41d2SMark Murray 
1619cf2b5f3bSDag-Erling Smørgrav 	(void) atomicio(vwrite, remout, "", 1);
1620511b41d2SMark Murray 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1621511b41d2SMark Murray 		targisdir = 1;
1622afde5170SEd Maste 	if (src != NULL && !iamrecursive && !Tflag) {
1623afde5170SEd Maste 		/*
1624afde5170SEd Maste 		 * Prepare to try to restrict incoming filenames to match
1625afde5170SEd Maste 		 * the requested destination file glob.
1626afde5170SEd Maste 		 */
16270967215dSEd Maste 		if (brace_expand(src, &patterns, &npatterns) != 0)
162819261079SEd Maste 			fatal_f("could not expand pattern");
1629afde5170SEd Maste 	}
1630511b41d2SMark Murray 	for (first = 1;; first = 0) {
1631511b41d2SMark Murray 		cp = buf;
1632d4ecd108SDag-Erling Smørgrav 		if (atomicio(read, remin, cp, 1) != 1)
16330967215dSEd Maste 			goto done;
1634511b41d2SMark Murray 		if (*cp++ == '\n')
1635511b41d2SMark Murray 			SCREWUP("unexpected <newline>");
1636511b41d2SMark Murray 		do {
1637a04a10f8SKris Kennaway 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1638511b41d2SMark Murray 				SCREWUP("lost connection");
1639511b41d2SMark Murray 			*cp++ = ch;
1640511b41d2SMark Murray 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1641511b41d2SMark Murray 		*cp = 0;
164221e764dfSDag-Erling Smørgrav 		if (verbose_mode)
1643076ad2f8SDag-Erling Smørgrav 			fmprintf(stderr, "Sink: %s", buf);
1644511b41d2SMark Murray 
1645511b41d2SMark Murray 		if (buf[0] == '\01' || buf[0] == '\02') {
1646076ad2f8SDag-Erling Smørgrav 			if (iamremote == 0) {
1647076ad2f8SDag-Erling Smørgrav 				(void) snmprintf(visbuf, sizeof(visbuf),
1648076ad2f8SDag-Erling Smørgrav 				    NULL, "%s", buf + 1);
1649cf2b5f3bSDag-Erling Smørgrav 				(void) atomicio(vwrite, STDERR_FILENO,
1650076ad2f8SDag-Erling Smørgrav 				    visbuf, strlen(visbuf));
1651076ad2f8SDag-Erling Smørgrav 			}
1652511b41d2SMark Murray 			if (buf[0] == '\02')
1653511b41d2SMark Murray 				exit(1);
1654511b41d2SMark Murray 			++errs;
1655511b41d2SMark Murray 			continue;
1656511b41d2SMark Murray 		}
1657511b41d2SMark Murray 		if (buf[0] == 'E') {
1658cf2b5f3bSDag-Erling Smørgrav 			(void) atomicio(vwrite, remout, "", 1);
16590967215dSEd Maste 			goto done;
1660511b41d2SMark Murray 		}
1661511b41d2SMark Murray 		if (ch == '\n')
1662511b41d2SMark Murray 			*--cp = 0;
1663511b41d2SMark Murray 
1664511b41d2SMark Murray 		cp = buf;
1665511b41d2SMark Murray 		if (*cp == 'T') {
1666511b41d2SMark Murray 			setimes++;
1667511b41d2SMark Murray 			cp++;
1668e4a9863fSDag-Erling Smørgrav 			if (!isdigit((unsigned char)*cp))
1669e4a9863fSDag-Erling Smørgrav 				SCREWUP("mtime.sec not present");
1670e4a9863fSDag-Erling Smørgrav 			ull = strtoull(cp, &cp, 10);
16711e8db6e2SBrian Feldman 			if (!cp || *cp++ != ' ')
1672511b41d2SMark Murray 				SCREWUP("mtime.sec not delimited");
16734f52dfbbSDag-Erling Smørgrav 			if (TYPE_OVERFLOW(time_t, ull))
1674e4a9863fSDag-Erling Smørgrav 				setimes = 0;	/* out of range */
1675e4a9863fSDag-Erling Smørgrav 			mtime.tv_sec = ull;
16761e8db6e2SBrian Feldman 			mtime.tv_usec = strtol(cp, &cp, 10);
1677e4a9863fSDag-Erling Smørgrav 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1678e4a9863fSDag-Erling Smørgrav 			    mtime.tv_usec > 999999)
1679511b41d2SMark Murray 				SCREWUP("mtime.usec not delimited");
1680e4a9863fSDag-Erling Smørgrav 			if (!isdigit((unsigned char)*cp))
1681e4a9863fSDag-Erling Smørgrav 				SCREWUP("atime.sec not present");
1682e4a9863fSDag-Erling Smørgrav 			ull = strtoull(cp, &cp, 10);
16831e8db6e2SBrian Feldman 			if (!cp || *cp++ != ' ')
1684511b41d2SMark Murray 				SCREWUP("atime.sec not delimited");
16854f52dfbbSDag-Erling Smørgrav 			if (TYPE_OVERFLOW(time_t, ull))
1686e4a9863fSDag-Erling Smørgrav 				setimes = 0;	/* out of range */
1687e4a9863fSDag-Erling Smørgrav 			atime.tv_sec = ull;
16881e8db6e2SBrian Feldman 			atime.tv_usec = strtol(cp, &cp, 10);
1689e4a9863fSDag-Erling Smørgrav 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1690e4a9863fSDag-Erling Smørgrav 			    atime.tv_usec > 999999)
1691511b41d2SMark Murray 				SCREWUP("atime.usec not delimited");
1692cf2b5f3bSDag-Erling Smørgrav 			(void) atomicio(vwrite, remout, "", 1);
1693511b41d2SMark Murray 			continue;
1694511b41d2SMark Murray 		}
1695511b41d2SMark Murray 		if (*cp != 'C' && *cp != 'D') {
1696511b41d2SMark Murray 			/*
1697511b41d2SMark Murray 			 * Check for the case "rcp remote:foo\* local:bar".
1698511b41d2SMark Murray 			 * In this case, the line "No match." can be returned
1699511b41d2SMark Murray 			 * by the shell before the rcp command on the remote is
1700511b41d2SMark Murray 			 * executed so the ^Aerror_message convention isn't
1701511b41d2SMark Murray 			 * followed.
1702511b41d2SMark Murray 			 */
1703511b41d2SMark Murray 			if (first) {
1704511b41d2SMark Murray 				run_err("%s", cp);
1705511b41d2SMark Murray 				exit(1);
1706511b41d2SMark Murray 			}
1707511b41d2SMark Murray 			SCREWUP("expected control record");
1708511b41d2SMark Murray 		}
1709511b41d2SMark Murray 		mode = 0;
1710511b41d2SMark Murray 		for (++cp; cp < buf + 5; cp++) {
1711511b41d2SMark Murray 			if (*cp < '0' || *cp > '7')
1712511b41d2SMark Murray 				SCREWUP("bad mode");
1713511b41d2SMark Murray 			mode = (mode << 3) | (*cp - '0');
1714511b41d2SMark Murray 		}
1715190cef3dSDag-Erling Smørgrav 		if (!pflag)
1716190cef3dSDag-Erling Smørgrav 			mode &= ~mask;
1717511b41d2SMark Murray 		if (*cp++ != ' ')
1718511b41d2SMark Murray 			SCREWUP("mode not delimited");
1719511b41d2SMark Murray 
17204f52dfbbSDag-Erling Smørgrav 		if (!isdigit((unsigned char)*cp))
17214f52dfbbSDag-Erling Smørgrav 			SCREWUP("size not present");
17224f52dfbbSDag-Erling Smørgrav 		ull = strtoull(cp, &cp, 10);
17234f52dfbbSDag-Erling Smørgrav 		if (!cp || *cp++ != ' ')
1724511b41d2SMark Murray 			SCREWUP("size not delimited");
17254f52dfbbSDag-Erling Smørgrav 		if (TYPE_OVERFLOW(off_t, ull))
17264f52dfbbSDag-Erling Smørgrav 			SCREWUP("size out of range");
17274f52dfbbSDag-Erling Smørgrav 		size = (off_t)ull;
17284f52dfbbSDag-Erling Smørgrav 
1729d366f891SEd Maste 		if (*cp == '\0' || strchr(cp, '/') != NULL ||
1730d366f891SEd Maste 		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
173121e764dfSDag-Erling Smørgrav 			run_err("error: unexpected filename: %s", cp);
173221e764dfSDag-Erling Smørgrav 			exit(1);
173321e764dfSDag-Erling Smørgrav 		}
17340967215dSEd Maste 		if (npatterns > 0) {
17350967215dSEd Maste 			for (n = 0; n < npatterns; n++) {
17360967215dSEd Maste 				if (fnmatch(patterns[n], cp, 0) == 0)
17370967215dSEd Maste 					break;
17380967215dSEd Maste 			}
17390967215dSEd Maste 			if (n >= npatterns)
1740afde5170SEd Maste 				SCREWUP("filename does not match request");
17410967215dSEd Maste 		}
1742511b41d2SMark Murray 		if (targisdir) {
1743511b41d2SMark Murray 			static char *namebuf;
1744d4ecd108SDag-Erling Smørgrav 			static size_t cursize;
1745511b41d2SMark Murray 			size_t need;
1746511b41d2SMark Murray 
1747511b41d2SMark Murray 			need = strlen(targ) + strlen(cp) + 250;
17481e8db6e2SBrian Feldman 			if (need > cursize) {
1749e4a9863fSDag-Erling Smørgrav 				free(namebuf);
1750511b41d2SMark Murray 				namebuf = xmalloc(need);
17511e8db6e2SBrian Feldman 				cursize = need;
17521e8db6e2SBrian Feldman 			}
17531e8db6e2SBrian Feldman 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1754545d5ecaSDag-Erling Smørgrav 			    strcmp(targ, "/") ? "/" : "", cp);
1755511b41d2SMark Murray 			np = namebuf;
1756511b41d2SMark Murray 		} else
1757511b41d2SMark Murray 			np = targ;
1758511b41d2SMark Murray 		curfile = cp;
1759511b41d2SMark Murray 		exists = stat(np, &stb) == 0;
1760511b41d2SMark Murray 		if (buf[0] == 'D') {
1761511b41d2SMark Murray 			int mod_flag = pflag;
176221e764dfSDag-Erling Smørgrav 			if (!iamrecursive)
176321e764dfSDag-Erling Smørgrav 				SCREWUP("received directory without -r");
1764511b41d2SMark Murray 			if (exists) {
1765511b41d2SMark Murray 				if (!S_ISDIR(stb.st_mode)) {
1766511b41d2SMark Murray 					errno = ENOTDIR;
1767511b41d2SMark Murray 					goto bad;
1768511b41d2SMark Murray 				}
1769511b41d2SMark Murray 				if (pflag)
1770511b41d2SMark Murray 					(void) chmod(np, mode);
1771511b41d2SMark Murray 			} else {
177219261079SEd Maste 				/* Handle copying from a read-only directory */
1773511b41d2SMark Murray 				mod_flag = 1;
177419261079SEd Maste 				if (mkdir(np, mode | S_IRWXU) == -1)
1775511b41d2SMark Murray 					goto bad;
1776511b41d2SMark Murray 			}
17771e8db6e2SBrian Feldman 			vect[0] = xstrdup(np);
1778afde5170SEd Maste 			sink(1, vect, src);
1779511b41d2SMark Murray 			if (setimes) {
1780511b41d2SMark Murray 				setimes = 0;
178119261079SEd Maste 				(void) utimes(vect[0], tv);
1782511b41d2SMark Murray 			}
1783511b41d2SMark Murray 			if (mod_flag)
17841e8db6e2SBrian Feldman 				(void) chmod(vect[0], mode);
1785e4a9863fSDag-Erling Smørgrav 			free(vect[0]);
1786511b41d2SMark Murray 			continue;
1787511b41d2SMark Murray 		}
1788511b41d2SMark Murray 		omode = mode;
1789e4a9863fSDag-Erling Smørgrav 		mode |= S_IWUSR;
179019261079SEd Maste 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1791511b41d2SMark Murray bad:			run_err("%s: %s", np, strerror(errno));
1792511b41d2SMark Murray 			continue;
1793511b41d2SMark Murray 		}
1794cf2b5f3bSDag-Erling Smørgrav 		(void) atomicio(vwrite, remout, "", 1);
1795d4af9e69SDag-Erling Smørgrav 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1796511b41d2SMark Murray 			(void) close(ofd);
1797511b41d2SMark Murray 			continue;
1798511b41d2SMark Murray 		}
1799511b41d2SMark Murray 		cp = bp->buf;
180019261079SEd Maste 		wrerr = 0;
1801511b41d2SMark Murray 
180219261079SEd Maste 		/*
180319261079SEd Maste 		 * NB. do not use run_err() unless immediately followed by
180419261079SEd Maste 		 * exit() below as it may send a spurious reply that might
180519261079SEd Maste 		 * desyncronise us from the peer. Use note_err() instead.
180619261079SEd Maste 		 */
1807511b41d2SMark Murray 		statbytes = 0;
1808e73e9afaSDag-Erling Smørgrav 		if (showprogress)
1809e73e9afaSDag-Erling Smørgrav 			start_progress_meter(curfile, size, &statbytes);
1810d4af9e69SDag-Erling Smørgrav 		set_nonblock(remin);
1811d4af9e69SDag-Erling Smørgrav 		for (count = i = 0; i < size; i += bp->cnt) {
1812d4af9e69SDag-Erling Smørgrav 			amt = bp->cnt;
1813511b41d2SMark Murray 			if (i + amt > size)
1814511b41d2SMark Murray 				amt = size - i;
1815511b41d2SMark Murray 			count += amt;
1816511b41d2SMark Murray 			do {
18174a421b63SDag-Erling Smørgrav 				j = atomicio6(read, remin, cp, amt,
18184a421b63SDag-Erling Smørgrav 				    scpio, &statbytes);
1819d4ecd108SDag-Erling Smørgrav 				if (j == 0) {
1820d4af9e69SDag-Erling Smørgrav 					run_err("%s", j != EPIPE ?
1821d4af9e69SDag-Erling Smørgrav 					    strerror(errno) :
1822511b41d2SMark Murray 					    "dropped connection");
1823511b41d2SMark Murray 					exit(1);
1824511b41d2SMark Murray 				}
1825511b41d2SMark Murray 				amt -= j;
1826511b41d2SMark Murray 				cp += j;
1827511b41d2SMark Murray 			} while (amt > 0);
1828e73e9afaSDag-Erling Smørgrav 
1829511b41d2SMark Murray 			if (count == bp->cnt) {
1830511b41d2SMark Murray 				/* Keep reading so we stay sync'd up. */
183119261079SEd Maste 				if (!wrerr) {
1832d4ecd108SDag-Erling Smørgrav 					if (atomicio(vwrite, ofd, bp->buf,
1833d4ecd108SDag-Erling Smørgrav 					    count) != count) {
183419261079SEd Maste 						note_err("%s: %s", np,
183519261079SEd Maste 						    strerror(errno));
183619261079SEd Maste 						wrerr = 1;
1837511b41d2SMark Murray 					}
1838511b41d2SMark Murray 				}
1839511b41d2SMark Murray 				count = 0;
1840511b41d2SMark Murray 				cp = bp->buf;
1841511b41d2SMark Murray 			}
1842511b41d2SMark Murray 		}
1843d4af9e69SDag-Erling Smørgrav 		unset_nonblock(remin);
184419261079SEd Maste 		if (count != 0 && !wrerr &&
1845d4ecd108SDag-Erling Smørgrav 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
184619261079SEd Maste 			note_err("%s: %s", np, strerror(errno));
184719261079SEd Maste 			wrerr = 1;
1848511b41d2SMark Murray 		}
184919261079SEd Maste 		if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
185019261079SEd Maste 		    ftruncate(ofd, size) != 0)
185119261079SEd Maste 			note_err("%s: truncate: %s", np, strerror(errno));
1852511b41d2SMark Murray 		if (pflag) {
1853511b41d2SMark Murray 			if (exists || omode != mode)
185483d2307dSDag-Erling Smørgrav #ifdef HAVE_FCHMOD
185521e764dfSDag-Erling Smørgrav 				if (fchmod(ofd, omode)) {
185683d2307dSDag-Erling Smørgrav #else /* HAVE_FCHMOD */
185721e764dfSDag-Erling Smørgrav 				if (chmod(np, omode)) {
185883d2307dSDag-Erling Smørgrav #endif /* HAVE_FCHMOD */
185919261079SEd Maste 					note_err("%s: set mode: %s",
1860511b41d2SMark Murray 					    np, strerror(errno));
186121e764dfSDag-Erling Smørgrav 				}
1862511b41d2SMark Murray 		} else {
1863511b41d2SMark Murray 			if (!exists && omode != mode)
186483d2307dSDag-Erling Smørgrav #ifdef HAVE_FCHMOD
186521e764dfSDag-Erling Smørgrav 				if (fchmod(ofd, omode & ~mask)) {
186683d2307dSDag-Erling Smørgrav #else /* HAVE_FCHMOD */
186721e764dfSDag-Erling Smørgrav 				if (chmod(np, omode & ~mask)) {
186883d2307dSDag-Erling Smørgrav #endif /* HAVE_FCHMOD */
186919261079SEd Maste 					note_err("%s: set mode: %s",
1870511b41d2SMark Murray 					    np, strerror(errno));
187121e764dfSDag-Erling Smørgrav 				}
1872511b41d2SMark Murray 		}
187319261079SEd Maste 		if (close(ofd) == -1)
187419261079SEd Maste 			note_err("%s: close: %s", np, strerror(errno));
1875511b41d2SMark Murray 		(void) response();
1876076ad2f8SDag-Erling Smørgrav 		if (showprogress)
1877076ad2f8SDag-Erling Smørgrav 			stop_progress_meter();
187819261079SEd Maste 		if (setimes && !wrerr) {
1879511b41d2SMark Murray 			setimes = 0;
188019261079SEd Maste 			if (utimes(np, tv) == -1) {
188119261079SEd Maste 				note_err("%s: set times: %s",
1882511b41d2SMark Murray 				    np, strerror(errno));
1883511b41d2SMark Murray 			}
1884511b41d2SMark Murray 		}
188519261079SEd Maste 		/* If no error was noted then signal success for this file */
188619261079SEd Maste 		if (note_err(NULL) == 0)
1887cf2b5f3bSDag-Erling Smørgrav 			(void) atomicio(vwrite, remout, "", 1);
1888511b41d2SMark Murray 	}
18890967215dSEd Maste done:
18900967215dSEd Maste 	for (n = 0; n < npatterns; n++)
18910967215dSEd Maste 		free(patterns[n]);
18920967215dSEd Maste 	free(patterns);
18930967215dSEd Maste 	return;
1894511b41d2SMark Murray screwup:
18950967215dSEd Maste 	for (n = 0; n < npatterns; n++)
18960967215dSEd Maste 		free(patterns[n]);
18970967215dSEd Maste 	free(patterns);
1898511b41d2SMark Murray 	run_err("protocol error: %s", why);
1899511b41d2SMark Murray 	exit(1);
1900511b41d2SMark Murray }
1901511b41d2SMark Murray 
190219261079SEd Maste void
190319261079SEd Maste throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
190419261079SEd Maste     char *src, char *targ)
190519261079SEd Maste {
190619261079SEd Maste 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
190719261079SEd Maste 	char *abs_src = NULL, *tmp = NULL;
190819261079SEd Maste 	glob_t g;
190919261079SEd Maste 	int i, r, targetisdir, err = 0;
191019261079SEd Maste 
191119261079SEd Maste 	if ((filename = basename(src)) == NULL)
191219261079SEd Maste 		fatal("basename %s: %s", src, strerror(errno));
191319261079SEd Maste 
191419261079SEd Maste 	if ((abs_src = prepare_remote_path(from, src)) == NULL ||
191519261079SEd Maste 	    (target = prepare_remote_path(to, targ)) == NULL)
191619261079SEd Maste 		cleanup_exit(255);
191719261079SEd Maste 	memset(&g, 0, sizeof(g));
191819261079SEd Maste 
191919261079SEd Maste 	targetisdir = remote_is_dir(to, target);
192019261079SEd Maste 	if (!targetisdir && targetshouldbedirectory) {
19211323ec57SEd Maste 		error("%s: destination is not a directory", targ);
192219261079SEd Maste 		err = -1;
192319261079SEd Maste 		goto out;
192419261079SEd Maste 	}
192519261079SEd Maste 
192619261079SEd Maste 	debug3_f("copying remote %s to remote %s", abs_src, target);
192719261079SEd Maste 	if ((r = remote_glob(from, abs_src, GLOB_MARK, NULL, &g)) != 0) {
192819261079SEd Maste 		if (r == GLOB_NOSPACE)
19291323ec57SEd Maste 			error("%s: too many glob matches", src);
193019261079SEd Maste 		else
19311323ec57SEd Maste 			error("%s: %s", src, strerror(ENOENT));
193219261079SEd Maste 		err = -1;
193319261079SEd Maste 		goto out;
193419261079SEd Maste 	}
193519261079SEd Maste 
193619261079SEd Maste 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
193719261079SEd Maste 		tmp = xstrdup(g.gl_pathv[i]);
193819261079SEd Maste 		if ((filename = basename(tmp)) == NULL) {
193919261079SEd Maste 			error("basename %s: %s", tmp, strerror(errno));
194019261079SEd Maste 			err = -1;
194119261079SEd Maste 			goto out;
194219261079SEd Maste 		}
194319261079SEd Maste 
194419261079SEd Maste 		if (targetisdir)
194519261079SEd Maste 			abs_dst = path_append(target, filename);
194619261079SEd Maste 		else
194719261079SEd Maste 			abs_dst = xstrdup(target);
194819261079SEd Maste 
194919261079SEd Maste 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
195019261079SEd Maste 		if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
195119261079SEd Maste 			if (crossload_dir(from, to, g.gl_pathv[i], abs_dst,
195219261079SEd Maste 			    NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
195319261079SEd Maste 				err = -1;
195419261079SEd Maste 		} else {
195519261079SEd Maste 			if (do_crossload(from, to, g.gl_pathv[i], abs_dst, NULL,
195619261079SEd Maste 			    pflag) == -1)
195719261079SEd Maste 				err = -1;
195819261079SEd Maste 		}
195919261079SEd Maste 		free(abs_dst);
196019261079SEd Maste 		abs_dst = NULL;
196119261079SEd Maste 		free(tmp);
196219261079SEd Maste 		tmp = NULL;
196319261079SEd Maste 	}
196419261079SEd Maste 
196519261079SEd Maste out:
196619261079SEd Maste 	free(abs_src);
196719261079SEd Maste 	free(abs_dst);
196819261079SEd Maste 	free(target);
196919261079SEd Maste 	free(tmp);
197019261079SEd Maste 	globfree(&g);
197119261079SEd Maste 	if (err == -1)
1972e9e8876aSEd Maste 		errs = 1;
197319261079SEd Maste }
197419261079SEd Maste 
1975511b41d2SMark Murray int
1976ae1f160dSDag-Erling Smørgrav response(void)
1977511b41d2SMark Murray {
1978076ad2f8SDag-Erling Smørgrav 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
1979511b41d2SMark Murray 
1980a04a10f8SKris Kennaway 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1981511b41d2SMark Murray 		lostconn(0);
1982511b41d2SMark Murray 
1983511b41d2SMark Murray 	cp = rbuf;
1984511b41d2SMark Murray 	switch (resp) {
1985511b41d2SMark Murray 	case 0:		/* ok */
1986511b41d2SMark Murray 		return (0);
1987511b41d2SMark Murray 	default:
1988511b41d2SMark Murray 		*cp++ = resp;
1989511b41d2SMark Murray 		/* FALLTHROUGH */
1990511b41d2SMark Murray 	case 1:		/* error, followed by error msg */
1991511b41d2SMark Murray 	case 2:		/* fatal error, "" */
1992511b41d2SMark Murray 		do {
1993a04a10f8SKris Kennaway 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1994511b41d2SMark Murray 				lostconn(0);
1995511b41d2SMark Murray 			*cp++ = ch;
1996511b41d2SMark Murray 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1997511b41d2SMark Murray 
1998076ad2f8SDag-Erling Smørgrav 		if (!iamremote) {
1999076ad2f8SDag-Erling Smørgrav 			cp[-1] = '\0';
2000076ad2f8SDag-Erling Smørgrav 			(void) snmprintf(visbuf, sizeof(visbuf),
2001076ad2f8SDag-Erling Smørgrav 			    NULL, "%s\n", rbuf);
2002076ad2f8SDag-Erling Smørgrav 			(void) atomicio(vwrite, STDERR_FILENO,
2003076ad2f8SDag-Erling Smørgrav 			    visbuf, strlen(visbuf));
2004076ad2f8SDag-Erling Smørgrav 		}
2005511b41d2SMark Murray 		++errs;
2006511b41d2SMark Murray 		if (resp == 1)
2007511b41d2SMark Murray 			return (-1);
2008511b41d2SMark Murray 		exit(1);
2009511b41d2SMark Murray 	}
2010511b41d2SMark Murray 	/* NOTREACHED */
2011511b41d2SMark Murray }
2012511b41d2SMark Murray 
2013511b41d2SMark Murray void
2014ae1f160dSDag-Erling Smørgrav usage(void)
2015511b41d2SMark Murray {
2016ae1f160dSDag-Erling Smørgrav 	(void) fprintf(stderr,
201719261079SEd Maste 	    "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
201819261079SEd Maste 	    "           [-i identity_file] [-J destination] [-l limit]\n"
201919261079SEd Maste 	    "           [-o ssh_option] [-P port] [-S program] source ... target\n");
2020511b41d2SMark Murray 	exit(1);
2021511b41d2SMark Murray }
2022511b41d2SMark Murray 
2023511b41d2SMark Murray void
2024511b41d2SMark Murray run_err(const char *fmt,...)
2025511b41d2SMark Murray {
2026511b41d2SMark Murray 	static FILE *fp;
2027511b41d2SMark Murray 	va_list ap;
2028511b41d2SMark Murray 
2029511b41d2SMark Murray 	++errs;
2030333ee039SDag-Erling Smørgrav 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
2031511b41d2SMark Murray 		(void) fprintf(fp, "%c", 0x01);
2032511b41d2SMark Murray 		(void) fprintf(fp, "scp: ");
2033ae1f160dSDag-Erling Smørgrav 		va_start(ap, fmt);
2034511b41d2SMark Murray 		(void) vfprintf(fp, fmt, ap);
2035ae1f160dSDag-Erling Smørgrav 		va_end(ap);
2036511b41d2SMark Murray 		(void) fprintf(fp, "\n");
2037511b41d2SMark Murray 		(void) fflush(fp);
2038333ee039SDag-Erling Smørgrav 	}
2039511b41d2SMark Murray 
2040511b41d2SMark Murray 	if (!iamremote) {
2041ae1f160dSDag-Erling Smørgrav 		va_start(ap, fmt);
2042076ad2f8SDag-Erling Smørgrav 		vfmprintf(stderr, fmt, ap);
2043ae1f160dSDag-Erling Smørgrav 		va_end(ap);
2044511b41d2SMark Murray 		fprintf(stderr, "\n");
2045511b41d2SMark Murray 	}
2046511b41d2SMark Murray }
2047511b41d2SMark Murray 
204819261079SEd Maste /*
204919261079SEd Maste  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
205019261079SEd Maste  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
205119261079SEd Maste  * any active error at the end of the transfer.
205219261079SEd Maste  */
205319261079SEd Maste int
205419261079SEd Maste note_err(const char *fmt, ...)
205519261079SEd Maste {
205619261079SEd Maste 	static char *emsg;
205719261079SEd Maste 	va_list ap;
205819261079SEd Maste 
205919261079SEd Maste 	/* Replay any previously-noted error */
206019261079SEd Maste 	if (fmt == NULL) {
206119261079SEd Maste 		if (emsg == NULL)
206219261079SEd Maste 			return 0;
206319261079SEd Maste 		run_err("%s", emsg);
206419261079SEd Maste 		free(emsg);
206519261079SEd Maste 		emsg = NULL;
206619261079SEd Maste 		return -1;
206719261079SEd Maste 	}
206819261079SEd Maste 
206919261079SEd Maste 	errs++;
207019261079SEd Maste 	/* Prefer first-noted error */
207119261079SEd Maste 	if (emsg != NULL)
207219261079SEd Maste 		return -1;
207319261079SEd Maste 
207419261079SEd Maste 	va_start(ap, fmt);
207519261079SEd Maste 	vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
207619261079SEd Maste 	va_end(ap);
207719261079SEd Maste 	return -1;
207819261079SEd Maste }
207919261079SEd Maste 
2080511b41d2SMark Murray void
2081cf2b5f3bSDag-Erling Smørgrav verifydir(char *cp)
2082511b41d2SMark Murray {
2083511b41d2SMark Murray 	struct stat stb;
2084511b41d2SMark Murray 
2085511b41d2SMark Murray 	if (!stat(cp, &stb)) {
2086511b41d2SMark Murray 		if (S_ISDIR(stb.st_mode))
2087511b41d2SMark Murray 			return;
2088511b41d2SMark Murray 		errno = ENOTDIR;
2089511b41d2SMark Murray 	}
2090511b41d2SMark Murray 	run_err("%s: %s", cp, strerror(errno));
2091d4ecd108SDag-Erling Smørgrav 	killchild(0);
2092511b41d2SMark Murray }
2093511b41d2SMark Murray 
2094511b41d2SMark Murray int
2095cf2b5f3bSDag-Erling Smørgrav okname(char *cp0)
2096511b41d2SMark Murray {
2097511b41d2SMark Murray 	int c;
2098511b41d2SMark Murray 	char *cp;
2099511b41d2SMark Murray 
2100511b41d2SMark Murray 	cp = cp0;
2101511b41d2SMark Murray 	do {
2102ae1f160dSDag-Erling Smørgrav 		c = (int)*cp;
2103511b41d2SMark Murray 		if (c & 0200)
2104511b41d2SMark Murray 			goto bad;
2105f7167e0eSDag-Erling Smørgrav 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
2106e73e9afaSDag-Erling Smørgrav 			switch (c) {
2107e73e9afaSDag-Erling Smørgrav 			case '\'':
2108e73e9afaSDag-Erling Smørgrav 			case '"':
2109e73e9afaSDag-Erling Smørgrav 			case '`':
2110e73e9afaSDag-Erling Smørgrav 			case ' ':
2111e73e9afaSDag-Erling Smørgrav 			case '#':
2112511b41d2SMark Murray 				goto bad;
2113e73e9afaSDag-Erling Smørgrav 			default:
2114e73e9afaSDag-Erling Smørgrav 				break;
2115e73e9afaSDag-Erling Smørgrav 			}
2116e73e9afaSDag-Erling Smørgrav 		}
2117511b41d2SMark Murray 	} while (*++cp);
2118511b41d2SMark Murray 	return (1);
2119511b41d2SMark Murray 
2120076ad2f8SDag-Erling Smørgrav bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
2121511b41d2SMark Murray 	return (0);
2122511b41d2SMark Murray }
2123511b41d2SMark Murray 
2124511b41d2SMark Murray BUF *
2125cf2b5f3bSDag-Erling Smørgrav allocbuf(BUF *bp, int fd, int blksize)
2126511b41d2SMark Murray {
2127511b41d2SMark Murray 	size_t size;
212883d2307dSDag-Erling Smørgrav #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2129511b41d2SMark Murray 	struct stat stb;
2130511b41d2SMark Murray 
213119261079SEd Maste 	if (fstat(fd, &stb) == -1) {
2132511b41d2SMark Murray 		run_err("fstat: %s", strerror(errno));
2133511b41d2SMark Murray 		return (0);
2134511b41d2SMark Murray 	}
2135ca86bcf2SDag-Erling Smørgrav 	size = ROUNDUP(stb.st_blksize, blksize);
2136e73e9afaSDag-Erling Smørgrav 	if (size == 0)
2137e73e9afaSDag-Erling Smørgrav 		size = blksize;
213883d2307dSDag-Erling Smørgrav #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
213983d2307dSDag-Erling Smørgrav 	size = blksize;
214083d2307dSDag-Erling Smørgrav #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2141511b41d2SMark Murray 	if (bp->cnt >= size)
2142511b41d2SMark Murray 		return (bp);
21434f52dfbbSDag-Erling Smørgrav 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
2144511b41d2SMark Murray 	bp->cnt = size;
2145511b41d2SMark Murray 	return (bp);
2146511b41d2SMark Murray }
2147511b41d2SMark Murray 
2148511b41d2SMark Murray void
2149cf2b5f3bSDag-Erling Smørgrav lostconn(int signo)
2150511b41d2SMark Murray {
2151511b41d2SMark Murray 	if (!iamremote)
2152e4a9863fSDag-Erling Smørgrav 		(void)write(STDERR_FILENO, "lost connection\n", 16);
2153ae1f160dSDag-Erling Smørgrav 	if (signo)
2154ae1f160dSDag-Erling Smørgrav 		_exit(1);
2155ae1f160dSDag-Erling Smørgrav 	else
2156511b41d2SMark Murray 		exit(1);
2157511b41d2SMark Murray }
215819261079SEd Maste 
215919261079SEd Maste void
216019261079SEd Maste cleanup_exit(int i)
216119261079SEd Maste {
216219261079SEd Maste 	if (remin > 0)
216319261079SEd Maste 		close(remin);
216419261079SEd Maste 	if (remout > 0)
216519261079SEd Maste 		close(remout);
216619261079SEd Maste 	if (remin2 > 0)
216719261079SEd Maste 		close(remin2);
216819261079SEd Maste 	if (remout2 > 0)
216919261079SEd Maste 		close(remout2);
217019261079SEd Maste 	if (do_cmd_pid > 0)
217119261079SEd Maste 		waitpid(do_cmd_pid, NULL, 0);
217219261079SEd Maste 	if (do_cmd_pid2 > 0)
217319261079SEd Maste 		waitpid(do_cmd_pid2, NULL, 0);
217419261079SEd Maste 	exit(i);
217519261079SEd Maste }
2176