scp.c 39.3 KB
Newer Older
1
/* $OpenBSD: scp.c,v 1.197 2018/06/01 04:31:48 dtucker Exp $ */
Damien Miller's avatar
Damien Miller committed
2
/*
3 4
 * scp - secure remote copy.  This is basically patched BSD rcp which
 * uses ssh to do the data transfer (instead of using rcmd).
Damien Miller's avatar
Damien Miller committed
5
 *
6 7
 * NOTE: This version should NOT be suid root.  (This uses ssh to
 * do the transfer and ssh has the necessary privileges.)
Damien Miller's avatar
Damien Miller committed
8
 *
9
 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi>
Damien Miller's avatar
Damien Miller committed
10
 *
11 12 13 14 15 16 17
 * As far as I am concerned, the code I have written for this software
 * can be used freely for any purpose.  Any derived versions of this
 * software must be clearly marked as such, and if the derived work is
 * incompatible with the protocol description in the RFC file, it must be
 * called by a name other than "ssh" or "Secure Shell".
 */
/*
18 19
 * Copyright (c) 1999 Theo de Raadt.  All rights reserved.
 * Copyright (c) 1999 Aaron Campbell.  All rights reserved.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
Damien Miller's avatar
Damien Miller committed
41 42

/*
43 44
 * Parts from:
 *
Damien Miller's avatar
Damien Miller committed
45 46 47 48 49 50 51 52 53 54 55
 * Copyright (c) 1983, 1990, 1992, 1993, 1995
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
56
 * 3. Neither the name of the University nor the names of its contributors
Damien Miller's avatar
Damien Miller committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

#include "includes.h"
75 76

#include <sys/types.h>
77 78 79
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
80 81 82 83 84 85
#ifdef HAVE_POLL_H
#include <poll.h>
#else
# ifdef HAVE_SYS_POLL_H
#  include <sys/poll.h>
# endif
86
#endif
87 88 89
#ifdef HAVE_SYS_TIME_H
# include <sys/time.h>
#endif
90
#include <sys/wait.h>
91
#include <sys/uio.h>
92

93
#include <ctype.h>
94
#include <dirent.h>
95
#include <errno.h>
96
#include <fcntl.h>
97
#include <fnmatch.h>
deraadt@openbsd.org's avatar
deraadt@openbsd.org committed
98
#include <limits.h>
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
99
#include <locale.h>
100
#include <pwd.h>
101
#include <signal.h>
102
#include <stdarg.h>
103
#ifdef HAVE_STDINT_H
millert@openbsd.org's avatar
millert@openbsd.org committed
104
#include <stdint.h>
105
#endif
106
#include <stdio.h>
107
#include <stdlib.h>
108
#include <string.h>
109
#include <time.h>
110
#include <unistd.h>
111
#if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS)
112 113
#include <vis.h>
#endif
Damien Miller's avatar
Damien Miller committed
114 115

#include "xmalloc.h"
millert@openbsd.org's avatar
millert@openbsd.org committed
116
#include "ssh.h"
117 118 119
#include "atomicio.h"
#include "pathnames.h"
#include "log.h"
120
#include "misc.h"
121
#include "progressmeter.h"
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
122
#include "utf8.h"
Damien Miller's avatar
Damien Miller committed
123

124 125
extern char *__progname;

126 127
#define COPY_BUFLEN	16384

millert@openbsd.org's avatar
millert@openbsd.org committed
128 129
int do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout);
int do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout);
130

131 132
/* Struct for addargs */
arglist args;
133
arglist remote_remote_args;
134

135
/* Bandwidth limit */
136 137
long long limit_kbps = 0;
struct bwlimit bwlimit;
138

Damien Miller's avatar
Damien Miller committed
139 140 141 142
/* Name of current file being transferred. */
char *curfile;

/* This is set to non-zero to enable verbose mode. */
143
int verbose_mode = 0;
Damien Miller's avatar
Damien Miller committed
144 145 146 147

/* This is set to zero if the progressmeter is not desired. */
int showprogress = 1;

148 149 150 151 152 153
/*
 * This is set to non-zero if remote-remote copy should be piped
 * through this process.
 */
int throughlocal = 0;

millert@openbsd.org's avatar
millert@openbsd.org committed
154 155 156
/* Non-standard port to use for the ssh connection or -1. */
int sshport = -1;

157
/* This is the program to execute for the secured connection. ("ssh" or -S) */
158
char *ssh_program = _PATH_SSH_PROGRAM;
159

160
/* This is used to store the pid of ssh_program */
161 162 163 164 165
pid_t do_cmd_pid = -1;

static void
killchild(int signo)
{
166
	if (do_cmd_pid > 1) {
167
		kill(do_cmd_pid, signo ? signo : SIGTERM);
168 169
		waitpid(do_cmd_pid, NULL, 0);
	}
170

171 172 173
	if (signo)
		_exit(1);
	exit(1);
174
}
175

176 177 178 179 180 181 182 183 184 185 186 187 188 189
static void
suspchild(int signo)
{
	int status;

	if (do_cmd_pid > 1) {
		kill(do_cmd_pid, signo);
		while (waitpid(do_cmd_pid, &status, WUNTRACED) == -1 &&
		    errno == EINTR)
			;
		kill(getpid(), SIGSTOP);
	}
}

190 191 192 193 194 195 196 197 198 199 200 201
static int
do_local_cmd(arglist *a)
{
	u_int i;
	int status;
	pid_t pid;

	if (a->num == 0)
		fatal("do_local_cmd: no arguments");

	if (verbose_mode) {
		fprintf(stderr, "Executing:");
202 203 204 205 206 207 208 209 210 211
		for (i = 0; i < a->num; i++) {
			if (i == 0)
				fmprintf(stderr, " %s", a->list[i]);
			else
				/*
				 * TODO: misbehaves if a->list[i] contains a
				 * single quote
				 */
				fmprintf(stderr, " '%s'", a->list[i]);
		}
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
		fprintf(stderr, "\n");
	}
	if ((pid = fork()) == -1)
		fatal("do_local_cmd: fork: %s", strerror(errno));

	if (pid == 0) {
		execvp(a->list[0], a->list);
		perror(a->list[0]);
		exit(1);
	}

	do_cmd_pid = pid;
	signal(SIGTERM, killchild);
	signal(SIGINT, killchild);
	signal(SIGHUP, killchild);

	while (waitpid(pid, &status, 0) == -1)
		if (errno != EINTR)
			fatal("do_local_cmd: waitpid: %s", strerror(errno));

	do_cmd_pid = -1;

	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
		return (-1);

	return (0);
}

