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