1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 2000-2014 Dag-Erling Smørgrav 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer 12 * in this position and unchanged. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 3. The name of the author may not be used to endorse or promote products 17 * derived from this software without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 */ 30 31 #include <sys/cdefs.h> 32 __FBSDID("$FreeBSD$"); 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 #include <sys/param.h> 67 #include <sys/socket.h> 68 #include <sys/time.h> 69 70 #include <ctype.h> 71 #include <err.h> 72 #include <errno.h> 73 #include <locale.h> 74 #include <netdb.h> 75 #include <stdarg.h> 76 #include <stdio.h> 77 #include <stdlib.h> 78 #include <string.h> 79 #include <time.h> 80 #include <unistd.h> 81 82 #ifdef WITH_SSL 83 #include <openssl/md5.h> 84 #define MD5Init(c) MD5_Init(c) 85 #define MD5Update(c, data, len) MD5_Update(c, data, len) 86 #define MD5Final(md, c) MD5_Final(md, c) 87 #else 88 #include <md5.h> 89 #endif 90 91 #include <netinet/in.h> 92 #include <netinet/tcp.h> 93 94 #include "fetch.h" 95 #include "common.h" 96 #include "httperr.h" 97 98 /* Maximum number of redirects to follow */ 99 #define MAX_REDIRECT 20 100 101 /* Symbolic names for reply codes we care about */ 102 #define HTTP_OK 200 103 #define HTTP_PARTIAL 206 104 #define HTTP_MOVED_PERM 301 105 #define HTTP_MOVED_TEMP 302 106 #define HTTP_SEE_OTHER 303 107 #define HTTP_NOT_MODIFIED 304 108 #define HTTP_USE_PROXY 305 109 #define HTTP_TEMP_REDIRECT 307 110 #define HTTP_PERM_REDIRECT 308 111 #define HTTP_NEED_AUTH 401 112 #define HTTP_NEED_PROXY_AUTH 407 113 #define HTTP_BAD_RANGE 416 114 #define HTTP_PROTOCOL_ERROR 999 115 116 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \ 117 || (xyz) == HTTP_MOVED_TEMP \ 118 || (xyz) == HTTP_TEMP_REDIRECT \ 119 || (xyz) == HTTP_PERM_REDIRECT \ 120 || (xyz) == HTTP_USE_PROXY \ 121 || (xyz) == HTTP_SEE_OTHER) 122 123 #define HTTP_ERROR(xyz) ((xyz) >= 400 && (xyz) <= 599) 124 125 126 /***************************************************************************** 127 * I/O functions for decoding chunked streams 128 */ 129 130 struct httpio 131 { 132 conn_t *conn; /* connection */ 133 int chunked; /* chunked mode */ 134 char *buf; /* chunk buffer */ 135 size_t bufsize; /* size of chunk buffer */ 136 size_t buflen; /* amount of data currently in buffer */ 137 size_t bufpos; /* current read offset in buffer */ 138 int eof; /* end-of-file flag */ 139 int error; /* error flag */ 140 size_t chunksize; /* remaining size of current chunk */ 141 #ifndef NDEBUG 142 size_t total; 143 #endif 144 }; 145 146 /* 147 * Get next chunk header 148 */ 149 static int 150 http_new_chunk(struct httpio *io) 151 { 152 char *p; 153 154 if (fetch_getln(io->conn) == -1) 155 return (-1); 156 157 if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf)) 158 return (-1); 159 160 for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) { 161 if (*p == ';') 162 break; 163 if (!isxdigit((unsigned char)*p)) 164 return (-1); 165 if (isdigit((unsigned char)*p)) { 166 io->chunksize = io->chunksize * 16 + 167 *p - '0'; 168 } else { 169 io->chunksize = io->chunksize * 16 + 170 10 + tolower((unsigned char)*p) - 'a'; 171 } 172 } 173 174 #ifndef NDEBUG 175 if (fetchDebug) { 176 io->total += io->chunksize; 177 if (io->chunksize == 0) 178 fprintf(stderr, "%s(): end of last chunk\n", __func__); 179 else 180 fprintf(stderr, "%s(): new chunk: %lu (%lu)\n", 181 __func__, (unsigned long)io->chunksize, 182 (unsigned long)io->total); 183 } 184 #endif 185 186 return (io->chunksize); 187 } 188 189 /* 190 * Grow the input buffer to at least len bytes 191 */ 192 static inline int 193 http_growbuf(struct httpio *io, size_t len) 194 { 195 char *tmp; 196 197 if (io->bufsize >= len) 198 return (0); 199 200 if ((tmp = realloc(io->buf, len)) == NULL) 201 return (-1); 202 io->buf = tmp; 203 io->bufsize = len; 204 return (0); 205 } 206 207 /* 208 * Fill the input buffer, do chunk decoding on the fly 209 */ 210 static ssize_t 211 http_fillbuf(struct httpio *io, size_t len) 212 { 213 ssize_t nbytes; 214 char ch; 215 216 if (io->error) 217 return (-1); 218 if (io->eof) 219 return (0); 220 221 /* not chunked: just fetch the requested amount */ 222 if (io->chunked == 0) { 223 if (http_growbuf(io, len) == -1) 224 return (-1); 225 if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) { 226 io->error = errno; 227 return (-1); 228 } 229 io->buflen = nbytes; 230 io->bufpos = 0; 231 return (io->buflen); 232 } 233 234 /* chunked, but we ran out: get the next chunk header */ 235 if (io->chunksize == 0) { 236 switch (http_new_chunk(io)) { 237 case -1: 238 io->error = EPROTO; 239 return (-1); 240 case 0: 241 io->eof = 1; 242 return (0); 243 } 244 } 245 246 /* fetch the requested amount, but no more than the current chunk */ 247 if (len > io->chunksize) 248 len = io->chunksize; 249 if (http_growbuf(io, len) == -1) 250 return (-1); 251 if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) { 252 io->error = errno; 253 return (-1); 254 } 255 io->bufpos = 0; 256 io->buflen = nbytes; 257 io->chunksize -= nbytes; 258 259 if (io->chunksize == 0) { 260 if (fetch_read(io->conn, &ch, 1) != 1 || ch != '\r' || 261 fetch_read(io->conn, &ch, 1) != 1 || ch != '\n') 262 return (-1); 263 } 264 265 return (io->buflen); 266 } 267 268 /* 269 * Read function 270 */ 271 static int 272 http_readfn(void *v, char *buf, int len) 273 { 274 struct httpio *io = (struct httpio *)v; 275 int rlen; 276 277 if (io->error) 278 return (-1); 279 if (io->eof) 280 return (0); 281 282 /* empty buffer */ 283 if (!io->buf || io->bufpos == io->buflen) { 284 if ((rlen = http_fillbuf(io, len)) < 0) { 285 if ((errno = io->error) == EINTR) 286 io->error = 0; 287 return (-1); 288 } else if (rlen == 0) { 289 return (0); 290 } 291 } 292 293 rlen = io->buflen - io->bufpos; 294 if (len < rlen) 295 rlen = len; 296 memcpy(buf, io->buf + io->bufpos, rlen); 297 io->bufpos += rlen; 298 return (rlen); 299 } 300 301 /* 302 * Write function 303 */ 304 static int 305 http_writefn(void *v, const char *buf, int len) 306 { 307 struct httpio *io = (struct httpio *)v; 308 309 return (fetch_write(io->conn, buf, len)); 310 } 311 312 /* 313 * Close function 314 */ 315 static int 316 http_closefn(void *v) 317 { 318 struct httpio *io = (struct httpio *)v; 319 int r; 320 321 r = fetch_close(io->conn); 322 if (io->buf) 323 free(io->buf); 324 free(io); 325 return (r); 326 } 327 328 /* 329 * Wrap a file descriptor up 330 */ 331 static FILE * 332 http_funopen(conn_t *conn, int chunked) 333 { 334 struct httpio *io; 335 FILE *f; 336 337 if ((io = calloc(1, sizeof(*io))) == NULL) { 338 fetch_syserr(); 339 return (NULL); 340 } 341 io->conn = conn; 342 io->chunked = chunked; 343 f = funopen(io, http_readfn, http_writefn, NULL, http_closefn); 344 if (f == NULL) { 345 fetch_syserr(); 346 free(io); 347 return (NULL); 348 } 349 return (f); 350 } 351 352 353 /***************************************************************************** 354 * Helper functions for talking to the server and parsing its replies 355 */ 356 357 /* Header types */ 358 typedef enum { 359 hdr_syserror = -2, 360 hdr_error = -1, 361 hdr_end = 0, 362 hdr_unknown = 1, 363 hdr_content_length, 364 hdr_content_range, 365 hdr_last_modified, 366 hdr_location, 367 hdr_transfer_encoding, 368 hdr_www_authenticate, 369 hdr_proxy_authenticate, 370 } hdr_t; 371 372 /* Names of interesting headers */ 373 static struct { 374 hdr_t num; 375 const char *name; 376 } hdr_names[] = { 377 { hdr_content_length, "Content-Length" }, 378 { hdr_content_range, "Content-Range" }, 379 { hdr_last_modified, "Last-Modified" }, 380 { hdr_location, "Location" }, 381 { hdr_transfer_encoding, "Transfer-Encoding" }, 382 { hdr_www_authenticate, "WWW-Authenticate" }, 383 { hdr_proxy_authenticate, "Proxy-Authenticate" }, 384 { hdr_unknown, NULL }, 385 }; 386 387 /* 388 * Send a formatted line; optionally echo to terminal 389 */ 390 static int 391 http_cmd(conn_t *conn, const char *fmt, ...) 392 { 393 va_list ap; 394 size_t len; 395 char *msg; 396 int r; 397 398 va_start(ap, fmt); 399 len = vasprintf(&msg, fmt, ap); 400 va_end(ap); 401 402 if (msg == NULL) { 403 errno = ENOMEM; 404 fetch_syserr(); 405 return (-1); 406 } 407 408 r = fetch_putln(conn, msg, len); 409 free(msg); 410 411 if (r == -1) { 412 fetch_syserr(); 413 return (-1); 414 } 415 416 return (0); 417 } 418 419 /* 420 * Get and parse status line 421 */ 422 static int 423 http_get_reply(conn_t *conn) 424 { 425 char *p; 426 427 if (fetch_getln(conn) == -1) 428 return (-1); 429 /* 430 * A valid status line looks like "HTTP/m.n xyz reason" where m 431 * and n are the major and minor protocol version numbers and xyz 432 * is the reply code. 433 * Unfortunately, there are servers out there (NCSA 1.5.1, to name 434 * just one) that do not send a version number, so we can't rely 435 * on finding one, but if we do, insist on it being 1.0 or 1.1. 436 * We don't care about the reason phrase. 437 */ 438 if (strncmp(conn->buf, "HTTP", 4) != 0) 439 return (HTTP_PROTOCOL_ERROR); 440 p = conn->buf + 4; 441 if (*p == '/') { 442 if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1')) 443 return (HTTP_PROTOCOL_ERROR); 444 p += 4; 445 } 446 if (*p != ' ' || 447 !isdigit((unsigned char)p[1]) || 448 !isdigit((unsigned char)p[2]) || 449 !isdigit((unsigned char)p[3])) 450 return (HTTP_PROTOCOL_ERROR); 451 452 conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0'); 453 return (conn->err); 454 } 455 456 /* 457 * Check a header; if the type matches the given string, return a pointer 458 * to the beginning of the value. 459 */ 460 static const char * 461 http_match(const char *str, const char *hdr) 462 { 463 while (*str && *hdr && 464 tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++)) 465 /* nothing */; 466 if (*str || *hdr != ':') 467 return (NULL); 468 while (*hdr && isspace((unsigned char)*++hdr)) 469 /* nothing */; 470 return (hdr); 471 } 472 473 474 /* 475 * Get the next header and return the appropriate symbolic code. We 476 * need to read one line ahead for checking for a continuation line 477 * belonging to the current header (continuation lines start with 478 * white space). 479 * 480 * We get called with a fresh line already in the conn buffer, either 481 * from the previous http_next_header() invocation, or, the first 482 * time, from a fetch_getln() performed by our caller. 483 * 484 * This stops when we encounter an empty line (we dont read beyond the header 485 * area). 486 * 487 * Note that the "headerbuf" is just a place to return the result. Its 488 * contents are not used for the next call. This means that no cleanup 489 * is needed when ie doing another connection, just call the cleanup when 490 * fully done to deallocate memory. 491 */ 492 493 /* Limit the max number of continuation lines to some reasonable value */ 494 #define HTTP_MAX_CONT_LINES 10 495 496 /* Place into which to build a header from one or several lines */ 497 typedef struct { 498 char *buf; /* buffer */ 499 size_t bufsize; /* buffer size */ 500 size_t buflen; /* length of buffer contents */ 501 } http_headerbuf_t; 502 503 static void 504 init_http_headerbuf(http_headerbuf_t *buf) 505 { 506 buf->buf = NULL; 507 buf->bufsize = 0; 508 buf->buflen = 0; 509 } 510 511 static void 512 clean_http_headerbuf(http_headerbuf_t *buf) 513 { 514 if (buf->buf) 515 free(buf->buf); 516 init_http_headerbuf(buf); 517 } 518 519 /* Remove whitespace at the end of the buffer */ 520 static void 521 http_conn_trimright(conn_t *conn) 522 { 523 while (conn->buflen && 524 isspace((unsigned char)conn->buf[conn->buflen - 1])) 525 conn->buflen--; 526 conn->buf[conn->buflen] = '\0'; 527 } 528 529 static hdr_t 530 http_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p) 531 { 532 unsigned int i, len; 533 534 /* 535 * Have to do the stripping here because of the first line. So 536 * it's done twice for the subsequent lines. No big deal 537 */ 538 http_conn_trimright(conn); 539 if (conn->buflen == 0) 540 return (hdr_end); 541 542 /* Copy the line to the headerbuf */ 543 if (hbuf->bufsize < conn->buflen + 1) { 544 if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL) 545 return (hdr_syserror); 546 hbuf->bufsize = conn->buflen + 1; 547 } 548 strcpy(hbuf->buf, conn->buf); 549 hbuf->buflen = conn->buflen; 550 551 /* 552 * Fetch possible continuation lines. Stop at 1st non-continuation 553 * and leave it in the conn buffer 554 */ 555 for (i = 0; i < HTTP_MAX_CONT_LINES; i++) { 556 if (fetch_getln(conn) == -1) 557 return (hdr_syserror); 558 559 /* 560 * Note: we carry on the idea from the previous version 561 * that a pure whitespace line is equivalent to an empty 562 * one (so it's not continuation and will be handled when 563 * we are called next) 564 */ 565 http_conn_trimright(conn); 566 if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0]) 567 break; 568 569 /* Got a continuation line. Concatenate to previous */ 570 len = hbuf->buflen + conn->buflen; 571 if (hbuf->bufsize < len + 1) { 572 len *= 2; 573 if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL) 574 return (hdr_syserror); 575 hbuf->bufsize = len + 1; 576 } 577 strcpy(hbuf->buf + hbuf->buflen, conn->buf); 578 hbuf->buflen += conn->buflen; 579 } 580 581 /* 582 * We could check for malformed headers but we don't really care. 583 * A valid header starts with a token immediately followed by a 584 * colon; a token is any sequence of non-control, non-whitespace 585 * characters except "()<>@,;:\\\"{}". 586 */ 587 for (i = 0; hdr_names[i].num != hdr_unknown; i++) 588 if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL) 589 return (hdr_names[i].num); 590 591 return (hdr_unknown); 592 } 593 594 /************************** 595 * [Proxy-]Authenticate header parsing 596 */ 597 598 /* 599 * Read doublequote-delimited string into output buffer obuf (allocated 600 * by caller, whose responsibility it is to ensure that it's big enough) 601 * cp points to the first char after the initial '"' 602 * Handles \ quoting 603 * Returns pointer to the first char after the terminating double quote, or 604 * NULL for error. 605 */ 606 static const char * 607 http_parse_headerstring(const char *cp, char *obuf) 608 { 609 for (;;) { 610 switch (*cp) { 611 case 0: /* Unterminated string */ 612 *obuf = 0; 613 return (NULL); 614 case '"': /* Ending quote */ 615 *obuf = 0; 616 return (++cp); 617 case '\\': 618 if (*++cp == 0) { 619 *obuf = 0; 620 return (NULL); 621 } 622 /* FALLTHROUGH */ 623 default: 624 *obuf++ = *cp++; 625 } 626 } 627 } 628 629 /* Http auth challenge schemes */ 630 typedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t; 631 632 /* Data holder for a Basic or Digest challenge. */ 633 typedef struct { 634 http_auth_schemes_t scheme; 635 char *realm; 636 char *qop; 637 char *nonce; 638 char *opaque; 639 char *algo; 640 int stale; 641 int nc; /* Nonce count */ 642 } http_auth_challenge_t; 643 644 static void 645 init_http_auth_challenge(http_auth_challenge_t *b) 646 { 647 b->scheme = HTTPAS_UNKNOWN; 648 b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL; 649 b->stale = b->nc = 0; 650 } 651 652 static void 653 clean_http_auth_challenge(http_auth_challenge_t *b) 654 { 655 if (b->realm) 656 free(b->realm); 657 if (b->qop) 658 free(b->qop); 659 if (b->nonce) 660 free(b->nonce); 661 if (b->opaque) 662 free(b->opaque); 663 if (b->algo) 664 free(b->algo); 665 init_http_auth_challenge(b); 666 } 667 668 /* Data holder for an array of challenges offered in an http response. */ 669 #define MAX_CHALLENGES 10 670 typedef struct { 671 http_auth_challenge_t *challenges[MAX_CHALLENGES]; 672 int count; /* Number of parsed challenges in the array */ 673 int valid; /* We did parse an authenticate header */ 674 } http_auth_challenges_t; 675 676 static void 677 init_http_auth_challenges(http_auth_challenges_t *cs) 678 { 679 int i; 680 for (i = 0; i < MAX_CHALLENGES; i++) 681 cs->challenges[i] = NULL; 682 cs->count = cs->valid = 0; 683 } 684 685 static void 686 clean_http_auth_challenges(http_auth_challenges_t *cs) 687 { 688 int i; 689 /* We rely on non-zero pointers being allocated, not on the count */ 690 for (i = 0; i < MAX_CHALLENGES; i++) { 691 if (cs->challenges[i] != NULL) { 692 clean_http_auth_challenge(cs->challenges[i]); 693 free(cs->challenges[i]); 694 } 695 } 696 init_http_auth_challenges(cs); 697 } 698 699 /* 700 * Enumeration for lexical elements. Separators will be returned as their own 701 * ascii value 702 */ 703 typedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258, 704 HTTPHL_ERROR = 259} http_header_lex_t; 705 706 /* 707 * Determine what kind of token comes next and return possible value 708 * in buf, which is supposed to have been allocated big enough by 709 * caller. Advance input pointer and return element type. 710 */ 711 static int 712 http_header_lex(const char **cpp, char *buf) 713 { 714 size_t l; 715 /* Eat initial whitespace */ 716 *cpp += strspn(*cpp, " \t"); 717 if (**cpp == 0) 718 return (HTTPHL_END); 719 720 /* Separator ? */ 721 if (**cpp == ',' || **cpp == '=') 722 return (*((*cpp)++)); 723 724 /* String ? */ 725 if (**cpp == '"') { 726 *cpp = http_parse_headerstring(++*cpp, buf); 727 if (*cpp == NULL) 728 return (HTTPHL_ERROR); 729 return (HTTPHL_STRING); 730 } 731 732 /* Read other token, until separator or whitespace */ 733 l = strcspn(*cpp, " \t,="); 734 memcpy(buf, *cpp, l); 735 buf[l] = 0; 736 *cpp += l; 737 return (HTTPHL_WORD); 738 } 739 740 /* 741 * Read challenges from http xxx-authenticate header and accumulate them 742 * in the challenges list structure. 743 * 744 * Headers with multiple challenges are specified by rfc2617, but 745 * servers (ie: squid) often send them in separate headers instead, 746 * which in turn is forbidden by the http spec (multiple headers with 747 * the same name are only allowed for pure comma-separated lists, see 748 * rfc2616 sec 4.2). 749 * 750 * We support both approaches anyway 751 */ 752 static int 753 http_parse_authenticate(const char *cp, http_auth_challenges_t *cs) 754 { 755 int ret = -1; 756 http_header_lex_t lex; 757 char *key = malloc(strlen(cp) + 1); 758 char *value = malloc(strlen(cp) + 1); 759 char *buf = malloc(strlen(cp) + 1); 760 761 if (key == NULL || value == NULL || buf == NULL) { 762 fetch_syserr(); 763 goto out; 764 } 765 766 /* In any case we've seen the header and we set the valid bit */ 767 cs->valid = 1; 768 769 /* Need word first */ 770 lex = http_header_lex(&cp, key); 771 if (lex != HTTPHL_WORD) 772 goto out; 773 774 /* Loop on challenges */ 775 for (; cs->count < MAX_CHALLENGES; cs->count++) { 776 cs->challenges[cs->count] = 777 malloc(sizeof(http_auth_challenge_t)); 778 if (cs->challenges[cs->count] == NULL) { 779 fetch_syserr(); 780 goto out; 781 } 782 init_http_auth_challenge(cs->challenges[cs->count]); 783 if (!strcasecmp(key, "basic")) { 784 cs->challenges[cs->count]->scheme = HTTPAS_BASIC; 785 } else if (!strcasecmp(key, "digest")) { 786 cs->challenges[cs->count]->scheme = HTTPAS_DIGEST; 787 } else { 788 cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN; 789 /* 790 * Continue parsing as basic or digest may 791 * follow, and the syntax is the same for 792 * all. We'll just ignore this one when 793 * looking at the list 794 */ 795 } 796 797 /* Loop on attributes */ 798 for (;;) { 799 /* Key */ 800 lex = http_header_lex(&cp, key); 801 if (lex != HTTPHL_WORD) 802 goto out; 803 804 /* Equal sign */ 805 lex = http_header_lex(&cp, buf); 806 if (lex != '=') 807 goto out; 808 809 /* Value */ 810 lex = http_header_lex(&cp, value); 811 if (lex != HTTPHL_WORD && lex != HTTPHL_STRING) 812 goto out; 813 814 if (!strcasecmp(key, "realm")) 815 cs->challenges[cs->count]->realm = 816 strdup(value); 817 else if (!strcasecmp(key, "qop")) 818 cs->challenges[cs->count]->qop = 819 strdup(value); 820 else if (!strcasecmp(key, "nonce")) 821 cs->challenges[cs->count]->nonce = 822 strdup(value); 823 else if (!strcasecmp(key, "opaque")) 824 cs->challenges[cs->count]->opaque = 825 strdup(value); 826 else if (!strcasecmp(key, "algorithm")) 827 cs->challenges[cs->count]->algo = 828 strdup(value); 829 else if (!strcasecmp(key, "stale")) 830 cs->challenges[cs->count]->stale = 831 strcasecmp(value, "no"); 832 /* Else ignore unknown attributes */ 833 834 /* Comma or Next challenge or End */ 835 lex = http_header_lex(&cp, key); 836 /* 837 * If we get a word here, this is the beginning of the 838 * next challenge. Break the attributes loop 839 */ 840 if (lex == HTTPHL_WORD) 841 break; 842 843 if (lex == HTTPHL_END) { 844 /* End while looking for ',' is normal exit */ 845 cs->count++; 846 ret = 0; 847 goto out; 848 } 849 /* Anything else is an error */ 850 if (lex != ',') 851 goto out; 852 853 } /* End attributes loop */ 854 } /* End challenge loop */ 855 856 /* 857 * Challenges max count exceeded. This really can't happen 858 * with normal data, something's fishy -> error 859 */ 860 861 out: 862 if (key) 863 free(key); 864 if (value) 865 free(value); 866 if (buf) 867 free(buf); 868 return (ret); 869 } 870 871 872 /* 873 * Parse a last-modified header 874 */ 875 static int 876 http_parse_mtime(const char *p, time_t *mtime) 877 { 878 char locale[64], *r; 879 struct tm tm; 880 881 strlcpy(locale, setlocale(LC_TIME, NULL), sizeof(locale)); 882 setlocale(LC_TIME, "C"); 883 r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm); 884 /* 885 * Some proxies use UTC in response, but it should still be 886 * parsed. RFC2616 states GMT and UTC are exactly equal for HTTP. 887 */ 888 if (r == NULL) 889 r = strptime(p, "%a, %d %b %Y %H:%M:%S UTC", &tm); 890 /* XXX should add support for date-2 and date-3 */ 891 setlocale(LC_TIME, locale); 892 if (r == NULL) 893 return (-1); 894 DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d " 895 "%02d:%02d:%02d]\n", 896 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 897 tm.tm_hour, tm.tm_min, tm.tm_sec)); 898 *mtime = timegm(&tm); 899 return (0); 900 } 901 902 /* 903 * Parse a content-length header 904 */ 905 static int 906 http_parse_length(const char *p, off_t *length) 907 { 908 off_t len; 909 910 for (len = 0; *p && isdigit((unsigned char)*p); ++p) 911 len = len * 10 + (*p - '0'); 912 if (*p) 913 return (-1); 914 DEBUG(fprintf(stderr, "content length: [%lld]\n", 915 (long long)len)); 916 *length = len; 917 return (0); 918 } 919 920 /* 921 * Parse a content-range header 922 */ 923 static int 924 http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size) 925 { 926 off_t first, last, len; 927 928 if (strncasecmp(p, "bytes ", 6) != 0) 929 return (-1); 930 p += 6; 931 if (*p == '*') { 932 first = last = -1; 933 ++p; 934 } else { 935 for (first = 0; *p && isdigit((unsigned char)*p); ++p) 936 first = first * 10 + *p - '0'; 937 if (*p != '-') 938 return (-1); 939 for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p) 940 last = last * 10 + *p - '0'; 941 } 942 if (first > last || *p != '/') 943 return (-1); 944 for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p) 945 len = len * 10 + *p - '0'; 946 if (*p || len < last - first + 1) 947 return (-1); 948 if (first == -1) { 949 DEBUG(fprintf(stderr, "content range: [*/%lld]\n", 950 (long long)len)); 951 *length = 0; 952 } else { 953 DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n", 954 (long long)first, (long long)last, (long long)len)); 955 *length = last - first + 1; 956 } 957 *offset = first; 958 *size = len; 959 return (0); 960 } 961 962 963 /***************************************************************************** 964 * Helper functions for authorization 965 */ 966 967 /* 968 * Base64 encoding 969 */ 970 static char * 971 http_base64(const char *src) 972 { 973 static const char base64[] = 974 "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 975 "abcdefghijklmnopqrstuvwxyz" 976 "0123456789+/"; 977 char *str, *dst; 978 size_t l; 979 int t, r; 980 981 l = strlen(src); 982 if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL) 983 return (NULL); 984 dst = str; 985 r = 0; 986 987 while (l >= 3) { 988 t = (src[0] << 16) | (src[1] << 8) | src[2]; 989 dst[0] = base64[(t >> 18) & 0x3f]; 990 dst[1] = base64[(t >> 12) & 0x3f]; 991 dst[2] = base64[(t >> 6) & 0x3f]; 992 dst[3] = base64[(t >> 0) & 0x3f]; 993 src += 3; l -= 3; 994 dst += 4; r += 4; 995 } 996 997 switch (l) { 998 case 2: 999 t = (src[0] << 16) | (src[1] << 8); 1000 dst[0] = base64[(t >> 18) & 0x3f]; 1001 dst[1] = base64[(t >> 12) & 0x3f]; 1002 dst[2] = base64[(t >> 6) & 0x3f]; 1003 dst[3] = '='; 1004 dst += 4; 1005 r += 4; 1006 break; 1007 case 1: 1008 t = src[0] << 16; 1009 dst[0] = base64[(t >> 18) & 0x3f]; 1010 dst[1] = base64[(t >> 12) & 0x3f]; 1011 dst[2] = dst[3] = '='; 1012 dst += 4; 1013 r += 4; 1014 break; 1015 case 0: 1016 break; 1017 } 1018 1019 *dst = 0; 1020 return (str); 1021 } 1022 1023 1024 /* 1025 * Extract authorization parameters from environment value. 1026 * The value is like scheme:realm:user:pass 1027 */ 1028 typedef struct { 1029 char *scheme; 1030 char *realm; 1031 char *user; 1032 char *password; 1033 } http_auth_params_t; 1034 1035 static void 1036 init_http_auth_params(http_auth_params_t *s) 1037 { 1038 s->scheme = s->realm = s->user = s->password = NULL; 1039 } 1040 1041 static void 1042 clean_http_auth_params(http_auth_params_t *s) 1043 { 1044 if (s->scheme) 1045 free(s->scheme); 1046 if (s->realm) 1047 free(s->realm); 1048 if (s->user) 1049 free(s->user); 1050 if (s->password) 1051 free(s->password); 1052 init_http_auth_params(s); 1053 } 1054 1055 static int 1056 http_authfromenv(const char *p, http_auth_params_t *parms) 1057 { 1058 int ret = -1; 1059 char *v, *ve; 1060 char *str = strdup(p); 1061 1062 if (str == NULL) { 1063 fetch_syserr(); 1064 return (-1); 1065 } 1066 v = str; 1067 1068 if ((ve = strchr(v, ':')) == NULL) 1069 goto out; 1070 1071 *ve = 0; 1072 if ((parms->scheme = strdup(v)) == NULL) { 1073 fetch_syserr(); 1074 goto out; 1075 } 1076 v = ve + 1; 1077 1078 if ((ve = strchr(v, ':')) == NULL) 1079 goto out; 1080 1081 *ve = 0; 1082 if ((parms->realm = strdup(v)) == NULL) { 1083 fetch_syserr(); 1084 goto out; 1085 } 1086 v = ve + 1; 1087 1088 if ((ve = strchr(v, ':')) == NULL) 1089 goto out; 1090 1091 *ve = 0; 1092 if ((parms->user = strdup(v)) == NULL) { 1093 fetch_syserr(); 1094 goto out; 1095 } 1096 v = ve + 1; 1097 1098 1099 if ((parms->password = strdup(v)) == NULL) { 1100 fetch_syserr(); 1101 goto out; 1102 } 1103 ret = 0; 1104 out: 1105 if (ret == -1) 1106 clean_http_auth_params(parms); 1107 if (str) 1108 free(str); 1109 return (ret); 1110 } 1111 1112 1113 /* 1114 * Digest response: the code to compute the digest is taken from the 1115 * sample implementation in RFC2616 1116 */ 1117 #define IN const 1118 #define OUT 1119 1120 #define HASHLEN 16 1121 typedef char HASH[HASHLEN]; 1122 #define HASHHEXLEN 32 1123 typedef char HASHHEX[HASHHEXLEN+1]; 1124 1125 static const char *hexchars = "0123456789abcdef"; 1126 static void 1127 CvtHex(IN HASH Bin, OUT HASHHEX Hex) 1128 { 1129 unsigned short i; 1130 unsigned char j; 1131 1132 for (i = 0; i < HASHLEN; i++) { 1133 j = (Bin[i] >> 4) & 0xf; 1134 Hex[i*2] = hexchars[j]; 1135 j = Bin[i] & 0xf; 1136 Hex[i*2+1] = hexchars[j]; 1137 } 1138 Hex[HASHHEXLEN] = '\0'; 1139 }; 1140 1141 /* calculate H(A1) as per spec */ 1142 static void 1143 DigestCalcHA1( 1144 IN char * pszAlg, 1145 IN char * pszUserName, 1146 IN char * pszRealm, 1147 IN char * pszPassword, 1148 IN char * pszNonce, 1149 IN char * pszCNonce, 1150 OUT HASHHEX SessionKey 1151 ) 1152 { 1153 MD5_CTX Md5Ctx; 1154 HASH HA1; 1155 1156 MD5Init(&Md5Ctx); 1157 MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName)); 1158 MD5Update(&Md5Ctx, ":", 1); 1159 MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm)); 1160 MD5Update(&Md5Ctx, ":", 1); 1161 MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword)); 1162 MD5Final(HA1, &Md5Ctx); 1163 if (strcasecmp(pszAlg, "md5-sess") == 0) { 1164 1165 MD5Init(&Md5Ctx); 1166 MD5Update(&Md5Ctx, HA1, HASHLEN); 1167 MD5Update(&Md5Ctx, ":", 1); 1168 MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce)); 1169 MD5Update(&Md5Ctx, ":", 1); 1170 MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce)); 1171 MD5Final(HA1, &Md5Ctx); 1172 } 1173 CvtHex(HA1, SessionKey); 1174 } 1175 1176 /* calculate request-digest/response-digest as per HTTP Digest spec */ 1177 static void 1178 DigestCalcResponse( 1179 IN HASHHEX HA1, /* H(A1) */ 1180 IN char * pszNonce, /* nonce from server */ 1181 IN char * pszNonceCount, /* 8 hex digits */ 1182 IN char * pszCNonce, /* client nonce */ 1183 IN char * pszQop, /* qop-value: "", "auth", "auth-int" */ 1184 IN char * pszMethod, /* method from the request */ 1185 IN char * pszDigestUri, /* requested URL */ 1186 IN HASHHEX HEntity, /* H(entity body) if qop="auth-int" */ 1187 OUT HASHHEX Response /* request-digest or response-digest */ 1188 ) 1189 { 1190 /* DEBUG(fprintf(stderr, 1191 "Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n", 1192 HA1, pszNonce, pszQop, pszMethod, pszDigestUri));*/ 1193 MD5_CTX Md5Ctx; 1194 HASH HA2; 1195 HASH RespHash; 1196 HASHHEX HA2Hex; 1197 1198 // calculate H(A2) 1199 MD5Init(&Md5Ctx); 1200 MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod)); 1201 MD5Update(&Md5Ctx, ":", 1); 1202 MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri)); 1203 if (strcasecmp(pszQop, "auth-int") == 0) { 1204 MD5Update(&Md5Ctx, ":", 1); 1205 MD5Update(&Md5Ctx, HEntity, HASHHEXLEN); 1206 } 1207 MD5Final(HA2, &Md5Ctx); 1208 CvtHex(HA2, HA2Hex); 1209 1210 // calculate response 1211 MD5Init(&Md5Ctx); 1212 MD5Update(&Md5Ctx, HA1, HASHHEXLEN); 1213 MD5Update(&Md5Ctx, ":", 1); 1214 MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce)); 1215 MD5Update(&Md5Ctx, ":", 1); 1216 if (*pszQop) { 1217 MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount)); 1218 MD5Update(&Md5Ctx, ":", 1); 1219 MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce)); 1220 MD5Update(&Md5Ctx, ":", 1); 1221 MD5Update(&Md5Ctx, pszQop, strlen(pszQop)); 1222 MD5Update(&Md5Ctx, ":", 1); 1223 } 1224 MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN); 1225 MD5Final(RespHash, &Md5Ctx); 1226 CvtHex(RespHash, Response); 1227 } 1228 1229 /* 1230 * Generate/Send a Digest authorization header 1231 * This looks like: [Proxy-]Authorization: credentials 1232 * 1233 * credentials = "Digest" digest-response 1234 * digest-response = 1#( username | realm | nonce | digest-uri 1235 * | response | [ algorithm ] | [cnonce] | 1236 * [opaque] | [message-qop] | 1237 * [nonce-count] | [auth-param] ) 1238 * username = "username" "=" username-value 1239 * username-value = quoted-string 1240 * digest-uri = "uri" "=" digest-uri-value 1241 * digest-uri-value = request-uri ; As specified by HTTP/1.1 1242 * message-qop = "qop" "=" qop-value 1243 * cnonce = "cnonce" "=" cnonce-value 1244 * cnonce-value = nonce-value 1245 * nonce-count = "nc" "=" nc-value 1246 * nc-value = 8LHEX 1247 * response = "response" "=" request-digest 1248 * request-digest = <"> 32LHEX <"> 1249 */ 1250 static int 1251 http_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c, 1252 http_auth_params_t *parms, struct url *url) 1253 { 1254 int r; 1255 char noncecount[10]; 1256 char cnonce[40]; 1257 char *options = NULL; 1258 1259 if (!c->realm || !c->nonce) { 1260 DEBUG(fprintf(stderr, "realm/nonce not set in challenge\n")); 1261 return(-1); 1262 } 1263 if (!c->algo) 1264 c->algo = strdup(""); 1265 1266 if (asprintf(&options, "%s%s%s%s", 1267 *c->algo? ",algorithm=" : "", c->algo, 1268 c->opaque? ",opaque=" : "", c->opaque?c->opaque:"")== -1) 1269 return (-1); 1270 1271 if (!c->qop) { 1272 c->qop = strdup(""); 1273 *noncecount = 0; 1274 *cnonce = 0; 1275 } else { 1276 c->nc++; 1277 sprintf(noncecount, "%08x", c->nc); 1278 /* We don't try very hard with the cnonce ... */ 1279 sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0)); 1280 } 1281 1282 HASHHEX HA1; 1283 DigestCalcHA1(c->algo, parms->user, c->realm, 1284 parms->password, c->nonce, cnonce, HA1); 1285 DEBUG(fprintf(stderr, "HA1: [%s]\n", HA1)); 1286 HASHHEX digest; 1287 DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop, 1288 "GET", url->doc, "", digest); 1289 1290 if (c->qop[0]) { 1291 r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\"," 1292 "nonce=\"%s\",uri=\"%s\",response=\"%s\"," 1293 "qop=\"auth\", cnonce=\"%s\", nc=%s%s", 1294 hdr, parms->user, c->realm, 1295 c->nonce, url->doc, digest, 1296 cnonce, noncecount, options); 1297 } else { 1298 r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\"," 1299 "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s", 1300 hdr, parms->user, c->realm, 1301 c->nonce, url->doc, digest, options); 1302 } 1303 if (options) 1304 free(options); 1305 return (r); 1306 } 1307 1308 /* 1309 * Encode username and password 1310 */ 1311 static int 1312 http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd) 1313 { 1314 char *upw, *auth; 1315 int r; 1316 1317 DEBUG(fprintf(stderr, "basic: usr: [%s]\n", usr)); 1318 DEBUG(fprintf(stderr, "basic: pwd: [%s]\n", pwd)); 1319 if (asprintf(&upw, "%s:%s", usr, pwd) == -1) 1320 return (-1); 1321 auth = http_base64(upw); 1322 free(upw); 1323 if (auth == NULL) 1324 return (-1); 1325 r = http_cmd(conn, "%s: Basic %s", hdr, auth); 1326 free(auth); 1327 return (r); 1328 } 1329 1330 /* 1331 * Chose the challenge to answer and call the appropriate routine to 1332 * produce the header. 1333 */ 1334 static int 1335 http_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs, 1336 http_auth_params_t *parms, struct url *url) 1337 { 1338 http_auth_challenge_t *digest = NULL; 1339 int i; 1340 1341 /* If user or pass are null we're not happy */ 1342 if (!parms->user || !parms->password) { 1343 DEBUG(fprintf(stderr, "NULL usr or pass\n")); 1344 return (-1); 1345 } 1346 1347 /* Look for a Digest */ 1348 for (i = 0; i < cs->count; i++) { 1349 if (cs->challenges[i]->scheme == HTTPAS_DIGEST) 1350 digest = cs->challenges[i]; 1351 } 1352 1353 /* Error if "Digest" was specified and there is no Digest challenge */ 1354 if (!digest && (parms->scheme && 1355 !strcasecmp(parms->scheme, "digest"))) { 1356 DEBUG(fprintf(stderr, 1357 "Digest auth in env, not supported by peer\n")); 1358 return (-1); 1359 } 1360 /* 1361 * If "basic" was specified in the environment, or there is no Digest 1362 * challenge, do the basic thing. Don't need a challenge for this, 1363 * so no need to check basic!=NULL 1364 */ 1365 if (!digest || (parms->scheme && !strcasecmp(parms->scheme,"basic"))) 1366 return (http_basic_auth(conn,hdr,parms->user,parms->password)); 1367 1368 /* Else, prefer digest. We just checked that it's not NULL */ 1369 return (http_digest_auth(conn, hdr, digest, parms, url)); 1370 } 1371 1372 /***************************************************************************** 1373 * Helper functions for connecting to a server or proxy 1374 */ 1375 1376 /* 1377 * Connect to the correct HTTP server or proxy. 1378 */ 1379 static conn_t * 1380 http_connect(struct url *URL, struct url *purl, const char *flags) 1381 { 1382 struct url *curl; 1383 conn_t *conn; 1384 hdr_t h; 1385 http_headerbuf_t headerbuf; 1386 const char *p; 1387 int verbose; 1388 int af, val; 1389 int serrno; 1390 1391 #ifdef INET6 1392 af = AF_UNSPEC; 1393 #else 1394 af = AF_INET; 1395 #endif 1396 1397 verbose = CHECK_FLAG('v'); 1398 if (CHECK_FLAG('4')) 1399 af = AF_INET; 1400 #ifdef INET6 1401 else if (CHECK_FLAG('6')) 1402 af = AF_INET6; 1403 #endif 1404 1405 curl = (purl != NULL) ? purl : URL; 1406 1407 if ((conn = fetch_connect(curl->host, curl->port, af, verbose)) == NULL) 1408 /* fetch_connect() has already set an error code */ 1409 return (NULL); 1410 init_http_headerbuf(&headerbuf); 1411 if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 && purl) { 1412 http_cmd(conn, "CONNECT %s:%d HTTP/1.1", 1413 URL->host, URL->port); 1414 http_cmd(conn, "Host: %s:%d", 1415 URL->host, URL->port); 1416 http_cmd(conn, ""); 1417 if (http_get_reply(conn) != HTTP_OK) { 1418 http_seterr(conn->err); 1419 goto ouch; 1420 } 1421 /* Read and discard the rest of the proxy response */ 1422 if (fetch_getln(conn) < 0) { 1423 fetch_syserr(); 1424 goto ouch; 1425 } 1426 do { 1427 switch ((h = http_next_header(conn, &headerbuf, &p))) { 1428 case hdr_syserror: 1429 fetch_syserr(); 1430 goto ouch; 1431 case hdr_error: 1432 http_seterr(HTTP_PROTOCOL_ERROR); 1433 goto ouch; 1434 default: 1435 /* ignore */ ; 1436 } 1437 } while (h > hdr_end); 1438 } 1439 if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 && 1440 fetch_ssl(conn, URL, verbose) == -1) { 1441 /* grrr */ 1442 errno = EAUTH; 1443 fetch_syserr(); 1444 goto ouch; 1445 } 1446 1447 val = 1; 1448 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val)); 1449 1450 clean_http_headerbuf(&headerbuf); 1451 return (conn); 1452 ouch: 1453 serrno = errno; 1454 clean_http_headerbuf(&headerbuf); 1455 fetch_close(conn); 1456 errno = serrno; 1457 return (NULL); 1458 } 1459 1460 static struct url * 1461 http_get_proxy(struct url * url, const char *flags) 1462 { 1463 struct url *purl; 1464 char *p; 1465 1466 if (flags != NULL && strchr(flags, 'd') != NULL) 1467 return (NULL); 1468 if (fetch_no_proxy_match(url->host)) 1469 return (NULL); 1470 if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 1471 *p && (purl = fetchParseURL(p))) { 1472 if (!*purl->scheme) 1473 strcpy(purl->scheme, SCHEME_HTTP); 1474 if (!purl->port) 1475 purl->port = fetch_default_proxy_port(purl->scheme); 1476 if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 1477 return (purl); 1478 fetchFreeURL(purl); 1479 } 1480 return (NULL); 1481 } 1482 1483 static void 1484 http_print_html(FILE *out, FILE *in) 1485 { 1486 size_t len; 1487 char *line, *p, *q; 1488 int comment, tag; 1489 1490 comment = tag = 0; 1491 while ((line = fgetln(in, &len)) != NULL) { 1492 while (len && isspace((unsigned char)line[len - 1])) 1493 --len; 1494 for (p = q = line; q < line + len; ++q) { 1495 if (comment && *q == '-') { 1496 if (q + 2 < line + len && 1497 strcmp(q, "-->") == 0) { 1498 tag = comment = 0; 1499 q += 2; 1500 } 1501 } else if (tag && !comment && *q == '>') { 1502 p = q + 1; 1503 tag = 0; 1504 } else if (!tag && *q == '<') { 1505 if (q > p) 1506 fwrite(p, q - p, 1, out); 1507 tag = 1; 1508 if (q + 3 < line + len && 1509 strcmp(q, "<!--") == 0) { 1510 comment = 1; 1511 q += 3; 1512 } 1513 } 1514 } 1515 if (!tag && q > p) 1516 fwrite(p, q - p, 1, out); 1517 fputc('\n', out); 1518 } 1519 } 1520 1521 1522 /***************************************************************************** 1523 * Core 1524 */ 1525 1526 FILE * 1527 http_request(struct url *URL, const char *op, struct url_stat *us, 1528 struct url *purl, const char *flags) 1529 { 1530 1531 return (http_request_body(URL, op, us, purl, flags, NULL, NULL)); 1532 } 1533 1534 /* 1535 * Send a request and process the reply 1536 * 1537 * XXX This function is way too long, the do..while loop should be split 1538 * XXX off into a separate function. 1539 */ 1540 FILE * 1541 http_request_body(struct url *URL, const char *op, struct url_stat *us, 1542 struct url *purl, const char *flags, const char *content_type, 1543 const char *body) 1544 { 1545 char timebuf[80]; 1546 char hbuf[MAXHOSTNAMELEN + 7], *host; 1547 conn_t *conn; 1548 struct url *url, *new; 1549 int chunked, direct, ims, noredirect, verbose; 1550 int e, i, n, val; 1551 off_t offset, clength, length, size; 1552 time_t mtime; 1553 const char *p; 1554 FILE *f; 1555 hdr_t h; 1556 struct tm *timestruct; 1557 http_headerbuf_t headerbuf; 1558 http_auth_challenges_t server_challenges; 1559 http_auth_challenges_t proxy_challenges; 1560 size_t body_len; 1561 1562 /* The following calls don't allocate anything */ 1563 init_http_headerbuf(&headerbuf); 1564 init_http_auth_challenges(&server_challenges); 1565 init_http_auth_challenges(&proxy_challenges); 1566 1567 direct = CHECK_FLAG('d'); 1568 noredirect = CHECK_FLAG('A'); 1569 verbose = CHECK_FLAG('v'); 1570 ims = CHECK_FLAG('i'); 1571 1572 if (direct && purl) { 1573 fetchFreeURL(purl); 1574 purl = NULL; 1575 } 1576 1577 /* try the provided URL first */ 1578 url = URL; 1579 1580 n = MAX_REDIRECT; 1581 i = 0; 1582 1583 e = HTTP_PROTOCOL_ERROR; 1584 do { 1585 new = NULL; 1586 chunked = 0; 1587 offset = 0; 1588 clength = -1; 1589 length = -1; 1590 size = -1; 1591 mtime = 0; 1592 1593 /* check port */ 1594 if (!url->port) 1595 url->port = fetch_default_port(url->scheme); 1596 1597 /* were we redirected to an FTP URL? */ 1598 if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) { 1599 if (strcmp(op, "GET") == 0) 1600 return (ftp_request(url, "RETR", us, purl, flags)); 1601 else if (strcmp(op, "HEAD") == 0) 1602 return (ftp_request(url, "STAT", us, purl, flags)); 1603 } 1604 1605 /* connect to server or proxy */ 1606 if ((conn = http_connect(url, purl, flags)) == NULL) 1607 goto ouch; 1608 1609 /* append port number only if necessary */ 1610 host = url->host; 1611 if (url->port != fetch_default_port(url->scheme)) { 1612 snprintf(hbuf, sizeof(hbuf), "%s:%d", host, url->port); 1613 host = hbuf; 1614 } 1615 1616 /* send request */ 1617 if (verbose) 1618 fetch_info("requesting %s://%s%s", 1619 url->scheme, host, url->doc); 1620 if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) { 1621 http_cmd(conn, "%s %s://%s%s HTTP/1.1", 1622 op, url->scheme, host, url->doc); 1623 } else { 1624 http_cmd(conn, "%s %s HTTP/1.1", 1625 op, url->doc); 1626 } 1627 1628 if (ims && url->ims_time) { 1629 timestruct = gmtime((time_t *)&url->ims_time); 1630 (void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT", 1631 timestruct); 1632 if (verbose) 1633 fetch_info("If-Modified-Since: %s", timebuf); 1634 http_cmd(conn, "If-Modified-Since: %s", timebuf); 1635 } 1636 /* virtual host */ 1637 http_cmd(conn, "Host: %s", host); 1638 1639 /* 1640 * Proxy authorization: we only send auth after we received 1641 * a 407 error. We do not first try basic anyway (changed 1642 * when support was added for digest-auth) 1643 */ 1644 if (purl && proxy_challenges.valid) { 1645 http_auth_params_t aparams; 1646 init_http_auth_params(&aparams); 1647 if (*purl->user || *purl->pwd) { 1648 aparams.user = strdup(purl->user); 1649 aparams.password = strdup(purl->pwd); 1650 } else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && 1651 *p != '\0') { 1652 if (http_authfromenv(p, &aparams) < 0) { 1653 http_seterr(HTTP_NEED_PROXY_AUTH); 1654 goto ouch; 1655 } 1656 } else if (fetch_netrc_auth(purl) == 0) { 1657 aparams.user = strdup(purl->user); 1658 aparams.password = strdup(purl->pwd); 1659 } 1660 http_authorize(conn, "Proxy-Authorization", 1661 &proxy_challenges, &aparams, url); 1662 clean_http_auth_params(&aparams); 1663 } 1664 1665 /* 1666 * Server authorization: we never send "a priori" 1667 * Basic auth, which used to be done if user/pass were 1668 * set in the url. This would be weird because we'd send the 1669 * password in the clear even if Digest is finally to be 1670 * used (it would have made more sense for the 1671 * pre-digest version to do this when Basic was specified 1672 * in the environment) 1673 */ 1674 if (server_challenges.valid) { 1675 http_auth_params_t aparams; 1676 init_http_auth_params(&aparams); 1677 if (*url->user || *url->pwd) { 1678 aparams.user = strdup(url->user); 1679 aparams.password = strdup(url->pwd); 1680 } else if ((p = getenv("HTTP_AUTH")) != NULL && 1681 *p != '\0') { 1682 if (http_authfromenv(p, &aparams) < 0) { 1683 http_seterr(HTTP_NEED_AUTH); 1684 goto ouch; 1685 } 1686 } else if (fetch_netrc_auth(url) == 0) { 1687 aparams.user = strdup(url->user); 1688 aparams.password = strdup(url->pwd); 1689 } else if (fetchAuthMethod && 1690 fetchAuthMethod(url) == 0) { 1691 aparams.user = strdup(url->user); 1692 aparams.password = strdup(url->pwd); 1693 } else { 1694 http_seterr(HTTP_NEED_AUTH); 1695 goto ouch; 1696 } 1697 http_authorize(conn, "Authorization", 1698 &server_challenges, &aparams, url); 1699 clean_http_auth_params(&aparams); 1700 } 1701 1702 /* other headers */ 1703 if ((p = getenv("HTTP_ACCEPT")) != NULL) { 1704 if (*p != '\0') 1705 http_cmd(conn, "Accept: %s", p); 1706 } else { 1707 http_cmd(conn, "Accept: */*"); 1708 } 1709 if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') { 1710 if (strcasecmp(p, "auto") == 0) 1711 http_cmd(conn, "Referer: %s://%s%s", 1712 url->scheme, host, url->doc); 1713 else 1714 http_cmd(conn, "Referer: %s", p); 1715 } 1716 if ((p = getenv("HTTP_USER_AGENT")) != NULL) { 1717 /* no User-Agent if defined but empty */ 1718 if (*p != '\0') 1719 http_cmd(conn, "User-Agent: %s", p); 1720 } else { 1721 /* default User-Agent */ 1722 http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, 1723 getprogname()); 1724 } 1725 if (url->offset > 0) 1726 http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset); 1727 http_cmd(conn, "Connection: close"); 1728 1729 if (body) { 1730 body_len = strlen(body); 1731 http_cmd(conn, "Content-Length: %zu", body_len); 1732 if (content_type != NULL) 1733 http_cmd(conn, "Content-Type: %s", content_type); 1734 } 1735 1736 http_cmd(conn, ""); 1737 1738 if (body) 1739 fetch_write(conn, body, body_len); 1740 1741 /* 1742 * Force the queued request to be dispatched. Normally, one 1743 * would do this with shutdown(2) but squid proxies can be 1744 * configured to disallow such half-closed connections. To 1745 * be compatible with such configurations, fiddle with socket 1746 * options to force the pending data to be written. 1747 */ 1748 val = 0; 1749 setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, 1750 sizeof(val)); 1751 val = 1; 1752 setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val, 1753 sizeof(val)); 1754 1755 /* get reply */ 1756 switch (http_get_reply(conn)) { 1757 case HTTP_OK: 1758 case HTTP_PARTIAL: 1759 case HTTP_NOT_MODIFIED: 1760 /* fine */ 1761 break; 1762 case HTTP_MOVED_PERM: 1763 case HTTP_MOVED_TEMP: 1764 case HTTP_TEMP_REDIRECT: 1765 case HTTP_PERM_REDIRECT: 1766 case HTTP_SEE_OTHER: 1767 case HTTP_USE_PROXY: 1768 /* 1769 * Not so fine, but we still have to read the 1770 * headers to get the new location. 1771 */ 1772 break; 1773 case HTTP_NEED_AUTH: 1774 if (server_challenges.valid) { 1775 /* 1776 * We already sent out authorization code, 1777 * so there's nothing more we can do. 1778 */ 1779 http_seterr(conn->err); 1780 goto ouch; 1781 } 1782 /* try again, but send the password this time */ 1783 if (verbose) 1784 fetch_info("server requires authorization"); 1785 break; 1786 case HTTP_NEED_PROXY_AUTH: 1787 if (proxy_challenges.valid) { 1788 /* 1789 * We already sent our proxy 1790 * authorization code, so there's 1791 * nothing more we can do. */ 1792 http_seterr(conn->err); 1793 goto ouch; 1794 } 1795 /* try again, but send the password this time */ 1796 if (verbose) 1797 fetch_info("proxy requires authorization"); 1798 break; 1799 case HTTP_BAD_RANGE: 1800 /* 1801 * This can happen if we ask for 0 bytes because 1802 * we already have the whole file. Consider this 1803 * a success for now, and check sizes later. 1804 */ 1805 break; 1806 case HTTP_PROTOCOL_ERROR: 1807 /* fall through */ 1808 case -1: 1809 fetch_syserr(); 1810 goto ouch; 1811 default: 1812 http_seterr(conn->err); 1813 if (!verbose) 1814 goto ouch; 1815 /* fall through so we can get the full error message */ 1816 } 1817 1818 /* get headers. http_next_header expects one line readahead */ 1819 if (fetch_getln(conn) == -1) { 1820 fetch_syserr(); 1821 goto ouch; 1822 } 1823 do { 1824 switch ((h = http_next_header(conn, &headerbuf, &p))) { 1825 case hdr_syserror: 1826 fetch_syserr(); 1827 goto ouch; 1828 case hdr_error: 1829 http_seterr(HTTP_PROTOCOL_ERROR); 1830 goto ouch; 1831 case hdr_content_length: 1832 http_parse_length(p, &clength); 1833 break; 1834 case hdr_content_range: 1835 http_parse_range(p, &offset, &length, &size); 1836 break; 1837 case hdr_last_modified: 1838 http_parse_mtime(p, &mtime); 1839 break; 1840 case hdr_location: 1841 if (!HTTP_REDIRECT(conn->err)) 1842 break; 1843 /* 1844 * if the A flag is set, we don't follow 1845 * temporary redirects. 1846 */ 1847 if (noredirect && 1848 conn->err != HTTP_MOVED_PERM && 1849 conn->err != HTTP_PERM_REDIRECT && 1850 conn->err != HTTP_USE_PROXY) { 1851 n = 1; 1852 break; 1853 } 1854 if (new) 1855 free(new); 1856 if (verbose) 1857 fetch_info("%d redirect to %s", conn->err, p); 1858 if (*p == '/') 1859 /* absolute path */ 1860 new = fetchMakeURL(url->scheme, url->host, url->port, p, 1861 url->user, url->pwd); 1862 else 1863 new = fetchParseURL(p); 1864 if (new == NULL) { 1865 /* XXX should set an error code */ 1866 DEBUG(fprintf(stderr, "failed to parse new URL\n")); 1867 goto ouch; 1868 } 1869 1870 /* Only copy credentials if the host matches */ 1871 if (!strcmp(new->host, url->host) && !*new->user && !*new->pwd) { 1872 strcpy(new->user, url->user); 1873 strcpy(new->pwd, url->pwd); 1874 } 1875 new->offset = url->offset; 1876 new->length = url->length; 1877 new->ims_time = url->ims_time; 1878 break; 1879 case hdr_transfer_encoding: 1880 /* XXX weak test*/ 1881 chunked = (strcasecmp(p, "chunked") == 0); 1882 break; 1883 case hdr_www_authenticate: 1884 if (conn->err != HTTP_NEED_AUTH) 1885 break; 1886 if (http_parse_authenticate(p, &server_challenges) == 0) 1887 ++n; 1888 break; 1889 case hdr_proxy_authenticate: 1890 if (conn->err != HTTP_NEED_PROXY_AUTH) 1891 break; 1892 if (http_parse_authenticate(p, &proxy_challenges) == 0) 1893 ++n; 1894 break; 1895 case hdr_end: 1896 /* fall through */ 1897 case hdr_unknown: 1898 /* ignore */ 1899 break; 1900 } 1901 } while (h > hdr_end); 1902 1903 /* we need to provide authentication */ 1904 if (conn->err == HTTP_NEED_AUTH || 1905 conn->err == HTTP_NEED_PROXY_AUTH) { 1906 e = conn->err; 1907 if ((conn->err == HTTP_NEED_AUTH && 1908 !server_challenges.valid) || 1909 (conn->err == HTTP_NEED_PROXY_AUTH && 1910 !proxy_challenges.valid)) { 1911 /* 401/7 but no www/proxy-authenticate ?? */ 1912 DEBUG(fprintf(stderr, "401/7 and no auth header\n")); 1913 goto ouch; 1914 } 1915 fetch_close(conn); 1916 conn = NULL; 1917 continue; 1918 } 1919 1920 /* requested range not satisfiable */ 1921 if (conn->err == HTTP_BAD_RANGE) { 1922 if (url->offset > 0 && url->length == 0) { 1923 /* asked for 0 bytes; fake it */ 1924 offset = url->offset; 1925 clength = -1; 1926 conn->err = HTTP_OK; 1927 break; 1928 } else { 1929 http_seterr(conn->err); 1930 goto ouch; 1931 } 1932 } 1933 1934 /* we have a hit or an error */ 1935 if (conn->err == HTTP_OK 1936 || conn->err == HTTP_NOT_MODIFIED 1937 || conn->err == HTTP_PARTIAL 1938 || HTTP_ERROR(conn->err)) 1939 break; 1940 1941 /* all other cases: we got a redirect */ 1942 e = conn->err; 1943 clean_http_auth_challenges(&server_challenges); 1944 fetch_close(conn); 1945 conn = NULL; 1946 if (!new) { 1947 DEBUG(fprintf(stderr, "redirect with no new location\n")); 1948 break; 1949 } 1950 if (url != URL) 1951 fetchFreeURL(url); 1952 url = new; 1953 } while (++i < n); 1954 1955 /* we failed, or ran out of retries */ 1956 if (conn == NULL) { 1957 http_seterr(e); 1958 goto ouch; 1959 } 1960 1961 DEBUG(fprintf(stderr, "offset %lld, length %lld," 1962 " size %lld, clength %lld\n", 1963 (long long)offset, (long long)length, 1964 (long long)size, (long long)clength)); 1965 1966 if (conn->err == HTTP_NOT_MODIFIED) { 1967 http_seterr(HTTP_NOT_MODIFIED); 1968 return (NULL); 1969 } 1970 1971 /* check for inconsistencies */ 1972 if (clength != -1 && length != -1 && clength != length) { 1973 http_seterr(HTTP_PROTOCOL_ERROR); 1974 goto ouch; 1975 } 1976 if (clength == -1) 1977 clength = length; 1978 if (clength != -1) 1979 length = offset + clength; 1980 if (length != -1 && size != -1 && length != size) { 1981 http_seterr(HTTP_PROTOCOL_ERROR); 1982 goto ouch; 1983 } 1984 if (size == -1) 1985 size = length; 1986 1987 /* fill in stats */ 1988 if (us) { 1989 us->size = size; 1990 us->atime = us->mtime = mtime; 1991 } 1992 1993 /* too far? */ 1994 if (URL->offset > 0 && offset > URL->offset) { 1995 http_seterr(HTTP_PROTOCOL_ERROR); 1996 goto ouch; 1997 } 1998 1999 /* report back real offset and size */ 2000 URL->offset = offset; 2001 URL->length = clength; 2002 2003 /* wrap it up in a FILE */ 2004 if ((f = http_funopen(conn, chunked)) == NULL) { 2005 fetch_syserr(); 2006 goto ouch; 2007 } 2008 2009 if (url != URL) 2010 fetchFreeURL(url); 2011 if (purl) 2012 fetchFreeURL(purl); 2013 2014 if (HTTP_ERROR(conn->err)) { 2015 http_print_html(stderr, f); 2016 fclose(f); 2017 f = NULL; 2018 } 2019 clean_http_headerbuf(&headerbuf); 2020 clean_http_auth_challenges(&server_challenges); 2021 clean_http_auth_challenges(&proxy_challenges); 2022 return (f); 2023 2024 ouch: 2025 if (url != URL) 2026 fetchFreeURL(url); 2027 if (purl) 2028 fetchFreeURL(purl); 2029 if (conn != NULL) 2030 fetch_close(conn); 2031 clean_http_headerbuf(&headerbuf); 2032 clean_http_auth_challenges(&server_challenges); 2033 clean_http_auth_challenges(&proxy_challenges); 2034 return (NULL); 2035 } 2036 2037 2038 /***************************************************************************** 2039 * Entry points 2040 */ 2041 2042 /* 2043 * Retrieve and stat a file by HTTP 2044 */ 2045 FILE * 2046 fetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags) 2047 { 2048 return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags)); 2049 } 2050 2051 /* 2052 * Retrieve a file by HTTP 2053 */ 2054 FILE * 2055 fetchGetHTTP(struct url *URL, const char *flags) 2056 { 2057 return (fetchXGetHTTP(URL, NULL, flags)); 2058 } 2059 2060 /* 2061 * Store a file by HTTP 2062 */ 2063 FILE * 2064 fetchPutHTTP(struct url *URL __unused, const char *flags __unused) 2065 { 2066 warnx("fetchPutHTTP(): not implemented"); 2067 return (NULL); 2068 } 2069 2070 /* 2071 * Get an HTTP document's metadata 2072 */ 2073 int 2074 fetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags) 2075 { 2076 FILE *f; 2077 2078 f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags); 2079 if (f == NULL) 2080 return (-1); 2081 fclose(f); 2082 return (0); 2083 } 2084 2085 /* 2086 * List a directory 2087 */ 2088 struct url_ent * 2089 fetchListHTTP(struct url *url __unused, const char *flags __unused) 2090 { 2091 warnx("fetchListHTTP(): not implemented"); 2092 return (NULL); 2093 } 2094 2095 FILE * 2096 fetchReqHTTP(struct url *URL, const char *method, const char *flags, 2097 const char *content_type, const char *body) 2098 { 2099 2100 return (http_request_body(URL, method, NULL, http_get_proxy(URL, flags), 2101 flags, content_type, body)); 2102 } 2103