Damien Miller's avatar
Damien Miller committed
240 241 242 243 244
/*
 * This function executes the given command as the specified user on the
 * given host.  This returns < 0 if execution fails, and >= 0 otherwise. This
 * assigns the input and output file descriptors on success.
 */
Damien Miller's avatar
Damien Miller committed
245

Damien Miller's avatar
Damien Miller committed
246
int
millert@openbsd.org's avatar
millert@openbsd.org committed
247
do_cmd(char *host, char *remuser, int port, char *cmd, int *fdin, int *fdout)
Damien Miller's avatar
Damien Miller committed
248
{
249 250 251
	int pin[2], pout[2], reserved[2];

	if (verbose_mode)
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
252
		fmprintf(stderr,
253 254 255
		    "Executing: program %s host %s, user %s, command %s\n",
		    ssh_program, host,
		    remuser ? remuser : "(unspecified)", cmd);
256

millert@openbsd.org's avatar
millert@openbsd.org committed
257 258 259
	if (port == -1)
		port = sshport;

Damien Miller's avatar
Damien Miller committed
260 261 262 263
	/*
	 * Reserve two descriptors so that the real pipes won't get
	 * descriptors 0 and 1 because that will screw up dup2 below.
	 */
264 265
	if (pipe(reserved) < 0)
		fatal("pipe: %s", strerror(errno));
266 267 268 269 270 271 272 273 274 275 276

	/* Create a socket pair for communicating with ssh. */
	if (pipe(pin) < 0)
		fatal("pipe: %s", strerror(errno));
	if (pipe(pout) < 0)
		fatal("pipe: %s", strerror(errno));

	/* Free the reserved descriptors. */
	close(reserved[0]);
	close(reserved[1]);

277 278 279 280
	signal(SIGTSTP, suspchild);
	signal(SIGTTIN, suspchild);
	signal(SIGTTOU, suspchild);

281
	/* Fork a child to execute the command on the remote host using ssh. */
282 283
	do_cmd_pid = fork();
	if (do_cmd_pid == 0) {
284 285 286 287 288 289 290 291
		/* Child. */
		close(pin[1]);
		close(pout[0]);
		dup2(pin[0], 0);
		dup2(pout[1], 1);
		close(pin[0]);
		close(pout[1]);

292
		replacearg(&args, 0, "%s", ssh_program);
millert@openbsd.org's avatar
millert@openbsd.org committed
293 294 295 296
		if (port != -1) {
			addargs(&args, "-p");
			addargs(&args, "%d", port);
		}
297 298 299 300 301
		if (remuser != NULL) {
			addargs(&args, "-l");
			addargs(&args, "%s", remuser);
		}
		addargs(&args, "--");
302 303
		addargs(&args, "%s", host);
		addargs(&args, "%s", cmd);
304

305
		execvp(ssh_program, args.list);
306
		perror(ssh_program);
307
		exit(1);
308 309
	} else if (do_cmd_pid == -1) {
		fatal("fork: %s", strerror(errno));
Damien Miller's avatar
Damien Miller committed
310
	}
311 312 313 314 315
	/* Parent.  Close the other side, and return the local side. */
	close(pin[0]);
	*fdout = pin[1];
	close(pout[1]);
	*fdin = pout[0];
316 317 318
	signal(SIGTERM, killchild);
	signal(SIGINT, killchild);
	signal(SIGHUP, killchild);
319
	return 0;
Damien Miller's avatar
Damien Miller committed
320 321
}

322
/*
323
 * This function executes a command similar to do_cmd(), but expects the
324 325 326 327
 * input and output descriptors to be setup by a previous call to do_cmd().
 * This way the input and output of two commands can be connected.
 */
int
millert@openbsd.org's avatar
millert@openbsd.org committed
328
do_cmd2(char *host, char *remuser, int port, char *cmd, int fdin, int fdout)
329 330 331 332 333
{
	pid_t pid;
	int status;

	if (verbose_mode)
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
334
		fmprintf(stderr,
335 336 337 338
		    "Executing: 2nd program %s host %s, user %s, command %s\n",
		    ssh_program, host,
		    remuser ? remuser : "(unspecified)", cmd);

millert@openbsd.org's avatar
millert@openbsd.org committed
339 340 341
	if (port == -1)
		port = sshport;

342 343 344 345 346 347 348
	/* Fork a child to execute the command on the remote host using ssh. */
	pid = fork();
	if (pid == 0) {
		dup2(fdin, 0);
		dup2(fdout, 1);

		replacearg(&args, 0, "%s", ssh_program);
millert@openbsd.org's avatar
millert@openbsd.org committed
349 350 351 352
		if (port != -1) {
			addargs(&args, "-p");
			addargs(&args, "%d", port);
		}
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
		if (remuser != NULL) {
			addargs(&args, "-l");
			addargs(&args, "%s", remuser);
		}
		addargs(&args, "--");
		addargs(&args, "%s", host);
		addargs(&args, "%s", cmd);

		execvp(ssh_program, args.list);
		perror(ssh_program);
		exit(1);
	} else if (pid == -1) {
		fatal("fork: %s", strerror(errno));
	}
	while (waitpid(pid, &status, 0) == -1)
		if (errno != EINTR)
			fatal("do_cmd2: waitpid: %s", strerror(errno));
	return 0;
}

Damien Miller's avatar
Damien Miller committed
373
typedef struct {
374
	size_t cnt;
Damien Miller's avatar
Damien Miller committed
375 376 377
	char *buf;
} BUF;

378 379 380 381 382
BUF *allocbuf(BUF *, int, int);
void lostconn(int);
int okname(char *);
void run_err(const char *,...);
void verifydir(char *);
Damien Miller's avatar
Damien Miller committed
383 384

struct passwd *pwd;
385
uid_t userid;
Damien Miller's avatar
Damien Miller committed
386
int errs, remin, remout;
387
int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory;
Damien Miller's avatar
Damien Miller committed
388 389 390 391

#define	CMDNEEDS	64
char cmd[CMDNEEDS];		/* must hold "rcp -r -p -d\0" */

392 393
int response(void);
void rsource(char *, struct stat *);
394
void sink(int, char *[], const char *);
395 396
void source(int, char *[]);
void tolocal(int, char *[]);
millert@openbsd.org's avatar
millert@openbsd.org committed
397
void toremote(int, char *[]);
398
void usage(void);
Damien Miller's avatar
Damien Miller committed
399 400

