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