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