int
401
main(int argc, char **argv)
Damien Miller's avatar
Damien Miller committed
402
{
403
	int ch, fflag, tflag, status, n;
millert@openbsd.org's avatar
millert@openbsd.org committed
404
	char **newargv;
405
	const char *errstr;
Damien Miller's avatar
Damien Miller committed
406 407 408
	extern char *optarg;
	extern int optind;

409 410 411
	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
	sanitise_stdfd();

412
	msetlocale();
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
413

414
	/* Copy argv, because we modify it */
deraadt@openbsd.org's avatar
deraadt@openbsd.org committed
415
	newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv));
416 417 418 419
	for (n = 0; n < argc; n++)
		newargv[n] = xstrdup(argv[n]);
	argv = newargv;

420
	__progname = ssh_get_progname(argv[0]);
421

422
	memset(&args, '\0', sizeof(args));
423 424
	memset(&remote_remote_args, '\0', sizeof(remote_remote_args));
	args.list = remote_remote_args.list = NULL;
425
	addargs(&args, "%s", ssh_program);
426
	addargs(&args, "-x");
427 428 429
	addargs(&args, "-oForwardAgent=no");
	addargs(&args, "-oPermitLocalCommand=no");
	addargs(&args, "-oClearAllForwardings=yes");
djm@openbsd.org's avatar
djm@openbsd.org committed
430 431
	addargs(&args, "-oRemoteCommand=none");
	addargs(&args, "-oRequestTTY=no");
432

433 434 435
	fflag = Tflag = tflag = 0;
	while ((ch = getopt(argc, argv,
	    "dfl:prtTvBCc:i:P:q12346S:o:F:")) != -1) {
436 437
		switch (ch) {
		/* User-visible flags. */
438
		case '1':
djm@openbsd.org's avatar
djm@openbsd.org committed
439 440
			fatal("SSH protocol v.1 is no longer supported");
			break;
441
		case '2':
djm@openbsd.org's avatar
djm@openbsd.org committed
442 443
			/* Ignored */
			break;
444 445
		case '4':
		case '6':
446
		case 'C':
447
			addargs(&args, "-%c", ch);
448
			addargs(&remote_remote_args, "-%c", ch);
449
			break;
450 451 452
		case '3':
			throughlocal = 1;
			break;
453 454 455
		case 'o':
		case 'c':
		case 'i':
456
		case 'F':
457 458
			addargs(&remote_remote_args, "-%c", ch);
			addargs(&remote_remote_args, "%s", optarg);
459 460
			addargs(&args, "-%c", ch);
			addargs(&args, "%s", optarg);
Damien Miller's avatar
Damien Miller committed
461 462
			break;
		case 'P':
millert@openbsd.org's avatar
millert@openbsd.org committed
463 464 465
			sshport = a2port(optarg);
			if (sshport <= 0)
				fatal("bad port \"%s\"\n", optarg);
466 467
			break;
		case 'B':
468 469
			addargs(&remote_remote_args, "-oBatchmode=yes");
			addargs(&args, "-oBatchmode=yes");
470
			break;
471
		case 'l':
472 473 474
			limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024,
			    &errstr);
			if (errstr != NULL)
475
				usage();
476 477
			limit_kbps *= 1024; /* kbps */
			bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN);
478
			break;
479 480
		case 'p':
			pflag = 1;
481
			break;
Damien Miller's avatar
Damien Miller committed
482 483 484
		case 'r':
			iamrecursive = 1;
			break;
485
		case 'S':
486 487 488
			ssh_program = xstrdup(optarg);
			break;
		case 'v':
489
			addargs(&args, "-v");
490
			addargs(&remote_remote_args, "-v");
491 492 493
			verbose_mode = 1;
			break;
		case 'q':
494
			addargs(&args, "-q");
495
			addargs(&remote_remote_args, "-q");
496
			showprogress = 0;
497 498
			break;

499
		/* Server options. */
Damien Miller's avatar
Damien Miller committed
500 501 502
		case 'd':
			targetshouldbedirectory = 1;
			break;
503
		case 'f':	/* "from" */
Damien Miller's avatar
Damien Miller committed
504 505 506
			iamremote = 1;
			fflag = 1;
			break;
507
		case 't':	/* "to" */
Damien Miller's avatar
Damien Miller committed
508 509
			iamremote = 1;
			tflag = 1;
510 511 512
#ifdef HAVE_CYGWIN
			setmode(0, O_BINARY);
#endif
Damien Miller's avatar
Damien Miller committed
513
			break;
514 515 516
		case 'T':
			Tflag = 1;
			break;
Damien Miller's avatar
Damien Miller committed
517 518 519
		default:
			usage();
		}
520
	}
Damien Miller's avatar
Damien Miller committed
521 522 523 524
	argc -= optind;
	argv += optind;

	if ((pwd = getpwuid(userid = getuid())) == NULL)
525
		fatal("unknown user %u", (u_int) userid);
Damien Miller's avatar
Damien Miller committed
526

527
	if (!isatty(STDOUT_FILENO))
Damien Miller's avatar
Damien Miller committed
528 529
		showprogress = 0;

deraadt@openbsd.org's avatar
deraadt@openbsd.org committed
530 531 532 533 534 535 536 537 538 539
	if (pflag) {
		/* Cannot pledge: -p allows setuid/setgid files... */
	} else {
		if (pledge("stdio rpath wpath cpath fattr tty proc exec",
		    NULL) == -1) {
			perror("pledge");
			exit(1);
		}
	}

Damien Miller's avatar
Damien Miller committed
540 541 542
	remin = STDIN_FILENO;
	remout = STDOUT_FILENO;

543
	if (fflag) {
544 545
		/* Follow "protocol", send data. */
		(void) response();
Damien Miller's avatar
Damien Miller committed
546 547 548
		source(argc, argv);
		exit(errs != 0);
	}
549 550
	if (tflag) {
		/* Receive data. */
551
		sink(argc, argv, NULL);
Damien Miller's avatar
Damien Miller committed
552 553 554 555 556 557 558 559
		exit(errs != 0);
	}
	if (argc < 2)
		usage();
	if (argc > 2)
		targetshouldbedirectory = 1;

	remin = remout = -1;
560
	do_cmd_pid = -1;
Damien Miller's avatar
Damien Miller committed
561
	/* Command to be executed on remote system using "ssh". */
562 563
	(void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s",
	    verbose_mode ? " -v" : "",
564 565
	    iamrecursive ? " -r" : "", pflag ? " -p" : "",
	    targetshouldbedirectory ? " -d" : "");
Damien Miller's avatar
Damien Miller committed
566

567
	(void) signal(SIGPIPE, lostconn);
Damien Miller's avatar
Damien Miller committed
568

