1 /* $NetBSD: http.c,v 1.1.1.7 2010/01/30 21:26:14 joerg Exp $ */ 2 /*- 3 * Copyright (c) 2000-2004 Dag-Erling Co�dan Sm�rgrav 4 * Copyright (c) 2003 Thomas Klausner <wiz@NetBSD.org> 5 * Copyright (c) 2008, 2009 Joerg Sonnenberger <joerg@NetBSD.org> 6 * All rights reserved. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 11 * 1. Redistributions of source code must retain the above copyright 12 * notice, this list of conditions and the following disclaimer 13 * in this position and unchanged. 14 * 2. Redistributions in binary form must reproduce the above copyright 15 * notice, this list of conditions and the following disclaimer in the 16 * documentation and/or other materials provided with the distribution. 17 * 3. The name of the author may not be used to endorse or promote products 18 * derived from this software without specific prior written permission. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 * 31 * $FreeBSD: http.c,v 1.83 2008/02/06 11:39:55 des Exp $ 32 */ 33 34 /* 35 * The following copyright applies to the base64 code: 36 * 37 *- 38 * Copyright 1997 Massachusetts Institute of Technology 39 * 40 * Permission to use, copy, modify, and distribute this software and 41 * its documentation for any purpose and without fee is hereby 42 * granted, provided that both the above copyright notice and this 43 * permission notice appear in all copies, that both the above 44 * copyright notice and this permission notice appear in all 45 * supporting documentation, and that the name of M.I.T. not be used 46 * in advertising or publicity pertaining to distribution of the 47 * software without specific, written prior permission. M.I.T. makes 48 * no representations about the suitability of this software for any 49 * purpose. It is provided "as is" without express or implied 50 * warranty. 51 * 52 * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS 53 * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, 54 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 55 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT 56 * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 57 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 58 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 59 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 60 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 61 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 62 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 63 * SUCH DAMAGE. 64 */ 65 66 #if defined(__linux__) || defined(__MINT__) 67 /* Keep this down to Linux or MiNT, it can create surprises elsewhere. */ 68 #define _GNU_SOURCE 69 #endif 70 71 /* Needed for gmtime_r on Interix */ 72 #define _REENTRANT 73 74 #if HAVE_CONFIG_H 75 #include "config.h" 76 #endif 77 #ifndef NETBSD 78 #include <nbcompat.h> 79 #endif 80 81 #include <sys/types.h> 82 #include <sys/socket.h> 83 84 #include <ctype.h> 85 #include <errno.h> 86 #include <locale.h> 87 #include <stdarg.h> 88 #ifndef NETBSD 89 #include <nbcompat/stdio.h> 90 #else 91 #include <stdio.h> 92 #endif 93 #include <stdlib.h> 94 #include <string.h> 95 #include <time.h> 96 #include <unistd.h> 97 98 #include <netinet/in.h> 99 #include <netinet/tcp.h> 100 101 #ifndef NETBSD 102 #include <nbcompat/netdb.h> 103 #else 104 #include <netdb.h> 105 #endif 106 107 #include <arpa/inet.h> 108 109 #include "fetch.h" 110 #include "common.h" 111 #include "httperr.h" 112 113 /* Maximum number of redirects to follow */ 114 #define MAX_REDIRECT 5 115 116 /* Symbolic names for reply codes we care about */ 117 #define HTTP_OK 200 118 #define HTTP_PARTIAL 206 119 #define HTTP_MOVED_PERM 301 120 #define HTTP_MOVED_TEMP 302 121 #define HTTP_SEE_OTHER 303 122 #define HTTP_NOT_MODIFIED 304 123 #define HTTP_TEMP_REDIRECT 307 124 #define HTTP_NEED_AUTH 401 125 #define HTTP_NEED_PROXY_AUTH 407 126 #define HTTP_BAD_RANGE 416 127 #define HTTP_PROTOCOL_ERROR 999 128 129 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \ 130 || (xyz) == HTTP_MOVED_TEMP \ 131 || (xyz) == HTTP_TEMP_REDIRECT \ 132 || (xyz) == HTTP_SEE_OTHER) 133 134 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599) 135 136 137 /***************************************************************************** 138 * I/O functions for decoding chunked streams 139 */ 140 141 struct httpio 142 { 143 conn_t *conn; /* connection */ 144 int chunked; /* chunked mode */ 145 int keep_alive; /* keep-alive mode */ 146 char *buf; /* chunk buffer */ 147 size_t bufsize; /* size of chunk buffer */ 148 ssize_t buflen; /* amount of data currently in buffer */ 149 int bufpos; /* current read offset in buffer */ 150 int eof; /* end-of-file flag */ 151 int error; /* error flag */ 152 size_t chunksize; /* remaining size of current chunk */ 153 off_t contentlength; /* remaining size of the content */ 154 }; 155 156 /* 157 * Get next chunk header 158 */ 159 static int 160 http_new_chunk(struct httpio *io) 161 { 162 char *p; 163 164 if (fetch_getln(io->conn) == -1) 165 return (-1); 166 167 if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf)) 168 return (-1); 169 170 for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) { 171 if (*p == ';') 172 break; 173 if (!isxdigit((unsigned char)*p)) 174 return (-1); 175 if (isdigit((unsigned char)*p)) { 176 io->chunksize = io->chunksize * 16 + 177 *p - '0'; 178 } else { 179 io->chunksize = io->chunksize * 16 + 180 10 + tolower((unsigned char)*p) - 'a'; 181 } 182 } 183 184 return (io->chunksize); 185 } 186 187 /* 188 * Grow the input buffer to at least len bytes 189 */ 190 static int 191 http_growbuf(struct httpio *io, size_t len) 192 { 193 char *tmp; 194 195 if (io->bufsize >= len) 196 return (0); 197 198 if ((tmp = realloc(io->buf, len)) == NULL) 199 return (-1); 200 io->buf = tmp; 201 io->bufsize = len; 202 return (0); 203 } 204 205 /* 206 * Fill the input buffer, do chunk decoding on the fly 207 */ 208 static int 209 http_fillbuf(struct httpio *io, size_t len) 210 { 211 if (io->error) 212 return (-1); 213 if (io->eof) 214 return (0); 215 216 if (io->contentlength >= 0 && (off_t)len > io->contentlength) 217 len = io->contentlength; 218 219 if (io->chunked == 0) { 220 if (http_growbuf(io, len) == -1) 221 return (-1); 222 if ((io->buflen = fetch_read(io->conn, io->buf, len)) == -1) { 223 io->error = 1; 224 return (-1); 225 } 226 if (io->contentlength) 227 io->contentlength -= io->buflen; 228 io->bufpos = 0; 229 return (io->buflen); 230 } 231 232 if (io->chunksize == 0) { 233 switch (http_new_chunk(io)) { 234 case -1: 235 io->error = 1; 236 return (-1); 237 case 0: 238 io->eof = 1; 239 if (fetch_getln(io->conn) == -1) 240 return (-1); 241 return (0); 242 } 243 } 244 245 if (len > io->chunksize) 246 len = io->chunksize; 247 if (http_growbuf(io, len) == -1) 248 return (-1); 249 if ((io->buflen = fetch_read(io->conn, io->buf, len)) == -1) { 250 io->error = 1; 251 return (-1); 252 } 253 io->chunksize -= io->buflen; 254 if (io->contentlength >= 0) 255 io->contentlength -= io->buflen; 256 257 if (io->chunksize == 0) { 258 char endl[2]; 259 ssize_t len2; 260 261 len2 = fetch_read(io->conn, endl, 2); 262 if (len2 == 1 && fetch_read(io->conn, endl + 1, 1) != 1) 263 return (-1); 264 if (len2 == -1 || endl[0] != '\r' || endl[1] != '\n') 265 return (-1); 266 } 267 268 io->bufpos = 0; 269 270 return (io->buflen); 271 } 272 273 /* 274 * Read function 275 */ 276 static ssize_t 277 http_readfn(void *v, void *buf, size_t len) 278 { 279 struct httpio *io = (struct httpio *)v; 280 size_t l, pos; 281 282 if (io->error) 283 return (-1); 284 if (io->eof) 285 return (0); 286 287 for (pos = 0; len > 0; pos += l, len -= l) { 288 /* empty buffer */ 289 if (!io->buf || io->bufpos == io->buflen) 290 if (http_fillbuf(io, len) < 1) 291 break; 292 l = io->buflen - io->bufpos; 293 if (len < l) 294 l = len; 295 memcpy((char *)buf + pos, io->buf + io->bufpos, l); 296 io->bufpos += l; 297 } 298 299 if (!pos && io->error) 300 return (-1); 301 return (pos); 302 } 303 304 /* 305 * Write function 306 */ 307 static ssize_t 308 http_writefn(void *v, const void *buf, size_t len) 309 { 310 struct httpio *io = (struct httpio *)v; 311 312 return (fetch_write(io->conn, buf, len)); 313 } 314 315 /* 316 * Close function 317 */ 318 static void 319 http_closefn(void *v) 320 { 321 struct httpio *io = (struct httpio *)v; 322 323 if (io->keep_alive) { 324 int val; 325 326 val = 0; 327 setsockopt(io->conn->sd, IPPROTO_TCP, TCP_NODELAY, &val, 328 sizeof(val)); 329 fetch_cache_put(io->conn, fetch_close); 330 #ifdef TCP_NOPUSH 331 val = 1; 332 setsockopt(io->conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, 333 sizeof(val)); 334 #endif 335 } else { 336 fetch_close(io->conn); 337 } 338 339 free(io->buf); 340 free(io); 341 } 342 343 /* 344 * Wrap a file descriptor up 345 */ 346 static fetchIO * 347 http_funopen(conn_t *conn, int chunked, int keep_alive, off_t clength) 348 { 349 struct httpio *io; 350 fetchIO *f; 351 352 if ((io = calloc(1, sizeof(*io))) == NULL) { 353 fetch_syserr(); 354 return (NULL); 355 } 356 io->conn = conn; 357 io->chunked = chunked; 358 io->contentlength = clength; 359 io->keep_alive = keep_alive; 360 f = fetchIO_unopen(io, http_readfn, http_writefn, http_closefn); 361 if (f == NULL) { 362 fetch_syserr(); 363 free(io); 364 return (NULL); 365 } 366 return (f); 367 } 368 369 370 /***************************************************************************** 371 * Helper functions for talking to the server and parsing its replies 372 */ 373 374 /* Header types */ 375 typedef enum { 376 hdr_syserror = -2, 377 hdr_error = -1, 378 hdr_end = 0, 379 hdr_unknown = 1, 380 hdr_connection, 381 hdr_content_length, 382 hdr_content_range, 383 hdr_last_modified, 384 hdr_location, 385 hdr_transfer_encoding, 386 hdr_www_authenticate 387 } hdr_t; 388 389 /* Names of interesting headers */ 390 static struct { 391 hdr_t num; 392 const char *name; 393 } hdr_names[] = { 394 { hdr_connection, "Connection" }, 395 { hdr_content_length, "Content-Length" }, 396 { hdr_content_range, "Content-Range" }, 397 { hdr_last_modified, "Last-Modified" }, 398 { hdr_location, "Location" }, 399 { hdr_transfer_encoding, "Transfer-Encoding" }, 400 { hdr_www_authenticate, "WWW-Authenticate" }, 401 { hdr_unknown, NULL }, 402 }; 403 404 /* 405 * Send a formatted line; optionally echo to terminal 406 */ 407 static int 408 http_cmd(conn_t *conn, const char *fmt, ...) 409 { 410 va_list ap; 411 size_t len; 412 char *msg; 413 int r; 414 415 va_start(ap, fmt); 416 len = vasprintf(&msg, fmt, ap); 417 va_end(ap); 418 419 if (msg == NULL) { 420 errno = ENOMEM; 421 fetch_syserr(); 422 return (-1); 423 } 424 425 r = fetch_write(conn, msg, len); 426 free(msg); 427 428 if (r == -1) { 429 fetch_syserr(); 430 return (-1); 431 } 432 433 return (0); 434 } 435 436 /* 437 * Get and parse status line 438 */ 439 static int 440 http_get_reply(conn_t *conn) 441 { 442 char *p; 443 444 if (fetch_getln(conn) == -1) 445 return (-1); 446 /* 447 * A valid status line looks like "HTTP/m.n xyz reason" where m 448 * and n are the major and minor protocol version numbers and xyz 449 * is the reply code. 450 * Unfortunately, there are servers out there (NCSA 1.5.1, to name 451 * just one) that do not send a version number, so we can't rely 452 * on finding one, but if we do, insist on it being 1.0 or 1.1. 453 * We don't care about the reason phrase. 454 */ 455 if (strncmp(conn->buf, "HTTP", 4) != 0) 456 return (HTTP_PROTOCOL_ERROR); 457 p = conn->buf + 4; 458 if (*p == '/') { 459 if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1')) 460 return (HTTP_PROTOCOL_ERROR); 461 p += 4; 462 } 463 if (*p != ' ' || 464 !isdigit((unsigned char)p[1]) || 465 !isdigit((unsigned char)p[2]) || 466 !isdigit((unsigned char)p[3])) 467 return (HTTP_PROTOCOL_ERROR); 468 469 conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0'); 470 return (conn->err); 471 } 472 473 /* 474 * Check a header; if the type matches the given string, return a pointer 475 * to the beginning of the value. 476 */ 477 static const char * 478 http_match(const char *str, const char *hdr) 479 { 480 while (*str && *hdr && 481 tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++)) 482 /* nothing */; 483 if (*str || *hdr != ':') 484 return (NULL); 485 while (*hdr && isspace((unsigned char)*++hdr)) 486 /* nothing */; 487 return (hdr); 488 } 489 490 /* 491 * Get the next header and return the appropriate symbolic code. 492 */ 493 static hdr_t 494 http_next_header(conn_t *conn, const char **p) 495 { 496 int i; 497 498 if (fetch_getln(conn) == -1) 499 return (hdr_syserror); 500 while (conn->buflen && isspace((unsigned char)conn->buf[conn->buflen - 1])) 501 conn->buflen--; 502 conn->buf[conn->buflen] = '\0'; 503 if (conn->buflen == 0) 504 return (hdr_end); 505 /* 506 * We could check for malformed headers but we don't really care. 507 * A valid header starts with a token immediately followed by a 508 * colon; a token is any sequence of non-control, non-whitespace 509 * characters except "()<>@,;:\\\"{}". 510 */ 511 for (i = 0; hdr_names[i].num != hdr_unknown; i++) 512 if ((*p = http_match(hdr_names[i].name, conn->buf)) != NULL) 513 return (hdr_names[i].num); 514 return (hdr_unknown); 515 } 516 517 /* 518 * Parse a last-modified header 519 */ 520 static int 521 http_parse_mtime(const char *p, time_t *mtime) 522 { 523 char locale[64], *r; 524 struct tm tm; 525 526 strncpy(locale, setlocale(LC_TIME, NULL), sizeof(locale)); 527 setlocale(LC_TIME, "C"); 528 r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm); 529 /* XXX should add support for date-2 and date-3 */ 530 setlocale(LC_TIME, locale); 531 if (r == NULL) 532 return (-1); 533 *mtime = timegm(&tm); 534 return (0); 535 } 536 537 /* 538 * Parse a content-length header 539 */ 540 static int 541 http_parse_length(const char *p, off_t *length) 542 { 543 off_t len; 544 545 for (len = 0; *p && isdigit((unsigned char)*p); ++p) 546 len = len * 10 + (*p - '0'); 547 if (*p) 548 return (-1); 549 *length = len; 550 return (0); 551 } 552 553 /* 554 * Parse a content-range header 555 */ 556 static int 557 http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size) 558 { 559 off_t first, last, len; 560 561 if (strncasecmp(p, "bytes ", 6) != 0) 562 return (-1); 563 p += 6; 564 if (*p == '*') { 565 first = last = -1; 566 ++p; 567 } else { 568 for (first = 0; *p && isdigit((unsigned char)*p); ++p) 569 first = first * 10 + *p - '0'; 570 if (*p != '-') 571 return (-1); 572 for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p) 573 last = last * 10 + *p - '0'; 574 } 575 if (first > last || *p != '/') 576 return (-1); 577 for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p) 578 len = len * 10 + *p - '0'; 579 if (*p || len < last - first + 1) 580 return (-1); 581 if (first == -1) 582 *length = 0; 583 else 584 *length = last - first + 1; 585 *offset = first; 586 *size = len; 587 return (0); 588 } 589 590 591 /***************************************************************************** 592 * Helper functions for authorization 593 */ 594 595 /* 596 * Base64 encoding 597 */ 598 static char * 599 http_base64(const char *src) 600 { 601 static const char base64[] = 602 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 603 "abcdefghijklmnopqrstuvwxyz" 604 "0123456789+/"; 605 char *str, *dst; 606 size_t l; 607 int t, r; 608 609 l = strlen(src); 610 if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL) 611 return (NULL); 612 dst = str; 613 r = 0; 614 615 while (l >= 3) { 616 t = (src[0] << 16) | (src[1] << 8) | src[2]; 617 dst[0] = base64[(t >> 18) & 0x3f]; 618 dst[1] = base64[(t >> 12) & 0x3f]; 619 dst[2] = base64[(t >> 6) & 0x3f]; 620 dst[3] = base64[(t >> 0) & 0x3f]; 621 src += 3; l -= 3; 622 dst += 4; r += 4; 623 } 624 625 switch (l) { 626 case 2: 627 t = (src[0] << 16) | (src[1] << 8); 628 dst[0] = base64[(t >> 18) & 0x3f]; 629 dst[1] = base64[(t >> 12) & 0x3f]; 630 dst[2] = base64[(t >> 6) & 0x3f]; 631 dst[3] = '='; 632 dst += 4; 633 r += 4; 634 break; 635 case 1: 636 t = src[0] << 16; 637 dst[0] = base64[(t >> 18) & 0x3f]; 638 dst[1] = base64[(t >> 12) & 0x3f]; 639 dst[2] = dst[3] = '='; 640 dst += 4; 641 r += 4; 642 break; 643 case 0: 644 break; 645 } 646 647 *dst = 0; 648 return (str); 649 } 650 651 /* 652 * Encode username and password 653 */ 654 static int 655 http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd) 656 { 657 char *upw, *auth; 658 int r; 659 660 if (asprintf(&upw, "%s:%s", usr, pwd) == -1) 661 return (-1); 662 auth = http_base64(upw); 663 free(upw); 664 if (auth == NULL) 665 return (-1); 666 r = http_cmd(conn, "%s: Basic %s\r\n", hdr, auth); 667 free(auth); 668 return (r); 669 } 670 671 /* 672 * Send an authorization header 673 */ 674 static int 675 http_authorize(conn_t *conn, const char *hdr, const char *p) 676 { 677 /* basic authorization */ 678 if (strncasecmp(p, "basic:", 6) == 0) { 679 char *user, *pwd, *str; 680 int r; 681 682 /* skip realm */ 683 for (p += 6; *p && *p != ':'; ++p) 684 /* nothing */ ; 685 if (!*p || strchr(++p, ':') == NULL) 686 return (-1); 687 if ((str = strdup(p)) == NULL) 688 return (-1); /* XXX */ 689 user = str; 690 pwd = strchr(str, ':'); 691 *pwd++ = '\0'; 692 r = http_basic_auth(conn, hdr, user, pwd); 693 free(str); 694 return (r); 695 } 696 return (-1); 697 } 698 699 700 /***************************************************************************** 701 * Helper functions for connecting to a server or proxy 702 */ 703 704 /* 705 * Connect to the correct HTTP server or proxy. 706 */ 707 static conn_t * 708 http_connect(struct url *URL, struct url *purl, const char *flags, int *cached) 709 { 710 conn_t *conn; 711 int af, verbose; 712 #ifdef TCP_NOPUSH 713 int val; 714 #endif 715 716 *cached = 1; 717 718 #ifdef INET6 719 af = AF_UNSPEC; 720 #else 721 af = AF_INET; 722 #endif 723 724 verbose = CHECK_FLAG('v'); 725 if (CHECK_FLAG('4')) 726 af = AF_INET; 727 #ifdef INET6 728 else if (CHECK_FLAG('6')) 729 af = AF_INET6; 730 #endif 731 732 if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) { 733 URL = purl; 734 } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) { 735 /* can't talk http to an ftp server */ 736 /* XXX should set an error code */ 737 return (NULL); 738 } 739 740 if ((conn = fetch_cache_get(URL, af)) != NULL) { 741 *cached = 1; 742 return (conn); 743 } 744 745 if ((conn = fetch_connect(URL, af, verbose)) == NULL) 746 /* fetch_connect() has already set an error code */ 747 return (NULL); 748 if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 && 749 fetch_ssl(conn, verbose) == -1) { 750 fetch_close(conn); 751 /* grrr */ 752 #ifdef EAUTH 753 errno = EAUTH; 754 #else 755 errno = EPERM; 756 #endif 757 fetch_syserr(); 758 return (NULL); 759 } 760 761 #ifdef TCP_NOPUSH 762 val = 1; 763 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val)); 764 #endif 765 766 return (conn); 767 } 768 769 static struct url * 770 http_get_proxy(struct url * url, const char *flags) 771 { 772 struct url *purl; 773 char *p; 774 775 if (flags != NULL && strchr(flags, 'd') != NULL) 776 return (NULL); 777 if (fetch_no_proxy_match(url->host)) 778 return (NULL); 779 if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 780 *p && (purl = fetchParseURL(p))) { 781 if (!*purl->scheme) 782 strcpy(purl->scheme, SCHEME_HTTP); 783 if (!purl->port) 784 purl->port = fetch_default_proxy_port(purl->scheme); 785 if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 786 return (purl); 787 fetchFreeURL(purl); 788 } 789 return (NULL); 790 } 791 792 static void 793 set_if_modified_since(conn_t *conn, time_t last_modified) 794 { 795 static const char weekdays[] = "SunMonTueWedThuFriSat"; 796 static const char months[] = "JanFebMarAprMayJunJulAugSepOctNovDec"; 797 struct tm tm; 798 char buf[80]; 799 gmtime_r(&last_modified, &tm); 800 snprintf(buf, sizeof(buf), "%.3s, %02d %.3s %4d %02d:%02d:%02d GMT", 801 weekdays + tm.tm_wday * 3, tm.tm_mday, months + tm.tm_mon * 3, 802 tm.tm_year + 1900, tm.tm_hour, tm.tm_min, tm.tm_sec); 803 http_cmd(conn, "If-Modified-Since: %s\r\n", buf); 804 } 805 806 807 /***************************************************************************** 808 * Core 809 */ 810 811 /* 812 * Send a request and process the reply 813 * 814 * XXX This function is way too long, the do..while loop should be split 815 * XXX off into a separate function. 816 */ 817 fetchIO * 818 http_request(struct url *URL, const char *op, struct url_stat *us, 819 struct url *purl, const char *flags) 820 { 821 conn_t *conn; 822 struct url *url, *new; 823 int chunked, direct, if_modified_since, need_auth, noredirect; 824 int keep_alive, verbose, cached; 825 int e, i, n, val; 826 off_t offset, clength, length, size; 827 time_t mtime; 828 const char *p; 829 fetchIO *f; 830 hdr_t h; 831 char hbuf[URL_HOSTLEN + 7], *host; 832 833 direct = CHECK_FLAG('d'); 834 noredirect = CHECK_FLAG('A'); 835 verbose = CHECK_FLAG('v'); 836 if_modified_since = CHECK_FLAG('i'); 837 keep_alive = 0; 838 839 if (direct && purl) { 840 fetchFreeURL(purl); 841 purl = NULL; 842 } 843 844 /* try the provided URL first */ 845 url = URL; 846 847 /* if the A flag is set, we only get one try */ 848 n = noredirect ? 1 : MAX_REDIRECT; 849 i = 0; 850 851 e = HTTP_PROTOCOL_ERROR; 852 need_auth = 0; 853 do { 854 new = NULL; 855 chunked = 0; 856 offset = 0; 857 clength = -1; 858 length = -1; 859 size = -1; 860 mtime = 0; 861 862 /* check port */ 863 if (!url->port) 864 url->port = fetch_default_port(url->scheme); 865 866 /* were we redirected to an FTP URL? */ 867 if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) { 868 if (strcmp(op, "GET") == 0) 869 return (ftp_request(url, "RETR", NULL, us, purl, flags)); 870 else if (strcmp(op, "HEAD") == 0) 871 return (ftp_request(url, "STAT", NULL, us, purl, flags)); 872 } 873 874 /* connect to server or proxy */ 875 if ((conn = http_connect(url, purl, flags, &cached)) == NULL) 876 goto ouch; 877 878 host = url->host; 879 #ifdef INET6 880 if (strchr(url->host, ':')) { 881 snprintf(hbuf, sizeof(hbuf), "[%s]", url->host); 882 host = hbuf; 883 } 884 #endif 885 if (url->port != fetch_default_port(url->scheme)) { 886 if (host != hbuf) { 887 strcpy(hbuf, host); 888 host = hbuf; 889 } 890 snprintf(hbuf + strlen(hbuf), 891 sizeof(hbuf) - strlen(hbuf), ":%d", url->port); 892 } 893 894 /* send request */ 895 if (verbose) 896 fetch_info("requesting %s://%s%s", 897 url->scheme, host, url->doc); 898 if (purl) { 899 http_cmd(conn, "%s %s://%s%s HTTP/1.1\r\n", 900 op, url->scheme, host, url->doc); 901 } else { 902 http_cmd(conn, "%s %s HTTP/1.1\r\n", 903 op, url->doc); 904 } 905 906 if (if_modified_since && url->last_modified > 0) 907 set_if_modified_since(conn, url->last_modified); 908 909 /* virtual host */ 910 http_cmd(conn, "Host: %s\r\n", host); 911 912 /* proxy authorization */ 913 if (purl) { 914 if (*purl->user || *purl->pwd) 915 http_basic_auth(conn, "Proxy-Authorization", 916 purl->user, purl->pwd); 917 else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0') 918 http_authorize(conn, "Proxy-Authorization", p); 919 } 920 921 /* server authorization */ 922 if (need_auth || *url->user || *url->pwd) { 923 if (*url->user || *url->pwd) 924 http_basic_auth(conn, "Authorization", url->user, url->pwd); 925 else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0') 926 http_authorize(conn, "Authorization", p); 927 else if (fetchAuthMethod && fetchAuthMethod(url) == 0) { 928 http_basic_auth(conn, "Authorization", url->user, url->pwd); 929 } else { 930 http_seterr(HTTP_NEED_AUTH); 931 goto ouch; 932 } 933 } 934 935 /* other headers */ 936 if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') { 937 if (strcasecmp(p, "auto") == 0) 938 http_cmd(conn, "Referer: %s://%s%s\r\n", 939 url->scheme, host, url->doc); 940 else 941 http_cmd(conn, "Referer: %s\r\n", p); 942 } 943 if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0') 944 http_cmd(conn, "User-Agent: %s\r\n", p); 945 else 946 http_cmd(conn, "User-Agent: %s\r\n", _LIBFETCH_VER); 947 if (url->offset > 0) 948 http_cmd(conn, "Range: bytes=%lld-\r\n", (long long)url->offset); 949 http_cmd(conn, "\r\n"); 950 951 /* 952 * Force the queued request to be dispatched. Normally, one 953 * would do this with shutdown(2) but squid proxies can be 954 * configured to disallow such half-closed connections. To 955 * be compatible with such configurations, fiddle with socket 956 * options to force the pending data to be written. 957 */ 958 #ifdef TCP_NOPUSH 959 val = 0; 960 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, 961 sizeof(val)); 962 #endif 963 val = 1; 964 setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val, 965 sizeof(val)); 966 967 /* get reply */ 968 switch (http_get_reply(conn)) { 969 case HTTP_OK: 970 case HTTP_PARTIAL: 971 case HTTP_NOT_MODIFIED: 972 /* fine */ 973 break; 974 case HTTP_MOVED_PERM: 975 case HTTP_MOVED_TEMP: 976 case HTTP_SEE_OTHER: 977 /* 978 * Not so fine, but we still have to read the 979 * headers to get the new location. 980 */ 981 break; 982 case HTTP_NEED_AUTH: 983 if (need_auth) { 984 /* 985 * We already sent out authorization code, 986 * so there's nothing more we can do. 987 */ 988 http_seterr(conn->err); 989 goto ouch; 990 } 991 /* try again, but send the password this time */ 992 if (verbose) 993 fetch_info("server requires authorization"); 994 break; 995 case HTTP_NEED_PROXY_AUTH: 996 /* 997 * If we're talking to a proxy, we already sent 998 * our proxy authorization code, so there's 999 * nothing more we can do. 1000 */ 1001 http_seterr(conn->err); 1002 goto ouch; 1003 case HTTP_BAD_RANGE: 1004 /* 1005 * This can happen if we ask for 0 bytes because 1006 * we already have the whole file. Consider this 1007 * a success for now, and check sizes later. 1008 */ 1009 break; 1010 case HTTP_PROTOCOL_ERROR: 1011 /* fall through */ 1012 case -1: 1013 --i; 1014 if (cached) 1015 continue; 1016 fetch_syserr(); 1017 goto ouch; 1018 default: 1019 http_seterr(conn->err); 1020 if (!verbose) 1021 goto ouch; 1022 /* fall through so we can get the full error message */ 1023 } 1024 1025 /* get headers */ 1026 do { 1027 switch ((h = http_next_header(conn, &p))) { 1028 case hdr_syserror: 1029 fetch_syserr(); 1030 goto ouch; 1031 case hdr_error: 1032 http_seterr(HTTP_PROTOCOL_ERROR); 1033 goto ouch; 1034 case hdr_connection: 1035 /* XXX too weak? */ 1036 keep_alive = (strcasecmp(p, "keep-alive") == 0); 1037 break; 1038 case hdr_content_length: 1039 http_parse_length(p, &clength); 1040 break; 1041 case hdr_content_range: 1042 http_parse_range(p, &offset, &length, &size); 1043 break; 1044 case hdr_last_modified: 1045 http_parse_mtime(p, &mtime); 1046 break; 1047 case hdr_location: 1048 if (!HTTP_REDIRECT(conn->err)) 1049 break; 1050 if (new) 1051 free(new); 1052 if (verbose) 1053 fetch_info("%d redirect to %s", conn->err, p); 1054 if (*p == '/') 1055 /* absolute path */ 1056 new = fetchMakeURL(url->scheme, url->host, url->port, p, 1057 url->user, url->pwd); 1058 else 1059 new = fetchParseURL(p); 1060 if (new == NULL) { 1061 /* XXX should set an error code */ 1062 goto ouch; 1063 } 1064 if (!*new->user && !*new->pwd) { 1065 strcpy(new->user, url->user); 1066 strcpy(new->pwd, url->pwd); 1067 } 1068 new->offset = url->offset; 1069 new->length = url->length; 1070 break; 1071 case hdr_transfer_encoding: 1072 /* XXX weak test*/ 1073 chunked = (strcasecmp(p, "chunked") == 0); 1074 break; 1075 case hdr_www_authenticate: 1076 if (conn->err != HTTP_NEED_AUTH) 1077 break; 1078 /* if we were smarter, we'd check the method and realm */ 1079 break; 1080 case hdr_end: 1081 /* fall through */ 1082 case hdr_unknown: 1083 /* ignore */ 1084 break; 1085 } 1086 } while (h > hdr_end); 1087 1088 /* we need to provide authentication */ 1089 if (conn->err == HTTP_NEED_AUTH) { 1090 e = conn->err; 1091 need_auth = 1; 1092 fetch_close(conn); 1093 conn = NULL; 1094 continue; 1095 } 1096 1097 /* requested range not satisfiable */ 1098 if (conn->err == HTTP_BAD_RANGE) { 1099 if (url->offset == size && url->length == 0) { 1100 /* asked for 0 bytes; fake it */ 1101 offset = url->offset; 1102 conn->err = HTTP_OK; 1103 break; 1104 } else { 1105 http_seterr(conn->err); 1106 goto ouch; 1107 } 1108 } 1109 1110 /* we have a hit or an error */ 1111 if (conn->err == HTTP_OK || 1112 conn->err == HTTP_PARTIAL || 1113 conn->err == HTTP_NOT_MODIFIED || 1114 HTTP_ERROR(conn->err)) 1115 break; 1116 1117 /* all other cases: we got a redirect */ 1118 e = conn->err; 1119 need_auth = 0; 1120 fetch_close(conn); 1121 conn = NULL; 1122 if (!new) 1123 break; 1124 if (url != URL) 1125 fetchFreeURL(url); 1126 url = new; 1127 } while (++i < n); 1128 1129 /* we failed, or ran out of retries */ 1130 if (conn == NULL) { 1131 http_seterr(e); 1132 goto ouch; 1133 } 1134 1135 /* check for inconsistencies */ 1136 if (clength != -1 && length != -1 && clength != length) { 1137 http_seterr(HTTP_PROTOCOL_ERROR); 1138 goto ouch; 1139 } 1140 if (clength == -1) 1141 clength = length; 1142 if (clength != -1) 1143 length = offset + clength; 1144 if (length != -1 && size != -1 && length != size) { 1145 http_seterr(HTTP_PROTOCOL_ERROR); 1146 goto ouch; 1147 } 1148 if (size == -1) 1149 size = length; 1150 1151 /* fill in stats */ 1152 if (us) { 1153 us->size = size; 1154 us->atime = us->mtime = mtime; 1155 } 1156 1157 /* too far? */ 1158 if (URL->offset > 0 && offset > URL->offset) { 1159 http_seterr(HTTP_PROTOCOL_ERROR); 1160 goto ouch; 1161 } 1162 1163 /* report back real offset and size */ 1164 URL->offset = offset; 1165 URL->length = clength; 1166 1167 if (clength == -1 && !chunked) 1168 keep_alive = 0; 1169 1170 if (conn->err == HTTP_NOT_MODIFIED) { 1171 http_seterr(HTTP_NOT_MODIFIED); 1172 if (keep_alive) { 1173 fetch_cache_put(conn, fetch_close); 1174 conn = NULL; 1175 } 1176 goto ouch; 1177 } 1178 1179 /* wrap it up in a fetchIO */ 1180 if ((f = http_funopen(conn, chunked, keep_alive, clength)) == NULL) { 1181 fetch_syserr(); 1182 goto ouch; 1183 } 1184 1185 if (url != URL) 1186 fetchFreeURL(url); 1187 if (purl) 1188 fetchFreeURL(purl); 1189 1190 if (HTTP_ERROR(conn->err)) { 1191 1192 if (keep_alive) { 1193 char buf[512]; 1194 do { 1195 } while (fetchIO_read(f, buf, sizeof(buf)) > 0); 1196 } 1197 1198 fetchIO_close(f); 1199 f = NULL; 1200 } 1201 1202 return (f); 1203 1204 ouch: 1205 if (url != URL) 1206 fetchFreeURL(url); 1207 if (purl) 1208 fetchFreeURL(purl); 1209 if (conn != NULL) 1210 fetch_close(conn); 1211 return (NULL); 1212 } 1213 1214 1215 /***************************************************************************** 1216 * Entry points 1217 */ 1218 1219 /* 1220 * Retrieve and stat a file by HTTP 1221 */ 1222 fetchIO * 1223 fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags) 1224 { 1225 return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags)); 1226 } 1227 1228 /* 1229 * Retrieve a file by HTTP 1230 */ 1231 fetchIO * 1232 fetchGetHTTP(struct url *URL, const char *flags) 1233 { 1234 return (fetchXGetHTTP(URL, NULL, flags)); 1235 } 1236 1237 /* 1238 * Store a file by HTTP 1239 */ 1240 fetchIO * 1241 fetchPutHTTP(struct url *URL, const char *flags) 1242 { 1243 fprintf(stderr, "fetchPutHTTP(): not implemented\n"); 1244 return (NULL); 1245 } 1246 1247 /* 1248 * Get an HTTP document's metadata 1249 */ 1250 int 1251 fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags) 1252 { 1253 fetchIO *f; 1254 1255 f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags); 1256 if (f == NULL) 1257 return (-1); 1258 fetchIO_close(f); 1259 return (0); 1260 } 1261 1262 enum http_states { 1263 ST_NONE, 1264 ST_LT, 1265 ST_LTA, 1266 ST_TAGA, 1267 ST_H, 1268 ST_R, 1269 ST_E, 1270 ST_F, 1271 ST_HREF, 1272 ST_HREFQ, 1273 ST_TAG, 1274 ST_TAGAX, 1275 ST_TAGAQ 1276 }; 1277 1278 struct index_parser { 1279 struct url_list *ue; 1280 struct url *url; 1281 enum http_states state; 1282 }; 1283 1284 static ssize_t 1285 parse_index(struct index_parser *parser, const char *buf, size_t len) 1286 { 1287 char *end_attr, p = *buf; 1288 1289 switch (parser->state) { 1290 case ST_NONE: 1291 /* Plain text, not in markup */ 1292 if (p == '<') 1293 parser->state = ST_LT; 1294 return 1; 1295 case ST_LT: 1296 /* In tag -- "<" already found */ 1297 if (p == '>') 1298 parser->state = ST_NONE; 1299 else if (p == 'a' || p == 'A') 1300 parser->state = ST_LTA; 1301 else if (!isspace((unsigned char)p)) 1302 parser->state = ST_TAG; 1303 return 1; 1304 case ST_LTA: 1305 /* In tag -- "<a" already found */ 1306 if (p == '>') 1307 parser->state = ST_NONE; 1308 else if (p == '"') 1309 parser->state = ST_TAGAQ; 1310 else if (isspace((unsigned char)p)) 1311 parser->state = ST_TAGA; 1312 else 1313 parser->state = ST_TAG; 1314 return 1; 1315 case ST_TAG: 1316 /* In tag, but not "<a" -- disregard */ 1317 if (p == '>') 1318 parser->state = ST_NONE; 1319 return 1; 1320 case ST_TAGA: 1321 /* In a-tag -- "<a " already found */ 1322 if (p == '>') 1323 parser->state = ST_NONE; 1324 else if (p == '"') 1325 parser->state = ST_TAGAQ; 1326 else if (p == 'h' || p == 'H') 1327 parser->state = ST_H; 1328 else if (!isspace((unsigned char)p)) 1329 parser->state = ST_TAGAX; 1330 return 1; 1331 case ST_TAGAX: 1332 /* In unknown keyword in a-tag */ 1333 if (p == '>') 1334 parser->state = ST_NONE; 1335 else if (p == '"') 1336 parser->state = ST_TAGAQ; 1337 else if (isspace((unsigned char)p)) 1338 parser->state = ST_TAGA; 1339 return 1; 1340 case ST_TAGAQ: 1341 /* In a-tag, unknown argument for keys. */ 1342 if (p == '>') 1343 parser->state = ST_NONE; 1344 else if (p == '"') 1345 parser->state = ST_TAGA; 1346 return 1; 1347 case ST_H: 1348 /* In a-tag -- "<a h" already found */ 1349 if (p == '>') 1350 parser->state = ST_NONE; 1351 else if (p == '"') 1352 parser->state = ST_TAGAQ; 1353 else if (p == 'r' || p == 'R') 1354 parser->state = ST_R; 1355 else if (isspace((unsigned char)p)) 1356 parser->state = ST_TAGA; 1357 else 1358 parser->state = ST_TAGAX; 1359 return 1; 1360 case ST_R: 1361 /* In a-tag -- "<a hr" already found */ 1362 if (p == '>') 1363 parser->state = ST_NONE; 1364 else if (p == '"') 1365 parser->state = ST_TAGAQ; 1366 else if (p == 'e' || p == 'E') 1367 parser->state = ST_E; 1368 else if (isspace((unsigned char)p)) 1369 parser->state = ST_TAGA; 1370 else 1371 parser->state = ST_TAGAX; 1372 return 1; 1373 case ST_E: 1374 /* In a-tag -- "<a hre" already found */ 1375 if (p == '>') 1376 parser->state = ST_NONE; 1377 else if (p == '"') 1378 parser->state = ST_TAGAQ; 1379 else if (p == 'f' || p == 'F') 1380 parser->state = ST_F; 1381 else if (isspace((unsigned char)p)) 1382 parser->state = ST_TAGA; 1383 else 1384 parser->state = ST_TAGAX; 1385 return 1; 1386 case ST_F: 1387 /* In a-tag -- "<a href" already found */ 1388 if (p == '>') 1389 parser->state = ST_NONE; 1390 else if (p == '"') 1391 parser->state = ST_TAGAQ; 1392 else if (p == '=') 1393 parser->state = ST_HREF; 1394 else if (!isspace((unsigned char)p)) 1395 parser->state = ST_TAGAX; 1396 return 1; 1397 case ST_HREF: 1398 /* In a-tag -- "<a href=" already found */ 1399 if (p == '>') 1400 parser->state = ST_NONE; 1401 else if (p == '"') 1402 parser->state = ST_HREFQ; 1403 else if (!isspace((unsigned char)p)) 1404 parser->state = ST_TAGA; 1405 return 1; 1406 case ST_HREFQ: 1407 /* In href of the a-tag */ 1408 end_attr = memchr(buf, '"', len); 1409 if (end_attr == NULL) 1410 return 0; 1411 *end_attr = '\0'; 1412 parser->state = ST_TAGA; 1413 if (fetch_add_entry(parser->ue, parser->url, buf, 1)) 1414 return -1; 1415 return end_attr + 1 - buf; 1416 } 1417 /* NOTREACHED */ 1418 abort(); 1419 } 1420 1421 struct http_index_cache { 1422 struct http_index_cache *next; 1423 struct url *location; 1424 struct url_list ue; 1425 }; 1426 1427 static struct http_index_cache *index_cache; 1428 1429 /* 1430 * List a directory 1431 */ 1432 int 1433 fetchListHTTP(struct url_list *ue, struct url *url, const char *pattern, const char *flags) 1434 { 1435 fetchIO *f; 1436 char buf[2 * PATH_MAX]; 1437 size_t buf_len, sum_processed; 1438 ssize_t read_len, processed; 1439 struct index_parser state; 1440 struct http_index_cache *cache = NULL; 1441 int do_cache, ret; 1442 1443 do_cache = CHECK_FLAG('c'); 1444 1445 if (do_cache) { 1446 for (cache = index_cache; cache != NULL; cache = cache->next) { 1447 if (strcmp(cache->location->scheme, url->scheme)) 1448 continue; 1449 if (strcmp(cache->location->user, url->user)) 1450 continue; 1451 if (strcmp(cache->location->pwd, url->pwd)) 1452 continue; 1453 if (strcmp(cache->location->host, url->host)) 1454 continue; 1455 if (cache->location->port != url->port) 1456 continue; 1457 if (strcmp(cache->location->doc, url->doc)) 1458 continue; 1459 return fetchAppendURLList(ue, &cache->ue); 1460 } 1461 1462 cache = malloc(sizeof(*cache)); 1463 fetchInitURLList(&cache->ue); 1464 cache->location = fetchCopyURL(url); 1465 } 1466 1467 f = fetchGetHTTP(url, flags); 1468 if (f == NULL) { 1469 if (do_cache) { 1470 fetchFreeURLList(&cache->ue); 1471 fetchFreeURL(cache->location); 1472 free(cache); 1473 } 1474 return -1; 1475 } 1476 1477 state.url = url; 1478 state.state = ST_NONE; 1479 if (do_cache) { 1480 state.ue = &cache->ue; 1481 } else { 1482 state.ue = ue; 1483 } 1484 1485 buf_len = 0; 1486 1487 while ((read_len = fetchIO_read(f, buf + buf_len, sizeof(buf) - buf_len)) > 0) { 1488 buf_len += read_len; 1489 sum_processed = 0; 1490 do { 1491 processed = parse_index(&state, buf + sum_processed, buf_len); 1492 if (processed == -1) 1493 break; 1494 buf_len -= processed; 1495 sum_processed += processed; 1496 } while (processed != 0 && buf_len > 0); 1497 if (processed == -1) { 1498 read_len = -1; 1499 break; 1500 } 1501 memmove(buf, buf + sum_processed, buf_len); 1502 } 1503 1504 fetchIO_close(f); 1505 1506 ret = read_len < 0 ? -1 : 0; 1507 1508 if (do_cache) { 1509 if (ret == 0) { 1510 cache->next = index_cache; 1511 index_cache = cache; 1512 } 1513 1514 if (fetchAppendURLList(ue, &cache->ue)) 1515 ret = -1; 1516 } 1517 1518 return ret; 1519 } 1520