1 /* $NetBSD: http.c,v 1.29 2010/01/24 19:10:35 joerg Exp $ */
3 * Copyright (c) 2000-2004 Dag-Erling Coïdan Smørgrav
4 * Copyright (c) 2003 Thomas Klausner <wiz@NetBSD.org>
5 * Copyright (c) 2008, 2009 Joerg Sonnenberger <joerg@NetBSD.org>
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer
13 * in this position and unchanged.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. The name of the author may not be used to endorse or promote products
18 * derived from this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 * $FreeBSD: http.c,v 1.83 2008/02/06 11:39:55 des Exp $
35 * The following copyright applies to the base64 code:
38 * Copyright 1997 Massachusetts Institute of Technology
40 * Permission to use, copy, modify, and distribute this software and
41 * its documentation for any purpose and without fee is hereby
42 * granted, provided that both the above copyright notice and this
43 * permission notice appear in all copies, that both the above
44 * copyright notice and this permission notice appear in all
45 * supporting documentation, and that the name of M.I.T. not be used
46 * in advertising or publicity pertaining to distribution of the
47 * software without specific, written prior permission. M.I.T. makes
48 * no representations about the suitability of this software for any
49 * purpose. It is provided "as is" without express or implied
52 * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS
53 * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
54 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
55 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
56 * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
57 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
58 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
59 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
60 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
61 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
62 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 #if defined(__linux__) || defined(__MINT__)
67 /* Keep this down to Linux or MiNT, it can create surprises elsewhere. */
71 /* Needed for gmtime_r on Interix */
77 #if !defined(NETBSD) && !defined(__minix)
81 #include <sys/types.h>
82 #include <sys/socket.h>
88 #if !defined(NETBSD) && !defined(__minix)
89 #include <nbcompat/stdio.h>
98 #include <netinet/in.h>
99 #include <netinet/tcp.h>
101 #if !defined(NETBSD) && !defined(__minix)
102 #include <nbcompat/netdb.h>
107 #include <arpa/inet.h>
112 /* Maximum number of redirects to follow */
113 #define MAX_REDIRECT 5
115 /* Symbolic names for reply codes we care about */
117 #define HTTP_PARTIAL 206
118 #define HTTP_MOVED_PERM 301
119 #define HTTP_MOVED_TEMP 302
120 #define HTTP_SEE_OTHER 303
121 #define HTTP_NOT_MODIFIED 304
122 #define HTTP_TEMP_REDIRECT 307
123 #define HTTP_NEED_AUTH 401
124 #define HTTP_NEED_PROXY_AUTH 407
125 #define HTTP_BAD_RANGE 416
126 #define HTTP_PROTOCOL_ERROR 999
128 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
129 || (xyz) == HTTP_MOVED_TEMP \
130 || (xyz) == HTTP_TEMP_REDIRECT \
131 || (xyz) == HTTP_SEE_OTHER)
133 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
135 #define MINBUFSIZE 4096
137 /*****************************************************************************
138 * I/O functions for decoding chunked streams
143 conn_t
*conn
; /* connection */
144 int chunked
; /* chunked mode */
145 int keep_alive
; /* keep-alive mode */
146 char *buf
; /* chunk buffer */
147 size_t bufsize
; /* size of chunk buffer */
148 ssize_t buflen
; /* amount of data currently in buffer */
149 int bufpos
; /* current read offset in buffer */
150 int eof
; /* end-of-file flag */
151 int error
; /* error flag */
152 size_t chunksize
; /* remaining size of current chunk */
153 off_t contentlength
; /* remaining size of the content */
157 * Get next chunk header
160 http_new_chunk(struct httpio
*io
)
164 if (fetch_getln(io
->conn
) == -1)
167 if (io
->conn
->buflen
< 2 || !isxdigit((unsigned char)*io
->conn
->buf
))
170 for (p
= io
->conn
->buf
; *p
&& !isspace((unsigned char)*p
); ++p
) {
173 if (!isxdigit((unsigned char)*p
))
175 if (isdigit((unsigned char)*p
)) {
176 io
->chunksize
= io
->chunksize
* 16 +
179 io
->chunksize
= io
->chunksize
* 16 +
180 10 + tolower((unsigned char)*p
) - 'a';
184 return (io
->chunksize
);
188 * Grow the input buffer to at least len bytes
191 http_growbuf(struct httpio
*io
, size_t len
)
195 if (io
->bufsize
>= len
)
198 if ((tmp
= realloc(io
->buf
, len
)) == NULL
)
206 * Fill the input buffer, do chunk decoding on the fly
209 http_fillbuf(struct httpio
*io
, size_t len
)
216 if (io
->contentlength
>= 0 && (off_t
)len
> io
->contentlength
)
217 len
= io
->contentlength
;
219 if (io
->chunked
== 0) {
220 if (http_growbuf(io
, len
) == -1)
222 if ((io
->buflen
= fetch_read(io
->conn
, io
->buf
, len
)) == -1) {
226 if (io
->contentlength
)
227 io
->contentlength
-= io
->buflen
;
232 if (io
->chunksize
== 0) {
233 switch (http_new_chunk(io
)) {
239 if (fetch_getln(io
->conn
) == -1)
245 if (len
> io
->chunksize
)
247 if (http_growbuf(io
, len
) == -1)
249 if ((io
->buflen
= fetch_read(io
->conn
, io
->buf
, len
)) == -1) {
253 io
->chunksize
-= io
->buflen
;
254 if (io
->contentlength
>= 0)
255 io
->contentlength
-= io
->buflen
;
257 if (io
->chunksize
== 0) {
261 len2
= fetch_read(io
->conn
, endl
, 2);
262 if (len2
== 1 && fetch_read(io
->conn
, endl
+ 1, 1) != 1)
264 if (len2
== -1 || endl
[0] != '\r' || endl
[1] != '\n')
277 http_readfn(void *v
, void *buf
, size_t len
)
279 struct httpio
*io
= (struct httpio
*)v
;
287 for (pos
= 0; len
> 0; pos
+= l
, len
-= l
) {
289 if (!io
->buf
|| io
->bufpos
== io
->buflen
)
290 if (http_fillbuf(io
, len
) < 1)
292 l
= io
->buflen
- io
->bufpos
;
295 memcpy((char *)buf
+ pos
, io
->buf
+ io
->bufpos
, l
);
299 if (!pos
&& io
->error
)
308 http_writefn(void *v
, const void *buf
, size_t len
)
310 struct httpio
*io
= (struct httpio
*)v
;
312 return (fetch_write(io
->conn
, buf
, len
));
319 http_closefn(void *v
)
321 struct httpio
*io
= (struct httpio
*)v
;
323 if (io
->keep_alive
) {
327 setsockopt(io
->conn
->sd
, IPPROTO_TCP
, TCP_NODELAY
, &val
,
329 fetch_cache_put(io
->conn
, fetch_close
);
332 setsockopt(io
->conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
,
336 fetch_close(io
->conn
);
344 * Wrap a file descriptor up
347 http_funopen(conn_t
*conn
, int chunked
, int keep_alive
, off_t clength
)
352 if ((io
= calloc(1, sizeof(*io
))) == NULL
) {
357 io
->chunked
= chunked
;
358 io
->contentlength
= clength
;
359 io
->keep_alive
= keep_alive
;
360 f
= fetchIO_unopen(io
, http_readfn
, http_writefn
, http_closefn
);
370 /*****************************************************************************
371 * Helper functions for talking to the server and parsing its replies
385 hdr_transfer_encoding
,
389 /* Names of interesting headers */
394 { hdr_connection
, "Connection" },
395 { hdr_content_length
, "Content-Length" },
396 { hdr_content_range
, "Content-Range" },
397 { hdr_last_modified
, "Last-Modified" },
398 { hdr_location
, "Location" },
399 { hdr_transfer_encoding
, "Transfer-Encoding" },
400 { hdr_www_authenticate
, "WWW-Authenticate" },
401 { hdr_unknown
, NULL
},
405 * Send a formatted line; optionally echo to terminal
409 http_cmd(conn_t
*conn
, const char *fmt
, ...)
417 len
= vasprintf(&msg
, fmt
, ap
);
426 r
= fetch_write(conn
, msg
, len
);
438 http_cmd(conn_t
*conn
, const char *fmt
, ...)
442 char msg
[MINBUFSIZE
];
446 len
= vsnprintf(&msg
[0], MINBUFSIZE
, fmt
, ap
);
449 if (len
>= MINBUFSIZE
) {
455 r
= fetch_write(conn
, &msg
[0], len
);
466 * Get and parse status line
469 http_get_reply(conn_t
*conn
)
473 if (fetch_getln(conn
) == -1)
476 * A valid status line looks like "HTTP/m.n xyz reason" where m
477 * and n are the major and minor protocol version numbers and xyz
479 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
480 * just one) that do not send a version number, so we can't rely
481 * on finding one, but if we do, insist on it being 1.0 or 1.1.
482 * We don't care about the reason phrase.
484 if (strncmp(conn
->buf
, "HTTP", 4) != 0)
485 return (HTTP_PROTOCOL_ERROR
);
488 if (p
[1] != '1' || p
[2] != '.' || (p
[3] != '0' && p
[3] != '1'))
489 return (HTTP_PROTOCOL_ERROR
);
493 !isdigit((unsigned char)p
[1]) ||
494 !isdigit((unsigned char)p
[2]) ||
495 !isdigit((unsigned char)p
[3]))
496 return (HTTP_PROTOCOL_ERROR
);
498 conn
->err
= (p
[1] - '0') * 100 + (p
[2] - '0') * 10 + (p
[3] - '0');
503 * Check a header; if the type matches the given string, return a pointer
504 * to the beginning of the value.
507 http_match(const char *str
, const char *hdr
)
509 while (*str
&& *hdr
&&
510 tolower((unsigned char)*str
++) == tolower((unsigned char)*hdr
++))
512 if (*str
|| *hdr
!= ':')
514 while (*hdr
&& isspace((unsigned char)*++hdr
))
520 * Get the next header and return the appropriate symbolic code.
523 http_next_header(conn_t
*conn
, const char **p
)
527 if (fetch_getln(conn
) == -1)
528 return (hdr_syserror
);
529 while (conn
->buflen
&& isspace((unsigned char)conn
->buf
[conn
->buflen
- 1]))
531 conn
->buf
[conn
->buflen
] = '\0';
532 if (conn
->buflen
== 0)
535 * We could check for malformed headers but we don't really care.
536 * A valid header starts with a token immediately followed by a
537 * colon; a token is any sequence of non-control, non-whitespace
538 * characters except "()<>@,;:\\\"{}".
540 for (i
= 0; hdr_names
[i
].num
!= hdr_unknown
; i
++)
541 if ((*p
= http_match(hdr_names
[i
].name
, conn
->buf
)) != NULL
)
542 return (hdr_names
[i
].num
);
543 return (hdr_unknown
);
547 * Parse a last-modified header
550 http_parse_mtime(const char *p
, time_t *mtime
)
555 strncpy(locale
, setlocale(LC_TIME
, NULL
), sizeof(locale
));
556 setlocale(LC_TIME
, "C");
557 r
= strptime(p
, "%a, %d %b %Y %H:%M:%S GMT", &tm
);
558 /* XXX should add support for date-2 and date-3 */
559 setlocale(LC_TIME
, locale
);
562 *mtime
= timegm(&tm
);
567 * Parse a content-length header
570 http_parse_length(const char *p
, off_t
*length
)
574 for (len
= 0; *p
&& isdigit((unsigned char)*p
); ++p
)
575 len
= len
* 10 + (*p
- '0');
583 * Parse a content-range header
586 http_parse_range(const char *p
, off_t
*offset
, off_t
*length
, off_t
*size
)
588 off_t first
, last
, len
;
590 if (strncasecmp(p
, "bytes ", 6) != 0)
597 for (first
= 0; *p
&& isdigit((unsigned char)*p
); ++p
)
598 first
= first
* 10 + *p
- '0';
601 for (last
= 0, ++p
; *p
&& isdigit((unsigned char)*p
); ++p
)
602 last
= last
* 10 + *p
- '0';
604 if (first
> last
|| *p
!= '/')
606 for (len
= 0, ++p
; *p
&& isdigit((unsigned char)*p
); ++p
)
607 len
= len
* 10 + *p
- '0';
608 if (*p
|| len
< last
- first
+ 1)
613 *length
= last
- first
+ 1;
620 /*****************************************************************************
621 * Helper functions for authorization
628 http_base64(const char *src
)
630 static const char base64
[] =
631 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
632 "abcdefghijklmnopqrstuvwxyz"
639 if ((str
= malloc(((l
+ 2) / 3) * 4 + 1)) == NULL
)
645 t
= (src
[0] << 16) | (src
[1] << 8) | src
[2];
646 dst
[0] = base64
[(t
>> 18) & 0x3f];
647 dst
[1] = base64
[(t
>> 12) & 0x3f];
648 dst
[2] = base64
[(t
>> 6) & 0x3f];
649 dst
[3] = base64
[(t
>> 0) & 0x3f];
656 t
= (src
[0] << 16) | (src
[1] << 8);
657 dst
[0] = base64
[(t
>> 18) & 0x3f];
658 dst
[1] = base64
[(t
>> 12) & 0x3f];
659 dst
[2] = base64
[(t
>> 6) & 0x3f];
666 dst
[0] = base64
[(t
>> 18) & 0x3f];
667 dst
[1] = base64
[(t
>> 12) & 0x3f];
668 dst
[2] = dst
[3] = '=';
681 * Encode username and password
685 http_basic_auth(conn_t
*conn
, const char *hdr
, const char *usr
, const char *pwd
)
690 if (asprintf(&upw
, "%s:%s", usr
, pwd
) == -1)
692 auth
= http_base64(upw
);
696 r
= http_cmd(conn
, "%s: Basic %s\r\n", hdr
, auth
);
702 http_basic_auth(conn_t
*conn
, const char *hdr
, const char *usr
, const char *pwd
)
704 char upw
[MINBUFSIZE
], *auth
;
707 len
= snprintf(&upw
[0], MINBUFSIZE
, "%s:%s", usr
, pwd
);
708 if (len
>= MINBUFSIZE
)
710 auth
= http_base64(&upw
[0]);
713 r
= http_cmd(conn
, "%s: Basic %s\r\n", hdr
, auth
);
719 * Send an authorization header
722 http_authorize(conn_t
*conn
, const char *hdr
, const char *p
)
724 /* basic authorization */
725 if (strncasecmp(p
, "basic:", 6) == 0) {
726 char *user
, *pwd
, *str
;
730 for (p
+= 6; *p
&& *p
!= ':'; ++p
)
732 if (!*p
|| strchr(++p
, ':') == NULL
)
734 if ((str
= strdup(p
)) == NULL
)
735 return (-1); /* XXX */
737 pwd
= strchr(str
, ':');
739 r
= http_basic_auth(conn
, hdr
, user
, pwd
);
747 /*****************************************************************************
748 * Helper functions for connecting to a server or proxy
752 * Connect to the correct HTTP server or proxy.
755 http_connect(struct url
*URL
, struct url
*purl
, const char *flags
, int *cached
)
771 verbose
= CHECK_FLAG('v');
775 else if (CHECK_FLAG('6'))
779 if (purl
&& strcasecmp(URL
->scheme
, SCHEME_HTTPS
) != 0) {
781 } else if (strcasecmp(URL
->scheme
, SCHEME_FTP
) == 0) {
782 /* can't talk http to an ftp server */
783 /* XXX should set an error code */
787 if ((conn
= fetch_cache_get(URL
, af
)) != NULL
) {
792 if ((conn
= fetch_connect(URL
, af
, verbose
)) == NULL
)
793 /* fetch_connect() has already set an error code */
795 if (strcasecmp(URL
->scheme
, SCHEME_HTTPS
) == 0 &&
796 fetch_ssl(conn
, verbose
) == -1) {
810 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
, sizeof(val
));
817 http_get_proxy(struct url
* url
, const char *flags
)
822 if (flags
!= NULL
&& strchr(flags
, 'd') != NULL
)
824 if (fetch_no_proxy_match(url
->host
))
826 if (((p
= getenv("HTTP_PROXY")) || (p
= getenv("http_proxy"))) &&
827 *p
&& (purl
= fetchParseURL(p
))) {
829 strcpy(purl
->scheme
, SCHEME_HTTP
);
831 purl
->port
= fetch_default_proxy_port(purl
->scheme
);
832 if (strcasecmp(purl
->scheme
, SCHEME_HTTP
) == 0)
840 set_if_modified_since(conn_t
*conn
, time_t last_modified
)
842 static const char weekdays
[] = "SunMonTueWedThuFriSat";
843 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
846 gmtime_r(&last_modified
, &tm
);
847 snprintf(buf
, sizeof(buf
), "%.3s, %02d %.3s %4d %02d:%02d:%02d GMT",
848 weekdays
+ tm
.tm_wday
* 3, tm
.tm_mday
, months
+ tm
.tm_mon
* 3,
849 tm
.tm_year
+ 1900, tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
850 http_cmd(conn
, "If-Modified-Since: %s\r\n", buf
);
854 /*****************************************************************************
859 * Send a request and process the reply
861 * XXX This function is way too long, the do..while loop should be split
862 * XXX off into a separate function.
865 http_request(struct url
*URL
, const char *op
, struct url_stat
*us
,
866 struct url
*purl
, const char *flags
)
869 struct url
*url
, *new;
870 int chunked
, direct
, if_modified_since
, need_auth
, noredirect
;
871 int keep_alive
, verbose
, cached
;
873 off_t offset
, clength
, length
, size
;
878 char hbuf
[URL_HOSTLEN
+ 7], *host
;
880 direct
= CHECK_FLAG('d');
881 noredirect
= CHECK_FLAG('A');
882 verbose
= CHECK_FLAG('v');
883 if_modified_since
= CHECK_FLAG('i');
886 if (direct
&& purl
) {
891 /* try the provided URL first */
894 /* if the A flag is set, we only get one try */
895 n
= noredirect
? 1 : MAX_REDIRECT
;
898 e
= HTTP_PROTOCOL_ERROR
;
911 url
->port
= fetch_default_port(url
->scheme
);
913 /* were we redirected to an FTP URL? */
914 if (purl
== NULL
&& strcmp(url
->scheme
, SCHEME_FTP
) == 0) {
915 if (strcmp(op
, "GET") == 0)
916 return (ftp_request(url
, "RETR", NULL
, us
, purl
, flags
));
917 else if (strcmp(op
, "HEAD") == 0)
918 return (ftp_request(url
, "STAT", NULL
, us
, purl
, flags
));
921 /* connect to server or proxy */
922 if ((conn
= http_connect(url
, purl
, flags
, &cached
)) == NULL
)
927 if (strchr(url
->host
, ':')) {
928 snprintf(hbuf
, sizeof(hbuf
), "[%s]", url
->host
);
932 if (url
->port
!= fetch_default_port(url
->scheme
)) {
937 snprintf(hbuf
+ strlen(hbuf
),
938 sizeof(hbuf
) - strlen(hbuf
), ":%d", url
->port
);
943 fetch_info("requesting %s://%s%s",
944 url
->scheme
, host
, url
->doc
);
946 http_cmd(conn
, "%s %s://%s%s HTTP/1.1\r\n",
947 op
, url
->scheme
, host
, url
->doc
);
949 http_cmd(conn
, "%s %s HTTP/1.1\r\n",
953 if (if_modified_since
&& url
->last_modified
> 0)
954 set_if_modified_since(conn
, url
->last_modified
);
957 http_cmd(conn
, "Host: %s\r\n", host
);
959 /* proxy authorization */
961 if (*purl
->user
|| *purl
->pwd
)
962 http_basic_auth(conn
, "Proxy-Authorization",
963 purl
->user
, purl
->pwd
);
964 else if ((p
= getenv("HTTP_PROXY_AUTH")) != NULL
&& *p
!= '\0')
965 http_authorize(conn
, "Proxy-Authorization", p
);
968 /* server authorization */
969 if (need_auth
|| *url
->user
|| *url
->pwd
) {
970 if (*url
->user
|| *url
->pwd
)
971 http_basic_auth(conn
, "Authorization", url
->user
, url
->pwd
);
972 else if ((p
= getenv("HTTP_AUTH")) != NULL
&& *p
!= '\0')
973 http_authorize(conn
, "Authorization", p
);
974 else if (fetchAuthMethod
&& fetchAuthMethod(url
) == 0) {
975 http_basic_auth(conn
, "Authorization", url
->user
, url
->pwd
);
977 http_seterr(HTTP_NEED_AUTH
);
983 if ((p
= getenv("HTTP_REFERER")) != NULL
&& *p
!= '\0') {
984 if (strcasecmp(p
, "auto") == 0)
985 http_cmd(conn
, "Referer: %s://%s%s\r\n",
986 url
->scheme
, host
, url
->doc
);
988 http_cmd(conn
, "Referer: %s\r\n", p
);
990 if ((p
= getenv("HTTP_USER_AGENT")) != NULL
&& *p
!= '\0')
991 http_cmd(conn
, "User-Agent: %s\r\n", p
);
993 http_cmd(conn
, "User-Agent: %s\r\n", _LIBFETCH_VER
);
996 http_cmd(conn
, "Range: bytes=%lld-\r\n", (long long)url
->offset
);
999 http_cmd(conn
, "Range: bytes=%ld-\r\n", (long)url
->offset
);
1001 http_cmd(conn
, "\r\n");
1004 * Force the queued request to be dispatched. Normally, one
1005 * would do this with shutdown(2) but squid proxies can be
1006 * configured to disallow such half-closed connections. To
1007 * be compatible with such configurations, fiddle with socket
1008 * options to force the pending data to be written.
1012 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
,
1016 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NODELAY
, &val
,
1020 switch (http_get_reply(conn
)) {
1023 case HTTP_NOT_MODIFIED
:
1026 case HTTP_MOVED_PERM
:
1027 case HTTP_MOVED_TEMP
:
1028 case HTTP_SEE_OTHER
:
1030 * Not so fine, but we still have to read the
1031 * headers to get the new location.
1034 case HTTP_NEED_AUTH
:
1037 * We already sent out authorization code,
1038 * so there's nothing more we can do.
1040 http_seterr(conn
->err
);
1043 /* try again, but send the password this time */
1045 fetch_info("server requires authorization");
1047 case HTTP_NEED_PROXY_AUTH
:
1049 * If we're talking to a proxy, we already sent
1050 * our proxy authorization code, so there's
1051 * nothing more we can do.
1053 http_seterr(conn
->err
);
1055 case HTTP_BAD_RANGE
:
1057 * This can happen if we ask for 0 bytes because
1058 * we already have the whole file. Consider this
1059 * a success for now, and check sizes later.
1062 case HTTP_PROTOCOL_ERROR
:
1071 http_seterr(conn
->err
);
1074 /* fall through so we can get the full error message */
1079 switch ((h
= http_next_header(conn
, &p
))) {
1084 http_seterr(HTTP_PROTOCOL_ERROR
);
1086 case hdr_connection
:
1088 keep_alive
= (strcasecmp(p
, "keep-alive") == 0);
1090 case hdr_content_length
:
1091 http_parse_length(p
, &clength
);
1093 case hdr_content_range
:
1094 http_parse_range(p
, &offset
, &length
, &size
);
1096 case hdr_last_modified
:
1097 http_parse_mtime(p
, &mtime
);
1100 if (!HTTP_REDIRECT(conn
->err
))
1105 fetch_info("%d redirect to %s", conn
->err
, p
);
1108 new = fetchMakeURL(url
->scheme
, url
->host
, url
->port
, p
,
1109 url
->user
, url
->pwd
);
1111 new = fetchParseURL(p
);
1113 /* XXX should set an error code */
1116 if (!*new->user
&& !*new->pwd
) {
1117 strcpy(new->user
, url
->user
);
1118 strcpy(new->pwd
, url
->pwd
);
1120 new->offset
= url
->offset
;
1121 new->length
= url
->length
;
1123 case hdr_transfer_encoding
:
1125 chunked
= (strcasecmp(p
, "chunked") == 0);
1127 case hdr_www_authenticate
:
1128 if (conn
->err
!= HTTP_NEED_AUTH
)
1130 /* if we were smarter, we'd check the method and realm */
1138 } while (h
> hdr_end
);
1140 /* we need to provide authentication */
1141 if (conn
->err
== HTTP_NEED_AUTH
) {
1149 /* requested range not satisfiable */
1150 if (conn
->err
== HTTP_BAD_RANGE
) {
1151 if (url
->offset
== size
&& url
->length
== 0) {
1152 /* asked for 0 bytes; fake it */
1153 offset
= url
->offset
;
1154 conn
->err
= HTTP_OK
;
1157 http_seterr(conn
->err
);
1162 /* we have a hit or an error */
1163 if (conn
->err
== HTTP_OK
||
1164 conn
->err
== HTTP_PARTIAL
||
1165 conn
->err
== HTTP_NOT_MODIFIED
||
1166 HTTP_ERROR(conn
->err
))
1169 /* all other cases: we got a redirect */
1181 /* we failed, or ran out of retries */
1187 /* check for inconsistencies */
1188 if (clength
!= -1 && length
!= -1 && clength
!= length
) {
1189 http_seterr(HTTP_PROTOCOL_ERROR
);
1195 length
= offset
+ clength
;
1196 if (length
!= -1 && size
!= -1 && length
!= size
) {
1197 http_seterr(HTTP_PROTOCOL_ERROR
);
1206 us
->atime
= us
->mtime
= mtime
;
1210 if (URL
->offset
> 0 && offset
> URL
->offset
) {
1211 http_seterr(HTTP_PROTOCOL_ERROR
);
1215 /* report back real offset and size */
1216 URL
->offset
= offset
;
1217 URL
->length
= clength
;
1219 if (clength
== -1 && !chunked
)
1222 if (conn
->err
== HTTP_NOT_MODIFIED
) {
1223 http_seterr(HTTP_NOT_MODIFIED
);
1225 fetch_cache_put(conn
, fetch_close
);
1231 /* wrap it up in a fetchIO */
1232 if ((f
= http_funopen(conn
, chunked
, keep_alive
, clength
)) == NULL
) {
1242 if (HTTP_ERROR(conn
->err
)) {
1247 } while (fetchIO_read(f
, buf
, sizeof(buf
)) > 0);
1267 /*****************************************************************************
1272 * Retrieve and stat a file by HTTP
1275 fetchXGetHTTP(struct url
*URL
, struct url_stat
*us
, const char *flags
)
1277 return (http_request(URL
, "GET", us
, http_get_proxy(URL
, flags
), flags
));
1281 * Retrieve a file by HTTP
1284 fetchGetHTTP(struct url
*URL
, const char *flags
)
1286 return (fetchXGetHTTP(URL
, NULL
, flags
));
1290 * Store a file by HTTP
1293 fetchPutHTTP(struct url
*URL
, const char *flags
)
1295 fprintf(stderr
, "fetchPutHTTP(): not implemented\n");
1300 * Get an HTTP document's metadata
1303 fetchStatHTTP(struct url
*URL
, struct url_stat
*us
, const char *flags
)
1307 f
= http_request(URL
, "HEAD", us
, http_get_proxy(URL
, flags
), flags
);
1330 struct index_parser
{
1331 struct url_list
*ue
;
1333 enum http_states state
;
1337 parse_index(struct index_parser
*parser
, const char *buf
, size_t len
)
1339 char *end_attr
, p
= *buf
;
1341 switch (parser
->state
) {
1343 /* Plain text, not in markup */
1345 parser
->state
= ST_LT
;
1348 /* In tag -- "<" already found */
1350 parser
->state
= ST_NONE
;
1351 else if (p
== 'a' || p
== 'A')
1352 parser
->state
= ST_LTA
;
1353 else if (!isspace((unsigned char)p
))
1354 parser
->state
= ST_TAG
;
1357 /* In tag -- "<a" already found */
1359 parser
->state
= ST_NONE
;
1361 parser
->state
= ST_TAGAQ
;
1362 else if (isspace((unsigned char)p
))
1363 parser
->state
= ST_TAGA
;
1365 parser
->state
= ST_TAG
;
1368 /* In tag, but not "<a" -- disregard */
1370 parser
->state
= ST_NONE
;
1373 /* In a-tag -- "<a " already found */
1375 parser
->state
= ST_NONE
;
1377 parser
->state
= ST_TAGAQ
;
1378 else if (p
== 'h' || p
== 'H')
1379 parser
->state
= ST_H
;
1380 else if (!isspace((unsigned char)p
))
1381 parser
->state
= ST_TAGAX
;
1384 /* In unknown keyword in a-tag */
1386 parser
->state
= ST_NONE
;
1388 parser
->state
= ST_TAGAQ
;
1389 else if (isspace((unsigned char)p
))
1390 parser
->state
= ST_TAGA
;
1393 /* In a-tag, unknown argument for keys. */
1395 parser
->state
= ST_NONE
;
1397 parser
->state
= ST_TAGA
;
1400 /* In a-tag -- "<a h" already found */
1402 parser
->state
= ST_NONE
;
1404 parser
->state
= ST_TAGAQ
;
1405 else if (p
== 'r' || p
== 'R')
1406 parser
->state
= ST_R
;
1407 else if (isspace((unsigned char)p
))
1408 parser
->state
= ST_TAGA
;
1410 parser
->state
= ST_TAGAX
;
1413 /* In a-tag -- "<a hr" already found */
1415 parser
->state
= ST_NONE
;
1417 parser
->state
= ST_TAGAQ
;
1418 else if (p
== 'e' || p
== 'E')
1419 parser
->state
= ST_E
;
1420 else if (isspace((unsigned char)p
))
1421 parser
->state
= ST_TAGA
;
1423 parser
->state
= ST_TAGAX
;
1426 /* In a-tag -- "<a hre" already found */
1428 parser
->state
= ST_NONE
;
1430 parser
->state
= ST_TAGAQ
;
1431 else if (p
== 'f' || p
== 'F')
1432 parser
->state
= ST_F
;
1433 else if (isspace((unsigned char)p
))
1434 parser
->state
= ST_TAGA
;
1436 parser
->state
= ST_TAGAX
;
1439 /* In a-tag -- "<a href" already found */
1441 parser
->state
= ST_NONE
;
1443 parser
->state
= ST_TAGAQ
;
1445 parser
->state
= ST_HREF
;
1446 else if (!isspace((unsigned char)p
))
1447 parser
->state
= ST_TAGAX
;
1450 /* In a-tag -- "<a href=" already found */
1452 parser
->state
= ST_NONE
;
1454 parser
->state
= ST_HREFQ
;
1455 else if (!isspace((unsigned char)p
))
1456 parser
->state
= ST_TAGA
;
1459 /* In href of the a-tag */
1460 end_attr
= memchr(buf
, '"', len
);
1461 if (end_attr
== NULL
)
1464 parser
->state
= ST_TAGA
;
1465 if (fetch_add_entry(parser
->ue
, parser
->url
, buf
, 1))
1467 return end_attr
+ 1 - buf
;
1473 struct http_index_cache
{
1474 struct http_index_cache
*next
;
1475 struct url
*location
;
1479 static struct http_index_cache
*index_cache
;
1485 fetchListHTTP(struct url_list
*ue
, struct url
*url
, const char *pattern
, const char *flags
)
1488 char buf
[2 * PATH_MAX
];
1489 size_t buf_len
, sum_processed
;
1490 ssize_t read_len
, processed
;
1491 struct index_parser state
;
1492 struct http_index_cache
*cache
= NULL
;
1495 do_cache
= CHECK_FLAG('c');
1498 for (cache
= index_cache
; cache
!= NULL
; cache
= cache
->next
) {
1499 if (strcmp(cache
->location
->scheme
, url
->scheme
))
1501 if (strcmp(cache
->location
->user
, url
->user
))
1503 if (strcmp(cache
->location
->pwd
, url
->pwd
))
1505 if (strcmp(cache
->location
->host
, url
->host
))
1507 if (cache
->location
->port
!= url
->port
)
1509 if (strcmp(cache
->location
->doc
, url
->doc
))
1511 return fetchAppendURLList(ue
, &cache
->ue
);
1514 cache
= malloc(sizeof(*cache
));
1515 fetchInitURLList(&cache
->ue
);
1516 cache
->location
= fetchCopyURL(url
);
1519 f
= fetchGetHTTP(url
, flags
);
1522 fetchFreeURLList(&cache
->ue
);
1523 fetchFreeURL(cache
->location
);
1530 state
.state
= ST_NONE
;
1532 state
.ue
= &cache
->ue
;
1539 while ((read_len
= fetchIO_read(f
, buf
+ buf_len
, sizeof(buf
) - buf_len
)) > 0) {
1540 buf_len
+= read_len
;
1543 processed
= parse_index(&state
, buf
+ sum_processed
, buf_len
);
1544 if (processed
== -1)
1546 buf_len
-= processed
;
1547 sum_processed
+= processed
;
1548 } while (processed
!= 0 && buf_len
> 0);
1549 if (processed
== -1) {
1553 memmove(buf
, buf
+ sum_processed
, buf_len
);
1558 ret
= read_len
< 0 ? -1 : 0;
1562 cache
->next
= index_cache
;
1563 index_cache
= cache
;
1566 if (fetchAppendURLList(ue
, &cache
->ue
))