millert@openbsd.org's avatar
millert@openbsd.org committed
569 570
	if (colon(argv[argc - 1]))	/* Dest is remote host. */
		toremote(argc, argv);
Damien Miller's avatar
Damien Miller committed
571 572 573
	else {
		if (targetshouldbedirectory)
			verifydir(argv[argc - 1]);
574
		tolocal(argc, argv);	/* Dest is local host. */
Damien Miller's avatar
Damien Miller committed
575
	}
576 577
	/*
	 * Finally check the exit status of the ssh process, if one was forked
578
	 * and no error has occurred yet
579 580 581 582 583 584 585 586 587 588 589 590 591
	 */
	if (do_cmd_pid != -1 && errs == 0) {
		if (remin != -1)
		    (void) close(remin);
		if (remout != -1)
		    (void) close(remout);
		if (waitpid(do_cmd_pid, &status, 0) == -1)
			errs = 1;
		else {
			if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
				errs = 1;
		}
	}
Damien Miller's avatar
Damien Miller committed
592 593 594
	exit(errs != 0);
}

595 596 597
/* Callback from atomicio6 to update progress meter and limit bandwidth */
static int
scpio(void *_cnt, size_t s)
598
{
599 600 601
	off_t *cnt = (off_t *)_cnt;

	*cnt += s;
602
	refresh_progress_meter(0);
603 604 605
	if (limit_kbps > 0)
		bandwidth_limit(&bwlimit, s);
	return 0;
606 607
}

608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
static int
do_times(int fd, int verb, const struct stat *sb)
{
	/* strlen(2^64) == 20; strlen(10^6) == 7 */
	char buf[(20 + 7 + 2) * 2 + 2];

	(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
	    (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
	    (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
	if (verb) {
		fprintf(stderr, "File mtime %lld atime %lld\n",
		    (long long)sb->st_mtime, (long long)sb->st_atime);
		fprintf(stderr, "Sending file timestamps: %s", buf);
	}
	(void) atomicio(vwrite, fd, buf, strlen(buf));
	return (response());
}

millert@openbsd.org's avatar
millert@openbsd.org committed
626 627 628 629 630 631 632 633 634 635 636 637
static int
parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
     char **pathp)
{
	int r;

	r = parse_uri("scp", uri, userp, hostp, portp, pathp);
	if (r == 0 && *pathp == NULL)
		*pathp = xstrdup(".");
	return r;
}

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
/* Appends a string to an array; returns 0 on success, -1 on alloc failure */
static int
append(char *cp, char ***ap, size_t *np)
{
	char **tmp;

	if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL)
		return -1;
	tmp[(*np)] = cp;
	(*np)++;
	*ap = tmp;
	return 0;
}

/*
 * Finds the start and end of the first brace pair in the pattern.
 * returns 0 on success or -1 for invalid patterns.
 */
static int
find_brace(const char *pattern, int *startp, int *endp)
{
	int i;
	int in_bracket, brace_level;

	*startp = *endp = -1;
	in_bracket = brace_level = 0;
	for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) {
		switch (pattern[i]) {
		case '\\':
			/* skip next character */
			if (pattern[i + 1] != '\0')
				i++;
			break;
		case '[':
			in_bracket = 1;
			break;
		case ']':
			in_bracket = 0;
			break;
		case '{':
			if (in_bracket)
				break;
			if (pattern[i + 1] == '}') {
				/* Protect a single {}, for find(1), like csh */
				i++; /* skip */
				break;
			}
			if (*startp == -1)
				*startp = i;
			brace_level++;
			break;
		case '}':
			if (in_bracket)
				break;
			if (*startp < 0) {
				/* Unbalanced brace */
				return -1;
			}
			if (--brace_level <= 0)
				*endp = i;
			break;
		}
	}
	/* unbalanced brackets/braces */
	if (*endp < 0 && (*startp >= 0 || in_bracket))
		return -1;
	return 0;
}

/*
 * Assembles and records a successfully-expanded pattern, returns -1 on
 * alloc failure.
 */
static int
emit_expansion(const char *pattern, int brace_start, int brace_end,
    int sel_start, int sel_end, char ***patternsp, size_t *npatternsp)
{
	char *cp;
	int o = 0, tail_len = strlen(pattern + brace_end + 1);

	if ((cp = malloc(brace_start + (sel_end - sel_start) +
	    tail_len + 1)) == NULL)
		return -1;

	/* Pattern before initial brace */
	if (brace_start > 0) {
		memcpy(cp, pattern, brace_start);
		o = brace_start;
	}
	/* Current braced selection */
	if (sel_end - sel_start > 0) {
		memcpy(cp + o, pattern + sel_start,
		    sel_end - sel_start);
		o += sel_end - sel_start;
	}
	/* Remainder of pattern after closing brace */
	if (tail_len > 0) {
		memcpy(cp + o, pattern + brace_end + 1, tail_len);
		o += tail_len;
	}
	cp[o] = '\0';
	if (append(cp, patternsp, npatternsp) != 0) {
		free(cp);
		return -1;
	}
	return 0;
}

/*
 * Expand the first encountered brace in pattern, appending the expanded
 * patterns it yielded to the *patternsp array.
 *
 * Returns 0 on success or -1 on allocation failure.
 *
 * Signals whether expansion was performed via *expanded and whether
 * pattern was invalid via *invalid.
 */
static int
brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp,
    int *expanded, int *invalid)
{
	int i;
	int in_bracket, brace_start, brace_end, brace_level;
	int sel_start, sel_end;

	*invalid = *expanded = 0;

	if (find_brace(pattern, &brace_start, &brace_end) != 0) {
		*invalid = 1;
		return 0;
	} else if (brace_start == -1)
		return 0;

	in_bracket = brace_level = 0;
	for (i = sel_start = brace_start + 1; i < brace_end; i++) {
		switch (pattern[i]) {
		case '{':
			if (in_bracket)
				break;
			brace_level++;
			break;
		case '}':
			if (in_bracket)
				break;
			brace_level--;
			break;
		case '[':
			in_bracket = 1;
			break;
		case ']':
			in_bracket = 0;
			break;
		case '\\':
			if (i < brace_end - 1)
				i++; /* skip */
			break;
		}
		if (pattern[i] == ',' || i == brace_end - 1) {
			if (in_bracket || brace_level > 0)
				continue;
			/* End of a selection, emit an expanded pattern */

			/* Adjust end index for last selection */
			sel_end = (i == brace_end - 1) ? brace_end : i;
			if (emit_expansion(pattern, brace_start, brace_end,
			    sel_start, sel_end, patternsp, npatternsp) != 0)
				return -1;
			/* move on to the next selection */
			sel_start = i + 1;
			continue;
		}
	}
	if (in_bracket || brace_level > 0) {
		*invalid = 1;
		return 0;
	}
	/* success */
	*expanded = 1;
	return 0;
}

