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