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.
14 /* TODO add compression support, Send the Accept- , and decompress on the
15 fly with ZLIB if found at compile-time */
21 #ifdef LIBXML_HTTP_ENABLED
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>
69 #define SOCKLEN_T unsigned int
73 #include <libxml/globals.h>
74 #include <libxml/xmlerror.h>
75 #include <libxml/xmlmemory.h>
76 #include <libxml/parser.h> /* for xmlStr(n)casecmp() */
77 #include <libxml/nanohttp.h>
78 #include <libxml/globals.h>
79 #include <libxml/uri.h>
82 * A couple portability macros
85 #define closesocket(s) close(s)
90 #define SOCKLEN_T unsigned int
98 #define xmlStrncasecmp(a, b, n) strncasecmp((char *)a, (char *)b, n)
99 #define xmlStrcasecmpi(a, b) strcasecmp((char *)a, (char *)b)
102 #define XML_NANO_HTTP_MAX_REDIR 10
104 #define XML_NANO_HTTP_CHUNK 4096
106 #define XML_NANO_HTTP_CLOSED 0
107 #define XML_NANO_HTTP_WRITE 1
108 #define XML_NANO_HTTP_READ 2
109 #define XML_NANO_HTTP_NONE 4
111 typedef struct xmlNanoHTTPCtxt {
112 char *protocol; /* the protocol name */
113 char *hostname; /* the host name */
114 int port; /* the port */
115 char *path; /* the path within the URL */
116 SOCKET fd; /* the file descriptor for the socket */
117 int state; /* WRITE / READ / CLOSED */
118 char *out; /* buffer sent (zero terminated) */
119 char *outptr; /* index within the buffer sent */
120 char *in; /* the receiving buffer */
121 char *content; /* the start of the content */
122 char *inptr; /* the next byte to read from network */
123 char *inrptr; /* the next byte to give back to the client */
124 int inlen; /* len of the input buffer */
125 int last; /* return code for last operation */
126 int returnValue; /* the protocol return value */
127 int ContentLength; /* specified content length from HTTP header */
128 char *contentType; /* the MIME type for the input */
129 char *location; /* the new URL in case of redirect */
130 char *authHeader; /* contents of {WWW,Proxy}-Authenticate header */
131 } xmlNanoHTTPCtxt, *xmlNanoHTTPCtxtPtr;
133 static int initialized = 0;
134 static char *proxy = NULL; /* the proxy name if any */
135 static int proxyPort; /* the proxy port if any */
136 static unsigned int timeout = 60;/* the select() timeout in seconds */
138 int xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len );
139 int xmlNanoHTTPContentLength( void * ctx );
142 * A portability function
144 static int socket_errno(void) {
146 return(WSAGetLastError());
155 * Initialize the HTTP protocol layer.
156 * Currently it just checks for proxy informations
160 xmlNanoHTTPInit(void) {
170 if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
176 env = getenv("no_proxy");
179 env = getenv("http_proxy");
181 xmlNanoHTTPScanProxy(env);
184 env = getenv("HTTP_PROXY");
186 xmlNanoHTTPScanProxy(env);
195 * xmlNanoHTTPCleanup:
197 * Cleanup the HTTP protocol layer.
201 xmlNanoHTTPCleanup(void) {
213 * xmlNanoHTTPScanURL:
214 * @ctxt: an HTTP context
215 * @URL: The URL used to initialize the context
217 * (Re)Initialize an HTTP context by parsing the URL and finding
218 * the protocol host port and path it indicates.
222 xmlNanoHTTPScanURL(xmlNanoHTTPCtxtPtr ctxt, const char *URL) {
223 const char *cur = URL;
228 if (ctxt->protocol != NULL) {
229 xmlFree(ctxt->protocol);
230 ctxt->protocol = NULL;
232 if (ctxt->hostname != NULL) {
233 xmlFree(ctxt->hostname);
234 ctxt->hostname = NULL;
236 if (ctxt->path != NULL) {
240 if (URL == NULL) return;
243 if ((cur[0] == ':') && (cur[1] == '/') && (cur[2] == '/')) {
245 ctxt->protocol = xmlMemStrdup(buf);
250 buf[indx++] = *cur++;
252 if (*cur == 0) return;
258 ctxt->hostname = xmlMemStrdup(buf);
261 while ((*cur >= '0') && (*cur <= '9')) {
266 if (port != 0) ctxt->port = port;
267 while ((cur[0] != '/') && (*cur != 0))
271 if ((*cur == '/') || (*cur == 0)) {
273 ctxt->hostname = xmlMemStrdup(buf);
277 buf[indx++] = *cur++;
280 ctxt->path = xmlMemStrdup("/");
285 buf[indx++] = *cur++;
287 ctxt->path = xmlMemStrdup(buf);
292 * xmlNanoHTTPScanProxy:
293 * @URL: The proxy URL used to initialize the proxy context
295 * (Re)Initialize the HTTP Proxy context by parsing the URL and finding
296 * the protocol host port it indicates.
297 * Should be like http://myproxy/ or http://myproxy:3128/
298 * A NULL URL cleans up proxy informations.
302 xmlNanoHTTPScanProxy(const char *URL) {
303 const char *cur = URL;
312 if (proxyPort != 0) {
317 xmlGenericError(xmlGenericErrorContext,
318 "Removing HTTP proxy info\n");
320 xmlGenericError(xmlGenericErrorContext,
321 "Using HTTP proxy %s\n", URL);
323 if (URL == NULL) return;
326 if ((cur[0] == ':') && (cur[1] == '/') && (cur[2] == '/')) {
332 buf[indx++] = *cur++;
334 if (*cur == 0) return;
340 proxy = xmlMemStrdup(buf);
343 while ((*cur >= '0') && (*cur <= '9')) {
348 if (port != 0) proxyPort = port;
349 while ((cur[0] != '/') && (*cur != 0))
353 if ((*cur == '/') || (*cur == 0)) {
355 proxy = xmlMemStrdup(buf);
359 buf[indx++] = *cur++;
364 * xmlNanoHTTPNewCtxt:
365 * @URL: The URL used to initialize the context
367 * Allocate and initialize a new HTTP context.
369 * Returns an HTTP context or NULL in case of error.
372 static xmlNanoHTTPCtxtPtr
373 xmlNanoHTTPNewCtxt(const char *URL) {
374 xmlNanoHTTPCtxtPtr ret;
376 ret = (xmlNanoHTTPCtxtPtr) xmlMalloc(sizeof(xmlNanoHTTPCtxt));
377 if (ret == NULL) return(NULL);
379 memset(ret, 0, sizeof(xmlNanoHTTPCtxt));
381 ret->returnValue = 0;
383 ret->ContentLength = -1;
385 xmlNanoHTTPScanURL(ret, URL);
391 * xmlNanoHTTPFreeCtxt:
392 * @ctxt: an HTTP context
394 * Frees the context after closing the connection.
398 xmlNanoHTTPFreeCtxt(xmlNanoHTTPCtxtPtr ctxt) {
399 if (ctxt == NULL) return;
400 if (ctxt->hostname != NULL) xmlFree(ctxt->hostname);
401 if (ctxt->protocol != NULL) xmlFree(ctxt->protocol);
402 if (ctxt->path != NULL) xmlFree(ctxt->path);
403 if (ctxt->out != NULL) xmlFree(ctxt->out);
404 if (ctxt->in != NULL) xmlFree(ctxt->in);
405 if (ctxt->contentType != NULL) xmlFree(ctxt->contentType);
406 if (ctxt->location != NULL) xmlFree(ctxt->location);
407 if (ctxt->authHeader != NULL) xmlFree(ctxt->authHeader);
408 ctxt->state = XML_NANO_HTTP_NONE;
409 if (ctxt->fd >= 0) closesocket(ctxt->fd);
416 * @ctxt: an HTTP context
418 * Send the input needed to initiate the processing on the server side
419 * Returns number of bytes sent or -1 on error.
423 xmlNanoHTTPSend(xmlNanoHTTPCtxtPtr ctxt, const char * xmt_ptr, int outlen) {
427 if ( (ctxt->state & XML_NANO_HTTP_WRITE) && (xmt_ptr != NULL ) ) {
428 while (total_sent < outlen) {
429 int nsent = send(ctxt->fd, xmt_ptr + total_sent,
430 outlen - total_sent, 0);
433 else if ( ( nsent == -1 ) &&
434 #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
435 ( socket_errno( ) != EAGAIN ) &&
437 ( socket_errno( ) != EWOULDBLOCK ) ) {
438 xmlGenericError( xmlGenericErrorContext,
439 "xmlNanoHTTPSend error: %s",
440 strerror( socket_errno( ) ) );
442 if ( total_sent == 0 )
449 ** Since non-blocking sockets are used, wait for
450 ** socket to be writable or default timeout prior
460 FD_SET( ctxt->fd, &wfd );
461 (void)select( ctxt->fd + 1, NULL, &wfd, NULL, &tv );
471 * @ctxt: an HTTP context
473 * Read information coming from the HTTP connection.
474 * This is a blocking call (but it blocks in select(), not read()).
476 * Returns the number of byte read or -1 in case of error.
480 xmlNanoHTTPRecv(xmlNanoHTTPCtxtPtr ctxt) {
485 while (ctxt->state & XML_NANO_HTTP_READ) {
486 if (ctxt->in == NULL) {
487 ctxt->in = (char *) xmlMalloc(65000 * sizeof(char));
488 if (ctxt->in == NULL) {
490 xmlGenericError( xmlGenericErrorContext,
491 "xmlNanoHTTPRecv: Error allocating input memory." );
495 ctxt->inptr = ctxt->content = ctxt->inrptr = ctxt->in;
497 if (ctxt->inrptr > ctxt->in + XML_NANO_HTTP_CHUNK) {
498 int delta = ctxt->inrptr - ctxt->in;
499 int len = ctxt->inptr - ctxt->inrptr;
501 memmove(ctxt->in, ctxt->inrptr, len);
502 ctxt->inrptr -= delta;
503 ctxt->content -= delta;
504 ctxt->inptr -= delta;
506 if ((ctxt->in + ctxt->inlen) < (ctxt->inptr + XML_NANO_HTTP_CHUNK)) {
507 int d_inptr = ctxt->inptr - ctxt->in;
508 int d_content = ctxt->content - ctxt->in;
509 int d_inrptr = ctxt->inrptr - ctxt->in;
510 char * tmp_ptr = ctxt->in;
513 ctxt->in = (char *) xmlRealloc(tmp_ptr, ctxt->inlen);
514 if (ctxt->in == NULL) {
515 xmlGenericError( xmlGenericErrorContext,
516 "xmlNanoHTTPRecv: %s %d bytes.",
517 "Failed to realloc input buffer to",
523 ctxt->inptr = ctxt->in + d_inptr;
524 ctxt->content = ctxt->in + d_content;
525 ctxt->inrptr = ctxt->in + d_inrptr;
527 ctxt->last = recv(ctxt->fd, ctxt->inptr, XML_NANO_HTTP_CHUNK, 0);
528 if (ctxt->last > 0) {
529 ctxt->inptr += ctxt->last;
532 if (ctxt->last == 0) {
535 if (ctxt->last == -1) {
536 switch (socket_errno()) {
539 #if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
549 xmlGenericError( xmlGenericErrorContext,
550 "xmlNanoHTTPRecv: recv( ) failure - %s",
551 strerror( socket_errno( ) ) );
559 FD_SET(ctxt->fd, &rfd);
561 if ( (select(ctxt->fd+1, &rfd, NULL, NULL, &tv)<1)
572 * xmlNanoHTTPReadLine:
573 * @ctxt: an HTTP context
575 * Read one line in the HTTP server output, usually for extracting
576 * the HTTP protocol informations from the answer header.
578 * Returns a newly allocated string with a copy of the line, or NULL
579 * which indicate the end of the input.
583 xmlNanoHTTPReadLine(xmlNanoHTTPCtxtPtr ctxt) {
588 while (bp - buf < 4095) {
589 if (ctxt->inrptr == ctxt->inptr) {
590 if ( (rc = xmlNanoHTTPRecv(ctxt)) == 0) {
595 return(xmlMemStrdup(buf));
597 else if ( rc == -1 ) {
601 *bp = *ctxt->inrptr++;
604 return(xmlMemStrdup(buf));
610 return(xmlMemStrdup(buf));
615 * xmlNanoHTTPScanAnswer:
616 * @ctxt: an HTTP context
617 * @line: an HTTP header line
619 * Try to extract useful informations from the server answer.
620 * We currently parse and process:
621 * - The HTTP revision/ return code
623 * - The Location for redirect processing.
625 * Returns -1 in case of failure, the file descriptor number otherwise
629 xmlNanoHTTPScanAnswer(xmlNanoHTTPCtxtPtr ctxt, const char *line) {
630 const char *cur = line;
632 if (line == NULL) return;
634 if (!strncmp(line, "HTTP/", 5)) {
639 while ((*cur >= '0') && (*cur <= '9')) {
641 version += *cur - '0';
646 if ((*cur >= '0') && (*cur <= '9')) {
648 version += *cur - '0';
651 while ((*cur >= '0') && (*cur <= '9'))
655 if ((*cur != ' ') && (*cur != '\t')) return;
656 while ((*cur == ' ') || (*cur == '\t')) cur++;
657 if ((*cur < '0') || (*cur > '9')) return;
658 while ((*cur >= '0') && (*cur <= '9')) {
663 if ((*cur != 0) && (*cur != ' ') && (*cur != '\t')) return;
664 ctxt->returnValue = ret;
665 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Content-Type:", 13)) {
667 while ((*cur == ' ') || (*cur == '\t')) cur++;
668 if (ctxt->contentType != NULL)
669 xmlFree(ctxt->contentType);
670 ctxt->contentType = xmlMemStrdup(cur);
671 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"ContentType:", 12)) {
673 if (ctxt->contentType != NULL) return;
674 while ((*cur == ' ') || (*cur == '\t')) cur++;
675 ctxt->contentType = xmlMemStrdup(cur);
676 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Location:", 9)) {
678 while ((*cur == ' ') || (*cur == '\t')) cur++;
679 if (ctxt->location != NULL)
680 xmlFree(ctxt->location);
681 ctxt->location = xmlMemStrdup(cur);
682 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"WWW-Authenticate:", 17)) {
684 while ((*cur == ' ') || (*cur == '\t')) cur++;
685 if (ctxt->authHeader != NULL)
686 xmlFree(ctxt->authHeader);
687 ctxt->authHeader = xmlMemStrdup(cur);
688 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Proxy-Authenticate:", 19)) {
690 while ((*cur == ' ') || (*cur == '\t')) cur++;
691 if (ctxt->authHeader != NULL)
692 xmlFree(ctxt->authHeader);
693 ctxt->authHeader = xmlMemStrdup(cur);
694 } else if ( !xmlStrncasecmp( BAD_CAST line, BAD_CAST"Content-Length:", 15) ) {
696 ctxt->ContentLength = strtol( cur, NULL, 10 );
701 * xmlNanoHTTPConnectAttempt:
702 * @addr: a socket address structure
704 * Attempt a connection to the given IP:port endpoint. It forces
705 * non-blocking semantic on the socket, and allow 60 seconds for
706 * the host to answer.
708 * Returns -1 in case of failure, the file descriptor number otherwise
712 xmlNanoHTTPConnectAttempt(struct sockaddr *addr)
714 SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
723 xmlGenericError( xmlGenericErrorContext,
724 "xmlNanoHTTPConnectAttempt: %s - %s",
725 "socket creation failure",
726 strerror( socket_errno( ) ) );
734 status = ioctlsocket(s, FIONBIO, &one) == SOCKET_ERROR ? -1 : 0;
736 #else /* _WINSOCKAPI_ */
740 status = ioctl(s, FIONBIO, &enable);
743 if ((status = fcntl(s, F_GETFL, 0)) != -1) {
745 status |= O_NONBLOCK;
746 #else /* O_NONBLOCK */
749 #endif /* F_NDELAY */
750 #endif /* !O_NONBLOCK */
751 status = fcntl(s, F_SETFL, status);
755 perror("nonblocking");
757 xmlGenericError( xmlGenericErrorContext,
758 "xmlNanoHTTPConnectAttempt: %s - %s",
759 "error setting non-blocking IO",
760 strerror( socket_errno( ) ) );
765 #endif /* !_WINSOCKAPI_ */
767 if ((connect(s, addr, sizeof(*addr))==-1)) {
768 switch (socket_errno()) {
773 xmlGenericError( xmlGenericErrorContext,
774 "xmlNanoHTTPConnectAttempt: %s - %s",
775 "error connecting to HTTP server",
776 strerror( socket_errno( ) ) );
788 switch(select(s+1, NULL, &wfd, NULL, &tv))
792 xmlGenericError( xmlGenericErrorContext,
793 "xmlNanoHTTPConnectAttempt: %s",
794 "Connect attempt timed out." );
799 xmlGenericError( xmlGenericErrorContext,
800 "xmlNanoHTTPConnectAttempt: %s - %s",
801 "Error connecting to host",
802 strerror( socket_errno( ) ) );
807 if ( FD_ISSET(s, &wfd) ) {
809 len = sizeof(status);
810 if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char*)&status, &len) < 0 ) {
811 /* Solaris error code */
812 xmlGenericError( xmlGenericErrorContext,
813 "xmlNanoHTTPConnectAttempt: %s - %s",
814 "Error retrieving pending socket errors",
815 strerror( socket_errno( ) ) );
821 xmlGenericError( xmlGenericErrorContext,
822 "xmlNanoHTTPConnectAttempt: %s - %s",
823 "Error connecting to remote host",
824 strerror( status ) );
829 xmlGenericError( xmlGenericErrorContext,
830 "xmlNanoHTTPConnectAttempt: %s\n",
831 "Select returned, but descriptor not set for connection.\n" );
840 * xmlNanoHTTPConnectHost:
841 * @host: the host name
842 * @port: the port number
844 * Attempt a connection to the given host:port endpoint. It tries
845 * the multiple IP provided by the DNS if available.
847 * Returns -1 in case of failure, the file descriptor number otherwise
851 xmlNanoHTTPConnectHost(const char *host, int port)
854 struct sockaddr *addr;
856 struct sockaddr_in sockin;
860 struct sockaddr_in6 sockin6;
865 #if defined(SUPPORT_IP6) && defined(RES_USE_INET6)
866 if (!(_res.options & RES_INIT))
868 _res.options |= RES_USE_INET6;
870 h = gethostbyname(host);
874 * Okay, I got fed up by the non-portability of this error message
875 * extraction code. it work on Linux, if it work on your platform
876 * and one want to enable it, send me the defined(foobar) needed
878 #if defined(HAVE_NETDB_H) && defined(HOST_NOT_FOUND) && defined(linux)
879 const char *h_err_txt = "";
883 h_err_txt = "Authoritive host not found";
888 "Non-authoritive host not found or server failure.";
893 "Non-recoverable errors: FORMERR, REFUSED, or NOTIMP.";
898 "Valid name, no data record of requested type.";
902 h_err_txt = "No error text defined.";
905 xmlGenericError(xmlGenericErrorContext,
906 "xmlNanoHTTPConnectHost: %s '%s' - %s",
907 "Failed to resolve host", host, h_err_txt);
909 xmlGenericError(xmlGenericErrorContext,
910 "xmlNanoHTTPConnectHost: %s '%s'",
911 "Failed to resolve host", host);
916 for (i = 0; h->h_addr_list[i]; i++) {
917 if (h->h_addrtype == AF_INET) {
918 /* A records (IPv4) */
919 memcpy(&ia, h->h_addr_list[i], h->h_length);
920 sockin.sin_family = h->h_addrtype;
921 sockin.sin_addr = ia;
922 sockin.sin_port = htons(port);
923 addr = (struct sockaddr *) &sockin;
925 } else if (h->h_addrtype == AF_INET6) {
926 /* AAAA records (IPv6) */
927 memcpy(&ia6, h->h_addr_list[i], h->h_length);
928 sockin6.sin_family = h->h_addrtype;
929 sockin6.sin_addr = ia6;
930 sockin6.sin_port = htons(port);
931 addr = (struct sockaddr *) &sockin6;
936 s = xmlNanoHTTPConnectAttempt(addr);
942 xmlGenericError(xmlGenericErrorContext,
943 "xmlNanoHTTPConnectHost: unable to connect to '%s'.\n",
952 * @URL: The URL to load
953 * @contentType: if available the Content-Type information will be
954 * returned at that location
956 * This function try to open a connection to the indicated resource
959 * Returns NULL in case of failure, otherwise a request handler.
960 * The contentType, if provided must be freed by the caller
964 xmlNanoHTTPOpen(const char *URL, char **contentType) {
965 if (contentType != NULL) *contentType = NULL;
966 return(xmlNanoHTTPMethod(URL, NULL, NULL, contentType, NULL, 0));
970 * xmlNanoHTTPOpenRedir:
971 * @URL: The URL to load
972 * @contentType: if available the Content-Type information will be
973 * returned at that location
974 * @redir: if available the redirected URL will be returned
976 * This function try to open a connection to the indicated resource
979 * Returns NULL in case of failure, otherwise a request handler.
980 * The contentType, if provided must be freed by the caller
984 xmlNanoHTTPOpenRedir(const char *URL, char **contentType, char **redir) {
985 if (contentType != NULL) *contentType = NULL;
986 if (redir != NULL) *redir = NULL;
987 return(xmlNanoHTTPMethodRedir(URL, NULL, NULL, contentType, redir, NULL,0));
992 * @ctx: the HTTP context
994 * @len: the buffer length
996 * This function tries to read @len bytes from the existing HTTP connection
997 * and saves them in @dest. This is a blocking call.
999 * Returns the number of byte read. 0 is an indication of an end of connection.
1000 * -1 indicates a parameter error.
1003 xmlNanoHTTPRead(void *ctx, void *dest, int len) {
1004 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1006 if (ctx == NULL) return(-1);
1007 if (dest == NULL) return(-1);
1008 if (len <= 0) return(0);
1010 while (ctxt->inptr - ctxt->inrptr < len) {
1011 if (xmlNanoHTTPRecv(ctxt) <= 0) break;
1013 if (ctxt->inptr - ctxt->inrptr < len)
1014 len = ctxt->inptr - ctxt->inrptr;
1015 memcpy(dest, ctxt->inrptr, len);
1016 ctxt->inrptr += len;
1022 * @ctx: the HTTP context
1024 * This function closes an HTTP context, it ends up the connection and
1025 * free all data related to it.
1028 xmlNanoHTTPClose(void *ctx) {
1029 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1031 if (ctx == NULL) return;
1033 xmlNanoHTTPFreeCtxt(ctxt);
1037 * xmlNanoHTTPMethodRedir:
1038 * @URL: The URL to load
1039 * @method: the HTTP method to use
1040 * @input: the input string if any
1041 * @contentType: the Content-Type information IN and OUT
1042 * @redir: the redirected URL OUT
1043 * @headers: the extra headers
1044 * @ilen: input length
1046 * This function try to open a connection to the indicated resource
1047 * via HTTP using the given @method, adding the given extra headers
1048 * and the input buffer for the request content.
1050 * Returns NULL in case of failure, otherwise a request handler.
1051 * The contentType, or redir, if provided must be freed by the caller
1055 xmlNanoHTTPMethodRedir(const char *URL, const char *method, const char *input,
1056 char **contentType, char **redir,
1057 const char *headers, int ilen ) {
1058 xmlNanoHTTPCtxtPtr ctxt;
1063 int nbRedirects = 0;
1064 char *redirURL = NULL;
1066 if (URL == NULL) return(NULL);
1067 if (method == NULL) method = "GET";
1071 if (redirURL == NULL)
1072 ctxt = xmlNanoHTTPNewCtxt(URL);
1074 ctxt = xmlNanoHTTPNewCtxt(redirURL);
1077 if ( ctxt == NULL ) {
1078 xmlGenericError( xmlGenericErrorContext,
1079 "xmlNanoHTTPMethodRedir: %s %s.",
1080 "Unable to allocate HTTP context to URI",
1081 ( ( redirURL == NULL ) ? URL : redirURL ) );
1085 if ((ctxt->protocol == NULL) || (strcmp(ctxt->protocol, "http"))) {
1086 xmlGenericError( xmlGenericErrorContext,
1087 "xmlNanoHTTPMethodRedir: %s - %s.",
1088 "Not a valid HTTP URI",
1089 ( ( redirURL == NULL ) ? URL : redirURL ) );
1090 xmlNanoHTTPFreeCtxt(ctxt);
1091 if (redirURL != NULL) xmlFree(redirURL);
1094 if (ctxt->hostname == NULL) {
1095 xmlGenericError( xmlGenericErrorContext,
1096 "xmlNanoHTTPMethodRedir: %s - %s",
1097 "Failed to identify host in URI",
1098 ( ( redirURL == NULL ) ? URL : redirURL ) );
1099 xmlNanoHTTPFreeCtxt(ctxt);
1100 if (redirURL != NULL) xmlFree(redirURL);
1104 blen = strlen(ctxt->hostname) * 2 + 16;
1105 ret = xmlNanoHTTPConnectHost(proxy, proxyPort);
1108 blen = strlen(ctxt->hostname);
1109 ret = xmlNanoHTTPConnectHost(ctxt->hostname, ctxt->port);
1112 xmlNanoHTTPFreeCtxt(ctxt);
1113 if (redirURL != NULL) xmlFree(redirURL);
1123 if (headers != NULL)
1124 blen += strlen(headers) + 2;
1125 if (contentType && *contentType)
1126 blen += strlen(*contentType) + 16;
1127 blen += strlen(method) + strlen(ctxt->path) + 24;
1128 bp = xmlMalloc(blen);
1130 xmlNanoHTTPFreeCtxt( ctxt );
1131 xmlGenericError( xmlGenericErrorContext,
1132 "xmlNanoHTTPMethodRedir: %s",
1133 "Error allocating HTTP header buffer." );
1140 if (ctxt->port != 80) {
1141 p += snprintf( p, blen - (p - bp), "%s http://%s:%d%s",
1142 method, ctxt->hostname,
1143 ctxt->port, ctxt->path );
1146 p += snprintf( p, blen - (p - bp), "%s http://%s%s", method,
1147 ctxt->hostname, ctxt->path);
1150 p += snprintf( p, blen - (p - bp), "%s %s", method, ctxt->path);
1152 p += snprintf( p, blen - (p - bp), " HTTP/1.0\r\nHost: %s\r\n",
1155 if (contentType != NULL && *contentType)
1156 p += snprintf(p, blen - (p - bp), "Content-Type: %s\r\n", *contentType);
1158 if (headers != NULL)
1159 p += snprintf( p, blen - (p - bp), "%s", headers );
1162 snprintf(p, blen - (p - bp), "Content-Length: %d\r\n\r\n", ilen );
1164 snprintf(p, blen - (p - bp), "\r\n");
1167 xmlGenericError(xmlGenericErrorContext,
1168 "-> %s%s", proxy? "(Proxy) " : "", bp);
1169 if ((blen -= strlen(bp)+1) < 0)
1170 xmlGenericError(xmlGenericErrorContext,
1171 "ERROR: overflowed buffer by %d bytes\n", -blen);
1173 ctxt->outptr = ctxt->out = bp;
1174 ctxt->state = XML_NANO_HTTP_WRITE;
1175 blen = strlen( ctxt->out );
1176 xmt_bytes = xmlNanoHTTPSend(ctxt, ctxt->out, blen );
1178 if ( xmt_bytes != blen )
1179 xmlGenericError( xmlGenericErrorContext,
1180 "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n",
1182 "bytes of HTTP headers sent to host",
1186 if ( input != NULL ) {
1187 xmt_bytes = xmlNanoHTTPSend( ctxt, input, ilen );
1190 if ( xmt_bytes != ilen )
1191 xmlGenericError( xmlGenericErrorContext,
1192 "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n",
1194 "bytes of HTTP content sent to host",
1199 ctxt->state = XML_NANO_HTTP_READ;
1202 while ((p = xmlNanoHTTPReadLine(ctxt)) != NULL) {
1203 if (head && (*p == 0)) {
1205 ctxt->content = ctxt->inrptr;
1209 xmlNanoHTTPScanAnswer(ctxt, p);
1212 xmlGenericError(xmlGenericErrorContext, "<- %s\n", p);
1217 if ((ctxt->location != NULL) && (ctxt->returnValue >= 300) &&
1218 (ctxt->returnValue < 400)) {
1220 xmlGenericError(xmlGenericErrorContext,
1221 "\nRedirect to: %s\n", ctxt->location);
1223 while ( xmlNanoHTTPRecv(ctxt) > 0 ) ;
1224 if (nbRedirects < XML_NANO_HTTP_MAX_REDIR) {
1226 if (redirURL != NULL)
1228 redirURL = xmlMemStrdup(ctxt->location);
1229 xmlNanoHTTPFreeCtxt(ctxt);
1232 xmlNanoHTTPFreeCtxt(ctxt);
1233 if (redirURL != NULL) xmlFree(redirURL);
1235 xmlGenericError(xmlGenericErrorContext,
1236 "xmlNanoHTTPMethodRedir: Too many redirects, aborting ...\n");
1241 if (contentType != NULL) {
1242 if (ctxt->contentType != NULL)
1243 *contentType = xmlMemStrdup(ctxt->contentType);
1245 *contentType = NULL;
1248 if ((redir != NULL) && (redirURL != NULL)) {
1251 if (redirURL != NULL)
1258 if (ctxt->contentType != NULL)
1259 xmlGenericError(xmlGenericErrorContext,
1260 "\nCode %d, content-type '%s'\n\n",
1261 ctxt->returnValue, ctxt->contentType);
1263 xmlGenericError(xmlGenericErrorContext,
1264 "\nCode %d, no content-type\n\n",
1268 return((void *) ctxt);
1272 * xmlNanoHTTPMethod:
1273 * @URL: The URL to load
1274 * @method: the HTTP method to use
1275 * @input: the input string if any
1276 * @contentType: the Content-Type information IN and OUT
1277 * @headers: the extra headers
1278 * @ilen: input length
1280 * This function try to open a connection to the indicated resource
1281 * via HTTP using the given @method, adding the given extra headers
1282 * and the input buffer for the request content.
1284 * Returns NULL in case of failure, otherwise a request handler.
1285 * The contentType, if provided must be freed by the caller
1289 xmlNanoHTTPMethod(const char *URL, const char *method, const char *input,
1290 char **contentType, const char *headers, int ilen) {
1291 return(xmlNanoHTTPMethodRedir(URL, method, input, contentType,
1292 NULL, headers, ilen));
1297 * @URL: The URL to load
1298 * @filename: the filename where the content should be saved
1299 * @contentType: if available the Content-Type information will be
1300 * returned at that location
1302 * This function try to fetch the indicated resource via HTTP GET
1303 * and save it's content in the file.
1305 * Returns -1 in case of failure, 0 incase of success. The contentType,
1306 * if provided must be freed by the caller
1309 xmlNanoHTTPFetch(const char *URL, const char *filename, char **contentType) {
1315 ctxt = xmlNanoHTTPOpen(URL, contentType);
1316 if (ctxt == NULL) return(-1);
1318 if (!strcmp(filename, "-"))
1321 fd = open(filename, O_CREAT | O_WRONLY, 00644);
1323 xmlNanoHTTPClose(ctxt);
1324 if ((contentType != NULL) && (*contentType != NULL)) {
1325 xmlFree(*contentType);
1326 *contentType = NULL;
1332 xmlNanoHTTPFetchContent( ctxt, &buf, &len );
1334 write(fd, buf, len);
1337 xmlNanoHTTPClose(ctxt);
1344 * @ctxt: the HTTP context
1345 * @filename: the filename where the content should be saved
1347 * This function saves the output of the HTTP transaction to a file
1348 * It closes and free the context at the end
1350 * Returns -1 in case of failure, 0 incase of success.
1353 xmlNanoHTTPSave(void *ctxt, const char *filename) {
1358 if (ctxt == NULL) return(-1);
1360 if (!strcmp(filename, "-"))
1363 fd = open(filename, O_CREAT | O_WRONLY);
1365 xmlNanoHTTPClose(ctxt);
1370 xmlNanoHTTPFetchContent( ctxt, &buf, &len );
1372 write(fd, buf, len);
1375 xmlNanoHTTPClose(ctxt);
1380 * xmlNanoHTTPReturnCode:
1381 * @ctx: the HTTP context
1383 * Get the latest HTTP return code received
1385 * Returns the HTTP return code for the request.
1388 xmlNanoHTTPReturnCode(void *ctx) {
1389 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1391 if (ctxt == NULL) return(-1);
1393 return(ctxt->returnValue);
1397 * xmlNanoHTTPAuthHeader:
1398 * @ctx: the HTTP context
1400 * Get the authentication header of an HTTP context
1402 * Returns the stashed value of the WWW-Authenticate or Proxy-Authenticate
1406 xmlNanoHTTPAuthHeader(void *ctx) {
1407 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1409 if (ctxt == NULL) return(NULL);
1411 return(ctxt->authHeader);
1415 * xmlNanoHTTPContentLength:
1416 * @ctx: the HTTP context
1418 * Provides the specified content length from the HTTP header.
1420 * Return the specified content length from the HTTP header. Note that
1421 * a value of -1 indicates that the content length element was not included in
1422 * the response header.
1425 xmlNanoHTTPContentLength( void * ctx ) {
1426 xmlNanoHTTPCtxtPtr ctxt = ctx;
1428 return ( ( ctxt == NULL ) ? -1 : ctxt->ContentLength );
1432 * xmlNanoHTTPFetchContent:
1433 * @ctx: the HTTP context
1434 * @ptr: pointer to set to the content buffer.
1435 * @len: integer pointer to hold the length of the content
1437 * Check if all the content was read
1439 * Returns 0 if all the content was read and available, returns
1440 * -1 if received content length was less than specified or an error
1444 xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len ) {
1445 xmlNanoHTTPCtxtPtr ctxt = ctx;
1451 char * dummy_ptr = NULL;
1453 /* Dummy up return input parameters if not provided */
1461 /* But can't work without the context pointer */
1463 if ( ( ctxt == NULL ) || ( ctxt->content == NULL ) ) {
1469 rcvd_lgth = ctxt->inptr - ctxt->content;
1471 while ( (cur_lgth = xmlNanoHTTPRecv( ctxt )) > 0 ) {
1473 rcvd_lgth += cur_lgth;
1474 if ( (ctxt->ContentLength > 0) && (rcvd_lgth >= ctxt->ContentLength) )
1478 *ptr = ctxt->content;
1481 if ( ( ctxt->ContentLength > 0 ) && ( rcvd_lgth < ctxt->ContentLength ) )
1483 else if ( rcvd_lgth == 0 )
1490 int main(int argc, char **argv) {
1491 char *contentType = NULL;
1493 if (argv[1] != NULL) {
1494 if (argv[2] != NULL)
1495 xmlNanoHTTPFetch(argv[1], argv[2], &contentType);
1497 xmlNanoHTTPFetch(argv[1], "-", &contentType);
1498 if (contentType != NULL) xmlFree(contentType);
1500 xmlGenericError(xmlGenericErrorContext,
1501 "%s: minimal HTTP GET implementation\n", argv[0]);
1502 xmlGenericError(xmlGenericErrorContext,
1503 "\tusage %s [ URL [ filename ] ]\n", argv[0]);
1505 xmlNanoHTTPCleanup();
1509 #endif /* STANDALONE */
1510 #else /* !LIBXML_HTTP_ENABLED */
1513 int main(int argc, char **argv) {
1514 xmlGenericError(xmlGenericErrorContext,
1515 "%s : HTTP support not compiled in\n", argv[0]);
1518 #endif /* STANDALONE */
1519 #endif /* LIBXML_HTTP_ENABLED */