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
57 #ifdef HAVE_SYS_SELECT_H
58 #include <sys/select.h>
73 #define XML_SOCKLEN_T unsigned int
80 #include <wsockcompat.h>
83 #define XML_SOCKLEN_T unsigned int
87 #include <libxml/globals.h>
88 #include <libxml/xmlerror.h>
89 #include <libxml/xmlmemory.h>
90 #include <libxml/parser.h> /* for xmlStr(n)casecmp() */
91 #include <libxml/nanohttp.h>
92 #include <libxml/globals.h>
93 #include <libxml/uri.h>
96 * A couple portability macros
100 #define closesocket(s) close(s)
107 #define PF_INET AF_INET
111 #ifndef XML_SOCKLEN_T
112 #define XML_SOCKLEN_T unsigned int
120 #define xmlStrncasecmp(a, b, n) strncasecmp((char *)a, (char *)b, n)
121 #define xmlStrcasecmpi(a, b) strcasecmp((char *)a, (char *)b)
124 #define XML_NANO_HTTP_MAX_REDIR 10
126 #define XML_NANO_HTTP_CHUNK 4096
128 #define XML_NANO_HTTP_CLOSED 0
129 #define XML_NANO_HTTP_WRITE 1
130 #define XML_NANO_HTTP_READ 2
131 #define XML_NANO_HTTP_NONE 4
133 typedef struct xmlNanoHTTPCtxt {
134 char *protocol; /* the protocol name */
135 char *hostname; /* the host name */
136 int port; /* the port */
137 char *path; /* the path within the URL */
138 char *query; /* the query string */
139 SOCKET fd; /* the file descriptor for the socket */
140 int state; /* WRITE / READ / CLOSED */
141 char *out; /* buffer sent (zero terminated) */
142 char *outptr; /* index within the buffer sent */
143 char *in; /* the receiving buffer */
144 char *content; /* the start of the content */
145 char *inptr; /* the next byte to read from network */
146 char *inrptr; /* the next byte to give back to the client */
147 int inlen; /* len of the input buffer */
148 int last; /* return code for last operation */
149 int returnValue; /* the protocol return value */
150 int ContentLength; /* specified content length from HTTP header */
151 char *contentType; /* the MIME type for the input */
152 char *location; /* the new URL in case of redirect */
153 char *authHeader; /* contents of {WWW,Proxy}-Authenticate header */
154 char *encoding; /* encoding extracted from the contentType */
155 char *mimeType; /* Mime-Type extracted from the contentType */
157 z_stream *strm; /* Zlib stream object */
158 int usesGzip; /* "Content-Encoding: gzip" was detected */
160 } xmlNanoHTTPCtxt, *xmlNanoHTTPCtxtPtr;
162 static int initialized = 0;
163 static char *proxy = NULL; /* the proxy name if any */
164 static int proxyPort; /* the proxy port if any */
165 static unsigned int timeout = 60;/* the select() timeout in seconds */
167 static int xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len );
171 * @extra: extra informations
173 * Handle an out of memory condition
176 xmlHTTPErrMemory(const char *extra)
178 __xmlSimpleError(XML_FROM_HTTP, XML_ERR_NO_MEMORY, NULL, NULL, extra);
182 * A portability function
184 static int socket_errno(void) {
186 return(WSAGetLastError());
194 int have_ipv6(void) {
197 s = socket (AF_INET6, SOCK_STREAM, 0);
209 * Initialize the HTTP protocol layer.
210 * Currently it just checks for proxy informations
214 xmlNanoHTTPInit(void) {
224 if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
230 env = getenv("no_proxy");
231 if (env && ((env[0] == '*') && (env[1] == 0)))
233 env = getenv("http_proxy");
235 xmlNanoHTTPScanProxy(env);
238 env = getenv("HTTP_PROXY");
240 xmlNanoHTTPScanProxy(env);
249 * xmlNanoHTTPCleanup:
251 * Cleanup the HTTP protocol layer.
255 xmlNanoHTTPCleanup(void) {
269 * xmlNanoHTTPScanURL:
270 * @ctxt: an HTTP context
271 * @URL: The URL used to initialize the context
273 * (Re)Initialize an HTTP context by parsing the URL and finding
274 * the protocol host port and path it indicates.
278 xmlNanoHTTPScanURL(xmlNanoHTTPCtxtPtr ctxt, const char *URL) {
281 * Clear any existing data from the context
283 if (ctxt->protocol != NULL) {
284 xmlFree(ctxt->protocol);
285 ctxt->protocol = NULL;
287 if (ctxt->hostname != NULL) {
288 xmlFree(ctxt->hostname);
289 ctxt->hostname = NULL;
291 if (ctxt->path != NULL) {
295 if (ctxt->query != NULL) {
296 xmlFree(ctxt->query);
299 if (URL == NULL) return;
301 uri = xmlParseURIRaw(URL, 1);
305 if ((uri->scheme == NULL) || (uri->server == NULL)) {
310 ctxt->protocol = xmlMemStrdup(uri->scheme);
311 ctxt->hostname = xmlMemStrdup(uri->server);
312 if (uri->path != NULL)
313 ctxt->path = xmlMemStrdup(uri->path);
315 ctxt->path = xmlMemStrdup("/");
316 if (uri->query != NULL)
317 ctxt->query = xmlMemStrdup(uri->query);
319 ctxt->port = uri->port;
325 * xmlNanoHTTPScanProxy:
326 * @URL: The proxy URL used to initialize the proxy context
328 * (Re)Initialize the HTTP Proxy context by parsing the URL and finding
329 * the protocol host port it indicates.
330 * Should be like http://myproxy/ or http://myproxy:3128/
331 * A NULL URL cleans up proxy informations.
335 xmlNanoHTTPScanProxy(const char *URL) {
346 xmlGenericError(xmlGenericErrorContext,
347 "Removing HTTP proxy info\n");
349 xmlGenericError(xmlGenericErrorContext,
350 "Using HTTP proxy %s\n", URL);
352 if (URL == NULL) return;
354 uri = xmlParseURIRaw(URL, 1);
355 if ((uri == NULL) || (uri->scheme == NULL) ||
356 (strcmp(uri->scheme, "http")) || (uri->server == NULL)) {
357 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_URL_SYNTAX, "Syntax Error\n");
363 proxy = xmlMemStrdup(uri->server);
365 proxyPort = uri->port;
371 * xmlNanoHTTPNewCtxt:
372 * @URL: The URL used to initialize the context
374 * Allocate and initialize a new HTTP context.
376 * Returns an HTTP context or NULL in case of error.
379 static xmlNanoHTTPCtxtPtr
380 xmlNanoHTTPNewCtxt(const char *URL) {
381 xmlNanoHTTPCtxtPtr ret;
383 ret = (xmlNanoHTTPCtxtPtr) xmlMalloc(sizeof(xmlNanoHTTPCtxt));
385 xmlHTTPErrMemory("allocating context");
389 memset(ret, 0, sizeof(xmlNanoHTTPCtxt));
391 ret->returnValue = 0;
393 ret->ContentLength = -1;
395 xmlNanoHTTPScanURL(ret, URL);
401 * xmlNanoHTTPFreeCtxt:
402 * @ctxt: an HTTP context
404 * Frees the context after closing the connection.
408 xmlNanoHTTPFreeCtxt(xmlNanoHTTPCtxtPtr ctxt) {
409 if (ctxt == NULL) return;
410 if (ctxt->hostname != NULL) xmlFree(ctxt->hostname);
411 if (ctxt->protocol != NULL) xmlFree(ctxt->protocol);
412 if (ctxt->path != NULL) xmlFree(ctxt->path);
413 if (ctxt->query != NULL) xmlFree(ctxt->query);
414 if (ctxt->out != NULL) xmlFree(ctxt->out);
415 if (ctxt->in != NULL) xmlFree(ctxt->in);
416 if (ctxt->contentType != NULL) xmlFree(ctxt->contentType);
417 if (ctxt->encoding != NULL) xmlFree(ctxt->encoding);
418 if (ctxt->mimeType != NULL) xmlFree(ctxt->mimeType);
419 if (ctxt->location != NULL) xmlFree(ctxt->location);
420 if (ctxt->authHeader != NULL) xmlFree(ctxt->authHeader);
422 if (ctxt->strm != NULL) {
423 inflateEnd(ctxt->strm);
428 ctxt->state = XML_NANO_HTTP_NONE;
429 if (ctxt->fd >= 0) closesocket(ctxt->fd);
436 * @ctxt: an HTTP context
438 * Send the input needed to initiate the processing on the server side
439 * Returns number of bytes sent or -1 on error.
443 xmlNanoHTTPSend(xmlNanoHTTPCtxtPtr ctxt, const char * xmt_ptr, int outlen) {
447 if ( (ctxt->state & XML_NANO_HTTP_WRITE) && (xmt_ptr != NULL ) ) {
448 while (total_sent < outlen) {
449 int nsent = send(ctxt->fd, xmt_ptr + total_sent,
450 outlen - total_sent, 0);
453 else if ( ( nsent == -1 ) &&
454 #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
455 ( socket_errno( ) != EAGAIN ) &&
457 ( socket_errno( ) != EWOULDBLOCK ) ) {
458 __xmlIOErr(XML_FROM_HTTP, 0, "send failed\n");
459 if ( total_sent == 0 )
466 ** Since non-blocking sockets are used, wait for
467 ** socket to be writable or default timeout prior
478 #pragma warning(push)
479 #pragma warning(disable: 4018)
481 FD_SET( ctxt->fd, &wfd );
485 (void)select( ctxt->fd + 1, NULL, &wfd, NULL, &tv );
495 * @ctxt: an HTTP context
497 * Read information coming from the HTTP connection.
498 * This is a blocking call (but it blocks in select(), not read()).
500 * Returns the number of byte read or -1 in case of error.
504 xmlNanoHTTPRecv(xmlNanoHTTPCtxtPtr ctxt) {
509 while (ctxt->state & XML_NANO_HTTP_READ) {
510 if (ctxt->in == NULL) {
511 ctxt->in = (char *) xmlMallocAtomic(65000 * sizeof(char));
512 if (ctxt->in == NULL) {
513 xmlHTTPErrMemory("allocating input");
518 ctxt->inptr = ctxt->content = ctxt->inrptr = ctxt->in;
520 if (ctxt->inrptr > ctxt->in + XML_NANO_HTTP_CHUNK) {
521 int delta = ctxt->inrptr - ctxt->in;
522 int len = ctxt->inptr - ctxt->inrptr;
524 memmove(ctxt->in, ctxt->inrptr, len);
525 ctxt->inrptr -= delta;
526 ctxt->content -= delta;
527 ctxt->inptr -= delta;
529 if ((ctxt->in + ctxt->inlen) < (ctxt->inptr + XML_NANO_HTTP_CHUNK)) {
530 int d_inptr = ctxt->inptr - ctxt->in;
531 int d_content = ctxt->content - ctxt->in;
532 int d_inrptr = ctxt->inrptr - ctxt->in;
533 char * tmp_ptr = ctxt->in;
536 ctxt->in = (char *) xmlRealloc(tmp_ptr, ctxt->inlen);
537 if (ctxt->in == NULL) {
538 xmlHTTPErrMemory("allocating input buffer");
543 ctxt->inptr = ctxt->in + d_inptr;
544 ctxt->content = ctxt->in + d_content;
545 ctxt->inrptr = ctxt->in + d_inrptr;
547 ctxt->last = recv(ctxt->fd, ctxt->inptr, XML_NANO_HTTP_CHUNK, 0);
548 if (ctxt->last > 0) {
549 ctxt->inptr += ctxt->last;
552 if (ctxt->last == 0) {
555 if (ctxt->last == -1) {
556 switch (socket_errno()) {
559 #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
569 __xmlIOErr(XML_FROM_HTTP, 0, "recv failed\n");
578 #pragma warning(push)
579 #pragma warning(disable: 4018)
581 FD_SET(ctxt->fd, &rfd);
586 if ( (select(ctxt->fd+1, &rfd, NULL, NULL, &tv)<1)
597 * xmlNanoHTTPReadLine:
598 * @ctxt: an HTTP context
600 * Read one line in the HTTP server output, usually for extracting
601 * the HTTP protocol informations from the answer header.
603 * Returns a newly allocated string with a copy of the line, or NULL
604 * which indicate the end of the input.
608 xmlNanoHTTPReadLine(xmlNanoHTTPCtxtPtr ctxt) {
613 while (bp - buf < 4095) {
614 if (ctxt->inrptr == ctxt->inptr) {
615 if ( (rc = xmlNanoHTTPRecv(ctxt)) == 0) {
620 return(xmlMemStrdup(buf));
622 else if ( rc == -1 ) {
626 *bp = *ctxt->inrptr++;
629 return(xmlMemStrdup(buf));
635 return(xmlMemStrdup(buf));
640 * xmlNanoHTTPScanAnswer:
641 * @ctxt: an HTTP context
642 * @line: an HTTP header line
644 * Try to extract useful informations from the server answer.
645 * We currently parse and process:
646 * - The HTTP revision/ return code
647 * - The Content-Type, Mime-Type and charset used
648 * - The Location for redirect processing.
650 * Returns -1 in case of failure, the file descriptor number otherwise
654 xmlNanoHTTPScanAnswer(xmlNanoHTTPCtxtPtr ctxt, const char *line) {
655 const char *cur = line;
657 if (line == NULL) return;
659 if (!strncmp(line, "HTTP/", 5)) {
664 while ((*cur >= '0') && (*cur <= '9')) {
666 version += *cur - '0';
671 if ((*cur >= '0') && (*cur <= '9')) {
673 version += *cur - '0';
676 while ((*cur >= '0') && (*cur <= '9'))
680 if ((*cur != ' ') && (*cur != '\t')) return;
681 while ((*cur == ' ') || (*cur == '\t')) cur++;
682 if ((*cur < '0') || (*cur > '9')) return;
683 while ((*cur >= '0') && (*cur <= '9')) {
688 if ((*cur != 0) && (*cur != ' ') && (*cur != '\t')) return;
689 ctxt->returnValue = ret;
690 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Content-Type:", 13)) {
691 const xmlChar *charset, *last, *mime;
693 while ((*cur == ' ') || (*cur == '\t')) cur++;
694 if (ctxt->contentType != NULL)
695 xmlFree(ctxt->contentType);
696 ctxt->contentType = xmlMemStrdup(cur);
697 mime = (const xmlChar *) cur;
699 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
700 (*last != ';') && (*last != ','))
702 if (ctxt->mimeType != NULL)
703 xmlFree(ctxt->mimeType);
704 ctxt->mimeType = (char *) xmlStrndup(mime, last - mime);
705 charset = xmlStrstr(BAD_CAST ctxt->contentType, BAD_CAST "charset=");
706 if (charset != NULL) {
709 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
710 (*last != ';') && (*last != ','))
712 if (ctxt->encoding != NULL)
713 xmlFree(ctxt->encoding);
714 ctxt->encoding = (char *) xmlStrndup(charset, last - charset);
716 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"ContentType:", 12)) {
717 const xmlChar *charset, *last, *mime;
719 if (ctxt->contentType != NULL) return;
720 while ((*cur == ' ') || (*cur == '\t')) cur++;
721 ctxt->contentType = xmlMemStrdup(cur);
722 mime = (const xmlChar *) cur;
724 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
725 (*last != ';') && (*last != ','))
727 if (ctxt->mimeType != NULL)
728 xmlFree(ctxt->mimeType);
729 ctxt->mimeType = (char *) xmlStrndup(mime, last - mime);
730 charset = xmlStrstr(BAD_CAST ctxt->contentType, BAD_CAST "charset=");
731 if (charset != NULL) {
734 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
735 (*last != ';') && (*last != ','))
737 if (ctxt->encoding != NULL)
738 xmlFree(ctxt->encoding);
739 ctxt->encoding = (char *) xmlStrndup(charset, last - charset);
741 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Location:", 9)) {
743 while ((*cur == ' ') || (*cur == '\t')) cur++;
744 if (ctxt->location != NULL)
745 xmlFree(ctxt->location);
747 xmlChar *tmp_http = xmlStrdup(BAD_CAST "http://");
749 xmlStrcat(tmp_http, (const xmlChar *) ctxt->hostname);
751 (char *) xmlStrcat (tmp_loc, (const xmlChar *) cur);
753 ctxt->location = xmlMemStrdup(cur);
755 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"WWW-Authenticate:", 17)) {
757 while ((*cur == ' ') || (*cur == '\t')) cur++;
758 if (ctxt->authHeader != NULL)
759 xmlFree(ctxt->authHeader);
760 ctxt->authHeader = xmlMemStrdup(cur);
761 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Proxy-Authenticate:", 19)) {
763 while ((*cur == ' ') || (*cur == '\t')) cur++;
764 if (ctxt->authHeader != NULL)
765 xmlFree(ctxt->authHeader);
766 ctxt->authHeader = xmlMemStrdup(cur);
768 } else if ( !xmlStrncasecmp( BAD_CAST line, BAD_CAST"Content-Encoding:", 17) ) {
770 while ((*cur == ' ') || (*cur == '\t')) cur++;
771 if ( !xmlStrncasecmp( BAD_CAST cur, BAD_CAST"gzip", 4) ) {
774 ctxt->strm = xmlMalloc(sizeof(z_stream));
776 if (ctxt->strm != NULL) {
777 ctxt->strm->zalloc = Z_NULL;
778 ctxt->strm->zfree = Z_NULL;
779 ctxt->strm->opaque = Z_NULL;
780 ctxt->strm->avail_in = 0;
781 ctxt->strm->next_in = Z_NULL;
783 inflateInit2( ctxt->strm, 31 );
787 } else if ( !xmlStrncasecmp( BAD_CAST line, BAD_CAST"Content-Length:", 15) ) {
789 ctxt->ContentLength = strtol( cur, NULL, 10 );
794 * xmlNanoHTTPConnectAttempt:
795 * @addr: a socket address structure
797 * Attempt a connection to the given IP:port endpoint. It forces
798 * non-blocking semantic on the socket, and allow 60 seconds for
799 * the host to answer.
801 * Returns -1 in case of failure, the file descriptor number otherwise
805 xmlNanoHTTPConnectAttempt(struct sockaddr *addr)
817 if (addr->sa_family == AF_INET6) {
818 s = socket (PF_INET6, SOCK_STREAM, IPPROTO_TCP);
819 addrlen = sizeof (struct sockaddr_in6);
824 s = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
825 addrlen = sizeof (struct sockaddr_in);
831 __xmlIOErr(XML_FROM_HTTP, 0, "socket failed\n");
839 status = ioctlsocket(s, FIONBIO, &one) == SOCKET_ERROR ? -1 : 0;
841 #else /* _WINSOCKAPI_ */
845 status = ioctl(s, FIONBIO, &enable);
848 #if defined(__BEOS__)
851 status = setsockopt(s, SOL_SOCKET, SO_NONBLOCK, &noblock, sizeof(noblock));
854 if ((status = fcntl(s, F_GETFL, 0)) != -1) {
856 status |= O_NONBLOCK;
857 #else /* O_NONBLOCK */
860 #endif /* F_NDELAY */
861 #endif /* !O_NONBLOCK */
862 status = fcntl(s, F_SETFL, status);
866 perror("nonblocking");
868 __xmlIOErr(XML_FROM_HTTP, 0, "error setting non-blocking IO\n");
872 #endif /* !__BEOS__ */
874 #endif /* !_WINSOCKAPI_ */
876 if (connect (s, addr, addrlen) == -1) {
877 switch (socket_errno()) {
882 __xmlIOErr(XML_FROM_HTTP, 0, "error connecting to HTTP server");
892 #pragma warning(push)
893 #pragma warning(disable: 4018)
902 switch(select(s+1, NULL, &wfd, &xfd, &tv))
904 switch(select(s+1, NULL, &wfd, NULL, &tv))
912 __xmlIOErr(XML_FROM_HTTP, 0, "Connect attempt timed out");
917 __xmlIOErr(XML_FROM_HTTP, 0, "Connect failed");
922 if ( FD_ISSET(s, &wfd)
928 len = sizeof(status);
930 if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char*)&status, &len) < 0 ) {
931 /* Solaris error code */
932 __xmlIOErr(XML_FROM_HTTP, 0, "getsockopt failed\n");
937 __xmlIOErr(XML_FROM_HTTP, 0, "Error connecting to remote host");
944 __xmlIOErr(XML_FROM_HTTP, 0, "select failed\n");
953 * xmlNanoHTTPConnectHost:
954 * @host: the host name
955 * @port: the port number
957 * Attempt a connection to the given host:port endpoint. It tries
958 * the multiple IP provided by the DNS if available.
960 * Returns -1 in case of failure, the file descriptor number otherwise
964 xmlNanoHTTPConnectHost(const char *host, int port)
967 struct sockaddr *addr = NULL;
969 struct sockaddr_in sockin;
973 struct sockaddr_in6 sockin6;
978 memset (&sockin, 0, sizeof(sockin));
980 memset (&sockin6, 0, sizeof(sockin6));
983 #if !defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && defined(RES_USE_INET6)
986 if (!(_res.options & RES_INIT))
988 _res.options |= RES_USE_INET6;
992 #if defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && !defined(_WIN32)
995 #if defined(HAVE_GETADDRINFO) && (defined(SUPPORT_IP6) || defined(_WIN32))
998 struct addrinfo hints, *res, *result;
1001 memset (&hints, 0,sizeof(hints));
1002 hints.ai_socktype = SOCK_STREAM;
1004 status = getaddrinfo (host, NULL, &hints, &result);
1006 __xmlIOErr(XML_FROM_HTTP, 0, "getaddrinfo failed\n");
1010 for (res = result; res; res = res->ai_next) {
1011 if (res->ai_family == AF_INET) {
1012 if (res->ai_addrlen > sizeof(sockin)) {
1013 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1014 freeaddrinfo (result);
1017 memcpy (&sockin, res->ai_addr, res->ai_addrlen);
1018 sockin.sin_port = htons (port);
1019 addr = (struct sockaddr *)&sockin;
1021 } else if (have_ipv6 () && (res->ai_family == AF_INET6)) {
1022 if (res->ai_addrlen > sizeof(sockin6)) {
1023 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1024 freeaddrinfo (result);
1027 memcpy (&sockin6, res->ai_addr, res->ai_addrlen);
1028 sockin6.sin6_port = htons (port);
1029 addr = (struct sockaddr *)&sockin6;
1034 s = xmlNanoHTTPConnectAttempt (addr);
1036 freeaddrinfo (result);
1042 freeaddrinfo (result);
1045 #if defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && !defined(_WIN32)
1048 #if !defined(HAVE_GETADDRINFO) || !defined(_WIN32)
1050 h = gethostbyname (host);
1054 * Okay, I got fed up by the non-portability of this error message
1055 * extraction code. it work on Linux, if it work on your platform
1056 * and one want to enable it, send me the defined(foobar) needed
1058 #if defined(HAVE_NETDB_H) && defined(HOST_NOT_FOUND) && defined(linux)
1059 const char *h_err_txt = "";
1062 case HOST_NOT_FOUND:
1063 h_err_txt = "Authoritive host not found";
1068 "Non-authoritive host not found or server failure.";
1073 "Non-recoverable errors: FORMERR, REFUSED, or NOTIMP.";
1078 "Valid name, no data record of requested type.";
1082 h_err_txt = "No error text defined.";
1085 __xmlIOErr(XML_FROM_HTTP, 0, h_err_txt);
1087 __xmlIOErr(XML_FROM_HTTP, 0, "Failed to resolve host");
1092 for (i = 0; h->h_addr_list[i]; i++) {
1093 if (h->h_addrtype == AF_INET) {
1094 /* A records (IPv4) */
1095 if ((unsigned int) h->h_length > sizeof(ia)) {
1096 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1099 memcpy (&ia, h->h_addr_list[i], h->h_length);
1100 sockin.sin_family = h->h_addrtype;
1101 sockin.sin_addr = ia;
1102 sockin.sin_port = (u_short)htons ((unsigned short)port);
1103 addr = (struct sockaddr *) &sockin;
1105 } else if (have_ipv6 () && (h->h_addrtype == AF_INET6)) {
1106 /* AAAA records (IPv6) */
1107 if ((unsigned int) h->h_length > sizeof(ia6)) {
1108 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1111 memcpy (&ia6, h->h_addr_list[i], h->h_length);
1112 sockin6.sin6_family = h->h_addrtype;
1113 sockin6.sin6_addr = ia6;
1114 sockin6.sin6_port = htons (port);
1115 addr = (struct sockaddr *) &sockin6;
1120 s = xmlNanoHTTPConnectAttempt (addr);
1128 xmlGenericError(xmlGenericErrorContext,
1129 "xmlNanoHTTPConnectHost: unable to connect to '%s'.\n",
1138 * @URL: The URL to load
1139 * @contentType: if available the Content-Type information will be
1140 * returned at that location
1142 * This function try to open a connection to the indicated resource
1145 * Returns NULL in case of failure, otherwise a request handler.
1146 * The contentType, if provided must be freed by the caller
1150 xmlNanoHTTPOpen(const char *URL, char **contentType) {
1151 if (contentType != NULL) *contentType = NULL;
1152 return(xmlNanoHTTPMethod(URL, NULL, NULL, contentType, NULL, 0));
1156 * xmlNanoHTTPOpenRedir:
1157 * @URL: The URL to load
1158 * @contentType: if available the Content-Type information will be
1159 * returned at that location
1160 * @redir: if available the redirected URL will be returned
1162 * This function try to open a connection to the indicated resource
1165 * Returns NULL in case of failure, otherwise a request handler.
1166 * The contentType, if provided must be freed by the caller
1170 xmlNanoHTTPOpenRedir(const char *URL, char **contentType, char **redir) {
1171 if (contentType != NULL) *contentType = NULL;
1172 if (redir != NULL) *redir = NULL;
1173 return(xmlNanoHTTPMethodRedir(URL, NULL, NULL, contentType, redir, NULL,0));
1178 * @ctx: the HTTP context
1180 * @len: the buffer length
1182 * This function tries to read @len bytes from the existing HTTP connection
1183 * and saves them in @dest. This is a blocking call.
1185 * Returns the number of byte read. 0 is an indication of an end of connection.
1186 * -1 indicates a parameter error.
1189 xmlNanoHTTPRead(void *ctx, void *dest, int len) {
1190 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1197 if (ctx == NULL) return(-1);
1198 if (dest == NULL) return(-1);
1199 if (len <= 0) return(0);
1202 if (ctxt->usesGzip == 1) {
1203 if (ctxt->strm == NULL) return(0);
1205 ctxt->strm->next_out = dest;
1206 ctxt->strm->avail_out = len;
1209 orig_avail_in = ctxt->strm->avail_in = ctxt->inptr - ctxt->inrptr - bytes_read;
1210 ctxt->strm->next_in = BAD_CAST (ctxt->inrptr + bytes_read);
1212 z_ret = inflate(ctxt->strm, Z_NO_FLUSH);
1213 bytes_read += orig_avail_in - ctxt->strm->avail_in;
1215 if (z_ret != Z_OK) break;
1216 } while (ctxt->strm->avail_out > 0 && xmlNanoHTTPRecv(ctxt) > 0);
1218 ctxt->inrptr += bytes_read;
1219 return(len - ctxt->strm->avail_out);
1223 while (ctxt->inptr - ctxt->inrptr < len) {
1224 if (xmlNanoHTTPRecv(ctxt) <= 0) break;
1226 if (ctxt->inptr - ctxt->inrptr < len)
1227 len = ctxt->inptr - ctxt->inrptr;
1228 memcpy(dest, ctxt->inrptr, len);
1229 ctxt->inrptr += len;
1235 * @ctx: the HTTP context
1237 * This function closes an HTTP context, it ends up the connection and
1238 * free all data related to it.
1241 xmlNanoHTTPClose(void *ctx) {
1242 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1244 if (ctx == NULL) return;
1246 xmlNanoHTTPFreeCtxt(ctxt);
1250 * xmlNanoHTTPMethodRedir:
1251 * @URL: The URL to load
1252 * @method: the HTTP method to use
1253 * @input: the input string if any
1254 * @contentType: the Content-Type information IN and OUT
1255 * @redir: the redirected URL OUT
1256 * @headers: the extra headers
1257 * @ilen: input length
1259 * This function try to open a connection to the indicated resource
1260 * via HTTP using the given @method, adding the given extra headers
1261 * and the input buffer for the request content.
1263 * Returns NULL in case of failure, otherwise a request handler.
1264 * The contentType, or redir, if provided must be freed by the caller
1268 xmlNanoHTTPMethodRedir(const char *URL, const char *method, const char *input,
1269 char **contentType, char **redir,
1270 const char *headers, int ilen ) {
1271 xmlNanoHTTPCtxtPtr ctxt;
1275 int nbRedirects = 0;
1276 char *redirURL = NULL;
1281 if (URL == NULL) return(NULL);
1282 if (method == NULL) method = "GET";
1286 if (redirURL == NULL)
1287 ctxt = xmlNanoHTTPNewCtxt(URL);
1289 ctxt = xmlNanoHTTPNewCtxt(redirURL);
1290 ctxt->location = xmlMemStrdup(redirURL);
1293 if ( ctxt == NULL ) {
1297 if ((ctxt->protocol == NULL) || (strcmp(ctxt->protocol, "http"))) {
1298 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_URL_SYNTAX, "Not a valid HTTP URI");
1299 xmlNanoHTTPFreeCtxt(ctxt);
1300 if (redirURL != NULL) xmlFree(redirURL);
1303 if (ctxt->hostname == NULL) {
1304 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_UNKNOWN_HOST,
1305 "Failed to identify host in URI");
1306 xmlNanoHTTPFreeCtxt(ctxt);
1307 if (redirURL != NULL) xmlFree(redirURL);
1311 blen = strlen(ctxt->hostname) * 2 + 16;
1312 ret = xmlNanoHTTPConnectHost(proxy, proxyPort);
1315 blen = strlen(ctxt->hostname);
1316 ret = xmlNanoHTTPConnectHost(ctxt->hostname, ctxt->port);
1319 xmlNanoHTTPFreeCtxt(ctxt);
1320 if (redirURL != NULL) xmlFree(redirURL);
1330 if (headers != NULL)
1331 blen += strlen(headers) + 2;
1332 if (contentType && *contentType)
1333 blen += strlen(*contentType) + 16;
1334 if (ctxt->query != NULL)
1335 blen += strlen(ctxt->query) + 1;
1336 blen += strlen(method) + strlen(ctxt->path) + 24;
1340 bp = (char*)xmlMallocAtomic(blen);
1342 xmlNanoHTTPFreeCtxt( ctxt );
1343 xmlHTTPErrMemory("allocating header buffer");
1350 if (ctxt->port != 80) {
1351 p += snprintf( p, blen - (p - bp), "%s http://%s:%d%s",
1352 method, ctxt->hostname,
1353 ctxt->port, ctxt->path );
1356 p += snprintf( p, blen - (p - bp), "%s http://%s%s", method,
1357 ctxt->hostname, ctxt->path);
1360 p += snprintf( p, blen - (p - bp), "%s %s", method, ctxt->path);
1362 if (ctxt->query != NULL)
1363 p += snprintf( p, blen - (p - bp), "?%s", ctxt->query);
1365 p += snprintf( p, blen - (p - bp), " HTTP/1.0\r\nHost: %s\r\n",
1369 p += snprintf(p, blen - (p - bp), "Accept-Encoding: gzip\r\n");
1372 if (contentType != NULL && *contentType)
1373 p += snprintf(p, blen - (p - bp), "Content-Type: %s\r\n", *contentType);
1375 if (headers != NULL)
1376 p += snprintf( p, blen - (p - bp), "%s", headers );
1379 snprintf(p, blen - (p - bp), "Content-Length: %d\r\n\r\n", ilen );
1381 snprintf(p, blen - (p - bp), "\r\n");
1384 xmlGenericError(xmlGenericErrorContext,
1385 "-> %s%s", proxy? "(Proxy) " : "", bp);
1386 if ((blen -= strlen(bp)+1) < 0)
1387 xmlGenericError(xmlGenericErrorContext,
1388 "ERROR: overflowed buffer by %d bytes\n", -blen);
1390 ctxt->outptr = ctxt->out = bp;
1391 ctxt->state = XML_NANO_HTTP_WRITE;
1392 blen = strlen( ctxt->out );
1394 xmt_bytes = xmlNanoHTTPSend(ctxt, ctxt->out, blen );
1395 if ( xmt_bytes != blen )
1396 xmlGenericError( xmlGenericErrorContext,
1397 "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n",
1399 "bytes of HTTP headers sent to host",
1402 xmlNanoHTTPSend(ctxt, ctxt->out, blen );
1405 if ( input != NULL ) {
1407 xmt_bytes = xmlNanoHTTPSend( ctxt, input, ilen );
1409 if ( xmt_bytes != ilen )
1410 xmlGenericError( xmlGenericErrorContext,
1411 "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n",
1413 "bytes of HTTP content sent to host",
1416 xmlNanoHTTPSend( ctxt, input, ilen );
1420 ctxt->state = XML_NANO_HTTP_READ;
1423 while ((p = xmlNanoHTTPReadLine(ctxt)) != NULL) {
1424 if (head && (*p == 0)) {
1426 ctxt->content = ctxt->inrptr;
1430 xmlNanoHTTPScanAnswer(ctxt, p);
1433 xmlGenericError(xmlGenericErrorContext, "<- %s\n", p);
1438 if ((ctxt->location != NULL) && (ctxt->returnValue >= 300) &&
1439 (ctxt->returnValue < 400)) {
1441 xmlGenericError(xmlGenericErrorContext,
1442 "\nRedirect to: %s\n", ctxt->location);
1444 while ( xmlNanoHTTPRecv(ctxt) > 0 ) ;
1445 if (nbRedirects < XML_NANO_HTTP_MAX_REDIR) {
1447 if (redirURL != NULL)
1449 redirURL = xmlMemStrdup(ctxt->location);
1450 xmlNanoHTTPFreeCtxt(ctxt);
1453 xmlNanoHTTPFreeCtxt(ctxt);
1454 if (redirURL != NULL) xmlFree(redirURL);
1456 xmlGenericError(xmlGenericErrorContext,
1457 "xmlNanoHTTPMethodRedir: Too many redirects, aborting ...\n");
1462 if (contentType != NULL) {
1463 if (ctxt->contentType != NULL)
1464 *contentType = xmlMemStrdup(ctxt->contentType);
1466 *contentType = NULL;
1469 if ((redir != NULL) && (redirURL != NULL)) {
1472 if (redirURL != NULL)
1479 if (ctxt->contentType != NULL)
1480 xmlGenericError(xmlGenericErrorContext,
1481 "\nCode %d, content-type '%s'\n\n",
1482 ctxt->returnValue, ctxt->contentType);
1484 xmlGenericError(xmlGenericErrorContext,
1485 "\nCode %d, no content-type\n\n",
1489 return((void *) ctxt);
1493 * xmlNanoHTTPMethod:
1494 * @URL: The URL to load
1495 * @method: the HTTP method to use
1496 * @input: the input string if any
1497 * @contentType: the Content-Type information IN and OUT
1498 * @headers: the extra headers
1499 * @ilen: input length
1501 * This function try to open a connection to the indicated resource
1502 * via HTTP using the given @method, adding the given extra headers
1503 * and the input buffer for the request content.
1505 * Returns NULL in case of failure, otherwise a request handler.
1506 * The contentType, if provided must be freed by the caller
1510 xmlNanoHTTPMethod(const char *URL, const char *method, const char *input,
1511 char **contentType, const char *headers, int ilen) {
1512 return(xmlNanoHTTPMethodRedir(URL, method, input, contentType,
1513 NULL, headers, ilen));
1518 * @URL: The URL to load
1519 * @filename: the filename where the content should be saved
1520 * @contentType: if available the Content-Type information will be
1521 * returned at that location
1523 * This function try to fetch the indicated resource via HTTP GET
1524 * and save it's content in the file.
1526 * Returns -1 in case of failure, 0 incase of success. The contentType,
1527 * if provided must be freed by the caller
1530 xmlNanoHTTPFetch(const char *URL, const char *filename, char **contentType) {
1536 if (filename == NULL) return(-1);
1537 ctxt = xmlNanoHTTPOpen(URL, contentType);
1538 if (ctxt == NULL) return(-1);
1540 if (!strcmp(filename, "-"))
1543 fd = open(filename, O_CREAT | O_WRONLY, 00644);
1545 xmlNanoHTTPClose(ctxt);
1546 if ((contentType != NULL) && (*contentType != NULL)) {
1547 xmlFree(*contentType);
1548 *contentType = NULL;
1554 xmlNanoHTTPFetchContent( ctxt, &buf, &len );
1556 write(fd, buf, len);
1559 xmlNanoHTTPClose(ctxt);
1564 #ifdef LIBXML_OUTPUT_ENABLED
1567 * @ctxt: the HTTP context
1568 * @filename: the filename where the content should be saved
1570 * This function saves the output of the HTTP transaction to a file
1571 * It closes and free the context at the end
1573 * Returns -1 in case of failure, 0 incase of success.
1576 xmlNanoHTTPSave(void *ctxt, const char *filename) {
1581 if ((ctxt == NULL) || (filename == NULL)) return(-1);
1583 if (!strcmp(filename, "-"))
1586 fd = open(filename, O_CREAT | O_WRONLY);
1588 xmlNanoHTTPClose(ctxt);
1593 xmlNanoHTTPFetchContent( ctxt, &buf, &len );
1595 write(fd, buf, len);
1598 xmlNanoHTTPClose(ctxt);
1602 #endif /* LIBXML_OUTPUT_ENABLED */
1605 * xmlNanoHTTPReturnCode:
1606 * @ctx: the HTTP context
1608 * Get the latest HTTP return code received
1610 * Returns the HTTP return code for the request.
1613 xmlNanoHTTPReturnCode(void *ctx) {
1614 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1616 if (ctxt == NULL) return(-1);
1618 return(ctxt->returnValue);
1622 * xmlNanoHTTPAuthHeader:
1623 * @ctx: the HTTP context
1625 * Get the authentication header of an HTTP context
1627 * Returns the stashed value of the WWW-Authenticate or Proxy-Authenticate
1631 xmlNanoHTTPAuthHeader(void *ctx) {
1632 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1634 if (ctxt == NULL) return(NULL);
1636 return(ctxt->authHeader);
1640 * xmlNanoHTTPContentLength:
1641 * @ctx: the HTTP context
1643 * Provides the specified content length from the HTTP header.
1645 * Return the specified content length from the HTTP header. Note that
1646 * a value of -1 indicates that the content length element was not included in
1647 * the response header.
1650 xmlNanoHTTPContentLength( void * ctx ) {
1651 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1653 return ( ( ctxt == NULL ) ? -1 : ctxt->ContentLength );
1658 * @ctx: the HTTP context
1660 * Provides the specified redirection URL if available from the HTTP header.
1662 * Return the specified redirection URL or NULL if not redirected.
1665 xmlNanoHTTPRedir( void * ctx ) {
1666 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1668 return ( ( ctxt == NULL ) ? NULL : ctxt->location );
1672 * xmlNanoHTTPEncoding:
1673 * @ctx: the HTTP context
1675 * Provides the specified encoding if specified in the HTTP headers.
1677 * Return the specified encoding or NULL if not available
1680 xmlNanoHTTPEncoding( void * ctx ) {
1681 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1683 return ( ( ctxt == NULL ) ? NULL : ctxt->encoding );
1687 * xmlNanoHTTPMimeType:
1688 * @ctx: the HTTP context
1690 * Provides the specified Mime-Type if specified in the HTTP headers.
1692 * Return the specified Mime-Type or NULL if not available
1695 xmlNanoHTTPMimeType( void * ctx ) {
1696 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1698 return ( ( ctxt == NULL ) ? NULL : ctxt->mimeType );
1702 * xmlNanoHTTPFetchContent:
1703 * @ctx: the HTTP context
1704 * @ptr: pointer to set to the content buffer.
1705 * @len: integer pointer to hold the length of the content
1707 * Check if all the content was read
1709 * Returns 0 if all the content was read and available, returns
1710 * -1 if received content length was less than specified or an error
1714 xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len ) {
1715 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1721 char * dummy_ptr = NULL;
1723 /* Dummy up return input parameters if not provided */
1731 /* But can't work without the context pointer */
1733 if ( ( ctxt == NULL ) || ( ctxt->content == NULL ) ) {
1739 rcvd_lgth = ctxt->inptr - ctxt->content;
1741 while ( (cur_lgth = xmlNanoHTTPRecv( ctxt )) > 0 ) {
1743 rcvd_lgth += cur_lgth;
1744 if ( (ctxt->ContentLength > 0) && (rcvd_lgth >= ctxt->ContentLength) )
1748 *ptr = ctxt->content;
1751 if ( ( ctxt->ContentLength > 0 ) && ( rcvd_lgth < ctxt->ContentLength ) )
1753 else if ( rcvd_lgth == 0 )
1760 int main(int argc, char **argv) {
1761 char *contentType = NULL;
1763 if (argv[1] != NULL) {
1764 if (argv[2] != NULL)
1765 xmlNanoHTTPFetch(argv[1], argv[2], &contentType);
1767 xmlNanoHTTPFetch(argv[1], "-", &contentType);
1768 if (contentType != NULL) xmlFree(contentType);
1770 xmlGenericError(xmlGenericErrorContext,
1771 "%s: minimal HTTP GET implementation\n", argv[0]);
1772 xmlGenericError(xmlGenericErrorContext,
1773 "\tusage %s [ URL [ filename ] ]\n", argv[0]);
1775 xmlNanoHTTPCleanup();
1779 #endif /* STANDALONE */
1780 #else /* !LIBXML_HTTP_ENABLED */
1783 int main(int argc, char **argv) {
1784 xmlGenericError(xmlGenericErrorContext,
1785 "%s : HTTP support not compiled in\n", argv[0]);
1788 #endif /* STANDALONE */
1789 #endif /* LIBXML_HTTP_ENABLED */
1790 #define bottom_nanohttp
1791 #include "elfgcchack.h"