]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/http.c
db97bc785d5e4705a9184880d1f7ba6b9eb03272
[thirdparty/cups.git] / cups / http.c
1 /*
2 * "$Id: http.c,v 1.96 2002/04/09 19:27:06 mike Exp $"
3 *
4 * HTTP routines for the Common UNIX Printing System (CUPS) scheduler.
5 *
6 * Copyright 1997-2002 by Easy Software Products, all rights reserved.
7 *
8 * These coded instructions, statements, and computer programs are the
9 * property of Easy Software Products and are protected by Federal
10 * copyright law. Distribution and use rights are outlined in the file
11 * "LICENSE.txt" which should have been included with this file. If this
12 * file is missing or damaged please contact Easy Software Products
13 * at:
14 *
15 * Attn: CUPS Licensing Information
16 * Easy Software Products
17 * 44141 Airport View Drive, Suite 204
18 * Hollywood, Maryland 20636-3111 USA
19 *
20 * Voice: (301) 373-9603
21 * EMail: cups-info@cups.org
22 * WWW: http://www.cups.org
23 *
24 * This file is subject to the Apple OS-Developed Software exception.
25 *
26 * Contents:
27 *
28 * httpInitialize() - Initialize the HTTP interface library and set the
29 * default HTTP proxy (if any).
30 * httpCheck() - Check to see if there is a pending response from
31 * the server.
32 * httpClose() - Close an HTTP connection...
33 * httpConnect() - Connect to a HTTP server.
34 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
35 * httpEncryption() - Set the required encryption on the link.
36 * httpReconnect() - Reconnect to a HTTP server...
37 * httpGetHostByName() - Lookup a hostname or IP address, and return
38 * address records for the specified name.
39 * httpSeparate() - Separate a Universal Resource Identifier into its
40 * components.
41 * httpGetSubField() - Get a sub-field value.
42 * httpSetField() - Set the value of an HTTP header.
43 * httpDelete() - Send a DELETE request to the server.
44 * httpGet() - Send a GET request to the server.
45 * httpHead() - Send a HEAD request to the server.
46 * httpOptions() - Send an OPTIONS request to the server.
47 * httpPost() - Send a POST request to the server.
48 * httpPut() - Send a PUT request to the server.
49 * httpTrace() - Send an TRACE request to the server.
50 * httpFlush() - Flush data from a HTTP connection.
51 * httpRead() - Read data from a HTTP connection.
52 * httpWrite() - Write data to a HTTP connection.
53 * httpGets() - Get a line of text from a HTTP connection.
54 * httpPrintf() - Print a formatted string to a HTTP connection.
55 * httpStatus() - Return a short string describing a HTTP status code.
56 * httpGetDateString() - Get a formatted date/time string from a time value.
57 * httpGetDateTime() - Get a time value from a formatted date/time string.
58 * httpUpdate() - Update the current HTTP state for incoming data.
59 * httpDecode64() - Base64-decode a string.
60 * httpEncode64() - Base64-encode a string.
61 * httpGetLength() - Get the amount of data remaining from the
62 * content-length or transfer-encoding fields.
63 * http_field() - Return the field index for a field name.
64 * http_send() - Send a request with all fields and the trailing
65 * blank line.
66 * http_upgrade() - Force upgrade to TLS encryption.
67 */
68
69 /*
70 * Include necessary headers...
71 */
72
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <stdarg.h>
76 #include <ctype.h>
77 #include "string.h"
78 #include <fcntl.h>
79 #include <errno.h>
80
81 #include "http.h"
82 #include "ipp.h"
83 #include "debug.h"
84
85 #ifndef WIN32
86 # include <signal.h>
87 #endif /* !WIN32 */
88
89 #ifdef HAVE_LIBSSL
90 # include <openssl/err.h>
91 # include <openssl/rand.h>
92 # include <openssl/ssl.h>
93 #endif /* HAVE_LIBSSL */
94
95
96 /*
97 * Some operating systems have done away with the Fxxxx constants for
98 * the fcntl() call; this works around that "feature"...
99 */
100
101 #ifndef FNONBLK
102 # define FNONBLK O_NONBLOCK
103 #endif /* !FNONBLK */
104
105
106 /*
107 * Local functions...
108 */
109
110 static http_field_t http_field(const char *name);
111 static int http_send(http_t *http, http_state_t request,
112 const char *uri);
113 #ifdef HAVE_LIBSSL
114 static int http_upgrade(http_t *http);
115 #endif /* HAVE_LIBSSL */
116
117
118 /*
119 * Local globals...
120 */
121
122 static const char *http_fields[] =
123 {
124 "Accept-Language",
125 "Accept-Ranges",
126 "Authorization",
127 "Connection",
128 "Content-Encoding",
129 "Content-Language",
130 "Content-Length",
131 "Content-Location",
132 "Content-MD5",
133 "Content-Range",
134 "Content-Type",
135 "Content-Version",
136 "Date",
137 "Host",
138 "If-Modified-Since",
139 "If-Unmodified-since",
140 "Keep-Alive",
141 "Last-Modified",
142 "Link",
143 "Location",
144 "Range",
145 "Referer",
146 "Retry-After",
147 "Transfer-Encoding",
148 "Upgrade",
149 "User-Agent",
150 "WWW-Authenticate"
151 };
152 static const char *days[7] =
153 {
154 "Sun",
155 "Mon",
156 "Tue",
157 "Wed",
158 "Thu",
159 "Fri",
160 "Sat"
161 };
162 static const char *months[12] =
163 {
164 "Jan",
165 "Feb",
166 "Mar",
167 "Apr",
168 "May",
169 "Jun",
170 "Jul",
171 "Aug",
172 "Sep",
173 "Oct",
174 "Nov",
175 "Dec"
176 };
177
178
179 /*
180 * 'httpInitialize()' - Initialize the HTTP interface library and set the
181 * default HTTP proxy (if any).
182 */
183
184 void
185 httpInitialize(void)
186 {
187 #ifdef HAVE_LIBSSL
188 struct timeval curtime; /* Current time in microseconds */
189 int i; /* Looping var */
190 unsigned char data[1024]; /* Seed data */
191 #endif /* HAVE_LIBSSL */
192
193 #ifdef WIN32
194 WSADATA winsockdata; /* WinSock data */
195 static int initialized = 0;/* Has WinSock been initialized? */
196
197
198 if (!initialized)
199 WSAStartup(MAKEWORD(1,1), &winsockdata);
200 #elif defined(HAVE_SIGSET)
201 sigset(SIGPIPE, SIG_IGN);
202 #elif defined(HAVE_SIGACTION)
203 struct sigaction action; /* POSIX sigaction data */
204
205
206 /*
207 * Ignore SIGPIPE signals...
208 */
209
210 memset(&action, 0, sizeof(action));
211 action.sa_handler = SIG_IGN;
212 sigaction(SIGPIPE, &action, NULL);
213 #else
214 signal(SIGPIPE, SIG_IGN);
215 #endif /* WIN32 */
216
217 #ifdef HAVE_LIBSSL
218 SSL_load_error_strings();
219 SSL_library_init();
220
221 /*
222 * Using the current time is a dubious random seed, but on some systems
223 * it is the best we can do (on others, this seed isn't even used...)
224 */
225
226 gettimeofday(&curtime, NULL);
227 srand(curtime.tv_sec + curtime.tv_usec);
228
229 for (i = 0; i < sizeof(data); i ++)
230 data[i] = rand(); /* Yes, this is a poor source of random data... */
231
232 RAND_seed(&data, sizeof(data));
233 #endif /* HAVE_LIBSSL */
234 }
235
236
237 /*
238 * 'httpCheck()' - Check to see if there is a pending response from the server.
239 */
240
241 int /* O - 0 = no data, 1 = data available */
242 httpCheck(http_t *http) /* I - HTTP connection */
243 {
244 fd_set input; /* Input set for select() */
245 struct timeval timeout; /* Timeout */
246
247
248 /*
249 * First see if there is data in the buffer...
250 */
251
252 if (http == NULL)
253 return (0);
254
255 if (http->used)
256 return (1);
257
258 /*
259 * Then try doing a select() to poll the socket...
260 */
261
262 FD_ZERO(&input);
263 FD_SET(http->fd, &input);
264
265 timeout.tv_sec = 0;
266 timeout.tv_usec = 0;
267
268 return (select(http->fd + 1, &input, NULL, NULL, &timeout) > 0);
269 }
270
271
272 /*
273 * 'httpClose()' - Close an HTTP connection...
274 */
275
276 void
277 httpClose(http_t *http) /* I - Connection to close */
278 {
279 #ifdef HAVE_LIBSSL
280 SSL_CTX *context; /* Context for encryption */
281 SSL *conn; /* Connection for encryption */
282 #endif /* HAVE_LIBSSL */
283
284
285 if (!http)
286 return;
287
288 #ifdef HAVE_LIBSSL
289 if (http->tls)
290 {
291 conn = (SSL *)(http->tls);
292 context = SSL_get_SSL_CTX(conn);
293
294 SSL_shutdown(conn);
295 SSL_CTX_free(context);
296 SSL_free(conn);
297
298 http->tls = NULL;
299 }
300 #endif /* HAVE_LIBSSL */
301
302 #ifdef WIN32
303 closesocket(http->fd);
304 #else
305 close(http->fd);
306 #endif /* WIN32 */
307
308 free(http);
309 }
310
311
312 /*
313 * 'httpConnect()' - Connect to a HTTP server.
314 */
315
316 http_t * /* O - New HTTP connection */
317 httpConnect(const char *host, /* I - Host to connect to */
318 int port) /* I - Port number */
319 {
320 http_encryption_t encrypt;/* Type of encryption to use */
321
322
323 /*
324 * Set the default encryption status...
325 */
326
327 if (port == 443)
328 encrypt = HTTP_ENCRYPT_ALWAYS;
329 else
330 encrypt = HTTP_ENCRYPT_IF_REQUESTED;
331
332 return (httpConnectEncrypt(host, port, encrypt));
333 }
334
335
336 /*
337 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
338 */
339
340 http_t * /* O - New HTTP connection */
341 httpConnectEncrypt(const char *host, /* I - Host to connect to */
342 int port, /* I - Port number */
343 http_encryption_t encrypt)
344 /* I - Type of encryption to use */
345 {
346 int i; /* Looping var */
347 http_t *http; /* New HTTP connection */
348 struct hostent *hostaddr; /* Host address data */
349
350
351 if (host == NULL)
352 return (NULL);
353
354 httpInitialize();
355
356 /*
357 * Lookup the host...
358 */
359
360 if ((hostaddr = httpGetHostByName(host)) == NULL)
361 {
362 /*
363 * This hack to make users that don't have a localhost entry in
364 * their hosts file or DNS happy...
365 */
366
367 if (strcasecmp(host, "localhost") != 0)
368 return (NULL);
369 else if ((hostaddr = httpGetHostByName("127.0.0.1")) == NULL)
370 return (NULL);
371 }
372
373 /*
374 * Verify that it is an IPv4 address (IPv6 support will come in CUPS 1.2...)
375 */
376
377 if (hostaddr->h_addrtype != AF_INET || hostaddr->h_length != 4)
378 return (NULL);
379
380 /*
381 * Allocate memory for the structure...
382 */
383
384 http = calloc(sizeof(http_t), 1);
385 if (http == NULL)
386 return (NULL);
387
388 http->version = HTTP_1_1;
389 http->blocking = 1;
390 http->activity = time(NULL);
391 http->fd = -1;
392
393 /*
394 * Copy the hostname and port and then "reconnect"...
395 */
396
397 strncpy(http->hostname, host, sizeof(http->hostname) - 1);
398 http->hostaddr.sin_family = hostaddr->h_addrtype;
399 #ifdef WIN32
400 http->hostaddr.sin_port = htons((u_short)port);
401 #else
402 http->hostaddr.sin_port = htons(port);
403 #endif /* WIN32 */
404
405 /*
406 * Set the encryption status...
407 */
408
409 if (port == 443) /* Always use encryption for https */
410 http->encryption = HTTP_ENCRYPT_ALWAYS;
411 else
412 http->encryption = encrypt;
413
414 /*
415 * Loop through the addresses we have until one of them connects...
416 */
417
418 strncpy(http->hostname, host, sizeof(http->hostname) - 1);
419
420 for (i = 0; hostaddr->h_addr_list[i]; i ++)
421 {
422 /*
423 * Load the address...
424 */
425
426 memcpy((char *)&(http->hostaddr.sin_addr), hostaddr->h_addr_list[i],
427 hostaddr->h_length);
428
429 /*
430 * Connect to the remote system...
431 */
432
433 if (!httpReconnect(http))
434 return (http);
435 }
436
437 /*
438 * Could not connect to any known address - bail out!
439 */
440
441 free(http);
442 return (NULL);
443 }
444
445
446 /*
447 * 'httpEncryption()' - Set the required encryption on the link.
448 */
449
450 int /* O - -1 on error, 0 on success */
451 httpEncryption(http_t *http, /* I - HTTP data */
452 http_encryption_t e) /* I - New encryption preference */
453 {
454 #ifdef HAVE_LIBSSL
455 if (!http)
456 return (0);
457
458 http->encryption = e;
459
460 if ((http->encryption == HTTP_ENCRYPT_ALWAYS && !http->tls) ||
461 (http->encryption == HTTP_ENCRYPT_NEVER && http->tls))
462 return (httpReconnect(http));
463 else if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
464 return (http_upgrade(http));
465 else
466 return (0);
467 #else
468 if (e == HTTP_ENCRYPT_ALWAYS || e == HTTP_ENCRYPT_REQUIRED)
469 return (-1);
470 else
471 return (0);
472 #endif /* HAVE_LIBSSL */
473 }
474
475
476 /*
477 * 'httpReconnect()' - Reconnect to a HTTP server...
478 */
479
480 int /* O - 0 on success, non-zero on failure */
481 httpReconnect(http_t *http) /* I - HTTP data */
482 {
483 int val; /* Socket option value */
484 #ifdef HAVE_LIBSSL
485 SSL_CTX *context; /* Context for encryption */
486 SSL *conn; /* Connection for encryption */
487
488
489 if (http->tls)
490 {
491 conn = (SSL *)(http->tls);
492 context = SSL_get_SSL_CTX(conn);
493
494 SSL_shutdown(conn);
495 SSL_CTX_free(context);
496 SSL_free(conn);
497
498 http->tls = NULL;
499 }
500 #endif /* HAVE_LIBSSL */
501
502 /*
503 * Close any previously open socket...
504 */
505
506 if (http->fd >= 0)
507 #ifdef WIN32
508 closesocket(http->fd);
509 #else
510 close(http->fd);
511 #endif /* WIN32 */
512
513 /*
514 * Create the socket and set options to allow reuse.
515 */
516
517 if ((http->fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
518 {
519 #ifdef WIN32
520 http->error = WSAGetLastError();
521 #else
522 http->error = errno;
523 #endif /* WIN32 */
524 http->status = HTTP_ERROR;
525 return (-1);
526 }
527
528 #ifdef FD_CLOEXEC
529 fcntl(http->fd, F_SETFD, FD_CLOEXEC); /* Close this socket when starting *
530 * other processes... */
531 #endif /* FD_CLOEXEC */
532
533 val = 1;
534 setsockopt(http->fd, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
535
536 #ifdef SO_REUSEPORT
537 val = 1;
538 setsockopt(http->fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val));
539 #endif /* SO_REUSEPORT */
540
541 /*
542 * Using TCP_NODELAY improves responsiveness, especially on systems
543 * with a slow loopback interface... Since we write large buffers
544 * when sending print files and requests, there shouldn't be any
545 * performance penalty for this...
546 */
547
548 val = 1;
549 setsockopt(http->fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
550
551 /*
552 * Connect to the server...
553 */
554
555 if (connect(http->fd, (struct sockaddr *)&(http->hostaddr),
556 sizeof(http->hostaddr)) < 0)
557 {
558 #ifdef WIN32
559 http->error = WSAGetLastError();
560 #else
561 http->error = errno;
562 #endif /* WIN32 */
563 http->status = HTTP_ERROR;
564
565 #ifdef WIN32
566 closesocket(http->fd);
567 #else
568 close(http->fd);
569 #endif
570
571 http->fd = -1;
572
573 return (-1);
574 }
575
576 http->error = 0;
577 http->status = HTTP_CONTINUE;
578
579 #ifdef HAVE_LIBSSL
580 if (http->encryption == HTTP_ENCRYPT_ALWAYS)
581 {
582 /*
583 * Always do encryption via SSL.
584 */
585
586 context = SSL_CTX_new(SSLv23_method());
587 conn = SSL_new(context);
588
589 SSL_set_fd(conn, http->fd);
590 if (SSL_connect(conn) != 1)
591 {
592 SSL_CTX_free(context);
593 SSL_free(conn);
594
595 #ifdef WIN32
596 http->error = WSAGetLastError();
597 #else
598 http->error = errno;
599 #endif /* WIN32 */
600 http->status = HTTP_ERROR;
601
602 #ifdef WIN32
603 closesocket(http->fd);
604 #else
605 close(http->fd);
606 #endif
607
608 return (-1);
609 }
610
611 http->tls = conn;
612 }
613 else if (http->encryption == HTTP_ENCRYPT_REQUIRED)
614 return (http_upgrade(http));
615 #endif /* HAVE_LIBSSL */
616
617 return (0);
618 }
619
620
621 /*
622 * 'httpGetHostByName()' - Lookup a hostname or IP address, and return
623 * address records for the specified name.
624 */
625
626 struct hostent * /* O - Host entry */
627 httpGetHostByName(const char *name) /* I - Hostname or IP address */
628 {
629 unsigned ip[4]; /* IP address components */
630 static unsigned packed_ip; /* Packed IPv4 address */
631 static char *packed_ptr[2]; /* Pointer to packed address */
632 static struct hostent host_ip; /* Host entry for IP address */
633
634 #if defined(__APPLE__)
635 /* OS X hack to avoid it's ocassional long delay in lookupd */
636 static char sLoopback[] = "127.0.0.1";
637 if (strcmp(name, "localhost") == 0)
638 name = sLoopback;
639 #endif /* __APPLE__ */
640
641 /*
642 * This function is needed because some operating systems have a
643 * buggy implementation of httpGetHostByName() that does not support
644 * IP addresses. If the first character of the name string is a
645 * number, then sscanf() is used to extract the IP components.
646 * We then pack the components into an IPv4 address manually,
647 * since the inet_aton() function is deprecated. We use the
648 * htonl() macro to get the right byte order for the address.
649 */
650
651 if (isdigit(name[0]))
652 {
653 /*
654 * We have an IP address; break it up and provide the host entry
655 * to the caller. Currently only supports IPv4 addresses, although
656 * it should be trivial to support IPv6 in CUPS 1.2.
657 */
658
659 if (sscanf(name, "%u.%u.%u.%u", ip, ip + 1, ip + 2, ip + 3) != 4)
660 return (NULL); /* Must have 4 numbers */
661
662 packed_ip = htonl(((((((ip[0] << 8) | ip[1]) << 8) | ip[2]) << 8) | ip[3]));
663
664 /*
665 * Fill in the host entry and return it...
666 */
667
668 host_ip.h_name = (char *)name;
669 host_ip.h_aliases = NULL;
670 host_ip.h_addrtype = AF_INET;
671 host_ip.h_length = 4;
672 host_ip.h_addr_list = packed_ptr;
673 packed_ptr[0] = (char *)(&packed_ip);
674 packed_ptr[1] = NULL;
675
676 return (&host_ip);
677 }
678 else
679 {
680 /*
681 * Use the gethostbyname() function to get the IP address for
682 * the name...
683 */
684
685 return (gethostbyname(name));
686 }
687 }
688
689
690 /*
691 * 'httpSeparate()' - Separate a Universal Resource Identifier into its
692 * components.
693 */
694
695 void
696 httpSeparate(const char *uri, /* I - Universal Resource Identifier */
697 char *method, /* O - Method [32] (http, https, etc.) */
698 char *username, /* O - Username [32] */
699 char *host, /* O - Hostname [32] */
700 int *port, /* O - Port number to use */
701 char *resource) /* O - Resource/filename [1024] */
702 {
703 char *ptr; /* Pointer into string... */
704 const char *atsign, /* @ sign */
705 *slash; /* Separator */
706 char safeuri[HTTP_MAX_URI]; /* "Safe" local copy of URI */
707
708
709 /*
710 * Range check input...
711 */
712
713 if (uri == NULL || method == NULL || username == NULL || host == NULL ||
714 port == NULL || resource == NULL)
715 return;
716
717 /*
718 * Copy the URL to a local string to make sure we don't have a URL
719 * longer than HTTP_MAX_URI characters long...
720 */
721
722 strncpy(safeuri, uri, sizeof(safeuri));
723 safeuri[sizeof(safeuri) - 1] = '\0';
724
725 uri = safeuri;
726
727 /*
728 * Grab the method portion of the URI...
729 */
730
731 if (strncmp(uri, "//", 2) == 0)
732 {
733 /*
734 * Workaround for HP IPP client bug...
735 */
736
737 strcpy(method, "ipp");
738 }
739 else
740 {
741 /*
742 * Standard URI with method...
743 */
744
745 for (ptr = host; *uri != ':' && *uri != '\0'; uri ++)
746 if (ptr < (host + HTTP_MAX_URI - 1))
747 *ptr++ = *uri;
748
749 *ptr = '\0';
750 if (*uri == ':')
751 uri ++;
752
753 /*
754 * If the method contains a period or slash, then it's probably
755 * hostname/filename...
756 */
757
758 if (strchr(host, '.') != NULL || strchr(host, '/') != NULL || *uri == '\0')
759 {
760 if ((ptr = strchr(host, '/')) != NULL)
761 {
762 strncpy(resource, ptr, HTTP_MAX_URI);
763 resource[HTTP_MAX_URI - 1] = '\0';
764 *ptr = '\0';
765 }
766 else
767 resource[0] = '\0';
768
769 if (isdigit(*uri))
770 {
771 /*
772 * OK, we have "hostname:port[/resource]"...
773 */
774
775 *port = strtol(uri, (char **)&uri, 10);
776
777 if (*uri == '/')
778 {
779 strncpy(resource, uri, HTTP_MAX_URI);
780 resource[HTTP_MAX_URI - 1] = '\0';
781 }
782 }
783 else
784 *port = 631;
785
786 strcpy(method, "http");
787 username[0] = '\0';
788 return;
789 }
790 else
791 {
792 strncpy(method, host, 31);
793 method[31] = '\0';
794 }
795 }
796
797 /*
798 * If the method starts with less than 2 slashes then it is a local resource...
799 */
800
801 if (strncmp(uri, "//", 2) != 0)
802 {
803 strncpy(resource, uri, 1023);
804 resource[1023] = '\0';
805
806 username[0] = '\0';
807 host[0] = '\0';
808 *port = 0;
809 return;
810 }
811
812 /*
813 * Grab the username, if any...
814 */
815
816 while (*uri == '/')
817 uri ++;
818
819 if ((slash = strchr(uri, '/')) == NULL)
820 slash = uri + strlen(uri);
821
822 if ((atsign = strchr(uri, '@')) != NULL && atsign < slash)
823 {
824 /*
825 * Got a username:password combo...
826 */
827
828 for (ptr = username; uri < atsign; uri ++)
829 if (ptr < (username + HTTP_MAX_URI - 1))
830 *ptr++ = *uri;
831
832 *ptr = '\0';
833
834 uri = atsign + 1;
835 }
836 else
837 username[0] = '\0';
838
839 /*
840 * Grab the hostname...
841 */
842
843 for (ptr = host; *uri != ':' && *uri != '/' && *uri != '\0'; uri ++)
844 if (ptr < (host + HTTP_MAX_URI - 1))
845 *ptr++ = *uri;
846
847 *ptr = '\0';
848
849 if (*uri != ':')
850 {
851 if (strcasecmp(method, "http") == 0)
852 *port = 80;
853 else if (strcasecmp(method, "https") == 0)
854 *port = 443;
855 else if (strcasecmp(method, "ipp") == 0)
856 *port = ippPort();
857 else if (strcasecmp(method, "socket") == 0) /* Not registered yet... */
858 *port = 9100;
859 else
860 *port = 0;
861 }
862 else
863 {
864 /*
865 * Parse port number...
866 */
867
868 *port = 0;
869 uri ++;
870 while (isdigit(*uri))
871 {
872 *port = (*port * 10) + *uri - '0';
873 uri ++;
874 }
875 }
876
877 if (*uri == '\0')
878 {
879 /*
880 * Hostname but no port or path...
881 */
882
883 resource[0] = '/';
884 resource[1] = '\0';
885 return;
886 }
887
888 /*
889 * The remaining portion is the resource string...
890 */
891
892 strncpy(resource, uri, HTTP_MAX_URI);
893 resource[HTTP_MAX_URI - 1] = '\0';
894 }
895
896
897 /*
898 * 'httpGetSubField()' - Get a sub-field value.
899 */
900
901 char * /* O - Value or NULL */
902 httpGetSubField(http_t *http, /* I - HTTP data */
903 http_field_t field, /* I - Field index */
904 const char *name, /* I - Name of sub-field */
905 char *value) /* O - Value string */
906 {
907 const char *fptr; /* Pointer into field */
908 char temp[HTTP_MAX_VALUE], /* Temporary buffer for name */
909 *ptr; /* Pointer into string buffer */
910
911
912 if (http == NULL ||
913 field < HTTP_FIELD_ACCEPT_LANGUAGE ||
914 field > HTTP_FIELD_WWW_AUTHENTICATE ||
915 name == NULL || value == NULL)
916 return (NULL);
917
918 DEBUG_printf(("httpGetSubField(%p, %d, \"%s\", %p)\n",
919 http, field, name, value));
920
921 for (fptr = http->fields[field]; *fptr;)
922 {
923 /*
924 * Skip leading whitespace...
925 */
926
927 while (isspace(*fptr))
928 fptr ++;
929
930 if (*fptr == ',')
931 {
932 fptr ++;
933 continue;
934 }
935
936 /*
937 * Get the sub-field name...
938 */
939
940 for (ptr = temp;
941 *fptr && *fptr != '=' && !isspace(*fptr) && ptr < (temp + sizeof(temp) - 1);
942 *ptr++ = *fptr++);
943
944 *ptr = '\0';
945
946 DEBUG_printf(("name = \"%s\"\n", temp));
947
948 /*
949 * Skip trailing chars up to the '='...
950 */
951
952 while (isspace(*fptr))
953 fptr ++;
954
955 if (!*fptr)
956 break;
957
958 if (*fptr != '=')
959 continue;
960
961 /*
962 * Skip = and leading whitespace...
963 */
964
965 fptr ++;
966
967 while (isspace(*fptr))
968 fptr ++;
969
970 if (*fptr == '\"')
971 {
972 /*
973 * Read quoted string...
974 */
975
976 for (ptr = value, fptr ++;
977 *fptr && *fptr != '\"' && ptr < (value + HTTP_MAX_VALUE - 1);
978 *ptr++ = *fptr++);
979
980 *ptr = '\0';
981
982 while (*fptr && *fptr != '\"')
983 fptr ++;
984
985 if (*fptr)
986 fptr ++;
987 }
988 else
989 {
990 /*
991 * Read unquoted string...
992 */
993
994 for (ptr = value;
995 *fptr && !isspace(*fptr) && *fptr != ',' && ptr < (value + HTTP_MAX_VALUE - 1);
996 *ptr++ = *fptr++);
997
998 *ptr = '\0';
999
1000 while (*fptr && !isspace(*fptr) && *fptr != ',')
1001 fptr ++;
1002 }
1003
1004 DEBUG_printf(("value = \"%s\"\n", value));
1005
1006 /*
1007 * See if this is the one...
1008 */
1009
1010 if (strcmp(name, temp) == 0)
1011 return (value);
1012 }
1013
1014 value[0] = '\0';
1015
1016 return (NULL);
1017 }
1018
1019
1020 /*
1021 * 'httpSetField()' - Set the value of an HTTP header.
1022 */
1023
1024 void
1025 httpSetField(http_t *http, /* I - HTTP data */
1026 http_field_t field, /* I - Field index */
1027 const char *value) /* I - Value */
1028 {
1029 if (http == NULL ||
1030 field < HTTP_FIELD_ACCEPT_LANGUAGE ||
1031 field > HTTP_FIELD_WWW_AUTHENTICATE ||
1032 value == NULL)
1033 return;
1034
1035 strncpy(http->fields[field], value, HTTP_MAX_VALUE - 1);
1036 http->fields[field][HTTP_MAX_VALUE - 1] = '\0';
1037 }
1038
1039
1040 /*
1041 * 'httpDelete()' - Send a DELETE request to the server.
1042 */
1043
1044 int /* O - Status of call (0 = success) */
1045 httpDelete(http_t *http, /* I - HTTP data */
1046 const char *uri) /* I - URI to delete */
1047 {
1048 return (http_send(http, HTTP_DELETE, uri));
1049 }
1050
1051
1052 /*
1053 * 'httpGet()' - Send a GET request to the server.
1054 */
1055
1056 int /* O - Status of call (0 = success) */
1057 httpGet(http_t *http, /* I - HTTP data */
1058 const char *uri) /* I - URI to get */
1059 {
1060 return (http_send(http, HTTP_GET, uri));
1061 }
1062
1063
1064 /*
1065 * 'httpHead()' - Send a HEAD request to the server.
1066 */
1067
1068 int /* O - Status of call (0 = success) */
1069 httpHead(http_t *http, /* I - HTTP data */
1070 const char *uri) /* I - URI for head */
1071 {
1072 return (http_send(http, HTTP_HEAD, uri));
1073 }
1074
1075
1076 /*
1077 * 'httpOptions()' - Send an OPTIONS request to the server.
1078 */
1079
1080 int /* O - Status of call (0 = success) */
1081 httpOptions(http_t *http, /* I - HTTP data */
1082 const char *uri) /* I - URI for options */
1083 {
1084 return (http_send(http, HTTP_OPTIONS, uri));
1085 }
1086
1087
1088 /*
1089 * 'httpPost()' - Send a POST request to the server.
1090 */
1091
1092 int /* O - Status of call (0 = success) */
1093 httpPost(http_t *http, /* I - HTTP data */
1094 const char *uri) /* I - URI for post */
1095 {
1096 httpGetLength(http);
1097
1098 return (http_send(http, HTTP_POST, uri));
1099 }
1100
1101
1102 /*
1103 * 'httpPut()' - Send a PUT request to the server.
1104 */
1105
1106 int /* O - Status of call (0 = success) */
1107 httpPut(http_t *http, /* I - HTTP data */
1108 const char *uri) /* I - URI to put */
1109 {
1110 httpGetLength(http);
1111
1112 return (http_send(http, HTTP_PUT, uri));
1113 }
1114
1115
1116 /*
1117 * 'httpTrace()' - Send an TRACE request to the server.
1118 */
1119
1120 int /* O - Status of call (0 = success) */
1121 httpTrace(http_t *http, /* I - HTTP data */
1122 const char *uri) /* I - URI for trace */
1123 {
1124 return (http_send(http, HTTP_TRACE, uri));
1125 }
1126
1127
1128 /*
1129 * 'httpFlush()' - Flush data from a HTTP connection.
1130 */
1131
1132 void
1133 httpFlush(http_t *http) /* I - HTTP data */
1134 {
1135 char buffer[8192]; /* Junk buffer */
1136
1137
1138 while (httpRead(http, buffer, sizeof(buffer)) > 0);
1139 }
1140
1141
1142 /*
1143 * 'httpRead()' - Read data from a HTTP connection.
1144 */
1145
1146 int /* O - Number of bytes read */
1147 httpRead(http_t *http, /* I - HTTP data */
1148 char *buffer, /* I - Buffer for data */
1149 int length) /* I - Maximum number of bytes */
1150 {
1151 int bytes; /* Bytes read */
1152 char len[32]; /* Length string */
1153
1154
1155 DEBUG_printf(("httpRead(%p, %p, %d)\n", http, buffer, length));
1156
1157 if (http == NULL || buffer == NULL)
1158 return (-1);
1159
1160 http->activity = time(NULL);
1161
1162 if (length <= 0)
1163 return (0);
1164
1165 if (http->data_encoding == HTTP_ENCODE_CHUNKED &&
1166 http->data_remaining <= 0)
1167 {
1168 DEBUG_puts("httpRead: Getting chunk length...");
1169
1170 if (httpGets(len, sizeof(len), http) == NULL)
1171 {
1172 DEBUG_puts("httpRead: Could not get length!");
1173 return (0);
1174 }
1175
1176 http->data_remaining = strtol(len, NULL, 16);
1177 }
1178
1179 DEBUG_printf(("httpRead: data_remaining = %d\n", http->data_remaining));
1180
1181 if (http->data_remaining == 0)
1182 {
1183 /*
1184 * A zero-length chunk ends a transfer; unless we are reading POST
1185 * data, go idle...
1186 */
1187
1188 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
1189 httpGets(len, sizeof(len), http);
1190
1191 if (http->state == HTTP_POST_RECV)
1192 http->state ++;
1193 else
1194 http->state = HTTP_WAITING;
1195
1196 return (0);
1197 }
1198 else if (length > http->data_remaining)
1199 length = http->data_remaining;
1200
1201 if (http->used == 0 && length <= 256)
1202 {
1203 /*
1204 * Buffer small reads for better performance...
1205 */
1206
1207 if (http->data_remaining > sizeof(http->buffer))
1208 bytes = sizeof(http->buffer);
1209 else
1210 bytes = http->data_remaining;
1211
1212 #ifdef HAVE_LIBSSL
1213 if (http->tls)
1214 bytes = SSL_read((SSL *)(http->tls), http->buffer, bytes);
1215 else
1216 #endif /* HAVE_LIBSSL */
1217 {
1218 DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
1219 bytes));
1220
1221 bytes = recv(http->fd, http->buffer, bytes, 0);
1222
1223 DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
1224 bytes));
1225 }
1226
1227 if (bytes > 0)
1228 http->used = bytes;
1229 else if (bytes < 0)
1230 {
1231 #ifdef WIN32
1232 http->error = WSAGetLastError();
1233 #else
1234 http->error = errno;
1235 #endif /* WIN32 */
1236 return (-1);
1237 }
1238 else
1239 return (0);
1240 }
1241
1242 if (http->used > 0)
1243 {
1244 if (length > http->used)
1245 length = http->used;
1246
1247 bytes = length;
1248
1249 DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes));
1250
1251 memcpy(buffer, http->buffer, length);
1252 http->used -= length;
1253
1254 if (http->used > 0)
1255 memcpy(http->buffer, http->buffer + length, http->used);
1256 }
1257 #ifdef HAVE_LIBSSL
1258 else if (http->tls)
1259 bytes = SSL_read((SSL *)(http->tls), buffer, length);
1260 #endif /* HAVE_LIBSSL */
1261 else
1262 {
1263 DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length));
1264 bytes = recv(http->fd, buffer, length, 0);
1265 DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes));
1266 }
1267
1268 if (bytes > 0)
1269 http->data_remaining -= bytes;
1270 else if (bytes < 0)
1271 #ifdef WIN32
1272 http->error = WSAGetLastError();
1273 #else
1274 http->error = errno;
1275 #endif /* WIN32 */
1276
1277 if (http->data_remaining == 0)
1278 {
1279 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
1280 httpGets(len, sizeof(len), http);
1281
1282 if (http->data_encoding != HTTP_ENCODE_CHUNKED)
1283 {
1284 if (http->state == HTTP_POST_RECV)
1285 http->state ++;
1286 else
1287 http->state = HTTP_WAITING;
1288 }
1289 }
1290
1291 #ifdef DEBUG
1292 {
1293 int i, j, ch;
1294 printf("httpRead: Read %d bytes:\n", bytes);
1295 for (i = 0; i < bytes; i += 16)
1296 {
1297 printf(" ");
1298
1299 for (j = 0; j < 16 && (i + j) < bytes; j ++)
1300 printf(" %02X", buffer[i + j] & 255);
1301
1302 while (j < 16)
1303 {
1304 printf(" ");
1305 j ++;
1306 }
1307
1308 printf(" ");
1309 for (j = 0; j < 16 && (i + j) < bytes; j ++)
1310 {
1311 ch = buffer[i + j] & 255;
1312
1313 if (ch < ' ' || ch == 127)
1314 ch = '.';
1315
1316 putchar(ch);
1317 }
1318 putchar('\n');
1319 }
1320 }
1321 #endif /* DEBUG */
1322
1323 return (bytes);
1324 }
1325
1326
1327 /*
1328 * 'httpWrite()' - Write data to a HTTP connection.
1329 */
1330
1331 int /* O - Number of bytes written */
1332 httpWrite(http_t *http, /* I - HTTP data */
1333 const char *buffer, /* I - Buffer for data */
1334 int length) /* I - Number of bytes to write */
1335 {
1336 int tbytes, /* Total bytes sent */
1337 bytes; /* Bytes sent */
1338
1339
1340 if (http == NULL || buffer == NULL)
1341 return (-1);
1342
1343 http->activity = time(NULL);
1344
1345 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
1346 {
1347 if (httpPrintf(http, "%x\r\n", length) < 0)
1348 return (-1);
1349
1350 if (length == 0)
1351 {
1352 /*
1353 * A zero-length chunk ends a transfer; unless we are sending POST
1354 * data, go idle...
1355 */
1356
1357 DEBUG_puts("httpWrite: changing states...");
1358
1359 if (http->state == HTTP_POST_RECV)
1360 http->state ++;
1361 else if (http->state == HTTP_PUT_RECV)
1362 http->state = HTTP_STATUS;
1363 else
1364 http->state = HTTP_WAITING;
1365
1366 if (httpPrintf(http, "\r\n") < 0)
1367 return (-1);
1368
1369 return (0);
1370 }
1371 }
1372
1373 tbytes = 0;
1374
1375 while (length > 0)
1376 {
1377 #ifdef HAVE_LIBSSL
1378 if (http->tls)
1379 bytes = SSL_write((SSL *)(http->tls), buffer, length);
1380 else
1381 #endif /* HAVE_LIBSSL */
1382 bytes = send(http->fd, buffer, length, 0);
1383
1384 if (bytes < 0)
1385 {
1386 DEBUG_puts("httpWrite: error writing data...\n");
1387
1388 return (-1);
1389 }
1390
1391 buffer += bytes;
1392 tbytes += bytes;
1393 length -= bytes;
1394 if (http->data_encoding == HTTP_ENCODE_LENGTH)
1395 http->data_remaining -= bytes;
1396 }
1397
1398 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
1399 if (httpPrintf(http, "\r\n") < 0)
1400 return (-1);
1401
1402 if (http->data_remaining == 0 && http->data_encoding == HTTP_ENCODE_LENGTH)
1403 {
1404 /*
1405 * Finished with the transfer; unless we are sending POST data, go idle...
1406 */
1407
1408 DEBUG_puts("httpWrite: changing states...");
1409
1410 if (http->state == HTTP_POST_RECV)
1411 http->state ++;
1412 else
1413 http->state = HTTP_WAITING;
1414 }
1415
1416 #ifdef DEBUG
1417 {
1418 int i, j, ch;
1419 printf("httpWrite: wrote %d bytes: \n", tbytes);
1420 for (i = 0, buffer -= tbytes; i < tbytes; i += 16)
1421 {
1422 printf(" ");
1423
1424 for (j = 0; j < 16 && (i + j) < tbytes; j ++)
1425 printf(" %02X", buffer[i + j] & 255);
1426
1427 while (j < 16)
1428 {
1429 printf(" ");
1430 j ++;
1431 }
1432
1433 printf(" ");
1434 for (j = 0; j < 16 && (i + j) < tbytes; j ++)
1435 {
1436 ch = buffer[i + j] & 255;
1437
1438 if (ch < ' ' || ch == 127)
1439 ch = '.';
1440
1441 putchar(ch);
1442 }
1443 putchar('\n');
1444 }
1445 }
1446 #endif /* DEBUG */
1447 return (tbytes);
1448 }
1449
1450
1451 /*
1452 * 'httpGets()' - Get a line of text from a HTTP connection.
1453 */
1454
1455 char * /* O - Line or NULL */
1456 httpGets(char *line, /* I - Line to read into */
1457 int length, /* I - Max length of buffer */
1458 http_t *http) /* I - HTTP data */
1459 {
1460 char *lineptr, /* Pointer into line */
1461 *bufptr, /* Pointer into input buffer */
1462 *bufend; /* Pointer to end of buffer */
1463 int bytes; /* Number of bytes read */
1464
1465
1466 DEBUG_printf(("httpGets(%p, %d, %p)\n", line, length, http));
1467
1468 if (http == NULL || line == NULL)
1469 return (NULL);
1470
1471 /*
1472 * Pre-scan the buffer and see if there is a newline in there...
1473 */
1474
1475 #ifdef WIN32
1476 WSASetLastError(0);
1477 #else
1478 errno = 0;
1479 #endif /* WIN32 */
1480
1481 do
1482 {
1483 bufptr = http->buffer;
1484 bufend = http->buffer + http->used;
1485
1486 while (bufptr < bufend)
1487 if (*bufptr == 0x0a)
1488 break;
1489 else
1490 bufptr ++;
1491
1492 if (bufptr >= bufend && http->used < HTTP_MAX_BUFFER)
1493 {
1494 /*
1495 * No newline; see if there is more data to be read...
1496 */
1497
1498 #ifdef HAVE_LIBSSL
1499 if (http->tls)
1500 bytes = SSL_read((SSL *)(http->tls), bufend,
1501 HTTP_MAX_BUFFER - http->used);
1502 else
1503 #endif /* HAVE_LIBSSL */
1504 bytes = recv(http->fd, bufend, HTTP_MAX_BUFFER - http->used, 0);
1505
1506 if (bytes < 0)
1507 {
1508 /*
1509 * Nope, can't get a line this time...
1510 */
1511
1512 #ifdef WIN32
1513 if (WSAGetLastError() != http->error)
1514 {
1515 http->error = WSAGetLastError();
1516 continue;
1517 }
1518
1519 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1520 #else
1521 if (errno != http->error)
1522 {
1523 http->error = errno;
1524 continue;
1525 }
1526
1527 DEBUG_printf(("httpGets(): recv() error %d!\n", errno));
1528 #endif /* WIN32 */
1529
1530 return (NULL);
1531 }
1532 else if (bytes == 0)
1533 {
1534 if (http->blocking)
1535 http->error = EPIPE;
1536
1537 return (NULL);
1538 }
1539
1540 /*
1541 * Yup, update the amount used and the end pointer...
1542 */
1543
1544 http->used += bytes;
1545 bufend += bytes;
1546 }
1547 }
1548 while (bufptr >= bufend && http->used < HTTP_MAX_BUFFER);
1549
1550 http->activity = time(NULL);
1551
1552 /*
1553 * Read a line from the buffer...
1554 */
1555
1556 lineptr = line;
1557 bufptr = http->buffer;
1558 bytes = 0;
1559 length --;
1560
1561 while (bufptr < bufend && bytes < length)
1562 {
1563 bytes ++;
1564
1565 if (*bufptr == 0x0a)
1566 {
1567 bufptr ++;
1568 break;
1569 }
1570 else if (*bufptr == 0x0d)
1571 bufptr ++;
1572 else
1573 *lineptr++ = *bufptr++;
1574 }
1575
1576 if (bytes > 0)
1577 {
1578 *lineptr = '\0';
1579
1580 http->used -= bytes;
1581 if (http->used > 0)
1582 memcpy(http->buffer, bufptr, http->used);
1583
1584 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line));
1585 return (line);
1586 }
1587
1588 DEBUG_puts("httpGets(): No new line available!");
1589
1590 return (NULL);
1591 }
1592
1593
1594 /*
1595 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1596 */
1597
1598 int /* O - Number of bytes written */
1599 httpPrintf(http_t *http, /* I - HTTP data */
1600 const char *format, /* I - printf-style format string */
1601 ...) /* I - Additional args as needed */
1602 {
1603 int bytes, /* Number of bytes to write */
1604 nbytes, /* Number of bytes written */
1605 tbytes; /* Number of bytes all together */
1606 char buf[HTTP_MAX_BUFFER], /* Buffer for formatted string */
1607 *bufptr; /* Pointer into buffer */
1608 va_list ap; /* Variable argument pointer */
1609
1610
1611 va_start(ap, format);
1612 bytes = vsnprintf(buf, sizeof(buf), format, ap);
1613 va_end(ap);
1614
1615 DEBUG_printf(("httpPrintf: %s", buf));
1616
1617 for (tbytes = 0, bufptr = buf; tbytes < bytes; tbytes += nbytes, bufptr += nbytes)
1618 {
1619 #ifdef HAVE_LIBSSL
1620 if (http->tls)
1621 nbytes = SSL_write((SSL *)(http->tls), bufptr, bytes - tbytes);
1622 else
1623 #endif /* HAVE_LIBSSL */
1624 nbytes = send(http->fd, bufptr, bytes - tbytes, 0);
1625
1626 if (nbytes < 0)
1627 return (-1);
1628 }
1629
1630 return (bytes);
1631 }
1632
1633
1634 /*
1635 * 'httpStatus()' - Return a short string describing a HTTP status code.
1636 */
1637
1638 const char * /* O - String or NULL */
1639 httpStatus(http_status_t status) /* I - HTTP status code */
1640 {
1641 switch (status)
1642 {
1643 case HTTP_CONTINUE :
1644 return ("Continue");
1645 case HTTP_SWITCHING_PROTOCOLS :
1646 return ("Switching Protocols");
1647 case HTTP_OK :
1648 return ("OK");
1649 case HTTP_CREATED :
1650 return ("Created");
1651 case HTTP_ACCEPTED :
1652 return ("Accepted");
1653 case HTTP_NO_CONTENT :
1654 return ("No Content");
1655 case HTTP_NOT_MODIFIED :
1656 return ("Not Modified");
1657 case HTTP_BAD_REQUEST :
1658 return ("Bad Request");
1659 case HTTP_UNAUTHORIZED :
1660 return ("Unauthorized");
1661 case HTTP_FORBIDDEN :
1662 return ("Forbidden");
1663 case HTTP_NOT_FOUND :
1664 return ("Not Found");
1665 case HTTP_REQUEST_TOO_LARGE :
1666 return ("Request Entity Too Large");
1667 case HTTP_URI_TOO_LONG :
1668 return ("URI Too Long");
1669 case HTTP_UPGRADE_REQUIRED :
1670 return ("Upgrade Required");
1671 case HTTP_NOT_IMPLEMENTED :
1672 return ("Not Implemented");
1673 case HTTP_NOT_SUPPORTED :
1674 return ("Not Supported");
1675 default :
1676 return ("Unknown");
1677 }
1678 }
1679
1680
1681 /*
1682 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1683 */
1684
1685 const char * /* O - Date/time string */
1686 httpGetDateString(time_t t) /* I - UNIX time */
1687 {
1688 struct tm *tdate;
1689 static char datetime[256];
1690
1691
1692 tdate = gmtime(&t);
1693 snprintf(datetime, sizeof(datetime), "%s, %02d %s %d %02d:%02d:%02d GMT",
1694 days[tdate->tm_wday], tdate->tm_mday, months[tdate->tm_mon],
1695 tdate->tm_year + 1900, tdate->tm_hour, tdate->tm_min, tdate->tm_sec);
1696
1697 return (datetime);
1698 }
1699
1700
1701 /*
1702 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1703 */
1704
1705 time_t /* O - UNIX time */
1706 httpGetDateTime(const char *s) /* I - Date/time string */
1707 {
1708 int i; /* Looping var */
1709 struct tm tdate; /* Time/date structure */
1710 char mon[16]; /* Abbreviated month name */
1711 int day, year; /* Day of month and year */
1712 int hour, min, sec; /* Time */
1713
1714
1715 if (sscanf(s, "%*s%d%15s%d%d:%d:%d", &day, mon, &year, &hour, &min, &sec) < 6)
1716 return (0);
1717
1718 for (i = 0; i < 12; i ++)
1719 if (strcasecmp(mon, months[i]) == 0)
1720 break;
1721
1722 if (i >= 12)
1723 return (0);
1724
1725 tdate.tm_mon = i;
1726 tdate.tm_mday = day;
1727 tdate.tm_year = year - 1900;
1728 tdate.tm_hour = hour;
1729 tdate.tm_min = min;
1730 tdate.tm_sec = sec;
1731 tdate.tm_isdst = 0;
1732
1733 return (mktime(&tdate));
1734 }
1735
1736
1737 /*
1738 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1739 */
1740
1741 http_status_t /* O - HTTP status */
1742 httpUpdate(http_t *http) /* I - HTTP data */
1743 {
1744 char line[1024], /* Line from connection... */
1745 *value; /* Pointer to value on line */
1746 http_field_t field; /* Field index */
1747 int major, minor; /* HTTP version numbers */
1748 http_status_t status; /* Authorization status */
1749 #ifdef HAVE_LIBSSL
1750 SSL_CTX *context; /* Context for encryption */
1751 SSL *conn; /* Connection for encryption */
1752 #endif /* HAVE_LIBSSL */
1753
1754
1755 DEBUG_printf(("httpUpdate(%p)\n", http));
1756
1757 /*
1758 * If we haven't issued any commands, then there is nothing to "update"...
1759 */
1760
1761 if (http->state == HTTP_WAITING)
1762 return (HTTP_CONTINUE);
1763
1764 /*
1765 * Grab all of the lines we can from the connection...
1766 */
1767
1768 while (httpGets(line, sizeof(line), http) != NULL)
1769 {
1770 DEBUG_puts(line);
1771
1772 if (line[0] == '\0')
1773 {
1774 /*
1775 * Blank line means the start of the data section (if any). Return
1776 * the result code, too...
1777 *
1778 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1779 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1780 * tryin'...
1781 */
1782
1783 if (http->status == HTTP_CONTINUE)
1784 return (http->status);
1785
1786 #ifdef HAVE_LIBSSL
1787 if (http->status == HTTP_SWITCHING_PROTOCOLS && !http->tls)
1788 {
1789 context = SSL_CTX_new(SSLv23_method());
1790 conn = SSL_new(context);
1791
1792 SSL_set_fd(conn, http->fd);
1793 if (SSL_connect(conn) != 1)
1794 {
1795 SSL_CTX_free(context);
1796 SSL_free(conn);
1797
1798 #ifdef WIN32
1799 http->error = WSAGetLastError();
1800 #else
1801 http->error = errno;
1802 #endif /* WIN32 */
1803 http->status = HTTP_ERROR;
1804
1805 #ifdef WIN32
1806 closesocket(http->fd);
1807 #else
1808 close(http->fd);
1809 #endif
1810
1811 return (HTTP_ERROR);
1812 }
1813
1814 http->tls = conn;
1815
1816 return (HTTP_CONTINUE);
1817 }
1818 #endif /* HAVE_LIBSSL */
1819
1820 httpGetLength(http);
1821
1822 switch (http->state)
1823 {
1824 case HTTP_GET :
1825 case HTTP_POST :
1826 case HTTP_POST_RECV :
1827 case HTTP_PUT :
1828 http->state ++;
1829 break;
1830
1831 default :
1832 http->state = HTTP_WAITING;
1833 break;
1834 }
1835
1836 return (http->status);
1837 }
1838 else if (strncmp(line, "HTTP/", 5) == 0)
1839 {
1840 /*
1841 * Got the beginning of a response...
1842 */
1843
1844 if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, (int *)&status) != 3)
1845 return (HTTP_ERROR);
1846
1847 http->version = (http_version_t)(major * 100 + minor);
1848 http->status = status;
1849 }
1850 else if ((value = strchr(line, ':')) != NULL)
1851 {
1852 /*
1853 * Got a value...
1854 */
1855
1856 *value++ = '\0';
1857 while (isspace(*value))
1858 value ++;
1859
1860 /*
1861 * Be tolerants of servers that send unknown attribute fields...
1862 */
1863
1864 if ((field = http_field(line)) == HTTP_FIELD_UNKNOWN)
1865 {
1866 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line));
1867 continue;
1868 }
1869
1870 httpSetField(http, field, value);
1871 }
1872 else
1873 {
1874 http->status = HTTP_ERROR;
1875 return (HTTP_ERROR);
1876 }
1877 }
1878
1879 /*
1880 * See if there was an error...
1881 */
1882
1883 if (http->error)
1884 {
1885 http->status = HTTP_ERROR;
1886 return (HTTP_ERROR);
1887 }
1888
1889 /*
1890 * If we haven't already returned, then there is nothing new...
1891 */
1892
1893 return (HTTP_CONTINUE);
1894 }
1895
1896
1897 /*
1898 * 'httpDecode64()' - Base64-decode a string.
1899 */
1900
1901 char * /* O - Decoded string */
1902 httpDecode64(char *out, /* I - String to write to */
1903 const char *in) /* I - String to read from */
1904 {
1905 int pos, /* Bit position */
1906 base64; /* Value of this character */
1907 char *outptr; /* Output pointer */
1908
1909
1910 for (outptr = out, pos = 0; *in != '\0'; in ++)
1911 {
1912 /*
1913 * Decode this character into a number from 0 to 63...
1914 */
1915
1916 if (*in >= 'A' && *in <= 'Z')
1917 base64 = *in - 'A';
1918 else if (*in >= 'a' && *in <= 'z')
1919 base64 = *in - 'a' + 26;
1920 else if (*in >= '0' && *in <= '9')
1921 base64 = *in - '0' + 52;
1922 else if (*in == '+')
1923 base64 = 62;
1924 else if (*in == '/')
1925 base64 = 63;
1926 else if (*in == '=')
1927 break;
1928 else
1929 continue;
1930
1931 /*
1932 * Store the result in the appropriate chars...
1933 */
1934
1935 switch (pos)
1936 {
1937 case 0 :
1938 *outptr = base64 << 2;
1939 pos ++;
1940 break;
1941 case 1 :
1942 *outptr++ |= (base64 >> 4) & 3;
1943 *outptr = (base64 << 4) & 255;
1944 pos ++;
1945 break;
1946 case 2 :
1947 *outptr++ |= (base64 >> 2) & 15;
1948 *outptr = (base64 << 6) & 255;
1949 pos ++;
1950 break;
1951 case 3 :
1952 *outptr++ |= base64;
1953 pos = 0;
1954 break;
1955 }
1956 }
1957
1958 *outptr = '\0';
1959
1960 /*
1961 * Return the decoded string...
1962 */
1963
1964 return (out);
1965 }
1966
1967
1968 /*
1969 * 'httpEncode64()' - Base64-encode a string.
1970 */
1971
1972 char * /* O - Encoded string */
1973 httpEncode64(char *out, /* I - String to write to */
1974 const char *in) /* I - String to read from */
1975 {
1976 char *outptr; /* Output pointer */
1977 static char base64[] = /* Base64 characters... */
1978 {
1979 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1980 "abcdefghijklmnopqrstuvwxyz"
1981 "0123456789"
1982 "+/"
1983 };
1984
1985
1986 for (outptr = out; *in != '\0'; in ++)
1987 {
1988 /*
1989 * Encode the up to 3 characters as 4 Base64 numbers...
1990 */
1991
1992 *outptr ++ = base64[in[0] >> 2];
1993 *outptr ++ = base64[((in[0] << 4) | (in[1] >> 4)) & 63];
1994
1995 in ++;
1996 if (*in == '\0')
1997 {
1998 *outptr ++ = '=';
1999 break;
2000 }
2001
2002 *outptr ++ = base64[((in[0] << 2) | (in[1] >> 6)) & 63];
2003
2004 in ++;
2005 if (*in == '\0')
2006 break;
2007
2008 *outptr ++ = base64[in[0] & 63];
2009 }
2010
2011 *outptr ++ = '=';
2012 *outptr = '\0';
2013
2014 /*
2015 * Return the encoded string...
2016 */
2017
2018 return (out);
2019 }
2020
2021
2022 /*
2023 * 'httpGetLength()' - Get the amount of data remaining from the
2024 * content-length or transfer-encoding fields.
2025 */
2026
2027 int /* O - Content length */
2028 httpGetLength(http_t *http) /* I - HTTP data */
2029 {
2030 DEBUG_printf(("httpGetLength(%p)\n", http));
2031
2032 if (strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked") == 0)
2033 {
2034 DEBUG_puts("httpGetLength: chunked request!");
2035
2036 http->data_encoding = HTTP_ENCODE_CHUNKED;
2037 http->data_remaining = 0;
2038 }
2039 else
2040 {
2041 http->data_encoding = HTTP_ENCODE_LENGTH;
2042
2043 /*
2044 * The following is a hack for HTTP servers that don't send a
2045 * content-length or transfer-encoding field...
2046 *
2047 * If there is no content-length then the connection must close
2048 * after the transfer is complete...
2049 */
2050
2051 if (http->fields[HTTP_FIELD_CONTENT_LENGTH][0] == '\0')
2052 http->data_remaining = 2147483647;
2053 else
2054 http->data_remaining = atoi(http->fields[HTTP_FIELD_CONTENT_LENGTH]);
2055
2056 DEBUG_printf(("httpGetLength: content_length = %d\n", http->data_remaining));
2057 }
2058
2059 return (http->data_remaining);
2060 }
2061
2062
2063 /*
2064 * 'http_field()' - Return the field index for a field name.
2065 */
2066
2067 static http_field_t /* O - Field index */
2068 http_field(const char *name) /* I - String name */
2069 {
2070 int i; /* Looping var */
2071
2072
2073 for (i = 0; i < HTTP_FIELD_MAX; i ++)
2074 if (strcasecmp(name, http_fields[i]) == 0)
2075 return ((http_field_t)i);
2076
2077 return (HTTP_FIELD_UNKNOWN);
2078 }
2079
2080
2081 /*
2082 * 'http_send()' - Send a request with all fields and the trailing blank line.
2083 */
2084
2085 static int /* O - 0 on success, non-zero on error */
2086 http_send(http_t *http, /* I - HTTP data */
2087 http_state_t request, /* I - Request code */
2088 const char *uri) /* I - URI */
2089 {
2090 int i; /* Looping var */
2091 char *ptr, /* Pointer in buffer */
2092 buf[1024]; /* Encoded URI buffer */
2093 static const char *codes[] = /* Request code strings */
2094 {
2095 NULL,
2096 "OPTIONS",
2097 "GET",
2098 NULL,
2099 "HEAD",
2100 "POST",
2101 NULL,
2102 NULL,
2103 "PUT",
2104 NULL,
2105 "DELETE",
2106 "TRACE",
2107 "CLOSE"
2108 };
2109 static const char *hex = "0123456789ABCDEF";
2110 /* Hex digits */
2111
2112
2113 if (http == NULL || uri == NULL)
2114 return (-1);
2115
2116 /*
2117 * Encode the URI as needed...
2118 */
2119
2120 for (ptr = buf; *uri != '\0' && ptr < (buf + sizeof(buf) - 1); uri ++)
2121 if (*uri <= ' ' || *uri >= 127)
2122 {
2123 if (ptr < (buf + sizeof(buf) - 1))
2124 *ptr ++ = '%';
2125 if (ptr < (buf + sizeof(buf) - 1))
2126 *ptr ++ = hex[(*uri >> 4) & 15];
2127 if (ptr < (buf + sizeof(buf) - 1))
2128 *ptr ++ = hex[*uri & 15];
2129 }
2130 else
2131 *ptr ++ = *uri;
2132
2133 *ptr = '\0';
2134
2135 /*
2136 * See if we had an error the last time around; if so, reconnect...
2137 */
2138
2139 if (http->status == HTTP_ERROR || http->status >= HTTP_BAD_REQUEST)
2140 httpReconnect(http);
2141
2142 /*
2143 * Send the request header...
2144 */
2145
2146 http->state = request;
2147 if (request == HTTP_POST || request == HTTP_PUT)
2148 http->state ++;
2149
2150 http->status = HTTP_CONTINUE;
2151
2152 #ifdef HAVE_LIBSSL
2153 if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
2154 {
2155 httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
2156 httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.0,SSL/2.0,SSL/3.0");
2157 }
2158 #endif /* HAVE_LIBSSL */
2159
2160 if (httpPrintf(http, "%s %s HTTP/1.1\r\n", codes[request], buf) < 1)
2161 {
2162 http->status = HTTP_ERROR;
2163 return (-1);
2164 }
2165
2166 for (i = 0; i < HTTP_FIELD_MAX; i ++)
2167 if (http->fields[i][0] != '\0')
2168 {
2169 DEBUG_printf(("%s: %s\n", http_fields[i], http->fields[i]));
2170
2171 if (httpPrintf(http, "%s: %s\r\n", http_fields[i], http->fields[i]) < 1)
2172 {
2173 http->status = HTTP_ERROR;
2174 return (-1);
2175 }
2176 }
2177
2178 if (httpPrintf(http, "\r\n") < 1)
2179 {
2180 http->status = HTTP_ERROR;
2181 return (-1);
2182 }
2183
2184 httpClearFields(http);
2185
2186 return (0);
2187 }
2188
2189
2190 #ifdef HAVE_LIBSSL
2191 /*
2192 * 'http_upgrade()' - Force upgrade to TLS encryption.
2193 */
2194
2195 static int /* O - Status of connection */
2196 http_upgrade(http_t *http) /* I - HTTP data */
2197 {
2198 int ret; /* Return value */
2199 http_t myhttp; /* Local copy of HTTP data */
2200
2201
2202 DEBUG_printf(("http_upgrade(%p)\n", http));
2203
2204 /*
2205 * Copy the HTTP data to a local variable so we can do the OPTIONS
2206 * request without interfering with the existing request data...
2207 */
2208
2209 memcpy(&myhttp, http, sizeof(myhttp));
2210
2211 /*
2212 * Send an OPTIONS request to the server, requiring SSL or TLS
2213 * encryption on the link...
2214 */
2215
2216 httpClearFields(&myhttp);
2217 httpSetField(&myhttp, HTTP_FIELD_CONNECTION, "upgrade");
2218 httpSetField(&myhttp, HTTP_FIELD_UPGRADE, "TLS/1.0, SSL/2.0, SSL/3.0");
2219
2220 if ((ret = httpOptions(&myhttp, "*")) == 0)
2221 {
2222 /*
2223 * Wait for the secure connection...
2224 */
2225
2226 while (httpUpdate(&myhttp) == HTTP_CONTINUE);
2227 }
2228
2229 httpFlush(&myhttp);
2230
2231 /*
2232 * Copy the HTTP data back over, if any...
2233 */
2234
2235 http->fd = myhttp.fd;
2236 http->error = myhttp.error;
2237 http->activity = myhttp.activity;
2238 http->status = myhttp.status;
2239 http->version = myhttp.version;
2240 http->keep_alive = myhttp.keep_alive;
2241 http->used = myhttp.used;
2242
2243 if (http->used)
2244 memcpy(http->buffer, myhttp.buffer, http->used);
2245
2246 http->auth_type = myhttp.auth_type;
2247 http->nonce_count = myhttp.nonce_count;
2248
2249 memcpy(http->nonce, myhttp.nonce, sizeof(http->nonce));
2250
2251 http->tls = myhttp.tls;
2252 http->encryption = myhttp.encryption;
2253
2254 /*
2255 * See if we actually went secure...
2256 */
2257
2258 if (!http->tls)
2259 {
2260 /*
2261 * Server does not support HTTP upgrade...
2262 */
2263
2264 DEBUG_puts("Server does not support HTTP upgrade!");
2265
2266 #ifdef WIN32
2267 closesocket(http->fd);
2268 #else
2269 close(http->fd);
2270 #endif
2271
2272 http->fd = -1;
2273
2274 return (-1);
2275 }
2276 else
2277 return (ret);
2278 }
2279 #endif /* HAVE_LIBSSL */
2280
2281
2282 /*
2283 * End of "$Id: http.c,v 1.96 2002/04/09 19:27:06 mike Exp $".
2284 */