2 * nanohttp.c: minimalist HTTP GET implementation to fetch external subsets.
3 * focuses on size, streamability, reentrancy and portability
5 * This is clearly not a general purpose HTTP implementation
6 * If you look for one, check:
7 * http://www.w3.org/Library/
9 * See Copyright for the status of this software.
18 #ifdef LIBXML_HTTP_ENABLED
27 #ifdef HAVE_SYS_TYPES_H
28 #include <sys/types.h>
30 #ifdef HAVE_SYS_SOCKET_H
31 #include <sys/socket.h>
33 #ifdef HAVE_NETINET_IN_H
34 #include <netinet/in.h>
36 #ifdef HAVE_ARPA_INET_H
37 #include <arpa/inet.h>
43 #ifdef HAVE_ARPA_NAMESER_H
44 #include <arpa/nameser.h>
54 #ifdef HAVE_SYS_TIME_H
58 #ifdef HAVE_SYS_SELECT_H
59 #include <sys/select.h>
77 #define XML_SOCKLEN_T unsigned int
80 #if defined(__MINGW32__) || defined(_WIN32_WCE)
84 #include <wsockcompat.h>
87 #define XML_SOCKLEN_T unsigned int
90 #include <libxml/globals.h>
91 #include <libxml/xmlerror.h>
92 #include <libxml/xmlmemory.h>
93 #include <libxml/parser.h> /* for xmlStr(n)casecmp() */
94 #include <libxml/nanohttp.h>
95 #include <libxml/globals.h>
96 #include <libxml/uri.h>
99 * A couple portability macros
102 #if !defined(__BEOS__) || defined(__HAIKU__)
103 #define closesocket(s) close(s)
106 #define INVALID_SOCKET (-1)
111 #define PF_INET AF_INET
115 #ifndef XML_SOCKLEN_T
116 #define XML_SOCKLEN_T unsigned int
121 #define xmlStrncasecmp(a, b, n) strncasecmp((char *)a, (char *)b, n)
122 #define xmlStrcasecmpi(a, b) strcasecmp((char *)a, (char *)b)
125 #define XML_NANO_HTTP_MAX_REDIR 10
127 #define XML_NANO_HTTP_CHUNK 4096
129 #define XML_NANO_HTTP_CLOSED 0
130 #define XML_NANO_HTTP_WRITE 1
131 #define XML_NANO_HTTP_READ 2
132 #define XML_NANO_HTTP_NONE 4
134 typedef struct xmlNanoHTTPCtxt {
135 char *protocol; /* the protocol name */
136 char *hostname; /* the host name */
137 int port; /* the port */
138 char *path; /* the path within the URL */
139 char *query; /* the query string */
140 SOCKET fd; /* the file descriptor for the socket */
141 int state; /* WRITE / READ / CLOSED */
142 char *out; /* buffer sent (zero terminated) */
143 char *outptr; /* index within the buffer sent */
144 char *in; /* the receiving buffer */
145 char *content; /* the start of the content */
146 char *inptr; /* the next byte to read from network */
147 char *inrptr; /* the next byte to give back to the client */
148 int inlen; /* len of the input buffer */
149 int last; /* return code for last operation */
150 int returnValue; /* the protocol return value */
151 int version; /* the protocol version */
152 int ContentLength; /* specified content length from HTTP header */
153 char *contentType; /* the MIME type for the input */
154 char *location; /* the new URL in case of redirect */
155 char *authHeader; /* contents of {WWW,Proxy}-Authenticate header */
156 char *encoding; /* encoding extracted from the contentType */
157 char *mimeType; /* Mime-Type extracted from the contentType */
159 z_stream *strm; /* Zlib stream object */
160 int usesGzip; /* "Content-Encoding: gzip" was detected */
162 } xmlNanoHTTPCtxt, *xmlNanoHTTPCtxtPtr;
164 static int initialized = 0;
165 static char *proxy = NULL; /* the proxy name if any */
166 static int proxyPort; /* the proxy port if any */
167 static unsigned int timeout = 60;/* the select() timeout in seconds */
169 static int xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len );
173 * @extra: extra informations
175 * Handle an out of memory condition
178 xmlHTTPErrMemory(const char *extra)
180 __xmlSimpleError(XML_FROM_HTTP, XML_ERR_NO_MEMORY, NULL, NULL, extra);
184 * A portability function
186 static int socket_errno(void) {
188 return(WSAGetLastError());
196 int have_ipv6(void) {
199 s = socket (AF_INET6, SOCK_STREAM, 0);
200 if (s != INVALID_SOCKET) {
211 * Initialize the HTTP protocol layer.
212 * Currently it just checks for proxy informations
216 xmlNanoHTTPInit(void) {
226 if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
232 env = getenv("no_proxy");
233 if (env && ((env[0] == '*') && (env[1] == 0)))
235 env = getenv("http_proxy");
237 xmlNanoHTTPScanProxy(env);
240 env = getenv("HTTP_PROXY");
242 xmlNanoHTTPScanProxy(env);
251 * xmlNanoHTTPCleanup:
253 * Cleanup the HTTP protocol layer.
257 xmlNanoHTTPCleanup(void) {
271 * xmlNanoHTTPScanURL:
272 * @ctxt: an HTTP context
273 * @URL: The URL used to initialize the context
275 * (Re)Initialize an HTTP context by parsing the URL and finding
276 * the protocol host port and path it indicates.
280 xmlNanoHTTPScanURL(xmlNanoHTTPCtxtPtr ctxt, const char *URL) {
283 * Clear any existing data from the context
285 if (ctxt->protocol != NULL) {
286 xmlFree(ctxt->protocol);
287 ctxt->protocol = NULL;
289 if (ctxt->hostname != NULL) {
290 xmlFree(ctxt->hostname);
291 ctxt->hostname = NULL;
293 if (ctxt->path != NULL) {
297 if (ctxt->query != NULL) {
298 xmlFree(ctxt->query);
301 if (URL == NULL) return;
303 uri = xmlParseURIRaw(URL, 1);
307 if ((uri->scheme == NULL) || (uri->server == NULL)) {
312 ctxt->protocol = xmlMemStrdup(uri->scheme);
313 ctxt->hostname = xmlMemStrdup(uri->server);
314 if (uri->path != NULL)
315 ctxt->path = xmlMemStrdup(uri->path);
317 ctxt->path = xmlMemStrdup("/");
318 if (uri->query != NULL)
319 ctxt->query = xmlMemStrdup(uri->query);
321 ctxt->port = uri->port;
327 * xmlNanoHTTPScanProxy:
328 * @URL: The proxy URL used to initialize the proxy context
330 * (Re)Initialize the HTTP Proxy context by parsing the URL and finding
331 * the protocol host port it indicates.
332 * Should be like http://myproxy/ or http://myproxy:3128/
333 * A NULL URL cleans up proxy informations.
337 xmlNanoHTTPScanProxy(const char *URL) {
348 xmlGenericError(xmlGenericErrorContext,
349 "Removing HTTP proxy info\n");
351 xmlGenericError(xmlGenericErrorContext,
352 "Using HTTP proxy %s\n", URL);
354 if (URL == NULL) return;
356 uri = xmlParseURIRaw(URL, 1);
357 if ((uri == NULL) || (uri->scheme == NULL) ||
358 (strcmp(uri->scheme, "http")) || (uri->server == NULL)) {
359 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_URL_SYNTAX, "Syntax Error\n");
365 proxy = xmlMemStrdup(uri->server);
367 proxyPort = uri->port;
373 * xmlNanoHTTPNewCtxt:
374 * @URL: The URL used to initialize the context
376 * Allocate and initialize a new HTTP context.
378 * Returns an HTTP context or NULL in case of error.
381 static xmlNanoHTTPCtxtPtr
382 xmlNanoHTTPNewCtxt(const char *URL) {
383 xmlNanoHTTPCtxtPtr ret;
385 ret = (xmlNanoHTTPCtxtPtr) xmlMalloc(sizeof(xmlNanoHTTPCtxt));
387 xmlHTTPErrMemory("allocating context");
391 memset(ret, 0, sizeof(xmlNanoHTTPCtxt));
393 ret->returnValue = 0;
394 ret->fd = INVALID_SOCKET;
395 ret->ContentLength = -1;
397 xmlNanoHTTPScanURL(ret, URL);
403 * xmlNanoHTTPFreeCtxt:
404 * @ctxt: an HTTP context
406 * Frees the context after closing the connection.
410 xmlNanoHTTPFreeCtxt(xmlNanoHTTPCtxtPtr ctxt) {
411 if (ctxt == NULL) return;
412 if (ctxt->hostname != NULL) xmlFree(ctxt->hostname);
413 if (ctxt->protocol != NULL) xmlFree(ctxt->protocol);
414 if (ctxt->path != NULL) xmlFree(ctxt->path);
415 if (ctxt->query != NULL) xmlFree(ctxt->query);
416 if (ctxt->out != NULL) xmlFree(ctxt->out);
417 if (ctxt->in != NULL) xmlFree(ctxt->in);
418 if (ctxt->contentType != NULL) xmlFree(ctxt->contentType);
419 if (ctxt->encoding != NULL) xmlFree(ctxt->encoding);
420 if (ctxt->mimeType != NULL) xmlFree(ctxt->mimeType);
421 if (ctxt->location != NULL) xmlFree(ctxt->location);
422 if (ctxt->authHeader != NULL) xmlFree(ctxt->authHeader);
424 if (ctxt->strm != NULL) {
425 inflateEnd(ctxt->strm);
430 ctxt->state = XML_NANO_HTTP_NONE;
431 if (ctxt->fd != INVALID_SOCKET) closesocket(ctxt->fd);
432 ctxt->fd = INVALID_SOCKET;
438 * @ctxt: an HTTP context
440 * Send the input needed to initiate the processing on the server side
441 * Returns number of bytes sent or -1 on error.
445 xmlNanoHTTPSend(xmlNanoHTTPCtxtPtr ctxt, const char *xmt_ptr, int outlen)
455 if ((ctxt->state & XML_NANO_HTTP_WRITE) && (xmt_ptr != NULL)) {
456 while (total_sent < outlen) {
457 int nsent = send(ctxt->fd, xmt_ptr + total_sent,
458 outlen - total_sent, 0);
462 else if ((nsent == -1) &&
463 #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
464 (socket_errno() != EAGAIN) &&
466 (socket_errno() != EWOULDBLOCK)) {
467 __xmlIOErr(XML_FROM_HTTP, 0, "send failed\n");
474 * Since non-blocking sockets are used, wait for
475 * socket to be writable or default timeout prior
480 if (ctxt->fd > FD_SETSIZE)
488 #pragma warning(push)
489 #pragma warning(disable: 4018)
491 FD_SET(ctxt->fd, &wfd);
495 (void) select(ctxt->fd + 1, NULL, &wfd, NULL, &tv);
499 (void) poll(&p, 1, timeout * 1000);
500 #endif /* !HAVE_POLL_H */
510 * @ctxt: an HTTP context
512 * Read information coming from the HTTP connection.
513 * This is a blocking call (but it blocks in select(), not read()).
515 * Returns the number of byte read or -1 in case of error.
519 xmlNanoHTTPRecv(xmlNanoHTTPCtxtPtr ctxt)
529 while (ctxt->state & XML_NANO_HTTP_READ) {
530 if (ctxt->in == NULL) {
531 ctxt->in = (char *) xmlMallocAtomic(65000 * sizeof(char));
532 if (ctxt->in == NULL) {
533 xmlHTTPErrMemory("allocating input");
538 ctxt->inptr = ctxt->content = ctxt->inrptr = ctxt->in;
540 if (ctxt->inrptr > ctxt->in + XML_NANO_HTTP_CHUNK) {
541 int delta = ctxt->inrptr - ctxt->in;
542 int len = ctxt->inptr - ctxt->inrptr;
544 memmove(ctxt->in, ctxt->inrptr, len);
545 ctxt->inrptr -= delta;
546 ctxt->content -= delta;
547 ctxt->inptr -= delta;
549 if ((ctxt->in + ctxt->inlen) < (ctxt->inptr + XML_NANO_HTTP_CHUNK)) {
550 int d_inptr = ctxt->inptr - ctxt->in;
551 int d_content = ctxt->content - ctxt->in;
552 int d_inrptr = ctxt->inrptr - ctxt->in;
553 char *tmp_ptr = ctxt->in;
556 ctxt->in = (char *) xmlRealloc(tmp_ptr, ctxt->inlen);
557 if (ctxt->in == NULL) {
558 xmlHTTPErrMemory("allocating input buffer");
563 ctxt->inptr = ctxt->in + d_inptr;
564 ctxt->content = ctxt->in + d_content;
565 ctxt->inrptr = ctxt->in + d_inrptr;
567 ctxt->last = recv(ctxt->fd, ctxt->inptr, XML_NANO_HTTP_CHUNK, 0);
568 if (ctxt->last > 0) {
569 ctxt->inptr += ctxt->last;
572 if (ctxt->last == 0) {
575 if (ctxt->last == -1) {
576 switch (socket_errno()) {
579 #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
589 __xmlIOErr(XML_FROM_HTTP, 0, "recv failed\n");
596 if ((poll(&p, 1, timeout * 1000) < 1)
602 #else /* !HAVE_POLL_H */
604 if (ctxt->fd > FD_SETSIZE)
613 #pragma warning(push)
614 #pragma warning(disable: 4018)
617 FD_SET(ctxt->fd, &rfd);
623 if ((select(ctxt->fd + 1, &rfd, NULL, NULL, &tv) < 1)
629 #endif /* !HAVE_POLL_H */
635 * xmlNanoHTTPReadLine:
636 * @ctxt: an HTTP context
638 * Read one line in the HTTP server output, usually for extracting
639 * the HTTP protocol informations from the answer header.
641 * Returns a newly allocated string with a copy of the line, or NULL
642 * which indicate the end of the input.
646 xmlNanoHTTPReadLine(xmlNanoHTTPCtxtPtr ctxt) {
651 while (bp - buf < 4095) {
652 if (ctxt->inrptr == ctxt->inptr) {
653 if ( (rc = xmlNanoHTTPRecv(ctxt)) == 0) {
658 return(xmlMemStrdup(buf));
660 else if ( rc == -1 ) {
664 *bp = *ctxt->inrptr++;
667 return(xmlMemStrdup(buf));
673 return(xmlMemStrdup(buf));
678 * xmlNanoHTTPScanAnswer:
679 * @ctxt: an HTTP context
680 * @line: an HTTP header line
682 * Try to extract useful informations from the server answer.
683 * We currently parse and process:
684 * - The HTTP revision/ return code
685 * - The Content-Type, Mime-Type and charset used
686 * - The Location for redirect processing.
688 * Returns -1 in case of failure, the file descriptor number otherwise
692 xmlNanoHTTPScanAnswer(xmlNanoHTTPCtxtPtr ctxt, const char *line) {
693 const char *cur = line;
695 if (line == NULL) return;
697 if (!strncmp(line, "HTTP/", 5)) {
702 while ((*cur >= '0') && (*cur <= '9')) {
704 version += *cur - '0';
709 if ((*cur >= '0') && (*cur <= '9')) {
711 version += *cur - '0';
714 while ((*cur >= '0') && (*cur <= '9'))
718 if ((*cur != ' ') && (*cur != '\t')) return;
719 while ((*cur == ' ') || (*cur == '\t')) cur++;
720 if ((*cur < '0') || (*cur > '9')) return;
721 while ((*cur >= '0') && (*cur <= '9')) {
726 if ((*cur != 0) && (*cur != ' ') && (*cur != '\t')) return;
727 ctxt->returnValue = ret;
728 ctxt->version = version;
729 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Content-Type:", 13)) {
730 const xmlChar *charset, *last, *mime;
732 while ((*cur == ' ') || (*cur == '\t')) cur++;
733 if (ctxt->contentType != NULL)
734 xmlFree(ctxt->contentType);
735 ctxt->contentType = xmlMemStrdup(cur);
736 mime = (const xmlChar *) cur;
738 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
739 (*last != ';') && (*last != ','))
741 if (ctxt->mimeType != NULL)
742 xmlFree(ctxt->mimeType);
743 ctxt->mimeType = (char *) xmlStrndup(mime, last - mime);
744 charset = xmlStrstr(BAD_CAST ctxt->contentType, BAD_CAST "charset=");
745 if (charset != NULL) {
748 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
749 (*last != ';') && (*last != ','))
751 if (ctxt->encoding != NULL)
752 xmlFree(ctxt->encoding);
753 ctxt->encoding = (char *) xmlStrndup(charset, last - charset);
755 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"ContentType:", 12)) {
756 const xmlChar *charset, *last, *mime;
758 if (ctxt->contentType != NULL) return;
759 while ((*cur == ' ') || (*cur == '\t')) cur++;
760 ctxt->contentType = xmlMemStrdup(cur);
761 mime = (const xmlChar *) cur;
763 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
764 (*last != ';') && (*last != ','))
766 if (ctxt->mimeType != NULL)
767 xmlFree(ctxt->mimeType);
768 ctxt->mimeType = (char *) xmlStrndup(mime, last - mime);
769 charset = xmlStrstr(BAD_CAST ctxt->contentType, BAD_CAST "charset=");
770 if (charset != NULL) {
773 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
774 (*last != ';') && (*last != ','))
776 if (ctxt->encoding != NULL)
777 xmlFree(ctxt->encoding);
778 ctxt->encoding = (char *) xmlStrndup(charset, last - charset);
780 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Location:", 9)) {
782 while ((*cur == ' ') || (*cur == '\t')) cur++;
783 if (ctxt->location != NULL)
784 xmlFree(ctxt->location);
786 xmlChar *tmp_http = xmlStrdup(BAD_CAST "http://");
788 xmlStrcat(tmp_http, (const xmlChar *) ctxt->hostname);
790 (char *) xmlStrcat (tmp_loc, (const xmlChar *) cur);
792 ctxt->location = xmlMemStrdup(cur);
794 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"WWW-Authenticate:", 17)) {
796 while ((*cur == ' ') || (*cur == '\t')) cur++;
797 if (ctxt->authHeader != NULL)
798 xmlFree(ctxt->authHeader);
799 ctxt->authHeader = xmlMemStrdup(cur);
800 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Proxy-Authenticate:", 19)) {
802 while ((*cur == ' ') || (*cur == '\t')) cur++;
803 if (ctxt->authHeader != NULL)
804 xmlFree(ctxt->authHeader);
805 ctxt->authHeader = xmlMemStrdup(cur);
807 } else if ( !xmlStrncasecmp( BAD_CAST line, BAD_CAST"Content-Encoding:", 17) ) {
809 while ((*cur == ' ') || (*cur == '\t')) cur++;
810 if ( !xmlStrncasecmp( BAD_CAST cur, BAD_CAST"gzip", 4) ) {
813 ctxt->strm = xmlMalloc(sizeof(z_stream));
815 if (ctxt->strm != NULL) {
816 ctxt->strm->zalloc = Z_NULL;
817 ctxt->strm->zfree = Z_NULL;
818 ctxt->strm->opaque = Z_NULL;
819 ctxt->strm->avail_in = 0;
820 ctxt->strm->next_in = Z_NULL;
822 inflateInit2( ctxt->strm, 31 );
826 } else if ( !xmlStrncasecmp( BAD_CAST line, BAD_CAST"Content-Length:", 15) ) {
828 ctxt->ContentLength = strtol( cur, NULL, 10 );
833 * xmlNanoHTTPConnectAttempt:
834 * @addr: a socket address structure
836 * Attempt a connection to the given IP:port endpoint. It forces
837 * non-blocking semantic on the socket, and allow 60 seconds for
838 * the host to answer.
840 * Returns -1 in case of failure, the file descriptor number otherwise
844 xmlNanoHTTPConnectAttempt(struct sockaddr *addr)
852 #else /* !HAVE_POLL_H */
854 #endif /* !HAVE_POLL_H */
862 if (addr->sa_family == AF_INET6) {
863 s = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
864 addrlen = sizeof(struct sockaddr_in6);
868 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
869 addrlen = sizeof(struct sockaddr_in);
871 if (s == INVALID_SOCKET) {
875 __xmlIOErr(XML_FROM_HTTP, 0, "socket failed\n");
876 return INVALID_SOCKET;
882 status = ioctlsocket(s, FIONBIO, &one) == SOCKET_ERROR ? -1 : 0;
884 #else /* _WINSOCKAPI_ */
889 status = ioctl(s, FIONBIO, &enable);
892 #if defined(__BEOS__) && !defined(__HAIKU__)
897 setsockopt(s, SOL_SOCKET, SO_NONBLOCK, &noblock,
901 if ((status = fcntl(s, F_GETFL, 0)) != -1) {
903 status |= O_NONBLOCK;
904 #else /* O_NONBLOCK */
907 #endif /* F_NDELAY */
908 #endif /* !O_NONBLOCK */
909 status = fcntl(s, F_SETFL, status);
913 perror("nonblocking");
915 __xmlIOErr(XML_FROM_HTTP, 0, "error setting non-blocking IO\n");
917 return INVALID_SOCKET;
919 #endif /* !__BEOS__ */
921 #endif /* !_WINSOCKAPI_ */
923 if (connect(s, addr, addrlen) == -1) {
924 switch (socket_errno()) {
929 __xmlIOErr(XML_FROM_HTTP, 0,
930 "error connecting to HTTP server");
932 return INVALID_SOCKET;
940 #pragma warning(push)
941 #pragma warning(disable: 4018)
945 return INVALID_SOCKET;
954 switch (select(s + 1, NULL, &wfd, &xfd, &tv))
956 switch (select(s + 1, NULL, &wfd, NULL, &tv))
962 #else /* !HAVE_POLL_H */
965 switch (poll(&p, 1, timeout * 1000))
966 #endif /* !HAVE_POLL_H */
971 __xmlIOErr(XML_FROM_HTTP, 0, "Connect attempt timed out");
973 return INVALID_SOCKET;
976 __xmlIOErr(XML_FROM_HTTP, 0, "Connect failed");
978 return INVALID_SOCKET;
982 if (FD_ISSET(s, &wfd)
987 #else /* !HAVE_POLL_H */
988 if (p.revents == POLLOUT)
989 #endif /* !HAVE_POLL_H */
993 len = sizeof(status);
995 if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char *) &status, &len) <
997 /* Solaris error code */
998 __xmlIOErr(XML_FROM_HTTP, 0, "getsockopt failed\n");
999 return INVALID_SOCKET;
1003 __xmlIOErr(XML_FROM_HTTP, 0,
1004 "Error connecting to remote host");
1007 return INVALID_SOCKET;
1011 __xmlIOErr(XML_FROM_HTTP, 0, "select failed\n");
1013 return INVALID_SOCKET;
1020 * xmlNanoHTTPConnectHost:
1021 * @host: the host name
1022 * @port: the port number
1024 * Attempt a connection to the given host:port endpoint. It tries
1025 * the multiple IP provided by the DNS if available.
1027 * Returns -1 in case of failure, the file descriptor number otherwise
1031 xmlNanoHTTPConnectHost(const char *host, int port)
1034 struct sockaddr *addr = NULL;
1036 struct sockaddr_in sockin;
1039 struct in6_addr ia6;
1040 struct sockaddr_in6 sockin6;
1045 memset (&sockin, 0, sizeof(sockin));
1047 memset (&sockin6, 0, sizeof(sockin6));
1050 #if !defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && defined(RES_USE_INET6)
1053 if (!(_res.options & RES_INIT))
1055 _res.options |= RES_USE_INET6;
1059 #if defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && !defined(_WIN32)
1062 #if defined(HAVE_GETADDRINFO) && (defined(SUPPORT_IP6) || defined(_WIN32))
1065 struct addrinfo hints, *res, *result;
1068 memset (&hints, 0,sizeof(hints));
1069 hints.ai_socktype = SOCK_STREAM;
1071 status = getaddrinfo (host, NULL, &hints, &result);
1073 __xmlIOErr(XML_FROM_HTTP, 0, "getaddrinfo failed\n");
1074 return INVALID_SOCKET;
1077 for (res = result; res; res = res->ai_next) {
1078 if (res->ai_family == AF_INET) {
1079 if (res->ai_addrlen > sizeof(sockin)) {
1080 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1081 freeaddrinfo (result);
1082 return INVALID_SOCKET;
1084 memcpy (&sockin, res->ai_addr, res->ai_addrlen);
1085 sockin.sin_port = htons (port);
1086 addr = (struct sockaddr *)&sockin;
1088 } else if (have_ipv6 () && (res->ai_family == AF_INET6)) {
1089 if (res->ai_addrlen > sizeof(sockin6)) {
1090 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1091 freeaddrinfo (result);
1092 return INVALID_SOCKET;
1094 memcpy (&sockin6, res->ai_addr, res->ai_addrlen);
1095 sockin6.sin6_port = htons (port);
1096 addr = (struct sockaddr *)&sockin6;
1101 s = xmlNanoHTTPConnectAttempt (addr);
1102 if (s != INVALID_SOCKET) {
1103 freeaddrinfo (result);
1109 freeaddrinfo (result);
1112 #if defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && !defined(_WIN32)
1115 #if !defined(HAVE_GETADDRINFO) || !defined(_WIN32)
1117 h = gethostbyname (host);
1121 * Okay, I got fed up by the non-portability of this error message
1122 * extraction code. it work on Linux, if it work on your platform
1123 * and one want to enable it, send me the defined(foobar) needed
1125 #if defined(HAVE_NETDB_H) && defined(HOST_NOT_FOUND) && defined(linux)
1126 const char *h_err_txt = "";
1129 case HOST_NOT_FOUND:
1130 h_err_txt = "Authoritive host not found";
1135 "Non-authoritive host not found or server failure.";
1140 "Non-recoverable errors: FORMERR, REFUSED, or NOTIMP.";
1145 "Valid name, no data record of requested type.";
1149 h_err_txt = "No error text defined.";
1152 __xmlIOErr(XML_FROM_HTTP, 0, h_err_txt);
1154 __xmlIOErr(XML_FROM_HTTP, 0, "Failed to resolve host");
1156 return INVALID_SOCKET;
1159 for (i = 0; h->h_addr_list[i]; i++) {
1160 if (h->h_addrtype == AF_INET) {
1161 /* A records (IPv4) */
1162 if ((unsigned int) h->h_length > sizeof(ia)) {
1163 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1164 return INVALID_SOCKET;
1166 memcpy (&ia, h->h_addr_list[i], h->h_length);
1167 sockin.sin_family = h->h_addrtype;
1168 sockin.sin_addr = ia;
1169 sockin.sin_port = (u_short)htons ((unsigned short)port);
1170 addr = (struct sockaddr *) &sockin;
1172 } else if (have_ipv6 () && (h->h_addrtype == AF_INET6)) {
1173 /* AAAA records (IPv6) */
1174 if ((unsigned int) h->h_length > sizeof(ia6)) {
1175 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1176 return INVALID_SOCKET;
1178 memcpy (&ia6, h->h_addr_list[i], h->h_length);
1179 sockin6.sin6_family = h->h_addrtype;
1180 sockin6.sin6_addr = ia6;
1181 sockin6.sin6_port = htons (port);
1182 addr = (struct sockaddr *) &sockin6;
1187 s = xmlNanoHTTPConnectAttempt (addr);
1188 if (s != INVALID_SOCKET)
1195 xmlGenericError(xmlGenericErrorContext,
1196 "xmlNanoHTTPConnectHost: unable to connect to '%s'.\n",
1199 return INVALID_SOCKET;
1205 * @URL: The URL to load
1206 * @contentType: if available the Content-Type information will be
1207 * returned at that location
1209 * This function try to open a connection to the indicated resource
1212 * Returns NULL in case of failure, otherwise a request handler.
1213 * The contentType, if provided must be freed by the caller
1217 xmlNanoHTTPOpen(const char *URL, char **contentType) {
1218 if (contentType != NULL) *contentType = NULL;
1219 return(xmlNanoHTTPMethod(URL, NULL, NULL, contentType, NULL, 0));
1223 * xmlNanoHTTPOpenRedir:
1224 * @URL: The URL to load
1225 * @contentType: if available the Content-Type information will be
1226 * returned at that location
1227 * @redir: if available the redirected URL will be returned
1229 * This function try to open a connection to the indicated resource
1232 * Returns NULL in case of failure, otherwise a request handler.
1233 * The contentType, if provided must be freed by the caller
1237 xmlNanoHTTPOpenRedir(const char *URL, char **contentType, char **redir) {
1238 if (contentType != NULL) *contentType = NULL;
1239 if (redir != NULL) *redir = NULL;
1240 return(xmlNanoHTTPMethodRedir(URL, NULL, NULL, contentType, redir, NULL,0));
1245 * @ctx: the HTTP context
1247 * @len: the buffer length
1249 * This function tries to read @len bytes from the existing HTTP connection
1250 * and saves them in @dest. This is a blocking call.
1252 * Returns the number of byte read. 0 is an indication of an end of connection.
1253 * -1 indicates a parameter error.
1256 xmlNanoHTTPRead(void *ctx, void *dest, int len) {
1257 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1264 if (ctx == NULL) return(-1);
1265 if (dest == NULL) return(-1);
1266 if (len <= 0) return(0);
1269 if (ctxt->usesGzip == 1) {
1270 if (ctxt->strm == NULL) return(0);
1272 ctxt->strm->next_out = dest;
1273 ctxt->strm->avail_out = len;
1274 ctxt->strm->avail_in = ctxt->inptr - ctxt->inrptr;
1276 while (ctxt->strm->avail_out > 0 &&
1277 (ctxt->strm->avail_in > 0 || xmlNanoHTTPRecv(ctxt) > 0)) {
1278 orig_avail_in = ctxt->strm->avail_in =
1279 ctxt->inptr - ctxt->inrptr - bytes_read;
1280 ctxt->strm->next_in = BAD_CAST (ctxt->inrptr + bytes_read);
1282 z_ret = inflate(ctxt->strm, Z_NO_FLUSH);
1283 bytes_read += orig_avail_in - ctxt->strm->avail_in;
1285 if (z_ret != Z_OK) break;
1288 ctxt->inrptr += bytes_read;
1289 return(len - ctxt->strm->avail_out);
1293 while (ctxt->inptr - ctxt->inrptr < len) {
1294 if (xmlNanoHTTPRecv(ctxt) <= 0) break;
1296 if (ctxt->inptr - ctxt->inrptr < len)
1297 len = ctxt->inptr - ctxt->inrptr;
1298 memcpy(dest, ctxt->inrptr, len);
1299 ctxt->inrptr += len;
1305 * @ctx: the HTTP context
1307 * This function closes an HTTP context, it ends up the connection and
1308 * free all data related to it.
1311 xmlNanoHTTPClose(void *ctx) {
1312 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1314 if (ctx == NULL) return;
1316 xmlNanoHTTPFreeCtxt(ctxt);
1320 * xmlNanoHTTPMethodRedir:
1321 * @URL: The URL to load
1322 * @method: the HTTP method to use
1323 * @input: the input string if any
1324 * @contentType: the Content-Type information IN and OUT
1325 * @redir: the redirected URL OUT
1326 * @headers: the extra headers
1327 * @ilen: input length
1329 * This function try to open a connection to the indicated resource
1330 * via HTTP using the given @method, adding the given extra headers
1331 * and the input buffer for the request content.
1333 * Returns NULL in case of failure, otherwise a request handler.
1334 * The contentType, or redir, if provided must be freed by the caller
1338 xmlNanoHTTPMethodRedir(const char *URL, const char *method, const char *input,
1339 char **contentType, char **redir,
1340 const char *headers, int ilen ) {
1341 xmlNanoHTTPCtxtPtr ctxt;
1345 int nbRedirects = 0;
1346 char *redirURL = NULL;
1351 if (URL == NULL) return(NULL);
1352 if (method == NULL) method = "GET";
1356 if (redirURL == NULL)
1357 ctxt = xmlNanoHTTPNewCtxt(URL);
1359 ctxt = xmlNanoHTTPNewCtxt(redirURL);
1360 ctxt->location = xmlMemStrdup(redirURL);
1363 if ( ctxt == NULL ) {
1367 if ((ctxt->protocol == NULL) || (strcmp(ctxt->protocol, "http"))) {
1368 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_URL_SYNTAX, "Not a valid HTTP URI");
1369 xmlNanoHTTPFreeCtxt(ctxt);
1370 if (redirURL != NULL) xmlFree(redirURL);
1373 if (ctxt->hostname == NULL) {
1374 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_UNKNOWN_HOST,
1375 "Failed to identify host in URI");
1376 xmlNanoHTTPFreeCtxt(ctxt);
1377 if (redirURL != NULL) xmlFree(redirURL);
1381 blen = strlen(ctxt->hostname) * 2 + 16;
1382 ret = xmlNanoHTTPConnectHost(proxy, proxyPort);
1385 blen = strlen(ctxt->hostname);
1386 ret = xmlNanoHTTPConnectHost(ctxt->hostname, ctxt->port);
1388 if (ret == INVALID_SOCKET) {
1389 xmlNanoHTTPFreeCtxt(ctxt);
1390 if (redirURL != NULL) xmlFree(redirURL);
1400 if (headers != NULL)
1401 blen += strlen(headers) + 2;
1402 if (contentType && *contentType)
1403 /* reserve for string plus 'Content-Type: \r\n" */
1404 blen += strlen(*contentType) + 16;
1405 if (ctxt->query != NULL)
1407 blen += strlen(ctxt->query) + 1;
1408 blen += strlen(method) + strlen(ctxt->path) + 24;
1410 /* reserve for possible 'Accept-Encoding: gzip' string */
1413 if (ctxt->port != 80) {
1414 /* reserve space for ':xxxxx', incl. potential proxy */
1420 bp = (char*)xmlMallocAtomic(blen);
1422 xmlNanoHTTPFreeCtxt( ctxt );
1423 xmlHTTPErrMemory("allocating header buffer");
1430 if (ctxt->port != 80) {
1431 p += snprintf( p, blen - (p - bp), "%s http://%s:%d%s",
1432 method, ctxt->hostname,
1433 ctxt->port, ctxt->path );
1436 p += snprintf( p, blen - (p - bp), "%s http://%s%s", method,
1437 ctxt->hostname, ctxt->path);
1440 p += snprintf( p, blen - (p - bp), "%s %s", method, ctxt->path);
1442 if (ctxt->query != NULL)
1443 p += snprintf( p, blen - (p - bp), "?%s", ctxt->query);
1445 if (ctxt->port == 80) {
1446 p += snprintf( p, blen - (p - bp), " HTTP/1.0\r\nHost: %s\r\n",
1449 p += snprintf( p, blen - (p - bp), " HTTP/1.0\r\nHost: %s:%d\r\n",
1450 ctxt->hostname, ctxt->port);
1454 p += snprintf(p, blen - (p - bp), "Accept-Encoding: gzip\r\n");
1457 if (contentType != NULL && *contentType)
1458 p += snprintf(p, blen - (p - bp), "Content-Type: %s\r\n", *contentType);
1460 if (headers != NULL)
1461 p += snprintf( p, blen - (p - bp), "%s", headers );
1464 snprintf(p, blen - (p - bp), "Content-Length: %d\r\n\r\n", ilen );
1466 snprintf(p, blen - (p - bp), "\r\n");
1469 xmlGenericError(xmlGenericErrorContext,
1470 "-> %s%s", proxy? "(Proxy) " : "", bp);
1471 if ((blen -= strlen(bp)+1) < 0)
1472 xmlGenericError(xmlGenericErrorContext,
1473 "ERROR: overflowed buffer by %d bytes\n", -blen);
1475 ctxt->outptr = ctxt->out = bp;
1476 ctxt->state = XML_NANO_HTTP_WRITE;
1477 blen = strlen( ctxt->out );
1479 xmt_bytes = xmlNanoHTTPSend(ctxt, ctxt->out, blen );
1480 if ( xmt_bytes != blen )
1481 xmlGenericError( xmlGenericErrorContext,
1482 "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n",
1484 "bytes of HTTP headers sent to host",
1487 xmlNanoHTTPSend(ctxt, ctxt->out, blen );
1490 if ( input != NULL ) {
1492 xmt_bytes = xmlNanoHTTPSend( ctxt, input, ilen );
1494 if ( xmt_bytes != ilen )
1495 xmlGenericError( xmlGenericErrorContext,
1496 "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n",
1498 "bytes of HTTP content sent to host",
1501 xmlNanoHTTPSend( ctxt, input, ilen );
1505 ctxt->state = XML_NANO_HTTP_READ;
1507 while ((p = xmlNanoHTTPReadLine(ctxt)) != NULL) {
1509 ctxt->content = ctxt->inrptr;
1513 xmlNanoHTTPScanAnswer(ctxt, p);
1516 xmlGenericError(xmlGenericErrorContext, "<- %s\n", p);
1521 if ((ctxt->location != NULL) && (ctxt->returnValue >= 300) &&
1522 (ctxt->returnValue < 400)) {
1524 xmlGenericError(xmlGenericErrorContext,
1525 "\nRedirect to: %s\n", ctxt->location);
1527 while ( xmlNanoHTTPRecv(ctxt) > 0 ) ;
1528 if (nbRedirects < XML_NANO_HTTP_MAX_REDIR) {
1530 if (redirURL != NULL)
1532 redirURL = xmlMemStrdup(ctxt->location);
1533 xmlNanoHTTPFreeCtxt(ctxt);
1536 xmlNanoHTTPFreeCtxt(ctxt);
1537 if (redirURL != NULL) xmlFree(redirURL);
1539 xmlGenericError(xmlGenericErrorContext,
1540 "xmlNanoHTTPMethodRedir: Too many redirects, aborting ...\n");
1545 if (contentType != NULL) {
1546 if (ctxt->contentType != NULL)
1547 *contentType = xmlMemStrdup(ctxt->contentType);
1549 *contentType = NULL;
1552 if ((redir != NULL) && (redirURL != NULL)) {
1555 if (redirURL != NULL)
1562 if (ctxt->contentType != NULL)
1563 xmlGenericError(xmlGenericErrorContext,
1564 "\nCode %d, content-type '%s'\n\n",
1565 ctxt->returnValue, ctxt->contentType);
1567 xmlGenericError(xmlGenericErrorContext,
1568 "\nCode %d, no content-type\n\n",
1572 return((void *) ctxt);
1576 * xmlNanoHTTPMethod:
1577 * @URL: The URL to load
1578 * @method: the HTTP method to use
1579 * @input: the input string if any
1580 * @contentType: the Content-Type information IN and OUT
1581 * @headers: the extra headers
1582 * @ilen: input length
1584 * This function try to open a connection to the indicated resource
1585 * via HTTP using the given @method, adding the given extra headers
1586 * and the input buffer for the request content.
1588 * Returns NULL in case of failure, otherwise a request handler.
1589 * The contentType, if provided must be freed by the caller
1593 xmlNanoHTTPMethod(const char *URL, const char *method, const char *input,
1594 char **contentType, const char *headers, int ilen) {
1595 return(xmlNanoHTTPMethodRedir(URL, method, input, contentType,
1596 NULL, headers, ilen));
1601 * @URL: The URL to load
1602 * @filename: the filename where the content should be saved
1603 * @contentType: if available the Content-Type information will be
1604 * returned at that location
1606 * This function try to fetch the indicated resource via HTTP GET
1607 * and save it's content in the file.
1609 * Returns -1 in case of failure, 0 incase of success. The contentType,
1610 * if provided must be freed by the caller
1613 xmlNanoHTTPFetch(const char *URL, const char *filename, char **contentType) {
1619 if (filename == NULL) return(-1);
1620 ctxt = xmlNanoHTTPOpen(URL, contentType);
1621 if (ctxt == NULL) return(-1);
1623 if (!strcmp(filename, "-"))
1626 fd = open(filename, O_CREAT | O_WRONLY, 00644);
1628 xmlNanoHTTPClose(ctxt);
1629 if ((contentType != NULL) && (*contentType != NULL)) {
1630 xmlFree(*contentType);
1631 *contentType = NULL;
1637 xmlNanoHTTPFetchContent( ctxt, &buf, &len );
1639 write(fd, buf, len);
1642 xmlNanoHTTPClose(ctxt);
1647 #ifdef LIBXML_OUTPUT_ENABLED
1650 * @ctxt: the HTTP context
1651 * @filename: the filename where the content should be saved
1653 * This function saves the output of the HTTP transaction to a file
1654 * It closes and free the context at the end
1656 * Returns -1 in case of failure, 0 incase of success.
1659 xmlNanoHTTPSave(void *ctxt, const char *filename) {
1664 if ((ctxt == NULL) || (filename == NULL)) return(-1);
1666 if (!strcmp(filename, "-"))
1669 fd = open(filename, O_CREAT | O_WRONLY, 0666);
1671 xmlNanoHTTPClose(ctxt);
1676 xmlNanoHTTPFetchContent( ctxt, &buf, &len );
1678 write(fd, buf, len);
1681 xmlNanoHTTPClose(ctxt);
1685 #endif /* LIBXML_OUTPUT_ENABLED */
1688 * xmlNanoHTTPReturnCode:
1689 * @ctx: the HTTP context
1691 * Get the latest HTTP return code received
1693 * Returns the HTTP return code for the request.
1696 xmlNanoHTTPReturnCode(void *ctx) {
1697 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1699 if (ctxt == NULL) return(-1);
1701 return(ctxt->returnValue);
1705 * xmlNanoHTTPAuthHeader:
1706 * @ctx: the HTTP context
1708 * Get the authentication header of an HTTP context
1710 * Returns the stashed value of the WWW-Authenticate or Proxy-Authenticate
1714 xmlNanoHTTPAuthHeader(void *ctx) {
1715 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1717 if (ctxt == NULL) return(NULL);
1719 return(ctxt->authHeader);
1723 * xmlNanoHTTPContentLength:
1724 * @ctx: the HTTP context
1726 * Provides the specified content length from the HTTP header.
1728 * Return the specified content length from the HTTP header. Note that
1729 * a value of -1 indicates that the content length element was not included in
1730 * the response header.
1733 xmlNanoHTTPContentLength( void * ctx ) {
1734 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1736 return ( ( ctxt == NULL ) ? -1 : ctxt->ContentLength );
1741 * @ctx: the HTTP context
1743 * Provides the specified redirection URL if available from the HTTP header.
1745 * Return the specified redirection URL or NULL if not redirected.
1748 xmlNanoHTTPRedir( void * ctx ) {
1749 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1751 return ( ( ctxt == NULL ) ? NULL : ctxt->location );
1755 * xmlNanoHTTPEncoding:
1756 * @ctx: the HTTP context
1758 * Provides the specified encoding if specified in the HTTP headers.
1760 * Return the specified encoding or NULL if not available
1763 xmlNanoHTTPEncoding( void * ctx ) {
1764 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1766 return ( ( ctxt == NULL ) ? NULL : ctxt->encoding );
1770 * xmlNanoHTTPMimeType:
1771 * @ctx: the HTTP context
1773 * Provides the specified Mime-Type if specified in the HTTP headers.
1775 * Return the specified Mime-Type or NULL if not available
1778 xmlNanoHTTPMimeType( void * ctx ) {
1779 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1781 return ( ( ctxt == NULL ) ? NULL : ctxt->mimeType );
1785 * xmlNanoHTTPFetchContent:
1786 * @ctx: the HTTP context
1787 * @ptr: pointer to set to the content buffer.
1788 * @len: integer pointer to hold the length of the content
1790 * Check if all the content was read
1792 * Returns 0 if all the content was read and available, returns
1793 * -1 if received content length was less than specified or an error
1797 xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len ) {
1798 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1804 char * dummy_ptr = NULL;
1806 /* Dummy up return input parameters if not provided */
1814 /* But can't work without the context pointer */
1816 if ( ( ctxt == NULL ) || ( ctxt->content == NULL ) ) {
1822 rcvd_lgth = ctxt->inptr - ctxt->content;
1824 while ( (cur_lgth = xmlNanoHTTPRecv( ctxt )) > 0 ) {
1826 rcvd_lgth += cur_lgth;
1827 if ( (ctxt->ContentLength > 0) && (rcvd_lgth >= ctxt->ContentLength) )
1831 *ptr = ctxt->content;
1834 if ( ( ctxt->ContentLength > 0 ) && ( rcvd_lgth < ctxt->ContentLength ) )
1836 else if ( rcvd_lgth == 0 )
1843 int main(int argc, char **argv) {
1844 char *contentType = NULL;
1846 if (argv[1] != NULL) {
1847 if (argv[2] != NULL)
1848 xmlNanoHTTPFetch(argv[1], argv[2], &contentType);
1850 xmlNanoHTTPFetch(argv[1], "-", &contentType);
1851 if (contentType != NULL) xmlFree(contentType);
1853 xmlGenericError(xmlGenericErrorContext,
1854 "%s: minimal HTTP GET implementation\n", argv[0]);
1855 xmlGenericError(xmlGenericErrorContext,
1856 "\tusage %s [ URL [ filename ] ]\n", argv[0]);
1858 xmlNanoHTTPCleanup();
1862 #endif /* STANDALONE */
1863 #else /* !LIBXML_HTTP_ENABLED */
1866 int main(int argc, char **argv) {
1867 xmlGenericError(xmlGenericErrorContext,
1868 "%s : HTTP support not compiled in\n", argv[0]);
1871 #endif /* STANDALONE */
1872 #endif /* LIBXML_HTTP_ENABLED */
1873 #define bottom_nanohttp
1874 #include "elfgcchack.h"