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