Home | History | Annotate | Line # | Download | only in dist
scp.c revision 1.28
      1  1.27  christos /*	$NetBSD: scp.c,v 1.28 2020/12/04 18:42:50 christos Exp $	*/
      2  1.28  christos /* $OpenBSD: scp.c,v 1.212 2020/08/03 02:43:41 djm Exp $ */
      3  1.28  christos 
      4   1.1  christos /*
      5   1.1  christos  * scp - secure remote copy.  This is basically patched BSD rcp which
      6   1.1  christos  * uses ssh to do the data transfer (instead of using rcmd).
      7   1.1  christos  *
      8   1.1  christos  * NOTE: This version should NOT be suid root.  (This uses ssh to
      9   1.1  christos  * do the transfer and ssh has the necessary privileges.)
     10   1.1  christos  *
     11   1.1  christos  * 1995 Timo Rinne <tri (at) iki.fi>, Tatu Ylonen <ylo (at) cs.hut.fi>
     12   1.1  christos  *
     13   1.1  christos  * As far as I am concerned, the code I have written for this software
     14   1.1  christos  * can be used freely for any purpose.  Any derived versions of this
     15   1.1  christos  * software must be clearly marked as such, and if the derived work is
     16   1.1  christos  * incompatible with the protocol description in the RFC file, it must be
     17   1.1  christos  * called by a name other than "ssh" or "Secure Shell".
     18   1.1  christos  */
     19   1.1  christos /*
     20   1.1  christos  * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
     21   1.1  christos  * Copyright (c) 1999 Aaron Campbell.  All rights reserved.
     22   1.1  christos  *
     23   1.1  christos  * Redistribution and use in source and binary forms, with or without
     24   1.1  christos  * modification, are permitted provided that the following conditions
     25   1.1  christos  * are met:
     26   1.1  christos  * 1. Redistributions of source code must retain the above copyright
     27   1.1  christos  *    notice, this list of conditions and the following disclaimer.
     28   1.1  christos  * 2. Redistributions in binary form must reproduce the above copyright
     29   1.1  christos  *    notice, this list of conditions and the following disclaimer in the
     30   1.1  christos  *    documentation and/or other materials provided with the distribution.
     31   1.1  christos  *
     32   1.1  christos  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     33   1.1  christos  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     34   1.1  christos  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     35   1.1  christos  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     36   1.1  christos  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     37   1.1  christos  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     38   1.1  christos  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     39   1.1  christos  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     40   1.1  christos  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     41   1.1  christos  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     42   1.1  christos  */
     43   1.1  christos 
     44   1.1  christos /*
     45   1.1  christos  * Parts from:
     46   1.1  christos  *
     47   1.1  christos  * Copyright (c) 1983, 1990, 1992, 1993, 1995
     48   1.1  christos  *	The Regents of the University of California.  All rights reserved.
     49   1.1  christos  *
     50   1.1  christos  * Redistribution and use in source and binary forms, with or without
     51   1.1  christos  * modification, are permitted provided that the following conditions
     52   1.1  christos  * are met:
     53   1.1  christos  * 1. Redistributions of source code must retain the above copyright
     54   1.1  christos  *    notice, this list of conditions and the following disclaimer.
     55   1.1  christos  * 2. Redistributions in binary form must reproduce the above copyright
     56   1.1  christos  *    notice, this list of conditions and the following disclaimer in the
     57   1.1  christos  *    documentation and/or other materials provided with the distribution.
     58   1.1  christos  * 3. Neither the name of the University nor the names of its contributors
     59   1.1  christos  *    may be used to endorse or promote products derived from this software
     60   1.1  christos  *    without specific prior written permission.
     61   1.1  christos  *
     62   1.1  christos  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     63   1.1  christos  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     64   1.1  christos  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     65   1.1  christos  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     66   1.1  christos  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     67   1.1  christos  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     68   1.1  christos  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     69   1.1  christos  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     70   1.1  christos  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     71   1.1  christos  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     72   1.1  christos  * SUCH DAMAGE.
     73   1.1  christos  *
     74   1.1  christos  */
     75   1.1  christos 
     76   1.2  christos #include "includes.h"
     77  1.27  christos __RCSID("$NetBSD: scp.c,v 1.28 2020/12/04 18:42:50 christos Exp $");
     78  1.15  christos 
     79  1.11  christos #include <sys/param.h>	/* roundup MAX */
     80   1.1  christos #include <sys/types.h>
     81   1.1  christos #include <sys/poll.h>
     82   1.1  christos #include <sys/wait.h>
     83   1.1  christos #include <sys/stat.h>
     84   1.1  christos #include <sys/time.h>
     85   1.1  christos #include <sys/uio.h>
     86   1.1  christos 
     87   1.1  christos #include <ctype.h>
     88   1.1  christos #include <dirent.h>
     89   1.1  christos #include <errno.h>
     90   1.1  christos #include <fcntl.h>
     91  1.23  christos #include <fnmatch.h>
     92  1.14  christos #include <locale.h>
     93   1.1  christos #include <pwd.h>
     94   1.1  christos #include <signal.h>
     95   1.1  christos #include <stdarg.h>
     96  1.17  christos #include <stdint.h>
     97   1.1  christos #include <stdio.h>
     98   1.1  christos #include <stdlib.h>
     99   1.1  christos #include <string.h>
    100   1.1  christos #include <time.h>
    101   1.1  christos #include <unistd.h>
    102  1.11  christos #include <limits.h>
    103   1.1  christos #include <vis.h>
    104   1.1  christos 
    105   1.1  christos #include "xmalloc.h"
    106  1.18  christos #include "ssh.h"
    107   1.1  christos #include "atomicio.h"
    108   1.1  christos #include "pathnames.h"
    109   1.1  christos #include "log.h"
    110   1.1  christos #include "misc.h"
    111   1.1  christos #include "progressmeter.h"
    112  1.14  christos #include "utf8.h"
    113   1.1  christos 
    114   1.1  christos #define COPY_BUFLEN	16384
    115   1.1  christos 
    116  1.18  christos int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout);
    117  1.18  christos int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout);
    118   1.1  christos 
    119   1.5  christos static char empty[] = "";
    120   1.1  christos 
    121   1.1  christos /* Struct for addargs */
    122   1.1  christos arglist args;
    123   1.5  christos arglist remote_remote_args;
    124   1.1  christos 
    125   1.1  christos /* Bandwidth limit */
    126   1.5  christos long long limit_kbps = 0;
    127   1.5  christos struct bwlimit bwlimit;
    128   1.1  christos 
    129   1.1  christos /* Name of current file being transferred. */
    130   1.1  christos char *curfile;
    131   1.1  christos 
    132   1.1  christos /* This is set to non-zero to enable verbose mode. */
    133   1.1  christos int verbose_mode = 0;
    134   1.1  christos 
    135   1.1  christos /* This is set to zero if the progressmeter is not desired. */
    136   1.1  christos int showprogress = 1;
    137   1.1  christos 
    138   1.5  christos /*
    139   1.5  christos  * This is set to non-zero if remote-remote copy should be piped
    140   1.5  christos  * through this process.
    141   1.5  christos  */
    142   1.5  christos int throughlocal = 0;
    143   1.5  christos 
    144  1.18  christos /* Non-standard port to use for the ssh connection or -1. */
    145  1.18  christos int sshport = -1;
    146  1.18  christos 
    147   1.1  christos /* This is the program to execute for the secured connection. ("ssh" or -S) */
    148   1.2  christos #ifdef RESCUEDIR
    149   1.5  christos const char *ssh_program = RESCUEDIR "/ssh";
    150   1.2  christos #else
    151   1.5  christos const char *ssh_program = _PATH_SSH_PROGRAM;
    152   1.2  christos #endif
    153   1.1  christos 
    154   1.1  christos /* This is used to store the pid of ssh_program */
    155   1.1  christos pid_t do_cmd_pid = -1;
    156   1.1  christos 
    157   1.6     joerg __dead static void
    158   1.1  christos killchild(int signo)
    159   1.1  christos {
    160   1.1  christos 	if (do_cmd_pid > 1) {
    161   1.1  christos 		kill(do_cmd_pid, signo ? signo : SIGTERM);
    162   1.1  christos 		waitpid(do_cmd_pid, NULL, 0);
    163   1.1  christos 	}
    164   1.1  christos 
    165   1.1  christos 	if (signo)
    166   1.1  christos 		_exit(1);
    167   1.1  christos 	exit(1);
    168   1.1  christos }
    169   1.1  christos 
    170   1.4      adam static void
    171   1.4      adam suspchild(int signo)
    172   1.4      adam {
    173   1.4      adam 	int status;
    174   1.4      adam 
    175   1.4      adam 	if (do_cmd_pid > 1) {
    176   1.4      adam 		kill(do_cmd_pid, signo);
    177   1.4      adam 		while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
    178   1.4      adam 		    errno == EINTR)
    179   1.4      adam 			;
    180   1.4      adam 		kill(getpid(), SIGSTOP);
    181   1.4      adam 	}
    182   1.4      adam }
    183   1.4      adam 
    184   1.1  christos static int
    185   1.1  christos do_local_cmd(arglist *a)
    186   1.1  christos {
    187   1.1  christos 	u_int i;
    188   1.1  christos 	int status;
    189   1.1  christos 	pid_t pid;
    190   1.1  christos 
    191   1.1  christos 	if (a->num == 0)
    192   1.1  christos 		fatal("do_local_cmd: no arguments");
    193   1.1  christos 
    194   1.1  christos 	if (verbose_mode) {
    195   1.1  christos 		fprintf(stderr, "Executing:");
    196   1.1  christos 		for (i = 0; i < a->num; i++)
    197  1.14  christos 			fmprintf(stderr, " %s", a->list[i]);
    198   1.1  christos 		fprintf(stderr, "\n");
    199   1.1  christos 	}
    200   1.1  christos 	if ((pid = fork()) == -1)
    201   1.1  christos 		fatal("do_local_cmd: fork: %s", strerror(errno));
    202   1.1  christos 
    203   1.1  christos 	if (pid == 0) {
    204   1.1  christos 		execvp(a->list[0], a->list);
    205   1.1  christos 		perror(a->list[0]);
    206   1.1  christos 		exit(1);
    207   1.1  christos 	}
    208   1.1  christos 
    209   1.1  christos 	do_cmd_pid = pid;
    210  1.25  christos 	ssh_signal(SIGTERM, killchild);
    211  1.25  christos 	ssh_signal(SIGINT, killchild);
    212  1.25  christos 	ssh_signal(SIGHUP, killchild);
    213   1.1  christos 
    214   1.1  christos 	while (waitpid(pid, &status, 0) == -1)
    215   1.1  christos 		if (errno != EINTR)
    216   1.1  christos 			fatal("do_local_cmd: waitpid: %s", strerror(errno));
    217   1.1  christos 
    218   1.1  christos 	do_cmd_pid = -1;
    219   1.1  christos 
    220   1.1  christos 	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
    221   1.1  christos 		return (-1);
    222   1.1  christos 
    223   1.1  christos 	return (0);
    224   1.1  christos }
    225   1.1  christos 
    226   1.1  christos /*
    227   1.1  christos  * This function executes the given command as the specified user on the
    228   1.1  christos  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
    229   1.1  christos  * assigns the input and output file descriptors on success.
    230   1.1  christos  */
    231   1.1  christos 
    232   1.1  christos int
    233  1.18  christos do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout)
    234   1.1  christos {
    235   1.1  christos 	int pin[2], pout[2], reserved[2];
    236   1.1  christos 
    237   1.1  christos 	if (verbose_mode)
    238  1.14  christos 		fmprintf(stderr,
    239   1.1  christos 		    "Executing: program %s host %s, user %s, command %s\n",
    240   1.1  christos 		    ssh_program, host,
    241   1.1  christos 		    remuser ? remuser : "(unspecified)", cmd);
    242   1.1  christos 
    243  1.18  christos 	if (port == -1)
    244  1.18  christos 		port = sshport;
    245  1.18  christos 
    246   1.1  christos 	/*
    247   1.1  christos 	 * Reserve two descriptors so that the real pipes won't get
    248   1.1  christos 	 * descriptors 0 and 1 because that will screw up dup2 below.
    249   1.1  christos 	 */
    250  1.24  christos 	if (pipe(reserved) == -1)
    251   1.1  christos 		fatal("pipe: %s", strerror(errno));
    252   1.1  christos 
    253   1.1  christos 	/* Create a socket pair for communicating with ssh. */
    254  1.24  christos 	if (pipe(pin) == -1)
    255   1.1  christos 		fatal("pipe: %s", strerror(errno));
    256  1.24  christos 	if (pipe(pout) == -1)
    257   1.1  christos 		fatal("pipe: %s", strerror(errno));
    258   1.1  christos 
    259   1.1  christos 	/* Free the reserved descriptors. */
    260   1.1  christos 	close(reserved[0]);
    261   1.1  christos 	close(reserved[1]);
    262   1.1  christos 
    263  1.25  christos 	ssh_signal(SIGTSTP, suspchild);
    264  1.25  christos 	ssh_signal(SIGTTIN, suspchild);
    265  1.25  christos 	ssh_signal(SIGTTOU, suspchild);
    266   1.4      adam 
    267   1.1  christos 	/* Fork a child to execute the command on the remote host using ssh. */
    268   1.1  christos 	do_cmd_pid = fork();
    269   1.1  christos 	if (do_cmd_pid == 0) {
    270   1.1  christos 		/* Child. */
    271   1.1  christos 		close(pin[1]);
    272   1.1  christos 		close(pout[0]);
    273   1.1  christos 		dup2(pin[0], 0);
    274   1.1  christos 		dup2(pout[1], 1);
    275   1.1  christos 		close(pin[0]);
    276   1.1  christos 		close(pout[1]);
    277   1.1  christos 
    278   1.1  christos 		replacearg(&args, 0, "%s", ssh_program);
    279  1.18  christos 		if (port != -1) {
    280  1.18  christos 			addargs(&args, "-p");
    281  1.18  christos 			addargs(&args, "%d", port);
    282  1.18  christos 		}
    283   1.4      adam 		if (remuser != NULL) {
    284   1.4      adam 			addargs(&args, "-l");
    285   1.4      adam 			addargs(&args, "%s", remuser);
    286   1.4      adam 		}
    287   1.4      adam 		addargs(&args, "--");
    288   1.1  christos 		addargs(&args, "%s", host);
    289   1.1  christos 		addargs(&args, "%s", cmd);
    290   1.1  christos 
    291   1.1  christos 		execvp(ssh_program, args.list);
    292   1.1  christos 		perror(ssh_program);
    293   1.1  christos 		exit(1);
    294   1.1  christos 	} else if (do_cmd_pid == -1) {
    295   1.1  christos 		fatal("fork: %s", strerror(errno));
    296   1.1  christos 	}
    297   1.1  christos 	/* Parent.  Close the other side, and return the local side. */
    298   1.1  christos 	close(pin[0]);
    299   1.1  christos 	*fdout = pin[1];
    300   1.1  christos 	close(pout[1]);
    301   1.1  christos 	*fdin = pout[0];
    302  1.25  christos 	ssh_signal(SIGTERM, killchild);
    303  1.25  christos 	ssh_signal(SIGINT, killchild);
    304  1.25  christos 	ssh_signal(SIGHUP, killchild);
    305   1.1  christos 	return 0;
    306   1.1  christos }
    307   1.1  christos 
    308   1.5  christos /*
    309  1.20  christos  * This function executes a command similar to do_cmd(), but expects the
    310   1.5  christos  * input and output descriptors to be setup by a previous call to do_cmd().
    311   1.5  christos  * This way the input and output of two commands can be connected.
    312   1.5  christos  */
    313   1.5  christos int
    314  1.18  christos do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout)
    315   1.5  christos {
    316   1.5  christos 	pid_t pid;
    317   1.5  christos 	int status;
    318   1.5  christos 
    319   1.5  christos 	if (verbose_mode)
    320  1.14  christos 		fmprintf(stderr,
    321   1.5  christos 		    "Executing: 2nd program %s host %s, user %s, command %s\n",
    322   1.5  christos 		    ssh_program, host,
    323   1.5  christos 		    remuser ? remuser : "(unspecified)", cmd);
    324   1.5  christos 
    325  1.18  christos 	if (port == -1)
    326  1.18  christos 		port = sshport;
    327  1.18  christos 
    328   1.5  christos 	/* Fork a child to execute the command on the remote host using ssh. */
    329   1.5  christos 	pid = fork();
    330   1.5  christos 	if (pid == 0) {
    331   1.5  christos 		dup2(fdin, 0);
    332   1.5  christos 		dup2(fdout, 1);
    333   1.5  christos 
    334   1.5  christos 		replacearg(&args, 0, "%s", ssh_program);
    335  1.18  christos 		if (port != -1) {
    336  1.18  christos 			addargs(&args, "-p");
    337  1.18  christos 			addargs(&args, "%d", port);
    338  1.18  christos 		}
    339   1.5  christos 		if (remuser != NULL) {
    340   1.5  christos 			addargs(&args, "-l");
    341   1.5  christos 			addargs(&args, "%s", remuser);
    342   1.5  christos 		}
    343  1.26  christos 		addargs(&args, "-oBatchMode=yes");
    344   1.5  christos 		addargs(&args, "--");
    345   1.5  christos 		addargs(&args, "%s", host);
    346   1.5  christos 		addargs(&args, "%s", cmd);
    347   1.5  christos 
    348   1.5  christos 		execvp(ssh_program, args.list);
    349   1.5  christos 		perror(ssh_program);
    350   1.5  christos 		exit(1);
    351   1.5  christos 	} else if (pid == -1) {
    352   1.5  christos 		fatal("fork: %s", strerror(errno));
    353   1.5  christos 	}
    354   1.5  christos 	while (waitpid(pid, &status, 0) == -1)
    355   1.5  christos 		if (errno != EINTR)
    356   1.5  christos 			fatal("do_cmd2: waitpid: %s", strerror(errno));
    357   1.5  christos 	return 0;
    358   1.5  christos }
    359   1.5  christos 
    360   1.1  christos typedef struct {
    361   1.1  christos 	size_t cnt;
    362   1.1  christos 	char *buf;
    363   1.1  christos } BUF;
    364   1.1  christos 
    365   1.1  christos BUF *allocbuf(BUF *, int, int);
    366   1.6     joerg __dead static void lostconn(int);
    367   1.1  christos int okname(char *);
    368  1.28  christos void run_err(const char *,...)
    369  1.28  christos     __attribute__((__format__ (printf, 1, 2)))
    370  1.28  christos     __attribute__((__nonnull__ (1)));
    371  1.28  christos int note_err(const char *,...)
    372  1.28  christos     __attribute__((__format__ (printf, 1, 2)));
    373   1.1  christos void verifydir(char *);
    374   1.1  christos 
    375   1.1  christos struct passwd *pwd;
    376   1.1  christos uid_t userid;
    377   1.1  christos int errs, remin, remout;
    378  1.23  christos int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
    379   1.1  christos 
    380   1.1  christos #define	CMDNEEDS	64
    381   1.1  christos char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
    382   1.1  christos 
    383   1.1  christos int response(void);
    384   1.1  christos void rsource(char *, struct stat *);
    385  1.23  christos void sink(int, char *[], const char *);
    386   1.1  christos void source(int, char *[]);
    387   1.6     joerg static void tolocal(int, char *[]);
    388  1.18  christos static void toremote(int, char *[]);
    389   1.6     joerg __dead static void usage(void);
    390   1.1  christos 
    391   1.1  christos int
    392   1.1  christos main(int argc, char **argv)
    393   1.1  christos {
    394   1.1  christos 	int ch, fflag, tflag, status, n;
    395  1.18  christos 	char **newargv;
    396   1.5  christos 	const char *errstr;
    397   1.1  christos 	extern char *optarg;
    398   1.1  christos 	extern int optind;
    399   1.1  christos 
    400   1.1  christos 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
    401   1.1  christos 	sanitise_stdfd();
    402   1.1  christos 
    403  1.14  christos 	setlocale(LC_CTYPE, "");
    404  1.14  christos 
    405   1.1  christos 	/* Copy argv, because we modify it */
    406  1.15  christos 	newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
    407   1.1  christos 	for (n = 0; n < argc; n++)
    408   1.1  christos 		newargv[n] = xstrdup(argv[n]);
    409   1.1  christos 	argv = newargv;
    410   1.1  christos 
    411   1.1  christos 	memset(&args, '\0', sizeof(args));
    412   1.5  christos 	memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
    413   1.5  christos 	args.list = remote_remote_args.list = NULL;
    414   1.1  christos 	addargs(&args, "%s", ssh_program);
    415   1.1  christos 	addargs(&args, "-x");
    416   1.5  christos 	addargs(&args, "-oPermitLocalCommand=no");
    417   1.5  christos 	addargs(&args, "-oClearAllForwardings=yes");
    418  1.18  christos 	addargs(&args, "-oRemoteCommand=none");
    419  1.18  christos 	addargs(&args, "-oRequestTTY=no");
    420   1.1  christos 
    421  1.23  christos 	fflag = Tflag = tflag = 0;
    422  1.23  christos 	while ((ch = getopt(argc, argv,
    423  1.28  christos 	    "12346ABCTdfpqrtvF:J:P:S:c:i:l:o:")) != -1) {
    424   1.1  christos 		switch (ch) {
    425   1.1  christos 		/* User-visible flags. */
    426   1.1  christos 		case '1':
    427  1.17  christos 			fatal("SSH protocol v.1 is no longer supported");
    428  1.17  christos 			break;
    429   1.1  christos 		case '2':
    430  1.17  christos 			/* Ignored */
    431  1.17  christos 			break;
    432  1.28  christos 		case 'A':
    433   1.1  christos 		case '4':
    434   1.1  christos 		case '6':
    435   1.1  christos 		case 'C':
    436   1.1  christos 			addargs(&args, "-%c", ch);
    437   1.5  christos 			addargs(&remote_remote_args, "-%c", ch);
    438   1.5  christos 			break;
    439   1.5  christos 		case '3':
    440   1.5  christos 			throughlocal = 1;
    441   1.1  christos 			break;
    442   1.1  christos 		case 'o':
    443   1.1  christos 		case 'c':
    444   1.1  christos 		case 'i':
    445   1.1  christos 		case 'F':
    446  1.23  christos 		case 'J':
    447   1.5  christos 			addargs(&remote_remote_args, "-%c", ch);
    448   1.5  christos 			addargs(&remote_remote_args, "%s", optarg);
    449   1.4      adam 			addargs(&args, "-%c", ch);
    450   1.4      adam 			addargs(&args, "%s", optarg);
    451   1.1  christos 			break;
    452   1.1  christos 		case 'P':
    453  1.18  christos 			sshport = a2port(optarg);
    454  1.18  christos 			if (sshport <= 0)
    455  1.18  christos 				fatal("bad port \"%s\"\n", optarg);
    456   1.1  christos 			break;
    457   1.1  christos 		case 'B':
    458   1.5  christos 			addargs(&remote_remote_args, "-oBatchmode=yes");
    459   1.5  christos 			addargs(&args, "-oBatchmode=yes");
    460   1.1  christos 			break;
    461   1.1  christos 		case 'l':
    462   1.5  christos 			limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
    463   1.5  christos 			    &errstr);
    464   1.5  christos 			if (errstr != NULL)
    465   1.1  christos 				usage();
    466   1.5  christos 			limit_kbps *= 1024; /* kbps */
    467   1.5  christos 			bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
    468   1.1  christos 			break;
    469   1.1  christos 		case 'p':
    470   1.1  christos 			pflag = 1;
    471   1.1  christos 			break;
    472   1.1  christos 		case 'r':
    473   1.1  christos 			iamrecursive = 1;
    474   1.1  christos 			break;
    475   1.1  christos 		case 'S':
    476   1.1  christos 			ssh_program = xstrdup(optarg);
    477   1.1  christos 			break;
    478   1.1  christos 		case 'v':
    479   1.1  christos 			addargs(&args, "-v");
    480   1.5  christos 			addargs(&remote_remote_args, "-v");
    481   1.1  christos 			verbose_mode = 1;
    482   1.1  christos 			break;
    483   1.1  christos 		case 'q':
    484   1.1  christos 			addargs(&args, "-q");
    485   1.5  christos 			addargs(&remote_remote_args, "-q");
    486   1.1  christos 			showprogress = 0;
    487   1.1  christos 			break;
    488   1.1  christos 
    489   1.1  christos 		/* Server options. */
    490   1.1  christos 		case 'd':
    491   1.1  christos 			targetshouldbedirectory = 1;
    492   1.1  christos 			break;
    493   1.1  christos 		case 'f':	/* "from" */
    494   1.1  christos 			iamremote = 1;
    495   1.1  christos 			fflag = 1;
    496   1.1  christos 			break;
    497   1.1  christos 		case 't':	/* "to" */
    498   1.1  christos 			iamremote = 1;
    499   1.1  christos 			tflag = 1;
    500   1.1  christos 			break;
    501  1.23  christos 		case 'T':
    502  1.23  christos 			Tflag = 1;
    503  1.23  christos 			break;
    504   1.1  christos 		default:
    505   1.1  christos 			usage();
    506   1.1  christos 		}
    507  1.23  christos 	}
    508   1.1  christos 	argc -= optind;
    509   1.1  christos 	argv += optind;
    510   1.1  christos 
    511  1.28  christos 	/* Do this last because we want the user to be able to override it */
    512  1.28  christos 	addargs(&args, "-oForwardAgent=no");
    513  1.28  christos 
    514   1.1  christos 	if ((pwd = getpwuid(userid = getuid())) == NULL)
    515   1.1  christos 		fatal("unknown user %u", (u_int) userid);
    516   1.1  christos 
    517   1.1  christos 	if (!isatty(STDOUT_FILENO))
    518   1.1  christos 		showprogress = 0;
    519   1.1  christos 
    520  1.13  christos 	if (pflag) {
    521  1.13  christos 		/* Cannot pledge: -p allows setuid/setgid files... */
    522  1.13  christos 	} else {
    523  1.13  christos #ifdef __OpenBSD__
    524  1.13  christos 		if (pledge("stdio rpath wpath cpath fattr tty proc exec",
    525  1.13  christos 		    NULL) == -1) {
    526  1.13  christos 			perror("pledge");
    527  1.13  christos 			exit(1);
    528  1.13  christos 		}
    529  1.13  christos #endif
    530  1.13  christos 	}
    531  1.13  christos 
    532   1.1  christos 	remin = STDIN_FILENO;
    533   1.1  christos 	remout = STDOUT_FILENO;
    534   1.1  christos 
    535   1.1  christos 	if (fflag) {
    536   1.1  christos 		/* Follow "protocol", send data. */
    537   1.1  christos 		(void) response();
    538   1.1  christos 		source(argc, argv);
    539   1.1  christos 		exit(errs != 0);
    540   1.1  christos 	}
    541   1.1  christos 	if (tflag) {
    542   1.1  christos 		/* Receive data. */
    543  1.23  christos 		sink(argc, argv, NULL);
    544   1.1  christos 		exit(errs != 0);
    545   1.1  christos 	}
    546   1.1  christos 	if (argc < 2)
    547   1.1  christos 		usage();
    548   1.1  christos 	if (argc > 2)
    549   1.1  christos 		targetshouldbedirectory = 1;
    550   1.1  christos 
    551   1.1  christos 	remin = remout = -1;
    552   1.1  christos 	do_cmd_pid = -1;
    553   1.1  christos 	/* Command to be executed on remote system using "ssh". */
    554   1.1  christos 	(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
    555   1.1  christos 	    verbose_mode ? " -v" : "",
    556   1.1  christos 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
    557   1.1  christos 	    targetshouldbedirectory ? " -d" : "");
    558   1.1  christos 
    559  1.25  christos 	(void) ssh_signal(SIGPIPE, lostconn);
    560   1.1  christos 
    561  1.18  christos 	if (colon(argv[argc - 1]))	/* Dest is remote host. */
    562  1.18  christos 		toremote(argc, argv);
    563   1.1  christos 	else {
    564   1.1  christos 		if (targetshouldbedirectory)
    565   1.1  christos 			verifydir(argv[argc - 1]);
    566   1.1  christos 		tolocal(argc, argv);	/* Dest is local host. */
    567   1.1  christos 	}
    568   1.1  christos 	/*
    569   1.1  christos 	 * Finally check the exit status of the ssh process, if one was forked
    570   1.1  christos 	 * and no error has occurred yet
    571   1.1  christos 	 */
    572   1.1  christos 	if (do_cmd_pid != -1 && errs == 0) {
    573   1.1  christos 		if (remin != -1)
    574   1.1  christos 		    (void) close(remin);
    575   1.1  christos 		if (remout != -1)
    576   1.1  christos 		    (void) close(remout);
    577   1.1  christos 		if (waitpid(do_cmd_pid, &status, 0) == -1)
    578   1.1  christos 			errs = 1;
    579   1.1  christos 		else {
    580   1.1  christos 			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
    581   1.1  christos 				errs = 1;
    582   1.1  christos 		}
    583   1.1  christos 	}
    584   1.1  christos 	exit(errs != 0);
    585   1.1  christos }
    586   1.1  christos 
    587   1.5  christos /* Callback from atomicio6 to update progress meter and limit bandwidth */
    588   1.5  christos static int
    589   1.5  christos scpio(void *_cnt, size_t s)
    590   1.1  christos {
    591   1.5  christos 	off_t *cnt = (off_t *)_cnt;
    592   1.5  christos 
    593   1.5  christos 	*cnt += s;
    594  1.23  christos 	refresh_progress_meter(0);
    595   1.5  christos 	if (limit_kbps > 0)
    596   1.5  christos 		bandwidth_limit(&bwlimit, s);
    597   1.5  christos 	return 0;
    598   1.1  christos }
    599   1.1  christos 
    600   1.9  christos static int
    601   1.9  christos do_times(int fd, int verb, const struct stat *sb)
    602   1.9  christos {
    603   1.9  christos 	/* strlen(2^64) == 20; strlen(10^6) == 7 */
    604   1.9  christos 	char buf[(20 + 7 + 2) * 2 + 2];
    605   1.9  christos 
    606   1.9  christos 	(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
    607   1.9  christos 	    (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
    608   1.9  christos 	    (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
    609   1.9  christos 	if (verb) {
    610   1.9  christos 		fprintf(stderr, "File mtime %lld atime %lld\n",
    611   1.9  christos 		    (long long)sb->st_mtime, (long long)sb->st_atime);
    612   1.9  christos 		fprintf(stderr, "Sending file timestamps: %s", buf);
    613   1.9  christos 	}
    614   1.9  christos 	(void) atomicio(vwrite, fd, buf, strlen(buf));
    615   1.9  christos 	return (response());
    616   1.9  christos }
    617   1.9  christos 
    618  1.18  christos static int
    619  1.18  christos parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
    620  1.19  christos      const char **pathp)
    621  1.18  christos {
    622  1.18  christos 	int r;
    623  1.18  christos 
    624  1.18  christos 	r = parse_uri("scp", uri, userp, hostp, portp, pathp);
    625  1.18  christos 	if (r == 0 && *pathp == NULL)
    626  1.18  christos 		*pathp = xstrdup(".");
    627  1.18  christos 	return r;
    628  1.18  christos }
    629  1.18  christos 
    630  1.23  christos /* Appends a string to an array; returns 0 on success, -1 on alloc failure */
    631  1.23  christos static int
    632  1.23  christos append(char *cp, char ***ap, size_t *np)
    633  1.23  christos {
    634  1.23  christos 	char **tmp;
    635  1.23  christos 
    636  1.23  christos 	if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
    637  1.23  christos 		return -1;
    638  1.23  christos 	tmp[(*np)] = cp;
    639  1.23  christos 	(*np)++;
    640  1.23  christos 	*ap = tmp;
    641  1.23  christos 	return 0;
    642  1.23  christos }
    643  1.23  christos 
    644  1.23  christos /*
    645  1.23  christos  * Finds the start and end of the first brace pair in the pattern.
    646  1.23  christos  * returns 0 on success or -1 for invalid patterns.
    647  1.23  christos  */
    648  1.23  christos static int
    649  1.23  christos find_brace(const char *pattern, int *startp, int *endp)
    650  1.23  christos {
    651  1.23  christos 	int i;
    652  1.23  christos 	int in_bracket, brace_level;
    653  1.23  christos 
    654  1.23  christos 	*startp = *endp = -1;
    655  1.23  christos 	in_bracket = brace_level = 0;
    656  1.23  christos 	for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
    657  1.23  christos 		switch (pattern[i]) {
    658  1.23  christos 		case '\\':
    659  1.23  christos 			/* skip next character */
    660  1.23  christos 			if (pattern[i + 1] != '\0')
    661  1.23  christos 				i++;
    662  1.23  christos 			break;
    663  1.23  christos 		case '[':
    664  1.23  christos 			in_bracket = 1;
    665  1.23  christos 			break;
    666  1.23  christos 		case ']':
    667  1.23  christos 			in_bracket = 0;
    668  1.23  christos 			break;
    669  1.23  christos 		case '{':
    670  1.23  christos 			if (in_bracket)
    671  1.23  christos 				break;
    672  1.23  christos 			if (pattern[i + 1] == '}') {
    673  1.23  christos 				/* Protect a single {}, for find(1), like csh */
    674  1.23  christos 				i++; /* skip */
    675  1.23  christos 				break;
    676  1.23  christos 			}
    677  1.23  christos 			if (*startp == -1)
    678  1.23  christos 				*startp = i;
    679  1.23  christos 			brace_level++;
    680  1.23  christos 			break;
    681  1.23  christos 		case '}':
    682  1.23  christos 			if (in_bracket)
    683  1.23  christos 				break;
    684  1.23  christos 			if (*startp < 0) {
    685  1.23  christos 				/* Unbalanced brace */
    686  1.23  christos 				return -1;
    687  1.23  christos 			}
    688  1.23  christos 			if (--brace_level <= 0)
    689  1.23  christos 				*endp = i;
    690  1.23  christos 			break;
    691  1.23  christos 		}
    692  1.23  christos 	}
    693  1.23  christos 	/* unbalanced brackets/braces */
    694  1.23  christos 	if (*endp < 0 && (*startp >= 0 || in_bracket))
    695  1.23  christos 		return -1;
    696  1.23  christos 	return 0;
    697  1.23  christos }
    698  1.23  christos 
    699  1.23  christos /*
    700  1.23  christos  * Assembles and records a successfully-expanded pattern, returns -1 on
    701  1.23  christos  * alloc failure.
    702  1.23  christos  */
    703  1.23  christos static int
    704  1.23  christos emit_expansion(const char *pattern, int brace_start, int brace_end,
    705  1.23  christos     int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
    706  1.23  christos {
    707  1.23  christos 	char *cp;
    708  1.23  christos 	int o = 0, tail_len = strlen(pattern + brace_end + 1);
    709  1.23  christos 
    710  1.23  christos 	if ((cp = malloc(brace_start + (sel_end - sel_start) +
    711  1.23  christos 	    tail_len + 1)) == NULL)
    712  1.23  christos 		return -1;
    713  1.23  christos 
    714  1.23  christos 	/* Pattern before initial brace */
    715  1.23  christos 	if (brace_start > 0) {
    716  1.23  christos 		memcpy(cp, pattern, brace_start);
    717  1.23  christos 		o = brace_start;
    718  1.23  christos 	}
    719  1.23  christos 	/* Current braced selection */
    720  1.23  christos 	if (sel_end - sel_start > 0) {
    721  1.23  christos 		memcpy(cp + o, pattern + sel_start,
    722  1.23  christos 		    sel_end - sel_start);
    723  1.23  christos 		o += sel_end - sel_start;
    724  1.23  christos 	}
    725  1.23  christos 	/* Remainder of pattern after closing brace */
    726  1.23  christos 	if (tail_len > 0) {
    727  1.23  christos 		memcpy(cp + o, pattern + brace_end + 1, tail_len);
    728  1.23  christos 		o += tail_len;
    729  1.23  christos 	}
    730  1.23  christos 	cp[o] = '\0';
    731  1.23  christos 	if (append(cp, patternsp, npatternsp) != 0) {
    732  1.23  christos 		free(cp);
    733  1.23  christos 		return -1;
    734  1.23  christos 	}
    735  1.23  christos 	return 0;
    736  1.23  christos }
    737  1.23  christos 
    738  1.23  christos /*
    739  1.23  christos  * Expand the first encountered brace in pattern, appending the expanded
    740  1.23  christos  * patterns it yielded to the *patternsp array.
    741  1.23  christos  *
    742  1.23  christos  * Returns 0 on success or -1 on allocation failure.
    743  1.23  christos  *
    744  1.23  christos  * Signals whether expansion was performed via *expanded and whether
    745  1.23  christos  * pattern was invalid via *invalid.
    746  1.23  christos  */
    747  1.23  christos static int
    748  1.23  christos brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
    749  1.23  christos     int *expanded, int *invalid)
    750  1.23  christos {
    751  1.23  christos 	int i;
    752  1.23  christos 	int in_bracket, brace_start, brace_end, brace_level;
    753  1.23  christos 	int sel_start, sel_end;
    754  1.23  christos 
    755  1.23  christos 	*invalid = *expanded = 0;
    756  1.23  christos 
    757  1.23  christos 	if (find_brace(pattern, &brace_start, &brace_end) != 0) {
    758  1.23  christos 		*invalid = 1;
    759  1.23  christos 		return 0;
    760  1.23  christos 	} else if (brace_start == -1)
    761  1.23  christos 		return 0;
    762  1.23  christos 
    763  1.23  christos 	in_bracket = brace_level = 0;
    764  1.23  christos 	for (i = sel_start = brace_start + 1; i < brace_end; i++) {
    765  1.23  christos 		switch (pattern[i]) {
    766  1.23  christos 		case '{':
    767  1.23  christos 			if (in_bracket)
    768  1.23  christos 				break;
    769  1.23  christos 			brace_level++;
    770  1.23  christos 			break;
    771  1.23  christos 		case '}':
    772  1.23  christos 			if (in_bracket)
    773  1.23  christos 				break;
    774  1.23  christos 			brace_level--;
    775  1.23  christos 			break;
    776  1.23  christos 		case '[':
    777  1.23  christos 			in_bracket = 1;
    778  1.23  christos 			break;
    779  1.23  christos 		case ']':
    780  1.23  christos 			in_bracket = 0;
    781  1.23  christos 			break;
    782  1.23  christos 		case '\\':
    783  1.23  christos 			if (i < brace_end - 1)
    784  1.23  christos 				i++; /* skip */
    785  1.23  christos 			break;
    786  1.23  christos 		}
    787  1.23  christos 		if (pattern[i] == ',' || i == brace_end - 1) {
    788  1.23  christos 			if (in_bracket || brace_level > 0)
    789  1.23  christos 				continue;
    790  1.23  christos 			/* End of a selection, emit an expanded pattern */
    791  1.23  christos 
    792  1.23  christos 			/* Adjust end index for last selection */
    793  1.23  christos 			sel_end = (i == brace_end - 1) ? brace_end : i;
    794  1.23  christos 			if (emit_expansion(pattern, brace_start, brace_end,
    795  1.23  christos 			    sel_start, sel_end, patternsp, npatternsp) != 0)
    796  1.23  christos 				return -1;
    797  1.23  christos 			/* move on to the next selection */
    798  1.23  christos 			sel_start = i + 1;
    799  1.23  christos 			continue;
    800  1.23  christos 		}
    801  1.23  christos 	}
    802  1.23  christos 	if (in_bracket || brace_level > 0) {
    803  1.23  christos 		*invalid = 1;
    804  1.23  christos 		return 0;
    805  1.23  christos 	}
    806  1.23  christos 	/* success */
    807  1.23  christos 	*expanded = 1;
    808  1.23  christos 	return 0;
    809  1.23  christos }
    810  1.23  christos 
    811  1.23  christos /* Expand braces from pattern. Returns 0 on success, -1 on failure */
    812  1.23  christos static int
    813  1.23  christos brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
    814  1.23  christos {
    815  1.23  christos 	char *cp, *cp2, **active = NULL, **done = NULL;
    816  1.23  christos 	size_t i, nactive = 0, ndone = 0;
    817  1.23  christos 	int ret = -1, invalid = 0, expanded = 0;
    818  1.23  christos 
    819  1.23  christos 	*patternsp = NULL;
    820  1.23  christos 	*npatternsp = 0;
    821  1.23  christos 
    822  1.23  christos 	/* Start the worklist with the original pattern */
    823  1.23  christos 	if ((cp = strdup(pattern)) == NULL)
    824  1.23  christos 		return -1;
    825  1.23  christos 	if (append(cp, &active, &nactive) != 0) {
    826  1.23  christos 		free(cp);
    827  1.23  christos 		return -1;
    828  1.23  christos 	}
    829  1.23  christos 	while (nactive > 0) {
    830  1.23  christos 		cp = active[nactive - 1];
    831  1.23  christos 		nactive--;
    832  1.23  christos 		if (brace_expand_one(cp, &active, &nactive,
    833  1.23  christos 		    &expanded, &invalid) == -1) {
    834  1.23  christos 			free(cp);
    835  1.23  christos 			goto fail;
    836  1.23  christos 		}
    837  1.23  christos 		if (invalid)
    838  1.23  christos 			fatal("%s: invalid brace pattern \"%s\"", __func__, cp);
    839  1.23  christos 		if (expanded) {
    840  1.23  christos 			/*
    841  1.23  christos 			 * Current entry expanded to new entries on the
    842  1.23  christos 			 * active list; discard the progenitor pattern.
    843  1.23  christos 			 */
    844  1.23  christos 			free(cp);
    845  1.23  christos 			continue;
    846  1.23  christos 		}
    847  1.23  christos 		/*
    848  1.23  christos 		 * Pattern did not expand; append the finename component to
    849  1.23  christos 		 * the completed list
    850  1.23  christos 		 */
    851  1.23  christos 		if ((cp2 = strrchr(cp, '/')) != NULL)
    852  1.23  christos 			*cp2++ = '\0';
    853  1.23  christos 		else
    854  1.23  christos 			cp2 = cp;
    855  1.23  christos 		if (append(xstrdup(cp2), &done, &ndone) != 0) {
    856  1.23  christos 			free(cp);
    857  1.23  christos 			goto fail;
    858  1.23  christos 		}
    859  1.23  christos 		free(cp);
    860  1.23  christos 	}
    861  1.23  christos 	/* success */
    862  1.23  christos 	*patternsp = done;
    863  1.23  christos 	*npatternsp = ndone;
    864  1.23  christos 	done = NULL;
    865  1.23  christos 	ndone = 0;
    866  1.23  christos 	ret = 0;
    867  1.23  christos  fail:
    868  1.23  christos 	for (i = 0; i < nactive; i++)
    869  1.23  christos 		free(active[i]);
    870  1.23  christos 	free(active);
    871  1.23  christos 	for (i = 0; i < ndone; i++)
    872  1.23  christos 		free(done[i]);
    873  1.23  christos 	free(done);
    874  1.23  christos 	return ret;
    875  1.23  christos }
    876  1.23  christos 
    877   1.9  christos void
    878  1.18  christos toremote(int argc, char **argv)
    879   1.1  christos {
    880  1.19  christos 	char *suser = NULL, *host = NULL;
    881  1.19  christos 	const char *src = NULL;
    882  1.19  christos 	char *bp, *tuser, *thost;
    883  1.19  christos 	const char *targ;
    884  1.18  christos 	int sport = -1, tport = -1;
    885   1.1  christos 	arglist alist;
    886  1.18  christos 	int i, r;
    887   1.5  christos 	u_int j;
    888   1.1  christos 
    889   1.1  christos 	memset(&alist, '\0', sizeof(alist));
    890   1.1  christos 	alist.list = NULL;
    891   1.1  christos 
    892  1.18  christos 	/* Parse target */
    893  1.18  christos 	r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
    894  1.18  christos 	if (r == -1) {
    895  1.18  christos 		fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
    896  1.18  christos 		++errs;
    897  1.18  christos 		goto out;
    898  1.18  christos 	}
    899  1.18  christos 	if (r != 0) {
    900  1.18  christos 		if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
    901  1.18  christos 		    &targ) == -1) {
    902  1.18  christos 			fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
    903  1.18  christos 			++errs;
    904  1.18  christos 			goto out;
    905  1.18  christos 		}
    906   1.1  christos 	}
    907   1.1  christos 	if (tuser != NULL && !okname(tuser)) {
    908  1.18  christos 		++errs;
    909  1.18  christos 		goto out;
    910   1.1  christos 	}
    911   1.1  christos 
    912  1.18  christos 	/* Parse source files */
    913   1.1  christos 	for (i = 0; i < argc - 1; i++) {
    914  1.18  christos 		free(suser);
    915  1.18  christos 		free(host);
    916  1.19  christos 		free(__UNCONST(src));
    917  1.18  christos 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
    918  1.18  christos 		if (r == -1) {
    919  1.18  christos 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
    920  1.18  christos 			++errs;
    921  1.18  christos 			continue;
    922  1.18  christos 		}
    923  1.18  christos 		if (r != 0) {
    924  1.18  christos 			parse_user_host_path(argv[i], &suser, &host, &src);
    925  1.18  christos 		}
    926  1.18  christos 		if (suser != NULL && !okname(suser)) {
    927  1.18  christos 			++errs;
    928  1.18  christos 			continue;
    929  1.18  christos 		}
    930  1.18  christos 		if (host && throughlocal) {	/* extended remote to remote */
    931   1.7  christos 			xasprintf(&bp, "%s -f %s%s", cmd,
    932   1.7  christos 			    *src == '-' ? "-- " : "", src);
    933  1.18  christos 			if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
    934   1.5  christos 				exit(1);
    935   1.9  christos 			free(bp);
    936   1.7  christos 			xasprintf(&bp, "%s -t %s%s", cmd,
    937   1.7  christos 			    *targ == '-' ? "-- " : "", targ);
    938  1.18  christos 			if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
    939   1.5  christos 				exit(1);
    940   1.9  christos 			free(bp);
    941   1.5  christos 			(void) close(remin);
    942   1.5  christos 			(void) close(remout);
    943   1.5  christos 			remin = remout = -1;
    944  1.18  christos 		} else if (host) {	/* standard remote to remote */
    945  1.18  christos 			if (tport != -1 && tport != SSH_DEFAULT_PORT) {
    946  1.18  christos 				/* This would require the remote support URIs */
    947  1.18  christos 				fatal("target port not supported with two "
    948  1.18  christos 				    "remote hosts without the -3 option");
    949  1.18  christos 			}
    950  1.18  christos 
    951   1.1  christos 			freeargs(&alist);
    952   1.1  christos 			addargs(&alist, "%s", ssh_program);
    953   1.1  christos 			addargs(&alist, "-x");
    954   1.5  christos 			addargs(&alist, "-oClearAllForwardings=yes");
    955   1.1  christos 			addargs(&alist, "-n");
    956   1.5  christos 			for (j = 0; j < remote_remote_args.num; j++) {
    957   1.5  christos 				addargs(&alist, "%s",
    958   1.5  christos 				    remote_remote_args.list[j]);
    959   1.5  christos 			}
    960  1.18  christos 			if (sport != -1) {
    961  1.18  christos 				addargs(&alist, "-p");
    962  1.18  christos 				addargs(&alist, "%d", sport);
    963  1.18  christos 			}
    964  1.18  christos 			if (suser) {
    965   1.1  christos 				addargs(&alist, "-l");
    966   1.1  christos 				addargs(&alist, "%s", suser);
    967   1.1  christos 			}
    968   1.4      adam 			addargs(&alist, "--");
    969   1.1  christos 			addargs(&alist, "%s", host);
    970   1.1  christos 			addargs(&alist, "%s", cmd);
    971   1.1  christos 			addargs(&alist, "%s", src);
    972   1.1  christos 			addargs(&alist, "%s%s%s:%s",
    973   1.1  christos 			    tuser ? tuser : "", tuser ? "@" : "",
    974   1.1  christos 			    thost, targ);
    975   1.1  christos 			if (do_local_cmd(&alist) != 0)
    976   1.1  christos 				errs = 1;
    977   1.1  christos 		} else {	/* local to remote */
    978   1.1  christos 			if (remin == -1) {
    979   1.7  christos 				xasprintf(&bp, "%s -t %s%s", cmd,
    980   1.7  christos 				    *targ == '-' ? "-- " : "", targ);
    981  1.18  christos 				if (do_cmd(thost, tuser, tport, bp, &remin,
    982   1.1  christos 				    &remout) < 0)
    983   1.1  christos 					exit(1);
    984   1.1  christos 				if (response() < 0)
    985   1.1  christos 					exit(1);
    986   1.9  christos 				free(bp);
    987   1.1  christos 			}
    988   1.1  christos 			source(1, argv + i);
    989   1.1  christos 		}
    990   1.1  christos 	}
    991  1.18  christos out:
    992  1.18  christos 	free(tuser);
    993  1.18  christos 	free(thost);
    994  1.19  christos 	free(__UNCONST(targ));
    995  1.18  christos 	free(suser);
    996  1.18  christos 	free(host);
    997  1.19  christos 	free(__UNCONST(src));
    998   1.1  christos }
    999   1.1  christos 
   1000   1.6     joerg static void
   1001   1.1  christos tolocal(int argc, char **argv)
   1002   1.1  christos {
   1003  1.19  christos 	char *bp, *host = NULL, *suser = NULL;
   1004  1.19  christos 	const char *src = NULL;
   1005   1.1  christos 	arglist alist;
   1006  1.18  christos 	int i, r, sport = -1;
   1007   1.1  christos 
   1008   1.1  christos 	memset(&alist, '\0', sizeof(alist));
   1009   1.1  christos 	alist.list = NULL;
   1010   1.1  christos 
   1011   1.1  christos 	for (i = 0; i < argc - 1; i++) {
   1012  1.18  christos 		free(suser);
   1013  1.18  christos 		free(host);
   1014  1.19  christos 		free(__UNCONST(src));
   1015  1.18  christos 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
   1016  1.18  christos 		if (r == -1) {
   1017  1.18  christos 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
   1018  1.18  christos 			++errs;
   1019  1.18  christos 			continue;
   1020  1.18  christos 		}
   1021  1.18  christos 		if (r != 0)
   1022  1.18  christos 			parse_user_host_path(argv[i], &suser, &host, &src);
   1023  1.18  christos 		if (suser != NULL && !okname(suser)) {
   1024  1.18  christos 			++errs;
   1025  1.18  christos 			continue;
   1026  1.18  christos 		}
   1027  1.18  christos 		if (!host) {	/* Local to local. */
   1028   1.1  christos 			freeargs(&alist);
   1029   1.1  christos 			addargs(&alist, "%s", _PATH_CP);
   1030   1.1  christos 			if (iamrecursive)
   1031   1.1  christos 				addargs(&alist, "-r");
   1032   1.1  christos 			if (pflag)
   1033   1.1  christos 				addargs(&alist, "-p");
   1034   1.4      adam 			addargs(&alist, "--");
   1035   1.1  christos 			addargs(&alist, "%s", argv[i]);
   1036   1.1  christos 			addargs(&alist, "%s", argv[argc-1]);
   1037   1.1  christos 			if (do_local_cmd(&alist))
   1038   1.1  christos 				++errs;
   1039   1.1  christos 			continue;
   1040   1.1  christos 		}
   1041  1.18  christos 		/* Remote to local. */
   1042   1.7  christos 		xasprintf(&bp, "%s -f %s%s",
   1043   1.7  christos 		    cmd, *src == '-' ? "-- " : "", src);
   1044  1.18  christos 		if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
   1045   1.9  christos 			free(bp);
   1046   1.1  christos 			++errs;
   1047   1.1  christos 			continue;
   1048   1.1  christos 		}
   1049   1.9  christos 		free(bp);
   1050  1.23  christos 		sink(1, argv + argc - 1, src);
   1051   1.1  christos 		(void) close(remin);
   1052   1.1  christos 		remin = remout = -1;
   1053   1.1  christos 	}
   1054  1.18  christos 	free(suser);
   1055  1.18  christos 	free(host);
   1056  1.19  christos 	free(__UNCONST(src));
   1057   1.1  christos }
   1058   1.1  christos 
   1059   1.1  christos void
   1060   1.1  christos source(int argc, char **argv)
   1061   1.1  christos {
   1062   1.1  christos 	struct stat stb;
   1063   1.1  christos 	static BUF buffer;
   1064   1.1  christos 	BUF *bp;
   1065   1.1  christos 	off_t i, statbytes;
   1066  1.10  christos 	size_t amt, nr;
   1067   1.1  christos 	int fd = -1, haderr, indx;
   1068  1.24  christos 	char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX];
   1069   1.1  christos 	int len;
   1070   1.1  christos 
   1071   1.1  christos 	for (indx = 0; indx < argc; ++indx) {
   1072   1.2  christos 		fd = -1;
   1073   1.1  christos 		name = argv[indx];
   1074   1.1  christos 		statbytes = 0;
   1075   1.1  christos 		len = strlen(name);
   1076   1.1  christos 		while (len > 1 && name[len-1] == '/')
   1077   1.1  christos 			name[--len] = '\0';
   1078  1.24  christos 		if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) == -1)
   1079   1.1  christos 			goto syserr;
   1080   1.1  christos 		if (strchr(name, '\n') != NULL) {
   1081   1.3  stacktic 			strvisx(encname, name, len, VIS_NL);
   1082   1.1  christos 			name = encname;
   1083   1.1  christos 		}
   1084  1.24  christos 		if (fstat(fd, &stb) == -1) {
   1085   1.1  christos syserr:			run_err("%s: %s", name, strerror(errno));
   1086   1.1  christos 			goto next;
   1087   1.1  christos 		}
   1088   1.1  christos 		if (stb.st_size < 0) {
   1089   1.1  christos 			run_err("%s: %s", name, "Negative file size");
   1090   1.1  christos 			goto next;
   1091   1.1  christos 		}
   1092   1.1  christos 		unset_nonblock(fd);
   1093   1.1  christos 		switch (stb.st_mode & S_IFMT) {
   1094   1.1  christos 		case S_IFREG:
   1095   1.1  christos 			break;
   1096   1.1  christos 		case S_IFDIR:
   1097   1.1  christos 			if (iamrecursive) {
   1098   1.1  christos 				rsource(name, &stb);
   1099   1.1  christos 				goto next;
   1100   1.1  christos 			}
   1101   1.1  christos 			/* FALLTHROUGH */
   1102   1.1  christos 		default:
   1103   1.1  christos 			run_err("%s: not a regular file", name);
   1104   1.1  christos 			goto next;
   1105   1.1  christos 		}
   1106   1.1  christos 		if ((last = strrchr(name, '/')) == NULL)
   1107   1.1  christos 			last = name;
   1108   1.1  christos 		else
   1109   1.1  christos 			++last;
   1110   1.1  christos 		curfile = last;
   1111   1.1  christos 		if (pflag) {
   1112   1.9  christos 			if (do_times(remout, verbose_mode, &stb) < 0)
   1113   1.1  christos 				goto next;
   1114   1.1  christos 		}
   1115   1.1  christos #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
   1116   1.1  christos 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
   1117   1.1  christos 		    (u_int) (stb.st_mode & FILEMODEMASK),
   1118   1.1  christos 		    (long long)stb.st_size, last);
   1119  1.14  christos 		if (verbose_mode)
   1120  1.14  christos 			fmprintf(stderr, "Sending file modes: %s", buf);
   1121   1.1  christos 		(void) atomicio(vwrite, remout, buf, strlen(buf));
   1122   1.1  christos 		if (response() < 0)
   1123   1.1  christos 			goto next;
   1124   1.1  christos 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
   1125   1.1  christos next:			if (fd != -1) {
   1126   1.1  christos 				(void) close(fd);
   1127   1.1  christos 				fd = -1;
   1128   1.1  christos 			}
   1129   1.1  christos 			continue;
   1130   1.1  christos 		}
   1131   1.1  christos 		if (showprogress)
   1132   1.1  christos 			start_progress_meter(curfile, stb.st_size, &statbytes);
   1133   1.1  christos 		set_nonblock(remout);
   1134   1.1  christos 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
   1135   1.1  christos 			amt = bp->cnt;
   1136   1.1  christos 			if (i + (off_t)amt > stb.st_size)
   1137   1.1  christos 				amt = stb.st_size - i;
   1138   1.1  christos 			if (!haderr) {
   1139  1.10  christos 				if ((nr = atomicio(read, fd,
   1140  1.10  christos 				    bp->buf, amt)) != amt) {
   1141   1.1  christos 					haderr = errno;
   1142  1.10  christos 					memset(bp->buf + nr, 0, amt - nr);
   1143  1.10  christos 				}
   1144   1.1  christos 			}
   1145   1.1  christos 			/* Keep writing after error to retain sync */
   1146   1.1  christos 			if (haderr) {
   1147   1.1  christos 				(void)atomicio(vwrite, remout, bp->buf, amt);
   1148  1.10  christos 				memset(bp->buf, 0, amt);
   1149   1.1  christos 				continue;
   1150   1.1  christos 			}
   1151   1.5  christos 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
   1152   1.1  christos 			    &statbytes) != amt)
   1153   1.1  christos 				haderr = errno;
   1154   1.1  christos 		}
   1155   1.1  christos 		unset_nonblock(remout);
   1156   1.1  christos 
   1157   1.1  christos 		if (fd != -1) {
   1158  1.24  christos 			if (close(fd) == -1 && !haderr)
   1159   1.1  christos 				haderr = errno;
   1160   1.1  christos 			fd = -1;
   1161   1.1  christos 		}
   1162   1.1  christos 		if (!haderr)
   1163   1.5  christos 			(void) atomicio(vwrite, remout, empty, 1);
   1164   1.1  christos 		else
   1165   1.1  christos 			run_err("%s: %s", name, strerror(haderr));
   1166   1.1  christos 		(void) response();
   1167  1.14  christos 		if (showprogress)
   1168  1.14  christos 			stop_progress_meter();
   1169   1.1  christos 	}
   1170   1.1  christos }
   1171   1.1  christos 
   1172   1.1  christos void
   1173   1.1  christos rsource(char *name, struct stat *statp)
   1174   1.1  christos {
   1175   1.1  christos 	DIR *dirp;
   1176   1.1  christos 	struct dirent *dp;
   1177  1.22       mrg 	char *last, *vect[1], path[PATH_MAX + 20];
   1178   1.1  christos 
   1179   1.1  christos 	if (!(dirp = opendir(name))) {
   1180   1.1  christos 		run_err("%s: %s", name, strerror(errno));
   1181   1.1  christos 		return;
   1182   1.1  christos 	}
   1183   1.1  christos 	last = strrchr(name, '/');
   1184  1.13  christos 	if (last == NULL)
   1185   1.1  christos 		last = name;
   1186   1.1  christos 	else
   1187   1.1  christos 		last++;
   1188   1.1  christos 	if (pflag) {
   1189   1.9  christos 		if (do_times(remout, verbose_mode, statp) < 0) {
   1190   1.1  christos 			closedir(dirp);
   1191   1.1  christos 			return;
   1192   1.1  christos 		}
   1193   1.1  christos 	}
   1194   1.1  christos 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
   1195   1.1  christos 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
   1196   1.1  christos 	if (verbose_mode)
   1197  1.14  christos 		fmprintf(stderr, "Entering directory: %s", path);
   1198   1.1  christos 	(void) atomicio(vwrite, remout, path, strlen(path));
   1199   1.1  christos 	if (response() < 0) {
   1200   1.1  christos 		closedir(dirp);
   1201   1.1  christos 		return;
   1202   1.1  christos 	}
   1203   1.1  christos 	while ((dp = readdir(dirp)) != NULL) {
   1204   1.1  christos 		if (dp->d_ino == 0)
   1205   1.1  christos 			continue;
   1206   1.1  christos 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
   1207   1.1  christos 			continue;
   1208   1.1  christos 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
   1209   1.1  christos 			run_err("%s/%s: name too long", name, dp->d_name);
   1210   1.1  christos 			continue;
   1211   1.1  christos 		}
   1212   1.1  christos 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
   1213   1.1  christos 		vect[0] = path;
   1214   1.1  christos 		source(1, vect);
   1215   1.1  christos 	}
   1216   1.1  christos 	(void) closedir(dirp);
   1217   1.5  christos 	(void) atomicio(vwrite, remout, __UNCONST("E\n"), 2);
   1218   1.1  christos 	(void) response();
   1219   1.1  christos }
   1220   1.1  christos 
   1221  1.17  christos #define TYPE_OVERFLOW(type, val) \
   1222  1.17  christos 	((sizeof(type) == 4 && (val) > INT32_MAX) || \
   1223  1.17  christos 	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
   1224  1.17  christos 	 (sizeof(type) != 4 && sizeof(type) != 8))
   1225  1.17  christos 
   1226   1.1  christos void
   1227  1.23  christos sink(int argc, char **argv, const char *src)
   1228   1.1  christos {
   1229   1.1  christos 	static BUF buffer;
   1230   1.1  christos 	struct stat stb;
   1231   1.1  christos 	BUF *bp;
   1232   1.1  christos 	off_t i;
   1233   1.1  christos 	size_t j, count;
   1234   1.1  christos 	int amt, exists, first, ofd;
   1235   1.1  christos 	mode_t mode, omode, mask;
   1236   1.1  christos 	off_t size, statbytes;
   1237   1.9  christos 	unsigned long long ull;
   1238  1.26  christos 	int setimes, targisdir, wrerr;
   1239  1.14  christos 	char ch, *cp, *np, *targ, *vect[1], buf[2048], visbuf[2048];
   1240   1.5  christos 	const char *why;
   1241  1.23  christos 	char **patterns = NULL;
   1242  1.23  christos 	size_t n, npatterns = 0;
   1243   1.1  christos 	struct timeval tv[2];
   1244   1.1  christos 
   1245   1.1  christos #define	atime	tv[0]
   1246   1.1  christos #define	mtime	tv[1]
   1247   1.1  christos #define	SCREWUP(str)	{ why = str; goto screwup; }
   1248   1.1  christos 
   1249  1.17  christos 	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
   1250  1.17  christos 		SCREWUP("Unexpected off_t/time_t size");
   1251  1.17  christos 
   1252   1.1  christos 	setimes = targisdir = 0;
   1253   1.1  christos 	mask = umask(0);
   1254   1.1  christos 	if (!pflag)
   1255   1.1  christos 		(void) umask(mask);
   1256   1.1  christos 	if (argc != 1) {
   1257   1.1  christos 		run_err("ambiguous target");
   1258   1.1  christos 		exit(1);
   1259   1.1  christos 	}
   1260   1.1  christos 	targ = *argv;
   1261   1.1  christos 	if (targetshouldbedirectory)
   1262   1.1  christos 		verifydir(targ);
   1263   1.1  christos 
   1264   1.5  christos 	(void) atomicio(vwrite, remout, empty, 1);
   1265   1.1  christos 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
   1266   1.1  christos 		targisdir = 1;
   1267  1.23  christos 	if (src != NULL && !iamrecursive && !Tflag) {
   1268  1.23  christos 		/*
   1269  1.23  christos 		 * Prepare to try to restrict incoming filenames to match
   1270  1.23  christos 		 * the requested destination file glob.
   1271  1.23  christos 		 */
   1272  1.23  christos 		if (brace_expand(src, &patterns, &npatterns) != 0)
   1273  1.23  christos 			fatal("%s: could not expand pattern", __func__);
   1274  1.23  christos 	}
   1275   1.1  christos 	for (first = 1;; first = 0) {
   1276   1.1  christos 		cp = buf;
   1277   1.1  christos 		if (atomicio(read, remin, cp, 1) != 1)
   1278  1.23  christos 			goto done;
   1279   1.1  christos 		if (*cp++ == '\n')
   1280   1.1  christos 			SCREWUP("unexpected <newline>");
   1281   1.1  christos 		do {
   1282   1.1  christos 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
   1283   1.1  christos 				SCREWUP("lost connection");
   1284   1.1  christos 			*cp++ = ch;
   1285   1.1  christos 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
   1286   1.1  christos 		*cp = 0;
   1287   1.1  christos 		if (verbose_mode)
   1288  1.14  christos 			fmprintf(stderr, "Sink: %s", buf);
   1289   1.1  christos 
   1290   1.1  christos 		if (buf[0] == '\01' || buf[0] == '\02') {
   1291  1.14  christos 			if (iamremote == 0) {
   1292  1.14  christos 				(void) snmprintf(visbuf, sizeof(visbuf),
   1293  1.14  christos 				    NULL, "%s", buf + 1);
   1294   1.1  christos 				(void) atomicio(vwrite, STDERR_FILENO,
   1295  1.14  christos 				    visbuf, strlen(visbuf));
   1296  1.14  christos 			}
   1297   1.1  christos 			if (buf[0] == '\02')
   1298   1.1  christos 				exit(1);
   1299   1.1  christos 			++errs;
   1300   1.1  christos 			continue;
   1301   1.1  christos 		}
   1302   1.1  christos 		if (buf[0] == 'E') {
   1303  1.23  christos 			(void) atomicio(vwrite, remout, __UNCONST(""), 1);
   1304  1.23  christos 			goto done;
   1305   1.1  christos 		}
   1306   1.1  christos 		if (ch == '\n')
   1307   1.1  christos 			*--cp = 0;
   1308   1.1  christos 
   1309   1.1  christos 		cp = buf;
   1310   1.1  christos 		if (*cp == 'T') {
   1311   1.1  christos 			setimes++;
   1312   1.1  christos 			cp++;
   1313   1.9  christos 			if (!isdigit((unsigned char)*cp))
   1314   1.9  christos 				SCREWUP("mtime.sec not present");
   1315   1.9  christos 			ull = strtoull(cp, &cp, 10);
   1316   1.1  christos 			if (!cp || *cp++ != ' ')
   1317   1.1  christos 				SCREWUP("mtime.sec not delimited");
   1318  1.17  christos 			if (TYPE_OVERFLOW(time_t, ull))
   1319   1.9  christos 				setimes = 0;	/* out of range */
   1320   1.9  christos 			mtime.tv_sec = ull;
   1321   1.1  christos 			mtime.tv_usec = strtol(cp, &cp, 10);
   1322   1.9  christos 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
   1323   1.9  christos 			    mtime.tv_usec > 999999)
   1324   1.1  christos 				SCREWUP("mtime.usec not delimited");
   1325   1.9  christos 			if (!isdigit((unsigned char)*cp))
   1326   1.9  christos 				SCREWUP("atime.sec not present");
   1327   1.9  christos 			ull = strtoull(cp, &cp, 10);
   1328   1.1  christos 			if (!cp || *cp++ != ' ')
   1329   1.1  christos 				SCREWUP("atime.sec not delimited");
   1330  1.17  christos 			if (TYPE_OVERFLOW(time_t, ull))
   1331   1.9  christos 				setimes = 0;	/* out of range */
   1332   1.9  christos 			atime.tv_sec = ull;
   1333   1.1  christos 			atime.tv_usec = strtol(cp, &cp, 10);
   1334   1.9  christos 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
   1335   1.9  christos 			    atime.tv_usec > 999999)
   1336   1.1  christos 				SCREWUP("atime.usec not delimited");
   1337   1.5  christos 			(void) atomicio(vwrite, remout, empty, 1);
   1338   1.1  christos 			continue;
   1339   1.1  christos 		}
   1340   1.1  christos 		if (*cp != 'C' && *cp != 'D') {
   1341   1.1  christos 			/*
   1342   1.1  christos 			 * Check for the case "rcp remote:foo\* local:bar".
   1343   1.1  christos 			 * In this case, the line "No match." can be returned
   1344   1.1  christos 			 * by the shell before the rcp command on the remote is
   1345   1.1  christos 			 * executed so the ^Aerror_message convention isn't
   1346   1.1  christos 			 * followed.
   1347   1.1  christos 			 */
   1348   1.1  christos 			if (first) {
   1349   1.1  christos 				run_err("%s", cp);
   1350   1.1  christos 				exit(1);
   1351   1.1  christos 			}
   1352   1.1  christos 			SCREWUP("expected control record");
   1353   1.1  christos 		}
   1354   1.1  christos 		mode = 0;
   1355   1.1  christos 		for (++cp; cp < buf + 5; cp++) {
   1356   1.1  christos 			if (*cp < '0' || *cp > '7')
   1357   1.1  christos 				SCREWUP("bad mode");
   1358   1.1  christos 			mode = (mode << 3) | (*cp - '0');
   1359   1.1  christos 		}
   1360  1.20  christos 		if (!pflag)
   1361  1.20  christos 			mode &= ~mask;
   1362   1.1  christos 		if (*cp++ != ' ')
   1363   1.1  christos 			SCREWUP("mode not delimited");
   1364   1.1  christos 
   1365  1.17  christos 		if (!isdigit((unsigned char)*cp))
   1366  1.17  christos 			SCREWUP("size not present");
   1367  1.17  christos 		ull = strtoull(cp, &cp, 10);
   1368  1.17  christos 		if (!cp || *cp++ != ' ')
   1369   1.1  christos 			SCREWUP("size not delimited");
   1370  1.17  christos 		if (TYPE_OVERFLOW(off_t, ull))
   1371  1.17  christos 			SCREWUP("size out of range");
   1372  1.17  christos 		size = (off_t)ull;
   1373  1.17  christos 
   1374  1.23  christos 		if (*cp == '\0' || strchr(cp, '/') != NULL ||
   1375  1.23  christos 		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
   1376   1.1  christos 			run_err("error: unexpected filename: %s", cp);
   1377   1.1  christos 			exit(1);
   1378   1.1  christos 		}
   1379  1.23  christos 		if (npatterns > 0) {
   1380  1.23  christos 			for (n = 0; n < npatterns; n++) {
   1381  1.23  christos 				if (fnmatch(patterns[n], cp, 0) == 0)
   1382  1.23  christos 					break;
   1383  1.23  christos 			}
   1384  1.23  christos 			if (n >= npatterns)
   1385  1.23  christos 				SCREWUP("filename does not match request");
   1386  1.23  christos 		}
   1387   1.1  christos 		if (targisdir) {
   1388   1.1  christos 			static char *namebuf;
   1389   1.1  christos 			static size_t cursize;
   1390   1.1  christos 			size_t need;
   1391   1.1  christos 
   1392   1.1  christos 			need = strlen(targ) + strlen(cp) + 250;
   1393   1.1  christos 			if (need > cursize) {
   1394   1.9  christos 				free(namebuf);
   1395   1.1  christos 				namebuf = xmalloc(need);
   1396   1.1  christos 				cursize = need;
   1397   1.1  christos 			}
   1398   1.1  christos 			(void) snprintf(namebuf, need, "%s%s%s", targ,
   1399   1.1  christos 			    strcmp(targ, "/") ? "/" : "", cp);
   1400   1.1  christos 			np = namebuf;
   1401   1.1  christos 		} else
   1402   1.1  christos 			np = targ;
   1403   1.1  christos 		curfile = cp;
   1404   1.1  christos 		exists = stat(np, &stb) == 0;
   1405   1.1  christos 		if (buf[0] == 'D') {
   1406   1.1  christos 			int mod_flag = pflag;
   1407   1.1  christos 			if (!iamrecursive)
   1408   1.1  christos 				SCREWUP("received directory without -r");
   1409   1.1  christos 			if (exists) {
   1410   1.1  christos 				if (!S_ISDIR(stb.st_mode)) {
   1411   1.1  christos 					errno = ENOTDIR;
   1412   1.1  christos 					goto bad;
   1413   1.1  christos 				}
   1414   1.1  christos 				if (pflag)
   1415   1.1  christos 					(void) chmod(np, mode);
   1416   1.1  christos 			} else {
   1417   1.1  christos 				/* Handle copying from a read-only
   1418   1.1  christos 				   directory */
   1419   1.1  christos 				mod_flag = 1;
   1420  1.24  christos 				if (mkdir(np, mode | S_IRWXU) == -1)
   1421   1.1  christos 					goto bad;
   1422   1.1  christos 			}
   1423   1.1  christos 			vect[0] = xstrdup(np);
   1424  1.23  christos 			sink(1, vect, src);
   1425   1.1  christos 			if (setimes) {
   1426   1.1  christos 				setimes = 0;
   1427  1.26  christos 				(void) utimes(vect[0], tv);
   1428   1.1  christos 			}
   1429   1.1  christos 			if (mod_flag)
   1430   1.1  christos 				(void) chmod(vect[0], mode);
   1431   1.9  christos 			free(vect[0]);
   1432   1.1  christos 			continue;
   1433   1.1  christos 		}
   1434   1.1  christos 		omode = mode;
   1435   1.9  christos 		mode |= S_IWUSR;
   1436  1.24  christos 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) {
   1437   1.1  christos bad:			run_err("%s: %s", np, strerror(errno));
   1438   1.1  christos 			continue;
   1439   1.1  christos 		}
   1440   1.5  christos 		(void) atomicio(vwrite, remout, empty, 1);
   1441   1.1  christos 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
   1442   1.1  christos 			(void) close(ofd);
   1443   1.1  christos 			continue;
   1444   1.1  christos 		}
   1445   1.1  christos 		cp = bp->buf;
   1446  1.26  christos 		wrerr = 0;
   1447   1.1  christos 
   1448  1.26  christos 		/*
   1449  1.26  christos 		 * NB. do not use run_err() unless immediately followed by
   1450  1.26  christos 		 * exit() below as it may send a spurious reply that might
   1451  1.26  christos 		 * desyncronise us from the peer. Use note_err() instead.
   1452  1.26  christos 		 */
   1453   1.1  christos 		statbytes = 0;
   1454   1.1  christos 		if (showprogress)
   1455   1.1  christos 			start_progress_meter(curfile, size, &statbytes);
   1456   1.1  christos 		set_nonblock(remin);
   1457   1.1  christos 		for (count = i = 0; i < size; i += bp->cnt) {
   1458   1.1  christos 			amt = bp->cnt;
   1459   1.1  christos 			if (i + amt > size)
   1460   1.1  christos 				amt = size - i;
   1461   1.1  christos 			count += amt;
   1462   1.1  christos 			do {
   1463   1.5  christos 				j = atomicio6(read, remin, cp, amt,
   1464   1.5  christos 				    scpio, &statbytes);
   1465   1.1  christos 				if (j == 0) {
   1466   1.1  christos 					run_err("%s", j != EPIPE ?
   1467   1.1  christos 					    strerror(errno) :
   1468   1.1  christos 					    "dropped connection");
   1469   1.1  christos 					exit(1);
   1470   1.1  christos 				}
   1471   1.1  christos 				amt -= j;
   1472   1.1  christos 				cp += j;
   1473   1.1  christos 			} while (amt > 0);
   1474   1.1  christos 
   1475   1.1  christos 			if (count == bp->cnt) {
   1476   1.1  christos 				/* Keep reading so we stay sync'd up. */
   1477  1.26  christos 				if (!wrerr) {
   1478   1.1  christos 					if (atomicio(vwrite, ofd, bp->buf,
   1479   1.1  christos 					    count) != count) {
   1480  1.26  christos 						note_err("%s: %s", np,
   1481  1.26  christos 						    strerror(errno));
   1482  1.26  christos 						wrerr = 1;
   1483   1.1  christos 					}
   1484   1.1  christos 				}
   1485   1.1  christos 				count = 0;
   1486   1.1  christos 				cp = bp->buf;
   1487   1.1  christos 			}
   1488   1.1  christos 		}
   1489   1.1  christos 		unset_nonblock(remin);
   1490  1.26  christos 		if (count != 0 && !wrerr &&
   1491   1.1  christos 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
   1492  1.26  christos 			note_err("%s: %s", np, strerror(errno));
   1493  1.26  christos 			wrerr = 1;
   1494   1.1  christos 		}
   1495  1.26  christos 		if (!wrerr && (!exists || S_ISREG(stb.st_mode)) &&
   1496  1.26  christos 		    ftruncate(ofd, size) != 0)
   1497  1.26  christos 			note_err("%s: truncate: %s", np, strerror(errno));
   1498   1.1  christos 		if (pflag) {
   1499   1.1  christos 			if (exists || omode != mode)
   1500   1.1  christos 				if (fchmod(ofd, omode)) {
   1501  1.26  christos 					note_err("%s: set mode: %s",
   1502   1.1  christos 					    np, strerror(errno));
   1503   1.1  christos 				}
   1504   1.1  christos 		} else {
   1505   1.1  christos 			if (!exists && omode != mode)
   1506   1.1  christos 				if (fchmod(ofd, omode & ~mask)) {
   1507  1.26  christos 					note_err("%s: set mode: %s",
   1508   1.1  christos 					    np, strerror(errno));
   1509   1.1  christos 				}
   1510   1.1  christos 		}
   1511  1.26  christos 		if (close(ofd) == -1)
   1512  1.27  christos 			note_err("%s: close: %s", np, strerror(errno));
   1513   1.1  christos 		(void) response();
   1514  1.14  christos 		if (showprogress)
   1515  1.14  christos 			stop_progress_meter();
   1516  1.26  christos 		if (setimes && !wrerr) {
   1517   1.1  christos 			setimes = 0;
   1518  1.24  christos 			if (utimes(np, tv) == -1) {
   1519  1.26  christos 				note_err("%s: set times: %s",
   1520   1.1  christos 				    np, strerror(errno));
   1521   1.1  christos 			}
   1522   1.1  christos 		}
   1523  1.26  christos 		/* If no error was noted then signal success for this file */
   1524  1.26  christos 		if (note_err(NULL) == 0)
   1525  1.26  christos 			(void) atomicio(vwrite, remout, __UNCONST(""), 1);
   1526   1.1  christos 	}
   1527  1.23  christos done:
   1528  1.23  christos 	for (n = 0; n < npatterns; n++)
   1529  1.23  christos 		free(patterns[n]);
   1530  1.23  christos 	free(patterns);
   1531  1.23  christos 	return;
   1532   1.1  christos screwup:
   1533  1.23  christos 	for (n = 0; n < npatterns; n++)
   1534  1.23  christos 		free(patterns[n]);
   1535  1.23  christos 	free(patterns);
   1536   1.1  christos 	run_err("protocol error: %s", why);
   1537   1.1  christos 	exit(1);
   1538   1.1  christos }
   1539   1.1  christos 
   1540   1.1  christos int
   1541   1.1  christos response(void)
   1542   1.1  christos {
   1543  1.14  christos 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
   1544   1.1  christos 
   1545   1.1  christos 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
   1546   1.1  christos 		lostconn(0);
   1547   1.1  christos 
   1548   1.1  christos 	cp = rbuf;
   1549   1.1  christos 	switch (resp) {
   1550   1.1  christos 	case 0:		/* ok */
   1551   1.1  christos 		return (0);
   1552   1.1  christos 	default:
   1553   1.1  christos 		*cp++ = resp;
   1554   1.1  christos 		/* FALLTHROUGH */
   1555   1.1  christos 	case 1:		/* error, followed by error msg */
   1556   1.1  christos 	case 2:		/* fatal error, "" */
   1557   1.1  christos 		do {
   1558   1.1  christos 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
   1559   1.1  christos 				lostconn(0);
   1560   1.1  christos 			*cp++ = ch;
   1561   1.1  christos 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
   1562   1.1  christos 
   1563  1.14  christos 		if (!iamremote) {
   1564  1.14  christos 			cp[-1] = '\0';
   1565  1.14  christos 			(void) snmprintf(visbuf, sizeof(visbuf),
   1566  1.14  christos 			    NULL, "%s\n", rbuf);
   1567  1.14  christos 			(void) atomicio(vwrite, STDERR_FILENO,
   1568  1.14  christos 			    visbuf, strlen(visbuf));
   1569  1.14  christos 		}
   1570   1.1  christos 		++errs;
   1571   1.1  christos 		if (resp == 1)
   1572   1.1  christos 			return (-1);
   1573   1.1  christos 		exit(1);
   1574   1.1  christos 	}
   1575   1.1  christos 	/* NOTREACHED */
   1576   1.1  christos }
   1577   1.1  christos 
   1578   1.1  christos void
   1579   1.1  christos usage(void)
   1580   1.1  christos {
   1581   1.1  christos 	(void) fprintf(stderr,
   1582  1.28  christos 	    "usage: scp [-346ABCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
   1583  1.23  christos 	    "            [-J destination] [-l limit] [-o ssh_option] [-P port]\n"
   1584  1.23  christos 	    "            [-S program] source ... target\n");
   1585   1.1  christos 	exit(1);
   1586   1.1  christos }
   1587   1.1  christos 
   1588   1.1  christos void
   1589   1.1  christos run_err(const char *fmt,...)
   1590   1.1  christos {
   1591   1.1  christos 	static FILE *fp;
   1592   1.1  christos 	va_list ap;
   1593   1.1  christos 
   1594   1.1  christos 	++errs;
   1595   1.1  christos 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
   1596   1.1  christos 		(void) fprintf(fp, "%c", 0x01);
   1597   1.1  christos 		(void) fprintf(fp, "scp: ");
   1598   1.1  christos 		va_start(ap, fmt);
   1599   1.1  christos 		(void) vfprintf(fp, fmt, ap);
   1600   1.1  christos 		va_end(ap);
   1601   1.1  christos 		(void) fprintf(fp, "\n");
   1602   1.1  christos 		(void) fflush(fp);
   1603   1.1  christos 	}
   1604   1.1  christos 
   1605   1.1  christos 	if (!iamremote) {
   1606   1.1  christos 		va_start(ap, fmt);
   1607  1.14  christos 		vfmprintf(stderr, fmt, ap);
   1608   1.1  christos 		va_end(ap);
   1609   1.1  christos 		fprintf(stderr, "\n");
   1610   1.1  christos 	}
   1611   1.1  christos }
   1612   1.1  christos 
   1613  1.26  christos /*
   1614  1.26  christos  * Notes a sink error for sending at the end of a file transfer. Returns 0 if
   1615  1.26  christos  * no error has been noted or -1 otherwise. Use note_err(NULL) to flush
   1616  1.26  christos  * any active error at the end of the transfer.
   1617  1.26  christos  */
   1618  1.26  christos int
   1619  1.26  christos note_err(const char *fmt, ...)
   1620  1.26  christos {
   1621  1.26  christos 	static char *emsg;
   1622  1.26  christos 	va_list ap;
   1623  1.26  christos 
   1624  1.26  christos 	/* Replay any previously-noted error */
   1625  1.26  christos 	if (fmt == NULL) {
   1626  1.26  christos 		if (emsg == NULL)
   1627  1.26  christos 			return 0;
   1628  1.26  christos 		run_err("%s", emsg);
   1629  1.26  christos 		free(emsg);
   1630  1.26  christos 		emsg = NULL;
   1631  1.26  christos 		return -1;
   1632  1.26  christos 	}
   1633  1.26  christos 
   1634  1.26  christos 	errs++;
   1635  1.26  christos 	/* Prefer first-noted error */
   1636  1.26  christos 	if (emsg != NULL)
   1637  1.26  christos 		return -1;
   1638  1.26  christos 
   1639  1.26  christos 	va_start(ap, fmt);
   1640  1.26  christos 	vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap);
   1641  1.26  christos 	va_end(ap);
   1642  1.26  christos 	return -1;
   1643  1.26  christos }
   1644  1.26  christos 
   1645   1.1  christos void
   1646   1.1  christos verifydir(char *cp)
   1647   1.1  christos {
   1648   1.1  christos 	struct stat stb;
   1649   1.1  christos 
   1650   1.1  christos 	if (!stat(cp, &stb)) {
   1651   1.1  christos 		if (S_ISDIR(stb.st_mode))
   1652   1.1  christos 			return;
   1653   1.1  christos 		errno = ENOTDIR;
   1654   1.1  christos 	}
   1655   1.1  christos 	run_err("%s: %s", cp, strerror(errno));
   1656   1.1  christos 	killchild(0);
   1657   1.1  christos }
   1658   1.1  christos 
   1659   1.1  christos int
   1660   1.1  christos okname(char *cp0)
   1661   1.1  christos {
   1662   1.1  christos 	int c;
   1663   1.1  christos 	char *cp;
   1664   1.1  christos 
   1665   1.1  christos 	cp = cp0;
   1666   1.1  christos 	do {
   1667   1.1  christos 		c = (int)*cp;
   1668   1.1  christos 		if (c & 0200)
   1669   1.1  christos 			goto bad;
   1670  1.10  christos 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
   1671   1.1  christos 			switch (c) {
   1672   1.1  christos 			case '\'':
   1673   1.1  christos 			case '"':
   1674   1.1  christos 			case '`':
   1675   1.1  christos 			case ' ':
   1676   1.1  christos 			case '#':
   1677   1.1  christos 				goto bad;
   1678   1.1  christos 			default:
   1679   1.1  christos 				break;
   1680   1.1  christos 			}
   1681   1.1  christos 		}
   1682   1.1  christos 	} while (*++cp);
   1683   1.1  christos 	return (1);
   1684   1.1  christos 
   1685  1.14  christos bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
   1686   1.1  christos 	return (0);
   1687   1.1  christos }
   1688   1.1  christos 
   1689   1.1  christos BUF *
   1690   1.1  christos allocbuf(BUF *bp, int fd, int blksize)
   1691   1.1  christos {
   1692   1.1  christos 	size_t size;
   1693   1.1  christos 	struct stat stb;
   1694   1.1  christos 
   1695  1.24  christos 	if (fstat(fd, &stb) == -1) {
   1696   1.1  christos 		run_err("fstat: %s", strerror(errno));
   1697   1.1  christos 		return (0);
   1698   1.1  christos 	}
   1699  1.15  christos 	size = ROUNDUP(stb.st_blksize, blksize);
   1700   1.1  christos 	if (size == 0)
   1701   1.1  christos 		size = blksize;
   1702   1.1  christos 	if (bp->cnt >= size)
   1703   1.1  christos 		return (bp);
   1704  1.17  christos 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
   1705   1.1  christos 	bp->cnt = size;
   1706   1.1  christos 	return (bp);
   1707   1.1  christos }
   1708   1.1  christos 
   1709   1.6     joerg static void
   1710   1.1  christos lostconn(int signo)
   1711   1.1  christos {
   1712   1.1  christos 	if (!iamremote)
   1713   1.9  christos 		(void)write(STDERR_FILENO, "lost connection\n", 16);
   1714   1.1  christos 	if (signo)
   1715   1.1  christos 		_exit(1);
   1716   1.1  christos 	else
   1717   1.1  christos 		exit(1);
   1718   1.1  christos }
   1719