/* Expand braces from pattern. Returns 0 on success, -1 on failure */
static int
brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp)
{
	char *cp, *cp2, **active = NULL, **done = NULL;
	size_t i, nactive = 0, ndone = 0;
	int ret = -1, invalid = 0, expanded = 0;

	*patternsp = NULL;
	*npatternsp = 0;

	/* Start the worklist with the original pattern */
	if ((cp = strdup(pattern)) == NULL)
		return -1;
	if (append(cp, &active, &nactive) != 0) {
		free(cp);
		return -1;
	}
	while (nactive > 0) {
		cp = active[nactive - 1];
		nactive--;
		if (brace_expand_one(cp, &active, &nactive,
		    &expanded, &invalid) == -1) {
			free(cp);
			goto fail;
		}
		if (invalid)
			fatal("%s: invalid brace pattern \"%s\"", __func__, cp);
		if (expanded) {
			/*
			 * Current entry expanded to new entries on the
			 * active list; discard the progenitor pattern.
			 */
			free(cp);
			continue;
		}
		/*
		 * Pattern did not expand; append the finename component to
		 * the completed list
		 */
		if ((cp2 = strrchr(cp, '/')) != NULL)
			*cp2++ = '\0';
		else
			cp2 = cp;
		if (append(xstrdup(cp2), &done, &ndone) != 0) {
			free(cp);
			goto fail;
		}
		free(cp);
	}
	/* success */
	*patternsp = done;
	*npatternsp = ndone;
	done = NULL;
	ndone = 0;
	ret = 0;
 fail:
	for (i = 0; i < nactive; i++)
		free(active[i]);
	free(active);
	for (i = 0; i < ndone; i++)
		free(done[i]);
	free(done);
	return ret;
}

Damien Miller's avatar
Damien Miller committed
885
void
millert@openbsd.org's avatar
millert@openbsd.org committed
886
toremote(int argc, char **argv)
Damien Miller's avatar
Damien Miller committed
887
{
millert@openbsd.org's avatar
millert@openbsd.org committed
888 889 890
	char *suser = NULL, *host = NULL, *src = NULL;
	char *bp, *tuser, *thost, *targ;
	int sport = -1, tport = -1;
891
	arglist alist;
millert@openbsd.org's avatar
millert@openbsd.org committed
892
	int i, r;
893
	u_int j;
894 895 896

	memset(&alist, '\0', sizeof(alist));
	alist.list = NULL;
Damien Miller's avatar
Damien Miller committed
897

millert@openbsd.org's avatar
millert@openbsd.org committed
898
	/* Parse target */
millert@openbsd.org's avatar
millert@openbsd.org committed
899 900 901 902 903 904
	r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
	if (r == -1) {
		fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
		++errs;
		goto out;
	}
millert@openbsd.org's avatar
millert@openbsd.org committed
905 906
	if (r != 0) {
		if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
millert@openbsd.org's avatar
millert@openbsd.org committed
907 908 909
		    &targ) == -1) {
			fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
			++errs;
millert@openbsd.org's avatar
millert@openbsd.org committed
910
			goto out;
millert@openbsd.org's avatar
millert@openbsd.org committed
911
		}
912
	}
millert@openbsd.org's avatar
millert@openbsd.org committed
913 914
	if (tuser != NULL && !okname(tuser)) {
		++errs;
millert@openbsd.org's avatar
millert@openbsd.org committed
915
		goto out;
millert@openbsd.org's avatar
millert@openbsd.org committed
916
	}
917

millert@openbsd.org's avatar
millert@openbsd.org committed
918
	/* Parse source files */
Damien Miller's avatar
Damien Miller committed
919
	for (i = 0; i < argc - 1; i++) {
millert@openbsd.org's avatar
millert@openbsd.org committed
920 921 922
		free(suser);
		free(host);
		free(src);
millert@openbsd.org's avatar
millert@openbsd.org committed
923 924 925 926 927 928 929
		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
		if (r == -1) {
			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
			++errs;
			continue;
		}
		if (r != 0) {
millert@openbsd.org's avatar
millert@openbsd.org committed
930
			parse_user_host_path(argv[i], &suser, &host, &src);
millert@openbsd.org's avatar
millert@openbsd.org committed
931
		}
millert@openbsd.org's avatar
millert@openbsd.org committed
932 933 934 935 936
		if (suser != NULL && !okname(suser)) {
			++errs;
			continue;
		}
		if (host && throughlocal) {	/* extended remote to remote */
937 938
			xasprintf(&bp, "%s -f %s%s", cmd,
			    *src == '-' ? "-- " : "", src);
millert@openbsd.org's avatar
millert@openbsd.org committed
939
			if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
940
				exit(1);
941
			free(bp);
942 943
			xasprintf(&bp, "%s -t %s%s", cmd,
			    *targ == '-' ? "-- " : "", targ);
millert@openbsd.org's avatar
millert@openbsd.org committed
944
			if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
945
				exit(1);
946
			free(bp);
947 948 949
			(void) close(remin);
			(void) close(remout);
			remin = remout = -1;
millert@openbsd.org's avatar
millert@openbsd.org committed
950 951 952 953 954 955 956
		} else if (host) {	/* standard remote to remote */
			if (tport != -1 && tport != SSH_DEFAULT_PORT) {
				/* This would require the remote support URIs */
				fatal("target port not supported with two "
				    "remote hosts without the -3 option");
			}

957 958 959
			freeargs(&alist);
			addargs(&alist, "%s", ssh_program);
			addargs(&alist, "-x");
960
			addargs(&alist, "-oClearAllForwardings=yes");
961
			addargs(&alist, "-n");
962 963 964 965
			for (j = 0; j < remote_remote_args.num; j++) {
				addargs(&alist, "%s",
				    remote_remote_args.list[j]);
			}
millert@openbsd.org's avatar
millert@openbsd.org committed
966 967 968 969 970 971

			if (sport != -1) {
				addargs(&alist, "-p");
				addargs(&alist, "%d", sport);
			}
			if (suser) {
972 973
				addargs(&alist, "-l");
				addargs(&alist, "%s", suser);
974
			}
975
			addargs(&alist, "--");
976 977 978 979 980 981 982
			addargs(&alist, "%s", host);
			addargs(&alist, "%s", cmd);
			addargs(&alist, "%s", src);
			addargs(&alist, "%s%s%s:%s",
			    tuser ? tuser : "", tuser ? "@" : "",
			    thost, targ);
			if (do_local_cmd(&alist) != 0)
983
				errs = 1;
984
		} else {	/* local to remote */
Damien Miller's avatar
Damien Miller committed
985
			if (remin == -1) {
986 987
				xasprintf(&bp, "%s -t %s%s", cmd,
				    *targ == '-' ? "-- " : "", targ);
millert@openbsd.org's avatar
millert@openbsd.org committed
988
				if (do_cmd(thost, tuser, tport, bp, &remin,
989
				    &remout) < 0)
990
					exit(1);
Damien Miller's avatar
Damien Miller committed
991 992
				if (response() < 0)
					exit(1);
993
				free(bp);
Damien Miller's avatar
Damien Miller committed
994
			}
995
			source(1, argv + i);
Damien Miller's avatar
Damien Miller committed
996 997
		}
	}
