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