blob: 26dcf3a6bf636823cd817157bef95279372433f8 [file] [log] [blame]
Daniel Veillard4ecf39f1999-09-22 12:14:03 +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
17#ifndef WIN32
18#include "config.h"
19#endif
20
21#include <stdio.h>
22#include <string.h>
23
24#ifdef HAVE_STDLIB_H
25#include <stdlib.h>
26#endif
27#ifdef HAVE_UNISTD_H
28#include <unistd.h>
29#endif
30#ifdef HAVE_SYS_SOCKET_H
31#include <sys/socket.h>
32#endif
33#ifdef HAVE_NETINET_IN_H
34#include <netinet/in.h>
35#endif
36#ifdef HAVE_ARPA_INET_H
37#include <arpa/inet.h>
38#endif
39#ifdef HAVE_NETDB_H
40#include <netdb.h>
41#endif
42#ifdef HAVE_FCNTL_H
43#include <fcntl.h>
44#endif
45#ifdef HAVE_ERRNO_H
46#include <errno.h>
47#endif
48#ifdef HAVE_SYS_TIME_H
49#include <sys/time.h>
50#endif
51#ifdef HAVE_SYS_SELECT_H
52#include <sys/select.h>
53#endif
54
55#include "xmlmemory.h"
56
57#ifdef STANDALONE
58#define DEBUG_HTTP
59#endif
60
61#define XML_NANO_HTTP_MAX_REDIR 10
62
63#define XML_NANO_HTTP_CHUNK 4096
64
65#define XML_NANO_HTTP_CLOSED 0
66#define XML_NANO_HTTP_WRITE 1
67#define XML_NANO_HTTP_READ 2
68#define XML_NANO_HTTP_NONE 4
69
70typedef struct xmlNanoHTTPCtxt {
71 char *protocol; /* the protocol name */
72 char *hostname; /* the host name */
73 int port; /* the port */
74 char *path; /* the path within the URL */
75 int fd; /* the file descriptor for the socket */
76 int state; /* WRITE / READ / CLOSED */
77 char *out; /* buffer sent (zero terminated) */
78 char *outptr; /* index within the buffer sent */
79 char *in; /* the receiving buffer */
80 char *content; /* the start of the content */
81 char *inptr; /* the next byte to read from network */
82 char *inrptr; /* the next byte to give back to the client */
83 int inlen; /* len of the input buffer */
84 int last; /* return code for last operation */
85 int returnValue; /* the protocol return value */
86 char *contentType; /* the MIME type for the input */
87 char *location; /* the new URL in case of redirect */
88} xmlNanoHTTPCtxt, *xmlNanoHTTPCtxtPtr;
89
90/**
91 * xmlNanoHTTPScanURL:
92 * @ctxt: an HTTP context
93 * @URL: The URL used to initialize the context
94 *
95 * (Re)Initialize an HTTP context by parsing the URL and finding
96 * the protocol host port and path it indicates.
97 */
98
99static void
100xmlNanoHTTPScanURL(xmlNanoHTTPCtxtPtr ctxt, const char *URL) {
101 const char *cur = URL;
102 char buf[4096];
103 int index = 0;
104 int port = 0;
105
106 if (ctxt->protocol != NULL) {
107 xmlFree(ctxt->protocol);
108 ctxt->protocol = NULL;
109 }
110 if (ctxt->hostname != NULL) {
111 xmlFree(ctxt->hostname);
112 ctxt->hostname = NULL;
113 }
114 if (ctxt->path != NULL) {
115 xmlFree(ctxt->path);
116 ctxt->path = NULL;
117 }
118 buf[index] = 0;
119 while (*cur != 0) {
120 if ((cur[0] == ':') && (cur[1] == '/') && (cur[2] == '/')) {
121 buf[index] = 0;
122 ctxt->protocol = xmlMemStrdup(buf);
123 index = 0;
124 cur += 3;
125 break;
126 }
127 buf[index++] = *cur++;
128 }
129 if (*cur == 0) return;
130
131 buf[index] = 0;
132 while (1) {
133 if (cur[0] == ':') {
134 buf[index] = 0;
135 ctxt->hostname = xmlMemStrdup(buf);
136 index = 0;
137 cur += 1;
138 while ((*cur >= '0') && (*cur <= '9')) {
139 port *= 10;
140 port += *cur - '0';
141 cur++;
142 }
143 if (port != 0) ctxt->port = port;
144 while ((cur[0] != '/') && (*cur != 0))
145 cur++;
146 break;
147 }
148 if ((*cur == '/') || (*cur == 0)) {
149 buf[index] = 0;
150 ctxt->hostname = xmlMemStrdup(buf);
151 index = 0;
152 break;
153 }
154 buf[index++] = *cur++;
155 }
156 if (*cur == 0)
157 ctxt->path = xmlMemStrdup("/");
158 else {
159 buf[index] = 0;
160 while (*cur != 0) {
161 if ((cur[0] == '#') || (cur[0] == '?'))
162 break;
163 buf[index++] = *cur++;
164 }
165 buf[index] = 0;
166 ctxt->path = xmlMemStrdup(buf);
167 }
168}
169
170/**
171 * xmlNanoHTTPNewCtxt:
172 * @URL: The URL used to initialize the context
173 *
174 * Allocate and initialize a new HTTP context.
175 *
176 * Returns an HTTP context or NULL in case of error.
177 */
178
179static xmlNanoHTTPCtxtPtr
180xmlNanoHTTPNewCtxt(const char *URL) {
181 xmlNanoHTTPCtxtPtr ret;
182
183 ret = (xmlNanoHTTPCtxtPtr) xmlMalloc(sizeof(xmlNanoHTTPCtxt));
184 if (ret == NULL) return(NULL);
185
186 memset(ret, 0, sizeof(xmlNanoHTTPCtxt));
187 ret->port = 80;
188 ret->returnValue = 0;
189
190 xmlNanoHTTPScanURL(ret, URL);
191
192 return(ret);
193}
194
195/**
196 * xmlNanoHTTPFreeCtxt:
197 * @ctxt: an HTTP context
198 *
199 * Frees the context after closing the connection.
200 */
201
202static void
203xmlNanoHTTPFreeCtxt(xmlNanoHTTPCtxtPtr ctxt) {
204 if (ctxt == NULL) return;
205 if (ctxt->hostname != NULL) xmlFree(ctxt->hostname);
206 if (ctxt->protocol != NULL) xmlFree(ctxt->protocol);
207 if (ctxt->path != NULL) xmlFree(ctxt->path);
208 if (ctxt->out != NULL) xmlFree(ctxt->out);
209 if (ctxt->in != NULL) xmlFree(ctxt->in);
210 if (ctxt->contentType != NULL) xmlFree(ctxt->contentType);
211 if (ctxt->location != NULL) xmlFree(ctxt->location);
212 ctxt->state = XML_NANO_HTTP_NONE;
213 if (ctxt->fd >= 0) close(ctxt->fd);
214 ctxt->fd = -1;
215 xmlFree(ctxt);
216}
217
218/**
219 * xmlNanoHTTPSend:
220 * @ctxt: an HTTP context
221 *
222 * Send the input needed to initiate the processing on the server side
223 */
224
225static void
226xmlNanoHTTPSend(xmlNanoHTTPCtxtPtr ctxt) {
227 if (ctxt->state & XML_NANO_HTTP_WRITE)
228 ctxt->last = write(ctxt->fd, ctxt->outptr, strlen(ctxt->outptr));
229}
230
231/**
232 * xmlNanoHTTPRecv:
233 * @ctxt: an HTTP context
234 *
235 * Read information coming from the HTTP connection.
236 * This is a blocking call (but it blocks in select(), not read()).
237 *
238 * Returns the number of byte read or -1 in case of error.
239 */
240
241static int
242xmlNanoHTTPRecv(xmlNanoHTTPCtxtPtr ctxt) {
243 fd_set rfd;
244 struct timeval tv;
245
246
247 while (ctxt->state & XML_NANO_HTTP_READ) {
248 if (ctxt->in == NULL) {
249 ctxt->in = (char *) xmlMalloc(65000 * sizeof(char));
250 if (ctxt->in == NULL) {
251 ctxt->last = -1;
252 return(-1);
253 }
254 ctxt->inlen = 65000;
255 ctxt->inptr = ctxt->content = ctxt->inrptr = ctxt->in;
256 }
257 if (ctxt->inrptr > ctxt->in + XML_NANO_HTTP_CHUNK) {
258 int delta = ctxt->inrptr - ctxt->in;
259 int len = ctxt->inptr - ctxt->inrptr;
260
261 memmove(ctxt->in, ctxt->inrptr, len);
262 ctxt->inrptr -= delta;
263 ctxt->content -= delta;
264 ctxt->inptr -= delta;
265 }
266 if ((ctxt->in + ctxt->inlen) < (ctxt->inptr + XML_NANO_HTTP_CHUNK)) {
267 int d_inptr = ctxt->inptr - ctxt->in;
268 int d_content = ctxt->content - ctxt->in;
269 int d_inrptr = ctxt->inrptr - ctxt->in;
270
271 ctxt->inlen *= 2;
272 ctxt->in = (char *) xmlRealloc(ctxt->in, ctxt->inlen);
273 if (ctxt->in == NULL) {
274 ctxt->last = -1;
275 return(-1);
276 }
277 ctxt->inptr = ctxt->in + d_inptr;
278 ctxt->content = ctxt->in + d_content;
279 ctxt->inrptr = ctxt->in + d_inrptr;
280 }
281 ctxt->last = read(ctxt->fd, ctxt->inptr, XML_NANO_HTTP_CHUNK);
282 if (ctxt->last > 0) {
283 ctxt->inptr += ctxt->last;
284 return(ctxt->last);
285 }
286 if (ctxt->last == 0) {
287 return(0);
288 }
289#ifdef EWOULDBLOCK
290 if ((ctxt->last == -1) && (errno != EWOULDBLOCK)) {
291 return(0);
292 }
293#endif
294 tv.tv_sec=10;
295 tv.tv_usec=0;
296 FD_ZERO(&rfd);
297 FD_SET(ctxt->fd, &rfd);
298
299 if(select(ctxt->fd+1, &rfd, NULL, NULL, &tv)<1)
300 return(0);
301 }
302 return(0);
303}
304
305/**
306 * xmlNanoHTTPReadLine:
307 * @ctxt: an HTTP context
308 *
309 * Read one line in the HTTP server output, usually for extracting
310 * the HTTP protocol informations from the answer header.
311 *
312 * Returns a newly allocated string with a copy of the line, or NULL
313 * which indicate the end of the input.
314 */
315
316static char *
317xmlNanoHTTPReadLine(xmlNanoHTTPCtxtPtr ctxt) {
318 char buf[4096];
319 char *bp=buf;
320
321 while(bp - buf < 4095) {
322 if(ctxt->inrptr == ctxt->inptr) {
323 if (xmlNanoHTTPRecv(ctxt) == 0) {
324 if (bp == buf)
325 return(NULL);
326 else
327 *bp = 0;
328 return(xmlMemStrdup(buf));
329 }
330 }
331 *bp = *ctxt->inrptr++;
332 if(*bp == '\n') {
333 *bp = 0;
334 return(xmlMemStrdup(buf));
335 }
336 if(*bp != '\r')
337 bp++;
338 }
339 buf[4095] = 0;
340 return(xmlMemStrdup(buf));
341}
342
343
344/**
345 * xmlNanoHTTPScanAnswer:
346 * @ctxt: an HTTP context
347 * @line: an HTTP header line
348 *
349 * Try to extract useful informations from the server answer.
350 * We currently parse and process:
351 * - The HTTP revision/ return code
352 * - The Content-Type
353 * - The Location for redirrect processing.
354 *
355 * Returns -1 in case of failure, the file descriptor number otherwise
356 */
357
358static void
359xmlNanoHTTPScanAnswer(xmlNanoHTTPCtxtPtr ctxt, const char *line) {
360 const char *cur = line;
361
362 if (line == NULL) return;
363
364 if (!strncmp(line, "HTTP/", 5)) {
365 int version = 0;
366 int ret = 0;
367
368 cur += 5;
369 while ((*cur >= '0') && (*cur <= '9')) {
370 version *= 10;
371 version += *cur - '0';
372 cur++;
373 }
374 if (*cur == '.') {
375 cur++;
376 if ((*cur >= '0') && (*cur <= '9')) {
377 version *= 10;
378 version += *cur - '0';
379 cur++;
380 }
381 while ((*cur >= '0') && (*cur <= '9'))
382 cur++;
383 } else
384 version *= 10;
385 if ((*cur != ' ') && (*cur != '\t')) return;
386 while ((*cur == ' ') || (*cur == '\t')) cur++;
387 if ((*cur < '0') || (*cur > '9')) return;
388 while ((*cur >= '0') && (*cur <= '9')) {
389 ret *= 10;
390 ret += *cur - '0';
391 cur++;
392 }
393 if ((*cur != 0) && (*cur != ' ') && (*cur != '\t')) return;
394 ctxt->returnValue = ret;
395 } else if (!strncmp(line, "Content-Type:", 13)) {
396 cur += 13;
397 while ((*cur == ' ') || (*cur == '\t')) cur++;
398 if (ctxt->contentType != NULL)
399 xmlFree(ctxt->contentType);
400 ctxt->contentType = xmlMemStrdup(cur);
401 } else if (!strncmp(line, "ContentType:", 12)) {
402 cur += 12;
403 if (ctxt->contentType != NULL) return;
404 while ((*cur == ' ') || (*cur == '\t')) cur++;
405 ctxt->contentType = xmlMemStrdup(cur);
406 } else if (!strncmp(line, "content-type:", 13)) {
407 cur += 13;
408 if (ctxt->contentType != NULL) return;
409 while ((*cur == ' ') || (*cur == '\t')) cur++;
410 ctxt->contentType = xmlMemStrdup(cur);
411 } else if (!strncmp(line, "contenttype:", 12)) {
412 cur += 12;
413 if (ctxt->contentType != NULL) return;
414 while ((*cur == ' ') || (*cur == '\t')) cur++;
415 ctxt->contentType = xmlMemStrdup(cur);
416 } else if (!strncmp(line, "Location:", 9)) {
417 cur += 9;
418 while ((*cur == ' ') || (*cur == '\t')) cur++;
419 if (ctxt->location != NULL)
420 xmlFree(ctxt->location);
421 ctxt->location = xmlMemStrdup(cur);
422 } else if (!strncmp(line, "location:", 9)) {
423 cur += 9;
424 if (ctxt->location != NULL) return;
425 while ((*cur == ' ') || (*cur == '\t')) cur++;
426 ctxt->location = xmlMemStrdup(cur);
427 }
428}
429
430/**
431 * xmlNanoHTTPConnectAttempt:
432 * @ia: an internet adress structure
433 * @port: the port number
434 *
435 * Attempt a connection to the given IP:port endpoint. It forces
436 * non-blocking semantic on the socket, and allow 60 seconds for
437 * the host to answer.
438 *
439 * Returns -1 in case of failure, the file descriptor number otherwise
440 */
441
442static int
443xmlNanoHTTPConnectAttempt(struct in_addr ia, int port)
444{
445 int s=socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
446 struct sockaddr_in sin;
447 fd_set wfd;
448 struct timeval tv;
449 int status;
450
451 if(s==-1) {
452#ifdef DEBUG_HTTP
453 perror("socket");
454#endif
455 return(-1);
456 }
457
458#ifdef _WINSOCKAPI_
459 {
460 long levents = FD_READ | FD_WRITE | FD_ACCEPT |
461 FD_CONNECT | FD_CLOSE ;
462 int rv = 0 ;
463 u_long one = 1;
464
465 status = ioctlsocket(s, FIONBIO, &one) == SOCKET_ERROR ? -1 : 0;
466 }
467#else /* _WINSOCKAPI_ */
468#if defined(VMS)
469 {
470 int enable = 1;
471 status = IOCTL(s, FIONBIO, &enable);
472 }
473#else /* VMS */
474 if((status = fcntl(s, F_GETFL, 0)) != -1) {
475#ifdef O_NONBLOCK
476 status |= O_NONBLOCK;
477#else /* O_NONBLOCK */
478#ifdef F_NDELAY
479 status |= F_NDELAY;
480#endif /* F_NDELAY */
481#endif /* !O_NONBLOCK */
482 status = fcntl(s, F_SETFL, status);
483 }
484 if(status < 0) {
485#ifdef DEBUG_HTTP
486 perror("nonblocking");
487#endif
488 close(s);
489 return(-1);
490 }
491#endif /* !VMS */
492#endif /* !_WINSOCKAPI_ */
493
494
495 sin.sin_family = AF_INET;
496 sin.sin_addr = ia;
497 sin.sin_port = htons(port);
498
499 if((connect(s, (struct sockaddr *)&sin, sizeof(sin))==-1) &&
500 (errno != EINPROGRESS)) {
501 perror("connect");
502 close(s);
503 return(-1);
504 }
505
506 tv.tv_sec = 60; /* We use 60 second timeouts for now */
507 tv.tv_usec = 0;
508
509 FD_ZERO(&wfd);
510 FD_SET(s, &wfd);
511
512 switch(select(s+1, NULL, &wfd, NULL, &tv))
513 {
514 case 0:
515 /* Time out */
516 close(s);
517 return(-1);
518 case -1:
519 /* Ermm.. ?? */
520#ifdef DEBUG_HTTP
521 perror("select");
522#endif
523 close(s);
524 return(-1);
525 }
526
527 return(s);
528}
529
530/**
531 * xmlNanoHTTPConnectHost:
532 * @host: the host name
533 * @port: the port number
534 *
535 * Attempt a connection to the given host:port endpoint. It tries
536 * the multiple IP provided by the DNS if available.
537 *
538 * Returns -1 in case of failure, the file descriptor number otherwise
539 */
540
541static int
542xmlNanoHTTPConnectHost(const char *host, int port)
543{
544 struct hostent *h;
545 int i;
546 int s;
547
548 h=gethostbyname(host);
549 if(h==NULL)
550 {
551#ifdef DEBUG_HTTP
552 fprintf(stderr,"unable to resolve '%s'.\n", host);
553#endif
554 return(-1);
555 }
556
557 for(i=0; h->h_addr_list[i]; i++)
558 {
559 struct in_addr ia;
560 memcpy(&ia, h->h_addr_list[i],4);
561 s = xmlNanoHTTPConnectAttempt(ia, port);
562 if(s != -1)
563 return(s);
564 }
565
566#ifdef DEBUG_HTTP
567 fprintf(stderr, "unable to connect to '%s'.\n", host);
568#endif
569 return(-1);
570}
571
572
573/**
574 * xmlNanoHTTPOpen:
575 * @URL: The URL to load
576 * @contentType: if available the Content-Type information will be
577 * returned at that location
578 *
579 * This function try to open a connection to the indicated resource
580 * via HTTP GET.
581 *
582 * Returns NULL in case of failure, otherwise a request handler.
583 * The contentType, if provided must be freed by the caller
584 */
585
586void *
587xmlNanoHTTPOpen(const char *URL, char **contentType) {
588 xmlNanoHTTPCtxtPtr ctxt;
589 char buf[4096];
590 int ret;
591 char *p;
592 int head;
593 int nbRedirects = 0;
594 char *redirURL = NULL;
595
596 if (contentType != NULL) *contentType = NULL;
597
598retry:
599 if (redirURL == NULL)
600 ctxt = xmlNanoHTTPNewCtxt(URL);
601 else {
602 ctxt = xmlNanoHTTPNewCtxt(redirURL);
603 xmlFree(redirURL);
604 redirURL = NULL;
605 }
606
607 if ((ctxt->protocol == NULL) || (strcmp(ctxt->protocol, "http"))) {
608 xmlNanoHTTPFreeCtxt(ctxt);
609 if (redirURL != NULL) xmlFree(redirURL);
610 return(NULL);
611 }
612 if (ctxt->hostname == NULL) {
613 xmlNanoHTTPFreeCtxt(ctxt);
614 return(NULL);
615 }
616 ret = xmlNanoHTTPConnectHost(ctxt->hostname, ctxt->port);
617 if (ret < 0) {
618 xmlNanoHTTPFreeCtxt(ctxt);
619 return(NULL);
620 }
621 ctxt->fd = ret;
622 snprintf(buf, sizeof(buf),"GET %s HTTP/1.0\r\nHost: %s\r\n\r\n",
623 ctxt->path, ctxt->hostname);
624#ifdef DEBUG_HTTP
625 printf("-> GET %s HTTP/1.0\n-> Host: %s\n\n",
626 ctxt->path, ctxt->hostname);
627#endif
628 ctxt->outptr = ctxt->out = xmlMemStrdup(buf);
629 ctxt->state = XML_NANO_HTTP_WRITE;
630 xmlNanoHTTPSend(ctxt);
631 ctxt->state = XML_NANO_HTTP_READ;
632 head = 1;
633
634 while ((p = xmlNanoHTTPReadLine(ctxt)) != NULL) {
635 if (head && (*p == 0)) {
636 head = 0;
637 ctxt->content = ctxt->inrptr;
638 break;
639 }
640 xmlNanoHTTPScanAnswer(ctxt, p);
641
642#ifdef DEBUG_HTTP
643 if (p != NULL) printf("<- %s\n", p);
644#endif
645 if (p != NULL) xmlFree(p);
646 }
647
648 if ((ctxt->location != NULL) && (ctxt->returnValue >= 300) &&
649 (ctxt->returnValue < 400)) {
650#ifdef DEBUG_HTTP
651 printf("\nRedirect to: %s\n", ctxt->location);
652#endif
653 while (xmlNanoHTTPRecv(ctxt)) ;
654 if (nbRedirects < XML_NANO_HTTP_MAX_REDIR) {
655 nbRedirects++;
656 redirURL = xmlMemStrdup(ctxt->location);
657 xmlNanoHTTPFreeCtxt(ctxt);
658 goto retry;
659 }
660 xmlNanoHTTPFreeCtxt(ctxt);
661#ifdef DEBUG_HTTP
662 printf("Too many redirrects, aborting ...\n");
663#endif
664 return(NULL);
665
666 }
667
668 if ((contentType != NULL) && (ctxt->contentType != NULL))
669 *contentType = xmlMemStrdup(ctxt->contentType);
670
671#ifdef DEBUG_HTTP
672 if (ctxt->contentType != NULL)
673 printf("\nCode %d, content-type '%s'\n\n",
674 ctxt->returnValue, ctxt->contentType);
675 else
676 printf("\nCode %d, no content-type\n\n",
677 ctxt->returnValue);
678#endif
679
680 return((void *) ctxt);
681}
682
683/**
684 * xmlNanoHTTPRead:
685 * @ctx: the HTTP context
686 * @dest: a buffer
687 * @len: the buffer length
688 *
689 * This function tries to read @len bytes from the existing HTTP connection
690 * and saves them in @dest. This is a blocking call.
691 *
692 * Returns the number of byte read. 0 is an indication of an end of connection.
693 * -1 indicates a parameter error.
694 */
695int
696xmlNanoHTTPRead(void *ctx, void *dest, int len) {
697 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
698
699 if (ctx == NULL) return(-1);
700 if (dest == NULL) return(-1);
701 if (len <= 0) return(0);
702
703 while (ctxt->inptr - ctxt->inrptr < len) {
704 if (xmlNanoHTTPRecv(ctxt) == 0) break;
705 }
706 if (ctxt->inptr - ctxt->inrptr < len)
707 len = ctxt->inptr - ctxt->inrptr;
708 memcpy(dest, ctxt->inrptr, len);
709 ctxt->inrptr += len;
710 return(len);
711}
712
713/**
714 * xmlNanoHTTPClose:
715 * @ctx: the HTTP context
716 *
717 * This function closes an HTTP context, it ends up the connection and
718 * free all data related to it.
719 */
720void
721xmlNanoHTTPClose(void *ctx) {
722 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
723
724 if (ctx == NULL) return;
725
726 xmlNanoHTTPFreeCtxt(ctxt);
727}
728
729/**
730 * xmlNanoHTTPMethod:
731 * @URL: The URL to load
732 * @method: the HTTP method to use
733 * @input: the input string if any
734 * @contentType: the Content-Type information IN and OUT
735 * @headers: the extra headers
736 *
737 * This function try to open a connection to the indicated resource
738 * via HTTP using the given @method, adding the given extra headers
739 * and the input buffer for the request content.
740 *
741 * Returns NULL in case of failure, otherwise a request handler.
742 * The contentType, if provided must be freed by the caller
743 */
744
745#ifndef DEBUG_HTTP
746#define DEBUG_HTTP
747#endif
748void *
749xmlNanoHTTPMethod(const char *URL, const char *method, const char *input,
750 char **contentType, const char *headers) {
751 xmlNanoHTTPCtxtPtr ctxt;
752 char buf[20000];
753 int ret;
754 char *p;
755 int head;
756 int nbRedirects = 0;
757 char *redirURL = NULL;
758
759 if (URL == NULL) return(NULL);
760 if (method == NULL) method = "GET";
761 if (contentType != NULL) *contentType = NULL;
762
763retry:
764 if (redirURL == NULL)
765 ctxt = xmlNanoHTTPNewCtxt(URL);
766 else {
767 ctxt = xmlNanoHTTPNewCtxt(redirURL);
768 xmlFree(redirURL);
769 redirURL = NULL;
770 }
771
772 if ((ctxt->protocol == NULL) || (strcmp(ctxt->protocol, "http"))) {
773 xmlNanoHTTPFreeCtxt(ctxt);
774 if (redirURL != NULL) xmlFree(redirURL);
775 return(NULL);
776 }
777 if (ctxt->hostname == NULL) {
778 xmlNanoHTTPFreeCtxt(ctxt);
779 return(NULL);
780 }
781 ret = xmlNanoHTTPConnectHost(ctxt->hostname, ctxt->port);
782 if (ret < 0) {
783 xmlNanoHTTPFreeCtxt(ctxt);
784 return(NULL);
785 }
786 ctxt->fd = ret;
787
788 if (input == NULL) {
789 if (headers == NULL) {
790 if ((contentType == NULL) || (*contentType == NULL)) {
791 snprintf(buf, sizeof(buf),
792 "%s %s HTTP/1.0\r\nHost: %s\r\n\r\n",
793 method, ctxt->path, ctxt->hostname);
794 } else {
795 snprintf(buf, sizeof(buf),
796 "%s %s HTTP/1.0\r\nHost: %s\r\nContent-Type: %s\r\n\r\n",
797 method, ctxt->path, ctxt->hostname, *contentType);
798 }
799 } else {
800 if ((contentType == NULL) || (*contentType == NULL)) {
801 snprintf(buf, sizeof(buf),
802 "%s %s HTTP/1.0\r\nHost: %s\r\n%s\r\n",
803 method, ctxt->path, ctxt->hostname, headers);
804 } else {
805 snprintf(buf, sizeof(buf),
806 "%s %s HTTP/1.0\r\nHost: %s\r\nContent-Type: %s\r\n%s\r\n",
807 method, ctxt->path, ctxt->hostname, *contentType,
808 headers);
809 }
810 }
811 } else {
812 int len = strlen(input);
813 if (headers == NULL) {
814 if ((contentType == NULL) || (*contentType == NULL)) {
815 snprintf(buf, sizeof(buf),
816 "%s %s HTTP/1.0\r\nHost: %s\r\nContent-Length: %d\r\n\r\n%s",
817 method, ctxt->path, ctxt->hostname, len, input);
818 } else {
819 snprintf(buf, sizeof(buf),
820"%s %s HTTP/1.0\r\nHost: %s\r\nContent-Type: %s\r\nContent-Length: %d\r\n\r\n%s",
821 method, ctxt->path, ctxt->hostname, *contentType, len,
822 input);
823 }
824 } else {
825 if ((contentType == NULL) || (*contentType == NULL)) {
826 snprintf(buf, sizeof(buf),
827 "%s %s HTTP/1.0\r\nHost: %s\r\nContent-Length: %d\r\n%s\r\n%s",
828 method, ctxt->path, ctxt->hostname, len,
829 headers, input);
830 } else {
831 snprintf(buf, sizeof(buf),
832"%s %s HTTP/1.0\r\nHost: %s\r\nContent-Type: %s\r\nContent-Length: %d\r\n%s\r\n%s",
833 method, ctxt->path, ctxt->hostname, *contentType,
834 len, headers, input);
835 }
836 }
837 }
838#ifdef DEBUG_HTTP
839 printf("-> %s", buf);
840#endif
841 ctxt->outptr = ctxt->out = xmlMemStrdup(buf);
842 ctxt->state = XML_NANO_HTTP_WRITE;
843 xmlNanoHTTPSend(ctxt);
844 ctxt->state = XML_NANO_HTTP_READ;
845 head = 1;
846
847 while ((p = xmlNanoHTTPReadLine(ctxt)) != NULL) {
848 if (head && (*p == 0)) {
849 head = 0;
850 ctxt->content = ctxt->inrptr;
851 if (p != NULL) xmlFree(p);
852 break;
853 }
854 xmlNanoHTTPScanAnswer(ctxt, p);
855
856#ifdef DEBUG_HTTP
857 if (p != NULL) printf("<- %s\n", p);
858#endif
859 if (p != NULL) xmlFree(p);
860 }
861
862 if ((ctxt->location != NULL) && (ctxt->returnValue >= 300) &&
863 (ctxt->returnValue < 400)) {
864#ifdef DEBUG_HTTP
865 printf("\nRedirect to: %s\n", ctxt->location);
866#endif
867 while (xmlNanoHTTPRecv(ctxt)) ;
868 if (nbRedirects < XML_NANO_HTTP_MAX_REDIR) {
869 nbRedirects++;
870 redirURL = xmlMemStrdup(ctxt->location);
871 xmlNanoHTTPFreeCtxt(ctxt);
872 goto retry;
873 }
874 xmlNanoHTTPFreeCtxt(ctxt);
875#ifdef DEBUG_HTTP
876 printf("Too many redirrects, aborting ...\n");
877#endif
878 return(NULL);
879
880 }
881
882 if ((contentType != NULL) && (ctxt->contentType != NULL))
883 *contentType = xmlMemStrdup(ctxt->contentType);
884 else if (contentType != NULL)
885 *contentType = NULL;
886
887#ifdef DEBUG_HTTP
888 if (ctxt->contentType != NULL)
889 printf("\nCode %d, content-type '%s'\n\n",
890 ctxt->returnValue, ctxt->contentType);
891 else
892 printf("\nCode %d, no content-type\n\n",
893 ctxt->returnValue);
894#endif
895
896 return((void *) ctxt);
897}
898
899/**
900 * xmlNanoHTTPFetch:
901 * @URL: The URL to load
902 * @filename: the filename where the content should be saved
903 * @contentType: if available the Content-Type information will be
904 * returned at that location
905 *
906 * This function try to fetch the indicated resource via HTTP GET
907 * and save it's content in the file.
908 *
909 * Returns -1 in case of failure, 0 incase of success. The contentType,
910 * if provided must be freed by the caller
911 */
912int
913xmlNanoHTTPFetch(const char *URL, const char *filename, char **contentType) {
914 void *ctxt;
915 char buf[4096];
916 int fd;
917 int len;
918
919 ctxt = xmlNanoHTTPOpen(URL, contentType);
920 if (ctxt == NULL) return(-1);
921
922 if (!strcmp(filename, "-"))
923 fd = 0;
924 else {
925 fd = open(filename, O_CREAT | O_WRONLY);
926 if (fd < 0) {
927 xmlNanoHTTPClose(ctxt);
928 if ((contentType != NULL) && (*contentType != NULL)) {
929 xmlFree(*contentType);
930 *contentType = NULL;
931 }
932 return(-1);
933 }
934 }
935
936 while ((len = xmlNanoHTTPRead(ctxt, buf, sizeof(buf))) > 0) {
937 write(fd, buf, len);
938 }
939
940 xmlNanoHTTPClose(ctxt);
941 return(0);
942}
943
944/**
945 * xmlNanoHTTPSave:
946 * @ctx: the HTTP context
947 * @filename: the filename where the content should be saved
948 *
949 * This function saves the output of the HTTP transaction to a file
950 * It closes and free the context at the end
951 *
952 * Returns -1 in case of failure, 0 incase of success.
953 */
954int
955xmlNanoHTTPSave(void *ctxt, const char *filename) {
956 char buf[4096];
957 int fd;
958 int len;
959
960 if (ctxt == NULL) return(-1);
961
962 if (!strcmp(filename, "-"))
963 fd = 0;
964 else {
965 fd = open(filename, O_CREAT | O_WRONLY);
966 if (fd < 0) {
967 xmlNanoHTTPClose(ctxt);
968 return(-1);
969 }
970 }
971
972 while ((len = xmlNanoHTTPRead(ctxt, buf, sizeof(buf))) > 0) {
973 write(fd, buf, len);
974 }
975
976 xmlNanoHTTPClose(ctxt);
977 return(0);
978}
979
980/**
981 * xmlNanoHTTPReturnCode:
982 * @ctx: the HTTP context
983 *
984 * Returns the HTTP return code for the request.
985 */
986int
987xmlNanoHTTPReturnCode(void *ctx) {
988 xmlNanoHTTPCtxtPtr ctxt = (xmlNanoHTTPCtxtPtr) ctx;
989
990 if (ctxt == NULL) return(-1);
991
992 return(ctxt->returnValue);
993}
994
995#ifdef STANDALONE
996int main(int argc, char **argv) {
997 char *contentType = NULL;
998
999 if (argv[1] != NULL) {
1000 if (argv[2] != NULL)
1001 xmlNanoHTTPFetch(argv[1], argv[2], &contentType);
1002 else
1003 xmlNanoHTTPFetch(argv[1], "-", &contentType);
1004 if (contentType != NULL) xmlFree(contentType);
1005 } else {
1006 printf("%s: minimal HTTP GET implementation\n", argv[0]);
1007 printf("\tusage %s [ URL [ filename ] ]\n", argv[0]);
1008 }
1009 return(0);
1010}
1011#endif /* STANDALONE */