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