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