]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/http.c
Fix 32-bit size alignment of FD set size (should divide by 8 for bytes, not
[thirdparty/cups.git] / cups / http.c
1 /*
2 * "$Id: http.c,v 1.125 2003/09/05 20:36:08 mike 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 * or PUT 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 or PUT
1205 * data, go idle...
1206 */
1207
1208 DEBUG_puts("httpWrite: changing states...");
1209
1210 if (http->state == HTTP_POST_RECV)
1211 http->state ++;
1212 else if (http->state == HTTP_PUT_RECV)
1213 http->state = HTTP_STATUS;
1214 else
1215 http->state = HTTP_WAITING;
1216 }
1217
1218 #ifdef DEBUG
1219 {
1220 int i, j, ch;
1221 printf("httpWrite: wrote %d bytes: \n", tbytes);
1222 for (i = 0, buffer -= tbytes; i < tbytes; i += 16)
1223 {
1224 printf(" ");
1225
1226 for (j = 0; j < 16 && (i + j) < tbytes; j ++)
1227 printf(" %02X", buffer[i + j] & 255);
1228
1229 while (j < 16)
1230 {
1231 printf(" ");
1232 j ++;
1233 }
1234
1235 printf(" ");
1236 for (j = 0; j < 16 && (i + j) < tbytes; j ++)
1237 {
1238 ch = buffer[i + j] & 255;
1239
1240 if (ch < ' ' || ch == 127)
1241 ch = '.';
1242
1243 putchar(ch);
1244 }
1245 putchar('\n');
1246 }
1247 }
1248 #endif /* DEBUG */
1249 return (tbytes);
1250 }
1251
1252
1253 /*
1254 * 'httpGets()' - Get a line of text from a HTTP connection.
1255 */
1256
1257 char * /* O - Line or NULL */
1258 httpGets(char *line, /* I - Line to read into */
1259 int length, /* I - Max length of buffer */
1260 http_t *http) /* I - HTTP data */
1261 {
1262 char *lineptr, /* Pointer into line */
1263 *bufptr, /* Pointer into input buffer */
1264 *bufend; /* Pointer to end of buffer */
1265 int bytes; /* Number of bytes read */
1266
1267
1268 DEBUG_printf(("httpGets(%p, %d, %p)\n", line, length, http));
1269
1270 if (http == NULL || line == NULL)
1271 return (NULL);
1272
1273 /*
1274 * Pre-scan the buffer and see if there is a newline in there...
1275 */
1276
1277 #ifdef WIN32
1278 WSASetLastError(0);
1279 #else
1280 errno = 0;
1281 #endif /* WIN32 */
1282
1283 do
1284 {
1285 bufptr = http->buffer;
1286 bufend = http->buffer + http->used;
1287
1288 while (bufptr < bufend)
1289 if (*bufptr == 0x0a)
1290 break;
1291 else
1292 bufptr ++;
1293
1294 if (bufptr >= bufend && http->used < HTTP_MAX_BUFFER)
1295 {
1296 /*
1297 * No newline; see if there is more data to be read...
1298 */
1299
1300 if (!http->blocking && !http_wait(http, 1000))
1301 return (NULL);
1302
1303 #ifdef HAVE_SSL
1304 if (http->tls)
1305 bytes = http_read_ssl(http, bufend, HTTP_MAX_BUFFER - http->used);
1306 else
1307 #endif /* HAVE_SSL */
1308 bytes = recv(http->fd, bufend, HTTP_MAX_BUFFER - http->used, 0);
1309
1310 if (bytes < 0)
1311 {
1312 /*
1313 * Nope, can't get a line this time...
1314 */
1315
1316 #ifdef WIN32
1317 if (WSAGetLastError() != http->error)
1318 {
1319 http->error = WSAGetLastError();
1320 continue;
1321 }
1322
1323 DEBUG_printf(("httpGets(): recv() error %d!\n", WSAGetLastError()));
1324 #else
1325 if (errno == EINTR)
1326 continue;
1327 else if (errno != http->error)
1328 {
1329 http->error = errno;
1330 continue;
1331 }
1332
1333 DEBUG_printf(("httpGets(): recv() error %d!\n", errno));
1334 #endif /* WIN32 */
1335
1336 return (NULL);
1337 }
1338 else if (bytes == 0)
1339 {
1340 http->error = EPIPE;
1341
1342 return (NULL);
1343 }
1344
1345 /*
1346 * Yup, update the amount used and the end pointer...
1347 */
1348
1349 http->used += bytes;
1350 bufend += bytes;
1351 bufptr = bufend;
1352 }
1353 }
1354 while (bufptr >= bufend && http->used < HTTP_MAX_BUFFER);
1355
1356 http->activity = time(NULL);
1357
1358 /*
1359 * Read a line from the buffer...
1360 */
1361
1362 lineptr = line;
1363 bufptr = http->buffer;
1364 bytes = 0;
1365 length --;
1366
1367 while (bufptr < bufend && bytes < length)
1368 {
1369 bytes ++;
1370
1371 if (*bufptr == 0x0a)
1372 {
1373 bufptr ++;
1374 break;
1375 }
1376 else if (*bufptr == 0x0d)
1377 bufptr ++;
1378 else
1379 *lineptr++ = *bufptr++;
1380 }
1381
1382 if (bytes > 0)
1383 {
1384 *lineptr = '\0';
1385
1386 http->used -= bytes;
1387 if (http->used > 0)
1388 memmove(http->buffer, bufptr, http->used);
1389
1390 DEBUG_printf(("httpGets(): Returning \"%s\"\n", line));
1391 return (line);
1392 }
1393
1394 DEBUG_puts("httpGets(): No new line available!");
1395
1396 return (NULL);
1397 }
1398
1399
1400 /*
1401 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1402 */
1403
1404 int /* O - Number of bytes written */
1405 httpPrintf(http_t *http, /* I - HTTP data */
1406 const char *format, /* I - printf-style format string */
1407 ...) /* I - Additional args as needed */
1408 {
1409 int bytes, /* Number of bytes to write */
1410 nbytes, /* Number of bytes written */
1411 tbytes; /* Number of bytes all together */
1412 char buf[HTTP_MAX_BUFFER], /* Buffer for formatted string */
1413 *bufptr; /* Pointer into buffer */
1414 va_list ap; /* Variable argument pointer */
1415
1416
1417 va_start(ap, format);
1418 bytes = vsnprintf(buf, sizeof(buf), format, ap);
1419 va_end(ap);
1420
1421 DEBUG_printf(("httpPrintf: %s", buf));
1422
1423 for (tbytes = 0, bufptr = buf; tbytes < bytes; tbytes += nbytes, bufptr += nbytes)
1424 {
1425 #ifdef HAVE_SSL
1426 if (http->tls)
1427 nbytes = http_write_ssl(http, bufptr, bytes - tbytes);
1428 else
1429 #endif /* HAVE_SSL */
1430 nbytes = send(http->fd, bufptr, bytes - tbytes, 0);
1431
1432 if (nbytes < 0)
1433 {
1434 nbytes = 0;
1435
1436 #ifdef WIN32
1437 if (WSAGetLastError() != http->error)
1438 {
1439 http->error = WSAGetLastError();
1440 continue;
1441 }
1442 #else
1443 if (errno == EINTR)
1444 continue;
1445 else if (errno != http->error)
1446 {
1447 http->error = errno;
1448 continue;
1449 }
1450 #endif /* WIN32 */
1451
1452 return (-1);
1453 }
1454 }
1455
1456 return (bytes);
1457 }
1458
1459
1460 /*
1461 * 'httpGetDateString()' - Get a formatted date/time string from a time value.
1462 */
1463
1464 const char * /* O - Date/time string */
1465 httpGetDateString(time_t t) /* I - UNIX time */
1466 {
1467 struct tm *tdate;
1468 static char datetime[256];
1469
1470
1471 tdate = gmtime(&t);
1472 snprintf(datetime, sizeof(datetime), "%s, %02d %s %d %02d:%02d:%02d GMT",
1473 days[tdate->tm_wday], tdate->tm_mday, months[tdate->tm_mon],
1474 tdate->tm_year + 1900, tdate->tm_hour, tdate->tm_min, tdate->tm_sec);
1475
1476 return (datetime);
1477 }
1478
1479
1480 /*
1481 * 'httpGetDateTime()' - Get a time value from a formatted date/time string.
1482 */
1483
1484 time_t /* O - UNIX time */
1485 httpGetDateTime(const char *s) /* I - Date/time string */
1486 {
1487 int i; /* Looping var */
1488 struct tm tdate; /* Time/date structure */
1489 char mon[16]; /* Abbreviated month name */
1490 int day, year; /* Day of month and year */
1491 int hour, min, sec; /* Time */
1492
1493
1494 if (sscanf(s, "%*s%d%15s%d%d:%d:%d", &day, mon, &year, &hour, &min, &sec) < 6)
1495 return (0);
1496
1497 for (i = 0; i < 12; i ++)
1498 if (strcasecmp(mon, months[i]) == 0)
1499 break;
1500
1501 if (i >= 12)
1502 return (0);
1503
1504 tdate.tm_mon = i;
1505 tdate.tm_mday = day;
1506 tdate.tm_year = year - 1900;
1507 tdate.tm_hour = hour;
1508 tdate.tm_min = min;
1509 tdate.tm_sec = sec;
1510 tdate.tm_isdst = 0;
1511
1512 return (mktime(&tdate));
1513 }
1514
1515
1516 /*
1517 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1518 */
1519
1520 http_status_t /* O - HTTP status */
1521 httpUpdate(http_t *http) /* I - HTTP data */
1522 {
1523 char line[1024], /* Line from connection... */
1524 *value; /* Pointer to value on line */
1525 http_field_t field; /* Field index */
1526 int major, minor; /* HTTP version numbers */
1527 http_status_t status; /* Authorization status */
1528
1529
1530 DEBUG_printf(("httpUpdate(%p)\n", http));
1531
1532 /*
1533 * If we haven't issued any commands, then there is nothing to "update"...
1534 */
1535
1536 if (http->state == HTTP_WAITING)
1537 return (HTTP_CONTINUE);
1538
1539 /*
1540 * Grab all of the lines we can from the connection...
1541 */
1542
1543 while (httpGets(line, sizeof(line), http) != NULL)
1544 {
1545 DEBUG_puts(line);
1546
1547 if (line[0] == '\0')
1548 {
1549 /*
1550 * Blank line means the start of the data section (if any). Return
1551 * the result code, too...
1552 *
1553 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1554 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1555 * tryin'...
1556 */
1557
1558 if (http->status == HTTP_CONTINUE)
1559 return (http->status);
1560
1561 #ifdef HAVE_SSL
1562 if (http->status == HTTP_SWITCHING_PROTOCOLS && !http->tls)
1563 {
1564 if (http_setup_ssl(http) != 0)
1565 {
1566 #ifdef WIN32
1567 closesocket(http->fd);
1568 #else
1569 close(http->fd);
1570 #endif
1571
1572 return (HTTP_ERROR);
1573 }
1574
1575 return (HTTP_CONTINUE);
1576 }
1577 #endif /* HAVE_SSL */
1578
1579 httpGetLength(http);
1580
1581 switch (http->state)
1582 {
1583 case HTTP_GET :
1584 case HTTP_POST :
1585 case HTTP_POST_RECV :
1586 case HTTP_PUT :
1587 http->state ++;
1588 case HTTP_POST_SEND :
1589 break;
1590
1591 default :
1592 http->state = HTTP_WAITING;
1593 break;
1594 }
1595
1596 return (http->status);
1597 }
1598 else if (strncmp(line, "HTTP/", 5) == 0)
1599 {
1600 /*
1601 * Got the beginning of a response...
1602 */
1603
1604 if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, (int *)&status) != 3)
1605 return (HTTP_ERROR);
1606
1607 http->version = (http_version_t)(major * 100 + minor);
1608 http->status = status;
1609 }
1610 else if ((value = strchr(line, ':')) != NULL)
1611 {
1612 /*
1613 * Got a value...
1614 */
1615
1616 *value++ = '\0';
1617 while (isspace(*value))
1618 value ++;
1619
1620 /*
1621 * Be tolerants of servers that send unknown attribute fields...
1622 */
1623
1624 if (!strcasecmp(line, "expect"))
1625 {
1626 /*
1627 * "Expect: 100-continue" or similar...
1628 */
1629
1630 http->expect = (http_status_t)atoi(value);
1631 }
1632 else if (!strcasecmp(line, "cookie"))
1633 {
1634 /*
1635 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1636 */
1637
1638 httpSetCookie(http, value);
1639 }
1640 else if ((field = http_field(line)) == HTTP_FIELD_UNKNOWN)
1641 {
1642 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line));
1643 continue;
1644 }
1645 else
1646 httpSetField(http, field, value);
1647 }
1648 else
1649 {
1650 http->status = HTTP_ERROR;
1651 return (HTTP_ERROR);
1652 }
1653 }
1654
1655 /*
1656 * See if there was an error...
1657 */
1658
1659 if (http->error)
1660 {
1661 http->status = HTTP_ERROR;
1662 return (HTTP_ERROR);
1663 }
1664
1665 /*
1666 * If we haven't already returned, then there is nothing new...
1667 */
1668
1669 return (HTTP_CONTINUE);
1670 }
1671
1672
1673 /*
1674 * 'httpDecode64()' - Base64-decode a string.
1675 */
1676
1677 char * /* O - Decoded string */
1678 httpDecode64(char *out, /* I - String to write to */
1679 const char *in) /* I - String to read from */
1680 {
1681 int pos, /* Bit position */
1682 base64; /* Value of this character */
1683 char *outptr; /* Output pointer */
1684
1685
1686 for (outptr = out, pos = 0; *in != '\0'; in ++)
1687 {
1688 /*
1689 * Decode this character into a number from 0 to 63...
1690 */
1691
1692 if (*in >= 'A' && *in <= 'Z')
1693 base64 = *in - 'A';
1694 else if (*in >= 'a' && *in <= 'z')
1695 base64 = *in - 'a' + 26;
1696 else if (*in >= '0' && *in <= '9')
1697 base64 = *in - '0' + 52;
1698 else if (*in == '+')
1699 base64 = 62;
1700 else if (*in == '/')
1701 base64 = 63;
1702 else if (*in == '=')
1703 break;
1704 else
1705 continue;
1706
1707 /*
1708 * Store the result in the appropriate chars...
1709 */
1710
1711 switch (pos)
1712 {
1713 case 0 :
1714 *outptr = base64 << 2;
1715 pos ++;
1716 break;
1717 case 1 :
1718 *outptr++ |= (base64 >> 4) & 3;
1719 *outptr = (base64 << 4) & 255;
1720 pos ++;
1721 break;
1722 case 2 :
1723 *outptr++ |= (base64 >> 2) & 15;
1724 *outptr = (base64 << 6) & 255;
1725 pos ++;
1726 break;
1727 case 3 :
1728 *outptr++ |= base64;
1729 pos = 0;
1730 break;
1731 }
1732 }
1733
1734 *outptr = '\0';
1735
1736 /*
1737 * Return the decoded string...
1738 */
1739
1740 return (out);
1741 }
1742
1743
1744 /*
1745 * 'httpEncode64()' - Base64-encode a string.
1746 */
1747
1748 char * /* O - Encoded string */
1749 httpEncode64(char *out, /* I - String to write to */
1750 const char *in) /* I - String to read from */
1751 {
1752 char *outptr; /* Output pointer */
1753 static const char base64[] = /* Base64 characters... */
1754 {
1755 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1756 "abcdefghijklmnopqrstuvwxyz"
1757 "0123456789"
1758 "+/"
1759 };
1760
1761
1762 for (outptr = out; *in != '\0'; in ++)
1763 {
1764 /*
1765 * Encode the up to 3 characters as 4 Base64 numbers...
1766 */
1767
1768 *outptr ++ = base64[in[0] >> 2];
1769 *outptr ++ = base64[((in[0] << 4) | (in[1] >> 4)) & 63];
1770
1771 in ++;
1772 if (*in == '\0')
1773 {
1774 *outptr ++ = '=';
1775 break;
1776 }
1777
1778 *outptr ++ = base64[((in[0] << 2) | (in[1] >> 6)) & 63];
1779
1780 in ++;
1781 if (*in == '\0')
1782 break;
1783
1784 *outptr ++ = base64[in[0] & 63];
1785 }
1786
1787 *outptr ++ = '=';
1788 *outptr = '\0';
1789
1790 /*
1791 * Return the encoded string...
1792 */
1793
1794 return (out);
1795 }
1796
1797
1798 /*
1799 * 'httpGetLength()' - Get the amount of data remaining from the
1800 * content-length or transfer-encoding fields.
1801 */
1802
1803 int /* O - Content length */
1804 httpGetLength(http_t *http) /* I - HTTP data */
1805 {
1806 DEBUG_printf(("httpGetLength(%p), state = %d\n", http, http->state));
1807
1808 if (strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked") == 0)
1809 {
1810 DEBUG_puts("httpGetLength: chunked request!");
1811
1812 http->data_encoding = HTTP_ENCODE_CHUNKED;
1813 http->data_remaining = 0;
1814 }
1815 else
1816 {
1817 http->data_encoding = HTTP_ENCODE_LENGTH;
1818
1819 /*
1820 * The following is a hack for HTTP servers that don't send a
1821 * content-length or transfer-encoding field...
1822 *
1823 * If there is no content-length then the connection must close
1824 * after the transfer is complete...
1825 */
1826
1827 if (http->fields[HTTP_FIELD_CONTENT_LENGTH][0] == '\0')
1828 http->data_remaining = 2147483647;
1829 else
1830 http->data_remaining = atoi(http->fields[HTTP_FIELD_CONTENT_LENGTH]);
1831
1832 DEBUG_printf(("httpGetLength: content_length = %d\n", http->data_remaining));
1833 }
1834
1835 return (http->data_remaining);
1836 }
1837
1838
1839 /*
1840 * 'http_field()' - Return the field index for a field name.
1841 */
1842
1843 static http_field_t /* O - Field index */
1844 http_field(const char *name) /* I - String name */
1845 {
1846 int i; /* Looping var */
1847
1848
1849 for (i = 0; i < HTTP_FIELD_MAX; i ++)
1850 if (strcasecmp(name, http_fields[i]) == 0)
1851 return ((http_field_t)i);
1852
1853 return (HTTP_FIELD_UNKNOWN);
1854 }
1855
1856
1857 /*
1858 * 'http_send()' - Send a request with all fields and the trailing blank line.
1859 */
1860
1861 static int /* O - 0 on success, non-zero on error */
1862 http_send(http_t *http, /* I - HTTP data */
1863 http_state_t request, /* I - Request code */
1864 const char *uri) /* I - URI */
1865 {
1866 int i; /* Looping var */
1867 char *ptr, /* Pointer in buffer */
1868 buf[1024]; /* Encoded URI buffer */
1869 static const char * const codes[] =
1870 { /* Request code strings */
1871 NULL,
1872 "OPTIONS",
1873 "GET",
1874 NULL,
1875 "HEAD",
1876 "POST",
1877 NULL,
1878 NULL,
1879 "PUT",
1880 NULL,
1881 "DELETE",
1882 "TRACE",
1883 "CLOSE"
1884 };
1885 static const char hex[] = "0123456789ABCDEF";
1886 /* Hex digits */
1887
1888
1889 if (http == NULL || uri == NULL)
1890 return (-1);
1891
1892 /*
1893 * Encode the URI as needed...
1894 */
1895
1896 for (ptr = buf; *uri != '\0' && ptr < (buf + sizeof(buf) - 1); uri ++)
1897 if (*uri <= ' ' || *uri >= 127)
1898 {
1899 if (ptr < (buf + sizeof(buf) - 1))
1900 *ptr ++ = '%';
1901 if (ptr < (buf + sizeof(buf) - 1))
1902 *ptr ++ = hex[(*uri >> 4) & 15];
1903 if (ptr < (buf + sizeof(buf) - 1))
1904 *ptr ++ = hex[*uri & 15];
1905 }
1906 else
1907 *ptr ++ = *uri;
1908
1909 *ptr = '\0';
1910
1911 /*
1912 * See if we had an error the last time around; if so, reconnect...
1913 */
1914
1915 if (http->status == HTTP_ERROR || http->status >= HTTP_BAD_REQUEST)
1916 httpReconnect(http);
1917
1918 /*
1919 * Send the request header...
1920 */
1921
1922 http->state = request;
1923 if (request == HTTP_POST || request == HTTP_PUT)
1924 http->state ++;
1925
1926 http->status = HTTP_CONTINUE;
1927
1928 #ifdef HAVE_SSL
1929 if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
1930 {
1931 httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
1932 httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.0,SSL/2.0,SSL/3.0");
1933 }
1934 #endif /* HAVE_SSL */
1935
1936 if (httpPrintf(http, "%s %s HTTP/1.1\r\n", codes[request], buf) < 1)
1937 {
1938 http->status = HTTP_ERROR;
1939 return (-1);
1940 }
1941
1942 for (i = 0; i < HTTP_FIELD_MAX; i ++)
1943 if (http->fields[i][0] != '\0')
1944 {
1945 DEBUG_printf(("%s: %s\n", http_fields[i], http->fields[i]));
1946
1947 if (httpPrintf(http, "%s: %s\r\n", http_fields[i], http->fields[i]) < 1)
1948 {
1949 http->status = HTTP_ERROR;
1950 return (-1);
1951 }
1952 }
1953
1954 if (httpPrintf(http, "\r\n") < 1)
1955 {
1956 http->status = HTTP_ERROR;
1957 return (-1);
1958 }
1959
1960 httpClearFields(http);
1961
1962 return (0);
1963 }
1964
1965
1966 /*
1967 * 'http_wait()' - Wait for data available on a connection.
1968 */
1969
1970 static int /* O - 1 if data is available, 0 otherwise */
1971 http_wait(http_t *http, /* I - HTTP data */
1972 int msec) /* I - Milliseconds to wait */
1973 {
1974 #ifndef WIN32
1975 struct rlimit limit; /* Runtime limit */
1976 #endif /* !WIN32 */
1977 struct timeval timeout; /* Timeout */
1978 int nfds; /* Result from select() */
1979
1980
1981 /*
1982 * Check the SSL/TLS buffers for data first...
1983 */
1984
1985 #ifdef HAVE_SSL
1986 if (http->tls)
1987 {
1988 # ifdef HAVE_LIBSSL
1989 if (SSL_pending((SSL *)(http->tls)))
1990 return (1);
1991 # elif defined(HAVE_GNUTLS)
1992 if (gnutls_record_check_pending(((http_tls_t *)(http->tls))->session))
1993 return (1);
1994 # elif defined(HAVE_CDSASSL)
1995 size_t bytes; /* Bytes that are available */
1996
1997 if (!SSLGetBufferedReadSize((SSLContextRef)http->tls, &bytes) && bytes > 0)
1998 return;
1999 # endif /* HAVE_LIBSSL */
2000 }
2001 #endif /* HAVE_SSL */
2002
2003 /*
2004 * Then try doing a select() to poll the socket...
2005 */
2006
2007 if (!http->input_set)
2008 {
2009 #ifdef WIN32
2010 /*
2011 * Windows has a fixed-size select() structure, different (surprise,
2012 * surprise!) from all UNIX implementations. Just allocate this
2013 * fixed structure...
2014 */
2015
2016 http->input_set = calloc(1, sizeof(fd_set));
2017 #else
2018 /*
2019 * Allocate the select() input set based upon the max number of file
2020 * descriptors available for this process...
2021 */
2022
2023 getrlimit(RLIMIT_NOFILE, &limit);
2024
2025 http->input_set = calloc(1, (limit.rlim_cur + 31) / 8);
2026 #endif /* WIN32 */
2027
2028 if (!http->input_set)
2029 return (0);
2030 }
2031
2032 FD_SET(http->fd, http->input_set);
2033
2034 if (msec >= 0)
2035 {
2036 timeout.tv_sec = msec / 1000;
2037 timeout.tv_usec = (msec % 1000) * 1000;
2038
2039 nfds = select(http->fd + 1, http->input_set, NULL, NULL, &timeout);
2040 }
2041 else
2042 nfds = select(http->fd + 1, http->input_set, NULL, NULL, NULL);
2043
2044 FD_CLR(http->fd, http->input_set);
2045
2046 return (nfds > 0);
2047 }
2048
2049
2050 #ifdef HAVE_SSL
2051 /*
2052 * 'http_upgrade()' - Force upgrade to TLS encryption.
2053 */
2054
2055 static int /* O - Status of connection */
2056 http_upgrade(http_t *http) /* I - HTTP data */
2057 {
2058 int ret; /* Return value */
2059 http_t myhttp; /* Local copy of HTTP data */
2060
2061
2062 DEBUG_printf(("http_upgrade(%p)\n", http));
2063
2064 /*
2065 * Copy the HTTP data to a local variable so we can do the OPTIONS
2066 * request without interfering with the existing request data...
2067 */
2068
2069 memcpy(&myhttp, http, sizeof(myhttp));
2070
2071 /*
2072 * Send an OPTIONS request to the server, requiring SSL or TLS
2073 * encryption on the link...
2074 */
2075
2076 httpClearFields(&myhttp);
2077 httpSetField(&myhttp, HTTP_FIELD_CONNECTION, "upgrade");
2078 httpSetField(&myhttp, HTTP_FIELD_UPGRADE, "TLS/1.0, SSL/2.0, SSL/3.0");
2079
2080 if ((ret = httpOptions(&myhttp, "*")) == 0)
2081 {
2082 /*
2083 * Wait for the secure connection...
2084 */
2085
2086 while (httpUpdate(&myhttp) == HTTP_CONTINUE);
2087 }
2088
2089 httpFlush(&myhttp);
2090
2091 /*
2092 * Copy the HTTP data back over, if any...
2093 */
2094
2095 http->fd = myhttp.fd;
2096 http->error = myhttp.error;
2097 http->activity = myhttp.activity;
2098 http->status = myhttp.status;
2099 http->version = myhttp.version;
2100 http->keep_alive = myhttp.keep_alive;
2101 http->used = myhttp.used;
2102
2103 if (http->used)
2104 memcpy(http->buffer, myhttp.buffer, http->used);
2105
2106 http->auth_type = myhttp.auth_type;
2107 http->nonce_count = myhttp.nonce_count;
2108
2109 memcpy(http->nonce, myhttp.nonce, sizeof(http->nonce));
2110
2111 http->tls = myhttp.tls;
2112 http->encryption = myhttp.encryption;
2113
2114 /*
2115 * See if we actually went secure...
2116 */
2117
2118 if (!http->tls)
2119 {
2120 /*
2121 * Server does not support HTTP upgrade...
2122 */
2123
2124 DEBUG_puts("Server does not support HTTP upgrade!");
2125
2126 # ifdef WIN32
2127 closesocket(http->fd);
2128 # else
2129 close(http->fd);
2130 # endif
2131
2132 http->fd = -1;
2133
2134 return (-1);
2135 }
2136 else
2137 return (ret);
2138 }
2139
2140
2141 /*
2142 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2143 */
2144
2145 static int /* O - Status of connection */
2146 http_setup_ssl(http_t *http) /* I - HTTP data */
2147 {
2148 # ifdef HAVE_LIBSSL
2149 SSL_CTX *context; /* Context for encryption */
2150 SSL *conn; /* Connection for encryption */
2151 # elif defined(HAVE_GNUTLS)
2152 http_tls_t *conn; /* TLS session object */
2153 gnutls_certificate_client_credentials *credentials;
2154 /* TLS credentials */
2155 # elif defined(HAVE_CDSASSL)
2156 SSLContextRef conn; /* Context for encryption */
2157 OSStatus error; /* Error info */
2158 # endif /* HAVE_LIBSSL */
2159
2160
2161 # ifdef HAVE_LIBSSL
2162 context = SSL_CTX_new(SSLv23_client_method());
2163 conn = SSL_new(context);
2164
2165 SSL_set_fd(conn, http->fd);
2166 if (SSL_connect(conn) != 1)
2167 {
2168 SSL_CTX_free(context);
2169 SSL_free(conn);
2170
2171 # ifdef WIN32
2172 http->error = WSAGetLastError();
2173 # else
2174 http->error = errno;
2175 # endif /* WIN32 */
2176 http->status = HTTP_ERROR;
2177
2178 return (HTTP_ERROR);
2179 }
2180
2181 # elif defined(HAVE_GNUTLS)
2182 conn = (http_tls_t *)malloc(sizeof(http_tls_t));
2183
2184 if (conn == NULL)
2185 {
2186 http->error = errno;
2187 http->status = HTTP_ERROR;
2188
2189 return (-1);
2190 }
2191
2192 credentials = (gnutls_certificate_client_credentials *)
2193 malloc(sizeof(gnutls_certificate_client_credentials));
2194 if (credentials == NULL)
2195 {
2196 free(conn);
2197
2198 http->error = errno;
2199 http->status = HTTP_ERROR;
2200
2201 return (-1);
2202 }
2203
2204 gnutls_certificate_allocate_credentials(credentials);
2205
2206 gnutls_init(&(conn->session), GNUTLS_CLIENT);
2207 gnutls_set_default_priority(conn->session);
2208 gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
2209 gnutls_transport_set_ptr(conn->session, http->fd);
2210
2211 if ((gnutls_handshake(conn->session)) != GNUTLS_E_SUCCESS)
2212 {
2213 http->error = errno;
2214 http->status = HTTP_ERROR;
2215
2216 return (-1);
2217 }
2218
2219 conn->credentials = credentials;
2220
2221 # elif defined(HAVE_CDSASSL)
2222 error = SSLNewContext(false, &conn);
2223
2224 if (!error)
2225 error = SSLSetIOFuncs(conn, CDSAReadFunc, CDSAWriteFunc);
2226
2227 if (!error)
2228 error = SSLSetConnection(conn, (SSLConnectionRef)http->fd);
2229
2230 if (!error)
2231 error = SSLSetAllowsExpiredCerts(conn, true);
2232
2233 if (!error)
2234 error = SSLSetAllowsAnyRoot(conn, true);
2235
2236 if (!error)
2237 error = SSLHandshake(conn);
2238
2239 if (error != 0)
2240 {
2241 http->error = error;
2242 http->status = HTTP_ERROR;
2243
2244 SSLDisposeContext(conn);
2245
2246 close(http->fd);
2247
2248 return (-1);
2249 }
2250 # endif /* HAVE_CDSASSL */
2251
2252 http->tls = conn;
2253 return (0);
2254 }
2255
2256
2257 /*
2258 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2259 */
2260
2261 static void
2262 http_shutdown_ssl(http_t *http) /* I - HTTP data */
2263 {
2264 # ifdef HAVE_LIBSSL
2265 SSL_CTX *context; /* Context for encryption */
2266 SSL *conn; /* Connection for encryption */
2267
2268
2269 conn = (SSL *)(http->tls);
2270 context = SSL_get_SSL_CTX(conn);
2271
2272 SSL_shutdown(conn);
2273 SSL_CTX_free(context);
2274 SSL_free(conn);
2275
2276 # elif defined(HAVE_GNUTLS)
2277 http_tls_t *conn; /* Encryption session */
2278 gnutls_certificate_client_credentials *credentials;
2279 /* TLS credentials */
2280
2281
2282 conn = (http_tls_t *)(http->tls);
2283 credentials = (gnutls_certificate_client_credentials *)(conn->credentials);
2284
2285 gnutls_bye(conn->session, GNUTLS_SHUT_RDWR);
2286 gnutls_deinit(conn->session);
2287 gnutls_certificate_free_credentials(*credentials);
2288 free(credentials);
2289 free(conn);
2290
2291 # elif defined(HAVE_CDSASSL)
2292 SSLClose((SSLContextRef)http->tls);
2293 SSLDisposeContext((SSLContextRef)http->tls);
2294 # endif /* HAVE_LIBSSL */
2295
2296 http->tls = NULL;
2297 }
2298
2299
2300 /*
2301 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2302 */
2303
2304 static int /* O - Bytes read */
2305 http_read_ssl(http_t *http, /* I - HTTP data */
2306 char *buf, /* I - Buffer to store data */
2307 int len) /* I - Length of buffer */
2308 {
2309 # if defined(HAVE_LIBSSL)
2310 return (SSL_read((SSL *)(http->tls), buf, len));
2311
2312 # elif defined(HAVE_GNUTLS)
2313 return (gnutls_record_recv(((http_tls_t *)(http->tls))->session, buf, len));
2314
2315 # elif defined(HAVE_CDSASSL)
2316 OSStatus error; /* Error info */
2317 size_t processed; /* Number of bytes processed */
2318
2319
2320 error = SSLRead((SSLContextRef)http->tls, buf, len, &processed);
2321
2322 if (error == 0)
2323 return (processed);
2324 else
2325 {
2326 http->error = error;
2327
2328 return (-1);
2329 }
2330 # endif /* HAVE_LIBSSL */
2331 }
2332
2333
2334 /*
2335 * 'http_write_ssl()' - Write to a SSL/TLS connection.
2336 */
2337
2338 static int /* O - Bytes written */
2339 http_write_ssl(http_t *http, /* I - HTTP data */
2340 const char *buf, /* I - Buffer holding data */
2341 int len) /* I - Length of buffer */
2342 {
2343 # if defined(HAVE_LIBSSL)
2344 return (SSL_write((SSL *)(http->tls), buf, len));
2345
2346 # elif defined(HAVE_GNUTLS)
2347 return (gnutls_record_send(((http_tls_t *)(http->tls))->session, buf, len));
2348 # elif defined(HAVE_CDSASSL)
2349 OSStatus error; /* Error info */
2350 size_t processed; /* Number of bytes processed */
2351
2352
2353 error = SSLWrite((SSLContextRef)http->tls, buf, len, &processed);
2354
2355 if (error == 0)
2356 return (processed);
2357 else
2358 {
2359 http->error = error;
2360 return (-1);
2361 }
2362 # endif /* HAVE_LIBSSL */
2363 }
2364
2365
2366 # if defined(HAVE_CDSASSL)
2367 /*
2368 * 'CDSAReadFunc()' - Read function for CDSA decryption code.
2369 */
2370
2371 static OSStatus /* O - -1 on error, 0 on success */
2372 CDSAReadFunc(SSLConnectionRef connection, /* I - SSL/TLS connection */
2373 void *data, /* I - Data buffer */
2374 size_t *dataLength) /* IO - Number of bytes */
2375 {
2376 ssize_t bytes; /* Number of bytes read */
2377
2378
2379 bytes = recv((int)connection, data, *dataLength, 0);
2380 if (bytes >= 0)
2381 {
2382 *dataLength = bytes;
2383 return (0);
2384 }
2385 else
2386 return (-1);
2387 }
2388
2389
2390 /*
2391 * 'CDSAWriteFunc()' - Write function for CDSA encryption code.
2392 */
2393
2394 static OSStatus /* O - -1 on error, 0 on success */
2395 CDSAWriteFunc(SSLConnectionRef connection, /* I - SSL/TLS connection */
2396 const void *data, /* I - Data buffer */
2397 size_t *dataLength) /* IO - Number of bytes */
2398 {
2399 ssize_t bytes;
2400
2401
2402 bytes = write((int)connection, data, *dataLength);
2403 if (bytes >= 0)
2404 {
2405 *dataLength = bytes;
2406 return (0);
2407 }
2408 else
2409 return (-1);
2410 }
2411 # endif /* HAVE_CDSASSL */
2412 #endif /* HAVE_SSL */
2413
2414
2415 /*
2416 * End of "$Id: http.c,v 1.125 2003/09/05 20:36:08 mike Exp $".
2417 */