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