1 /* $NetBSD: http.c,v 1.25 2009/10/15 12:36:57 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 */
81 #include <sys/types.h>
82 #include <sys/socket.h>
89 #include <nbcompat/stdio.h>
98 #include <netinet/in.h>
99 #include <netinet/tcp.h>
102 #include <nbcompat/netdb.h>
107 #include <arpa/inet.h>
113 /* Maximum number of redirects to follow */
114 #define MAX_REDIRECT 5
116 /* Symbolic names for reply codes we care about */
118 #define HTTP_PARTIAL 206
119 #define HTTP_MOVED_PERM 301
120 #define HTTP_MOVED_TEMP 302
121 #define HTTP_SEE_OTHER 303
122 #define HTTP_NOT_MODIFIED 304
123 #define HTTP_TEMP_REDIRECT 307
124 #define HTTP_NEED_AUTH 401
125 #define HTTP_NEED_PROXY_AUTH 407
126 #define HTTP_BAD_RANGE 416
127 #define HTTP_PROTOCOL_ERROR 999
129 #define HTTP_REDIRECT(xyz) ((xyz) == HTTP_MOVED_PERM \
130 || (xyz) == HTTP_MOVED_TEMP \
131 || (xyz) == HTTP_TEMP_REDIRECT \
132 || (xyz) == HTTP_SEE_OTHER)
134 #define HTTP_ERROR(xyz) ((xyz) > 400 && (xyz) < 599)
137 /*****************************************************************************
138 * I/O functions for decoding chunked streams
143 conn_t
*conn
; /* connection */
144 int chunked
; /* chunked mode */
145 char *buf
; /* chunk buffer */
146 size_t bufsize
; /* size of chunk buffer */
147 ssize_t buflen
; /* amount of data currently in buffer */
148 int bufpos
; /* current read offset in buffer */
149 int eof
; /* end-of-file flag */
150 int error
; /* error flag */
151 size_t chunksize
; /* remaining size of current chunk */
155 * Get next chunk header
158 http_new_chunk(struct httpio
*io
)
162 if (fetch_getln(io
->conn
) == -1)
165 if (io
->conn
->buflen
< 2 || !isxdigit((unsigned char)*io
->conn
->buf
))
168 for (p
= io
->conn
->buf
; *p
&& !isspace((unsigned char)*p
); ++p
) {
171 if (!isxdigit((unsigned char)*p
))
173 if (isdigit((unsigned char)*p
)) {
174 io
->chunksize
= io
->chunksize
* 16 +
177 io
->chunksize
= io
->chunksize
* 16 +
178 10 + tolower((unsigned char)*p
) - 'a';
182 return (io
->chunksize
);
186 * Grow the input buffer to at least len bytes
189 http_growbuf(struct httpio
*io
, size_t len
)
193 if (io
->bufsize
>= len
)
196 if ((tmp
= realloc(io
->buf
, len
)) == NULL
)
204 * Fill the input buffer, do chunk decoding on the fly
207 http_fillbuf(struct httpio
*io
, size_t len
)
214 if (io
->chunked
== 0) {
215 if (http_growbuf(io
, len
) == -1)
217 if ((io
->buflen
= fetch_read(io
->conn
, io
->buf
, len
)) == -1) {
225 if (io
->chunksize
== 0) {
226 switch (http_new_chunk(io
)) {
236 if (len
> io
->chunksize
)
238 if (http_growbuf(io
, len
) == -1)
240 if ((io
->buflen
= fetch_read(io
->conn
, io
->buf
, len
)) == -1) {
244 io
->chunksize
-= io
->buflen
;
246 if (io
->chunksize
== 0) {
250 len2
= fetch_read(io
->conn
, endl
, 2);
251 if (len2
== 1 && fetch_read(io
->conn
, endl
+ 1, 1) != 1)
253 if (len2
== -1 || endl
[0] != '\r' || endl
[1] != '\n')
266 http_readfn(void *v
, void *buf
, size_t len
)
268 struct httpio
*io
= (struct httpio
*)v
;
276 for (pos
= 0; len
> 0; pos
+= l
, len
-= l
) {
278 if (!io
->buf
|| io
->bufpos
== io
->buflen
)
279 if (http_fillbuf(io
, len
) < 1)
281 l
= io
->buflen
- io
->bufpos
;
284 memcpy((char *)buf
+ pos
, io
->buf
+ io
->bufpos
, l
);
288 if (!pos
&& io
->error
)
297 http_writefn(void *v
, const void *buf
, size_t len
)
299 struct httpio
*io
= (struct httpio
*)v
;
301 return (fetch_write(io
->conn
, buf
, len
));
308 http_closefn(void *v
)
310 struct httpio
*io
= (struct httpio
*)v
;
312 fetch_close(io
->conn
);
319 * Wrap a file descriptor up
322 http_funopen(conn_t
*conn
, int chunked
)
327 if ((io
= calloc(1, sizeof(*io
))) == NULL
) {
332 io
->chunked
= chunked
;
333 f
= fetchIO_unopen(io
, http_readfn
, http_writefn
, http_closefn
);
343 /*****************************************************************************
344 * Helper functions for talking to the server and parsing its replies
357 hdr_transfer_encoding
,
361 /* Names of interesting headers */
366 { hdr_content_length
, "Content-Length" },
367 { hdr_content_range
, "Content-Range" },
368 { hdr_last_modified
, "Last-Modified" },
369 { hdr_location
, "Location" },
370 { hdr_transfer_encoding
, "Transfer-Encoding" },
371 { hdr_www_authenticate
, "WWW-Authenticate" },
372 { hdr_unknown
, NULL
},
376 * Send a formatted line; optionally echo to terminal
379 http_cmd(conn_t
*conn
, const char *fmt
, ...)
387 len
= vasprintf(&msg
, fmt
, ap
);
396 r
= fetch_putln(conn
, msg
, len
);
408 * Get and parse status line
411 http_get_reply(conn_t
*conn
)
415 if (fetch_getln(conn
) == -1)
418 * A valid status line looks like "HTTP/m.n xyz reason" where m
419 * and n are the major and minor protocol version numbers and xyz
421 * Unfortunately, there are servers out there (NCSA 1.5.1, to name
422 * just one) that do not send a version number, so we can't rely
423 * on finding one, but if we do, insist on it being 1.0 or 1.1.
424 * We don't care about the reason phrase.
426 if (strncmp(conn
->buf
, "HTTP", 4) != 0)
427 return (HTTP_PROTOCOL_ERROR
);
430 if (p
[1] != '1' || p
[2] != '.' || (p
[3] != '0' && p
[3] != '1'))
431 return (HTTP_PROTOCOL_ERROR
);
435 !isdigit((unsigned char)p
[1]) ||
436 !isdigit((unsigned char)p
[2]) ||
437 !isdigit((unsigned char)p
[3]))
438 return (HTTP_PROTOCOL_ERROR
);
440 conn
->err
= (p
[1] - '0') * 100 + (p
[2] - '0') * 10 + (p
[3] - '0');
445 * Check a header; if the type matches the given string, return a pointer
446 * to the beginning of the value.
449 http_match(const char *str
, const char *hdr
)
451 while (*str
&& *hdr
&&
452 tolower((unsigned char)*str
++) == tolower((unsigned char)*hdr
++))
454 if (*str
|| *hdr
!= ':')
456 while (*hdr
&& isspace((unsigned char)*++hdr
))
462 * Get the next header and return the appropriate symbolic code.
465 http_next_header(conn_t
*conn
, const char **p
)
469 if (fetch_getln(conn
) == -1)
470 return (hdr_syserror
);
471 while (conn
->buflen
&& isspace((unsigned char)conn
->buf
[conn
->buflen
- 1]))
473 conn
->buf
[conn
->buflen
] = '\0';
474 if (conn
->buflen
== 0)
477 * We could check for malformed headers but we don't really care.
478 * A valid header starts with a token immediately followed by a
479 * colon; a token is any sequence of non-control, non-whitespace
480 * characters except "()<>@,;:\\\"{}".
482 for (i
= 0; hdr_names
[i
].num
!= hdr_unknown
; i
++)
483 if ((*p
= http_match(hdr_names
[i
].name
, conn
->buf
)) != NULL
)
484 return (hdr_names
[i
].num
);
485 return (hdr_unknown
);
489 * Parse a last-modified header
492 http_parse_mtime(const char *p
, time_t *mtime
)
497 strncpy(locale
, setlocale(LC_TIME
, NULL
), sizeof(locale
));
498 setlocale(LC_TIME
, "C");
499 r
= strptime(p
, "%a, %d %b %Y %H:%M:%S GMT", &tm
);
500 /* XXX should add support for date-2 and date-3 */
501 setlocale(LC_TIME
, locale
);
504 *mtime
= timegm(&tm
);
509 * Parse a content-length header
512 http_parse_length(const char *p
, off_t
*length
)
516 for (len
= 0; *p
&& isdigit((unsigned char)*p
); ++p
)
517 len
= len
* 10 + (*p
- '0');
525 * Parse a content-range header
528 http_parse_range(const char *p
, off_t
*offset
, off_t
*length
, off_t
*size
)
530 off_t first
, last
, len
;
532 if (strncasecmp(p
, "bytes ", 6) != 0)
539 for (first
= 0; *p
&& isdigit((unsigned char)*p
); ++p
)
540 first
= first
* 10 + *p
- '0';
543 for (last
= 0, ++p
; *p
&& isdigit((unsigned char)*p
); ++p
)
544 last
= last
* 10 + *p
- '0';
546 if (first
> last
|| *p
!= '/')
548 for (len
= 0, ++p
; *p
&& isdigit((unsigned char)*p
); ++p
)
549 len
= len
* 10 + *p
- '0';
550 if (*p
|| len
< last
- first
+ 1)
555 *length
= last
- first
+ 1;
562 /*****************************************************************************
563 * Helper functions for authorization
570 http_base64(const char *src
)
572 static const char base64
[] =
573 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
574 "abcdefghijklmnopqrstuvwxyz"
581 if ((str
= malloc(((l
+ 2) / 3) * 4 + 1)) == NULL
)
587 t
= (src
[0] << 16) | (src
[1] << 8) | src
[2];
588 dst
[0] = base64
[(t
>> 18) & 0x3f];
589 dst
[1] = base64
[(t
>> 12) & 0x3f];
590 dst
[2] = base64
[(t
>> 6) & 0x3f];
591 dst
[3] = base64
[(t
>> 0) & 0x3f];
598 t
= (src
[0] << 16) | (src
[1] << 8);
599 dst
[0] = base64
[(t
>> 18) & 0x3f];
600 dst
[1] = base64
[(t
>> 12) & 0x3f];
601 dst
[2] = base64
[(t
>> 6) & 0x3f];
608 dst
[0] = base64
[(t
>> 18) & 0x3f];
609 dst
[1] = base64
[(t
>> 12) & 0x3f];
610 dst
[2] = dst
[3] = '=';
623 * Encode username and password
626 http_basic_auth(conn_t
*conn
, const char *hdr
, const char *usr
, const char *pwd
)
631 if (asprintf(&upw
, "%s:%s", usr
, pwd
) == -1)
633 auth
= http_base64(upw
);
637 r
= http_cmd(conn
, "%s: Basic %s", hdr
, auth
);
643 * Send an authorization header
646 http_authorize(conn_t
*conn
, const char *hdr
, const char *p
)
648 /* basic authorization */
649 if (strncasecmp(p
, "basic:", 6) == 0) {
650 char *user
, *pwd
, *str
;
654 for (p
+= 6; *p
&& *p
!= ':'; ++p
)
656 if (!*p
|| strchr(++p
, ':') == NULL
)
658 if ((str
= strdup(p
)) == NULL
)
659 return (-1); /* XXX */
661 pwd
= strchr(str
, ':');
663 r
= http_basic_auth(conn
, hdr
, user
, pwd
);
671 /*****************************************************************************
672 * Helper functions for connecting to a server or proxy
676 * Connect to the correct HTTP server or proxy.
679 http_connect(struct url
*URL
, struct url
*purl
, const char *flags
)
693 verbose
= CHECK_FLAG('v');
697 else if (CHECK_FLAG('6'))
701 if (purl
&& strcasecmp(URL
->scheme
, SCHEME_HTTPS
) != 0) {
703 } else if (strcasecmp(URL
->scheme
, SCHEME_FTP
) == 0) {
704 /* can't talk http to an ftp server */
705 /* XXX should set an error code */
709 if ((conn
= fetch_connect(URL
->host
, URL
->port
, af
, verbose
)) == NULL
)
710 /* fetch_connect() has already set an error code */
712 if (strcasecmp(URL
->scheme
, SCHEME_HTTPS
) == 0 &&
713 fetch_ssl(conn
, verbose
) == -1) {
727 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
, sizeof(val
));
734 http_get_proxy(struct url
* url
, const char *flags
)
739 if (flags
!= NULL
&& strchr(flags
, 'd') != NULL
)
741 if (fetch_no_proxy_match(url
->host
))
743 if (((p
= getenv("HTTP_PROXY")) || (p
= getenv("http_proxy"))) &&
744 *p
&& (purl
= fetchParseURL(p
))) {
746 strcpy(purl
->scheme
, SCHEME_HTTP
);
748 purl
->port
= fetch_default_proxy_port(purl
->scheme
);
749 if (strcasecmp(purl
->scheme
, SCHEME_HTTP
) == 0)
757 set_if_modified_since(conn_t
*conn
, time_t last_modified
)
759 static const char weekdays
[] = "SunMonTueWedThuFriSat";
760 static const char months
[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
763 gmtime_r(&last_modified
, &tm
);
764 snprintf(buf
, sizeof(buf
), "%.3s, %02d %.3s %4d %02d:%02d:%02d GMT",
765 weekdays
+ tm
.tm_wday
* 3, tm
.tm_mday
, months
+ tm
.tm_mon
* 3,
766 tm
.tm_year
+ 1900, tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
);
767 http_cmd(conn
, "If-Modified-Since: %s", buf
);
771 /*****************************************************************************
776 * Send a request and process the reply
778 * XXX This function is way too long, the do..while loop should be split
779 * XXX off into a separate function.
782 http_request(struct url
*URL
, const char *op
, struct url_stat
*us
,
783 struct url
*purl
, const char *flags
)
786 struct url
*url
, *new;
787 int chunked
, direct
, if_modified_since
, need_auth
, noredirect
, verbose
;
789 off_t offset
, clength
, length
, size
;
794 char hbuf
[URL_HOSTLEN
+ 7], *host
;
796 direct
= CHECK_FLAG('d');
797 noredirect
= CHECK_FLAG('A');
798 verbose
= CHECK_FLAG('v');
799 if_modified_since
= CHECK_FLAG('i');
801 if (direct
&& purl
) {
806 /* try the provided URL first */
809 /* if the A flag is set, we only get one try */
810 n
= noredirect
? 1 : MAX_REDIRECT
;
813 e
= HTTP_PROTOCOL_ERROR
;
826 url
->port
= fetch_default_port(url
->scheme
);
828 /* were we redirected to an FTP URL? */
829 if (purl
== NULL
&& strcmp(url
->scheme
, SCHEME_FTP
) == 0) {
830 if (strcmp(op
, "GET") == 0)
831 return (ftp_request(url
, "RETR", NULL
, us
, purl
, flags
));
832 else if (strcmp(op
, "HEAD") == 0)
833 return (ftp_request(url
, "STAT", NULL
, us
, purl
, flags
));
836 /* connect to server or proxy */
837 if ((conn
= http_connect(url
, purl
, flags
)) == NULL
)
842 if (strchr(url
->host
, ':')) {
843 snprintf(hbuf
, sizeof(hbuf
), "[%s]", url
->host
);
847 if (url
->port
!= fetch_default_port(url
->scheme
)) {
852 snprintf(hbuf
+ strlen(hbuf
),
853 sizeof(hbuf
) - strlen(hbuf
), ":%d", url
->port
);
858 fetch_info("requesting %s://%s%s",
859 url
->scheme
, host
, url
->doc
);
861 http_cmd(conn
, "%s %s://%s%s HTTP/1.1",
862 op
, url
->scheme
, host
, url
->doc
);
864 http_cmd(conn
, "%s %s HTTP/1.1",
868 if (if_modified_since
&& url
->last_modified
> 0)
869 set_if_modified_since(conn
, url
->last_modified
);
872 http_cmd(conn
, "Host: %s", host
);
874 /* proxy authorization */
876 if (*purl
->user
|| *purl
->pwd
)
877 http_basic_auth(conn
, "Proxy-Authorization",
878 purl
->user
, purl
->pwd
);
879 else if ((p
= getenv("HTTP_PROXY_AUTH")) != NULL
&& *p
!= '\0')
880 http_authorize(conn
, "Proxy-Authorization", p
);
883 /* server authorization */
884 if (need_auth
|| *url
->user
|| *url
->pwd
) {
885 if (*url
->user
|| *url
->pwd
)
886 http_basic_auth(conn
, "Authorization", url
->user
, url
->pwd
);
887 else if ((p
= getenv("HTTP_AUTH")) != NULL
&& *p
!= '\0')
888 http_authorize(conn
, "Authorization", p
);
889 else if (fetchAuthMethod
&& fetchAuthMethod(url
) == 0) {
890 http_basic_auth(conn
, "Authorization", url
->user
, url
->pwd
);
892 http_seterr(HTTP_NEED_AUTH
);
898 if ((p
= getenv("HTTP_REFERER")) != NULL
&& *p
!= '\0') {
899 if (strcasecmp(p
, "auto") == 0)
900 http_cmd(conn
, "Referer: %s://%s%s",
901 url
->scheme
, host
, url
->doc
);
903 http_cmd(conn
, "Referer: %s", p
);
905 if ((p
= getenv("HTTP_USER_AGENT")) != NULL
&& *p
!= '\0')
906 http_cmd(conn
, "User-Agent: %s", p
);
908 http_cmd(conn
, "User-Agent: %s ", _LIBFETCH_VER
);
910 http_cmd(conn
, "Range: bytes=%lld-", (long long)url
->offset
);
911 http_cmd(conn
, "Connection: close");
915 * Force the queued request to be dispatched. Normally, one
916 * would do this with shutdown(2) but squid proxies can be
917 * configured to disallow such half-closed connections. To
918 * be compatible with such configurations, fiddle with socket
919 * options to force the pending data to be written.
923 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NOPUSH
, &val
,
927 setsockopt(conn
->sd
, IPPROTO_TCP
, TCP_NODELAY
, &val
,
931 switch (http_get_reply(conn
)) {
934 case HTTP_NOT_MODIFIED
:
937 case HTTP_MOVED_PERM
:
938 case HTTP_MOVED_TEMP
:
941 * Not so fine, but we still have to read the
942 * headers to get the new location.
948 * We already sent out authorization code,
949 * so there's nothing more we can do.
951 http_seterr(conn
->err
);
954 /* try again, but send the password this time */
956 fetch_info("server requires authorization");
958 case HTTP_NEED_PROXY_AUTH
:
960 * If we're talking to a proxy, we already sent
961 * our proxy authorization code, so there's
962 * nothing more we can do.
964 http_seterr(conn
->err
);
968 * This can happen if we ask for 0 bytes because
969 * we already have the whole file. Consider this
970 * a success for now, and check sizes later.
973 case HTTP_PROTOCOL_ERROR
:
979 http_seterr(conn
->err
);
982 /* fall through so we can get the full error message */
987 switch ((h
= http_next_header(conn
, &p
))) {
992 http_seterr(HTTP_PROTOCOL_ERROR
);
994 case hdr_content_length
:
995 http_parse_length(p
, &clength
);
997 case hdr_content_range
:
998 http_parse_range(p
, &offset
, &length
, &size
);
1000 case hdr_last_modified
:
1001 http_parse_mtime(p
, &mtime
);
1004 if (!HTTP_REDIRECT(conn
->err
))
1009 fetch_info("%d redirect to %s", conn
->err
, p
);
1012 new = fetchMakeURL(url
->scheme
, url
->host
, url
->port
, p
,
1013 url
->user
, url
->pwd
);
1015 new = fetchParseURL(p
);
1017 /* XXX should set an error code */
1020 if (!*new->user
&& !*new->pwd
) {
1021 strcpy(new->user
, url
->user
);
1022 strcpy(new->pwd
, url
->pwd
);
1024 new->offset
= url
->offset
;
1025 new->length
= url
->length
;
1027 case hdr_transfer_encoding
:
1029 chunked
= (strcasecmp(p
, "chunked") == 0);
1031 case hdr_www_authenticate
:
1032 if (conn
->err
!= HTTP_NEED_AUTH
)
1034 /* if we were smarter, we'd check the method and realm */
1042 } while (h
> hdr_end
);
1044 /* we need to provide authentication */
1045 if (conn
->err
== HTTP_NEED_AUTH
) {
1053 /* requested range not satisfiable */
1054 if (conn
->err
== HTTP_BAD_RANGE
) {
1055 if (url
->offset
== size
&& url
->length
== 0) {
1056 /* asked for 0 bytes; fake it */
1057 offset
= url
->offset
;
1058 conn
->err
= HTTP_OK
;
1061 http_seterr(conn
->err
);
1066 /* we have a hit or an error */
1067 if (conn
->err
== HTTP_OK
||
1068 conn
->err
== HTTP_PARTIAL
||
1069 conn
->err
== HTTP_NOT_MODIFIED
||
1070 HTTP_ERROR(conn
->err
))
1073 /* all other cases: we got a redirect */
1085 /* we failed, or ran out of retries */
1091 /* check for inconsistencies */
1092 if (clength
!= -1 && length
!= -1 && clength
!= length
) {
1093 http_seterr(HTTP_PROTOCOL_ERROR
);
1099 length
= offset
+ clength
;
1100 if (length
!= -1 && size
!= -1 && length
!= size
) {
1101 http_seterr(HTTP_PROTOCOL_ERROR
);
1110 us
->atime
= us
->mtime
= mtime
;
1114 if (URL
->offset
> 0 && offset
> URL
->offset
) {
1115 http_seterr(HTTP_PROTOCOL_ERROR
);
1119 /* report back real offset and size */
1120 URL
->offset
= offset
;
1121 URL
->length
= clength
;
1123 if (conn
->err
== HTTP_NOT_MODIFIED
) {
1124 http_seterr(HTTP_NOT_MODIFIED
);
1128 /* wrap it up in a fetchIO */
1129 if ((f
= http_funopen(conn
, chunked
)) == NULL
) {
1139 if (HTTP_ERROR(conn
->err
)) {
1157 /*****************************************************************************
1162 * Retrieve and stat a file by HTTP
1165 fetchXGetHTTP(struct url
*URL
, struct url_stat
*us
, const char *flags
)
1167 return (http_request(URL
, "GET", us
, http_get_proxy(URL
, flags
), flags
));
1171 * Retrieve a file by HTTP
1174 fetchGetHTTP(struct url
*URL
, const char *flags
)
1176 return (fetchXGetHTTP(URL
, NULL
, flags
));
1180 * Store a file by HTTP
1183 fetchPutHTTP(struct url
*URL
, const char *flags
)
1185 fprintf(stderr
, "fetchPutHTTP(): not implemented\n");
1190 * Get an HTTP document's metadata
1193 fetchStatHTTP(struct url
*URL
, struct url_stat
*us
, const char *flags
)
1197 f
= http_request(URL
, "HEAD", us
, http_get_proxy(URL
, flags
), flags
);
1220 struct index_parser
{
1221 struct url_list
*ue
;
1223 enum http_states state
;
1227 parse_index(struct index_parser
*parser
, const char *buf
, size_t len
)
1229 char *end_attr
, p
= *buf
;
1231 switch (parser
->state
) {
1233 /* Plain text, not in markup */
1235 parser
->state
= ST_LT
;
1238 /* In tag -- "<" already found */
1240 parser
->state
= ST_NONE
;
1241 else if (p
== 'a' || p
== 'A')
1242 parser
->state
= ST_LTA
;
1243 else if (!isspace((unsigned char)p
))
1244 parser
->state
= ST_TAG
;
1247 /* In tag -- "<a" already found */
1249 parser
->state
= ST_NONE
;
1251 parser
->state
= ST_TAGAQ
;
1252 else if (isspace((unsigned char)p
))
1253 parser
->state
= ST_TAGA
;
1255 parser
->state
= ST_TAG
;
1258 /* In tag, but not "<a" -- disregard */
1260 parser
->state
= ST_NONE
;
1263 /* In a-tag -- "<a " already found */
1265 parser
->state
= ST_NONE
;
1267 parser
->state
= ST_TAGAQ
;
1268 else if (p
== 'h' || p
== 'H')
1269 parser
->state
= ST_H
;
1270 else if (!isspace((unsigned char)p
))
1271 parser
->state
= ST_TAGAX
;
1274 /* In unknown keyword in a-tag */
1276 parser
->state
= ST_NONE
;
1278 parser
->state
= ST_TAGAQ
;
1279 else if (isspace((unsigned char)p
))
1280 parser
->state
= ST_TAGA
;
1283 /* In a-tag, unknown argument for keys. */
1285 parser
->state
= ST_NONE
;
1287 parser
->state
= ST_TAGA
;
1290 /* In a-tag -- "<a h" already found */
1292 parser
->state
= ST_NONE
;
1294 parser
->state
= ST_TAGAQ
;
1295 else if (p
== 'r' || p
== 'R')
1296 parser
->state
= ST_R
;
1297 else if (isspace((unsigned char)p
))
1298 parser
->state
= ST_TAGA
;
1300 parser
->state
= ST_TAGAX
;
1303 /* In a-tag -- "<a hr" already found */
1305 parser
->state
= ST_NONE
;
1307 parser
->state
= ST_TAGAQ
;
1308 else if (p
== 'e' || p
== 'E')
1309 parser
->state
= ST_E
;
1310 else if (isspace((unsigned char)p
))
1311 parser
->state
= ST_TAGA
;
1313 parser
->state
= ST_TAGAX
;
1316 /* In a-tag -- "<a hre" already found */
1318 parser
->state
= ST_NONE
;
1320 parser
->state
= ST_TAGAQ
;
1321 else if (p
== 'f' || p
== 'F')
1322 parser
->state
= ST_F
;
1323 else if (isspace((unsigned char)p
))
1324 parser
->state
= ST_TAGA
;
1326 parser
->state
= ST_TAGAX
;
1329 /* In a-tag -- "<a href" already found */
1331 parser
->state
= ST_NONE
;
1333 parser
->state
= ST_TAGAQ
;
1335 parser
->state
= ST_HREF
;
1336 else if (!isspace((unsigned char)p
))
1337 parser
->state
= ST_TAGAX
;
1340 /* In a-tag -- "<a href=" already found */
1342 parser
->state
= ST_NONE
;
1344 parser
->state
= ST_HREFQ
;
1345 else if (!isspace((unsigned char)p
))
1346 parser
->state
= ST_TAGA
;
1349 /* In href of the a-tag */
1350 end_attr
= memchr(buf
, '"', len
);
1351 if (end_attr
== NULL
)
1354 parser
->state
= ST_TAGA
;
1355 if (fetch_add_entry(parser
->ue
, parser
->url
, buf
, 1))
1357 return end_attr
+ 1 - buf
;
1362 struct http_index_cache
{
1363 struct http_index_cache
*next
;
1364 struct url
*location
;
1368 static struct http_index_cache
*index_cache
;
1374 fetchListHTTP(struct url_list
*ue
, struct url
*url
, const char *pattern
, const char *flags
)
1377 char buf
[2 * PATH_MAX
];
1378 size_t buf_len
, sum_processed
;
1379 ssize_t read_len
, processed
;
1380 struct index_parser state
;
1381 struct http_index_cache
*cache
= NULL
;
1384 do_cache
= CHECK_FLAG('c');
1387 for (cache
= index_cache
; cache
!= NULL
; cache
= cache
->next
) {
1388 if (strcmp(cache
->location
->scheme
, url
->scheme
))
1390 if (strcmp(cache
->location
->user
, url
->user
))
1392 if (strcmp(cache
->location
->pwd
, url
->pwd
))
1394 if (strcmp(cache
->location
->host
, url
->host
))
1396 if (cache
->location
->port
!= url
->port
)
1398 if (strcmp(cache
->location
->doc
, url
->doc
))
1400 return fetchAppendURLList(ue
, &cache
->ue
);
1403 cache
= malloc(sizeof(*cache
));
1404 fetchInitURLList(&cache
->ue
);
1405 cache
->location
= fetchCopyURL(url
);
1408 f
= fetchGetHTTP(url
, flags
);
1411 fetchFreeURLList(&cache
->ue
);
1412 fetchFreeURL(cache
->location
);
1419 state
.state
= ST_NONE
;
1421 state
.ue
= &cache
->ue
;
1428 while ((read_len
= fetchIO_read(f
, buf
+ buf_len
, sizeof(buf
) - buf_len
)) > 0) {
1429 buf_len
+= read_len
;
1432 processed
= parse_index(&state
, buf
+ sum_processed
, buf_len
);
1433 if (processed
== -1)
1435 buf_len
-= processed
;
1436 sum_processed
+= processed
;
1437 } while (processed
!= 0 && buf_len
> 0);
1438 if (processed
== -1) {
1442 memmove(buf
, buf
+ sum_processed
, buf_len
);
1447 ret
= read_len
< 0 ? -1 : 0;
1451 cache
->next
= index_cache
;
1452 index_cache
= cache
;
1455 if (fetchAppendURLList(ue
, &cache
->ue
))