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