http.c revision 88771
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 88771 2002-01-01 16:25:29Z 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 10288771Sdes#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599) 10363012Sdes 10463012Sdes 10563012Sdes/***************************************************************************** 10663012Sdes * I/O functions for decoding chunked streams 10763012Sdes */ 10863012Sdes 10937535Sdesstruct cookie 11037535Sdes{ 11163012Sdes int fd; 11263012Sdes char *buf; 11363012Sdes size_t b_size; 11485093Sdes ssize_t b_len; 11563012Sdes int b_pos; 11663012Sdes int eof; 11763012Sdes int error; 11885093Sdes size_t chunksize; 11963281Sdes#ifndef NDEBUG 12085093Sdes size_t total; 12163012Sdes#endif 12237535Sdes}; 12337535Sdes 12437608Sdes/* 12563012Sdes * Get next chunk header 12637608Sdes */ 12737608Sdesstatic int 12863012Sdes_http_new_chunk(struct cookie *c) 12937608Sdes{ 13063012Sdes char *p; 13137608Sdes 13263012Sdes if (_fetch_getln(c->fd, &c->buf, &c->b_size, &c->b_len) == -1) 13363012Sdes return -1; 13463012Sdes 13563012Sdes if (c->b_len < 2 || !ishexnumber(*c->buf)) 13663012Sdes return -1; 13763012Sdes 13863012Sdes for (p = c->buf; !isspace(*p) && *p != ';' && p < c->buf + c->b_len; ++p) 13963012Sdes if (!ishexnumber(*p)) 14063012Sdes return -1; 14163012Sdes else if (isdigit(*p)) 14263012Sdes c->chunksize = c->chunksize * 16 + *p - '0'; 14363012Sdes else 14463012Sdes c->chunksize = c->chunksize * 16 + 10 + tolower(*p) - 'a'; 14563012Sdes 14663281Sdes#ifndef NDEBUG 14787561Sdes if (fetchDebug) { 14887561Sdes c->total += c->chunksize; 14987561Sdes if (c->chunksize == 0) 15088769Sdes fprintf(stderr, "_http_fillbuf(): " 15188769Sdes "end of last chunk\n"); 15287561Sdes else 15388769Sdes fprintf(stderr, "_http_fillbuf(): " 15488769Sdes "new chunk: %lu (%lu)\n", 15587561Sdes (unsigned long)c->chunksize, (unsigned long)c->total); 15687561Sdes } 15763012Sdes#endif 15863012Sdes 15963012Sdes return c->chunksize; 16037608Sdes} 16137608Sdes 16237608Sdes/* 16337608Sdes * Fill the input buffer, do chunk decoding on the fly 16437608Sdes */ 16563012Sdesstatic int 16637535Sdes_http_fillbuf(struct cookie *c) 16737535Sdes{ 16863012Sdes if (c->error) 16963012Sdes return -1; 17037535Sdes if (c->eof) 17163012Sdes return 0; 17263012Sdes 17363012Sdes if (c->chunksize == 0) { 17463012Sdes switch (_http_new_chunk(c)) { 17563012Sdes case -1: 17663012Sdes c->error = 1; 17763012Sdes return -1; 17863012Sdes case 0: 17963012Sdes c->eof = 1; 18063012Sdes return 0; 18137535Sdes } 18237535Sdes } 18363012Sdes 18463012Sdes if (c->b_size < c->chunksize) { 18563012Sdes char *tmp; 18663012Sdes 18763012Sdes if ((tmp = realloc(c->buf, c->chunksize)) == NULL) 18863012Sdes return -1; 18963012Sdes c->buf = tmp; 19063012Sdes c->b_size = c->chunksize; 19163012Sdes } 19263012Sdes 19363012Sdes if ((c->b_len = read(c->fd, c->buf, c->chunksize)) == -1) 19463012Sdes return -1; 19563012Sdes c->chunksize -= c->b_len; 19663012Sdes 19763012Sdes if (c->chunksize == 0) { 19863012Sdes char endl[2]; 19963012Sdes read(c->fd, endl, 2); 20063012Sdes } 20163012Sdes 20263012Sdes c->b_pos = 0; 20363012Sdes 20463012Sdes return c->b_len; 20537535Sdes} 20637535Sdes 20737608Sdes/* 20837608Sdes * Read function 20937608Sdes */ 21037535Sdesstatic int 21163012Sdes_http_readfn(void *v, char *buf, int len) 21237535Sdes{ 21363012Sdes struct cookie *c = (struct cookie *)v; 21463012Sdes int l, pos; 21563012Sdes 21663012Sdes if (c->error) 21763012Sdes return -1; 21863012Sdes if (c->eof) 21963012Sdes return 0; 22063012Sdes 22163012Sdes for (pos = 0; len > 0; pos += l, len -= l) { 22237535Sdes /* empty buffer */ 22363012Sdes if (!c->buf || c->b_pos == c->b_len) 22463012Sdes if (_http_fillbuf(c) < 1) 22537535Sdes break; 22663012Sdes l = c->b_len - c->b_pos; 22763012Sdes if (len < l) 22863012Sdes l = len; 22963012Sdes bcopy(c->buf + c->b_pos, buf + pos, l); 23063012Sdes c->b_pos += l; 23163012Sdes } 23237535Sdes 23363012Sdes if (!pos && c->error) 23437535Sdes return -1; 23563012Sdes return pos; 23637535Sdes} 23737535Sdes 23837608Sdes/* 23937608Sdes * Write function 24037608Sdes */ 24137535Sdesstatic int 24263012Sdes_http_writefn(void *v, const char *buf, int len) 24337535Sdes{ 24463012Sdes struct cookie *c = (struct cookie *)v; 24563012Sdes 24663012Sdes return write(c->fd, buf, len); 24737535Sdes} 24837535Sdes 24937608Sdes/* 25037608Sdes * Close function 25137608Sdes */ 25237535Sdesstatic int 25363012Sdes_http_closefn(void *v) 25437535Sdes{ 25563012Sdes struct cookie *c = (struct cookie *)v; 25663012Sdes int r; 25763012Sdes 25863012Sdes r = close(c->fd); 25963012Sdes if (c->buf) 26063012Sdes free(c->buf); 26137535Sdes free(c); 26263012Sdes return r; 26337535Sdes} 26437535Sdes 26537608Sdes/* 26663012Sdes * Wrap a file descriptor up 26737608Sdes */ 26863012Sdesstatic FILE * 26963012Sdes_http_funopen(int fd) 27037535Sdes{ 27163012Sdes struct cookie *c; 27263012Sdes FILE *f; 27363012Sdes 27463012Sdes if ((c = calloc(1, sizeof *c)) == NULL) { 27563012Sdes _fetch_syserr(); 27663012Sdes return NULL; 27763012Sdes } 27863012Sdes c->fd = fd; 27963012Sdes if (!(f = funopen(c, _http_readfn, _http_writefn, NULL, _http_closefn))) { 28063012Sdes _fetch_syserr(); 28163012Sdes free(c); 28263012Sdes return NULL; 28363012Sdes } 28463012Sdes return f; 28563012Sdes} 28663012Sdes 28763012Sdes 28863012Sdes/***************************************************************************** 28963012Sdes * Helper functions for talking to the server and parsing its replies 29063012Sdes */ 29163012Sdes 29263012Sdes/* Header types */ 29363012Sdestypedef enum { 29463012Sdes hdr_syserror = -2, 29563012Sdes hdr_error = -1, 29663012Sdes hdr_end = 0, 29763012Sdes hdr_unknown = 1, 29863012Sdes hdr_content_length, 29963012Sdes hdr_content_range, 30063012Sdes hdr_last_modified, 30163012Sdes hdr_location, 30277238Sdes hdr_transfer_encoding, 30377238Sdes hdr_www_authenticate 30485093Sdes} hdr_t; 30563012Sdes 30663012Sdes/* Names of interesting headers */ 30763012Sdesstatic struct { 30885093Sdes hdr_t num; 30975891Sarchie const char *name; 31063012Sdes} hdr_names[] = { 31163012Sdes { hdr_content_length, "Content-Length" }, 31263012Sdes { hdr_content_range, "Content-Range" }, 31363012Sdes { hdr_last_modified, "Last-Modified" }, 31463012Sdes { hdr_location, "Location" }, 31563012Sdes { hdr_transfer_encoding, "Transfer-Encoding" }, 31677238Sdes { hdr_www_authenticate, "WWW-Authenticate" }, 31763012Sdes { hdr_unknown, NULL }, 31863012Sdes}; 31963012Sdes 32063012Sdesstatic char *reply_buf; 32163012Sdesstatic size_t reply_size; 32263012Sdesstatic size_t reply_length; 32363012Sdes 32463012Sdes/* 32563012Sdes * Send a formatted line; optionally echo to terminal 32663012Sdes */ 32763012Sdesstatic int 32875891Sarchie_http_cmd(int fd, const char *fmt, ...) 32963012Sdes{ 33063012Sdes va_list ap; 33163012Sdes size_t len; 33263012Sdes char *msg; 33363012Sdes int r; 33463012Sdes 33563012Sdes va_start(ap, fmt); 33663012Sdes len = vasprintf(&msg, fmt, ap); 33763012Sdes va_end(ap); 33863012Sdes 33963012Sdes if (msg == NULL) { 34063012Sdes errno = ENOMEM; 34163012Sdes _fetch_syserr(); 34263012Sdes return -1; 34363012Sdes } 34463012Sdes 34563012Sdes r = _fetch_putln(fd, msg, len); 34663012Sdes free(msg); 34763012Sdes 34863012Sdes if (r == -1) { 34963012Sdes _fetch_syserr(); 35063012Sdes return -1; 35163012Sdes } 35263012Sdes 35363012Sdes return 0; 35463012Sdes} 35563012Sdes 35663012Sdes/* 35763012Sdes * Get and parse status line 35863012Sdes */ 35963012Sdesstatic int 36063012Sdes_http_get_reply(int fd) 36163012Sdes{ 36266325Sdes char *p; 36366325Sdes 36463012Sdes if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1) 36563012Sdes return -1; 36637535Sdes /* 36763012Sdes * A valid status line looks like "HTTP/m.n xyz reason" where m 36863012Sdes * and n are the major and minor protocol version numbers and xyz 36963012Sdes * is the reply code. 37066325Sdes * Unfortunately, there are servers out there (NCSA 1.5.1, to name 37166325Sdes * just one) that do not send a version number, so we can't rely 37266325Sdes * on finding one, but if we do, insist on it being 1.0 or 1.1. 37363012Sdes * We don't care about the reason phrase. 37437535Sdes */ 37566325Sdes if (strncmp(reply_buf, "HTTP", 4) != 0) 37663012Sdes return HTTP_PROTOCOL_ERROR; 37766325Sdes p = reply_buf + 4; 37866325Sdes if (*p == '/') { 37966325Sdes if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1')) 38066325Sdes return HTTP_PROTOCOL_ERROR; 38166325Sdes p += 4; 38266325Sdes } 38366325Sdes if (*p != ' ' 38466325Sdes || !isdigit(p[1]) 38566325Sdes || !isdigit(p[2]) 38666325Sdes || !isdigit(p[3])) 38766325Sdes return HTTP_PROTOCOL_ERROR; 38863012Sdes 38966325Sdes return ((p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0')); 39037535Sdes} 39137535Sdes 39237608Sdes/* 39363012Sdes * Check a header; if the type matches the given string, return a 39463012Sdes * pointer to the beginning of the value. 39563012Sdes */ 39675891Sarchiestatic const char * 39775891Sarchie_http_match(const char *str, const char *hdr) 39863012Sdes{ 39963012Sdes while (*str && *hdr && tolower(*str++) == tolower(*hdr++)) 40063012Sdes /* nothing */; 40163012Sdes if (*str || *hdr != ':') 40263012Sdes return NULL; 40363012Sdes while (*hdr && isspace(*++hdr)) 40463012Sdes /* nothing */; 40563012Sdes return hdr; 40663012Sdes} 40763012Sdes 40863012Sdes/* 40963012Sdes * Get the next header and return the appropriate symbolic code. 41063012Sdes */ 41185093Sdesstatic hdr_t 41275891Sarchie_http_next_header(int fd, const char **p) 41363012Sdes{ 41463012Sdes int i; 41563012Sdes 41663012Sdes if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1) 41763012Sdes return hdr_syserror; 41863012Sdes while (reply_length && isspace(reply_buf[reply_length-1])) 41963012Sdes reply_length--; 42063012Sdes reply_buf[reply_length] = 0; 42163012Sdes if (reply_length == 0) 42263012Sdes return hdr_end; 42363012Sdes /* 42463012Sdes * We could check for malformed headers but we don't really care. 42563012Sdes * A valid header starts with a token immediately followed by a 42663012Sdes * colon; a token is any sequence of non-control, non-whitespace 42763012Sdes * characters except "()<>@,;:\\\"{}". 42863012Sdes */ 42963012Sdes for (i = 0; hdr_names[i].num != hdr_unknown; i++) 43063012Sdes if ((*p = _http_match(hdr_names[i].name, reply_buf)) != NULL) 43163012Sdes return hdr_names[i].num; 43263012Sdes return hdr_unknown; 43363012Sdes} 43463012Sdes 43563012Sdes/* 43663012Sdes * Parse a last-modified header 43763012Sdes */ 43863716Sdesstatic int 43975891Sarchie_http_parse_mtime(const char *p, time_t *mtime) 44063012Sdes{ 44163716Sdes char locale[64], *r; 44263012Sdes struct tm tm; 44363012Sdes 44463012Sdes strncpy(locale, setlocale(LC_TIME, NULL), sizeof locale); 44563012Sdes setlocale(LC_TIME, "C"); 44663716Sdes r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm); 44763012Sdes /* XXX should add support for date-2 and date-3 */ 44863012Sdes setlocale(LC_TIME, locale); 44963716Sdes if (r == NULL) 45063716Sdes return -1; 45188769Sdes DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d " 45288769Sdes "%02d:%02d:%02d]\n", 45363012Sdes tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 45463012Sdes tm.tm_hour, tm.tm_min, tm.tm_sec)); 45563716Sdes *mtime = timegm(&tm); 45663716Sdes return 0; 45763012Sdes} 45863012Sdes 45963012Sdes/* 46063012Sdes * Parse a content-length header 46163012Sdes */ 46263716Sdesstatic int 46375891Sarchie_http_parse_length(const char *p, off_t *length) 46463012Sdes{ 46564129Sdes off_t len; 46663012Sdes 46763012Sdes for (len = 0; *p && isdigit(*p); ++p) 46863012Sdes len = len * 10 + (*p - '0'); 46985093Sdes if (*p) 47085093Sdes return -1; 47188769Sdes DEBUG(fprintf(stderr, "content length: [%lld]\n", 47285093Sdes (long long)len)); 47363716Sdes *length = len; 47463716Sdes return 0; 47563012Sdes} 47663012Sdes 47763012Sdes/* 47863012Sdes * Parse a content-range header 47963012Sdes */ 48063716Sdesstatic int 48175891Sarchie_http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size) 48263012Sdes{ 48385093Sdes off_t first, last, len; 48463716Sdes 48563012Sdes if (strncasecmp(p, "bytes ", 6) != 0) 48663012Sdes return -1; 48763716Sdes for (first = 0, p += 6; *p && isdigit(*p); ++p) 48863716Sdes first = first * 10 + *p - '0'; 48963012Sdes if (*p != '-') 49063012Sdes return -1; 49163716Sdes for (last = 0, ++p; *p && isdigit(*p); ++p) 49263716Sdes last = last * 10 + *p - '0'; 49363716Sdes if (first > last || *p != '/') 49463716Sdes return -1; 49563716Sdes for (len = 0, ++p; *p && isdigit(*p); ++p) 49663716Sdes len = len * 10 + *p - '0'; 49785093Sdes if (*p || len < last - first + 1) 49863716Sdes return -1; 49988769Sdes DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n", 50085093Sdes (long long)first, (long long)last, (long long)len)); 50163716Sdes *offset = first; 50263716Sdes *length = last - first + 1; 50363716Sdes *size = len; 50463716Sdes return 0; 50563012Sdes} 50663012Sdes 50763012Sdes 50863012Sdes/***************************************************************************** 50963012Sdes * Helper functions for authorization 51063012Sdes */ 51163012Sdes 51263012Sdes/* 51337608Sdes * Base64 encoding 51437608Sdes */ 51562965Sdesstatic char * 51662965Sdes_http_base64(char *src) 51737608Sdes{ 51837608Sdes static const char base64[] = 51937608Sdes "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 52037608Sdes "abcdefghijklmnopqrstuvwxyz" 52137608Sdes "0123456789+/"; 52262965Sdes char *str, *dst; 52362965Sdes size_t l; 52462965Sdes int t, r; 52562965Sdes 52662965Sdes l = strlen(src); 52762965Sdes if ((str = malloc(((l + 2) / 3) * 4)) == NULL) 52862965Sdes return NULL; 52962965Sdes dst = str; 53062965Sdes r = 0; 53137608Sdes 53237608Sdes while (l >= 3) { 53337608Sdes t = (src[0] << 16) | (src[1] << 8) | src[2]; 53437608Sdes dst[0] = base64[(t >> 18) & 0x3f]; 53537608Sdes dst[1] = base64[(t >> 12) & 0x3f]; 53637608Sdes dst[2] = base64[(t >> 6) & 0x3f]; 53737608Sdes dst[3] = base64[(t >> 0) & 0x3f]; 53837608Sdes src += 3; l -= 3; 53937608Sdes dst += 4; r += 4; 54037608Sdes } 54137608Sdes 54237608Sdes switch (l) { 54337608Sdes case 2: 54437608Sdes t = (src[0] << 16) | (src[1] << 8); 54537608Sdes dst[0] = base64[(t >> 18) & 0x3f]; 54637608Sdes dst[1] = base64[(t >> 12) & 0x3f]; 54737608Sdes dst[2] = base64[(t >> 6) & 0x3f]; 54837608Sdes dst[3] = '='; 54937608Sdes dst += 4; 55037608Sdes r += 4; 55137608Sdes break; 55237608Sdes case 1: 55337608Sdes t = src[0] << 16; 55437608Sdes dst[0] = base64[(t >> 18) & 0x3f]; 55537608Sdes dst[1] = base64[(t >> 12) & 0x3f]; 55637608Sdes dst[2] = dst[3] = '='; 55737608Sdes dst += 4; 55837608Sdes r += 4; 55937608Sdes break; 56037608Sdes case 0: 56137608Sdes break; 56237608Sdes } 56337608Sdes 56437608Sdes *dst = 0; 56562965Sdes return str; 56637608Sdes} 56737608Sdes 56837608Sdes/* 56937608Sdes * Encode username and password 57037608Sdes */ 57162965Sdesstatic int 57275891Sarchie_http_basic_auth(int fd, const char *hdr, const char *usr, const char *pwd) 57337608Sdes{ 57462965Sdes char *upw, *auth; 57562965Sdes int r; 57637608Sdes 57788769Sdes DEBUG(fprintf(stderr, "usr: [%s]\n", usr)); 57888769Sdes DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd)); 57962965Sdes if (asprintf(&upw, "%s:%s", usr, pwd) == -1) 58062965Sdes return -1; 58162965Sdes auth = _http_base64(upw); 58262965Sdes free(upw); 58362965Sdes if (auth == NULL) 58462965Sdes return -1; 58563012Sdes r = _http_cmd(fd, "%s: Basic %s", hdr, auth); 58662965Sdes free(auth); 58762965Sdes return r; 58862965Sdes} 58962965Sdes 59062965Sdes/* 59162965Sdes * Send an authorization header 59262965Sdes */ 59362965Sdesstatic int 59475891Sarchie_http_authorize(int fd, const char *hdr, const char *p) 59562965Sdes{ 59662965Sdes /* basic authorization */ 59762965Sdes if (strncasecmp(p, "basic:", 6) == 0) { 59862965Sdes char *user, *pwd, *str; 59962965Sdes int r; 60062965Sdes 60162965Sdes /* skip realm */ 60262965Sdes for (p += 6; *p && *p != ':'; ++p) 60362965Sdes /* nothing */ ; 60462965Sdes if (!*p || strchr(++p, ':') == NULL) 60562965Sdes return -1; 60662965Sdes if ((str = strdup(p)) == NULL) 60762965Sdes return -1; /* XXX */ 60862965Sdes user = str; 60962965Sdes pwd = strchr(str, ':'); 61062965Sdes *pwd++ = '\0'; 61163012Sdes r = _http_basic_auth(fd, hdr, user, pwd); 61262965Sdes free(str); 61362965Sdes return r; 61462811Sdes } 61562965Sdes return -1; 61637608Sdes} 61737608Sdes 61863012Sdes 61963012Sdes/***************************************************************************** 62063012Sdes * Helper functions for connecting to a server or proxy 62163012Sdes */ 62263012Sdes 62337608Sdes/* 62463012Sdes * Connect to the correct HTTP server or proxy. 62563012Sdes */ 62663012Sdesstatic int 62775891Sarchie_http_connect(struct url *URL, struct url *purl, const char *flags) 62863012Sdes{ 62967043Sdes int verbose; 63063012Sdes int af, fd; 63163012Sdes 63263012Sdes#ifdef INET6 63363012Sdes af = AF_UNSPEC; 63460737Sume#else 63563012Sdes af = AF_INET; 63660737Sume#endif 63767043Sdes 63867892Sdes verbose = CHECK_FLAG('v'); 63967892Sdes if (CHECK_FLAG('4')) 64060737Sume af = AF_INET; 64167043Sdes#ifdef INET6 64267892Sdes else if (CHECK_FLAG('6')) 64360737Sume af = AF_INET6; 64467043Sdes#endif 64567043Sdes 64667043Sdes if (purl) { 64767043Sdes URL = purl; 64867043Sdes } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) { 64967043Sdes /* can't talk http to an ftp server */ 65067043Sdes /* XXX should set an error code */ 65167043Sdes return -1; 65267043Sdes } 65341862Sdes 65467043Sdes if ((fd = _fetch_connect(URL->host, URL->port, af, verbose)) == -1) 65567043Sdes /* _fetch_connect() has already set an error code */ 65667043Sdes return -1; 65767043Sdes return fd; 65867043Sdes} 65967043Sdes 66067043Sdesstatic struct url * 66175891Sarchie_http_get_proxy(void) 66267043Sdes{ 66367043Sdes struct url *purl; 66467043Sdes char *p; 66537535Sdes 66673932Sdes if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 66773932Sdes (purl = fetchParseURL(p))) { 66867043Sdes if (!*purl->scheme) 66967043Sdes strcpy(purl->scheme, SCHEME_HTTP); 67067043Sdes if (!purl->port) 67168551Sdes purl->port = _fetch_default_proxy_port(purl->scheme); 67267043Sdes if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 67367043Sdes return purl; 67467043Sdes fetchFreeURL(purl); 67537535Sdes } 67667043Sdes return NULL; 67760376Sdes} 67860376Sdes 67988771Sdesstatic void 68088771Sdes_http_print_html(FILE *out, FILE *in) 68188771Sdes{ 68288771Sdes size_t len; 68388771Sdes char *line, *p, *q; 68488771Sdes int comment, tag; 68588771Sdes 68688771Sdes comment = tag = 0; 68788771Sdes while ((line = fgetln(in, &len)) != NULL) { 68888771Sdes while (len && isspace(line[len - 1])) 68988771Sdes --len; 69088771Sdes for (p = q = line; q < line + len; ++q) { 69188771Sdes if (comment && *q == '-') { 69288771Sdes if (q + 2 < line + len && strcmp(q, "-->") == 0) { 69388771Sdes tag = comment = 0; 69488771Sdes q += 2; 69588771Sdes } 69688771Sdes } if (tag && !comment && *q == '>') { 69788771Sdes p = q + 1; 69888771Sdes tag = 0; 69988771Sdes } else if (!tag && *q == '<') { 70088771Sdes if (q > p) 70188771Sdes fwrite(p, q - p, 1, out); 70288771Sdes tag = 1; 70388771Sdes if (q + 3 < line + len && strcmp(q, "<!--") == 0) { 70488771Sdes comment = 1; 70588771Sdes q += 3; 70688771Sdes } 70788771Sdes } 70888771Sdes } 70988771Sdes if (!tag && q > p) 71088771Sdes fwrite(p, q - p, 1, out); 71188771Sdes fputc('\n', out); 71288771Sdes } 71388771Sdes} 71488771Sdes 71563012Sdes 71663012Sdes/***************************************************************************** 71763012Sdes * Core 71860954Sdes */ 71960954Sdes 72060954Sdes/* 72163012Sdes * Send a request and process the reply 72260376Sdes */ 72367043SdesFILE * 72475891Sarchie_http_request(struct url *URL, const char *op, struct url_stat *us, 72575891Sarchie struct url *purl, const char *flags) 72660376Sdes{ 72763012Sdes struct url *url, *new; 72867043Sdes int chunked, direct, need_auth, noredirect, verbose; 72963012Sdes int code, fd, i, n; 73064129Sdes off_t offset, clength, length, size; 73163716Sdes time_t mtime; 73275891Sarchie const char *p; 73363012Sdes FILE *f; 73485093Sdes hdr_t h; 73560737Sume char *host; 73660737Sume#ifdef INET6 73760737Sume char hbuf[MAXHOSTNAMELEN + 1]; 73860737Sume#endif 73963012Sdes 74067892Sdes direct = CHECK_FLAG('d'); 74167892Sdes noredirect = CHECK_FLAG('A'); 74267892Sdes verbose = CHECK_FLAG('v'); 74360737Sume 74467043Sdes if (direct && purl) { 74567043Sdes fetchFreeURL(purl); 74667043Sdes purl = NULL; 74767043Sdes } 74867043Sdes 74963716Sdes /* try the provided URL first */ 75063716Sdes url = URL; 75163716Sdes 75263716Sdes /* if the A flag is set, we only get one try */ 75363012Sdes n = noredirect ? 1 : MAX_REDIRECT; 75463716Sdes i = 0; 75563012Sdes 75677238Sdes need_auth = 0; 75763716Sdes do { 75863069Sdes new = NULL; 75963069Sdes chunked = 0; 76063069Sdes offset = 0; 76163716Sdes clength = -1; 76263716Sdes length = -1; 76363716Sdes size = -1; 76463716Sdes mtime = 0; 76577238Sdes 76667043Sdes /* check port */ 76767043Sdes if (!url->port) 76868551Sdes url->port = _fetch_default_port(url->scheme); 76967043Sdes 77087317Sdes /* were we redirected to an FTP URL? */ 77187317Sdes if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) { 77287317Sdes if (strcmp(op, "GET") == 0) 77387317Sdes return _ftp_request(url, "RETR", us, purl, flags); 77487317Sdes else if (strcmp(op, "HEAD") == 0) 77587317Sdes return _ftp_request(url, "STAT", us, purl, flags); 77687317Sdes } 77787317Sdes 77863012Sdes /* connect to server or proxy */ 77967043Sdes if ((fd = _http_connect(url, purl, flags)) == -1) 78063012Sdes goto ouch; 78163012Sdes 78263012Sdes host = url->host; 78360737Sume#ifdef INET6 78463012Sdes if (strchr(url->host, ':')) { 78563012Sdes snprintf(hbuf, sizeof(hbuf), "[%s]", url->host); 78663012Sdes host = hbuf; 78763012Sdes } 78860737Sume#endif 78937535Sdes 79063012Sdes /* send request */ 79163012Sdes if (verbose) 79263012Sdes _fetch_info("requesting %s://%s:%d%s", 79363012Sdes url->scheme, host, url->port, url->doc); 79467043Sdes if (purl) { 79563012Sdes _http_cmd(fd, "%s %s://%s:%d%s HTTP/1.1", 79663012Sdes op, url->scheme, host, url->port, url->doc); 79763012Sdes } else { 79863012Sdes _http_cmd(fd, "%s %s HTTP/1.1", 79963012Sdes op, url->doc); 80063012Sdes } 80137535Sdes 80277238Sdes /* virtual host */ 80377238Sdes if (url->port == _fetch_default_port(url->scheme)) 80477238Sdes _http_cmd(fd, "Host: %s", host); 80577238Sdes else 80677238Sdes _http_cmd(fd, "Host: %s:%d", host, url->port); 80777238Sdes 80863012Sdes /* proxy authorization */ 80967043Sdes if (purl) { 81067043Sdes if (*purl->user || *purl->pwd) 81167043Sdes _http_basic_auth(fd, "Proxy-Authorization", 81267043Sdes purl->user, purl->pwd); 81367043Sdes else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0') 81467043Sdes _http_authorize(fd, "Proxy-Authorization", p); 81567043Sdes } 81663012Sdes 81763012Sdes /* server authorization */ 81877238Sdes if (need_auth || *url->user || *url->pwd) { 81963012Sdes if (*url->user || *url->pwd) 82067043Sdes _http_basic_auth(fd, "Authorization", url->user, url->pwd); 82163716Sdes else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0') 82263012Sdes _http_authorize(fd, "Authorization", p); 82377238Sdes else if (fetchAuthMethod && fetchAuthMethod(url) == 0) { 82477238Sdes _http_basic_auth(fd, "Authorization", url->user, url->pwd); 82577238Sdes } else { 82663012Sdes _http_seterr(HTTP_NEED_AUTH); 82763012Sdes goto ouch; 82863012Sdes } 82963012Sdes } 83060376Sdes 83163012Sdes /* other headers */ 83277261Sdes if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0') 83377261Sdes _http_cmd(fd, "User-Agent: %s", p); 83477261Sdes else 83577261Sdes _http_cmd(fd, "User-Agent: %s " _LIBFETCH_VER, __progname); 83663567Sdes if (url->offset) 83785093Sdes _http_cmd(fd, "Range: bytes=%lld-", (long long)url->offset); 83863012Sdes _http_cmd(fd, "Connection: close"); 83963012Sdes _http_cmd(fd, ""); 84060376Sdes 84163012Sdes /* get reply */ 84263012Sdes switch ((code = _http_get_reply(fd))) { 84363012Sdes case HTTP_OK: 84463012Sdes case HTTP_PARTIAL: 84563012Sdes /* fine */ 84663012Sdes break; 84763012Sdes case HTTP_MOVED_PERM: 84863012Sdes case HTTP_MOVED_TEMP: 84987317Sdes case HTTP_SEE_OTHER: 85063012Sdes /* 85163012Sdes * Not so fine, but we still have to read the headers to 85263012Sdes * get the new location. 85363012Sdes */ 85463012Sdes break; 85563012Sdes case HTTP_NEED_AUTH: 85663012Sdes if (need_auth) { 85763012Sdes /* 85863012Sdes * We already sent out authorization code, so there's 85963012Sdes * nothing more we can do. 86063012Sdes */ 86163012Sdes _http_seterr(code); 86263012Sdes goto ouch; 86363012Sdes } 86463012Sdes /* try again, but send the password this time */ 86563012Sdes if (verbose) 86663012Sdes _fetch_info("server requires authorization"); 86777238Sdes break; 86863012Sdes case HTTP_NEED_PROXY_AUTH: 86963012Sdes /* 87063012Sdes * If we're talking to a proxy, we already sent our proxy 87163012Sdes * authorization code, so there's nothing more we can do. 87263012Sdes */ 87363012Sdes _http_seterr(code); 87463012Sdes goto ouch; 87563012Sdes case HTTP_PROTOCOL_ERROR: 87663012Sdes /* fall through */ 87763012Sdes case -1: 87863012Sdes _fetch_syserr(); 87963012Sdes goto ouch; 88063012Sdes default: 88163012Sdes _http_seterr(code); 88288771Sdes if (!verbose) 88388771Sdes goto ouch; 88488771Sdes /* fall through so we can get the full error message */ 88563012Sdes } 88663012Sdes 88763012Sdes /* get headers */ 88863012Sdes do { 88963012Sdes switch ((h = _http_next_header(fd, &p))) { 89063012Sdes case hdr_syserror: 89163012Sdes _fetch_syserr(); 89263012Sdes goto ouch; 89363012Sdes case hdr_error: 89463012Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 89563012Sdes goto ouch; 89663012Sdes case hdr_content_length: 89763716Sdes _http_parse_length(p, &clength); 89863012Sdes break; 89963012Sdes case hdr_content_range: 90063716Sdes _http_parse_range(p, &offset, &length, &size); 90163012Sdes break; 90263012Sdes case hdr_last_modified: 90363716Sdes _http_parse_mtime(p, &mtime); 90463012Sdes break; 90563012Sdes case hdr_location: 90663012Sdes if (!HTTP_REDIRECT(code)) 90763012Sdes break; 90863069Sdes if (new) 90963069Sdes free(new); 91063012Sdes if (verbose) 91163012Sdes _fetch_info("%d redirect to %s", code, p); 91263069Sdes if (*p == '/') 91363069Sdes /* absolute path */ 91463069Sdes new = fetchMakeURL(url->scheme, url->host, url->port, p, 91563069Sdes url->user, url->pwd); 91663069Sdes else 91763069Sdes new = fetchParseURL(p); 91863069Sdes if (new == NULL) { 91963069Sdes /* XXX should set an error code */ 92063069Sdes DEBUG(fprintf(stderr, "failed to parse new URL\n")); 92163012Sdes goto ouch; 92263069Sdes } 92363012Sdes if (!*new->user && !*new->pwd) { 92463012Sdes strcpy(new->user, url->user); 92563012Sdes strcpy(new->pwd, url->pwd); 92663012Sdes } 92763012Sdes new->offset = url->offset; 92863012Sdes new->length = url->length; 92963069Sdes break; 93063012Sdes case hdr_transfer_encoding: 93163012Sdes /* XXX weak test*/ 93263012Sdes chunked = (strcasecmp(p, "chunked") == 0); 93363012Sdes break; 93477238Sdes case hdr_www_authenticate: 93577238Sdes if (code != HTTP_NEED_AUTH) 93677238Sdes break; 93777238Sdes /* if we were smarter, we'd check the method and realm */ 93877238Sdes break; 93963012Sdes case hdr_end: 94063012Sdes /* fall through */ 94163012Sdes case hdr_unknown: 94263012Sdes /* ignore */ 94363012Sdes break; 94463012Sdes } 94563012Sdes } while (h > hdr_end); 94660376Sdes 94788771Sdes /* we have a hit or an error */ 94888771Sdes if (code == HTTP_OK || code == HTTP_PARTIAL || HTTP_ERROR(code)) 94963012Sdes break; 95063069Sdes 95177238Sdes /* we need to provide authentication */ 95277238Sdes if (code == HTTP_NEED_AUTH) { 95377238Sdes need_auth = 1; 95477238Sdes close(fd); 95577238Sdes fd = -1; 95677238Sdes continue; 95777238Sdes } 95877238Sdes 95977238Sdes /* all other cases: we got a redirect */ 96077238Sdes need_auth = 0; 96163069Sdes close(fd); 96263337Sdes fd = -1; 96377238Sdes if (!new) { 96477238Sdes DEBUG(fprintf(stderr, "redirect with no new location\n")); 96577238Sdes break; 96677238Sdes } 96763069Sdes if (url != URL) 96863069Sdes fetchFreeURL(url); 96963069Sdes url = new; 97063716Sdes } while (++i < n); 97160376Sdes 97277238Sdes /* we failed, or ran out of retries */ 97363012Sdes if (fd == -1) { 97463012Sdes _http_seterr(code); 97563012Sdes goto ouch; 97637571Sdes } 97737535Sdes 97885093Sdes DEBUG(fprintf(stderr, "offset %lld, length %lld," 97985093Sdes " size %lld, clength %lld\n", 98085093Sdes (long long)offset, (long long)length, 98185093Sdes (long long)size, (long long)clength)); 98263716Sdes 98363716Sdes /* check for inconsistencies */ 98463716Sdes if (clength != -1 && length != -1 && clength != length) { 98563716Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 98663716Sdes goto ouch; 98763716Sdes } 98863716Sdes if (clength == -1) 98963716Sdes clength = length; 99063716Sdes if (clength != -1) 99163716Sdes length = offset + clength; 99263716Sdes if (length != -1 && size != -1 && length != size) { 99363716Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 99463716Sdes goto ouch; 99563716Sdes } 99663716Sdes if (size == -1) 99763716Sdes size = length; 99863716Sdes 99963716Sdes /* fill in stats */ 100063716Sdes if (us) { 100163716Sdes us->size = size; 100263716Sdes us->atime = us->mtime = mtime; 100363716Sdes } 100463716Sdes 100563567Sdes /* too far? */ 100663716Sdes if (offset > URL->offset) { 100763567Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 100863567Sdes goto ouch; 100963567Sdes } 101063567Sdes 101163716Sdes /* report back real offset and size */ 101263567Sdes URL->offset = offset; 101363716Sdes URL->length = clength; 101463567Sdes 101563012Sdes /* wrap it up in a FILE */ 101663012Sdes if ((f = chunked ? _http_funopen(fd) : fdopen(fd, "r")) == NULL) { 101763012Sdes _fetch_syserr(); 101863012Sdes goto ouch; 101963012Sdes } 102063012Sdes 102163012Sdes if (url != URL) 102263012Sdes fetchFreeURL(url); 102367043Sdes if (purl) 102467043Sdes fetchFreeURL(purl); 102588771Sdes 102688771Sdes if (HTTP_ERROR(code)) { 102788771Sdes _http_print_html(stderr, f); 102888771Sdes fclose(f); 102988771Sdes f = NULL; 103088771Sdes } 103163012Sdes 103263012Sdes return f; 103337535Sdes 103463012Sdes ouch: 103563012Sdes if (url != URL) 103663012Sdes fetchFreeURL(url); 103767043Sdes if (purl) 103867043Sdes fetchFreeURL(purl); 103963012Sdes if (fd != -1) 104063012Sdes close(fd); 104163012Sdes return NULL; 104263012Sdes} 104360189Sdes 104463012Sdes 104563012Sdes/***************************************************************************** 104663012Sdes * Entry points 104763012Sdes */ 104863012Sdes 104963012Sdes/* 105063340Sdes * Retrieve and stat a file by HTTP 105163340Sdes */ 105263340SdesFILE * 105375891SarchiefetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags) 105463340Sdes{ 105567043Sdes return _http_request(URL, "GET", us, _http_get_proxy(), flags); 105663340Sdes} 105763340Sdes 105863340Sdes/* 105963012Sdes * Retrieve a file by HTTP 106063012Sdes */ 106163012SdesFILE * 106275891SarchiefetchGetHTTP(struct url *URL, const char *flags) 106363012Sdes{ 106463340Sdes return fetchXGetHTTP(URL, NULL, flags); 106537535Sdes} 106637535Sdes 106763340Sdes/* 106863340Sdes * Store a file by HTTP 106963340Sdes */ 107037535SdesFILE * 107185093SdesfetchPutHTTP(struct url *URL __unused, const char *flags __unused) 107237535Sdes{ 107337535Sdes warnx("fetchPutHTTP(): not implemented"); 107437535Sdes return NULL; 107537535Sdes} 107640975Sdes 107740975Sdes/* 107840975Sdes * Get an HTTP document's metadata 107940975Sdes */ 108040975Sdesint 108175891SarchiefetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags) 108240975Sdes{ 108360376Sdes FILE *f; 108460376Sdes 108567043Sdes if ((f = _http_request(URL, "HEAD", us, _http_get_proxy(), flags)) == NULL) 108660376Sdes return -1; 108760581Sdes fclose(f); 108860376Sdes return 0; 108940975Sdes} 109041989Sdes 109141989Sdes/* 109241989Sdes * List a directory 109341989Sdes */ 109441989Sdesstruct url_ent * 109585093SdesfetchListHTTP(struct url *url __unused, const char *flags __unused) 109641989Sdes{ 109741989Sdes warnx("fetchListHTTP(): not implemented"); 109841989Sdes return NULL; 109941989Sdes} 1100