http.c revision 174751
1/*- 2 * Copyright (c) 2000-2004 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: head/lib/libfetch/http.c 174751 2007-12-18 10:41:12Z des $"); 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 <netinet/in.h> 80#include <netinet/tcp.h> 81 82#include "fetch.h" 83#include "common.h" 84#include "httperr.h" 85 86/* Maximum number of redirects to follow */ 87#define MAX_REDIRECT 5 88 89/* Symbolic names for reply codes we care about */ 90#define HTTP_OK 200 91#define HTTP_PARTIAL 206 92#define HTTP_MOVED_PERM 301 93#define HTTP_MOVED_TEMP 302 94#define HTTP_SEE_OTHER 303 95#define HTTP_TEMP_REDIRECT 307 96#define HTTP_NEED_AUTH 401 97#define HTTP_NEED_PROXY_AUTH 407 98#define HTTP_BAD_RANGE 416 99#define HTTP_PROTOCOL_ERROR 999 100 101#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \ 102 || (xyz) == HTTP_MOVED_TEMP \ 103 || (xyz) == HTTP_TEMP_REDIRECT \ 104 || (xyz) == HTTP_SEE_OTHER) 105 106#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599) 107 108 109/***************************************************************************** 110 * I/O functions for decoding chunked streams 111 */ 112 113struct httpio 114{ 115 conn_t *conn; /* connection */ 116 int chunked; /* chunked mode */ 117 char *buf; /* chunk buffer */ 118 size_t bufsize; /* size of chunk buffer */ 119 ssize_t buflen; /* amount of data currently in buffer */ 120 int bufpos; /* current read offset in buffer */ 121 int eof; /* end-of-file flag */ 122 int error; /* error flag */ 123 size_t chunksize; /* remaining size of current chunk */ 124#ifndef NDEBUG 125 size_t total; 126#endif 127}; 128 129/* 130 * Get next chunk header 131 */ 132static int 133http_new_chunk(struct httpio *io) 134{ 135 char *p; 136 137 if (fetch_getln(io->conn) == -1) 138 return (-1); 139 140 if (io->conn->buflen < 2 || !isxdigit((int)*io->conn->buf)) 141 return (-1); 142 143 for (p = io->conn->buf; *p && !isspace((int)*p); ++p) { 144 if (*p == ';') 145 break; 146 if (!isxdigit((int)*p)) 147 return (-1); 148 if (isdigit((int)*p)) { 149 io->chunksize = io->chunksize * 16 + 150 *p - '0'; 151 } else { 152 io->chunksize = io->chunksize * 16 + 153 10 + tolower(*p) - 'a'; 154 } 155 } 156 157#ifndef NDEBUG 158 if (fetchDebug) { 159 io->total += io->chunksize; 160 if (io->chunksize == 0) 161 fprintf(stderr, "%s(): end of last chunk\n", __func__); 162 else 163 fprintf(stderr, "%s(): new chunk: %lu (%lu)\n", 164 __func__, (unsigned long)io->chunksize, 165 (unsigned long)io->total); 166 } 167#endif 168 169 return (io->chunksize); 170} 171 172/* 173 * Grow the input buffer to at least len bytes 174 */ 175static inline int 176http_growbuf(struct httpio *io, size_t len) 177{ 178 char *tmp; 179 180 if (io->bufsize >= len) 181 return (0); 182 183 if ((tmp = realloc(io->buf, len)) == NULL) 184 return (-1); 185 io->buf = tmp; 186 io->bufsize = len; 187 return (0); 188} 189 190/* 191 * Fill the input buffer, do chunk decoding on the fly 192 */ 193static int 194http_fillbuf(struct httpio *io, size_t len) 195{ 196 if (io->error) 197 return (-1); 198 if (io->eof) 199 return (0); 200 201 if (io->chunked == 0) { 202 if (http_growbuf(io, len) == -1) 203 return (-1); 204 if ((io->buflen = fetch_read(io->conn, io->buf, len)) == -1) { 205 io->error = 1; 206 return (-1); 207 } 208 io->bufpos = 0; 209 return (io->buflen); 210 } 211 212 if (io->chunksize == 0) { 213 switch (http_new_chunk(io)) { 214 case -1: 215 io->error = 1; 216 return (-1); 217 case 0: 218 io->eof = 1; 219 return (0); 220 } 221 } 222 223 if (len > io->chunksize) 224 len = io->chunksize; 225 if (http_growbuf(io, len) == -1) 226 return (-1); 227 if ((io->buflen = fetch_read(io->conn, io->buf, len)) == -1) { 228 io->error = 1; 229 return (-1); 230 } 231 io->chunksize -= io->buflen; 232 233 if (io->chunksize == 0) { 234 char endl[2]; 235 236 if (fetch_read(io->conn, endl, 2) != 2 || 237 endl[0] != '\r' || endl[1] != '\n') 238 return (-1); 239 } 240 241 io->bufpos = 0; 242 243 return (io->buflen); 244} 245 246/* 247 * Read function 248 */ 249static int 250http_readfn(void *v, char *buf, int len) 251{ 252 struct httpio *io = (struct httpio *)v; 253 int l, pos; 254 255 if (io->error) 256 return (-1); 257 if (io->eof) 258 return (0); 259 260 for (pos = 0; len > 0; pos += l, len -= l) { 261 /* empty buffer */ 262 if (!io->buf || io->bufpos == io->buflen) 263 if (http_fillbuf(io, len) < 1) 264 break; 265 l = io->buflen - io->bufpos; 266 if (len < l) 267 l = len; 268 bcopy(io->buf + io->bufpos, buf + pos, l); 269 io->bufpos += l; 270 } 271 272 if (!pos && io->error) 273 return (-1); 274 return (pos); 275} 276 277/* 278 * Write function 279 */ 280static int 281http_writefn(void *v, const char *buf, int len) 282{ 283 struct httpio *io = (struct httpio *)v; 284 285 return (fetch_write(io->conn, buf, len)); 286} 287 288/* 289 * Close function 290 */ 291static int 292http_closefn(void *v) 293{ 294 struct httpio *io = (struct httpio *)v; 295 int r; 296 297 r = fetch_close(io->conn); 298 if (io->buf) 299 free(io->buf); 300 free(io); 301 return (r); 302} 303 304/* 305 * Wrap a file descriptor up 306 */ 307static FILE * 308http_funopen(conn_t *conn, int chunked) 309{ 310 struct httpio *io; 311 FILE *f; 312 313 if ((io = calloc(1, sizeof(*io))) == NULL) { 314 fetch_syserr(); 315 return (NULL); 316 } 317 io->conn = conn; 318 io->chunked = chunked; 319 f = funopen(io, http_readfn, http_writefn, NULL, http_closefn); 320 if (f == NULL) { 321 fetch_syserr(); 322 free(io); 323 return (NULL); 324 } 325 return (f); 326} 327 328 329/***************************************************************************** 330 * Helper functions for talking to the server and parsing its replies 331 */ 332 333/* Header types */ 334typedef enum { 335 hdr_syserror = -2, 336 hdr_error = -1, 337 hdr_end = 0, 338 hdr_unknown = 1, 339 hdr_content_length, 340 hdr_content_range, 341 hdr_last_modified, 342 hdr_location, 343 hdr_transfer_encoding, 344 hdr_www_authenticate 345} hdr_t; 346 347/* Names of interesting headers */ 348static struct { 349 hdr_t num; 350 const char *name; 351} hdr_names[] = { 352 { hdr_content_length, "Content-Length" }, 353 { hdr_content_range, "Content-Range" }, 354 { hdr_last_modified, "Last-Modified" }, 355 { hdr_location, "Location" }, 356 { hdr_transfer_encoding, "Transfer-Encoding" }, 357 { hdr_www_authenticate, "WWW-Authenticate" }, 358 { hdr_unknown, NULL }, 359}; 360 361/* 362 * Send a formatted line; optionally echo to terminal 363 */ 364static int 365http_cmd(conn_t *conn, const char *fmt, ...) 366{ 367 va_list ap; 368 size_t len; 369 char *msg; 370 int r; 371 372 va_start(ap, fmt); 373 len = vasprintf(&msg, fmt, ap); 374 va_end(ap); 375 376 if (msg == NULL) { 377 errno = ENOMEM; 378 fetch_syserr(); 379 return (-1); 380 } 381 382 r = fetch_putln(conn, msg, len); 383 free(msg); 384 385 if (r == -1) { 386 fetch_syserr(); 387 return (-1); 388 } 389 390 return (0); 391} 392 393/* 394 * Get and parse status line 395 */ 396static int 397http_get_reply(conn_t *conn) 398{ 399 char *p; 400 401 if (fetch_getln(conn) == -1) 402 return (-1); 403 /* 404 * A valid status line looks like "HTTP/m.n xyz reason" where m 405 * and n are the major and minor protocol version numbers and xyz 406 * is the reply code. 407 * Unfortunately, there are servers out there (NCSA 1.5.1, to name 408 * just one) that do not send a version number, so we can't rely 409 * on finding one, but if we do, insist on it being 1.0 or 1.1. 410 * We don't care about the reason phrase. 411 */ 412 if (strncmp(conn->buf, "HTTP", 4) != 0) 413 return (HTTP_PROTOCOL_ERROR); 414 p = conn->buf + 4; 415 if (*p == '/') { 416 if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1')) 417 return (HTTP_PROTOCOL_ERROR); 418 p += 4; 419 } 420 if (*p != ' ' || !isdigit((int)p[1]) || 421 !isdigit((int)p[2]) || !isdigit((int)p[3])) 422 return (HTTP_PROTOCOL_ERROR); 423 424 conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0'); 425 return (conn->err); 426} 427 428/* 429 * Check a header; if the type matches the given string, return a pointer 430 * to the beginning of the value. 431 */ 432static const char * 433http_match(const char *str, const char *hdr) 434{ 435 while (*str && *hdr && tolower(*str++) == tolower(*hdr++)) 436 /* nothing */; 437 if (*str || *hdr != ':') 438 return (NULL); 439 while (*hdr && isspace((int)*++hdr)) 440 /* nothing */; 441 return (hdr); 442} 443 444/* 445 * Get the next header and return the appropriate symbolic code. 446 */ 447static hdr_t 448http_next_header(conn_t *conn, const char **p) 449{ 450 int i; 451 452 if (fetch_getln(conn) == -1) 453 return (hdr_syserror); 454 while (conn->buflen && isspace((int)conn->buf[conn->buflen - 1])) 455 conn->buflen--; 456 conn->buf[conn->buflen] = '\0'; 457 if (conn->buflen == 0) 458 return (hdr_end); 459 /* 460 * We could check for malformed headers but we don't really care. 461 * A valid header starts with a token immediately followed by a 462 * colon; a token is any sequence of non-control, non-whitespace 463 * characters except "()<>@,;:\\\"{}". 464 */ 465 for (i = 0; hdr_names[i].num != hdr_unknown; i++) 466 if ((*p = http_match(hdr_names[i].name, conn->buf)) != NULL) 467 return (hdr_names[i].num); 468 return (hdr_unknown); 469} 470 471/* 472 * Parse a last-modified header 473 */ 474static int 475http_parse_mtime(const char *p, time_t *mtime) 476{ 477 char locale[64], *r; 478 struct tm tm; 479 480 strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale)); 481 setlocale(LC_TIME, "C"); 482 r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm); 483 /* XXX should add support for date-2 and date-3 */ 484 setlocale(LC_TIME, locale); 485 if (r == NULL) 486 return (-1); 487 DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d " 488 "%02d:%02d:%02d]\n", 489 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 490 tm.tm_hour, tm.tm_min, tm.tm_sec)); 491 *mtime = timegm(&tm); 492 return (0); 493} 494 495/* 496 * Parse a content-length header 497 */ 498static int 499http_parse_length(const char *p, off_t *length) 500{ 501 off_t len; 502 503 for (len = 0; *p && isdigit((int)*p); ++p) 504 len = len * 10 + (*p - '0'); 505 if (*p) 506 return (-1); 507 DEBUG(fprintf(stderr, "content length: [%lld]\n", 508 (long long)len)); 509 *length = len; 510 return (0); 511} 512 513/* 514 * Parse a content-range header 515 */ 516static int 517http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size) 518{ 519 off_t first, last, len; 520 521 if (strncasecmp(p, "bytes ", 6) != 0) 522 return (-1); 523 p += 6; 524 if (*p == '*') { 525 first = last = -1; 526 ++p; 527 } else { 528 for (first = 0; *p && isdigit((int)*p); ++p) 529 first = first * 10 + *p - '0'; 530 if (*p != '-') 531 return (-1); 532 for (last = 0, ++p; *p && isdigit((int)*p); ++p) 533 last = last * 10 + *p - '0'; 534 } 535 if (first > last || *p != '/') 536 return (-1); 537 for (len = 0, ++p; *p && isdigit((int)*p); ++p) 538 len = len * 10 + *p - '0'; 539 if (*p || len < last - first + 1) 540 return (-1); 541 if (first == -1) { 542 DEBUG(fprintf(stderr, "content range: [*/%lld]\n", 543 (long long)len)); 544 *length = 0; 545 } else { 546 DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n", 547 (long long)first, (long long)last, (long long)len)); 548 *length = last - first + 1; 549 } 550 *offset = first; 551 *size = len; 552 return (0); 553} 554 555 556/***************************************************************************** 557 * Helper functions for authorization 558 */ 559 560/* 561 * Base64 encoding 562 */ 563static char * 564http_base64(const char *src) 565{ 566 static const char base64[] = 567 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 568 "abcdefghijklmnopqrstuvwxyz" 569 "0123456789+/"; 570 char *str, *dst; 571 size_t l; 572 int t, r; 573 574 l = strlen(src); 575 if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL) 576 return (NULL); 577 dst = str; 578 r = 0; 579 580 while (l >= 3) { 581 t = (src[0] << 16) | (src[1] << 8) | src[2]; 582 dst[0] = base64[(t >> 18) & 0x3f]; 583 dst[1] = base64[(t >> 12) & 0x3f]; 584 dst[2] = base64[(t >> 6) & 0x3f]; 585 dst[3] = base64[(t >> 0) & 0x3f]; 586 src += 3; l -= 3; 587 dst += 4; r += 4; 588 } 589 590 switch (l) { 591 case 2: 592 t = (src[0] << 16) | (src[1] << 8); 593 dst[0] = base64[(t >> 18) & 0x3f]; 594 dst[1] = base64[(t >> 12) & 0x3f]; 595 dst[2] = base64[(t >> 6) & 0x3f]; 596 dst[3] = '='; 597 dst += 4; 598 r += 4; 599 break; 600 case 1: 601 t = src[0] << 16; 602 dst[0] = base64[(t >> 18) & 0x3f]; 603 dst[1] = base64[(t >> 12) & 0x3f]; 604 dst[2] = dst[3] = '='; 605 dst += 4; 606 r += 4; 607 break; 608 case 0: 609 break; 610 } 611 612 *dst = 0; 613 return (str); 614} 615 616/* 617 * Encode username and password 618 */ 619static int 620http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd) 621{ 622 char *upw, *auth; 623 int r; 624 625 DEBUG(fprintf(stderr, "usr: [%s]\n", usr)); 626 DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd)); 627 if (asprintf(&upw, "%s:%s", usr, pwd) == -1) 628 return (-1); 629 auth = http_base64(upw); 630 free(upw); 631 if (auth == NULL) 632 return (-1); 633 r = http_cmd(conn, "%s: Basic %s", hdr, auth); 634 free(auth); 635 return (r); 636} 637 638/* 639 * Send an authorization header 640 */ 641static int 642http_authorize(conn_t *conn, const char *hdr, const char *p) 643{ 644 /* basic authorization */ 645 if (strncasecmp(p, "basic:", 6) == 0) { 646 char *user, *pwd, *str; 647 int r; 648 649 /* skip realm */ 650 for (p += 6; *p && *p != ':'; ++p) 651 /* nothing */ ; 652 if (!*p || strchr(++p, ':') == NULL) 653 return (-1); 654 if ((str = strdup(p)) == NULL) 655 return (-1); /* XXX */ 656 user = str; 657 pwd = strchr(str, ':'); 658 *pwd++ = '\0'; 659 r = http_basic_auth(conn, hdr, user, pwd); 660 free(str); 661 return (r); 662 } 663 return (-1); 664} 665 666 667/***************************************************************************** 668 * Helper functions for connecting to a server or proxy 669 */ 670 671/* 672 * Connect to the correct HTTP server or proxy. 673 */ 674static conn_t * 675http_connect(struct url *URL, struct url *purl, const char *flags) 676{ 677 conn_t *conn; 678 int verbose; 679 int af, val; 680 681#ifdef INET6 682 af = AF_UNSPEC; 683#else 684 af = AF_INET; 685#endif 686 687 verbose = CHECK_FLAG('v'); 688 if (CHECK_FLAG('4')) 689 af = AF_INET; 690#ifdef INET6 691 else if (CHECK_FLAG('6')) 692 af = AF_INET6; 693#endif 694 695 if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) { 696 URL = purl; 697 } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) { 698 /* can't talk http to an ftp server */ 699 /* XXX should set an error code */ 700 return (NULL); 701 } 702 703 if ((conn = fetch_connect(URL->host, URL->port, af, verbose)) == NULL) 704 /* fetch_connect() has already set an error code */ 705 return (NULL); 706 if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 && 707 fetch_ssl(conn, verbose) == -1) { 708 fetch_close(conn); 709 /* grrr */ 710 errno = EAUTH; 711 fetch_syserr(); 712 return (NULL); 713 } 714 715 val = 1; 716 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val)); 717 718 return (conn); 719} 720 721static struct url * 722http_get_proxy(const char *flags) 723{ 724 struct url *purl; 725 char *p; 726 727 if (flags != NULL && strchr(flags, 'd') != NULL) 728 return (NULL); 729 if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 730 *p && (purl = fetchParseURL(p))) { 731 if (!*purl->scheme) 732 strcpy(purl->scheme, SCHEME_HTTP); 733 if (!purl->port) 734 purl->port = fetch_default_proxy_port(purl->scheme); 735 if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 736 return (purl); 737 fetchFreeURL(purl); 738 } 739 return (NULL); 740} 741 742static void 743http_print_html(FILE *out, FILE *in) 744{ 745 size_t len; 746 char *line, *p, *q; 747 int comment, tag; 748 749 comment = tag = 0; 750 while ((line = fgetln(in, &len)) != NULL) { 751 while (len && isspace((int)line[len - 1])) 752 --len; 753 for (p = q = line; q < line + len; ++q) { 754 if (comment && *q == '-') { 755 if (q + 2 < line + len && 756 strcmp(q, "-->") == 0) { 757 tag = comment = 0; 758 q += 2; 759 } 760 } else if (tag && !comment && *q == '>') { 761 p = q + 1; 762 tag = 0; 763 } else if (!tag && *q == '<') { 764 if (q > p) 765 fwrite(p, q - p, 1, out); 766 tag = 1; 767 if (q + 3 < line + len && 768 strcmp(q, "<!--") == 0) { 769 comment = 1; 770 q += 3; 771 } 772 } 773 } 774 if (!tag && q > p) 775 fwrite(p, q - p, 1, out); 776 fputc('\n', out); 777 } 778} 779 780 781/***************************************************************************** 782 * Core 783 */ 784 785/* 786 * Send a request and process the reply 787 * 788 * XXX This function is way too long, the do..while loop should be split 789 * XXX off into a separate function. 790 */ 791FILE * 792http_request(struct url *URL, const char *op, struct url_stat *us, 793 struct url *purl, const char *flags) 794{ 795 conn_t *conn; 796 struct url *url, *new; 797 int chunked, direct, need_auth, noredirect, verbose; 798 int e, i, n, val; 799 off_t offset, clength, length, size; 800 time_t mtime; 801 const char *p; 802 FILE *f; 803 hdr_t h; 804 char hbuf[MAXHOSTNAMELEN + 7], *host; 805 806 direct = CHECK_FLAG('d'); 807 noredirect = CHECK_FLAG('A'); 808 verbose = CHECK_FLAG('v'); 809 810 if (direct && purl) { 811 fetchFreeURL(purl); 812 purl = NULL; 813 } 814 815 /* try the provided URL first */ 816 url = URL; 817 818 /* if the A flag is set, we only get one try */ 819 n = noredirect ? 1 : MAX_REDIRECT; 820 i = 0; 821 822 e = HTTP_PROTOCOL_ERROR; 823 need_auth = 0; 824 do { 825 new = NULL; 826 chunked = 0; 827 offset = 0; 828 clength = -1; 829 length = -1; 830 size = -1; 831 mtime = 0; 832 833 /* check port */ 834 if (!url->port) 835 url->port = fetch_default_port(url->scheme); 836 837 /* were we redirected to an FTP URL? */ 838 if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) { 839 if (strcmp(op, "GET") == 0) 840 return (ftp_request(url, "RETR", us, purl, flags)); 841 else if (strcmp(op, "HEAD") == 0) 842 return (ftp_request(url, "STAT", us, purl, flags)); 843 } 844 845 /* connect to server or proxy */ 846 if ((conn = http_connect(url, purl, flags)) == NULL) 847 goto ouch; 848 849 host = url->host; 850#ifdef INET6 851 if (strchr(url->host, ':')) { 852 snprintf(hbuf, sizeof(hbuf), "[%s]", url->host); 853 host = hbuf; 854 } 855#endif 856 if (url->port != fetch_default_port(url->scheme)) { 857 if (host != hbuf) { 858 strcpy(hbuf, host); 859 host = hbuf; 860 } 861 snprintf(hbuf + strlen(hbuf), 862 sizeof(hbuf) - strlen(hbuf), ":%d", url->port); 863 } 864 865 /* send request */ 866 if (verbose) 867 fetch_info("requesting %s://%s%s", 868 url->scheme, host, url->doc); 869 if (purl) { 870 http_cmd(conn, "%s %s://%s%s HTTP/1.1", 871 op, url->scheme, host, url->doc); 872 } else { 873 http_cmd(conn, "%s %s HTTP/1.1", 874 op, url->doc); 875 } 876 877 /* virtual host */ 878 http_cmd(conn, "Host: %s", host); 879 880 /* proxy authorization */ 881 if (purl) { 882 if (*purl->user || *purl->pwd) 883 http_basic_auth(conn, "Proxy-Authorization", 884 purl->user, purl->pwd); 885 else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0') 886 http_authorize(conn, "Proxy-Authorization", p); 887 } 888 889 /* server authorization */ 890 if (need_auth || *url->user || *url->pwd) { 891 if (*url->user || *url->pwd) 892 http_basic_auth(conn, "Authorization", url->user, url->pwd); 893 else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0') 894 http_authorize(conn, "Authorization", p); 895 else if (fetchAuthMethod && fetchAuthMethod(url) == 0) { 896 http_basic_auth(conn, "Authorization", url->user, url->pwd); 897 } else { 898 http_seterr(HTTP_NEED_AUTH); 899 goto ouch; 900 } 901 } 902 903 /* other headers */ 904 if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') { 905 if (strcasecmp(p, "auto") == 0) 906 http_cmd(conn, "Referer: %s://%s%s", 907 url->scheme, host, url->doc); 908 else 909 http_cmd(conn, "Referer: %s", p); 910 } 911 if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0') 912 http_cmd(conn, "User-Agent: %s", p); 913 else 914 http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname()); 915 if (url->offset > 0) 916 http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset); 917 http_cmd(conn, "Connection: close"); 918 http_cmd(conn, ""); 919 920 /* 921 * Force the queued request to be dispatched. Normally, one 922 * would do this with shutdown(2) but squid proxies can be 923 * configured to disallow such half-closed connections. To 924 * be compatible with such configurations, fiddle with socket 925 * options to force the pending data to be written. 926 */ 927 val = 0; 928 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, 929 sizeof(val)); 930 val = 1; 931 setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val, 932 sizeof(val)); 933 934 /* get reply */ 935 switch (http_get_reply(conn)) { 936 case HTTP_OK: 937 case HTTP_PARTIAL: 938 /* fine */ 939 break; 940 case HTTP_MOVED_PERM: 941 case HTTP_MOVED_TEMP: 942 case HTTP_SEE_OTHER: 943 /* 944 * Not so fine, but we still have to read the 945 * headers to get the new location. 946 */ 947 break; 948 case HTTP_NEED_AUTH: 949 if (need_auth) { 950 /* 951 * We already sent out authorization code, 952 * so there's nothing more we can do. 953 */ 954 http_seterr(conn->err); 955 goto ouch; 956 } 957 /* try again, but send the password this time */ 958 if (verbose) 959 fetch_info("server requires authorization"); 960 break; 961 case HTTP_NEED_PROXY_AUTH: 962 /* 963 * If we're talking to a proxy, we already sent 964 * our proxy authorization code, so there's 965 * nothing more we can do. 966 */ 967 http_seterr(conn->err); 968 goto ouch; 969 case HTTP_BAD_RANGE: 970 /* 971 * This can happen if we ask for 0 bytes because 972 * we already have the whole file. Consider this 973 * a success for now, and check sizes later. 974 */ 975 break; 976 case HTTP_PROTOCOL_ERROR: 977 /* fall through */ 978 case -1: 979 fetch_syserr(); 980 goto ouch; 981 default: 982 http_seterr(conn->err); 983 if (!verbose) 984 goto ouch; 985 /* fall through so we can get the full error message */ 986 } 987 988 /* get headers */ 989 do { 990 switch ((h = http_next_header(conn, &p))) { 991 case hdr_syserror: 992 fetch_syserr(); 993 goto ouch; 994 case hdr_error: 995 http_seterr(HTTP_PROTOCOL_ERROR); 996 goto ouch; 997 case hdr_content_length: 998 http_parse_length(p, &clength); 999 break; 1000 case hdr_content_range: 1001 http_parse_range(p, &offset, &length, &size); 1002 break; 1003 case hdr_last_modified: 1004 http_parse_mtime(p, &mtime); 1005 break; 1006 case hdr_location: 1007 if (!HTTP_REDIRECT(conn->err)) 1008 break; 1009 if (new) 1010 free(new); 1011 if (verbose) 1012 fetch_info("%d redirect to %s", conn->err, p); 1013 if (*p == '/') 1014 /* absolute path */ 1015 new = fetchMakeURL(url->scheme, url->host, url->port, p, 1016 url->user, url->pwd); 1017 else 1018 new = fetchParseURL(p); 1019 if (new == NULL) { 1020 /* XXX should set an error code */ 1021 DEBUG(fprintf(stderr, "failed to parse new URL\n")); 1022 goto ouch; 1023 } 1024 if (!*new->user && !*new->pwd) { 1025 strcpy(new->user, url->user); 1026 strcpy(new->pwd, url->pwd); 1027 } 1028 new->offset = url->offset; 1029 new->length = url->length; 1030 break; 1031 case hdr_transfer_encoding: 1032 /* XXX weak test*/ 1033 chunked = (strcasecmp(p, "chunked") == 0); 1034 break; 1035 case hdr_www_authenticate: 1036 if (conn->err != HTTP_NEED_AUTH) 1037 break; 1038 /* if we were smarter, we'd check the method and realm */ 1039 break; 1040 case hdr_end: 1041 /* fall through */ 1042 case hdr_unknown: 1043 /* ignore */ 1044 break; 1045 } 1046 } while (h > hdr_end); 1047 1048 /* we need to provide authentication */ 1049 if (conn->err == HTTP_NEED_AUTH) { 1050 e = conn->err; 1051 need_auth = 1; 1052 fetch_close(conn); 1053 conn = NULL; 1054 continue; 1055 } 1056 1057 /* requested range not satisfiable */ 1058 if (conn->err == HTTP_BAD_RANGE) { 1059 if (url->offset == size && url->length == 0) { 1060 /* asked for 0 bytes; fake it */ 1061 offset = url->offset; 1062 conn->err = HTTP_OK; 1063 break; 1064 } else { 1065 http_seterr(conn->err); 1066 goto ouch; 1067 } 1068 } 1069 1070 /* we have a hit or an error */ 1071 if (conn->err == HTTP_OK || conn->err == HTTP_PARTIAL || HTTP_ERROR(conn->err)) 1072 break; 1073 1074 /* all other cases: we got a redirect */ 1075 e = conn->err; 1076 need_auth = 0; 1077 fetch_close(conn); 1078 conn = NULL; 1079 if (!new) { 1080 DEBUG(fprintf(stderr, "redirect with no new location\n")); 1081 break; 1082 } 1083 if (url != URL) 1084 fetchFreeURL(url); 1085 url = new; 1086 } while (++i < n); 1087 1088 /* we failed, or ran out of retries */ 1089 if (conn == NULL) { 1090 http_seterr(e); 1091 goto ouch; 1092 } 1093 1094 DEBUG(fprintf(stderr, "offset %lld, length %lld," 1095 " size %lld, clength %lld\n", 1096 (long long)offset, (long long)length, 1097 (long long)size, (long long)clength)); 1098 1099 /* check for inconsistencies */ 1100 if (clength != -1 && length != -1 && clength != length) { 1101 http_seterr(HTTP_PROTOCOL_ERROR); 1102 goto ouch; 1103 } 1104 if (clength == -1) 1105 clength = length; 1106 if (clength != -1) 1107 length = offset + clength; 1108 if (length != -1 && size != -1 && length != size) { 1109 http_seterr(HTTP_PROTOCOL_ERROR); 1110 goto ouch; 1111 } 1112 if (size == -1) 1113 size = length; 1114 1115 /* fill in stats */ 1116 if (us) { 1117 us->size = size; 1118 us->atime = us->mtime = mtime; 1119 } 1120 1121 /* too far? */ 1122 if (URL->offset > 0 && offset > URL->offset) { 1123 http_seterr(HTTP_PROTOCOL_ERROR); 1124 goto ouch; 1125 } 1126 1127 /* report back real offset and size */ 1128 URL->offset = offset; 1129 URL->length = clength; 1130 1131 /* wrap it up in a FILE */ 1132 if ((f = http_funopen(conn, chunked)) == NULL) { 1133 fetch_syserr(); 1134 goto ouch; 1135 } 1136 1137 if (url != URL) 1138 fetchFreeURL(url); 1139 if (purl) 1140 fetchFreeURL(purl); 1141 1142 if (HTTP_ERROR(conn->err)) { 1143 http_print_html(stderr, f); 1144 fclose(f); 1145 f = NULL; 1146 } 1147 1148 return (f); 1149 1150ouch: 1151 if (url != URL) 1152 fetchFreeURL(url); 1153 if (purl) 1154 fetchFreeURL(purl); 1155 if (conn != NULL) 1156 fetch_close(conn); 1157 return (NULL); 1158} 1159 1160 1161/***************************************************************************** 1162 * Entry points 1163 */ 1164 1165/* 1166 * Retrieve and stat a file by HTTP 1167 */ 1168FILE * 1169fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags) 1170{ 1171 return (http_request(URL, "GET", us, http_get_proxy(flags), flags)); 1172} 1173 1174/* 1175 * Retrieve a file by HTTP 1176 */ 1177FILE * 1178fetchGetHTTP(struct url *URL, const char *flags) 1179{ 1180 return (fetchXGetHTTP(URL, NULL, flags)); 1181} 1182 1183/* 1184 * Store a file by HTTP 1185 */ 1186FILE * 1187fetchPutHTTP(struct url *URL __unused, const char *flags __unused) 1188{ 1189 warnx("fetchPutHTTP(): not implemented"); 1190 return (NULL); 1191} 1192 1193/* 1194 * Get an HTTP document's metadata 1195 */ 1196int 1197fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags) 1198{ 1199 FILE *f; 1200 1201 f = http_request(URL, "HEAD", us, http_get_proxy(flags), flags); 1202 if (f == NULL) 1203 return (-1); 1204 fclose(f); 1205 return (0); 1206} 1207 1208/* 1209 * List a directory 1210 */ 1211struct url_ent * 1212fetchListHTTP(struct url *url __unused, const char *flags __unused) 1213{ 1214 warnx("fetchListHTTP(): not implemented"); 1215 return (NULL); 1216} 1217