millert@openbsd.org's avatar
millert@openbsd.org committed
998 999 1000 1001 1002 1003 1004
out:
	free(tuser);
	free(thost);
	free(targ);
	free(suser);
	free(host);
	free(src);
Damien Miller's avatar
Damien Miller committed
1005 1006 1007
}

void
1008
tolocal(int argc, char **argv)
Damien Miller's avatar
Damien Miller committed
1009
{
millert@openbsd.org's avatar
millert@openbsd.org committed
1010
	char *bp, *host = NULL, *src = NULL, *suser = NULL;
1011
	arglist alist;
millert@openbsd.org's avatar
millert@openbsd.org committed
1012
	int i, r, sport = -1;
1013 1014 1015

	memset(&alist, '\0', sizeof(alist));
	alist.list = NULL;
Damien Miller's avatar
Damien Miller committed
1016 1017

	for (i = 0; i < argc - 1; i++) {
millert@openbsd.org's avatar
millert@openbsd.org committed
1018 1019 1020
		free(suser);
		free(host);
		free(src);
millert@openbsd.org's avatar
millert@openbsd.org committed
1021
		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
millert@openbsd.org's avatar
millert@openbsd.org committed
1022
		if (r == -1) {
millert@openbsd.org's avatar
millert@openbsd.org committed
1023
			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
millert@openbsd.org's avatar
millert@openbsd.org committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
			++errs;
			continue;
		}
		if (r != 0)
			parse_user_host_path(argv[i], &suser, &host, &src);
		if (suser != NULL && !okname(suser)) {
			++errs;
			continue;
		}
		if (!host) {	/* Local to local. */
1034 1035 1036 1037 1038 1039
			freeargs(&alist);
			addargs(&alist, "%s", _PATH_CP);
			if (iamrecursive)
				addargs(&alist, "-r");
			if (pflag)
				addargs(&alist, "-p");
1040
			addargs(&alist, "--");
1041 1042 1043
			addargs(&alist, "%s", argv[i]);
			addargs(&alist, "%s", argv[argc-1]);
			if (do_local_cmd(&alist))
Damien Miller's avatar
Damien Miller committed
1044 1045 1046
				++errs;
			continue;
		}
millert@openbsd.org's avatar
millert@openbsd.org committed
1047
		/* Remote to local. */
1048 1049
		xasprintf(&bp, "%s -f %s%s",
		    cmd, *src == '-' ? "-- " : "", src);
millert@openbsd.org's avatar
millert@openbsd.org committed
1050
		if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
1051
			free(bp);
1052 1053
			++errs;
			continue;
Damien Miller's avatar
Damien Miller committed
1054
		}
1055
		free(bp);
1056
		sink(1, argv + argc - 1, src);
1057
		(void) close(remin);
Damien Miller's avatar
Damien Miller committed
1058 1059
		remin = remout = -1;
	}
millert@openbsd.org's avatar
millert@openbsd.org committed
1060 1061 1062
	free(suser);
	free(host);
	free(src);
Damien Miller's avatar
Damien Miller committed
1063 1064 1065
}

void
1066
source(int argc, char **argv)
Damien Miller's avatar
Damien Miller committed
1067 1068 1069 1070
{
	struct stat stb;
	static BUF buffer;
	BUF *bp;
1071
	off_t i, statbytes;
1072
	size_t amt, nr;
1073
	int fd = -1, haderr, indx;
deraadt@openbsd.org's avatar
deraadt@openbsd.org committed
1074
	char *last, *name, buf[2048], encname[PATH_MAX];
1075
	int len;
Damien Miller's avatar
Damien Miller committed
1076 1077

	for (indx = 0; indx < argc; ++indx) {
1078
		name = argv[indx];
Damien Miller's avatar
Damien Miller committed
1079
		statbytes = 0;
1080 1081 1082
		len = strlen(name);
		while (len > 1 && name[len-1] == '/')
			name[--len] = '\0';
1083
		if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
Damien Miller's avatar
Damien Miller committed
1084
			goto syserr;
1085 1086 1087 1088
		if (strchr(name, '\n') != NULL) {
			strnvis(encname, name, sizeof(encname), VIS_NL);
			name = encname;
		}
Damien Miller's avatar
Damien Miller committed
1089 1090 1091 1092
		if (fstat(fd, &stb) < 0) {
syserr:			run_err("%s: %s", name, strerror(errno));
			goto next;
		}
1093 1094 1095 1096
		if (stb.st_size < 0) {
			run_err("%s: %s", name, "Negative file size");
			goto next;
		}
1097
		unset_nonblock(fd);
Damien Miller's avatar
Damien Miller committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
		switch (stb.st_mode & S_IFMT) {
		case S_IFREG:
			break;
		case S_IFDIR:
			if (iamrecursive) {
				rsource(name, &stb);
				goto next;
			}
			/* FALLTHROUGH */
		default:
			run_err("%s: not a regular file", name);
			goto next;
		}
		if ((last = strrchr(name, '/')) == NULL)
			last = name;
		else
			++last;
		curfile = last;
		if (pflag) {
1117
			if (do_times(remout, verbose_mode, &stb) < 0)
Damien Miller's avatar
Damien Miller committed
1118 1119 1120
				goto next;
		}
#define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
1121
		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
1122
		    (u_int) (stb.st_mode & FILEMODEMASK),
1123
		    (long long)stb.st_size, last);
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
1124 1125
		if (verbose_mode)
			fmprintf(stderr, "Sending file modes: %s", buf);
1126
		(void) atomicio(vwrite, remout, buf, strlen(buf));
Damien Miller's avatar
Damien Miller committed
1127 1128
		if (response() < 0)
			goto next;
1129
		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
1130 1131 1132 1133
next:			if (fd != -1) {
				(void) close(fd);
				fd = -1;
			}
Damien Miller's avatar
Damien Miller committed
1134 1135
			continue;
		}
