xref: /openssh-portable/scp.c (revision 622dedf1)
1 /* $OpenBSD: scp.c,v 1.199 2019/01/21 22:50:42 tb 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 	if (limit_kbps > 0)
592 		bandwidth_limit(&bwlimit, s);
593 	return 0;
594 }
595 
596 static int
597 do_times(int fd, int verb, const struct stat *sb)
598 {
599 	/* strlen(2^64) == 20; strlen(10^6) == 7 */
600 	char buf[(20 + 7 + 2) * 2 + 2];
601 
602 	(void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n",
603 	    (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime),
604 	    (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime));
605 	if (verb) {
606 		fprintf(stderr, "File mtime %lld atime %lld\n",
607 		    (long long)sb->st_mtime, (long long)sb->st_atime);
608 		fprintf(stderr, "Sending file timestamps: %s", buf);
609 	}
610 	(void) atomicio(vwrite, fd, buf, strlen(buf));
611 	return (response());
612 }
613 
614 static int
615 parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp,
616      char **pathp)
617 {
618 	int r;
619 
620 	r = parse_uri("scp", uri, userp, hostp, portp, pathp);
621 	if (r == 0 && *pathp == NULL)
622 		*pathp = xstrdup(".");
623 	return r;
624 }
625 
626 void
627 toremote(int argc, char **argv)
628 {
629 	char *suser = NULL, *host = NULL, *src = NULL;
630 	char *bp, *tuser, *thost, *targ;
631 	int sport = -1, tport = -1;
632 	arglist alist;
633 	int i, r;
634 	u_int j;
635 
636 	memset(&alist, '\0', sizeof(alist));
637 	alist.list = NULL;
638 
639 	/* Parse target */
640 	r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ);
641 	if (r == -1) {
642 		fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]);
643 		++errs;
644 		goto out;
645 	}
646 	if (r != 0) {
647 		if (parse_user_host_path(argv[argc - 1], &tuser, &thost,
648 		    &targ) == -1) {
649 			fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]);
650 			++errs;
651 			goto out;
652 		}
653 	}
654 	if (tuser != NULL && !okname(tuser)) {
655 		++errs;
656 		goto out;
657 	}
658 
659 	/* Parse source files */
660 	for (i = 0; i < argc - 1; i++) {
661 		free(suser);
662 		free(host);
663 		free(src);
664 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
665 		if (r == -1) {
666 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
667 			++errs;
668 			continue;
669 		}
670 		if (r != 0) {
671 			parse_user_host_path(argv[i], &suser, &host, &src);
672 		}
673 		if (suser != NULL && !okname(suser)) {
674 			++errs;
675 			continue;
676 		}
677 		if (host && throughlocal) {	/* extended remote to remote */
678 			xasprintf(&bp, "%s -f %s%s", cmd,
679 			    *src == '-' ? "-- " : "", src);
680 			if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0)
681 				exit(1);
682 			free(bp);
683 			xasprintf(&bp, "%s -t %s%s", cmd,
684 			    *targ == '-' ? "-- " : "", targ);
685 			if (do_cmd2(thost, tuser, tport, bp, remin, remout) < 0)
686 				exit(1);
687 			free(bp);
688 			(void) close(remin);
689 			(void) close(remout);
690 			remin = remout = -1;
691 		} else if (host) {	/* standard remote to remote */
692 			if (tport != -1 && tport != SSH_DEFAULT_PORT) {
693 				/* This would require the remote support URIs */
694 				fatal("target port not supported with two "
695 				    "remote hosts without the -3 option");
696 			}
697 
698 			freeargs(&alist);
699 			addargs(&alist, "%s", ssh_program);
700 			addargs(&alist, "-x");
701 			addargs(&alist, "-oClearAllForwardings=yes");
702 			addargs(&alist, "-n");
703 			for (j = 0; j < remote_remote_args.num; j++) {
704 				addargs(&alist, "%s",
705 				    remote_remote_args.list[j]);
706 			}
707 
708 			if (sport != -1) {
709 				addargs(&alist, "-p");
710 				addargs(&alist, "%d", sport);
711 			}
712 			if (suser) {
713 				addargs(&alist, "-l");
714 				addargs(&alist, "%s", suser);
715 			}
716 			addargs(&alist, "--");
717 			addargs(&alist, "%s", host);
718 			addargs(&alist, "%s", cmd);
719 			addargs(&alist, "%s", src);
720 			addargs(&alist, "%s%s%s:%s",
721 			    tuser ? tuser : "", tuser ? "@" : "",
722 			    thost, targ);
723 			if (do_local_cmd(&alist) != 0)
724 				errs = 1;
725 		} else {	/* local to remote */
726 			if (remin == -1) {
727 				xasprintf(&bp, "%s -t %s%s", cmd,
728 				    *targ == '-' ? "-- " : "", targ);
729 				if (do_cmd(thost, tuser, tport, bp, &remin,
730 				    &remout) < 0)
731 					exit(1);
732 				if (response() < 0)
733 					exit(1);
734 				free(bp);
735 			}
736 			source(1, argv + i);
737 		}
738 	}
739 out:
740 	free(tuser);
741 	free(thost);
742 	free(targ);
743 	free(suser);
744 	free(host);
745 	free(src);
746 }
747 
748 void
749 tolocal(int argc, char **argv)
750 {
751 	char *bp, *host = NULL, *src = NULL, *suser = NULL;
752 	arglist alist;
753 	int i, r, sport = -1;
754 
755 	memset(&alist, '\0', sizeof(alist));
756 	alist.list = NULL;
757 
758 	for (i = 0; i < argc - 1; i++) {
759 		free(suser);
760 		free(host);
761 		free(src);
762 		r = parse_scp_uri(argv[i], &suser, &host, &sport, &src);
763 		if (r == -1) {
764 			fmprintf(stderr, "%s: invalid uri\n", argv[i]);
765 			++errs;
766 			continue;
767 		}
768 		if (r != 0)
769 			parse_user_host_path(argv[i], &suser, &host, &src);
770 		if (suser != NULL && !okname(suser)) {
771 			++errs;
772 			continue;
773 		}
774 		if (!host) {	/* Local to local. */
775 			freeargs(&alist);
776 			addargs(&alist, "%s", _PATH_CP);
777 			if (iamrecursive)
778 				addargs(&alist, "-r");
779 			if (pflag)
780 				addargs(&alist, "-p");
781 			addargs(&alist, "--");
782 			addargs(&alist, "%s", argv[i]);
783 			addargs(&alist, "%s", argv[argc-1]);
784 			if (do_local_cmd(&alist))
785 				++errs;
786 			continue;
787 		}
788 		/* Remote to local. */
789 		xasprintf(&bp, "%s -f %s%s",
790 		    cmd, *src == '-' ? "-- " : "", src);
791 		if (do_cmd(host, suser, sport, bp, &remin, &remout) < 0) {
792 			free(bp);
793 			++errs;
794 			continue;
795 		}
796 		free(bp);
797 		sink(1, argv + argc - 1);
798 		(void) close(remin);
799 		remin = remout = -1;
800 	}
801 	free(suser);
802 	free(host);
803 	free(src);
804 }
805 
806 void
807 source(int argc, char **argv)
808 {
809 	struct stat stb;
810 	static BUF buffer;
811 	BUF *bp;
812 	off_t i, statbytes;
813 	size_t amt, nr;
814 	int fd = -1, haderr, indx;
815 	char *last, *name, buf[2048], encname[PATH_MAX];
816 	int len;
817 
818 	for (indx = 0; indx < argc; ++indx) {
819 		name = argv[indx];
820 		statbytes = 0;
821 		len = strlen(name);
822 		while (len > 1 && name[len-1] == '/')
823 			name[--len] = '\0';
824 		if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) < 0)
825 			goto syserr;
826 		if (strchr(name, '\n') != NULL) {
827 			strnvis(encname, name, sizeof(encname), VIS_NL);
828 			name = encname;
829 		}
830 		if (fstat(fd, &stb) < 0) {
831 syserr:			run_err("%s: %s", name, strerror(errno));
832 			goto next;
833 		}
834 		if (stb.st_size < 0) {
835 			run_err("%s: %s", name, "Negative file size");
836 			goto next;
837 		}
838 		unset_nonblock(fd);
839 		switch (stb.st_mode & S_IFMT) {
840 		case S_IFREG:
841 			break;
842 		case S_IFDIR:
843 			if (iamrecursive) {
844 				rsource(name, &stb);
845 				goto next;
846 			}
847 			/* FALLTHROUGH */
848 		default:
849 			run_err("%s: not a regular file", name);
850 			goto next;
851 		}
852 		if ((last = strrchr(name, '/')) == NULL)
853 			last = name;
854 		else
855 			++last;
856 		curfile = last;
857 		if (pflag) {
858 			if (do_times(remout, verbose_mode, &stb) < 0)
859 				goto next;
860 		}
861 #define	FILEMODEMASK	(S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO)
862 		snprintf(buf, sizeof buf, "C%04o %lld %s\n",
863 		    (u_int) (stb.st_mode & FILEMODEMASK),
864 		    (long long)stb.st_size, last);
865 		if (verbose_mode)
866 			fmprintf(stderr, "Sending file modes: %s", buf);
867 		(void) atomicio(vwrite, remout, buf, strlen(buf));
868 		if (response() < 0)
869 			goto next;
870 		if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) {
871 next:			if (fd != -1) {
872 				(void) close(fd);
873 				fd = -1;
874 			}
875 			continue;
876 		}
877 		if (showprogress)
878 			start_progress_meter(curfile, stb.st_size, &statbytes);
879 		set_nonblock(remout);
880 		for (haderr = i = 0; i < stb.st_size; i += bp->cnt) {
881 			amt = bp->cnt;
882 			if (i + (off_t)amt > stb.st_size)
883 				amt = stb.st_size - i;
884 			if (!haderr) {
885 				if ((nr = atomicio(read, fd,
886 				    bp->buf, amt)) != amt) {
887 					haderr = errno;
888 					memset(bp->buf + nr, 0, amt - nr);
889 				}
890 			}
891 			/* Keep writing after error to retain sync */
892 			if (haderr) {
893 				(void)atomicio(vwrite, remout, bp->buf, amt);
894 				memset(bp->buf, 0, amt);
895 				continue;
896 			}
897 			if (atomicio6(vwrite, remout, bp->buf, amt, scpio,
898 			    &statbytes) != amt)
899 				haderr = errno;
900 		}
901 		unset_nonblock(remout);
902 
903 		if (fd != -1) {
904 			if (close(fd) < 0 && !haderr)
905 				haderr = errno;
906 			fd = -1;
907 		}
908 		if (!haderr)
909 			(void) atomicio(vwrite, remout, "", 1);
910 		else
911 			run_err("%s: %s", name, strerror(haderr));
912 		(void) response();
913 		if (showprogress)
914 			stop_progress_meter();
915 	}
916 }
917 
918 void
919 rsource(char *name, struct stat *statp)
920 {
921 	DIR *dirp;
922 	struct dirent *dp;
923 	char *last, *vect[1], path[PATH_MAX];
924 
925 	if (!(dirp = opendir(name))) {
926 		run_err("%s: %s", name, strerror(errno));
927 		return;
928 	}
929 	last = strrchr(name, '/');
930 	if (last == NULL)
931 		last = name;
932 	else
933 		last++;
934 	if (pflag) {
935 		if (do_times(remout, verbose_mode, statp) < 0) {
936 			closedir(dirp);
937 			return;
938 		}
939 	}
940 	(void) snprintf(path, sizeof path, "D%04o %d %.1024s\n",
941 	    (u_int) (statp->st_mode & FILEMODEMASK), 0, last);
942 	if (verbose_mode)
943 		fmprintf(stderr, "Entering directory: %s", path);
944 	(void) atomicio(vwrite, remout, path, strlen(path));
945 	if (response() < 0) {
946 		closedir(dirp);
947 		return;
948 	}
949 	while ((dp = readdir(dirp)) != NULL) {
950 		if (dp->d_ino == 0)
951 			continue;
952 		if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, ".."))
953 			continue;
954 		if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) {
955 			run_err("%s/%s: name too long", name, dp->d_name);
956 			continue;
957 		}
958 		(void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name);
959 		vect[0] = path;
960 		source(1, vect);
961 	}
962 	(void) closedir(dirp);
963 	(void) atomicio(vwrite, remout, "E\n", 2);
964 	(void) response();
965 }
966 
967 #define TYPE_OVERFLOW(type, val) \
968 	((sizeof(type) == 4 && (val) > INT32_MAX) || \
969 	 (sizeof(type) == 8 && (val) > INT64_MAX) || \
970 	 (sizeof(type) != 4 && sizeof(type) != 8))
971 
972 void
973 sink(int argc, char **argv)
974 {
975 	static BUF buffer;
976 	struct stat stb;
977 	enum {
978 		YES, NO, DISPLAYED
979 	} wrerr;
980 	BUF *bp;
981 	off_t i;
982 	size_t j, count;
983 	int amt, exists, first, ofd;
984 	mode_t mode, omode, mask;
985 	off_t size, statbytes;
986 	unsigned long long ull;
987 	int setimes, targisdir, wrerrno = 0;
988 	char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048];
989 	struct timeval tv[2];
990 
991 #define	atime	tv[0]
992 #define	mtime	tv[1]
993 #define	SCREWUP(str)	{ why = str; goto screwup; }
994 
995 	if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0))
996 		SCREWUP("Unexpected off_t/time_t size");
997 
998 	setimes = targisdir = 0;
999 	mask = umask(0);
1000 	if (!pflag)
1001 		(void) umask(mask);
1002 	if (argc != 1) {
1003 		run_err("ambiguous target");
1004 		exit(1);
1005 	}
1006 	targ = *argv;
1007 	if (targetshouldbedirectory)
1008 		verifydir(targ);
1009 
1010 	(void) atomicio(vwrite, remout, "", 1);
1011 	if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode))
1012 		targisdir = 1;
1013 	for (first = 1;; first = 0) {
1014 		cp = buf;
1015 		if (atomicio(read, remin, cp, 1) != 1)
1016 			return;
1017 		if (*cp++ == '\n')
1018 			SCREWUP("unexpected <newline>");
1019 		do {
1020 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1021 				SCREWUP("lost connection");
1022 			*cp++ = ch;
1023 		} while (cp < &buf[sizeof(buf) - 1] && ch != '\n');
1024 		*cp = 0;
1025 		if (verbose_mode)
1026 			fmprintf(stderr, "Sink: %s", buf);
1027 
1028 		if (buf[0] == '\01' || buf[0] == '\02') {
1029 			if (iamremote == 0) {
1030 				(void) snmprintf(visbuf, sizeof(visbuf),
1031 				    NULL, "%s", buf + 1);
1032 				(void) atomicio(vwrite, STDERR_FILENO,
1033 				    visbuf, strlen(visbuf));
1034 			}
1035 			if (buf[0] == '\02')
1036 				exit(1);
1037 			++errs;
1038 			continue;
1039 		}
1040 		if (buf[0] == 'E') {
1041 			(void) atomicio(vwrite, remout, "", 1);
1042 			return;
1043 		}
1044 		if (ch == '\n')
1045 			*--cp = 0;
1046 
1047 		cp = buf;
1048 		if (*cp == 'T') {
1049 			setimes++;
1050 			cp++;
1051 			if (!isdigit((unsigned char)*cp))
1052 				SCREWUP("mtime.sec not present");
1053 			ull = strtoull(cp, &cp, 10);
1054 			if (!cp || *cp++ != ' ')
1055 				SCREWUP("mtime.sec not delimited");
1056 			if (TYPE_OVERFLOW(time_t, ull))
1057 				setimes = 0;	/* out of range */
1058 			mtime.tv_sec = ull;
1059 			mtime.tv_usec = strtol(cp, &cp, 10);
1060 			if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 ||
1061 			    mtime.tv_usec > 999999)
1062 				SCREWUP("mtime.usec not delimited");
1063 			if (!isdigit((unsigned char)*cp))
1064 				SCREWUP("atime.sec not present");
1065 			ull = strtoull(cp, &cp, 10);
1066 			if (!cp || *cp++ != ' ')
1067 				SCREWUP("atime.sec not delimited");
1068 			if (TYPE_OVERFLOW(time_t, ull))
1069 				setimes = 0;	/* out of range */
1070 			atime.tv_sec = ull;
1071 			atime.tv_usec = strtol(cp, &cp, 10);
1072 			if (!cp || *cp++ != '\0' || atime.tv_usec < 0 ||
1073 			    atime.tv_usec > 999999)
1074 				SCREWUP("atime.usec not delimited");
1075 			(void) atomicio(vwrite, remout, "", 1);
1076 			continue;
1077 		}
1078 		if (*cp != 'C' && *cp != 'D') {
1079 			/*
1080 			 * Check for the case "rcp remote:foo\* local:bar".
1081 			 * In this case, the line "No match." can be returned
1082 			 * by the shell before the rcp command on the remote is
1083 			 * executed so the ^Aerror_message convention isn't
1084 			 * followed.
1085 			 */
1086 			if (first) {
1087 				run_err("%s", cp);
1088 				exit(1);
1089 			}
1090 			SCREWUP("expected control record");
1091 		}
1092 		mode = 0;
1093 		for (++cp; cp < buf + 5; cp++) {
1094 			if (*cp < '0' || *cp > '7')
1095 				SCREWUP("bad mode");
1096 			mode = (mode << 3) | (*cp - '0');
1097 		}
1098 		if (!pflag)
1099 			mode &= ~mask;
1100 		if (*cp++ != ' ')
1101 			SCREWUP("mode not delimited");
1102 
1103 		if (!isdigit((unsigned char)*cp))
1104 			SCREWUP("size not present");
1105 		ull = strtoull(cp, &cp, 10);
1106 		if (!cp || *cp++ != ' ')
1107 			SCREWUP("size not delimited");
1108 		if (TYPE_OVERFLOW(off_t, ull))
1109 			SCREWUP("size out of range");
1110 		size = (off_t)ull;
1111 
1112 		if (*cp == '\0' || strchr(cp, '/') != NULL ||
1113 		    strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) {
1114 			run_err("error: unexpected filename: %s", cp);
1115 			exit(1);
1116 		}
1117 		if (targisdir) {
1118 			static char *namebuf;
1119 			static size_t cursize;
1120 			size_t need;
1121 
1122 			need = strlen(targ) + strlen(cp) + 250;
1123 			if (need > cursize) {
1124 				free(namebuf);
1125 				namebuf = xmalloc(need);
1126 				cursize = need;
1127 			}
1128 			(void) snprintf(namebuf, need, "%s%s%s", targ,
1129 			    strcmp(targ, "/") ? "/" : "", cp);
1130 			np = namebuf;
1131 		} else
1132 			np = targ;
1133 		curfile = cp;
1134 		exists = stat(np, &stb) == 0;
1135 		if (buf[0] == 'D') {
1136 			int mod_flag = pflag;
1137 			if (!iamrecursive)
1138 				SCREWUP("received directory without -r");
1139 			if (exists) {
1140 				if (!S_ISDIR(stb.st_mode)) {
1141 					errno = ENOTDIR;
1142 					goto bad;
1143 				}
1144 				if (pflag)
1145 					(void) chmod(np, mode);
1146 			} else {
1147 				/* Handle copying from a read-only
1148 				   directory */
1149 				mod_flag = 1;
1150 				if (mkdir(np, mode | S_IRWXU) < 0)
1151 					goto bad;
1152 			}
1153 			vect[0] = xstrdup(np);
1154 			sink(1, vect);
1155 			if (setimes) {
1156 				setimes = 0;
1157 				if (utimes(vect[0], tv) < 0)
1158 					run_err("%s: set times: %s",
1159 					    vect[0], strerror(errno));
1160 			}
1161 			if (mod_flag)
1162 				(void) chmod(vect[0], mode);
1163 			free(vect[0]);
1164 			continue;
1165 		}
1166 		omode = mode;
1167 		mode |= S_IWUSR;
1168 		if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) {
1169 bad:			run_err("%s: %s", np, strerror(errno));
1170 			continue;
1171 		}
1172 		(void) atomicio(vwrite, remout, "", 1);
1173 		if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) {
1174 			(void) close(ofd);
1175 			continue;
1176 		}
1177 		cp = bp->buf;
1178 		wrerr = NO;
1179 
1180 		statbytes = 0;
1181 		if (showprogress)
1182 			start_progress_meter(curfile, size, &statbytes);
1183 		set_nonblock(remin);
1184 		for (count = i = 0; i < size; i += bp->cnt) {
1185 			amt = bp->cnt;
1186 			if (i + amt > size)
1187 				amt = size - i;
1188 			count += amt;
1189 			do {
1190 				j = atomicio6(read, remin, cp, amt,
1191 				    scpio, &statbytes);
1192 				if (j == 0) {
1193 					run_err("%s", j != EPIPE ?
1194 					    strerror(errno) :
1195 					    "dropped connection");
1196 					exit(1);
1197 				}
1198 				amt -= j;
1199 				cp += j;
1200 			} while (amt > 0);
1201 
1202 			if (count == bp->cnt) {
1203 				/* Keep reading so we stay sync'd up. */
1204 				if (wrerr == NO) {
1205 					if (atomicio(vwrite, ofd, bp->buf,
1206 					    count) != count) {
1207 						wrerr = YES;
1208 						wrerrno = errno;
1209 					}
1210 				}
1211 				count = 0;
1212 				cp = bp->buf;
1213 			}
1214 		}
1215 		unset_nonblock(remin);
1216 		if (count != 0 && wrerr == NO &&
1217 		    atomicio(vwrite, ofd, bp->buf, count) != count) {
1218 			wrerr = YES;
1219 			wrerrno = errno;
1220 		}
1221 		if (wrerr == NO && (!exists || S_ISREG(stb.st_mode)) &&
1222 		    ftruncate(ofd, size) != 0) {
1223 			run_err("%s: truncate: %s", np, strerror(errno));
1224 			wrerr = DISPLAYED;
1225 		}
1226 		if (pflag) {
1227 			if (exists || omode != mode)
1228 #ifdef HAVE_FCHMOD
1229 				if (fchmod(ofd, omode)) {
1230 #else /* HAVE_FCHMOD */
1231 				if (chmod(np, omode)) {
1232 #endif /* HAVE_FCHMOD */
1233 					run_err("%s: set mode: %s",
1234 					    np, strerror(errno));
1235 					wrerr = DISPLAYED;
1236 				}
1237 		} else {
1238 			if (!exists && omode != mode)
1239 #ifdef HAVE_FCHMOD
1240 				if (fchmod(ofd, omode & ~mask)) {
1241 #else /* HAVE_FCHMOD */
1242 				if (chmod(np, omode & ~mask)) {
1243 #endif /* HAVE_FCHMOD */
1244 					run_err("%s: set mode: %s",
1245 					    np, strerror(errno));
1246 					wrerr = DISPLAYED;
1247 				}
1248 		}
1249 		if (close(ofd) == -1) {
1250 			wrerr = YES;
1251 			wrerrno = errno;
1252 		}
1253 		(void) response();
1254 		if (showprogress)
1255 			stop_progress_meter();
1256 		if (setimes && wrerr == NO) {
1257 			setimes = 0;
1258 			if (utimes(np, tv) < 0) {
1259 				run_err("%s: set times: %s",
1260 				    np, strerror(errno));
1261 				wrerr = DISPLAYED;
1262 			}
1263 		}
1264 		switch (wrerr) {
1265 		case YES:
1266 			run_err("%s: %s", np, strerror(wrerrno));
1267 			break;
1268 		case NO:
1269 			(void) atomicio(vwrite, remout, "", 1);
1270 			break;
1271 		case DISPLAYED:
1272 			break;
1273 		}
1274 	}
1275 screwup:
1276 	run_err("protocol error: %s", why);
1277 	exit(1);
1278 }
1279 
1280 int
1281 response(void)
1282 {
1283 	char ch, *cp, resp, rbuf[2048], visbuf[2048];
1284 
1285 	if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp))
1286 		lostconn(0);
1287 
1288 	cp = rbuf;
1289 	switch (resp) {
1290 	case 0:		/* ok */
1291 		return (0);
1292 	default:
1293 		*cp++ = resp;
1294 		/* FALLTHROUGH */
1295 	case 1:		/* error, followed by error msg */
1296 	case 2:		/* fatal error, "" */
1297 		do {
1298 			if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch))
1299 				lostconn(0);
1300 			*cp++ = ch;
1301 		} while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n');
1302 
1303 		if (!iamremote) {
1304 			cp[-1] = '\0';
1305 			(void) snmprintf(visbuf, sizeof(visbuf),
1306 			    NULL, "%s\n", rbuf);
1307 			(void) atomicio(vwrite, STDERR_FILENO,
1308 			    visbuf, strlen(visbuf));
1309 		}
1310 		++errs;
1311 		if (resp == 1)
1312 			return (-1);
1313 		exit(1);
1314 	}
1315 	/* NOTREACHED */
1316 }
1317 
1318 void
1319 usage(void)
1320 {
1321 	(void) fprintf(stderr,
1322 	    "usage: scp [-346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]\n"
1323 	    "            [-J destination] [-l limit] [-o ssh_option] [-P port]\n"
1324 	    "            [-S program] source ... target\n");
1325 	exit(1);
1326 }
1327 
1328 void
1329 run_err(const char *fmt,...)
1330 {
1331 	static FILE *fp;
1332 	va_list ap;
1333 
1334 	++errs;
1335 	if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) {
1336 		(void) fprintf(fp, "%c", 0x01);
1337 		(void) fprintf(fp, "scp: ");
1338 		va_start(ap, fmt);
1339 		(void) vfprintf(fp, fmt, ap);
1340 		va_end(ap);
1341 		(void) fprintf(fp, "\n");
1342 		(void) fflush(fp);
1343 	}
1344 
1345 	if (!iamremote) {
1346 		va_start(ap, fmt);
1347 		vfmprintf(stderr, fmt, ap);
1348 		va_end(ap);
1349 		fprintf(stderr, "\n");
1350 	}
1351 }
1352 
1353 void
1354 verifydir(char *cp)
1355 {
1356 	struct stat stb;
1357 
1358 	if (!stat(cp, &stb)) {
1359 		if (S_ISDIR(stb.st_mode))
1360 			return;
1361 		errno = ENOTDIR;
1362 	}
1363 	run_err("%s: %s", cp, strerror(errno));
1364 	killchild(0);
1365 }
1366 
1367 int
1368 okname(char *cp0)
1369 {
1370 	int c;
1371 	char *cp;
1372 
1373 	cp = cp0;
1374 	do {
1375 		c = (int)*cp;
1376 		if (c & 0200)
1377 			goto bad;
1378 		if (!isalpha(c) && !isdigit((unsigned char)c)) {
1379 			switch (c) {
1380 			case '\'':
1381 			case '"':
1382 			case '`':
1383 			case ' ':
1384 			case '#':
1385 				goto bad;
1386 			default:
1387 				break;
1388 			}
1389 		}
1390 	} while (*++cp);
1391 	return (1);
1392 
1393 bad:	fmprintf(stderr, "%s: invalid user name\n", cp0);
1394 	return (0);
1395 }
1396 
1397 BUF *
1398 allocbuf(BUF *bp, int fd, int blksize)
1399 {
1400 	size_t size;
1401 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
1402 	struct stat stb;
1403 
1404 	if (fstat(fd, &stb) < 0) {
1405 		run_err("fstat: %s", strerror(errno));
1406 		return (0);
1407 	}
1408 	size = ROUNDUP(stb.st_blksize, blksize);
1409 	if (size == 0)
1410 		size = blksize;
1411 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1412 	size = blksize;
1413 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */
1414 	if (bp->cnt >= size)
1415 		return (bp);
1416 	bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1);
1417 	bp->cnt = size;
1418 	return (bp);
1419 }
1420 
1421 void
1422 lostconn(int signo)
1423 {
1424 	if (!iamremote)
1425 		(void)write(STDERR_FILENO, "lost connection\n", 16);
1426 	if (signo)
1427 		_exit(1);
1428 	else
1429 		exit(1);
1430 }
1431