Bug Summary

File:nanohttp.c
Location:line 1504, column 6
Description:Value stored to 'head' is never read

Annotated Source Code

1/*
2 * nanohttp.c: minimalist HTTP GET implementation to fetch external subsets.
3 * focuses on size, streamability, reentrancy and portability
4 *
5 * This is clearly not a general purpose HTTP implementation
6 * If you look for one, check:
7 * http://www.w3.org/Library/
8 *
9 * See Copyright for the status of this software.
10 *
11 * daniel@veillard.com
12 */
13
14#define NEED_SOCKETS
15#define IN_LIBXML
16#include "libxml.h"
17
18#ifdef LIBXML_HTTP_ENABLED
19#include <string.h>
20
21#ifdef HAVE_STDLIB_H1
22#include <stdlib.h>
23#endif
24#ifdef HAVE_UNISTD_H1
25#include <unistd.h>
26#endif
27#ifdef HAVE_SYS_TYPES_H1
28#include <sys/types.h>
29#endif
30#ifdef HAVE_SYS_SOCKET_H1
31#include <sys/socket.h>
32#endif
33#ifdef HAVE_NETINET_IN_H1
34#include <netinet/in.h>
35#endif
36#ifdef HAVE_ARPA_INET_H1
37#include <arpa/inet.h>
38#endif
39#ifdef HAVE_NETDB_H1
40#include <netdb.h>
41#endif
42#ifdef HAVE_RESOLV_H1
43#ifdef HAVE_ARPA_NAMESER_H1
44#include <arpa/nameser.h>
45#endif
46#include <resolv.h>
47#endif
48#ifdef HAVE_FCNTL_H1
49#include <fcntl.h>
50#endif
51#ifdef HAVE_ERRNO_H1
52#include <errno(*__errno_location ()).h>
53#endif
54#ifdef HAVE_SYS_TIME_H1
55#include <sys/time.h>
56#endif
57#ifndef HAVE_POLL_H1
58#ifdef HAVE_SYS_SELECT_H1
59#include <sys/select.h>
60#endif
61#else
62#include <poll.h>
63#endif
64#ifdef HAVE_STRINGS_H1
65#include <strings.h>
66#endif
67#ifdef SUPPORT_IP6
68#include <resolv.h>
69#endif
70#ifdef HAVE_ZLIB_H1
71#include <zlib.h>
72#endif
73
74
75#ifdef VMS
76#include <stropts>
77#define XML_SOCKLEN_Tint unsigned int
78#define SOCKETint int
79#endif
80
81#if defined(__MINGW32__) || defined(_WIN32_WCE)
82#define _WINSOCKAPI_
83#include <wsockcompat.h>
84#include <winsock2.h>
85#undef XML_SOCKLEN_Tint
86#define XML_SOCKLEN_Tint unsigned int
87#endif
88
89
90#include <libxml/globals.h>
91#include <libxml/xmlerror.h>
92#include <libxml/xmlmemory.h>
93#include <libxml/parser.h> /* for xmlStr(n)casecmp() */
94#include <libxml/nanohttp.h>
95#include <libxml/globals.h>
96#include <libxml/uri.h>
97
98/**
99 * A couple portability macros
100 */
101#ifndef _WINSOCKAPI_
102#if !defined(__BEOS__) || defined(__HAIKU__)
103#define closesocket(s)close(s) close(s)
104#endif
105#define SOCKETint int
106#endif
107
108#ifdef __BEOS__
109#ifndef PF_INET2
110#define PF_INET2 AF_INET2
111#endif
112#endif
113
114#ifndef XML_SOCKLEN_Tint
115#define XML_SOCKLEN_Tint unsigned int
116#endif
117#ifndef SOCKETint
118#define SOCKETint int
119#endif
120
121#ifdef STANDALONE
122#define DEBUG_HTTP
123#define xmlStrncasecmp(a, b, n) strncasecmp((char *)a, (char *)b, n)
124#define xmlStrcasecmpi(a, b) strcasecmp((char *)a, (char *)b)
125#endif
126
127#define XML_NANO_HTTP_MAX_REDIR10 10
128
129#define XML_NANO_HTTP_CHUNK4096 4096
130
131#define XML_NANO_HTTP_CLOSED0 0
132#define XML_NANO_HTTP_WRITE1 1
133#define XML_NANO_HTTP_READ2 2
134#define XML_NANO_HTTP_NONE4 4
135
136typedef struct xmlNanoHTTPCtxt {
137 char *protocol; /* the protocol name */
138 char *hostname; /* the host name */
139 int port; /* the port */
140 char *path; /* the path within the URL */
141 char *query; /* the query string */
142 SOCKETint fd; /* the file descriptor for the socket */
143 int state; /* WRITE / READ / CLOSED */
144 char *out; /* buffer sent (zero terminated) */
145 char *outptr; /* index within the buffer sent */
146 char *in; /* the receiving buffer */
147 char *content; /* the start of the content */
148 char *inptr; /* the next byte to read from network */
149 char *inrptr; /* the next byte to give back to the client */
150 int inlen; /* len of the input buffer */
151 int last; /* return code for last operation */
152 int returnValue; /* the protocol return value */
153 int ContentLength; /* specified content length from HTTP header */
154 char *contentType; /* the MIME type for the input */
155 char *location; /* the new URL in case of redirect */
156 char *authHeader; /* contents of {WWW,Proxy}-Authenticate header */
157 char *encoding; /* encoding extracted from the contentType */
158 char *mimeType; /* Mime-Type extracted from the contentType */
159#ifdef HAVE_ZLIB_H1
160 z_stream *strm; /* Zlib stream object */
161 int usesGzip; /* "Content-Encoding: gzip" was detected */
162#endif
163} xmlNanoHTTPCtxt, *xmlNanoHTTPCtxtPtr;
164
165static int initialized = 0;
166static char *proxy = NULL((void*)0); /* the proxy name if any */
167static int proxyPort; /* the proxy port if any */
168static unsigned int timeout = 60;/* the select() timeout in seconds */
169
170static int xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len );
171
172/**
173 * xmlHTTPErrMemory:
174 * @extra: extra informations
175 *
176 * Handle an out of memory condition
177 */
178static void
179xmlHTTPErrMemory(const char *extra)
180{
181 __xmlSimpleError(XML_FROM_HTTP, XML_ERR_NO_MEMORY, NULL((void*)0), NULL((void*)0), extra);
182}
183
184/**
185 * A portability function
186 */
187static int socket_errno(void) {
188#ifdef _WINSOCKAPI_
189 return(WSAGetLastError());
190#else
191 return(errno(*__errno_location ()));
192#endif
193}
194
195#ifdef SUPPORT_IP6
196static
197int have_ipv6(void) {
198 int s;
199
200 s = socket (AF_INET610, SOCK_STREAMSOCK_STREAM, 0);
201 if (s != -1) {
202 close (s);
203 return (1);
204 }
205 return (0);
206}
207#endif
208
209/**
210 * xmlNanoHTTPInit:
211 *
212 * Initialize the HTTP protocol layer.
213 * Currently it just checks for proxy informations
214 */
215
216void
217xmlNanoHTTPInit(void) {
218 const char *env;
219#ifdef _WINSOCKAPI_
220 WSADATA wsaData;
221#endif
222
223 if (initialized)
224 return;
225
226#ifdef _WINSOCKAPI_
227 if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
228 return;
229#endif
230
231 if (proxy == NULL((void*)0)) {
232 proxyPort = 80;
233 env = getenv("no_proxy");
234 if (env && ((env[0] == '*') && (env[1] == 0)))
235 goto done;
236 env = getenv("http_proxy");
237 if (env != NULL((void*)0)) {
238 xmlNanoHTTPScanProxy(env);
239 goto done;
240 }
241 env = getenv("HTTP_PROXY");
242 if (env != NULL((void*)0)) {
243 xmlNanoHTTPScanProxy(env);
244 goto done;
245 }
246 }
247done:
248 initialized = 1;
249}
250
251/**
252 * xmlNanoHTTPCleanup:
253 *
254 * Cleanup the HTTP protocol layer.
255 */
256
257void
258xmlNanoHTTPCleanup(void) {
259 if (proxy != NULL((void*)0)) {
260 xmlFree(proxy);
261 proxy = NULL((void*)0);
262 }
263#ifdef _WINSOCKAPI_
264 if (initialized)
265 WSACleanup();
266#endif
267 initialized = 0;
268 return;
269}
270
271/**
272 * xmlNanoHTTPScanURL:
273 * @ctxt: an HTTP context
274 * @URL: The URL used to initialize the context
275 *
276 * (Re)Initialize an HTTP context by parsing the URL and finding
277 * the protocol host port and path it indicates.
278 */
279
280static void
281xmlNanoHTTPScanURL(xmlNanoHTTPCtxtPtr ctxt, const char *URL) {
282 xmlURIPtr uri;
283 /*
284 * Clear any existing data from the context
285 */
286 if (ctxt->protocol != NULL((void*)0)) {
287 xmlFree(ctxt->protocol);
288 ctxt->protocol = NULL((void*)0);
289 }
290 if (ctxt->hostname != NULL((void*)0)) {
291 xmlFree(ctxt->hostname);
292 ctxt->hostname = NULL((void*)0);
293 }
294 if (ctxt->path != NULL((void*)0)) {
295 xmlFree(ctxt->path);
296 ctxt->path = NULL((void*)0);
297 }
298 if (ctxt->query != NULL((void*)0)) {
299 xmlFree(ctxt->query);
300 ctxt->query = NULL((void*)0);
301 }
302 if (URL == NULL((void*)0)) return;
303
304 uri = xmlParseURIRaw(URL, 1);
305 if (uri == NULL((void*)0))
306 return;
307
308 if ((uri->scheme == NULL((void*)0)) || (uri->server == NULL((void*)0))) {
309 xmlFreeURI(uri);
310 return;
311 }
312
313 ctxt->protocol = xmlMemStrdup(uri->scheme);
314 ctxt->hostname = xmlMemStrdup(uri->server);
315 if (uri->path != NULL((void*)0))
316 ctxt->path = xmlMemStrdup(uri->path);
317 else
318 ctxt->path = xmlMemStrdup("/");
319 if (uri->query != NULL((void*)0))
320 ctxt->query = xmlMemStrdup(uri->query);
321 if (uri->port != 0)
322 ctxt->port = uri->port;
323
324 xmlFreeURI(uri);
325}
326
327/**
328 * xmlNanoHTTPScanProxy:
329 * @URL: The proxy URL used to initialize the proxy context
330 *
331 * (Re)Initialize the HTTP Proxy context by parsing the URL and finding
332 * the protocol host port it indicates.
333 * Should be like http://myproxy/ or http://myproxy:3128/
334 * A NULL URL cleans up proxy informations.
335 */
336
337void
338xmlNanoHTTPScanProxy(const char *URL) {
339 xmlURIPtr uri;
340
341 if (proxy != NULL((void*)0)) {
342 xmlFree(proxy);
343 proxy = NULL((void*)0);
344 }
345 proxyPort = 0;
346
347#ifdef DEBUG_HTTP
348 if (URL == NULL((void*)0))
349 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
350 "Removing HTTP proxy info\n");
351 else
352 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
353 "Using HTTP proxy %s\n", URL);
354#endif
355 if (URL == NULL((void*)0)) return;
356
357 uri = xmlParseURIRaw(URL, 1);
358 if ((uri == NULL((void*)0)) || (uri->scheme == NULL((void*)0)) ||
359 (strcmp(uri->scheme, "http")) || (uri->server == NULL((void*)0))) {
360 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_URL_SYNTAX, "Syntax Error\n");
361 if (uri != NULL((void*)0))
362 xmlFreeURI(uri);
363 return;
364 }
365
366 proxy = xmlMemStrdup(uri->server);
367 if (uri->port != 0)
368 proxyPort = uri->port;
369
370 xmlFreeURI(uri);
371}
372
373/**
374 * xmlNanoHTTPNewCtxt:
375 * @URL: The URL used to initialize the context
376 *
377 * Allocate and initialize a new HTTP context.
378 *
379 * Returns an HTTP context or NULL in case of error.
380 */
381
382static xmlNanoHTTPCtxtPtr
383xmlNanoHTTPNewCtxt(const char *URL) {
384 xmlNanoHTTPCtxtPtr ret;
385
386 ret = (xmlNanoHTTPCtxtPtr) xmlMalloc(sizeof(xmlNanoHTTPCtxt));
387 if (ret == NULL((void*)0)) {
388 xmlHTTPErrMemory("allocating context");
389 return(NULL((void*)0));
390 }
391
392 memset(ret, 0, sizeof(xmlNanoHTTPCtxt));
393 ret->port = 80;
394 ret->returnValue = 0;
395 ret->fd = -1;
396 ret->ContentLength = -1;
397
398 xmlNanoHTTPScanURL(ret, URL);
399
400 return(ret);
401}
402
403/**
404 * xmlNanoHTTPFreeCtxt:
405 * @ctxt: an HTTP context
406 *
407 * Frees the context after closing the connection.
408 */
409
410static void
411xmlNanoHTTPFreeCtxt(xmlNanoHTTPCtxtPtr ctxt) {
412 if (ctxt == NULL((void*)0)) return;
413 if (ctxt->hostname != NULL((void*)0)) xmlFree(ctxt->hostname);
414 if (ctxt->protocol != NULL((void*)0)) xmlFree(ctxt->protocol);
415 if (ctxt->path != NULL((void*)0)) xmlFree(ctxt->path);
416 if (ctxt->query != NULL((void*)0)) xmlFree(ctxt->query);
417 if (ctxt->out != NULL((void*)0)) xmlFree(ctxt->out);
418 if (ctxt->in != NULL((void*)0)) xmlFree(ctxt->in);
419 if (ctxt->contentType != NULL((void*)0)) xmlFree(ctxt->contentType);
420 if (ctxt->encoding != NULL((void*)0)) xmlFree(ctxt->encoding);
421 if (ctxt->mimeType != NULL((void*)0)) xmlFree(ctxt->mimeType);
422 if (ctxt->location != NULL((void*)0)) xmlFree(ctxt->location);
423 if (ctxt->authHeader != NULL((void*)0)) xmlFree(ctxt->authHeader);
424#ifdef HAVE_ZLIB_H1
425 if (ctxt->strm != NULL((void*)0)) {
426 inflateEnd(ctxt->strm);
427 xmlFree(ctxt->strm);
428 }
429#endif
430
431 ctxt->state = XML_NANO_HTTP_NONE4;
432 if (ctxt->fd >= 0) closesocket(ctxt->fd)close(ctxt->fd);
433 ctxt->fd = -1;
434 xmlFree(ctxt);
435}
436
437/**
438 * xmlNanoHTTPSend:
439 * @ctxt: an HTTP context
440 *
441 * Send the input needed to initiate the processing on the server side
442 * Returns number of bytes sent or -1 on error.
443 */
444
445static int
446xmlNanoHTTPSend(xmlNanoHTTPCtxtPtr ctxt, const char *xmt_ptr, int outlen)
447{
448 int total_sent = 0;
449#ifdef HAVE_POLL_H1
450 struct pollfd p;
451#else
452 struct timeval tv;
453 fd_set wfd;
454#endif
455
456 if ((ctxt->state & XML_NANO_HTTP_WRITE1) && (xmt_ptr != NULL((void*)0))) {
457 while (total_sent < outlen) {
458 int nsent = send(ctxt->fd, xmt_ptr + total_sent,
459 outlen - total_sent, 0);
460
461 if (nsent > 0)
462 total_sent += nsent;
463 else if ((nsent == -1) &&
464#if defined(EAGAIN11) && EAGAIN11 != EWOULDBLOCK11
465 (socket_errno() != EAGAIN11) &&
466#endif
467 (socket_errno() != EWOULDBLOCK11)) {
468 __xmlIOErr(XML_FROM_HTTP, 0, "send failed\n");
469 if (total_sent == 0)
470 total_sent = -1;
471 break;
472 } else {
473 /*
474 * No data sent
475 * Since non-blocking sockets are used, wait for
476 * socket to be writable or default timeout prior
477 * to retrying.
478 */
479#ifndef HAVE_POLL_H1
480 if (ctxt->fd > FD_SETSIZE1024)
481 return -1;
482
483 tv.tv_sec = timeout;
484 tv.tv_usec = 0;
485 FD_ZERO(&wfd)do { int __d0, __d1; __asm__ __volatile__ ("cld; rep; " "stosq"
: "=c" (__d0), "=D" (__d1) : "a" (0), "0" (sizeof (fd_set) /
sizeof (__fd_mask)), "1" (&((&wfd)->__fds_bits)[0
]) : "memory"); } while (0)
;
486#ifdef _MSC_VER
487#pragma warning(push)
488#pragma warning(disable: 4018)
489#endif
490 FD_SET(ctxt->fd, &wfd)__asm__ __volatile__ ("btsq" " %1,%0" : "=m" (((&wfd)->
__fds_bits)[((ctxt->fd) / (8 * sizeof (__fd_mask)))]) : "r"
(((int) (ctxt->fd)) % (8 * sizeof (__fd_mask))) : "cc","memory"
)
;
491#ifdef _MSC_VER
492#pragma warning(pop)
493#endif
494 (void) select(ctxt->fd + 1, NULL((void*)0), &wfd, NULL((void*)0), &tv);
495#else
496 p.fd = ctxt->fd;
497 p.events = POLLOUT0x004;
498 (void) poll(&p, 1, timeout * 1000);
499#endif /* !HAVE_POLL_H */
500 }
501 }
502 }
503
504 return total_sent;
505}
506
507/**
508 * xmlNanoHTTPRecv:
509 * @ctxt: an HTTP context
510 *
511 * Read information coming from the HTTP connection.
512 * This is a blocking call (but it blocks in select(), not read()).
513 *
514 * Returns the number of byte read or -1 in case of error.
515 */
516
517static int
518xmlNanoHTTPRecv(xmlNanoHTTPCtxtPtr ctxt)
519{
520#ifdef HAVE_POLL_H1
521 struct pollfd p;
522#else
523 fd_set rfd;
524 struct timeval tv;
525#endif
526
527
528 while (ctxt->state & XML_NANO_HTTP_READ2) {
529 if (ctxt->in == NULL((void*)0)) {
530 ctxt->in = (char *) xmlMallocAtomic(65000 * sizeof(char));
531 if (ctxt->in == NULL((void*)0)) {
532 xmlHTTPErrMemory("allocating input");
533 ctxt->last = -1;
534 return (-1);
535 }
536 ctxt->inlen = 65000;
537 ctxt->inptr = ctxt->content = ctxt->inrptr = ctxt->in;
538 }
539 if (ctxt->inrptr > ctxt->in + XML_NANO_HTTP_CHUNK4096) {
540 int delta = ctxt->inrptr - ctxt->in;
541 int len = ctxt->inptr - ctxt->inrptr;
542
543 memmove(ctxt->in, ctxt->inrptr, len);
544 ctxt->inrptr -= delta;
545 ctxt->content -= delta;
546 ctxt->inptr -= delta;
547 }
548 if ((ctxt->in + ctxt->inlen) < (ctxt->inptr + XML_NANO_HTTP_CHUNK4096)) {
549 int d_inptr = ctxt->inptr - ctxt->in;
550 int d_content = ctxt->content - ctxt->in;
551 int d_inrptr = ctxt->inrptr - ctxt->in;
552 char *tmp_ptr = ctxt->in;
553
554 ctxt->inlen *= 2;
555 ctxt->in = (char *) xmlRealloc(tmp_ptr, ctxt->inlen);
556 if (ctxt->in == NULL((void*)0)) {
557 xmlHTTPErrMemory("allocating input buffer");
558 xmlFree(tmp_ptr);
559 ctxt->last = -1;
560 return (-1);
561 }
562 ctxt->inptr = ctxt->in + d_inptr;
563 ctxt->content = ctxt->in + d_content;
564 ctxt->inrptr = ctxt->in + d_inrptr;
565 }
566 ctxt->last = recv(ctxt->fd, ctxt->inptr, XML_NANO_HTTP_CHUNK4096, 0);
567 if (ctxt->last > 0) {
568 ctxt->inptr += ctxt->last;
569 return (ctxt->last);
570 }
571 if (ctxt->last == 0) {
572 return (0);
573 }
574 if (ctxt->last == -1) {
575 switch (socket_errno()) {
576 case EINPROGRESS115:
577 case EWOULDBLOCK11:
578#if defined(EAGAIN11) && EAGAIN11 != EWOULDBLOCK11
579 case EAGAIN11:
580#endif
581 break;
582
583 case ECONNRESET104:
584 case ESHUTDOWN108:
585 return (0);
586
587 default:
588 __xmlIOErr(XML_FROM_HTTP, 0, "recv failed\n");
589 return (-1);
590 }
591 }
592#ifdef HAVE_POLL_H1
593 p.fd = ctxt->fd;
594 p.events = POLLIN0x001;
595 if ((poll(&p, 1, timeout * 1000) < 1)
596#if defined(EINTR4)
597 && (errno(*__errno_location ()) != EINTR4)
598#endif
599 )
600 return (0);
601#else /* !HAVE_POLL_H */
602 if (ctxt->fd > FD_SETSIZE1024)
603 return 0;
604
605 tv.tv_sec = timeout;
606 tv.tv_usec = 0;
607 FD_ZERO(&rfd)do { int __d0, __d1; __asm__ __volatile__ ("cld; rep; " "stosq"
: "=c" (__d0), "=D" (__d1) : "a" (0), "0" (sizeof (fd_set) /
sizeof (__fd_mask)), "1" (&((&rfd)->__fds_bits)[0
]) : "memory"); } while (0)
;
608
609#ifdef _MSC_VER
610#pragma warning(push)
611#pragma warning(disable: 4018)
612#endif
613
614 FD_SET(ctxt->fd, &rfd)__asm__ __volatile__ ("btsq" " %1,%0" : "=m" (((&rfd)->
__fds_bits)[((ctxt->fd) / (8 * sizeof (__fd_mask)))]) : "r"
(((int) (ctxt->fd)) % (8 * sizeof (__fd_mask))) : "cc","memory"
)
;
615
616#ifdef _MSC_VER
617#pragma warning(pop)
618#endif
619
620 if ((select(ctxt->fd + 1, &rfd, NULL((void*)0), NULL((void*)0), &tv) < 1)
621#if defined(EINTR4)
622 && (errno(*__errno_location ()) != EINTR4)
623#endif
624 )
625 return (0);
626#endif /* !HAVE_POLL_H */
627 }
628 return (0);
629}
630
631/**
632 * xmlNanoHTTPReadLine:
633 * @ctxt: an HTTP context
634 *
635 * Read one line in the HTTP server output, usually for extracting
636 * the HTTP protocol informations from the answer header.
637 *
638 * Returns a newly allocated string with a copy of the line, or NULL
639 * which indicate the end of the input.
640 */
641
642static char *
643xmlNanoHTTPReadLine(xmlNanoHTTPCtxtPtr ctxt) {
644 char buf[4096];
645 char *bp = buf;
646 int rc;
647
648 while (bp - buf < 4095) {
649 if (ctxt->inrptr == ctxt->inptr) {
650 if ( (rc = xmlNanoHTTPRecv(ctxt)) == 0) {
651 if (bp == buf)
652 return(NULL((void*)0));
653 else
654 *bp = 0;
655 return(xmlMemStrdup(buf));
656 }
657 else if ( rc == -1 ) {
658 return ( NULL((void*)0) );
659 }
660 }
661 *bp = *ctxt->inrptr++;
662 if (*bp == '\n') {
663 *bp = 0;
664 return(xmlMemStrdup(buf));
665 }
666 if (*bp != '\r')
667 bp++;
668 }
669 buf[4095] = 0;
670 return(xmlMemStrdup(buf));
671}
672
673
674/**
675 * xmlNanoHTTPScanAnswer:
676 * @ctxt: an HTTP context
677 * @line: an HTTP header line
678 *
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.
684 *
685 * Returns -1 in case of failure, the file descriptor number otherwise
686 */
687
688static void
689xmlNanoHTTPScanAnswer(xmlNanoHTTPCtxtPtr ctxt, const char *line) {
690 const char *cur = line;
691
692 if (line == NULL((void*)0)) return;
693
694 if (!strncmp(line, "HTTP/", 5)) {
695 int version = 0;
696 int ret = 0;
697
698 cur += 5;
699 while ((*cur >= '0') && (*cur <= '9')) {
700 version *= 10;
701 version += *cur - '0';
702 cur++;
703 }
704 if (*cur == '.') {
705 cur++;
706 if ((*cur >= '0') && (*cur <= '9')) {
707 version *= 10;
708 version += *cur - '0';
709 cur++;
710 }
711 while ((*cur >= '0') && (*cur <= '9'))
712 cur++;
713 } else
714 version *= 10;
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')) {
719 ret *= 10;
720 ret += *cur - '0';
721 cur++;
722 }
723 if ((*cur != 0) && (*cur != ' ') && (*cur != '\t')) return;
724 ctxt->returnValue = ret;
725 } else if (!xmlStrncasecmp(BAD_CAST(xmlChar *) line, BAD_CAST(xmlChar *)"Content-Type:", 13)) {
726 const xmlChar *charset, *last, *mime;
727 cur += 13;
728 while ((*cur == ' ') || (*cur == '\t')) cur++;
729 if (ctxt->contentType != NULL((void*)0))
730 xmlFree(ctxt->contentType);
731 ctxt->contentType = xmlMemStrdup(cur);
732 mime = (const xmlChar *) cur;
733 last = mime;
734 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
735 (*last != ';') && (*last != ','))
736 last++;
737 if (ctxt->mimeType != NULL((void*)0))
738 xmlFree(ctxt->mimeType);
739 ctxt->mimeType = (char *) xmlStrndup(mime, last - mime);
740 charset = xmlStrstr(BAD_CAST(xmlChar *) ctxt->contentType, BAD_CAST(xmlChar *) "charset=");
741 if (charset != NULL((void*)0)) {
742 charset += 8;
743 last = charset;
744 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
745 (*last != ';') && (*last != ','))
746 last++;
747 if (ctxt->encoding != NULL((void*)0))
748 xmlFree(ctxt->encoding);
749 ctxt->encoding = (char *) xmlStrndup(charset, last - charset);
750 }
751 } else if (!xmlStrncasecmp(BAD_CAST(xmlChar *) line, BAD_CAST(xmlChar *)"ContentType:", 12)) {
752 const xmlChar *charset, *last, *mime;
753 cur += 12;
754 if (ctxt->contentType != NULL((void*)0)) return;
755 while ((*cur == ' ') || (*cur == '\t')) cur++;
756 ctxt->contentType = xmlMemStrdup(cur);
757 mime = (const xmlChar *) cur;
758 last = mime;
759 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
760 (*last != ';') && (*last != ','))
761 last++;
762 if (ctxt->mimeType != NULL((void*)0))
763 xmlFree(ctxt->mimeType);
764 ctxt->mimeType = (char *) xmlStrndup(mime, last - mime);
765 charset = xmlStrstr(BAD_CAST(xmlChar *) ctxt->contentType, BAD_CAST(xmlChar *) "charset=");
766 if (charset != NULL((void*)0)) {
767 charset += 8;
768 last = charset;
769 while ((*last != 0) && (*last != ' ') && (*last != '\t') &&
770 (*last != ';') && (*last != ','))
771 last++;
772 if (ctxt->encoding != NULL((void*)0))
773 xmlFree(ctxt->encoding);
774 ctxt->encoding = (char *) xmlStrndup(charset, last - charset);
775 }
776 } else if (!xmlStrncasecmp(BAD_CAST(xmlChar *) line, BAD_CAST(xmlChar *)"Location:", 9)) {
777 cur += 9;
778 while ((*cur == ' ') || (*cur == '\t')) cur++;
779 if (ctxt->location != NULL((void*)0))
780 xmlFree(ctxt->location);
781 if (*cur == '/') {
782 xmlChar *tmp_http = xmlStrdup(BAD_CAST(xmlChar *) "http://");
783 xmlChar *tmp_loc =
784 xmlStrcat(tmp_http, (const xmlChar *) ctxt->hostname);
785 ctxt->location =
786 (char *) xmlStrcat (tmp_loc, (const xmlChar *) cur);
787 } else {
788 ctxt->location = xmlMemStrdup(cur);
789 }
790 } else if (!xmlStrncasecmp(BAD_CAST(xmlChar *) line, BAD_CAST(xmlChar *)"WWW-Authenticate:", 17)) {
791 cur += 17;
792 while ((*cur == ' ') || (*cur == '\t')) cur++;
793 if (ctxt->authHeader != NULL((void*)0))
794 xmlFree(ctxt->authHeader);
795 ctxt->authHeader = xmlMemStrdup(cur);
796 } else if (!xmlStrncasecmp(BAD_CAST(xmlChar *) line, BAD_CAST(xmlChar *)"Proxy-Authenticate:", 19)) {
797 cur += 19;
798 while ((*cur == ' ') || (*cur == '\t')) cur++;
799 if (ctxt->authHeader != NULL((void*)0))
800 xmlFree(ctxt->authHeader);
801 ctxt->authHeader = xmlMemStrdup(cur);
802#ifdef HAVE_ZLIB_H1
803 } else if ( !xmlStrncasecmp( BAD_CAST(xmlChar *) line, BAD_CAST(xmlChar *)"Content-Encoding:", 17) ) {
804 cur += 17;
805 while ((*cur == ' ') || (*cur == '\t')) cur++;
806 if ( !xmlStrncasecmp( BAD_CAST(xmlChar *) cur, BAD_CAST(xmlChar *)"gzip", 4) ) {
807 ctxt->usesGzip = 1;
808
809 ctxt->strm = xmlMalloc(sizeof(z_stream));
810
811 if (ctxt->strm != NULL((void*)0)) {
812 ctxt->strm->zalloc = Z_NULL0;
813 ctxt->strm->zfree = Z_NULL0;
814 ctxt->strm->opaque = Z_NULL0;
815 ctxt->strm->avail_in = 0;
816 ctxt->strm->next_in = Z_NULL0;
817
818 inflateInit2( ctxt->strm, 31 )inflateInit2_((ctxt->strm), (31), "1.2.3", sizeof(z_stream
))
;
819 }
820 }
821#endif
822 } else if ( !xmlStrncasecmp( BAD_CAST(xmlChar *) line, BAD_CAST(xmlChar *)"Content-Length:", 15) ) {
823 cur += 15;
824 ctxt->ContentLength = strtol( cur, NULL((void*)0), 10 );
825 }
826}
827
828/**
829 * xmlNanoHTTPConnectAttempt:
830 * @addr: a socket address structure
831 *
832 * Attempt a connection to the given IP:port endpoint. It forces
833 * non-blocking semantic on the socket, and allow 60 seconds for
834 * the host to answer.
835 *
836 * Returns -1 in case of failure, the file descriptor number otherwise
837 */
838
839static int
840xmlNanoHTTPConnectAttempt(struct sockaddr *addr)
841{
842#ifndef HAVE_POLL_H1
843 fd_set wfd;
844#ifdef _WINSOCKAPI_
845 fd_set xfd;
846#endif
847 struct timeval tv;
848#else /* !HAVE_POLL_H */
849 struct pollfd p;
850#endif /* !HAVE_POLL_H */
851 int status;
852
853 int addrlen;
854
855 SOCKETint s;
856
857#ifdef SUPPORT_IP6
858 if (addr->sa_family == AF_INET610) {
859 s = socket(PF_INET610, SOCK_STREAMSOCK_STREAM, IPPROTO_TCPIPPROTO_TCP);
860 addrlen = sizeof(struct sockaddr_in6);
861 } else
862#endif
863 {
864 s = socket(PF_INET2, SOCK_STREAMSOCK_STREAM, IPPROTO_TCPIPPROTO_TCP);
865 addrlen = sizeof(struct sockaddr_in);
866 }
867 if (s == -1) {
868#ifdef DEBUG_HTTP
869 perror("socket");
870#endif
871 __xmlIOErr(XML_FROM_HTTP, 0, "socket failed\n");
872 return (-1);
873 }
874#ifdef _WINSOCKAPI_
875 {
876 u_long one = 1;
877
878 status = ioctlsocket(s, FIONBIO, &one) == SOCKET_ERROR ? -1 : 0;
879 }
880#else /* _WINSOCKAPI_ */
881#if defined(VMS)
882 {
883 int enable = 1;
884
885 status = ioctl(s, FIONBIO, &enable);
886 }
887#else /* VMS */
888#if defined(__BEOS__) && !defined(__HAIKU__)
889 {
890 bool noblock = true;
891
892 status =
893 setsockopt(s, SOL_SOCKET1, SO_NONBLOCK, &noblock,
894 sizeof(noblock));
895 }
896#else /* __BEOS__ */
897 if ((status = fcntl(s, F_GETFL3, 0)) != -1) {
898#ifdef O_NONBLOCK04000
899 status |= O_NONBLOCK04000;
900#else /* O_NONBLOCK */
901#ifdef F_NDELAY
902 status |= F_NDELAY;
903#endif /* F_NDELAY */
904#endif /* !O_NONBLOCK */
905 status = fcntl(s, F_SETFL4, status);
906 }
907 if (status < 0) {
908#ifdef DEBUG_HTTP
909 perror("nonblocking");
910#endif
911 __xmlIOErr(XML_FROM_HTTP, 0, "error setting non-blocking IO\n");
912 closesocket(s)close(s);
913 return (-1);
914 }
915#endif /* !__BEOS__ */
916#endif /* !VMS */
917#endif /* !_WINSOCKAPI_ */
918
919 if (connect(s, addr, addrlen) == -1) {
920 switch (socket_errno()) {
921 case EINPROGRESS115:
922 case EWOULDBLOCK11:
923 break;
924 default:
925 __xmlIOErr(XML_FROM_HTTP, 0,
926 "error connecting to HTTP server");
927 closesocket(s)close(s);
928 return (-1);
929 }
930 }
931#ifndef HAVE_POLL_H1
932 tv.tv_sec = timeout;
933 tv.tv_usec = 0;
934
935#ifdef _MSC_VER
936#pragma warning(push)
937#pragma warning(disable: 4018)
938#endif
939 if (s > FD_SETSIZE1024)
940 return -1;
941 FD_ZERO(&wfd)do { int __d0, __d1; __asm__ __volatile__ ("cld; rep; " "stosq"
: "=c" (__d0), "=D" (__d1) : "a" (0), "0" (sizeof (fd_set) /
sizeof (__fd_mask)), "1" (&((&wfd)->__fds_bits)[0
]) : "memory"); } while (0)
;
942 FD_SET(s, &wfd)__asm__ __volatile__ ("btsq" " %1,%0" : "=m" (((&wfd)->
__fds_bits)[((s) / (8 * sizeof (__fd_mask)))]) : "r" (((int) (
s)) % (8 * sizeof (__fd_mask))) : "cc","memory")
;
943
944#ifdef _WINSOCKAPI_
945 FD_ZERO(&xfd)do { int __d0, __d1; __asm__ __volatile__ ("cld; rep; " "stosq"
: "=c" (__d0), "=D" (__d1) : "a" (0), "0" (sizeof (fd_set) /
sizeof (__fd_mask)), "1" (&((&xfd)->__fds_bits)[0
]) : "memory"); } while (0)
;
946 FD_SET(s, &xfd)__asm__ __volatile__ ("btsq" " %1,%0" : "=m" (((&xfd)->
__fds_bits)[((s) / (8 * sizeof (__fd_mask)))]) : "r" (((int) (
s)) % (8 * sizeof (__fd_mask))) : "cc","memory")
;
947
948 switch (select(s + 1, NULL((void*)0), &wfd, &xfd, &tv))
949#else
950 switch (select(s + 1, NULL((void*)0), &wfd, NULL((void*)0), &tv))
951#endif
952#ifdef _MSC_VER
953#pragma warning(pop)
954#endif
955
956#else /* !HAVE_POLL_H */
957 p.fd = s;
958 p.events = POLLOUT0x004;
959 switch (poll(&p, 1, timeout * 1000))
960#endif /* !HAVE_POLL_H */
961
962 {
963 case 0:
964 /* Time out */
965 __xmlIOErr(XML_FROM_HTTP, 0, "Connect attempt timed out");
966 closesocket(s)close(s);
967 return (-1);
968 case -1:
969 /* Ermm.. ?? */
970 __xmlIOErr(XML_FROM_HTTP, 0, "Connect failed");
971 closesocket(s)close(s);
972 return (-1);
973 }
974
975#ifndef HAVE_POLL_H1
976 if (FD_ISSET(s, &wfd)(__extension__ ({register char __result; __asm__ __volatile__
("btq" " %1,%2 ; setcb %b0" : "=q" (__result) : "r" (((int) (
s)) % (8 * sizeof (__fd_mask))), "m" (((&wfd)->__fds_bits
)[((s) / (8 * sizeof (__fd_mask)))]) : "cc"); __result; }))
977#ifdef _WINSOCKAPI_
978 || FD_ISSET(s, &xfd)(__extension__ ({register char __result; __asm__ __volatile__
("btq" " %1,%2 ; setcb %b0" : "=q" (__result) : "r" (((int) (
s)) % (8 * sizeof (__fd_mask))), "m" (((&xfd)->__fds_bits
)[((s) / (8 * sizeof (__fd_mask)))]) : "cc"); __result; }))
979#endif
980 )
981#else /* !HAVE_POLL_H */
982 if (p.revents == POLLOUT0x004)
983#endif /* !HAVE_POLL_H */
984 {
985 XML_SOCKLEN_Tint len;
986
987 len = sizeof(status);
988#ifdef SO_ERROR4
989 if (getsockopt(s, SOL_SOCKET1, SO_ERROR4, (char *) &status, &len) <
990 0) {
991 /* Solaris error code */
992 __xmlIOErr(XML_FROM_HTTP, 0, "getsockopt failed\n");
993 return (-1);
994 }
995#endif
996 if (status) {
997 __xmlIOErr(XML_FROM_HTTP, 0,
998 "Error connecting to remote host");
999 closesocket(s)close(s);
1000 errno(*__errno_location ()) = status;
1001 return (-1);
1002 }
1003 } else {
1004 /* pbm */
1005 __xmlIOErr(XML_FROM_HTTP, 0, "select failed\n");
1006 closesocket(s)close(s);
1007 return (-1);
1008 }
1009
1010 return (s);
1011}
1012
1013/**
1014 * xmlNanoHTTPConnectHost:
1015 * @host: the host name
1016 * @port: the port number
1017 *
1018 * Attempt a connection to the given host:port endpoint. It tries
1019 * the multiple IP provided by the DNS if available.
1020 *
1021 * Returns -1 in case of failure, the file descriptor number otherwise
1022 */
1023
1024static int
1025xmlNanoHTTPConnectHost(const char *host, int port)
1026{
1027 struct hostent *h;
1028 struct sockaddr *addr = NULL((void*)0);
1029 struct in_addr ia;
1030 struct sockaddr_in sockin;
1031
1032#ifdef SUPPORT_IP6
1033 struct in6_addr ia6;
1034 struct sockaddr_in6 sockin6;
1035#endif
1036 int i;
1037 int s;
1038
1039 memset (&sockin, 0, sizeof(sockin));
1040#ifdef SUPPORT_IP6
1041 memset (&sockin6, 0, sizeof(sockin6));
1042#endif
1043
1044#if !defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && defined(RES_USE_INET60x00002000)
1045 if (have_ipv6 ())
1046 {
1047 if (!(_res(*__res_state()).options & RES_INIT0x00000001))
1048 res_init__res_init();
1049 _res(*__res_state()).options |= RES_USE_INET60x00002000;
1050 }
1051#endif
1052
1053#if defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && !defined(_WIN32)
1054 if (have_ipv6 ())
1055#endif
1056#if defined(HAVE_GETADDRINFO) && (defined(SUPPORT_IP6) || defined(_WIN32))
1057 {
1058 int status;
1059 struct addrinfo hints, *res, *result;
1060
1061 result = NULL((void*)0);
1062 memset (&hints, 0,sizeof(hints));
1063 hints.ai_socktype = SOCK_STREAMSOCK_STREAM;
1064
1065 status = getaddrinfo (host, NULL((void*)0), &hints, &result);
1066 if (status) {
1067 __xmlIOErr(XML_FROM_HTTP, 0, "getaddrinfo failed\n");
1068 return (-1);
1069 }
1070
1071 for (res = result; res; res = res->ai_next) {
1072 if (res->ai_family == AF_INET2) {
1073 if (res->ai_addrlen > sizeof(sockin)) {
1074 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1075 freeaddrinfo (result);
1076 return (-1);
1077 }
1078 memcpy (&sockin, res->ai_addr, res->ai_addrlen);
1079 sockin.sin_port = htons (port);
1080 addr = (struct sockaddr *)&sockin;
1081#ifdef SUPPORT_IP6
1082 } else if (have_ipv6 () && (res->ai_family == AF_INET610)) {
1083 if (res->ai_addrlen > sizeof(sockin6)) {
1084 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1085 freeaddrinfo (result);
1086 return (-1);
1087 }
1088 memcpy (&sockin6, res->ai_addr, res->ai_addrlen);
1089 sockin6.sin6_port = htons (port);
1090 addr = (struct sockaddr *)&sockin6;
1091#endif
1092 } else
1093 continue; /* for */
1094
1095 s = xmlNanoHTTPConnectAttempt (addr);
1096 if (s != -1) {
1097 freeaddrinfo (result);
1098 return (s);
1099 }
1100 }
1101
1102 if (result)
1103 freeaddrinfo (result);
1104 }
1105#endif
1106#if defined(HAVE_GETADDRINFO) && defined(SUPPORT_IP6) && !defined(_WIN32)
1107 else
1108#endif
1109#if !defined(HAVE_GETADDRINFO) || !defined(_WIN32)
1110 {
1111 h = gethostbyname (host);
1112 if (h == NULL((void*)0)) {
1113
1114/*
1115 * Okay, I got fed up by the non-portability of this error message
1116 * extraction code. it work on Linux, if it work on your platform
1117 * and one want to enable it, send me the defined(foobar) needed
1118 */
1119#if defined(HAVE_NETDB_H1) && defined(HOST_NOT_FOUND1) && defined(linux1)
1120 const char *h_err_txt = "";
1121
1122 switch (h_errno(*__h_errno_location ())) {
1123 case HOST_NOT_FOUND1:
1124 h_err_txt = "Authoritive host not found";
1125 break;
1126
1127 case TRY_AGAIN2:
1128 h_err_txt =
1129 "Non-authoritive host not found or server failure.";
1130 break;
1131
1132 case NO_RECOVERY3:
1133 h_err_txt =
1134 "Non-recoverable errors: FORMERR, REFUSED, or NOTIMP.";
1135 break;
1136
1137 case NO_ADDRESS4:
1138 h_err_txt =
1139 "Valid name, no data record of requested type.";
1140 break;
1141
1142 default:
1143 h_err_txt = "No error text defined.";
1144 break;
1145 }
1146 __xmlIOErr(XML_FROM_HTTP, 0, h_err_txt);
1147#else
1148 __xmlIOErr(XML_FROM_HTTP, 0, "Failed to resolve host");
1149#endif
1150 return (-1);
1151 }
1152
1153 for (i = 0; h->h_addr_list[i]; i++) {
1154 if (h->h_addrtype == AF_INET2) {
1155 /* A records (IPv4) */
1156 if ((unsigned int) h->h_length > sizeof(ia)) {
1157 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1158 return (-1);
1159 }
1160 memcpy (&ia, h->h_addr_list[i], h->h_length);
1161 sockin.sin_family = h->h_addrtype;
1162 sockin.sin_addr = ia;
1163 sockin.sin_port = (u_short)htons ((unsigned short)port);
1164 addr = (struct sockaddr *) &sockin;
1165#ifdef SUPPORT_IP6
1166 } else if (have_ipv6 () && (h->h_addrtype == AF_INET610)) {
1167 /* AAAA records (IPv6) */
1168 if ((unsigned int) h->h_length > sizeof(ia6)) {
1169 __xmlIOErr(XML_FROM_HTTP, 0, "address size mismatch\n");
1170 return (-1);
1171 }
1172 memcpy (&ia6, h->h_addr_list[i], h->h_length);
1173 sockin6.sin6_family = h->h_addrtype;
1174 sockin6.sin6_addr = ia6;
1175 sockin6.sin6_port = htons (port);
1176 addr = (struct sockaddr *) &sockin6;
1177#endif
1178 } else
1179 break; /* for */
1180
1181 s = xmlNanoHTTPConnectAttempt (addr);
1182 if (s != -1)
1183 return (s);
1184 }
1185 }
1186#endif
1187
1188#ifdef DEBUG_HTTP
1189 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1190 "xmlNanoHTTPConnectHost: unable to connect to '%s'.\n",
1191 host);
1192#endif
1193 return (-1);
1194}
1195
1196
1197/**
1198 * xmlNanoHTTPOpen:
1199 * @URL: The URL to load
1200 * @contentType: if available the Content-Type information will be
1201 * returned at that location
1202 *
1203 * This function try to open a connection to the indicated resource
1204 * via HTTP GET.
1205 *
1206 * Returns NULL in case of failure, otherwise a request handler.
1207 * The contentType, if provided must be freed by the caller
1208 */
1209
1210void*
1211xmlNanoHTTPOpen(const char *URL, char **contentType) {
1212 if (contentType != NULL((void*)0)) *contentType = NULL((void*)0);
1213 return(xmlNanoHTTPMethod(URL, NULL((void*)0), NULL((void*)0), contentType, NULL((void*)0), 0));
1214}
1215
1216/**
1217 * xmlNanoHTTPOpenRedir:
1218 * @URL: The URL to load
1219 * @contentType: if available the Content-Type information will be
1220 * returned at that location
1221 * @redir: if available the redirected URL will be returned
1222 *
1223 * This function try to open a connection to the indicated resource
1224 * via HTTP GET.
1225 *
1226 * Returns NULL in case of failure, otherwise a request handler.
1227 * The contentType, if provided must be freed by the caller
1228 */
1229
1230void*
1231xmlNanoHTTPOpenRedir(const char *URL, char **contentType, char **redir) {
1232 if (contentType != NULL((void*)0)) *contentType = NULL((void*)0);
1233 if (redir != NULL((void*)0)) *redir = NULL((void*)0);
1234 return(xmlNanoHTTPMethodRedir(URL, NULL((void*)0), NULL((void*)0), contentType, redir, NULL((void*)0),0));
1235}
1236
1237/**
1238 * xmlNanoHTTPRead:
1239 * @ctx: the HTTP context
1240 * @dest: a buffer
1241 * @len: the buffer length
1242 *
1243 * This function tries to read @len bytes from the existing HTTP connection
1244 * and saves them in @dest. This is a blocking call.
1245 *
1246 * Returns the number of byte read. 0 is an indication of an end of connection.
1247 * -1 indicates a parameter error.
1248 */
1249int
1250xmlNanoHTTPRead(void *ctx, void *dest, int len) {
1251 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1252#ifdef HAVE_ZLIB_H1
1253 int bytes_read = 0;
1254 int orig_avail_in;
1255 int z_ret;
1256#endif
1257
1258 if (ctx == NULL((void*)0)) return(-1);
1259 if (dest == NULL((void*)0)) return(-1);
1260 if (len <= 0) return(0);
1261
1262#ifdef HAVE_ZLIB_H1
1263 if (ctxt->usesGzip == 1) {
1264 if (ctxt->strm == NULL((void*)0)) return(0);
1265
1266 ctxt->strm->next_out = dest;
1267 ctxt->strm->avail_out = len;
1268 ctxt->strm->avail_in = ctxt->inptr - ctxt->inrptr;
1269
1270 while (ctxt->strm->avail_out > 0 &&
1271 (ctxt->strm->avail_in > 0 || xmlNanoHTTPRecv(ctxt) > 0)) {
1272 orig_avail_in = ctxt->strm->avail_in =
1273 ctxt->inptr - ctxt->inrptr - bytes_read;
1274 ctxt->strm->next_in = BAD_CAST(xmlChar *) (ctxt->inrptr + bytes_read);
1275
1276 z_ret = inflate(ctxt->strm, Z_NO_FLUSH0);
1277 bytes_read += orig_avail_in - ctxt->strm->avail_in;
1278
1279 if (z_ret != Z_OK0) break;
1280 }
1281
1282 ctxt->inrptr += bytes_read;
1283 return(len - ctxt->strm->avail_out);
1284 }
1285#endif
1286
1287 while (ctxt->inptr - ctxt->inrptr < len) {
1288 if (xmlNanoHTTPRecv(ctxt) <= 0) break;
1289 }
1290 if (ctxt->inptr - ctxt->inrptr < len)
1291 len = ctxt->inptr - ctxt->inrptr;
1292 memcpy(dest, ctxt->inrptr, len);
1293 ctxt->inrptr += len;
1294 return(len);
1295}
1296
1297/**
1298 * xmlNanoHTTPClose:
1299 * @ctx: the HTTP context
1300 *
1301 * This function closes an HTTP context, it ends up the connection and
1302 * free all data related to it.
1303 */
1304void
1305xmlNanoHTTPClose(void *ctx) {
1306 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1307
1308 if (ctx == NULL((void*)0)) return;
1309
1310 xmlNanoHTTPFreeCtxt(ctxt);
1311}
1312
1313/**
1314 * xmlNanoHTTPMethodRedir:
1315 * @URL: The URL to load
1316 * @method: the HTTP method to use
1317 * @input: the input string if any
1318 * @contentType: the Content-Type information IN and OUT
1319 * @redir: the redirected URL OUT
1320 * @headers: the extra headers
1321 * @ilen: input length
1322 *
1323 * This function try to open a connection to the indicated resource
1324 * via HTTP using the given @method, adding the given extra headers
1325 * and the input buffer for the request content.
1326 *
1327 * Returns NULL in case of failure, otherwise a request handler.
1328 * The contentType, or redir, if provided must be freed by the caller
1329 */
1330
1331void*
1332xmlNanoHTTPMethodRedir(const char *URL, const char *method, const char *input,
1333 char **contentType, char **redir,
1334 const char *headers, int ilen ) {
1335 xmlNanoHTTPCtxtPtr ctxt;
1336 char *bp, *p;
1337 int blen, ret;
1338 int head;
1339 int nbRedirects = 0;
1340 char *redirURL = NULL((void*)0);
1341#ifdef DEBUG_HTTP
1342 int xmt_bytes;
1343#endif
1344
1345 if (URL == NULL((void*)0)) return(NULL((void*)0));
1346 if (method == NULL((void*)0)) method = "GET";
1347 xmlNanoHTTPInit();
1348
1349retry:
1350 if (redirURL == NULL((void*)0))
1351 ctxt = xmlNanoHTTPNewCtxt(URL);
1352 else {
1353 ctxt = xmlNanoHTTPNewCtxt(redirURL);
1354 ctxt->location = xmlMemStrdup(redirURL);
1355 }
1356
1357 if ( ctxt == NULL((void*)0) ) {
1358 return ( NULL((void*)0) );
1359 }
1360
1361 if ((ctxt->protocol == NULL((void*)0)) || (strcmp(ctxt->protocol, "http"))) {
1362 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_URL_SYNTAX, "Not a valid HTTP URI");
1363 xmlNanoHTTPFreeCtxt(ctxt);
1364 if (redirURL != NULL((void*)0)) xmlFree(redirURL);
1365 return(NULL((void*)0));
1366 }
1367 if (ctxt->hostname == NULL((void*)0)) {
1368 __xmlIOErr(XML_FROM_HTTP, XML_HTTP_UNKNOWN_HOST,
1369 "Failed to identify host in URI");
1370 xmlNanoHTTPFreeCtxt(ctxt);
1371 if (redirURL != NULL((void*)0)) xmlFree(redirURL);
1372 return(NULL((void*)0));
1373 }
1374 if (proxy) {
1375 blen = strlen(ctxt->hostname) * 2 + 16;
1376 ret = xmlNanoHTTPConnectHost(proxy, proxyPort);
1377 }
1378 else {
1379 blen = strlen(ctxt->hostname);
1380 ret = xmlNanoHTTPConnectHost(ctxt->hostname, ctxt->port);
1381 }
1382 if (ret < 0) {
1383 xmlNanoHTTPFreeCtxt(ctxt);
1384 if (redirURL != NULL((void*)0)) xmlFree(redirURL);
1385 return(NULL((void*)0));
1386 }
1387 ctxt->fd = ret;
1388
1389 if (input == NULL((void*)0))
1390 ilen = 0;
1391 else
1392 blen += 36;
1393
1394 if (headers != NULL((void*)0))
1395 blen += strlen(headers) + 2;
1396 if (contentType && *contentType)
1397 /* reserve for string plus 'Content-Type: \r\n" */
1398 blen += strlen(*contentType) + 16;
1399 if (ctxt->query != NULL((void*)0))
1400 /* 1 for '?' */
1401 blen += strlen(ctxt->query) + 1;
1402 blen += strlen(method) + strlen(ctxt->path) + 24;
1403#ifdef HAVE_ZLIB_H1
1404 /* reserve for possible 'Accept-Encoding: gzip' string */
1405 blen += 23;
1406#endif
1407 if (ctxt->port != 80) {
1408 /* reserve space for ':xxxxx', incl. potential proxy */
1409 if (proxy)
1410 blen += 12;
1411 else
1412 blen += 6;
1413 }
1414 bp = (char*)xmlMallocAtomic(blen);
1415 if ( bp == NULL((void*)0) ) {
1416 xmlNanoHTTPFreeCtxt( ctxt );
1417 xmlHTTPErrMemory("allocating header buffer");
1418 return ( NULL((void*)0) );
1419 }
1420
1421 p = bp;
1422
1423 if (proxy) {
1424 if (ctxt->port != 80) {
1425 p += snprintf( p, blen - (p - bp), "%s http://%s:%d%s",
1426 method, ctxt->hostname,
1427 ctxt->port, ctxt->path );
1428 }
1429 else
1430 p += snprintf( p, blen - (p - bp), "%s http://%s%s", method,
1431 ctxt->hostname, ctxt->path);
1432 }
1433 else
1434 p += snprintf( p, blen - (p - bp), "%s %s", method, ctxt->path);
1435
1436 if (ctxt->query != NULL((void*)0))
1437 p += snprintf( p, blen - (p - bp), "?%s", ctxt->query);
1438
1439 if (ctxt->port == 80) {
1440 p += snprintf( p, blen - (p - bp), " HTTP/1.0\r\nHost: %s\r\n",
1441 ctxt->hostname);
1442 } else {
1443 p += snprintf( p, blen - (p - bp), " HTTP/1.0\r\nHost: %s:%d\r\n",
1444 ctxt->hostname, ctxt->port);
1445 }
1446
1447#ifdef HAVE_ZLIB_H1
1448 p += snprintf(p, blen - (p - bp), "Accept-Encoding: gzip\r\n");
1449#endif
1450
1451 if (contentType != NULL((void*)0) && *contentType)
1452 p += snprintf(p, blen - (p - bp), "Content-Type: %s\r\n", *contentType);
1453
1454 if (headers != NULL((void*)0))
1455 p += snprintf( p, blen - (p - bp), "%s", headers );
1456
1457 if (input != NULL((void*)0))
1458 snprintf(p, blen - (p - bp), "Content-Length: %d\r\n\r\n", ilen );
1459 else
1460 snprintf(p, blen - (p - bp), "\r\n");
1461
1462#ifdef DEBUG_HTTP
1463 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1464 "-> %s%s", proxy? "(Proxy) " : "", bp);
1465 if ((blen -= strlen(bp)+1) < 0)
1466 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1467 "ERROR: overflowed buffer by %d bytes\n", -blen);
1468#endif
1469 ctxt->outptr = ctxt->out = bp;
1470 ctxt->state = XML_NANO_HTTP_WRITE1;
1471 blen = strlen( ctxt->out );
1472#ifdef DEBUG_HTTP
1473 xmt_bytes = xmlNanoHTTPSend(ctxt, ctxt->out, blen );
1474 if ( xmt_bytes != blen )
1475 xmlGenericError(*(__xmlGenericError()))( xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1476 "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n",
1477 xmt_bytes, blen,
1478 "bytes of HTTP headers sent to host",
1479 ctxt->hostname );
1480#else
1481 xmlNanoHTTPSend(ctxt, ctxt->out, blen );
1482#endif
1483
1484 if ( input != NULL((void*)0) ) {
1485#ifdef DEBUG_HTTP
1486 xmt_bytes = xmlNanoHTTPSend( ctxt, input, ilen );
1487
1488 if ( xmt_bytes != ilen )
1489 xmlGenericError(*(__xmlGenericError()))( xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1490 "xmlNanoHTTPMethodRedir: Only %d of %d %s %s\n",
1491 xmt_bytes, ilen,
1492 "bytes of HTTP content sent to host",
1493 ctxt->hostname );
1494#else
1495 xmlNanoHTTPSend( ctxt, input, ilen );
1496#endif
1497 }
1498
1499 ctxt->state = XML_NANO_HTTP_READ2;
1500 head = 1;
1501
1502 while ((p = xmlNanoHTTPReadLine(ctxt)) != NULL((void*)0)) {
1503 if (head && (*p == 0)) {
1504 head = 0;
Value stored to 'head' is never read
1505 ctxt->content = ctxt->inrptr;
1506 xmlFree(p);
1507 break;
1508 }
1509 xmlNanoHTTPScanAnswer(ctxt, p);
1510
1511#ifdef DEBUG_HTTP
1512 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())), "<- %s\n", p);
1513#endif
1514 xmlFree(p);
1515 }
1516
1517 if ((ctxt->location != NULL((void*)0)) && (ctxt->returnValue >= 300) &&
1518 (ctxt->returnValue < 400)) {
1519#ifdef DEBUG_HTTP
1520 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1521 "\nRedirect to: %s\n", ctxt->location);
1522#endif
1523 while ( xmlNanoHTTPRecv(ctxt) > 0 ) ;
1524 if (nbRedirects < XML_NANO_HTTP_MAX_REDIR10) {
1525 nbRedirects++;
1526 if (redirURL != NULL((void*)0))
1527 xmlFree(redirURL);
1528 redirURL = xmlMemStrdup(ctxt->location);
1529 xmlNanoHTTPFreeCtxt(ctxt);
1530 goto retry;
1531 }
1532 xmlNanoHTTPFreeCtxt(ctxt);
1533 if (redirURL != NULL((void*)0)) xmlFree(redirURL);
1534#ifdef DEBUG_HTTP
1535 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1536 "xmlNanoHTTPMethodRedir: Too many redirects, aborting ...\n");
1537#endif
1538 return(NULL((void*)0));
1539 }
1540
1541 if (contentType != NULL((void*)0)) {
1542 if (ctxt->contentType != NULL((void*)0))
1543 *contentType = xmlMemStrdup(ctxt->contentType);
1544 else
1545 *contentType = NULL((void*)0);
1546 }
1547
1548 if ((redir != NULL((void*)0)) && (redirURL != NULL((void*)0))) {
1549 *redir = redirURL;
1550 } else {
1551 if (redirURL != NULL((void*)0))
1552 xmlFree(redirURL);
1553 if (redir != NULL((void*)0))
1554 *redir = NULL((void*)0);
1555 }
1556
1557#ifdef DEBUG_HTTP
1558 if (ctxt->contentType != NULL((void*)0))
1559 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1560 "\nCode %d, content-type '%s'\n\n",
1561 ctxt->returnValue, ctxt->contentType);
1562 else
1563 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1564 "\nCode %d, no content-type\n\n",
1565 ctxt->returnValue);
1566#endif
1567
1568 return((void *) ctxt);
1569}
1570
1571/**
1572 * xmlNanoHTTPMethod:
1573 * @URL: The URL to load
1574 * @method: the HTTP method to use
1575 * @input: the input string if any
1576 * @contentType: the Content-Type information IN and OUT
1577 * @headers: the extra headers
1578 * @ilen: input length
1579 *
1580 * This function try to open a connection to the indicated resource
1581 * via HTTP using the given @method, adding the given extra headers
1582 * and the input buffer for the request content.
1583 *
1584 * Returns NULL in case of failure, otherwise a request handler.
1585 * The contentType, if provided must be freed by the caller
1586 */
1587
1588void*
1589xmlNanoHTTPMethod(const char *URL, const char *method, const char *input,
1590 char **contentType, const char *headers, int ilen) {
1591 return(xmlNanoHTTPMethodRedir(URL, method, input, contentType,
1592 NULL((void*)0), headers, ilen));
1593}
1594
1595/**
1596 * xmlNanoHTTPFetch:
1597 * @URL: The URL to load
1598 * @filename: the filename where the content should be saved
1599 * @contentType: if available the Content-Type information will be
1600 * returned at that location
1601 *
1602 * This function try to fetch the indicated resource via HTTP GET
1603 * and save it's content in the file.
1604 *
1605 * Returns -1 in case of failure, 0 incase of success. The contentType,
1606 * if provided must be freed by the caller
1607 */
1608int
1609xmlNanoHTTPFetch(const char *URL, const char *filename, char **contentType) {
1610 void *ctxt = NULL((void*)0);
1611 char *buf = NULL((void*)0);
1612 int fd;
1613 int len;
1614
1615 if (filename == NULL((void*)0)) return(-1);
1616 ctxt = xmlNanoHTTPOpen(URL, contentType);
1617 if (ctxt == NULL((void*)0)) return(-1);
1618
1619 if (!strcmp(filename, "-"))
1620 fd = 0;
1621 else {
1622 fd = open(filename, O_CREAT0100 | O_WRONLY01, 00644);
1623 if (fd < 0) {
1624 xmlNanoHTTPClose(ctxt);
1625 if ((contentType != NULL((void*)0)) && (*contentType != NULL((void*)0))) {
1626 xmlFree(*contentType);
1627 *contentType = NULL((void*)0);
1628 }
1629 return(-1);
1630 }
1631 }
1632
1633 xmlNanoHTTPFetchContent( ctxt, &buf, &len );
1634 if ( len > 0 ) {
1635 write(fd, buf, len);
1636 }
1637
1638 xmlNanoHTTPClose(ctxt);
1639 close(fd);
1640 return(0);
1641}
1642
1643#ifdef LIBXML_OUTPUT_ENABLED
1644/**
1645 * xmlNanoHTTPSave:
1646 * @ctxt: the HTTP context
1647 * @filename: the filename where the content should be saved
1648 *
1649 * This function saves the output of the HTTP transaction to a file
1650 * It closes and free the context at the end
1651 *
1652 * Returns -1 in case of failure, 0 incase of success.
1653 */
1654int
1655xmlNanoHTTPSave(void *ctxt, const char *filename) {
1656 char *buf = NULL((void*)0);
1657 int fd;
1658 int len;
1659
1660 if ((ctxt == NULL((void*)0)) || (filename == NULL((void*)0))) return(-1);
1661
1662 if (!strcmp(filename, "-"))
1663 fd = 0;
1664 else {
1665 fd = open(filename, O_CREAT0100 | O_WRONLY01, 0666);
1666 if (fd < 0) {
1667 xmlNanoHTTPClose(ctxt);
1668 return(-1);
1669 }
1670 }
1671
1672 xmlNanoHTTPFetchContent( ctxt, &buf, &len );
1673 if ( len > 0 ) {
1674 write(fd, buf, len);
1675 }
1676
1677 xmlNanoHTTPClose(ctxt);
1678 close(fd);
1679 return(0);
1680}
1681#endif /* LIBXML_OUTPUT_ENABLED */
1682
1683/**
1684 * xmlNanoHTTPReturnCode:
1685 * @ctx: the HTTP context
1686 *
1687 * Get the latest HTTP return code received
1688 *
1689 * Returns the HTTP return code for the request.
1690 */
1691int
1692xmlNanoHTTPReturnCode(void *ctx) {
1693 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1694
1695 if (ctxt == NULL((void*)0)) return(-1);
1696
1697 return(ctxt->returnValue);
1698}
1699
1700/**
1701 * xmlNanoHTTPAuthHeader:
1702 * @ctx: the HTTP context
1703 *
1704 * Get the authentication header of an HTTP context
1705 *
1706 * Returns the stashed value of the WWW-Authenticate or Proxy-Authenticate
1707 * header.
1708 */
1709const char *
1710xmlNanoHTTPAuthHeader(void *ctx) {
1711 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1712
1713 if (ctxt == NULL((void*)0)) return(NULL((void*)0));
1714
1715 return(ctxt->authHeader);
1716}
1717
1718/**
1719 * xmlNanoHTTPContentLength:
1720 * @ctx: the HTTP context
1721 *
1722 * Provides the specified content length from the HTTP header.
1723 *
1724 * Return the specified content length from the HTTP header. Note that
1725 * a value of -1 indicates that the content length element was not included in
1726 * the response header.
1727 */
1728int
1729xmlNanoHTTPContentLength( void * ctx ) {
1730 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1731
1732 return ( ( ctxt == NULL((void*)0) ) ? -1 : ctxt->ContentLength );
1733}
1734
1735/**
1736 * xmlNanoHTTPRedir:
1737 * @ctx: the HTTP context
1738 *
1739 * Provides the specified redirection URL if available from the HTTP header.
1740 *
1741 * Return the specified redirection URL or NULL if not redirected.
1742 */
1743const char *
1744xmlNanoHTTPRedir( void * ctx ) {
1745 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1746
1747 return ( ( ctxt == NULL((void*)0) ) ? NULL((void*)0) : ctxt->location );
1748}
1749
1750/**
1751 * xmlNanoHTTPEncoding:
1752 * @ctx: the HTTP context
1753 *
1754 * Provides the specified encoding if specified in the HTTP headers.
1755 *
1756 * Return the specified encoding or NULL if not available
1757 */
1758const char *
1759xmlNanoHTTPEncoding( void * ctx ) {
1760 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1761
1762 return ( ( ctxt == NULL((void*)0) ) ? NULL((void*)0) : ctxt->encoding );
1763}
1764
1765/**
1766 * xmlNanoHTTPMimeType:
1767 * @ctx: the HTTP context
1768 *
1769 * Provides the specified Mime-Type if specified in the HTTP headers.
1770 *
1771 * Return the specified Mime-Type or NULL if not available
1772 */
1773const char *
1774xmlNanoHTTPMimeType( void * ctx ) {
1775 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1776
1777 return ( ( ctxt == NULL((void*)0) ) ? NULL((void*)0) : ctxt->mimeType );
1778}
1779
1780/**
1781 * xmlNanoHTTPFetchContent:
1782 * @ctx: the HTTP context
1783 * @ptr: pointer to set to the content buffer.
1784 * @len: integer pointer to hold the length of the content
1785 *
1786 * Check if all the content was read
1787 *
1788 * Returns 0 if all the content was read and available, returns
1789 * -1 if received content length was less than specified or an error
1790 * occurred.
1791 */
1792static int
1793xmlNanoHTTPFetchContent( void * ctx, char ** ptr, int * len ) {
1794 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr)ctx;
1795
1796 int rc = 0;
1797 int cur_lgth;
1798 int rcvd_lgth;
1799 int dummy_int;
1800 char * dummy_ptr = NULL((void*)0);
1801
1802 /* Dummy up return input parameters if not provided */
1803
1804 if ( len == NULL((void*)0) )
1805 len = &dummy_int;
1806
1807 if ( ptr == NULL((void*)0) )
1808 ptr = &dummy_ptr;
1809
1810 /* But can't work without the context pointer */
1811
1812 if ( ( ctxt == NULL((void*)0) ) || ( ctxt->content == NULL((void*)0) ) ) {
1813 *len = 0;
1814 *ptr = NULL((void*)0);
1815 return ( -1 );
1816 }
1817
1818 rcvd_lgth = ctxt->inptr - ctxt->content;
1819
1820 while ( (cur_lgth = xmlNanoHTTPRecv( ctxt )) > 0 ) {
1821
1822 rcvd_lgth += cur_lgth;
1823 if ( (ctxt->ContentLength > 0) && (rcvd_lgth >= ctxt->ContentLength) )
1824 break;
1825 }
1826
1827 *ptr = ctxt->content;
1828 *len = rcvd_lgth;
1829
1830 if ( ( ctxt->ContentLength > 0 ) && ( rcvd_lgth < ctxt->ContentLength ) )
1831 rc = -1;
1832 else if ( rcvd_lgth == 0 )
1833 rc = -1;
1834
1835 return ( rc );
1836}
1837
1838#ifdef STANDALONE
1839int main(int argc, char **argv) {
1840 char *contentType = NULL((void*)0);
1841
1842 if (argv[1] != NULL((void*)0)) {
1843 if (argv[2] != NULL((void*)0))
1844 xmlNanoHTTPFetch(argv[1], argv[2], &contentType);
1845 else
1846 xmlNanoHTTPFetch(argv[1], "-", &contentType);
1847 if (contentType != NULL((void*)0)) xmlFree(contentType);
1848 } else {
1849 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1850 "%s: minimal HTTP GET implementation\n", argv[0]);
1851 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1852 "\tusage %s [ URL [ filename ] ]\n", argv[0]);
1853 }
1854 xmlNanoHTTPCleanup();
1855 xmlMemoryDump();
1856 return(0);
1857}
1858#endif /* STANDALONE */
1859#else /* !LIBXML_HTTP_ENABLED */
1860#ifdef STANDALONE
1861#include <stdio.h>
1862int main(int argc, char **argv) {
1863 xmlGenericError(*(__xmlGenericError()))(xmlGenericErrorContext(*(__xmlGenericErrorContext())),
1864 "%s : HTTP support not compiled in\n", argv[0]);
1865 return(0);
1866}
1867#endif /* STANDALONE */
1868#endif /* LIBXML_HTTP_ENABLED */
1869#define bottom_nanohttp
1870#include "elfgcchack.h"