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