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