http.c revision 87317
137535Sdes/*- 263012Sdes * Copyright (c) 2000 Dag-Erling Co�dan 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: head/lib/libfetch/http.c 87317 2001-12-04 01:12:51Z 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. 4963236Sdes * 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> 6637535Sdes 6763012Sdes#include <ctype.h> 6837535Sdes#include <err.h> 6963012Sdes#include <errno.h> 7060376Sdes#include <locale.h> 7160189Sdes#include <netdb.h> 7237608Sdes#include <stdarg.h> 7337535Sdes#include <stdio.h> 7437535Sdes#include <stdlib.h> 7537535Sdes#include <string.h> 7660376Sdes#include <time.h> 7737535Sdes#include <unistd.h> 7837535Sdes 7937535Sdes#include "fetch.h" 8040939Sdes#include "common.h" 8141862Sdes#include "httperr.h" 8237535Sdes 8363012Sdesextern char *__progname; /* XXX not portable */ 8437535Sdes 8563012Sdes/* Maximum number of redirects to follow */ 8663012Sdes#define MAX_REDIRECT 5 8737535Sdes 8863012Sdes/* Symbolic names for reply codes we care about */ 8963012Sdes#define HTTP_OK 200 9063012Sdes#define HTTP_PARTIAL 206 9163012Sdes#define HTTP_MOVED_PERM 301 9263012Sdes#define HTTP_MOVED_TEMP 302 9363012Sdes#define HTTP_SEE_OTHER 303 9463012Sdes#define HTTP_NEED_AUTH 401 9587317Sdes#define HTTP_NEED_PROXY_AUTH 407 9663012Sdes#define HTTP_PROTOCOL_ERROR 999 9760196Sdes 9863012Sdes#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \ 9963012Sdes || (xyz) == HTTP_MOVED_TEMP \ 10063012Sdes || (xyz) == HTTP_SEE_OTHER) 10163012Sdes 10263012Sdes 10363012Sdes 10463012Sdes/***************************************************************************** 10563012Sdes * I/O functions for decoding chunked streams 10663012Sdes */ 10763012Sdes 10837535Sdesstruct cookie 10937535Sdes{ 11063012Sdes int fd; 11163012Sdes char *buf; 11263012Sdes size_t b_size; 11385093Sdes ssize_t b_len; 11463012Sdes int b_pos; 11563012Sdes int eof; 11663012Sdes int error; 11785093Sdes size_t chunksize; 11863281Sdes#ifndef NDEBUG 11985093Sdes size_t total; 12063012Sdes#endif 12137535Sdes}; 12237535Sdes 12337608Sdes/* 12463012Sdes * Get next chunk header 12537608Sdes */ 12637608Sdesstatic int 12763012Sdes_http_new_chunk(struct cookie *c) 12837608Sdes{ 12963012Sdes char *p; 13037608Sdes 13163012Sdes if (_fetch_getln(c->fd, &c->buf, &c->b_size, &c->b_len) == -1) 13263012Sdes return -1; 13363012Sdes 13463012Sdes if (c->b_len < 2 || !ishexnumber(*c->buf)) 13563012Sdes return -1; 13663012Sdes 13763012Sdes for (p = c->buf; !isspace(*p) && *p != ';' && p < c->buf + c->b_len; ++p) 13863012Sdes if (!ishexnumber(*p)) 13963012Sdes return -1; 14063012Sdes else if (isdigit(*p)) 14163012Sdes c->chunksize = c->chunksize * 16 + *p - '0'; 14263012Sdes else 14363012Sdes c->chunksize = c->chunksize * 16 + 10 + tolower(*p) - 'a'; 14463012Sdes 14563281Sdes#ifndef NDEBUG 14663012Sdes c->total += c->chunksize; 14763012Sdes if (c->chunksize == 0) 14863012Sdes fprintf(stderr, "\033[1m_http_fillbuf(): " 14963012Sdes "end of last chunk\033[m\n"); 15063012Sdes else 15163012Sdes fprintf(stderr, "\033[1m_http_fillbuf(): " 15285093Sdes "new chunk: %lu (%lu)\033[m\n", 15385093Sdes (unsigned long)c->chunksize, (unsigned long)c->total); 15463012Sdes#endif 15563012Sdes 15663012Sdes return c->chunksize; 15737608Sdes} 15837608Sdes 15937608Sdes/* 16037608Sdes * Fill the input buffer, do chunk decoding on the fly 16137608Sdes */ 16263012Sdesstatic int 16337535Sdes_http_fillbuf(struct cookie *c) 16437535Sdes{ 16563012Sdes if (c->error) 16663012Sdes return -1; 16737535Sdes if (c->eof) 16863012Sdes return 0; 16963012Sdes 17063012Sdes if (c->chunksize == 0) { 17163012Sdes switch (_http_new_chunk(c)) { 17263012Sdes case -1: 17363012Sdes c->error = 1; 17463012Sdes return -1; 17563012Sdes case 0: 17663012Sdes c->eof = 1; 17763012Sdes return 0; 17837535Sdes } 17937535Sdes } 18063012Sdes 18163012Sdes if (c->b_size < c->chunksize) { 18263012Sdes char *tmp; 18363012Sdes 18463012Sdes if ((tmp = realloc(c->buf, c->chunksize)) == NULL) 18563012Sdes return -1; 18663012Sdes c->buf = tmp; 18763012Sdes c->b_size = c->chunksize; 18863012Sdes } 18963012Sdes 19063012Sdes if ((c->b_len = read(c->fd, c->buf, c->chunksize)) == -1) 19163012Sdes return -1; 19263012Sdes c->chunksize -= c->b_len; 19363012Sdes 19463012Sdes if (c->chunksize == 0) { 19563012Sdes char endl[2]; 19663012Sdes read(c->fd, endl, 2); 19763012Sdes } 19863012Sdes 19963012Sdes c->b_pos = 0; 20063012Sdes 20163012Sdes return c->b_len; 20237535Sdes} 20337535Sdes 20437608Sdes/* 20537608Sdes * Read function 20637608Sdes */ 20737535Sdesstatic int 20863012Sdes_http_readfn(void *v, char *buf, int len) 20937535Sdes{ 21063012Sdes struct cookie *c = (struct cookie *)v; 21163012Sdes int l, pos; 21263012Sdes 21363012Sdes if (c->error) 21463012Sdes return -1; 21563012Sdes if (c->eof) 21663012Sdes return 0; 21763012Sdes 21863012Sdes for (pos = 0; len > 0; pos += l, len -= l) { 21937535Sdes /* empty buffer */ 22063012Sdes if (!c->buf || c->b_pos == c->b_len) 22163012Sdes if (_http_fillbuf(c) < 1) 22237535Sdes break; 22363012Sdes l = c->b_len - c->b_pos; 22463012Sdes if (len < l) 22563012Sdes l = len; 22663012Sdes bcopy(c->buf + c->b_pos, buf + pos, l); 22763012Sdes c->b_pos += l; 22863012Sdes } 22937535Sdes 23063012Sdes if (!pos && c->error) 23137535Sdes return -1; 23263012Sdes return pos; 23337535Sdes} 23437535Sdes 23537608Sdes/* 23637608Sdes * Write function 23737608Sdes */ 23837535Sdesstatic int 23963012Sdes_http_writefn(void *v, const char *buf, int len) 24037535Sdes{ 24163012Sdes struct cookie *c = (struct cookie *)v; 24263012Sdes 24363012Sdes return write(c->fd, buf, len); 24437535Sdes} 24537535Sdes 24637608Sdes/* 24737608Sdes * Close function 24837608Sdes */ 24937535Sdesstatic int 25063012Sdes_http_closefn(void *v) 25137535Sdes{ 25263012Sdes struct cookie *c = (struct cookie *)v; 25363012Sdes int r; 25463012Sdes 25563012Sdes r = close(c->fd); 25663012Sdes if (c->buf) 25763012Sdes free(c->buf); 25837535Sdes free(c); 25963012Sdes return r; 26037535Sdes} 26137535Sdes 26237608Sdes/* 26363012Sdes * Wrap a file descriptor up 26437608Sdes */ 26563012Sdesstatic FILE * 26663012Sdes_http_funopen(int fd) 26737535Sdes{ 26863012Sdes struct cookie *c; 26963012Sdes FILE *f; 27063012Sdes 27163012Sdes if ((c = calloc(1, sizeof *c)) == NULL) { 27263012Sdes _fetch_syserr(); 27363012Sdes return NULL; 27463012Sdes } 27563012Sdes c->fd = fd; 27663012Sdes if (!(f = funopen(c, _http_readfn, _http_writefn, NULL, _http_closefn))) { 27763012Sdes _fetch_syserr(); 27863012Sdes free(c); 27963012Sdes return NULL; 28063012Sdes } 28163012Sdes return f; 28263012Sdes} 28363012Sdes 28463012Sdes 28563012Sdes/***************************************************************************** 28663012Sdes * Helper functions for talking to the server and parsing its replies 28763012Sdes */ 28863012Sdes 28963012Sdes/* Header types */ 29063012Sdestypedef enum { 29163012Sdes hdr_syserror = -2, 29263012Sdes hdr_error = -1, 29363012Sdes hdr_end = 0, 29463012Sdes hdr_unknown = 1, 29563012Sdes hdr_content_length, 29663012Sdes hdr_content_range, 29763012Sdes hdr_last_modified, 29863012Sdes hdr_location, 29977238Sdes hdr_transfer_encoding, 30077238Sdes hdr_www_authenticate 30185093Sdes} hdr_t; 30263012Sdes 30363012Sdes/* Names of interesting headers */ 30463012Sdesstatic struct { 30585093Sdes hdr_t num; 30675891Sarchie const char *name; 30763012Sdes} hdr_names[] = { 30863012Sdes { hdr_content_length, "Content-Length" }, 30963012Sdes { hdr_content_range, "Content-Range" }, 31063012Sdes { hdr_last_modified, "Last-Modified" }, 31163012Sdes { hdr_location, "Location" }, 31263012Sdes { hdr_transfer_encoding, "Transfer-Encoding" }, 31377238Sdes { hdr_www_authenticate, "WWW-Authenticate" }, 31463012Sdes { hdr_unknown, NULL }, 31563012Sdes}; 31663012Sdes 31763012Sdesstatic char *reply_buf; 31863012Sdesstatic size_t reply_size; 31963012Sdesstatic size_t reply_length; 32063012Sdes 32163012Sdes/* 32263012Sdes * Send a formatted line; optionally echo to terminal 32363012Sdes */ 32463012Sdesstatic int 32575891Sarchie_http_cmd(int fd, const char *fmt, ...) 32663012Sdes{ 32763012Sdes va_list ap; 32863012Sdes size_t len; 32963012Sdes char *msg; 33063012Sdes int r; 33163012Sdes 33263012Sdes va_start(ap, fmt); 33363012Sdes len = vasprintf(&msg, fmt, ap); 33463012Sdes va_end(ap); 33563012Sdes 33663012Sdes if (msg == NULL) { 33763012Sdes errno = ENOMEM; 33863012Sdes _fetch_syserr(); 33963012Sdes return -1; 34063012Sdes } 34163012Sdes 34263012Sdes r = _fetch_putln(fd, msg, len); 34363012Sdes free(msg); 34463012Sdes 34563012Sdes if (r == -1) { 34663012Sdes _fetch_syserr(); 34763012Sdes return -1; 34863012Sdes } 34963012Sdes 35063012Sdes return 0; 35163012Sdes} 35263012Sdes 35363012Sdes/* 35463012Sdes * Get and parse status line 35563012Sdes */ 35663012Sdesstatic int 35763012Sdes_http_get_reply(int fd) 35863012Sdes{ 35966325Sdes char *p; 36066325Sdes 36163012Sdes if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1) 36263012Sdes return -1; 36337535Sdes /* 36463012Sdes * A valid status line looks like "HTTP/m.n xyz reason" where m 36563012Sdes * and n are the major and minor protocol version numbers and xyz 36663012Sdes * is the reply code. 36766325Sdes * Unfortunately, there are servers out there (NCSA 1.5.1, to name 36866325Sdes * just one) that do not send a version number, so we can't rely 36966325Sdes * on finding one, but if we do, insist on it being 1.0 or 1.1. 37063012Sdes * We don't care about the reason phrase. 37137535Sdes */ 37266325Sdes if (strncmp(reply_buf, "HTTP", 4) != 0) 37363012Sdes return HTTP_PROTOCOL_ERROR; 37466325Sdes p = reply_buf + 4; 37566325Sdes if (*p == '/') { 37666325Sdes if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1')) 37766325Sdes return HTTP_PROTOCOL_ERROR; 37866325Sdes p += 4; 37966325Sdes } 38066325Sdes if (*p != ' ' 38166325Sdes || !isdigit(p[1]) 38266325Sdes || !isdigit(p[2]) 38366325Sdes || !isdigit(p[3])) 38466325Sdes return HTTP_PROTOCOL_ERROR; 38563012Sdes 38666325Sdes return ((p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0')); 38737535Sdes} 38837535Sdes 38937608Sdes/* 39063012Sdes * Check a header; if the type matches the given string, return a 39163012Sdes * pointer to the beginning of the value. 39263012Sdes */ 39375891Sarchiestatic const char * 39475891Sarchie_http_match(const char *str, const char *hdr) 39563012Sdes{ 39663012Sdes while (*str && *hdr && tolower(*str++) == tolower(*hdr++)) 39763012Sdes /* nothing */; 39863012Sdes if (*str || *hdr != ':') 39963012Sdes return NULL; 40063012Sdes while (*hdr && isspace(*++hdr)) 40163012Sdes /* nothing */; 40263012Sdes return hdr; 40363012Sdes} 40463012Sdes 40563012Sdes/* 40663012Sdes * Get the next header and return the appropriate symbolic code. 40763012Sdes */ 40885093Sdesstatic hdr_t 40975891Sarchie_http_next_header(int fd, const char **p) 41063012Sdes{ 41163012Sdes int i; 41263012Sdes 41363012Sdes if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1) 41463012Sdes return hdr_syserror; 41563012Sdes while (reply_length && isspace(reply_buf[reply_length-1])) 41663012Sdes reply_length--; 41763012Sdes reply_buf[reply_length] = 0; 41863012Sdes if (reply_length == 0) 41963012Sdes return hdr_end; 42063012Sdes /* 42163012Sdes * We could check for malformed headers but we don't really care. 42263012Sdes * A valid header starts with a token immediately followed by a 42363012Sdes * colon; a token is any sequence of non-control, non-whitespace 42463012Sdes * characters except "()<>@,;:\\\"{}". 42563012Sdes */ 42663012Sdes for (i = 0; hdr_names[i].num != hdr_unknown; i++) 42763012Sdes if ((*p = _http_match(hdr_names[i].name, reply_buf)) != NULL) 42863012Sdes return hdr_names[i].num; 42963012Sdes return hdr_unknown; 43063012Sdes} 43163012Sdes 43263012Sdes/* 43363012Sdes * Parse a last-modified header 43463012Sdes */ 43563716Sdesstatic int 43675891Sarchie_http_parse_mtime(const char *p, time_t *mtime) 43763012Sdes{ 43863716Sdes char locale[64], *r; 43963012Sdes struct tm tm; 44063012Sdes 44163012Sdes strncpy(locale, setlocale(LC_TIME, NULL), sizeof locale); 44263012Sdes setlocale(LC_TIME, "C"); 44363716Sdes r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm); 44463012Sdes /* XXX should add support for date-2 and date-3 */ 44563012Sdes setlocale(LC_TIME, locale); 44663716Sdes if (r == NULL) 44763716Sdes return -1; 44863012Sdes DEBUG(fprintf(stderr, "last modified: [\033[1m%04d-%02d-%02d " 44963012Sdes "%02d:%02d:%02d\033[m]\n", 45063012Sdes tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 45163012Sdes tm.tm_hour, tm.tm_min, tm.tm_sec)); 45263716Sdes *mtime = timegm(&tm); 45363716Sdes return 0; 45463012Sdes} 45563012Sdes 45663012Sdes/* 45763012Sdes * Parse a content-length header 45863012Sdes */ 45963716Sdesstatic int 46075891Sarchie_http_parse_length(const char *p, off_t *length) 46163012Sdes{ 46264129Sdes off_t len; 46363012Sdes 46463012Sdes for (len = 0; *p && isdigit(*p); ++p) 46563012Sdes len = len * 10 + (*p - '0'); 46685093Sdes if (*p) 46785093Sdes return -1; 46885093Sdes DEBUG(fprintf(stderr, "content length: [\033[1m%lld\033[m]\n", 46985093Sdes (long long)len)); 47063716Sdes *length = len; 47163716Sdes return 0; 47263012Sdes} 47363012Sdes 47463012Sdes/* 47563012Sdes * Parse a content-range header 47663012Sdes */ 47763716Sdesstatic int 47875891Sarchie_http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size) 47963012Sdes{ 48085093Sdes off_t first, last, len; 48163716Sdes 48263012Sdes if (strncasecmp(p, "bytes ", 6) != 0) 48363012Sdes return -1; 48463716Sdes for (first = 0, p += 6; *p && isdigit(*p); ++p) 48563716Sdes first = first * 10 + *p - '0'; 48663012Sdes if (*p != '-') 48763012Sdes return -1; 48863716Sdes for (last = 0, ++p; *p && isdigit(*p); ++p) 48963716Sdes last = last * 10 + *p - '0'; 49063716Sdes if (first > last || *p != '/') 49163716Sdes return -1; 49263716Sdes for (len = 0, ++p; *p && isdigit(*p); ++p) 49363716Sdes len = len * 10 + *p - '0'; 49485093Sdes if (*p || len < last - first + 1) 49563716Sdes return -1; 49685093Sdes DEBUG(fprintf(stderr, "content range: [\033[1m%lld-%lld/%lld\033[m]\n", 49785093Sdes (long long)first, (long long)last, (long long)len)); 49863716Sdes *offset = first; 49963716Sdes *length = last - first + 1; 50063716Sdes *size = len; 50163716Sdes return 0; 50263012Sdes} 50363012Sdes 50463012Sdes 50563012Sdes/***************************************************************************** 50663012Sdes * Helper functions for authorization 50763012Sdes */ 50863012Sdes 50963012Sdes/* 51037608Sdes * Base64 encoding 51137608Sdes */ 51262965Sdesstatic char * 51362965Sdes_http_base64(char *src) 51437608Sdes{ 51537608Sdes static const char base64[] = 51637608Sdes "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 51737608Sdes "abcdefghijklmnopqrstuvwxyz" 51837608Sdes "0123456789+/"; 51962965Sdes char *str, *dst; 52062965Sdes size_t l; 52162965Sdes int t, r; 52262965Sdes 52362965Sdes l = strlen(src); 52462965Sdes if ((str = malloc(((l + 2) / 3) * 4)) == NULL) 52562965Sdes return NULL; 52662965Sdes dst = str; 52762965Sdes r = 0; 52837608Sdes 52937608Sdes while (l >= 3) { 53037608Sdes t = (src[0] << 16) | (src[1] << 8) | src[2]; 53137608Sdes dst[0] = base64[(t >> 18) & 0x3f]; 53237608Sdes dst[1] = base64[(t >> 12) & 0x3f]; 53337608Sdes dst[2] = base64[(t >> 6) & 0x3f]; 53437608Sdes dst[3] = base64[(t >> 0) & 0x3f]; 53537608Sdes src += 3; l -= 3; 53637608Sdes dst += 4; r += 4; 53737608Sdes } 53837608Sdes 53937608Sdes switch (l) { 54037608Sdes case 2: 54137608Sdes t = (src[0] << 16) | (src[1] << 8); 54237608Sdes dst[0] = base64[(t >> 18) & 0x3f]; 54337608Sdes dst[1] = base64[(t >> 12) & 0x3f]; 54437608Sdes dst[2] = base64[(t >> 6) & 0x3f]; 54537608Sdes dst[3] = '='; 54637608Sdes dst += 4; 54737608Sdes r += 4; 54837608Sdes break; 54937608Sdes case 1: 55037608Sdes t = src[0] << 16; 55137608Sdes dst[0] = base64[(t >> 18) & 0x3f]; 55237608Sdes dst[1] = base64[(t >> 12) & 0x3f]; 55337608Sdes dst[2] = dst[3] = '='; 55437608Sdes dst += 4; 55537608Sdes r += 4; 55637608Sdes break; 55737608Sdes case 0: 55837608Sdes break; 55937608Sdes } 56037608Sdes 56137608Sdes *dst = 0; 56262965Sdes return str; 56337608Sdes} 56437608Sdes 56537608Sdes/* 56637608Sdes * Encode username and password 56737608Sdes */ 56862965Sdesstatic int 56975891Sarchie_http_basic_auth(int fd, const char *hdr, const char *usr, const char *pwd) 57037608Sdes{ 57162965Sdes char *upw, *auth; 57262965Sdes int r; 57337608Sdes 57477238Sdes DEBUG(fprintf(stderr, "usr: [\033[1m%s\033[m]\n", usr)); 57577238Sdes DEBUG(fprintf(stderr, "pwd: [\033[1m%s\033[m]\n", pwd)); 57662965Sdes if (asprintf(&upw, "%s:%s", usr, pwd) == -1) 57762965Sdes return -1; 57862965Sdes auth = _http_base64(upw); 57962965Sdes free(upw); 58062965Sdes if (auth == NULL) 58162965Sdes return -1; 58263012Sdes r = _http_cmd(fd, "%s: Basic %s", hdr, auth); 58362965Sdes free(auth); 58462965Sdes return r; 58562965Sdes} 58662965Sdes 58762965Sdes/* 58862965Sdes * Send an authorization header 58962965Sdes */ 59062965Sdesstatic int 59175891Sarchie_http_authorize(int fd, const char *hdr, const char *p) 59262965Sdes{ 59362965Sdes /* basic authorization */ 59462965Sdes if (strncasecmp(p, "basic:", 6) == 0) { 59562965Sdes char *user, *pwd, *str; 59662965Sdes int r; 59762965Sdes 59862965Sdes /* skip realm */ 59962965Sdes for (p += 6; *p && *p != ':'; ++p) 60062965Sdes /* nothing */ ; 60162965Sdes if (!*p || strchr(++p, ':') == NULL) 60262965Sdes return -1; 60362965Sdes if ((str = strdup(p)) == NULL) 60462965Sdes return -1; /* XXX */ 60562965Sdes user = str; 60662965Sdes pwd = strchr(str, ':'); 60762965Sdes *pwd++ = '\0'; 60863012Sdes r = _http_basic_auth(fd, hdr, user, pwd); 60962965Sdes free(str); 61062965Sdes return r; 61162811Sdes } 61262965Sdes return -1; 61337608Sdes} 61437608Sdes 61563012Sdes 61663012Sdes/***************************************************************************** 61763012Sdes * Helper functions for connecting to a server or proxy 61863012Sdes */ 61963012Sdes 62037608Sdes/* 62163012Sdes * Connect to the correct HTTP server or proxy. 62263012Sdes */ 62363012Sdesstatic int 62475891Sarchie_http_connect(struct url *URL, struct url *purl, const char *flags) 62563012Sdes{ 62667043Sdes int verbose; 62763012Sdes int af, fd; 62863012Sdes 62963012Sdes#ifdef INET6 63063012Sdes af = AF_UNSPEC; 63160737Sume#else 63263012Sdes af = AF_INET; 63360737Sume#endif 63467043Sdes 63567892Sdes verbose = CHECK_FLAG('v'); 63667892Sdes if (CHECK_FLAG('4')) 63760737Sume af = AF_INET; 63867043Sdes#ifdef INET6 63967892Sdes else if (CHECK_FLAG('6')) 64060737Sume af = AF_INET6; 64167043Sdes#endif 64267043Sdes 64367043Sdes if (purl) { 64467043Sdes URL = purl; 64567043Sdes } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) { 64667043Sdes /* can't talk http to an ftp server */ 64767043Sdes /* XXX should set an error code */ 64867043Sdes return -1; 64967043Sdes } 65041862Sdes 65167043Sdes if ((fd = _fetch_connect(URL->host, URL->port, af, verbose)) == -1) 65267043Sdes /* _fetch_connect() has already set an error code */ 65367043Sdes return -1; 65467043Sdes return fd; 65567043Sdes} 65667043Sdes 65767043Sdesstatic struct url * 65875891Sarchie_http_get_proxy(void) 65967043Sdes{ 66067043Sdes struct url *purl; 66167043Sdes char *p; 66237535Sdes 66373932Sdes if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 66473932Sdes (purl = fetchParseURL(p))) { 66567043Sdes if (!*purl->scheme) 66667043Sdes strcpy(purl->scheme, SCHEME_HTTP); 66767043Sdes if (!purl->port) 66868551Sdes purl->port = _fetch_default_proxy_port(purl->scheme); 66967043Sdes if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 67067043Sdes return purl; 67167043Sdes fetchFreeURL(purl); 67237535Sdes } 67367043Sdes return NULL; 67460376Sdes} 67560376Sdes 67663012Sdes 67763012Sdes/***************************************************************************** 67863012Sdes * Core 67960954Sdes */ 68060954Sdes 68160954Sdes/* 68263012Sdes * Send a request and process the reply 68360376Sdes */ 68467043SdesFILE * 68575891Sarchie_http_request(struct url *URL, const char *op, struct url_stat *us, 68675891Sarchie struct url *purl, const char *flags) 68760376Sdes{ 68863012Sdes struct url *url, *new; 68967043Sdes int chunked, direct, need_auth, noredirect, verbose; 69063012Sdes int code, fd, i, n; 69164129Sdes off_t offset, clength, length, size; 69263716Sdes time_t mtime; 69375891Sarchie const char *p; 69463012Sdes FILE *f; 69585093Sdes hdr_t h; 69660737Sume char *host; 69760737Sume#ifdef INET6 69860737Sume char hbuf[MAXHOSTNAMELEN + 1]; 69960737Sume#endif 70063012Sdes 70167892Sdes direct = CHECK_FLAG('d'); 70267892Sdes noredirect = CHECK_FLAG('A'); 70367892Sdes verbose = CHECK_FLAG('v'); 70460737Sume 70567043Sdes if (direct && purl) { 70667043Sdes fetchFreeURL(purl); 70767043Sdes purl = NULL; 70867043Sdes } 70967043Sdes 71063716Sdes /* try the provided URL first */ 71163716Sdes url = URL; 71263716Sdes 71363716Sdes /* if the A flag is set, we only get one try */ 71463012Sdes n = noredirect ? 1 : MAX_REDIRECT; 71563716Sdes i = 0; 71663012Sdes 71777238Sdes need_auth = 0; 71863716Sdes do { 71963069Sdes new = NULL; 72063069Sdes chunked = 0; 72163069Sdes offset = 0; 72263716Sdes clength = -1; 72363716Sdes length = -1; 72463716Sdes size = -1; 72563716Sdes mtime = 0; 72677238Sdes 72767043Sdes /* check port */ 72867043Sdes if (!url->port) 72968551Sdes url->port = _fetch_default_port(url->scheme); 73067043Sdes 73187317Sdes /* were we redirected to an FTP URL? */ 73287317Sdes if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) { 73387317Sdes if (strcmp(op, "GET") == 0) 73487317Sdes return _ftp_request(url, "RETR", us, purl, flags); 73587317Sdes else if (strcmp(op, "HEAD") == 0) 73687317Sdes return _ftp_request(url, "STAT", us, purl, flags); 73787317Sdes } 73887317Sdes 73963012Sdes /* connect to server or proxy */ 74067043Sdes if ((fd = _http_connect(url, purl, flags)) == -1) 74163012Sdes goto ouch; 74263012Sdes 74363012Sdes host = url->host; 74460737Sume#ifdef INET6 74563012Sdes if (strchr(url->host, ':')) { 74663012Sdes snprintf(hbuf, sizeof(hbuf), "[%s]", url->host); 74763012Sdes host = hbuf; 74863012Sdes } 74960737Sume#endif 75037535Sdes 75163012Sdes /* send request */ 75263012Sdes if (verbose) 75363012Sdes _fetch_info("requesting %s://%s:%d%s", 75463012Sdes url->scheme, host, url->port, url->doc); 75567043Sdes if (purl) { 75663012Sdes _http_cmd(fd, "%s %s://%s:%d%s HTTP/1.1", 75763012Sdes op, url->scheme, host, url->port, url->doc); 75863012Sdes } else { 75963012Sdes _http_cmd(fd, "%s %s HTTP/1.1", 76063012Sdes op, url->doc); 76163012Sdes } 76237535Sdes 76377238Sdes /* virtual host */ 76477238Sdes if (url->port == _fetch_default_port(url->scheme)) 76577238Sdes _http_cmd(fd, "Host: %s", host); 76677238Sdes else 76777238Sdes _http_cmd(fd, "Host: %s:%d", host, url->port); 76877238Sdes 76963012Sdes /* proxy authorization */ 77067043Sdes if (purl) { 77167043Sdes if (*purl->user || *purl->pwd) 77267043Sdes _http_basic_auth(fd, "Proxy-Authorization", 77367043Sdes purl->user, purl->pwd); 77467043Sdes else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0') 77567043Sdes _http_authorize(fd, "Proxy-Authorization", p); 77667043Sdes } 77763012Sdes 77863012Sdes /* server authorization */ 77977238Sdes if (need_auth || *url->user || *url->pwd) { 78063012Sdes if (*url->user || *url->pwd) 78167043Sdes _http_basic_auth(fd, "Authorization", url->user, url->pwd); 78263716Sdes else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0') 78363012Sdes _http_authorize(fd, "Authorization", p); 78477238Sdes else if (fetchAuthMethod && fetchAuthMethod(url) == 0) { 78577238Sdes _http_basic_auth(fd, "Authorization", url->user, url->pwd); 78677238Sdes } else { 78763012Sdes _http_seterr(HTTP_NEED_AUTH); 78863012Sdes goto ouch; 78963012Sdes } 79063012Sdes } 79160376Sdes 79263012Sdes /* other headers */ 79377261Sdes if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0') 79477261Sdes _http_cmd(fd, "User-Agent: %s", p); 79577261Sdes else 79677261Sdes _http_cmd(fd, "User-Agent: %s " _LIBFETCH_VER, __progname); 79763567Sdes if (url->offset) 79885093Sdes _http_cmd(fd, "Range: bytes=%lld-", (long long)url->offset); 79963012Sdes _http_cmd(fd, "Connection: close"); 80063012Sdes _http_cmd(fd, ""); 80160376Sdes 80263012Sdes /* get reply */ 80363012Sdes switch ((code = _http_get_reply(fd))) { 80463012Sdes case HTTP_OK: 80563012Sdes case HTTP_PARTIAL: 80663012Sdes /* fine */ 80763012Sdes break; 80863012Sdes case HTTP_MOVED_PERM: 80963012Sdes case HTTP_MOVED_TEMP: 81087317Sdes case HTTP_SEE_OTHER: 81163012Sdes /* 81263012Sdes * Not so fine, but we still have to read the headers to 81363012Sdes * get the new location. 81463012Sdes */ 81563012Sdes break; 81663012Sdes case HTTP_NEED_AUTH: 81763012Sdes if (need_auth) { 81863012Sdes /* 81963012Sdes * We already sent out authorization code, so there's 82063012Sdes * nothing more we can do. 82163012Sdes */ 82263012Sdes _http_seterr(code); 82363012Sdes goto ouch; 82463012Sdes } 82563012Sdes /* try again, but send the password this time */ 82663012Sdes if (verbose) 82763012Sdes _fetch_info("server requires authorization"); 82877238Sdes break; 82963012Sdes case HTTP_NEED_PROXY_AUTH: 83063012Sdes /* 83163012Sdes * If we're talking to a proxy, we already sent our proxy 83263012Sdes * authorization code, so there's nothing more we can do. 83363012Sdes */ 83463012Sdes _http_seterr(code); 83563012Sdes goto ouch; 83663012Sdes case HTTP_PROTOCOL_ERROR: 83763012Sdes /* fall through */ 83863012Sdes case -1: 83963012Sdes _fetch_syserr(); 84063012Sdes goto ouch; 84163012Sdes default: 84263012Sdes _http_seterr(code); 84363012Sdes goto ouch; 84463012Sdes } 84563012Sdes 84663012Sdes /* get headers */ 84763012Sdes do { 84863012Sdes switch ((h = _http_next_header(fd, &p))) { 84963012Sdes case hdr_syserror: 85063012Sdes _fetch_syserr(); 85163012Sdes goto ouch; 85263012Sdes case hdr_error: 85363012Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 85463012Sdes goto ouch; 85563012Sdes case hdr_content_length: 85663716Sdes _http_parse_length(p, &clength); 85763012Sdes break; 85863012Sdes case hdr_content_range: 85963716Sdes _http_parse_range(p, &offset, &length, &size); 86063012Sdes break; 86163012Sdes case hdr_last_modified: 86263716Sdes _http_parse_mtime(p, &mtime); 86363012Sdes break; 86463012Sdes case hdr_location: 86563012Sdes if (!HTTP_REDIRECT(code)) 86663012Sdes break; 86763069Sdes if (new) 86863069Sdes free(new); 86963012Sdes if (verbose) 87063012Sdes _fetch_info("%d redirect to %s", code, p); 87163069Sdes if (*p == '/') 87263069Sdes /* absolute path */ 87363069Sdes new = fetchMakeURL(url->scheme, url->host, url->port, p, 87463069Sdes url->user, url->pwd); 87563069Sdes else 87663069Sdes new = fetchParseURL(p); 87763069Sdes if (new == NULL) { 87863069Sdes /* XXX should set an error code */ 87963069Sdes DEBUG(fprintf(stderr, "failed to parse new URL\n")); 88063012Sdes goto ouch; 88163069Sdes } 88263012Sdes if (!*new->user && !*new->pwd) { 88363012Sdes strcpy(new->user, url->user); 88463012Sdes strcpy(new->pwd, url->pwd); 88563012Sdes } 88663012Sdes new->offset = url->offset; 88763012Sdes new->length = url->length; 88863069Sdes break; 88963012Sdes case hdr_transfer_encoding: 89063012Sdes /* XXX weak test*/ 89163012Sdes chunked = (strcasecmp(p, "chunked") == 0); 89263012Sdes break; 89377238Sdes case hdr_www_authenticate: 89477238Sdes if (code != HTTP_NEED_AUTH) 89577238Sdes break; 89677238Sdes /* if we were smarter, we'd check the method and realm */ 89777238Sdes break; 89863012Sdes case hdr_end: 89963012Sdes /* fall through */ 90063012Sdes case hdr_unknown: 90163012Sdes /* ignore */ 90263012Sdes break; 90363012Sdes } 90463012Sdes } while (h > hdr_end); 90560376Sdes 90677238Sdes /* we have a hit */ 90777238Sdes if (code == HTTP_OK || code == HTTP_PARTIAL) 90863012Sdes break; 90963069Sdes 91077238Sdes /* we need to provide authentication */ 91177238Sdes if (code == HTTP_NEED_AUTH) { 91277238Sdes need_auth = 1; 91377238Sdes close(fd); 91477238Sdes fd = -1; 91577238Sdes continue; 91677238Sdes } 91777238Sdes 91877238Sdes /* all other cases: we got a redirect */ 91977238Sdes need_auth = 0; 92063069Sdes close(fd); 92163337Sdes fd = -1; 92277238Sdes if (!new) { 92377238Sdes DEBUG(fprintf(stderr, "redirect with no new location\n")); 92477238Sdes break; 92577238Sdes } 92663069Sdes if (url != URL) 92763069Sdes fetchFreeURL(url); 92863069Sdes url = new; 92963716Sdes } while (++i < n); 93060376Sdes 93177238Sdes /* we failed, or ran out of retries */ 93263012Sdes if (fd == -1) { 93363012Sdes _http_seterr(code); 93463012Sdes goto ouch; 93537571Sdes } 93637535Sdes 93785093Sdes DEBUG(fprintf(stderr, "offset %lld, length %lld," 93885093Sdes " size %lld, clength %lld\n", 93985093Sdes (long long)offset, (long long)length, 94085093Sdes (long long)size, (long long)clength)); 94163716Sdes 94263716Sdes /* check for inconsistencies */ 94363716Sdes if (clength != -1 && length != -1 && clength != length) { 94463716Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 94563716Sdes goto ouch; 94663716Sdes } 94763716Sdes if (clength == -1) 94863716Sdes clength = length; 94963716Sdes if (clength != -1) 95063716Sdes length = offset + clength; 95163716Sdes if (length != -1 && size != -1 && length != size) { 95263716Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 95363716Sdes goto ouch; 95463716Sdes } 95563716Sdes if (size == -1) 95663716Sdes size = length; 95763716Sdes 95863716Sdes /* fill in stats */ 95963716Sdes if (us) { 96063716Sdes us->size = size; 96163716Sdes us->atime = us->mtime = mtime; 96263716Sdes } 96363716Sdes 96463567Sdes /* too far? */ 96563716Sdes if (offset > URL->offset) { 96663567Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 96763567Sdes goto ouch; 96863567Sdes } 96963567Sdes 97063716Sdes /* report back real offset and size */ 97163567Sdes URL->offset = offset; 97263716Sdes URL->length = clength; 97363567Sdes 97463012Sdes /* wrap it up in a FILE */ 97563012Sdes if ((f = chunked ? _http_funopen(fd) : fdopen(fd, "r")) == NULL) { 97663012Sdes _fetch_syserr(); 97763012Sdes goto ouch; 97863012Sdes } 97963012Sdes 98063012Sdes if (url != URL) 98163012Sdes fetchFreeURL(url); 98267043Sdes if (purl) 98367043Sdes fetchFreeURL(purl); 98463012Sdes 98563012Sdes return f; 98637535Sdes 98763012Sdes ouch: 98863012Sdes if (url != URL) 98963012Sdes fetchFreeURL(url); 99067043Sdes if (purl) 99167043Sdes fetchFreeURL(purl); 99263012Sdes if (fd != -1) 99363012Sdes close(fd); 99463012Sdes return NULL; 99563012Sdes} 99660189Sdes 99763012Sdes 99863012Sdes/***************************************************************************** 99963012Sdes * Entry points 100063012Sdes */ 100163012Sdes 100263012Sdes/* 100363340Sdes * Retrieve and stat a file by HTTP 100463340Sdes */ 100563340SdesFILE * 100675891SarchiefetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags) 100763340Sdes{ 100867043Sdes return _http_request(URL, "GET", us, _http_get_proxy(), flags); 100963340Sdes} 101063340Sdes 101163340Sdes/* 101263012Sdes * Retrieve a file by HTTP 101363012Sdes */ 101463012SdesFILE * 101575891SarchiefetchGetHTTP(struct url *URL, const char *flags) 101663012Sdes{ 101763340Sdes return fetchXGetHTTP(URL, NULL, flags); 101837535Sdes} 101937535Sdes 102063340Sdes/* 102163340Sdes * Store a file by HTTP 102263340Sdes */ 102337535SdesFILE * 102485093SdesfetchPutHTTP(struct url *URL __unused, const char *flags __unused) 102537535Sdes{ 102637535Sdes warnx("fetchPutHTTP(): not implemented"); 102737535Sdes return NULL; 102837535Sdes} 102940975Sdes 103040975Sdes/* 103140975Sdes * Get an HTTP document's metadata 103240975Sdes */ 103340975Sdesint 103475891SarchiefetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags) 103540975Sdes{ 103660376Sdes FILE *f; 103760376Sdes 103867043Sdes if ((f = _http_request(URL, "HEAD", us, _http_get_proxy(), flags)) == NULL) 103960376Sdes return -1; 104060581Sdes fclose(f); 104160376Sdes return 0; 104240975Sdes} 104341989Sdes 104441989Sdes/* 104541989Sdes * List a directory 104641989Sdes */ 104741989Sdesstruct url_ent * 104885093SdesfetchListHTTP(struct url *url __unused, const char *flags __unused) 104941989Sdes{ 105041989Sdes warnx("fetchListHTTP(): not implemented"); 105141989Sdes return NULL; 105241989Sdes} 1053