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