xref: /freebsd/crypto/openssh/scp.c (revision 069ac184)
1069ac184SEd Maste /* $OpenBSD: scp.c,v 1.260 2023/10/11 05:42:08 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>
109f374ba41SEd Maste #ifdef HAVE_UTIL_H
110f374ba41SEd Maste # include <util.h>
111f374ba41SEd Maste #endif
112076ad2f8SDag-Erling Smørgrav #include <locale.h>
113333ee039SDag-Erling Smørgrav #include <pwd.h>
114333ee039SDag-Erling Smørgrav #include <signal.h>
115333ee039SDag-Erling Smørgrav #include <stdarg.h>
1164f52dfbbSDag-Erling Smørgrav #ifdef HAVE_STDINT_H
1174f52dfbbSDag-Erling Smørgrav # include <stdint.h>
1184f52dfbbSDag-Erling Smørgrav #endif
119333ee039SDag-Erling Smørgrav #include <stdio.h>
120333ee039SDag-Erling Smørgrav #include <stdlib.h>
121333ee039SDag-Erling Smørgrav #include <string.h>
122333ee039SDag-Erling Smørgrav #include <time.h>
123333ee039SDag-Erling Smørgrav #include <unistd.h>
1246888a9beSDag-Erling Smørgrav #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
125d4af9e69SDag-Erling Smørgrav #include <vis.h>
126d4af9e69SDag-Erling Smørgrav #endif
127511b41d2SMark Murray 
128511b41d2SMark Murray #include "xmalloc.h"
12947dd1d1bSDag-Erling Smørgrav #include "ssh.h"
1301e8db6e2SBrian Feldman #include "atomicio.h"
1311e8db6e2SBrian Feldman #include "pathnames.h"
1321e8db6e2SBrian Feldman #include "log.h"
133ae1f160dSDag-Erling Smørgrav #include "misc.h"
134e73e9afaSDag-Erling Smørgrav #include "progressmeter.h"
135076ad2f8SDag-Erling Smørgrav #include "utf8.h"
1361323ec57SEd Maste #include "sftp.h"
137511b41d2SMark Murray 
13819261079SEd Maste #include "sftp-common.h"
13919261079SEd Maste #include "sftp-client.h"
14019261079SEd Maste 
14183d2307dSDag-Erling Smørgrav extern char *__progname;
14283d2307dSDag-Erling Smørgrav 
143d4af9e69SDag-Erling Smørgrav #define COPY_BUFLEN	16384
144d4af9e69SDag-Erling Smørgrav 
14519261079SEd Maste int do_cmd(char *, char *, char *, int, int, char *, int *, int *, pid_t *);
14619261079SEd Maste int do_cmd2(char *, char *, int, char *, int, int);
147511b41d2SMark Murray 
148ae1f160dSDag-Erling Smørgrav /* Struct for addargs */
149ae1f160dSDag-Erling Smørgrav arglist args;
1504a421b63SDag-Erling Smørgrav arglist remote_remote_args;
1515b9b2fafSBrian Feldman 
152e73e9afaSDag-Erling Smørgrav /* Bandwidth limit */
1534a421b63SDag-Erling Smørgrav long long limit_kbps = 0;
1544a421b63SDag-Erling Smørgrav struct bwlimit bwlimit;
155511b41d2SMark Murray 
156511b41d2SMark Murray /* Name of current file being transferred. */
157511b41d2SMark Murray char *curfile;
158511b41d2SMark Murray 
159511b41d2SMark Murray /* This is set to non-zero to enable verbose mode. */
160511b41d2SMark Murray int verbose_mode = 0;
16119261079SEd Maste LogLevel log_level = SYSLOG_LEVEL_INFO;
162511b41d2SMark Murray 
163511b41d2SMark Murray /* This is set to zero if the progressmeter is not desired. */
164511b41d2SMark Murray int showprogress = 1;
165511b41d2SMark Murray 
1664a421b63SDag-Erling Smørgrav /*
1674a421b63SDag-Erling Smørgrav  * This is set to non-zero if remote-remote copy should be piped
1684a421b63SDag-Erling Smørgrav  * through this process.
1694a421b63SDag-Erling Smørgrav  */
17019261079SEd Maste int throughlocal = 1;
1714a421b63SDag-Erling Smørgrav 
17247dd1d1bSDag-Erling Smørgrav /* Non-standard port to use for the ssh connection or -1. */
17347dd1d1bSDag-Erling Smørgrav int sshport = -1;
17447dd1d1bSDag-Erling Smørgrav 
175b66f2d16SKris Kennaway /* This is the program to execute for the secured connection. ("ssh" or -S) */
1761e8db6e2SBrian Feldman char *ssh_program = _PATH_SSH_PROGRAM;
177b66f2d16SKris Kennaway 
178e73e9afaSDag-Erling Smørgrav /* This is used to store the pid of ssh_program */
179cf2b5f3bSDag-Erling Smørgrav pid_t do_cmd_pid = -1;
18019261079SEd Maste pid_t do_cmd_pid2 = -1;
18119261079SEd Maste 
182f374ba41SEd Maste /* SFTP copy parameters */
183f374ba41SEd Maste size_t sftp_copy_buflen;
184f374ba41SEd Maste size_t sftp_nrequests;
185f374ba41SEd Maste 
18619261079SEd Maste /* Needed for sftp */
18719261079SEd Maste volatile sig_atomic_t interrupted = 0;
18819261079SEd Maste 
189edf85781SEd Maste int sftp_glob(struct sftp_conn *, const char *, int,
19019261079SEd Maste     int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */
191cf2b5f3bSDag-Erling Smørgrav 
192cf2b5f3bSDag-Erling Smørgrav static void
killchild(int signo)193cf2b5f3bSDag-Erling Smørgrav killchild(int signo)
194cf2b5f3bSDag-Erling Smørgrav {
195aa49c926SDag-Erling Smørgrav 	if (do_cmd_pid > 1) {
196d4ecd108SDag-Erling Smørgrav 		kill(do_cmd_pid, signo ? signo : SIGTERM);
197535af610SEd Maste 		(void)waitpid(do_cmd_pid, NULL, 0);
198aa49c926SDag-Erling Smørgrav 	}
19919261079SEd Maste 	if (do_cmd_pid2 > 1) {
20019261079SEd Maste 		kill(do_cmd_pid2, signo ? signo : SIGTERM);
201535af610SEd Maste 		(void)waitpid(do_cmd_pid2, NULL, 0);
20219261079SEd Maste 	}
203cf2b5f3bSDag-Erling Smørgrav 
204d4ecd108SDag-Erling Smørgrav 	if (signo)
205cf2b5f3bSDag-Erling Smørgrav 		_exit(1);
206d4ecd108SDag-Erling Smørgrav 	exit(1);
207cf2b5f3bSDag-Erling Smørgrav }
208e73e9afaSDag-Erling Smørgrav 
209e2f6069cSDag-Erling Smørgrav static void
suspone(int pid,int signo)21019261079SEd Maste suspone(int pid, int signo)
211e2f6069cSDag-Erling Smørgrav {
212e2f6069cSDag-Erling Smørgrav 	int status;
213e2f6069cSDag-Erling Smørgrav 
21419261079SEd Maste 	if (pid > 1) {
21519261079SEd Maste 		kill(pid, signo);
21619261079SEd Maste 		while (waitpid(pid, &status, WUNTRACED) == -1 &&
217e2f6069cSDag-Erling Smørgrav 		    errno == EINTR)
218e2f6069cSDag-Erling Smørgrav 			;
219e2f6069cSDag-Erling Smørgrav 	}
220e2f6069cSDag-Erling Smørgrav }
221e2f6069cSDag-Erling Smørgrav 
22219261079SEd Maste static void
suspchild(int signo)22319261079SEd Maste suspchild(int signo)
22419261079SEd Maste {
22519261079SEd Maste 	suspone(do_cmd_pid, signo);
22619261079SEd Maste 	suspone(do_cmd_pid2, signo);
22719261079SEd Maste 	kill(getpid(), SIGSTOP);
22819261079SEd Maste }
22919261079SEd Maste 
230b74df5b2SDag-Erling Smørgrav static int
do_local_cmd(arglist * a)231b74df5b2SDag-Erling Smørgrav do_local_cmd(arglist *a)
232b74df5b2SDag-Erling Smørgrav {
233b74df5b2SDag-Erling Smørgrav 	u_int i;
234b74df5b2SDag-Erling Smørgrav 	int status;
235b74df5b2SDag-Erling Smørgrav 	pid_t pid;
236b74df5b2SDag-Erling Smørgrav 
237b74df5b2SDag-Erling Smørgrav 	if (a->num == 0)
238b74df5b2SDag-Erling Smørgrav 		fatal("do_local_cmd: no arguments");
239b74df5b2SDag-Erling Smørgrav 
240b74df5b2SDag-Erling Smørgrav 	if (verbose_mode) {
241b74df5b2SDag-Erling Smørgrav 		fprintf(stderr, "Executing:");
242b74df5b2SDag-Erling Smørgrav 		for (i = 0; i < a->num; i++)
243076ad2f8SDag-Erling Smørgrav 			fmprintf(stderr, " %s", a->list[i]);
244b74df5b2SDag-Erling Smørgrav 		fprintf(stderr, "\n");
245b74df5b2SDag-Erling Smørgrav 	}
246b74df5b2SDag-Erling Smørgrav 	if ((pid = fork()) == -1)
247b74df5b2SDag-Erling Smørgrav 		fatal("do_local_cmd: fork: %s", strerror(errno));
248b74df5b2SDag-Erling Smørgrav 
249b74df5b2SDag-Erling Smørgrav 	if (pid == 0) {
250b74df5b2SDag-Erling Smørgrav 		execvp(a->list[0], a->list);
251b74df5b2SDag-Erling Smørgrav 		perror(a->list[0]);
252b74df5b2SDag-Erling Smørgrav 		exit(1);
253b74df5b2SDag-Erling Smørgrav 	}
254b74df5b2SDag-Erling Smørgrav 
255b74df5b2SDag-Erling Smørgrav 	do_cmd_pid = pid;
25619261079SEd Maste 	ssh_signal(SIGTERM, killchild);
25719261079SEd Maste 	ssh_signal(SIGINT, killchild);
25819261079SEd Maste 	ssh_signal(SIGHUP, killchild);
259b74df5b2SDag-Erling Smørgrav 
260b74df5b2SDag-Erling Smørgrav 	while (waitpid(pid, &status, 0) == -1)
261b74df5b2SDag-Erling Smørgrav 		if (errno != EINTR)
262b74df5b2SDag-Erling Smørgrav 			fatal("do_local_cmd: waitpid: %s", strerror(errno));
263b74df5b2SDag-Erling Smørgrav 
264b74df5b2SDag-Erling Smørgrav 	do_cmd_pid = -1;
265b74df5b2SDag-Erling Smørgrav 
266b74df5b2SDag-Erling Smørgrav 	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
267b74df5b2SDag-Erling Smørgrav 		return (-1);
268b74df5b2SDag-Erling Smørgrav 
269b74df5b2SDag-Erling Smørgrav 	return (0);
270b74df5b2SDag-Erling Smørgrav }
271b74df5b2SDag-Erling Smørgrav 
272511b41d2SMark Murray /*
273511b41d2SMark Murray  * This function executes the given command as the specified user on the
274511b41d2SMark Murray  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
275511b41d2SMark Murray  * assigns the input and output file descriptors on success.
276511b41d2SMark Murray  */
277511b41d2SMark Murray 
278511b41d2SMark Murray int
do_cmd(char * program,char * host,char * remuser,int port,int subsystem,char * cmd,int * fdin,int * fdout,pid_t * pid)27919261079SEd Maste do_cmd(char *program, char *host, char *remuser, int port, int subsystem,
28019261079SEd Maste     char *cmd, int *fdin, int *fdout, pid_t *pid)
281511b41d2SMark Murray {
282f374ba41SEd Maste #ifdef USE_PIPES
283f374ba41SEd Maste 	int pin[2], pout[2];
284f374ba41SEd Maste #else
285f374ba41SEd Maste 	int sv[2];
286f374ba41SEd Maste #endif
287511b41d2SMark Murray 
288511b41d2SMark Murray 	if (verbose_mode)
289076ad2f8SDag-Erling Smørgrav 		fmprintf(stderr,
290ae1f160dSDag-Erling Smørgrav 		    "Executing: program %s host %s, user %s, command %s\n",
29119261079SEd Maste 		    program, host,
292ae1f160dSDag-Erling Smørgrav 		    remuser ? remuser : "(unspecified)", cmd);
293511b41d2SMark Murray 
29447dd1d1bSDag-Erling Smørgrav 	if (port == -1)
29547dd1d1bSDag-Erling Smørgrav 		port = sshport;
29647dd1d1bSDag-Erling Smørgrav 
297f374ba41SEd Maste #ifdef USE_PIPES
298f374ba41SEd Maste 	if (pipe(pin) == -1 || pipe(pout) == -1)
299333ee039SDag-Erling Smørgrav 		fatal("pipe: %s", strerror(errno));
300f374ba41SEd Maste #else
301511b41d2SMark Murray 	/* Create a socket pair for communicating with ssh. */
302f374ba41SEd Maste 	if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1)
303f374ba41SEd Maste 		fatal("socketpair: %s", strerror(errno));
304f374ba41SEd Maste #endif
305511b41d2SMark Murray 
30619261079SEd Maste 	ssh_signal(SIGTSTP, suspchild);
30719261079SEd Maste 	ssh_signal(SIGTTIN, suspchild);
30819261079SEd Maste 	ssh_signal(SIGTTOU, suspchild);
309e2f6069cSDag-Erling Smørgrav 
310cf2b5f3bSDag-Erling Smørgrav 	/* Fork a child to execute the command on the remote host using ssh. */
31119261079SEd Maste 	*pid = fork();
312f374ba41SEd Maste 	switch (*pid) {
313f374ba41SEd Maste 	case -1:
314f374ba41SEd Maste 		fatal("fork: %s", strerror(errno));
315f374ba41SEd Maste 	case 0:
316511b41d2SMark Murray 		/* Child. */
317f374ba41SEd Maste #ifdef USE_PIPES
318f374ba41SEd Maste 		if (dup2(pin[0], STDIN_FILENO) == -1 ||
319f374ba41SEd Maste 		    dup2(pout[1], STDOUT_FILENO) == -1) {
320f374ba41SEd Maste 			error("dup2: %s", strerror(errno));
321f374ba41SEd Maste 			_exit(1);
322f374ba41SEd Maste 		}
323f374ba41SEd Maste 		close(pin[0]);
324511b41d2SMark Murray 		close(pin[1]);
325511b41d2SMark Murray 		close(pout[0]);
326511b41d2SMark Murray 		close(pout[1]);
327f374ba41SEd Maste #else
328f374ba41SEd Maste 		if (dup2(sv[0], STDIN_FILENO) == -1 ||
329f374ba41SEd Maste 		    dup2(sv[0], STDOUT_FILENO) == -1) {
330f374ba41SEd Maste 			error("dup2: %s", strerror(errno));
331f374ba41SEd Maste 			_exit(1);
332f374ba41SEd Maste 		}
333f374ba41SEd Maste 		close(sv[0]);
334f374ba41SEd Maste 		close(sv[1]);
335f374ba41SEd Maste #endif
33619261079SEd Maste 		replacearg(&args, 0, "%s", program);
33747dd1d1bSDag-Erling Smørgrav 		if (port != -1) {
33847dd1d1bSDag-Erling Smørgrav 			addargs(&args, "-p");
33947dd1d1bSDag-Erling Smørgrav 			addargs(&args, "%d", port);
34047dd1d1bSDag-Erling Smørgrav 		}
341b15c8340SDag-Erling Smørgrav 		if (remuser != NULL) {
342b15c8340SDag-Erling Smørgrav 			addargs(&args, "-l");
343b15c8340SDag-Erling Smørgrav 			addargs(&args, "%s", remuser);
344b15c8340SDag-Erling Smørgrav 		}
34519261079SEd Maste 		if (subsystem)
34619261079SEd Maste 			addargs(&args, "-s");
347b15c8340SDag-Erling Smørgrav 		addargs(&args, "--");
348ae1f160dSDag-Erling Smørgrav 		addargs(&args, "%s", host);
349ae1f160dSDag-Erling Smørgrav 		addargs(&args, "%s", cmd);
350511b41d2SMark Murray 
35119261079SEd Maste 		execvp(program, args.list);
35219261079SEd Maste 		perror(program);
353f374ba41SEd Maste 		_exit(1);
354f374ba41SEd Maste 	default:
355511b41d2SMark Murray 		/* Parent.  Close the other side, and return the local side. */
356f374ba41SEd Maste #ifdef USE_PIPES
357511b41d2SMark Murray 		close(pin[0]);
358511b41d2SMark Murray 		close(pout[1]);
359f374ba41SEd Maste 		*fdout = pin[1];
360511b41d2SMark Murray 		*fdin = pout[0];
361f374ba41SEd Maste #else
362f374ba41SEd Maste 		close(sv[0]);
363f374ba41SEd Maste 		*fdin = sv[1];
364f374ba41SEd Maste 		*fdout = sv[1];
365f374ba41SEd Maste #endif
36619261079SEd Maste 		ssh_signal(SIGTERM, killchild);
36719261079SEd Maste 		ssh_signal(SIGINT, killchild);
36819261079SEd Maste 		ssh_signal(SIGHUP, killchild);
369511b41d2SMark Murray 		return 0;
370511b41d2SMark Murray 	}
371f374ba41SEd Maste }
372511b41d2SMark Murray 
3734a421b63SDag-Erling Smørgrav /*
374190cef3dSDag-Erling Smørgrav  * This function executes a command similar to do_cmd(), but expects the
3754a421b63SDag-Erling Smørgrav  * input and output descriptors to be setup by a previous call to do_cmd().
3764a421b63SDag-Erling Smørgrav  * This way the input and output of two commands can be connected.
3774a421b63SDag-Erling Smørgrav  */
3784a421b63SDag-Erling Smørgrav int
do_cmd2(char * host,char * remuser,int port,char * cmd,int fdin,int fdout)37919261079SEd Maste do_cmd2(char *host, char *remuser, int port, char *cmd,
38019261079SEd Maste     int fdin, int fdout)
3814a421b63SDag-Erling Smørgrav {
3824a421b63SDag-Erling Smørgrav 	int status;
38319261079SEd Maste 	pid_t pid;
3844a421b63SDag-Erling Smørgrav 
3854a421b63SDag-Erling Smørgrav 	if (verbose_mode)
386076ad2f8SDag-Erling Smørgrav 		fmprintf(stderr,
3874a421b63SDag-Erling Smørgrav 		    "Executing: 2nd program %s host %s, user %s, command %s\n",
3884a421b63SDag-Erling Smørgrav 		    ssh_program, host,
3894a421b63SDag-Erling Smørgrav 		    remuser ? remuser : "(unspecified)", cmd);
3904a421b63SDag-Erling Smørgrav 
39147dd1d1bSDag-Erling Smørgrav 	if (port == -1)
39247dd1d1bSDag-Erling Smørgrav 		port = sshport;
39347dd1d1bSDag-Erling Smørgrav 
3944a421b63SDag-Erling Smørgrav 	/* Fork a child to execute the command on the remote host using ssh. */
3954a421b63SDag-Erling Smørgrav 	pid = fork();
3964a421b63SDag-Erling Smørgrav 	if (pid == 0) {
3974d3fc8b0SEd Maste 		if (dup2(fdin, 0) == -1)
3984d3fc8b0SEd Maste 			perror("dup2");
3994d3fc8b0SEd Maste 		if (dup2(fdout, 1) == -1)
4004d3fc8b0SEd Maste 			perror("dup2");
4014a421b63SDag-Erling Smørgrav 
4024a421b63SDag-Erling Smørgrav 		replacearg(&args, 0, "%s", ssh_program);
40347dd1d1bSDag-Erling Smørgrav 		if (port != -1) {
40447dd1d1bSDag-Erling Smørgrav 			addargs(&args, "-p");
40547dd1d1bSDag-Erling Smørgrav 			addargs(&args, "%d", port);
40647dd1d1bSDag-Erling Smørgrav 		}
4074a421b63SDag-Erling Smørgrav 		if (remuser != NULL) {
4084a421b63SDag-Erling Smørgrav 			addargs(&args, "-l");
4094a421b63SDag-Erling Smørgrav 			addargs(&args, "%s", remuser);
4104a421b63SDag-Erling Smørgrav 		}
41119261079SEd Maste 		addargs(&args, "-oBatchMode=yes");
4124a421b63SDag-Erling Smørgrav 		addargs(&args, "--");
4134a421b63SDag-Erling Smørgrav 		addargs(&args, "%s", host);
4144a421b63SDag-Erling Smørgrav 		addargs(&args, "%s", cmd);
4154a421b63SDag-Erling Smørgrav 
4164a421b63SDag-Erling Smørgrav 		execvp(ssh_program, args.list);
4174a421b63SDag-Erling Smørgrav 		perror(ssh_program);
4184a421b63SDag-Erling Smørgrav 		exit(1);
4194a421b63SDag-Erling Smørgrav 	} else if (pid == -1) {
4204a421b63SDag-Erling Smørgrav 		fatal("fork: %s", strerror(errno));
4214a421b63SDag-Erling Smørgrav 	}
4224a421b63SDag-Erling Smørgrav 	while (waitpid(pid, &status, 0) == -1)
4234a421b63SDag-Erling Smørgrav 		if (errno != EINTR)
4244a421b63SDag-Erling Smørgrav 			fatal("do_cmd2: waitpid: %s", strerror(errno));
4254a421b63SDag-Erling Smørgrav 	return 0;
4264a421b63SDag-Erling Smørgrav }
4274a421b63SDag-Erling Smørgrav 
428511b41d2SMark Murray typedef struct {
429d4ecd108SDag-Erling Smørgrav 	size_t cnt;
430511b41d2SMark Murray 	char *buf;
431511b41d2SMark Murray } BUF;
432511b41d2SMark Murray 
433511b41d2SMark Murray BUF *allocbuf(BUF *, int, int);
434511b41d2SMark Murray void lostconn(int);
435511b41d2SMark Murray int okname(char *);
43619261079SEd Maste void run_err(const char *,...)
43719261079SEd Maste     __attribute__((__format__ (printf, 1, 2)))
43819261079SEd Maste     __attribute__((__nonnull__ (1)));
43919261079SEd Maste int note_err(const char *,...)
44019261079SEd Maste     __attribute__((__format__ (printf, 1, 2)));
441511b41d2SMark Murray void verifydir(char *);
442511b41d2SMark Murray 
443511b41d2SMark Murray struct passwd *pwd;
444511b41d2SMark Murray uid_t userid;
44519261079SEd Maste int errs, remin, remout, remin2, remout2;
446afde5170SEd Maste int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
447511b41d2SMark Murray 
448511b41d2SMark Murray #define	CMDNEEDS	64
449511b41d2SMark Murray char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
450511b41d2SMark Murray 
45119261079SEd Maste enum scp_mode_e {
45219261079SEd Maste 	MODE_SCP,
45319261079SEd Maste 	MODE_SFTP
45419261079SEd Maste };
45519261079SEd Maste 
456511b41d2SMark Murray int response(void);
457511b41d2SMark Murray void rsource(char *, struct stat *);
458afde5170SEd Maste void sink(int, char *[], const char *);
459511b41d2SMark Murray void source(int, char *[]);
46019261079SEd Maste void tolocal(int, char *[], enum scp_mode_e, char *sftp_direct);
46119261079SEd Maste void toremote(int, char *[], enum scp_mode_e, char *sftp_direct);
462511b41d2SMark Murray void usage(void);
463511b41d2SMark Murray 
46419261079SEd Maste void source_sftp(int, char *, char *, struct sftp_conn *);
46519261079SEd Maste void sink_sftp(int, char *, const char *, struct sftp_conn *);
46619261079SEd Maste void throughlocal_sftp(struct sftp_conn *, struct sftp_conn *,
46719261079SEd Maste     char *, char *);
46819261079SEd Maste 
469511b41d2SMark Murray int
main(int argc,char ** argv)470cf2b5f3bSDag-Erling Smørgrav main(int argc, char **argv)
471511b41d2SMark Murray {
472f374ba41SEd Maste 	int ch, fflag, tflag, status, r, n;
47319261079SEd Maste 	char **newargv, *argv0;
4744a421b63SDag-Erling Smørgrav 	const char *errstr;
475511b41d2SMark Murray 	extern char *optarg;
476511b41d2SMark Murray 	extern int optind;
477fb5aabcbSEd Maste 	enum scp_mode_e mode = MODE_SFTP;
47819261079SEd Maste 	char *sftp_direct = NULL;
479f374ba41SEd Maste 	long long llv;
480511b41d2SMark Murray 
481b74df5b2SDag-Erling Smørgrav 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
482b74df5b2SDag-Erling Smørgrav 	sanitise_stdfd();
483b74df5b2SDag-Erling Smørgrav 
484ca86bcf2SDag-Erling Smørgrav 	msetlocale();
485076ad2f8SDag-Erling Smørgrav 
486333ee039SDag-Erling Smørgrav 	/* Copy argv, because we modify it */
48719261079SEd Maste 	argv0 = argv[0];
488ca86bcf2SDag-Erling Smørgrav 	newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
489333ee039SDag-Erling Smørgrav 	for (n = 0; n < argc; n++)
490333ee039SDag-Erling Smørgrav 		newargv[n] = xstrdup(argv[n]);
491333ee039SDag-Erling Smørgrav 	argv = newargv;
492333ee039SDag-Erling Smørgrav 
493cf2b5f3bSDag-Erling Smørgrav 	__progname = ssh_get_progname(argv[0]);
49483d2307dSDag-Erling Smørgrav 
495e9e8876aSEd Maste 	log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
49619261079SEd Maste 
497b74df5b2SDag-Erling Smørgrav 	memset(&args, '\0', sizeof(args));
4984a421b63SDag-Erling Smørgrav 	memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
4994a421b63SDag-Erling Smørgrav 	args.list = remote_remote_args.list = NULL;
500b74df5b2SDag-Erling Smørgrav 	addargs(&args, "%s", ssh_program);
501ae1f160dSDag-Erling Smørgrav 	addargs(&args, "-x");
5024a421b63SDag-Erling Smørgrav 	addargs(&args, "-oPermitLocalCommand=no");
5034a421b63SDag-Erling Smørgrav 	addargs(&args, "-oClearAllForwardings=yes");
50447dd1d1bSDag-Erling Smørgrav 	addargs(&args, "-oRemoteCommand=none");
50547dd1d1bSDag-Erling Smørgrav 	addargs(&args, "-oRequestTTY=no");
5065b9b2fafSBrian Feldman 
507afde5170SEd Maste 	fflag = Tflag = tflag = 0;
508afde5170SEd Maste 	while ((ch = getopt(argc, argv,
509f374ba41SEd Maste 	    "12346ABCTdfOpqRrstvD:F:J:M:P:S:c:i:l:o:X:")) != -1) {
510511b41d2SMark Murray 		switch (ch) {
511511b41d2SMark Murray 		/* User-visible flags. */
512e73e9afaSDag-Erling Smørgrav 		case '1':
5134f52dfbbSDag-Erling Smørgrav 			fatal("SSH protocol v.1 is no longer supported");
5144f52dfbbSDag-Erling Smørgrav 			break;
515e73e9afaSDag-Erling Smørgrav 		case '2':
5164f52dfbbSDag-Erling Smørgrav 			/* Ignored */
5174f52dfbbSDag-Erling Smørgrav 			break;
51819261079SEd Maste 		case 'A':
519511b41d2SMark Murray 		case '4':
520511b41d2SMark Murray 		case '6':
5215b9b2fafSBrian Feldman 		case 'C':
522ae1f160dSDag-Erling Smørgrav 			addargs(&args, "-%c", ch);
5234a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "-%c", ch);
5244a421b63SDag-Erling Smørgrav 			break;
52519261079SEd Maste 		case 'D':
52619261079SEd Maste 			sftp_direct = optarg;
52719261079SEd Maste 			break;
5284a421b63SDag-Erling Smørgrav 		case '3':
5294a421b63SDag-Erling Smørgrav 			throughlocal = 1;
5305b9b2fafSBrian Feldman 			break;
53119261079SEd Maste 		case 'R':
53219261079SEd Maste 			throughlocal = 0;
53319261079SEd Maste 			break;
5345b9b2fafSBrian Feldman 		case 'o':
5355b9b2fafSBrian Feldman 		case 'c':
5365b9b2fafSBrian Feldman 		case 'i':
537ae1f160dSDag-Erling Smørgrav 		case 'F':
53819261079SEd Maste 		case 'J':
5394a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "-%c", ch);
5404a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "%s", optarg);
541b15c8340SDag-Erling Smørgrav 			addargs(&args, "-%c", ch);
542b15c8340SDag-Erling Smørgrav 			addargs(&args, "%s", optarg);
5435b9b2fafSBrian Feldman 			break;
54419261079SEd Maste 		case 'O':
54519261079SEd Maste 			mode = MODE_SCP;
54619261079SEd Maste 			break;
54719261079SEd Maste 		case 's':
54819261079SEd Maste 			mode = MODE_SFTP;
54919261079SEd Maste 			break;
5505b9b2fafSBrian Feldman 		case 'P':
55147dd1d1bSDag-Erling Smørgrav 			sshport = a2port(optarg);
55247dd1d1bSDag-Erling Smørgrav 			if (sshport <= 0)
55347dd1d1bSDag-Erling Smørgrav 				fatal("bad port \"%s\"\n", optarg);
5545b9b2fafSBrian Feldman 			break;
5555b9b2fafSBrian Feldman 		case 'B':
5564a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "-oBatchmode=yes");
5574a421b63SDag-Erling Smørgrav 			addargs(&args, "-oBatchmode=yes");
558511b41d2SMark Murray 			break;
559e73e9afaSDag-Erling Smørgrav 		case 'l':
5604a421b63SDag-Erling Smørgrav 			limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
5614a421b63SDag-Erling Smørgrav 			    &errstr);
5624a421b63SDag-Erling Smørgrav 			if (errstr != NULL)
563e73e9afaSDag-Erling Smørgrav 				usage();
5644a421b63SDag-Erling Smørgrav 			limit_kbps *= 1024; /* kbps */
5654a421b63SDag-Erling Smørgrav 			bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
566e73e9afaSDag-Erling Smørgrav 			break;
567511b41d2SMark Murray 		case 'p':
568511b41d2SMark Murray 			pflag = 1;
569511b41d2SMark Murray 			break;
570511b41d2SMark Murray 		case 'r':
571511b41d2SMark Murray 			iamrecursive = 1;
572511b41d2SMark Murray 			break;
573b66f2d16SKris Kennaway 		case 'S':
5745b9b2fafSBrian Feldman 			ssh_program = xstrdup(optarg);
5755b9b2fafSBrian Feldman 			break;
5765b9b2fafSBrian Feldman 		case 'v':
577ae1f160dSDag-Erling Smørgrav 			addargs(&args, "-v");
5784a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "-v");
57919261079SEd Maste 			if (verbose_mode == 0)
58019261079SEd Maste 				log_level = SYSLOG_LEVEL_DEBUG1;
58119261079SEd Maste 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
58219261079SEd Maste 				log_level++;
5835b9b2fafSBrian Feldman 			verbose_mode = 1;
5845b9b2fafSBrian Feldman 			break;
5855b9b2fafSBrian Feldman 		case 'q':
5861ec0d754SDag-Erling Smørgrav 			addargs(&args, "-q");
5874a421b63SDag-Erling Smørgrav 			addargs(&remote_remote_args, "-q");
5885b9b2fafSBrian Feldman 			showprogress = 0;
589b66f2d16SKris Kennaway 			break;
590f374ba41SEd Maste 		case 'X':
591f374ba41SEd Maste 			/* Please keep in sync with sftp.c -X */
592f374ba41SEd Maste 			if (strncmp(optarg, "buffer=", 7) == 0) {
593f374ba41SEd Maste 				r = scan_scaled(optarg + 7, &llv);
594f374ba41SEd Maste 				if (r == 0 && (llv <= 0 || llv > 256 * 1024)) {
595f374ba41SEd Maste 					r = -1;
596f374ba41SEd Maste 					errno = EINVAL;
597f374ba41SEd Maste 				}
598f374ba41SEd Maste 				if (r == -1) {
599f374ba41SEd Maste 					fatal("Invalid buffer size \"%s\": %s",
600f374ba41SEd Maste 					     optarg + 7, strerror(errno));
601f374ba41SEd Maste 				}
602f374ba41SEd Maste 				sftp_copy_buflen = (size_t)llv;
603f374ba41SEd Maste 			} else if (strncmp(optarg, "nrequests=", 10) == 0) {
604f374ba41SEd Maste 				llv = strtonum(optarg + 10, 1, 256 * 1024,
605f374ba41SEd Maste 				    &errstr);
606f374ba41SEd Maste 				if (errstr != NULL) {
607f374ba41SEd Maste 					fatal("Invalid number of requests "
608f374ba41SEd Maste 					    "\"%s\": %s", optarg + 10, errstr);
609f374ba41SEd Maste 				}
610f374ba41SEd Maste 				sftp_nrequests = (size_t)llv;
611f374ba41SEd Maste 			} else {
612f374ba41SEd Maste 				fatal("Invalid -X option");
613f374ba41SEd Maste 			}
614f374ba41SEd Maste 			break;
615b66f2d16SKris Kennaway 
616511b41d2SMark Murray 		/* Server options. */
617511b41d2SMark Murray 		case 'd':
618511b41d2SMark Murray 			targetshouldbedirectory = 1;
619511b41d2SMark Murray 			break;
620511b41d2SMark Murray 		case 'f':	/* "from" */
621511b41d2SMark Murray 			iamremote = 1;
622511b41d2SMark Murray 			fflag = 1;
623511b41d2SMark Murray 			break;
624511b41d2SMark Murray 		case 't':	/* "to" */
625511b41d2SMark Murray 			iamremote = 1;
626511b41d2SMark Murray 			tflag = 1;
62783d2307dSDag-Erling Smørgrav #ifdef HAVE_CYGWIN
62883d2307dSDag-Erling Smørgrav 			setmode(0, O_BINARY);
62983d2307dSDag-Erling Smørgrav #endif
630511b41d2SMark Murray 			break;
631afde5170SEd Maste 		case 'T':
632afde5170SEd Maste 			Tflag = 1;
633afde5170SEd Maste 			break;
634511b41d2SMark Murray 		default:
635511b41d2SMark Murray 			usage();
636511b41d2SMark Murray 		}
637afde5170SEd Maste 	}
638511b41d2SMark Murray 	argc -= optind;
639511b41d2SMark Murray 	argv += optind;
640511b41d2SMark Murray 
641e9e8876aSEd Maste 	log_init(argv0, log_level, SYSLOG_FACILITY_USER, 2);
64219261079SEd Maste 
64319261079SEd Maste 	/* Do this last because we want the user to be able to override it */
64419261079SEd Maste 	addargs(&args, "-oForwardAgent=no");
64519261079SEd Maste 
64619261079SEd Maste 	if (iamremote)
64719261079SEd Maste 		mode = MODE_SCP;
64819261079SEd Maste 
649511b41d2SMark Murray 	if ((pwd = getpwuid(userid = getuid())) == NULL)
650cf2b5f3bSDag-Erling Smørgrav 		fatal("unknown user %u", (u_int) userid);
651511b41d2SMark Murray 
652d4af9e69SDag-Erling Smørgrav 	if (!isatty(STDOUT_FILENO))
653511b41d2SMark Murray 		showprogress = 0;
654511b41d2SMark Murray 
655acc1a9efSDag-Erling Smørgrav 	if (pflag) {
656acc1a9efSDag-Erling Smørgrav 		/* Cannot pledge: -p allows setuid/setgid files... */
657acc1a9efSDag-Erling Smørgrav 	} else {
658acc1a9efSDag-Erling Smørgrav 		if (pledge("stdio rpath wpath cpath fattr tty proc exec",
659acc1a9efSDag-Erling Smørgrav 		    NULL) == -1) {
660acc1a9efSDag-Erling Smørgrav 			perror("pledge");
661acc1a9efSDag-Erling Smørgrav 			exit(1);
662acc1a9efSDag-Erling Smørgrav 		}
663acc1a9efSDag-Erling Smørgrav 	}
664acc1a9efSDag-Erling Smørgrav 
665511b41d2SMark Murray 	remin = STDIN_FILENO;
666511b41d2SMark Murray 	remout = STDOUT_FILENO;
667511b41d2SMark Murray 
668511b41d2SMark Murray 	if (fflag) {
669511b41d2SMark Murray 		/* Follow "protocol", send data. */
670511b41d2SMark Murray 		(void) response();
671511b41d2SMark Murray 		source(argc, argv);
672511b41d2SMark Murray 		exit(errs != 0);
673511b41d2SMark Murray 	}
674511b41d2SMark Murray 	if (tflag) {
675511b41d2SMark Murray 		/* Receive data. */
676afde5170SEd Maste 		sink(argc, argv, NULL);
677511b41d2SMark Murray 		exit(errs != 0);
678511b41d2SMark Murray 	}
679511b41d2SMark Murray 	if (argc < 2)
680511b41d2SMark Murray 		usage();
681511b41d2SMark Murray 	if (argc > 2)
682511b41d2SMark Murray 		targetshouldbedirectory = 1;
683511b41d2SMark Murray 
684511b41d2SMark Murray 	remin = remout = -1;
685e73e9afaSDag-Erling Smørgrav 	do_cmd_pid = -1;
686511b41d2SMark Murray 	/* Command to be executed on remote system using "ssh". */
6871e8db6e2SBrian Feldman 	(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
6881e8db6e2SBrian Feldman 	    verbose_mode ? " -v" : "",
689511b41d2SMark Murray 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
690511b41d2SMark Murray 	    targetshouldbedirectory ? " -d" : "");
691511b41d2SMark Murray 
69219261079SEd Maste 	(void) ssh_signal(SIGPIPE, lostconn);
693511b41d2SMark Murray 
69447dd1d1bSDag-Erling Smørgrav 	if (colon(argv[argc - 1]))	/* Dest is remote host. */
69519261079SEd Maste 		toremote(argc, argv, mode, sftp_direct);
696511b41d2SMark Murray 	else {
697511b41d2SMark Murray 		if (targetshouldbedirectory)
698511b41d2SMark Murray 			verifydir(argv[argc - 1]);
69919261079SEd Maste 		tolocal(argc, argv, mode, sftp_direct);	/* Dest is local host. */
700511b41d2SMark Murray 	}
701e73e9afaSDag-Erling Smørgrav 	/*
702e73e9afaSDag-Erling Smørgrav 	 * Finally check the exit status of the ssh process, if one was forked
703cce7d346SDag-Erling Smørgrav 	 * and no error has occurred yet
704e73e9afaSDag-Erling Smørgrav 	 */
705e9e8876aSEd Maste 	if (do_cmd_pid != -1 && (mode == MODE_SFTP || errs == 0)) {
706e73e9afaSDag-Erling Smørgrav 		if (remin != -1)
707e73e9afaSDag-Erling Smørgrav 		    (void) close(remin);
708e73e9afaSDag-Erling Smørgrav 		if (remout != -1)
709e73e9afaSDag-Erling Smørgrav 		    (void) close(remout);
710e73e9afaSDag-Erling Smørgrav 		if (waitpid(do_cmd_pid, &status, 0) == -1)
711e73e9afaSDag-Erling Smørgrav 			errs = 1;
712e73e9afaSDag-Erling Smørgrav 		else {
713e73e9afaSDag-Erling Smørgrav 			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
714e73e9afaSDag-Erling Smørgrav 				errs = 1;
715e73e9afaSDag-Erling Smørgrav 		}
716e73e9afaSDag-Erling Smørgrav 	}
717511b41d2SMark Murray 	exit(errs != 0);
718511b41d2SMark Murray }
719511b41d2SMark Murray 
7204a421b63SDag-Erling Smørgrav /* Callback from atomicio6 to update progress meter and limit bandwidth */
7214a421b63SDag-Erling Smørgrav static int
scpio(void * _cnt,size_t s)7224a421b63SDag-Erling Smørgrav scpio(void *_cnt, size_t s)
723d4af9e69SDag-Erling Smørgrav {
7244a421b63SDag-Erling Smørgrav 	off_t *cnt = (off_t *)_cnt;
725d4af9e69SDag-Erling Smørgrav 
7264a421b63SDag-Erling Smørgrav 	*cnt += s;
72719261079SEd Maste 	refresh_progress_meter(0);
7284a421b63SDag-Erling Smørgrav 	if (limit_kbps > 0)
7294a421b63SDag-Erling Smørgrav 		bandwidth_limit(&bwlimit, s);
7304a421b63SDag-Erling Smørgrav 	return 0;
731d4af9e69SDag-Erling Smørgrav }
732d4af9e69SDag-Erling Smørgrav 
733e4a9863fSDag-Erling Smørgrav static int
do_times(int fd,int verb,const struct stat * sb)734e4a9863fSDag-Erling Smørgrav do_times(int fd, int verb, const struct stat *sb)
735e4a9863fSDag-Erling Smørgrav {
736e4a9863fSDag-Erling Smørgrav 	/* strlen(2^64) == 20; strlen(10^6) == 7 */
737e4a9863fSDag-Erling Smørgrav 	char buf[(20 + 7 + 2) * 2 + 2];
738e4a9863fSDag-Erling Smørgrav 
739e4a9863fSDag-Erling Smørgrav 	(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
740e4a9863fSDag-Erling Smørgrav 	    (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
741e4a9863fSDag-Erling Smørgrav 	    (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
742e4a9863fSDag-Erling Smørgrav 	if (verb) {
743e4a9863fSDag-Erling Smørgrav 		fprintf(stderr, "File mtime %lld atime %lld\n",
744e4a9863fSDag-Erling Smørgrav 		    (long long)sb->st_mtime, (long long)sb->st_atime);
745e4a9863fSDag-Erling Smørgrav 		fprintf(stderr, "Sending file timestamps: %s", buf);
746e4a9863fSDag-Erling Smørgrav 	}
747e4a9863fSDag-Erling Smørgrav 	(void) atomicio(vwrite, fd, buf, strlen(buf));
748e4a9863fSDag-Erling Smørgrav 	return (response());
749e4a9863fSDag-Erling Smørgrav }
750e4a9863fSDag-Erling Smørgrav 
75147dd1d1bSDag-Erling Smørgrav static int
parse_scp_uri(const char * uri,char ** userp,char ** hostp,int * portp,char ** pathp)75247dd1d1bSDag-Erling Smørgrav parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
75347dd1d1bSDag-Erling Smørgrav     char **pathp)
754511b41d2SMark Murray {
75547dd1d1bSDag-Erling Smørgrav 	int r;
75647dd1d1bSDag-Erling Smørgrav 
75747dd1d1bSDag-Erling Smørgrav 	r = parse_uri("scp", uri, userp, hostp, portp, pathp);
75847dd1d1bSDag-Erling Smørgrav 	if (r == 0 && *pathp == NULL)
75947dd1d1bSDag-Erling Smørgrav 		*pathp = xstrdup(".");
76047dd1d1bSDag-Erling Smørgrav 	return r;
76147dd1d1bSDag-Erling Smørgrav }
76247dd1d1bSDag-Erling Smørgrav 
7630967215dSEd Maste /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
7640967215dSEd Maste static int
append(char * cp,char *** ap,size_t * np)7650967215dSEd Maste append(char *cp, char ***ap, size_t *np)
7660967215dSEd Maste {
7670967215dSEd Maste 	char **tmp;
7680967215dSEd Maste 
7690967215dSEd Maste 	if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
7700967215dSEd Maste 		return -1;
7710967215dSEd Maste 	tmp[(*np)] = cp;
7720967215dSEd Maste 	(*np)++;
7730967215dSEd Maste 	*ap = tmp;
7740967215dSEd Maste 	return 0;
7750967215dSEd Maste }
7760967215dSEd Maste 
7770967215dSEd Maste /*
7780967215dSEd Maste  * Finds the start and end of the first brace pair in the pattern.
7790967215dSEd Maste  * returns 0 on success or -1 for invalid patterns.
7800967215dSEd Maste  */
7810967215dSEd Maste static int
find_brace(const char * pattern,int * startp,int * endp)7820967215dSEd Maste find_brace(const char *pattern, int *startp, int *endp)
7830967215dSEd Maste {
7840967215dSEd Maste 	int i;
7850967215dSEd Maste 	int in_bracket, brace_level;
7860967215dSEd Maste 
7870967215dSEd Maste 	*startp = *endp = -1;
7880967215dSEd Maste 	in_bracket = brace_level = 0;
7890967215dSEd Maste 	for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
7900967215dSEd Maste 		switch (pattern[i]) {
7910967215dSEd Maste 		case '\\':
7920967215dSEd Maste 			/* skip next character */
7930967215dSEd Maste 			if (pattern[i + 1] != '\0')
7940967215dSEd Maste 				i++;
7950967215dSEd Maste 			break;
7960967215dSEd Maste 		case '[':
7970967215dSEd Maste 			in_bracket = 1;
7980967215dSEd Maste 			break;
7990967215dSEd Maste 		case ']':
8000967215dSEd Maste 			in_bracket = 0;
8010967215dSEd Maste 			break;
8020967215dSEd Maste 		case '{':
8030967215dSEd Maste 			if (in_bracket)
8040967215dSEd Maste 				break;
8050967215dSEd Maste 			if (pattern[i + 1] == '}') {
8060967215dSEd Maste 				/* Protect a single {}, for find(1), like csh */
8070967215dSEd Maste 				i++; /* skip */
8080967215dSEd Maste 				break;
8090967215dSEd Maste 			}
8100967215dSEd Maste 			if (*startp == -1)
8110967215dSEd Maste 				*startp = i;
8120967215dSEd Maste 			brace_level++;
8130967215dSEd Maste 			break;
8140967215dSEd Maste 		case '}':
8150967215dSEd Maste 			if (in_bracket)
8160967215dSEd Maste 				break;
8170967215dSEd Maste 			if (*startp < 0) {
8180967215dSEd Maste 				/* Unbalanced brace */
8190967215dSEd Maste 				return -1;
8200967215dSEd Maste 			}
8210967215dSEd Maste 			if (--brace_level <= 0)
8220967215dSEd Maste 				*endp = i;
8230967215dSEd Maste 			break;
8240967215dSEd Maste 		}
8250967215dSEd Maste 	}
8260967215dSEd Maste 	/* unbalanced brackets/braces */
8270967215dSEd Maste 	if (*endp < 0 && (*startp >= 0 || in_bracket))
8280967215dSEd Maste 		return -1;
8290967215dSEd Maste 	return 0;
8300967215dSEd Maste }
8310967215dSEd Maste 
8320967215dSEd Maste /*
8330967215dSEd Maste  * Assembles and records a successfully-expanded pattern, returns -1 on
8340967215dSEd Maste  * alloc failure.
8350967215dSEd Maste  */
8360967215dSEd Maste static int
emit_expansion(const char * pattern,int brace_start,int brace_end,int sel_start,int sel_end,char *** patternsp,size_t * npatternsp)8370967215dSEd Maste emit_expansion(const char *pattern, int brace_start, int brace_end,
8380967215dSEd Maste     int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
8390967215dSEd Maste {
8400967215dSEd Maste 	char *cp;
841535af610SEd Maste 	size_t pattern_len;
842535af610SEd Maste 	int o = 0, tail_len;
8430967215dSEd Maste 
844535af610SEd Maste 	if ((pattern_len = strlen(pattern)) == 0 || pattern_len >= INT_MAX)
845535af610SEd Maste 		return -1;
846535af610SEd Maste 
847535af610SEd Maste 	tail_len = strlen(pattern + brace_end + 1);
8480967215dSEd Maste 	if ((cp = malloc(brace_start + (sel_end - sel_start) +
8490967215dSEd Maste 	    tail_len + 1)) == NULL)
8500967215dSEd Maste 		return -1;
8510967215dSEd Maste 
8520967215dSEd Maste 	/* Pattern before initial brace */
8530967215dSEd Maste 	if (brace_start > 0) {
8540967215dSEd Maste 		memcpy(cp, pattern, brace_start);
8550967215dSEd Maste 		o = brace_start;
8560967215dSEd Maste 	}
8570967215dSEd Maste 	/* Current braced selection */
8580967215dSEd Maste 	if (sel_end - sel_start > 0) {
8590967215dSEd Maste 		memcpy(cp + o, pattern + sel_start,
8600967215dSEd Maste 		    sel_end - sel_start);
8610967215dSEd Maste 		o += sel_end - sel_start;
8620967215dSEd Maste 	}
8630967215dSEd Maste 	/* Remainder of pattern after closing brace */
8640967215dSEd Maste 	if (tail_len > 0) {
8650967215dSEd Maste 		memcpy(cp + o, pattern + brace_end + 1, tail_len);
8660967215dSEd Maste 		o += tail_len;
8670967215dSEd Maste 	}
8680967215dSEd Maste 	cp[o] = '\0';
8690967215dSEd Maste 	if (append(cp, patternsp, npatternsp) != 0) {
8700967215dSEd Maste 		free(cp);
8710967215dSEd Maste 		return -1;
8720967215dSEd Maste 	}
8730967215dSEd Maste 	return 0;
8740967215dSEd Maste }
8750967215dSEd Maste 
8760967215dSEd Maste /*
8770967215dSEd Maste  * Expand the first encountered brace in pattern, appending the expanded
8780967215dSEd Maste  * patterns it yielded to the *patternsp array.
8790967215dSEd Maste  *
8800967215dSEd Maste  * Returns 0 on success or -1 on allocation failure.
8810967215dSEd Maste  *
8820967215dSEd Maste  * Signals whether expansion was performed via *expanded and whether
8830967215dSEd Maste  * pattern was invalid via *invalid.
8840967215dSEd Maste  */
8850967215dSEd Maste static int
brace_expand_one(const char * pattern,char *** patternsp,size_t * npatternsp,int * expanded,int * invalid)8860967215dSEd Maste brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
8870967215dSEd Maste     int *expanded, int *invalid)
8880967215dSEd Maste {
8890967215dSEd Maste 	int i;
8900967215dSEd Maste 	int in_bracket, brace_start, brace_end, brace_level;
8910967215dSEd Maste 	int sel_start, sel_end;
8920967215dSEd Maste 
8930967215dSEd Maste 	*invalid = *expanded = 0;
8940967215dSEd Maste 
8950967215dSEd Maste 	if (find_brace(pattern, &brace_start, &brace_end) != 0) {
8960967215dSEd Maste 		*invalid = 1;
8970967215dSEd Maste 		return 0;
8980967215dSEd Maste 	} else if (brace_start == -1)
8990967215dSEd Maste 		return 0;
9000967215dSEd Maste 
9010967215dSEd Maste 	in_bracket = brace_level = 0;
9020967215dSEd Maste 	for (i = sel_start = brace_start + 1; i < brace_end; i++) {
9030967215dSEd Maste 		switch (pattern[i]) {
9040967215dSEd Maste 		case '{':
9050967215dSEd Maste 			if (in_bracket)
9060967215dSEd Maste 				break;
9070967215dSEd Maste 			brace_level++;
9080967215dSEd Maste 			break;
9090967215dSEd Maste 		case '}':
9100967215dSEd Maste 			if (in_bracket)
9110967215dSEd Maste 				break;
9120967215dSEd Maste 			brace_level--;
9130967215dSEd Maste 			break;
9140967215dSEd Maste 		case '[':
9150967215dSEd Maste 			in_bracket = 1;
9160967215dSEd Maste 			break;
9170967215dSEd Maste 		case ']':
9180967215dSEd Maste 			in_bracket = 0;
9190967215dSEd Maste 			break;
9200967215dSEd Maste 		case '\\':
9210967215dSEd Maste 			if (i < brace_end - 1)
9220967215dSEd Maste 				i++; /* skip */
9230967215dSEd Maste 			break;
9240967215dSEd Maste 		}
9250967215dSEd Maste 		if (pattern[i] == ',' || i == brace_end - 1) {
9260967215dSEd Maste 			if (in_bracket || brace_level > 0)
9270967215dSEd Maste 				continue;
9280967215dSEd Maste 			/* End of a selection, emit an expanded pattern */
9290967215dSEd Maste 
9300967215dSEd Maste 			/* Adjust end index for last selection */
9310967215dSEd Maste 			sel_end = (i == brace_end - 1) ? brace_end : i;
9320967215dSEd Maste 			if (emit_expansion(pattern, brace_start, brace_end,
9330967215dSEd Maste 			    sel_start, sel_end, patternsp, npatternsp) != 0)
9340967215dSEd Maste 				return -1;
9350967215dSEd Maste 			/* move on to the next selection */
9360967215dSEd Maste 			sel_start = i + 1;
9370967215dSEd Maste 			continue;
9380967215dSEd Maste 		}
9390967215dSEd Maste 	}
9400967215dSEd Maste 	if (in_bracket || brace_level > 0) {
9410967215dSEd Maste 		*invalid = 1;
9420967215dSEd Maste 		return 0;
9430967215dSEd Maste 	}
9440967215dSEd Maste 	/* success */
9450967215dSEd Maste 	*expanded = 1;
9460967215dSEd Maste 	return 0;
9470967215dSEd Maste }
9480967215dSEd Maste 
9490967215dSEd Maste /* Expand braces from pattern. Returns 0 on success, -1 on failure */
9500967215dSEd Maste static int
brace_expand(const char * pattern,char *** patternsp,size_t * npatternsp)9510967215dSEd Maste brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
9520967215dSEd Maste {
9530967215dSEd Maste 	char *cp, *cp2, **active = NULL, **done = NULL;
9540967215dSEd Maste 	size_t i, nactive = 0, ndone = 0;
9550967215dSEd Maste 	int ret = -1, invalid = 0, expanded = 0;
9560967215dSEd Maste 
9570967215dSEd Maste 	*patternsp = NULL;
9580967215dSEd Maste 	*npatternsp = 0;
9590967215dSEd Maste 
9600967215dSEd Maste 	/* Start the worklist with the original pattern */
9610967215dSEd Maste 	if ((cp = strdup(pattern)) == NULL)
9620967215dSEd Maste 		return -1;
9630967215dSEd Maste 	if (append(cp, &active, &nactive) != 0) {
9640967215dSEd Maste 		free(cp);
9650967215dSEd Maste 		return -1;
9660967215dSEd Maste 	}
9670967215dSEd Maste 	while (nactive > 0) {
9680967215dSEd Maste 		cp = active[nactive - 1];
9690967215dSEd Maste 		nactive--;
9700967215dSEd Maste 		if (brace_expand_one(cp, &active, &nactive,
9710967215dSEd Maste 		    &expanded, &invalid) == -1) {
9720967215dSEd Maste 			free(cp);
9730967215dSEd Maste 			goto fail;
9740967215dSEd Maste 		}
9750967215dSEd Maste 		if (invalid)
97619261079SEd Maste 			fatal_f("invalid brace pattern \"%s\"", cp);
9770967215dSEd Maste 		if (expanded) {
9780967215dSEd Maste 			/*
9790967215dSEd Maste 			 * Current entry expanded to new entries on the
9800967215dSEd Maste 			 * active list; discard the progenitor pattern.
9810967215dSEd Maste 			 */
9820967215dSEd Maste 			free(cp);
9830967215dSEd Maste 			continue;
9840967215dSEd Maste 		}
9850967215dSEd Maste 		/*
9860967215dSEd Maste 		 * Pattern did not expand; append the finename component to
9870967215dSEd Maste 		 * the completed list
9880967215dSEd Maste 		 */
9890967215dSEd Maste 		if ((cp2 = strrchr(cp, '/')) != NULL)
9900967215dSEd Maste 			*cp2++ = '\0';
9910967215dSEd Maste 		else
9920967215dSEd Maste 			cp2 = cp;
9930967215dSEd Maste 		if (append(xstrdup(cp2), &done, &ndone) != 0) {
9940967215dSEd Maste 			free(cp);
9950967215dSEd Maste 			goto fail;
9960967215dSEd Maste 		}
9970967215dSEd Maste 		free(cp);
9980967215dSEd Maste 	}
9990967215dSEd Maste 	/* success */
10000967215dSEd Maste 	*patternsp = done;
10010967215dSEd Maste 	*npatternsp = ndone;
10020967215dSEd Maste 	done = NULL;
10030967215dSEd Maste 	ndone = 0;
10040967215dSEd Maste 	ret = 0;
10050967215dSEd Maste  fail:
10060967215dSEd Maste 	for (i = 0; i < nactive; i++)
10070967215dSEd Maste 		free(active[i]);
10080967215dSEd Maste 	free(active);
10090967215dSEd Maste 	for (i = 0; i < ndone; i++)
10100967215dSEd Maste 		free(done[i]);
10110967215dSEd Maste 	free(done);
10120967215dSEd Maste 	return ret;
10130967215dSEd Maste }
10140967215dSEd Maste 
101519261079SEd Maste static struct sftp_conn *
do_sftp_connect(char * host,char * user,int port,char * sftp_direct,int * reminp,int * remoutp,int * pidp)101619261079SEd Maste do_sftp_connect(char *host, char *user, int port, char *sftp_direct,
101719261079SEd Maste    int *reminp, int *remoutp, int *pidp)
101819261079SEd Maste {
101919261079SEd Maste 	if (sftp_direct == NULL) {
102019261079SEd Maste 		if (do_cmd(ssh_program, host, user, port, 1, "sftp",
102119261079SEd Maste 		    reminp, remoutp, pidp) < 0)
102219261079SEd Maste 			return NULL;
102319261079SEd Maste 
102419261079SEd Maste 	} else {
102587c1498dSEd Maste 		freeargs(&args);
102619261079SEd Maste 		addargs(&args, "sftp-server");
102719261079SEd Maste 		if (do_cmd(sftp_direct, host, NULL, -1, 0, "sftp",
102819261079SEd Maste 		    reminp, remoutp, pidp) < 0)
102919261079SEd Maste 			return NULL;
103019261079SEd Maste 	}
1031edf85781SEd Maste 	return sftp_init(*reminp, *remoutp,
1032f374ba41SEd Maste 	    sftp_copy_buflen, sftp_nrequests, limit_kbps);
103319261079SEd Maste }
103419261079SEd Maste 
103547dd1d1bSDag-Erling Smørgrav void
toremote(int argc,char ** argv,enum scp_mode_e mode,char * sftp_direct)103619261079SEd Maste toremote(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
103747dd1d1bSDag-Erling Smørgrav {
103847dd1d1bSDag-Erling Smørgrav 	char *suser = NULL, *host = NULL, *src = NULL;
103947dd1d1bSDag-Erling Smørgrav 	char *bp, *tuser, *thost, *targ;
104047dd1d1bSDag-Erling Smørgrav 	int sport = -1, tport = -1;
104119261079SEd Maste 	struct sftp_conn *conn = NULL, *conn2 = NULL;
1042b74df5b2SDag-Erling Smørgrav 	arglist alist;
104319261079SEd Maste 	int i, r, status;
1044535af610SEd Maste 	struct stat sb;
10454a421b63SDag-Erling Smørgrav 	u_int j;
1046b74df5b2SDag-Erling Smørgrav 
1047b74df5b2SDag-Erling Smørgrav 	memset(&alist, '\0', sizeof(alist));
1048b74df5b2SDag-Erling Smørgrav 	alist.list = NULL;
1049511b41d2SMark Murray 
105047dd1d1bSDag-Erling Smørgrav 	/* Parse target */
105147dd1d1bSDag-Erling Smørgrav 	r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
105247dd1d1bSDag-Erling Smørgrav 	if (r == -1) {
105347dd1d1bSDag-Erling Smørgrav 		fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
105447dd1d1bSDag-Erling Smørgrav 		++errs;
105547dd1d1bSDag-Erling Smørgrav 		goto out;
1056511b41d2SMark Murray 	}
105747dd1d1bSDag-Erling Smørgrav 	if (r != 0) {
105847dd1d1bSDag-Erling Smørgrav 		if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
105947dd1d1bSDag-Erling Smørgrav 		    &targ) == -1) {
106047dd1d1bSDag-Erling Smørgrav 			fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
106147dd1d1bSDag-Erling Smørgrav 			++errs;
106247dd1d1bSDag-Erling Smørgrav 			goto out;
106347dd1d1bSDag-Erling Smørgrav 		}
106447dd1d1bSDag-Erling Smørgrav 	}
1065b74df5b2SDag-Erling Smørgrav 
106647dd1d1bSDag-Erling Smørgrav 	/* Parse source files */
1067511b41d2SMark Murray 	for (i = 0; i < argc - 1; i++) {
106847dd1d1bSDag-Erling Smørgrav 		free(suser);
106947dd1d1bSDag-Erling Smørgrav 		free(host);
107047dd1d1bSDag-Erling Smørgrav 		free(src);
107147dd1d1bSDag-Erling Smørgrav 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
107247dd1d1bSDag-Erling Smørgrav 		if (r == -1) {
107347dd1d1bSDag-Erling Smørgrav 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
107447dd1d1bSDag-Erling Smørgrav 			++errs;
10754a421b63SDag-Erling Smørgrav 			continue;
10764a421b63SDag-Erling Smørgrav 		}
107747dd1d1bSDag-Erling Smørgrav 		if (r != 0) {
107847dd1d1bSDag-Erling Smørgrav 			parse_user_host_path(argv[i], &suser, &host, &src);
107947dd1d1bSDag-Erling Smørgrav 		}
108047dd1d1bSDag-Erling Smørgrav 		if (suser != NULL && !okname(suser)) {
108147dd1d1bSDag-Erling Smørgrav 			++errs;
108247dd1d1bSDag-Erling Smørgrav 			continue;
108347dd1d1bSDag-Erling Smørgrav 		}
108447dd1d1bSDag-Erling Smørgrav 		if (host && throughlocal) {	/* extended remote to remote */
108519261079SEd Maste 			if (mode == MODE_SFTP) {
108619261079SEd Maste 				if (remin == -1) {
108719261079SEd Maste 					/* Connect to dest now */
108819261079SEd Maste 					conn = do_sftp_connect(thost, tuser,
108919261079SEd Maste 					    tport, sftp_direct,
109019261079SEd Maste 					    &remin, &remout, &do_cmd_pid);
109119261079SEd Maste 					if (conn == NULL) {
109219261079SEd Maste 						fatal("Unable to open "
109319261079SEd Maste 						    "destination connection");
109419261079SEd Maste 					}
109519261079SEd Maste 					debug3_f("origin in %d out %d pid %ld",
109619261079SEd Maste 					    remin, remout, (long)do_cmd_pid);
109719261079SEd Maste 				}
109819261079SEd Maste 				/*
109919261079SEd Maste 				 * XXX remember suser/host/sport and only
110019261079SEd Maste 				 * reconnect if they change between arguments.
110119261079SEd Maste 				 * would save reconnections for cases like
110219261079SEd Maste 				 * scp -3 hosta:/foo hosta:/bar hostb:
110319261079SEd Maste 				 */
110419261079SEd Maste 				/* Connect to origin now */
110519261079SEd Maste 				conn2 = do_sftp_connect(host, suser,
110619261079SEd Maste 				    sport, sftp_direct,
110719261079SEd Maste 				    &remin2, &remout2, &do_cmd_pid2);
110819261079SEd Maste 				if (conn2 == NULL) {
110919261079SEd Maste 					fatal("Unable to open "
111019261079SEd Maste 					    "source connection");
111119261079SEd Maste 				}
111219261079SEd Maste 				debug3_f("destination in %d out %d pid %ld",
111319261079SEd Maste 				    remin2, remout2, (long)do_cmd_pid2);
111419261079SEd Maste 				throughlocal_sftp(conn2, conn, src, targ);
111519261079SEd Maste 				(void) close(remin2);
111619261079SEd Maste 				(void) close(remout2);
111719261079SEd Maste 				remin2 = remout2 = -1;
111819261079SEd Maste 				if (waitpid(do_cmd_pid2, &status, 0) == -1)
111919261079SEd Maste 					++errs;
112019261079SEd Maste 				else if (!WIFEXITED(status) ||
112119261079SEd Maste 				    WEXITSTATUS(status) != 0)
112219261079SEd Maste 					++errs;
112319261079SEd Maste 				do_cmd_pid2 = -1;
112419261079SEd Maste 				continue;
112519261079SEd Maste 			} else {
1126462c32cbSDag-Erling Smørgrav 				xasprintf(&bp, "%s -f %s%s", cmd,
1127462c32cbSDag-Erling Smørgrav 				    *src == '-' ? "-- " : "", src);
112819261079SEd Maste 				if (do_cmd(ssh_program, host, suser, sport, 0,
112919261079SEd Maste 				    bp, &remin, &remout, &do_cmd_pid) < 0)
11304a421b63SDag-Erling Smørgrav 					exit(1);
1131e4a9863fSDag-Erling Smørgrav 				free(bp);
1132462c32cbSDag-Erling Smørgrav 				xasprintf(&bp, "%s -t %s%s", cmd,
1133462c32cbSDag-Erling Smørgrav 				    *targ == '-' ? "-- " : "", targ);
113419261079SEd Maste 				if (do_cmd2(thost, tuser, tport, bp,
113519261079SEd Maste 				    remin, remout) < 0)
11364a421b63SDag-Erling Smørgrav 					exit(1);
1137e4a9863fSDag-Erling Smørgrav 				free(bp);
11384a421b63SDag-Erling Smørgrav 				(void) close(remin);
11394a421b63SDag-Erling Smørgrav 				(void) close(remout);
11404a421b63SDag-Erling Smørgrav 				remin = remout = -1;
114119261079SEd Maste 			}
114247dd1d1bSDag-Erling Smørgrav 		} else if (host) {	/* standard remote to remote */
114319261079SEd Maste 			/*
114419261079SEd Maste 			 * Second remote user is passed to first remote side
114519261079SEd Maste 			 * via scp command-line. Ensure it contains no obvious
114619261079SEd Maste 			 * shell characters.
114719261079SEd Maste 			 */
114819261079SEd Maste 			if (tuser != NULL && !okname(tuser)) {
114919261079SEd Maste 				++errs;
115019261079SEd Maste 				continue;
115119261079SEd Maste 			}
115247dd1d1bSDag-Erling Smørgrav 			if (tport != -1 && tport != SSH_DEFAULT_PORT) {
115347dd1d1bSDag-Erling Smørgrav 				/* This would require the remote support URIs */
115447dd1d1bSDag-Erling Smørgrav 				fatal("target port not supported with two "
115519261079SEd Maste 				    "remote hosts and the -R option");
115647dd1d1bSDag-Erling Smørgrav 			}
115747dd1d1bSDag-Erling Smørgrav 
1158b74df5b2SDag-Erling Smørgrav 			freeargs(&alist);
1159b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", ssh_program);
1160b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "-x");
11614a421b63SDag-Erling Smørgrav 			addargs(&alist, "-oClearAllForwardings=yes");
1162b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "-n");
11634a421b63SDag-Erling Smørgrav 			for (j = 0; j < remote_remote_args.num; j++) {
11644a421b63SDag-Erling Smørgrav 				addargs(&alist, "%s",
11654a421b63SDag-Erling Smørgrav 				    remote_remote_args.list[j]);
11664a421b63SDag-Erling Smørgrav 			}
1167b74df5b2SDag-Erling Smørgrav 
116847dd1d1bSDag-Erling Smørgrav 			if (sport != -1) {
116947dd1d1bSDag-Erling Smørgrav 				addargs(&alist, "-p");
117047dd1d1bSDag-Erling Smørgrav 				addargs(&alist, "%d", sport);
117147dd1d1bSDag-Erling Smørgrav 			}
117247dd1d1bSDag-Erling Smørgrav 			if (suser) {
1173b74df5b2SDag-Erling Smørgrav 				addargs(&alist, "-l");
1174b74df5b2SDag-Erling Smørgrav 				addargs(&alist, "%s", suser);
1175b74df5b2SDag-Erling Smørgrav 			}
1176b15c8340SDag-Erling Smørgrav 			addargs(&alist, "--");
1177b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", host);
1178b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", cmd);
1179b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", src);
1180b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s%s%s:%s",
1181511b41d2SMark Murray 			    tuser ? tuser : "", tuser ? "@" : "",
1182511b41d2SMark Murray 			    thost, targ);
1183b74df5b2SDag-Erling Smørgrav 			if (do_local_cmd(&alist) != 0)
11841ec0d754SDag-Erling Smørgrav 				errs = 1;
1185511b41d2SMark Murray 		} else {	/* local to remote */
118619261079SEd Maste 			if (mode == MODE_SFTP) {
1187535af610SEd Maste 				/* no need to glob: already done by shell */
1188535af610SEd Maste 				if (stat(argv[i], &sb) != 0) {
1189535af610SEd Maste 					fatal("stat local \"%s\": %s", argv[i],
1190535af610SEd Maste 					    strerror(errno));
1191535af610SEd Maste 				}
119219261079SEd Maste 				if (remin == -1) {
119319261079SEd Maste 					/* Connect to remote now */
119419261079SEd Maste 					conn = do_sftp_connect(thost, tuser,
119519261079SEd Maste 					    tport, sftp_direct,
119619261079SEd Maste 					    &remin, &remout, &do_cmd_pid);
119719261079SEd Maste 					if (conn == NULL) {
119819261079SEd Maste 						fatal("Unable to open sftp "
119919261079SEd Maste 						    "connection");
120019261079SEd Maste 					}
120119261079SEd Maste 				}
120219261079SEd Maste 
120319261079SEd Maste 				/* The protocol */
120419261079SEd Maste 				source_sftp(1, argv[i], targ, conn);
120519261079SEd Maste 				continue;
120619261079SEd Maste 			}
120719261079SEd Maste 			/* SCP */
1208511b41d2SMark Murray 			if (remin == -1) {
1209462c32cbSDag-Erling Smørgrav 				xasprintf(&bp, "%s -t %s%s", cmd,
1210462c32cbSDag-Erling Smørgrav 				    *targ == '-' ? "-- " : "", targ);
121119261079SEd Maste 				if (do_cmd(ssh_program, thost, tuser, tport, 0,
121219261079SEd Maste 				    bp, &remin, &remout, &do_cmd_pid) < 0)
1213511b41d2SMark Murray 					exit(1);
1214511b41d2SMark Murray 				if (response() < 0)
1215511b41d2SMark Murray 					exit(1);
1216e4a9863fSDag-Erling Smørgrav 				free(bp);
1217511b41d2SMark Murray 			}
1218511b41d2SMark Murray 			source(1, argv + i);
1219511b41d2SMark Murray 		}
1220511b41d2SMark Murray 	}
122147dd1d1bSDag-Erling Smørgrav out:
122219261079SEd Maste 	if (mode == MODE_SFTP)
122319261079SEd Maste 		free(conn);
122447dd1d1bSDag-Erling Smørgrav 	free(tuser);
122547dd1d1bSDag-Erling Smørgrav 	free(thost);
122647dd1d1bSDag-Erling Smørgrav 	free(targ);
122747dd1d1bSDag-Erling Smørgrav 	free(suser);
122847dd1d1bSDag-Erling Smørgrav 	free(host);
122947dd1d1bSDag-Erling Smørgrav 	free(src);
1230511b41d2SMark Murray }
1231511b41d2SMark Murray 
1232511b41d2SMark Murray void
tolocal(int argc,char ** argv,enum scp_mode_e mode,char * sftp_direct)123319261079SEd Maste tolocal(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct)
1234511b41d2SMark Murray {
123547dd1d1bSDag-Erling Smørgrav 	char *bp, *host = NULL, *src = NULL, *suser = NULL;
1236b74df5b2SDag-Erling Smørgrav 	arglist alist;
123719261079SEd Maste 	struct sftp_conn *conn = NULL;
123847dd1d1bSDag-Erling Smørgrav 	int i, r, sport = -1;
1239b74df5b2SDag-Erling Smørgrav 
1240b74df5b2SDag-Erling Smørgrav 	memset(&alist, '\0', sizeof(alist));
1241b74df5b2SDag-Erling Smørgrav 	alist.list = NULL;
1242511b41d2SMark Murray 
1243511b41d2SMark Murray 	for (i = 0; i < argc - 1; i++) {
124447dd1d1bSDag-Erling Smørgrav 		free(suser);
124547dd1d1bSDag-Erling Smørgrav 		free(host);
124647dd1d1bSDag-Erling Smørgrav 		free(src);
124747dd1d1bSDag-Erling Smørgrav 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
124847dd1d1bSDag-Erling Smørgrav 		if (r == -1) {
124947dd1d1bSDag-Erling Smørgrav 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
125047dd1d1bSDag-Erling Smørgrav 			++errs;
125147dd1d1bSDag-Erling Smørgrav 			continue;
125247dd1d1bSDag-Erling Smørgrav 		}
125347dd1d1bSDag-Erling Smørgrav 		if (r != 0)
125447dd1d1bSDag-Erling Smørgrav 			parse_user_host_path(argv[i], &suser, &host, &src);
125547dd1d1bSDag-Erling Smørgrav 		if (suser != NULL && !okname(suser)) {
125647dd1d1bSDag-Erling Smørgrav 			++errs;
125747dd1d1bSDag-Erling Smørgrav 			continue;
125847dd1d1bSDag-Erling Smørgrav 		}
125947dd1d1bSDag-Erling Smørgrav 		if (!host) {	/* Local to local. */
1260b74df5b2SDag-Erling Smørgrav 			freeargs(&alist);
1261b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", _PATH_CP);
1262b74df5b2SDag-Erling Smørgrav 			if (iamrecursive)
1263b74df5b2SDag-Erling Smørgrav 				addargs(&alist, "-r");
1264b74df5b2SDag-Erling Smørgrav 			if (pflag)
1265b74df5b2SDag-Erling Smørgrav 				addargs(&alist, "-p");
1266b15c8340SDag-Erling Smørgrav 			addargs(&alist, "--");
1267b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", argv[i]);
1268b74df5b2SDag-Erling Smørgrav 			addargs(&alist, "%s", argv[argc-1]);
1269b74df5b2SDag-Erling Smørgrav 			if (do_local_cmd(&alist))
1270511b41d2SMark Murray 				++errs;
1271511b41d2SMark Murray 			continue;
1272511b41d2SMark Murray 		}
127347dd1d1bSDag-Erling Smørgrav 		/* Remote to local. */
127419261079SEd Maste 		if (mode == MODE_SFTP) {
127519261079SEd Maste 			conn = do_sftp_connect(host, suser, sport,
127619261079SEd Maste 			    sftp_direct, &remin, &remout, &do_cmd_pid);
127719261079SEd Maste 			if (conn == NULL) {
1278e9e8876aSEd Maste 				error("sftp connection failed");
127919261079SEd Maste 				++errs;
128019261079SEd Maste 				continue;
128119261079SEd Maste 			}
128219261079SEd Maste 
128319261079SEd Maste 			/* The protocol */
128419261079SEd Maste 			sink_sftp(1, argv[argc - 1], src, conn);
128519261079SEd Maste 
128619261079SEd Maste 			free(conn);
128719261079SEd Maste 			(void) close(remin);
128819261079SEd Maste 			(void) close(remout);
128919261079SEd Maste 			remin = remout = -1;
129019261079SEd Maste 			continue;
129119261079SEd Maste 		}
129219261079SEd Maste 		/* SCP */
1293462c32cbSDag-Erling Smørgrav 		xasprintf(&bp, "%s -f %s%s",
1294462c32cbSDag-Erling Smørgrav 		    cmd, *src == '-' ? "-- " : "", src);
129519261079SEd Maste 		if (do_cmd(ssh_program, host, suser, sport, 0, bp,
129619261079SEd Maste 		    &remin, &remout, &do_cmd_pid) < 0) {
1297e4a9863fSDag-Erling Smørgrav 			free(bp);
1298511b41d2SMark Murray 			++errs;
1299511b41d2SMark Murray 			continue;
1300511b41d2SMark Murray 		}
1301e4a9863fSDag-Erling Smørgrav 		free(bp);
1302afde5170SEd Maste 		sink(1, argv + argc - 1, src);
1303511b41d2SMark Murray 		(void) close(remin);
1304511b41d2SMark Murray 		remin = remout = -1;
1305511b41d2SMark Murray 	}
130647dd1d1bSDag-Erling Smørgrav 	free(suser);
130747dd1d1bSDag-Erling Smørgrav 	free(host);
130847dd1d1bSDag-Erling Smørgrav 	free(src);
1309511b41d2SMark Murray }
1310511b41d2SMark Murray 
131119261079SEd Maste /* Prepare remote path, handling ~ by assuming cwd is the homedir */
131219261079SEd Maste static char *
prepare_remote_path(struct sftp_conn * conn,const char * path)131319261079SEd Maste prepare_remote_path(struct sftp_conn *conn, const char *path)
131419261079SEd Maste {
13151323ec57SEd Maste 	size_t nslash;
13161323ec57SEd Maste 
131719261079SEd Maste 	/* Handle ~ prefixed paths */
131819261079SEd Maste 	if (*path == '\0' || strcmp(path, "~") == 0)
131919261079SEd Maste 		return xstrdup(".");
13201323ec57SEd Maste 	if (*path != '~')
13211323ec57SEd Maste 		return xstrdup(path);
13221323ec57SEd Maste 	if (strncmp(path, "~/", 2) == 0) {
13231323ec57SEd Maste 		if ((nslash = strspn(path + 2, "/")) == strlen(path + 2))
13241323ec57SEd Maste 			return xstrdup(".");
13251323ec57SEd Maste 		return xstrdup(path + 2 + nslash);
13261323ec57SEd Maste 	}
1327edf85781SEd Maste 	if (sftp_can_expand_path(conn))
1328edf85781SEd Maste 		return sftp_expand_path(conn, path);
132919261079SEd Maste 	/* No protocol extension */
1330e9e8876aSEd Maste 	error("server expand-path extension is required "
1331e9e8876aSEd Maste 	    "for ~user paths in SFTP mode");
133219261079SEd Maste 	return NULL;
133319261079SEd Maste }
133419261079SEd Maste 
133519261079SEd Maste void
source_sftp(int argc,char * src,char * targ,struct sftp_conn * conn)133619261079SEd Maste source_sftp(int argc, char *src, char *targ, struct sftp_conn *conn)
133719261079SEd Maste {
133819261079SEd Maste 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
13391323ec57SEd Maste 	int src_is_dir, target_is_dir;
13401323ec57SEd Maste 	Attrib a;
13411323ec57SEd Maste 	struct stat st;
134219261079SEd Maste 
13431323ec57SEd Maste 	memset(&a, '\0', sizeof(a));
13441323ec57SEd Maste 	if (stat(src, &st) != 0)
13451323ec57SEd Maste 		fatal("stat local \"%s\": %s", src, strerror(errno));
13461323ec57SEd Maste 	src_is_dir = S_ISDIR(st.st_mode);
134719261079SEd Maste 	if ((filename = basename(src)) == NULL)
13481323ec57SEd Maste 		fatal("basename \"%s\": %s", src, strerror(errno));
134919261079SEd Maste 
135019261079SEd Maste 	/*
135119261079SEd Maste 	 * No need to glob here - the local shell already took care of
135219261079SEd Maste 	 * the expansions
135319261079SEd Maste 	 */
135419261079SEd Maste 	if ((target = prepare_remote_path(conn, targ)) == NULL)
135519261079SEd Maste 		cleanup_exit(255);
1356edf85781SEd Maste 	target_is_dir = sftp_remote_is_dir(conn, target);
135719261079SEd Maste 	if (targetshouldbedirectory && !target_is_dir) {
13581323ec57SEd Maste 		debug("target directory \"%s\" does not exist", target);
13591323ec57SEd Maste 		a.flags = SSH2_FILEXFER_ATTR_PERMISSIONS;
13601323ec57SEd Maste 		a.perm = st.st_mode | 0700; /* ensure writable */
1361edf85781SEd Maste 		if (sftp_mkdir(conn, target, &a, 1) != 0)
13621323ec57SEd Maste 			cleanup_exit(255); /* error already logged */
13631323ec57SEd Maste 		target_is_dir = 1;
136419261079SEd Maste 	}
136519261079SEd Maste 	if (target_is_dir)
1366edf85781SEd Maste 		abs_dst = sftp_path_append(target, filename);
136719261079SEd Maste 	else {
136819261079SEd Maste 		abs_dst = target;
136919261079SEd Maste 		target = NULL;
137019261079SEd Maste 	}
137119261079SEd Maste 	debug3_f("copying local %s to remote %s", src, abs_dst);
137219261079SEd Maste 
13731323ec57SEd Maste 	if (src_is_dir && iamrecursive) {
1374edf85781SEd Maste 		if (sftp_upload_dir(conn, src, abs_dst, pflag,
137538a52bd3SEd Maste 		    SFTP_PROGRESS_ONLY, 0, 0, 1, 1) != 0) {
13761323ec57SEd Maste 			error("failed to upload directory %s to %s", src, targ);
1377e9e8876aSEd Maste 			errs = 1;
137819261079SEd Maste 		}
1379edf85781SEd Maste 	} else if (sftp_upload(conn, src, abs_dst, pflag, 0, 0, 1) != 0) {
13801323ec57SEd Maste 		error("failed to upload file %s to %s", src, targ);
1381e9e8876aSEd Maste 		errs = 1;
1382e9e8876aSEd Maste 	}
138319261079SEd Maste 
138419261079SEd Maste 	free(abs_dst);
138519261079SEd Maste 	free(target);
138619261079SEd Maste }
138719261079SEd Maste 
1388511b41d2SMark Murray void
source(int argc,char ** argv)1389cf2b5f3bSDag-Erling Smørgrav source(int argc, char **argv)
1390511b41d2SMark Murray {
1391511b41d2SMark Murray 	struct stat stb;
1392511b41d2SMark Murray 	static BUF buffer;
1393511b41d2SMark Murray 	BUF *bp;
1394d4af9e69SDag-Erling Smørgrav 	off_t i, statbytes;
1395a0ee8cc6SDag-Erling Smørgrav 	size_t amt, nr;
1396d4ecd108SDag-Erling Smørgrav 	int fd = -1, haderr, indx;
139719261079SEd Maste 	char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
13981e8db6e2SBrian Feldman 	int len;
1399511b41d2SMark Murray 
1400511b41d2SMark Murray 	for (indx = 0; indx < argc; ++indx) {
1401511b41d2SMark Murray 		name = argv[indx];
1402511b41d2SMark Murray 		statbytes = 0;
14031e8db6e2SBrian Feldman 		len = strlen(name);
14041e8db6e2SBrian Feldman 		while (len > 1 && name[len-1] == '/')
14051e8db6e2SBrian Feldman 			name[--len] = '\0';
14061323ec57SEd Maste 		if ((fd = open(name, O_RDONLY|O_NONBLOCK)) == -1)
1407511b41d2SMark Murray 			goto syserr;
1408d4af9e69SDag-Erling Smørgrav 		if (strchr(name, '\n') != NULL) {
1409d4af9e69SDag-Erling Smørgrav 			strnvis(encname, name, sizeof(encname), VIS_NL);
1410d4af9e69SDag-Erling Smørgrav 			name = encname;
1411d4af9e69SDag-Erling Smørgrav 		}
141219261079SEd Maste 		if (fstat(fd, &stb) == -1) {
1413511b41d2SMark Murray syserr:			run_err("%s: %s", name, strerror(errno));
1414511b41d2SMark Murray 			goto next;
1415511b41d2SMark Murray 		}
1416d4af9e69SDag-Erling Smørgrav 		if (stb.st_size < 0) {
1417d4af9e69SDag-Erling Smørgrav 			run_err("%s: %s", name, "Negative file size");
1418d4af9e69SDag-Erling Smørgrav 			goto next;
1419d4af9e69SDag-Erling Smørgrav 		}
1420d4af9e69SDag-Erling Smørgrav 		unset_nonblock(fd);
1421511b41d2SMark Murray 		switch (stb.st_mode & S_IFMT) {
1422511b41d2SMark Murray 		case S_IFREG:
1423511b41d2SMark Murray 			break;
1424511b41d2SMark Murray 		case S_IFDIR:
1425511b41d2SMark Murray 			if (iamrecursive) {
1426511b41d2SMark Murray 				rsource(name, &stb);
1427511b41d2SMark Murray 				goto next;
1428511b41d2SMark Murray 			}
1429511b41d2SMark Murray 			/* FALLTHROUGH */
1430511b41d2SMark Murray 		default:
1431511b41d2SMark Murray 			run_err("%s: not a regular file", name);
1432511b41d2SMark Murray 			goto next;
1433511b41d2SMark Murray 		}
1434511b41d2SMark Murray 		if ((last = strrchr(name, '/')) == NULL)
1435511b41d2SMark Murray 			last = name;
1436511b41d2SMark Murray 		else
1437511b41d2SMark Murray 			++last;
1438511b41d2SMark Murray 		curfile = last;
1439511b41d2SMark Murray 		if (pflag) {
1440e4a9863fSDag-Erling Smørgrav 			if (do_times(remout, verbose_mode, &stb) < 0)
1441511b41d2SMark Murray 				goto next;
1442511b41d2SMark Murray 		}
1443511b41d2SMark Murray #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
14441e8db6e2SBrian Feldman 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
14451e8db6e2SBrian Feldman 		    (u_int) (stb.st_mode & FILEMODEMASK),
1446b74df5b2SDag-Erling Smørgrav 		    (long long)stb.st_size, last);
1447076ad2f8SDag-Erling Smørgrav 		if (verbose_mode)
1448076ad2f8SDag-Erling Smørgrav 			fmprintf(stderr, "Sending file modes: %s", buf);
1449cf2b5f3bSDag-Erling Smørgrav 		(void) atomicio(vwrite, remout, buf, strlen(buf));
1450511b41d2SMark Murray 		if (response() < 0)
1451511b41d2SMark Murray 			goto next;
1452d4af9e69SDag-Erling Smørgrav 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1453b74df5b2SDag-Erling Smørgrav next:			if (fd != -1) {
1454b74df5b2SDag-Erling Smørgrav 				(void) close(fd);
1455b74df5b2SDag-Erling Smørgrav 				fd = -1;
1456b74df5b2SDag-Erling Smørgrav 			}
1457511b41d2SMark Murray 			continue;
1458511b41d2SMark Murray 		}
1459e73e9afaSDag-Erling Smørgrav 		if (showprogress)
1460e73e9afaSDag-Erling Smørgrav 			start_progress_meter(curfile, stb.st_size, &statbytes);
1461d4af9e69SDag-Erling Smørgrav 		set_nonblock(remout);
1462511b41d2SMark Murray 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
1463511b41d2SMark Murray 			amt = bp->cnt;
1464d4af9e69SDag-Erling Smørgrav 			if (i + (off_t)amt > stb.st_size)
1465511b41d2SMark Murray 				amt = stb.st_size - i;
1466511b41d2SMark Murray 			if (!haderr) {
1467a0ee8cc6SDag-Erling Smørgrav 				if ((nr = atomicio(read, fd,
1468a0ee8cc6SDag-Erling Smørgrav 				    bp->buf, amt)) != amt) {
1469d4ecd108SDag-Erling Smørgrav 					haderr = errno;
1470a0ee8cc6SDag-Erling Smørgrav 					memset(bp->buf + nr, 0, amt - nr);
1471a0ee8cc6SDag-Erling Smørgrav 				}
1472511b41d2SMark Murray 			}
1473d4af9e69SDag-Erling Smørgrav 			/* Keep writing after error to retain sync */
1474d4af9e69SDag-Erling Smørgrav 			if (haderr) {
1475cf2b5f3bSDag-Erling Smørgrav 				(void)atomicio(vwrite, remout, bp->buf, amt);
1476a0ee8cc6SDag-Erling Smørgrav 				memset(bp->buf, 0, amt);
1477d4af9e69SDag-Erling Smørgrav 				continue;
1478d4af9e69SDag-Erling Smørgrav 			}
14794a421b63SDag-Erling Smørgrav 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1480d4af9e69SDag-Erling Smørgrav 			    &statbytes) != amt)
1481d4ecd108SDag-Erling Smørgrav 				haderr = errno;
1482511b41d2SMark Murray 		}
1483d4af9e69SDag-Erling Smørgrav 		unset_nonblock(remout);
1484511b41d2SMark Murray 
1485b74df5b2SDag-Erling Smørgrav 		if (fd != -1) {
148619261079SEd Maste 			if (close(fd) == -1 && !haderr)
1487511b41d2SMark Murray 				haderr = errno;
1488b74df5b2SDag-Erling Smørgrav 			fd = -1;
1489b74df5b2SDag-Erling Smørgrav 		}
1490511b41d2SMark Murray 		if (!haderr)
1491cf2b5f3bSDag-Erling Smørgrav 			(void) atomicio(vwrite, remout, "", 1);
1492511b41d2SMark Murray 		else
1493511b41d2SMark Murray 			run_err("%s: %s", name, strerror(haderr));
1494511b41d2SMark Murray 		(void) response();
1495076ad2f8SDag-Erling Smørgrav 		if (showprogress)
1496076ad2f8SDag-Erling Smørgrav 			stop_progress_meter();
1497511b41d2SMark Murray 	}
1498511b41d2SMark Murray }
1499511b41d2SMark Murray 
1500511b41d2SMark Murray void
rsource(char * name,struct stat * statp)1501cf2b5f3bSDag-Erling Smørgrav rsource(char *name, struct stat *statp)
1502511b41d2SMark Murray {
1503511b41d2SMark Murray 	DIR *dirp;
1504511b41d2SMark Murray 	struct dirent *dp;
1505bc5531deSDag-Erling Smørgrav 	char *last, *vect[1], path[PATH_MAX];
1506511b41d2SMark Murray 
1507511b41d2SMark Murray 	if (!(dirp = opendir(name))) {
1508511b41d2SMark Murray 		run_err("%s: %s", name, strerror(errno));
1509511b41d2SMark Murray 		return;
1510511b41d2SMark Murray 	}
1511511b41d2SMark Murray 	last = strrchr(name, '/');
1512acc1a9efSDag-Erling Smørgrav 	if (last == NULL)
1513511b41d2SMark Murray 		last = name;
1514511b41d2SMark Murray 	else
1515511b41d2SMark Murray 		last++;
1516511b41d2SMark Murray 	if (pflag) {
1517e4a9863fSDag-Erling Smørgrav 		if (do_times(remout, verbose_mode, statp) < 0) {
1518511b41d2SMark Murray 			closedir(dirp);
1519511b41d2SMark Murray 			return;
1520511b41d2SMark Murray 		}
1521511b41d2SMark Murray 	}
15221e8db6e2SBrian Feldman 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
15231e8db6e2SBrian Feldman 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1524511b41d2SMark Murray 	if (verbose_mode)
1525076ad2f8SDag-Erling Smørgrav 		fmprintf(stderr, "Entering directory: %s", path);
1526cf2b5f3bSDag-Erling Smørgrav 	(void) atomicio(vwrite, remout, path, strlen(path));
1527511b41d2SMark Murray 	if (response() < 0) {
1528511b41d2SMark Murray 		closedir(dirp);
1529511b41d2SMark Murray 		return;
1530511b41d2SMark Murray 	}
15311e8db6e2SBrian Feldman 	while ((dp = readdir(dirp)) != NULL) {
1532511b41d2SMark Murray 		if (dp->d_ino == 0)
1533511b41d2SMark Murray 			continue;
1534511b41d2SMark Murray 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
1535511b41d2SMark Murray 			continue;
1536511b41d2SMark Murray 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
1537511b41d2SMark Murray 			run_err("%s/%s: name too long", name, dp->d_name);
1538511b41d2SMark Murray 			continue;
1539511b41d2SMark Murray 		}
15401e8db6e2SBrian Feldman 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
1541511b41d2SMark Murray 		vect[0] = path;
1542511b41d2SMark Murray 		source(1, vect);
1543511b41d2SMark Murray 	}
1544511b41d2SMark Murray 	(void) closedir(dirp);
1545cf2b5f3bSDag-Erling Smørgrav 	(void) atomicio(vwrite, remout, "E\n", 2);
1546511b41d2SMark Murray 	(void) response();
1547511b41d2SMark Murray }
1548511b41d2SMark Murray 
154919261079SEd Maste void
sink_sftp(int argc,char * dst,const char * src,struct sftp_conn * conn)155019261079SEd Maste sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn)
155119261079SEd Maste {
155219261079SEd Maste 	char *abs_src = NULL;
155319261079SEd Maste 	char *abs_dst = NULL;
155419261079SEd Maste 	glob_t g;
155519261079SEd Maste 	char *filename, *tmp = NULL;
15561323ec57SEd Maste 	int i, r, err = 0, dst_is_dir;
15571323ec57SEd Maste 	struct stat st;
155819261079SEd Maste 
155919261079SEd Maste 	memset(&g, 0, sizeof(g));
15601323ec57SEd Maste 
156119261079SEd Maste 	/*
156219261079SEd Maste 	 * Here, we need remote glob as SFTP can not depend on remote shell
156319261079SEd Maste 	 * expansions
156419261079SEd Maste 	 */
156519261079SEd Maste 	if ((abs_src = prepare_remote_path(conn, src)) == NULL) {
156619261079SEd Maste 		err = -1;
156719261079SEd Maste 		goto out;
156819261079SEd Maste 	}
156919261079SEd Maste 
157019261079SEd Maste 	debug3_f("copying remote %s to local %s", abs_src, dst);
1571edf85781SEd Maste 	if ((r = sftp_glob(conn, abs_src, GLOB_NOCHECK|GLOB_MARK,
1572f374ba41SEd Maste 	    NULL, &g)) != 0) {
157319261079SEd Maste 		if (r == GLOB_NOSPACE)
15741323ec57SEd Maste 			error("%s: too many glob matches", src);
157519261079SEd Maste 		else
15761323ec57SEd Maste 			error("%s: %s", src, strerror(ENOENT));
157719261079SEd Maste 		err = -1;
157819261079SEd Maste 		goto out;
157919261079SEd Maste 	}
158019261079SEd Maste 
1581f374ba41SEd Maste 	/* Did we actually get any matches back from the glob? */
1582f374ba41SEd Maste 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
1583f374ba41SEd Maste 		/*
1584f374ba41SEd Maste 		 * If nothing matched but a path returned, then it's probably
1585f374ba41SEd Maste 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
1586f374ba41SEd Maste 		 * exists so we can give a nice error message early.
1587f374ba41SEd Maste 		 */
1588edf85781SEd Maste 		if (sftp_stat(conn, g.gl_pathv[0], 1, NULL) != 0) {
1589f374ba41SEd Maste 			error("%s: %s", src, strerror(ENOENT));
1590f374ba41SEd Maste 			err = -1;
1591f374ba41SEd Maste 			goto out;
1592f374ba41SEd Maste 		}
1593f374ba41SEd Maste 	}
1594f374ba41SEd Maste 
15951323ec57SEd Maste 	if ((r = stat(dst, &st)) != 0)
15961323ec57SEd Maste 		debug2_f("stat local \"%s\": %s", dst, strerror(errno));
15971323ec57SEd Maste 	dst_is_dir = r == 0 && S_ISDIR(st.st_mode);
15981323ec57SEd Maste 
15991323ec57SEd Maste 	if (g.gl_matchc > 1 && !dst_is_dir) {
16001323ec57SEd Maste 		if (r == 0) {
160119261079SEd Maste 			error("Multiple files match pattern, but destination "
160219261079SEd Maste 			    "\"%s\" is not a directory", dst);
160319261079SEd Maste 			err = -1;
160419261079SEd Maste 			goto out;
160519261079SEd Maste 		}
16061323ec57SEd Maste 		debug2_f("creating destination \"%s\"", dst);
16071323ec57SEd Maste 		if (mkdir(dst, 0777) != 0) {
16081323ec57SEd Maste 			error("local mkdir \"%s\": %s", dst, strerror(errno));
16091323ec57SEd Maste 			err = -1;
16101323ec57SEd Maste 			goto out;
16111323ec57SEd Maste 		}
16121323ec57SEd Maste 		dst_is_dir = 1;
16131323ec57SEd Maste 	}
161419261079SEd Maste 
161519261079SEd Maste 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
161619261079SEd Maste 		tmp = xstrdup(g.gl_pathv[i]);
161719261079SEd Maste 		if ((filename = basename(tmp)) == NULL) {
161819261079SEd Maste 			error("basename %s: %s", tmp, strerror(errno));
161919261079SEd Maste 			err = -1;
162019261079SEd Maste 			goto out;
162119261079SEd Maste 		}
162219261079SEd Maste 
16231323ec57SEd Maste 		if (dst_is_dir)
1624edf85781SEd Maste 			abs_dst = sftp_path_append(dst, filename);
162519261079SEd Maste 		else
162619261079SEd Maste 			abs_dst = xstrdup(dst);
162719261079SEd Maste 
162819261079SEd Maste 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
1629edf85781SEd Maste 		if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
1630edf85781SEd Maste 			if (sftp_download_dir(conn, g.gl_pathv[i], abs_dst,
1631edf85781SEd Maste 			    NULL, pflag, SFTP_PROGRESS_ONLY, 0, 0, 1, 1) == -1)
163219261079SEd Maste 				err = -1;
163319261079SEd Maste 		} else {
1634edf85781SEd Maste 			if (sftp_download(conn, g.gl_pathv[i], abs_dst, NULL,
163538a52bd3SEd Maste 			    pflag, 0, 0, 1) == -1)
163619261079SEd Maste 				err = -1;
163719261079SEd Maste 		}
163819261079SEd Maste 		free(abs_dst);
163919261079SEd Maste 		abs_dst = NULL;
164019261079SEd Maste 		free(tmp);
164119261079SEd Maste 		tmp = NULL;
164219261079SEd Maste 	}
164319261079SEd Maste 
164419261079SEd Maste out:
164519261079SEd Maste 	free(abs_src);
164619261079SEd Maste 	free(tmp);
164719261079SEd Maste 	globfree(&g);
1648e9e8876aSEd Maste 	if (err == -1)
1649e9e8876aSEd Maste 		errs = 1;
165019261079SEd Maste }
165119261079SEd Maste 
165219261079SEd Maste 
16534f52dfbbSDag-Erling Smørgrav #define TYPE_OVERFLOW(type, val) \
16544f52dfbbSDag-Erling Smørgrav 	((sizeof(type) == 4 && (val) > INT32_MAX) || \
16554f52dfbbSDag-Erling Smørgrav 	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
16564f52dfbbSDag-Erling Smørgrav 	 (sizeof(type) != 4 && sizeof(type) != 8))
16574f52dfbbSDag-Erling Smørgrav 
1658511b41d2SMark Murray void
sink(int argc,char ** argv,const char * src)1659afde5170SEd Maste sink(int argc, char **argv, const char *src)
1660511b41d2SMark Murray {
1661511b41d2SMark Murray 	static BUF buffer;
1662511b41d2SMark Murray 	struct stat stb;
1663511b41d2SMark Murray 	BUF *bp;
1664d4ecd108SDag-Erling Smørgrav 	off_t i;
1665d4ecd108SDag-Erling Smørgrav 	size_t j, count;
1666333ee039SDag-Erling Smørgrav 	int amt, exists, first, ofd;
1667333ee039SDag-Erling Smørgrav 	mode_t mode, omode, mask;
1668e73e9afaSDag-Erling Smørgrav 	off_t size, statbytes;
1669e4a9863fSDag-Erling Smørgrav 	unsigned long long ull;
167019261079SEd Maste 	int setimes, targisdir, wrerr;
1671076ad2f8SDag-Erling Smørgrav 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
16720967215dSEd Maste 	char **patterns = NULL;
16730967215dSEd Maste 	size_t n, npatterns = 0;
16745b9b2fafSBrian Feldman 	struct timeval tv[2];
1675511b41d2SMark Murray 
16761e8db6e2SBrian Feldman #define	atime	tv[0]
16771e8db6e2SBrian Feldman #define	mtime	tv[1]
1678aa49c926SDag-Erling Smørgrav #define	SCREWUP(str)	{ why = str; goto screwup; }
1679511b41d2SMark Murray 
16804f52dfbbSDag-Erling Smørgrav 	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
16814f52dfbbSDag-Erling Smørgrav 		SCREWUP("Unexpected off_t/time_t size");
16824f52dfbbSDag-Erling Smørgrav 
1683511b41d2SMark Murray 	setimes = targisdir = 0;
1684511b41d2SMark Murray 	mask = umask(0);
1685511b41d2SMark Murray 	if (!pflag)
1686511b41d2SMark Murray 		(void) umask(mask);
1687511b41d2SMark Murray 	if (argc != 1) {
1688511b41d2SMark Murray 		run_err("ambiguous target");
1689511b41d2SMark Murray 		exit(1);
1690511b41d2SMark Murray 	}
1691511b41d2SMark Murray 	targ = *argv;
1692511b41d2SMark Murray 	if (targetshouldbedirectory)
1693511b41d2SMark Murray 		verifydir(targ);
1694511b41d2SMark Murray 
1695cf2b5f3bSDag-Erling Smørgrav 	(void) atomicio(vwrite, remout, "", 1);
1696511b41d2SMark Murray 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1697511b41d2SMark Murray 		targisdir = 1;
1698afde5170SEd Maste 	if (src != NULL && !iamrecursive && !Tflag) {
1699afde5170SEd Maste 		/*
1700afde5170SEd Maste 		 * Prepare to try to restrict incoming filenames to match
1701afde5170SEd Maste 		 * the requested destination file glob.
1702afde5170SEd Maste 		 */
17030967215dSEd Maste 		if (brace_expand(src, &patterns, &npatterns) != 0)
170419261079SEd Maste 			fatal_f("could not expand pattern");
1705afde5170SEd Maste 	}
1706511b41d2SMark Murray 	for (first = 1;; first = 0) {
1707511b41d2SMark Murray 		cp = buf;
1708d4ecd108SDag-Erling Smørgrav 		if (atomicio(read, remin, cp, 1) != 1)
17090967215dSEd Maste 			goto done;
1710511b41d2SMark Murray 		if (*cp++ == '\n')
1711511b41d2SMark Murray 			SCREWUP("unexpected <newline>");
1712511b41d2SMark Murray 		do {
1713a04a10f8SKris Kennaway 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1714511b41d2SMark Murray 				SCREWUP("lost connection");
1715511b41d2SMark Murray 			*cp++ = ch;
1716511b41d2SMark Murray 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1717511b41d2SMark Murray 		*cp = 0;
171821e764dfSDag-Erling Smørgrav 		if (verbose_mode)
1719076ad2f8SDag-Erling Smørgrav 			fmprintf(stderr, "Sink: %s", buf);
1720511b41d2SMark Murray 
1721511b41d2SMark Murray 		if (buf[0] == '\01' || buf[0] == '\02') {
1722076ad2f8SDag-Erling Smørgrav 			if (iamremote == 0) {
1723076ad2f8SDag-Erling Smørgrav 				(void) snmprintf(visbuf, sizeof(visbuf),
1724076ad2f8SDag-Erling Smørgrav 				    NULL, "%s", buf + 1);
1725cf2b5f3bSDag-Erling Smørgrav 				(void) atomicio(vwrite, STDERR_FILENO,
1726076ad2f8SDag-Erling Smørgrav 				    visbuf, strlen(visbuf));
1727076ad2f8SDag-Erling Smørgrav 			}
1728511b41d2SMark Murray 			if (buf[0] == '\02')
1729511b41d2SMark Murray 				exit(1);
1730511b41d2SMark Murray 			++errs;
1731511b41d2SMark Murray 			continue;
1732511b41d2SMark Murray 		}
1733511b41d2SMark Murray 		if (buf[0] == 'E') {
1734cf2b5f3bSDag-Erling Smørgrav 			(void) atomicio(vwrite, remout, "", 1);
17350967215dSEd Maste 			goto done;
1736511b41d2SMark Murray 		}
1737511b41d2SMark Murray 		if (ch == '\n')
1738511b41d2SMark Murray 			*--cp = 0;
1739511b41d2SMark Murray 
1740511b41d2SMark Murray 		cp = buf;
1741511b41d2SMark Murray 		if (*cp == 'T') {
1742511b41d2SMark Murray 			setimes++;
1743511b41d2SMark Murray 			cp++;
1744e4a9863fSDag-Erling Smørgrav 			if (!isdigit((unsigned char)*cp))
1745e4a9863fSDag-Erling Smørgrav 				SCREWUP("mtime.sec not present");
1746e4a9863fSDag-Erling Smørgrav 			ull = strtoull(cp, &cp, 10);
17471e8db6e2SBrian Feldman 			if (!cp || *cp++ != ' ')
1748511b41d2SMark Murray 				SCREWUP("mtime.sec not delimited");
17494f52dfbbSDag-Erling Smørgrav 			if (TYPE_OVERFLOW(time_t, ull))
1750e4a9863fSDag-Erling Smørgrav 				setimes = 0;	/* out of range */
1751e4a9863fSDag-Erling Smørgrav 			mtime.tv_sec = ull;
17521e8db6e2SBrian Feldman 			mtime.tv_usec = strtol(cp, &cp, 10);
1753e4a9863fSDag-Erling Smørgrav 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1754e4a9863fSDag-Erling Smørgrav 			    mtime.tv_usec > 999999)
1755511b41d2SMark Murray 				SCREWUP("mtime.usec not delimited");
1756e4a9863fSDag-Erling Smørgrav 			if (!isdigit((unsigned char)*cp))
1757e4a9863fSDag-Erling Smørgrav 				SCREWUP("atime.sec not present");
1758e4a9863fSDag-Erling Smørgrav 			ull = strtoull(cp, &cp, 10);
17591e8db6e2SBrian Feldman 			if (!cp || *cp++ != ' ')
1760511b41d2SMark Murray 				SCREWUP("atime.sec not delimited");
17614f52dfbbSDag-Erling Smørgrav 			if (TYPE_OVERFLOW(time_t, ull))
1762e4a9863fSDag-Erling Smørgrav 				setimes = 0;	/* out of range */
1763e4a9863fSDag-Erling Smørgrav 			atime.tv_sec = ull;
17641e8db6e2SBrian Feldman 			atime.tv_usec = strtol(cp, &cp, 10);
1765e4a9863fSDag-Erling Smørgrav 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1766e4a9863fSDag-Erling Smørgrav 			    atime.tv_usec > 999999)
1767511b41d2SMark Murray 				SCREWUP("atime.usec not delimited");
1768cf2b5f3bSDag-Erling Smørgrav 			(void) atomicio(vwrite, remout, "", 1);
1769511b41d2SMark Murray 			continue;
1770511b41d2SMark Murray 		}
1771511b41d2SMark Murray 		if (*cp != 'C' && *cp != 'D') {
1772511b41d2SMark Murray 			/*
1773511b41d2SMark Murray 			 * Check for the case "rcp remote:foo\* local:bar".
1774511b41d2SMark Murray 			 * In this case, the line "No match." can be returned
1775511b41d2SMark Murray 			 * by the shell before the rcp command on the remote is
1776511b41d2SMark Murray 			 * executed so the ^Aerror_message convention isn't
1777511b41d2SMark Murray 			 * followed.
1778511b41d2SMark Murray 			 */
1779511b41d2SMark Murray 			if (first) {
1780511b41d2SMark Murray 				run_err("%s", cp);
1781511b41d2SMark Murray 				exit(1);
1782511b41d2SMark Murray 			}
1783511b41d2SMark Murray 			SCREWUP("expected control record");
1784511b41d2SMark Murray 		}
1785511b41d2SMark Murray 		mode = 0;
1786511b41d2SMark Murray 		for (++cp; cp < buf + 5; cp++) {
1787511b41d2SMark Murray 			if (*cp < '0' || *cp > '7')
1788511b41d2SMark Murray 				SCREWUP("bad mode");
1789511b41d2SMark Murray 			mode = (mode << 3) | (*cp - '0');
1790511b41d2SMark Murray 		}
1791190cef3dSDag-Erling Smørgrav 		if (!pflag)
1792190cef3dSDag-Erling Smørgrav 			mode &= ~mask;
1793511b41d2SMark Murray 		if (*cp++ != ' ')
1794511b41d2SMark Murray 			SCREWUP("mode not delimited");
1795511b41d2SMark Murray 
17964f52dfbbSDag-Erling Smørgrav 		if (!isdigit((unsigned char)*cp))
17974f52dfbbSDag-Erling Smørgrav 			SCREWUP("size not present");
17984f52dfbbSDag-Erling Smørgrav 		ull = strtoull(cp, &cp, 10);
17994f52dfbbSDag-Erling Smørgrav 		if (!cp || *cp++ != ' ')
1800511b41d2SMark Murray 			SCREWUP("size not delimited");
18014f52dfbbSDag-Erling Smørgrav 		if (TYPE_OVERFLOW(off_t, ull))
18024f52dfbbSDag-Erling Smørgrav 			SCREWUP("size out of range");
18034f52dfbbSDag-Erling Smørgrav 		size = (off_t)ull;
18044f52dfbbSDag-Erling Smørgrav 
1805d366f891SEd Maste 		if (*cp == '\0' || strchr(cp, '/') != NULL ||
1806d366f891SEd Maste 		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
180721e764dfSDag-Erling Smørgrav 			run_err("error: unexpected filename: %s", cp);
180821e764dfSDag-Erling Smørgrav 			exit(1);
180921e764dfSDag-Erling Smørgrav 		}
18100967215dSEd Maste 		if (npatterns > 0) {
18110967215dSEd Maste 			for (n = 0; n < npatterns; n++) {
1812f374ba41SEd Maste 				if (strcmp(patterns[n], cp) == 0 ||
1813f374ba41SEd Maste 				    fnmatch(patterns[n], cp, 0) == 0)
18140967215dSEd Maste 					break;
18150967215dSEd Maste 			}
1816069ac184SEd Maste 			if (n >= npatterns) {
1817069ac184SEd Maste 				debug2_f("incoming filename \"%s\" does not "
1818069ac184SEd Maste 				    "match any of %zu expected patterns", cp,
1819069ac184SEd Maste 				    npatterns);
1820069ac184SEd Maste 				for (n = 0; n < npatterns; n++) {
1821069ac184SEd Maste 					debug3_f("expected pattern %zu: \"%s\"",
1822069ac184SEd Maste 					    n, patterns[n]);
1823069ac184SEd Maste 				}
1824afde5170SEd Maste 				SCREWUP("filename does not match request");
18250967215dSEd Maste 			}
1826069ac184SEd Maste 		}
1827511b41d2SMark Murray 		if (targisdir) {
1828511b41d2SMark Murray 			static char *namebuf;
1829d4ecd108SDag-Erling Smørgrav 			static size_t cursize;
1830511b41d2SMark Murray 			size_t need;
1831511b41d2SMark Murray 
1832511b41d2SMark Murray 			need = strlen(targ) + strlen(cp) + 250;
18331e8db6e2SBrian Feldman 			if (need > cursize) {
1834e4a9863fSDag-Erling Smørgrav 				free(namebuf);
1835511b41d2SMark Murray 				namebuf = xmalloc(need);
18361e8db6e2SBrian Feldman 				cursize = need;
18371e8db6e2SBrian Feldman 			}
18381e8db6e2SBrian Feldman 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1839545d5ecaSDag-Erling Smørgrav 			    strcmp(targ, "/") ? "/" : "", cp);
1840511b41d2SMark Murray 			np = namebuf;
1841511b41d2SMark Murray 		} else
1842511b41d2SMark Murray 			np = targ;
1843511b41d2SMark Murray 		curfile = cp;
1844511b41d2SMark Murray 		exists = stat(np, &stb) == 0;
1845511b41d2SMark Murray 		if (buf[0] == 'D') {
1846511b41d2SMark Murray 			int mod_flag = pflag;
184721e764dfSDag-Erling Smørgrav 			if (!iamrecursive)
184821e764dfSDag-Erling Smørgrav 				SCREWUP("received directory without -r");
1849511b41d2SMark Murray 			if (exists) {
1850511b41d2SMark Murray 				if (!S_ISDIR(stb.st_mode)) {
1851511b41d2SMark Murray 					errno = ENOTDIR;
1852511b41d2SMark Murray 					goto bad;
1853511b41d2SMark Murray 				}
1854511b41d2SMark Murray 				if (pflag)
1855511b41d2SMark Murray 					(void) chmod(np, mode);
1856511b41d2SMark Murray 			} else {
185719261079SEd Maste 				/* Handle copying from a read-only directory */
1858511b41d2SMark Murray 				mod_flag = 1;
185919261079SEd Maste 				if (mkdir(np, mode | S_IRWXU) == -1)
1860511b41d2SMark Murray 					goto bad;
1861511b41d2SMark Murray 			}
18621e8db6e2SBrian Feldman 			vect[0] = xstrdup(np);
1863afde5170SEd Maste 			sink(1, vect, src);
1864511b41d2SMark Murray 			if (setimes) {
1865511b41d2SMark Murray 				setimes = 0;
186619261079SEd Maste 				(void) utimes(vect[0], tv);
1867511b41d2SMark Murray 			}
1868511b41d2SMark Murray 			if (mod_flag)
18691e8db6e2SBrian Feldman 				(void) chmod(vect[0], mode);
1870e4a9863fSDag-Erling Smørgrav 			free(vect[0]);
1871511b41d2SMark Murray 			continue;
1872511b41d2SMark Murray 		}
1873511b41d2SMark Murray 		omode = mode;
1874e4a9863fSDag-Erling Smørgrav 		mode |= S_IWUSR;
187519261079SEd Maste 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
1876511b41d2SMark Murray bad:			run_err("%s: %s", np, strerror(errno));
1877511b41d2SMark Murray 			continue;
1878511b41d2SMark Murray 		}
1879cf2b5f3bSDag-Erling Smørgrav 		(void) atomicio(vwrite, remout, "", 1);
1880d4af9e69SDag-Erling Smørgrav 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1881511b41d2SMark Murray 			(void) close(ofd);
1882511b41d2SMark Murray 			continue;
1883511b41d2SMark Murray 		}
1884511b41d2SMark Murray 		cp = bp->buf;
188519261079SEd Maste 		wrerr = 0;
1886511b41d2SMark Murray 
188719261079SEd Maste 		/*
188819261079SEd Maste 		 * NB. do not use run_err() unless immediately followed by
188919261079SEd Maste 		 * exit() below as it may send a spurious reply that might
189019261079SEd Maste 		 * desyncronise us from the peer. Use note_err() instead.
189119261079SEd Maste 		 */
1892511b41d2SMark Murray 		statbytes = 0;
1893e73e9afaSDag-Erling Smørgrav 		if (showprogress)
1894e73e9afaSDag-Erling Smørgrav 			start_progress_meter(curfile, size, &statbytes);
1895d4af9e69SDag-Erling Smørgrav 		set_nonblock(remin);
1896d4af9e69SDag-Erling Smørgrav 		for (count = i = 0; i < size; i += bp->cnt) {
1897d4af9e69SDag-Erling Smørgrav 			amt = bp->cnt;
1898511b41d2SMark Murray 			if (i + amt > size)
1899511b41d2SMark Murray 				amt = size - i;
1900511b41d2SMark Murray 			count += amt;
1901511b41d2SMark Murray 			do {
19024a421b63SDag-Erling Smørgrav 				j = atomicio6(read, remin, cp, amt,
19034a421b63SDag-Erling Smørgrav 				    scpio, &statbytes);
1904d4ecd108SDag-Erling Smørgrav 				if (j == 0) {
1905d4af9e69SDag-Erling Smørgrav 					run_err("%s", j != EPIPE ?
1906d4af9e69SDag-Erling Smørgrav 					    strerror(errno) :
1907511b41d2SMark Murray 					    "dropped connection");
1908511b41d2SMark Murray 					exit(1);
1909511b41d2SMark Murray 				}
1910511b41d2SMark Murray 				amt -= j;
1911511b41d2SMark Murray 				cp += j;
1912511b41d2SMark Murray 			} while (amt > 0);
1913e73e9afaSDag-Erling Smørgrav 
1914511b41d2SMark Murray 			if (count == bp->cnt) {
1915511b41d2SMark Murray 				/* Keep reading so we stay sync'd up. */
191619261079SEd Maste 				if (!wrerr) {
1917d4ecd108SDag-Erling Smørgrav 					if (atomicio(vwrite, ofd, bp->buf,
1918d4ecd108SDag-Erling Smørgrav 					    count) != count) {
191919261079SEd Maste 						note_err("%s: %s", np,
192019261079SEd Maste 						    strerror(errno));
192119261079SEd Maste 						wrerr = 1;
1922511b41d2SMark Murray 					}
1923511b41d2SMark Murray 				}
1924511b41d2SMark Murray 				count = 0;
1925511b41d2SMark Murray 				cp = bp->buf;
1926511b41d2SMark Murray 			}
1927511b41d2SMark Murray 		}
1928d4af9e69SDag-Erling Smørgrav 		unset_nonblock(remin);
192919261079SEd Maste 		if (count != 0 && !wrerr &&
1930d4ecd108SDag-Erling Smørgrav 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
193119261079SEd Maste 			note_err("%s: %s", np, strerror(errno));
193219261079SEd Maste 			wrerr = 1;
1933511b41d2SMark Murray 		}
193419261079SEd Maste 		if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
193519261079SEd Maste 		    ftruncate(ofd, size) != 0)
193619261079SEd Maste 			note_err("%s: truncate: %s", np, strerror(errno));
1937511b41d2SMark Murray 		if (pflag) {
1938511b41d2SMark Murray 			if (exists || omode != mode)
193983d2307dSDag-Erling Smørgrav #ifdef HAVE_FCHMOD
194021e764dfSDag-Erling Smørgrav 				if (fchmod(ofd, omode)) {
194183d2307dSDag-Erling Smørgrav #else /* HAVE_FCHMOD */
194221e764dfSDag-Erling Smørgrav 				if (chmod(np, omode)) {
194383d2307dSDag-Erling Smørgrav #endif /* HAVE_FCHMOD */
194419261079SEd Maste 					note_err("%s: set mode: %s",
1945511b41d2SMark Murray 					    np, strerror(errno));
194621e764dfSDag-Erling Smørgrav 				}
1947511b41d2SMark Murray 		} else {
1948511b41d2SMark Murray 			if (!exists && omode != mode)
194983d2307dSDag-Erling Smørgrav #ifdef HAVE_FCHMOD
195021e764dfSDag-Erling Smørgrav 				if (fchmod(ofd, omode & ~mask)) {
195183d2307dSDag-Erling Smørgrav #else /* HAVE_FCHMOD */
195221e764dfSDag-Erling Smørgrav 				if (chmod(np, omode & ~mask)) {
195383d2307dSDag-Erling Smørgrav #endif /* HAVE_FCHMOD */
195419261079SEd Maste 					note_err("%s: set mode: %s",
1955511b41d2SMark Murray 					    np, strerror(errno));
195621e764dfSDag-Erling Smørgrav 				}
1957511b41d2SMark Murray 		}
195819261079SEd Maste 		if (close(ofd) == -1)
195919261079SEd Maste 			note_err("%s: close: %s", np, strerror(errno));
1960511b41d2SMark Murray 		(void) response();
1961076ad2f8SDag-Erling Smørgrav 		if (showprogress)
1962076ad2f8SDag-Erling Smørgrav 			stop_progress_meter();
196319261079SEd Maste 		if (setimes && !wrerr) {
1964511b41d2SMark Murray 			setimes = 0;
196519261079SEd Maste 			if (utimes(np, tv) == -1) {
196619261079SEd Maste 				note_err("%s: set times: %s",
1967511b41d2SMark Murray 				    np, strerror(errno));
1968511b41d2SMark Murray 			}
1969511b41d2SMark Murray 		}
197019261079SEd Maste 		/* If no error was noted then signal success for this file */
197119261079SEd Maste 		if (note_err(NULL) == 0)
1972cf2b5f3bSDag-Erling Smørgrav 			(void) atomicio(vwrite, remout, "", 1);
1973511b41d2SMark Murray 	}
19740967215dSEd Maste done:
19750967215dSEd Maste 	for (n = 0; n < npatterns; n++)
19760967215dSEd Maste 		free(patterns[n]);
19770967215dSEd Maste 	free(patterns);
19780967215dSEd Maste 	return;
1979511b41d2SMark Murray screwup:
19800967215dSEd Maste 	for (n = 0; n < npatterns; n++)
19810967215dSEd Maste 		free(patterns[n]);
19820967215dSEd Maste 	free(patterns);
1983511b41d2SMark Murray 	run_err("protocol error: %s", why);
1984511b41d2SMark Murray 	exit(1);
1985511b41d2SMark Murray }
1986511b41d2SMark Murray 
198719261079SEd Maste void
198819261079SEd Maste throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to,
198919261079SEd Maste     char *src, char *targ)
199019261079SEd Maste {
199119261079SEd Maste 	char *target = NULL, *filename = NULL, *abs_dst = NULL;
199219261079SEd Maste 	char *abs_src = NULL, *tmp = NULL;
199319261079SEd Maste 	glob_t g;
199419261079SEd Maste 	int i, r, targetisdir, err = 0;
199519261079SEd Maste 
199619261079SEd Maste 	if ((filename = basename(src)) == NULL)
199719261079SEd Maste 		fatal("basename %s: %s", src, strerror(errno));
199819261079SEd Maste 
199919261079SEd Maste 	if ((abs_src = prepare_remote_path(from, src)) == NULL ||
200019261079SEd Maste 	    (target = prepare_remote_path(to, targ)) == NULL)
200119261079SEd Maste 		cleanup_exit(255);
200219261079SEd Maste 	memset(&g, 0, sizeof(g));
200319261079SEd Maste 
2004edf85781SEd Maste 	targetisdir = sftp_remote_is_dir(to, target);
200519261079SEd Maste 	if (!targetisdir && targetshouldbedirectory) {
20061323ec57SEd Maste 		error("%s: destination is not a directory", targ);
200719261079SEd Maste 		err = -1;
200819261079SEd Maste 		goto out;
200919261079SEd Maste 	}
201019261079SEd Maste 
201119261079SEd Maste 	debug3_f("copying remote %s to remote %s", abs_src, target);
2012edf85781SEd Maste 	if ((r = sftp_glob(from, abs_src, GLOB_NOCHECK|GLOB_MARK,
2013f374ba41SEd Maste 	    NULL, &g)) != 0) {
201419261079SEd Maste 		if (r == GLOB_NOSPACE)
20151323ec57SEd Maste 			error("%s: too many glob matches", src);
201619261079SEd Maste 		else
20171323ec57SEd Maste 			error("%s: %s", src, strerror(ENOENT));
201819261079SEd Maste 		err = -1;
201919261079SEd Maste 		goto out;
202019261079SEd Maste 	}
202119261079SEd Maste 
2022f374ba41SEd Maste 	/* Did we actually get any matches back from the glob? */
2023f374ba41SEd Maste 	if (g.gl_matchc == 0 && g.gl_pathc == 1 && g.gl_pathv[0] != 0) {
2024f374ba41SEd Maste 		/*
2025f374ba41SEd Maste 		 * If nothing matched but a path returned, then it's probably
2026f374ba41SEd Maste 		 * a GLOB_NOCHECK result. Check whether the unglobbed path
2027f374ba41SEd Maste 		 * exists so we can give a nice error message early.
2028f374ba41SEd Maste 		 */
2029edf85781SEd Maste 		if (sftp_stat(from, g.gl_pathv[0], 1, NULL) != 0) {
2030f374ba41SEd Maste 			error("%s: %s", src, strerror(ENOENT));
2031f374ba41SEd Maste 			err = -1;
2032f374ba41SEd Maste 			goto out;
2033f374ba41SEd Maste 		}
2034f374ba41SEd Maste 	}
2035f374ba41SEd Maste 
203619261079SEd Maste 	for (i = 0; g.gl_pathv[i] && !interrupted; i++) {
203719261079SEd Maste 		tmp = xstrdup(g.gl_pathv[i]);
203819261079SEd Maste 		if ((filename = basename(tmp)) == NULL) {
203919261079SEd Maste 			error("basename %s: %s", tmp, strerror(errno));
204019261079SEd Maste 			err = -1;
204119261079SEd Maste 			goto out;
204219261079SEd Maste 		}
204319261079SEd Maste 
204419261079SEd Maste 		if (targetisdir)
2045edf85781SEd Maste 			abs_dst = sftp_path_append(target, filename);
204619261079SEd Maste 		else
204719261079SEd Maste 			abs_dst = xstrdup(target);
204819261079SEd Maste 
204919261079SEd Maste 		debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst);
2050edf85781SEd Maste 		if (sftp_globpath_is_dir(g.gl_pathv[i]) && iamrecursive) {
2051edf85781SEd Maste 			if (sftp_crossload_dir(from, to, g.gl_pathv[i], abs_dst,
205219261079SEd Maste 			    NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1)
205319261079SEd Maste 				err = -1;
205419261079SEd Maste 		} else {
2055edf85781SEd Maste 			if (sftp_crossload(from, to, g.gl_pathv[i], abs_dst,
2056edf85781SEd Maste 			    NULL, pflag) == -1)
205719261079SEd Maste 				err = -1;
205819261079SEd Maste 		}
205919261079SEd Maste 		free(abs_dst);
206019261079SEd Maste 		abs_dst = NULL;
206119261079SEd Maste 		free(tmp);
206219261079SEd Maste 		tmp = NULL;
206319261079SEd Maste 	}
206419261079SEd Maste 
206519261079SEd Maste out:
206619261079SEd Maste 	free(abs_src);
206719261079SEd Maste 	free(abs_dst);
206819261079SEd Maste 	free(target);
206919261079SEd Maste 	free(tmp);
207019261079SEd Maste 	globfree(&g);
207119261079SEd Maste 	if (err == -1)
2072e9e8876aSEd Maste 		errs = 1;
207319261079SEd Maste }
207419261079SEd Maste 
2075511b41d2SMark Murray int
2076ae1f160dSDag-Erling Smørgrav response(void)
2077511b41d2SMark Murray {
2078076ad2f8SDag-Erling Smørgrav 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
2079511b41d2SMark Murray 
2080a04a10f8SKris Kennaway 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
2081511b41d2SMark Murray 		lostconn(0);
2082511b41d2SMark Murray 
2083511b41d2SMark Murray 	cp = rbuf;
2084511b41d2SMark Murray 	switch (resp) {
2085511b41d2SMark Murray 	case 0:		/* ok */
2086511b41d2SMark Murray 		return (0);
2087511b41d2SMark Murray 	default:
2088511b41d2SMark Murray 		*cp++ = resp;
2089511b41d2SMark Murray 		/* FALLTHROUGH */
2090511b41d2SMark Murray 	case 1:		/* error, followed by error msg */
2091511b41d2SMark Murray 	case 2:		/* fatal error, "" */
2092511b41d2SMark Murray 		do {
2093a04a10f8SKris Kennaway 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
2094511b41d2SMark Murray 				lostconn(0);
2095511b41d2SMark Murray 			*cp++ = ch;
2096511b41d2SMark Murray 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
2097511b41d2SMark Murray 
2098076ad2f8SDag-Erling Smørgrav 		if (!iamremote) {
2099076ad2f8SDag-Erling Smørgrav 			cp[-1] = '\0';
2100076ad2f8SDag-Erling Smørgrav 			(void) snmprintf(visbuf, sizeof(visbuf),
2101076ad2f8SDag-Erling Smørgrav 			    NULL, "%s\n", rbuf);
2102076ad2f8SDag-Erling Smørgrav 			(void) atomicio(vwrite, STDERR_FILENO,
2103076ad2f8SDag-Erling Smørgrav 			    visbuf, strlen(visbuf));
2104076ad2f8SDag-Erling Smørgrav 		}
2105511b41d2SMark Murray 		++errs;
2106511b41d2SMark Murray 		if (resp == 1)
2107511b41d2SMark Murray 			return (-1);
2108511b41d2SMark Murray 		exit(1);
2109511b41d2SMark Murray 	}
2110511b41d2SMark Murray 	/* NOTREACHED */
2111511b41d2SMark Murray }
2112511b41d2SMark Murray 
2113511b41d2SMark Murray void
2114ae1f160dSDag-Erling Smørgrav usage(void)
2115511b41d2SMark Murray {
2116ae1f160dSDag-Erling Smørgrav 	(void) fprintf(stderr,
211719261079SEd Maste 	    "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n"
2118f374ba41SEd Maste 	    "           [-i identity_file] [-J destination] [-l limit] [-o ssh_option]\n"
2119f374ba41SEd Maste 	    "           [-P port] [-S program] [-X sftp_option] source ... target\n");
2120511b41d2SMark Murray 	exit(1);
2121511b41d2SMark Murray }
2122511b41d2SMark Murray 
2123511b41d2SMark Murray void
2124511b41d2SMark Murray run_err(const char *fmt,...)
2125511b41d2SMark Murray {
2126511b41d2SMark Murray 	static FILE *fp;
2127511b41d2SMark Murray 	va_list ap;
2128511b41d2SMark Murray 
2129511b41d2SMark Murray 	++errs;
2130333ee039SDag-Erling Smørgrav 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
2131511b41d2SMark Murray 		(void) fprintf(fp, "%c", 0x01);
2132511b41d2SMark Murray 		(void) fprintf(fp, "scp: ");
2133ae1f160dSDag-Erling Smørgrav 		va_start(ap, fmt);
2134511b41d2SMark Murray 		(void) vfprintf(fp, fmt, ap);
2135ae1f160dSDag-Erling Smørgrav 		va_end(ap);
2136511b41d2SMark Murray 		(void) fprintf(fp, "\n");
2137511b41d2SMark Murray 		(void) fflush(fp);
2138333ee039SDag-Erling Smørgrav 	}
2139511b41d2SMark Murray 
2140511b41d2SMark Murray 	if (!iamremote) {
2141ae1f160dSDag-Erling Smørgrav 		va_start(ap, fmt);
2142076ad2f8SDag-Erling Smørgrav 		vfmprintf(stderr, fmt, ap);
2143ae1f160dSDag-Erling Smørgrav 		va_end(ap);
2144511b41d2SMark Murray 		fprintf(stderr, "\n");
2145511b41d2SMark Murray 	}
2146511b41d2SMark Murray }
2147511b41d2SMark Murray 
214819261079SEd Maste /*
214919261079SEd Maste  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
215019261079SEd Maste  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
215119261079SEd Maste  * any active error at the end of the transfer.
215219261079SEd Maste  */
215319261079SEd Maste int
215419261079SEd Maste note_err(const char *fmt, ...)
215519261079SEd Maste {
215619261079SEd Maste 	static char *emsg;
215719261079SEd Maste 	va_list ap;
215819261079SEd Maste 
215919261079SEd Maste 	/* Replay any previously-noted error */
216019261079SEd Maste 	if (fmt == NULL) {
216119261079SEd Maste 		if (emsg == NULL)
216219261079SEd Maste 			return 0;
216319261079SEd Maste 		run_err("%s", emsg);
216419261079SEd Maste 		free(emsg);
216519261079SEd Maste 		emsg = NULL;
216619261079SEd Maste 		return -1;
216719261079SEd Maste 	}
216819261079SEd Maste 
216919261079SEd Maste 	errs++;
217019261079SEd Maste 	/* Prefer first-noted error */
217119261079SEd Maste 	if (emsg != NULL)
217219261079SEd Maste 		return -1;
217319261079SEd Maste 
217419261079SEd Maste 	va_start(ap, fmt);
217519261079SEd Maste 	vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
217619261079SEd Maste 	va_end(ap);
217719261079SEd Maste 	return -1;
217819261079SEd Maste }
217919261079SEd Maste 
2180511b41d2SMark Murray void
2181cf2b5f3bSDag-Erling Smørgrav verifydir(char *cp)
2182511b41d2SMark Murray {
2183511b41d2SMark Murray 	struct stat stb;
2184511b41d2SMark Murray 
2185511b41d2SMark Murray 	if (!stat(cp, &stb)) {
2186511b41d2SMark Murray 		if (S_ISDIR(stb.st_mode))
2187511b41d2SMark Murray 			return;
2188511b41d2SMark Murray 		errno = ENOTDIR;
2189511b41d2SMark Murray 	}
2190511b41d2SMark Murray 	run_err("%s: %s", cp, strerror(errno));
2191d4ecd108SDag-Erling Smørgrav 	killchild(0);
2192511b41d2SMark Murray }
2193511b41d2SMark Murray 
2194511b41d2SMark Murray int
2195cf2b5f3bSDag-Erling Smørgrav okname(char *cp0)
2196511b41d2SMark Murray {
2197511b41d2SMark Murray 	int c;
2198511b41d2SMark Murray 	char *cp;
2199511b41d2SMark Murray 
2200511b41d2SMark Murray 	cp = cp0;
2201511b41d2SMark Murray 	do {
2202ae1f160dSDag-Erling Smørgrav 		c = (int)*cp;
2203511b41d2SMark Murray 		if (c & 0200)
2204511b41d2SMark Murray 			goto bad;
2205f7167e0eSDag-Erling Smørgrav 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
2206e73e9afaSDag-Erling Smørgrav 			switch (c) {
2207e73e9afaSDag-Erling Smørgrav 			case '\'':
2208e73e9afaSDag-Erling Smørgrav 			case '"':
2209e73e9afaSDag-Erling Smørgrav 			case '`':
2210e73e9afaSDag-Erling Smørgrav 			case ' ':
2211e73e9afaSDag-Erling Smørgrav 			case '#':
2212511b41d2SMark Murray 				goto bad;
2213e73e9afaSDag-Erling Smørgrav 			default:
2214e73e9afaSDag-Erling Smørgrav 				break;
2215e73e9afaSDag-Erling Smørgrav 			}
2216e73e9afaSDag-Erling Smørgrav 		}
2217511b41d2SMark Murray 	} while (*++cp);
2218511b41d2SMark Murray 	return (1);
2219511b41d2SMark Murray 
2220076ad2f8SDag-Erling Smørgrav bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
2221511b41d2SMark Murray 	return (0);
2222511b41d2SMark Murray }
2223511b41d2SMark Murray 
2224511b41d2SMark Murray BUF *
2225cf2b5f3bSDag-Erling Smørgrav allocbuf(BUF *bp, int fd, int blksize)
2226511b41d2SMark Murray {
2227511b41d2SMark Murray 	size_t size;
222883d2307dSDag-Erling Smørgrav #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
2229511b41d2SMark Murray 	struct stat stb;
2230511b41d2SMark Murray 
223119261079SEd Maste 	if (fstat(fd, &stb) == -1) {
2232511b41d2SMark Murray 		run_err("fstat: %s", strerror(errno));
2233511b41d2SMark Murray 		return (0);
2234511b41d2SMark Murray 	}
2235ca86bcf2SDag-Erling Smørgrav 	size = ROUNDUP(stb.st_blksize, blksize);
2236e73e9afaSDag-Erling Smørgrav 	if (size == 0)
2237e73e9afaSDag-Erling Smørgrav 		size = blksize;
223883d2307dSDag-Erling Smørgrav #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
223983d2307dSDag-Erling Smørgrav 	size = blksize;
224083d2307dSDag-Erling Smørgrav #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
2241511b41d2SMark Murray 	if (bp->cnt >= size)
2242511b41d2SMark Murray 		return (bp);
22434f52dfbbSDag-Erling Smørgrav 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
2244511b41d2SMark Murray 	bp->cnt = size;
2245511b41d2SMark Murray 	return (bp);
2246511b41d2SMark Murray }
2247511b41d2SMark Murray 
2248511b41d2SMark Murray void
2249cf2b5f3bSDag-Erling Smørgrav lostconn(int signo)
2250511b41d2SMark Murray {
2251511b41d2SMark Murray 	if (!iamremote)
2252e4a9863fSDag-Erling Smørgrav 		(void)write(STDERR_FILENO, "lost connection\n", 16);
2253ae1f160dSDag-Erling Smørgrav 	if (signo)
2254ae1f160dSDag-Erling Smørgrav 		_exit(1);
2255ae1f160dSDag-Erling Smørgrav 	else
2256511b41d2SMark Murray 		exit(1);
2257511b41d2SMark Murray }
225819261079SEd Maste 
225919261079SEd Maste void
226019261079SEd Maste cleanup_exit(int i)
226119261079SEd Maste {
226219261079SEd Maste 	if (remin > 0)
226319261079SEd Maste 		close(remin);
226419261079SEd Maste 	if (remout > 0)
226519261079SEd Maste 		close(remout);
226619261079SEd Maste 	if (remin2 > 0)
226719261079SEd Maste 		close(remin2);
226819261079SEd Maste 	if (remout2 > 0)
226919261079SEd Maste 		close(remout2);
227019261079SEd Maste 	if (do_cmd_pid > 0)
2271535af610SEd Maste 		(void)waitpid(do_cmd_pid, NULL, 0);
227219261079SEd Maste 	if (do_cmd_pid2 > 0)
2273535af610SEd Maste 		(void)waitpid(do_cmd_pid2, NULL, 0);
227419261079SEd Maste 	exit(i);
227519261079SEd Maste }
2276