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