http.c revision 88769
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 88769 2002-01-01 14:48:09Z 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 14687561Sdes if (fetchDebug) { 14787561Sdes c->total += c->chunksize; 14887561Sdes if (c->chunksize == 0) 14988769Sdes fprintf(stderr, "_http_fillbuf(): " 15088769Sdes "end of last chunk\n"); 15187561Sdes else 15288769Sdes fprintf(stderr, "_http_fillbuf(): " 15388769Sdes "new chunk: %lu (%lu)\n", 15487561Sdes (unsigned long)c->chunksize, (unsigned long)c->total); 15587561Sdes } 15663012Sdes#endif 15763012Sdes 15863012Sdes return c->chunksize; 15937608Sdes} 16037608Sdes 16137608Sdes/* 16237608Sdes * Fill the input buffer, do chunk decoding on the fly 16337608Sdes */ 16463012Sdesstatic int 16537535Sdes_http_fillbuf(struct cookie *c) 16637535Sdes{ 16763012Sdes if (c->error) 16863012Sdes return -1; 16937535Sdes if (c->eof) 17063012Sdes return 0; 17163012Sdes 17263012Sdes if (c->chunksize == 0) { 17363012Sdes switch (_http_new_chunk(c)) { 17463012Sdes case -1: 17563012Sdes c->error = 1; 17663012Sdes return -1; 17763012Sdes case 0: 17863012Sdes c->eof = 1; 17963012Sdes return 0; 18037535Sdes } 18137535Sdes } 18263012Sdes 18363012Sdes if (c->b_size < c->chunksize) { 18463012Sdes char *tmp; 18563012Sdes 18663012Sdes if ((tmp = realloc(c->buf, c->chunksize)) == NULL) 18763012Sdes return -1; 18863012Sdes c->buf = tmp; 18963012Sdes c->b_size = c->chunksize; 19063012Sdes } 19163012Sdes 19263012Sdes if ((c->b_len = read(c->fd, c->buf, c->chunksize)) == -1) 19363012Sdes return -1; 19463012Sdes c->chunksize -= c->b_len; 19563012Sdes 19663012Sdes if (c->chunksize == 0) { 19763012Sdes char endl[2]; 19863012Sdes read(c->fd, endl, 2); 19963012Sdes } 20063012Sdes 20163012Sdes c->b_pos = 0; 20263012Sdes 20363012Sdes return c->b_len; 20437535Sdes} 20537535Sdes 20637608Sdes/* 20737608Sdes * Read function 20837608Sdes */ 20937535Sdesstatic int 21063012Sdes_http_readfn(void *v, char *buf, int len) 21137535Sdes{ 21263012Sdes struct cookie *c = (struct cookie *)v; 21363012Sdes int l, pos; 21463012Sdes 21563012Sdes if (c->error) 21663012Sdes return -1; 21763012Sdes if (c->eof) 21863012Sdes return 0; 21963012Sdes 22063012Sdes for (pos = 0; len > 0; pos += l, len -= l) { 22137535Sdes /* empty buffer */ 22263012Sdes if (!c->buf || c->b_pos == c->b_len) 22363012Sdes if (_http_fillbuf(c) < 1) 22437535Sdes break; 22563012Sdes l = c->b_len - c->b_pos; 22663012Sdes if (len < l) 22763012Sdes l = len; 22863012Sdes bcopy(c->buf + c->b_pos, buf + pos, l); 22963012Sdes c->b_pos += l; 23063012Sdes } 23137535Sdes 23263012Sdes if (!pos && c->error) 23337535Sdes return -1; 23463012Sdes return pos; 23537535Sdes} 23637535Sdes 23737608Sdes/* 23837608Sdes * Write function 23937608Sdes */ 24037535Sdesstatic int 24163012Sdes_http_writefn(void *v, const char *buf, int len) 24237535Sdes{ 24363012Sdes struct cookie *c = (struct cookie *)v; 24463012Sdes 24563012Sdes return write(c->fd, buf, len); 24637535Sdes} 24737535Sdes 24837608Sdes/* 24937608Sdes * Close function 25037608Sdes */ 25137535Sdesstatic int 25263012Sdes_http_closefn(void *v) 25337535Sdes{ 25463012Sdes struct cookie *c = (struct cookie *)v; 25563012Sdes int r; 25663012Sdes 25763012Sdes r = close(c->fd); 25863012Sdes if (c->buf) 25963012Sdes free(c->buf); 26037535Sdes free(c); 26163012Sdes return r; 26237535Sdes} 26337535Sdes 26437608Sdes/* 26563012Sdes * Wrap a file descriptor up 26637608Sdes */ 26763012Sdesstatic FILE * 26863012Sdes_http_funopen(int fd) 26937535Sdes{ 27063012Sdes struct cookie *c; 27163012Sdes FILE *f; 27263012Sdes 27363012Sdes if ((c = calloc(1, sizeof *c)) == NULL) { 27463012Sdes _fetch_syserr(); 27563012Sdes return NULL; 27663012Sdes } 27763012Sdes c->fd = fd; 27863012Sdes if (!(f = funopen(c, _http_readfn, _http_writefn, NULL, _http_closefn))) { 27963012Sdes _fetch_syserr(); 28063012Sdes free(c); 28163012Sdes return NULL; 28263012Sdes } 28363012Sdes return f; 28463012Sdes} 28563012Sdes 28663012Sdes 28763012Sdes/***************************************************************************** 28863012Sdes * Helper functions for talking to the server and parsing its replies 28963012Sdes */ 29063012Sdes 29163012Sdes/* Header types */ 29263012Sdestypedef enum { 29363012Sdes hdr_syserror = -2, 29463012Sdes hdr_error = -1, 29563012Sdes hdr_end = 0, 29663012Sdes hdr_unknown = 1, 29763012Sdes hdr_content_length, 29863012Sdes hdr_content_range, 29963012Sdes hdr_last_modified, 30063012Sdes hdr_location, 30177238Sdes hdr_transfer_encoding, 30277238Sdes hdr_www_authenticate 30385093Sdes} hdr_t; 30463012Sdes 30563012Sdes/* Names of interesting headers */ 30663012Sdesstatic struct { 30785093Sdes hdr_t num; 30875891Sarchie const char *name; 30963012Sdes} hdr_names[] = { 31063012Sdes { hdr_content_length, "Content-Length" }, 31163012Sdes { hdr_content_range, "Content-Range" }, 31263012Sdes { hdr_last_modified, "Last-Modified" }, 31363012Sdes { hdr_location, "Location" }, 31463012Sdes { hdr_transfer_encoding, "Transfer-Encoding" }, 31577238Sdes { hdr_www_authenticate, "WWW-Authenticate" }, 31663012Sdes { hdr_unknown, NULL }, 31763012Sdes}; 31863012Sdes 31963012Sdesstatic char *reply_buf; 32063012Sdesstatic size_t reply_size; 32163012Sdesstatic size_t reply_length; 32263012Sdes 32363012Sdes/* 32463012Sdes * Send a formatted line; optionally echo to terminal 32563012Sdes */ 32663012Sdesstatic int 32775891Sarchie_http_cmd(int fd, const char *fmt, ...) 32863012Sdes{ 32963012Sdes va_list ap; 33063012Sdes size_t len; 33163012Sdes char *msg; 33263012Sdes int r; 33363012Sdes 33463012Sdes va_start(ap, fmt); 33563012Sdes len = vasprintf(&msg, fmt, ap); 33663012Sdes va_end(ap); 33763012Sdes 33863012Sdes if (msg == NULL) { 33963012Sdes errno = ENOMEM; 34063012Sdes _fetch_syserr(); 34163012Sdes return -1; 34263012Sdes } 34363012Sdes 34463012Sdes r = _fetch_putln(fd, msg, len); 34563012Sdes free(msg); 34663012Sdes 34763012Sdes if (r == -1) { 34863012Sdes _fetch_syserr(); 34963012Sdes return -1; 35063012Sdes } 35163012Sdes 35263012Sdes return 0; 35363012Sdes} 35463012Sdes 35563012Sdes/* 35663012Sdes * Get and parse status line 35763012Sdes */ 35863012Sdesstatic int 35963012Sdes_http_get_reply(int fd) 36063012Sdes{ 36166325Sdes char *p; 36266325Sdes 36363012Sdes if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1) 36463012Sdes return -1; 36537535Sdes /* 36663012Sdes * A valid status line looks like "HTTP/m.n xyz reason" where m 36763012Sdes * and n are the major and minor protocol version numbers and xyz 36863012Sdes * is the reply code. 36966325Sdes * Unfortunately, there are servers out there (NCSA 1.5.1, to name 37066325Sdes * just one) that do not send a version number, so we can't rely 37166325Sdes * on finding one, but if we do, insist on it being 1.0 or 1.1. 37263012Sdes * We don't care about the reason phrase. 37337535Sdes */ 37466325Sdes if (strncmp(reply_buf, "HTTP", 4) != 0) 37563012Sdes return HTTP_PROTOCOL_ERROR; 37666325Sdes p = reply_buf + 4; 37766325Sdes if (*p == '/') { 37866325Sdes if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1')) 37966325Sdes return HTTP_PROTOCOL_ERROR; 38066325Sdes p += 4; 38166325Sdes } 38266325Sdes if (*p != ' ' 38366325Sdes || !isdigit(p[1]) 38466325Sdes || !isdigit(p[2]) 38566325Sdes || !isdigit(p[3])) 38666325Sdes return HTTP_PROTOCOL_ERROR; 38763012Sdes 38866325Sdes return ((p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0')); 38937535Sdes} 39037535Sdes 39137608Sdes/* 39263012Sdes * Check a header; if the type matches the given string, return a 39363012Sdes * pointer to the beginning of the value. 39463012Sdes */ 39575891Sarchiestatic const char * 39675891Sarchie_http_match(const char *str, const char *hdr) 39763012Sdes{ 39863012Sdes while (*str && *hdr && tolower(*str++) == tolower(*hdr++)) 39963012Sdes /* nothing */; 40063012Sdes if (*str || *hdr != ':') 40163012Sdes return NULL; 40263012Sdes while (*hdr && isspace(*++hdr)) 40363012Sdes /* nothing */; 40463012Sdes return hdr; 40563012Sdes} 40663012Sdes 40763012Sdes/* 40863012Sdes * Get the next header and return the appropriate symbolic code. 40963012Sdes */ 41085093Sdesstatic hdr_t 41175891Sarchie_http_next_header(int fd, const char **p) 41263012Sdes{ 41363012Sdes int i; 41463012Sdes 41563012Sdes if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1) 41663012Sdes return hdr_syserror; 41763012Sdes while (reply_length && isspace(reply_buf[reply_length-1])) 41863012Sdes reply_length--; 41963012Sdes reply_buf[reply_length] = 0; 42063012Sdes if (reply_length == 0) 42163012Sdes return hdr_end; 42263012Sdes /* 42363012Sdes * We could check for malformed headers but we don't really care. 42463012Sdes * A valid header starts with a token immediately followed by a 42563012Sdes * colon; a token is any sequence of non-control, non-whitespace 42663012Sdes * characters except "()<>@,;:\\\"{}". 42763012Sdes */ 42863012Sdes for (i = 0; hdr_names[i].num != hdr_unknown; i++) 42963012Sdes if ((*p = _http_match(hdr_names[i].name, reply_buf)) != NULL) 43063012Sdes return hdr_names[i].num; 43163012Sdes return hdr_unknown; 43263012Sdes} 43363012Sdes 43463012Sdes/* 43563012Sdes * Parse a last-modified header 43663012Sdes */ 43763716Sdesstatic int 43875891Sarchie_http_parse_mtime(const char *p, time_t *mtime) 43963012Sdes{ 44063716Sdes char locale[64], *r; 44163012Sdes struct tm tm; 44263012Sdes 44363012Sdes strncpy(locale, setlocale(LC_TIME, NULL), sizeof locale); 44463012Sdes setlocale(LC_TIME, "C"); 44563716Sdes r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm); 44663012Sdes /* XXX should add support for date-2 and date-3 */ 44763012Sdes setlocale(LC_TIME, locale); 44863716Sdes if (r == NULL) 44963716Sdes return -1; 45088769Sdes DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d " 45188769Sdes "%02d:%02d:%02d]\n", 45263012Sdes tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 45363012Sdes tm.tm_hour, tm.tm_min, tm.tm_sec)); 45463716Sdes *mtime = timegm(&tm); 45563716Sdes return 0; 45663012Sdes} 45763012Sdes 45863012Sdes/* 45963012Sdes * Parse a content-length header 46063012Sdes */ 46163716Sdesstatic int 46275891Sarchie_http_parse_length(const char *p, off_t *length) 46363012Sdes{ 46464129Sdes off_t len; 46563012Sdes 46663012Sdes for (len = 0; *p && isdigit(*p); ++p) 46763012Sdes len = len * 10 + (*p - '0'); 46885093Sdes if (*p) 46985093Sdes return -1; 47088769Sdes DEBUG(fprintf(stderr, "content length: [%lld]\n", 47185093Sdes (long long)len)); 47263716Sdes *length = len; 47363716Sdes return 0; 47463012Sdes} 47563012Sdes 47663012Sdes/* 47763012Sdes * Parse a content-range header 47863012Sdes */ 47963716Sdesstatic int 48075891Sarchie_http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size) 48163012Sdes{ 48285093Sdes off_t first, last, len; 48363716Sdes 48463012Sdes if (strncasecmp(p, "bytes ", 6) != 0) 48563012Sdes return -1; 48663716Sdes for (first = 0, p += 6; *p && isdigit(*p); ++p) 48763716Sdes first = first * 10 + *p - '0'; 48863012Sdes if (*p != '-') 48963012Sdes return -1; 49063716Sdes for (last = 0, ++p; *p && isdigit(*p); ++p) 49163716Sdes last = last * 10 + *p - '0'; 49263716Sdes if (first > last || *p != '/') 49363716Sdes return -1; 49463716Sdes for (len = 0, ++p; *p && isdigit(*p); ++p) 49563716Sdes len = len * 10 + *p - '0'; 49685093Sdes if (*p || len < last - first + 1) 49763716Sdes return -1; 49888769Sdes DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n", 49985093Sdes (long long)first, (long long)last, (long long)len)); 50063716Sdes *offset = first; 50163716Sdes *length = last - first + 1; 50263716Sdes *size = len; 50363716Sdes return 0; 50463012Sdes} 50563012Sdes 50663012Sdes 50763012Sdes/***************************************************************************** 50863012Sdes * Helper functions for authorization 50963012Sdes */ 51063012Sdes 51163012Sdes/* 51237608Sdes * Base64 encoding 51337608Sdes */ 51462965Sdesstatic char * 51562965Sdes_http_base64(char *src) 51637608Sdes{ 51737608Sdes static const char base64[] = 51837608Sdes "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 51937608Sdes "abcdefghijklmnopqrstuvwxyz" 52037608Sdes "0123456789+/"; 52162965Sdes char *str, *dst; 52262965Sdes size_t l; 52362965Sdes int t, r; 52462965Sdes 52562965Sdes l = strlen(src); 52662965Sdes if ((str = malloc(((l + 2) / 3) * 4)) == NULL) 52762965Sdes return NULL; 52862965Sdes dst = str; 52962965Sdes r = 0; 53037608Sdes 53137608Sdes while (l >= 3) { 53237608Sdes t = (src[0] << 16) | (src[1] << 8) | src[2]; 53337608Sdes dst[0] = base64[(t >> 18) & 0x3f]; 53437608Sdes dst[1] = base64[(t >> 12) & 0x3f]; 53537608Sdes dst[2] = base64[(t >> 6) & 0x3f]; 53637608Sdes dst[3] = base64[(t >> 0) & 0x3f]; 53737608Sdes src += 3; l -= 3; 53837608Sdes dst += 4; r += 4; 53937608Sdes } 54037608Sdes 54137608Sdes switch (l) { 54237608Sdes case 2: 54337608Sdes t = (src[0] << 16) | (src[1] << 8); 54437608Sdes dst[0] = base64[(t >> 18) & 0x3f]; 54537608Sdes dst[1] = base64[(t >> 12) & 0x3f]; 54637608Sdes dst[2] = base64[(t >> 6) & 0x3f]; 54737608Sdes dst[3] = '='; 54837608Sdes dst += 4; 54937608Sdes r += 4; 55037608Sdes break; 55137608Sdes case 1: 55237608Sdes t = src[0] << 16; 55337608Sdes dst[0] = base64[(t >> 18) & 0x3f]; 55437608Sdes dst[1] = base64[(t >> 12) & 0x3f]; 55537608Sdes dst[2] = dst[3] = '='; 55637608Sdes dst += 4; 55737608Sdes r += 4; 55837608Sdes break; 55937608Sdes case 0: 56037608Sdes break; 56137608Sdes } 56237608Sdes 56337608Sdes *dst = 0; 56462965Sdes return str; 56537608Sdes} 56637608Sdes 56737608Sdes/* 56837608Sdes * Encode username and password 56937608Sdes */ 57062965Sdesstatic int 57175891Sarchie_http_basic_auth(int fd, const char *hdr, const char *usr, const char *pwd) 57237608Sdes{ 57362965Sdes char *upw, *auth; 57462965Sdes int r; 57537608Sdes 57688769Sdes DEBUG(fprintf(stderr, "usr: [%s]\n", usr)); 57788769Sdes DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd)); 57862965Sdes if (asprintf(&upw, "%s:%s", usr, pwd) == -1) 57962965Sdes return -1; 58062965Sdes auth = _http_base64(upw); 58162965Sdes free(upw); 58262965Sdes if (auth == NULL) 58362965Sdes return -1; 58463012Sdes r = _http_cmd(fd, "%s: Basic %s", hdr, auth); 58562965Sdes free(auth); 58662965Sdes return r; 58762965Sdes} 58862965Sdes 58962965Sdes/* 59062965Sdes * Send an authorization header 59162965Sdes */ 59262965Sdesstatic int 59375891Sarchie_http_authorize(int fd, const char *hdr, const char *p) 59462965Sdes{ 59562965Sdes /* basic authorization */ 59662965Sdes if (strncasecmp(p, "basic:", 6) == 0) { 59762965Sdes char *user, *pwd, *str; 59862965Sdes int r; 59962965Sdes 60062965Sdes /* skip realm */ 60162965Sdes for (p += 6; *p && *p != ':'; ++p) 60262965Sdes /* nothing */ ; 60362965Sdes if (!*p || strchr(++p, ':') == NULL) 60462965Sdes return -1; 60562965Sdes if ((str = strdup(p)) == NULL) 60662965Sdes return -1; /* XXX */ 60762965Sdes user = str; 60862965Sdes pwd = strchr(str, ':'); 60962965Sdes *pwd++ = '\0'; 61063012Sdes r = _http_basic_auth(fd, hdr, user, pwd); 61162965Sdes free(str); 61262965Sdes return r; 61362811Sdes } 61462965Sdes return -1; 61537608Sdes} 61637608Sdes 61763012Sdes 61863012Sdes/***************************************************************************** 61963012Sdes * Helper functions for connecting to a server or proxy 62063012Sdes */ 62163012Sdes 62237608Sdes/* 62363012Sdes * Connect to the correct HTTP server or proxy. 62463012Sdes */ 62563012Sdesstatic int 62675891Sarchie_http_connect(struct url *URL, struct url *purl, const char *flags) 62763012Sdes{ 62867043Sdes int verbose; 62963012Sdes int af, fd; 63063012Sdes 63163012Sdes#ifdef INET6 63263012Sdes af = AF_UNSPEC; 63360737Sume#else 63463012Sdes af = AF_INET; 63560737Sume#endif 63667043Sdes 63767892Sdes verbose = CHECK_FLAG('v'); 63867892Sdes if (CHECK_FLAG('4')) 63960737Sume af = AF_INET; 64067043Sdes#ifdef INET6 64167892Sdes else if (CHECK_FLAG('6')) 64260737Sume af = AF_INET6; 64367043Sdes#endif 64467043Sdes 64567043Sdes if (purl) { 64667043Sdes URL = purl; 64767043Sdes } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) { 64867043Sdes /* can't talk http to an ftp server */ 64967043Sdes /* XXX should set an error code */ 65067043Sdes return -1; 65167043Sdes } 65241862Sdes 65367043Sdes if ((fd = _fetch_connect(URL->host, URL->port, af, verbose)) == -1) 65467043Sdes /* _fetch_connect() has already set an error code */ 65567043Sdes return -1; 65667043Sdes return fd; 65767043Sdes} 65867043Sdes 65967043Sdesstatic struct url * 66075891Sarchie_http_get_proxy(void) 66167043Sdes{ 66267043Sdes struct url *purl; 66367043Sdes char *p; 66437535Sdes 66573932Sdes if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 66673932Sdes (purl = fetchParseURL(p))) { 66767043Sdes if (!*purl->scheme) 66867043Sdes strcpy(purl->scheme, SCHEME_HTTP); 66967043Sdes if (!purl->port) 67068551Sdes purl->port = _fetch_default_proxy_port(purl->scheme); 67167043Sdes if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 67267043Sdes return purl; 67367043Sdes fetchFreeURL(purl); 67437535Sdes } 67567043Sdes return NULL; 67660376Sdes} 67760376Sdes 67863012Sdes 67963012Sdes/***************************************************************************** 68063012Sdes * Core 68160954Sdes */ 68260954Sdes 68360954Sdes/* 68463012Sdes * Send a request and process the reply 68560376Sdes */ 68667043SdesFILE * 68775891Sarchie_http_request(struct url *URL, const char *op, struct url_stat *us, 68875891Sarchie struct url *purl, const char *flags) 68960376Sdes{ 69063012Sdes struct url *url, *new; 69167043Sdes int chunked, direct, need_auth, noredirect, verbose; 69263012Sdes int code, fd, i, n; 69364129Sdes off_t offset, clength, length, size; 69463716Sdes time_t mtime; 69575891Sarchie const char *p; 69663012Sdes FILE *f; 69785093Sdes hdr_t h; 69860737Sume char *host; 69960737Sume#ifdef INET6 70060737Sume char hbuf[MAXHOSTNAMELEN + 1]; 70160737Sume#endif 70263012Sdes 70367892Sdes direct = CHECK_FLAG('d'); 70467892Sdes noredirect = CHECK_FLAG('A'); 70567892Sdes verbose = CHECK_FLAG('v'); 70660737Sume 70767043Sdes if (direct && purl) { 70867043Sdes fetchFreeURL(purl); 70967043Sdes purl = NULL; 71067043Sdes } 71167043Sdes 71263716Sdes /* try the provided URL first */ 71363716Sdes url = URL; 71463716Sdes 71563716Sdes /* if the A flag is set, we only get one try */ 71663012Sdes n = noredirect ? 1 : MAX_REDIRECT; 71763716Sdes i = 0; 71863012Sdes 71977238Sdes need_auth = 0; 72063716Sdes do { 72163069Sdes new = NULL; 72263069Sdes chunked = 0; 72363069Sdes offset = 0; 72463716Sdes clength = -1; 72563716Sdes length = -1; 72663716Sdes size = -1; 72763716Sdes mtime = 0; 72877238Sdes 72967043Sdes /* check port */ 73067043Sdes if (!url->port) 73168551Sdes url->port = _fetch_default_port(url->scheme); 73267043Sdes 73387317Sdes /* were we redirected to an FTP URL? */ 73487317Sdes if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) { 73587317Sdes if (strcmp(op, "GET") == 0) 73687317Sdes return _ftp_request(url, "RETR", us, purl, flags); 73787317Sdes else if (strcmp(op, "HEAD") == 0) 73887317Sdes return _ftp_request(url, "STAT", us, purl, flags); 73987317Sdes } 74087317Sdes 74163012Sdes /* connect to server or proxy */ 74267043Sdes if ((fd = _http_connect(url, purl, flags)) == -1) 74363012Sdes goto ouch; 74463012Sdes 74563012Sdes host = url->host; 74660737Sume#ifdef INET6 74763012Sdes if (strchr(url->host, ':')) { 74863012Sdes snprintf(hbuf, sizeof(hbuf), "[%s]", url->host); 74963012Sdes host = hbuf; 75063012Sdes } 75160737Sume#endif 75237535Sdes 75363012Sdes /* send request */ 75463012Sdes if (verbose) 75563012Sdes _fetch_info("requesting %s://%s:%d%s", 75663012Sdes url->scheme, host, url->port, url->doc); 75767043Sdes if (purl) { 75863012Sdes _http_cmd(fd, "%s %s://%s:%d%s HTTP/1.1", 75963012Sdes op, url->scheme, host, url->port, url->doc); 76063012Sdes } else { 76163012Sdes _http_cmd(fd, "%s %s HTTP/1.1", 76263012Sdes op, url->doc); 76363012Sdes } 76437535Sdes 76577238Sdes /* virtual host */ 76677238Sdes if (url->port == _fetch_default_port(url->scheme)) 76777238Sdes _http_cmd(fd, "Host: %s", host); 76877238Sdes else 76977238Sdes _http_cmd(fd, "Host: %s:%d", host, url->port); 77077238Sdes 77163012Sdes /* proxy authorization */ 77267043Sdes if (purl) { 77367043Sdes if (*purl->user || *purl->pwd) 77467043Sdes _http_basic_auth(fd, "Proxy-Authorization", 77567043Sdes purl->user, purl->pwd); 77667043Sdes else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0') 77767043Sdes _http_authorize(fd, "Proxy-Authorization", p); 77867043Sdes } 77963012Sdes 78063012Sdes /* server authorization */ 78177238Sdes if (need_auth || *url->user || *url->pwd) { 78263012Sdes if (*url->user || *url->pwd) 78367043Sdes _http_basic_auth(fd, "Authorization", url->user, url->pwd); 78463716Sdes else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0') 78563012Sdes _http_authorize(fd, "Authorization", p); 78677238Sdes else if (fetchAuthMethod && fetchAuthMethod(url) == 0) { 78777238Sdes _http_basic_auth(fd, "Authorization", url->user, url->pwd); 78877238Sdes } else { 78963012Sdes _http_seterr(HTTP_NEED_AUTH); 79063012Sdes goto ouch; 79163012Sdes } 79263012Sdes } 79360376Sdes 79463012Sdes /* other headers */ 79577261Sdes if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0') 79677261Sdes _http_cmd(fd, "User-Agent: %s", p); 79777261Sdes else 79877261Sdes _http_cmd(fd, "User-Agent: %s " _LIBFETCH_VER, __progname); 79963567Sdes if (url->offset) 80085093Sdes _http_cmd(fd, "Range: bytes=%lld-", (long long)url->offset); 80163012Sdes _http_cmd(fd, "Connection: close"); 80263012Sdes _http_cmd(fd, ""); 80360376Sdes 80463012Sdes /* get reply */ 80563012Sdes switch ((code = _http_get_reply(fd))) { 80663012Sdes case HTTP_OK: 80763012Sdes case HTTP_PARTIAL: 80863012Sdes /* fine */ 80963012Sdes break; 81063012Sdes case HTTP_MOVED_PERM: 81163012Sdes case HTTP_MOVED_TEMP: 81287317Sdes case HTTP_SEE_OTHER: 81363012Sdes /* 81463012Sdes * Not so fine, but we still have to read the headers to 81563012Sdes * get the new location. 81663012Sdes */ 81763012Sdes break; 81863012Sdes case HTTP_NEED_AUTH: 81963012Sdes if (need_auth) { 82063012Sdes /* 82163012Sdes * We already sent out authorization code, so there's 82263012Sdes * nothing more we can do. 82363012Sdes */ 82463012Sdes _http_seterr(code); 82563012Sdes goto ouch; 82663012Sdes } 82763012Sdes /* try again, but send the password this time */ 82863012Sdes if (verbose) 82963012Sdes _fetch_info("server requires authorization"); 83077238Sdes break; 83163012Sdes case HTTP_NEED_PROXY_AUTH: 83263012Sdes /* 83363012Sdes * If we're talking to a proxy, we already sent our proxy 83463012Sdes * authorization code, so there's nothing more we can do. 83563012Sdes */ 83663012Sdes _http_seterr(code); 83763012Sdes goto ouch; 83863012Sdes case HTTP_PROTOCOL_ERROR: 83963012Sdes /* fall through */ 84063012Sdes case -1: 84163012Sdes _fetch_syserr(); 84263012Sdes goto ouch; 84363012Sdes default: 84463012Sdes _http_seterr(code); 84563012Sdes goto ouch; 84663012Sdes } 84763012Sdes 84863012Sdes /* get headers */ 84963012Sdes do { 85063012Sdes switch ((h = _http_next_header(fd, &p))) { 85163012Sdes case hdr_syserror: 85263012Sdes _fetch_syserr(); 85363012Sdes goto ouch; 85463012Sdes case hdr_error: 85563012Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 85663012Sdes goto ouch; 85763012Sdes case hdr_content_length: 85863716Sdes _http_parse_length(p, &clength); 85963012Sdes break; 86063012Sdes case hdr_content_range: 86163716Sdes _http_parse_range(p, &offset, &length, &size); 86263012Sdes break; 86363012Sdes case hdr_last_modified: 86463716Sdes _http_parse_mtime(p, &mtime); 86563012Sdes break; 86663012Sdes case hdr_location: 86763012Sdes if (!HTTP_REDIRECT(code)) 86863012Sdes break; 86963069Sdes if (new) 87063069Sdes free(new); 87163012Sdes if (verbose) 87263012Sdes _fetch_info("%d redirect to %s", code, p); 87363069Sdes if (*p == '/') 87463069Sdes /* absolute path */ 87563069Sdes new = fetchMakeURL(url->scheme, url->host, url->port, p, 87663069Sdes url->user, url->pwd); 87763069Sdes else 87863069Sdes new = fetchParseURL(p); 87963069Sdes if (new == NULL) { 88063069Sdes /* XXX should set an error code */ 88163069Sdes DEBUG(fprintf(stderr, "failed to parse new URL\n")); 88263012Sdes goto ouch; 88363069Sdes } 88463012Sdes if (!*new->user && !*new->pwd) { 88563012Sdes strcpy(new->user, url->user); 88663012Sdes strcpy(new->pwd, url->pwd); 88763012Sdes } 88863012Sdes new->offset = url->offset; 88963012Sdes new->length = url->length; 89063069Sdes break; 89163012Sdes case hdr_transfer_encoding: 89263012Sdes /* XXX weak test*/ 89363012Sdes chunked = (strcasecmp(p, "chunked") == 0); 89463012Sdes break; 89577238Sdes case hdr_www_authenticate: 89677238Sdes if (code != HTTP_NEED_AUTH) 89777238Sdes break; 89877238Sdes /* if we were smarter, we'd check the method and realm */ 89977238Sdes break; 90063012Sdes case hdr_end: 90163012Sdes /* fall through */ 90263012Sdes case hdr_unknown: 90363012Sdes /* ignore */ 90463012Sdes break; 90563012Sdes } 90663012Sdes } while (h > hdr_end); 90760376Sdes 90877238Sdes /* we have a hit */ 90977238Sdes if (code == HTTP_OK || code == HTTP_PARTIAL) 91063012Sdes break; 91163069Sdes 91277238Sdes /* we need to provide authentication */ 91377238Sdes if (code == HTTP_NEED_AUTH) { 91477238Sdes need_auth = 1; 91577238Sdes close(fd); 91677238Sdes fd = -1; 91777238Sdes continue; 91877238Sdes } 91977238Sdes 92077238Sdes /* all other cases: we got a redirect */ 92177238Sdes need_auth = 0; 92263069Sdes close(fd); 92363337Sdes fd = -1; 92477238Sdes if (!new) { 92577238Sdes DEBUG(fprintf(stderr, "redirect with no new location\n")); 92677238Sdes break; 92777238Sdes } 92863069Sdes if (url != URL) 92963069Sdes fetchFreeURL(url); 93063069Sdes url = new; 93163716Sdes } while (++i < n); 93260376Sdes 93377238Sdes /* we failed, or ran out of retries */ 93463012Sdes if (fd == -1) { 93563012Sdes _http_seterr(code); 93663012Sdes goto ouch; 93737571Sdes } 93837535Sdes 93985093Sdes DEBUG(fprintf(stderr, "offset %lld, length %lld," 94085093Sdes " size %lld, clength %lld\n", 94185093Sdes (long long)offset, (long long)length, 94285093Sdes (long long)size, (long long)clength)); 94363716Sdes 94463716Sdes /* check for inconsistencies */ 94563716Sdes if (clength != -1 && length != -1 && clength != length) { 94663716Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 94763716Sdes goto ouch; 94863716Sdes } 94963716Sdes if (clength == -1) 95063716Sdes clength = length; 95163716Sdes if (clength != -1) 95263716Sdes length = offset + clength; 95363716Sdes if (length != -1 && size != -1 && length != size) { 95463716Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 95563716Sdes goto ouch; 95663716Sdes } 95763716Sdes if (size == -1) 95863716Sdes size = length; 95963716Sdes 96063716Sdes /* fill in stats */ 96163716Sdes if (us) { 96263716Sdes us->size = size; 96363716Sdes us->atime = us->mtime = mtime; 96463716Sdes } 96563716Sdes 96663567Sdes /* too far? */ 96763716Sdes if (offset > URL->offset) { 96863567Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 96963567Sdes goto ouch; 97063567Sdes } 97163567Sdes 97263716Sdes /* report back real offset and size */ 97363567Sdes URL->offset = offset; 97463716Sdes URL->length = clength; 97563567Sdes 97663012Sdes /* wrap it up in a FILE */ 97763012Sdes if ((f = chunked ? _http_funopen(fd) : fdopen(fd, "r")) == NULL) { 97863012Sdes _fetch_syserr(); 97963012Sdes goto ouch; 98063012Sdes } 98163012Sdes 98263012Sdes if (url != URL) 98363012Sdes fetchFreeURL(url); 98467043Sdes if (purl) 98567043Sdes fetchFreeURL(purl); 98663012Sdes 98763012Sdes return f; 98837535Sdes 98963012Sdes ouch: 99063012Sdes if (url != URL) 99163012Sdes fetchFreeURL(url); 99267043Sdes if (purl) 99367043Sdes fetchFreeURL(purl); 99463012Sdes if (fd != -1) 99563012Sdes close(fd); 99663012Sdes return NULL; 99763012Sdes} 99860189Sdes 99963012Sdes 100063012Sdes/***************************************************************************** 100163012Sdes * Entry points 100263012Sdes */ 100363012Sdes 100463012Sdes/* 100563340Sdes * Retrieve and stat a file by HTTP 100663340Sdes */ 100763340SdesFILE * 100875891SarchiefetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags) 100963340Sdes{ 101067043Sdes return _http_request(URL, "GET", us, _http_get_proxy(), flags); 101163340Sdes} 101263340Sdes 101363340Sdes/* 101463012Sdes * Retrieve a file by HTTP 101563012Sdes */ 101663012SdesFILE * 101775891SarchiefetchGetHTTP(struct url *URL, const char *flags) 101863012Sdes{ 101963340Sdes return fetchXGetHTTP(URL, NULL, flags); 102037535Sdes} 102137535Sdes 102263340Sdes/* 102363340Sdes * Store a file by HTTP 102463340Sdes */ 102537535SdesFILE * 102685093SdesfetchPutHTTP(struct url *URL __unused, const char *flags __unused) 102737535Sdes{ 102837535Sdes warnx("fetchPutHTTP(): not implemented"); 102937535Sdes return NULL; 103037535Sdes} 103140975Sdes 103240975Sdes/* 103340975Sdes * Get an HTTP document's metadata 103440975Sdes */ 103540975Sdesint 103675891SarchiefetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags) 103740975Sdes{ 103860376Sdes FILE *f; 103960376Sdes 104067043Sdes if ((f = _http_request(URL, "HEAD", us, _http_get_proxy(), flags)) == NULL) 104160376Sdes return -1; 104260581Sdes fclose(f); 104360376Sdes return 0; 104440975Sdes} 104541989Sdes 104641989Sdes/* 104741989Sdes * List a directory 104841989Sdes */ 104941989Sdesstruct url_ent * 105085093SdesfetchListHTTP(struct url *url __unused, const char *flags __unused) 105141989Sdes{ 105241989Sdes warnx("fetchListHTTP(): not implemented"); 105341989Sdes return NULL; 105441989Sdes} 1055