1136 1137
		if (showprogress)
			start_progress_meter(curfile, stb.st_size, &statbytes);
1138
		set_nonblock(remout);
Damien Miller's avatar
Damien Miller committed
1139 1140
		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
			amt = bp->cnt;
1141
			if (i + (off_t)amt > stb.st_size)
Damien Miller's avatar
Damien Miller committed
1142 1143
				amt = stb.st_size - i;
			if (!haderr) {
1144 1145
				if ((nr = atomicio(read, fd,
				    bp->buf, amt)) != amt) {
1146
					haderr = errno;
1147 1148
					memset(bp->buf + nr, 0, amt - nr);
				}
Damien Miller's avatar
Damien Miller committed
1149
			}
1150 1151 1152
			/* Keep writing after error to retain sync */
			if (haderr) {
				(void)atomicio(vwrite, remout, bp->buf, amt);
1153
				memset(bp->buf, 0, amt);
1154
				continue;
Damien Miller's avatar
Damien Miller committed
1155
			}
1156
			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
1157 1158
			    &statbytes) != amt)
				haderr = errno;
Damien Miller's avatar
Damien Miller committed
1159
		}
1160
		unset_nonblock(remout);
Damien Miller's avatar
Damien Miller committed
1161

1162 1163 1164 1165 1166
		if (fd != -1) {
			if (close(fd) < 0 && !haderr)
				haderr = errno;
			fd = -1;
		}
Damien Miller's avatar
Damien Miller committed
1167
		if (!haderr)
1168
			(void) atomicio(vwrite, remout, "", 1);
Damien Miller's avatar
Damien Miller committed
1169 1170
		else
			run_err("%s: %s", name, strerror(haderr));
1171
		(void) response();
dtucker@openbsd.org's avatar
dtucker@openbsd.org committed
1172 1173
		if (showprogress)
			stop_progress_meter();
Damien Miller's avatar
Damien Miller committed
1174 1175 1176 1177
	}
}

void
1178
rsource(char *name, struct stat *statp)
Damien Miller's avatar
Damien Miller committed
1179 1180 1181
{
	DIR *dirp;
	struct dirent *dp;
deraadt@openbsd.org's avatar
deraadt@openbsd.org committed
1182
	char *last, *vect[1], path[PATH_MAX];
Damien Miller's avatar
Damien Miller committed
1183 1184 1185 1186 1187 1188

	if (!(dirp = opendir(name))) {
		run_err("%s: %s", name, strerror(errno));
		return;
	}
	last = strrchr(name, '/');
mmcc@openbsd.org's avatar
mmcc@openbsd.org committed
1189
	if (last == NULL)
Damien Miller's avatar
Damien Miller committed
1190 1191 1192 1193
		last = name;
	else
		last++;
	if (pflag) {
1194
		if (do_times(remout, verbose_mode, statp) < 0) {
Damien Miller's avatar
Damien Miller committed
1195 1196 1197 1198
			closedir(dirp);
			return;
		}
	}
1199
	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
1200
	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
1201
	if (verbose_mode)
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
1202
		fmprintf(stderr, "Entering directory: %s", path);
1203
	(void) atomicio(vwrite, remout, path, strlen(path));
Damien Miller's avatar
Damien Miller committed
1204 1205 1206 1207
	if (response() < 0) {
		closedir(dirp);
		return;
	}
1208
	while ((dp = readdir(dirp)) != NULL) {
Damien Miller's avatar
Damien Miller committed
1209 1210 1211 1212 1213 1214 1215 1216
		if (dp->d_ino == 0)
			continue;
		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
			continue;
		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
			run_err("%s/%s: name too long", name, dp->d_name);
			continue;
		}
1217
		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
Damien Miller's avatar
Damien Miller committed
1218 1219 1220
		vect[0] = path;
		source(1, vect);
	}
1221
	(void) closedir(dirp);
1222
	(void) atomicio(vwrite, remout, "E\n", 2);
1223
	(void) response();
Damien Miller's avatar
Damien Miller committed
1224 1225
}

millert@openbsd.org's avatar
millert@openbsd.org committed
1226 1227 1228 1229 1230
#define TYPE_OVERFLOW(type, val) \
	((sizeof(type) == 4 && (val) > INT32_MAX) || \
	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
	 (sizeof(type) != 4 && sizeof(type) != 8))

