1 /* 2 * Copyright 2006 Sun Microsystems, Inc. All rights reserved. 3 * Use is subject to license terms. 4 */ 5 /* 6 * scp - secure remote copy. This is basically patched BSD rcp which 7 * uses ssh to do the data transfer (instead of using rcmd). 8 * 9 * NOTE: This version should NOT be suid root. (This uses ssh to 10 * do the transfer and ssh has the necessary privileges.) 11 * 12 * 1995 Timo Rinne <tri@iki.fi>, Tatu Ylonen <ylo@cs.hut.fi> 13 * 14 * As far as I am concerned, the code I have written for this software 15 * can be used freely for any purpose. Any derived versions of this 16 * software must be clearly marked as such, and if the derived work is 17 * incompatible with the protocol description in the RFC file, it must be 18 * called by a name other than "ssh" or "Secure Shell". 19 */ 20 /* 21 * Copyright (c) 1999 Theo de Raadt. All rights reserved. 22 * Copyright (c) 1999 Aaron Campbell. All rights reserved. 23 * 24 * Redistribution and use in source and binary forms, with or without 25 * modification, are permitted provided that the following conditions 26 * are met: 27 * 1. Redistributions of source code must retain the above copyright 28 * notice, this list of conditions and the following disclaimer. 29 * 2. Redistributions in binary form must reproduce the above copyright 30 * notice, this list of conditions and the following disclaimer in the 31 * documentation and/or other materials provided with the distribution. 32 * 33 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 34 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 35 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 36 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 37 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 38 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 39 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 40 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 41 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 42 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 43 */ 44 45 /* 46 * Parts from: 47 * 48 * Copyright (c) 1983, 1990, 1992, 1993, 1995 49 * The Regents of the University of California. All rights reserved. 50 * 51 * Redistribution and use in source and binary forms, with or without 52 * modification, are permitted provided that the following conditions 53 * are met: 54 * 1. Redistributions of source code must retain the above copyright 55 * notice, this list of conditions and the following disclaimer. 56 * 2. Redistributions in binary form must reproduce the above copyright 57 * notice, this list of conditions and the following disclaimer in the 58 * documentation and/or other materials provided with the distribution. 59 * 3. All advertising materials mentioning features or use of this software 60 * must display the following acknowledgement: 61 * This product includes software developed by the University of 62 * California, Berkeley and its contributors. 63 * 4. Neither the name of the University nor the names of its contributors 64 * may be used to endorse or promote products derived from this software 65 * without specific prior written permission. 66 * 67 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 68 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 69 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 70 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 71 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 72 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 73 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 74 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 75 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 76 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 77 * SUCH DAMAGE. 78 * 79 */ 80 81 #include "includes.h" 82 RCSID("$OpenBSD: scp.c,v 1.91 2002/06/19 00:27:55 deraadt Exp $"); 83 84 #pragma ident "%Z%%M% %I% %E% SMI" 85 86 #include "xmalloc.h" 87 #include "atomicio.h" 88 #include "pathnames.h" 89 #include "log.h" 90 #include "misc.h" 91 92 #ifdef HAVE___PROGNAME 93 extern char *__progname; 94 #else 95 char *__progname; 96 #endif 97 98 /* For progressmeter() -- number of seconds before xfer considered "stalled" */ 99 #define STALLTIME 5 100 /* alarm() interval for updating progress meter */ 101 #define PROGRESSTIME 1 102 103 /* Visual statistics about files as they are transferred. */ 104 void progressmeter(int); 105 106 /* Returns width of the terminal (for progress meter calculations). */ 107 int getttywidth(void); 108 int do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, 109 int argc); 110 111 /* Struct for addargs */ 112 arglist args; 113 114 /* Time a transfer started. */ 115 static struct timeval start; 116 117 /* Number of bytes of current file transferred so far. */ 118 volatile off_t statbytes; 119 120 /* Total size of current file. */ 121 off_t totalbytes = 0; 122 123 /* Name of current file being transferred. */ 124 char *curfile; 125 126 /* This is set to non-zero to enable verbose mode. */ 127 int verbose_mode = 0; 128 129 /* This is set to zero if the progressmeter is not desired. */ 130 int showprogress = 1; 131 132 /* This is the program to execute for the secured connection. ("ssh" or -S) */ 133 char *ssh_program = _PATH_SSH_PROGRAM; 134 135 /* This is used to store the pid of ssh_program */ 136 static pid_t do_cmd_pid; 137 138 /* 139 * This function executes the given command as the specified user on the 140 * given host. This returns < 0 if execution fails, and >= 0 otherwise. This 141 * assigns the input and output file descriptors on success. 142 */ 143 144 int 145 do_cmd(char *host, char *remuser, char *cmd, int *fdin, int *fdout, int argc) 146 { 147 int pin[2], pout[2], reserved[2]; 148 149 if (verbose_mode) 150 fprintf(stderr, 151 gettext("Executing: program %s host %s, " 152 "user %s, command %s\n"), 153 ssh_program, host, 154 remuser ? remuser : gettext("(unspecified)"), cmd); 155 156 /* 157 * Reserve two descriptors so that the real pipes won't get 158 * descriptors 0 and 1 because that will screw up dup2 below. 159 */ 160 pipe(reserved); 161 162 /* Create a socket pair for communicating with ssh. */ 163 if (pipe(pin) < 0) 164 fatal("pipe: %s", strerror(errno)); 165 if (pipe(pout) < 0) 166 fatal("pipe: %s", strerror(errno)); 167 168 /* Free the reserved descriptors. */ 169 close(reserved[0]); 170 close(reserved[1]); 171 172 /* For a child to execute the command on the remote host using ssh. */ 173 if ((do_cmd_pid = fork()) == 0) { 174 /* Child. */ 175 close(pin[1]); 176 close(pout[0]); 177 dup2(pin[0], 0); 178 dup2(pout[1], 1); 179 close(pin[0]); 180 close(pout[1]); 181 182 args.list[0] = ssh_program; 183 if (remuser != NULL) 184 addargs(&args, "-l%s", remuser); 185 addargs(&args, "%s", host); 186 addargs(&args, "%s", cmd); 187 188 execvp(ssh_program, args.list); 189 perror(ssh_program); 190 exit(1); 191 } else if (do_cmd_pid == (pid_t)-1) { 192 /* fork() failed */ 193 fatal("fork: %s", strerror(errno)); 194 } 195 196 /* Parent. Close the other side, and return the local side. */ 197 close(pin[0]); 198 *fdout = pin[1]; 199 close(pout[1]); 200 *fdin = pout[0]; 201 return (0); 202 } 203 204 typedef struct { 205 int cnt; 206 char *buf; 207 } BUF; 208 209 BUF *allocbuf(BUF *, int, int); 210 void lostconn(int); 211 void nospace(void); 212 int okname(char *); 213 void run_err(const char *, ...); 214 void verifydir(char *); 215 216 struct passwd *pwd; 217 uid_t userid; 218 int errs, remin, remout; 219 int pflag, iamremote, iamrecursive, targetshouldbedirectory; 220 221 #define CMDNEEDS 64 222 char cmd[CMDNEEDS]; /* must hold "rcp -r -p -d\0" */ 223 224 int response(void); 225 void rsource(char *, struct stat *); 226 void sink(int, char *[]); 227 void source(int, char *[]); 228 void tolocal(int, char *[]); 229 void toremote(char *, int, char *[]); 230 void usage(void); 231 232 int 233 main(argc, argv) 234 int argc; 235 char *argv[]; 236 { 237 int ch, fflag, tflag, status; 238 char *targ; 239 extern char *optarg; 240 extern int optind; 241 242 __progname = get_progname(argv[0]); 243 244 g11n_setlocale(LC_ALL, ""); 245 246 args.list = NULL; 247 addargs(&args, "ssh"); /* overwritten with ssh_program */ 248 addargs(&args, "-x"); 249 addargs(&args, "-oForwardAgent no"); 250 addargs(&args, "-oClearAllForwardings yes"); 251 252 fflag = tflag = 0; 253 while ((ch = getopt(argc, argv, "dfprtvBCc:i:P:q46S:o:F:")) != -1) 254 switch (ch) { 255 /* User-visible flags. */ 256 case '4': 257 case '6': 258 case 'C': 259 addargs(&args, "-%c", ch); 260 break; 261 case 'o': 262 case 'c': 263 case 'i': 264 case 'F': 265 addargs(&args, "-%c%s", ch, optarg); 266 break; 267 case 'P': 268 addargs(&args, "-p%s", optarg); 269 break; 270 case 'B': 271 addargs(&args, "-oBatchmode yes"); 272 break; 273 case 'p': 274 pflag = 1; 275 break; 276 case 'r': 277 iamrecursive = 1; 278 break; 279 case 'S': 280 ssh_program = xstrdup(optarg); 281 break; 282 case 'v': 283 addargs(&args, "-v"); 284 verbose_mode = 1; 285 break; 286 case 'q': 287 showprogress = 0; 288 break; 289 290 /* Server options. */ 291 case 'd': 292 targetshouldbedirectory = 1; 293 break; 294 case 'f': /* "from" */ 295 iamremote = 1; 296 fflag = 1; 297 break; 298 case 't': /* "to" */ 299 iamremote = 1; 300 tflag = 1; 301 #ifdef HAVE_CYGWIN 302 setmode(0, O_BINARY); 303 #endif 304 break; 305 default: 306 usage(); 307 } 308 argc -= optind; 309 argv += optind; 310 311 if ((pwd = getpwuid(userid = getuid())) == NULL) 312 fatal("unknown user %d", (int)userid); 313 314 if (!isatty(STDERR_FILENO)) 315 showprogress = 0; 316 317 remin = STDIN_FILENO; 318 remout = STDOUT_FILENO; 319 320 if (fflag) { 321 /* Follow "protocol", send data. */ 322 (void) response(); 323 source(argc, argv); 324 exit(errs != 0); 325 } 326 if (tflag) { 327 /* Receive data. */ 328 sink(argc, argv); 329 exit(errs != 0); 330 } 331 if (argc < 2) 332 usage(); 333 if (argc > 2) 334 targetshouldbedirectory = 1; 335 336 remin = remout = -1; 337 do_cmd_pid = (pid_t)-1; 338 339 /* Command to be executed on remote system using "ssh". */ 340 (void) snprintf(cmd, sizeof (cmd), "scp%s%s%s%s", 341 verbose_mode ? " -v" : "", 342 iamrecursive ? " -r" : "", pflag ? " -p" : "", 343 targetshouldbedirectory ? " -d" : ""); 344 345 (void) signal(SIGPIPE, lostconn); 346 347 if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */ 348 toremote(targ, argc, argv); 349 else { 350 tolocal(argc, argv); /* Dest is local host. */ 351 if (targetshouldbedirectory) 352 verifydir(argv[argc - 1]); 353 } 354 /* 355 * Finally check the exit status of the ssh process, if one was forked 356 * and no error has occurred yet 357 */ 358 if (do_cmd_pid != (pid_t)-1 && errs == 0) { 359 if (remin != -1) { 360 (void) close(remin); 361 } 362 if (remout != -1) { 363 (void) close(remout); 364 } 365 if (waitpid(do_cmd_pid, &status, 0) == -1) { 366 errs = 1; 367 } else if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { 368 errs = 1; 369 } 370 } 371 372 return (errs != 0); 373 } 374 375 void 376 toremote(targ, argc, argv) 377 char *targ, *argv[]; 378 int argc; 379 { 380 int i, len; 381 char *bp, *host, *src, *suser, *thost, *tuser; 382 383 *targ++ = 0; 384 if (*targ == 0) 385 targ = "."; 386 387 if ((thost = strchr(argv[argc - 1], '@'))) { 388 /* user@host */ 389 *thost++ = 0; 390 tuser = argv[argc - 1]; 391 if (*tuser == '\0') 392 tuser = NULL; 393 else if (!okname(tuser)) 394 exit(1); 395 } else { 396 thost = argv[argc - 1]; 397 tuser = NULL; 398 } 399 400 for (i = 0; i < argc - 1; i++) { 401 src = colon(argv[i]); 402 if (src) { /* remote to remote */ 403 static char *ssh_options = 404 "-x -o'ClearAllForwardings yes'"; 405 *src++ = 0; 406 if (*src == 0) 407 src = "."; 408 host = strchr(argv[i], '@'); 409 len = strlen(ssh_program) + strlen(argv[i]) + 410 strlen(src) + (tuser ? strlen(tuser) : 0) + 411 strlen(thost) + strlen(targ) + 412 strlen(ssh_options) + CMDNEEDS + 20; 413 bp = xmalloc(len); 414 if (host) { 415 *host++ = 0; 416 host = cleanhostname(host); 417 suser = argv[i]; 418 if (*suser == '\0') 419 suser = pwd->pw_name; 420 else if (!okname(suser)) 421 continue; 422 snprintf(bp, len, 423 "%s%s %s -n " 424 "-l %s %s %s %s '%s%s%s:%s'", 425 ssh_program, verbose_mode ? " -v" : "", 426 ssh_options, suser, host, cmd, src, 427 tuser ? tuser : "", tuser ? "@" : "", 428 thost, targ); 429 } else { 430 host = cleanhostname(argv[i]); 431 snprintf(bp, len, 432 "exec %s%s %s -n %s " 433 "%s %s '%s%s%s:%s'", 434 ssh_program, verbose_mode ? " -v" : "", 435 ssh_options, host, cmd, src, 436 tuser ? tuser : "", tuser ? "@" : "", 437 thost, targ); 438 } 439 if (verbose_mode) 440 fprintf(stderr, gettext("Executing: %s\n"), bp); 441 (void) system(bp); 442 (void) xfree(bp); 443 } else { /* local to remote */ 444 if (remin == -1) { 445 len = strlen(targ) + CMDNEEDS + 20; 446 bp = xmalloc(len); 447 (void) snprintf(bp, len, "%s -t %s", cmd, targ); 448 host = cleanhostname(thost); 449 if (do_cmd(host, tuser, bp, &remin, 450 &remout, argc) < 0) 451 exit(1); 452 if (response() < 0) 453 exit(1); 454 (void) xfree(bp); 455 } 456 source(1, argv + i); 457 } 458 } 459 } 460 461 void 462 tolocal(argc, argv) 463 int argc; 464 char *argv[]; 465 { 466 int i, len; 467 char *bp, *host, *src, *suser; 468 469 for (i = 0; i < argc - 1; i++) { 470 if (!(src = colon(argv[i]))) { /* Local to local. */ 471 len = strlen(_PATH_CP) + strlen(argv[i]) + 472 strlen(argv[argc - 1]) + 20; 473 bp = xmalloc(len); 474 (void) snprintf(bp, len, "exec %s%s%s %s %s", _PATH_CP, 475 iamrecursive ? " -r" : "", pflag ? " -p" : "", 476 argv[i], argv[argc - 1]); 477 if (verbose_mode) 478 fprintf(stderr, gettext("Executing: %s\n"), bp); 479 if (system(bp)) 480 ++errs; 481 (void) xfree(bp); 482 continue; 483 } 484 *src++ = 0; 485 if (*src == 0) 486 src = "."; 487 if ((host = strchr(argv[i], '@')) == NULL) { 488 host = argv[i]; 489 suser = NULL; 490 } else { 491 *host++ = 0; 492 suser = argv[i]; 493 if (*suser == '\0') 494 suser = pwd->pw_name; 495 else if (!okname(suser)) 496 continue; 497 } 498 host = cleanhostname(host); 499 len = strlen(src) + CMDNEEDS + 20; 500 bp = xmalloc(len); 501 (void) snprintf(bp, len, "%s -f %s", cmd, src); 502 if (do_cmd(host, suser, bp, &remin, &remout, argc) < 0) { 503 (void) xfree(bp); 504 ++errs; 505 continue; 506 } 507 xfree(bp); 508 sink(1, argv + argc - 1); 509 (void) close(remin); 510 remin = remout = -1; 511 } 512 } 513 514 void 515 source(argc, argv) 516 int argc; 517 char *argv[]; 518 { 519 struct stat stb; 520 static BUF buffer; 521 BUF *bp; 522 off_t i, amt, result; 523 int fd, haderr, indx; 524 char *last, *name, buf[2048]; 525 int len; 526 527 for (indx = 0; indx < argc; ++indx) { 528 name = argv[indx]; 529 statbytes = 0; 530 len = strlen(name); 531 while (len > 1 && name[len-1] == '/') 532 name[--len] = '\0'; 533 if (strchr(name, '\n') != NULL) { 534 run_err("%s: skipping, filename contains a newline", 535 name); 536 goto next; 537 } 538 if ((fd = open(name, O_RDONLY, 0)) < 0) 539 goto syserr; 540 if (fstat(fd, &stb) < 0) { 541 syserr: run_err("%s: %s", name, strerror(errno)); 542 goto next; 543 } 544 switch (stb.st_mode & S_IFMT) { 545 case S_IFREG: 546 break; 547 case S_IFDIR: 548 if (iamrecursive) { 549 rsource(name, &stb); 550 goto next; 551 } 552 /* FALLTHROUGH */ 553 default: 554 run_err("%s: not a regular file", name); 555 goto next; 556 } 557 if ((last = strrchr(name, '/')) == NULL) 558 last = name; 559 else 560 ++last; 561 curfile = last; 562 if (pflag) { 563 /* 564 * Make it compatible with possible future 565 * versions expecting microseconds. 566 */ 567 (void) snprintf(buf, sizeof (buf), "T%lu 0 %lu 0\n", 568 (ulong_t)stb.st_mtime, 569 (ulong_t)stb.st_atime); 570 (void) atomicio(write, remout, buf, strlen(buf)); 571 if (response() < 0) 572 goto next; 573 } 574 #define FILEMODEMASK (S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO) 575 #ifdef HAVE_LONG_LONG_INT 576 snprintf(buf, sizeof (buf), "C%04o %lld %s\n", 577 (uint_t)(stb.st_mode & FILEMODEMASK), 578 (long long)stb.st_size, last); 579 #else 580 /* XXX: Handle integer overflow? */ 581 snprintf(buf, sizeof (buf), "C%04o %lu %s\n", 582 (uint_t)(stb.st_mode & FILEMODEMASK), 583 (ulong_t)stb.st_size, last); 584 #endif 585 if (verbose_mode) { 586 fprintf(stderr, gettext("Sending file modes: %s"), buf); 587 fflush(stderr); 588 } 589 (void) atomicio(write, remout, buf, strlen(buf)); 590 if (response() < 0) 591 goto next; 592 if ((bp = allocbuf(&buffer, fd, 2048)) == NULL) { 593 next: (void) close(fd); 594 continue; 595 } 596 if (showprogress) { 597 totalbytes = stb.st_size; 598 progressmeter(-1); 599 } 600 /* Keep writing after an error so that we stay sync'd up. */ 601 for (haderr = i = 0; i < stb.st_size; i += bp->cnt) { 602 amt = bp->cnt; 603 if (i + amt > stb.st_size) 604 amt = stb.st_size - i; 605 if (!haderr) { 606 result = atomicio(read, fd, bp->buf, amt); 607 if (result != amt) 608 haderr = result >= 0 ? EIO : errno; 609 } 610 if (haderr) 611 (void) atomicio(write, remout, bp->buf, amt); 612 else { 613 result = atomicio(write, remout, bp->buf, amt); 614 if (result != amt) 615 haderr = result >= 0 ? EIO : errno; 616 statbytes += result; 617 } 618 } 619 if (showprogress) 620 progressmeter(1); 621 622 if (close(fd) < 0 && !haderr) 623 haderr = errno; 624 if (!haderr) 625 (void) atomicio(write, remout, "", 1); 626 else 627 run_err("%s: %s", name, strerror(haderr)); 628 (void) response(); 629 } 630 } 631 632 void 633 rsource(name, statp) 634 char *name; 635 struct stat *statp; 636 { 637 DIR *dirp; 638 struct dirent *dp; 639 char *last, *vect[1], path[1100]; 640 641 if (!(dirp = opendir(name))) { 642 run_err("%s: %s", name, strerror(errno)); 643 return; 644 } 645 last = strrchr(name, '/'); 646 if (last == 0) 647 last = name; 648 else 649 last++; 650 if (pflag) { 651 (void) snprintf(path, sizeof (path), "T%lu 0 %lu 0\n", 652 (ulong_t)statp->st_mtime, 653 (ulong_t)statp->st_atime); 654 (void) atomicio(write, remout, path, strlen(path)); 655 if (response() < 0) { 656 closedir(dirp); 657 return; 658 } 659 } 660 (void) snprintf(path, sizeof (path), "D%04o %d %.1024s\n", 661 (uint_t)(statp->st_mode & FILEMODEMASK), 0, last); 662 if (verbose_mode) 663 fprintf(stderr, gettext("Entering directory: %s"), path); 664 (void) atomicio(write, remout, path, strlen(path)); 665 if (response() < 0) { 666 closedir(dirp); 667 return; 668 } 669 while ((dp = readdir(dirp)) != NULL) { 670 if (dp->d_ino == 0) 671 continue; 672 if ((strcmp(dp->d_name, ".") == 0) || 673 (strcmp(dp->d_name, "..") == 0)) 674 continue; 675 if (strlen(name) + 1 + strlen(dp->d_name) >= 676 sizeof (path) - 1) { 677 run_err("%s/%s: name too long", name, dp->d_name); 678 continue; 679 } 680 (void) snprintf(path, sizeof (path), "%s/%s", name, dp->d_name); 681 vect[0] = path; 682 source(1, vect); 683 } 684 (void) closedir(dirp); 685 (void) atomicio(write, remout, "E\n", 2); 686 (void) response(); 687 } 688 689 void 690 sink(argc, argv) 691 int argc; 692 char *argv[]; 693 { 694 static BUF buffer; 695 struct stat stb; 696 enum { 697 YES, NO, DISPLAYED 698 } wrerr; 699 BUF *bp; 700 off_t i, j; 701 int amt, count, exists, first, mask, mode, ofd, omode; 702 off_t size; 703 int setimes, targisdir, wrerrno = 0; 704 char ch, *cp, *np, *targ, *why, *vect[1], buf[2048]; 705 struct timeval tv[2]; 706 707 #define atime tv[0] 708 #define mtime tv[1] 709 #define SCREWUP(str) { why = str; goto screwup; } 710 711 setimes = targisdir = 0; 712 mask = umask(0); 713 if (!pflag) 714 (void) umask(mask); 715 if (argc != 1) { 716 run_err("ambiguous target"); 717 exit(1); 718 } 719 targ = *argv; 720 if (targetshouldbedirectory) 721 verifydir(targ); 722 723 (void) atomicio(write, remout, "", 1); 724 if (stat(targ, &stb) == 0 && S_ISDIR(stb.st_mode)) 725 targisdir = 1; 726 for (first = 1; ; first = 0) { 727 cp = buf; 728 if (atomicio(read, remin, cp, 1) <= 0) 729 return; 730 if (*cp++ == '\n') 731 SCREWUP("unexpected <newline>") 732 do { 733 if (atomicio(read, remin, &ch, sizeof (ch)) != 734 sizeof (ch)) 735 SCREWUP("lost connection") 736 *cp++ = ch; 737 } while (cp < &buf[sizeof (buf) - 1] && ch != '\n'); 738 *cp = 0; 739 740 if (buf[0] == '\01' || buf[0] == '\02') { 741 if (iamremote == 0) 742 (void) atomicio(write, STDERR_FILENO, 743 buf + 1, strlen(buf + 1)); 744 if (buf[0] == '\02') 745 exit(1); 746 ++errs; 747 continue; 748 } 749 if (buf[0] == 'E') { 750 (void) atomicio(write, remout, "", 1); 751 return; 752 } 753 if (ch == '\n') 754 *--cp = 0; 755 756 cp = buf; 757 if (*cp == 'T') { 758 setimes++; 759 cp++; 760 mtime.tv_sec = strtol(cp, &cp, 10); 761 if (!cp || *cp++ != ' ') 762 SCREWUP("mtime.sec not delimited") 763 mtime.tv_usec = strtol(cp, &cp, 10); 764 if (!cp || *cp++ != ' ') 765 SCREWUP("mtime.usec not delimited") 766 atime.tv_sec = strtol(cp, &cp, 10); 767 if (!cp || *cp++ != ' ') 768 SCREWUP("atime.sec not delimited") 769 atime.tv_usec = strtol(cp, &cp, 10); 770 if (!cp || *cp++ != '\0') 771 SCREWUP("atime.usec not delimited") 772 (void) atomicio(write, remout, "", 1); 773 continue; 774 } 775 if (*cp != 'C' && *cp != 'D') { 776 /* 777 * Check for the case "rcp remote:foo\* local:bar". 778 * In this case, the line "No match." can be returned 779 * by the shell before the rcp command on the remote is 780 * executed so the ^Aerror_message convention isn't 781 * followed. 782 */ 783 if (first) { 784 run_err("%s", cp); 785 exit(1); 786 } 787 SCREWUP("expected control record") 788 } 789 mode = 0; 790 for (++cp; cp < buf + 5; cp++) { 791 if (*cp < '0' || *cp > '7') 792 SCREWUP("bad mode") 793 mode = (mode << 3) | (*cp - '0'); 794 } 795 if (*cp++ != ' ') 796 SCREWUP("mode not delimited") 797 798 for (size = 0; isdigit(*cp); ) 799 size = size * 10 + (*cp++ - '0'); 800 if (*cp++ != ' ') 801 SCREWUP("size not delimited") 802 if (targisdir) { 803 static char *namebuf; 804 static int cursize; 805 size_t need; 806 807 need = strlen(targ) + strlen(cp) + 250; 808 if (need > cursize) { 809 if (namebuf) 810 xfree(namebuf); 811 namebuf = xmalloc(need); 812 cursize = need; 813 } 814 (void) snprintf(namebuf, need, "%s%s%s", targ, 815 strcmp(targ, "/") ? "/" : "", cp); 816 np = namebuf; 817 } else 818 np = targ; 819 curfile = cp; 820 exists = stat(np, &stb) == 0; 821 if (buf[0] == 'D') { 822 int mod_flag = pflag; 823 if (exists) { 824 if (!S_ISDIR(stb.st_mode)) { 825 errno = ENOTDIR; 826 goto bad; 827 } 828 if (pflag) 829 (void) chmod(np, mode); 830 } else { 831 /* 832 * Handle copying from a read-only 833 * directory 834 */ 835 mod_flag = 1; 836 if (mkdir(np, mode | S_IRWXU) < 0) 837 goto bad; 838 } 839 vect[0] = xstrdup(np); 840 sink(1, vect); 841 if (setimes) { 842 setimes = 0; 843 if (utimes(vect[0], tv) < 0) 844 run_err("%s: set times: %s", 845 vect[0], strerror(errno)); 846 } 847 if (mod_flag) 848 (void) chmod(vect[0], mode); 849 if (vect[0]) 850 xfree(vect[0]); 851 continue; 852 } 853 omode = mode; 854 mode |= S_IWRITE; 855 if ((ofd = open(np, O_WRONLY|O_CREAT, mode)) < 0) { 856 bad: run_err("%s: %s", np, strerror(errno)); 857 continue; 858 } 859 (void) atomicio(write, remout, "", 1); 860 if ((bp = allocbuf(&buffer, ofd, 4096)) == NULL) { 861 (void) close(ofd); 862 continue; 863 } 864 wrerr = NO; 865 866 if (showprogress) { 867 totalbytes = size; 868 progressmeter(-1); 869 } 870 statbytes = 0; 871 for (i = 0; i < size; i += bp->cnt) { 872 amt = bp->cnt; 873 cp = bp->buf; 874 if (i + amt > size) 875 amt = size - i; 876 count = amt; 877 do { 878 j = read(remin, cp, amt); 879 if (j == -1 && (errno == EINTR || 880 errno == EAGAIN)) { 881 continue; 882 } else if (j <= 0) { 883 run_err("%s", j ? strerror(errno) : 884 "dropped connection"); 885 exit(1); 886 } 887 amt -= j; 888 cp += j; 889 statbytes += j; 890 } while (amt > 0); 891 /* Keep reading so we stay sync'd up. */ 892 if (wrerr == NO) { 893 j = atomicio(write, ofd, bp->buf, 894 count); 895 if (j != count) { 896 wrerr = YES; 897 wrerrno = j >= 0 ? EIO : errno; 898 } 899 } 900 } 901 if (showprogress) 902 progressmeter(1); 903 if (count != 0 && wrerr == NO && 904 (j = atomicio(write, ofd, bp->buf, count)) != count) { 905 wrerr = YES; 906 wrerrno = j >= 0 ? EIO : errno; 907 } 908 if (ftruncate(ofd, size)) { 909 run_err("%s: truncate: %s", np, strerror(errno)); 910 wrerr = DISPLAYED; 911 } 912 if (pflag) { 913 if (exists || omode != mode) 914 #ifdef HAVE_FCHMOD 915 if (fchmod(ofd, omode)) 916 #else /* HAVE_FCHMOD */ 917 if (chmod(np, omode)) 918 #endif /* HAVE_FCHMOD */ 919 run_err("%s: set mode: %s", 920 np, strerror(errno)); 921 } else { 922 if (!exists && omode != mode) 923 #ifdef HAVE_FCHMOD 924 if (fchmod(ofd, omode & ~mask)) 925 #else /* HAVE_FCHMOD */ 926 if (chmod(np, omode & ~mask)) 927 #endif /* HAVE_FCHMOD */ 928 run_err("%s: set mode: %s", 929 np, strerror(errno)); 930 } 931 if (close(ofd) == -1) { 932 wrerr = YES; 933 wrerrno = errno; 934 } 935 (void) response(); 936 if (setimes && wrerr == NO) { 937 setimes = 0; 938 if (utimes(np, tv) < 0) { 939 run_err("%s: set times: %s", 940 np, strerror(errno)); 941 wrerr = DISPLAYED; 942 } 943 } 944 switch (wrerr) { 945 case YES: 946 run_err("%s: %s", np, strerror(wrerrno)); 947 break; 948 case NO: 949 (void) atomicio(write, remout, "", 1); 950 break; 951 case DISPLAYED: 952 break; 953 } 954 } 955 screwup: 956 run_err("protocol error: %s", why); 957 exit(1); 958 } 959 960 int 961 response(void) 962 { 963 char ch, *cp, resp, rbuf[2048]; 964 965 if (atomicio(read, remin, &resp, sizeof (resp)) != sizeof (resp)) 966 lostconn(0); 967 968 cp = rbuf; 969 switch (resp) { 970 case 0: /* ok */ 971 return (0); 972 default: 973 *cp++ = resp; 974 /* FALLTHROUGH */ 975 case 1: /* error, followed by error msg */ 976 case 2: /* fatal error, "" */ 977 do { 978 if (atomicio(read, remin, &ch, sizeof (ch)) != 979 sizeof (ch)) 980 lostconn(0); 981 *cp++ = ch; 982 } while (cp < &rbuf[sizeof (rbuf) - 1] && ch != '\n'); 983 984 if (!iamremote) 985 (void) atomicio(write, STDERR_FILENO, rbuf, cp - rbuf); 986 ++errs; 987 if (resp == 1) 988 return (-1); 989 exit(1); 990 } 991 /* NOTREACHED */ 992 } 993 994 void 995 usage(void) 996 { 997 (void) fprintf(stderr, 998 gettext( 999 "Usage: scp [-pqrvBC46] [-F config] [-S program] [-P port]\n" 1000 " [-c cipher] [-i identity] [-o option]\n" 1001 " [[user@]host1:]file1 [...] " 1002 "[[user@]host2:]file2\n")); 1003 exit(1); 1004 } 1005 1006 /* PRINTFLIKE1 */ 1007 void 1008 run_err(const char *fmt, ...) 1009 { 1010 static FILE *fp; 1011 va_list ap; 1012 1013 ++errs; 1014 if (fp == NULL && !(fp = fdopen(remout, "w"))) 1015 return; 1016 (void) fprintf(fp, "%c", 0x01); 1017 (void) fprintf(fp, "scp: "); 1018 va_start(ap, fmt); 1019 (void) vfprintf(fp, fmt, ap); 1020 va_end(ap); 1021 (void) fprintf(fp, "\n"); 1022 (void) fflush(fp); 1023 1024 if (!iamremote) { 1025 va_start(ap, fmt); 1026 vfprintf(stderr, fmt, ap); 1027 va_end(ap); 1028 fprintf(stderr, "\n"); 1029 } 1030 } 1031 1032 void 1033 verifydir(cp) 1034 char *cp; 1035 { 1036 struct stat stb; 1037 1038 if (!stat(cp, &stb)) { 1039 if (S_ISDIR(stb.st_mode)) 1040 return; 1041 errno = ENOTDIR; 1042 } 1043 run_err("%s: %s", cp, strerror(errno)); 1044 exit(1); 1045 } 1046 1047 int 1048 okname(cp0) 1049 char *cp0; 1050 { 1051 int c; 1052 char *cp; 1053 1054 cp = cp0; 1055 do { 1056 c = (int)*cp; 1057 if (c & 0200) 1058 goto bad; 1059 if (!isalpha(c) && !isdigit(c) && 1060 c != '_' && c != '-' && c != '.' && c != '+') 1061 goto bad; 1062 } while (*++cp); 1063 return (1); 1064 1065 bad: fprintf(stderr, gettext("%s: invalid user name\n"), cp0); 1066 return (0); 1067 } 1068 1069 BUF * 1070 allocbuf(bp, fd, blksize) 1071 BUF *bp; 1072 int fd, blksize; 1073 { 1074 size_t size; 1075 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE 1076 struct stat stb; 1077 1078 if (fstat(fd, &stb) < 0) { 1079 run_err("fstat: %s", strerror(errno)); 1080 return (0); 1081 } 1082 if (stb.st_blksize == 0) 1083 size = blksize; 1084 else 1085 size = blksize + (stb.st_blksize - blksize % stb.st_blksize) % 1086 stb.st_blksize; 1087 #else /* HAVE_STRUCT_STAT_ST_BLKSIZE */ 1088 size = blksize; 1089 #endif /* HAVE_STRUCT_STAT_ST_BLKSIZE */ 1090 if (bp->cnt >= size) 1091 return (bp); 1092 if (bp->buf == NULL) 1093 bp->buf = xmalloc(size); 1094 else 1095 bp->buf = xrealloc(bp->buf, size); 1096 memset(bp->buf, 0, size); 1097 bp->cnt = size; 1098 return (bp); 1099 } 1100 1101 void 1102 lostconn(signo) 1103 int signo; 1104 { 1105 if (!iamremote) 1106 write(STDERR_FILENO, "lost connection\n", 16); 1107 if (signo) 1108 _exit(1); 1109 else 1110 exit(1); 1111 } 1112 1113 static void 1114 updateprogressmeter(int ignore) 1115 { 1116 int save_errno = errno; 1117 1118 progressmeter(0); 1119 signal(SIGALRM, updateprogressmeter); 1120 alarm(PROGRESSTIME); 1121 errno = save_errno; 1122 } 1123 1124 static int 1125 foregroundproc(void) 1126 { 1127 static pid_t pgrp = -1; 1128 int ctty_pgrp; 1129 1130 if (pgrp == -1) 1131 pgrp = getpgrp(); 1132 1133 #ifdef HAVE_TCGETPGRP 1134 return ((ctty_pgrp = tcgetpgrp(STDOUT_FILENO)) != -1 && 1135 ctty_pgrp == pgrp); 1136 #else 1137 return ((ioctl(STDOUT_FILENO, TIOCGPGRP, &ctty_pgrp) != -1 && 1138 ctty_pgrp == pgrp)); 1139 #endif 1140 } 1141 1142 void 1143 progressmeter(int flag) 1144 { 1145 static const char prefixes[] = " KMGTP"; 1146 static struct timeval lastupdate; 1147 static off_t lastsize; 1148 struct timeval now, td, wait; 1149 off_t cursize, abbrevsize; 1150 double elapsed; 1151 int ratio, barlength, i, remaining; 1152 char buf[512]; 1153 1154 if (flag == -1) { 1155 (void) gettimeofday(&start, (struct timezone *)0); 1156 lastupdate = start; 1157 lastsize = 0; 1158 } 1159 if (foregroundproc() == 0) 1160 return; 1161 1162 (void) gettimeofday(&now, (struct timezone *)0); 1163 cursize = statbytes; 1164 if (totalbytes != 0) { 1165 ratio = (int)(100.0 * cursize / totalbytes); 1166 ratio = MAX(ratio, 0); 1167 ratio = MIN(ratio, 100); 1168 } else 1169 ratio = 100; 1170 1171 snprintf(buf, sizeof (buf), "\r%-20.20s %3d%% ", curfile, ratio); 1172 1173 barlength = getttywidth() - 51; 1174 if (barlength > 0) { 1175 i = barlength * ratio / 100; 1176 snprintf(buf + strlen(buf), sizeof (buf) - strlen(buf), 1177 "|%.*s%*s|", i, 1178 "*******************************************************" 1179 "*******************************************************" 1180 "*******************************************************" 1181 "*******************************************************" 1182 "*******************************************************" 1183 "*******************************************************" 1184 "*******************************************************", 1185 barlength - i, ""); 1186 } 1187 i = 0; 1188 abbrevsize = cursize; 1189 while (abbrevsize >= 100000 && i < sizeof (prefixes)) { 1190 i++; 1191 abbrevsize >>= 10; 1192 } 1193 snprintf(buf + strlen(buf), sizeof (buf) - strlen(buf), " %5lu %c%c ", 1194 (unsigned long) abbrevsize, prefixes[i], 1195 prefixes[i] == ' ' ? ' ' : 'B'); 1196 1197 timersub(&now, &lastupdate, &wait); 1198 if (cursize > lastsize) { 1199 lastupdate = now; 1200 lastsize = cursize; 1201 if (wait.tv_sec >= STALLTIME) { 1202 start.tv_sec += wait.tv_sec; 1203 start.tv_usec += wait.tv_usec; 1204 } 1205 wait.tv_sec = 0; 1206 } 1207 timersub(&now, &start, &td); 1208 elapsed = td.tv_sec + (td.tv_usec / 1000000.0); 1209 1210 if (flag != 1 && 1211 (statbytes <= 0 || elapsed <= 0.0 || cursize > totalbytes)) { 1212 snprintf(buf + strlen(buf), sizeof (buf) - strlen(buf), 1213 " --:-- ETA"); 1214 } else if (wait.tv_sec >= STALLTIME) { 1215 snprintf(buf + strlen(buf), sizeof (buf) - strlen(buf), 1216 " - stalled -"); 1217 } else { 1218 if (flag != 1) 1219 remaining = (int)(totalbytes / (statbytes / elapsed) - 1220 elapsed); 1221 else 1222 remaining = (int)elapsed; 1223 1224 i = remaining / 3600; 1225 if (i) 1226 snprintf(buf + strlen(buf), sizeof (buf) - strlen(buf), 1227 "%2d:", i); 1228 else 1229 snprintf(buf + strlen(buf), sizeof (buf) - strlen(buf), 1230 " "); 1231 i = remaining % 3600; 1232 snprintf(buf + strlen(buf), sizeof (buf) - strlen(buf), 1233 "%02d:%02d%s", i / 60, i % 60, 1234 (flag != 1) ? " ETA" : " "); 1235 } 1236 atomicio(write, fileno(stdout), buf, strlen(buf)); 1237 1238 if (flag == -1) { 1239 mysignal(SIGALRM, updateprogressmeter); 1240 alarm(PROGRESSTIME); 1241 } else if (flag == 1) { 1242 alarm(0); 1243 atomicio(write, fileno(stdout), "\n", 1); 1244 statbytes = 0; 1245 } 1246 } 1247 1248 int 1249 getttywidth(void) 1250 { 1251 struct winsize winsize; 1252 1253 if (ioctl(fileno(stdout), TIOCGWINSZ, &winsize) != -1) 1254 return (winsize.ws_col ? winsize.ws_col : 80); 1255 else 1256 return (80); 1257 } 1258