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