http.c revision 97856
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 97856 2002-06-05 10:05:03Z 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 8363012Sdes/* Maximum number of redirects to follow */ 8463012Sdes#define MAX_REDIRECT 5 8537535Sdes 8663012Sdes/* Symbolic names for reply codes we care about */ 8763012Sdes#define HTTP_OK 200 8863012Sdes#define HTTP_PARTIAL 206 8963012Sdes#define HTTP_MOVED_PERM 301 9063012Sdes#define HTTP_MOVED_TEMP 302 9163012Sdes#define HTTP_SEE_OTHER 303 9263012Sdes#define HTTP_NEED_AUTH 401 9387317Sdes#define HTTP_NEED_PROXY_AUTH 407 9463012Sdes#define HTTP_PROTOCOL_ERROR 999 9560196Sdes 9663012Sdes#define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \ 9790267Sdes || (xyz) == HTTP_MOVED_TEMP \ 9890267Sdes || (xyz) == HTTP_SEE_OTHER) 9963012Sdes 10088771Sdes#define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599) 10163012Sdes 10290267Sdes 10363012Sdes/***************************************************************************** 10463012Sdes * I/O functions for decoding chunked streams 10563012Sdes */ 10663012Sdes 10737535Sdesstruct cookie 10837535Sdes{ 10997856Sdes conn_t *conn; 11090267Sdes char *buf; 11190267Sdes size_t b_size; 11290267Sdes ssize_t b_len; 11390267Sdes int b_pos; 11490267Sdes int eof; 11590267Sdes int error; 11690267Sdes size_t chunksize; 11763281Sdes#ifndef NDEBUG 11890267Sdes size_t total; 11963012Sdes#endif 12037535Sdes}; 12137535Sdes 12237608Sdes/* 12363012Sdes * Get next chunk header 12437608Sdes */ 12537608Sdesstatic int 12663012Sdes_http_new_chunk(struct cookie *c) 12737608Sdes{ 12890267Sdes char *p; 12990267Sdes 13097856Sdes if (_fetch_getln(c->conn) == -1) 13190267Sdes return (-1); 13290267Sdes 13397856Sdes if (c->b_len < 2 || !ishexnumber(*c->conn->buf)) 13490267Sdes return (-1); 13590267Sdes 13697856Sdes for (p = c->conn->buf; *p && !isspace(*p); ++p) { 13790267Sdes if (*p == ';') 13890267Sdes break; 13990267Sdes if (!ishexnumber(*p)) 14090267Sdes return (-1); 14190267Sdes if (isdigit(*p)) { 14290267Sdes c->chunksize = c->chunksize * 16 + 14390267Sdes *p - '0'; 14490267Sdes } else { 14590267Sdes c->chunksize = c->chunksize * 16 + 14690267Sdes 10 + tolower(*p) - 'a'; 14790267Sdes } 14890267Sdes } 14990267Sdes 15063281Sdes#ifndef NDEBUG 15190267Sdes if (fetchDebug) { 15290267Sdes c->total += c->chunksize; 15390267Sdes if (c->chunksize == 0) 15490267Sdes fprintf(stderr, "_http_fillbuf(): " 15590267Sdes "end of last chunk\n"); 15690267Sdes else 15790267Sdes fprintf(stderr, "_http_fillbuf(): " 15890267Sdes "new chunk: %lu (%lu)\n", 15990267Sdes (unsigned long)c->chunksize, (unsigned long)c->total); 16090267Sdes } 16163012Sdes#endif 16290267Sdes 16390267Sdes return (c->chunksize); 16437608Sdes} 16537608Sdes 16637608Sdes/* 16737608Sdes * Fill the input buffer, do chunk decoding on the fly 16837608Sdes */ 16963012Sdesstatic int 17037535Sdes_http_fillbuf(struct cookie *c) 17137535Sdes{ 17290267Sdes if (c->error) 17390267Sdes return (-1); 17490267Sdes if (c->eof) 17590267Sdes return (0); 17690267Sdes 17790267Sdes if (c->chunksize == 0) { 17890267Sdes switch (_http_new_chunk(c)) { 17990267Sdes case -1: 18090267Sdes c->error = 1; 18190267Sdes return (-1); 18290267Sdes case 0: 18390267Sdes c->eof = 1; 18490267Sdes return (0); 18590267Sdes } 18637535Sdes } 18763012Sdes 18890267Sdes if (c->b_size < c->chunksize) { 18990267Sdes char *tmp; 19063012Sdes 19190267Sdes if ((tmp = realloc(c->buf, c->chunksize)) == NULL) 19290267Sdes return (-1); 19390267Sdes c->buf = tmp; 19490267Sdes c->b_size = c->chunksize; 19590267Sdes } 19690267Sdes 19797856Sdes if ((c->b_len = read(c->conn->sd, c->buf, c->chunksize)) == -1) 19890267Sdes return (-1); 19990267Sdes c->chunksize -= c->b_len; 20090267Sdes 20190267Sdes if (c->chunksize == 0) { 20297856Sdes char endl[2]; 20397856Sdes 20497856Sdes if (read(c->conn->sd, &endl[0], 1) == -1 || 20597856Sdes read(c->conn->sd, &endl[1], 1) == -1 || 20697856Sdes endl[0] != '\r' || endl[1] != '\n') 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 25497856Sdes return (write(c->conn->sd, 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 26697856Sdes r = _fetch_close(c->conn); 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 * 27797856Sdes_http_funopen(conn_t *conn) 27837535Sdes{ 27990267Sdes struct cookie *c; 28090267Sdes FILE *f; 28163012Sdes 28290267Sdes if ((c = calloc(1, sizeof *c)) == NULL) { 28390267Sdes _fetch_syserr(); 28490267Sdes return (NULL); 28590267Sdes } 28697856Sdes c->conn = conn; 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 32963012Sdes/* 33063012Sdes * Send a formatted line; optionally echo to terminal 33163012Sdes */ 33263012Sdesstatic int 33397856Sdes_http_cmd(conn_t *conn, const char *fmt, ...) 33463012Sdes{ 33590267Sdes va_list ap; 33690267Sdes size_t len; 33790267Sdes char *msg; 33890267Sdes int r; 33963012Sdes 34090267Sdes va_start(ap, fmt); 34190267Sdes len = vasprintf(&msg, fmt, ap); 34290267Sdes va_end(ap); 34390267Sdes 34490267Sdes if (msg == NULL) { 34590267Sdes errno = ENOMEM; 34690267Sdes _fetch_syserr(); 34790267Sdes return (-1); 34890267Sdes } 34990267Sdes 35097856Sdes r = _fetch_putln(conn, msg, len); 35190267Sdes free(msg); 35290267Sdes 35390267Sdes if (r == -1) { 35490267Sdes _fetch_syserr(); 35590267Sdes return (-1); 35690267Sdes } 35790267Sdes 35890267Sdes return (0); 35963012Sdes} 36063012Sdes 36163012Sdes/* 36263012Sdes * Get and parse status line 36363012Sdes */ 36463012Sdesstatic int 36597856Sdes_http_get_reply(conn_t *conn) 36663012Sdes{ 36790267Sdes char *p; 36890267Sdes 36997856Sdes if (_fetch_getln(conn) == -1) 37090267Sdes return (-1); 37190267Sdes /* 37290267Sdes * A valid status line looks like "HTTP/m.n xyz reason" where m 37390267Sdes * and n are the major and minor protocol version numbers and xyz 37490267Sdes * is the reply code. 37590267Sdes * Unfortunately, there are servers out there (NCSA 1.5.1, to name 37690267Sdes * just one) that do not send a version number, so we can't rely 37790267Sdes * on finding one, but if we do, insist on it being 1.0 or 1.1. 37890267Sdes * We don't care about the reason phrase. 37990267Sdes */ 38097856Sdes if (strncmp(conn->buf, "HTTP", 4) != 0) 38190267Sdes return (HTTP_PROTOCOL_ERROR); 38297856Sdes p = conn->buf + 4; 38390267Sdes if (*p == '/') { 38490267Sdes if (p[1] != '1' || p[2] != '.' || (p[3] != '0' && p[3] != '1')) 38590267Sdes return (HTTP_PROTOCOL_ERROR); 38690267Sdes p += 4; 38790267Sdes } 38890267Sdes if (*p != ' ' || !isdigit(p[1]) || !isdigit(p[2]) || !isdigit(p[3])) 38990267Sdes return (HTTP_PROTOCOL_ERROR); 39090267Sdes 39197856Sdes conn->err = (p[1] - '0') * 100 + (p[2] - '0') * 10 + (p[3] - '0'); 39297856Sdes return (conn->err); 39337535Sdes} 39437535Sdes 39537608Sdes/* 39690267Sdes * Check a header; if the type matches the given string, return a pointer 39790267Sdes * to the beginning of the value. 39863012Sdes */ 39975891Sarchiestatic const char * 40075891Sarchie_http_match(const char *str, const char *hdr) 40163012Sdes{ 40290267Sdes while (*str && *hdr && tolower(*str++) == tolower(*hdr++)) 40390267Sdes /* nothing */; 40490267Sdes if (*str || *hdr != ':') 40590267Sdes return (NULL); 40690267Sdes while (*hdr && isspace(*++hdr)) 40790267Sdes /* nothing */; 40890267Sdes return (hdr); 40963012Sdes} 41063012Sdes 41163012Sdes/* 41263012Sdes * Get the next header and return the appropriate symbolic code. 41363012Sdes */ 41485093Sdesstatic hdr_t 41597856Sdes_http_next_header(conn_t *conn, const char **p) 41663012Sdes{ 41790267Sdes int i; 41890267Sdes 41997856Sdes if (_fetch_getln(conn) == -1) 42090267Sdes return (hdr_syserror); 42197856Sdes while (conn->buflen && isspace(conn->buf[conn->buflen - 1])) 42297856Sdes conn->buflen--; 42397856Sdes conn->buf[conn->buflen] = '\0'; 42497856Sdes if (conn->buflen == 0) 42597856Sdes return (hdr_end); 42690267Sdes /* 42790267Sdes * We could check for malformed headers but we don't really care. 42890267Sdes * A valid header starts with a token immediately followed by a 42990267Sdes * colon; a token is any sequence of non-control, non-whitespace 43090267Sdes * characters except "()<>@,;:\\\"{}". 43190267Sdes */ 43290267Sdes for (i = 0; hdr_names[i].num != hdr_unknown; i++) 43397856Sdes if ((*p = _http_match(hdr_names[i].name, conn->buf)) != NULL) 43490267Sdes return (hdr_names[i].num); 43590267Sdes return (hdr_unknown); 43663012Sdes} 43763012Sdes 43863012Sdes/* 43963012Sdes * Parse a last-modified header 44063012Sdes */ 44163716Sdesstatic int 44275891Sarchie_http_parse_mtime(const char *p, time_t *mtime) 44363012Sdes{ 44490267Sdes char locale[64], *r; 44590267Sdes struct tm tm; 44663012Sdes 44790267Sdes strncpy(locale, setlocale(LC_TIME, NULL), sizeof locale); 44890267Sdes setlocale(LC_TIME, "C"); 44990267Sdes r = strptime(p, "%a, %d %b %Y %H:%M:%S GMT", &tm); 45090267Sdes /* XXX should add support for date-2 and date-3 */ 45190267Sdes setlocale(LC_TIME, locale); 45290267Sdes if (r == NULL) 45390267Sdes return (-1); 45490267Sdes DEBUG(fprintf(stderr, "last modified: [%04d-%02d-%02d " 45588769Sdes "%02d:%02d:%02d]\n", 45663012Sdes tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, 45763012Sdes tm.tm_hour, tm.tm_min, tm.tm_sec)); 45890267Sdes *mtime = timegm(&tm); 45990267Sdes return (0); 46063012Sdes} 46163012Sdes 46263012Sdes/* 46363012Sdes * Parse a content-length header 46463012Sdes */ 46563716Sdesstatic int 46675891Sarchie_http_parse_length(const char *p, off_t *length) 46763012Sdes{ 46890267Sdes off_t len; 46990267Sdes 47090267Sdes for (len = 0; *p && isdigit(*p); ++p) 47190267Sdes len = len * 10 + (*p - '0'); 47290267Sdes if (*p) 47390267Sdes return (-1); 47490267Sdes DEBUG(fprintf(stderr, "content length: [%lld]\n", 47590267Sdes (long long)len)); 47690267Sdes *length = len; 47790267Sdes return (0); 47863012Sdes} 47963012Sdes 48063012Sdes/* 48163012Sdes * Parse a content-range header 48263012Sdes */ 48363716Sdesstatic int 48475891Sarchie_http_parse_range(const char *p, off_t *offset, off_t *length, off_t *size) 48563012Sdes{ 48690267Sdes off_t first, last, len; 48763716Sdes 48890267Sdes if (strncasecmp(p, "bytes ", 6) != 0) 48990267Sdes return (-1); 49090267Sdes for (first = 0, p += 6; *p && isdigit(*p); ++p) 49190267Sdes first = first * 10 + *p - '0'; 49290267Sdes if (*p != '-') 49390267Sdes return (-1); 49490267Sdes for (last = 0, ++p; *p && isdigit(*p); ++p) 49590267Sdes last = last * 10 + *p - '0'; 49690267Sdes if (first > last || *p != '/') 49790267Sdes return (-1); 49890267Sdes for (len = 0, ++p; *p && isdigit(*p); ++p) 49990267Sdes len = len * 10 + *p - '0'; 50090267Sdes if (*p || len < last - first + 1) 50190267Sdes return (-1); 50290267Sdes DEBUG(fprintf(stderr, "content range: [%lld-%lld/%lld]\n", 50390267Sdes (long long)first, (long long)last, (long long)len)); 50490267Sdes *offset = first; 50590267Sdes *length = last - first + 1; 50690267Sdes *size = len; 50790267Sdes return (0); 50863012Sdes} 50963012Sdes 51090267Sdes 51163012Sdes/***************************************************************************** 51263012Sdes * Helper functions for authorization 51363012Sdes */ 51463012Sdes 51563012Sdes/* 51637608Sdes * Base64 encoding 51737608Sdes */ 51862965Sdesstatic char * 51990267Sdes_http_base64(const char *src) 52037608Sdes{ 52190267Sdes static const char base64[] = 52290267Sdes "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 52390267Sdes "abcdefghijklmnopqrstuvwxyz" 52490267Sdes "0123456789+/"; 52590267Sdes char *str, *dst; 52690267Sdes size_t l; 52790267Sdes int t, r; 52862965Sdes 52990267Sdes l = strlen(src); 53090267Sdes if ((str = malloc(((l + 2) / 3) * 4)) == NULL) 53190267Sdes return (NULL); 53290267Sdes dst = str; 53390267Sdes r = 0; 53437608Sdes 53590267Sdes while (l >= 3) { 53690267Sdes t = (src[0] << 16) | (src[1] << 8) | src[2]; 53790267Sdes dst[0] = base64[(t >> 18) & 0x3f]; 53890267Sdes dst[1] = base64[(t >> 12) & 0x3f]; 53990267Sdes dst[2] = base64[(t >> 6) & 0x3f]; 54090267Sdes dst[3] = base64[(t >> 0) & 0x3f]; 54190267Sdes src += 3; l -= 3; 54290267Sdes dst += 4; r += 4; 54390267Sdes } 54437608Sdes 54590267Sdes switch (l) { 54690267Sdes case 2: 54790267Sdes t = (src[0] << 16) | (src[1] << 8); 54890267Sdes dst[0] = base64[(t >> 18) & 0x3f]; 54990267Sdes dst[1] = base64[(t >> 12) & 0x3f]; 55090267Sdes dst[2] = base64[(t >> 6) & 0x3f]; 55190267Sdes dst[3] = '='; 55290267Sdes dst += 4; 55390267Sdes r += 4; 55490267Sdes break; 55590267Sdes case 1: 55690267Sdes t = src[0] << 16; 55790267Sdes dst[0] = base64[(t >> 18) & 0x3f]; 55890267Sdes dst[1] = base64[(t >> 12) & 0x3f]; 55990267Sdes dst[2] = dst[3] = '='; 56090267Sdes dst += 4; 56190267Sdes r += 4; 56290267Sdes break; 56390267Sdes case 0: 56490267Sdes break; 56590267Sdes } 56690267Sdes 56790267Sdes *dst = 0; 56890267Sdes return (str); 56937608Sdes} 57037608Sdes 57137608Sdes/* 57237608Sdes * Encode username and password 57337608Sdes */ 57462965Sdesstatic int 57597856Sdes_http_basic_auth(conn_t *conn, const char *hdr, const char *usr, const char *pwd) 57637608Sdes{ 57790267Sdes char *upw, *auth; 57890267Sdes int r; 57937608Sdes 58090267Sdes DEBUG(fprintf(stderr, "usr: [%s]\n", usr)); 58190267Sdes DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd)); 58290267Sdes if (asprintf(&upw, "%s:%s", usr, pwd) == -1) 58390267Sdes return (-1); 58490267Sdes auth = _http_base64(upw); 58590267Sdes free(upw); 58690267Sdes if (auth == NULL) 58790267Sdes return (-1); 58897856Sdes r = _http_cmd(conn, "%s: Basic %s", hdr, auth); 58990267Sdes free(auth); 59090267Sdes return (r); 59162965Sdes} 59262965Sdes 59362965Sdes/* 59462965Sdes * Send an authorization header 59562965Sdes */ 59662965Sdesstatic int 59797856Sdes_http_authorize(conn_t *conn, const char *hdr, const char *p) 59862965Sdes{ 59990267Sdes /* basic authorization */ 60090267Sdes if (strncasecmp(p, "basic:", 6) == 0) { 60190267Sdes char *user, *pwd, *str; 60290267Sdes int r; 60362965Sdes 60490267Sdes /* skip realm */ 60590267Sdes for (p += 6; *p && *p != ':'; ++p) 60690267Sdes /* nothing */ ; 60790267Sdes if (!*p || strchr(++p, ':') == NULL) 60890267Sdes return (-1); 60990267Sdes if ((str = strdup(p)) == NULL) 61090267Sdes return (-1); /* XXX */ 61190267Sdes user = str; 61290267Sdes pwd = strchr(str, ':'); 61390267Sdes *pwd++ = '\0'; 61497856Sdes r = _http_basic_auth(conn, hdr, user, pwd); 61590267Sdes free(str); 61690267Sdes return (r); 61790267Sdes } 61890267Sdes return (-1); 61937608Sdes} 62037608Sdes 62190267Sdes 62263012Sdes/***************************************************************************** 62363012Sdes * Helper functions for connecting to a server or proxy 62463012Sdes */ 62563012Sdes 62637608Sdes/* 62790267Sdes * Connect to the correct HTTP server or proxy. 62863012Sdes */ 62997856Sdesstatic conn_t * 63075891Sarchie_http_connect(struct url *URL, struct url *purl, const char *flags) 63163012Sdes{ 63297856Sdes conn_t *conn; 63390267Sdes int verbose; 63497856Sdes int af; 63590267Sdes 63663012Sdes#ifdef INET6 63790267Sdes af = AF_UNSPEC; 63860737Sume#else 63990267Sdes af = AF_INET; 64060737Sume#endif 64190267Sdes 64290267Sdes verbose = CHECK_FLAG('v'); 64390267Sdes if (CHECK_FLAG('4')) 64490267Sdes af = AF_INET; 64567043Sdes#ifdef INET6 64690267Sdes else if (CHECK_FLAG('6')) 64790267Sdes af = AF_INET6; 64867043Sdes#endif 64967043Sdes 65090267Sdes if (purl) { 65190267Sdes URL = purl; 65290267Sdes } else if (strcasecmp(URL->scheme, SCHEME_FTP) == 0) { 65390267Sdes /* can't talk http to an ftp server */ 65490267Sdes /* XXX should set an error code */ 65597856Sdes return (NULL); 65690267Sdes } 65790267Sdes 65897856Sdes if ((conn = _fetch_connect(URL->host, URL->port, af, verbose)) == NULL) 65990267Sdes /* _fetch_connect() has already set an error code */ 66097856Sdes return (NULL); 66197856Sdes return (conn); 66267043Sdes} 66367043Sdes 66467043Sdesstatic struct url * 66575891Sarchie_http_get_proxy(void) 66667043Sdes{ 66790267Sdes struct url *purl; 66890267Sdes char *p; 66990267Sdes 67090267Sdes if (((p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) && 67190267Sdes (purl = fetchParseURL(p))) { 67290267Sdes if (!*purl->scheme) 67390267Sdes strcpy(purl->scheme, SCHEME_HTTP); 67490267Sdes if (!purl->port) 67590267Sdes purl->port = _fetch_default_proxy_port(purl->scheme); 67690267Sdes if (strcasecmp(purl->scheme, SCHEME_HTTP) == 0) 67790267Sdes return (purl); 67890267Sdes fetchFreeURL(purl); 67990267Sdes } 68090267Sdes return (NULL); 68160376Sdes} 68260376Sdes 68388771Sdesstatic void 68488771Sdes_http_print_html(FILE *out, FILE *in) 68588771Sdes{ 68690267Sdes size_t len; 68790267Sdes char *line, *p, *q; 68890267Sdes int comment, tag; 68988771Sdes 69090267Sdes comment = tag = 0; 69190267Sdes while ((line = fgetln(in, &len)) != NULL) { 69290267Sdes while (len && isspace(line[len - 1])) 69390267Sdes --len; 69490267Sdes for (p = q = line; q < line + len; ++q) { 69590267Sdes if (comment && *q == '-') { 69690267Sdes if (q + 2 < line + len && 69790267Sdes strcmp(q, "-->") == 0) { 69890267Sdes tag = comment = 0; 69990267Sdes q += 2; 70090267Sdes } 70190267Sdes } else if (tag && !comment && *q == '>') { 70290267Sdes p = q + 1; 70390267Sdes tag = 0; 70490267Sdes } else if (!tag && *q == '<') { 70590267Sdes if (q > p) 70690267Sdes fwrite(p, q - p, 1, out); 70790267Sdes tag = 1; 70890267Sdes if (q + 3 < line + len && 70990267Sdes strcmp(q, "<!--") == 0) { 71090267Sdes comment = 1; 71190267Sdes q += 3; 71290267Sdes } 71390267Sdes } 71488771Sdes } 71590267Sdes if (!tag && q > p) 71690267Sdes fwrite(p, q - p, 1, out); 71790267Sdes fputc('\n', out); 71888771Sdes } 71988771Sdes} 72088771Sdes 72190267Sdes 72263012Sdes/***************************************************************************** 72363012Sdes * Core 72460954Sdes */ 72560954Sdes 72660954Sdes/* 72763012Sdes * Send a request and process the reply 72860376Sdes */ 72967043SdesFILE * 73075891Sarchie_http_request(struct url *URL, const char *op, struct url_stat *us, 73190267Sdes struct url *purl, const char *flags) 73260376Sdes{ 73397856Sdes conn_t *conn; 73490267Sdes struct url *url, *new; 73590267Sdes int chunked, direct, need_auth, noredirect, verbose; 73697856Sdes int i, n; 73790267Sdes off_t offset, clength, length, size; 73890267Sdes time_t mtime; 73990267Sdes const char *p; 74090267Sdes FILE *f; 74190267Sdes hdr_t h; 74290267Sdes char *host; 74360737Sume#ifdef INET6 74490267Sdes char hbuf[MAXHOSTNAMELEN + 1]; 74560737Sume#endif 74663012Sdes 74790267Sdes direct = CHECK_FLAG('d'); 74890267Sdes noredirect = CHECK_FLAG('A'); 74990267Sdes verbose = CHECK_FLAG('v'); 75060737Sume 75190267Sdes if (direct && purl) { 75290267Sdes fetchFreeURL(purl); 75390267Sdes purl = NULL; 75490267Sdes } 75563716Sdes 75690267Sdes /* try the provided URL first */ 75790267Sdes url = URL; 75863012Sdes 75990267Sdes /* if the A flag is set, we only get one try */ 76090267Sdes n = noredirect ? 1 : MAX_REDIRECT; 76190267Sdes i = 0; 76263012Sdes 76390267Sdes need_auth = 0; 76490267Sdes do { 76590267Sdes new = NULL; 76690267Sdes chunked = 0; 76790267Sdes offset = 0; 76890267Sdes clength = -1; 76990267Sdes length = -1; 77090267Sdes size = -1; 77190267Sdes mtime = 0; 77290267Sdes 77390267Sdes /* check port */ 77490267Sdes if (!url->port) 77590267Sdes url->port = _fetch_default_port(url->scheme); 77690267Sdes 77790267Sdes /* were we redirected to an FTP URL? */ 77890267Sdes if (purl == NULL && strcmp(url->scheme, SCHEME_FTP) == 0) { 77990267Sdes if (strcmp(op, "GET") == 0) 78090267Sdes return (_ftp_request(url, "RETR", us, purl, flags)); 78190267Sdes else if (strcmp(op, "HEAD") == 0) 78290267Sdes return (_ftp_request(url, "STAT", us, purl, flags)); 78390267Sdes } 78490267Sdes 78590267Sdes /* connect to server or proxy */ 78697856Sdes if ((conn = _http_connect(url, purl, flags)) == NULL) 78790267Sdes goto ouch; 78890267Sdes 78990267Sdes host = url->host; 79060737Sume#ifdef INET6 79190267Sdes if (strchr(url->host, ':')) { 79290267Sdes snprintf(hbuf, sizeof(hbuf), "[%s]", url->host); 79390267Sdes host = hbuf; 79490267Sdes } 79560737Sume#endif 79637535Sdes 79790267Sdes /* send request */ 79890267Sdes if (verbose) 79990267Sdes _fetch_info("requesting %s://%s:%d%s", 80090267Sdes url->scheme, host, url->port, url->doc); 80190267Sdes if (purl) { 80297856Sdes _http_cmd(conn, "%s %s://%s:%d%s HTTP/1.1", 80390267Sdes op, url->scheme, host, url->port, url->doc); 80490267Sdes } else { 80597856Sdes _http_cmd(conn, "%s %s HTTP/1.1", 80690267Sdes op, url->doc); 80790267Sdes } 80837535Sdes 80990267Sdes /* virtual host */ 81090267Sdes if (url->port == _fetch_default_port(url->scheme)) 81197856Sdes _http_cmd(conn, "Host: %s", host); 81290267Sdes else 81397856Sdes _http_cmd(conn, "Host: %s:%d", host, url->port); 81490267Sdes 81590267Sdes /* proxy authorization */ 81690267Sdes if (purl) { 81790267Sdes if (*purl->user || *purl->pwd) 81897856Sdes _http_basic_auth(conn, "Proxy-Authorization", 81990267Sdes purl->user, purl->pwd); 82090267Sdes else if ((p = getenv("HTTP_PROXY_AUTH")) != NULL && *p != '\0') 82197856Sdes _http_authorize(conn, "Proxy-Authorization", p); 82290267Sdes } 82390267Sdes 82490267Sdes /* server authorization */ 82590267Sdes if (need_auth || *url->user || *url->pwd) { 82690267Sdes if (*url->user || *url->pwd) 82797856Sdes _http_basic_auth(conn, "Authorization", url->user, url->pwd); 82890267Sdes else if ((p = getenv("HTTP_AUTH")) != NULL && *p != '\0') 82997856Sdes _http_authorize(conn, "Authorization", p); 83090267Sdes else if (fetchAuthMethod && fetchAuthMethod(url) == 0) { 83197856Sdes _http_basic_auth(conn, "Authorization", url->user, url->pwd); 83290267Sdes } else { 83390267Sdes _http_seterr(HTTP_NEED_AUTH); 83490267Sdes goto ouch; 83590267Sdes } 83690267Sdes } 83790267Sdes 83890267Sdes /* other headers */ 83990267Sdes if ((p = getenv("HTTP_USER_AGENT")) != NULL && *p != '\0') 84097856Sdes _http_cmd(conn, "User-Agent: %s", p); 84190267Sdes else 84297856Sdes _http_cmd(conn, "User-Agent: %s " _LIBFETCH_VER, getprogname()); 84390267Sdes if (url->offset) 84497856Sdes _http_cmd(conn, "Range: bytes=%lld-", (long long)url->offset); 84597856Sdes _http_cmd(conn, "Connection: close"); 84697856Sdes _http_cmd(conn, ""); 84790267Sdes 84890267Sdes /* get reply */ 84997856Sdes switch (_http_get_reply(conn)) { 85090267Sdes case HTTP_OK: 85190267Sdes case HTTP_PARTIAL: 85290267Sdes /* fine */ 85390267Sdes break; 85490267Sdes case HTTP_MOVED_PERM: 85590267Sdes case HTTP_MOVED_TEMP: 85690267Sdes case HTTP_SEE_OTHER: 85790267Sdes /* 85890267Sdes * Not so fine, but we still have to read the headers to 85990267Sdes * get the new location. 86090267Sdes */ 86190267Sdes break; 86290267Sdes case HTTP_NEED_AUTH: 86390267Sdes if (need_auth) { 86490267Sdes /* 86590267Sdes * We already sent out authorization code, so there's 86690267Sdes * nothing more we can do. 86790267Sdes */ 86897856Sdes _http_seterr(conn->err); 86990267Sdes goto ouch; 87090267Sdes } 87190267Sdes /* try again, but send the password this time */ 87290267Sdes if (verbose) 87390267Sdes _fetch_info("server requires authorization"); 87490267Sdes break; 87590267Sdes case HTTP_NEED_PROXY_AUTH: 87690267Sdes /* 87790267Sdes * If we're talking to a proxy, we already sent our proxy 87890267Sdes * authorization code, so there's nothing more we can do. 87990267Sdes */ 88097856Sdes _http_seterr(conn->err); 88190267Sdes goto ouch; 88290267Sdes case HTTP_PROTOCOL_ERROR: 88390267Sdes /* fall through */ 88490267Sdes case -1: 88590267Sdes _fetch_syserr(); 88690267Sdes goto ouch; 88790267Sdes default: 88897856Sdes _http_seterr(conn->err); 88990267Sdes if (!verbose) 89090267Sdes goto ouch; 89190267Sdes /* fall through so we can get the full error message */ 89290267Sdes } 89390267Sdes 89490267Sdes /* get headers */ 89590267Sdes do { 89697856Sdes switch ((h = _http_next_header(conn, &p))) { 89790267Sdes case hdr_syserror: 89890267Sdes _fetch_syserr(); 89990267Sdes goto ouch; 90090267Sdes case hdr_error: 90190267Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 90290267Sdes goto ouch; 90390267Sdes case hdr_content_length: 90490267Sdes _http_parse_length(p, &clength); 90590267Sdes break; 90690267Sdes case hdr_content_range: 90790267Sdes _http_parse_range(p, &offset, &length, &size); 90890267Sdes break; 90990267Sdes case hdr_last_modified: 91090267Sdes _http_parse_mtime(p, &mtime); 91190267Sdes break; 91290267Sdes case hdr_location: 91397856Sdes if (!HTTP_REDIRECT(conn->err)) 91490267Sdes break; 91590267Sdes if (new) 91690267Sdes free(new); 91790267Sdes if (verbose) 91897856Sdes _fetch_info("%d redirect to %s", conn->err, p); 91990267Sdes if (*p == '/') 92090267Sdes /* absolute path */ 92190267Sdes new = fetchMakeURL(url->scheme, url->host, url->port, p, 92290267Sdes url->user, url->pwd); 92390267Sdes else 92490267Sdes new = fetchParseURL(p); 92590267Sdes if (new == NULL) { 92690267Sdes /* XXX should set an error code */ 92790267Sdes DEBUG(fprintf(stderr, "failed to parse new URL\n")); 92890267Sdes goto ouch; 92990267Sdes } 93090267Sdes if (!*new->user && !*new->pwd) { 93190267Sdes strcpy(new->user, url->user); 93290267Sdes strcpy(new->pwd, url->pwd); 93390267Sdes } 93490267Sdes new->offset = url->offset; 93590267Sdes new->length = url->length; 93690267Sdes break; 93790267Sdes case hdr_transfer_encoding: 93890267Sdes /* XXX weak test*/ 93990267Sdes chunked = (strcasecmp(p, "chunked") == 0); 94090267Sdes break; 94190267Sdes case hdr_www_authenticate: 94297856Sdes if (conn->err != HTTP_NEED_AUTH) 94390267Sdes break; 94490267Sdes /* if we were smarter, we'd check the method and realm */ 94590267Sdes break; 94690267Sdes case hdr_end: 94790267Sdes /* fall through */ 94890267Sdes case hdr_unknown: 94990267Sdes /* ignore */ 95090267Sdes break; 95190267Sdes } 95290267Sdes } while (h > hdr_end); 95390267Sdes 95490267Sdes /* we have a hit or an error */ 95597856Sdes if (conn->err == HTTP_OK || conn->err == HTTP_PARTIAL || HTTP_ERROR(conn->err)) 95690267Sdes break; 95790267Sdes 95890267Sdes /* we need to provide authentication */ 95997856Sdes if (conn->err == HTTP_NEED_AUTH) { 96090267Sdes need_auth = 1; 96197856Sdes _fetch_close(conn); 96297856Sdes conn = NULL; 96390267Sdes continue; 96490267Sdes } 96590267Sdes 96690267Sdes /* all other cases: we got a redirect */ 96790267Sdes need_auth = 0; 96897856Sdes _fetch_close(conn); 96997856Sdes conn = NULL; 97090267Sdes if (!new) { 97190267Sdes DEBUG(fprintf(stderr, "redirect with no new location\n")); 97290267Sdes break; 97390267Sdes } 97490267Sdes if (url != URL) 97590267Sdes fetchFreeURL(url); 97690267Sdes url = new; 97790267Sdes } while (++i < n); 97890267Sdes 97990267Sdes /* we failed, or ran out of retries */ 98097856Sdes if (conn == NULL) { 98197856Sdes _http_seterr(conn->err); 98263012Sdes goto ouch; 98363012Sdes } 98460376Sdes 98590267Sdes DEBUG(fprintf(stderr, "offset %lld, length %lld," 98690267Sdes " size %lld, clength %lld\n", 98790267Sdes (long long)offset, (long long)length, 98890267Sdes (long long)size, (long long)clength)); 98960376Sdes 99090267Sdes /* check for inconsistencies */ 99190267Sdes if (clength != -1 && length != -1 && clength != length) { 99290267Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 99363012Sdes goto ouch; 99463012Sdes } 99590267Sdes if (clength == -1) 99690267Sdes clength = length; 99790267Sdes if (clength != -1) 99890267Sdes length = offset + clength; 99990267Sdes if (length != -1 && size != -1 && length != size) { 100063012Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 100163012Sdes goto ouch; 100290267Sdes } 100390267Sdes if (size == -1) 100490267Sdes size = length; 100560376Sdes 100690267Sdes /* fill in stats */ 100790267Sdes if (us) { 100890267Sdes us->size = size; 100990267Sdes us->atime = us->mtime = mtime; 101090267Sdes } 101163069Sdes 101290267Sdes /* too far? */ 101390267Sdes if (offset > URL->offset) { 101490267Sdes _http_seterr(HTTP_PROTOCOL_ERROR); 101590267Sdes goto ouch; 101677238Sdes } 101760376Sdes 101890267Sdes /* report back real offset and size */ 101990267Sdes URL->offset = offset; 102090267Sdes URL->length = clength; 102137535Sdes 102290267Sdes /* wrap it up in a FILE */ 102397856Sdes if (chunked) { 102497856Sdes f = _http_funopen(conn); 102597856Sdes } else { 102697856Sdes f = fdopen(dup(conn->sd), "r"); 102797856Sdes _fetch_close(conn); 102897856Sdes } 102997856Sdes if (f == NULL) { 103090267Sdes _fetch_syserr(); 103190267Sdes goto ouch; 103290267Sdes } 103363716Sdes 103490267Sdes if (url != URL) 103590267Sdes fetchFreeURL(url); 103690267Sdes if (purl) 103790267Sdes fetchFreeURL(purl); 103863567Sdes 103997856Sdes if (HTTP_ERROR(conn->err)) { 104090267Sdes _http_print_html(stderr, f); 104190267Sdes fclose(f); 104290267Sdes f = NULL; 104390267Sdes } 104463012Sdes 104590267Sdes return (f); 104688771Sdes 104790267Sdesouch: 104890267Sdes if (url != URL) 104990267Sdes fetchFreeURL(url); 105090267Sdes if (purl) 105190267Sdes fetchFreeURL(purl); 105297856Sdes if (conn != NULL) 105397856Sdes _fetch_close(conn); 105490267Sdes return (NULL); 105563012Sdes} 105660189Sdes 105790267Sdes 105863012Sdes/***************************************************************************** 105963012Sdes * Entry points 106063012Sdes */ 106163012Sdes 106263012Sdes/* 106363340Sdes * Retrieve and stat a file by HTTP 106463340Sdes */ 106563340SdesFILE * 106675891SarchiefetchXGetHTTP(struct url *URL, struct url_stat *us, const char *flags) 106763340Sdes{ 106890267Sdes return (_http_request(URL, "GET", us, _http_get_proxy(), flags)); 106963340Sdes} 107063340Sdes 107163340Sdes/* 107263012Sdes * Retrieve a file by HTTP 107363012Sdes */ 107463012SdesFILE * 107575891SarchiefetchGetHTTP(struct url *URL, const char *flags) 107663012Sdes{ 107790267Sdes return (fetchXGetHTTP(URL, NULL, flags)); 107837535Sdes} 107937535Sdes 108063340Sdes/* 108163340Sdes * Store a file by HTTP 108263340Sdes */ 108337535SdesFILE * 108485093SdesfetchPutHTTP(struct url *URL __unused, const char *flags __unused) 108537535Sdes{ 108690267Sdes warnx("fetchPutHTTP(): not implemented"); 108790267Sdes return (NULL); 108837535Sdes} 108940975Sdes 109040975Sdes/* 109140975Sdes * Get an HTTP document's metadata 109240975Sdes */ 109340975Sdesint 109475891SarchiefetchStatHTTP(struct url *URL, struct url_stat *us, const char *flags) 109540975Sdes{ 109690267Sdes FILE *f; 109790267Sdes 109890267Sdes if ((f = _http_request(URL, "HEAD", us, _http_get_proxy(), flags)) == NULL) 109990267Sdes return (-1); 110090267Sdes fclose(f); 110190267Sdes return (0); 110240975Sdes} 110341989Sdes 110441989Sdes/* 110541989Sdes * List a directory 110641989Sdes */ 110741989Sdesstruct url_ent * 110885093SdesfetchListHTTP(struct url *url __unused, const char *flags __unused) 110941989Sdes{ 111090267Sdes warnx("fetchListHTTP(): not implemented"); 111190267Sdes return (NULL); 111241989Sdes} 1113