Home | History | Annotate | Line # | Download | only in dist
scp.c revision 1.9
      1  1.9  christos /*	$NetBSD: scp.c,v 1.9 2013/11/08 19:18:25 christos Exp $	*/
      2  1.9  christos /* $OpenBSD: scp.c,v 1.178 2013/06/22 06:31:57 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.9  christos __RCSID("$NetBSD: scp.c,v 1.9 2013/11/08 19:18:25 christos Exp $");
     77  1.1  christos #include <sys/param.h>
     78  1.1  christos #include <sys/types.h>
     79  1.1  christos #include <sys/poll.h>
     80  1.1  christos #include <sys/wait.h>
     81  1.1  christos #include <sys/stat.h>
     82  1.1  christos #include <sys/time.h>
     83  1.1  christos #include <sys/uio.h>
     84  1.1  christos 
     85  1.1  christos #include <ctype.h>
     86  1.1  christos #include <dirent.h>
     87  1.1  christos #include <errno.h>
     88  1.1  christos #include <fcntl.h>
     89  1.1  christos #include <pwd.h>
     90  1.1  christos #include <signal.h>
     91  1.1  christos #include <stdarg.h>
     92  1.1  christos #include <stdio.h>
     93  1.1  christos #include <stdlib.h>
     94  1.1  christos #include <string.h>
     95  1.1  christos #include <time.h>
     96  1.1  christos #include <unistd.h>
     97  1.1  christos #include <vis.h>
     98  1.1  christos 
     99  1.1  christos #include "xmalloc.h"
    100  1.1  christos #include "atomicio.h"
    101  1.1  christos #include "pathnames.h"
    102  1.1  christos #include "log.h"
    103  1.1  christos #include "misc.h"
    104  1.1  christos #include "progressmeter.h"
    105  1.1  christos 
    106  1.1  christos #define COPY_BUFLEN	16384
    107  1.1  christos 
    108  1.1  christos int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout);
    109  1.5  christos int do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout);
    110  1.1  christos 
    111  1.5  christos static char dot[] = ".";
    112  1.5  christos static char empty[] = "";
    113  1.1  christos 
    114  1.1  christos /* Struct for addargs */
    115  1.1  christos arglist args;
    116  1.5  christos arglist remote_remote_args;
    117  1.1  christos 
    118  1.1  christos /* Bandwidth limit */
    119  1.5  christos long long limit_kbps = 0;
    120  1.5  christos struct bwlimit bwlimit;
    121  1.1  christos 
    122  1.1  christos /* Name of current file being transferred. */
    123  1.1  christos char *curfile;
    124  1.1  christos 
    125  1.1  christos /* This is set to non-zero to enable verbose mode. */
    126  1.1  christos int verbose_mode = 0;
    127  1.1  christos 
    128  1.1  christos /* This is set to zero if the progressmeter is not desired. */
    129  1.1  christos int showprogress = 1;
    130  1.1  christos 
    131  1.5  christos /*
    132  1.5  christos  * This is set to non-zero if remote-remote copy should be piped
    133  1.5  christos  * through this process.
    134  1.5  christos  */
    135  1.5  christos int throughlocal = 0;
    136  1.5  christos 
    137  1.1  christos /* This is the program to execute for the secured connection. ("ssh" or -S) */
    138  1.2  christos #ifdef RESCUEDIR
    139  1.5  christos const char *ssh_program = RESCUEDIR "/ssh";
    140  1.2  christos #else
    141  1.5  christos const char *ssh_program = _PATH_SSH_PROGRAM;
    142  1.2  christos #endif
    143  1.1  christos 
    144  1.1  christos /* This is used to store the pid of ssh_program */
    145  1.1  christos pid_t do_cmd_pid = -1;
    146  1.1  christos 
    147  1.6     joerg __dead static void
    148  1.1  christos killchild(int signo)
    149  1.1  christos {
    150  1.1  christos 	if (do_cmd_pid > 1) {
    151  1.1  christos 		kill(do_cmd_pid, signo ? signo : SIGTERM);
    152  1.1  christos 		waitpid(do_cmd_pid, NULL, 0);
    153  1.1  christos 	}
    154  1.1  christos 
    155  1.1  christos 	if (signo)
    156  1.1  christos 		_exit(1);
    157  1.1  christos 	exit(1);
    158  1.1  christos }
    159  1.1  christos 
    160  1.4      adam static void
    161  1.4      adam suspchild(int signo)
    162  1.4      adam {
    163  1.4      adam 	int status;
    164  1.4      adam 
    165  1.4      adam 	if (do_cmd_pid > 1) {
    166  1.4      adam 		kill(do_cmd_pid, signo);
    167  1.4      adam 		while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
    168  1.4      adam 		    errno == EINTR)
    169  1.4      adam 			;
    170  1.4      adam 		kill(getpid(), SIGSTOP);
    171  1.4      adam 	}
    172  1.4      adam }
    173  1.4      adam 
    174  1.1  christos static int
    175  1.1  christos do_local_cmd(arglist *a)
    176  1.1  christos {
    177  1.1  christos 	u_int i;
    178  1.1  christos 	int status;
    179  1.1  christos 	pid_t pid;
    180  1.1  christos 
    181  1.1  christos 	if (a->num == 0)
    182  1.1  christos 		fatal("do_local_cmd: no arguments");
    183  1.1  christos 
    184  1.1  christos 	if (verbose_mode) {
    185  1.1  christos 		fprintf(stderr, "Executing:");
    186  1.1  christos 		for (i = 0; i < a->num; i++)
    187  1.1  christos 			fprintf(stderr, " %s", a->list[i]);
    188  1.1  christos 		fprintf(stderr, "\n");
    189  1.1  christos 	}
    190  1.1  christos 	if ((pid = fork()) == -1)
    191  1.1  christos 		fatal("do_local_cmd: fork: %s", strerror(errno));
    192  1.1  christos 
    193  1.1  christos 	if (pid == 0) {
    194  1.1  christos 		execvp(a->list[0], a->list);
    195  1.1  christos 		perror(a->list[0]);
    196  1.1  christos 		exit(1);
    197  1.1  christos 	}
    198  1.1  christos 
    199  1.1  christos 	do_cmd_pid = pid;
    200  1.1  christos 	signal(SIGTERM, killchild);
    201  1.1  christos 	signal(SIGINT, killchild);
    202  1.1  christos 	signal(SIGHUP, killchild);
    203  1.1  christos 
    204  1.1  christos 	while (waitpid(pid, &status, 0) == -1)
    205  1.1  christos 		if (errno != EINTR)
    206  1.1  christos 			fatal("do_local_cmd: waitpid: %s", strerror(errno));
    207  1.1  christos 
    208  1.1  christos 	do_cmd_pid = -1;
    209  1.1  christos 
    210  1.1  christos 	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
    211  1.1  christos 		return (-1);
    212  1.1  christos 
    213  1.1  christos 	return (0);
    214  1.1  christos }
    215  1.1  christos 
    216  1.1  christos /*
    217  1.1  christos  * This function executes the given command as the specified user on the
    218  1.1  christos  * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
    219  1.1  christos  * assigns the input and output file descriptors on success.
    220  1.1  christos  */
    221  1.1  christos 
    222  1.1  christos int
    223  1.1  christos do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout)
    224  1.1  christos {
    225  1.1  christos 	int pin[2], pout[2], reserved[2];
    226  1.1  christos 
    227  1.1  christos 	if (verbose_mode)
    228  1.1  christos 		fprintf(stderr,
    229  1.1  christos 		    "Executing: program %s host %s, user %s, command %s\n",
    230  1.1  christos 		    ssh_program, host,
    231  1.1  christos 		    remuser ? remuser : "(unspecified)", cmd);
    232  1.1  christos 
    233  1.1  christos 	/*
    234  1.1  christos 	 * Reserve two descriptors so that the real pipes won't get
    235  1.1  christos 	 * descriptors 0 and 1 because that will screw up dup2 below.
    236  1.1  christos 	 */
    237  1.1  christos 	if (pipe(reserved) < 0)
    238  1.1  christos 		fatal("pipe: %s", strerror(errno));
    239  1.1  christos 
    240  1.1  christos 	/* Create a socket pair for communicating with ssh. */
    241  1.1  christos 	if (pipe(pin) < 0)
    242  1.1  christos 		fatal("pipe: %s", strerror(errno));
    243  1.1  christos 	if (pipe(pout) < 0)
    244  1.1  christos 		fatal("pipe: %s", strerror(errno));
    245  1.1  christos 
    246  1.1  christos 	/* Free the reserved descriptors. */
    247  1.1  christos 	close(reserved[0]);
    248  1.1  christos 	close(reserved[1]);
    249  1.1  christos 
    250  1.4      adam 	signal(SIGTSTP, suspchild);
    251  1.4      adam 	signal(SIGTTIN, suspchild);
    252  1.4      adam 	signal(SIGTTOU, suspchild);
    253  1.4      adam 
    254  1.1  christos 	/* Fork a child to execute the command on the remote host using ssh. */
    255  1.1  christos 	do_cmd_pid = fork();
    256  1.1  christos 	if (do_cmd_pid == 0) {
    257  1.1  christos 		/* Child. */
    258  1.1  christos 		close(pin[1]);
    259  1.1  christos 		close(pout[0]);
    260  1.1  christos 		dup2(pin[0], 0);
    261  1.1  christos 		dup2(pout[1], 1);
    262  1.1  christos 		close(pin[0]);
    263  1.1  christos 		close(pout[1]);
    264  1.1  christos 
    265  1.1  christos 		replacearg(&args, 0, "%s", ssh_program);
    266  1.4      adam 		if (remuser != NULL) {
    267  1.4      adam 			addargs(&args, "-l");
    268  1.4      adam 			addargs(&args, "%s", remuser);
    269  1.4      adam 		}
    270  1.4      adam 		addargs(&args, "--");
    271  1.1  christos 		addargs(&args, "%s", host);
    272  1.1  christos 		addargs(&args, "%s", cmd);
    273  1.1  christos 
    274  1.1  christos 		execvp(ssh_program, args.list);
    275  1.1  christos 		perror(ssh_program);
    276  1.1  christos 		exit(1);
    277  1.1  christos 	} else if (do_cmd_pid == -1) {
    278  1.1  christos 		fatal("fork: %s", strerror(errno));
    279  1.1  christos 	}
    280  1.1  christos 	/* Parent.  Close the other side, and return the local side. */
    281  1.1  christos 	close(pin[0]);
    282  1.1  christos 	*fdout = pin[1];
    283  1.1  christos 	close(pout[1]);
    284  1.1  christos 	*fdin = pout[0];
    285  1.1  christos 	signal(SIGTERM, killchild);
    286  1.1  christos 	signal(SIGINT, killchild);
    287  1.1  christos 	signal(SIGHUP, killchild);
    288  1.1  christos 	return 0;
    289  1.1  christos }
    290  1.1  christos 
    291  1.5  christos /*
    292  1.5  christos  * This functions executes a command simlar to do_cmd(), but expects the
    293  1.5  christos  * input and output descriptors to be setup by a previous call to do_cmd().
    294  1.5  christos  * This way the input and output of two commands can be connected.
    295  1.5  christos  */
    296  1.5  christos int
    297  1.5  christos do_cmd2(char *host, char *remuser, char *cmd, int fdin, int fdout)
    298  1.5  christos {
    299  1.5  christos 	pid_t pid;
    300  1.5  christos 	int status;
    301  1.5  christos 
    302  1.5  christos 	if (verbose_mode)
    303  1.5  christos 		fprintf(stderr,
    304  1.5  christos 		    "Executing: 2nd program %s host %s, user %s, command %s\n",
    305  1.5  christos 		    ssh_program, host,
    306  1.5  christos 		    remuser ? remuser : "(unspecified)", cmd);
    307  1.5  christos 
    308  1.5  christos 	/* Fork a child to execute the command on the remote host using ssh. */
    309  1.5  christos 	pid = fork();
    310  1.5  christos 	if (pid == 0) {
    311  1.5  christos 		dup2(fdin, 0);
    312  1.5  christos 		dup2(fdout, 1);
    313  1.5  christos 
    314  1.5  christos 		replacearg(&args, 0, "%s", ssh_program);
    315  1.5  christos 		if (remuser != NULL) {
    316  1.5  christos 			addargs(&args, "-l");
    317  1.5  christos 			addargs(&args, "%s", remuser);
    318  1.5  christos 		}
    319  1.5  christos 		addargs(&args, "--");
    320  1.5  christos 		addargs(&args, "%s", host);
    321  1.5  christos 		addargs(&args, "%s", cmd);
    322  1.5  christos 
    323  1.5  christos 		execvp(ssh_program, args.list);
    324  1.5  christos 		perror(ssh_program);
    325  1.5  christos 		exit(1);
    326  1.5  christos 	} else if (pid == -1) {
    327  1.5  christos 		fatal("fork: %s", strerror(errno));
    328  1.5  christos 	}
    329  1.5  christos 	while (waitpid(pid, &status, 0) == -1)
    330  1.5  christos 		if (errno != EINTR)
    331  1.5  christos 			fatal("do_cmd2: waitpid: %s", strerror(errno));
    332  1.5  christos 	return 0;
    333  1.5  christos }
    334  1.5  christos 
    335  1.1  christos typedef struct {
    336  1.1  christos 	size_t cnt;
    337  1.1  christos 	char *buf;
    338  1.1  christos } BUF;
    339  1.1  christos 
    340  1.1  christos BUF *allocbuf(BUF *, int, int);
    341  1.6     joerg __dead static void lostconn(int);
    342  1.1  christos int okname(char *);
    343  1.8     joerg void run_err(const char *,...) __printflike(1, 2);
    344  1.1  christos void verifydir(char *);
    345  1.1  christos 
    346  1.1  christos struct passwd *pwd;
    347  1.1  christos uid_t userid;
    348  1.1  christos int errs, remin, remout;
    349  1.1  christos int pflag, iamremote, iamrecursive, targetshouldbedirectory;
    350  1.1  christos 
    351  1.1  christos #define	CMDNEEDS	64
    352  1.1  christos char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */
    353  1.1  christos 
    354  1.1  christos int response(void);
    355  1.1  christos void rsource(char *, struct stat *);
    356  1.1  christos void sink(int, char *[]);
    357  1.1  christos void source(int, char *[]);
    358  1.6     joerg static void tolocal(int, char *[]);
    359  1.6     joerg static void toremote(char *, int, char *[]);
    360  1.6     joerg __dead static void usage(void);
    361  1.1  christos 
    362  1.1  christos int
    363  1.1  christos main(int argc, char **argv)
    364  1.1  christos {
    365  1.1  christos 	int ch, fflag, tflag, status, n;
    366  1.5  christos 	char *targ, **newargv;
    367  1.5  christos 	const char *errstr;
    368  1.1  christos 	extern char *optarg;
    369  1.1  christos 	extern int optind;
    370  1.1  christos 
    371  1.1  christos 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
    372  1.1  christos 	sanitise_stdfd();
    373  1.1  christos 
    374  1.1  christos 	/* Copy argv, because we modify it */
    375  1.1  christos 	newargv = xcalloc(MAX(argc + 1, 1), sizeof(*newargv));
    376  1.1  christos 	for (n = 0; n < argc; n++)
    377  1.1  christos 		newargv[n] = xstrdup(argv[n]);
    378  1.1  christos 	argv = newargv;
    379  1.1  christos 
    380  1.1  christos 	memset(&args, '\0', sizeof(args));
    381  1.5  christos 	memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
    382  1.5  christos 	args.list = remote_remote_args.list = NULL;
    383  1.1  christos 	addargs(&args, "%s", ssh_program);
    384  1.1  christos 	addargs(&args, "-x");
    385  1.5  christos 	addargs(&args, "-oForwardAgent=no");
    386  1.5  christos 	addargs(&args, "-oPermitLocalCommand=no");
    387  1.5  christos 	addargs(&args, "-oClearAllForwardings=yes");
    388  1.1  christos 
    389  1.1  christos 	fflag = tflag = 0;
    390  1.5  christos 	while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1)
    391  1.1  christos 		switch (ch) {
    392  1.1  christos 		/* User-visible flags. */
    393  1.1  christos 		case '1':
    394  1.1  christos 		case '2':
    395  1.1  christos 		case '4':
    396  1.1  christos 		case '6':
    397  1.1  christos 		case 'C':
    398  1.1  christos 			addargs(&args, "-%c", ch);
    399  1.5  christos 			addargs(&remote_remote_args, "-%c", ch);
    400  1.5  christos 			break;
    401  1.5  christos 		case '3':
    402  1.5  christos 			throughlocal = 1;
    403  1.1  christos 			break;
    404  1.1  christos 		case 'o':
    405  1.1  christos 		case 'c':
    406  1.1  christos 		case 'i':
    407  1.1  christos 		case 'F':
    408  1.5  christos 			addargs(&remote_remote_args, "-%c", ch);
    409  1.5  christos 			addargs(&remote_remote_args, "%s", optarg);
    410  1.4      adam 			addargs(&args, "-%c", ch);
    411  1.4      adam 			addargs(&args, "%s", optarg);
    412  1.1  christos 			break;
    413  1.1  christos 		case 'P':
    414  1.5  christos 			addargs(&remote_remote_args, "-p");
    415  1.5  christos 			addargs(&remote_remote_args, "%s", optarg);
    416  1.4      adam 			addargs(&args, "-p");
    417  1.4      adam 			addargs(&args, "%s", optarg);
    418  1.1  christos 			break;
    419  1.1  christos 		case 'B':
    420  1.5  christos 			addargs(&remote_remote_args, "-oBatchmode=yes");
    421  1.5  christos 			addargs(&args, "-oBatchmode=yes");
    422  1.1  christos 			break;
    423  1.1  christos 		case 'l':
    424  1.5  christos 			limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
    425  1.5  christos 			    &errstr);
    426  1.5  christos 			if (errstr != NULL)
    427  1.1  christos 				usage();
    428  1.5  christos 			limit_kbps *= 1024; /* kbps */
    429  1.5  christos 			bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
    430  1.1  christos 			break;
    431  1.1  christos 		case 'p':
    432  1.1  christos 			pflag = 1;
    433  1.1  christos 			break;
    434  1.1  christos 		case 'r':
    435  1.1  christos 			iamrecursive = 1;
    436  1.1  christos 			break;
    437  1.1  christos 		case 'S':
    438  1.1  christos 			ssh_program = xstrdup(optarg);
    439  1.1  christos 			break;
    440  1.1  christos 		case 'v':
    441  1.1  christos 			addargs(&args, "-v");
    442  1.5  christos 			addargs(&remote_remote_args, "-v");
    443  1.1  christos 			verbose_mode = 1;
    444  1.1  christos 			break;
    445  1.1  christos 		case 'q':
    446  1.1  christos 			addargs(&args, "-q");
    447  1.5  christos 			addargs(&remote_remote_args, "-q");
    448  1.1  christos 			showprogress = 0;
    449  1.1  christos 			break;
    450  1.1  christos 
    451  1.1  christos 		/* Server options. */
    452  1.1  christos 		case 'd':
    453  1.1  christos 			targetshouldbedirectory = 1;
    454  1.1  christos 			break;
    455  1.1  christos 		case 'f':	/* "from" */
    456  1.1  christos 			iamremote = 1;
    457  1.1  christos 			fflag = 1;
    458  1.1  christos 			break;
    459  1.1  christos 		case 't':	/* "to" */
    460  1.1  christos 			iamremote = 1;
    461  1.1  christos 			tflag = 1;
    462  1.1  christos 			break;
    463  1.1  christos 		default:
    464  1.1  christos 			usage();
    465  1.1  christos 		}
    466  1.1  christos 	argc -= optind;
    467  1.1  christos 	argv += optind;
    468  1.1  christos 
    469  1.1  christos 	if ((pwd = getpwuid(userid = getuid())) == NULL)
    470  1.1  christos 		fatal("unknown user %u", (u_int) userid);
    471  1.1  christos 
    472  1.1  christos 	if (!isatty(STDOUT_FILENO))
    473  1.1  christos 		showprogress = 0;
    474  1.1  christos 
    475  1.1  christos 	remin = STDIN_FILENO;
    476  1.1  christos 	remout = STDOUT_FILENO;
    477  1.1  christos 
    478  1.1  christos 	if (fflag) {
    479  1.1  christos 		/* Follow "protocol", send data. */
    480  1.1  christos 		(void) response();
    481  1.1  christos 		source(argc, argv);
    482  1.1  christos 		exit(errs != 0);
    483  1.1  christos 	}
    484  1.1  christos 	if (tflag) {
    485  1.1  christos 		/* Receive data. */
    486  1.1  christos 		sink(argc, argv);
    487  1.1  christos 		exit(errs != 0);
    488  1.1  christos 	}
    489  1.1  christos 	if (argc < 2)
    490  1.1  christos 		usage();
    491  1.1  christos 	if (argc > 2)
    492  1.1  christos 		targetshouldbedirectory = 1;
    493  1.1  christos 
    494  1.1  christos 	remin = remout = -1;
    495  1.1  christos 	do_cmd_pid = -1;
    496  1.1  christos 	/* Command to be executed on remote system using "ssh". */
    497  1.1  christos 	(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
    498  1.1  christos 	    verbose_mode ? " -v" : "",
    499  1.1  christos 	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
    500  1.1  christos 	    targetshouldbedirectory ? " -d" : "");
    501  1.1  christos 
    502  1.1  christos 	(void) signal(SIGPIPE, lostconn);
    503  1.1  christos 
    504  1.1  christos 	if ((targ = colon(argv[argc - 1])))	/* Dest is remote host. */
    505  1.1  christos 		toremote(targ, argc, argv);
    506  1.1  christos 	else {
    507  1.1  christos 		if (targetshouldbedirectory)
    508  1.1  christos 			verifydir(argv[argc - 1]);
    509  1.1  christos 		tolocal(argc, argv);	/* Dest is local host. */
    510  1.1  christos 	}
    511  1.1  christos 	/*
    512  1.1  christos 	 * Finally check the exit status of the ssh process, if one was forked
    513  1.1  christos 	 * and no error has occurred yet
    514  1.1  christos 	 */
    515  1.1  christos 	if (do_cmd_pid != -1 && errs == 0) {
    516  1.1  christos 		if (remin != -1)
    517  1.1  christos 		    (void) close(remin);
    518  1.1  christos 		if (remout != -1)
    519  1.1  christos 		    (void) close(remout);
    520  1.1  christos 		if (waitpid(do_cmd_pid, &status, 0) == -1)
    521  1.1  christos 			errs = 1;
    522  1.1  christos 		else {
    523  1.1  christos 			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
    524  1.1  christos 				errs = 1;
    525  1.1  christos 		}
    526  1.1  christos 	}
    527  1.1  christos 	exit(errs != 0);
    528  1.1  christos }
    529  1.1  christos 
    530  1.5  christos /* Callback from atomicio6 to update progress meter and limit bandwidth */
    531  1.5  christos static int
    532  1.5  christos scpio(void *_cnt, size_t s)
    533  1.1  christos {
    534  1.5  christos 	off_t *cnt = (off_t *)_cnt;
    535  1.5  christos 
    536  1.5  christos 	*cnt += s;
    537  1.5  christos 	if (limit_kbps > 0)
    538  1.5  christos 		bandwidth_limit(&bwlimit, s);
    539  1.5  christos 	return 0;
    540  1.1  christos }
    541  1.1  christos 
    542  1.9  christos static int
    543  1.9  christos do_times(int fd, int verb, const struct stat *sb)
    544  1.9  christos {
    545  1.9  christos 	/* strlen(2^64) == 20; strlen(10^6) == 7 */
    546  1.9  christos 	char buf[(20 + 7 + 2) * 2 + 2];
    547  1.9  christos 
    548  1.9  christos 	(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
    549  1.9  christos 	    (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
    550  1.9  christos 	    (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
    551  1.9  christos 	if (verb) {
    552  1.9  christos 		fprintf(stderr, "File mtime %lld atime %lld\n",
    553  1.9  christos 		    (long long)sb->st_mtime, (long long)sb->st_atime);
    554  1.9  christos 		fprintf(stderr, "Sending file timestamps: %s", buf);
    555  1.9  christos 	}
    556  1.9  christos 	(void) atomicio(vwrite, fd, buf, strlen(buf));
    557  1.9  christos 	return (response());
    558  1.9  christos }
    559  1.9  christos 
    560  1.9  christos void
    561  1.1  christos toremote(char *targ, int argc, char **argv)
    562  1.1  christos {
    563  1.1  christos 	char *bp, *host, *src, *suser, *thost, *tuser, *arg;
    564  1.1  christos 	arglist alist;
    565  1.1  christos 	int i;
    566  1.5  christos 	u_int j;
    567  1.1  christos 
    568  1.1  christos 	memset(&alist, '\0', sizeof(alist));
    569  1.1  christos 	alist.list = NULL;
    570  1.1  christos 
    571  1.1  christos 	*targ++ = 0;
    572  1.1  christos 	if (*targ == 0)
    573  1.5  christos 		targ = dot;
    574  1.1  christos 
    575  1.1  christos 	arg = xstrdup(argv[argc - 1]);
    576  1.1  christos 	if ((thost = strrchr(arg, '@'))) {
    577  1.1  christos 		/* user@host */
    578  1.1  christos 		*thost++ = 0;
    579  1.1  christos 		tuser = arg;
    580  1.1  christos 		if (*tuser == '\0')
    581  1.1  christos 			tuser = NULL;
    582  1.1  christos 	} else {
    583  1.1  christos 		thost = arg;
    584  1.1  christos 		tuser = NULL;
    585  1.1  christos 	}
    586  1.1  christos 
    587  1.1  christos 	if (tuser != NULL && !okname(tuser)) {
    588  1.9  christos 		free(arg);
    589  1.1  christos 		return;
    590  1.1  christos 	}
    591  1.1  christos 
    592  1.1  christos 	for (i = 0; i < argc - 1; i++) {
    593  1.1  christos 		src = colon(argv[i]);
    594  1.5  christos 		if (src && throughlocal) {	/* extended remote to remote */
    595  1.5  christos 			*src++ = 0;
    596  1.5  christos 			if (*src == 0)
    597  1.5  christos 				src = dot;
    598  1.5  christos 			host = strrchr(argv[i], '@');
    599  1.5  christos 			if (host) {
    600  1.5  christos 				*host++ = 0;
    601  1.5  christos 				host = cleanhostname(host);
    602  1.5  christos 				suser = argv[i];
    603  1.5  christos 				if (*suser == '\0')
    604  1.5  christos 					suser = pwd->pw_name;
    605  1.5  christos 				else if (!okname(suser))
    606  1.5  christos 					continue;
    607  1.5  christos 			} else {
    608  1.5  christos 				host = cleanhostname(argv[i]);
    609  1.5  christos 				suser = NULL;
    610  1.5  christos 			}
    611  1.7  christos 			xasprintf(&bp, "%s -f %s%s", cmd,
    612  1.7  christos 			    *src == '-' ? "-- " : "", src);
    613  1.5  christos 			if (do_cmd(host, suser, bp, &remin, &remout) < 0)
    614  1.5  christos 				exit(1);
    615  1.9  christos 			free(bp);
    616  1.5  christos 			host = cleanhostname(thost);
    617  1.7  christos 			xasprintf(&bp, "%s -t %s%s", cmd,
    618  1.7  christos 			    *targ == '-' ? "-- " : "", targ);
    619  1.5  christos 			if (do_cmd2(host, tuser, bp, remin, remout) < 0)
    620  1.5  christos 				exit(1);
    621  1.9  christos 			free(bp);
    622  1.5  christos 			(void) close(remin);
    623  1.5  christos 			(void) close(remout);
    624  1.5  christos 			remin = remout = -1;
    625  1.5  christos 		} else if (src) {	/* standard remote to remote */
    626  1.1  christos 			freeargs(&alist);
    627  1.1  christos 			addargs(&alist, "%s", ssh_program);
    628  1.1  christos 			addargs(&alist, "-x");
    629  1.5  christos 			addargs(&alist, "-oClearAllForwardings=yes");
    630  1.1  christos 			addargs(&alist, "-n");
    631  1.5  christos 			for (j = 0; j < remote_remote_args.num; j++) {
    632  1.5  christos 				addargs(&alist, "%s",
    633  1.5  christos 				    remote_remote_args.list[j]);
    634  1.5  christos 			}
    635  1.1  christos 			*src++ = 0;
    636  1.1  christos 			if (*src == 0)
    637  1.5  christos 				src = dot;
    638  1.1  christos 			host = strrchr(argv[i], '@');
    639  1.1  christos 
    640  1.1  christos 			if (host) {
    641  1.1  christos 				*host++ = 0;
    642  1.1  christos 				host = cleanhostname(host);
    643  1.1  christos 				suser = argv[i];
    644  1.1  christos 				if (*suser == '\0')
    645  1.1  christos 					suser = pwd->pw_name;
    646  1.1  christos 				else if (!okname(suser))
    647  1.1  christos 					continue;
    648  1.1  christos 				addargs(&alist, "-l");
    649  1.1  christos 				addargs(&alist, "%s", suser);
    650  1.1  christos 			} else {
    651  1.1  christos 				host = cleanhostname(argv[i]);
    652  1.1  christos 			}
    653  1.4      adam 			addargs(&alist, "--");
    654  1.1  christos 			addargs(&alist, "%s", host);
    655  1.1  christos 			addargs(&alist, "%s", cmd);
    656  1.1  christos 			addargs(&alist, "%s", src);
    657  1.1  christos 			addargs(&alist, "%s%s%s:%s",
    658  1.1  christos 			    tuser ? tuser : "", tuser ? "@" : "",
    659  1.1  christos 			    thost, targ);
    660  1.1  christos 			if (do_local_cmd(&alist) != 0)
    661  1.1  christos 				errs = 1;
    662  1.1  christos 		} else {	/* local to remote */
    663  1.1  christos 			if (remin == -1) {
    664  1.7  christos 				xasprintf(&bp, "%s -t %s%s", cmd,
    665  1.7  christos 				    *targ == '-' ? "-- " : "", targ);
    666  1.1  christos 				host = cleanhostname(thost);
    667  1.1  christos 				if (do_cmd(host, tuser, bp, &remin,
    668  1.1  christos 				    &remout) < 0)
    669  1.1  christos 					exit(1);
    670  1.1  christos 				if (response() < 0)
    671  1.1  christos 					exit(1);
    672  1.9  christos 				free(bp);
    673  1.1  christos 			}
    674  1.1  christos 			source(1, argv + i);
    675  1.1  christos 		}
    676  1.1  christos 	}
    677  1.9  christos 	free(arg);
    678  1.1  christos }
    679  1.1  christos 
    680  1.6     joerg static void
    681  1.1  christos tolocal(int argc, char **argv)
    682  1.1  christos {
    683  1.1  christos 	char *bp, *host, *src, *suser;
    684  1.1  christos 	arglist alist;
    685  1.1  christos 	int i;
    686  1.1  christos 
    687  1.1  christos 	memset(&alist, '\0', sizeof(alist));
    688  1.1  christos 	alist.list = NULL;
    689  1.1  christos 
    690  1.1  christos 	for (i = 0; i < argc - 1; i++) {
    691  1.1  christos 		if (!(src = colon(argv[i]))) {	/* Local to local. */
    692  1.1  christos 			freeargs(&alist);
    693  1.1  christos 			addargs(&alist, "%s", _PATH_CP);
    694  1.1  christos 			if (iamrecursive)
    695  1.1  christos 				addargs(&alist, "-r");
    696  1.1  christos 			if (pflag)
    697  1.1  christos 				addargs(&alist, "-p");
    698  1.4      adam 			addargs(&alist, "--");
    699  1.1  christos 			addargs(&alist, "%s", argv[i]);
    700  1.1  christos 			addargs(&alist, "%s", argv[argc-1]);
    701  1.1  christos 			if (do_local_cmd(&alist))
    702  1.1  christos 				++errs;
    703  1.1  christos 			continue;
    704  1.1  christos 		}
    705  1.1  christos 		*src++ = 0;
    706  1.1  christos 		if (*src == 0)
    707  1.5  christos 			src = dot;
    708  1.1  christos 		if ((host = strrchr(argv[i], '@')) == NULL) {
    709  1.1  christos 			host = argv[i];
    710  1.1  christos 			suser = NULL;
    711  1.1  christos 		} else {
    712  1.1  christos 			*host++ = 0;
    713  1.1  christos 			suser = argv[i];
    714  1.1  christos 			if (*suser == '\0')
    715  1.1  christos 				suser = pwd->pw_name;
    716  1.1  christos 		}
    717  1.1  christos 		host = cleanhostname(host);
    718  1.7  christos 		xasprintf(&bp, "%s -f %s%s",
    719  1.7  christos 		    cmd, *src == '-' ? "-- " : "", src);
    720  1.1  christos 		if (do_cmd(host, suser, bp, &remin, &remout) < 0) {
    721  1.9  christos 			free(bp);
    722  1.1  christos 			++errs;
    723  1.1  christos 			continue;
    724  1.1  christos 		}
    725  1.9  christos 		free(bp);
    726  1.1  christos 		sink(1, argv + argc - 1);
    727  1.1  christos 		(void) close(remin);
    728  1.1  christos 		remin = remout = -1;
    729  1.1  christos 	}
    730  1.1  christos }
    731  1.1  christos 
    732  1.1  christos void
    733  1.1  christos source(int argc, char **argv)
    734  1.1  christos {
    735  1.1  christos 	struct stat stb;
    736  1.1  christos 	static BUF buffer;
    737  1.1  christos 	BUF *bp;
    738  1.1  christos 	off_t i, statbytes;
    739  1.1  christos 	size_t amt;
    740  1.1  christos 	int fd = -1, haderr, indx;
    741  1.2  christos 	char *last, *name, buf[16384], encname[MAXPATHLEN];
    742  1.1  christos 	int len;
    743  1.1  christos 
    744  1.1  christos 	for (indx = 0; indx < argc; ++indx) {
    745  1.2  christos 		fd = -1;
    746  1.1  christos 		name = argv[indx];
    747  1.1  christos 		statbytes = 0;
    748  1.1  christos 		len = strlen(name);
    749  1.1  christos 		while (len > 1 && name[len-1] == '/')
    750  1.1  christos 			name[--len] = '\0';
    751  1.1  christos 		if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
    752  1.1  christos 			goto syserr;
    753  1.1  christos 		if (strchr(name, '\n') != NULL) {
    754  1.3  stacktic 			strvisx(encname, name, len, VIS_NL);
    755  1.1  christos 			name = encname;
    756  1.1  christos 		}
    757  1.1  christos 		if (fstat(fd, &stb) < 0) {
    758  1.1  christos syserr:			run_err("%s: %s", name, strerror(errno));
    759  1.1  christos 			goto next;
    760  1.1  christos 		}
    761  1.1  christos 		if (stb.st_size < 0) {
    762  1.1  christos 			run_err("%s: %s", name, "Negative file size");
    763  1.1  christos 			goto next;
    764  1.1  christos 		}
    765  1.1  christos 		unset_nonblock(fd);
    766  1.1  christos 		switch (stb.st_mode & S_IFMT) {
    767  1.1  christos 		case S_IFREG:
    768  1.1  christos 			break;
    769  1.1  christos 		case S_IFDIR:
    770  1.1  christos 			if (iamrecursive) {
    771  1.1  christos 				rsource(name, &stb);
    772  1.1  christos 				goto next;
    773  1.1  christos 			}
    774  1.1  christos 			/* FALLTHROUGH */
    775  1.1  christos 		default:
    776  1.1  christos 			run_err("%s: not a regular file", name);
    777  1.1  christos 			goto next;
    778  1.1  christos 		}
    779  1.1  christos 		if ((last = strrchr(name, '/')) == NULL)
    780  1.1  christos 			last = name;
    781  1.1  christos 		else
    782  1.1  christos 			++last;
    783  1.1  christos 		curfile = last;
    784  1.1  christos 		if (pflag) {
    785  1.9  christos 			if (do_times(remout, verbose_mode, &stb) < 0)
    786  1.1  christos 				goto next;
    787  1.1  christos 		}
    788  1.1  christos #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
    789  1.1  christos 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
    790  1.1  christos 		    (u_int) (stb.st_mode & FILEMODEMASK),
    791  1.1  christos 		    (long long)stb.st_size, last);
    792  1.1  christos 		if (verbose_mode) {
    793  1.1  christos 			fprintf(stderr, "Sending file modes: %s", buf);
    794  1.1  christos 		}
    795  1.1  christos 		(void) atomicio(vwrite, remout, buf, strlen(buf));
    796  1.1  christos 		if (response() < 0)
    797  1.1  christos 			goto next;
    798  1.1  christos 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
    799  1.1  christos next:			if (fd != -1) {
    800  1.1  christos 				(void) close(fd);
    801  1.1  christos 				fd = -1;
    802  1.1  christos 			}
    803  1.1  christos 			continue;
    804  1.1  christos 		}
    805  1.1  christos 		if (showprogress)
    806  1.1  christos 			start_progress_meter(curfile, stb.st_size, &statbytes);
    807  1.1  christos 		set_nonblock(remout);
    808  1.1  christos 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
    809  1.1  christos 			amt = bp->cnt;
    810  1.1  christos 			if (i + (off_t)amt > stb.st_size)
    811  1.1  christos 				amt = stb.st_size - i;
    812  1.1  christos 			if (!haderr) {
    813  1.1  christos 				if (atomicio(read, fd, bp->buf, amt) != amt)
    814  1.1  christos 					haderr = errno;
    815  1.1  christos 			}
    816  1.1  christos 			/* Keep writing after error to retain sync */
    817  1.1  christos 			if (haderr) {
    818  1.1  christos 				(void)atomicio(vwrite, remout, bp->buf, amt);
    819  1.1  christos 				continue;
    820  1.1  christos 			}
    821  1.5  christos 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
    822  1.1  christos 			    &statbytes) != amt)
    823  1.1  christos 				haderr = errno;
    824  1.1  christos 		}
    825  1.1  christos 		unset_nonblock(remout);
    826  1.1  christos 		if (showprogress)
    827  1.1  christos 			stop_progress_meter();
    828  1.1  christos 
    829  1.1  christos 		if (fd != -1) {
    830  1.1  christos 			if (close(fd) < 0 && !haderr)
    831  1.1  christos 				haderr = errno;
    832  1.1  christos 			fd = -1;
    833  1.1  christos 		}
    834  1.1  christos 		if (!haderr)
    835  1.5  christos 			(void) atomicio(vwrite, remout, empty, 1);
    836  1.1  christos 		else
    837  1.1  christos 			run_err("%s: %s", name, strerror(haderr));
    838  1.1  christos 		(void) response();
    839  1.1  christos 	}
    840  1.1  christos }
    841  1.1  christos 
    842  1.1  christos void
    843  1.1  christos rsource(char *name, struct stat *statp)
    844  1.1  christos {
    845  1.1  christos 	DIR *dirp;
    846  1.1  christos 	struct dirent *dp;
    847  1.9  christos 	char *last, *vect[1], path[MAXPATHLEN];
    848  1.1  christos 
    849  1.1  christos 	if (!(dirp = opendir(name))) {
    850  1.1  christos 		run_err("%s: %s", name, strerror(errno));
    851  1.1  christos 		return;
    852  1.1  christos 	}
    853  1.1  christos 	last = strrchr(name, '/');
    854  1.1  christos 	if (last == 0)
    855  1.1  christos 		last = name;
    856  1.1  christos 	else
    857  1.1  christos 		last++;
    858  1.1  christos 	if (pflag) {
    859  1.9  christos 		if (do_times(remout, verbose_mode, statp) < 0) {
    860  1.1  christos 			closedir(dirp);
    861  1.1  christos 			return;
    862  1.1  christos 		}
    863  1.1  christos 	}
    864  1.1  christos 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
    865  1.1  christos 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
    866  1.1  christos 	if (verbose_mode)
    867  1.1  christos 		fprintf(stderr, "Entering directory: %s", path);
    868  1.1  christos 	(void) atomicio(vwrite, remout, path, strlen(path));
    869  1.1  christos 	if (response() < 0) {
    870  1.1  christos 		closedir(dirp);
    871  1.1  christos 		return;
    872  1.1  christos 	}
    873  1.1  christos 	while ((dp = readdir(dirp)) != NULL) {
    874  1.1  christos 		if (dp->d_ino == 0)
    875  1.1  christos 			continue;
    876  1.1  christos 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
    877  1.1  christos 			continue;
    878  1.1  christos 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
    879  1.1  christos 			run_err("%s/%s: name too long", name, dp->d_name);
    880  1.1  christos 			continue;
    881  1.1  christos 		}
    882  1.1  christos 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
    883  1.1  christos 		vect[0] = path;
    884  1.1  christos 		source(1, vect);
    885  1.1  christos 	}
    886  1.1  christos 	(void) closedir(dirp);
    887  1.5  christos 	(void) atomicio(vwrite, remout, __UNCONST("E\n"), 2);
    888  1.1  christos 	(void) response();
    889  1.1  christos }
    890  1.1  christos 
    891  1.1  christos void
    892  1.1  christos sink(int argc, char **argv)
    893  1.1  christos {
    894  1.1  christos 	static BUF buffer;
    895  1.1  christos 	struct stat stb;
    896  1.1  christos 	enum {
    897  1.1  christos 		YES, NO, DISPLAYED
    898  1.1  christos 	} wrerr;
    899  1.1  christos 	BUF *bp;
    900  1.1  christos 	off_t i;
    901  1.1  christos 	size_t j, count;
    902  1.1  christos 	int amt, exists, first, ofd;
    903  1.1  christos 	mode_t mode, omode, mask;
    904  1.1  christos 	off_t size, statbytes;
    905  1.9  christos 	unsigned long long ull;
    906  1.1  christos 	int setimes, targisdir, wrerrno = 0;
    907  1.5  christos 	char ch, *cp, *np, *targ, *vect[1], buf[16384];
    908  1.5  christos 	const char *why;
    909  1.1  christos 	struct timeval tv[2];
    910  1.1  christos 
    911  1.1  christos #define	atime	tv[0]
    912  1.1  christos #define	mtime	tv[1]
    913  1.1  christos #define	SCREWUP(str)	{ why = str; goto screwup; }
    914  1.1  christos 
    915  1.1  christos 	setimes = targisdir = 0;
    916  1.1  christos 	mask = umask(0);
    917  1.1  christos 	if (!pflag)
    918  1.1  christos 		(void) umask(mask);
    919  1.1  christos 	if (argc != 1) {
    920  1.1  christos 		run_err("ambiguous target");
    921  1.1  christos 		exit(1);
    922  1.1  christos 	}
    923  1.1  christos 	targ = *argv;
    924  1.1  christos 	if (targetshouldbedirectory)
    925  1.1  christos 		verifydir(targ);
    926  1.1  christos 
    927  1.5  christos 	(void) atomicio(vwrite, remout, empty, 1);
    928  1.1  christos 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
    929  1.1  christos 		targisdir = 1;
    930  1.1  christos 	for (first = 1;; first = 0) {
    931  1.1  christos 		cp = buf;
    932  1.1  christos 		if (atomicio(read, remin, cp, 1) != 1)
    933  1.1  christos 			return;
    934  1.1  christos 		if (*cp++ == '\n')
    935  1.1  christos 			SCREWUP("unexpected <newline>");
    936  1.1  christos 		do {
    937  1.1  christos 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
    938  1.1  christos 				SCREWUP("lost connection");
    939  1.1  christos 			*cp++ = ch;
    940  1.1  christos 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
    941  1.1  christos 		*cp = 0;
    942  1.1  christos 		if (verbose_mode)
    943  1.1  christos 			fprintf(stderr, "Sink: %s", buf);
    944  1.1  christos 
    945  1.1  christos 		if (buf[0] == '\01' || buf[0] == '\02') {
    946  1.1  christos 			if (iamremote == 0)
    947  1.1  christos 				(void) atomicio(vwrite, STDERR_FILENO,
    948  1.1  christos 				    buf + 1, strlen(buf + 1));
    949  1.1  christos 			if (buf[0] == '\02')
    950  1.1  christos 				exit(1);
    951  1.1  christos 			++errs;
    952  1.1  christos 			continue;
    953  1.1  christos 		}
    954  1.1  christos 		if (buf[0] == 'E') {
    955  1.5  christos 			(void) atomicio(vwrite, remout, empty, 1);
    956  1.1  christos 			return;
    957  1.1  christos 		}
    958  1.1  christos 		if (ch == '\n')
    959  1.1  christos 			*--cp = 0;
    960  1.1  christos 
    961  1.1  christos 		cp = buf;
    962  1.1  christos 		if (*cp == 'T') {
    963  1.1  christos 			setimes++;
    964  1.1  christos 			cp++;
    965  1.9  christos 			if (!isdigit((unsigned char)*cp))
    966  1.9  christos 				SCREWUP("mtime.sec not present");
    967  1.9  christos 			ull = strtoull(cp, &cp, 10);
    968  1.1  christos 			if (!cp || *cp++ != ' ')
    969  1.1  christos 				SCREWUP("mtime.sec not delimited");
    970  1.9  christos 			if ((time_t)ull < 0 ||
    971  1.9  christos 			    (unsigned long long)(time_t)ull != ull)
    972  1.9  christos 				setimes = 0;	/* out of range */
    973  1.9  christos 			mtime.tv_sec = ull;
    974  1.1  christos 			mtime.tv_usec = strtol(cp, &cp, 10);
    975  1.9  christos 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
    976  1.9  christos 			    mtime.tv_usec > 999999)
    977  1.1  christos 				SCREWUP("mtime.usec not delimited");
    978  1.9  christos 			if (!isdigit((unsigned char)*cp))
    979  1.9  christos 				SCREWUP("atime.sec not present");
    980  1.9  christos 			ull = strtoull(cp, &cp, 10);
    981  1.1  christos 			if (!cp || *cp++ != ' ')
    982  1.1  christos 				SCREWUP("atime.sec not delimited");
    983  1.9  christos 			if ((time_t)ull < 0 ||
    984  1.9  christos 			    (unsigned long long)(time_t)ull != ull)
    985  1.9  christos 				setimes = 0;	/* out of range */
    986  1.9  christos 			atime.tv_sec = ull;
    987  1.1  christos 			atime.tv_usec = strtol(cp, &cp, 10);
    988  1.9  christos 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
    989  1.9  christos 			    atime.tv_usec > 999999)
    990  1.1  christos 				SCREWUP("atime.usec not delimited");
    991  1.5  christos 			(void) atomicio(vwrite, remout, empty, 1);
    992  1.1  christos 			continue;
    993  1.1  christos 		}
    994  1.1  christos 		if (*cp != 'C' && *cp != 'D') {
    995  1.1  christos 			/*
    996  1.1  christos 			 * Check for the case "rcp remote:foo\* local:bar".
    997  1.1  christos 			 * In this case, the line "No match." can be returned
    998  1.1  christos 			 * by the shell before the rcp command on the remote is
    999  1.1  christos 			 * executed so the ^Aerror_message convention isn't
   1000  1.1  christos 			 * followed.
   1001  1.1  christos 			 */
   1002  1.1  christos 			if (first) {
   1003  1.1  christos 				run_err("%s", cp);
   1004  1.1  christos 				exit(1);
   1005  1.1  christos 			}
   1006  1.1  christos 			SCREWUP("expected control record");
   1007  1.1  christos 		}
   1008  1.1  christos 		mode = 0;
   1009  1.1  christos 		for (++cp; cp < buf + 5; cp++) {
   1010  1.1  christos 			if (*cp < '0' || *cp > '7')
   1011  1.1  christos 				SCREWUP("bad mode");
   1012  1.1  christos 			mode = (mode << 3) | (*cp - '0');
   1013  1.1  christos 		}
   1014  1.1  christos 		if (*cp++ != ' ')
   1015  1.1  christos 			SCREWUP("mode not delimited");
   1016  1.1  christos 
   1017  1.2  christos 		for (size = 0; isdigit((unsigned char)*cp);)
   1018  1.1  christos 			size = size * 10 + (*cp++ - '0');
   1019  1.1  christos 		if (*cp++ != ' ')
   1020  1.1  christos 			SCREWUP("size not delimited");
   1021  1.1  christos 		if ((strchr(cp, '/') != NULL) || (strcmp(cp, "..") == 0)) {
   1022  1.1  christos 			run_err("error: unexpected filename: %s", cp);
   1023  1.1  christos 			exit(1);
   1024  1.1  christos 		}
   1025  1.1  christos 		if (targisdir) {
   1026  1.1  christos 			static char *namebuf;
   1027  1.1  christos 			static size_t cursize;
   1028  1.1  christos 			size_t need;
   1029  1.1  christos 
   1030  1.1  christos 			need = strlen(targ) + strlen(cp) + 250;
   1031  1.1  christos 			if (need > cursize) {
   1032  1.9  christos 				free(namebuf);
   1033  1.1  christos 				namebuf = xmalloc(need);
   1034  1.1  christos 				cursize = need;
   1035  1.1  christos 			}
   1036  1.1  christos 			(void) snprintf(namebuf, need, "%s%s%s", targ,
   1037  1.1  christos 			    strcmp(targ, "/") ? "/" : "", cp);
   1038  1.1  christos 			np = namebuf;
   1039  1.1  christos 		} else
   1040  1.1  christos 			np = targ;
   1041  1.1  christos 		curfile = cp;
   1042  1.1  christos 		exists = stat(np, &stb) == 0;
   1043  1.1  christos 		if (buf[0] == 'D') {
   1044  1.1  christos 			int mod_flag = pflag;
   1045  1.1  christos 			if (!iamrecursive)
   1046  1.1  christos 				SCREWUP("received directory without -r");
   1047  1.1  christos 			if (exists) {
   1048  1.1  christos 				if (!S_ISDIR(stb.st_mode)) {
   1049  1.1  christos 					errno = ENOTDIR;
   1050  1.1  christos 					goto bad;
   1051  1.1  christos 				}
   1052  1.1  christos 				if (pflag)
   1053  1.1  christos 					(void) chmod(np, mode);
   1054  1.1  christos 			} else {
   1055  1.1  christos 				/* Handle copying from a read-only
   1056  1.1  christos 				   directory */
   1057  1.1  christos 				mod_flag = 1;
   1058  1.1  christos 				if (mkdir(np, mode | S_IRWXU) < 0)
   1059  1.1  christos 					goto bad;
   1060  1.1  christos 			}
   1061  1.1  christos 			vect[0] = xstrdup(np);
   1062  1.1  christos 			sink(1, vect);
   1063  1.1  christos 			if (setimes) {
   1064  1.1  christos 				setimes = 0;
   1065  1.1  christos 				if (utimes(vect[0], tv) < 0)
   1066  1.1  christos 					run_err("%s: set times: %s",
   1067  1.1  christos 					    vect[0], strerror(errno));
   1068  1.1  christos 			}
   1069  1.1  christos 			if (mod_flag)
   1070  1.1  christos 				(void) chmod(vect[0], mode);
   1071  1.9  christos 			free(vect[0]);
   1072  1.1  christos 			continue;
   1073  1.1  christos 		}
   1074  1.1  christos 		omode = mode;
   1075  1.9  christos 		mode |= S_IWUSR;
   1076  1.1  christos 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
   1077  1.1  christos bad:			run_err("%s: %s", np, strerror(errno));
   1078  1.1  christos 			continue;
   1079  1.1  christos 		}
   1080  1.5  christos 		(void) atomicio(vwrite, remout, empty, 1);
   1081  1.1  christos 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
   1082  1.1  christos 			(void) close(ofd);
   1083  1.1  christos 			continue;
   1084  1.1  christos 		}
   1085  1.1  christos 		cp = bp->buf;
   1086  1.1  christos 		wrerr = NO;
   1087  1.1  christos 
   1088  1.1  christos 		statbytes = 0;
   1089  1.1  christos 		if (showprogress)
   1090  1.1  christos 			start_progress_meter(curfile, size, &statbytes);
   1091  1.1  christos 		set_nonblock(remin);
   1092  1.1  christos 		for (count = i = 0; i < size; i += bp->cnt) {
   1093  1.1  christos 			amt = bp->cnt;
   1094  1.1  christos 			if (i + amt > size)
   1095  1.1  christos 				amt = size - i;
   1096  1.1  christos 			count += amt;
   1097  1.1  christos 			do {
   1098  1.5  christos 				j = atomicio6(read, remin, cp, amt,
   1099  1.5  christos 				    scpio, &statbytes);
   1100  1.1  christos 				if (j == 0) {
   1101  1.1  christos 					run_err("%s", j != EPIPE ?
   1102  1.1  christos 					    strerror(errno) :
   1103  1.1  christos 					    "dropped connection");
   1104  1.1  christos 					exit(1);
   1105  1.1  christos 				}
   1106  1.1  christos 				amt -= j;
   1107  1.1  christos 				cp += j;
   1108  1.1  christos 			} while (amt > 0);
   1109  1.1  christos 
   1110  1.1  christos 			if (count == bp->cnt) {
   1111  1.1  christos 				/* Keep reading so we stay sync'd up. */
   1112  1.1  christos 				if (wrerr == NO) {
   1113  1.1  christos 					if (atomicio(vwrite, ofd, bp->buf,
   1114  1.1  christos 					    count) != count) {
   1115  1.1  christos 						wrerr = YES;
   1116  1.1  christos 						wrerrno = errno;
   1117  1.1  christos 					}
   1118  1.1  christos 				}
   1119  1.1  christos 				count = 0;
   1120  1.1  christos 				cp = bp->buf;
   1121  1.1  christos 			}
   1122  1.1  christos 		}
   1123  1.1  christos 		unset_nonblock(remin);
   1124  1.1  christos 		if (showprogress)
   1125  1.1  christos 			stop_progress_meter();
   1126  1.1  christos 		if (count != 0 && wrerr == NO &&
   1127  1.1  christos 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
   1128  1.1  christos 			wrerr = YES;
   1129  1.1  christos 			wrerrno = errno;
   1130  1.1  christos 		}
   1131  1.1  christos 		if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
   1132  1.1  christos 		    ftruncate(ofd, size) != 0) {
   1133  1.1  christos 			run_err("%s: truncate: %s", np, strerror(errno));
   1134  1.1  christos 			wrerr = DISPLAYED;
   1135  1.1  christos 		}
   1136  1.1  christos 		if (pflag) {
   1137  1.1  christos 			if (exists || omode != mode)
   1138  1.1  christos 				if (fchmod(ofd, omode)) {
   1139  1.1  christos 					run_err("%s: set mode: %s",
   1140  1.1  christos 					    np, strerror(errno));
   1141  1.1  christos 					wrerr = DISPLAYED;
   1142  1.1  christos 				}
   1143  1.1  christos 		} else {
   1144  1.1  christos 			if (!exists && omode != mode)
   1145  1.1  christos 				if (fchmod(ofd, omode & ~mask)) {
   1146  1.1  christos 					run_err("%s: set mode: %s",
   1147  1.1  christos 					    np, strerror(errno));
   1148  1.1  christos 					wrerr = DISPLAYED;
   1149  1.1  christos 				}
   1150  1.1  christos 		}
   1151  1.1  christos 		if (close(ofd) == -1) {
   1152  1.1  christos 			wrerr = YES;
   1153  1.1  christos 			wrerrno = errno;
   1154  1.1  christos 		}
   1155  1.1  christos 		(void) response();
   1156  1.1  christos 		if (setimes && wrerr == NO) {
   1157  1.1  christos 			setimes = 0;
   1158  1.1  christos 			if (utimes(np, tv) < 0) {
   1159  1.1  christos 				run_err("%s: set times: %s",
   1160  1.1  christos 				    np, strerror(errno));
   1161  1.1  christos 				wrerr = DISPLAYED;
   1162  1.1  christos 			}
   1163  1.1  christos 		}
   1164  1.1  christos 		switch (wrerr) {
   1165  1.1  christos 		case YES:
   1166  1.1  christos 			run_err("%s: %s", np, strerror(wrerrno));
   1167  1.1  christos 			break;
   1168  1.1  christos 		case NO:
   1169  1.5  christos 			(void) atomicio(vwrite, remout, empty, 1);
   1170  1.1  christos 			break;
   1171  1.1  christos 		case DISPLAYED:
   1172  1.1  christos 			break;
   1173  1.1  christos 		}
   1174  1.1  christos 	}
   1175  1.1  christos screwup:
   1176  1.1  christos 	run_err("protocol error: %s", why);
   1177  1.1  christos 	exit(1);
   1178  1.1  christos }
   1179  1.1  christos 
   1180  1.1  christos int
   1181  1.1  christos response(void)
   1182  1.1  christos {
   1183  1.1  christos 	char ch, *cp, resp, rbuf[2048];
   1184  1.1  christos 
   1185  1.1  christos 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
   1186  1.1  christos 		lostconn(0);
   1187  1.1  christos 
   1188  1.1  christos 	cp = rbuf;
   1189  1.1  christos 	switch (resp) {
   1190  1.1  christos 	case 0:		/* ok */
   1191  1.1  christos 		return (0);
   1192  1.1  christos 	default:
   1193  1.1  christos 		*cp++ = resp;
   1194  1.1  christos 		/* FALLTHROUGH */
   1195  1.1  christos 	case 1:		/* error, followed by error msg */
   1196  1.1  christos 	case 2:		/* fatal error, "" */
   1197  1.1  christos 		do {
   1198  1.1  christos 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
   1199  1.1  christos 				lostconn(0);
   1200  1.1  christos 			*cp++ = ch;
   1201  1.1  christos 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
   1202  1.1  christos 
   1203  1.1  christos 		if (!iamremote)
   1204  1.1  christos 			(void) atomicio(vwrite, STDERR_FILENO, rbuf, cp - rbuf);
   1205  1.1  christos 		++errs;
   1206  1.1  christos 		if (resp == 1)
   1207  1.1  christos 			return (-1);
   1208  1.1  christos 		exit(1);
   1209  1.1  christos 	}
   1210  1.1  christos 	/* NOTREACHED */
   1211  1.1  christos }
   1212  1.1  christos 
   1213  1.1  christos void
   1214  1.1  christos usage(void)
   1215  1.1  christos {
   1216  1.1  christos 	(void) fprintf(stderr,
   1217  1.5  christos 	    "usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
   1218  1.1  christos 	    "           [-l limit] [-o ssh_option] [-P port] [-S program]\n"
   1219  1.1  christos 	    "           [[user@]host1:]file1 ... [[user@]host2:]file2\n");
   1220  1.1  christos 	exit(1);
   1221  1.1  christos }
   1222  1.1  christos 
   1223  1.1  christos void
   1224  1.1  christos run_err(const char *fmt,...)
   1225  1.1  christos {
   1226  1.1  christos 	static FILE *fp;
   1227  1.1  christos 	va_list ap;
   1228  1.1  christos 
   1229  1.1  christos 	++errs;
   1230  1.1  christos 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
   1231  1.1  christos 		(void) fprintf(fp, "%c", 0x01);
   1232  1.1  christos 		(void) fprintf(fp, "scp: ");
   1233  1.1  christos 		va_start(ap, fmt);
   1234  1.1  christos 		(void) vfprintf(fp, fmt, ap);
   1235  1.1  christos 		va_end(ap);
   1236  1.1  christos 		(void) fprintf(fp, "\n");
   1237  1.1  christos 		(void) fflush(fp);
   1238  1.1  christos 	}
   1239  1.1  christos 
   1240  1.1  christos 	if (!iamremote) {
   1241  1.1  christos 		va_start(ap, fmt);
   1242  1.1  christos 		vfprintf(stderr, fmt, ap);
   1243  1.1  christos 		va_end(ap);
   1244  1.1  christos 		fprintf(stderr, "\n");
   1245  1.1  christos 	}
   1246  1.1  christos }
   1247  1.1  christos 
   1248  1.1  christos void
   1249  1.1  christos verifydir(char *cp)
   1250  1.1  christos {
   1251  1.1  christos 	struct stat stb;
   1252  1.1  christos 
   1253  1.1  christos 	if (!stat(cp, &stb)) {
   1254  1.1  christos 		if (S_ISDIR(stb.st_mode))
   1255  1.1  christos 			return;
   1256  1.1  christos 		errno = ENOTDIR;
   1257  1.1  christos 	}
   1258  1.1  christos 	run_err("%s: %s", cp, strerror(errno));
   1259  1.1  christos 	killchild(0);
   1260  1.1  christos }
   1261  1.1  christos 
   1262  1.1  christos int
   1263  1.1  christos okname(char *cp0)
   1264  1.1  christos {
   1265  1.1  christos 	int c;
   1266  1.1  christos 	char *cp;
   1267  1.1  christos 
   1268  1.1  christos 	cp = cp0;
   1269  1.1  christos 	do {
   1270  1.1  christos 		c = (int)*cp;
   1271  1.1  christos 		if (c & 0200)
   1272  1.1  christos 			goto bad;
   1273  1.1  christos 		if (!isalpha(c) && !isdigit(c)) {
   1274  1.1  christos 			switch (c) {
   1275  1.1  christos 			case '\'':
   1276  1.1  christos 			case '"':
   1277  1.1  christos 			case '`':
   1278  1.1  christos 			case ' ':
   1279  1.1  christos 			case '#':
   1280  1.1  christos 				goto bad;
   1281  1.1  christos 			default:
   1282  1.1  christos 				break;
   1283  1.1  christos 			}
   1284  1.1  christos 		}
   1285  1.1  christos 	} while (*++cp);
   1286  1.1  christos 	return (1);
   1287  1.1  christos 
   1288  1.1  christos bad:	fprintf(stderr, "%s: invalid user name\n", cp0);
   1289  1.1  christos 	return (0);
   1290  1.1  christos }
   1291  1.1  christos 
   1292  1.1  christos BUF *
   1293  1.1  christos allocbuf(BUF *bp, int fd, int blksize)
   1294  1.1  christos {
   1295  1.1  christos 	size_t size;
   1296  1.1  christos 	struct stat stb;
   1297  1.1  christos 
   1298  1.1  christos 	if (fstat(fd, &stb) < 0) {
   1299  1.1  christos 		run_err("fstat: %s", strerror(errno));
   1300  1.1  christos 		return (0);
   1301  1.1  christos 	}
   1302  1.1  christos 	size = roundup(stb.st_blksize, blksize);
   1303  1.1  christos 	if (size == 0)
   1304  1.1  christos 		size = blksize;
   1305  1.1  christos 	if (bp->cnt >= size)
   1306  1.1  christos 		return (bp);
   1307  1.1  christos 	if (bp->buf == NULL)
   1308  1.1  christos 		bp->buf = xmalloc(size);
   1309  1.1  christos 	else
   1310  1.1  christos 		bp->buf = xrealloc(bp->buf, 1, size);
   1311  1.1  christos 	memset(bp->buf, 0, size);
   1312  1.1  christos 	bp->cnt = size;
   1313  1.1  christos 	return (bp);
   1314  1.1  christos }
   1315  1.1  christos 
   1316  1.6     joerg static void
   1317  1.1  christos lostconn(int signo)
   1318  1.1  christos {
   1319  1.1  christos 	if (!iamremote)
   1320  1.9  christos 		(void)write(STDERR_FILENO, "lost connection\n", 16);
   1321  1.1  christos 	if (signo)
   1322  1.1  christos 		_exit(1);
   1323  1.1  christos 	else
   1324  1.1  christos 		exit(1);
   1325  1.1  christos }
   1326