1 /* $OpenBSD: fetch.c,v 1.51 2004/09/16 04:39:16 deraadt Exp $ */ 2 /* $NetBSD: fetch.c,v 1.14 1997/08/18 10:20:20 lukem Exp $ */ 3 4 /*- 5 * Copyright (c) 1997 The NetBSD Foundation, Inc. 6 * All rights reserved. 7 * 8 * This code is derived from software contributed to The NetBSD Foundation 9 * by Jason Thorpe and Luke Mewburn. 10 * 11 * Redistribution and use in source and binary forms, with or without 12 * modification, are permitted provided that the following conditions 13 * are met: 14 * 1. Redistributions of source code must retain the above copyright 15 * notice, this list of conditions and the following disclaimer. 16 * 2. Redistributions in binary form must reproduce the above copyright 17 * notice, this list of conditions and the following disclaimer in the 18 * documentation and/or other materials provided with the distribution. 19 * 3. All advertising materials mentioning features or use of this software 20 * must display the following acknowledgement: 21 * This product includes software developed by the NetBSD 22 * Foundation, Inc. and its contributors. 23 * 4. Neither the name of The NetBSD Foundation nor the names of its 24 * contributors may be used to endorse or promote products derived 25 * from this software without specific prior written permission. 26 * 27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 37 * POSSIBILITY OF SUCH DAMAGE. 38 */ 39 40 #if !defined(lint) && !defined(SMALL) 41 static char rcsid[] = "$OpenBSD: fetch.c,v 1.51 2004/09/16 04:39:16 deraadt Exp $"; 42 #endif /* not lint and not SMALL */ 43 44 /* 45 * FTP User Program -- Command line file retrieval 46 */ 47 48 #include <sys/types.h> 49 #include <sys/param.h> 50 #include <sys/socket.h> 51 #include <sys/stat.h> 52 53 #include <netinet/in.h> 54 55 #include <arpa/ftp.h> 56 #include <arpa/inet.h> 57 58 #include <ctype.h> 59 #include <err.h> 60 #include <libgen.h> 61 #include <netdb.h> 62 #include <fcntl.h> 63 #include <signal.h> 64 #include <stdio.h> 65 #include <errno.h> 66 #include <stdlib.h> 67 #include <string.h> 68 #include <unistd.h> 69 #include <util.h> 70 71 #include "ftp_var.h" 72 73 static int url_get(const char *, const char *, const char *); 74 void aborthttp(int); 75 void abortfile(int); 76 char hextochar(const char *); 77 char *urldecode(const char *); 78 79 #define FTP_URL "ftp://" /* ftp URL prefix */ 80 #define HTTP_URL "http://" /* http URL prefix */ 81 #define FILE_URL "file:" /* file URL prefix */ 82 #define FTP_PROXY "ftp_proxy" /* env var with ftp proxy location */ 83 #define HTTP_PROXY "http_proxy" /* env var with http proxy location */ 84 85 86 #define EMPTYSTRING(x) ((x) == NULL || (*(x) == '\0')) 87 88 static const char *at_encoding_warning = 89 "Extra `@' characters in usernames and passwords should be encoded as %%40"; 90 91 jmp_buf httpabort; 92 93 /* 94 * Retrieve URL, via the proxy in $proxyvar if necessary. 95 * Modifies the string argument given. 96 * Returns -1 on failure, 0 on success 97 */ 98 static int 99 url_get(const char *origline, const char *proxyenv, const char *outfile) 100 { 101 struct addrinfo hints, *res0, *res; 102 int error; 103 int i, isftpurl, isfileurl, isredirect; 104 volatile int s, out; 105 size_t len; 106 char *cp, *ep, *portnum, *path; 107 char pbuf[NI_MAXSERV], hbuf[NI_MAXHOST]; 108 const char * volatile savefile; 109 char *line, *host, *port, *buf; 110 char * volatile proxy; 111 char *hosttail; 112 volatile sig_t oldintr; 113 off_t hashbytes; 114 char *cause = "unknown"; 115 FILE *fin; 116 int rval; 117 118 s = -1; 119 proxy = NULL; 120 fin = NULL; 121 buf = NULL; 122 isftpurl = 0; 123 isfileurl = 0; 124 isredirect = 0; 125 rval = -1; 126 127 line = strdup(origline); 128 if (line == NULL) 129 errx(1, "Can't allocate memory to parse URL"); 130 if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) 131 host = line + sizeof(HTTP_URL) - 1; 132 else if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) { 133 host = line + sizeof(FTP_URL) - 1; 134 isftpurl = 1; 135 } else if (strncasecmp(line, FILE_URL, sizeof(FILE_URL) - 1) == 0) { 136 host = line + sizeof(FILE_URL) - 1; 137 isfileurl = 1; 138 } else 139 errx(1, "url_get: Invalid URL '%s'", line); 140 141 if (isfileurl) { 142 path = host; 143 } else { 144 path = strchr(host, '/'); /* find path */ 145 if (EMPTYSTRING(path)) { 146 if (isftpurl) 147 goto noftpautologin; 148 warnx("Invalid URL (no `/' after host): %s", origline); 149 goto cleanup_url_get; 150 } 151 *path++ = '\0'; 152 if (EMPTYSTRING(path)) { 153 if (isftpurl) 154 goto noftpautologin; 155 warnx("Invalid URL (no file after host): %s", origline); 156 goto cleanup_url_get; 157 } 158 } 159 160 if (outfile) 161 savefile = outfile; 162 else 163 savefile = basename(path); 164 165 if (EMPTYSTRING(savefile)) { 166 if (isftpurl) 167 goto noftpautologin; 168 warnx("Invalid URL (no file after directory): %s", origline); 169 goto cleanup_url_get; 170 } 171 172 if (proxyenv != NULL) { /* use proxy */ 173 proxy = strdup(proxyenv); 174 if (proxy == NULL) 175 errx(1, "Can't allocate memory for proxy URL."); 176 if (strncasecmp(proxy, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) 177 host = proxy + sizeof(HTTP_URL) - 1; 178 else if (strncasecmp(proxy, FTP_URL, sizeof(FTP_URL) - 1) == 0) 179 host = proxy + sizeof(FTP_URL) - 1; 180 else { 181 warnx("Malformed proxy URL: %s", proxyenv); 182 goto cleanup_url_get; 183 } 184 if (EMPTYSTRING(host)) { 185 warnx("Malformed proxy URL: %s", proxyenv); 186 goto cleanup_url_get; 187 } 188 *--path = '/'; /* add / back to real path */ 189 path = strchr(host, '/'); /* remove trailing / on host */ 190 if (!EMPTYSTRING(path)) 191 *path++ = '\0'; 192 path = line; 193 } 194 195 if (isfileurl) { 196 struct stat st; 197 198 s = open(path, O_RDONLY); 199 if (s == -1) { 200 warn("Can't open file %s", path); 201 goto cleanup_url_get; 202 } 203 204 if (fstat(s, &st) == -1) 205 filesize = -1; 206 else 207 filesize = st.st_size; 208 209 /* Open the output file. */ 210 if (strcmp(savefile, "-") != 0) { 211 out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666); 212 if (out < 0) { 213 warn("Can't open %s", savefile); 214 goto cleanup_url_get; 215 } 216 } else 217 out = fileno(stdout); 218 219 /* Trap signals */ 220 oldintr = NULL; 221 if (setjmp(httpabort)) { 222 if (oldintr) 223 (void)signal(SIGINT, oldintr); 224 goto cleanup_url_get; 225 } 226 oldintr = signal(SIGINT, abortfile); 227 228 bytes = 0; 229 hashbytes = mark; 230 progressmeter(-1); 231 232 if ((buf = malloc(4096)) == NULL) 233 errx(1, "Can't allocate memory for transfer buffer"); 234 235 /* Finally, suck down the file. */ 236 i = 0; 237 while ((len = read(s, buf, 4096)) > 0) { 238 bytes += len; 239 for (cp = buf; len > 0; len -= i, cp += i) { 240 if ((i = write(out, cp, len)) == -1) { 241 warn("Writing %s", savefile); 242 goto cleanup_url_get; 243 } 244 else if (i == 0) 245 break; 246 } 247 if (hash && !progress) { 248 while (bytes >= hashbytes) { 249 (void)putc('#', ttyout); 250 hashbytes += mark; 251 } 252 (void)fflush(ttyout); 253 } 254 } 255 if (hash && !progress && bytes > 0) { 256 if (bytes < mark) 257 (void)putc('#', ttyout); 258 (void)putc('\n', ttyout); 259 (void)fflush(ttyout); 260 } 261 if (len != 0) { 262 warn("Reading from file"); 263 goto cleanup_url_get; 264 } 265 progressmeter(1); 266 if (verbose) 267 fputs("Successfully retrieved file.\n", ttyout); 268 (void)signal(SIGINT, oldintr); 269 270 rval = 0; 271 goto cleanup_url_get; 272 } 273 274 if (*host == '[' && (hosttail = strrchr(host, ']')) != NULL && 275 (hosttail[1] == '\0' || hosttail[1] == ':')) { 276 host++; 277 *hosttail++ = '\0'; 278 } else 279 hosttail = host; 280 281 portnum = strrchr(hosttail, ':'); /* find portnum */ 282 if (portnum != NULL) 283 *portnum++ = '\0'; 284 285 if (debug) 286 fprintf(ttyout, "host %s, port %s, path %s, save as %s.\n", 287 host, portnum, path, savefile); 288 289 memset(&hints, 0, sizeof(hints)); 290 hints.ai_family = family; 291 hints.ai_socktype = SOCK_STREAM; 292 port = portnum ? portnum : httpport; 293 error = getaddrinfo(host, port, &hints, &res0); 294 if (error == EAI_SERVICE && port == httpport) { 295 /* 296 * If the services file is corrupt/missing, fall back 297 * on our hard-coded defines. 298 */ 299 snprintf(pbuf, sizeof(pbuf), "%d", HTTP_PORT); 300 error = getaddrinfo(host, pbuf, &hints, &res0); 301 } 302 if (error) { 303 warnx("%s: %s", gai_strerror(error), host); 304 goto cleanup_url_get; 305 } 306 307 s = -1; 308 for (res = res0; res; res = res->ai_next) { 309 if (getnameinfo(res->ai_addr, res->ai_addrlen, hbuf, 310 sizeof(hbuf), NULL, 0, NI_NUMERICHOST) != 0) 311 strlcpy(hbuf, "(unknown)", sizeof(hbuf)); 312 if (verbose) 313 fprintf(ttyout, "Trying %s...\n", hbuf); 314 315 s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); 316 if (s == -1) { 317 cause = "socket"; 318 continue; 319 } 320 321 again: 322 if (connect(s, res->ai_addr, res->ai_addrlen) < 0) { 323 if (errno == EINTR) 324 goto again; 325 close(s); 326 s = -1; 327 cause = "connect"; 328 continue; 329 } 330 331 /* get port in numeric */ 332 if (getnameinfo(res->ai_addr, res->ai_addrlen, NULL, 0, 333 pbuf, sizeof(pbuf), NI_NUMERICSERV) == 0) 334 port = pbuf; 335 else 336 port = NULL; 337 338 break; 339 } 340 freeaddrinfo(res0); 341 if (s < 0) { 342 warn("%s", cause); 343 goto cleanup_url_get; 344 } 345 346 fin = fdopen(s, "r+"); 347 348 /* 349 * Construct and send the request. Proxy requests don't want leading /. 350 */ 351 if (proxy) { 352 /* 353 * Host: directive must use the destination host address for 354 * the original URI (path). We do not attach it at this moment. 355 */ 356 if (verbose) 357 fprintf(ttyout, "Requesting %s (via %s)\n", 358 origline, proxyenv); 359 fprintf(fin, "GET %s HTTP/1.0\r\n%s\r\n\r\n", path, HTTP_USER_AGENT); 360 } else { 361 if (verbose) 362 fprintf(ttyout, "Requesting %s\n", origline); 363 if (strchr(host, ':')) { 364 char *h, *p; 365 366 /* strip off scoped address portion, since it's local to node */ 367 h = strdup(host); 368 if (h == NULL) 369 errx(1, "Can't allocate memory."); 370 if ((p = strchr(h, '%')) != NULL) 371 *p = '\0'; 372 /* 373 * Send port number only if it's specified and does not equal 374 * 80. Some broken HTTP servers get confused if you explicitly 375 * send them the port number. 376 */ 377 if (port && strcmp(port, "80") != 0) 378 fprintf(fin, 379 "GET /%s HTTP/1.0\r\nHost: [%s]:%s\r\n%s\r\n\r\n", 380 path, h, port, HTTP_USER_AGENT); 381 else 382 fprintf(fin, 383 "GET /%s HTTP/1.0\r\nHost: [%s]\r\n%s\r\n\r\n", 384 path, h, HTTP_USER_AGENT); 385 free(h); 386 } else { 387 if (port && strcmp(port, "80") != 0) 388 fprintf(fin, 389 "GET /%s HTTP/1.0\r\nHost: %s:%s\r\n%s\r\n\r\n", 390 path, host, port, HTTP_USER_AGENT); 391 else 392 fprintf(fin, 393 "GET /%s HTTP/1.0\r\nHost: %s\r\n%s\r\n\r\n", 394 path, host, HTTP_USER_AGENT); 395 } 396 } 397 if (fflush(fin) == EOF) { 398 warn("Writing HTTP request"); 399 goto cleanup_url_get; 400 } 401 402 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) { 403 warn("Receiving HTTP reply"); 404 goto cleanup_url_get; 405 } 406 407 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n')) 408 buf[--len] = '\0'; 409 if (debug) 410 fprintf(ttyout, "received '%s'\n", buf); 411 412 cp = strchr(buf, ' '); 413 if (cp == NULL) 414 goto improper; 415 else 416 cp++; 417 if (strncmp(cp, "301", 3) == 0 || strncmp(cp, "302", 3) == 0) { 418 isredirect++; 419 } else if (strncmp(cp, "200", 3)) { 420 warnx("Error retrieving file: %s", cp); 421 goto cleanup_url_get; 422 } 423 424 /* 425 * Read the rest of the header. 426 */ 427 free(buf); 428 filesize = -1; 429 430 while (1) { 431 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) { 432 warn("Receiving HTTP reply"); 433 goto cleanup_url_get; 434 } 435 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n')) 436 buf[--len] = '\0'; 437 if (len == 0) 438 break; 439 if (debug) 440 fprintf(ttyout, "received '%s'\n", buf); 441 442 /* Look for some headers */ 443 cp = buf; 444 #define CONTENTLEN "Content-Length: " 445 if (strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0) { 446 cp += sizeof(CONTENTLEN) - 1; 447 filesize = strtol(cp, &ep, 10); 448 if (filesize < 1 || *ep != '\0') 449 goto improper; 450 #define LOCATION "Location: " 451 } else if (isredirect && 452 strncasecmp(cp, LOCATION, sizeof(LOCATION) - 1) == 0) { 453 cp += sizeof(LOCATION) - 1; 454 if (verbose) 455 fprintf(ttyout, "Redirected to %s\n", cp); 456 if (fin != NULL) 457 fclose(fin); 458 else if (s != -1) 459 close(s); 460 if (proxy) 461 free(proxy); 462 free(line); 463 rval = url_get(cp, proxyenv, outfile); 464 if (buf) 465 free(buf); 466 return (rval); 467 } 468 } 469 470 /* Open the output file. */ 471 if (strcmp(savefile, "-") != 0) { 472 out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666); 473 if (out < 0) { 474 warn("Can't open %s", savefile); 475 goto cleanup_url_get; 476 } 477 } else 478 out = fileno(stdout); 479 480 /* Trap signals */ 481 oldintr = NULL; 482 if (setjmp(httpabort)) { 483 if (oldintr) 484 (void)signal(SIGINT, oldintr); 485 goto cleanup_url_get; 486 } 487 oldintr = signal(SIGINT, aborthttp); 488 489 bytes = 0; 490 hashbytes = mark; 491 progressmeter(-1); 492 493 free(buf); 494 495 /* Finally, suck down the file. */ 496 if ((buf = malloc(4096)) == NULL) 497 errx(1, "Can't allocate memory for transfer buffer"); 498 i = 0; 499 while ((len = fread(buf, sizeof(char), 4096, fin)) > 0) { 500 bytes += len; 501 for (cp = buf; len > 0; len -= i, cp += i) { 502 if ((i = write(out, cp, len)) == -1) { 503 warn("Writing %s", savefile); 504 goto cleanup_url_get; 505 } 506 else if (i == 0) 507 break; 508 } 509 if (hash && !progress) { 510 while (bytes >= hashbytes) { 511 (void)putc('#', ttyout); 512 hashbytes += mark; 513 } 514 (void)fflush(ttyout); 515 } 516 } 517 if (hash && !progress && bytes > 0) { 518 if (bytes < mark) 519 (void)putc('#', ttyout); 520 (void)putc('\n', ttyout); 521 (void)fflush(ttyout); 522 } 523 if (len != 0) { 524 warn("Reading from socket"); 525 goto cleanup_url_get; 526 } 527 progressmeter(1); 528 if (filesize != -1 && len == 0 && bytes != filesize) { 529 if (verbose) 530 fputs("Read short file.\n", ttyout); 531 goto cleanup_url_get; 532 } 533 534 if (verbose) 535 fputs("Successfully retrieved file.\n", ttyout); 536 (void)signal(SIGINT, oldintr); 537 538 rval = 0; 539 goto cleanup_url_get; 540 541 noftpautologin: 542 warnx( 543 "Auto-login using ftp URLs isn't supported when using $ftp_proxy"); 544 goto cleanup_url_get; 545 546 improper: 547 warnx("Improper response from %s", host); 548 549 cleanup_url_get: 550 if (fin != NULL) 551 fclose(fin); 552 else if (s != -1) 553 close(s); 554 if (buf) 555 free(buf); 556 if (proxy) 557 free(proxy); 558 free(line); 559 return (rval); 560 } 561 562 /* 563 * Abort a http retrieval 564 */ 565 /* ARGSUSED */ 566 void 567 aborthttp(int signo) 568 { 569 570 alarmtimer(0); 571 fputs("\nhttp fetch aborted.\n", ttyout); 572 (void)fflush(ttyout); 573 longjmp(httpabort, 1); 574 } 575 576 /* 577 * Abort a http retrieval 578 */ 579 /* ARGSUSED */ 580 void 581 abortfile(int signo) 582 { 583 584 alarmtimer(0); 585 fputs("\nfile fetch aborted.\n", ttyout); 586 (void)fflush(ttyout); 587 longjmp(httpabort, 1); 588 } 589 590 /* 591 * Retrieve multiple files from the command line, transferring 592 * files of the form "host:path", "ftp://host/path" using the 593 * ftp protocol, and files of the form "http://host/path" using 594 * the http protocol. 595 * If path has a trailing "/", then return (-1); 596 * the path will be cd-ed into and the connection remains open, 597 * and the function will return -1 (to indicate the connection 598 * is alive). 599 * If an error occurs the return value will be the offset+1 in 600 * argv[] of the file that caused a problem (i.e, argv[x] 601 * returns x+1) 602 * Otherwise, 0 is returned if all files retrieved successfully. 603 */ 604 int 605 auto_fetch(int argc, char *argv[], char *outfile) 606 { 607 char *xargv[5]; 608 char *cp, *line, *host, *dir, *file, *portnum; 609 char *user, *pass; 610 char *ftpproxy, *httpproxy; 611 int rval, xargc; 612 volatile int argpos; 613 int dirhasglob, filehasglob, oautologin; 614 char rempath[MAXPATHLEN]; 615 616 argpos = 0; 617 618 if (setjmp(toplevel)) { 619 if (connected) 620 disconnect(0, NULL); 621 return (argpos + 1); 622 } 623 (void)signal(SIGINT, (sig_t)intr); 624 (void)signal(SIGPIPE, (sig_t)lostpeer); 625 626 if ((ftpproxy = getenv(FTP_PROXY)) != NULL && *ftpproxy == '\0') 627 ftpproxy = NULL; 628 if ((httpproxy = getenv(HTTP_PROXY)) != NULL && *httpproxy == '\0') 629 httpproxy = NULL; 630 631 /* 632 * Loop through as long as there's files to fetch. 633 */ 634 for (rval = 0; (rval == 0) && (argpos < argc); free(line), argpos++) { 635 if (strchr(argv[argpos], ':') == NULL) 636 break; 637 host = dir = file = portnum = user = pass = NULL; 638 639 /* 640 * We muck with the string, so we make a copy. 641 */ 642 line = strdup(argv[argpos]); 643 if (line == NULL) 644 errx(1, "Can't allocate memory for auto-fetch."); 645 646 /* 647 * Try HTTP URL-style arguments first. 648 */ 649 if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 || 650 strncasecmp(line, FILE_URL, sizeof(FILE_URL) - 1) == 0) { 651 if (url_get(line, httpproxy, outfile) == -1) 652 rval = argpos + 1; 653 continue; 654 } 655 656 /* 657 * Try FTP URL-style arguments next. If ftpproxy is 658 * set, use url_get() instead of standard ftp. 659 * Finally, try host:file. 660 */ 661 host = line; 662 if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) { 663 char *passend, *passagain, *userend; 664 665 if (ftpproxy) { 666 if (url_get(line, ftpproxy, outfile) == -1) 667 rval = argpos + 1; 668 continue; 669 } 670 host += sizeof(FTP_URL) - 1; 671 dir = strchr(host, '/'); 672 673 /* Look for [user:pass@]host[:port] */ 674 675 /* check if we have "user:pass@" */ 676 userend = strchr(host, ':'); 677 passend = strchr(host, '@'); 678 if (passend && userend && userend < passend && 679 (!dir || passend < dir)) { 680 user = host; 681 pass = userend + 1; 682 host = passend + 1; 683 *userend = *passend = '\0'; 684 passagain = strchr(host, '@'); 685 if (strchr(pass, '@') != NULL || 686 (passagain != NULL && passagain < dir)) { 687 warnx(at_encoding_warning); 688 goto bad_ftp_url; 689 } 690 691 if (EMPTYSTRING(user) || EMPTYSTRING(pass)) { 692 bad_ftp_url: 693 warnx("Invalid URL: %s", argv[argpos]); 694 rval = argpos + 1; 695 continue; 696 } 697 user = urldecode(user); 698 pass = urldecode(pass); 699 } 700 701 #ifdef INET6 702 /* check [host]:port, or [host] */ 703 if (host[0] == '[') { 704 cp = strchr(host, ']'); 705 if (cp && (!dir || cp < dir)) { 706 if (cp + 1 == dir || cp[1] == ':') { 707 host++; 708 *cp++ = '\0'; 709 } else 710 cp = NULL; 711 } else 712 cp = host; 713 } else 714 cp = host; 715 #else 716 cp = host; 717 #endif 718 719 /* split off host[:port] if there is */ 720 if (cp) { 721 portnum = strchr(cp, ':'); 722 if (!portnum) 723 ; 724 else { 725 if (!dir) 726 ; 727 else if (portnum + 1 < dir) { 728 *portnum++ = '\0'; 729 /* 730 * XXX should check if portnum 731 * is decimal number 732 */ 733 } else { 734 /* empty portnum */ 735 goto bad_ftp_url; 736 } 737 } 738 } else 739 portnum = NULL; 740 } else { /* classic style `host:file' */ 741 dir = strchr(host, ':'); 742 } 743 if (EMPTYSTRING(host)) { 744 rval = argpos + 1; 745 continue; 746 } 747 748 /* 749 * If dir is NULL, the file wasn't specified 750 * (URL looked something like ftp://host) 751 */ 752 if (dir != NULL) 753 *dir++ = '\0'; 754 755 /* 756 * Extract the file and (if present) directory name. 757 */ 758 if (!EMPTYSTRING(dir)) { 759 cp = strrchr(dir, '/'); 760 if (cp != NULL) { 761 *cp++ = '\0'; 762 file = cp; 763 } else { 764 file = dir; 765 dir = NULL; 766 } 767 } 768 if (debug) 769 fprintf(ttyout, 770 "user %s:%s host %s port %s dir %s file %s\n", 771 user, pass, host, portnum, dir, file); 772 773 /* 774 * Set up the connection. 775 */ 776 if (connected) 777 disconnect(0, NULL); 778 xargv[0] = __progname; 779 xargv[1] = host; 780 xargv[2] = NULL; 781 xargc = 2; 782 if (!EMPTYSTRING(portnum)) { 783 xargv[2] = portnum; 784 xargv[3] = NULL; 785 xargc = 3; 786 } 787 oautologin = autologin; 788 if (user != NULL) 789 autologin = 0; 790 setpeer(xargc, xargv); 791 autologin = oautologin; 792 if ((connected == 0) || 793 ((connected == 1) && !ftp_login(host, user, pass))) { 794 warnx("Can't connect or login to host `%s'", host); 795 rval = argpos + 1; 796 continue; 797 } 798 799 /* Always use binary transfers. */ 800 setbinary(0, NULL); 801 802 dirhasglob = filehasglob = 0; 803 if (doglob) { 804 if (!EMPTYSTRING(dir) && 805 strpbrk(dir, "*?[]{}") != NULL) 806 dirhasglob = 1; 807 if (!EMPTYSTRING(file) && 808 strpbrk(file, "*?[]{}") != NULL) 809 filehasglob = 1; 810 } 811 812 /* Change directories, if necessary. */ 813 if (!EMPTYSTRING(dir) && !dirhasglob) { 814 xargv[0] = "cd"; 815 xargv[1] = dir; 816 xargv[2] = NULL; 817 cd(2, xargv); 818 if (!dirchange) { 819 rval = argpos + 1; 820 continue; 821 } 822 } 823 824 if (EMPTYSTRING(file)) { 825 rval = -1; 826 continue; 827 } 828 829 if (verbose) 830 fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "", file); 831 832 if (dirhasglob) { 833 snprintf(rempath, sizeof(rempath), "%s/%s", dir, file); 834 file = rempath; 835 } 836 837 /* Fetch the file(s). */ 838 xargc = 2; 839 xargv[0] = "get"; 840 xargv[1] = file; 841 xargv[2] = NULL; 842 if (dirhasglob || filehasglob) { 843 int ointeractive; 844 845 ointeractive = interactive; 846 interactive = 0; 847 xargv[0] = "mget"; 848 mget(xargc, xargv); 849 interactive = ointeractive; 850 } else { 851 if (outfile != NULL) { 852 xargv[2] = outfile; 853 xargv[3] = NULL; 854 xargc++; 855 } 856 get(xargc, xargv); 857 } 858 859 if ((code / 100) != COMPLETE) 860 rval = argpos + 1; 861 } 862 if (connected && rval != -1) 863 disconnect(0, NULL); 864 return (rval); 865 } 866 867 char * 868 urldecode(const char *str) 869 { 870 char *ret; 871 char c; 872 int i, reallen; 873 874 if (str == NULL) 875 return NULL; 876 if ((ret = malloc(strlen(str)+1)) == NULL) 877 err(1, "Can't allocate memory for URL decoding"); 878 for (i = 0, reallen = 0; str[i] != '\0'; i++, reallen++, ret++) { 879 c = str[i]; 880 if (c == '+') { 881 *ret = ' '; 882 continue; 883 } 884 /* Can't use strtol here because next char after %xx may be 885 * a digit. */ 886 if (c == '%' && isxdigit(str[i+1]) && isxdigit(str[i+2])) { 887 *ret = hextochar(&str[i+1]); 888 i+=2; 889 continue; 890 } 891 *ret = c; 892 } 893 *ret = '\0'; 894 895 return ret-reallen; 896 } 897 898 char 899 hextochar(const char *str) 900 { 901 char c, ret; 902 903 c = str[0]; 904 ret = c; 905 if (isalpha(c)) 906 ret -= isupper(c) ? 'A' - 10 : 'a' - 10; 907 else 908 ret -= '0'; 909 ret *= 16; 910 911 c = str[1]; 912 ret += c; 913 if (isalpha(c)) 914 ret -= isupper(c) ? 'A' - 10 : 'a' - 10; 915 else 916 ret -= '0'; 917 return ret; 918 } 919 920 int 921 isurl(const char *p) 922 { 923 924 if (strncasecmp(p, FTP_URL, sizeof(FTP_URL) - 1) == 0 || 925 strncasecmp(p, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 || 926 strncasecmp(p, FILE_URL, sizeof(FILE_URL) - 1) == 0 || 927 strstr(p, ":/")) 928 return (1); 929 return (0); 930 } 931