137535Sdes/*- 2262560Sdes * Copyright (c) 2000-2014 Dag-Erling Sm��rgrav 337535Sdes * All rights reserved. 437535Sdes * 537535Sdes * Redistribution and use in source and binary forms, with or without 637535Sdes * modification, are permitted provided that the following conditions 737535Sdes * are met: 837535Sdes * 1. Redistributions of source code must retain the above copyright 937535Sdes * notice, this list of conditions and the following disclaimer 1037535Sdes * in this position and unchanged. 1137535Sdes * 2. Redistributions in binary form must reproduce the above copyright 1237535Sdes * notice, this list of conditions and the following disclaimer in the 1337535Sdes * documentation and/or other materials provided with the distribution. 1437535Sdes * 3. The name of the author may not be used to endorse or promote products 1563012Sdes * derived from this software without specific prior written permission. 1637535Sdes * 1737535Sdes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 1837535Sdes * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 1937535Sdes * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 2037535Sdes * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 2137535Sdes * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 2237535Sdes * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 2337535Sdes * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 2437535Sdes * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 2537535Sdes * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 2637535Sdes * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 2737535Sdes */ 2837535Sdes 2984203Sdillon#include <sys/cdefs.h> 3084203Sdillon__FBSDID("$FreeBSD: stable/10/lib/libfetch/http.c 315904 2017-03-24 14:26:01Z des $"); 3184203Sdillon 3263236Sdes/* 3363236Sdes * The following copyright applies to the base64 code: 3463236Sdes * 3563236Sdes *- 3663236Sdes * Copyright 1997 Massachusetts Institute of Technology 3763236Sdes * 3863236Sdes * Permission to use, copy, modify, and distribute this software and 3963236Sdes * its documentation for any purpose and without fee is hereby 4063236Sdes * granted, provided that both the above copyright notice and this 4163236Sdes * permission notice appear in all copies, that both the above 4263236Sdes * copyright notice and this permission notice appear in all 4363236Sdes * supporting documentation, and that the name of M.I.T. not be used 4463236Sdes * in advertising or publicity pertaining to distribution of the 4563236Sdes * software without specific, written prior permission. M.I.T. makes 4663236Sdes * no representations about the suitability of this software for any 4763236Sdes * purpose. It is provided "as is" without express or implied 4863236Sdes * warranty. 4990267Sdes * 5063236Sdes * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS 5163236Sdes * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, 5263236Sdes * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 5363236Sdes * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT 5463236Sdes * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 5563236Sdes * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 5663236Sdes * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 5763236Sdes * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 5863236Sdes * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 5963236Sdes * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 6063236Sdes * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 6163236Sdes * SUCH DAMAGE. 6263236Sdes */ 6363236Sdes 6437535Sdes#include <sys/param.h> 6560737Sume#include <sys/socket.h> 66186124Smurray#include <sys/time.h> 6737535Sdes 6863012Sdes#include <ctype.h> 6937535Sdes#include <err.h> 7063012Sdes#include <errno.h> 7160376Sdes#include <locale.h> 7260189Sdes#include <netdb.h> 7337608Sdes#include <stdarg.h> 7437535Sdes#include <stdio.h> 7537535Sdes#include <stdlib.h> 7637535Sdes#include <string.h> 7760376Sdes#include <time.h> 7837535Sdes#include <unistd.h> 79240496Sdes 80240496Sdes#ifdef WITH_SSL 81240496Sdes#include <openssl/md5.h> 82240496Sdes#define MD5Init(c) MD5_Init(c) 83240496Sdes#define MD5Update(c, data, len) MD5_Update(c, data, len) 84240496Sdes#define MD5Final(md, c) MD5_Final(md, c) 85240496Sdes#else 86202613Sdes#include <md5.h> 87240496Sdes#endif 8837535Sdes 89141958Skbyanc#include <netinet/in.h> 90141958Skbyanc#include <netinet/tcp.h> 91141958Skbyanc 9237535Sdes#include "fetch.h" 9340939Sdes#include "common.h" 9441862Sdes#include "httperr.h" 9537535Sdes 9663012Sdes/* Maximum number of redirects to follow */ 97241839Seadler#define MAX_REDIRECT 20 9837535Sdes 9963012Sdes/* Symbolic names for reply codes we care about */ 10063012Sdes#define HTTP_OK 200 10163012Sdes#define HTTP_PARTIAL 206 10263012Sdes#define HTTP_MOVED_PERM 301 10363012Sdes#define HTTP_MOVED_TEMP 302 10463012Sdes#define HTTP_SEE_OTHER 303 105186124Smurray#define HTTP_NOT_MODIFIED 304 106241841Seadler#define HTTP_USE_PROXY 305 107169386Sdes#define HTTP_TEMP_REDIRECT 307 108241840Seadler#define HTTP_PERM_REDIRECT 308 10963012Sdes#define HTTP_NEED_AUTH 401 11087317Sdes#define HTTP_NEED_PROXY_AUTH 407 111125696Sdes#define HTTP_BAD_RANGE 416 11263012Sdes#define HTTP_PROTOCOL_ERROR 999 11360196Sdes 11463012Sdes#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \ 11590267Sdes || (xyz) == HTTP_MOVED_TEMP \ 116169386Sdes || (xyz) == HTTP_TEMP_REDIRECT \ 117311864Sdes || (xyz) == HTTP_PERM_REDIRECT \ 118241841Seadler || (xyz) == HTTP_USE_PROXY \ 11990267Sdes || (xyz) == HTTP_SEE_OTHER) 12063012Sdes 121315904Sdes#define HTTP_ERROR(xyz) ((xyz) >= 400 && (xyz) <= 599) 12263012Sdes 12390267Sdes 12463012Sdes/***************************************************************************** 12563012Sdes * I/O functions for decoding chunked streams 12663012Sdes */ 12763012Sdes 12897859Sdesstruct httpio 12937535Sdes{ 13097858Sdes conn_t *conn; /* connection */ 13197866Sdes int chunked; /* chunked mode */ 13297858Sdes char *buf; /* chunk buffer */ 13397866Sdes size_t bufsize; /* size of chunk buffer */ 134294194Sdes size_t buflen; /* amount of data currently in buffer */ 135294194Sdes size_t bufpos; /* current read offset in buffer */ 13697858Sdes int eof; /* end-of-file flag */ 13797858Sdes int error; /* error flag */ 13897858Sdes size_t chunksize; /* remaining size of current chunk */ 13963281Sdes#ifndef NDEBUG 14090267Sdes size_t total; 14163012Sdes#endif 14237535Sdes}; 14337535Sdes 14437608Sdes/* 14563012Sdes * Get next chunk header 14637608Sdes */ 14737608Sdesstatic int 148174588Sdeshttp_new_chunk(struct httpio *io) 14937608Sdes{ 15090267Sdes char *p; 15190267Sdes 152174588Sdes if (fetch_getln(io->conn) == -1) 15390267Sdes return (-1); 15490267Sdes 155174761Sdes if (io->conn->buflen < 2 || !isxdigit((unsigned char)*io->conn->buf)) 15690267Sdes return (-1); 15790267Sdes 158174761Sdes for (p = io->conn->buf; *p && !isspace((unsigned char)*p); ++p) { 15990267Sdes if (*p == ';') 16090267Sdes break; 161174761Sdes if (!isxdigit((unsigned char)*p)) 16290267Sdes return (-1); 163174761Sdes if (isdigit((unsigned char)*p)) { 16497859Sdes io->chunksize = io->chunksize * 16 + 16590267Sdes *p - '0'; 16690267Sdes } else { 16797859Sdes io->chunksize = io->chunksize * 16 + 168176036Sdes 10 + tolower((unsigned char)*p) - 'a'; 16990267Sdes } 17090267Sdes } 17190267Sdes 17263281Sdes#ifndef NDEBUG 17390267Sdes if (fetchDebug) { 17497859Sdes io->total += io->chunksize; 17597859Sdes if (io->chunksize == 0) 176106207Sdes fprintf(stderr, "%s(): end of last chunk\n", __func__); 17790267Sdes else 178106207Sdes fprintf(stderr, "%s(): new chunk: %lu (%lu)\n", 179106207Sdes __func__, (unsigned long)io->chunksize, 180106207Sdes (unsigned long)io->total); 18190267Sdes } 18263012Sdes#endif 18390267Sdes 18497859Sdes return (io->chunksize); 18537608Sdes} 18637608Sdes 18737608Sdes/* 18897866Sdes * Grow the input buffer to at least len bytes 18997866Sdes */ 19097866Sdesstatic inline int 191174588Sdeshttp_growbuf(struct httpio *io, size_t len) 19297866Sdes{ 19397866Sdes char *tmp; 19497866Sdes 19597866Sdes if (io->bufsize >= len) 19697866Sdes return (0); 19797866Sdes 19897866Sdes if ((tmp = realloc(io->buf, len)) == NULL) 19997866Sdes return (-1); 20097866Sdes io->buf = tmp; 20197866Sdes io->bufsize = len; 202106044Sdes return (0); 20397866Sdes} 20497866Sdes 20597866Sdes/* 20637608Sdes * Fill the input buffer, do chunk decoding on the fly 20737608Sdes */ 208262560Sdesstatic ssize_t 209174588Sdeshttp_fillbuf(struct httpio *io, size_t len) 21037535Sdes{ 211230307Sdes ssize_t nbytes; 212262560Sdes char ch; 213230307Sdes 21497859Sdes if (io->error) 21590267Sdes return (-1); 21697859Sdes if (io->eof) 21790267Sdes return (0); 21890267Sdes 219294194Sdes /* not chunked: just fetch the requested amount */ 22097866Sdes if (io->chunked == 0) { 221174588Sdes if (http_growbuf(io, len) == -1) 22297866Sdes return (-1); 223230307Sdes if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) { 224230307Sdes io->error = errno; 22597866Sdes return (-1); 226106185Sdes } 227230307Sdes io->buflen = nbytes; 22897866Sdes io->bufpos = 0; 22997866Sdes return (io->buflen); 23097866Sdes } 23197866Sdes 232294194Sdes /* chunked, but we ran out: get the next chunk header */ 23397859Sdes if (io->chunksize == 0) { 234174588Sdes switch (http_new_chunk(io)) { 23590267Sdes case -1: 236262560Sdes io->error = EPROTO; 23790267Sdes return (-1); 23890267Sdes case 0: 23997859Sdes io->eof = 1; 24090267Sdes return (0); 24190267Sdes } 24237535Sdes } 24363012Sdes 244294194Sdes /* fetch the requested amount, but no more than the current chunk */ 24597866Sdes if (len > io->chunksize) 24697866Sdes len = io->chunksize; 247174588Sdes if (http_growbuf(io, len) == -1) 24890267Sdes return (-1); 249230307Sdes if ((nbytes = fetch_read(io->conn, io->buf, len)) == -1) { 250230307Sdes io->error = errno; 25197866Sdes return (-1); 252106185Sdes } 253294194Sdes io->bufpos = 0; 254230307Sdes io->buflen = nbytes; 255294194Sdes io->chunksize -= nbytes; 25690267Sdes 25797859Sdes if (io->chunksize == 0) { 258262560Sdes if (fetch_read(io->conn, &ch, 1) != 1 || ch != '\r' || 259262560Sdes fetch_read(io->conn, &ch, 1) != 1 || ch != '\n') 26090267Sdes return (-1); 26190267Sdes } 26290267Sdes 26397866Sdes return (io->buflen); 26437535Sdes} 26537535Sdes 26637608Sdes/* 26737608Sdes * Read function 26837608Sdes */ 26937535Sdesstatic int 270174588Sdeshttp_readfn(void *v, char *buf, int len) 27137535Sdes{ 27297859Sdes struct httpio *io = (struct httpio *)v; 273262560Sdes int rlen; 27463012Sdes 27597859Sdes if (io->error) 27690267Sdes return (-1); 27797859Sdes if (io->eof) 27890267Sdes return (0); 27963012Sdes 280262560Sdes /* empty buffer */ 281262560Sdes if (!io->buf || io->bufpos == io->buflen) { 282262560Sdes if ((rlen = http_fillbuf(io, len)) < 0) { 283262560Sdes if ((errno = io->error) == EINTR) 284262560Sdes io->error = 0; 285262560Sdes return (-1); 286262560Sdes } else if (rlen == 0) { 287262560Sdes return (0); 288262560Sdes } 28990267Sdes } 29037535Sdes 291262560Sdes rlen = io->buflen - io->bufpos; 292262560Sdes if (len < rlen) 293262560Sdes rlen = len; 294262560Sdes memcpy(buf, io->buf + io->bufpos, rlen); 295262560Sdes io->bufpos += rlen; 296262560Sdes return (rlen); 29737535Sdes} 29837535Sdes 29937608Sdes/* 30037608Sdes * Write function 30137608Sdes */ 30237535Sdesstatic int 303174588Sdeshttp_writefn(void *v, const char *buf, int len) 30437535Sdes{ 30597859Sdes struct httpio *io = (struct httpio *)v; 30690267Sdes 307174588Sdes return (fetch_write(io->conn, buf, len)); 30837535Sdes} 30937535Sdes 31037608Sdes/* 31137608Sdes * Close function 31237608Sdes */ 31337535Sdesstatic int 314174588Sdeshttp_closefn(void *v) 31537535Sdes{ 31697859Sdes struct httpio *io = (struct httpio *)v; 31790267Sdes int r; 31863012Sdes 319174588Sdes r = fetch_close(io->conn); 32097859Sdes if (io->buf) 32197859Sdes free(io->buf); 32297859Sdes free(io); 32390267Sdes return (r); 32437535Sdes} 32537535Sdes 32637608Sdes/* 32763012Sdes * Wrap a file descriptor up 32837608Sdes */ 32963012Sdesstatic FILE * 330174588Sdeshttp_funopen(conn_t *conn, int chunked) 33137535Sdes{ 33297859Sdes struct httpio *io; 33390267Sdes FILE *f; 33463012Sdes 335109967Sdes if ((io = calloc(1, sizeof(*io))) == NULL) { 336174588Sdes fetch_syserr(); 33790267Sdes return (NULL); 33890267Sdes } 33997859Sdes io->conn = conn; 34097866Sdes io->chunked = chunked; 341174588Sdes f = funopen(io, http_readfn, http_writefn, NULL, http_closefn); 34290267Sdes if (f == NULL) { 343174588Sdes fetch_syserr(); 34497859Sdes free(io); 34590267Sdes return (NULL); 34690267Sdes } 34790267Sdes return (f); 34863012Sdes} 34963012Sdes 35090267Sdes 35163012Sdes/***************************************************************************** 35263012Sdes * Helper functions for talking to the server and parsing its replies 35363012Sdes */ 35463012Sdes 35563012Sdes/* Header types */ 35663012Sdestypedef enum { 35790267Sdes hdr_syserror = -2, 35890267Sdes hdr_error = -1, 35990267Sdes hdr_end = 0, 36090267Sdes hdr_unknown = 1, 36190267Sdes hdr_content_length, 36290267Sdes hdr_content_range, 36390267Sdes hdr_last_modified, 36490267Sdes hdr_location, 36590267Sdes hdr_transfer_encoding, 366202613Sdes hdr_www_authenticate, 367202613Sdes hdr_proxy_authenticate, 36885093Sdes} hdr_t; 36963012Sdes 37063012Sdes/* Names of interesting headers */ 37163012Sdesstatic struct { 37290267Sdes hdr_t num; 37390267Sdes const char *name; 37463012Sdes} hdr_names[] = { 37590267Sdes { hdr_content_length, "Content-Length" }, 37690267Sdes { hdr_content_range, "Content-Range" }, 37790267Sdes { hdr_last_modified, "Last-Modified" }, 37890267Sdes { hdr_location, "Location" }, 37990267Sdes { hdr_transfer_encoding, "Transfer-Encoding" }, 38090267Sdes { hdr_www_authenticate, "WWW-Authenticate" }, 381202613Sdes { hdr_proxy_authenticate, "Proxy-Authenticate" }, 38290267Sdes { hdr_unknown, NULL }, 38363012Sdes}; 38463012Sdes 38563012Sdes/* 38663012Sdes * Send a formatted line; optionally echo to terminal 38763012Sdes */ 38863012Sdesstatic int 389174588Sdeshttp_cmd(conn_t *conn, const char *fmt, ...) 39063012Sdes{ 39190267Sdes va_list ap; 39290267Sdes size_t len; 39390267Sdes char *msg; 39490267Sdes int r; 39563012Sdes 39690267Sdes va_start(ap, fmt); 39790267Sdes len = vasprintf(&msg, fmt, ap); 39890267Sdes va_end(ap); 39990267Sdes 40090267Sdes if (msg == NULL) { 40190267Sdes errno = ENOMEM; 402174588Sdes fetch_syserr(); 40390267Sdes return (-1); 40490267Sdes } 40590267Sdes 406174588Sdes r = fetch_putln(conn, msg, len); 40790267Sdes free(msg); 40890267Sdes 40990267Sdes if (r == -1) { 410174588Sdes fetch_syserr(); 41190267Sdes return (-1); 41290267Sdes } 41390267Sdes 41490267Sdes return (0); 41563012Sdes} 41663012Sdes 41763012Sdes/* 41863012Sdes * Get and parse status line 41963012Sdes */ 42063012Sdesstatic int 421174588Sdeshttp_get_reply(conn_t *conn) 42263012Sdes{ 42390267Sdes char *p; 42490267Sdes 425174588Sdes if (fetch_getln(conn) == -1) 42690267Sdes return (-1); 42790267Sdes /* 42890267Sdes * A valid status line looks like "HTTP/m.n xyz reason" where m 42990267Sdes * and n are the major and minor protocol version numbers and xyz 43090267Sdes * is the reply code. 43190267Sdes * Unfortunately, there are servers out there (NCSA 1.5.1, to name 43290267Sdes * just one) that do not send a version number, so we can't rely 43390267Sdes * on finding one, but if we do, insist on it being 1.0 or 1.1. 43490267Sdes * We don't care about the reason phrase. 43590267Sdes */ 43697856Sdes if (strncmp(conn->buf, "HTTP", 4) != 0) 43790267Sdes return (HTTP_PROTOCOL_ERROR); 43897856Sdes p = conn->buf + 4; 43990267Sdes if (*p == '/') { 44090267Sdes if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1')) 44190267Sdes return (HTTP_PROTOCOL_ERROR); 44290267Sdes p += 4; 44390267Sdes } 444174761Sdes if (*p != ' ' || 445174761Sdes !isdigit((unsigned char)p[1]) || 446174761Sdes !isdigit((unsigned char)p[2]) || 447174761Sdes !isdigit((unsigned char)p[3])) 44890267Sdes return (HTTP_PROTOCOL_ERROR); 44990267Sdes 45097856Sdes conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0'); 45197856Sdes return (conn->err); 45237535Sdes} 45337535Sdes 45437608Sdes/* 45590267Sdes * Check a header; if the type matches the given string, return a pointer 45690267Sdes * to the beginning of the value. 45763012Sdes */ 45875891Sarchiestatic const char * 459174588Sdeshttp_match(const char *str, const char *hdr) 46063012Sdes{ 461176036Sdes while (*str && *hdr && 462176036Sdes tolower((unsigned char)*str++) == tolower((unsigned char)*hdr++)) 46390267Sdes /* nothing */; 46490267Sdes if (*str || *hdr != ':') 46590267Sdes return (NULL); 466174761Sdes while (*hdr && isspace((unsigned char)*++hdr)) 46790267Sdes /* nothing */; 46890267Sdes return (hdr); 46963012Sdes} 47063012Sdes 471202613Sdes 47263012Sdes/* 473202613Sdes * Get the next header and return the appropriate symbolic code. We 474202613Sdes * need to read one line ahead for checking for a continuation line 475202613Sdes * belonging to the current header (continuation lines start with 476221821Sdes * white space). 477202613Sdes * 478202613Sdes * We get called with a fresh line already in the conn buffer, either 479202613Sdes * from the previous http_next_header() invocation, or, the first 480202613Sdes * time, from a fetch_getln() performed by our caller. 481202613Sdes * 482202613Sdes * This stops when we encounter an empty line (we dont read beyond the header 483202613Sdes * area). 484221821Sdes * 485202613Sdes * Note that the "headerbuf" is just a place to return the result. Its 486202613Sdes * contents are not used for the next call. This means that no cleanup 487202613Sdes * is needed when ie doing another connection, just call the cleanup when 488202613Sdes * fully done to deallocate memory. 48963012Sdes */ 490202613Sdes 491202613Sdes/* Limit the max number of continuation lines to some reasonable value */ 492202613Sdes#define HTTP_MAX_CONT_LINES 10 493202613Sdes 494202613Sdes/* Place into which to build a header from one or several lines */ 495202613Sdestypedef struct { 496202613Sdes char *buf; /* buffer */ 497202613Sdes size_t bufsize; /* buffer size */ 498202613Sdes size_t buflen; /* length of buffer contents */ 499202613Sdes} http_headerbuf_t; 500202613Sdes 501202613Sdesstatic void 502202613Sdesinit_http_headerbuf(http_headerbuf_t *buf) 50363012Sdes{ 504202613Sdes buf->buf = NULL; 505202613Sdes buf->bufsize = 0; 506202613Sdes buf->buflen = 0; 507202613Sdes} 50890267Sdes 509221821Sdesstatic void 510202613Sdesclean_http_headerbuf(http_headerbuf_t *buf) 511202613Sdes{ 512202613Sdes if (buf->buf) 513202613Sdes free(buf->buf); 514202613Sdes init_http_headerbuf(buf); 515202613Sdes} 516202613Sdes 517202613Sdes/* Remove whitespace at the end of the buffer */ 518221821Sdesstatic void 519202613Sdeshttp_conn_trimright(conn_t *conn) 520202613Sdes{ 521221821Sdes while (conn->buflen && 522202613Sdes isspace((unsigned char)conn->buf[conn->buflen - 1])) 52397856Sdes conn->buflen--; 52497856Sdes conn->buf[conn->buflen] = '\0'; 525202613Sdes} 526202613Sdes 527202613Sdesstatic hdr_t 528202613Sdeshttp_next_header(conn_t *conn, http_headerbuf_t *hbuf, const char **p) 529202613Sdes{ 530221820Sdes unsigned int i, len; 531202613Sdes 532221821Sdes /* 533202613Sdes * Have to do the stripping here because of the first line. So 534221821Sdes * it's done twice for the subsequent lines. No big deal 535202613Sdes */ 536202613Sdes http_conn_trimright(conn); 53797856Sdes if (conn->buflen == 0) 53897856Sdes return (hdr_end); 539202613Sdes 540202613Sdes /* Copy the line to the headerbuf */ 541202613Sdes if (hbuf->bufsize < conn->buflen + 1) { 542202613Sdes if ((hbuf->buf = realloc(hbuf->buf, conn->buflen + 1)) == NULL) 543202613Sdes return (hdr_syserror); 544202613Sdes hbuf->bufsize = conn->buflen + 1; 545202613Sdes } 546202613Sdes strcpy(hbuf->buf, conn->buf); 547202613Sdes hbuf->buflen = conn->buflen; 548202613Sdes 549221821Sdes /* 550202613Sdes * Fetch possible continuation lines. Stop at 1st non-continuation 551221821Sdes * and leave it in the conn buffer 552221821Sdes */ 553202613Sdes for (i = 0; i < HTTP_MAX_CONT_LINES; i++) { 554202613Sdes if (fetch_getln(conn) == -1) 555202613Sdes return (hdr_syserror); 556202613Sdes 557221821Sdes /* 558202613Sdes * Note: we carry on the idea from the previous version 559202613Sdes * that a pure whitespace line is equivalent to an empty 560202613Sdes * one (so it's not continuation and will be handled when 561221821Sdes * we are called next) 562202613Sdes */ 563202613Sdes http_conn_trimright(conn); 564202613Sdes if (conn->buf[0] != ' ' && conn->buf[0] != "\t"[0]) 565202613Sdes break; 566202613Sdes 567202613Sdes /* Got a continuation line. Concatenate to previous */ 568202613Sdes len = hbuf->buflen + conn->buflen; 569202613Sdes if (hbuf->bufsize < len + 1) { 570202613Sdes len *= 2; 571202613Sdes if ((hbuf->buf = realloc(hbuf->buf, len + 1)) == NULL) 572202613Sdes return (hdr_syserror); 573202613Sdes hbuf->bufsize = len + 1; 574202613Sdes } 575202613Sdes strcpy(hbuf->buf + hbuf->buflen, conn->buf); 576202613Sdes hbuf->buflen += conn->buflen; 577221821Sdes } 578202613Sdes 57990267Sdes /* 58090267Sdes * We could check for malformed headers but we don't really care. 58190267Sdes * A valid header starts with a token immediately followed by a 58290267Sdes * colon; a token is any sequence of non-control, non-whitespace 58390267Sdes * characters except "()<>@,;:\\\"{}". 58490267Sdes */ 58590267Sdes for (i = 0; hdr_names[i].num != hdr_unknown; i++) 586202613Sdes if ((*p = http_match(hdr_names[i].name, hbuf->buf)) != NULL) 58790267Sdes return (hdr_names[i].num); 588202613Sdes 58990267Sdes return (hdr_unknown); 59063012Sdes} 59163012Sdes 592202613Sdes/************************** 593202613Sdes * [Proxy-]Authenticate header parsing 594202613Sdes */ 595202613Sdes 596221821Sdes/* 597221821Sdes * Read doublequote-delimited string into output buffer obuf (allocated 598202613Sdes * by caller, whose responsibility it is to ensure that it's big enough) 599202613Sdes * cp points to the first char after the initial '"' 600221821Sdes * Handles \ quoting 601221821Sdes * Returns pointer to the first char after the terminating double quote, or 602202613Sdes * NULL for error. 603202613Sdes */ 604202613Sdesstatic const char * 605202613Sdeshttp_parse_headerstring(const char *cp, char *obuf) 606202613Sdes{ 607202613Sdes for (;;) { 608202613Sdes switch (*cp) { 609202613Sdes case 0: /* Unterminated string */ 610202613Sdes *obuf = 0; 611202613Sdes return (NULL); 612202613Sdes case '"': /* Ending quote */ 613202613Sdes *obuf = 0; 614202613Sdes return (++cp); 615202613Sdes case '\\': 616202613Sdes if (*++cp == 0) { 617202613Sdes *obuf = 0; 618202613Sdes return (NULL); 619202613Sdes } 620202613Sdes /* FALLTHROUGH */ 621202613Sdes default: 622202613Sdes *obuf++ = *cp++; 623202613Sdes } 624202613Sdes } 625202613Sdes} 626202613Sdes 627202613Sdes/* Http auth challenge schemes */ 628202613Sdestypedef enum {HTTPAS_UNKNOWN, HTTPAS_BASIC,HTTPAS_DIGEST} http_auth_schemes_t; 629202613Sdes 630202613Sdes/* Data holder for a Basic or Digest challenge. */ 631202613Sdestypedef struct { 632202613Sdes http_auth_schemes_t scheme; 633202613Sdes char *realm; 634202613Sdes char *qop; 635202613Sdes char *nonce; 636202613Sdes char *opaque; 637202613Sdes char *algo; 638202613Sdes int stale; 639202613Sdes int nc; /* Nonce count */ 640202613Sdes} http_auth_challenge_t; 641202613Sdes 642221821Sdesstatic void 643202613Sdesinit_http_auth_challenge(http_auth_challenge_t *b) 644202613Sdes{ 645202613Sdes b->scheme = HTTPAS_UNKNOWN; 646202613Sdes b->realm = b->qop = b->nonce = b->opaque = b->algo = NULL; 647202613Sdes b->stale = b->nc = 0; 648202613Sdes} 649202613Sdes 650221821Sdesstatic void 651202613Sdesclean_http_auth_challenge(http_auth_challenge_t *b) 652202613Sdes{ 653221821Sdes if (b->realm) 654202613Sdes free(b->realm); 655221821Sdes if (b->qop) 656202613Sdes free(b->qop); 657221821Sdes if (b->nonce) 658202613Sdes free(b->nonce); 659221821Sdes if (b->opaque) 660202613Sdes free(b->opaque); 661221821Sdes if (b->algo) 662202613Sdes free(b->algo); 663202613Sdes init_http_auth_challenge(b); 664202613Sdes} 665202613Sdes 666202613Sdes/* Data holder for an array of challenges offered in an http response. */ 667202613Sdes#define MAX_CHALLENGES 10 668202613Sdestypedef struct { 669202613Sdes http_auth_challenge_t *challenges[MAX_CHALLENGES]; 670202613Sdes int count; /* Number of parsed challenges in the array */ 671202613Sdes int valid; /* We did parse an authenticate header */ 672202613Sdes} http_auth_challenges_t; 673202613Sdes 674221821Sdesstatic void 675202613Sdesinit_http_auth_challenges(http_auth_challenges_t *cs) 676202613Sdes{ 677202613Sdes int i; 678202613Sdes for (i = 0; i < MAX_CHALLENGES; i++) 679202613Sdes cs->challenges[i] = NULL; 680202613Sdes cs->count = cs->valid = 0; 681202613Sdes} 682202613Sdes 683221821Sdesstatic void 684202613Sdesclean_http_auth_challenges(http_auth_challenges_t *cs) 685202613Sdes{ 686202613Sdes int i; 687202613Sdes /* We rely on non-zero pointers being allocated, not on the count */ 688202613Sdes for (i = 0; i < MAX_CHALLENGES; i++) { 689202613Sdes if (cs->challenges[i] != NULL) { 690202613Sdes clean_http_auth_challenge(cs->challenges[i]); 691202613Sdes free(cs->challenges[i]); 692202613Sdes } 693202613Sdes } 694202613Sdes init_http_auth_challenges(cs); 695202613Sdes} 696202613Sdes 697221821Sdes/* 698202613Sdes * Enumeration for lexical elements. Separators will be returned as their own 699202613Sdes * ascii value 700202613Sdes */ 701202613Sdestypedef enum {HTTPHL_WORD=256, HTTPHL_STRING=257, HTTPHL_END=258, 702202613Sdes HTTPHL_ERROR = 259} http_header_lex_t; 703202613Sdes 704221821Sdes/* 705202613Sdes * Determine what kind of token comes next and return possible value 706202613Sdes * in buf, which is supposed to have been allocated big enough by 707221821Sdes * caller. Advance input pointer and return element type. 708202613Sdes */ 709221821Sdesstatic int 710202613Sdeshttp_header_lex(const char **cpp, char *buf) 711202613Sdes{ 712202613Sdes size_t l; 713202613Sdes /* Eat initial whitespace */ 714202613Sdes *cpp += strspn(*cpp, " \t"); 715202613Sdes if (**cpp == 0) 716202613Sdes return (HTTPHL_END); 717202613Sdes 718202613Sdes /* Separator ? */ 719202613Sdes if (**cpp == ',' || **cpp == '=') 720202613Sdes return (*((*cpp)++)); 721202613Sdes 722202613Sdes /* String ? */ 723202613Sdes if (**cpp == '"') { 724202613Sdes *cpp = http_parse_headerstring(++*cpp, buf); 725202613Sdes if (*cpp == NULL) 726202613Sdes return (HTTPHL_ERROR); 727202613Sdes return (HTTPHL_STRING); 728202613Sdes } 729202613Sdes 730202613Sdes /* Read other token, until separator or whitespace */ 731202613Sdes l = strcspn(*cpp, " \t,="); 732202613Sdes memcpy(buf, *cpp, l); 733202613Sdes buf[l] = 0; 734202613Sdes *cpp += l; 735202613Sdes return (HTTPHL_WORD); 736202613Sdes} 737202613Sdes 738221821Sdes/* 739202613Sdes * Read challenges from http xxx-authenticate header and accumulate them 740202613Sdes * in the challenges list structure. 741202613Sdes * 742202613Sdes * Headers with multiple challenges are specified by rfc2617, but 743202613Sdes * servers (ie: squid) often send them in separate headers instead, 744202613Sdes * which in turn is forbidden by the http spec (multiple headers with 745202613Sdes * the same name are only allowed for pure comma-separated lists, see 746202613Sdes * rfc2616 sec 4.2). 747202613Sdes * 748202613Sdes * We support both approaches anyway 749202613Sdes */ 750221821Sdesstatic int 751202613Sdeshttp_parse_authenticate(const char *cp, http_auth_challenges_t *cs) 752202613Sdes{ 753202613Sdes int ret = -1; 754202613Sdes http_header_lex_t lex; 755202613Sdes char *key = malloc(strlen(cp) + 1); 756202613Sdes char *value = malloc(strlen(cp) + 1); 757202613Sdes char *buf = malloc(strlen(cp) + 1); 758202613Sdes 759202613Sdes if (key == NULL || value == NULL || buf == NULL) { 760202613Sdes fetch_syserr(); 761202613Sdes goto out; 762202613Sdes } 763202613Sdes 764202613Sdes /* In any case we've seen the header and we set the valid bit */ 765202613Sdes cs->valid = 1; 766202613Sdes 767202613Sdes /* Need word first */ 768202613Sdes lex = http_header_lex(&cp, key); 769202613Sdes if (lex != HTTPHL_WORD) 770202613Sdes goto out; 771202613Sdes 772202613Sdes /* Loop on challenges */ 773202613Sdes for (; cs->count < MAX_CHALLENGES; cs->count++) { 774221821Sdes cs->challenges[cs->count] = 775202613Sdes malloc(sizeof(http_auth_challenge_t)); 776202613Sdes if (cs->challenges[cs->count] == NULL) { 777202613Sdes fetch_syserr(); 778202613Sdes goto out; 779202613Sdes } 780202613Sdes init_http_auth_challenge(cs->challenges[cs->count]); 781202613Sdes if (!strcasecmp(key, "basic")) { 782202613Sdes cs->challenges[cs->count]->scheme = HTTPAS_BASIC; 783202613Sdes } else if (!strcasecmp(key, "digest")) { 784202613Sdes cs->challenges[cs->count]->scheme = HTTPAS_DIGEST; 785202613Sdes } else { 786202613Sdes cs->challenges[cs->count]->scheme = HTTPAS_UNKNOWN; 787221821Sdes /* 788221821Sdes * Continue parsing as basic or digest may 789202613Sdes * follow, and the syntax is the same for 790202613Sdes * all. We'll just ignore this one when 791202613Sdes * looking at the list 792202613Sdes */ 793202613Sdes } 794221821Sdes 795202613Sdes /* Loop on attributes */ 796202613Sdes for (;;) { 797202613Sdes /* Key */ 798202613Sdes lex = http_header_lex(&cp, key); 799202613Sdes if (lex != HTTPHL_WORD) 800202613Sdes goto out; 801202613Sdes 802202613Sdes /* Equal sign */ 803202613Sdes lex = http_header_lex(&cp, buf); 804202613Sdes if (lex != '=') 805202613Sdes goto out; 806202613Sdes 807202613Sdes /* Value */ 808202613Sdes lex = http_header_lex(&cp, value); 809202613Sdes if (lex != HTTPHL_WORD && lex != HTTPHL_STRING) 810202613Sdes goto out; 811202613Sdes 812202613Sdes if (!strcasecmp(key, "realm")) 813221821Sdes cs->challenges[cs->count]->realm = 814202613Sdes strdup(value); 815202613Sdes else if (!strcasecmp(key, "qop")) 816221821Sdes cs->challenges[cs->count]->qop = 817202613Sdes strdup(value); 818202613Sdes else if (!strcasecmp(key, "nonce")) 819221821Sdes cs->challenges[cs->count]->nonce = 820202613Sdes strdup(value); 821202613Sdes else if (!strcasecmp(key, "opaque")) 822221821Sdes cs->challenges[cs->count]->opaque = 823202613Sdes strdup(value); 824202613Sdes else if (!strcasecmp(key, "algorithm")) 825221821Sdes cs->challenges[cs->count]->algo = 826202613Sdes strdup(value); 827202613Sdes else if (!strcasecmp(key, "stale")) 828221821Sdes cs->challenges[cs->count]->stale = 829202613Sdes strcasecmp(value, "no"); 830202613Sdes /* Else ignore unknown attributes */ 831202613Sdes 832202613Sdes /* Comma or Next challenge or End */ 833202613Sdes lex = http_header_lex(&cp, key); 834221821Sdes /* 835221821Sdes * If we get a word here, this is the beginning of the 836221821Sdes * next challenge. Break the attributes loop 837221821Sdes */ 838202613Sdes if (lex == HTTPHL_WORD) 839202613Sdes break; 840202613Sdes 841202613Sdes if (lex == HTTPHL_END) { 842202613Sdes /* End while looking for ',' is normal exit */ 843202613Sdes cs->count++; 844202613Sdes ret = 0; 845202613Sdes goto out; 846202613Sdes } 847202613Sdes /* Anything else is an error */ 848202613Sdes if (lex != ',') 849202613Sdes goto out; 850202613Sdes 851202613Sdes } /* End attributes loop */ 852202613Sdes } /* End challenge loop */ 853202613Sdes 854221821Sdes /* 855221821Sdes * Challenges max count exceeded. This really can't happen 856221821Sdes * with normal data, something's fishy -> error 857221821Sdes */ 858202613Sdes 859202613Sdesout: 860202613Sdes if (key) 861202613Sdes free(key); 862202613Sdes if (value) 863202613Sdes free(value); 864202613Sdes if (buf) 865202613Sdes free(buf); 866202613Sdes return (ret); 867202613Sdes} 868202613Sdes 869202613Sdes 87063012Sdes/* 87163012Sdes * Parse a last-modified header 87263012Sdes */ 87363716Sdesstatic int 874174588Sdeshttp_parse_mtime(const char *p, time_t *mtime) 87563012Sdes{ 87690267Sdes char locale[64], *r; 87790267Sdes struct tm tm; 87863012Sdes 879311863Sdes strlcpy(locale, setlocale(LC_TIME, NULL), sizeof(locale)); 88090267Sdes setlocale(LC_TIME, "C"); 88190267Sdes r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm); 882263325Sbdrewery /* 883263325Sbdrewery * Some proxies use UTC in response, but it should still be 884263325Sbdrewery * parsed. RFC2616 states GMT and UTC are exactly equal for HTTP. 885263325Sbdrewery */ 886263325Sbdrewery if (r == NULL) 887263325Sbdrewery r = strptime(p, "%a, %d %b %Y %H:%M:%S UTC", &tm); 88890267Sdes /* XXX should add support for date-2 and date-3 */ 88990267Sdes setlocale(LC_TIME, locale); 89090267Sdes if (r == NULL) 89190267Sdes return (-1); 89290267Sdes DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d " 89388769Sdes "%02d:%02d:%02d]\n", 89463012Sdes tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 89563012Sdes tm.tm_hour, tm.tm_min, tm.tm_sec)); 89690267Sdes *mtime = timegm(&tm); 89790267Sdes return (0); 89863012Sdes} 89963012Sdes 90063012Sdes/* 90163012Sdes * Parse a content-length header 90263012Sdes */ 90363716Sdesstatic int 904174588Sdeshttp_parse_length(const char *p, off_t *length) 90563012Sdes{ 90690267Sdes off_t len; 90790267Sdes 908174761Sdes for (len = 0; *p && isdigit((unsigned char)*p); ++p) 90990267Sdes len = len * 10 + (*p - '0'); 91090267Sdes if (*p) 91190267Sdes return (-1); 91290267Sdes DEBUG(fprintf(stderr, "content length: [%lld]\n", 91390267Sdes (long long)len)); 91490267Sdes *length = len; 91590267Sdes return (0); 91663012Sdes} 91763012Sdes 91863012Sdes/* 91963012Sdes * Parse a content-range header 92063012Sdes */ 92163716Sdesstatic int 922174588Sdeshttp_parse_range(const char *p, off_t *offset, off_t *length, off_t *size) 92363012Sdes{ 92490267Sdes off_t first, last, len; 92563716Sdes 92690267Sdes if (strncasecmp(p, "bytes ", 6) != 0) 92790267Sdes return (-1); 928125696Sdes p += 6; 929125696Sdes if (*p == '*') { 930125696Sdes first = last = -1; 931125696Sdes ++p; 932125696Sdes } else { 933174761Sdes for (first = 0; *p && isdigit((unsigned char)*p); ++p) 934125696Sdes first = first * 10 + *p - '0'; 935125696Sdes if (*p != '-') 936125696Sdes return (-1); 937174761Sdes for (last = 0, ++p; *p && isdigit((unsigned char)*p); ++p) 938125696Sdes last = last * 10 + *p - '0'; 939125696Sdes } 94090267Sdes if (first > last || *p != '/') 94190267Sdes return (-1); 942174761Sdes for (len = 0, ++p; *p && isdigit((unsigned char)*p); ++p) 94390267Sdes len = len * 10 + *p - '0'; 94490267Sdes if (*p || len < last - first + 1) 94590267Sdes return (-1); 946125696Sdes if (first == -1) { 947125696Sdes DEBUG(fprintf(stderr, "content range: [*/%lld]\n", 948125696Sdes (long long)len)); 949125696Sdes *length = 0; 950125696Sdes } else { 951125696Sdes DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n", 952125696Sdes (long long)first, (long long)last, (long long)len)); 953125696Sdes *length = last - first + 1; 954125696Sdes } 95590267Sdes *offset = first; 95690267Sdes *size = len; 95790267Sdes return (0); 95863012Sdes} 95963012Sdes 96090267Sdes 96163012Sdes/***************************************************************************** 96263012Sdes * Helper functions for authorization 96363012Sdes */ 96463012Sdes 96563012Sdes/* 96637608Sdes * Base64 encoding 96737608Sdes */ 96862965Sdesstatic char * 969174588Sdeshttp_base64(const char *src) 97037608Sdes{ 97190267Sdes static const char base64[] = 97290267Sdes "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 97390267Sdes "abcdefghijklmnopqrstuvwxyz" 97490267Sdes "0123456789+/"; 97590267Sdes char *str, *dst; 97690267Sdes size_t l; 97790267Sdes int t, r; 97862965Sdes 97990267Sdes l = strlen(src); 980133280Sdes if ((str = malloc(((l + 2) / 3) * 4 + 1)) == NULL) 98190267Sdes return (NULL); 98290267Sdes dst = str; 98390267Sdes r = 0; 98437608Sdes 98590267Sdes while (l >= 3) { 98690267Sdes t = (src[0] << 16) | (src[1] << 8) | src[2]; 98790267Sdes dst[0] = base64[(t >> 18) & 0x3f]; 98890267Sdes dst[1] = base64[(t >> 12) & 0x3f]; 98990267Sdes dst[2] = base64[(t >> 6) & 0x3f]; 99090267Sdes dst[3] = base64[(t >> 0) & 0x3f]; 99190267Sdes src += 3; l -= 3; 99290267Sdes dst += 4; r += 4; 99390267Sdes } 99437608Sdes 99590267Sdes switch (l) { 99690267Sdes case 2: 99790267Sdes t = (src[0] << 16) | (src[1] << 8); 99890267Sdes dst[0] = base64[(t >> 18) & 0x3f]; 99990267Sdes dst[1] = base64[(t >> 12) & 0x3f]; 100090267Sdes dst[2] = base64[(t >> 6) & 0x3f]; 100190267Sdes dst[3] = '='; 100290267Sdes dst += 4; 100390267Sdes r += 4; 100490267Sdes break; 100590267Sdes case 1: 100690267Sdes t = src[0] << 16; 100790267Sdes dst[0] = base64[(t >> 18) & 0x3f]; 100890267Sdes dst[1] = base64[(t >> 12) & 0x3f]; 100990267Sdes dst[2] = dst[3] = '='; 101090267Sdes dst += 4; 101190267Sdes r += 4; 101290267Sdes break; 101390267Sdes case 0: 101490267Sdes break; 101590267Sdes } 101690267Sdes 101790267Sdes *dst = 0; 101890267Sdes return (str); 101937608Sdes} 102037608Sdes 1021202613Sdes 102237608Sdes/* 1023202613Sdes * Extract authorization parameters from environment value. 1024202613Sdes * The value is like scheme:realm:user:pass 1025202613Sdes */ 1026202613Sdestypedef struct { 1027202613Sdes char *scheme; 1028202613Sdes char *realm; 1029202613Sdes char *user; 1030202613Sdes char *password; 1031202613Sdes} http_auth_params_t; 1032202613Sdes 1033202613Sdesstatic void 1034202613Sdesinit_http_auth_params(http_auth_params_t *s) 1035202613Sdes{ 1036268900Sbapt s->scheme = s->realm = s->user = s->password = NULL; 1037202613Sdes} 1038202613Sdes 1039221821Sdesstatic void 1040202613Sdesclean_http_auth_params(http_auth_params_t *s) 1041202613Sdes{ 1042221821Sdes if (s->scheme) 1043202613Sdes free(s->scheme); 1044221821Sdes if (s->realm) 1045202613Sdes free(s->realm); 1046221821Sdes if (s->user) 1047202613Sdes free(s->user); 1048221821Sdes if (s->password) 1049202613Sdes free(s->password); 1050202613Sdes init_http_auth_params(s); 1051202613Sdes} 1052202613Sdes 1053202613Sdesstatic int 1054202613Sdeshttp_authfromenv(const char *p, http_auth_params_t *parms) 1055202613Sdes{ 1056202613Sdes int ret = -1; 1057202613Sdes char *v, *ve; 1058202613Sdes char *str = strdup(p); 1059202613Sdes 1060202613Sdes if (str == NULL) { 1061202613Sdes fetch_syserr(); 1062202613Sdes return (-1); 1063202613Sdes } 1064202613Sdes v = str; 1065202613Sdes 1066202613Sdes if ((ve = strchr(v, ':')) == NULL) 1067202613Sdes goto out; 1068202613Sdes 1069202613Sdes *ve = 0; 1070202613Sdes if ((parms->scheme = strdup(v)) == NULL) { 1071202613Sdes fetch_syserr(); 1072202613Sdes goto out; 1073202613Sdes } 1074202613Sdes v = ve + 1; 1075202613Sdes 1076202613Sdes if ((ve = strchr(v, ':')) == NULL) 1077202613Sdes goto out; 1078202613Sdes 1079202613Sdes *ve = 0; 1080202613Sdes if ((parms->realm = strdup(v)) == NULL) { 1081202613Sdes fetch_syserr(); 1082202613Sdes goto out; 1083202613Sdes } 1084202613Sdes v = ve + 1; 1085202613Sdes 1086202613Sdes if ((ve = strchr(v, ':')) == NULL) 1087202613Sdes goto out; 1088202613Sdes 1089202613Sdes *ve = 0; 1090202613Sdes if ((parms->user = strdup(v)) == NULL) { 1091202613Sdes fetch_syserr(); 1092202613Sdes goto out; 1093202613Sdes } 1094202613Sdes v = ve + 1; 1095202613Sdes 1096202613Sdes 1097202613Sdes if ((parms->password = strdup(v)) == NULL) { 1098202613Sdes fetch_syserr(); 1099202613Sdes goto out; 1100202613Sdes } 1101202613Sdes ret = 0; 1102202613Sdesout: 1103221821Sdes if (ret == -1) 1104202613Sdes clean_http_auth_params(parms); 1105202613Sdes if (str) 1106202613Sdes free(str); 1107202613Sdes return (ret); 1108202613Sdes} 1109202613Sdes 1110202613Sdes 1111221821Sdes/* 1112202613Sdes * Digest response: the code to compute the digest is taken from the 1113221821Sdes * sample implementation in RFC2616 1114202613Sdes */ 1115221822Sdes#define IN const 1116202613Sdes#define OUT 1117202613Sdes 1118202613Sdes#define HASHLEN 16 1119202613Sdestypedef char HASH[HASHLEN]; 1120202613Sdes#define HASHHEXLEN 32 1121202613Sdestypedef char HASHHEX[HASHHEXLEN+1]; 1122202613Sdes 1123202613Sdesstatic const char *hexchars = "0123456789abcdef"; 1124221821Sdesstatic void 1125202613SdesCvtHex(IN HASH Bin, OUT HASHHEX Hex) 1126202613Sdes{ 1127202613Sdes unsigned short i; 1128202613Sdes unsigned char j; 1129202613Sdes 1130202613Sdes for (i = 0; i < HASHLEN; i++) { 1131202613Sdes j = (Bin[i] >> 4) & 0xf; 1132202613Sdes Hex[i*2] = hexchars[j]; 1133202613Sdes j = Bin[i] & 0xf; 1134202613Sdes Hex[i*2+1] = hexchars[j]; 1135268900Sbapt } 1136202613Sdes Hex[HASHHEXLEN] = '\0'; 1137202613Sdes}; 1138202613Sdes 1139202613Sdes/* calculate H(A1) as per spec */ 1140221821Sdesstatic void 1141202613SdesDigestCalcHA1( 1142202613Sdes IN char * pszAlg, 1143202613Sdes IN char * pszUserName, 1144202613Sdes IN char * pszRealm, 1145202613Sdes IN char * pszPassword, 1146202613Sdes IN char * pszNonce, 1147202613Sdes IN char * pszCNonce, 1148202613Sdes OUT HASHHEX SessionKey 1149202613Sdes ) 1150202613Sdes{ 1151202613Sdes MD5_CTX Md5Ctx; 1152202613Sdes HASH HA1; 1153202613Sdes 1154202613Sdes MD5Init(&Md5Ctx); 1155202613Sdes MD5Update(&Md5Ctx, pszUserName, strlen(pszUserName)); 1156202613Sdes MD5Update(&Md5Ctx, ":", 1); 1157202613Sdes MD5Update(&Md5Ctx, pszRealm, strlen(pszRealm)); 1158202613Sdes MD5Update(&Md5Ctx, ":", 1); 1159202613Sdes MD5Update(&Md5Ctx, pszPassword, strlen(pszPassword)); 1160202613Sdes MD5Final(HA1, &Md5Ctx); 1161202613Sdes if (strcasecmp(pszAlg, "md5-sess") == 0) { 1162202613Sdes 1163202613Sdes MD5Init(&Md5Ctx); 1164202613Sdes MD5Update(&Md5Ctx, HA1, HASHLEN); 1165202613Sdes MD5Update(&Md5Ctx, ":", 1); 1166202613Sdes MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce)); 1167202613Sdes MD5Update(&Md5Ctx, ":", 1); 1168202613Sdes MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce)); 1169202613Sdes MD5Final(HA1, &Md5Ctx); 1170268900Sbapt } 1171202613Sdes CvtHex(HA1, SessionKey); 1172202613Sdes} 1173202613Sdes 1174202613Sdes/* calculate request-digest/response-digest as per HTTP Digest spec */ 1175221821Sdesstatic void 1176202613SdesDigestCalcResponse( 1177202613Sdes IN HASHHEX HA1, /* H(A1) */ 1178202613Sdes IN char * pszNonce, /* nonce from server */ 1179202613Sdes IN char * pszNonceCount, /* 8 hex digits */ 1180202613Sdes IN char * pszCNonce, /* client nonce */ 1181202613Sdes IN char * pszQop, /* qop-value: "", "auth", "auth-int" */ 1182202613Sdes IN char * pszMethod, /* method from the request */ 1183202613Sdes IN char * pszDigestUri, /* requested URL */ 1184202613Sdes IN HASHHEX HEntity, /* H(entity body) if qop="auth-int" */ 1185202613Sdes OUT HASHHEX Response /* request-digest or response-digest */ 1186202613Sdes ) 1187202613Sdes{ 1188221821Sdes/* DEBUG(fprintf(stderr, 1189202613Sdes "Calc: HA1[%s] Nonce[%s] qop[%s] method[%s] URI[%s]\n", 1190202613Sdes HA1, pszNonce, pszQop, pszMethod, pszDigestUri));*/ 1191202613Sdes MD5_CTX Md5Ctx; 1192202613Sdes HASH HA2; 1193202613Sdes HASH RespHash; 1194202613Sdes HASHHEX HA2Hex; 1195202613Sdes 1196202613Sdes // calculate H(A2) 1197202613Sdes MD5Init(&Md5Ctx); 1198202613Sdes MD5Update(&Md5Ctx, pszMethod, strlen(pszMethod)); 1199202613Sdes MD5Update(&Md5Ctx, ":", 1); 1200202613Sdes MD5Update(&Md5Ctx, pszDigestUri, strlen(pszDigestUri)); 1201202613Sdes if (strcasecmp(pszQop, "auth-int") == 0) { 1202202613Sdes MD5Update(&Md5Ctx, ":", 1); 1203202613Sdes MD5Update(&Md5Ctx, HEntity, HASHHEXLEN); 1204268900Sbapt } 1205202613Sdes MD5Final(HA2, &Md5Ctx); 1206202613Sdes CvtHex(HA2, HA2Hex); 1207202613Sdes 1208202613Sdes // calculate response 1209202613Sdes MD5Init(&Md5Ctx); 1210202613Sdes MD5Update(&Md5Ctx, HA1, HASHHEXLEN); 1211202613Sdes MD5Update(&Md5Ctx, ":", 1); 1212202613Sdes MD5Update(&Md5Ctx, pszNonce, strlen(pszNonce)); 1213202613Sdes MD5Update(&Md5Ctx, ":", 1); 1214202613Sdes if (*pszQop) { 1215202613Sdes MD5Update(&Md5Ctx, pszNonceCount, strlen(pszNonceCount)); 1216202613Sdes MD5Update(&Md5Ctx, ":", 1); 1217202613Sdes MD5Update(&Md5Ctx, pszCNonce, strlen(pszCNonce)); 1218202613Sdes MD5Update(&Md5Ctx, ":", 1); 1219202613Sdes MD5Update(&Md5Ctx, pszQop, strlen(pszQop)); 1220202613Sdes MD5Update(&Md5Ctx, ":", 1); 1221268900Sbapt } 1222202613Sdes MD5Update(&Md5Ctx, HA2Hex, HASHHEXLEN); 1223202613Sdes MD5Final(RespHash, &Md5Ctx); 1224202613Sdes CvtHex(RespHash, Response); 1225202613Sdes} 1226202613Sdes 1227221821Sdes/* 1228221821Sdes * Generate/Send a Digest authorization header 1229202613Sdes * This looks like: [Proxy-]Authorization: credentials 1230202613Sdes * 1231202613Sdes * credentials = "Digest" digest-response 1232202613Sdes * digest-response = 1#( username | realm | nonce | digest-uri 1233202613Sdes * | response | [ algorithm ] | [cnonce] | 1234202613Sdes * [opaque] | [message-qop] | 1235202613Sdes * [nonce-count] | [auth-param] ) 1236202613Sdes * username = "username" "=" username-value 1237202613Sdes * username-value = quoted-string 1238202613Sdes * digest-uri = "uri" "=" digest-uri-value 1239202613Sdes * digest-uri-value = request-uri ; As specified by HTTP/1.1 1240202613Sdes * message-qop = "qop" "=" qop-value 1241202613Sdes * cnonce = "cnonce" "=" cnonce-value 1242202613Sdes * cnonce-value = nonce-value 1243202613Sdes * nonce-count = "nc" "=" nc-value 1244202613Sdes * nc-value = 8LHEX 1245202613Sdes * response = "response" "=" request-digest 1246202613Sdes * request-digest = <"> 32LHEX <"> 1247202613Sdes */ 1248202613Sdesstatic int 1249202613Sdeshttp_digest_auth(conn_t *conn, const char *hdr, http_auth_challenge_t *c, 1250202613Sdes http_auth_params_t *parms, struct url *url) 1251202613Sdes{ 1252202613Sdes int r; 1253202613Sdes char noncecount[10]; 1254202613Sdes char cnonce[40]; 1255268900Sbapt char *options = NULL; 1256202613Sdes 1257202613Sdes if (!c->realm || !c->nonce) { 1258202613Sdes DEBUG(fprintf(stderr, "realm/nonce not set in challenge\n")); 1259202613Sdes return(-1); 1260202613Sdes } 1261221821Sdes if (!c->algo) 1262202613Sdes c->algo = strdup(""); 1263202613Sdes 1264221821Sdes if (asprintf(&options, "%s%s%s%s", 1265202613Sdes *c->algo? ",algorithm=" : "", c->algo, 1266202613Sdes c->opaque? ",opaque=" : "", c->opaque?c->opaque:"")== -1) 1267202613Sdes return (-1); 1268202613Sdes 1269202613Sdes if (!c->qop) { 1270202613Sdes c->qop = strdup(""); 1271202613Sdes *noncecount = 0; 1272202613Sdes *cnonce = 0; 1273202613Sdes } else { 1274202613Sdes c->nc++; 1275202613Sdes sprintf(noncecount, "%08x", c->nc); 1276202613Sdes /* We don't try very hard with the cnonce ... */ 1277202613Sdes sprintf(cnonce, "%x%lx", getpid(), (unsigned long)time(0)); 1278202613Sdes } 1279202613Sdes 1280202613Sdes HASHHEX HA1; 1281202613Sdes DigestCalcHA1(c->algo, parms->user, c->realm, 1282202613Sdes parms->password, c->nonce, cnonce, HA1); 1283202613Sdes DEBUG(fprintf(stderr, "HA1: [%s]\n", HA1)); 1284202613Sdes HASHHEX digest; 1285202613Sdes DigestCalcResponse(HA1, c->nonce, noncecount, cnonce, c->qop, 1286202613Sdes "GET", url->doc, "", digest); 1287202613Sdes 1288202613Sdes if (c->qop[0]) { 1289202613Sdes r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\"," 1290202613Sdes "nonce=\"%s\",uri=\"%s\",response=\"%s\"," 1291202613Sdes "qop=\"auth\", cnonce=\"%s\", nc=%s%s", 1292221821Sdes hdr, parms->user, c->realm, 1293202613Sdes c->nonce, url->doc, digest, 1294202613Sdes cnonce, noncecount, options); 1295202613Sdes } else { 1296202613Sdes r = http_cmd(conn, "%s: Digest username=\"%s\",realm=\"%s\"," 1297202613Sdes "nonce=\"%s\",uri=\"%s\",response=\"%s\"%s", 1298221821Sdes hdr, parms->user, c->realm, 1299202613Sdes c->nonce, url->doc, digest, options); 1300202613Sdes } 1301202613Sdes if (options) 1302202613Sdes free(options); 1303202613Sdes return (r); 1304202613Sdes} 1305202613Sdes 1306202613Sdes/* 130737608Sdes * Encode username and password 130837608Sdes */ 130962965Sdesstatic int 1310174588Sdeshttp_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd) 131137608Sdes{ 131290267Sdes char *upw, *auth; 131390267Sdes int r; 131437608Sdes 1315202613Sdes DEBUG(fprintf(stderr, "basic: usr: [%s]\n", usr)); 1316202613Sdes DEBUG(fprintf(stderr, "basic: pwd: [%s]\n", pwd)); 131790267Sdes if (asprintf(&upw, "%s:%s", usr, pwd) == -1) 131890267Sdes return (-1); 1319174588Sdes auth = http_base64(upw); 132090267Sdes free(upw); 132190267Sdes if (auth == NULL) 132290267Sdes return (-1); 1323174588Sdes r = http_cmd(conn, "%s: Basic %s", hdr, auth); 132490267Sdes free(auth); 132590267Sdes return (r); 132662965Sdes} 132762965Sdes 132862965Sdes/* 1329221821Sdes * Chose the challenge to answer and call the appropriate routine to 1330202613Sdes * produce the header. 133162965Sdes */ 133262965Sdesstatic int 1333202613Sdeshttp_authorize(conn_t *conn, const char *hdr, http_auth_challenges_t *cs, 1334202613Sdes http_auth_params_t *parms, struct url *url) 133562965Sdes{ 1336202613Sdes http_auth_challenge_t *digest = NULL; 1337202613Sdes int i; 133862965Sdes 1339202613Sdes /* If user or pass are null we're not happy */ 1340202613Sdes if (!parms->user || !parms->password) { 1341202613Sdes DEBUG(fprintf(stderr, "NULL usr or pass\n")); 1342202613Sdes return (-1); 134390267Sdes } 1344202613Sdes 1345294194Sdes /* Look for a Digest */ 1346202613Sdes for (i = 0; i < cs->count; i++) { 1347202613Sdes if (cs->challenges[i]->scheme == HTTPAS_DIGEST) 1348202613Sdes digest = cs->challenges[i]; 1349202613Sdes } 1350202613Sdes 1351202613Sdes /* Error if "Digest" was specified and there is no Digest challenge */ 1352221821Sdes if (!digest && (parms->scheme && 1353202613Sdes !strcasecmp(parms->scheme, "digest"))) { 1354221821Sdes DEBUG(fprintf(stderr, 1355202613Sdes "Digest auth in env, not supported by peer\n")); 1356202613Sdes return (-1); 1357202613Sdes } 1358221821Sdes /* 1359221821Sdes * If "basic" was specified in the environment, or there is no Digest 1360202613Sdes * challenge, do the basic thing. Don't need a challenge for this, 1361221821Sdes * so no need to check basic!=NULL 1362202613Sdes */ 1363202613Sdes if (!digest || (parms->scheme && !strcasecmp(parms->scheme,"basic"))) 1364202613Sdes return (http_basic_auth(conn,hdr,parms->user,parms->password)); 1365202613Sdes 1366202613Sdes /* Else, prefer digest. We just checked that it's not NULL */ 1367202613Sdes return (http_digest_auth(conn, hdr, digest, parms, url)); 136837608Sdes} 136937608Sdes 137063012Sdes/***************************************************************************** 137163012Sdes * Helper functions for connecting to a server or proxy 137263012Sdes */ 137363012Sdes 137437608Sdes/* 137590267Sdes * Connect to the correct HTTP server or proxy. 137663012Sdes */ 137797856Sdesstatic conn_t * 1378174588Sdeshttp_connect(struct url *URL, struct url *purl, const char *flags) 137963012Sdes{ 1380249431Sdes struct url *curl; 138197856Sdes conn_t *conn; 1382294194Sdes hdr_t h; 1383294194Sdes http_headerbuf_t headerbuf; 1384294194Sdes const char *p; 138590267Sdes int verbose; 1386141958Skbyanc int af, val; 1387294194Sdes int serrno; 138890267Sdes 138963012Sdes#ifdef INET6 139090267Sdes af = AF_UNSPEC; 139160737Sume#else 139290267Sdes af = AF_INET; 139360737Sume#endif 139490267Sdes 139590267Sdes verbose = CHECK_FLAG('v'); 139690267Sdes if (CHECK_FLAG('4')) 139790267Sdes af = AF_INET; 139867043Sdes#ifdef INET6 139990267Sdes else if (CHECK_FLAG('6')) 140090267Sdes af = AF_INET6; 140167043Sdes#endif 140267043Sdes 1403249431Sdes curl = (purl != NULL) ? purl : URL; 140490267Sdes 1405249431Sdes if ((conn = fetch_connect(curl->host, curl->port, af, verbose)) == NULL) 1406174588Sdes /* fetch_connect() has already set an error code */ 140797856Sdes return (NULL); 1408294194Sdes init_http_headerbuf(&headerbuf); 1409249431Sdes if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 && purl) { 1410249431Sdes http_cmd(conn, "CONNECT %s:%d HTTP/1.1", 1411249431Sdes URL->host, URL->port); 1412254650Sdes http_cmd(conn, "Host: %s:%d", 1413254650Sdes URL->host, URL->port); 1414249431Sdes http_cmd(conn, ""); 1415249431Sdes if (http_get_reply(conn) != HTTP_OK) { 1416294194Sdes http_seterr(conn->err); 1417294194Sdes goto ouch; 1418249431Sdes } 1419294194Sdes /* Read and discard the rest of the proxy response */ 1420294194Sdes if (fetch_getln(conn) < 0) { 1421294194Sdes fetch_syserr(); 1422294194Sdes goto ouch; 1423294194Sdes } 1424294194Sdes do { 1425294194Sdes switch ((h = http_next_header(conn, &headerbuf, &p))) { 1426294194Sdes case hdr_syserror: 1427294194Sdes fetch_syserr(); 1428294194Sdes goto ouch; 1429294194Sdes case hdr_error: 1430294194Sdes http_seterr(HTTP_PROTOCOL_ERROR); 1431294194Sdes goto ouch; 1432294194Sdes default: 1433294194Sdes /* ignore */ ; 1434294194Sdes } 1435311864Sdes } while (h > hdr_end); 1436249431Sdes } 143797868Sdes if (strcasecmp(URL->scheme, SCHEME_HTTPS) == 0 && 1438253680Sdes fetch_ssl(conn, URL, verbose) == -1) { 143997891Sdes /* grrr */ 144097891Sdes errno = EAUTH; 1441174588Sdes fetch_syserr(); 1442294194Sdes goto ouch; 144397868Sdes } 1444141958Skbyanc 1445141958Skbyanc val = 1; 1446141958Skbyanc setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, sizeof(val)); 1447141958Skbyanc 1448294194Sdes clean_http_headerbuf(&headerbuf); 144997856Sdes return (conn); 1450294194Sdesouch: 1451294194Sdes serrno = errno; 1452294194Sdes clean_http_headerbuf(&headerbuf); 1453294194Sdes fetch_close(conn); 1454294194Sdes errno = serrno; 1455294194Sdes return (NULL); 145667043Sdes} 145767043Sdes 145867043Sdesstatic struct url * 1459174752Sdeshttp_get_proxy(struct url * url, const char *flags) 146067043Sdes{ 146190267Sdes struct url *purl; 146290267Sdes char *p; 146390267Sdes 1464112797Sdes if (flags != NULL && strchr(flags, 'd') != NULL) 1465112081Sdes return (NULL); 1466174752Sdes if (fetch_no_proxy_match(url->host)) 1467174752Sdes return (NULL); 146890267Sdes if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 1469149414Sdes *p && (purl = fetchParseURL(p))) { 147090267Sdes if (!*purl->scheme) 147190267Sdes strcpy(purl->scheme, SCHEME_HTTP); 147290267Sdes if (!purl->port) 1473174588Sdes purl->port = fetch_default_proxy_port(purl->scheme); 147490267Sdes if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 147590267Sdes return (purl); 147690267Sdes fetchFreeURL(purl); 147790267Sdes } 147890267Sdes return (NULL); 147960376Sdes} 148060376Sdes 148188771Sdesstatic void 1482174588Sdeshttp_print_html(FILE *out, FILE *in) 148388771Sdes{ 148490267Sdes size_t len; 148590267Sdes char *line, *p, *q; 148690267Sdes int comment, tag; 148788771Sdes 148890267Sdes comment = tag = 0; 148990267Sdes while ((line = fgetln(in, &len)) != NULL) { 1490174761Sdes while (len && isspace((unsigned char)line[len - 1])) 149190267Sdes --len; 149290267Sdes for (p = q = line; q < line + len; ++q) { 149390267Sdes if (comment && *q == '-') { 149490267Sdes if (q + 2 < line + len && 149590267Sdes strcmp(q, "-->") == 0) { 149690267Sdes tag = comment = 0; 149790267Sdes q += 2; 149890267Sdes } 149990267Sdes } else if (tag && !comment && *q == '>') { 150090267Sdes p = q + 1; 150190267Sdes tag = 0; 150290267Sdes } else if (!tag && *q == '<') { 150390267Sdes if (q > p) 150490267Sdes fwrite(p, q - p, 1, out); 150590267Sdes tag = 1; 150690267Sdes if (q + 3 < line + len && 150790267Sdes strcmp(q, "<!--") == 0) { 150890267Sdes comment = 1; 150990267Sdes q += 3; 151090267Sdes } 151190267Sdes } 151288771Sdes } 151390267Sdes if (!tag && q > p) 151490267Sdes fwrite(p, q - p, 1, out); 151590267Sdes fputc('\n', out); 151688771Sdes } 151788771Sdes} 151888771Sdes 151990267Sdes 152063012Sdes/***************************************************************************** 152163012Sdes * Core 152260954Sdes */ 152360954Sdes 1524268900SbaptFILE * 1525268900Sbapthttp_request(struct url *URL, const char *op, struct url_stat *us, 1526268900Sbapt struct url *purl, const char *flags) 1527268900Sbapt{ 1528268900Sbapt 1529268900Sbapt return (http_request_body(URL, op, us, purl, flags, NULL, NULL)); 1530268900Sbapt} 1531268900Sbapt 153260954Sdes/* 153363012Sdes * Send a request and process the reply 153497866Sdes * 153597866Sdes * XXX This function is way too long, the do..while loop should be split 153697866Sdes * XXX off into a separate function. 153760376Sdes */ 153867043SdesFILE * 1539268900Sbapthttp_request_body(struct url *URL, const char *op, struct url_stat *us, 1540268900Sbapt struct url *purl, const char *flags, const char *content_type, 1541268900Sbapt const char *body) 154260376Sdes{ 1543186124Smurray char timebuf[80]; 1544186124Smurray char hbuf[MAXHOSTNAMELEN + 7], *host; 154597856Sdes conn_t *conn; 154690267Sdes struct url *url, *new; 1547202613Sdes int chunked, direct, ims, noredirect, verbose; 1548143049Skbyanc int e, i, n, val; 154990267Sdes off_t offset, clength, length, size; 155090267Sdes time_t mtime; 155190267Sdes const char *p; 155290267Sdes FILE *f; 155390267Sdes hdr_t h; 1554186124Smurray struct tm *timestruct; 1555202613Sdes http_headerbuf_t headerbuf; 1556202613Sdes http_auth_challenges_t server_challenges; 1557202613Sdes http_auth_challenges_t proxy_challenges; 1558268900Sbapt size_t body_len; 155963012Sdes 1560202613Sdes /* The following calls don't allocate anything */ 1561221821Sdes init_http_headerbuf(&headerbuf); 1562202613Sdes init_http_auth_challenges(&server_challenges); 1563202613Sdes init_http_auth_challenges(&proxy_challenges); 1564202613Sdes 156590267Sdes direct = CHECK_FLAG('d'); 156690267Sdes noredirect = CHECK_FLAG('A'); 156790267Sdes verbose = CHECK_FLAG('v'); 1568186124Smurray ims = CHECK_FLAG('i'); 156960737Sume 157090267Sdes if (direct && purl) { 157190267Sdes fetchFreeURL(purl); 157290267Sdes purl = NULL; 157390267Sdes } 157463716Sdes 157590267Sdes /* try the provided URL first */ 157690267Sdes url = URL; 157763012Sdes 1578241840Seadler n = MAX_REDIRECT; 157990267Sdes i = 0; 158063012Sdes 158198422Sdes e = HTTP_PROTOCOL_ERROR; 158290267Sdes do { 158390267Sdes new = NULL; 158490267Sdes chunked = 0; 158590267Sdes offset = 0; 158690267Sdes clength = -1; 158790267Sdes length = -1; 158890267Sdes size = -1; 158990267Sdes mtime = 0; 159090267Sdes 159190267Sdes /* check port */ 159290267Sdes if (!url->port) 1593174588Sdes url->port = fetch_default_port(url->scheme); 159490267Sdes 159590267Sdes /* were we redirected to an FTP URL? */ 159690267Sdes if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) { 159790267Sdes if (strcmp(op, "GET") == 0) 1598174588Sdes return (ftp_request(url, "RETR", us, purl, flags)); 159990267Sdes else if (strcmp(op, "HEAD") == 0) 1600174588Sdes return (ftp_request(url, "STAT", us, purl, flags)); 160190267Sdes } 160290267Sdes 160390267Sdes /* connect to server or proxy */ 1604174588Sdes if ((conn = http_connect(url, purl, flags)) == NULL) 160590267Sdes goto ouch; 160690267Sdes 1607315904Sdes /* append port number only if necessary */ 160890267Sdes host = url->host; 1609315904Sdes if (url->port != fetch_default_port(url->scheme)) { 1610315904Sdes snprintf(hbuf, sizeof(hbuf), "%s:%d", host, url->port); 161190267Sdes host = hbuf; 161290267Sdes } 161337535Sdes 161490267Sdes /* send request */ 161590267Sdes if (verbose) 1616174588Sdes fetch_info("requesting %s://%s%s", 1617107372Sdes url->scheme, host, url->doc); 1618253514Sdes if (purl && strcasecmp(URL->scheme, SCHEME_HTTPS) != 0) { 1619174588Sdes http_cmd(conn, "%s %s://%s%s HTTP/1.1", 1620107372Sdes op, url->scheme, host, url->doc); 162190267Sdes } else { 1622174588Sdes http_cmd(conn, "%s %s HTTP/1.1", 162390267Sdes op, url->doc); 162490267Sdes } 162537535Sdes 1626186124Smurray if (ims && url->ims_time) { 1627186124Smurray timestruct = gmtime((time_t *)&url->ims_time); 1628186124Smurray (void)strftime(timebuf, 80, "%a, %d %b %Y %T GMT", 1629186124Smurray timestruct); 1630186124Smurray if (verbose) 1631186124Smurray fetch_info("If-Modified-Since: %s", timebuf); 1632186124Smurray http_cmd(conn, "If-Modified-Since: %s", timebuf); 1633186124Smurray } 163490267Sdes /* virtual host */ 1635174588Sdes http_cmd(conn, "Host: %s", host); 163690267Sdes 1637221821Sdes /* 1638221821Sdes * Proxy authorization: we only send auth after we received 1639221821Sdes * a 407 error. We do not first try basic anyway (changed 1640221821Sdes * when support was added for digest-auth) 1641221821Sdes */ 1642202613Sdes if (purl && proxy_challenges.valid) { 1643202613Sdes http_auth_params_t aparams; 1644202613Sdes init_http_auth_params(&aparams); 1645202613Sdes if (*purl->user || *purl->pwd) { 1646284643Sdim aparams.user = strdup(purl->user); 1647284643Sdim aparams.password = strdup(purl->pwd); 1648221821Sdes } else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && 1649202613Sdes *p != '\0') { 1650202613Sdes if (http_authfromenv(p, &aparams) < 0) { 1651202613Sdes http_seterr(HTTP_NEED_PROXY_AUTH); 1652202613Sdes goto ouch; 1653202613Sdes } 1654294194Sdes } else if (fetch_netrc_auth(purl) == 0) { 1655294194Sdes aparams.user = strdup(purl->user); 1656294194Sdes aparams.password = strdup(purl->pwd); 1657202613Sdes } 1658221821Sdes http_authorize(conn, "Proxy-Authorization", 1659202613Sdes &proxy_challenges, &aparams, url); 1660202613Sdes clean_http_auth_params(&aparams); 166190267Sdes } 166290267Sdes 1663221821Sdes /* 1664221821Sdes * Server authorization: we never send "a priori" 1665202613Sdes * Basic auth, which used to be done if user/pass were 1666202613Sdes * set in the url. This would be weird because we'd send the 1667221821Sdes * password in the clear even if Digest is finally to be 1668202613Sdes * used (it would have made more sense for the 1669221821Sdes * pre-digest version to do this when Basic was specified 1670221821Sdes * in the environment) 1671221821Sdes */ 1672202613Sdes if (server_challenges.valid) { 1673202613Sdes http_auth_params_t aparams; 1674202613Sdes init_http_auth_params(&aparams); 1675202613Sdes if (*url->user || *url->pwd) { 1676284643Sdim aparams.user = strdup(url->user); 1677284643Sdim aparams.password = strdup(url->pwd); 1678221821Sdes } else if ((p = getenv("HTTP_AUTH")) != NULL && 1679202613Sdes *p != '\0') { 1680202613Sdes if (http_authfromenv(p, &aparams) < 0) { 1681202613Sdes http_seterr(HTTP_NEED_AUTH); 1682202613Sdes goto ouch; 1683202613Sdes } 1684294194Sdes } else if (fetch_netrc_auth(url) == 0) { 1685294194Sdes aparams.user = strdup(url->user); 1686294194Sdes aparams.password = strdup(url->pwd); 1687221821Sdes } else if (fetchAuthMethod && 1688202613Sdes fetchAuthMethod(url) == 0) { 1689284643Sdim aparams.user = strdup(url->user); 1690284643Sdim aparams.password = strdup(url->pwd); 169190267Sdes } else { 1692174588Sdes http_seterr(HTTP_NEED_AUTH); 169390267Sdes goto ouch; 169490267Sdes } 1695221821Sdes http_authorize(conn, "Authorization", 1696202613Sdes &server_challenges, &aparams, url); 1697202613Sdes clean_http_auth_params(&aparams); 169890267Sdes } 169990267Sdes 170090267Sdes /* other headers */ 1701253805Sdes if ((p = getenv("HTTP_ACCEPT")) != NULL) { 1702253805Sdes if (*p != '\0') 1703253805Sdes http_cmd(conn, "Accept: %s", p); 1704253805Sdes } else { 1705253805Sdes http_cmd(conn, "Accept: */*"); 1706253805Sdes } 1707107372Sdes if ((p = getenv("HTTP_REFERER")) != NULL && *p != '\0') { 1708107372Sdes if (strcasecmp(p, "auto") == 0) 1709174588Sdes http_cmd(conn, "Referer: %s://%s%s", 1710107372Sdes url->scheme, host, url->doc); 1711107372Sdes else 1712174588Sdes http_cmd(conn, "Referer: %s", p); 1713107372Sdes } 1714270460Sdes if ((p = getenv("HTTP_USER_AGENT")) != NULL) { 1715270460Sdes /* no User-Agent if defined but empty */ 1716270460Sdes if (*p != '\0') 1717270460Sdes http_cmd(conn, "User-Agent: %s", p); 1718270460Sdes } else { 1719270460Sdes /* default User-Agent */ 1720270460Sdes http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, 1721270460Sdes getprogname()); 1722270460Sdes } 1723109693Sdes if (url->offset > 0) 1724174588Sdes http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset); 1725174588Sdes http_cmd(conn, "Connection: close"); 1726268900Sbapt 1727268900Sbapt if (body) { 1728268900Sbapt body_len = strlen(body); 1729268900Sbapt http_cmd(conn, "Content-Length: %zu", body_len); 1730268900Sbapt if (content_type != NULL) 1731268900Sbapt http_cmd(conn, "Content-Type: %s", content_type); 1732268900Sbapt } 1733268900Sbapt 1734174588Sdes http_cmd(conn, ""); 173590267Sdes 1736268900Sbapt if (body) 1737268900Sbapt fetch_write(conn, body, body_len); 1738268900Sbapt 1739143049Skbyanc /* 1740143049Skbyanc * Force the queued request to be dispatched. Normally, one 1741143049Skbyanc * would do this with shutdown(2) but squid proxies can be 1742143049Skbyanc * configured to disallow such half-closed connections. To 1743143049Skbyanc * be compatible with such configurations, fiddle with socket 1744143049Skbyanc * options to force the pending data to be written. 1745143049Skbyanc */ 1746143049Skbyanc val = 0; 1747143049Skbyanc setsockopt(conn->sd, IPPROTO_TCP, TCP_NOPUSH, &val, 1748143049Skbyanc sizeof(val)); 1749143049Skbyanc val = 1; 1750143049Skbyanc setsockopt(conn->sd, IPPROTO_TCP, TCP_NODELAY, &val, 1751143049Skbyanc sizeof(val)); 1752143049Skbyanc 175390267Sdes /* get reply */ 1754174588Sdes switch (http_get_reply(conn)) { 175590267Sdes case HTTP_OK: 175690267Sdes case HTTP_PARTIAL: 1757186124Smurray case HTTP_NOT_MODIFIED: 175890267Sdes /* fine */ 175990267Sdes break; 176090267Sdes case HTTP_MOVED_PERM: 176190267Sdes case HTTP_MOVED_TEMP: 1762311864Sdes case HTTP_TEMP_REDIRECT: 1763311864Sdes case HTTP_PERM_REDIRECT: 176490267Sdes case HTTP_SEE_OTHER: 1765241841Seadler case HTTP_USE_PROXY: 176690267Sdes /* 1767125695Sdes * Not so fine, but we still have to read the 1768125695Sdes * headers to get the new location. 176990267Sdes */ 177090267Sdes break; 177190267Sdes case HTTP_NEED_AUTH: 1772202613Sdes if (server_challenges.valid) { 177390267Sdes /* 1774125695Sdes * We already sent out authorization code, 1775125695Sdes * so there's nothing more we can do. 177690267Sdes */ 1777174588Sdes http_seterr(conn->err); 177890267Sdes goto ouch; 177990267Sdes } 178090267Sdes /* try again, but send the password this time */ 178190267Sdes if (verbose) 1782174588Sdes fetch_info("server requires authorization"); 178390267Sdes break; 178490267Sdes case HTTP_NEED_PROXY_AUTH: 1785202613Sdes if (proxy_challenges.valid) { 1786202613Sdes /* 1787202613Sdes * We already sent our proxy 1788202613Sdes * authorization code, so there's 1789202613Sdes * nothing more we can do. */ 1790202613Sdes http_seterr(conn->err); 1791202613Sdes goto ouch; 1792202613Sdes } 1793202613Sdes /* try again, but send the password this time */ 1794202613Sdes if (verbose) 1795202613Sdes fetch_info("proxy requires authorization"); 1796202613Sdes break; 1797125696Sdes case HTTP_BAD_RANGE: 1798125696Sdes /* 1799125696Sdes * This can happen if we ask for 0 bytes because 1800125696Sdes * we already have the whole file. Consider this 1801125696Sdes * a success for now, and check sizes later. 1802125696Sdes */ 1803125696Sdes break; 180490267Sdes case HTTP_PROTOCOL_ERROR: 180590267Sdes /* fall through */ 180690267Sdes case -1: 1807174588Sdes fetch_syserr(); 180890267Sdes goto ouch; 180990267Sdes default: 1810174588Sdes http_seterr(conn->err); 181190267Sdes if (!verbose) 181290267Sdes goto ouch; 181390267Sdes /* fall through so we can get the full error message */ 181490267Sdes } 181590267Sdes 1816202613Sdes /* get headers. http_next_header expects one line readahead */ 1817202613Sdes if (fetch_getln(conn) == -1) { 1818243149Sdes fetch_syserr(); 1819243149Sdes goto ouch; 1820202613Sdes } 182190267Sdes do { 1822243149Sdes switch ((h = http_next_header(conn, &headerbuf, &p))) { 182390267Sdes case hdr_syserror: 1824174588Sdes fetch_syserr(); 182590267Sdes goto ouch; 182690267Sdes case hdr_error: 1827174588Sdes http_seterr(HTTP_PROTOCOL_ERROR); 182890267Sdes goto ouch; 182990267Sdes case hdr_content_length: 1830174588Sdes http_parse_length(p, &clength); 183190267Sdes break; 183290267Sdes case hdr_content_range: 1833174588Sdes http_parse_range(p, &offset, &length, &size); 183490267Sdes break; 183590267Sdes case hdr_last_modified: 1836174588Sdes http_parse_mtime(p, &mtime); 183790267Sdes break; 183890267Sdes case hdr_location: 183997856Sdes if (!HTTP_REDIRECT(conn->err)) 184090267Sdes break; 1841241840Seadler /* 1842241840Seadler * if the A flag is set, we don't follow 1843241840Seadler * temporary redirects. 1844241840Seadler */ 1845241840Seadler if (noredirect && 1846241840Seadler conn->err != HTTP_MOVED_PERM && 1847241841Seadler conn->err != HTTP_PERM_REDIRECT && 1848241841Seadler conn->err != HTTP_USE_PROXY) { 1849241840Seadler n = 1; 1850241840Seadler break; 1851243149Sdes } 185290267Sdes if (new) 185390267Sdes free(new); 185490267Sdes if (verbose) 1855174588Sdes fetch_info("%d redirect to %s", conn->err, p); 185690267Sdes if (*p == '/') 185790267Sdes /* absolute path */ 185890267Sdes new = fetchMakeURL(url->scheme, url->host, url->port, p, 185990267Sdes url->user, url->pwd); 186090267Sdes else 186190267Sdes new = fetchParseURL(p); 186290267Sdes if (new == NULL) { 186390267Sdes /* XXX should set an error code */ 186490267Sdes DEBUG(fprintf(stderr, "failed to parse new URL\n")); 186590267Sdes goto ouch; 186690267Sdes } 1867234838Sdes 1868234838Sdes /* Only copy credentials if the host matches */ 1869234838Sdes if (!strcmp(new->host, url->host) && !*new->user && !*new->pwd) { 187090267Sdes strcpy(new->user, url->user); 187190267Sdes strcpy(new->pwd, url->pwd); 187290267Sdes } 187390267Sdes new->offset = url->offset; 187490267Sdes new->length = url->length; 187590267Sdes break; 187690267Sdes case hdr_transfer_encoding: 187790267Sdes /* XXX weak test*/ 187890267Sdes chunked = (strcasecmp(p, "chunked") == 0); 187990267Sdes break; 188090267Sdes case hdr_www_authenticate: 188197856Sdes if (conn->err != HTTP_NEED_AUTH) 188290267Sdes break; 1883210563Sdes if (http_parse_authenticate(p, &server_challenges) == 0) 1884209632Sdes ++n; 188590267Sdes break; 1886202613Sdes case hdr_proxy_authenticate: 1887202613Sdes if (conn->err != HTTP_NEED_PROXY_AUTH) 1888202613Sdes break; 1889210563Sdes if (http_parse_authenticate(p, &proxy_challenges) == 0) 1890209632Sdes ++n; 1891202613Sdes break; 189290267Sdes case hdr_end: 189390267Sdes /* fall through */ 189490267Sdes case hdr_unknown: 189590267Sdes /* ignore */ 189690267Sdes break; 189790267Sdes } 189890267Sdes } while (h > hdr_end); 189990267Sdes 190090267Sdes /* we need to provide authentication */ 1901221821Sdes if (conn->err == HTTP_NEED_AUTH || 1902202613Sdes conn->err == HTTP_NEED_PROXY_AUTH) { 190398422Sdes e = conn->err; 1904221821Sdes if ((conn->err == HTTP_NEED_AUTH && 1905221821Sdes !server_challenges.valid) || 1906221821Sdes (conn->err == HTTP_NEED_PROXY_AUTH && 1907202613Sdes !proxy_challenges.valid)) { 1908202613Sdes /* 401/7 but no www/proxy-authenticate ?? */ 1909202613Sdes DEBUG(fprintf(stderr, "401/7 and no auth header\n")); 1910202613Sdes goto ouch; 1911202613Sdes } 1912174588Sdes fetch_close(conn); 191397856Sdes conn = NULL; 191490267Sdes continue; 191590267Sdes } 191690267Sdes 1917125696Sdes /* requested range not satisfiable */ 1918125696Sdes if (conn->err == HTTP_BAD_RANGE) { 1919315904Sdes if (url->offset > 0 && url->length == 0) { 1920125696Sdes /* asked for 0 bytes; fake it */ 1921125696Sdes offset = url->offset; 1922184222Sru clength = -1; 1923125696Sdes conn->err = HTTP_OK; 1924125696Sdes break; 1925125696Sdes } else { 1926174588Sdes http_seterr(conn->err); 1927125696Sdes goto ouch; 1928125696Sdes } 1929125696Sdes } 1930125696Sdes 1931104404Sru /* we have a hit or an error */ 1932186124Smurray if (conn->err == HTTP_OK 1933186124Smurray || conn->err == HTTP_NOT_MODIFIED 1934186124Smurray || conn->err == HTTP_PARTIAL 1935186124Smurray || HTTP_ERROR(conn->err)) 1936104404Sru break; 1937104404Sru 193890267Sdes /* all other cases: we got a redirect */ 193998422Sdes e = conn->err; 1940202613Sdes clean_http_auth_challenges(&server_challenges); 1941174588Sdes fetch_close(conn); 194297856Sdes conn = NULL; 194390267Sdes if (!new) { 194490267Sdes DEBUG(fprintf(stderr, "redirect with no new location\n")); 194590267Sdes break; 194690267Sdes } 194790267Sdes if (url != URL) 194890267Sdes fetchFreeURL(url); 194990267Sdes url = new; 195090267Sdes } while (++i < n); 195190267Sdes 195290267Sdes /* we failed, or ran out of retries */ 195397856Sdes if (conn == NULL) { 1954174588Sdes http_seterr(e); 195563012Sdes goto ouch; 195663012Sdes } 195760376Sdes 195890267Sdes DEBUG(fprintf(stderr, "offset %lld, length %lld," 195990267Sdes " size %lld, clength %lld\n", 196090267Sdes (long long)offset, (long long)length, 196190267Sdes (long long)size, (long long)clength)); 196260376Sdes 1963186124Smurray if (conn->err == HTTP_NOT_MODIFIED) { 1964186124Smurray http_seterr(HTTP_NOT_MODIFIED); 1965186124Smurray return (NULL); 1966186124Smurray } 1967186124Smurray 196890267Sdes /* check for inconsistencies */ 196990267Sdes if (clength != -1 && length != -1 && clength != length) { 1970174588Sdes http_seterr(HTTP_PROTOCOL_ERROR); 197163012Sdes goto ouch; 197263012Sdes } 197390267Sdes if (clength == -1) 197490267Sdes clength = length; 197590267Sdes if (clength != -1) 197690267Sdes length = offset + clength; 197790267Sdes if (length != -1 && size != -1 && length != size) { 1978174588Sdes http_seterr(HTTP_PROTOCOL_ERROR); 197963012Sdes goto ouch; 198090267Sdes } 198190267Sdes if (size == -1) 198290267Sdes size = length; 198360376Sdes 198490267Sdes /* fill in stats */ 198590267Sdes if (us) { 198690267Sdes us->size = size; 198790267Sdes us->atime = us->mtime = mtime; 198890267Sdes } 198963069Sdes 199090267Sdes /* too far? */ 1991109693Sdes if (URL->offset > 0 && offset > URL->offset) { 1992174588Sdes http_seterr(HTTP_PROTOCOL_ERROR); 199390267Sdes goto ouch; 199477238Sdes } 199560376Sdes 199690267Sdes /* report back real offset and size */ 199790267Sdes URL->offset = offset; 199890267Sdes URL->length = clength; 199937535Sdes 200090267Sdes /* wrap it up in a FILE */ 2001174588Sdes if ((f = http_funopen(conn, chunked)) == NULL) { 2002174588Sdes fetch_syserr(); 200390267Sdes goto ouch; 200490267Sdes } 200563716Sdes 200690267Sdes if (url != URL) 200790267Sdes fetchFreeURL(url); 200890267Sdes if (purl) 200990267Sdes fetchFreeURL(purl); 201063567Sdes 201197856Sdes if (HTTP_ERROR(conn->err)) { 2012174588Sdes http_print_html(stderr, f); 201390267Sdes fclose(f); 201490267Sdes f = NULL; 201590267Sdes } 2016202613Sdes clean_http_headerbuf(&headerbuf); 2017202613Sdes clean_http_auth_challenges(&server_challenges); 2018202613Sdes clean_http_auth_challenges(&proxy_challenges); 201990267Sdes return (f); 202088771Sdes 202190267Sdesouch: 202290267Sdes if (url != URL) 202390267Sdes fetchFreeURL(url); 202490267Sdes if (purl) 202590267Sdes fetchFreeURL(purl); 202697856Sdes if (conn != NULL) 2027174588Sdes fetch_close(conn); 2028202613Sdes clean_http_headerbuf(&headerbuf); 2029202613Sdes clean_http_auth_challenges(&server_challenges); 2030202613Sdes clean_http_auth_challenges(&proxy_challenges); 203190267Sdes return (NULL); 203263012Sdes} 203360189Sdes 203490267Sdes 203563012Sdes/***************************************************************************** 203663012Sdes * Entry points 203763012Sdes */ 203863012Sdes 203963012Sdes/* 204063340Sdes * Retrieve and stat a file by HTTP 204163340Sdes */ 204263340SdesFILE * 204375891SarchiefetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags) 204463340Sdes{ 2045174752Sdes return (http_request(URL, "GET", us, http_get_proxy(URL, flags), flags)); 204663340Sdes} 204763340Sdes 204863340Sdes/* 204963012Sdes * Retrieve a file by HTTP 205063012Sdes */ 205163012SdesFILE * 205275891SarchiefetchGetHTTP(struct url *URL, const char *flags) 205363012Sdes{ 205490267Sdes return (fetchXGetHTTP(URL, NULL, flags)); 205537535Sdes} 205637535Sdes 205763340Sdes/* 205863340Sdes * Store a file by HTTP 205963340Sdes */ 206037535SdesFILE * 206185093SdesfetchPutHTTP(struct url *URL __unused, const char *flags __unused) 206237535Sdes{ 206390267Sdes warnx("fetchPutHTTP(): not implemented"); 206490267Sdes return (NULL); 206537535Sdes} 206640975Sdes 206740975Sdes/* 206840975Sdes * Get an HTTP document's metadata 206940975Sdes */ 207040975Sdesint 207175891SarchiefetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags) 207240975Sdes{ 207390267Sdes FILE *f; 207490267Sdes 2075174752Sdes f = http_request(URL, "HEAD", us, http_get_proxy(URL, flags), flags); 2076112081Sdes if (f == NULL) 207790267Sdes return (-1); 207890267Sdes fclose(f); 207990267Sdes return (0); 208040975Sdes} 208141989Sdes 208241989Sdes/* 208341989Sdes * List a directory 208441989Sdes */ 208541989Sdesstruct url_ent * 208685093SdesfetchListHTTP(struct url *url __unused, const char *flags __unused) 208741989Sdes{ 208890267Sdes warnx("fetchListHTTP(): not implemented"); 208990267Sdes return (NULL); 209041989Sdes} 2091268900Sbapt 2092268900SbaptFILE * 2093268900SbaptfetchReqHTTP(struct url *URL, const char *method, const char *flags, 2094268900Sbapt const char *content_type, const char *body) 2095268900Sbapt{ 2096268900Sbapt 2097268900Sbapt return (http_request_body(URL, method, NULL, http_get_proxy(URL, flags), 2098268900Sbapt flags, content_type, body)); 2099268900Sbapt} 2100