1 /* $OpenBSD: scp.c,v 1.232 2021/08/11 14:07:54 naddy 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 #ifdef HAVE_FNMATCH_H 98 #include <fnmatch.h> 99 #endif 100 #ifdef USE_SYSTEM_GLOB 101 # include <glob.h> 102 #else 103 # include "openbsd-compat/glob.h" 104 #endif 105 #ifdef HAVE_LIBGEN_H 106 #include <libgen.h> 107 #endif 108 #include <limits.h> 109 #include <locale.h> 110 #include <pwd.h> 111 #include <signal.h> 112 #include <stdarg.h> 113 #ifdef HAVE_STDINT_H 114 # include <stdint.h> 115 #endif 116 #include <stdio.h> 117 #include <stdlib.h> 118 #include <string.h> 119 #include <time.h> 120 #include <unistd.h> 121 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS) 122 #include <vis.h> 123 #endif 124 125 #include "xmalloc.h" 126 #include "ssh.h" 127 #include "atomicio.h" 128 #include "pathnames.h" 129 #include "log.h" 130 #include "misc.h" 131 #include "progressmeter.h" 132 #include "utf8.h" 133 134 #include "sftp-common.h" 135 #include "sftp-client.h" 136 137 extern char *__progname; 138 139 #define COPY_BUFLEN 16384 140 141 int do_cmd(char *, char *, char *, int, int, char *, int *, int *, pid_t *); 142 int do_cmd2(char *, char *, int, char *, int, int); 143 144 /* Struct for addargs */ 145 arglist args; 146 arglist remote_remote_args; 147 148 /* Bandwidth limit */ 149 long long limit_kbps = 0; 150 struct bwlimit bwlimit; 151 152 /* Name of current file being transferred. */ 153 char *curfile; 154 155 /* This is set to non-zero to enable verbose mode. */ 156 int verbose_mode = 0; 157 LogLevel log_level = SYSLOG_LEVEL_INFO; 158 159 /* This is set to zero if the progressmeter is not desired. */ 160 int showprogress = 1; 161 162 /* 163 * This is set to non-zero if remote-remote copy should be piped 164 * through this process. 165 */ 166 int throughlocal = 1; 167 168 /* Non-standard port to use for the ssh connection or -1. */ 169 int sshport = -1; 170 171 /* This is the program to execute for the secured connection. ("ssh" or -S) */ 172 char *ssh_program = _PATH_SSH_PROGRAM; 173 174 /* This is used to store the pid of ssh_program */ 175 pid_t do_cmd_pid = -1; 176 pid_t do_cmd_pid2 = -1; 177 178 /* Needed for sftp */ 179 volatile sig_atomic_t interrupted = 0; 180 181 int remote_glob(struct sftp_conn *, const char *, int, 182 int (*)(const char *, int), glob_t *); /* proto for sftp-glob.c */ 183 184 static void 185 killchild(int signo) 186 { 187 if (do_cmd_pid > 1) { 188 kill(do_cmd_pid, signo ? signo : SIGTERM); 189 waitpid(do_cmd_pid, NULL, 0); 190 } 191 if (do_cmd_pid2 > 1) { 192 kill(do_cmd_pid2, signo ? signo : SIGTERM); 193 waitpid(do_cmd_pid2, NULL, 0); 194 } 195 196 if (signo) 197 _exit(1); 198 exit(1); 199 } 200 201 static void 202 suspone(int pid, int signo) 203 { 204 int status; 205 206 if (pid > 1) { 207 kill(pid, signo); 208 while (waitpid(pid, &status, WUNTRACED) == -1 && 209 errno == EINTR) 210 ; 211 } 212 } 213 214 static void 215 suspchild(int signo) 216 { 217 suspone(do_cmd_pid, signo); 218 suspone(do_cmd_pid2, signo); 219 kill(getpid(), SIGSTOP); 220 } 221 222 static int 223 do_local_cmd(arglist *a) 224 { 225 u_int i; 226 int status; 227 pid_t pid; 228 229 if (a->num == 0) 230 fatal("do_local_cmd: no arguments"); 231 232 if (verbose_mode) { 233 fprintf(stderr, "Executing:"); 234 for (i = 0; i < a->num; i++) 235 fmprintf(stderr, " %s", a->list[i]); 236 fprintf(stderr, "\n"); 237 } 238 if ((pid = fork()) == -1) 239 fatal("do_local_cmd: fork: %s", strerror(errno)); 240 241 if (pid == 0) { 242 execvp(a->list[0], a->list); 243 perror(a->list[0]); 244 exit(1); 245 } 246 247 do_cmd_pid = pid; 248 ssh_signal(SIGTERM, killchild); 249 ssh_signal(SIGINT, killchild); 250 ssh_signal(SIGHUP, killchild); 251 252 while (waitpid(pid, &status, 0) == -1) 253 if (errno != EINTR) 254 fatal("do_local_cmd: waitpid: %s", strerror(errno)); 255 256 do_cmd_pid = -1; 257 258 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) 259 return (-1); 260 261 return (0); 262 } 263 264 /* 265 * This function executes the given command as the specified user on the 266 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This 267 * assigns the input and output file descriptors on success. 268 */ 269 270 int 271 do_cmd(char *program, char *host, char *remuser, int port, int subsystem, 272 char *cmd, int *fdin, int *fdout, pid_t *pid) 273 { 274 int pin[2], pout[2], reserved[2]; 275 276 if (verbose_mode) 277 fmprintf(stderr, 278 "Executing: program %s host %s, user %s, command %s\n", 279 program, host, 280 remuser ? remuser : "(unspecified)", cmd); 281 282 if (port == -1) 283 port = sshport; 284 285 /* 286 * Reserve two descriptors so that the real pipes won't get 287 * descriptors 0 and 1 because that will screw up dup2 below. 288 */ 289 if (pipe(reserved) == -1) 290 fatal("pipe: %s", strerror(errno)); 291 292 /* Create a socket pair for communicating with ssh. */ 293 if (pipe(pin) == -1) 294 fatal("pipe: %s", strerror(errno)); 295 if (pipe(pout) == -1) 296 fatal("pipe: %s", strerror(errno)); 297 298 /* Free the reserved descriptors. */ 299 close(reserved[0]); 300 close(reserved[1]); 301 302 ssh_signal(SIGTSTP, suspchild); 303 ssh_signal(SIGTTIN, suspchild); 304 ssh_signal(SIGTTOU, suspchild); 305 306 /* Fork a child to execute the command on the remote host using ssh. */ 307 *pid = fork(); 308 if (*pid == 0) { 309 /* Child. */ 310 close(pin[1]); 311 close(pout[0]); 312 dup2(pin[0], 0); 313 dup2(pout[1], 1); 314 close(pin[0]); 315 close(pout[1]); 316 317 replacearg(&args, 0, "%s", program); 318 if (port != -1) { 319 addargs(&args, "-p"); 320 addargs(&args, "%d", port); 321 } 322 if (remuser != NULL) { 323 addargs(&args, "-l"); 324 addargs(&args, "%s", remuser); 325 } 326 if (subsystem) 327 addargs(&args, "-s"); 328 addargs(&args, "--"); 329 addargs(&args, "%s", host); 330 addargs(&args, "%s", cmd); 331 332 execvp(program, args.list); 333 perror(program); 334 exit(1); 335 } else if (*pid == -1) { 336 fatal("fork: %s", strerror(errno)); 337 } 338 /* Parent. Close the other side, and return the local side. */ 339 close(pin[0]); 340 *fdout = pin[1]; 341 close(pout[1]); 342 *fdin = pout[0]; 343 ssh_signal(SIGTERM, killchild); 344 ssh_signal(SIGINT, killchild); 345 ssh_signal(SIGHUP, killchild); 346 return 0; 347 } 348 349 /* 350 * This function executes a command similar to do_cmd(), but expects the 351 * input and output descriptors to be setup by a previous call to do_cmd(). 352 * This way the input and output of two commands can be connected. 353 */ 354 int 355 do_cmd2(char *host, char *remuser, int port, char *cmd, 356 int fdin, int fdout) 357 { 358 int status; 359 pid_t pid; 360 361 if (verbose_mode) 362 fmprintf(stderr, 363 "Executing: 2nd program %s host %s, user %s, command %s\n", 364 ssh_program, host, 365 remuser ? remuser : "(unspecified)", cmd); 366 367 if (port == -1) 368 port = sshport; 369 370 /* Fork a child to execute the command on the remote host using ssh. */ 371 pid = fork(); 372 if (pid == 0) { 373 dup2(fdin, 0); 374 dup2(fdout, 1); 375 376 replacearg(&args, 0, "%s", ssh_program); 377 if (port != -1) { 378 addargs(&args, "-p"); 379 addargs(&args, "%d", port); 380 } 381 if (remuser != NULL) { 382 addargs(&args, "-l"); 383 addargs(&args, "%s", remuser); 384 } 385 addargs(&args, "-oBatchMode=yes"); 386 addargs(&args, "--"); 387 addargs(&args, "%s", host); 388 addargs(&args, "%s", cmd); 389 390 execvp(ssh_program, args.list); 391 perror(ssh_program); 392 exit(1); 393 } else if (pid == -1) { 394 fatal("fork: %s", strerror(errno)); 395 } 396 while (waitpid(pid, &status, 0) == -1) 397 if (errno != EINTR) 398 fatal("do_cmd2: waitpid: %s", strerror(errno)); 399 return 0; 400 } 401 402 typedef struct { 403 size_t cnt; 404 char *buf; 405 } BUF; 406 407 BUF *allocbuf(BUF *, int, int); 408 void lostconn(int); 409 int okname(char *); 410 void run_err(const char *,...) 411 __attribute__((__format__ (printf, 1, 2))) 412 __attribute__((__nonnull__ (1))); 413 int note_err(const char *,...) 414 __attribute__((__format__ (printf, 1, 2))); 415 void verifydir(char *); 416 417 struct passwd *pwd; 418 uid_t userid; 419 int errs, remin, remout, remin2, remout2; 420 int Tflag, pflag, iamremote, iamrecursive, targetshouldbedirectory; 421 422 #define CMDNEEDS 64 423 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */ 424 425 enum scp_mode_e { 426 MODE_SCP, 427 MODE_SFTP 428 }; 429 430 int response(void); 431 void rsource(char *, struct stat *); 432 void sink(int, char *[], const char *); 433 void source(int, char *[]); 434 void tolocal(int, char *[], enum scp_mode_e, char *sftp_direct); 435 void toremote(int, char *[], enum scp_mode_e, char *sftp_direct); 436 void usage(void); 437 438 void source_sftp(int, char *, char *, struct sftp_conn *); 439 void sink_sftp(int, char *, const char *, struct sftp_conn *); 440 void throughlocal_sftp(struct sftp_conn *, struct sftp_conn *, 441 char *, char *); 442 443 int 444 main(int argc, char **argv) 445 { 446 int ch, fflag, tflag, status, n; 447 char **newargv, *argv0; 448 const char *errstr; 449 extern char *optarg; 450 extern int optind; 451 enum scp_mode_e mode = MODE_SCP; 452 char *sftp_direct = NULL; 453 454 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 455 sanitise_stdfd(); 456 457 seed_rng(); 458 459 msetlocale(); 460 461 /* Copy argv, because we modify it */ 462 argv0 = argv[0]; 463 newargv = xcalloc(MAXIMUM(argc + 1, 1), sizeof(*newargv)); 464 for (n = 0; n < argc; n++) 465 newargv[n] = xstrdup(argv[n]); 466 argv = newargv; 467 468 __progname = ssh_get_progname(argv[0]); 469 470 log_init(argv0, log_level, SYSLOG_FACILITY_USER, 1); 471 472 memset(&args, '\0', sizeof(args)); 473 memset(&remote_remote_args, '\0', sizeof(remote_remote_args)); 474 args.list = remote_remote_args.list = NULL; 475 addargs(&args, "%s", ssh_program); 476 addargs(&args, "-x"); 477 addargs(&args, "-oPermitLocalCommand=no"); 478 addargs(&args, "-oClearAllForwardings=yes"); 479 addargs(&args, "-oRemoteCommand=none"); 480 addargs(&args, "-oRequestTTY=no"); 481 482 fflag = Tflag = tflag = 0; 483 while ((ch = getopt(argc, argv, 484 "12346ABCTdfOpqRrstvD:F:J:M:P:S:c:i:l:o:")) != -1) { 485 switch (ch) { 486 /* User-visible flags. */ 487 case '1': 488 fatal("SSH protocol v.1 is no longer supported"); 489 break; 490 case '2': 491 /* Ignored */ 492 break; 493 case 'A': 494 case '4': 495 case '6': 496 case 'C': 497 addargs(&args, "-%c", ch); 498 addargs(&remote_remote_args, "-%c", ch); 499 break; 500 case 'D': 501 sftp_direct = optarg; 502 break; 503 case '3': 504 throughlocal = 1; 505 break; 506 case 'R': 507 throughlocal = 0; 508 break; 509 case 'o': 510 case 'c': 511 case 'i': 512 case 'F': 513 case 'J': 514 addargs(&remote_remote_args, "-%c", ch); 515 addargs(&remote_remote_args, "%s", optarg); 516 addargs(&args, "-%c", ch); 517 addargs(&args, "%s", optarg); 518 break; 519 case 'O': 520 mode = MODE_SCP; 521 break; 522 case 's': 523 mode = MODE_SFTP; 524 break; 525 case 'P': 526 sshport = a2port(optarg); 527 if (sshport <= 0) 528 fatal("bad port \"%s\"\n", optarg); 529 break; 530 case 'B': 531 addargs(&remote_remote_args, "-oBatchmode=yes"); 532 addargs(&args, "-oBatchmode=yes"); 533 break; 534 case 'l': 535 limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024, 536 &errstr); 537 if (errstr != NULL) 538 usage(); 539 limit_kbps *= 1024; /* kbps */ 540 bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN); 541 break; 542 case 'p': 543 pflag = 1; 544 break; 545 case 'r': 546 iamrecursive = 1; 547 break; 548 case 'S': 549 ssh_program = xstrdup(optarg); 550 break; 551 case 'v': 552 addargs(&args, "-v"); 553 addargs(&remote_remote_args, "-v"); 554 if (verbose_mode == 0) 555 log_level = SYSLOG_LEVEL_DEBUG1; 556 else if (log_level < SYSLOG_LEVEL_DEBUG3) 557 log_level++; 558 verbose_mode = 1; 559 break; 560 case 'q': 561 addargs(&args, "-q"); 562 addargs(&remote_remote_args, "-q"); 563 showprogress = 0; 564 break; 565 566 /* Server options. */ 567 case 'd': 568 targetshouldbedirectory = 1; 569 break; 570 case 'f': /* "from" */ 571 iamremote = 1; 572 fflag = 1; 573 break; 574 case 't': /* "to" */ 575 iamremote = 1; 576 tflag = 1; 577 #ifdef HAVE_CYGWIN 578 setmode(0, O_BINARY); 579 #endif 580 break; 581 case 'T': 582 Tflag = 1; 583 break; 584 default: 585 usage(); 586 } 587 } 588 argc -= optind; 589 argv += optind; 590 591 log_init(argv0, log_level, SYSLOG_FACILITY_USER, 1); 592 593 /* Do this last because we want the user to be able to override it */ 594 addargs(&args, "-oForwardAgent=no"); 595 596 if (iamremote) 597 mode = MODE_SCP; 598 599 if ((pwd = getpwuid(userid = getuid())) == NULL) 600 fatal("unknown user %u", (u_int) userid); 601 602 if (!isatty(STDOUT_FILENO)) 603 showprogress = 0; 604 605 if (pflag) { 606 /* Cannot pledge: -p allows setuid/setgid files... */ 607 } else { 608 if (pledge("stdio rpath wpath cpath fattr tty proc exec", 609 NULL) == -1) { 610 perror("pledge"); 611 exit(1); 612 } 613 } 614 615 remin = STDIN_FILENO; 616 remout = STDOUT_FILENO; 617 618 if (fflag) { 619 /* Follow "protocol", send data. */ 620 (void) response(); 621 source(argc, argv); 622 exit(errs != 0); 623 } 624 if (tflag) { 625 /* Receive data. */ 626 sink(argc, argv, NULL); 627 exit(errs != 0); 628 } 629 if (argc < 2) 630 usage(); 631 if (argc > 2) 632 targetshouldbedirectory = 1; 633 634 remin = remout = -1; 635 do_cmd_pid = -1; 636 /* Command to be executed on remote system using "ssh". */ 637 (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s", 638 verbose_mode ? " -v" : "", 639 iamrecursive ? " -r" : "", pflag ? " -p" : "", 640 targetshouldbedirectory ? " -d" : ""); 641 642 (void) ssh_signal(SIGPIPE, lostconn); 643 644 if (colon(argv[argc - 1])) /* Dest is remote host. */ 645 toremote(argc, argv, mode, sftp_direct); 646 else { 647 if (targetshouldbedirectory) 648 verifydir(argv[argc - 1]); 649 tolocal(argc, argv, mode, sftp_direct); /* Dest is local host. */ 650 } 651 /* 652 * Finally check the exit status of the ssh process, if one was forked 653 * and no error has occurred yet 654 */ 655 if (do_cmd_pid != -1 && errs == 0) { 656 if (remin != -1) 657 (void) close(remin); 658 if (remout != -1) 659 (void) close(remout); 660 if (waitpid(do_cmd_pid, &status, 0) == -1) 661 errs = 1; 662 else { 663 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) 664 errs = 1; 665 } 666 } 667 exit(errs != 0); 668 } 669 670 /* Callback from atomicio6 to update progress meter and limit bandwidth */ 671 static int 672 scpio(void *_cnt, size_t s) 673 { 674 off_t *cnt = (off_t *)_cnt; 675 676 *cnt += s; 677 refresh_progress_meter(0); 678 if (limit_kbps > 0) 679 bandwidth_limit(&bwlimit, s); 680 return 0; 681 } 682 683 static int 684 do_times(int fd, int verb, const struct stat *sb) 685 { 686 /* strlen(2^64) == 20; strlen(10^6) == 7 */ 687 char buf[(20 + 7 + 2) * 2 + 2]; 688 689 (void)snprintf(buf, sizeof(buf), "T%llu 0 %llu 0\n", 690 (unsigned long long) (sb->st_mtime < 0 ? 0 : sb->st_mtime), 691 (unsigned long long) (sb->st_atime < 0 ? 0 : sb->st_atime)); 692 if (verb) { 693 fprintf(stderr, "File mtime %lld atime %lld\n", 694 (long long)sb->st_mtime, (long long)sb->st_atime); 695 fprintf(stderr, "Sending file timestamps: %s", buf); 696 } 697 (void) atomicio(vwrite, fd, buf, strlen(buf)); 698 return (response()); 699 } 700 701 static int 702 parse_scp_uri(const char *uri, char **userp, char **hostp, int *portp, 703 char **pathp) 704 { 705 int r; 706 707 r = parse_uri("scp", uri, userp, hostp, portp, pathp); 708 if (r == 0 && *pathp == NULL) 709 *pathp = xstrdup("."); 710 return r; 711 } 712 713 /* Appends a string to an array; returns 0 on success, -1 on alloc failure */ 714 static int 715 append(char *cp, char ***ap, size_t *np) 716 { 717 char **tmp; 718 719 if ((tmp = reallocarray(*ap, *np + 1, sizeof(*tmp))) == NULL) 720 return -1; 721 tmp[(*np)] = cp; 722 (*np)++; 723 *ap = tmp; 724 return 0; 725 } 726 727 /* 728 * Finds the start and end of the first brace pair in the pattern. 729 * returns 0 on success or -1 for invalid patterns. 730 */ 731 static int 732 find_brace(const char *pattern, int *startp, int *endp) 733 { 734 int i; 735 int in_bracket, brace_level; 736 737 *startp = *endp = -1; 738 in_bracket = brace_level = 0; 739 for (i = 0; i < INT_MAX && *endp < 0 && pattern[i] != '\0'; i++) { 740 switch (pattern[i]) { 741 case '\\': 742 /* skip next character */ 743 if (pattern[i + 1] != '\0') 744 i++; 745 break; 746 case '[': 747 in_bracket = 1; 748 break; 749 case ']': 750 in_bracket = 0; 751 break; 752 case '{': 753 if (in_bracket) 754 break; 755 if (pattern[i + 1] == '}') { 756 /* Protect a single {}, for find(1), like csh */ 757 i++; /* skip */ 758 break; 759 } 760 if (*startp == -1) 761 *startp = i; 762 brace_level++; 763 break; 764 case '}': 765 if (in_bracket) 766 break; 767 if (*startp < 0) { 768 /* Unbalanced brace */ 769 return -1; 770 } 771 if (--brace_level <= 0) 772 *endp = i; 773 break; 774 } 775 } 776 /* unbalanced brackets/braces */ 777 if (*endp < 0 && (*startp >= 0 || in_bracket)) 778 return -1; 779 return 0; 780 } 781 782 /* 783 * Assembles and records a successfully-expanded pattern, returns -1 on 784 * alloc failure. 785 */ 786 static int 787 emit_expansion(const char *pattern, int brace_start, int brace_end, 788 int sel_start, int sel_end, char ***patternsp, size_t *npatternsp) 789 { 790 char *cp; 791 int o = 0, tail_len = strlen(pattern + brace_end + 1); 792 793 if ((cp = malloc(brace_start + (sel_end - sel_start) + 794 tail_len + 1)) == NULL) 795 return -1; 796 797 /* Pattern before initial brace */ 798 if (brace_start > 0) { 799 memcpy(cp, pattern, brace_start); 800 o = brace_start; 801 } 802 /* Current braced selection */ 803 if (sel_end - sel_start > 0) { 804 memcpy(cp + o, pattern + sel_start, 805 sel_end - sel_start); 806 o += sel_end - sel_start; 807 } 808 /* Remainder of pattern after closing brace */ 809 if (tail_len > 0) { 810 memcpy(cp + o, pattern + brace_end + 1, tail_len); 811 o += tail_len; 812 } 813 cp[o] = '\0'; 814 if (append(cp, patternsp, npatternsp) != 0) { 815 free(cp); 816 return -1; 817 } 818 return 0; 819 } 820 821 /* 822 * Expand the first encountered brace in pattern, appending the expanded 823 * patterns it yielded to the *patternsp array. 824 * 825 * Returns 0 on success or -1 on allocation failure. 826 * 827 * Signals whether expansion was performed via *expanded and whether 828 * pattern was invalid via *invalid. 829 */ 830 static int 831 brace_expand_one(const char *pattern, char ***patternsp, size_t *npatternsp, 832 int *expanded, int *invalid) 833 { 834 int i; 835 int in_bracket, brace_start, brace_end, brace_level; 836 int sel_start, sel_end; 837 838 *invalid = *expanded = 0; 839 840 if (find_brace(pattern, &brace_start, &brace_end) != 0) { 841 *invalid = 1; 842 return 0; 843 } else if (brace_start == -1) 844 return 0; 845 846 in_bracket = brace_level = 0; 847 for (i = sel_start = brace_start + 1; i < brace_end; i++) { 848 switch (pattern[i]) { 849 case '{': 850 if (in_bracket) 851 break; 852 brace_level++; 853 break; 854 case '}': 855 if (in_bracket) 856 break; 857 brace_level--; 858 break; 859 case '[': 860 in_bracket = 1; 861 break; 862 case ']': 863 in_bracket = 0; 864 break; 865 case '\\': 866 if (i < brace_end - 1) 867 i++; /* skip */ 868 break; 869 } 870 if (pattern[i] == ',' || i == brace_end - 1) { 871 if (in_bracket || brace_level > 0) 872 continue; 873 /* End of a selection, emit an expanded pattern */ 874 875 /* Adjust end index for last selection */ 876 sel_end = (i == brace_end - 1) ? brace_end : i; 877 if (emit_expansion(pattern, brace_start, brace_end, 878 sel_start, sel_end, patternsp, npatternsp) != 0) 879 return -1; 880 /* move on to the next selection */ 881 sel_start = i + 1; 882 continue; 883 } 884 } 885 if (in_bracket || brace_level > 0) { 886 *invalid = 1; 887 return 0; 888 } 889 /* success */ 890 *expanded = 1; 891 return 0; 892 } 893 894 /* Expand braces from pattern. Returns 0 on success, -1 on failure */ 895 static int 896 brace_expand(const char *pattern, char ***patternsp, size_t *npatternsp) 897 { 898 char *cp, *cp2, **active = NULL, **done = NULL; 899 size_t i, nactive = 0, ndone = 0; 900 int ret = -1, invalid = 0, expanded = 0; 901 902 *patternsp = NULL; 903 *npatternsp = 0; 904 905 /* Start the worklist with the original pattern */ 906 if ((cp = strdup(pattern)) == NULL) 907 return -1; 908 if (append(cp, &active, &nactive) != 0) { 909 free(cp); 910 return -1; 911 } 912 while (nactive > 0) { 913 cp = active[nactive - 1]; 914 nactive--; 915 if (brace_expand_one(cp, &active, &nactive, 916 &expanded, &invalid) == -1) { 917 free(cp); 918 goto fail; 919 } 920 if (invalid) 921 fatal_f("invalid brace pattern \"%s\"", cp); 922 if (expanded) { 923 /* 924 * Current entry expanded to new entries on the 925 * active list; discard the progenitor pattern. 926 */ 927 free(cp); 928 continue; 929 } 930 /* 931 * Pattern did not expand; append the finename component to 932 * the completed list 933 */ 934 if ((cp2 = strrchr(cp, '/')) != NULL) 935 *cp2++ = '\0'; 936 else 937 cp2 = cp; 938 if (append(xstrdup(cp2), &done, &ndone) != 0) { 939 free(cp); 940 goto fail; 941 } 942 free(cp); 943 } 944 /* success */ 945 *patternsp = done; 946 *npatternsp = ndone; 947 done = NULL; 948 ndone = 0; 949 ret = 0; 950 fail: 951 for (i = 0; i < nactive; i++) 952 free(active[i]); 953 free(active); 954 for (i = 0; i < ndone; i++) 955 free(done[i]); 956 free(done); 957 return ret; 958 } 959 960 static struct sftp_conn * 961 do_sftp_connect(char *host, char *user, int port, char *sftp_direct, 962 int *reminp, int *remoutp, int *pidp) 963 { 964 if (sftp_direct == NULL) { 965 if (do_cmd(ssh_program, host, user, port, 1, "sftp", 966 reminp, remoutp, pidp) < 0) 967 return NULL; 968 969 } else { 970 args.list = NULL; 971 addargs(&args, "sftp-server"); 972 if (do_cmd(sftp_direct, host, NULL, -1, 0, "sftp", 973 reminp, remoutp, pidp) < 0) 974 return NULL; 975 } 976 return do_init(*reminp, *remoutp, 32768, 64, limit_kbps); 977 } 978 979 void 980 toremote(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct) 981 { 982 char *suser = NULL, *host = NULL, *src = NULL; 983 char *bp, *tuser, *thost, *targ; 984 int sport = -1, tport = -1; 985 struct sftp_conn *conn = NULL, *conn2 = NULL; 986 arglist alist; 987 int i, r, status; 988 u_int j; 989 990 memset(&alist, '\0', sizeof(alist)); 991 alist.list = NULL; 992 993 /* Parse target */ 994 r = parse_scp_uri(argv[argc - 1], &tuser, &thost, &tport, &targ); 995 if (r == -1) { 996 fmprintf(stderr, "%s: invalid uri\n", argv[argc - 1]); 997 ++errs; 998 goto out; 999 } 1000 if (r != 0) { 1001 if (parse_user_host_path(argv[argc - 1], &tuser, &thost, 1002 &targ) == -1) { 1003 fmprintf(stderr, "%s: invalid target\n", argv[argc - 1]); 1004 ++errs; 1005 goto out; 1006 } 1007 } 1008 1009 /* Parse source files */ 1010 for (i = 0; i < argc - 1; i++) { 1011 free(suser); 1012 free(host); 1013 free(src); 1014 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src); 1015 if (r == -1) { 1016 fmprintf(stderr, "%s: invalid uri\n", argv[i]); 1017 ++errs; 1018 continue; 1019 } 1020 if (r != 0) { 1021 parse_user_host_path(argv[i], &suser, &host, &src); 1022 } 1023 if (suser != NULL && !okname(suser)) { 1024 ++errs; 1025 continue; 1026 } 1027 if (host && throughlocal) { /* extended remote to remote */ 1028 if (mode == MODE_SFTP) { 1029 if (remin == -1) { 1030 /* Connect to dest now */ 1031 conn = do_sftp_connect(thost, tuser, 1032 tport, sftp_direct, 1033 &remin, &remout, &do_cmd_pid); 1034 if (conn == NULL) { 1035 fatal("Unable to open " 1036 "destination connection"); 1037 } 1038 debug3_f("origin in %d out %d pid %ld", 1039 remin, remout, (long)do_cmd_pid); 1040 } 1041 /* 1042 * XXX remember suser/host/sport and only 1043 * reconnect if they change between arguments. 1044 * would save reconnections for cases like 1045 * scp -3 hosta:/foo hosta:/bar hostb: 1046 */ 1047 /* Connect to origin now */ 1048 conn2 = do_sftp_connect(host, suser, 1049 sport, sftp_direct, 1050 &remin2, &remout2, &do_cmd_pid2); 1051 if (conn2 == NULL) { 1052 fatal("Unable to open " 1053 "source connection"); 1054 } 1055 debug3_f("destination in %d out %d pid %ld", 1056 remin2, remout2, (long)do_cmd_pid2); 1057 throughlocal_sftp(conn2, conn, src, targ); 1058 (void) close(remin2); 1059 (void) close(remout2); 1060 remin2 = remout2 = -1; 1061 if (waitpid(do_cmd_pid2, &status, 0) == -1) 1062 ++errs; 1063 else if (!WIFEXITED(status) || 1064 WEXITSTATUS(status) != 0) 1065 ++errs; 1066 do_cmd_pid2 = -1; 1067 continue; 1068 } else { 1069 xasprintf(&bp, "%s -f %s%s", cmd, 1070 *src == '-' ? "-- " : "", src); 1071 if (do_cmd(ssh_program, host, suser, sport, 0, 1072 bp, &remin, &remout, &do_cmd_pid) < 0) 1073 exit(1); 1074 free(bp); 1075 xasprintf(&bp, "%s -t %s%s", cmd, 1076 *targ == '-' ? "-- " : "", targ); 1077 if (do_cmd2(thost, tuser, tport, bp, 1078 remin, remout) < 0) 1079 exit(1); 1080 free(bp); 1081 (void) close(remin); 1082 (void) close(remout); 1083 remin = remout = -1; 1084 } 1085 } else if (host) { /* standard remote to remote */ 1086 /* 1087 * Second remote user is passed to first remote side 1088 * via scp command-line. Ensure it contains no obvious 1089 * shell characters. 1090 */ 1091 if (tuser != NULL && !okname(tuser)) { 1092 ++errs; 1093 continue; 1094 } 1095 if (tport != -1 && tport != SSH_DEFAULT_PORT) { 1096 /* This would require the remote support URIs */ 1097 fatal("target port not supported with two " 1098 "remote hosts and the -R option"); 1099 } 1100 1101 freeargs(&alist); 1102 addargs(&alist, "%s", ssh_program); 1103 addargs(&alist, "-x"); 1104 addargs(&alist, "-oClearAllForwardings=yes"); 1105 addargs(&alist, "-n"); 1106 for (j = 0; j < remote_remote_args.num; j++) { 1107 addargs(&alist, "%s", 1108 remote_remote_args.list[j]); 1109 } 1110 1111 if (sport != -1) { 1112 addargs(&alist, "-p"); 1113 addargs(&alist, "%d", sport); 1114 } 1115 if (suser) { 1116 addargs(&alist, "-l"); 1117 addargs(&alist, "%s", suser); 1118 } 1119 addargs(&alist, "--"); 1120 addargs(&alist, "%s", host); 1121 addargs(&alist, "%s", cmd); 1122 addargs(&alist, "%s", src); 1123 addargs(&alist, "%s%s%s:%s", 1124 tuser ? tuser : "", tuser ? "@" : "", 1125 thost, targ); 1126 if (do_local_cmd(&alist) != 0) 1127 errs = 1; 1128 } else { /* local to remote */ 1129 if (mode == MODE_SFTP) { 1130 if (remin == -1) { 1131 /* Connect to remote now */ 1132 conn = do_sftp_connect(thost, tuser, 1133 tport, sftp_direct, 1134 &remin, &remout, &do_cmd_pid); 1135 if (conn == NULL) { 1136 fatal("Unable to open sftp " 1137 "connection"); 1138 } 1139 } 1140 1141 /* The protocol */ 1142 source_sftp(1, argv[i], targ, conn); 1143 continue; 1144 } 1145 /* SCP */ 1146 if (remin == -1) { 1147 xasprintf(&bp, "%s -t %s%s", cmd, 1148 *targ == '-' ? "-- " : "", targ); 1149 if (do_cmd(ssh_program, thost, tuser, tport, 0, 1150 bp, &remin, &remout, &do_cmd_pid) < 0) 1151 exit(1); 1152 if (response() < 0) 1153 exit(1); 1154 free(bp); 1155 } 1156 source(1, argv + i); 1157 } 1158 } 1159 out: 1160 if (mode == MODE_SFTP) 1161 free(conn); 1162 free(tuser); 1163 free(thost); 1164 free(targ); 1165 free(suser); 1166 free(host); 1167 free(src); 1168 } 1169 1170 void 1171 tolocal(int argc, char **argv, enum scp_mode_e mode, char *sftp_direct) 1172 { 1173 char *bp, *host = NULL, *src = NULL, *suser = NULL; 1174 arglist alist; 1175 struct sftp_conn *conn = NULL; 1176 int i, r, sport = -1; 1177 1178 memset(&alist, '\0', sizeof(alist)); 1179 alist.list = NULL; 1180 1181 for (i = 0; i < argc - 1; i++) { 1182 free(suser); 1183 free(host); 1184 free(src); 1185 r = parse_scp_uri(argv[i], &suser, &host, &sport, &src); 1186 if (r == -1) { 1187 fmprintf(stderr, "%s: invalid uri\n", argv[i]); 1188 ++errs; 1189 continue; 1190 } 1191 if (r != 0) 1192 parse_user_host_path(argv[i], &suser, &host, &src); 1193 if (suser != NULL && !okname(suser)) { 1194 ++errs; 1195 continue; 1196 } 1197 if (!host) { /* Local to local. */ 1198 freeargs(&alist); 1199 addargs(&alist, "%s", _PATH_CP); 1200 if (iamrecursive) 1201 addargs(&alist, "-r"); 1202 if (pflag) 1203 addargs(&alist, "-p"); 1204 addargs(&alist, "--"); 1205 addargs(&alist, "%s", argv[i]); 1206 addargs(&alist, "%s", argv[argc-1]); 1207 if (do_local_cmd(&alist)) 1208 ++errs; 1209 continue; 1210 } 1211 /* Remote to local. */ 1212 if (mode == MODE_SFTP) { 1213 conn = do_sftp_connect(host, suser, sport, 1214 sftp_direct, &remin, &remout, &do_cmd_pid); 1215 if (conn == NULL) { 1216 error("Couldn't make sftp connection " 1217 "to server"); 1218 ++errs; 1219 continue; 1220 } 1221 1222 /* The protocol */ 1223 sink_sftp(1, argv[argc - 1], src, conn); 1224 1225 free(conn); 1226 (void) close(remin); 1227 (void) close(remout); 1228 remin = remout = -1; 1229 continue; 1230 } 1231 /* SCP */ 1232 xasprintf(&bp, "%s -f %s%s", 1233 cmd, *src == '-' ? "-- " : "", src); 1234 if (do_cmd(ssh_program, host, suser, sport, 0, bp, 1235 &remin, &remout, &do_cmd_pid) < 0) { 1236 free(bp); 1237 ++errs; 1238 continue; 1239 } 1240 free(bp); 1241 sink(1, argv + argc - 1, src); 1242 (void) close(remin); 1243 remin = remout = -1; 1244 } 1245 free(suser); 1246 free(host); 1247 free(src); 1248 } 1249 1250 /* Prepare remote path, handling ~ by assuming cwd is the homedir */ 1251 static char * 1252 prepare_remote_path(struct sftp_conn *conn, const char *path) 1253 { 1254 /* Handle ~ prefixed paths */ 1255 if (*path != '~') 1256 return xstrdup(path); 1257 if (*path == '\0' || strcmp(path, "~") == 0) 1258 return xstrdup("."); 1259 if (strncmp(path, "~/", 2) == 0) 1260 return xstrdup(path + 2); 1261 if (can_expand_path(conn)) 1262 return do_expand_path(conn, path); 1263 /* No protocol extension */ 1264 error("~user paths are not currently supported"); 1265 return NULL; 1266 } 1267 1268 void 1269 source_sftp(int argc, char *src, char *targ, struct sftp_conn *conn) 1270 { 1271 char *target = NULL, *filename = NULL, *abs_dst = NULL; 1272 int target_is_dir; 1273 1274 if ((filename = basename(src)) == NULL) 1275 fatal("basename %s: %s", src, strerror(errno)); 1276 1277 /* 1278 * No need to glob here - the local shell already took care of 1279 * the expansions 1280 */ 1281 if ((target = prepare_remote_path(conn, targ)) == NULL) 1282 cleanup_exit(255); 1283 target_is_dir = remote_is_dir(conn, target); 1284 if (targetshouldbedirectory && !target_is_dir) { 1285 fatal("Target is not a directory, but more files selected " 1286 "for upload"); 1287 } 1288 if (target_is_dir) 1289 abs_dst = path_append(target, filename); 1290 else { 1291 abs_dst = target; 1292 target = NULL; 1293 } 1294 debug3_f("copying local %s to remote %s", src, abs_dst); 1295 1296 if (local_is_dir(src) && iamrecursive) { 1297 if (upload_dir(conn, src, abs_dst, pflag, 1298 SFTP_PROGRESS_ONLY, 0, 0, 1) != 0) { 1299 fatal("failed to upload directory %s to %s", 1300 src, abs_dst); 1301 } 1302 } else if (do_upload(conn, src, abs_dst, pflag, 0, 0) != 0) 1303 fatal("failed to upload file %s to %s", src, abs_dst); 1304 1305 free(abs_dst); 1306 free(target); 1307 } 1308 1309 void 1310 source(int argc, char **argv) 1311 { 1312 struct stat stb; 1313 static BUF buffer; 1314 BUF *bp; 1315 off_t i, statbytes; 1316 size_t amt, nr; 1317 int fd = -1, haderr, indx; 1318 char *last, *name, buf[PATH_MAX + 128], encname[PATH_MAX]; 1319 int len; 1320 1321 for (indx = 0; indx < argc; ++indx) { 1322 name = argv[indx]; 1323 statbytes = 0; 1324 len = strlen(name); 1325 while (len > 1 && name[len-1] == '/') 1326 name[--len] = '\0'; 1327 if ((fd = open(name, O_RDONLY|O_NONBLOCK, 0)) == -1) 1328 goto syserr; 1329 if (strchr(name, '\n') != NULL) { 1330 strnvis(encname, name, sizeof(encname), VIS_NL); 1331 name = encname; 1332 } 1333 if (fstat(fd, &stb) == -1) { 1334 syserr: run_err("%s: %s", name, strerror(errno)); 1335 goto next; 1336 } 1337 if (stb.st_size < 0) { 1338 run_err("%s: %s", name, "Negative file size"); 1339 goto next; 1340 } 1341 unset_nonblock(fd); 1342 switch (stb.st_mode & S_IFMT) { 1343 case S_IFREG: 1344 break; 1345 case S_IFDIR: 1346 if (iamrecursive) { 1347 rsource(name, &stb); 1348 goto next; 1349 } 1350 /* FALLTHROUGH */ 1351 default: 1352 run_err("%s: not a regular file", name); 1353 goto next; 1354 } 1355 if ((last = strrchr(name, '/')) == NULL) 1356 last = name; 1357 else 1358 ++last; 1359 curfile = last; 1360 if (pflag) { 1361 if (do_times(remout, verbose_mode, &stb) < 0) 1362 goto next; 1363 } 1364 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO) 1365 snprintf(buf, sizeof buf, "C%04o %lld %s\n", 1366 (u_int) (stb.st_mode & FILEMODEMASK), 1367 (long long)stb.st_size, last); 1368 if (verbose_mode) 1369 fmprintf(stderr, "Sending file modes: %s", buf); 1370 (void) atomicio(vwrite, remout, buf, strlen(buf)); 1371 if (response() < 0) 1372 goto next; 1373 if ((bp = allocbuf(&buffer, fd, COPY_BUFLEN)) == NULL) { 1374 next: if (fd != -1) { 1375 (void) close(fd); 1376 fd = -1; 1377 } 1378 continue; 1379 } 1380 if (showprogress) 1381 start_progress_meter(curfile, stb.st_size, &statbytes); 1382 set_nonblock(remout); 1383 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) { 1384 amt = bp->cnt; 1385 if (i + (off_t)amt > stb.st_size) 1386 amt = stb.st_size - i; 1387 if (!haderr) { 1388 if ((nr = atomicio(read, fd, 1389 bp->buf, amt)) != amt) { 1390 haderr = errno; 1391 memset(bp->buf + nr, 0, amt - nr); 1392 } 1393 } 1394 /* Keep writing after error to retain sync */ 1395 if (haderr) { 1396 (void)atomicio(vwrite, remout, bp->buf, amt); 1397 memset(bp->buf, 0, amt); 1398 continue; 1399 } 1400 if (atomicio6(vwrite, remout, bp->buf, amt, scpio, 1401 &statbytes) != amt) 1402 haderr = errno; 1403 } 1404 unset_nonblock(remout); 1405 1406 if (fd != -1) { 1407 if (close(fd) == -1 && !haderr) 1408 haderr = errno; 1409 fd = -1; 1410 } 1411 if (!haderr) 1412 (void) atomicio(vwrite, remout, "", 1); 1413 else 1414 run_err("%s: %s", name, strerror(haderr)); 1415 (void) response(); 1416 if (showprogress) 1417 stop_progress_meter(); 1418 } 1419 } 1420 1421 void 1422 rsource(char *name, struct stat *statp) 1423 { 1424 DIR *dirp; 1425 struct dirent *dp; 1426 char *last, *vect[1], path[PATH_MAX]; 1427 1428 if (!(dirp = opendir(name))) { 1429 run_err("%s: %s", name, strerror(errno)); 1430 return; 1431 } 1432 last = strrchr(name, '/'); 1433 if (last == NULL) 1434 last = name; 1435 else 1436 last++; 1437 if (pflag) { 1438 if (do_times(remout, verbose_mode, statp) < 0) { 1439 closedir(dirp); 1440 return; 1441 } 1442 } 1443 (void) snprintf(path, sizeof path, "D%04o %d %.1024s\n", 1444 (u_int) (statp->st_mode & FILEMODEMASK), 0, last); 1445 if (verbose_mode) 1446 fmprintf(stderr, "Entering directory: %s", path); 1447 (void) atomicio(vwrite, remout, path, strlen(path)); 1448 if (response() < 0) { 1449 closedir(dirp); 1450 return; 1451 } 1452 while ((dp = readdir(dirp)) != NULL) { 1453 if (dp->d_ino == 0) 1454 continue; 1455 if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) 1456 continue; 1457 if (strlen(name) + 1 + strlen(dp->d_name) >= sizeof(path) - 1) { 1458 run_err("%s/%s: name too long", name, dp->d_name); 1459 continue; 1460 } 1461 (void) snprintf(path, sizeof path, "%s/%s", name, dp->d_name); 1462 vect[0] = path; 1463 source(1, vect); 1464 } 1465 (void) closedir(dirp); 1466 (void) atomicio(vwrite, remout, "E\n", 2); 1467 (void) response(); 1468 } 1469 1470 void 1471 sink_sftp(int argc, char *dst, const char *src, struct sftp_conn *conn) 1472 { 1473 char *abs_src = NULL; 1474 char *abs_dst = NULL; 1475 glob_t g; 1476 char *filename, *tmp = NULL; 1477 int i, r, err = 0; 1478 1479 memset(&g, 0, sizeof(g)); 1480 /* 1481 * Here, we need remote glob as SFTP can not depend on remote shell 1482 * expansions 1483 */ 1484 1485 if ((abs_src = prepare_remote_path(conn, src)) == NULL) { 1486 err = -1; 1487 goto out; 1488 } 1489 1490 debug3_f("copying remote %s to local %s", abs_src, dst); 1491 if ((r = remote_glob(conn, abs_src, GLOB_MARK, NULL, &g)) != 0) { 1492 if (r == GLOB_NOSPACE) 1493 error("Too many glob matches for \"%s\".", abs_src); 1494 else 1495 error("File \"%s\" not found.", abs_src); 1496 err = -1; 1497 goto out; 1498 } 1499 1500 if (g.gl_matchc > 1 && !local_is_dir(dst)) { 1501 error("Multiple files match pattern, but destination " 1502 "\"%s\" is not a directory", dst); 1503 err = -1; 1504 goto out; 1505 } 1506 1507 for (i = 0; g.gl_pathv[i] && !interrupted; i++) { 1508 tmp = xstrdup(g.gl_pathv[i]); 1509 if ((filename = basename(tmp)) == NULL) { 1510 error("basename %s: %s", tmp, strerror(errno)); 1511 err = -1; 1512 goto out; 1513 } 1514 1515 if (local_is_dir(dst)) 1516 abs_dst = path_append(dst, filename); 1517 else 1518 abs_dst = xstrdup(dst); 1519 1520 debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst); 1521 if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) { 1522 if (download_dir(conn, g.gl_pathv[i], abs_dst, NULL, 1523 pflag, SFTP_PROGRESS_ONLY, 0, 0, 1) == -1) 1524 err = -1; 1525 } else { 1526 if (do_download(conn, g.gl_pathv[i], abs_dst, NULL, 1527 pflag, 0, 0) == -1) 1528 err = -1; 1529 } 1530 free(abs_dst); 1531 abs_dst = NULL; 1532 free(tmp); 1533 tmp = NULL; 1534 } 1535 1536 out: 1537 free(abs_src); 1538 free(tmp); 1539 globfree(&g); 1540 if (err == -1) { 1541 fatal("Failed to download file '%s'", src); 1542 } 1543 } 1544 1545 1546 #define TYPE_OVERFLOW(type, val) \ 1547 ((sizeof(type) == 4 && (val) > INT32_MAX) || \ 1548 (sizeof(type) == 8 && (val) > INT64_MAX) || \ 1549 (sizeof(type) != 4 && sizeof(type) != 8)) 1550 1551 void 1552 sink(int argc, char **argv, const char *src) 1553 { 1554 static BUF buffer; 1555 struct stat stb; 1556 BUF *bp; 1557 off_t i; 1558 size_t j, count; 1559 int amt, exists, first, ofd; 1560 mode_t mode, omode, mask; 1561 off_t size, statbytes; 1562 unsigned long long ull; 1563 int setimes, targisdir, wrerr; 1564 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048], visbuf[2048]; 1565 char **patterns = NULL; 1566 size_t n, npatterns = 0; 1567 struct timeval tv[2]; 1568 1569 #define atime tv[0] 1570 #define mtime tv[1] 1571 #define SCREWUP(str) { why = str; goto screwup; } 1572 1573 if (TYPE_OVERFLOW(time_t, 0) || TYPE_OVERFLOW(off_t, 0)) 1574 SCREWUP("Unexpected off_t/time_t size"); 1575 1576 setimes = targisdir = 0; 1577 mask = umask(0); 1578 if (!pflag) 1579 (void) umask(mask); 1580 if (argc != 1) { 1581 run_err("ambiguous target"); 1582 exit(1); 1583 } 1584 targ = *argv; 1585 if (targetshouldbedirectory) 1586 verifydir(targ); 1587 1588 (void) atomicio(vwrite, remout, "", 1); 1589 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode)) 1590 targisdir = 1; 1591 if (src != NULL && !iamrecursive && !Tflag) { 1592 /* 1593 * Prepare to try to restrict incoming filenames to match 1594 * the requested destination file glob. 1595 */ 1596 if (brace_expand(src, &patterns, &npatterns) != 0) 1597 fatal_f("could not expand pattern"); 1598 } 1599 for (first = 1;; first = 0) { 1600 cp = buf; 1601 if (atomicio(read, remin, cp, 1) != 1) 1602 goto done; 1603 if (*cp++ == '\n') 1604 SCREWUP("unexpected <newline>"); 1605 do { 1606 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch)) 1607 SCREWUP("lost connection"); 1608 *cp++ = ch; 1609 } while (cp < &buf[sizeof(buf) - 1] && ch != '\n'); 1610 *cp = 0; 1611 if (verbose_mode) 1612 fmprintf(stderr, "Sink: %s", buf); 1613 1614 if (buf[0] == '\01' || buf[0] == '\02') { 1615 if (iamremote == 0) { 1616 (void) snmprintf(visbuf, sizeof(visbuf), 1617 NULL, "%s", buf + 1); 1618 (void) atomicio(vwrite, STDERR_FILENO, 1619 visbuf, strlen(visbuf)); 1620 } 1621 if (buf[0] == '\02') 1622 exit(1); 1623 ++errs; 1624 continue; 1625 } 1626 if (buf[0] == 'E') { 1627 (void) atomicio(vwrite, remout, "", 1); 1628 goto done; 1629 } 1630 if (ch == '\n') 1631 *--cp = 0; 1632 1633 cp = buf; 1634 if (*cp == 'T') { 1635 setimes++; 1636 cp++; 1637 if (!isdigit((unsigned char)*cp)) 1638 SCREWUP("mtime.sec not present"); 1639 ull = strtoull(cp, &cp, 10); 1640 if (!cp || *cp++ != ' ') 1641 SCREWUP("mtime.sec not delimited"); 1642 if (TYPE_OVERFLOW(time_t, ull)) 1643 setimes = 0; /* out of range */ 1644 mtime.tv_sec = ull; 1645 mtime.tv_usec = strtol(cp, &cp, 10); 1646 if (!cp || *cp++ != ' ' || mtime.tv_usec < 0 || 1647 mtime.tv_usec > 999999) 1648 SCREWUP("mtime.usec not delimited"); 1649 if (!isdigit((unsigned char)*cp)) 1650 SCREWUP("atime.sec not present"); 1651 ull = strtoull(cp, &cp, 10); 1652 if (!cp || *cp++ != ' ') 1653 SCREWUP("atime.sec not delimited"); 1654 if (TYPE_OVERFLOW(time_t, ull)) 1655 setimes = 0; /* out of range */ 1656 atime.tv_sec = ull; 1657 atime.tv_usec = strtol(cp, &cp, 10); 1658 if (!cp || *cp++ != '\0' || atime.tv_usec < 0 || 1659 atime.tv_usec > 999999) 1660 SCREWUP("atime.usec not delimited"); 1661 (void) atomicio(vwrite, remout, "", 1); 1662 continue; 1663 } 1664 if (*cp != 'C' && *cp != 'D') { 1665 /* 1666 * Check for the case "rcp remote:foo\* local:bar". 1667 * In this case, the line "No match." can be returned 1668 * by the shell before the rcp command on the remote is 1669 * executed so the ^Aerror_message convention isn't 1670 * followed. 1671 */ 1672 if (first) { 1673 run_err("%s", cp); 1674 exit(1); 1675 } 1676 SCREWUP("expected control record"); 1677 } 1678 mode = 0; 1679 for (++cp; cp < buf + 5; cp++) { 1680 if (*cp < '0' || *cp > '7') 1681 SCREWUP("bad mode"); 1682 mode = (mode << 3) | (*cp - '0'); 1683 } 1684 if (!pflag) 1685 mode &= ~mask; 1686 if (*cp++ != ' ') 1687 SCREWUP("mode not delimited"); 1688 1689 if (!isdigit((unsigned char)*cp)) 1690 SCREWUP("size not present"); 1691 ull = strtoull(cp, &cp, 10); 1692 if (!cp || *cp++ != ' ') 1693 SCREWUP("size not delimited"); 1694 if (TYPE_OVERFLOW(off_t, ull)) 1695 SCREWUP("size out of range"); 1696 size = (off_t)ull; 1697 1698 if (*cp == '\0' || strchr(cp, '/') != NULL || 1699 strcmp(cp, ".") == 0 || strcmp(cp, "..") == 0) { 1700 run_err("error: unexpected filename: %s", cp); 1701 exit(1); 1702 } 1703 if (npatterns > 0) { 1704 for (n = 0; n < npatterns; n++) { 1705 if (fnmatch(patterns[n], cp, 0) == 0) 1706 break; 1707 } 1708 if (n >= npatterns) 1709 SCREWUP("filename does not match request"); 1710 } 1711 if (targisdir) { 1712 static char *namebuf; 1713 static size_t cursize; 1714 size_t need; 1715 1716 need = strlen(targ) + strlen(cp) + 250; 1717 if (need > cursize) { 1718 free(namebuf); 1719 namebuf = xmalloc(need); 1720 cursize = need; 1721 } 1722 (void) snprintf(namebuf, need, "%s%s%s", targ, 1723 strcmp(targ, "/") ? "/" : "", cp); 1724 np = namebuf; 1725 } else 1726 np = targ; 1727 curfile = cp; 1728 exists = stat(np, &stb) == 0; 1729 if (buf[0] == 'D') { 1730 int mod_flag = pflag; 1731 if (!iamrecursive) 1732 SCREWUP("received directory without -r"); 1733 if (exists) { 1734 if (!S_ISDIR(stb.st_mode)) { 1735 errno = ENOTDIR; 1736 goto bad; 1737 } 1738 if (pflag) 1739 (void) chmod(np, mode); 1740 } else { 1741 /* Handle copying from a read-only directory */ 1742 mod_flag = 1; 1743 if (mkdir(np, mode | S_IRWXU) == -1) 1744 goto bad; 1745 } 1746 vect[0] = xstrdup(np); 1747 sink(1, vect, src); 1748 if (setimes) { 1749 setimes = 0; 1750 (void) utimes(vect[0], tv); 1751 } 1752 if (mod_flag) 1753 (void) chmod(vect[0], mode); 1754 free(vect[0]); 1755 continue; 1756 } 1757 omode = mode; 1758 mode |= S_IWUSR; 1759 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) == -1) { 1760 bad: run_err("%s: %s", np, strerror(errno)); 1761 continue; 1762 } 1763 (void) atomicio(vwrite, remout, "", 1); 1764 if ((bp = allocbuf(&buffer, ofd, COPY_BUFLEN)) == NULL) { 1765 (void) close(ofd); 1766 continue; 1767 } 1768 cp = bp->buf; 1769 wrerr = 0; 1770 1771 /* 1772 * NB. do not use run_err() unless immediately followed by 1773 * exit() below as it may send a spurious reply that might 1774 * desyncronise us from the peer. Use note_err() instead. 1775 */ 1776 statbytes = 0; 1777 if (showprogress) 1778 start_progress_meter(curfile, size, &statbytes); 1779 set_nonblock(remin); 1780 for (count = i = 0; i < size; i += bp->cnt) { 1781 amt = bp->cnt; 1782 if (i + amt > size) 1783 amt = size - i; 1784 count += amt; 1785 do { 1786 j = atomicio6(read, remin, cp, amt, 1787 scpio, &statbytes); 1788 if (j == 0) { 1789 run_err("%s", j != EPIPE ? 1790 strerror(errno) : 1791 "dropped connection"); 1792 exit(1); 1793 } 1794 amt -= j; 1795 cp += j; 1796 } while (amt > 0); 1797 1798 if (count == bp->cnt) { 1799 /* Keep reading so we stay sync'd up. */ 1800 if (!wrerr) { 1801 if (atomicio(vwrite, ofd, bp->buf, 1802 count) != count) { 1803 note_err("%s: %s", np, 1804 strerror(errno)); 1805 wrerr = 1; 1806 } 1807 } 1808 count = 0; 1809 cp = bp->buf; 1810 } 1811 } 1812 unset_nonblock(remin); 1813 if (count != 0 && !wrerr && 1814 atomicio(vwrite, ofd, bp->buf, count) != count) { 1815 note_err("%s: %s", np, strerror(errno)); 1816 wrerr = 1; 1817 } 1818 if (!wrerr && (!exists || S_ISREG(stb.st_mode)) && 1819 ftruncate(ofd, size) != 0) 1820 note_err("%s: truncate: %s", np, strerror(errno)); 1821 if (pflag) { 1822 if (exists || omode != mode) 1823 #ifdef HAVE_FCHMOD 1824 if (fchmod(ofd, omode)) { 1825 #else /* HAVE_FCHMOD */ 1826 if (chmod(np, omode)) { 1827 #endif /* HAVE_FCHMOD */ 1828 note_err("%s: set mode: %s", 1829 np, strerror(errno)); 1830 } 1831 } else { 1832 if (!exists && omode != mode) 1833 #ifdef HAVE_FCHMOD 1834 if (fchmod(ofd, omode & ~mask)) { 1835 #else /* HAVE_FCHMOD */ 1836 if (chmod(np, omode & ~mask)) { 1837 #endif /* HAVE_FCHMOD */ 1838 note_err("%s: set mode: %s", 1839 np, strerror(errno)); 1840 } 1841 } 1842 if (close(ofd) == -1) 1843 note_err("%s: close: %s", np, strerror(errno)); 1844 (void) response(); 1845 if (showprogress) 1846 stop_progress_meter(); 1847 if (setimes && !wrerr) { 1848 setimes = 0; 1849 if (utimes(np, tv) == -1) { 1850 note_err("%s: set times: %s", 1851 np, strerror(errno)); 1852 } 1853 } 1854 /* If no error was noted then signal success for this file */ 1855 if (note_err(NULL) == 0) 1856 (void) atomicio(vwrite, remout, "", 1); 1857 } 1858 done: 1859 for (n = 0; n < npatterns; n++) 1860 free(patterns[n]); 1861 free(patterns); 1862 return; 1863 screwup: 1864 for (n = 0; n < npatterns; n++) 1865 free(patterns[n]); 1866 free(patterns); 1867 run_err("protocol error: %s", why); 1868 exit(1); 1869 } 1870 1871 void 1872 throughlocal_sftp(struct sftp_conn *from, struct sftp_conn *to, 1873 char *src, char *targ) 1874 { 1875 char *target = NULL, *filename = NULL, *abs_dst = NULL; 1876 char *abs_src = NULL, *tmp = NULL; 1877 glob_t g; 1878 int i, r, targetisdir, err = 0; 1879 1880 if ((filename = basename(src)) == NULL) 1881 fatal("basename %s: %s", src, strerror(errno)); 1882 1883 if ((abs_src = prepare_remote_path(from, src)) == NULL || 1884 (target = prepare_remote_path(to, targ)) == NULL) 1885 cleanup_exit(255); 1886 memset(&g, 0, sizeof(g)); 1887 1888 targetisdir = remote_is_dir(to, target); 1889 if (!targetisdir && targetshouldbedirectory) { 1890 error("Destination path \"%s\" is not a directory", target); 1891 err = -1; 1892 goto out; 1893 } 1894 1895 debug3_f("copying remote %s to remote %s", abs_src, target); 1896 if ((r = remote_glob(from, abs_src, GLOB_MARK, NULL, &g)) != 0) { 1897 if (r == GLOB_NOSPACE) 1898 error("Too many glob matches for \"%s\".", abs_src); 1899 else 1900 error("File \"%s\" not found.", abs_src); 1901 err = -1; 1902 goto out; 1903 } 1904 1905 for (i = 0; g.gl_pathv[i] && !interrupted; i++) { 1906 tmp = xstrdup(g.gl_pathv[i]); 1907 if ((filename = basename(tmp)) == NULL) { 1908 error("basename %s: %s", tmp, strerror(errno)); 1909 err = -1; 1910 goto out; 1911 } 1912 1913 if (targetisdir) 1914 abs_dst = path_append(target, filename); 1915 else 1916 abs_dst = xstrdup(target); 1917 1918 debug("Fetching %s to %s\n", g.gl_pathv[i], abs_dst); 1919 if (globpath_is_dir(g.gl_pathv[i]) && iamrecursive) { 1920 if (crossload_dir(from, to, g.gl_pathv[i], abs_dst, 1921 NULL, pflag, SFTP_PROGRESS_ONLY, 1) == -1) 1922 err = -1; 1923 } else { 1924 if (do_crossload(from, to, g.gl_pathv[i], abs_dst, NULL, 1925 pflag) == -1) 1926 err = -1; 1927 } 1928 free(abs_dst); 1929 abs_dst = NULL; 1930 free(tmp); 1931 tmp = NULL; 1932 } 1933 1934 out: 1935 free(abs_src); 1936 free(abs_dst); 1937 free(target); 1938 free(tmp); 1939 globfree(&g); 1940 if (err == -1) 1941 fatal("Failed to download file '%s'", src); 1942 } 1943 1944 int 1945 response(void) 1946 { 1947 char ch, *cp, resp, rbuf[2048], visbuf[2048]; 1948 1949 if (atomicio(read, remin, &resp, sizeof(resp)) != sizeof(resp)) 1950 lostconn(0); 1951 1952 cp = rbuf; 1953 switch (resp) { 1954 case 0: /* ok */ 1955 return (0); 1956 default: 1957 *cp++ = resp; 1958 /* FALLTHROUGH */ 1959 case 1: /* error, followed by error msg */ 1960 case 2: /* fatal error, "" */ 1961 do { 1962 if (atomicio(read, remin, &ch, sizeof(ch)) != sizeof(ch)) 1963 lostconn(0); 1964 *cp++ = ch; 1965 } while (cp < &rbuf[sizeof(rbuf) - 1] && ch != '\n'); 1966 1967 if (!iamremote) { 1968 cp[-1] = '\0'; 1969 (void) snmprintf(visbuf, sizeof(visbuf), 1970 NULL, "%s\n", rbuf); 1971 (void) atomicio(vwrite, STDERR_FILENO, 1972 visbuf, strlen(visbuf)); 1973 } 1974 ++errs; 1975 if (resp == 1) 1976 return (-1); 1977 exit(1); 1978 } 1979 /* NOTREACHED */ 1980 } 1981 1982 void 1983 usage(void) 1984 { 1985 (void) fprintf(stderr, 1986 "usage: scp [-346ABCOpqRrsTv] [-c cipher] [-D sftp_server_path] [-F ssh_config]\n" 1987 " [-i identity_file] [-J destination] [-l limit]\n" 1988 " [-o ssh_option] [-P port] [-S program] source ... target\n"); 1989 exit(1); 1990 } 1991 1992 void 1993 run_err(const char *fmt,...) 1994 { 1995 static FILE *fp; 1996 va_list ap; 1997 1998 ++errs; 1999 if (fp != NULL || (remout != -1 && (fp = fdopen(remout, "w")))) { 2000 (void) fprintf(fp, "%c", 0x01); 2001 (void) fprintf(fp, "scp: "); 2002 va_start(ap, fmt); 2003 (void) vfprintf(fp, fmt, ap); 2004 va_end(ap); 2005 (void) fprintf(fp, "\n"); 2006 (void) fflush(fp); 2007 } 2008 2009 if (!iamremote) { 2010 va_start(ap, fmt); 2011 vfmprintf(stderr, fmt, ap); 2012 va_end(ap); 2013 fprintf(stderr, "\n"); 2014 } 2015 } 2016 2017 /* 2018 * Notes a sink error for sending at the end of a file transfer. Returns 0 if 2019 * no error has been noted or -1 otherwise. Use note_err(NULL) to flush 2020 * any active error at the end of the transfer. 2021 */ 2022 int 2023 note_err(const char *fmt, ...) 2024 { 2025 static char *emsg; 2026 va_list ap; 2027 2028 /* Replay any previously-noted error */ 2029 if (fmt == NULL) { 2030 if (emsg == NULL) 2031 return 0; 2032 run_err("%s", emsg); 2033 free(emsg); 2034 emsg = NULL; 2035 return -1; 2036 } 2037 2038 errs++; 2039 /* Prefer first-noted error */ 2040 if (emsg != NULL) 2041 return -1; 2042 2043 va_start(ap, fmt); 2044 vasnmprintf(&emsg, INT_MAX, NULL, fmt, ap); 2045 va_end(ap); 2046 return -1; 2047 } 2048 2049 void 2050 verifydir(char *cp) 2051 { 2052 struct stat stb; 2053 2054 if (!stat(cp, &stb)) { 2055 if (S_ISDIR(stb.st_mode)) 2056 return; 2057 errno = ENOTDIR; 2058 } 2059 run_err("%s: %s", cp, strerror(errno)); 2060 killchild(0); 2061 } 2062 2063 int 2064 okname(char *cp0) 2065 { 2066 int c; 2067 char *cp; 2068 2069 cp = cp0; 2070 do { 2071 c = (int)*cp; 2072 if (c & 0200) 2073 goto bad; 2074 if (!isalpha(c) && !isdigit((unsigned char)c)) { 2075 switch (c) { 2076 case '\'': 2077 case '"': 2078 case '`': 2079 case ' ': 2080 case '#': 2081 goto bad; 2082 default: 2083 break; 2084 } 2085 } 2086 } while (*++cp); 2087 return (1); 2088 2089 bad: fmprintf(stderr, "%s: invalid user name\n", cp0); 2090 return (0); 2091 } 2092 2093 BUF * 2094 allocbuf(BUF *bp, int fd, int blksize) 2095 { 2096 size_t size; 2097 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE 2098 struct stat stb; 2099 2100 if (fstat(fd, &stb) == -1) { 2101 run_err("fstat: %s", strerror(errno)); 2102 return (0); 2103 } 2104 size = ROUNDUP(stb.st_blksize, blksize); 2105 if (size == 0) 2106 size = blksize; 2107 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */ 2108 size = blksize; 2109 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */ 2110 if (bp->cnt >= size) 2111 return (bp); 2112 bp->buf = xrecallocarray(bp->buf, bp->cnt, size, 1); 2113 bp->cnt = size; 2114 return (bp); 2115 } 2116 2117 void 2118 lostconn(int signo) 2119 { 2120 if (!iamremote) 2121 (void)write(STDERR_FILENO, "lost connection\n", 16); 2122 if (signo) 2123 _exit(1); 2124 else 2125 exit(1); 2126 } 2127 2128 void 2129 cleanup_exit(int i) 2130 { 2131 if (remin > 0) 2132 close(remin); 2133 if (remout > 0) 2134 close(remout); 2135 if (remin2 > 0) 2136 close(remin2); 2137 if (remout2 > 0) 2138 close(remout2); 2139 if (do_cmd_pid > 0) 2140 waitpid(do_cmd_pid, NULL, 0); 2141 if (do_cmd_pid2 > 0) 2142 waitpid(do_cmd_pid2, NULL, 0); 2143 exit(i); 2144 } 2145