http.c revision 90267
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 90267 2002-02-05 22:13: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. 4990267Sdes * 5063236Sdes * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS 5163236Sdes * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE, 5263236Sdes * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 5363236Sdes * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT 5463236Sdes * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 5563236Sdes * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 5663236Sdes * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 5763236Sdes * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 5863236Sdes * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 5963236Sdes * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 6063236Sdes * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 6163236Sdes * SUCH DAMAGE. 6263236Sdes */ 6363236Sdes 6437535Sdes#include <sys/param.h> 6560737Sume#include <sys/socket.h> 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 8390267Sdesextern 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 \ 9990267Sdes || (xyz) == HTTP_MOVED_TEMP \ 10090267Sdes || (xyz) == HTTP_SEE_OTHER) 10163012Sdes 10288771Sdes#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599) 10363012Sdes 10490267Sdes 10563012Sdes/***************************************************************************** 10663012Sdes * I/O functions for decoding chunked streams 10763012Sdes */ 10863012Sdes 10937535Sdesstruct cookie 11037535Sdes{ 11190267Sdes int fd; 11290267Sdes char *buf; 11390267Sdes size_t b_size; 11490267Sdes ssize_t b_len; 11590267Sdes int b_pos; 11690267Sdes int eof; 11790267Sdes int error; 11890267Sdes size_t chunksize; 11963281Sdes#ifndef NDEBUG 12090267Sdes size_t total; 12163012Sdes#endif 12237535Sdes}; 12337535Sdes 12437608Sdes/* 12563012Sdes * Get next chunk header 12637608Sdes */ 12737608Sdesstatic int 12863012Sdes_http_new_chunk(struct cookie *c) 12937608Sdes{ 13090267Sdes char *p; 13190267Sdes 13290267Sdes if (_fetch_getln(c->fd, &c->buf, &c->b_size, &c->b_len) == -1) 13390267Sdes return (-1); 13490267Sdes 13590267Sdes if (c->b_len < 2 || !ishexnumber(*c->buf)) 13690267Sdes return (-1); 13790267Sdes 13890267Sdes for (p = c->buf; !isspace(*p) && p < c->buf + c->b_len; ++p) { 13990267Sdes if (*p == ';') 14090267Sdes break; 14190267Sdes if (!ishexnumber(*p)) 14290267Sdes return (-1); 14390267Sdes if (isdigit(*p)) { 14490267Sdes c->chunksize = c->chunksize * 16 + 14590267Sdes *p - '0'; 14690267Sdes } else { 14790267Sdes c->chunksize = c->chunksize * 16 + 14890267Sdes 10 + tolower(*p) - 'a'; 14990267Sdes } 15090267Sdes } 15190267Sdes 15263281Sdes#ifndef NDEBUG 15390267Sdes if (fetchDebug) { 15490267Sdes c->total += c->chunksize; 15590267Sdes if (c->chunksize == 0) 15690267Sdes fprintf(stderr, "_http_fillbuf(): " 15790267Sdes "end of last chunk\n"); 15890267Sdes else 15990267Sdes fprintf(stderr, "_http_fillbuf(): " 16090267Sdes "new chunk: %lu (%lu)\n", 16190267Sdes (unsigned long)c->chunksize, (unsigned long)c->total); 16290267Sdes } 16363012Sdes#endif 16490267Sdes 16590267Sdes return (c->chunksize); 16637608Sdes} 16737608Sdes 16837608Sdes/* 16937608Sdes * Fill the input buffer, do chunk decoding on the fly 17037608Sdes */ 17163012Sdesstatic int 17237535Sdes_http_fillbuf(struct cookie *c) 17337535Sdes{ 17490267Sdes if (c->error) 17590267Sdes return (-1); 17690267Sdes if (c->eof) 17790267Sdes return (0); 17890267Sdes 17990267Sdes if (c->chunksize == 0) { 18090267Sdes switch (_http_new_chunk(c)) { 18190267Sdes case -1: 18290267Sdes c->error = 1; 18390267Sdes return (-1); 18490267Sdes case 0: 18590267Sdes c->eof = 1; 18690267Sdes return (0); 18790267Sdes } 18837535Sdes } 18963012Sdes 19090267Sdes if (c->b_size < c->chunksize) { 19190267Sdes char *tmp; 19263012Sdes 19390267Sdes if ((tmp = realloc(c->buf, c->chunksize)) == NULL) 19490267Sdes return (-1); 19590267Sdes c->buf = tmp; 19690267Sdes c->b_size = c->chunksize; 19790267Sdes } 19890267Sdes 19990267Sdes if ((c->b_len = read(c->fd, c->buf, c->chunksize)) == -1) 20090267Sdes return (-1); 20190267Sdes c->chunksize -= c->b_len; 20290267Sdes 20390267Sdes if (c->chunksize == 0) { 20490267Sdes char endl; 20590267Sdes if (read(c->fd, &endl, 1) == -1 || 20690267Sdes read(c->fd, &endl, 1) == -1) 20790267Sdes return (-1); 20890267Sdes } 20990267Sdes 21090267Sdes c->b_pos = 0; 21190267Sdes 21290267Sdes return (c->b_len); 21337535Sdes} 21437535Sdes 21537608Sdes/* 21637608Sdes * Read function 21737608Sdes */ 21837535Sdesstatic int 21963012Sdes_http_readfn(void *v, char *buf, int len) 22037535Sdes{ 22190267Sdes struct cookie *c = (struct cookie *)v; 22290267Sdes int l, pos; 22363012Sdes 22490267Sdes if (c->error) 22590267Sdes return (-1); 22690267Sdes if (c->eof) 22790267Sdes return (0); 22863012Sdes 22990267Sdes for (pos = 0; len > 0; pos += l, len -= l) { 23090267Sdes /* empty buffer */ 23190267Sdes if (!c->buf || c->b_pos == c->b_len) 23290267Sdes if (_http_fillbuf(c) < 1) 23390267Sdes break; 23490267Sdes l = c->b_len - c->b_pos; 23590267Sdes if (len < l) 23690267Sdes l = len; 23790267Sdes bcopy(c->buf + c->b_pos, buf + pos, l); 23890267Sdes c->b_pos += l; 23990267Sdes } 24037535Sdes 24190267Sdes if (!pos && c->error) 24290267Sdes return (-1); 24390267Sdes return (pos); 24437535Sdes} 24537535Sdes 24637608Sdes/* 24737608Sdes * Write function 24837608Sdes */ 24937535Sdesstatic int 25063012Sdes_http_writefn(void *v, const char *buf, int len) 25137535Sdes{ 25290267Sdes struct cookie *c = (struct cookie *)v; 25390267Sdes 25490267Sdes return (write(c->fd, buf, len)); 25537535Sdes} 25637535Sdes 25737608Sdes/* 25837608Sdes * Close function 25937608Sdes */ 26037535Sdesstatic int 26163012Sdes_http_closefn(void *v) 26237535Sdes{ 26390267Sdes struct cookie *c = (struct cookie *)v; 26490267Sdes int r; 26563012Sdes 26690267Sdes r = close(c->fd); 26790267Sdes if (c->buf) 26890267Sdes free(c->buf); 26990267Sdes free(c); 27090267Sdes return (r); 27137535Sdes} 27237535Sdes 27337608Sdes/* 27463012Sdes * Wrap a file descriptor up 27537608Sdes */ 27663012Sdesstatic FILE * 27763012Sdes_http_funopen(int fd) 27837535Sdes{ 27990267Sdes struct cookie *c; 28090267Sdes FILE *f; 28163012Sdes 28290267Sdes if ((c = calloc(1, sizeof *c)) == NULL) { 28390267Sdes _fetch_syserr(); 28490267Sdes return (NULL); 28590267Sdes } 28690267Sdes c->fd = fd; 28790267Sdes f = funopen(c, _http_readfn, _http_writefn, NULL, _http_closefn); 28890267Sdes if (f == NULL) { 28990267Sdes _fetch_syserr(); 29090267Sdes free(c); 29190267Sdes return (NULL); 29290267Sdes } 29390267Sdes return (f); 29463012Sdes} 29563012Sdes 29690267Sdes 29763012Sdes/***************************************************************************** 29863012Sdes * Helper functions for talking to the server and parsing its replies 29963012Sdes */ 30063012Sdes 30163012Sdes/* Header types */ 30263012Sdestypedef enum { 30390267Sdes hdr_syserror = -2, 30490267Sdes hdr_error = -1, 30590267Sdes hdr_end = 0, 30690267Sdes hdr_unknown = 1, 30790267Sdes hdr_content_length, 30890267Sdes hdr_content_range, 30990267Sdes hdr_last_modified, 31090267Sdes hdr_location, 31190267Sdes hdr_transfer_encoding, 31290267Sdes hdr_www_authenticate 31385093Sdes} hdr_t; 31463012Sdes 31563012Sdes/* Names of interesting headers */ 31663012Sdesstatic struct { 31790267Sdes hdr_t num; 31890267Sdes const char *name; 31963012Sdes} hdr_names[] = { 32090267Sdes { hdr_content_length, "Content-Length" }, 32190267Sdes { hdr_content_range, "Content-Range" }, 32290267Sdes { hdr_last_modified, "Last-Modified" }, 32390267Sdes { hdr_location, "Location" }, 32490267Sdes { hdr_transfer_encoding, "Transfer-Encoding" }, 32590267Sdes { hdr_www_authenticate, "WWW-Authenticate" }, 32690267Sdes { hdr_unknown, NULL }, 32763012Sdes}; 32863012Sdes 32990267Sdesstatic char *reply_buf; 33090267Sdesstatic size_t reply_size; 33190267Sdesstatic size_t reply_length; 33263012Sdes 33363012Sdes/* 33463012Sdes * Send a formatted line; optionally echo to terminal 33563012Sdes */ 33663012Sdesstatic int 33775891Sarchie_http_cmd(int fd, const char *fmt, ...) 33863012Sdes{ 33990267Sdes va_list ap; 34090267Sdes size_t len; 34190267Sdes char *msg; 34290267Sdes int r; 34363012Sdes 34490267Sdes va_start(ap, fmt); 34590267Sdes len = vasprintf(&msg, fmt, ap); 34690267Sdes va_end(ap); 34790267Sdes 34890267Sdes if (msg == NULL) { 34990267Sdes errno = ENOMEM; 35090267Sdes _fetch_syserr(); 35190267Sdes return (-1); 35290267Sdes } 35390267Sdes 35490267Sdes r = _fetch_putln(fd, msg, len); 35590267Sdes free(msg); 35690267Sdes 35790267Sdes if (r == -1) { 35890267Sdes _fetch_syserr(); 35990267Sdes return (-1); 36090267Sdes } 36190267Sdes 36290267Sdes return (0); 36363012Sdes} 36463012Sdes 36563012Sdes/* 36663012Sdes * Get and parse status line 36763012Sdes */ 36863012Sdesstatic int 36963012Sdes_http_get_reply(int fd) 37063012Sdes{ 37190267Sdes char *p; 37290267Sdes 37390267Sdes if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1) 37490267Sdes return (-1); 37590267Sdes /* 37690267Sdes * A valid status line looks like "HTTP/m.n xyz reason" where m 37790267Sdes * and n are the major and minor protocol version numbers and xyz 37890267Sdes * is the reply code. 37990267Sdes * Unfortunately, there are servers out there (NCSA 1.5.1, to name 38090267Sdes * just one) that do not send a version number, so we can't rely 38190267Sdes * on finding one, but if we do, insist on it being 1.0 or 1.1. 38290267Sdes * We don't care about the reason phrase. 38390267Sdes */ 38490267Sdes if (strncmp(reply_buf, "HTTP", 4) != 0) 38590267Sdes return (HTTP_PROTOCOL_ERROR); 38690267Sdes p = reply_buf + 4; 38790267Sdes if (*p == '/') { 38890267Sdes if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1')) 38990267Sdes return (HTTP_PROTOCOL_ERROR); 39090267Sdes p += 4; 39190267Sdes } 39290267Sdes if (*p != ' ' || !isdigit(p[1]) || !isdigit(p[2]) || !isdigit(p[3])) 39390267Sdes return (HTTP_PROTOCOL_ERROR); 39490267Sdes 39590267Sdes return ((p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0')); 39637535Sdes} 39737535Sdes 39837608Sdes/* 39990267Sdes * Check a header; if the type matches the given string, return a pointer 40090267Sdes * to the beginning of the value. 40163012Sdes */ 40275891Sarchiestatic const char * 40375891Sarchie_http_match(const char *str, const char *hdr) 40463012Sdes{ 40590267Sdes while (*str && *hdr && tolower(*str++) == tolower(*hdr++)) 40690267Sdes /* nothing */; 40790267Sdes if (*str || *hdr != ':') 40890267Sdes return (NULL); 40990267Sdes while (*hdr && isspace(*++hdr)) 41090267Sdes /* nothing */; 41190267Sdes return (hdr); 41263012Sdes} 41363012Sdes 41463012Sdes/* 41563012Sdes * Get the next header and return the appropriate symbolic code. 41663012Sdes */ 41785093Sdesstatic hdr_t 41875891Sarchie_http_next_header(int fd, const char **p) 41963012Sdes{ 42090267Sdes int i; 42190267Sdes 42290267Sdes if (_fetch_getln(fd, &reply_buf, &reply_size, &reply_length) == -1) 42390267Sdes return (hdr_syserror); 42490267Sdes while (reply_length && isspace(reply_buf[reply_length-1])) 42590267Sdes reply_length--; 42690267Sdes reply_buf[reply_length] = 0; 42790267Sdes if (reply_length == 0) 42890267Sdes return (hdr_end); 42990267Sdes /* 43090267Sdes * We could check for malformed headers but we don't really care. 43190267Sdes * A valid header starts with a token immediately followed by a 43290267Sdes * colon; a token is any sequence of non-control, non-whitespace 43390267Sdes * characters except "()<>@,;:\\\"{}". 43490267Sdes */ 43590267Sdes for (i = 0; hdr_names[i].num != hdr_unknown; i++) 43690267Sdes if ((*p = _http_match(hdr_names[i].name, reply_buf)) != NULL) 43790267Sdes return (hdr_names[i].num); 43890267Sdes return (hdr_unknown); 43963012Sdes} 44063012Sdes 44163012Sdes/* 44263012Sdes * Parse a last-modified header 44363012Sdes */ 44463716Sdesstatic int 44575891Sarchie_http_parse_mtime(const char *p, time_t *mtime) 44663012Sdes{ 44790267Sdes char locale[64], *r; 44890267Sdes struct tm tm; 44963012Sdes 45090267Sdes strncpy(locale, setlocale(LC_TIME, NULL), sizeof locale); 45190267Sdes setlocale(LC_TIME, "C"); 45290267Sdes r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm); 45390267Sdes /* XXX should add support for date-2 and date-3 */ 45490267Sdes setlocale(LC_TIME, locale); 45590267Sdes if (r == NULL) 45690267Sdes return (-1); 45790267Sdes DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d " 45888769Sdes "%02d:%02d:%02d]\n", 45963012Sdes tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 46063012Sdes tm.tm_hour, tm.tm_min, tm.tm_sec)); 46190267Sdes *mtime = timegm(&tm); 46290267Sdes return (0); 46363012Sdes} 46463012Sdes 46563012Sdes/* 46663012Sdes * Parse a content-length header 46763012Sdes */ 46863716Sdesstatic int 46975891Sarchie_http_parse_length(const char *p, off_t *length) 47063012Sdes{ 47190267Sdes off_t len; 47290267Sdes 47390267Sdes for (len = 0; *p && isdigit(*p); ++p) 47490267Sdes len = len * 10 + (*p - '0'); 47590267Sdes if (*p) 47690267Sdes return (-1); 47790267Sdes DEBUG(fprintf(stderr, "content length: [%lld]\n", 47890267Sdes (long long)len)); 47990267Sdes *length = len; 48090267Sdes return (0); 48163012Sdes} 48263012Sdes 48363012Sdes/* 48463012Sdes * Parse a content-range header 48563012Sdes */ 48663716Sdesstatic int 48775891Sarchie_http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size) 48863012Sdes{ 48990267Sdes off_t first, last, len; 49063716Sdes 49190267Sdes if (strncasecmp(p, "bytes ", 6) != 0) 49290267Sdes return (-1); 49390267Sdes for (first = 0, p += 6; *p && isdigit(*p); ++p) 49490267Sdes first = first * 10 + *p - '0'; 49590267Sdes if (*p != '-') 49690267Sdes return (-1); 49790267Sdes for (last = 0, ++p; *p && isdigit(*p); ++p) 49890267Sdes last = last * 10 + *p - '0'; 49990267Sdes if (first > last || *p != '/') 50090267Sdes return (-1); 50190267Sdes for (len = 0, ++p; *p && isdigit(*p); ++p) 50290267Sdes len = len * 10 + *p - '0'; 50390267Sdes if (*p || len < last - first + 1) 50490267Sdes return (-1); 50590267Sdes DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n", 50690267Sdes (long long)first, (long long)last, (long long)len)); 50790267Sdes *offset = first; 50890267Sdes *length = last - first + 1; 50990267Sdes *size = len; 51090267Sdes return (0); 51163012Sdes} 51263012Sdes 51390267Sdes 51463012Sdes/***************************************************************************** 51563012Sdes * Helper functions for authorization 51663012Sdes */ 51763012Sdes 51863012Sdes/* 51937608Sdes * Base64 encoding 52037608Sdes */ 52162965Sdesstatic char * 52290267Sdes_http_base64(const char *src) 52337608Sdes{ 52490267Sdes static const char base64[] = 52590267Sdes "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 52690267Sdes "abcdefghijklmnopqrstuvwxyz" 52790267Sdes "0123456789+/"; 52890267Sdes char *str, *dst; 52990267Sdes size_t l; 53090267Sdes int t, r; 53162965Sdes 53290267Sdes l = strlen(src); 53390267Sdes if ((str = malloc(((l + 2) / 3) * 4)) == NULL) 53490267Sdes return (NULL); 53590267Sdes dst = str; 53690267Sdes r = 0; 53737608Sdes 53890267Sdes while (l >= 3) { 53990267Sdes t = (src[0] << 16) | (src[1] << 8) | src[2]; 54090267Sdes dst[0] = base64[(t >> 18) & 0x3f]; 54190267Sdes dst[1] = base64[(t >> 12) & 0x3f]; 54290267Sdes dst[2] = base64[(t >> 6) & 0x3f]; 54390267Sdes dst[3] = base64[(t >> 0) & 0x3f]; 54490267Sdes src += 3; l -= 3; 54590267Sdes dst += 4; r += 4; 54690267Sdes } 54737608Sdes 54890267Sdes switch (l) { 54990267Sdes case 2: 55090267Sdes t = (src[0] << 16) | (src[1] << 8); 55190267Sdes dst[0] = base64[(t >> 18) & 0x3f]; 55290267Sdes dst[1] = base64[(t >> 12) & 0x3f]; 55390267Sdes dst[2] = base64[(t >> 6) & 0x3f]; 55490267Sdes dst[3] = '='; 55590267Sdes dst += 4; 55690267Sdes r += 4; 55790267Sdes break; 55890267Sdes case 1: 55990267Sdes t = src[0] << 16; 56090267Sdes dst[0] = base64[(t >> 18) & 0x3f]; 56190267Sdes dst[1] = base64[(t >> 12) & 0x3f]; 56290267Sdes dst[2] = dst[3] = '='; 56390267Sdes dst += 4; 56490267Sdes r += 4; 56590267Sdes break; 56690267Sdes case 0: 56790267Sdes break; 56890267Sdes } 56990267Sdes 57090267Sdes *dst = 0; 57190267Sdes return (str); 57237608Sdes} 57337608Sdes 57437608Sdes/* 57537608Sdes * Encode username and password 57637608Sdes */ 57762965Sdesstatic int 57875891Sarchie_http_basic_auth(int fd, const char *hdr, const char *usr, const char *pwd) 57937608Sdes{ 58090267Sdes char *upw, *auth; 58190267Sdes int r; 58237608Sdes 58390267Sdes DEBUG(fprintf(stderr, "usr: [%s]\n", usr)); 58490267Sdes DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd)); 58590267Sdes if (asprintf(&upw, "%s:%s", usr, pwd) == -1) 58690267Sdes return (-1); 58790267Sdes auth = _http_base64(upw); 58890267Sdes free(upw); 58990267Sdes if (auth == NULL) 59090267Sdes return (-1); 59190267Sdes r = _http_cmd(fd, "%s: Basic %s", hdr, auth); 59290267Sdes free(auth); 59390267Sdes return (r); 59462965Sdes} 59562965Sdes 59662965Sdes/* 59762965Sdes * Send an authorization header 59862965Sdes */ 59962965Sdesstatic int 60075891Sarchie_http_authorize(int fd, const char *hdr, const char *p) 60162965Sdes{ 60290267Sdes /* basic authorization */ 60390267Sdes if (strncasecmp(p, "basic:", 6) == 0) { 60490267Sdes char *user, *pwd, *str; 60590267Sdes int r; 60662965Sdes 60790267Sdes /* skip realm */ 60890267Sdes for (p += 6; *p && *p != ':'; ++p) 60990267Sdes /* nothing */ ; 61090267Sdes if (!*p || strchr(++p, ':') == NULL) 61190267Sdes return (-1); 61290267Sdes if ((str = strdup(p)) == NULL) 61390267Sdes return (-1); /* XXX */ 61490267Sdes user = str; 61590267Sdes pwd = strchr(str, ':'); 61690267Sdes *pwd++ = '\0'; 61790267Sdes r = _http_basic_auth(fd, hdr, user, pwd); 61890267Sdes free(str); 61990267Sdes return (r); 62090267Sdes } 62190267Sdes return (-1); 62237608Sdes} 62337608Sdes 62490267Sdes 62563012Sdes/***************************************************************************** 62663012Sdes * Helper functions for connecting to a server or proxy 62763012Sdes */ 62863012Sdes 62937608Sdes/* 63090267Sdes * Connect to the correct HTTP server or proxy. 63163012Sdes */ 63263012Sdesstatic int 63375891Sarchie_http_connect(struct url *URL, struct url *purl, const char *flags) 63463012Sdes{ 63590267Sdes int verbose; 63690267Sdes int af, fd; 63790267Sdes 63863012Sdes#ifdef INET6 63990267Sdes af = AF_UNSPEC; 64060737Sume#else 64190267Sdes af = AF_INET; 64260737Sume#endif 64390267Sdes 64490267Sdes verbose = CHECK_FLAG('v'); 64590267Sdes if (CHECK_FLAG('4')) 64690267Sdes af = AF_INET; 64767043Sdes#ifdef INET6 64890267Sdes else if (CHECK_FLAG('6')) 64990267Sdes af = AF_INET6; 65067043Sdes#endif 65167043Sdes 65290267Sdes if (purl) { 65390267Sdes URL = purl; 65490267Sdes } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) { 65590267Sdes /* can't talk http to an ftp server */ 65690267Sdes /* XXX should set an error code */ 65790267Sdes return (-1); 65890267Sdes } 65990267Sdes 66090267Sdes if ((fd = _fetch_connect(URL->host, URL->port, af, verbose)) == -1) 66190267Sdes /* _fetch_connect() has already set an error code */ 66290267Sdes return (-1); 66390267Sdes return (fd); 66467043Sdes} 66567043Sdes 66667043Sdesstatic struct url * 66775891Sarchie_http_get_proxy(void) 66867043Sdes{ 66990267Sdes struct url *purl; 67090267Sdes char *p; 67190267Sdes 67290267Sdes if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 67390267Sdes (purl = fetchParseURL(p))) { 67490267Sdes if (!*purl->scheme) 67590267Sdes strcpy(purl->scheme, SCHEME_HTTP); 67690267Sdes if (!purl->port) 67790267Sdes purl->port = _fetch_default_proxy_port(purl->scheme); 67890267Sdes if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 67990267Sdes return (purl); 68090267Sdes fetchFreeURL(purl); 68190267Sdes } 68290267Sdes return (NULL); 68360376Sdes} 68460376Sdes 68588771Sdesstatic void 68688771Sdes_http_print_html(FILE *out, FILE *in) 68788771Sdes{ 68890267Sdes size_t len; 68990267Sdes char *line, *p, *q; 69090267Sdes int comment, tag; 69188771Sdes 69290267Sdes comment = tag = 0; 69390267Sdes while ((line = fgetln(in, &len)) != NULL) { 69490267Sdes while (len && isspace(line[len - 1])) 69590267Sdes --len; 69690267Sdes for (p = q = line; q < line + len; ++q) { 69790267Sdes if (comment && *q == '-') { 69890267Sdes if (q + 2 < line + len && 69990267Sdes strcmp(q, "-->") == 0) { 70090267Sdes tag = comment = 0; 70190267Sdes q += 2; 70290267Sdes } 70390267Sdes } else if (tag && !comment && *q == '>') { 70490267Sdes p = q + 1; 70590267Sdes tag = 0; 70690267Sdes } else if (!tag && *q == '<') { 70790267Sdes if (q > p) 70890267Sdes fwrite(p, q - p, 1, out); 70990267Sdes tag = 1; 71090267Sdes if (q + 3 < line + len && 71190267Sdes strcmp(q, "<!--") == 0) { 71290267Sdes comment = 1; 71390267Sdes q += 3; 71490267Sdes } 71590267Sdes } 71688771Sdes } 71790267Sdes if (!tag && q > p) 71890267Sdes fwrite(p, q - p, 1, out); 71990267Sdes fputc('\n', out); 72088771Sdes } 72188771Sdes} 72288771Sdes 72390267Sdes 72463012Sdes/***************************************************************************** 72563012Sdes * Core 72660954Sdes */ 72760954Sdes 72860954Sdes/* 72963012Sdes * Send a request and process the reply 73060376Sdes */ 73167043SdesFILE * 73275891Sarchie_http_request(struct url *URL, const char *op, struct url_stat *us, 73390267Sdes struct url *purl, const char *flags) 73460376Sdes{ 73590267Sdes struct url *url, *new; 73690267Sdes int chunked, direct, need_auth, noredirect, verbose; 73790267Sdes int code, fd, i, n; 73890267Sdes off_t offset, clength, length, size; 73990267Sdes time_t mtime; 74090267Sdes const char *p; 74190267Sdes FILE *f; 74290267Sdes hdr_t h; 74390267Sdes char *host; 74460737Sume#ifdef INET6 74590267Sdes char hbuf[MAXHOSTNAMELEN + 1]; 74660737Sume#endif 74763012Sdes 74890267Sdes direct = CHECK_FLAG('d'); 74990267Sdes noredirect = CHECK_FLAG('A'); 75090267Sdes verbose = CHECK_FLAG('v'); 75160737Sume 75290267Sdes if (direct && purl) { 75390267Sdes fetchFreeURL(purl); 75490267Sdes purl = NULL; 75590267Sdes } 75663716Sdes 75790267Sdes /* try the provided URL first */ 75890267Sdes url = URL; 75963012Sdes 76090267Sdes /* if the A flag is set, we only get one try */ 76190267Sdes n = noredirect ? 1 : MAX_REDIRECT; 76290267Sdes i = 0; 76363012Sdes 76490267Sdes need_auth = 0; 76590267Sdes do { 76690267Sdes new = NULL; 76790267Sdes chunked = 0; 76890267Sdes offset = 0; 76990267Sdes clength = -1; 77090267Sdes length = -1; 77190267Sdes size = -1; 77290267Sdes mtime = 0; 77390267Sdes 77490267Sdes /* check port */ 77590267Sdes if (!url->port) 77690267Sdes url->port = _fetch_default_port(url->scheme); 77790267Sdes 77890267Sdes /* were we redirected to an FTP URL? */ 77990267Sdes if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) { 78090267Sdes if (strcmp(op, "GET") == 0) 78190267Sdes return (_ftp_request(url, "RETR", us, purl, flags)); 78290267Sdes else if (strcmp(op, "HEAD") == 0) 78390267Sdes return (_ftp_request(url, "STAT", us, purl, flags)); 78490267Sdes } 78590267Sdes 78690267Sdes /* connect to server or proxy */ 78790267Sdes if ((fd = _http_connect(url, purl, flags)) == -1) 78890267Sdes goto ouch; 78990267Sdes 79090267Sdes host = url->host; 79160737Sume#ifdef INET6 79290267Sdes if (strchr(url->host, ':')) { 79390267Sdes snprintf(hbuf, sizeof(hbuf), "[%s]", url->host); 79490267Sdes host = hbuf; 79590267Sdes } 79660737Sume#endif 79737535Sdes 79890267Sdes /* send request */ 79990267Sdes if (verbose) 80090267Sdes _fetch_info("requesting %s://%s:%d%s", 80190267Sdes url->scheme, host, url->port, url->doc); 80290267Sdes if (purl) { 80390267Sdes _http_cmd(fd, "%s %s://%s:%d%s HTTP/1.1", 80490267Sdes op, url->scheme, host, url->port, url->doc); 80590267Sdes } else { 80690267Sdes _http_cmd(fd, "%s %s HTTP/1.1", 80790267Sdes op, url->doc); 80890267Sdes } 80937535Sdes 81090267Sdes /* virtual host */ 81190267Sdes if (url->port == _fetch_default_port(url->scheme)) 81290267Sdes _http_cmd(fd, "Host: %s", host); 81390267Sdes else 81490267Sdes _http_cmd(fd, "Host: %s:%d", host, url->port); 81590267Sdes 81690267Sdes /* proxy authorization */ 81790267Sdes if (purl) { 81890267Sdes if (*purl->user || *purl->pwd) 81990267Sdes _http_basic_auth(fd, "Proxy-Authorization", 82090267Sdes purl->user, purl->pwd); 82190267Sdes else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0') 82290267Sdes _http_authorize(fd, "Proxy-Authorization", p); 82390267Sdes } 82490267Sdes 82590267Sdes /* server authorization */ 82690267Sdes if (need_auth || *url->user || *url->pwd) { 82790267Sdes if (*url->user || *url->pwd) 82890267Sdes _http_basic_auth(fd, "Authorization", url->user, url->pwd); 82990267Sdes else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0') 83090267Sdes _http_authorize(fd, "Authorization", p); 83190267Sdes else if (fetchAuthMethod && fetchAuthMethod(url) == 0) { 83290267Sdes _http_basic_auth(fd, "Authorization", url->user, url->pwd); 83390267Sdes } else { 83490267Sdes _http_seterr(HTTP_NEED_AUTH); 83590267Sdes goto ouch; 83690267Sdes } 83790267Sdes } 83890267Sdes 83990267Sdes /* other headers */ 84090267Sdes if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0') 84190267Sdes _http_cmd(fd, "User-Agent: %s", p); 84290267Sdes else 84390267Sdes _http_cmd(fd, "User-Agent: %s " _LIBFETCH_VER, __progname); 84490267Sdes if (url->offset) 84590267Sdes _http_cmd(fd, "Range: bytes=%lld-", (long long)url->offset); 84690267Sdes _http_cmd(fd, "Connection: close"); 84790267Sdes _http_cmd(fd, ""); 84890267Sdes 84990267Sdes /* get reply */ 85090267Sdes switch ((code = _http_get_reply(fd))) { 85190267Sdes case HTTP_OK: 85290267Sdes case HTTP_PARTIAL: 85390267Sdes /* fine */ 85490267Sdes break; 85590267Sdes case HTTP_MOVED_PERM: 85690267Sdes case HTTP_MOVED_TEMP: 85790267Sdes case HTTP_SEE_OTHER: 85890267Sdes /* 85990267Sdes * Not so fine, but we still have to read the headers to 86090267Sdes * get the new location. 86190267Sdes */ 86290267Sdes break; 86390267Sdes case HTTP_NEED_AUTH: 86490267Sdes if (need_auth) { 86590267Sdes /* 86690267Sdes * We already sent out authorization code, so there's 86790267Sdes * nothing more we can do. 86890267Sdes */ 86990267Sdes _http_seterr(code); 87090267Sdes goto ouch; 87190267Sdes } 87290267Sdes /* try again, but send the password this time */ 87390267Sdes if (verbose) 87490267Sdes _fetch_info("server requires authorization"); 87590267Sdes break; 87690267Sdes case HTTP_NEED_PROXY_AUTH: 87790267Sdes /* 87890267Sdes * If we're talking to a proxy, we already sent our proxy 87990267Sdes * authorization code, so there's nothing more we can do. 88090267Sdes */ 88190267Sdes _http_seterr(code); 88290267Sdes goto ouch; 88390267Sdes case HTTP_PROTOCOL_ERROR: 88490267Sdes /* fall through */ 88590267Sdes case -1: 88690267Sdes _fetch_syserr(); 88790267Sdes goto ouch; 88890267Sdes default: 88990267Sdes _http_seterr(code); 89090267Sdes if (!verbose) 89190267Sdes goto ouch; 89290267Sdes /* fall through so we can get the full error message */ 89390267Sdes } 89490267Sdes 89590267Sdes /* get headers */ 89690267Sdes do { 89790267Sdes switch ((h = _http_next_header(fd, &p))) { 89890267Sdes case hdr_syserror: 89990267Sdes _fetch_syserr(); 90090267Sdes goto ouch; 90190267Sdes case hdr_error: 90290267Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 90390267Sdes goto ouch; 90490267Sdes case hdr_content_length: 90590267Sdes _http_parse_length(p, &clength); 90690267Sdes break; 90790267Sdes case hdr_content_range: 90890267Sdes _http_parse_range(p, &offset, &length, &size); 90990267Sdes break; 91090267Sdes case hdr_last_modified: 91190267Sdes _http_parse_mtime(p, &mtime); 91290267Sdes break; 91390267Sdes case hdr_location: 91490267Sdes if (!HTTP_REDIRECT(code)) 91590267Sdes break; 91690267Sdes if (new) 91790267Sdes free(new); 91890267Sdes if (verbose) 91990267Sdes _fetch_info("%d redirect to %s", code, p); 92090267Sdes if (*p == '/') 92190267Sdes /* absolute path */ 92290267Sdes new = fetchMakeURL(url->scheme, url->host, url->port, p, 92390267Sdes url->user, url->pwd); 92490267Sdes else 92590267Sdes new = fetchParseURL(p); 92690267Sdes if (new == NULL) { 92790267Sdes /* XXX should set an error code */ 92890267Sdes DEBUG(fprintf(stderr, "failed to parse new URL\n")); 92990267Sdes goto ouch; 93090267Sdes } 93190267Sdes if (!*new->user && !*new->pwd) { 93290267Sdes strcpy(new->user, url->user); 93390267Sdes strcpy(new->pwd, url->pwd); 93490267Sdes } 93590267Sdes new->offset = url->offset; 93690267Sdes new->length = url->length; 93790267Sdes break; 93890267Sdes case hdr_transfer_encoding: 93990267Sdes /* XXX weak test*/ 94090267Sdes chunked = (strcasecmp(p, "chunked") == 0); 94190267Sdes break; 94290267Sdes case hdr_www_authenticate: 94390267Sdes if (code != HTTP_NEED_AUTH) 94490267Sdes break; 94590267Sdes /* if we were smarter, we'd check the method and realm */ 94690267Sdes break; 94790267Sdes case hdr_end: 94890267Sdes /* fall through */ 94990267Sdes case hdr_unknown: 95090267Sdes /* ignore */ 95190267Sdes break; 95290267Sdes } 95390267Sdes } while (h > hdr_end); 95490267Sdes 95590267Sdes /* we have a hit or an error */ 95690267Sdes if (code == HTTP_OK || code == HTTP_PARTIAL || HTTP_ERROR(code)) 95790267Sdes break; 95890267Sdes 95990267Sdes /* we need to provide authentication */ 96090267Sdes if (code == HTTP_NEED_AUTH) { 96190267Sdes need_auth = 1; 96290267Sdes close(fd); 96390267Sdes fd = -1; 96490267Sdes continue; 96590267Sdes } 96690267Sdes 96790267Sdes /* all other cases: we got a redirect */ 96890267Sdes need_auth = 0; 96990267Sdes close(fd); 97090267Sdes fd = -1; 97190267Sdes if (!new) { 97290267Sdes DEBUG(fprintf(stderr, "redirect with no new location\n")); 97390267Sdes break; 97490267Sdes } 97590267Sdes if (url != URL) 97690267Sdes fetchFreeURL(url); 97790267Sdes url = new; 97890267Sdes } while (++i < n); 97990267Sdes 98090267Sdes /* we failed, or ran out of retries */ 98190267Sdes if (fd == -1) { 98290267Sdes _http_seterr(code); 98363012Sdes goto ouch; 98463012Sdes } 98560376Sdes 98690267Sdes DEBUG(fprintf(stderr, "offset %lld, length %lld," 98790267Sdes " size %lld, clength %lld\n", 98890267Sdes (long long)offset, (long long)length, 98990267Sdes (long long)size, (long long)clength)); 99060376Sdes 99190267Sdes /* check for inconsistencies */ 99290267Sdes if (clength != -1 && length != -1 && clength != length) { 99390267Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 99463012Sdes goto ouch; 99563012Sdes } 99690267Sdes if (clength == -1) 99790267Sdes clength = length; 99890267Sdes if (clength != -1) 99990267Sdes length = offset + clength; 100090267Sdes if (length != -1 && size != -1 && length != size) { 100163012Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 100263012Sdes goto ouch; 100390267Sdes } 100490267Sdes if (size == -1) 100590267Sdes size = length; 100660376Sdes 100790267Sdes /* fill in stats */ 100890267Sdes if (us) { 100990267Sdes us->size = size; 101090267Sdes us->atime = us->mtime = mtime; 101190267Sdes } 101263069Sdes 101390267Sdes /* too far? */ 101490267Sdes if (offset > URL->offset) { 101590267Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 101690267Sdes goto ouch; 101777238Sdes } 101860376Sdes 101990267Sdes /* report back real offset and size */ 102090267Sdes URL->offset = offset; 102190267Sdes URL->length = clength; 102237535Sdes 102390267Sdes /* wrap it up in a FILE */ 102490267Sdes if ((f = chunked ? _http_funopen(fd) : fdopen(fd, "r")) == NULL) { 102590267Sdes _fetch_syserr(); 102690267Sdes goto ouch; 102790267Sdes } 102863716Sdes 102990267Sdes if (url != URL) 103090267Sdes fetchFreeURL(url); 103190267Sdes if (purl) 103290267Sdes fetchFreeURL(purl); 103363567Sdes 103490267Sdes if (HTTP_ERROR(code)) { 103590267Sdes _http_print_html(stderr, f); 103690267Sdes fclose(f); 103790267Sdes f = NULL; 103890267Sdes } 103963012Sdes 104090267Sdes return (f); 104188771Sdes 104290267Sdesouch: 104390267Sdes if (url != URL) 104490267Sdes fetchFreeURL(url); 104590267Sdes if (purl) 104690267Sdes fetchFreeURL(purl); 104790267Sdes if (fd != -1) 104890267Sdes close(fd); 104990267Sdes return (NULL); 105063012Sdes} 105160189Sdes 105290267Sdes 105363012Sdes/***************************************************************************** 105463012Sdes * Entry points 105563012Sdes */ 105663012Sdes 105763012Sdes/* 105863340Sdes * Retrieve and stat a file by HTTP 105963340Sdes */ 106063340SdesFILE * 106175891SarchiefetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags) 106263340Sdes{ 106390267Sdes return (_http_request(URL, "GET", us, _http_get_proxy(), flags)); 106463340Sdes} 106563340Sdes 106663340Sdes/* 106763012Sdes * Retrieve a file by HTTP 106863012Sdes */ 106963012SdesFILE * 107075891SarchiefetchGetHTTP(struct url *URL, const char *flags) 107163012Sdes{ 107290267Sdes return (fetchXGetHTTP(URL, NULL, flags)); 107337535Sdes} 107437535Sdes 107563340Sdes/* 107663340Sdes * Store a file by HTTP 107763340Sdes */ 107837535SdesFILE * 107985093SdesfetchPutHTTP(struct url *URL __unused, const char *flags __unused) 108037535Sdes{ 108190267Sdes warnx("fetchPutHTTP(): not implemented"); 108290267Sdes return (NULL); 108337535Sdes} 108440975Sdes 108540975Sdes/* 108640975Sdes * Get an HTTP document's metadata 108740975Sdes */ 108840975Sdesint 108975891SarchiefetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags) 109040975Sdes{ 109190267Sdes FILE *f; 109290267Sdes 109390267Sdes if ((f = _http_request(URL, "HEAD", us, _http_get_proxy(), flags)) == NULL) 109490267Sdes return (-1); 109590267Sdes fclose(f); 109690267Sdes return (0); 109740975Sdes} 109841989Sdes 109941989Sdes/* 110041989Sdes * List a directory 110141989Sdes */ 110241989Sdesstruct url_ent * 110385093SdesfetchListHTTP(struct url *url __unused, const char *flags __unused) 110441989Sdes{ 110590267Sdes warnx("fetchListHTTP(): not implemented"); 110690267Sdes return (NULL); 110741989Sdes} 1108