blob: 31ed07c811227fb809f2dcbd8c906911c1ed8b91 [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;
Daniel Veillard9403a042001-05-28 11:00:53 +0000817 return(xmlNanoHTTPMethod(URL, NULL, NULL, contentType, NULL));
818}
819
820/**
821 * xmlNanoHTTPOpenRedir:
822 * @URL: The URL to load
823 * @contentType: if available the Content-Type information will be
824 * returned at that location
825 * @redir: if availble the redirected URL will be returned
826 *
827 * This function try to open a connection to the indicated resource
828 * via HTTP GET.
829 *
830 * Returns NULL in case of failure, otherwise a request handler.
831 * The contentType, if provided must be freed by the caller
832 */
833
834void*
835xmlNanoHTTPOpenRedir(const char *URL, char **contentType, char **redir) {
836 if (contentType != NULL) *contentType = NULL;
837 if (redir != NULL) *redir = NULL;
838 return(xmlNanoHTTPMethodRedir(URL, NULL, NULL, contentType, redir, NULL));
Owen Taylor3473f882001-02-23 17:55:21 +0000839}
840
841/**
842 * xmlNanoHTTPRead:
843 * @ctx: the HTTP context
844 * @dest: a buffer
845 * @len: the buffer length
846 *
847 * This function tries to read @len bytes from the existing HTTP connection
848 * and saves them in @dest. This is a blocking call.
849 *
850 * Returns the number of byte read. 0 is an indication of an end of connection.
851 * -1 indicates a parameter error.
852 */
853int
854xmlNanoHTTPRead(void *ctx, void *dest, int len) {
855 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
856
857 if (ctx == NULL) return(-1);
858 if (dest == NULL) return(-1);
859 if (len <= 0) return(0);
860
861 while (ctxt->inptr - ctxt->inrptr < len) {
862 if (xmlNanoHTTPRecv(ctxt) == 0) break;
863 }
864 if (ctxt->inptr - ctxt->inrptr < len)
865 len = ctxt->inptr - ctxt->inrptr;
866 memcpy(dest, ctxt->inrptr, len);
867 ctxt->inrptr += len;
868 return(len);
869}
870
871/**
872 * xmlNanoHTTPClose:
873 * @ctx: the HTTP context
874 *
875 * This function closes an HTTP context, it ends up the connection and
876 * free all data related to it.
877 */
878void
879xmlNanoHTTPClose(void *ctx) {
880 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
881
882 if (ctx == NULL) return;
883
884 xmlNanoHTTPFreeCtxt(ctxt);
885}
886
887/**
Daniel Veillard9403a042001-05-28 11:00:53 +0000888 * xmlNanoHTTPMethodRedir:
Owen Taylor3473f882001-02-23 17:55:21 +0000889 * @URL: The URL to load
890 * @method: the HTTP method to use
891 * @input: the input string if any
892 * @contentType: the Content-Type information IN and OUT
Daniel Veillard9403a042001-05-28 11:00:53 +0000893 * @redir: the redirected URL OUT
Owen Taylor3473f882001-02-23 17:55:21 +0000894 * @headers: the extra headers
895 *
896 * This function try to open a connection to the indicated resource
897 * via HTTP using the given @method, adding the given extra headers
898 * and the input buffer for the request content.
899 *
900 * Returns NULL in case of failure, otherwise a request handler.
Daniel Veillard9403a042001-05-28 11:00:53 +0000901 * The contentType, or redir, if provided must be freed by the caller
Owen Taylor3473f882001-02-23 17:55:21 +0000902 */
903
904void*
Daniel Veillard9403a042001-05-28 11:00:53 +0000905xmlNanoHTTPMethodRedir(const char *URL, const char *method, const char *input,
906 char **contentType, char **redir, const char *headers) {
Owen Taylor3473f882001-02-23 17:55:21 +0000907 xmlNanoHTTPCtxtPtr ctxt;
908 char *bp, *p;
909 int blen, ilen, ret;
910 int head;
911 int nbRedirects = 0;
912 char *redirURL = NULL;
913
914 if (URL == NULL) return(NULL);
915 if (method == NULL) method = "GET";
916 xmlNanoHTTPInit();
917
918retry:
919 if (redirURL == NULL)
920 ctxt = xmlNanoHTTPNewCtxt(URL);
921 else {
922 ctxt = xmlNanoHTTPNewCtxt(redirURL);
Owen Taylor3473f882001-02-23 17:55:21 +0000923 }
924
925 if ((ctxt->protocol == NULL) || (strcmp(ctxt->protocol, "http"))) {
926 xmlNanoHTTPFreeCtxt(ctxt);
927 if (redirURL != NULL) xmlFree(redirURL);
928 return(NULL);
929 }
930 if (ctxt->hostname == NULL) {
931 xmlNanoHTTPFreeCtxt(ctxt);
Daniel Veillard9403a042001-05-28 11:00:53 +0000932 if (redirURL != NULL) xmlFree(redirURL);
Owen Taylor3473f882001-02-23 17:55:21 +0000933 return(NULL);
934 }
935 if (proxy) {
936 blen = strlen(ctxt->hostname) * 2 + 16;
937 ret = xmlNanoHTTPConnectHost(proxy, proxyPort);
938 }
939 else {
940 blen = strlen(ctxt->hostname);
941 ret = xmlNanoHTTPConnectHost(ctxt->hostname, ctxt->port);
942 }
943 if (ret < 0) {
944 xmlNanoHTTPFreeCtxt(ctxt);
Daniel Veillard9403a042001-05-28 11:00:53 +0000945 if (redirURL != NULL) xmlFree(redirURL);
Owen Taylor3473f882001-02-23 17:55:21 +0000946 return(NULL);
947 }
948 ctxt->fd = ret;
949
950 if (input != NULL) {
951 ilen = strlen(input);
952 blen += ilen + 32;
953 }
954 else
955 ilen = 0;
956 if (headers != NULL)
957 blen += strlen(headers);
958 if (contentType && *contentType)
959 blen += strlen(*contentType) + 16;
960 blen += strlen(method) + strlen(ctxt->path) + 23;
961 bp = xmlMalloc(blen);
962 if (proxy) {
963 if (ctxt->port != 80) {
964 sprintf(bp, "%s http://%s:%d%s", method, ctxt->hostname,
965 ctxt->port, ctxt->path);
966 }
967 else
968 sprintf(bp, "%s http://%s%s", method, ctxt->hostname, ctxt->path);
969 }
970 else
971 sprintf(bp, "%s %s", method, ctxt->path);
972 p = bp + strlen(bp);
973 sprintf(p, " HTTP/1.0\r\nHost: %s\r\n", ctxt->hostname);
974 p += strlen(p);
975 if (contentType != NULL && *contentType) {
976 sprintf(p, "Content-Type: %s\r\n", *contentType);
977 p += strlen(p);
978 }
979 if (headers != NULL) {
980 strcpy(p, headers);
981 p += strlen(p);
982 }
983 if (input != NULL)
984 sprintf(p, "Content-Length: %d\r\n\r\n%s", ilen, input);
985 else
986 strcpy(p, "\r\n");
987#ifdef DEBUG_HTTP
988 xmlGenericError(xmlGenericErrorContext,
989 "-> %s%s", proxy? "(Proxy) " : "", bp);
990 if ((blen -= strlen(bp)+1) < 0)
991 xmlGenericError(xmlGenericErrorContext,
992 "ERROR: overflowed buffer by %d bytes\n", -blen);
993#endif
994 ctxt->outptr = ctxt->out = bp;
995 ctxt->state = XML_NANO_HTTP_WRITE;
996 xmlNanoHTTPSend(ctxt);
997 ctxt->state = XML_NANO_HTTP_READ;
998 head = 1;
999
1000 while ((p = xmlNanoHTTPReadLine(ctxt)) != NULL) {
1001 if (head && (*p == 0)) {
1002 head = 0;
1003 ctxt->content = ctxt->inrptr;
1004 xmlFree(p);
1005 break;
1006 }
1007 xmlNanoHTTPScanAnswer(ctxt, p);
1008
1009#ifdef DEBUG_HTTP
1010 xmlGenericError(xmlGenericErrorContext, "<- %s\n", p);
1011#endif
1012 xmlFree(p);
1013 }
1014
1015 if ((ctxt->location != NULL) && (ctxt->returnValue >= 300) &&
1016 (ctxt->returnValue < 400)) {
1017#ifdef DEBUG_HTTP
1018 xmlGenericError(xmlGenericErrorContext,
1019 "\nRedirect to: %s\n", ctxt->location);
1020#endif
1021 while (xmlNanoHTTPRecv(ctxt)) ;
1022 if (nbRedirects < XML_NANO_HTTP_MAX_REDIR) {
1023 nbRedirects++;
Daniel Veillard9403a042001-05-28 11:00:53 +00001024 if (redirURL != NULL)
1025 xmlFree(redirURL);
Owen Taylor3473f882001-02-23 17:55:21 +00001026 redirURL = xmlMemStrdup(ctxt->location);
1027 xmlNanoHTTPFreeCtxt(ctxt);
1028 goto retry;
1029 }
1030 xmlNanoHTTPFreeCtxt(ctxt);
Daniel Veillard9403a042001-05-28 11:00:53 +00001031 if (redirURL != NULL) xmlFree(redirURL);
Owen Taylor3473f882001-02-23 17:55:21 +00001032#ifdef DEBUG_HTTP
1033 xmlGenericError(xmlGenericErrorContext,
1034 "Too many redirects, aborting ...\n");
1035#endif
1036 return(NULL);
1037
1038 }
1039
1040 if (contentType != NULL) {
1041 if (ctxt->contentType != NULL)
1042 *contentType = xmlMemStrdup(ctxt->contentType);
1043 else
1044 *contentType = NULL;
1045 }
1046
Daniel Veillard9403a042001-05-28 11:00:53 +00001047 if ((redir != NULL) && (redirURL != NULL)) {
1048 *redir = redirURL;
1049 } else {
1050 if (redirURL != NULL)
1051 xmlFree(redirURL);
1052 if (redir != NULL)
1053 *redir = NULL;
1054 }
1055
Owen Taylor3473f882001-02-23 17:55:21 +00001056#ifdef DEBUG_HTTP
1057 if (ctxt->contentType != NULL)
1058 xmlGenericError(xmlGenericErrorContext,
1059 "\nCode %d, content-type '%s'\n\n",
1060 ctxt->returnValue, ctxt->contentType);
1061 else
1062 xmlGenericError(xmlGenericErrorContext,
1063 "\nCode %d, no content-type\n\n",
1064 ctxt->returnValue);
1065#endif
1066
1067 return((void *) ctxt);
1068}
1069
1070/**
Daniel Veillard9403a042001-05-28 11:00:53 +00001071 * xmlNanoHTTPMethod:
1072 * @URL: The URL to load
1073 * @method: the HTTP method to use
1074 * @input: the input string if any
1075 * @contentType: the Content-Type information IN and OUT
1076 * @headers: the extra headers
1077 *
1078 * This function try to open a connection to the indicated resource
1079 * via HTTP using the given @method, adding the given extra headers
1080 * and the input buffer for the request content.
1081 *
1082 * Returns NULL in case of failure, otherwise a request handler.
1083 * The contentType, if provided must be freed by the caller
1084 */
1085
1086void*
1087xmlNanoHTTPMethod(const char *URL, const char *method, const char *input,
1088 char **contentType, const char *headers) {
1089 return(xmlNanoHTTPMethodRedir(URL, method, input, contentType,
1090 NULL, headers));
1091}
1092
1093/**
Owen Taylor3473f882001-02-23 17:55:21 +00001094 * xmlNanoHTTPFetch:
1095 * @URL: The URL to load
1096 * @filename: the filename where the content should be saved
1097 * @contentType: if available the Content-Type information will be
1098 * returned at that location
1099 *
1100 * This function try to fetch the indicated resource via HTTP GET
1101 * and save it's content in the file.
1102 *
1103 * Returns -1 in case of failure, 0 incase of success. The contentType,
1104 * if provided must be freed by the caller
1105 */
1106int
1107xmlNanoHTTPFetch(const char *URL, const char *filename, char **contentType) {
1108 void *ctxt;
1109 char buf[4096];
1110 int fd;
1111 int len;
1112
1113 ctxt = xmlNanoHTTPOpen(URL, contentType);
1114 if (ctxt == NULL) return(-1);
1115
1116 if (!strcmp(filename, "-"))
1117 fd = 0;
1118 else {
1119 fd = open(filename, O_CREAT | O_WRONLY, 00644);
1120 if (fd < 0) {
1121 xmlNanoHTTPClose(ctxt);
1122 if ((contentType != NULL) && (*contentType != NULL)) {
1123 xmlFree(*contentType);
1124 *contentType = NULL;
1125 }
1126 return(-1);
1127 }
1128 }
1129
1130 while ((len = xmlNanoHTTPRead(ctxt, buf, sizeof(buf))) > 0) {
1131 write(fd, buf, len);
1132 }
1133
1134 xmlNanoHTTPClose(ctxt);
1135 close(fd);
1136 return(0);
1137}
1138
1139/**
1140 * xmlNanoHTTPSave:
1141 * @ctxt: the HTTP context
1142 * @filename: the filename where the content should be saved
1143 *
1144 * This function saves the output of the HTTP transaction to a file
1145 * It closes and free the context at the end
1146 *
1147 * Returns -1 in case of failure, 0 incase of success.
1148 */
1149int
1150xmlNanoHTTPSave(void *ctxt, const char *filename) {
1151 char buf[4096];
1152 int fd;
1153 int len;
1154
1155 if (ctxt == NULL) return(-1);
1156
1157 if (!strcmp(filename, "-"))
1158 fd = 0;
1159 else {
1160 fd = open(filename, O_CREAT | O_WRONLY);
1161 if (fd < 0) {
1162 xmlNanoHTTPClose(ctxt);
1163 return(-1);
1164 }
1165 }
1166
1167 while ((len = xmlNanoHTTPRead(ctxt, buf, sizeof(buf))) > 0) {
1168 write(fd, buf, len);
1169 }
1170
1171 xmlNanoHTTPClose(ctxt);
1172 return(0);
1173}
1174
1175/**
1176 * xmlNanoHTTPReturnCode:
1177 * @ctx: the HTTP context
1178 *
1179 * Returns the HTTP return code for the request.
1180 */
1181int
1182xmlNanoHTTPReturnCode(void *ctx) {
1183 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1184
1185 if (ctxt == NULL) return(-1);
1186
1187 return(ctxt->returnValue);
1188}
1189
1190/**
1191 * xmlNanoHTTPAuthHeader:
1192 * @ctx: the HTTP context
1193 *
1194 * Returns the stashed value of the WWW-Authenticate or Proxy-Authenticate
1195 * header.
1196 */
1197const char *
1198xmlNanoHTTPAuthHeader(void *ctx) {
1199 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
1200
1201 if (ctxt == NULL) return(NULL);
1202
1203 return(ctxt->authHeader);
1204}
1205
1206#ifdef STANDALONE
1207int main(int argc, char **argv) {
1208 char *contentType = NULL;
1209
1210 if (argv[1] != NULL) {
1211 if (argv[2] != NULL)
1212 xmlNanoHTTPFetch(argv[1], argv[2], &contentType);
1213 else
1214 xmlNanoHTTPFetch(argv[1], "-", &contentType);
1215 if (contentType != NULL) xmlFree(contentType);
1216 } else {
1217 xmlGenericError(xmlGenericErrorContext,
1218 "%s: minimal HTTP GET implementation\n", argv[0]);
1219 xmlGenericError(xmlGenericErrorContext,
1220 "\tusage %s [ URL [ filename ] ]\n", argv[0]);
1221 }
1222 xmlNanoHTTPCleanup();
1223 xmlMemoryDump();
1224 return(0);
1225}
1226#endif /* STANDALONE */
1227#else /* !LIBXML_HTTP_ENABLED */
1228#ifdef STANDALONE
1229#include <stdio.h>
1230int main(int argc, char **argv) {
1231 xmlGenericError(xmlGenericErrorContext,
1232 "%s : HTTP support not compiled in\n", argv[0]);
1233 return(0);
1234}
1235#endif /* STANDALONE */
1236#endif /* LIBXML_HTTP_ENABLED */