blob: 00b7fde08b9c0adaf442b9ca4bde8c8b2c65952a [file] [log] [blame]
Owen Taylor3473f882001-02-23 17:55:21 +00001/*
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@w3.org
12 */
13
14/* TODO add compression support, Send the Accept- , and decompress on the
15 fly with ZLIB if found at compile-time */
16
Bjorn Reese70a9da52001-04-21 16:57:29 +000017#include "libxml.h"
Owen Taylor3473f882001-02-23 17:55:21 +000018
19#ifdef LIBXML_HTTP_ENABLED
Owen Taylor3473f882001-02-23 17:55:21 +000020#include <string.h>
21
22#ifdef HAVE_STDLIB_H
23#include <stdlib.h>
24#endif
25#ifdef HAVE_UNISTD_H
26#include <unistd.h>
27#endif
28#ifdef HAVE_SYS_SOCKET_H
29#include <sys/socket.h>
30#endif
31#ifdef HAVE_NETINET_IN_H
32#include <netinet/in.h>
33#endif
34#ifdef HAVE_ARPA_INET_H
35#include <arpa/inet.h>
36#endif
37#ifdef HAVE_NETDB_H
38#include <netdb.h>
39#endif
40#ifdef HAVE_FCNTL_H
41#include <fcntl.h>
42#endif
43#ifdef HAVE_ERRNO_H
44#include <errno.h>
45#endif
46#ifdef HAVE_SYS_TIME_H
47#include <sys/time.h>
48#endif
49#ifdef HAVE_SYS_SELECT_H
50#include <sys/select.h>
51#endif
52#ifdef HAVE_STRINGS_H
53#include <strings.h>
54#endif
55#ifdef SUPPORT_IP6
56#include <resolv.h>
57#endif
58
59#ifdef VMS
60#include <stropts>
61#define SOCKLEN_T unsigned int
62#define SOCKET int
63#endif
64
65#include <libxml/xmlmemory.h>
66#include <libxml/parser.h> /* for xmlStr(n)casecmp() */
67#include <libxml/nanohttp.h>
68
69/**
70 * A couple portability macros
71 */
72#ifndef _WINSOCKAPI_
73#define closesocket(s) close(s)
74#define SOCKET int
75#endif
76
77#ifdef STANDALONE
78#define DEBUG_HTTP
79#define xmlStrncasecmp(a, b, n) strncasecmp((char *)a, (char *)b, n)
80#define xmlStrcasecmpi(a, b) strcasecmp((char *)a, (char *)b)
81#endif
82
83#define XML_NANO_HTTP_MAX_REDIR 10
84
85#define XML_NANO_HTTP_CHUNK 4096
86
87#define XML_NANO_HTTP_CLOSED 0
88#define XML_NANO_HTTP_WRITE 1
89#define XML_NANO_HTTP_READ 2
90#define XML_NANO_HTTP_NONE 4
91
92typedef struct xmlNanoHTTPCtxt {
93 char *protocol; /* the protocol name */
94 char *hostname; /* the host name */
95 int port; /* the port */
96 char *path; /* the path within the URL */
97 SOCKET fd; /* the file descriptor for the socket */
98 int state; /* WRITE / READ / CLOSED */
99 char *out; /* buffer sent (zero terminated) */
100 char *outptr; /* index within the buffer sent */
101 char *in; /* the receiving buffer */
102 char *content; /* the start of the content */
103 char *inptr; /* the next byte to read from network */
104 char *inrptr; /* the next byte to give back to the client */
105 int inlen; /* len of the input buffer */
106 int last; /* return code for last operation */
107 int returnValue; /* the protocol return value */
108 char *contentType; /* the MIME type for the input */
109 char *location; /* the new URL in case of redirect */
110 char *authHeader; /* contents of {WWW,Proxy}-Authenticate header */
111} xmlNanoHTTPCtxt, *xmlNanoHTTPCtxtPtr;
112
113static int initialized = 0;
114static char *proxy = NULL; /* the proxy name if any */
115static int proxyPort; /* the proxy port if any */
116static unsigned int timeout = 60;/* the select() timeout in seconds */
117
118/**
119 * A portability function
120 */
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000121static int socket_errno(void) {
Owen Taylor3473f882001-02-23 17:55:21 +0000122#ifdef _WINSOCKAPI_
123 return(WSAGetLastError());
124#else
125 return(errno);
126#endif
127}
128
129/**
130 * xmlNanoHTTPInit:
131 *
132 * Initialize the HTTP protocol layer.
133 * Currently it just checks for proxy informations
134 */
135
136void
137xmlNanoHTTPInit(void) {
138 const char *env;
139#ifdef _WINSOCKAPI_
140 WSADATA wsaData;
141#endif
142
143 if (initialized)
144 return;
145
146#ifdef _WINSOCKAPI_
147 if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
148 return;
149#endif
150
151 if (proxy == NULL) {
152 proxyPort = 80;
153 env = getenv("no_proxy");
154 if (env != NULL)
155 goto done;
156 env = getenv("http_proxy");
157 if (env != NULL) {
158 xmlNanoHTTPScanProxy(env);
159 goto done;
160 }
161 env = getenv("HTTP_PROXY");
162 if (env != NULL) {
163 xmlNanoHTTPScanProxy(env);
164 goto done;
165 }
166 }
167done:
168 initialized = 1;
169}
170
171/**
172 * xmlNanoHTTPClenup:
173 *
174 * Cleanup the HTTP protocol layer.
175 */
176
177void
178xmlNanoHTTPCleanup(void) {
179 if (proxy != NULL)
180 xmlFree(proxy);
181#ifdef _WINSOCKAPI_
182 if (initialized)
183 WSACleanup();
184#endif
185 initialized = 0;
186 return;
187}
188
189/**
Owen Taylor3473f882001-02-23 17:55:21 +0000190 * xmlNanoHTTPScanURL:
191 * @ctxt: an HTTP context
192 * @URL: The URL used to initialize the context
193 *
194 * (Re)Initialize an HTTP context by parsing the URL and finding
195 * the protocol host port and path it indicates.
196 */
197
198static void
199xmlNanoHTTPScanURL(xmlNanoHTTPCtxtPtr ctxt, const char *URL) {
200 const char *cur = URL;
201 char buf[4096];
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000202 int indx = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000203 int port = 0;
204
205 if (ctxt->protocol != NULL) {
206 xmlFree(ctxt->protocol);
207 ctxt->protocol = NULL;
208 }
209 if (ctxt->hostname != NULL) {
210 xmlFree(ctxt->hostname);
211 ctxt->hostname = NULL;
212 }
213 if (ctxt->path != NULL) {
214 xmlFree(ctxt->path);
215 ctxt->path = NULL;
216 }
217 if (URL == NULL) return;
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000218 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000219 while (*cur != 0) {
220 if ((cur[0] == ':') && (cur[1] == '/') && (cur[2] == '/')) {
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000221 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000222 ctxt->protocol = xmlMemStrdup(buf);
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000223 indx = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000224 cur += 3;
225 break;
226 }
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000227 buf[indx++] = *cur++;
Owen Taylor3473f882001-02-23 17:55:21 +0000228 }
229 if (*cur == 0) return;
230
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000231 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000232 while (1) {
233 if (cur[0] == ':') {
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000234 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000235 ctxt->hostname = xmlMemStrdup(buf);
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000236 indx = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000237 cur += 1;
238 while ((*cur >= '0') && (*cur <= '9')) {
239 port *= 10;
240 port += *cur - '0';
241 cur++;
242 }
243 if (port != 0) ctxt->port = port;
244 while ((cur[0] != '/') && (*cur != 0))
245 cur++;
246 break;
247 }
248 if ((*cur == '/') || (*cur == 0)) {
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000249 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000250 ctxt->hostname = xmlMemStrdup(buf);
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000251 indx = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000252 break;
253 }
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000254 buf[indx++] = *cur++;
Owen Taylor3473f882001-02-23 17:55:21 +0000255 }
256 if (*cur == 0)
257 ctxt->path = xmlMemStrdup("/");
258 else {
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000259 indx = 0;
260 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000261 while (*cur != 0)
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000262 buf[indx++] = *cur++;
263 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000264 ctxt->path = xmlMemStrdup(buf);
265 }
266}
267
268/**
269 * xmlNanoHTTPScanProxy:
270 * @URL: The proxy URL used to initialize the proxy context
271 *
272 * (Re)Initialize the HTTP Proxy context by parsing the URL and finding
273 * the protocol host port it indicates.
274 * Should be like http://myproxy/ or http://myproxy:3128/
275 * A NULL URL cleans up proxy informations.
276 */
277
278void
279xmlNanoHTTPScanProxy(const char *URL) {
280 const char *cur = URL;
281 char buf[4096];
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000282 int indx = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000283 int port = 0;
284
285 if (proxy != NULL) {
286 xmlFree(proxy);
287 proxy = NULL;
288 }
289 if (proxyPort != 0) {
290 proxyPort = 0;
291 }
292#ifdef DEBUG_HTTP
293 if (URL == NULL)
294 xmlGenericError(xmlGenericErrorContext,
295 "Removing HTTP proxy info\n");
296 else
297 xmlGenericError(xmlGenericErrorContext,
298 "Using HTTP proxy %s\n", URL);
299#endif
300 if (URL == NULL) return;
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000301 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000302 while (*cur != 0) {
303 if ((cur[0] == ':') && (cur[1] == '/') && (cur[2] == '/')) {
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000304 buf[indx] = 0;
305 indx = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000306 cur += 3;
307 break;
308 }
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000309 buf[indx++] = *cur++;
Owen Taylor3473f882001-02-23 17:55:21 +0000310 }
311 if (*cur == 0) return;
312
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000313 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000314 while (1) {
315 if (cur[0] == ':') {
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000316 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000317 proxy = xmlMemStrdup(buf);
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000318 indx = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000319 cur += 1;
320 while ((*cur >= '0') && (*cur <= '9')) {
321 port *= 10;
322 port += *cur - '0';
323 cur++;
324 }
325 if (port != 0) proxyPort = port;
326 while ((cur[0] != '/') && (*cur != 0))
327 cur++;
328 break;
329 }
330 if ((*cur == '/') || (*cur == 0)) {
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000331 buf[indx] = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000332 proxy = xmlMemStrdup(buf);
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000333 indx = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000334 break;
335 }
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000336 buf[indx++] = *cur++;
Owen Taylor3473f882001-02-23 17:55:21 +0000337 }
338}
339
340/**
341 * xmlNanoHTTPNewCtxt:
342 * @URL: The URL used to initialize the context
343 *
344 * Allocate and initialize a new HTTP context.
345 *
346 * Returns an HTTP context or NULL in case of error.
347 */
348
349static xmlNanoHTTPCtxtPtr
350xmlNanoHTTPNewCtxt(const char *URL) {
351 xmlNanoHTTPCtxtPtr ret;
352
353 ret = (xmlNanoHTTPCtxtPtr) xmlMalloc(sizeof(xmlNanoHTTPCtxt));
354 if (ret == NULL) return(NULL);
355
356 memset(ret, 0, sizeof(xmlNanoHTTPCtxt));
357 ret->port = 80;
358 ret->returnValue = 0;
359 ret->fd = -1;
360
361 xmlNanoHTTPScanURL(ret, URL);
362
363 return(ret);
364}
365
366/**
367 * xmlNanoHTTPFreeCtxt:
368 * @ctxt: an HTTP context
369 *
370 * Frees the context after closing the connection.
371 */
372
373static void
374xmlNanoHTTPFreeCtxt(xmlNanoHTTPCtxtPtr ctxt) {
375 if (ctxt == NULL) return;
376 if (ctxt->hostname != NULL) xmlFree(ctxt->hostname);
377 if (ctxt->protocol != NULL) xmlFree(ctxt->protocol);
378 if (ctxt->path != NULL) xmlFree(ctxt->path);
379 if (ctxt->out != NULL) xmlFree(ctxt->out);
380 if (ctxt->in != NULL) xmlFree(ctxt->in);
381 if (ctxt->contentType != NULL) xmlFree(ctxt->contentType);
382 if (ctxt->location != NULL) xmlFree(ctxt->location);
383 if (ctxt->authHeader != NULL) xmlFree(ctxt->authHeader);
384 ctxt->state = XML_NANO_HTTP_NONE;
385 if (ctxt->fd >= 0) closesocket(ctxt->fd);
386 ctxt->fd = -1;
387 xmlFree(ctxt);
388}
389
390/**
391 * xmlNanoHTTPSend:
392 * @ctxt: an HTTP context
393 *
394 * Send the input needed to initiate the processing on the server side
395 */
396
397static void
398xmlNanoHTTPSend(xmlNanoHTTPCtxtPtr ctxt) {
399 if (ctxt->state & XML_NANO_HTTP_WRITE) {
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000400 unsigned int total_sent = 0;
Owen Taylor3473f882001-02-23 17:55:21 +0000401 while (total_sent <strlen(ctxt->outptr)) {
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000402 unsigned int nsent = send(ctxt->fd, ctxt->outptr+total_sent,
403 strlen(ctxt->outptr)-total_sent, 0);
Owen Taylor3473f882001-02-23 17:55:21 +0000404 if (nsent>0)
405 total_sent += nsent;
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000406 }
Owen Taylor3473f882001-02-23 17:55:21 +0000407 ctxt->last = total_sent;
408 }
409}
410
411/**
412 * xmlNanoHTTPRecv:
413 * @ctxt: an HTTP context
414 *
415 * Read information coming from the HTTP connection.
416 * This is a blocking call (but it blocks in select(), not read()).
417 *
418 * Returns the number of byte read or -1 in case of error.
419 */
420
421static int
422xmlNanoHTTPRecv(xmlNanoHTTPCtxtPtr ctxt) {
423 fd_set rfd;
424 struct timeval tv;
425
426
427 while (ctxt->state & XML_NANO_HTTP_READ) {
428 if (ctxt->in == NULL) {
429 ctxt->in = (char *) xmlMalloc(65000 * sizeof(char));
430 if (ctxt->in == NULL) {
431 ctxt->last = -1;
432 return(-1);
433 }
434 ctxt->inlen = 65000;
435 ctxt->inptr = ctxt->content = ctxt->inrptr = ctxt->in;
436 }
437 if (ctxt->inrptr > ctxt->in + XML_NANO_HTTP_CHUNK) {
438 int delta = ctxt->inrptr - ctxt->in;
439 int len = ctxt->inptr - ctxt->inrptr;
440
441 memmove(ctxt->in, ctxt->inrptr, len);
442 ctxt->inrptr -= delta;
443 ctxt->content -= delta;
444 ctxt->inptr -= delta;
445 }
446 if ((ctxt->in + ctxt->inlen) < (ctxt->inptr + XML_NANO_HTTP_CHUNK)) {
447 int d_inptr = ctxt->inptr - ctxt->in;
448 int d_content = ctxt->content - ctxt->in;
449 int d_inrptr = ctxt->inrptr - ctxt->in;
450
451 ctxt->inlen *= 2;
452 ctxt->in = (char *) xmlRealloc(ctxt->in, ctxt->inlen);
453 if (ctxt->in == NULL) {
454 ctxt->last = -1;
455 return(-1);
456 }
457 ctxt->inptr = ctxt->in + d_inptr;
458 ctxt->content = ctxt->in + d_content;
459 ctxt->inrptr = ctxt->in + d_inrptr;
460 }
461 ctxt->last = recv(ctxt->fd, ctxt->inptr, XML_NANO_HTTP_CHUNK, 0);
462 if (ctxt->last > 0) {
463 ctxt->inptr += ctxt->last;
464 return(ctxt->last);
465 }
466 if (ctxt->last == 0) {
467 return(0);
468 }
469 if (ctxt->last == -1) {
470 switch (socket_errno()) {
471 case EINPROGRESS:
472 case EWOULDBLOCK:
473#if defined(EAGAIN) && EAGAIN != EWOULDBLOCK
474 case EAGAIN:
475#endif
476 break;
477 default:
478 return(0);
479 }
480 }
481
482 tv.tv_sec = timeout;
483 tv.tv_usec = 0;
484 FD_ZERO(&rfd);
485 FD_SET(ctxt->fd, &rfd);
486
487 if (select(ctxt->fd+1, &rfd, NULL, NULL, &tv)<1)
488 return(0);
489 }
490 return(0);
491}
492
493/**
494 * xmlNanoHTTPReadLine:
495 * @ctxt: an HTTP context
496 *
497 * Read one line in the HTTP server output, usually for extracting
498 * the HTTP protocol informations from the answer header.
499 *
500 * Returns a newly allocated string with a copy of the line, or NULL
501 * which indicate the end of the input.
502 */
503
504static char *
505xmlNanoHTTPReadLine(xmlNanoHTTPCtxtPtr ctxt) {
506 char buf[4096];
507 char *bp = buf;
508
509 while (bp - buf < 4095) {
510 if (ctxt->inrptr == ctxt->inptr) {
511 if (xmlNanoHTTPRecv(ctxt) == 0) {
512 if (bp == buf)
513 return(NULL);
514 else
515 *bp = 0;
516 return(xmlMemStrdup(buf));
517 }
518 }
519 *bp = *ctxt->inrptr++;
520 if (*bp == '\n') {
521 *bp = 0;
522 return(xmlMemStrdup(buf));
523 }
524 if (*bp != '\r')
525 bp++;
526 }
527 buf[4095] = 0;
528 return(xmlMemStrdup(buf));
529}
530
531
532/**
533 * xmlNanoHTTPScanAnswer:
534 * @ctxt: an HTTP context
535 * @line: an HTTP header line
536 *
537 * Try to extract useful informations from the server answer.
538 * We currently parse and process:
539 * - The HTTP revision/ return code
540 * - The Content-Type
541 * - The Location for redirrect processing.
542 *
543 * Returns -1 in case of failure, the file descriptor number otherwise
544 */
545
546static void
547xmlNanoHTTPScanAnswer(xmlNanoHTTPCtxtPtr ctxt, const char *line) {
548 const char *cur = line;
549
550 if (line == NULL) return;
551
552 if (!strncmp(line, "HTTP/", 5)) {
553 int version = 0;
554 int ret = 0;
555
556 cur += 5;
557 while ((*cur >= '0') && (*cur <= '9')) {
558 version *= 10;
559 version += *cur - '0';
560 cur++;
561 }
562 if (*cur == '.') {
563 cur++;
564 if ((*cur >= '0') && (*cur <= '9')) {
565 version *= 10;
566 version += *cur - '0';
567 cur++;
568 }
569 while ((*cur >= '0') && (*cur <= '9'))
570 cur++;
571 } else
572 version *= 10;
573 if ((*cur != ' ') && (*cur != '\t')) return;
574 while ((*cur == ' ') || (*cur == '\t')) cur++;
575 if ((*cur < '0') || (*cur > '9')) return;
576 while ((*cur >= '0') && (*cur <= '9')) {
577 ret *= 10;
578 ret += *cur - '0';
579 cur++;
580 }
581 if ((*cur != 0) && (*cur != ' ') && (*cur != '\t')) return;
582 ctxt->returnValue = ret;
583 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Content-Type:", 13)) {
584 cur += 13;
585 while ((*cur == ' ') || (*cur == '\t')) cur++;
586 if (ctxt->contentType != NULL)
587 xmlFree(ctxt->contentType);
588 ctxt->contentType = xmlMemStrdup(cur);
589 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"ContentType:", 12)) {
590 cur += 12;
591 if (ctxt->contentType != NULL) return;
592 while ((*cur == ' ') || (*cur == '\t')) cur++;
593 ctxt->contentType = xmlMemStrdup(cur);
594 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Location:", 9)) {
595 cur += 9;
596 while ((*cur == ' ') || (*cur == '\t')) cur++;
597 if (ctxt->location != NULL)
598 xmlFree(ctxt->location);
599 ctxt->location = xmlMemStrdup(cur);
600 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"WWW-Authenticate:", 17)) {
601 cur += 17;
602 while ((*cur == ' ') || (*cur == '\t')) cur++;
603 if (ctxt->authHeader != NULL)
604 xmlFree(ctxt->authHeader);
605 ctxt->authHeader = xmlMemStrdup(cur);
606 } else if (!xmlStrncasecmp(BAD_CAST line, BAD_CAST"Proxy-Authenticate:", 19)) {
607 cur += 19;
608 while ((*cur == ' ') || (*cur == '\t')) cur++;
609 if (ctxt->authHeader != NULL)
610 xmlFree(ctxt->authHeader);
611 ctxt->authHeader = xmlMemStrdup(cur);
612 }
613}
614
615/**
616 * xmlNanoHTTPConnectAttempt:
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000617 * @addr: a socket adress structure
Owen Taylor3473f882001-02-23 17:55:21 +0000618 *
619 * Attempt a connection to the given IP:port endpoint. It forces
620 * non-blocking semantic on the socket, and allow 60 seconds for
621 * the host to answer.
622 *
623 * Returns -1 in case of failure, the file descriptor number otherwise
624 */
625
626static int
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000627xmlNanoHTTPConnectAttempt(struct sockaddr *addr)
Owen Taylor3473f882001-02-23 17:55:21 +0000628{
629 SOCKET s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
630 fd_set wfd;
631 struct timeval tv;
632 int status;
633
634 if (s==-1) {
635#ifdef DEBUG_HTTP
636 perror("socket");
637#endif
638 return(-1);
639 }
640
641#ifdef _WINSOCKAPI_
642 {
643 u_long one = 1;
644
645 status = ioctlsocket(s, FIONBIO, &one) == SOCKET_ERROR ? -1 : 0;
646 }
647#else /* _WINSOCKAPI_ */
648#if defined(VMS)
649 {
650 int enable = 1;
651 status = ioctl(s, FIONBIO, &enable);
652 }
653#else /* VMS */
654 if ((status = fcntl(s, F_GETFL, 0)) != -1) {
655#ifdef O_NONBLOCK
656 status |= O_NONBLOCK;
657#else /* O_NONBLOCK */
658#ifdef F_NDELAY
659 status |= F_NDELAY;
660#endif /* F_NDELAY */
661#endif /* !O_NONBLOCK */
662 status = fcntl(s, F_SETFL, status);
663 }
664 if (status < 0) {
665#ifdef DEBUG_HTTP
666 perror("nonblocking");
667#endif
668 closesocket(s);
669 return(-1);
670 }
671#endif /* !VMS */
672#endif /* !_WINSOCKAPI_ */
673
674
675 if ((connect(s, addr, sizeof(*addr))==-1)) {
676 switch (socket_errno()) {
677 case EINPROGRESS:
678 case EWOULDBLOCK:
679 break;
680 default:
681 perror("connect");
682 closesocket(s);
683 return(-1);
684 }
685 }
686
687 tv.tv_sec = timeout;
688 tv.tv_usec = 0;
689
690 FD_ZERO(&wfd);
691 FD_SET(s, &wfd);
692
693 switch(select(s+1, NULL, &wfd, NULL, &tv))
694 {
695 case 0:
696 /* Time out */
697 closesocket(s);
698 return(-1);
699 case -1:
700 /* Ermm.. ?? */
701#ifdef DEBUG_HTTP
702 perror("select");
703#endif
704 closesocket(s);
705 return(-1);
706 }
707
708 if ( FD_ISSET(s, &wfd) ) {
709 SOCKLEN_T len;
710 len = sizeof(status);
711 if (getsockopt(s, SOL_SOCKET, SO_ERROR, (char*)&status, &len) < 0 ) {
712 /* Solaris error code */
713 return (-1);
714 }
715 if ( status ) {
716 closesocket(s);
717 errno = status;
718 return (-1);
719 }
720 } else {
721 /* pbm */
722 return (-1);
723 }
724
725 return(s);
726}
727
728/**
729 * xmlNanoHTTPConnectHost:
730 * @host: the host name
731 * @port: the port number
732 *
733 * Attempt a connection to the given host:port endpoint. It tries
734 * the multiple IP provided by the DNS if available.
735 *
736 * Returns -1 in case of failure, the file descriptor number otherwise
737 */
738
739static int
740xmlNanoHTTPConnectHost(const char *host, int port)
741{
742 struct hostent *h;
743 struct sockaddr *addr;
744 struct in_addr ia;
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000745 struct sockaddr_in sockin;
Owen Taylor3473f882001-02-23 17:55:21 +0000746#ifdef SUPPORT_IP6
747 struct in6_addr ia6;
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000748 struct sockaddr_in6 sockin6;
Owen Taylor3473f882001-02-23 17:55:21 +0000749#endif
750 int i;
751 int s;
752
753#if defined(SUPPORT_IP6) && defined(RES_USE_INET6)
754 if (!(_res.options & RES_INIT))
755 res_init();
756 _res.options |= RES_USE_INET6;
757#endif
758 h=gethostbyname(host);
759 if (h==NULL)
760 {
761#ifdef DEBUG_HTTP
762 xmlGenericError(xmlGenericErrorContext,"unable to resolve '%s'.\n", host);
763#endif
764 return(-1);
765 }
766
767 for(i=0; h->h_addr_list[i]; i++)
768 {
769 if (h->h_addrtype == AF_INET) {
770 /* A records (IPv4) */
771 memcpy(&ia, h->h_addr_list[i], h->h_length);
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000772 sockin.sin_family = h->h_addrtype;
773 sockin.sin_addr = ia;
774 sockin.sin_port = htons(port);
775 addr = (struct sockaddr *)&sockin;
Owen Taylor3473f882001-02-23 17:55:21 +0000776#ifdef SUPPORT_IP6
777 } else if (h->h_addrtype == AF_INET6) {
778 /* AAAA records (IPv6) */
779 memcpy(&ia6, h->h_addr_list[i], h->h_length);
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000780 sockin6.sin_family = h->h_addrtype;
781 sockin6.sin_addr = ia6;
782 sockin6.sin_port = htons(port);
783 addr = (struct sockaddr *)&sockin6;
Owen Taylor3473f882001-02-23 17:55:21 +0000784#endif
785 } else
786 break; /* for */
787
Daniel Veillard56a4cb82001-03-24 17:00:36 +0000788 s = xmlNanoHTTPConnectAttempt(addr);
Owen Taylor3473f882001-02-23 17:55:21 +0000789 if (s != -1)
790 return(s);
791 }
792
793#ifdef DEBUG_HTTP
794 xmlGenericError(xmlGenericErrorContext,
795 "unable to connect to '%s'.\n", host);
796#endif
797 return(-1);
798}
799
800
801/**
802 * xmlNanoHTTPOpen:
803 * @URL: The URL to load
804 * @contentType: if available the Content-Type information will be
805 * returned at that location
806 *
807 * This function try to open a connection to the indicated resource
808 * via HTTP GET.
809 *
810 * Returns NULL in case of failure, otherwise a request handler.
811 * The contentType, if provided must be freed by the caller
812 */
813
814void*
815xmlNanoHTTPOpen(const char *URL, char **contentType) {
816 if (contentType != NULL) *contentType = NULL;
817 return xmlNanoHTTPMethod(URL, NULL, NULL, contentType, NULL);
818}
819
820/**
821 * xmlNanoHTTPRead:
822 * @ctx: the HTTP context
823 * @dest: a buffer
824 * @len: the buffer length
825 *
826 * This function tries to read @len bytes from the existing HTTP connection
827 * and saves them in @dest. This is a blocking call.
828 *
829 * Returns the number of byte read. 0 is an indication of an end of connection.
830 * -1 indicates a parameter error.
831 */
832int
833xmlNanoHTTPRead(void *ctx, void *dest, int len) {
834 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
835
836 if (ctx == NULL) return(-1);
837 if (dest == NULL) return(-1);
838 if (len <= 0) return(0);
839
840 while (ctxt->inptr - ctxt->inrptr < len) {
841 if (xmlNanoHTTPRecv(ctxt) == 0) break;
842 }
843 if (ctxt->inptr - ctxt->inrptr < len)
844 len = ctxt->inptr - ctxt->inrptr;
845 memcpy(dest, ctxt->inrptr, len);
846 ctxt->inrptr += len;
847 return(len);
848}
849
850/**
851 * xmlNanoHTTPClose:
852 * @ctx: the HTTP context
853 *
854 * This function closes an HTTP context, it ends up the connection and
855 * free all data related to it.
856 */
857void
858xmlNanoHTTPClose(void *ctx) {
859 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
860
861 if (ctx == NULL) return;
862
863 xmlNanoHTTPFreeCtxt(ctxt);
864}
865
866/**
867 * xmlNanoHTTPMethod:
868 * @URL: The URL to load
869 * @method: the HTTP method to use
870 * @input: the input string if any
871 * @contentType: the Content-Type information IN and OUT
872 * @headers: the extra headers
873 *
874 * This function try to open a connection to the indicated resource
875 * via HTTP using the given @method, adding the given extra headers
876 * and the input buffer for the request content.
877 *
878 * Returns NULL in case of failure, otherwise a request handler.
879 * The contentType, if provided must be freed by the caller
880 */
881
882void*
883xmlNanoHTTPMethod(const char *URL, const char *method, const char *input,
884 char **contentType, const char *headers) {
885 xmlNanoHTTPCtxtPtr ctxt;
886 char *bp, *p;
887 int blen, ilen, ret;
888 int head;
889 int nbRedirects = 0;
890 char *redirURL = NULL;
891
892 if (URL == NULL) return(NULL);
893 if (method == NULL) method = "GET";
894 xmlNanoHTTPInit();
895
896retry:
897 if (redirURL == NULL)
898 ctxt = xmlNanoHTTPNewCtxt(URL);
899 else {
900 ctxt = xmlNanoHTTPNewCtxt(redirURL);
901 xmlFree(redirURL);
902 redirURL = NULL;
903 }
904
905 if ((ctxt->protocol == NULL) || (strcmp(ctxt->protocol, "http"))) {
906 xmlNanoHTTPFreeCtxt(ctxt);
907 if (redirURL != NULL) xmlFree(redirURL);
908 return(NULL);
909 }
910 if (ctxt->hostname == NULL) {
911 xmlNanoHTTPFreeCtxt(ctxt);
912 return(NULL);
913 }
914 if (proxy) {
915 blen = strlen(ctxt->hostname) * 2 + 16;
916 ret = xmlNanoHTTPConnectHost(proxy, proxyPort);
917 }
918 else {
919 blen = strlen(ctxt->hostname);
920 ret = xmlNanoHTTPConnectHost(ctxt->hostname, ctxt->port);
921 }
922 if (ret < 0) {
923 xmlNanoHTTPFreeCtxt(ctxt);
924 return(NULL);
925 }
926 ctxt->fd = ret;
927
928 if (input != NULL) {
929 ilen = strlen(input);
930 blen += ilen + 32;
931 }
932 else
933 ilen = 0;
934 if (headers != NULL)
935 blen += strlen(headers);
936 if (contentType && *contentType)
937 blen += strlen(*contentType) + 16;
938 blen += strlen(method) + strlen(ctxt->path) + 23;
939 bp = xmlMalloc(blen);
940 if (proxy) {
941 if (ctxt->port != 80) {
942 sprintf(bp, "%s http://%s:%d%s", method, ctxt->hostname,
943 ctxt->port, ctxt->path);
944 }
945 else
946 sprintf(bp, "%s http://%s%s", method, ctxt->hostname, ctxt->path);
947 }
948 else
949 sprintf(bp, "%s %s", method, ctxt->path);
950 p = bp + strlen(bp);
951 sprintf(p, " HTTP/1.0\r\nHost: %s\r\n", ctxt->hostname);
952 p += strlen(p);
953 if (contentType != NULL && *contentType) {
954 sprintf(p, "Content-Type: %s\r\n", *contentType);
955 p += strlen(p);
956 }
957 if (headers != NULL) {
958 strcpy(p, headers);
959 p += strlen(p);
960 }
961 if (input != NULL)
962 sprintf(p, "Content-Length: %d\r\n\r\n%s", ilen, input);
963 else
964 strcpy(p, "\r\n");
965#ifdef DEBUG_HTTP
966 xmlGenericError(xmlGenericErrorContext,
967 "-> %s%s", proxy? "(Proxy) " : "", bp);
968 if ((blen -= strlen(bp)+1) < 0)
969 xmlGenericError(xmlGenericErrorContext,
970 "ERROR: overflowed buffer by %d bytes\n", -blen);
971#endif
972 ctxt->outptr = ctxt->out = bp;
973 ctxt->state = XML_NANO_HTTP_WRITE;
974 xmlNanoHTTPSend(ctxt);
975 ctxt->state = XML_NANO_HTTP_READ;
976 head = 1;
977
978 while ((p = xmlNanoHTTPReadLine(ctxt)) != NULL) {
979 if (head && (*p == 0)) {
980 head = 0;
981 ctxt->content = ctxt->inrptr;
982 xmlFree(p);
983 break;
984 }
985 xmlNanoHTTPScanAnswer(ctxt, p);
986
987#ifdef DEBUG_HTTP
988 xmlGenericError(xmlGenericErrorContext, "<- %s\n", p);
989#endif
990 xmlFree(p);
991 }
992
993 if ((ctxt->location != NULL) && (ctxt->returnValue >= 300) &&
994 (ctxt->returnValue < 400)) {
995#ifdef DEBUG_HTTP
996 xmlGenericError(xmlGenericErrorContext,
997 "\nRedirect to: %s\n", ctxt->location);
998#endif
999 while (xmlNanoHTTPRecv(ctxt)) ;
1000 if (nbRedirects < XML_NANO_HTTP_MAX_REDIR) {
1001 nbRedirects++;
1002 redirURL = xmlMemStrdup(ctxt->location);
1003 xmlNanoHTTPFreeCtxt(ctxt);
1004 goto retry;
1005 }
1006 xmlNanoHTTPFreeCtxt(ctxt);
1007#ifdef DEBUG_HTTP
1008 xmlGenericError(xmlGenericErrorContext,
1009 "Too many redirects, aborting ...\n");
1010#endif
1011 return(NULL);
1012
1013 }
1014
1015 if (contentType != NULL) {
1016 if (ctxt->contentType != NULL)
1017 *contentType = xmlMemStrdup(ctxt->contentType);
1018 else
1019 *contentType = NULL;
1020 }
1021
1022#ifdef DEBUG_HTTP
1023 if (ctxt->contentType != NULL)
1024 xmlGenericError(xmlGenericErrorContext,
1025 "\nCode %d, content-type '%s'\n\n",
1026 ctxt->returnValue, ctxt->contentType);
1027 else
1028 xmlGenericError(xmlGenericErrorContext,
1029 "\nCode %d, no content-type\n\n",
1030 ctxt->returnValue);
1031#endif
1032
1033 return((void *) ctxt);
1034}
1035
1036/**
1037 * xmlNanoHTTPFetch:
1038 * @URL: The URL to load
1039 * @filename: the filename where the content should be saved
1040 * @contentType: if available the Content-Type information will be
1041 * returned at that location
1042 *
1043 * This function try to fetch the indicated resource via HTTP GET
1044 * and save it's content in the file.
1045 *
1046 * Returns -1 in case of failure, 0 incase of success. The contentType,
1047 * if provided must be freed by the caller
1048 */
1049int
1050xmlNanoHTTPFetch(const char *URL, const char *filename, char **contentType) {
1051 void *ctxt;
1052 char buf[4096];
1053 int fd;
1054 int len;
1055
1056 ctxt = xmlNanoHTTPOpen(URL, contentType);
1057 if (ctxt == NULL) return(-1);
1058
1059 if (!strcmp(filename, "-"))
1060 fd = 0;
1061 else {
1062 fd = open(filename, O_CREAT | O_WRONLY, 00644);
1063 if (fd < 0) {
1064 xmlNanoHTTPClose(ctxt);
1065 if ((contentType != NULL) && (*contentType != NULL)) {
1066 xmlFree(*contentType);
1067 *contentType = NULL;
1068 }
1069 return(-1);
1070 }
1071 }
1072
1073 while ((len = xmlNanoHTTPRead(ctxt, buf, sizeof(buf))) > 0) {
1074 write(fd, buf, len);
1075 }
1076
1077 xmlNanoHTTPClose(ctxt);
1078 close(fd);
1079 return(0);
1080}
1081
1082/**
1083 * xmlNanoHTTPSave:
1084 * @ctxt: the HTTP context
1085 * @filename: the filename where the content should be saved
1086 *
1087 * This function saves the output of the HTTP transaction to a file
1088 * It closes and free the context at the end
1089 *
1090 * Returns -1 in case of failure, 0 incase of success.
1091 */
1092int
1093xmlNanoHTTPSave(void *ctxt, const char *filename) {
1094 char buf[4096];
1095 int fd;
1096 int len;
1097
1098 if (ctxt == NULL) return(-1);
1099
1100 if (!strcmp(filename, "-"))
1101 fd = 0;
1102 else {
1103 fd = open(filename, O_CREAT | O_WRONLY);
1104 if (fd < 0) {
1105 xmlNanoHTTPClose(ctxt);
1106 return(-1);
1107 }
1108 }
1109
1110 while ((len = xmlNanoHTTPRead(ctxt, buf, sizeof(buf))) > 0) {
1111 write(fd, buf, len);
1112 }
1113
1114 xmlNanoHTTPClose(ctxt);
1115 return(0);
1116}
1117
1118/**
1119 * xmlNanoHTTPReturnCode:
1120 * @ctx: the HTTP context
1121 *
1122 * Returns the HTTP return code for the request.
1123 */
1124int
1125xmlNanoHTTPReturnCode(void *ctx) {
1126 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1127
1128 if (ctxt == NULL) return(-1);
1129
1130 return(ctxt->returnValue);
1131}
1132
1133/**
1134 * xmlNanoHTTPAuthHeader:
1135 * @ctx: the HTTP context
1136 *
1137 * Returns the stashed value of the WWW-Authenticate or Proxy-Authenticate
1138 * header.
1139 */
1140const char *
1141xmlNanoHTTPAuthHeader(void *ctx) {
1142 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1143
1144 if (ctxt == NULL) return(NULL);
1145
1146 return(ctxt->authHeader);
1147}
1148
1149#ifdef STANDALONE
1150int main(int argc, char **argv) {
1151 char *contentType = NULL;
1152
1153 if (argv[1] != NULL) {
1154 if (argv[2] != NULL)
1155 xmlNanoHTTPFetch(argv[1], argv[2], &contentType);
1156 else
1157 xmlNanoHTTPFetch(argv[1], "-", &contentType);
1158 if (contentType != NULL) xmlFree(contentType);
1159 } else {
1160 xmlGenericError(xmlGenericErrorContext,
1161 "%s: minimal HTTP GET implementation\n", argv[0]);
1162 xmlGenericError(xmlGenericErrorContext,
1163 "\tusage %s [ URL [ filename ] ]\n", argv[0]);
1164 }
1165 xmlNanoHTTPCleanup();
1166 xmlMemoryDump();
1167 return(0);
1168}
1169#endif /* STANDALONE */
1170#else /* !LIBXML_HTTP_ENABLED */
1171#ifdef STANDALONE
1172#include <stdio.h>
1173int main(int argc, char **argv) {
1174 xmlGenericError(xmlGenericErrorContext,
1175 "%s : HTTP support not compiled in\n", argv[0]);
1176 return(0);
1177}
1178#endif /* STANDALONE */
1179#endif /* LIBXML_HTTP_ENABLED */