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