1 /* $NetBSD: util.c,v 1.146 2008/04/28 20:24:13 martin Exp $ */ 2 3 /*- 4 * Copyright (c) 1997-2008 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Luke Mewburn. 9 * 10 * This code is derived from software contributed to The NetBSD Foundation 11 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility, 12 * NASA Ames Research Center. 13 * 14 * Redistribution and use in source and binary forms, with or without 15 * modification, are permitted provided that the following conditions 16 * are met: 17 * 1. Redistributions of source code must retain the above copyright 18 * notice, this list of conditions and the following disclaimer. 19 * 2. Redistributions in binary form must reproduce the above copyright 20 * notice, this list of conditions and the following disclaimer in the 21 * documentation and/or other materials provided with the distribution. 22 * 23 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 24 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 25 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 26 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 27 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 33 * POSSIBILITY OF SUCH DAMAGE. 34 */ 35 36 /* 37 * Copyright (c) 1985, 1989, 1993, 1994 38 * The Regents of the University of California. All rights reserved. 39 * 40 * Redistribution and use in source and binary forms, with or without 41 * modification, are permitted provided that the following conditions 42 * are met: 43 * 1. Redistributions of source code must retain the above copyright 44 * notice, this list of conditions and the following disclaimer. 45 * 2. Redistributions in binary form must reproduce the above copyright 46 * notice, this list of conditions and the following disclaimer in the 47 * documentation and/or other materials provided with the distribution. 48 * 3. Neither the name of the University nor the names of its contributors 49 * may be used to endorse or promote products derived from this software 50 * without specific prior written permission. 51 * 52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 55 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 62 * SUCH DAMAGE. 63 */ 64 65 #include <sys/cdefs.h> 66 #ifndef lint 67 __RCSID("$NetBSD: util.c,v 1.146 2008/04/28 20:24:13 martin Exp $"); 68 #endif /* not lint */ 69 70 /* 71 * FTP User Program -- Misc support routines 72 */ 73 #include <sys/param.h> 74 #include <sys/socket.h> 75 #include <sys/ioctl.h> 76 #include <sys/time.h> 77 #include <netinet/in.h> 78 #include <arpa/ftp.h> 79 80 #include <ctype.h> 81 #include <err.h> 82 #include <errno.h> 83 #include <fcntl.h> 84 #include <glob.h> 85 #include <signal.h> 86 #include <libgen.h> 87 #include <limits.h> 88 #include <netdb.h> 89 #include <stdio.h> 90 #include <stdlib.h> 91 #include <string.h> 92 #include <termios.h> 93 #include <time.h> 94 #include <tzfile.h> 95 #include <unistd.h> 96 97 #include "ftp_var.h" 98 99 /* 100 * Connect to peer server and auto-login, if possible. 101 */ 102 void 103 setpeer(int argc, char *argv[]) 104 { 105 char *host; 106 char *port; 107 108 if (argc == 0) 109 goto usage; 110 if (connected) { 111 fprintf(ttyout, "Already connected to %s, use close first.\n", 112 hostname); 113 code = -1; 114 return; 115 } 116 if (argc < 2) 117 (void)another(&argc, &argv, "to"); 118 if (argc < 2 || argc > 3) { 119 usage: 120 UPRINTF("usage: %s host-name [port]\n", argv[0]); 121 code = -1; 122 return; 123 } 124 if (gatemode) 125 port = gateport; 126 else 127 port = ftpport; 128 if (argc > 2) 129 port = argv[2]; 130 131 if (gatemode) { 132 if (gateserver == NULL || *gateserver == '\0') 133 errx(1, "main: gateserver not defined"); 134 host = hookup(gateserver, port); 135 } else 136 host = hookup(argv[1], port); 137 138 if (host) { 139 if (gatemode && verbose) { 140 fprintf(ttyout, 141 "Connecting via pass-through server %s\n", 142 gateserver); 143 } 144 145 connected = 1; 146 /* 147 * Set up defaults for FTP. 148 */ 149 (void)strlcpy(typename, "ascii", sizeof(typename)); 150 type = TYPE_A; 151 curtype = TYPE_A; 152 (void)strlcpy(formname, "non-print", sizeof(formname)); 153 form = FORM_N; 154 (void)strlcpy(modename, "stream", sizeof(modename)); 155 mode = MODE_S; 156 (void)strlcpy(structname, "file", sizeof(structname)); 157 stru = STRU_F; 158 (void)strlcpy(bytename, "8", sizeof(bytename)); 159 bytesize = 8; 160 if (autologin) 161 (void)ftp_login(argv[1], NULL, NULL); 162 } 163 } 164 165 static void 166 parse_feat(const char *line) 167 { 168 169 /* 170 * work-around broken ProFTPd servers that can't 171 * even obey RFC2389. 172 */ 173 while (*line && isspace((int)*line)) 174 line++; 175 176 if (strcasecmp(line, "MDTM") == 0) 177 features[FEAT_MDTM] = 1; 178 else if (strncasecmp(line, "MLST", sizeof("MLST") - 1) == 0) { 179 features[FEAT_MLST] = 1; 180 } else if (strcasecmp(line, "REST STREAM") == 0) 181 features[FEAT_REST_STREAM] = 1; 182 else if (strcasecmp(line, "SIZE") == 0) 183 features[FEAT_SIZE] = 1; 184 else if (strcasecmp(line, "TVFS") == 0) 185 features[FEAT_TVFS] = 1; 186 } 187 188 /* 189 * Determine the remote system type (SYST) and features (FEAT). 190 * Call after a successful login (i.e, connected = -1) 191 */ 192 void 193 getremoteinfo(void) 194 { 195 int overbose, i; 196 197 overbose = verbose; 198 if (ftp_debug == 0) 199 verbose = -1; 200 201 /* determine remote system type */ 202 if (command("SYST") == COMPLETE) { 203 if (overbose) { 204 char *cp, c; 205 206 c = 0; 207 cp = strchr(reply_string + 4, ' '); 208 if (cp == NULL) 209 cp = strchr(reply_string + 4, '\r'); 210 if (cp) { 211 if (cp[-1] == '.') 212 cp--; 213 c = *cp; 214 *cp = '\0'; 215 } 216 217 fprintf(ttyout, "Remote system type is %s.\n", 218 reply_string + 4); 219 if (cp) 220 *cp = c; 221 } 222 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) { 223 if (proxy) 224 unix_proxy = 1; 225 else 226 unix_server = 1; 227 /* 228 * Set type to 0 (not specified by user), 229 * meaning binary by default, but don't bother 230 * telling server. We can use binary 231 * for text files unless changed by the user. 232 */ 233 type = 0; 234 (void)strlcpy(typename, "binary", sizeof(typename)); 235 if (overbose) 236 fprintf(ttyout, 237 "Using %s mode to transfer files.\n", 238 typename); 239 } else { 240 if (proxy) 241 unix_proxy = 0; 242 else 243 unix_server = 0; 244 if (overbose && 245 !strncmp(reply_string, "215 TOPS20", 10)) 246 fputs( 247 "Remember to set tenex mode when transferring binary files from this machine.\n", 248 ttyout); 249 } 250 } 251 252 /* determine features (if any) */ 253 for (i = 0; i < FEAT_max; i++) 254 features[i] = -1; 255 reply_callback = parse_feat; 256 if (command("FEAT") == COMPLETE) { 257 for (i = 0; i < FEAT_max; i++) { 258 if (features[i] == -1) 259 features[i] = 0; 260 } 261 features[FEAT_FEAT] = 1; 262 } else 263 features[FEAT_FEAT] = 0; 264 #ifndef NO_DEBUG 265 if (ftp_debug) { 266 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)]) 267 DEBUG_FEAT(FEAT_FEAT); 268 DEBUG_FEAT(FEAT_MDTM); 269 DEBUG_FEAT(FEAT_MLST); 270 DEBUG_FEAT(FEAT_REST_STREAM); 271 DEBUG_FEAT(FEAT_SIZE); 272 DEBUG_FEAT(FEAT_TVFS); 273 #undef DEBUG_FEAT 274 } 275 #endif 276 reply_callback = NULL; 277 278 verbose = overbose; 279 } 280 281 /* 282 * Reset the various variables that indicate connection state back to 283 * disconnected settings. 284 * The caller is responsible for issuing any commands to the remote server 285 * to perform a clean shutdown before this is invoked. 286 */ 287 void 288 cleanuppeer(void) 289 { 290 291 if (cout) 292 (void)fclose(cout); 293 cout = NULL; 294 connected = 0; 295 unix_server = 0; 296 unix_proxy = 0; 297 /* 298 * determine if anonftp was specifically set with -a 299 * (1), or implicitly set by auto_fetch() (2). in the 300 * latter case, disable after the current xfer 301 */ 302 if (anonftp == 2) 303 anonftp = 0; 304 data = -1; 305 epsv4bad = 0; 306 if (username) 307 free(username); 308 username = NULL; 309 if (!proxy) 310 macnum = 0; 311 } 312 313 /* 314 * Top-level signal handler for interrupted commands. 315 */ 316 void 317 intr(int signo) 318 { 319 320 sigint_raised = 1; 321 alarmtimer(0); 322 if (fromatty) 323 write(fileno(ttyout), "\n", 1); 324 siglongjmp(toplevel, 1); 325 } 326 327 /* 328 * Signal handler for lost connections; cleanup various elements of 329 * the connection state, and call cleanuppeer() to finish it off. 330 */ 331 void 332 lostpeer(int dummy) 333 { 334 int oerrno = errno; 335 336 alarmtimer(0); 337 if (connected) { 338 if (cout != NULL) { 339 (void)shutdown(fileno(cout), 1+1); 340 (void)fclose(cout); 341 cout = NULL; 342 } 343 if (data >= 0) { 344 (void)shutdown(data, 1+1); 345 (void)close(data); 346 data = -1; 347 } 348 connected = 0; 349 } 350 pswitch(1); 351 if (connected) { 352 if (cout != NULL) { 353 (void)shutdown(fileno(cout), 1+1); 354 (void)fclose(cout); 355 cout = NULL; 356 } 357 connected = 0; 358 } 359 proxflag = 0; 360 pswitch(0); 361 cleanuppeer(); 362 errno = oerrno; 363 } 364 365 366 /* 367 * Login to remote host, using given username & password if supplied. 368 * Return non-zero if successful. 369 */ 370 int 371 ftp_login(const char *host, const char *luser, const char *lpass) 372 { 373 char tmp[80]; 374 char *user, *pass, *acct, *p; 375 char emptypass[] = ""; 376 const char *errormsg; 377 int n, aflag, rval, nlen; 378 379 aflag = rval = 0; 380 user = pass = acct = NULL; 381 if (luser) 382 user = ftp_strdup(luser); 383 if (lpass) 384 pass = ftp_strdup(lpass); 385 386 DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n", 387 STRorNULL(user), STRorNULL(pass), STRorNULL(host)); 388 389 /* 390 * Set up arguments for an anonymous FTP session, if necessary. 391 */ 392 if (anonftp) { 393 FREEPTR(user); 394 user = ftp_strdup("anonymous"); /* as per RFC1635 */ 395 FREEPTR(pass); 396 pass = ftp_strdup(getoptionvalue("anonpass")); 397 } 398 399 if (ruserpass(host, &user, &pass, &acct) < 0) { 400 code = -1; 401 goto cleanup_ftp_login; 402 } 403 404 while (user == NULL) { 405 if (localname) 406 fprintf(ttyout, "Name (%s:%s): ", host, localname); 407 else 408 fprintf(ttyout, "Name (%s): ", host); 409 errormsg = NULL; 410 nlen = getline(stdin, tmp, sizeof(tmp), &errormsg); 411 if (nlen < 0) { 412 fprintf(ttyout, "%s; %s aborted.\n", errormsg, "login"); 413 code = -1; 414 goto cleanup_ftp_login; 415 } else if (nlen == 0) { 416 user = ftp_strdup(localname); 417 } else { 418 user = ftp_strdup(tmp); 419 } 420 } 421 422 if (gatemode) { 423 char *nuser; 424 size_t len; 425 426 len = strlen(user) + 1 + strlen(host) + 1; 427 nuser = ftp_malloc(len); 428 (void)strlcpy(nuser, user, len); 429 (void)strlcat(nuser, "@", len); 430 (void)strlcat(nuser, host, len); 431 FREEPTR(user); 432 user = nuser; 433 } 434 435 n = command("USER %s", user); 436 if (n == CONTINUE) { 437 if (pass == NULL) { 438 p = getpass("Password: "); 439 if (p == NULL) 440 p = emptypass; 441 pass = ftp_strdup(p); 442 memset(p, 0, strlen(p)); 443 } 444 n = command("PASS %s", pass); 445 memset(pass, 0, strlen(pass)); 446 } 447 if (n == CONTINUE) { 448 aflag++; 449 if (acct == NULL) { 450 p = getpass("Account: "); 451 if (p == NULL) 452 p = emptypass; 453 acct = ftp_strdup(p); 454 memset(p, 0, strlen(p)); 455 } 456 if (acct[0] == '\0') { 457 warnx("Login failed"); 458 goto cleanup_ftp_login; 459 } 460 n = command("ACCT %s", acct); 461 memset(acct, 0, strlen(acct)); 462 } 463 if ((n != COMPLETE) || 464 (!aflag && acct != NULL && command("ACCT %s", acct) != COMPLETE)) { 465 warnx("Login failed"); 466 goto cleanup_ftp_login; 467 } 468 rval = 1; 469 username = ftp_strdup(user); 470 if (proxy) 471 goto cleanup_ftp_login; 472 473 connected = -1; 474 getremoteinfo(); 475 for (n = 0; n < macnum; ++n) { 476 if (!strcmp("init", macros[n].mac_name)) { 477 (void)strlcpy(line, "$init", sizeof(line)); 478 makeargv(); 479 domacro(margc, margv); 480 break; 481 } 482 } 483 updatelocalcwd(); 484 updateremotecwd(); 485 486 cleanup_ftp_login: 487 FREEPTR(user); 488 if (pass != NULL) 489 memset(pass, 0, strlen(pass)); 490 FREEPTR(pass); 491 if (acct != NULL) 492 memset(acct, 0, strlen(acct)); 493 FREEPTR(acct); 494 return (rval); 495 } 496 497 /* 498 * `another' gets another argument, and stores the new argc and argv. 499 * It reverts to the top level (via intr()) on EOF/error. 500 * 501 * Returns false if no new arguments have been added. 502 */ 503 int 504 another(int *pargc, char ***pargv, const char *prompt) 505 { 506 const char *errormsg; 507 int ret, nlen; 508 size_t len; 509 510 len = strlen(line); 511 if (len >= sizeof(line) - 3) { 512 fputs("Sorry, arguments too long.\n", ttyout); 513 intr(0); 514 } 515 fprintf(ttyout, "(%s) ", prompt); 516 line[len++] = ' '; 517 errormsg = NULL; 518 nlen = getline(stdin, line + len, sizeof(line)-len, &errormsg); 519 if (nlen < 0) { 520 fprintf(ttyout, "%s; %s aborted.\n", errormsg, "operation"); 521 intr(0); 522 } 523 len += nlen; 524 makeargv(); 525 ret = margc > *pargc; 526 *pargc = margc; 527 *pargv = margv; 528 return (ret); 529 } 530 531 /* 532 * glob files given in argv[] from the remote server. 533 * if errbuf isn't NULL, store error messages there instead 534 * of writing to the screen. 535 */ 536 char * 537 remglob(char *argv[], int doswitch, const char **errbuf) 538 { 539 static char buf[MAXPATHLEN]; 540 static FILE *ftemp = NULL; 541 static char **args; 542 char temp[MAXPATHLEN]; 543 int oldverbose, oldhash, oldprogress, fd; 544 char *cp; 545 const char *mode; 546 size_t len; 547 548 if (!mflag || !connected) { 549 if (!doglob) 550 args = NULL; 551 else { 552 if (ftemp) { 553 (void)fclose(ftemp); 554 ftemp = NULL; 555 } 556 } 557 return (NULL); 558 } 559 if (!doglob) { 560 if (args == NULL) 561 args = argv; 562 if ((cp = *++args) == NULL) 563 args = NULL; 564 return (cp); 565 } 566 if (ftemp == NULL) { 567 len = strlcpy(temp, tmpdir, sizeof(temp)); 568 if (temp[len - 1] != '/') 569 (void)strlcat(temp, "/", sizeof(temp)); 570 (void)strlcat(temp, TMPFILE, sizeof(temp)); 571 if ((fd = mkstemp(temp)) < 0) { 572 warn("Unable to create temporary file `%s'", temp); 573 return (NULL); 574 } 575 close(fd); 576 oldverbose = verbose; 577 verbose = (errbuf != NULL) ? -1 : 0; 578 oldhash = hash; 579 oldprogress = progress; 580 hash = 0; 581 progress = 0; 582 if (doswitch) 583 pswitch(!proxy); 584 for (mode = "w"; *++argv != NULL; mode = "a") 585 recvrequest("NLST", temp, *argv, mode, 0, 0); 586 if ((code / 100) != COMPLETE) { 587 if (errbuf != NULL) 588 *errbuf = reply_string; 589 } 590 if (doswitch) 591 pswitch(!proxy); 592 verbose = oldverbose; 593 hash = oldhash; 594 progress = oldprogress; 595 ftemp = fopen(temp, "r"); 596 (void)unlink(temp); 597 if (ftemp == NULL) { 598 if (errbuf == NULL) 599 warnx("Can't find list of remote files"); 600 else 601 *errbuf = 602 "Can't find list of remote files"; 603 return (NULL); 604 } 605 } 606 if (fgets(buf, sizeof(buf), ftemp) == NULL) { 607 (void)fclose(ftemp); 608 ftemp = NULL; 609 return (NULL); 610 } 611 if ((cp = strchr(buf, '\n')) != NULL) 612 *cp = '\0'; 613 return (buf); 614 } 615 616 /* 617 * Glob a local file name specification with the expectation of a single 618 * return value. Can't control multiple values being expanded from the 619 * expression, we return only the first. 620 * Returns NULL on error, or a pointer to a buffer containing the filename 621 * that's the caller's responsiblity to free(3) when finished with. 622 */ 623 char * 624 globulize(const char *pattern) 625 { 626 glob_t gl; 627 int flags; 628 char *p; 629 630 if (!doglob) 631 return (ftp_strdup(pattern)); 632 633 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE; 634 memset(&gl, 0, sizeof(gl)); 635 if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) { 636 warnx("Glob pattern `%s' not found", pattern); 637 globfree(&gl); 638 return (NULL); 639 } 640 p = ftp_strdup(gl.gl_pathv[0]); 641 globfree(&gl); 642 return (p); 643 } 644 645 /* 646 * determine size of remote file 647 */ 648 off_t 649 remotesize(const char *file, int noisy) 650 { 651 int overbose, r; 652 off_t size; 653 654 overbose = verbose; 655 size = -1; 656 if (ftp_debug == 0) 657 verbose = -1; 658 if (! features[FEAT_SIZE]) { 659 if (noisy) 660 fprintf(ttyout, 661 "SIZE is not supported by remote server.\n"); 662 goto cleanup_remotesize; 663 } 664 r = command("SIZE %s", file); 665 if (r == COMPLETE) { 666 char *cp, *ep; 667 668 cp = strchr(reply_string, ' '); 669 if (cp != NULL) { 670 cp++; 671 size = STRTOLL(cp, &ep, 10); 672 if (*ep != '\0' && !isspace((unsigned char)*ep)) 673 size = -1; 674 } 675 } else { 676 if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1) 677 features[FEAT_SIZE] = 0; 678 if (noisy && ftp_debug == 0) { 679 fputs(reply_string, ttyout); 680 putc('\n', ttyout); 681 } 682 } 683 cleanup_remotesize: 684 verbose = overbose; 685 return (size); 686 } 687 688 /* 689 * determine last modification time (in GMT) of remote file 690 */ 691 time_t 692 remotemodtime(const char *file, int noisy) 693 { 694 int overbose, ocode, r; 695 time_t rtime; 696 697 overbose = verbose; 698 ocode = code; 699 rtime = -1; 700 if (ftp_debug == 0) 701 verbose = -1; 702 if (! features[FEAT_MDTM]) { 703 if (noisy) 704 fprintf(ttyout, 705 "MDTM is not supported by remote server.\n"); 706 goto cleanup_parse_time; 707 } 708 r = command("MDTM %s", file); 709 if (r == COMPLETE) { 710 struct tm timebuf; 711 char *timestr, *frac; 712 713 /* 714 * time-val = 14DIGIT [ "." 1*DIGIT ] 715 * YYYYMMDDHHMMSS[.sss] 716 * mdtm-response = "213" SP time-val CRLF / error-response 717 */ 718 timestr = reply_string + 4; 719 720 /* 721 * parse fraction. 722 * XXX: ignored for now 723 */ 724 frac = strchr(timestr, '\r'); 725 if (frac != NULL) 726 *frac = '\0'; 727 frac = strchr(timestr, '.'); 728 if (frac != NULL) 729 *frac++ = '\0'; 730 if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) { 731 /* 732 * XXX: Workaround for lame ftpd's that return 733 * `19100' instead of `2000' 734 */ 735 fprintf(ttyout, 736 "Y2K warning! Incorrect time-val `%s' received from server.\n", 737 timestr); 738 timestr++; 739 timestr[0] = '2'; 740 timestr[1] = '0'; 741 fprintf(ttyout, "Converted to `%s'\n", timestr); 742 } 743 memset(&timebuf, 0, sizeof(timebuf)); 744 if (strlen(timestr) != 14 || 745 (strptime(timestr, "%Y%m%d%H%M%S", &timebuf) == NULL)) { 746 bad_parse_time: 747 fprintf(ttyout, "Can't parse time `%s'.\n", timestr); 748 goto cleanup_parse_time; 749 } 750 timebuf.tm_isdst = -1; 751 rtime = timegm(&timebuf); 752 if (rtime == -1) { 753 if (noisy || ftp_debug != 0) 754 goto bad_parse_time; 755 else 756 goto cleanup_parse_time; 757 } else 758 DPRINTF("remotemodtime: parsed date `%s' as " LLF 759 ", %s", 760 timestr, (LLT)rtime, 761 rfc2822time(localtime(&rtime))); 762 } else { 763 if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1) 764 features[FEAT_MDTM] = 0; 765 if (noisy && ftp_debug == 0) { 766 fputs(reply_string, ttyout); 767 putc('\n', ttyout); 768 } 769 } 770 cleanup_parse_time: 771 verbose = overbose; 772 if (rtime == -1) 773 code = ocode; 774 return (rtime); 775 } 776 777 /* 778 * Format tm in an RFC2822 compatible manner, with a trailing \n. 779 * Returns a pointer to a static string containing the result. 780 */ 781 const char * 782 rfc2822time(const struct tm *tm) 783 { 784 static char result[50]; 785 786 if (strftime(result, sizeof(result), 787 "%a, %d %b %Y %H:%M:%S %z\n", tm) == 0) 788 errx(1, "Can't convert RFC2822 time: buffer too small"); 789 return result; 790 } 791 792 /* 793 * Update global `localcwd', which contains the state of the local cwd 794 */ 795 void 796 updatelocalcwd(void) 797 { 798 799 if (getcwd(localcwd, sizeof(localcwd)) == NULL) 800 localcwd[0] = '\0'; 801 DPRINTF("updatelocalcwd: got `%s'\n", localcwd); 802 } 803 804 /* 805 * Update global `remotecwd', which contains the state of the remote cwd 806 */ 807 void 808 updateremotecwd(void) 809 { 810 int overbose, ocode, i; 811 char *cp; 812 813 overbose = verbose; 814 ocode = code; 815 if (ftp_debug == 0) 816 verbose = -1; 817 if (command("PWD") != COMPLETE) 818 goto badremotecwd; 819 cp = strchr(reply_string, ' '); 820 if (cp == NULL || cp[0] == '\0' || cp[1] != '"') 821 goto badremotecwd; 822 cp += 2; 823 for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) { 824 if (cp[0] == '"') { 825 if (cp[1] == '"') 826 cp++; 827 else 828 break; 829 } 830 remotecwd[i] = *cp; 831 } 832 remotecwd[i] = '\0'; 833 DPRINTF("updateremotecwd: got `%s'\n", remotecwd); 834 goto cleanupremotecwd; 835 badremotecwd: 836 remotecwd[0]='\0'; 837 cleanupremotecwd: 838 verbose = overbose; 839 code = ocode; 840 } 841 842 /* 843 * Ensure file is in or under dir. 844 * Returns 1 if so, 0 if not (or an error occurred). 845 */ 846 int 847 fileindir(const char *file, const char *dir) 848 { 849 char parentdirbuf[PATH_MAX+1], *parentdir; 850 char realdir[PATH_MAX+1]; 851 size_t dirlen; 852 853 /* determine parent directory of file */ 854 (void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf)); 855 parentdir = dirname(parentdirbuf); 856 if (strcmp(parentdir, ".") == 0) 857 return 1; /* current directory is ok */ 858 859 /* find the directory */ 860 if (realpath(parentdir, realdir) == NULL) { 861 warn("Unable to determine real path of `%s'", parentdir); 862 return 0; 863 } 864 if (realdir[0] != '/') /* relative result is ok */ 865 return 1; 866 dirlen = strlen(dir); 867 if (strncmp(realdir, dir, dirlen) == 0 && 868 (realdir[dirlen] == '/' || realdir[dirlen] == '\0')) 869 return 1; 870 return 0; 871 } 872 873 /* 874 * List words in stringlist, vertically arranged 875 */ 876 void 877 list_vertical(StringList *sl) 878 { 879 int i, j; 880 int columns, lines; 881 char *p; 882 size_t w, width; 883 884 width = 0; 885 886 for (i = 0 ; i < sl->sl_cur ; i++) { 887 w = strlen(sl->sl_str[i]); 888 if (w > width) 889 width = w; 890 } 891 width = (width + 8) &~ 7; 892 893 columns = ttywidth / width; 894 if (columns == 0) 895 columns = 1; 896 lines = (sl->sl_cur + columns - 1) / columns; 897 for (i = 0; i < lines; i++) { 898 for (j = 0; j < columns; j++) { 899 p = sl->sl_str[j * lines + i]; 900 if (p) 901 fputs(p, ttyout); 902 if (j * lines + i + lines >= sl->sl_cur) { 903 putc('\n', ttyout); 904 break; 905 } 906 if (p) { 907 w = strlen(p); 908 while (w < width) { 909 w = (w + 8) &~ 7; 910 (void)putc('\t', ttyout); 911 } 912 } 913 } 914 } 915 } 916 917 /* 918 * Update the global ttywidth value, using TIOCGWINSZ. 919 */ 920 void 921 setttywidth(int a) 922 { 923 struct winsize winsize; 924 int oerrno = errno; 925 926 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 && 927 winsize.ws_col != 0) 928 ttywidth = winsize.ws_col; 929 else 930 ttywidth = 80; 931 errno = oerrno; 932 } 933 934 /* 935 * Change the rate limit up (SIGUSR1) or down (SIGUSR2) 936 */ 937 void 938 crankrate(int sig) 939 { 940 941 switch (sig) { 942 case SIGUSR1: 943 if (rate_get) 944 rate_get += rate_get_incr; 945 if (rate_put) 946 rate_put += rate_put_incr; 947 break; 948 case SIGUSR2: 949 if (rate_get && rate_get > rate_get_incr) 950 rate_get -= rate_get_incr; 951 if (rate_put && rate_put > rate_put_incr) 952 rate_put -= rate_put_incr; 953 break; 954 default: 955 err(1, "crankrate invoked with unknown signal: %d", sig); 956 } 957 } 958 959 960 /* 961 * Setup or cleanup EditLine structures 962 */ 963 #ifndef NO_EDITCOMPLETE 964 void 965 controlediting(void) 966 { 967 if (editing && el == NULL && hist == NULL) { 968 HistEvent ev; 969 int editmode; 970 971 el = el_init(getprogname(), stdin, ttyout, stderr); 972 /* init editline */ 973 hist = history_init(); /* init the builtin history */ 974 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */ 975 el_set(el, EL_HIST, history, hist); /* use history */ 976 977 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */ 978 el_set(el, EL_PROMPT, prompt); /* set the prompt functions */ 979 el_set(el, EL_RPROMPT, rprompt); 980 981 /* add local file completion, bind to TAB */ 982 el_set(el, EL_ADDFN, "ftp-complete", 983 "Context sensitive argument completion", 984 complete); 985 el_set(el, EL_BIND, "^I", "ftp-complete", NULL); 986 el_source(el, NULL); /* read ~/.editrc */ 987 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0) 988 editing = 0; /* the user doesn't want editing, 989 * so disable, and let statement 990 * below cleanup */ 991 else 992 el_set(el, EL_SIGNAL, 1); 993 } 994 if (!editing) { 995 if (hist) { 996 history_end(hist); 997 hist = NULL; 998 } 999 if (el) { 1000 el_end(el); 1001 el = NULL; 1002 } 1003 } 1004 } 1005 #endif /* !NO_EDITCOMPLETE */ 1006 1007 /* 1008 * Convert the string `arg' to an int, which may have an optional SI suffix 1009 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise. 1010 */ 1011 int 1012 strsuftoi(const char *arg) 1013 { 1014 char *cp; 1015 long val; 1016 1017 if (!isdigit((unsigned char)arg[0])) 1018 return (-1); 1019 1020 val = strtol(arg, &cp, 10); 1021 if (cp != NULL) { 1022 if (cp[0] != '\0' && cp[1] != '\0') 1023 return (-1); 1024 switch (tolower((unsigned char)cp[0])) { 1025 case '\0': 1026 case 'b': 1027 break; 1028 case 'k': 1029 val <<= 10; 1030 break; 1031 case 'm': 1032 val <<= 20; 1033 break; 1034 case 'g': 1035 val <<= 30; 1036 break; 1037 default: 1038 return (-1); 1039 } 1040 } 1041 if (val < 0 || val > INT_MAX) 1042 return (-1); 1043 1044 return (val); 1045 } 1046 1047 /* 1048 * Set up socket buffer sizes before a connection is made. 1049 */ 1050 void 1051 setupsockbufsize(int sock) 1052 { 1053 1054 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, 1055 (void *)&sndbuf_size, sizeof(sndbuf_size)) == -1) 1056 warn("Unable to set sndbuf size %d", sndbuf_size); 1057 1058 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, 1059 (void *)&rcvbuf_size, sizeof(rcvbuf_size)) == -1) 1060 warn("Unable to set rcvbuf size %d", rcvbuf_size); 1061 } 1062 1063 /* 1064 * Copy characters from src into dst, \ quoting characters that require it 1065 */ 1066 void 1067 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen) 1068 { 1069 int di, si; 1070 1071 for (di = si = 0; 1072 src[si] != '\0' && di < dstlen && si < srclen; 1073 di++, si++) { 1074 switch (src[si]) { 1075 case '\\': 1076 case ' ': 1077 case '\t': 1078 case '\r': 1079 case '\n': 1080 case '"': 1081 dst[di++] = '\\'; 1082 if (di >= dstlen) 1083 break; 1084 /* FALLTHROUGH */ 1085 default: 1086 dst[di] = src[si]; 1087 } 1088 } 1089 dst[di] = '\0'; 1090 } 1091 1092 /* 1093 * Copy src into buf (which is len bytes long), expanding % sequences. 1094 */ 1095 void 1096 formatbuf(char *buf, size_t len, const char *src) 1097 { 1098 const char *p, *p2, *q; 1099 int i, op, updirs, pdirs; 1100 1101 #define ADDBUF(x) do { \ 1102 if (i >= len - 1) \ 1103 goto endbuf; \ 1104 buf[i++] = (x); \ 1105 } while (0) 1106 1107 p = src; 1108 for (i = 0; *p; p++) { 1109 if (*p != '%') { 1110 ADDBUF(*p); 1111 continue; 1112 } 1113 p++; 1114 1115 switch (op = *p) { 1116 1117 case '/': 1118 case '.': 1119 case 'c': 1120 p2 = connected ? remotecwd : ""; 1121 updirs = pdirs = 0; 1122 1123 /* option to determine fixed # of dirs from path */ 1124 if (op == '.' || op == 'c') { 1125 int skip; 1126 1127 q = p2; 1128 while (*p2) /* calc # of /'s */ 1129 if (*p2++ == '/') 1130 updirs++; 1131 if (p[1] == '0') { /* print <x> or ... */ 1132 pdirs = 1; 1133 p++; 1134 } 1135 if (p[1] >= '1' && p[1] <= '9') { 1136 /* calc # to skip */ 1137 skip = p[1] - '0'; 1138 p++; 1139 } else 1140 skip = 1; 1141 1142 updirs -= skip; 1143 while (skip-- > 0) { 1144 while ((p2 > q) && (*p2 != '/')) 1145 p2--; /* back up */ 1146 if (skip && p2 > q) 1147 p2--; 1148 } 1149 if (*p2 == '/' && p2 != q) 1150 p2++; 1151 } 1152 1153 if (updirs > 0 && pdirs) { 1154 if (i >= len - 5) 1155 break; 1156 if (op == '.') { 1157 ADDBUF('.'); 1158 ADDBUF('.'); 1159 ADDBUF('.'); 1160 } else { 1161 ADDBUF('/'); 1162 ADDBUF('<'); 1163 if (updirs > 9) { 1164 ADDBUF('9'); 1165 ADDBUF('+'); 1166 } else 1167 ADDBUF('0' + updirs); 1168 ADDBUF('>'); 1169 } 1170 } 1171 for (; *p2; p2++) 1172 ADDBUF(*p2); 1173 break; 1174 1175 case 'M': 1176 case 'm': 1177 for (p2 = connected && hostname ? hostname : "-"; 1178 *p2 ; p2++) { 1179 if (op == 'm' && *p2 == '.') 1180 break; 1181 ADDBUF(*p2); 1182 } 1183 break; 1184 1185 case 'n': 1186 for (p2 = connected ? username : "-"; *p2 ; p2++) 1187 ADDBUF(*p2); 1188 break; 1189 1190 case '%': 1191 ADDBUF('%'); 1192 break; 1193 1194 default: /* display unknown codes literally */ 1195 ADDBUF('%'); 1196 ADDBUF(op); 1197 break; 1198 1199 } 1200 } 1201 endbuf: 1202 buf[i] = '\0'; 1203 } 1204 1205 /* 1206 * Determine if given string is an IPv6 address or not. 1207 * Return 1 for yes, 0 for no 1208 */ 1209 int 1210 isipv6addr(const char *addr) 1211 { 1212 int rv = 0; 1213 #ifdef INET6 1214 struct addrinfo hints, *res; 1215 1216 memset(&hints, 0, sizeof(hints)); 1217 hints.ai_family = PF_INET6; 1218 hints.ai_socktype = SOCK_DGRAM; /*dummy*/ 1219 hints.ai_flags = AI_NUMERICHOST; 1220 if (getaddrinfo(addr, "0", &hints, &res) != 0) 1221 rv = 0; 1222 else { 1223 rv = 1; 1224 freeaddrinfo(res); 1225 } 1226 DPRINTF("isipv6addr: got %d for %s\n", rv, addr); 1227 #endif 1228 return (rv == 1) ? 1 : 0; 1229 } 1230 1231 /* 1232 * Read a line from the FILE stream into buf/buflen using fgets(), so up 1233 * to buflen-1 chars will be read and the result will be NUL terminated. 1234 * If the line has a trailing newline it will be removed. 1235 * If the line is too long, excess characters will be read until 1236 * newline/EOF/error. 1237 * If EOF/error occurs or a too-long line is encountered and errormsg 1238 * isn't NULL, it will be changed to a description of the problem. 1239 * (The EOF message has a leading \n for cosmetic purposes). 1240 * Returns: 1241 * >=0 length of line (excluding trailing newline) if all ok 1242 * -1 error occurred 1243 * -2 EOF encountered 1244 * -3 line was too long 1245 */ 1246 int 1247 getline(FILE *stream, char *buf, size_t buflen, const char **errormsg) 1248 { 1249 int rv, ch; 1250 size_t len; 1251 1252 if (fgets(buf, buflen, stream) == NULL) { 1253 if (feof(stream)) { /* EOF */ 1254 rv = -2; 1255 if (errormsg) 1256 *errormsg = "\nEOF received"; 1257 } else { /* error */ 1258 rv = -1; 1259 if (errormsg) 1260 *errormsg = "Error encountered"; 1261 } 1262 clearerr(stream); 1263 return rv; 1264 } 1265 len = strlen(buf); 1266 if (buf[len-1] == '\n') { /* clear any trailing newline */ 1267 buf[--len] = '\0'; 1268 } else if (len == buflen-1) { /* line too long */ 1269 while ((ch = getchar()) != '\n' && ch != EOF) 1270 continue; 1271 if (errormsg) 1272 *errormsg = "Input line is too long"; 1273 clearerr(stream); 1274 return -3; 1275 } 1276 if (errormsg) 1277 *errormsg = NULL; 1278 return len; 1279 } 1280 1281 /* 1282 * Internal version of connect(2); sets socket buffer sizes, 1283 * binds to a specific local address (if set), and 1284 * supports a connection timeout using a non-blocking connect(2) with 1285 * a poll(2). 1286 * Socket fcntl flags are temporarily updated to include O_NONBLOCK; 1287 * these will not be reverted on connection failure. 1288 * Returns 0 on success, or -1 upon failure (with an appropriate 1289 * error message displayed.) 1290 */ 1291 int 1292 ftp_connect(int sock, const struct sockaddr *name, socklen_t namelen) 1293 { 1294 int flags, rv, timeout, error; 1295 socklen_t slen; 1296 struct timeval endtime, now, td; 1297 struct pollfd pfd[1]; 1298 char hname[NI_MAXHOST]; 1299 char sname[NI_MAXSERV]; 1300 1301 setupsockbufsize(sock); 1302 if (getnameinfo(name, namelen, 1303 hname, sizeof(hname), sname, sizeof(sname), 1304 NI_NUMERICHOST | NI_NUMERICSERV) != 0) { 1305 strlcpy(hname, "?", sizeof(hname)); 1306 strlcpy(sname, "?", sizeof(sname)); 1307 } 1308 1309 if (bindai != NULL) { /* bind to specific addr */ 1310 struct addrinfo *ai; 1311 1312 for (ai = bindai; ai != NULL; ai = ai->ai_next) { 1313 if (ai->ai_family == name->sa_family) 1314 break; 1315 } 1316 if (ai == NULL) 1317 ai = bindai; 1318 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) { 1319 char bname[NI_MAXHOST]; 1320 int saveerr; 1321 1322 saveerr = errno; 1323 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, 1324 bname, sizeof(bname), NULL, 0, NI_NUMERICHOST) != 0) 1325 strlcpy(bname, "?", sizeof(bname)); 1326 errno = saveerr; 1327 warn("Can't bind to `%s'", bname); 1328 return -1; 1329 } 1330 } 1331 1332 /* save current socket flags */ 1333 if ((flags = fcntl(sock, F_GETFL, 0)) == -1) { 1334 warn("Can't %s socket flags for connect to `%s:%s'", 1335 "save", hname, sname); 1336 return -1; 1337 } 1338 /* set non-blocking connect */ 1339 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1) { 1340 warn("Can't set socket non-blocking for connect to `%s:%s'", 1341 hname, sname); 1342 return -1; 1343 } 1344 1345 /* NOTE: we now must restore socket flags on successful exit */ 1346 1347 pfd[0].fd = sock; 1348 pfd[0].events = POLLIN|POLLOUT; 1349 1350 if (quit_time > 0) { /* want a non default timeout */ 1351 (void)gettimeofday(&endtime, NULL); 1352 endtime.tv_sec += quit_time; /* determine end time */ 1353 } 1354 1355 rv = connect(sock, name, namelen); /* inititate the connection */ 1356 if (rv == -1) { /* connection error */ 1357 if (errno != EINPROGRESS) { /* error isn't "please wait" */ 1358 connecterror: 1359 warn("Can't connect to `%s:%s'", hname, sname); 1360 return -1; 1361 } 1362 1363 /* connect EINPROGRESS; wait */ 1364 do { 1365 if (quit_time > 0) { /* determine timeout */ 1366 (void)gettimeofday(&now, NULL); 1367 timersub(&endtime, &now, &td); 1368 timeout = td.tv_sec * 1000 + td.tv_usec/1000; 1369 if (timeout < 0) 1370 timeout = 0; 1371 } else { 1372 timeout = INFTIM; 1373 } 1374 pfd[0].revents = 0; 1375 rv = ftp_poll(pfd, 1, timeout); 1376 /* loop until poll ! EINTR */ 1377 } while (rv == -1 && errno == EINTR); 1378 1379 if (rv == 0) { /* poll (connect) timed out */ 1380 errno = ETIMEDOUT; 1381 goto connecterror; 1382 } 1383 1384 if (rv == -1) { /* poll error */ 1385 goto connecterror; 1386 } else if (pfd[0].revents & (POLLIN|POLLOUT)) { 1387 slen = sizeof(error); /* OK, or pending error */ 1388 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, 1389 &error, &slen) == -1) { 1390 /* Solaris pending error */ 1391 goto connecterror; 1392 } else if (error != 0) { 1393 errno = error; /* BSD pending error */ 1394 goto connecterror; 1395 } 1396 } else { 1397 errno = EBADF; /* this shouldn't happen ... */ 1398 goto connecterror; 1399 } 1400 } 1401 1402 if (fcntl(sock, F_SETFL, flags) == -1) { 1403 /* restore socket flags */ 1404 warn("Can't %s socket flags for connect to `%s:%s'", 1405 "restore", hname, sname); 1406 return -1; 1407 } 1408 return 0; 1409 } 1410 1411 /* 1412 * Internal version of listen(2); sets socket buffer sizes first. 1413 */ 1414 int 1415 ftp_listen(int sock, int backlog) 1416 { 1417 1418 setupsockbufsize(sock); 1419 return (listen(sock, backlog)); 1420 } 1421 1422 /* 1423 * Internal version of poll(2), to allow reimplementation by select(2) 1424 * on platforms without the former. 1425 */ 1426 int 1427 ftp_poll(struct pollfd *fds, int nfds, int timeout) 1428 { 1429 return poll(fds, nfds, timeout); 1430 } 1431 1432 /* 1433 * malloc() with inbuilt error checking 1434 */ 1435 void * 1436 ftp_malloc(size_t size) 1437 { 1438 void *p; 1439 1440 p = malloc(size); 1441 if (p == NULL) 1442 err(1, "Unable to allocate %ld bytes of memory", (long)size); 1443 return (p); 1444 } 1445 1446 /* 1447 * sl_init() with inbuilt error checking 1448 */ 1449 StringList * 1450 ftp_sl_init(void) 1451 { 1452 StringList *p; 1453 1454 p = sl_init(); 1455 if (p == NULL) 1456 err(1, "Unable to allocate memory for stringlist"); 1457 return (p); 1458 } 1459 1460 /* 1461 * sl_add() with inbuilt error checking 1462 */ 1463 void 1464 ftp_sl_add(StringList *sl, char *i) 1465 { 1466 1467 if (sl_add(sl, i) == -1) 1468 err(1, "Unable to add `%s' to stringlist", i); 1469 } 1470 1471 /* 1472 * strdup() with inbuilt error checking 1473 */ 1474 char * 1475 ftp_strdup(const char *str) 1476 { 1477 char *s; 1478 1479 if (str == NULL) 1480 errx(1, "ftp_strdup: called with NULL argument"); 1481 s = strdup(str); 1482 if (s == NULL) 1483 err(1, "Unable to allocate memory for string copy"); 1484 return (s); 1485 } 1486