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>
74 #define XML_SOCKLEN_T unsigned int
77 #if defined(__MINGW32__) || defined(_WIN32_WCE)
81 #include <wsockcompat.h>
84 #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
99 #if !defined(__BEOS__) || defined(__HAIKU__)
100 #define closesocket(s) close(s)
103 #define INVALID_SOCKET (-1)
108 #define PF_INET AF_INET
112 #ifndef XML_SOCKLEN_T
113 #define XML_SOCKLEN_T unsigned int
118 #define xmlStrncasecmp(a, b, n) strncasecmp((char *)a, (char *)b, n)
119 #define xmlStrcasecmpi(a, b) strcasecmp((char *)a, (char *)b)
122 #define XML_NANO_HTTP_MAX_REDIR 10
124 #define XML_NANO_HTTP_CHUNK 4096
126 #define XML_NANO_HTTP_CLOSED 0
127 #define XML_NANO_HTTP_WRITE 1
128 #define XML_NANO_HTTP_READ 2
129 #define XML_NANO_HTTP_NONE 4
131 typedef struct xmlNanoHTTPCtxt {
132 char *protocol; /* the protocol name */
133 char *hostname; /* the host name */
134 int port; /* the port */
135 char *path; /* the path within the URL */
136 char *query; /* the query string */
137 SOCKET fd; /* the file descriptor for the socket */
138 int state; /* WRITE / READ / CLOSED */
139 char *out; /* buffer sent (zero terminated) */
140 char *outptr; /* index within the buffer sent */
141 char *in; /* the receiving buffer */
142 char *content; /* the start of the content */
143 char *inptr; /* the next byte to read from network */
144 char *inrptr; /* the next byte to give back to the client */
145 int inlen; /* len of the input buffer */
146 int last; /* return code for last operation */
147 int returnValue; /* the protocol return value */
148 int version; /* the protocol version */
149 int ContentLength; /* specified content length from HTTP header */
150 char *contentType; /* the MIME type for the input */
151 char *location; /* the new URL in case of redirect */
152 char *authHeader; /* contents of {WWW,Proxy}-Authenticate header */
153 char *encoding; /* encoding extracted from the contentType */
154 char *mimeType; /* Mime-Type extracted from the contentType */
156 z_stream *strm; /* Zlib stream object */
157 int usesGzip; /* "Content-Encoding: gzip" was detected */
159 } xmlNanoHTTPCtxt, *xmlNanoHTTPCtxtPtr;
161 static int initialized = 0;
162 static char *proxy = NULL; /* the proxy name if any */
163 static int proxyPort; /* the proxy port if any */
164 static unsigned int timeout = 60;/* the select() timeout in seconds */
166 static int xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len );
170 * @extra: extra informations
172 * Handle an out of memory condition
175 xmlHTTPErrMemory(const char *extra)
177 __xmlSimpleError(XML_FROM_HTTP, XML_ERR_NO_MEMORY, NULL, NULL, extra);
181 * A portability function
183 static int socket_errno(void) {
185 return(WSAGetLastError());
193 int have_ipv6(void) {
196 s = socket (AF_INET6, SOCK_STREAM, 0);
197 if (s != INVALID_SOCKET) {
208 * Initialize the HTTP protocol layer.
209 * Currently it just checks for proxy informations
213 xmlNanoHTTPInit(void) {
223 if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
229 env = getenv("no_proxy");
230 if (env && ((env[0] == '*') && (env[1] == 0)))
232 env = getenv("http_proxy");
234 xmlNanoHTTPScanProxy(env);
237 env = getenv("HTTP_PROXY");
239 xmlNanoHTTPScanProxy(env);
248 * xmlNanoHTTPCleanup:
250 * Cleanup the HTTP protocol layer.
254 xmlNanoHTTPCleanup(void) {
268 * xmlNanoHTTPScanURL:
269 * @ctxt: an HTTP context
270 * @URL: The URL used to initialize the context
272 * (Re)Initialize an HTTP context by parsing the URL and finding
273 * the protocol host port and path it indicates.
277 xmlNanoHTTPScanURL(xmlNanoHTTPCtxtPtr ctxt, const char *URL) {
280 * Clear any existing data from the context
282 if (ctxt->protocol != NULL) {
283 xmlFree(ctxt->protocol);
284 ctxt->protocol = NULL;
286 if (ctxt->hostname != NULL) {
287 xmlFree(ctxt->hostname);
288 ctxt->hostname = NULL;
290 if (ctxt->path != NULL) {
294 if (ctxt->query != NULL) {
295 xmlFree(ctxt->query);
298 if (URL == NULL) return;
300 uri = xmlParseURIRaw(URL, 1);
304 if ((uri->scheme == NULL) || (uri->server == NULL)) {
309 ctxt->protocol = xmlMemStrdup(uri->scheme);
310 ctxt->hostname = xmlMemStrdup(uri->server);
311 if (uri->path != NULL)
312 ctxt->path = xmlMemStrdup(uri->path);
314 ctxt->path = xmlMemStrdup("/");
315 if (uri->query != NULL)
316 ctxt->query = xmlMemStrdup(uri->query);
318 ctxt->port = uri->port;
324 * xmlNanoHTTPScanProxy:
325 * @URL: The proxy URL used to initialize the proxy context
327 * (Re)Initialize the HTTP Proxy context by parsing the URL and finding
328 * the protocol host port it indicates.
329 * Should be like http://myproxy/ or http://myproxy:3128/
330 * A NULL URL cleans up proxy informations.
334 xmlNanoHTTPScanProxy(const char *URL) {
345 xmlGenericError(xmlGenericErrorContext,
346 "Removing HTTP proxy info\n");
348 xmlGenericError(xmlGenericErrorContext,
349 "Using HTTP proxy %s\n", URL);
351 if (URL == NULL) return;
353 uri = xmlParseURIRaw(URL, 1);
354 if ((uri == NULL) || (uri->scheme == NULL) ||
355 (strcmp(uri->scheme, "http")) || (uri->server == NULL)) {
356 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_URL_SYNTAX, "Syntax Error\n");
362 proxy = xmlMemStrdup(uri->server);
364 proxyPort = uri->port;
370 * xmlNanoHTTPNewCtxt:
371 * @URL: The URL used to initialize the context
373 * Allocate and initialize a new HTTP context.
375 * Returns an HTTP context or NULL in case of error.
378 static xmlNanoHTTPCtxtPtr
379 xmlNanoHTTPNewCtxt(const char *URL) {
380 xmlNanoHTTPCtxtPtr ret;
382 ret = (xmlNanoHTTPCtxtPtr) xmlMalloc(sizeof(xmlNanoHTTPCtxt));
384 xmlHTTPErrMemory("allocating context");
388 memset(ret, 0, sizeof(xmlNanoHTTPCtxt));
390 ret->returnValue = 0;
391 ret->fd = INVALID_SOCKET;
392 ret->ContentLength = -1;
394 xmlNanoHTTPScanURL(ret, URL);
400 * xmlNanoHTTPFreeCtxt:
401 * @ctxt: an HTTP context
403 * Frees the context after closing the connection.
407 xmlNanoHTTPFreeCtxt(xmlNanoHTTPCtxtPtr ctxt) {
408 if (ctxt == NULL) return;
409 if (ctxt->hostname != NULL) xmlFree(ctxt->hostname);
410 if (ctxt->protocol != NULL) xmlFree(ctxt->protocol);
411 if (ctxt->path != NULL) xmlFree(ctxt->path);
412 if (ctxt->query != NULL) xmlFree(ctxt->query);
413 if (ctxt->out != NULL) xmlFree(ctxt->out);
414 if (ctxt->in != NULL) xmlFree(ctxt->in);
415 if (ctxt->contentType != NULL) xmlFree(ctxt->contentType);
416 if (ctxt->encoding != NULL) xmlFree(ctxt->encoding);
417 if (ctxt->mimeType != NULL) xmlFree(ctxt->mimeType);
418 if (ctxt->location != NULL) xmlFree(ctxt->location);
419 if (ctxt->authHeader != NULL) xmlFree(ctxt->authHeader);
421 if (ctxt->strm != NULL) {
422 inflateEnd(ctxt->strm);
427 ctxt->state = XML_NANO_HTTP_NONE;
428 if (ctxt->fd != INVALID_SOCKET) closesocket(ctxt->fd);
429 ctxt->fd = INVALID_SOCKET;
435 * @ctxt: an HTTP context
437 * Send the input needed to initiate the processing on the server side
438 * Returns number of bytes sent or -1 on error.
442 xmlNanoHTTPSend(xmlNanoHTTPCtxtPtr ctxt, const char *xmt_ptr, int outlen)
452 if ((ctxt->state & XML_NANO_HTTP_WRITE) && (xmt_ptr != NULL)) {
453 while (total_sent < outlen) {
454 int nsent = send(ctxt->fd, xmt_ptr + total_sent,
455 outlen - total_sent, 0);
459 else if ((nsent == -1) &&
460 #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
461 (socket_errno() != EAGAIN) &&
463 (socket_errno() != EWOULDBLOCK)) {
464 __xmlIOErr(XML_FROM_HTTP, 0, "send failed\n");
471 * Since non-blocking sockets are used, wait for
472 * socket to be writable or default timeout prior
477 if (ctxt->fd > FD_SETSIZE)
485 #pragma warning(push)
486 #pragma warning(disable: 4018)
488 FD_SET(ctxt->fd, &wfd);
492 (void) select(ctxt->fd + 1, NULL, &wfd, NULL, &tv);
496 (void) poll(&p, 1, timeout * 1000);
497 #endif /* !HAVE_POLL_H */
507 * @ctxt: an HTTP context
509 * Read information coming from the HTTP connection.
510 * This is a blocking call (but it blocks in select(), not read()).
512 * Returns the number of byte read or -1 in case of error.
516 xmlNanoHTTPRecv(xmlNanoHTTPCtxtPtr ctxt)
526 while (ctxt->state & XML_NANO_HTTP_READ) {
527 if (ctxt->in == NULL) {
528 ctxt->in = (char *) xmlMallocAtomic(65000 * sizeof(char));
529 if (ctxt->in == NULL) {
530 xmlHTTPErrMemory("allocating input");
535 ctxt->inptr = ctxt->content = ctxt->inrptr = ctxt->in;
537 if (ctxt->inrptr > ctxt->in + XML_NANO_HTTP_CHUNK) {
538 int delta = ctxt->inrptr - ctxt->in;
539 int len = ctxt->inptr - ctxt->inrptr;
541 memmove(ctxt->in, ctxt->inrptr, len);
542 ctxt->inrptr -= delta;
543 ctxt->content -= delta;
544 ctxt->inptr -= delta;
546 if ((ctxt->in + ctxt->inlen) < (ctxt->inptr + XML_NANO_HTTP_CHUNK)) {
547 int d_inptr = ctxt->inptr - ctxt->in;
548 int d_content = ctxt->content - ctxt->in;
549 int d_inrptr = ctxt->inrptr - ctxt->in;
550 char *tmp_ptr = ctxt->in;
553 ctxt->in = (char *) xmlRealloc(tmp_ptr, ctxt->inlen);
554 if (ctxt->in == NULL) {
555 xmlHTTPErrMemory("allocating input buffer");
560 ctxt->inptr = ctxt->in + d_inptr;
561 ctxt->content = ctxt->in + d_content;
562 ctxt->inrptr = ctxt->in + d_inrptr;
564 ctxt->last = recv(ctxt->fd, ctxt->inptr, XML_NANO_HTTP_CHUNK, 0);
565 if (ctxt->last > 0) {
566 ctxt->inptr += ctxt->last;
569 if (ctxt->last == 0) {
572 if (ctxt->last == -1) {
573 switch (socket_errno()) {
576 #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
586 __xmlIOErr(XML_FROM_HTTP, 0, "recv failed\n");
593 if ((poll(&p, 1, timeout * 1000) < 1)
599 #else /* !HAVE_POLL_H */
601 if (ctxt->fd > FD_SETSIZE)
610 #pragma warning(push)
611 #pragma warning(disable: 4018)
614 FD_SET(ctxt->fd, &rfd);
620 if ((select(ctxt->fd + 1, &rfd, NULL, NULL, &tv) < 1)
626 #endif /* !HAVE_POLL_H */
632 * xmlNanoHTTPReadLine:
633 * @ctxt: an HTTP context
635 * Read one line in the HTTP server output, usually for extracting
636 * the HTTP protocol informations from the answer header.
638 * Returns a newly allocated string with a copy of the line, or NULL
639 * which indicate the end of the input.
643 xmlNanoHTTPReadLine(xmlNanoHTTPCtxtPtr ctxt) {
648 while (bp - buf < 4095) {
649 if (ctxt->inrptr == ctxt->inptr) {
650 if ( (rc = xmlNanoHTTPRecv(ctxt)) == 0) {
655 return(xmlMemStrdup(buf));
657 else if ( rc == -1 ) {
661 *bp = *ctxt->inrptr++;
664 return(xmlMemStrdup(buf));
670 return(xmlMemStrdup(buf));
675 * xmlNanoHTTPScanAnswer:
676 * @ctxt: an HTTP context
677 * @line: an HTTP header line
679 * Try to extract useful informations from the server answer.
680 * We currently parse and process:
681 * - The HTTP revision/ return code
682 * - The Content-Type, Mime-Type and charset used
683 * - The Location for redirect processing.
685 * Returns -1 in case of failure, the file descriptor number otherwise
689 xmlNanoHTTPScanAnswer(xmlNanoHTTPCtxtPtr ctxt, const char *line) {
690 const char *cur = line;
692 if (line == NULL) return;
694 if (!strncmp(line, "HTTP/", 5)) {
699 while ((*cur >= '0') && (*cur <= '9')) {
701 version += *cur - '0';
706 if ((*cur >= '0') && (*cur <= '9')) {
708 version += *cur - '0';
711 while ((*cur >= '0') && (*cur <= '9'))
715 if ((*cur != ' ') && (*cur != '\t')) return;
716 while ((*cur == ' ') || (*cur == '\t')) cur++;
717 if ((*cur < '0') || (*cur > '9')) return;
718 while ((*cur >= '0') && (*cur <= '9')) {
723 if ((*cur != 0) && (*cur != ' ') && (*cur != '\t')) return;
724 ctxt->returnValue = ret;
725 ctxt->version = version;
726 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Content-Type:", 13)) {
727 const xmlChar *charset, *last, *mime;
729 while ((*cur == ' ') || (*cur == '\t')) cur++;
730 if (ctxt->contentType != NULL)
731 xmlFree(ctxt->contentType);
732 ctxt->contentType = xmlMemStrdup(cur);
733 mime = (const xmlChar *) cur;
735 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
736 (*last != ';') && (*last != ','))
738 if (ctxt->mimeType != NULL)
739 xmlFree(ctxt->mimeType);
740 ctxt->mimeType = (char *) xmlStrndup(mime, last - mime);
741 charset = xmlStrstr(BAD_CAST ctxt->contentType, BAD_CAST "charset=");
742 if (charset != NULL) {
745 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
746 (*last != ';') && (*last != ','))
748 if (ctxt->encoding != NULL)
749 xmlFree(ctxt->encoding);
750 ctxt->encoding = (char *) xmlStrndup(charset, last - charset);
752 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"ContentType:", 12)) {
753 const xmlChar *charset, *last, *mime;
755 if (ctxt->contentType != NULL) return;
756 while ((*cur == ' ') || (*cur == '\t')) cur++;
757 ctxt->contentType = xmlMemStrdup(cur);
758 mime = (const xmlChar *) cur;
760 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
761 (*last != ';') && (*last != ','))
763 if (ctxt->mimeType != NULL)
764 xmlFree(ctxt->mimeType);
765 ctxt->mimeType = (char *) xmlStrndup(mime, last - mime);
766 charset = xmlStrstr(BAD_CAST ctxt->contentType, BAD_CAST "charset=");
767 if (charset != NULL) {
770 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
771 (*last != ';') && (*last != ','))
773 if (ctxt->encoding != NULL)
774 xmlFree(ctxt->encoding);
775 ctxt->encoding = (char *) xmlStrndup(charset, last - charset);
777 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Location:", 9)) {
779 while ((*cur == ' ') || (*cur == '\t')) cur++;
780 if (ctxt->location != NULL)
781 xmlFree(ctxt->location);
783 xmlChar *tmp_http = xmlStrdup(BAD_CAST "http://");
785 xmlStrcat(tmp_http, (const xmlChar *) ctxt->hostname);
787 (char *) xmlStrcat (tmp_loc, (const xmlChar *) cur);
789 ctxt->location = xmlMemStrdup(cur);
791 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"WWW-Authenticate:", 17)) {
793 while ((*cur == ' ') || (*cur == '\t')) cur++;
794 if (ctxt->authHeader != NULL)
795 xmlFree(ctxt->authHeader);
796 ctxt->authHeader = xmlMemStrdup(cur);
797 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Proxy-Authenticate:", 19)) {
799 while ((*cur == ' ') || (*cur == '\t')) cur++;
800 if (ctxt->authHeader != NULL)
801 xmlFree(ctxt->authHeader);
802 ctxt->authHeader = xmlMemStrdup(cur);
804 } else if ( !xmlStrncasecmp( BAD_CAST line, BAD_CAST"Content-Encoding:", 17) ) {
806 while ((*cur == ' ') || (*cur == '\t')) cur++;
807 if ( !xmlStrncasecmp( BAD_CAST cur, BAD_CAST"gzip", 4) ) {
810 ctxt->strm = xmlMalloc(sizeof(z_stream));
812 if (ctxt->strm != NULL) {
813 ctxt->strm->zalloc = Z_NULL;
814 ctxt->strm->zfree = Z_NULL;
815 ctxt->strm->opaque = Z_NULL;
816 ctxt->strm->avail_in = 0;
817 ctxt->strm->next_in = Z_NULL;
819 inflateInit2( ctxt->strm, 31 );
823 } else if ( !xmlStrncasecmp( BAD_CAST line, BAD_CAST"Content-Length:", 15) ) {
825 ctxt->ContentLength = strtol( cur, NULL, 10 );
830 * xmlNanoHTTPConnectAttempt:
831 * @addr: a socket address structure
833 * Attempt a connection to the given IP:port endpoint. It forces
834 * non-blocking semantic on the socket, and allow 60 seconds for
835 * the host to answer.
837 * Returns -1 in case of failure, the file descriptor number otherwise
841 xmlNanoHTTPConnectAttempt(struct sockaddr *addr)
849 #else /* !HAVE_POLL_H */
851 #endif /* !HAVE_POLL_H */
859 if (addr->sa_family == AF_INET6) {
860 s = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
861 addrlen = sizeof(struct sockaddr_in6);
865 s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
866 addrlen = sizeof(struct sockaddr_in);
868 if (s == INVALID_SOCKET) {
872 __xmlIOErr(XML_FROM_HTTP, 0, "socket failed\n");
873 return INVALID_SOCKET;
879 status = ioctlsocket(s, FIONBIO, &one) == SOCKET_ERROR ? -1 : 0;
881 #else /* _WINSOCKAPI_ */
886 status = ioctl(s, FIONBIO, &enable);
889 #if defined(__BEOS__) && !defined(__HAIKU__)
894 setsockopt(s, SOL_SOCKET, SO_NONBLOCK, &noblock,
898 if ((status = fcntl(s, F_GETFL, 0)) != -1) {
900 status |= O_NONBLOCK;
901 #else /* O_NONBLOCK */
904 #endif /* F_NDELAY */
905 #endif /* !O_NONBLOCK */
906 status = fcntl(s, F_SETFL, status);
910 perror("nonblocking");
912 __xmlIOErr(XML_FROM_HTTP, 0, "error setting non-blocking IO\n");
914 return INVALID_SOCKET;
916 #endif /* !__BEOS__ */
918 #endif /* !_WINSOCKAPI_ */
920 if (connect(s, addr, addrlen) == -1) {
921 switch (socket_errno()) {
926 __xmlIOErr(XML_FROM_HTTP, 0,
927 "error connecting to HTTP server");
929 return INVALID_SOCKET;
937 #pragma warning(push)
938 #pragma warning(disable: 4018)
942 return INVALID_SOCKET;
951 switch (select(s + 1, NULL, &wfd, &xfd, &tv))
953 switch (select(s + 1, NULL, &wfd, NULL, &tv))
959 #else /* !HAVE_POLL_H */
962 switch (poll(&p, 1, timeout * 1000))
963 #endif /* !HAVE_POLL_H */
968 __xmlIOErr(XML_FROM_HTTP, 0, "Connect attempt timed out");
970 return INVALID_SOCKET;
973 __xmlIOErr(XML_FROM_HTTP, 0, "Connect failed");
975 return INVALID_SOCKET;
979 if (FD_ISSET(s, &wfd)
984 #else /* !HAVE_POLL_H */
985 if (p.revents == POLLOUT)
986 #endif /* !HAVE_POLL_H */
990 len = sizeof(status);
992 if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char *) &status, &len) <
994 /* Solaris error code */
995 __xmlIOErr(XML_FROM_HTTP, 0, "getsockopt failed\n");
996 return INVALID_SOCKET;
1000 __xmlIOErr(XML_FROM_HTTP, 0,
1001 "Error connecting to remote host");
1004 return INVALID_SOCKET;
1008 __xmlIOErr(XML_FROM_HTTP, 0, "select failed\n");
1010 return INVALID_SOCKET;
1017 * xmlNanoHTTPConnectHost:
1018 * @host: the host name
1019 * @port: the port number
1021 * Attempt a connection to the given host:port endpoint. It tries
1022 * the multiple IP provided by the DNS if available.
1024 * Returns -1 in case of failure, the file descriptor number otherwise
1028 xmlNanoHTTPConnectHost(const char *host, int port)
1031 struct sockaddr *addr = NULL;
1033 struct sockaddr_in sockin;
1036 struct in6_addr ia6;
1037 struct sockaddr_in6 sockin6;
1042 memset (&sockin, 0, sizeof(sockin));
1044 memset (&sockin6, 0, sizeof(sockin6));
1047 #if !defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && defined(RES_USE_INET6)
1050 if (!(_res.options & RES_INIT))
1052 _res.options |= RES_USE_INET6;
1056 #if defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && !defined(_WIN32)
1059 #if defined(HAVE_GETADDRINFO) && (defined(SUPPORT_IP6) || defined(_WIN32))
1062 struct addrinfo hints, *res, *result;
1065 memset (&hints, 0,sizeof(hints));
1066 hints.ai_socktype = SOCK_STREAM;
1068 status = getaddrinfo (host, NULL, &hints, &result);
1070 __xmlIOErr(XML_FROM_HTTP, 0, "getaddrinfo failed\n");
1071 return INVALID_SOCKET;
1074 for (res = result; res; res = res->ai_next) {
1075 if (res->ai_family == AF_INET) {
1076 if (res->ai_addrlen > sizeof(sockin)) {
1077 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1078 freeaddrinfo (result);
1079 return INVALID_SOCKET;
1081 memcpy (&sockin, res->ai_addr, res->ai_addrlen);
1082 sockin.sin_port = htons (port);
1083 addr = (struct sockaddr *)&sockin;
1085 } else if (have_ipv6 () && (res->ai_family == AF_INET6)) {
1086 if (res->ai_addrlen > sizeof(sockin6)) {
1087 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1088 freeaddrinfo (result);
1089 return INVALID_SOCKET;
1091 memcpy (&sockin6, res->ai_addr, res->ai_addrlen);
1092 sockin6.sin6_port = htons (port);
1093 addr = (struct sockaddr *)&sockin6;
1098 s = xmlNanoHTTPConnectAttempt (addr);
1099 if (s != INVALID_SOCKET) {
1100 freeaddrinfo (result);
1106 freeaddrinfo (result);
1109 #if defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && !defined(_WIN32)
1112 #if !defined(HAVE_GETADDRINFO) || !defined(_WIN32)
1114 h = gethostbyname (host);
1118 * Okay, I got fed up by the non-portability of this error message
1119 * extraction code. it work on Linux, if it work on your platform
1120 * and one want to enable it, send me the defined(foobar) needed
1122 #if defined(HAVE_NETDB_H) && defined(HOST_NOT_FOUND) && defined(linux)
1123 const char *h_err_txt = "";
1126 case HOST_NOT_FOUND:
1127 h_err_txt = "Authoritive host not found";
1132 "Non-authoritive host not found or server failure.";
1137 "Non-recoverable errors: FORMERR, REFUSED, or NOTIMP.";
1143 "Valid name, no data record of requested type.";
1148 h_err_txt = "No error text defined.";
1151 __xmlIOErr(XML_FROM_HTTP, 0, h_err_txt);
1153 __xmlIOErr(XML_FROM_HTTP, 0, "Failed to resolve host");
1155 return INVALID_SOCKET;
1158 for (i = 0; h->h_addr_list[i]; i++) {
1159 if (h->h_addrtype == AF_INET) {
1160 /* A records (IPv4) */
1161 if ((unsigned int) h->h_length > sizeof(ia)) {
1162 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1163 return INVALID_SOCKET;
1165 memcpy (&ia, h->h_addr_list[i], h->h_length);
1166 sockin.sin_family = h->h_addrtype;
1167 sockin.sin_addr = ia;
1168 sockin.sin_port = (unsigned short)htons ((unsigned short)port);
1169 addr = (struct sockaddr *) &sockin;
1171 } else if (have_ipv6 () && (h->h_addrtype == AF_INET6)) {
1172 /* AAAA records (IPv6) */
1173 if ((unsigned int) h->h_length > sizeof(ia6)) {
1174 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1175 return INVALID_SOCKET;
1177 memcpy (&ia6, h->h_addr_list[i], h->h_length);
1178 sockin6.sin6_family = h->h_addrtype;
1179 sockin6.sin6_addr = ia6;
1180 sockin6.sin6_port = htons (port);
1181 addr = (struct sockaddr *) &sockin6;
1186 s = xmlNanoHTTPConnectAttempt (addr);
1187 if (s != INVALID_SOCKET)
1194 xmlGenericError(xmlGenericErrorContext,
1195 "xmlNanoHTTPConnectHost: unable to connect to '%s'.\n",
1198 return INVALID_SOCKET;
1204 * @URL: The URL to load
1205 * @contentType: if available the Content-Type information will be
1206 * returned at that location
1208 * This function try to open a connection to the indicated resource
1211 * Returns NULL in case of failure, otherwise a request handler.
1212 * The contentType, if provided must be freed by the caller
1216 xmlNanoHTTPOpen(const char *URL, char **contentType) {
1217 if (contentType != NULL) *contentType = NULL;
1218 return(xmlNanoHTTPMethod(URL, NULL, NULL, contentType, NULL, 0));
1222 * xmlNanoHTTPOpenRedir:
1223 * @URL: The URL to load
1224 * @contentType: if available the Content-Type information will be
1225 * returned at that location
1226 * @redir: if available the redirected URL will be returned
1228 * This function try to open a connection to the indicated resource
1231 * Returns NULL in case of failure, otherwise a request handler.
1232 * The contentType, if provided must be freed by the caller
1236 xmlNanoHTTPOpenRedir(const char *URL, char **contentType, char **redir) {
1237 if (contentType != NULL) *contentType = NULL;
1238 if (redir != NULL) *redir = NULL;
1239 return(xmlNanoHTTPMethodRedir(URL, NULL, NULL, contentType, redir, NULL,0));
1244 * @ctx: the HTTP context
1246 * @len: the buffer length
1248 * This function tries to read @len bytes from the existing HTTP connection
1249 * and saves them in @dest. This is a blocking call.
1251 * Returns the number of byte read. 0 is an indication of an end of connection.
1252 * -1 indicates a parameter error.
1255 xmlNanoHTTPRead(void *ctx, void *dest, int len) {
1256 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1263 if (ctx == NULL) return(-1);
1264 if (dest == NULL) return(-1);
1265 if (len <= 0) return(0);
1268 if (ctxt->usesGzip == 1) {
1269 if (ctxt->strm == NULL) return(0);
1271 ctxt->strm->next_out = dest;
1272 ctxt->strm->avail_out = len;
1273 ctxt->strm->avail_in = ctxt->inptr - ctxt->inrptr;
1275 while (ctxt->strm->avail_out > 0 &&
1276 (ctxt->strm->avail_in > 0 || xmlNanoHTTPRecv(ctxt) > 0)) {
1277 orig_avail_in = ctxt->strm->avail_in =
1278 ctxt->inptr - ctxt->inrptr - bytes_read;
1279 ctxt->strm->next_in = BAD_CAST (ctxt->inrptr + bytes_read);
1281 z_ret = inflate(ctxt->strm, Z_NO_FLUSH);
1282 bytes_read += orig_avail_in - ctxt->strm->avail_in;
1284 if (z_ret != Z_OK) break;
1287 ctxt->inrptr += bytes_read;
1288 return(len - ctxt->strm->avail_out);
1292 while (ctxt->inptr - ctxt->inrptr < len) {
1293 if (xmlNanoHTTPRecv(ctxt) <= 0) break;
1295 if (ctxt->inptr - ctxt->inrptr < len)
1296 len = ctxt->inptr - ctxt->inrptr;
1297 memcpy(dest, ctxt->inrptr, len);
1298 ctxt->inrptr += len;
1304 * @ctx: the HTTP context
1306 * This function closes an HTTP context, it ends up the connection and
1307 * free all data related to it.
1310 xmlNanoHTTPClose(void *ctx) {
1311 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1313 if (ctx == NULL) return;
1315 xmlNanoHTTPFreeCtxt(ctxt);
1319 * xmlNanoHTTPMethodRedir:
1320 * @URL: The URL to load
1321 * @method: the HTTP method to use
1322 * @input: the input string if any
1323 * @contentType: the Content-Type information IN and OUT
1324 * @redir: the redirected URL OUT
1325 * @headers: the extra headers
1326 * @ilen: input length
1328 * This function try to open a connection to the indicated resource
1329 * via HTTP using the given @method, adding the given extra headers
1330 * and the input buffer for the request content.
1332 * Returns NULL in case of failure, otherwise a request handler.
1333 * The contentType, or redir, if provided must be freed by the caller
1337 xmlNanoHTTPMethodRedir(const char *URL, const char *method, const char *input,
1338 char **contentType, char **redir,
1339 const char *headers, int ilen ) {
1340 xmlNanoHTTPCtxtPtr ctxt;
1344 int nbRedirects = 0;
1345 char *redirURL = NULL;
1350 if (URL == NULL) return(NULL);
1351 if (method == NULL) method = "GET";
1355 if (redirURL == NULL)
1356 ctxt = xmlNanoHTTPNewCtxt(URL);
1358 ctxt = xmlNanoHTTPNewCtxt(redirURL);
1359 ctxt->location = xmlMemStrdup(redirURL);
1362 if ( ctxt == NULL ) {
1366 if ((ctxt->protocol == NULL) || (strcmp(ctxt->protocol, "http"))) {
1367 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_URL_SYNTAX, "Not a valid HTTP URI");
1368 xmlNanoHTTPFreeCtxt(ctxt);
1369 if (redirURL != NULL) xmlFree(redirURL);
1372 if (ctxt->hostname == NULL) {
1373 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_UNKNOWN_HOST,
1374 "Failed to identify host in URI");
1375 xmlNanoHTTPFreeCtxt(ctxt);
1376 if (redirURL != NULL) xmlFree(redirURL);
1380 blen = strlen(ctxt->hostname) * 2 + 16;
1381 ret = xmlNanoHTTPConnectHost(proxy, proxyPort);
1384 blen = strlen(ctxt->hostname);
1385 ret = xmlNanoHTTPConnectHost(ctxt->hostname, ctxt->port);
1387 if (ret == INVALID_SOCKET) {
1388 xmlNanoHTTPFreeCtxt(ctxt);
1389 if (redirURL != NULL) xmlFree(redirURL);
1399 if (headers != NULL)
1400 blen += strlen(headers) + 2;
1401 if (contentType && *contentType)
1402 /* reserve for string plus 'Content-Type: \r\n" */
1403 blen += strlen(*contentType) + 16;
1404 if (ctxt->query != NULL)
1406 blen += strlen(ctxt->query) + 1;
1407 blen += strlen(method) + strlen(ctxt->path) + 24;
1409 /* reserve for possible 'Accept-Encoding: gzip' string */
1412 if (ctxt->port != 80) {
1413 /* reserve space for ':xxxxx', incl. potential proxy */
1419 bp = (char*)xmlMallocAtomic(blen);
1421 xmlNanoHTTPFreeCtxt( ctxt );
1422 xmlHTTPErrMemory("allocating header buffer");
1429 if (ctxt->port != 80) {
1430 p += snprintf( p, blen - (p - bp), "%s http://%s:%d%s",
1431 method, ctxt->hostname,
1432 ctxt->port, ctxt->path );
1435 p += snprintf( p, blen - (p - bp), "%s http://%s%s", method,
1436 ctxt->hostname, ctxt->path);
1439 p += snprintf( p, blen - (p - bp), "%s %s", method, ctxt->path);
1441 if (ctxt->query != NULL)
1442 p += snprintf( p, blen - (p - bp), "?%s", ctxt->query);
1444 if (ctxt->port == 80) {
1445 p += snprintf( p, blen - (p - bp), " HTTP/1.0\r\nHost: %s\r\n",
1448 p += snprintf( p, blen - (p - bp), " HTTP/1.0\r\nHost: %s:%d\r\n",
1449 ctxt->hostname, ctxt->port);
1453 p += snprintf(p, blen - (p - bp), "Accept-Encoding: gzip\r\n");
1456 if (contentType != NULL && *contentType)
1457 p += snprintf(p, blen - (p - bp), "Content-Type: %s\r\n", *contentType);
1459 if (headers != NULL)
1460 p += snprintf( p, blen - (p - bp), "%s", headers );
1463 snprintf(p, blen - (p - bp), "Content-Length: %d\r\n\r\n", ilen );
1465 snprintf(p, blen - (p - bp), "\r\n");
1468 xmlGenericError(xmlGenericErrorContext,
1469 "-> %s%s", proxy? "(Proxy) " : "", bp);
1470 if ((blen -= strlen(bp)+1) < 0)
1471 xmlGenericError(xmlGenericErrorContext,
1472 "ERROR: overflowed buffer by %d bytes\n", -blen);
1474 ctxt->outptr = ctxt->out = bp;
1475 ctxt->state = XML_NANO_HTTP_WRITE;
1476 blen = strlen( ctxt->out );
1478 xmt_bytes = xmlNanoHTTPSend(ctxt, ctxt->out, blen );
1479 if ( xmt_bytes != blen )
1480 xmlGenericError( xmlGenericErrorContext,
1481 "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n",
1483 "bytes of HTTP headers sent to host",
1486 xmlNanoHTTPSend(ctxt, ctxt->out, blen );
1489 if ( input != NULL ) {
1491 xmt_bytes = xmlNanoHTTPSend( ctxt, input, ilen );
1493 if ( xmt_bytes != ilen )
1494 xmlGenericError( xmlGenericErrorContext,
1495 "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n",
1497 "bytes of HTTP content sent to host",
1500 xmlNanoHTTPSend( ctxt, input, ilen );
1504 ctxt->state = XML_NANO_HTTP_READ;
1506 while ((p = xmlNanoHTTPReadLine(ctxt)) != NULL) {
1508 ctxt->content = ctxt->inrptr;
1512 xmlNanoHTTPScanAnswer(ctxt, p);
1515 xmlGenericError(xmlGenericErrorContext, "<- %s\n", p);
1520 if ((ctxt->location != NULL) && (ctxt->returnValue >= 300) &&
1521 (ctxt->returnValue < 400)) {
1523 xmlGenericError(xmlGenericErrorContext,
1524 "\nRedirect to: %s\n", ctxt->location);
1526 while ( xmlNanoHTTPRecv(ctxt) > 0 ) ;
1527 if (nbRedirects < XML_NANO_HTTP_MAX_REDIR) {
1529 if (redirURL != NULL)
1531 redirURL = xmlMemStrdup(ctxt->location);
1532 xmlNanoHTTPFreeCtxt(ctxt);
1535 xmlNanoHTTPFreeCtxt(ctxt);
1536 if (redirURL != NULL) xmlFree(redirURL);
1538 xmlGenericError(xmlGenericErrorContext,
1539 "xmlNanoHTTPMethodRedir: Too many redirects, aborting ...\n");
1544 if (contentType != NULL) {
1545 if (ctxt->contentType != NULL)
1546 *contentType = xmlMemStrdup(ctxt->contentType);
1548 *contentType = NULL;
1551 if ((redir != NULL) && (redirURL != NULL)) {
1554 if (redirURL != NULL)
1561 if (ctxt->contentType != NULL)
1562 xmlGenericError(xmlGenericErrorContext,
1563 "\nCode %d, content-type '%s'\n\n",
1564 ctxt->returnValue, ctxt->contentType);
1566 xmlGenericError(xmlGenericErrorContext,
1567 "\nCode %d, no content-type\n\n",
1571 return((void *) ctxt);
1575 * xmlNanoHTTPMethod:
1576 * @URL: The URL to load
1577 * @method: the HTTP method to use
1578 * @input: the input string if any
1579 * @contentType: the Content-Type information IN and OUT
1580 * @headers: the extra headers
1581 * @ilen: input length
1583 * This function try to open a connection to the indicated resource
1584 * via HTTP using the given @method, adding the given extra headers
1585 * and the input buffer for the request content.
1587 * Returns NULL in case of failure, otherwise a request handler.
1588 * The contentType, if provided must be freed by the caller
1592 xmlNanoHTTPMethod(const char *URL, const char *method, const char *input,
1593 char **contentType, const char *headers, int ilen) {
1594 return(xmlNanoHTTPMethodRedir(URL, method, input, contentType,
1595 NULL, headers, ilen));
1600 * @URL: The URL to load
1601 * @filename: the filename where the content should be saved
1602 * @contentType: if available the Content-Type information will be
1603 * returned at that location
1605 * This function try to fetch the indicated resource via HTTP GET
1606 * and save it's content in the file.
1608 * Returns -1 in case of failure, 0 incase of success. The contentType,
1609 * if provided must be freed by the caller
1612 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 if (write(fd, buf, len) == -1) {
1644 xmlNanoHTTPClose(ctxt);
1649 #ifdef LIBXML_OUTPUT_ENABLED
1652 * @ctxt: the HTTP context
1653 * @filename: the filename where the content should be saved
1655 * This function saves the output of the HTTP transaction to a file
1656 * It closes and free the context at the end
1658 * Returns -1 in case of failure, 0 incase of success.
1661 xmlNanoHTTPSave(void *ctxt, const char *filename) {
1667 if ((ctxt == NULL) || (filename == NULL)) return(-1);
1669 if (!strcmp(filename, "-"))
1672 fd = open(filename, O_CREAT | O_WRONLY, 0666);
1674 xmlNanoHTTPClose(ctxt);
1679 xmlNanoHTTPFetchContent( ctxt, &buf, &len );
1681 if (write(fd, buf, len) == -1) {
1686 xmlNanoHTTPClose(ctxt);
1690 #endif /* LIBXML_OUTPUT_ENABLED */
1693 * xmlNanoHTTPReturnCode:
1694 * @ctx: the HTTP context
1696 * Get the latest HTTP return code received
1698 * Returns the HTTP return code for the request.
1701 xmlNanoHTTPReturnCode(void *ctx) {
1702 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1704 if (ctxt == NULL) return(-1);
1706 return(ctxt->returnValue);
1710 * xmlNanoHTTPAuthHeader:
1711 * @ctx: the HTTP context
1713 * Get the authentication header of an HTTP context
1715 * Returns the stashed value of the WWW-Authenticate or Proxy-Authenticate
1719 xmlNanoHTTPAuthHeader(void *ctx) {
1720 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1722 if (ctxt == NULL) return(NULL);
1724 return(ctxt->authHeader);
1728 * xmlNanoHTTPContentLength:
1729 * @ctx: the HTTP context
1731 * Provides the specified content length from the HTTP header.
1733 * Return the specified content length from the HTTP header. Note that
1734 * a value of -1 indicates that the content length element was not included in
1735 * the response header.
1738 xmlNanoHTTPContentLength( void * ctx ) {
1739 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1741 return ( ( ctxt == NULL ) ? -1 : ctxt->ContentLength );
1746 * @ctx: the HTTP context
1748 * Provides the specified redirection URL if available from the HTTP header.
1750 * Return the specified redirection URL or NULL if not redirected.
1753 xmlNanoHTTPRedir( void * ctx ) {
1754 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1756 return ( ( ctxt == NULL ) ? NULL : ctxt->location );
1760 * xmlNanoHTTPEncoding:
1761 * @ctx: the HTTP context
1763 * Provides the specified encoding if specified in the HTTP headers.
1765 * Return the specified encoding or NULL if not available
1768 xmlNanoHTTPEncoding( void * ctx ) {
1769 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1771 return ( ( ctxt == NULL ) ? NULL : ctxt->encoding );
1775 * xmlNanoHTTPMimeType:
1776 * @ctx: the HTTP context
1778 * Provides the specified Mime-Type if specified in the HTTP headers.
1780 * Return the specified Mime-Type or NULL if not available
1783 xmlNanoHTTPMimeType( void * ctx ) {
1784 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1786 return ( ( ctxt == NULL ) ? NULL : ctxt->mimeType );
1790 * xmlNanoHTTPFetchContent:
1791 * @ctx: the HTTP context
1792 * @ptr: pointer to set to the content buffer.
1793 * @len: integer pointer to hold the length of the content
1795 * Check if all the content was read
1797 * Returns 0 if all the content was read and available, returns
1798 * -1 if received content length was less than specified or an error
1802 xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len ) {
1803 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1809 char * dummy_ptr = NULL;
1811 /* Dummy up return input parameters if not provided */
1819 /* But can't work without the context pointer */
1821 if ( ( ctxt == NULL ) || ( ctxt->content == NULL ) ) {
1827 rcvd_lgth = ctxt->inptr - ctxt->content;
1829 while ( (cur_lgth = xmlNanoHTTPRecv( ctxt )) > 0 ) {
1831 rcvd_lgth += cur_lgth;
1832 if ( (ctxt->ContentLength > 0) && (rcvd_lgth >= ctxt->ContentLength) )
1836 *ptr = ctxt->content;
1839 if ( ( ctxt->ContentLength > 0 ) && ( rcvd_lgth < ctxt->ContentLength ) )
1841 else if ( rcvd_lgth == 0 )
1848 int main(int argc, char **argv) {
1849 char *contentType = NULL;
1851 if (argv[1] != NULL) {
1852 if (argv[2] != NULL)
1853 xmlNanoHTTPFetch(argv[1], argv[2], &contentType);
1855 xmlNanoHTTPFetch(argv[1], "-", &contentType);
1856 if (contentType != NULL) xmlFree(contentType);
1858 xmlGenericError(xmlGenericErrorContext,
1859 "%s: minimal HTTP GET implementation\n", argv[0]);
1860 xmlGenericError(xmlGenericErrorContext,
1861 "\tusage %s [ URL [ filename ] ]\n", argv[0]);
1863 xmlNanoHTTPCleanup();
1867 #endif /* STANDALONE */
1868 #else /* !LIBXML_HTTP_ENABLED */
1871 int main(int argc, char **argv) {
1872 xmlGenericError(xmlGenericErrorContext,
1873 "%s : HTTP support not compiled in\n", argv[0]);
1876 #endif /* STANDALONE */
1877 #endif /* LIBXML_HTTP_ENABLED */
1878 #define bottom_nanohttp
1879 #include "elfgcchack.h"