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