Damien Miller's avatar
Damien Miller committed
1231
void
1232
sink(int argc, char **argv, const char *src)
Damien Miller's avatar
Damien Miller committed
1233 1234 1235
{
	static BUF buffer;
	struct stat stb;
1236 1237 1238
	enum {
		YES, NO, DISPLAYED
	} wrerr;
Damien Miller's avatar
Damien Miller committed
1239
	BUF *bp;
1240
	off_t i;
1241
	size_t j, count;
1242 1243
	int amt, exists, first, ofd;
	mode_t mode, omode, mask;
1244
	off_t size, statbytes;
1245
	unsigned long long ull;
1246
	int setimes, targisdir, wrerrno = 0;
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
1247
	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
1248 1249
	char **patterns = NULL;
	size_t n, npatterns = 0;
1250
	struct timeval tv[2];
Damien Miller's avatar
Damien Miller committed
1251

1252 1253
#define	atime	tv[0]
#define	mtime	tv[1]
1254
#define	SCREWUP(str)	{ why = str; goto screwup; }
Damien Miller's avatar
Damien Miller committed
1255

millert@openbsd.org's avatar
millert@openbsd.org committed
1256 1257 1258
	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
		SCREWUP("Unexpected off_t/time_t size");

Damien Miller's avatar
Damien Miller committed
1259 1260 1261
	setimes = targisdir = 0;
	mask = umask(0);
	if (!pflag)
1262
		(void) umask(mask);
Damien Miller's avatar
Damien Miller committed
1263 1264 1265 1266 1267 1268 1269
	if (argc != 1) {
		run_err("ambiguous target");
		exit(1);
	}
	targ = *argv;
	if (targetshouldbedirectory)
		verifydir(targ);
1270

1271
	(void) atomicio(vwrite, remout, "", 1);
Damien Miller's avatar
Damien Miller committed
1272 1273
	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
		targisdir = 1;
1274 1275 1276 1277 1278
	if (src != NULL && !iamrecursive && !Tflag) {
		/*
		 * Prepare to try to restrict incoming filenames to match
		 * the requested destination file glob.
		 */
1279 1280
		if (brace_expand(src, &patterns, &npatterns) != 0)
			fatal("%s: could not expand pattern", __func__);
1281
	}
Damien Miller's avatar
Damien Miller committed
1282 1283
	for (first = 1;; first = 0) {
		cp = buf;
1284
		if (atomicio(read, remin, cp, 1) != 1)
1285
			goto done;
Damien Miller's avatar
Damien Miller committed
1286 1287 1288
		if (*cp++ == '\n')
			SCREWUP("unexpected <newline>");
		do {
1289
			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
Damien Miller's avatar
Damien Miller committed
1290 1291 1292 1293
				SCREWUP("lost connection");
			*cp++ = ch;
		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
		*cp = 0;
1294
		if (verbose_mode)
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
1295
			fmprintf(stderr, "Sink: %s", buf);
Damien Miller's avatar
Damien Miller committed
1296 1297

		if (buf[0] == '\01' || buf[0] == '\02') {
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
1298 1299 1300
			if (iamremote == 0) {
				(void) snmprintf(visbuf, sizeof(visbuf),
				    NULL, "%s", buf + 1);
1301
				(void) atomicio(vwrite, STDERR_FILENO,
schwarze@openbsd.org's avatar
schwarze@openbsd.org committed
1302 1303
				    visbuf, strlen(visbuf));
			}
Damien Miller's avatar
Damien Miller committed
1304 1305 1306 1307 1308 1309
			if (buf[0] == '\02')
				exit(1);
			++errs;
			continue;
		}
		if (buf[0] == 'E') {
1310
			(void) atomicio(vwrite, remout, "", 1);
1311
			goto done;
Damien Miller's avatar
Damien Miller committed
1312 1313 1314 1315 1316 1317 1318 1319
		}
		if (ch == '\n')
			*--cp = 0;

		cp = buf;
		if (*cp == 'T') {
			setimes++;
			cp++;
1320 1321 1322
			if (!isdigit((unsigned char)*cp))
				SCREWUP("mtime.sec not present");
			ull = strtoull(cp, &cp, 10);
1323
			if (!cp || *cp++ != ' ')
Damien Miller's avatar
Damien Miller committed
1324
				SCREWUP("mtime.sec not delimited");
millert@openbsd.org's avatar
millert@openbsd.org committed
1325
			if (TYPE_OVERFLOW(time_t, ull))
1326 1327
				setimes = 0;	/* out of range */
			mtime.tv_sec = ull;
1328
			mtime.tv_usec = strtol(cp, &cp, 10);
1329 1330
			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
			    mtime.tv_usec > 999999)
Damien Miller's avatar
Damien Miller committed
1331
				SCREWUP("mtime.usec not delimited");
1332 1333 1334
			if (!isdigit((unsigned char)*cp))
				SCREWUP("atime.sec not present");
			ull = strtoull(cp, &cp, 10);
1335
			if (!cp || *cp++ != ' ')
Damien Miller's avatar
Damien Miller committed
1336
				SCREWUP("atime.sec not delimited");
millert@openbsd.org's avatar
millert@openbsd.org committed
1337
			if (TYPE_OVERFLOW(time_t, ull))
1338 1339
				setimes = 0;	/* out of range */
			atime.tv_sec = ull;
1340
			atime.tv_usec = strtol(cp, &cp, 10);
1341 1342
			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
			    atime.tv_usec > 999999)
Damien Miller's avatar
Damien Miller committed
1343
				SCREWUP("atime.usec not delimited");
1344
			(void) atomicio(vwrite, remout, "", 1);
Damien Miller's avatar
Damien Miller committed
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
			continue;
		}
		if (*cp != 'C' && *cp != 'D') {
			/*
			 * Check for the case "rcp remote:foo\* local:bar".
			 * In this case, the line "No match." can be returned
			 * by the shell before the rcp command on the remote is
			 * executed so the ^Aerror_message convention isn't
			 * followed.
			 */
			if (first) {
				run_err("%s", cp);
				exit(1);
			}
			SCREWUP("expected control record");
		}
		mode = 0;
		for (++cp; cp < buf + 5; cp++) {
			if (*cp < '0' || *cp > '7')
				SCREWUP("bad mode");
			mode = (mode << 3) | (*cp - '0');
		}
1367 1368
		if (!pflag)
			mode &= ~mask;
Damien Miller's avatar
Damien Miller committed
1369 1370 1371
		if (*cp++ != ' ')
			SCREWUP("mode not delimited");

millert@openbsd.org's avatar
millert@openbsd.org committed
1372 1373 1374 1375
		if (!isdigit((unsigned char)*cp))
			SCREWUP("size not present");
		ull = strtoull(cp, &cp, 10);
		if (!cp || *cp++ != ' ')
Damien Miller's avatar
Damien Miller committed
1376
			SCREWUP("size not delimited");
millert@openbsd.org's avatar
millert@openbsd.org committed
1377
		if (TYPE_OVERFLOW(off_t, ull))
millert@openbsd.org's avatar
millert@openbsd.org committed
1378 1379 1380
			SCREWUP("size out of range");
		size = (off_t)ull;

1381 1382
		if (*cp == '\0' || strchr(cp, '/') != NULL ||
		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1383 1384 1385
			run_err("error: unexpected filename: %s", cp);
			exit(1);
		}
1386 1387 1388 1389 1390 1391 1392 1393
		if (npatterns > 0) {
			for (n = 0; n < npatterns; n++) {
				if (fnmatch(patterns[n], cp, 0) == 0)
					break;
			}
			if (n >= npatterns)
				SCREWUP("filename does not match request");
		}
Damien Miller's avatar
Damien Miller committed
1394 1395
		if (targisdir) {
			static char *namebuf;
1396
			static size_t cursize;
Damien Miller's avatar
Damien Miller committed
1397 1398 1399
			size_t need;

			need = strlen(targ) + strlen(cp) + 250;
1400
			if (need > cursize) {
1401
				free(namebuf);
1402
				namebuf = xmalloc(need);
1403 1404 1405
				cursize = need;
			}
			(void) snprintf(namebuf, need, "%s%s%s", targ,
1406
			    strcmp(targ, "/") ? "/" : "", cp);
Damien Miller's avatar
Damien Miller committed
1407 1408 1409 1410 1411 1412 1413
			np = namebuf;
		} else
			np = targ;
		curfile = cp;
		exists = stat(np, &stb) == 0;
		if (buf[0] == 'D') {
			int mod_flag = pflag;
1414 1415
			if (!iamrecursive)
				SCREWUP("received directory without -r");
Damien Miller's avatar