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