1 /*- 2 * Copyright (c) 2000 Dag-Erling Co�dan Sm�rgrav 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer 10 * in this position and unchanged. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 3. The name of the author may not be used to endorse or promote products 15 * derived from this software without specific prior written permission. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 */ 28 29 #include <sys/cdefs.h> 30 __FBSDID("$FreeBSD$"); 31 32 /* 33 * The following copyright applies to the base64 code: 34 * 35 *- 36 * Copyright 1997 Massachusetts Institute of Technology 37 * 38 * Permission to use, copy, modify, and distribute this software and 39 * its documentation for any purpose and without fee is hereby 40 * granted, provided that both the above copyright notice and this 41 * permission notice appear in all copies, that both the above 42 * copyright notice and this permission notice appear in all 43 * supporting documentation, and that the name of M.I.T. not be used 44 * in advertising or publicity pertaining to distribution of the 45 * software without specific, written prior permission. M.I.T. makes 46 * no representations about the suitability of this software for any 47 * purpose. It is provided "as is" without express or implied 48 * warranty. 49 * 50 * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS 51 * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, 52 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 53 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT 54 * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 55 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 56 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 57 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 58 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 59 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 60 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 61 * SUCH DAMAGE. 62 */ 63 64 #include <sys/param.h> 65 #include <sys/socket.h> 66 67 #include <ctype.h> 68 #include <err.h> 69 #include <errno.h> 70 #include <locale.h> 71 #include <netdb.h> 72 #include <stdarg.h> 73 #include <stdio.h> 74 #include <stdlib.h> 75 #include <string.h> 76 #include <time.h> 77 #include <unistd.h> 78 79 #include "fetch.h" 80 #include "common.h" 81 #include "httperr.h" 82 83 /* Maximum number of redirects to follow */ 84 #define MAX_REDIRECT 5 85 86 /* Symbolic names for reply codes we care about */ 87 #define HTTP_OK 200 88 #define HTTP_PARTIAL 206 89 #define HTTP_MOVED_PERM 301 90 #define HTTP_MOVED_TEMP 302 91 #define HTTP_SEE_OTHER 303 92 #define HTTP_NEED_AUTH 401 93 #define HTTP_NEED_PROXY_AUTH 407 94 #define HTTP_PROTOCOL_ERROR 999 95 96 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \ 97 || (xyz) == HTTP_MOVED_TEMP \ 98 || (xyz) == HTTP_SEE_OTHER) 99 100 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599) 101 102 103 /***************************************************************************** 104 * I/O functions for decoding chunked streams 105 */ 106 107 struct httpio 108 { 109 conn_t *conn; /* connection */ 110 int chunked; /* chunked mode */ 111 char *buf; /* chunk buffer */ 112 size_t bufsize; /* size of chunk buffer */ 113 ssize_t buflen; /* amount of data currently in buffer */ 114 int bufpos; /* current read offset in buffer */ 115 int eof; /* end-of-file flag */ 116 int error; /* error flag */ 117 size_t chunksize; /* remaining size of current chunk */ 118 #ifndef NDEBUG 119 size_t total; 120 #endif 121 }; 122 123 /* 124 * Get next chunk header 125 */ 126 static int 127 _http_new_chunk(struct httpio *io) 128 { 129 char *p; 130 131 if (_fetch_getln(io->conn) == -1) 132 return (-1); 133 134 if (io->conn->buflen < 2 || !ishexnumber(*io->conn->buf)) 135 return (-1); 136 137 for (p = io->conn->buf; *p && !isspace(*p); ++p) { 138 if (*p == ';') 139 break; 140 if (!ishexnumber(*p)) 141 return (-1); 142 if (isdigit(*p)) { 143 io->chunksize = io->chunksize * 16 + 144 *p - '0'; 145 } else { 146 io->chunksize = io->chunksize * 16 + 147 10 + tolower(*p) - 'a'; 148 } 149 } 150 151 #ifndef NDEBUG 152 if (fetchDebug) { 153 io->total += io->chunksize; 154 if (io->chunksize == 0) 155 fprintf(stderr, "%s(): end of last chunk\n", __func__); 156 else 157 fprintf(stderr, "%s(): new chunk: %lu (%lu)\n", 158 __func__, (unsigned long)io->chunksize, 159 (unsigned long)io->total); 160 } 161 #endif 162 163 return (io->chunksize); 164 } 165 166 /* 167 * Grow the input buffer to at least len bytes 168 */ 169 static inline int 170 _http_growbuf(struct httpio *io, size_t len) 171 { 172 char *tmp; 173 174 if (io->bufsize >= len) 175 return (0); 176 177 if ((tmp = realloc(io->buf, len)) == NULL) 178 return (-1); 179 io->buf = tmp; 180 io->bufsize = len; 181 return (0); 182 } 183 184 /* 185 * Fill the input buffer, do chunk decoding on the fly 186 */ 187 static int 188 _http_fillbuf(struct httpio *io, size_t len) 189 { 190 if (io->error) 191 return (-1); 192 if (io->eof) 193 return (0); 194 195 if (io->chunked == 0) { 196 if (_http_growbuf(io, len) == -1) 197 return (-1); 198 if ((io->buflen = _fetch_read(io->conn, io->buf, len)) == -1) { 199 io->error = 1; 200 return (-1); 201 } 202 io->bufpos = 0; 203 return (io->buflen); 204 } 205 206 if (io->chunksize == 0) { 207 switch (_http_new_chunk(io)) { 208 case -1: 209 io->error = 1; 210 return (-1); 211 case 0: 212 io->eof = 1; 213 return (0); 214 } 215 } 216 217 if (len > io->chunksize) 218 len = io->chunksize; 219 if (_http_growbuf(io, len) == -1) 220 return (-1); 221 if ((io->buflen = _fetch_read(io->conn, io->buf, len)) == -1) { 222 io->error = 1; 223 return (-1); 224 } 225 io->chunksize -= io->buflen; 226 227 if (io->chunksize == 0) { 228 char endl[2]; 229 230 if (_fetch_read(io->conn, endl, 2) != 2 || 231 endl[0] != '\r' || endl[1] != '\n') 232 return (-1); 233 } 234 235 io->bufpos = 0; 236 237 return (io->buflen); 238 } 239 240 /* 241 * Read function 242 */ 243 static int 244 _http_readfn(void *v, char *buf, int len) 245 { 246 struct httpio *io = (struct httpio *)v; 247 int l, pos; 248 249 if (io->error) 250 return (-1); 251 if (io->eof) 252 return (0); 253 254 for (pos = 0; len > 0; pos += l, len -= l) { 255 /* empty buffer */ 256 if (!io->buf || io->bufpos == io->buflen) 257 if (_http_fillbuf(io, len) < 1) 258 break; 259 l = io->buflen - io->bufpos; 260 if (len < l) 261 l = len; 262 bcopy(io->buf + io->bufpos, buf + pos, l); 263 io->bufpos += l; 264 } 265 266 if (!pos && io->error) 267 return (-1); 268 return (pos); 269 } 270 271 /* 272 * Write function 273 */ 274 static int 275 _http_writefn(void *v, const char *buf, int len) 276 { 277 struct httpio *io = (struct httpio *)v; 278 279 return (_fetch_write(io->conn, buf, len)); 280 } 281 282 /* 283 * Close function 284 */ 285 static int 286 _http_closefn(void *v) 287 { 288 struct httpio *io = (struct httpio *)v; 289 int r; 290 291 r = _fetch_close(io->conn); 292 if (io->buf) 293 free(io->buf); 294 free(io); 295 return (r); 296 } 297 298 /* 299 * Wrap a file descriptor up 300 */ 301 static FILE * 302 _http_funopen(conn_t *conn, int chunked) 303 { 304 struct httpio *io; 305 FILE *f; 306 307 if ((io = calloc(1, sizeof *io)) == NULL) { 308 _fetch_syserr(); 309 return (NULL); 310 } 311 io->conn = conn; 312 io->chunked = chunked; 313 f = funopen(io, _http_readfn, _http_writefn, NULL, _http_closefn); 314 if (f == NULL) { 315 _fetch_syserr(); 316 free(io); 317 return (NULL); 318 } 319 return (f); 320 } 321 322 323 /***************************************************************************** 324 * Helper functions for talking to the server and parsing its replies 325 */ 326 327 /* Header types */ 328 typedef enum { 329 hdr_syserror = -2, 330 hdr_error = -1, 331 hdr_end = 0, 332 hdr_unknown = 1, 333 hdr_content_length, 334 hdr_content_range, 335 hdr_last_modified, 336 hdr_location, 337 hdr_transfer_encoding, 338 hdr_www_authenticate 339 } hdr_t; 340 341 /* Names of interesting headers */ 342 static struct { 343 hdr_t num; 344 const char *name; 345 } hdr_names[] = { 346 { hdr_content_length, "Content-Length" }, 347 { hdr_content_range, "Content-Range" }, 348 { hdr_last_modified, "Last-Modified" }, 349 { hdr_location, "Location" }, 350 { hdr_transfer_encoding, "Transfer-Encoding" }, 351 { hdr_www_authenticate, "WWW-Authenticate" }, 352 { hdr_unknown, NULL }, 353 }; 354 355 /* 356 * Send a formatted line; optionally echo to terminal 357 */ 358 static int 359 _http_cmd(conn_t *conn, const char *fmt, ...) 360 { 361 va_list ap; 362 size_t len; 363 char *msg; 364 int r; 365 366 va_start(ap, fmt); 367 len = vasprintf(&msg, fmt, ap); 368 va_end(ap); 369 370 if (msg == NULL) { 371 errno = ENOMEM; 372 _fetch_syserr(); 373 return (-1); 374 } 375 376 r = _fetch_putln(conn, msg, len); 377 free(msg); 378 379 if (r == -1) { 380 _fetch_syserr(); 381 return (-1); 382 } 383 384 return (0); 385 } 386 387 /* 388 * Get and parse status line 389 */ 390 static int 391 _http_get_reply(conn_t *conn) 392 { 393 char *p; 394 395 if (_fetch_getln(conn) == -1) 396 return (-1); 397 /* 398 * A valid status line looks like "HTTP/m.n xyz reason" where m 399 * and n are the major and minor protocol version numbers and xyz 400 * is the reply code. 401 * Unfortunately, there are servers out there (NCSA 1.5.1, to name 402 * just one) that do not send a version number, so we can't rely 403 * on finding one, but if we do, insist on it being 1.0 or 1.1. 404 * We don't care about the reason phrase. 405 */ 406 if (strncmp(conn->buf, "HTTP", 4) != 0) 407 return (HTTP_PROTOCOL_ERROR); 408 p = conn->buf + 4; 409 if (*p == '/') { 410 if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1')) 411 return (HTTP_PROTOCOL_ERROR); 412 p += 4; 413 } 414 if (*p != ' ' || !isdigit(p[1]) || !isdigit(p[2]) || !isdigit(p[3])) 415 return (HTTP_PROTOCOL_ERROR); 416 417 conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0'); 418 return (conn->err); 419 } 420 421 /* 422 * Check a header; if the type matches the given string, return a pointer 423 * to the beginning of the value. 424 */ 425 static const char * 426 _http_match(const char *str, const char *hdr) 427 { 428 while (*str && *hdr && tolower(*str++) == tolower(*hdr++)) 429 /* nothing */; 430 if (*str || *hdr != ':') 431 return (NULL); 432 while (*hdr && isspace(*++hdr)) 433 /* nothing */; 434 return (hdr); 435 } 436 437 /* 438 * Get the next header and return the appropriate symbolic code. 439 */ 440 static hdr_t 441 _http_next_header(conn_t *conn, const char **p) 442 { 443 int i; 444 445 if (_fetch_getln(conn) == -1) 446 return (hdr_syserror); 447 while (conn->buflen && isspace(conn->buf[conn->buflen - 1])) 448 conn->buflen--; 449 conn->buf[conn->buflen] = '\0'; 450 if (conn->buflen == 0) 451 return (hdr_end); 452 /* 453 * We could check for malformed headers but we don't really care. 454 * A valid header starts with a token immediately followed by a 455 * colon; a token is any sequence of non-control, non-whitespace 456 * characters except "()<>@,;:\\\"{}". 457 */ 458 for (i = 0; hdr_names[i].num != hdr_unknown; i++) 459 if ((*p = _http_match(hdr_names[i].name, conn->buf)) != NULL) 460 return (hdr_names[i].num); 461 return (hdr_unknown); 462 } 463 464 /* 465 * Parse a last-modified header 466 */ 467 static int 468 _http_parse_mtime(const char *p, time_t *mtime) 469 { 470 char locale[64], *r; 471 struct tm tm; 472 473 strncpy(locale, setlocale(LC_TIME, NULL), sizeof locale); 474 setlocale(LC_TIME, "C"); 475 r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm); 476 /* XXX should add support for date-2 and date-3 */ 477 setlocale(LC_TIME, locale); 478 if (r == NULL) 479 return (-1); 480 DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d " 481 "%02d:%02d:%02d]\n", 482 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 483 tm.tm_hour, tm.tm_min, tm.tm_sec)); 484 *mtime = timegm(&tm); 485 return (0); 486 } 487 488 /* 489 * Parse a content-length header 490 */ 491 static int 492 _http_parse_length(const char *p, off_t *length) 493 { 494 off_t len; 495 496 for (len = 0; *p && isdigit(*p); ++p) 497 len = len * 10 + (*p - '0'); 498 if (*p) 499 return (-1); 500 DEBUG(fprintf(stderr, "content length: [%lld]\n", 501 (long long)len)); 502 *length = len; 503 return (0); 504 } 505 506 /* 507 * Parse a content-range header 508 */ 509 static int 510 _http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size) 511 { 512 off_t first, last, len; 513 514 if (strncasecmp(p, "bytes ", 6) != 0) 515 return (-1); 516 for (first = 0, p += 6; *p && isdigit(*p); ++p) 517 first = first * 10 + *p - '0'; 518 if (*p != '-') 519 return (-1); 520 for (last = 0, ++p; *p && isdigit(*p); ++p) 521 last = last * 10 + *p - '0'; 522 if (first > last || *p != '/') 523 return (-1); 524 for (len = 0, ++p; *p && isdigit(*p); ++p) 525 len = len * 10 + *p - '0'; 526 if (*p || len < last - first + 1) 527 return (-1); 528 DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n", 529 (long long)first, (long long)last, (long long)len)); 530 *offset = first; 531 *length = last - first + 1; 532 *size = len; 533 return (0); 534 } 535 536 537 /***************************************************************************** 538 * Helper functions for authorization 539 */ 540 541 /* 542 * Base64 encoding 543 */ 544 static char * 545 _http_base64(const char *src) 546 { 547 static const char base64[] = 548 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 549 "abcdefghijklmnopqrstuvwxyz" 550 "0123456789+/"; 551 char *str, *dst; 552 size_t l; 553 int t, r; 554 555 l = strlen(src); 556 if ((str = malloc(((l + 2) / 3) * 4)) == NULL) 557 return (NULL); 558 dst = str; 559 r = 0; 560 561 while (l >= 3) { 562 t = (src[0] << 16) | (src[1] << 8) | src[2]; 563 dst[0] = base64[(t >> 18) & 0x3f]; 564 dst[1] = base64[(t >> 12) & 0x3f]; 565 dst[2] = base64[(t >> 6) & 0x3f]; 566 dst[3] = base64[(t >> 0) & 0x3f]; 567 src += 3; l -= 3; 568 dst += 4; r += 4; 569 } 570 571 switch (l) { 572 case 2: 573 t = (src[0] << 16) | (src[1] << 8); 574 dst[0] = base64[(t >> 18) & 0x3f]; 575 dst[1] = base64[(t >> 12) & 0x3f]; 576 dst[2] = base64[(t >> 6) & 0x3f]; 577 dst[3] = '='; 578 dst += 4; 579 r += 4; 580 break; 581 case 1: 582 t = src[0] << 16; 583 dst[0] = base64[(t >> 18) & 0x3f]; 584 dst[1] = base64[(t >> 12) & 0x3f]; 585 dst[2] = dst[3] = '='; 586 dst += 4; 587 r += 4; 588 break; 589 case 0: 590 break; 591 } 592 593 *dst = 0; 594 return (str); 595 } 596 597 /* 598 * Encode username and password 599 */ 600 static int 601 _http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd) 602 { 603 char *upw, *auth; 604 int r; 605 606 DEBUG(fprintf(stderr, "usr: [%s]\n", usr)); 607 DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd)); 608 if (asprintf(&upw, "%s:%s", usr, pwd) == -1) 609 return (-1); 610 auth = _http_base64(upw); 611 free(upw); 612 if (auth == NULL) 613 return (-1); 614 r = _http_cmd(conn, "%s: Basic %s", hdr, auth); 615 free(auth); 616 return (r); 617 } 618 619 /* 620 * Send an authorization header 621 */ 622 static int 623 _http_authorize(conn_t *conn, const char *hdr, const char *p) 624 { 625 /* basic authorization */ 626 if (strncasecmp(p, "basic:", 6) == 0) { 627 char *user, *pwd, *str; 628 int r; 629 630 /* skip realm */ 631 for (p += 6; *p && *p != ':'; ++p) 632 /* nothing */ ; 633 if (!*p || strchr(++p, ':') == NULL) 634 return (-1); 635 if ((str = strdup(p)) == NULL) 636 return (-1); /* XXX */ 637 user = str; 638 pwd = strchr(str, ':'); 639 *pwd++ = '\0'; 640 r = _http_basic_auth(conn, hdr, user, pwd); 641 free(str); 642 return (r); 643 } 644 return (-1); 645 } 646 647 648 /***************************************************************************** 649 * Helper functions for connecting to a server or proxy 650 */ 651 652 /* 653 * Connect to the correct HTTP server or proxy. 654 */ 655 static conn_t * 656 _http_connect(struct url *URL, struct url *purl, const char *flags) 657 { 658 conn_t *conn; 659 int verbose; 660 int af; 661 662 #ifdef INET6 663 af = AF_UNSPEC; 664 #else 665 af = AF_INET; 666 #endif 667 668 verbose = CHECK_FLAG('v'); 669 if (CHECK_FLAG('4')) 670 af = AF_INET; 671 #ifdef INET6 672 else if (CHECK_FLAG('6')) 673 af = AF_INET6; 674 #endif 675 676 if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) { 677 URL = purl; 678 } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) { 679 /* can't talk http to an ftp server */ 680 /* XXX should set an error code */ 681 return (NULL); 682 } 683 684 if ((conn = _fetch_connect(URL->host, URL->port, af, verbose)) == NULL) 685 /* _fetch_connect() has already set an error code */ 686 return (NULL); 687 if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 && 688 _fetch_ssl(conn, verbose) == -1) { 689 _fetch_close(conn); 690 /* grrr */ 691 errno = EAUTH; 692 _fetch_syserr(); 693 return (NULL); 694 } 695 return (conn); 696 } 697 698 static struct url * 699 _http_get_proxy(void) 700 { 701 struct url *purl; 702 char *p; 703 704 if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 705 (purl = fetchParseURL(p))) { 706 if (!*purl->scheme) 707 strcpy(purl->scheme, SCHEME_HTTP); 708 if (!purl->port) 709 purl->port = _fetch_default_proxy_port(purl->scheme); 710 if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 711 return (purl); 712 fetchFreeURL(purl); 713 } 714 return (NULL); 715 } 716 717 static void 718 _http_print_html(FILE *out, FILE *in) 719 { 720 size_t len; 721 char *line, *p, *q; 722 int comment, tag; 723 724 comment = tag = 0; 725 while ((line = fgetln(in, &len)) != NULL) { 726 while (len && isspace(line[len - 1])) 727 --len; 728 for (p = q = line; q < line + len; ++q) { 729 if (comment && *q == '-') { 730 if (q + 2 < line + len && 731 strcmp(q, "-->") == 0) { 732 tag = comment = 0; 733 q += 2; 734 } 735 } else if (tag && !comment && *q == '>') { 736 p = q + 1; 737 tag = 0; 738 } else if (!tag && *q == '<') { 739 if (q > p) 740 fwrite(p, q - p, 1, out); 741 tag = 1; 742 if (q + 3 < line + len && 743 strcmp(q, "<!--") == 0) { 744 comment = 1; 745 q += 3; 746 } 747 } 748 } 749 if (!tag && q > p) 750 fwrite(p, q - p, 1, out); 751 fputc('\n', out); 752 } 753 } 754 755 756 /***************************************************************************** 757 * Core 758 */ 759 760 /* 761 * Send a request and process the reply 762 * 763 * XXX This function is way too long, the do..while loop should be split 764 * XXX off into a separate function. 765 */ 766 FILE * 767 _http_request(struct url *URL, const char *op, struct url_stat *us, 768 struct url *purl, const char *flags) 769 { 770 conn_t *conn; 771 struct url *url, *new; 772 int chunked, direct, need_auth, noredirect, verbose; 773 int e, i, n; 774 off_t offset, clength, length, size; 775 time_t mtime; 776 const char *p; 777 FILE *f; 778 hdr_t h; 779 char *host; 780 #ifdef INET6 781 char hbuf[MAXHOSTNAMELEN + 1]; 782 #endif 783 784 direct = CHECK_FLAG('d'); 785 noredirect = CHECK_FLAG('A'); 786 verbose = CHECK_FLAG('v'); 787 788 if (direct && purl) { 789 fetchFreeURL(purl); 790 purl = NULL; 791 } 792 793 /* try the provided URL first */ 794 url = URL; 795 796 /* if the A flag is set, we only get one try */ 797 n = noredirect ? 1 : MAX_REDIRECT; 798 i = 0; 799 800 e = HTTP_PROTOCOL_ERROR; 801 need_auth = 0; 802 do { 803 new = NULL; 804 chunked = 0; 805 offset = 0; 806 clength = -1; 807 length = -1; 808 size = -1; 809 mtime = 0; 810 811 /* check port */ 812 if (!url->port) 813 url->port = _fetch_default_port(url->scheme); 814 815 /* were we redirected to an FTP URL? */ 816 if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) { 817 if (strcmp(op, "GET") == 0) 818 return (_ftp_request(url, "RETR", us, purl, flags)); 819 else if (strcmp(op, "HEAD") == 0) 820 return (_ftp_request(url, "STAT", us, purl, flags)); 821 } 822 823 /* connect to server or proxy */ 824 if ((conn = _http_connect(url, purl, flags)) == NULL) 825 goto ouch; 826 827 host = url->host; 828 #ifdef INET6 829 if (strchr(url->host, ':')) { 830 snprintf(hbuf, sizeof(hbuf), "[%s]", url->host); 831 host = hbuf; 832 } 833 #endif 834 835 /* send request */ 836 if (verbose) 837 _fetch_info("requesting %s://%s:%d%s", 838 url->scheme, host, url->port, url->doc); 839 if (purl) { 840 _http_cmd(conn, "%s %s://%s:%d%s HTTP/1.1", 841 op, url->scheme, host, url->port, url->doc); 842 } else { 843 _http_cmd(conn, "%s %s HTTP/1.1", 844 op, url->doc); 845 } 846 847 /* virtual host */ 848 if (url->port == _fetch_default_port(url->scheme)) 849 _http_cmd(conn, "Host: %s", host); 850 else 851 _http_cmd(conn, "Host: %s:%d", host, url->port); 852 853 /* proxy authorization */ 854 if (purl) { 855 if (*purl->user || *purl->pwd) 856 _http_basic_auth(conn, "Proxy-Authorization", 857 purl->user, purl->pwd); 858 else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0') 859 _http_authorize(conn, "Proxy-Authorization", p); 860 } 861 862 /* server authorization */ 863 if (need_auth || *url->user || *url->pwd) { 864 if (*url->user || *url->pwd) 865 _http_basic_auth(conn, "Authorization", url->user, url->pwd); 866 else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0') 867 _http_authorize(conn, "Authorization", p); 868 else if (fetchAuthMethod && fetchAuthMethod(url) == 0) { 869 _http_basic_auth(conn, "Authorization", url->user, url->pwd); 870 } else { 871 _http_seterr(HTTP_NEED_AUTH); 872 goto ouch; 873 } 874 } 875 876 /* other headers */ 877 if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0') 878 _http_cmd(conn, "User-Agent: %s", p); 879 else 880 _http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname()); 881 if (url->offset) 882 _http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset); 883 _http_cmd(conn, "Connection: close"); 884 _http_cmd(conn, ""); 885 886 /* get reply */ 887 switch (_http_get_reply(conn)) { 888 case HTTP_OK: 889 case HTTP_PARTIAL: 890 /* fine */ 891 break; 892 case HTTP_MOVED_PERM: 893 case HTTP_MOVED_TEMP: 894 case HTTP_SEE_OTHER: 895 /* 896 * Not so fine, but we still have to read the headers to 897 * get the new location. 898 */ 899 break; 900 case HTTP_NEED_AUTH: 901 if (need_auth) { 902 /* 903 * We already sent out authorization code, so there's 904 * nothing more we can do. 905 */ 906 _http_seterr(conn->err); 907 goto ouch; 908 } 909 /* try again, but send the password this time */ 910 if (verbose) 911 _fetch_info("server requires authorization"); 912 break; 913 case HTTP_NEED_PROXY_AUTH: 914 /* 915 * If we're talking to a proxy, we already sent our proxy 916 * authorization code, so there's nothing more we can do. 917 */ 918 _http_seterr(conn->err); 919 goto ouch; 920 case HTTP_PROTOCOL_ERROR: 921 /* fall through */ 922 case -1: 923 _fetch_syserr(); 924 goto ouch; 925 default: 926 _http_seterr(conn->err); 927 if (!verbose) 928 goto ouch; 929 /* fall through so we can get the full error message */ 930 } 931 932 /* get headers */ 933 do { 934 switch ((h = _http_next_header(conn, &p))) { 935 case hdr_syserror: 936 _fetch_syserr(); 937 goto ouch; 938 case hdr_error: 939 _http_seterr(HTTP_PROTOCOL_ERROR); 940 goto ouch; 941 case hdr_content_length: 942 _http_parse_length(p, &clength); 943 break; 944 case hdr_content_range: 945 _http_parse_range(p, &offset, &length, &size); 946 break; 947 case hdr_last_modified: 948 _http_parse_mtime(p, &mtime); 949 break; 950 case hdr_location: 951 if (!HTTP_REDIRECT(conn->err)) 952 break; 953 if (new) 954 free(new); 955 if (verbose) 956 _fetch_info("%d redirect to %s", conn->err, p); 957 if (*p == '/') 958 /* absolute path */ 959 new = fetchMakeURL(url->scheme, url->host, url->port, p, 960 url->user, url->pwd); 961 else 962 new = fetchParseURL(p); 963 if (new == NULL) { 964 /* XXX should set an error code */ 965 DEBUG(fprintf(stderr, "failed to parse new URL\n")); 966 goto ouch; 967 } 968 if (!*new->user && !*new->pwd) { 969 strcpy(new->user, url->user); 970 strcpy(new->pwd, url->pwd); 971 } 972 new->offset = url->offset; 973 new->length = url->length; 974 break; 975 case hdr_transfer_encoding: 976 /* XXX weak test*/ 977 chunked = (strcasecmp(p, "chunked") == 0); 978 break; 979 case hdr_www_authenticate: 980 if (conn->err != HTTP_NEED_AUTH) 981 break; 982 /* if we were smarter, we'd check the method and realm */ 983 break; 984 case hdr_end: 985 /* fall through */ 986 case hdr_unknown: 987 /* ignore */ 988 break; 989 } 990 } while (h > hdr_end); 991 992 /* we need to provide authentication */ 993 if (conn->err == HTTP_NEED_AUTH) { 994 e = conn->err; 995 need_auth = 1; 996 _fetch_close(conn); 997 conn = NULL; 998 continue; 999 } 1000 1001 /* we have a hit or an error */ 1002 if (conn->err == HTTP_OK || conn->err == HTTP_PARTIAL || HTTP_ERROR(conn->err)) 1003 break; 1004 1005 /* all other cases: we got a redirect */ 1006 e = conn->err; 1007 need_auth = 0; 1008 _fetch_close(conn); 1009 conn = NULL; 1010 if (!new) { 1011 DEBUG(fprintf(stderr, "redirect with no new location\n")); 1012 break; 1013 } 1014 if (url != URL) 1015 fetchFreeURL(url); 1016 url = new; 1017 } while (++i < n); 1018 1019 /* we failed, or ran out of retries */ 1020 if (conn == NULL) { 1021 _http_seterr(e); 1022 goto ouch; 1023 } 1024 1025 DEBUG(fprintf(stderr, "offset %lld, length %lld," 1026 " size %lld, clength %lld\n", 1027 (long long)offset, (long long)length, 1028 (long long)size, (long long)clength)); 1029 1030 /* check for inconsistencies */ 1031 if (clength != -1 && length != -1 && clength != length) { 1032 _http_seterr(HTTP_PROTOCOL_ERROR); 1033 goto ouch; 1034 } 1035 if (clength == -1) 1036 clength = length; 1037 if (clength != -1) 1038 length = offset + clength; 1039 if (length != -1 && size != -1 && length != size) { 1040 _http_seterr(HTTP_PROTOCOL_ERROR); 1041 goto ouch; 1042 } 1043 if (size == -1) 1044 size = length; 1045 1046 /* fill in stats */ 1047 if (us) { 1048 us->size = size; 1049 us->atime = us->mtime = mtime; 1050 } 1051 1052 /* too far? */ 1053 if (offset > URL->offset) { 1054 _http_seterr(HTTP_PROTOCOL_ERROR); 1055 goto ouch; 1056 } 1057 1058 /* report back real offset and size */ 1059 URL->offset = offset; 1060 URL->length = clength; 1061 1062 /* wrap it up in a FILE */ 1063 if ((f = _http_funopen(conn, chunked)) == NULL) { 1064 _fetch_syserr(); 1065 goto ouch; 1066 } 1067 1068 if (url != URL) 1069 fetchFreeURL(url); 1070 if (purl) 1071 fetchFreeURL(purl); 1072 1073 if (HTTP_ERROR(conn->err)) { 1074 _http_print_html(stderr, f); 1075 fclose(f); 1076 f = NULL; 1077 } 1078 1079 return (f); 1080 1081 ouch: 1082 if (url != URL) 1083 fetchFreeURL(url); 1084 if (purl) 1085 fetchFreeURL(purl); 1086 if (conn != NULL) 1087 _fetch_close(conn); 1088 return (NULL); 1089 } 1090 1091 1092 /***************************************************************************** 1093 * Entry points 1094 */ 1095 1096 /* 1097 * Retrieve and stat a file by HTTP 1098 */ 1099 FILE * 1100 fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags) 1101 { 1102 return (_http_request(URL, "GET", us, _http_get_proxy(), flags)); 1103 } 1104 1105 /* 1106 * Retrieve a file by HTTP 1107 */ 1108 FILE * 1109 fetchGetHTTP(struct url *URL, const char *flags) 1110 { 1111 return (fetchXGetHTTP(URL, NULL, flags)); 1112 } 1113 1114 /* 1115 * Store a file by HTTP 1116 */ 1117 FILE * 1118 fetchPutHTTP(struct url *URL __unused, const char *flags __unused) 1119 { 1120 warnx("fetchPutHTTP(): not implemented"); 1121 return (NULL); 1122 } 1123 1124 /* 1125 * Get an HTTP document's metadata 1126 */ 1127 int 1128 fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags) 1129 { 1130 FILE *f; 1131 1132 if ((f = _http_request(URL, "HEAD", us, _http_get_proxy(), flags)) == NULL) 1133 return (-1); 1134 fclose(f); 1135 return (0); 1136 } 1137 1138 /* 1139 * List a directory 1140 */ 1141 struct url_ent * 1142 fetchListHTTP(struct url *url __unused, const char *flags __unused) 1143 { 1144 warnx("fetchListHTTP(): not implemented"); 1145 return (NULL); 1146 } 1147