]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/http.c
Load cups into easysw/current.
[thirdparty/cups.git] / cups / http.c
1 /*
2 * "$Id: http.c 6191 2007-01-10 16:48:37Z mike $"
3 *
4 * HTTP routines for the Common UNIX Printing System (CUPS).
5 *
6 * Copyright 1997-2007 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 USA
19 *
20 * Voice: (301) 373-9600
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 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP connections.
29 * httpBlocking() - Set blocking/non-blocking behavior on a connection.
30 * httpCheck() - Check to see if there is a pending response from
31 * the server.
32 * httpClearCookie() - Clear the cookie value(s).
33 * httpClearFields() - Clear HTTP request fields.
34 * httpClose() - Close an HTTP connection...
35 * httpConnect() - Connect to a HTTP server.
36 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
37 * httpDelete() - Send a DELETE request to the server.
38 * httpEncryption() - Set the required encryption on the link.
39 * httpError() - Get the last error on a connection.
40 * httpFlush() - Flush data from a HTTP connection.
41 * httpFlushWrite() - Flush data in write buffer.
42 * httpGet() - Send a GET request to the server.
43 * httpGetBlocking() - Get the blocking/non-block state of a connection.
44 * httpGetCookie() - Get any cookie data from the response.
45 * httpGetFd() - Get the file descriptor associated with a
46 * connection.
47 * httpGetField() - Get a field value from a request/response.
48 * httpGetLength() - Get the amount of data remaining from the
49 * content-length or transfer-encoding fields.
50 * httpGetLength2() - Get the amount of data remaining from the
51 * content-length or transfer-encoding fields.
52 * httpGetStatus() - Get the status of the last HTTP request.
53 * httpGetSubField() - Get a sub-field value.
54 * httpGets() - Get a line of text from a HTTP connection.
55 * httpHead() - Send a HEAD request to the server.
56 * httpInitialize() - Initialize the HTTP interface library and set the
57 * default HTTP proxy (if any).
58 * httpOptions() - Send an OPTIONS request to the server.
59 * httpPost() - Send a POST request to the server.
60 * httpPrintf() - Print a formatted string to a HTTP connection.
61 * httpPut() - Send a PUT request to the server.
62 * httpRead() - Read data from a HTTP connection.
63 * httpRead2() - Read data from a HTTP connection.
64 * _httpReadCDSA() - Read function for the CDSA library.
65 * _httpReadGNUTLS() - Read function for the GNU TLS library.
66 * httpReconnect() - Reconnect to a HTTP server...
67 * httpSetCookie() - Set the cookie value(s)...
68 * httpSetExpect() - Set the Expect: header in a request.
69 * httpSetField() - Set the value of an HTTP header.
70 * httpSetLength() - Set the content-length and transfer-encoding.
71 * httpTrace() - Send an TRACE request to the server.
72 * httpUpdate() - Update the current HTTP state for incoming data.
73 * httpWait() - Wait for data available on a connection.
74 * httpWrite() - Write data to a HTTP connection.
75 * httpWrite2() - Write data to a HTTP connection.
76 * _httpWriteCDSA() - Write function for the CDSA library.
77 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
78 * http_bio_ctrl() - Control the HTTP connection.
79 * http_bio_free() - Free OpenSSL data.
80 * http_bio_new() - Initialize an OpenSSL BIO structure.
81 * http_bio_puts() - Send a string for OpenSSL.
82 * http_bio_read() - Read data for OpenSSL.
83 * http_bio_write() - Write data for OpenSSL.
84 * http_field() - Return the field index for a field name.
85 * http_read_ssl() - Read from a SSL/TLS connection.
86 * http_send() - Send a request with all fields and the trailing
87 * blank line.
88 * http_setup_ssl() - Set up SSL/TLS on a connection.
89 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
90 * http_upgrade() - Force upgrade to TLS encryption.
91 * http_wait() - Wait for data available on a connection.
92 * http_write() - Write data to a connection.
93 * http_write_ssl() - Write to a SSL/TLS connection.
94 */
95
96 /*
97 * Include necessary headers...
98 */
99
100 #include "http-private.h"
101 #include "globals.h"
102 #include "debug.h"
103 #include <stdlib.h>
104 #include <fcntl.h>
105 #include <errno.h>
106 #ifndef WIN32
107 # include <signal.h>
108 # include <sys/time.h>
109 # include <sys/resource.h>
110 #endif /* !WIN32 */
111
112
113 /*
114 * Some operating systems have done away with the Fxxxx constants for
115 * the fcntl() call; this works around that "feature"...
116 */
117
118 #ifndef FNONBLK
119 # define FNONBLK O_NONBLOCK
120 #endif /* !FNONBLK */
121
122
123 /*
124 * Local functions...
125 */
126
127 static http_field_t http_field(const char *name);
128 static int http_send(http_t *http, http_state_t request,
129 const char *uri);
130 static int http_wait(http_t *http, int msec, int usessl);
131 static int http_write(http_t *http, const char *buffer,
132 int length);
133 static int http_write_chunk(http_t *http, const char *buffer,
134 int length);
135 #ifdef HAVE_SSL
136 static int http_read_ssl(http_t *http, char *buf, int len);
137 static int http_setup_ssl(http_t *http);
138 static void http_shutdown_ssl(http_t *http);
139 static int http_upgrade(http_t *http);
140 static int http_write_ssl(http_t *http, const char *buf, int len);
141 #endif /* HAVE_SSL */
142
143
144 /*
145 * Local globals...
146 */
147
148 static const char * const http_fields[] =
149 {
150 "Accept-Language",
151 "Accept-Ranges",
152 "Authorization",
153 "Connection",
154 "Content-Encoding",
155 "Content-Language",
156 "Content-Length",
157 "Content-Location",
158 "Content-MD5",
159 "Content-Range",
160 "Content-Type",
161 "Content-Version",
162 "Date",
163 "Host",
164 "If-Modified-Since",
165 "If-Unmodified-since",
166 "Keep-Alive",
167 "Last-Modified",
168 "Link",
169 "Location",
170 "Range",
171 "Referer",
172 "Retry-After",
173 "Transfer-Encoding",
174 "Upgrade",
175 "User-Agent",
176 "WWW-Authenticate"
177 };
178
179
180 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
181 /*
182 * BIO methods for OpenSSL...
183 */
184
185 static int http_bio_write(BIO *h, const char *buf, int num);
186 static int http_bio_read(BIO *h, char *buf, int size);
187 static int http_bio_puts(BIO *h, const char *str);
188 static long http_bio_ctrl(BIO *h, int cmd, long arg1, void *arg2);
189 static int http_bio_new(BIO *h);
190 static int http_bio_free(BIO *data);
191
192 static BIO_METHOD http_bio_methods =
193 {
194 BIO_TYPE_SOCKET,
195 "http",
196 http_bio_write,
197 http_bio_read,
198 http_bio_puts,
199 NULL, /* http_bio_gets, */
200 http_bio_ctrl,
201 http_bio_new,
202 http_bio_free,
203 NULL,
204 };
205
206
207 /*
208 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
209 */
210
211 BIO_METHOD * /* O - BIO methods for OpenSSL */
212 _httpBIOMethods(void)
213 {
214 return (&http_bio_methods);
215 }
216 #endif /* HAVE_SSL && HAVE_LIBSSL */
217
218
219 /*
220 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
221 */
222
223 void
224 httpBlocking(http_t *http, /* I - HTTP connection */
225 int b) /* I - 1 = blocking, 0 = non-blocking */
226 {
227 if (http)
228 http->blocking = b;
229 }
230
231
232 /*
233 * 'httpCheck()' - Check to see if there is a pending response from the server.
234 */
235
236 int /* O - 0 = no data, 1 = data available */
237 httpCheck(http_t *http) /* I - HTTP connection */
238 {
239 return (httpWait(http, 0));
240 }
241
242
243 /*
244 * 'httpClearCookie()' - Clear the cookie value(s).
245 *
246 * @since CUPS 1.1.19@
247 */
248
249 void
250 httpClearCookie(http_t *http) /* I - HTTP connection */
251 {
252 if (!http)
253 return;
254
255 if (http->cookie)
256 {
257 free(http->cookie);
258 http->cookie = NULL;
259 }
260 }
261
262
263 /*
264 * 'httpClearFields()' - Clear HTTP request fields.
265 */
266
267 void
268 httpClearFields(http_t *http) /* I - HTTP connection */
269 {
270 if (http)
271 {
272 memset(http->fields, 0, sizeof(http->fields));
273 if (http->hostname[0] == '/')
274 httpSetField(http, HTTP_FIELD_HOST, "localhost");
275 else
276 httpSetField(http, HTTP_FIELD_HOST, http->hostname);
277
278 http->expect = (http_status_t)0;
279 }
280 }
281
282
283 /*
284 * 'httpClose()' - Close an HTTP connection...
285 */
286
287 void
288 httpClose(http_t *http) /* I - HTTP connection */
289 {
290 DEBUG_printf(("httpClose(http=%p)\n", http));
291
292 if (!http)
293 return;
294
295 httpAddrFreeList(http->addrlist);
296
297 if (http->input_set)
298 free(http->input_set);
299
300 if (http->cookie)
301 free(http->cookie);
302
303 #ifdef HAVE_SSL
304 if (http->tls)
305 http_shutdown_ssl(http);
306 #endif /* HAVE_SSL */
307
308 #ifdef WIN32
309 closesocket(http->fd);
310 #else
311 close(http->fd);
312 #endif /* WIN32 */
313
314 free(http);
315 }
316
317
318 /*
319 * 'httpConnect()' - Connect to a HTTP server.
320 */
321
322 http_t * /* O - New HTTP connection */
323 httpConnect(const char *host, /* I - Host to connect to */
324 int port) /* I - Port number */
325 {
326 http_encryption_t encryption; /* Type of encryption to use */
327
328
329 /*
330 * Set the default encryption status...
331 */
332
333 if (port == 443)
334 encryption = HTTP_ENCRYPT_ALWAYS;
335 else
336 encryption = HTTP_ENCRYPT_IF_REQUESTED;
337
338 return (httpConnectEncrypt(host, port, encryption));
339 }
340
341
342 /*
343 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
344 */
345
346 http_t * /* O - New HTTP connection */
347 httpConnectEncrypt(
348 const char *host, /* I - Host to connect to */
349 int port, /* I - Port number */
350 http_encryption_t encryption) /* I - Type of encryption to use */
351 {
352 http_t *http; /* New HTTP connection */
353 http_addrlist_t *addrlist; /* Host address data */
354 char service[255]; /* Service name */
355
356
357 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)\n",
358 host ? host : "(null)", port, encryption));
359
360 if (!host)
361 return (NULL);
362
363 httpInitialize();
364
365 /*
366 * Lookup the host...
367 */
368
369 sprintf(service, "%d", port);
370
371 if ((addrlist = httpAddrGetList(host, AF_UNSPEC, service)) == NULL)
372 return (NULL);
373
374 /*
375 * Allocate memory for the structure...
376 */
377
378 http = calloc(sizeof(http_t), 1);
379 if (http == NULL)
380 return (NULL);
381
382 http->version = HTTP_1_1;
383 http->blocking = 1;
384 http->activity = time(NULL);
385 http->fd = -1;
386
387 /*
388 * Set the encryption status...
389 */
390
391 if (port == 443) /* Always use encryption for https */
392 http->encryption = HTTP_ENCRYPT_ALWAYS;
393 else
394 http->encryption = encryption;
395
396 /*
397 * Loop through the addresses we have until one of them connects...
398 */
399
400 strlcpy(http->hostname, host, sizeof(http->hostname));
401
402 /*
403 * Connect to the remote system...
404 */
405
406 http->addrlist = addrlist;
407
408 if (!httpReconnect(http))
409 return (http);
410
411 /*
412 * Could not connect to any known address - bail out!
413 */
414
415 httpAddrFreeList(addrlist);
416
417 free(http);
418
419 return (NULL);
420 }
421
422
423 /*
424 * 'httpDelete()' - Send a DELETE request to the server.
425 */
426
427 int /* O - Status of call (0 = success) */
428 httpDelete(http_t *http, /* I - HTTP connection */
429 const char *uri) /* I - URI to delete */
430 {
431 return (http_send(http, HTTP_DELETE, uri));
432 }
433
434
435 /*
436 * 'httpEncryption()' - Set the required encryption on the link.
437 */
438
439 int /* O - -1 on error, 0 on success */
440 httpEncryption(http_t *http, /* I - HTTP connection */
441 http_encryption_t e) /* I - New encryption preference */
442 {
443 DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", http, e));
444
445 #ifdef HAVE_SSL
446 if (!http)
447 return (0);
448
449 http->encryption = e;
450
451 if ((http->encryption == HTTP_ENCRYPT_ALWAYS && !http->tls) ||
452 (http->encryption == HTTP_ENCRYPT_NEVER && http->tls))
453 return (httpReconnect(http));
454 else if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
455 return (http_upgrade(http));
456 else
457 return (0);
458 #else
459 if (e == HTTP_ENCRYPT_ALWAYS || e == HTTP_ENCRYPT_REQUIRED)
460 return (-1);
461 else
462 return (0);
463 #endif /* HAVE_SSL */
464 }
465
466
467 /*
468 * 'httpError()' - Get the last error on a connection.
469 */
470
471 int /* O - Error code (errno) value */
472 httpError(http_t *http) /* I - HTTP connection */
473 {
474 if (http)
475 return (http->error);
476 else
477 return (EINVAL);
478 }
479
480
481 /*
482 * 'httpFlush()' - Flush data from a HTTP connection.
483 */
484
485 void
486 httpFlush(http_t *http) /* I - HTTP connection */
487 {
488 char buffer[8192]; /* Junk buffer */
489 int blocking; /* To block or not to block */
490
491
492 DEBUG_printf(("httpFlush(http=%p), state=%d\n", http, http->state));
493
494 /*
495 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
496 */
497
498 blocking = http->blocking;
499 http->blocking = 0;
500
501 /*
502 * Read any data we can...
503 */
504
505 while (httpRead2(http, buffer, sizeof(buffer)) > 0);
506
507 /*
508 * Restore blocking and reset the connection if we didn't get all of
509 * the remaining data...
510 */
511
512 http->blocking = blocking;
513
514 if (http->state != HTTP_WAITING && http->fd >= 0)
515 {
516 /*
517 * Didn't get the data back, so close the current connection.
518 */
519
520 http->state = HTTP_WAITING;
521
522 #ifdef HAVE_SSL
523 if (http->tls)
524 http_shutdown_ssl(http);
525 #endif /* HAVE_SSL */
526
527 #ifdef WIN32
528 closesocket(http->fd);
529 #else
530 close(http->fd);
531 #endif /* WIN32 */
532
533 http->fd = -1;
534 }
535 }
536
537
538 /*
539 * 'httpFlushWrite()' - Flush data in write buffer.
540 *
541 * @since CUPS 1.2@
542 */
543
544 int /* O - Bytes written or -1 on error */
545 httpFlushWrite(http_t *http) /* I - HTTP connection */
546 {
547 int bytes; /* Bytes written */
548
549
550 DEBUG_printf(("httpFlushWrite(http=%p)\n", http));
551
552 if (!http || !http->wused)
553 return (0);
554
555 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
556 bytes = http_write_chunk(http, http->wbuffer, http->wused);
557 else
558 bytes = http_write(http, http->wbuffer, http->wused);
559
560 http->wused = 0;
561
562 return (bytes);
563 }
564
565
566 /*
567 * 'httpGet()' - Send a GET request to the server.
568 */
569
570 int /* O - Status of call (0 = success) */
571 httpGet(http_t *http, /* I - HTTP connection */
572 const char *uri) /* I - URI to get */
573 {
574 return (http_send(http, HTTP_GET, uri));
575 }
576
577
578 /*
579 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
580 *
581 * @since CUPS 1.2@
582 */
583
584 int /* O - 1 if blocking, 0 if non-blocking */
585 httpGetBlocking(http_t *http) /* I - HTTP connection */
586 {
587 return (http ? http->blocking : 0);
588 }
589
590
591 /*
592 * 'httpGetCookie()' - Get any cookie data from the response.
593 *
594 * @since CUPS 1.1.19@
595 */
596
597 const char * /* O - Cookie data or NULL */
598 httpGetCookie(http_t *http) /* I - HTTP connecion */
599 {
600 return (http ? http->cookie : NULL);
601 }
602
603
604 /*
605 * 'httpGetFd()' - Get the file descriptor associated with a connection.
606 *
607 * @since CUPS 1.2@
608 */
609
610 int /* O - File descriptor or -1 if none */
611 httpGetFd(http_t *http) /* I - HTTP connection */
612 {
613 return (http ? http->fd : -1);
614 }
615
616
617 /*
618 * 'httpGetField()' - Get a field value from a request/response.
619 */
620
621 const char * /* O - Field value */
622 httpGetField(http_t *http, /* I - HTTP connection */
623 http_field_t field) /* I - Field to get */
624 {
625 if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
626 return (NULL);
627 else
628 return (http->fields[field]);
629 }
630
631
632 /*
633 * 'httpGetLength()' - Get the amount of data remaining from the
634 * content-length or transfer-encoding fields.
635 *
636 * This function is deprecated and will not return lengths larger than
637 * 2^31 - 1; use httpGetLength2() instead.
638 *
639 * @deprecated@
640 */
641
642 int /* O - Content length */
643 httpGetLength(http_t *http) /* I - HTTP connection */
644 {
645 /*
646 * Get the read content length and return the 32-bit value.
647 */
648
649 if (http)
650 {
651 httpGetLength2(http);
652
653 return (http->_data_remaining);
654 }
655 else
656 return (-1);
657 }
658
659
660 /*
661 * 'httpGetLength2()' - Get the amount of data remaining from the
662 * content-length or transfer-encoding fields.
663 *
664 * This function returns the complete content length, even for
665 * content larger than 2^31 - 1.
666 *
667 * @since CUPS 1.2@
668 */
669
670 off_t /* O - Content length */
671 httpGetLength2(http_t *http) /* I - HTTP connection */
672 {
673 DEBUG_printf(("httpGetLength2(http=%p), state=%d\n", http, http->state));
674
675 if (!http)
676 return (-1);
677
678 if (!strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked"))
679 {
680 DEBUG_puts("httpGetLength2: chunked request!");
681
682 http->data_encoding = HTTP_ENCODE_CHUNKED;
683 http->data_remaining = 0;
684 }
685 else
686 {
687 http->data_encoding = HTTP_ENCODE_LENGTH;
688
689 /*
690 * The following is a hack for HTTP servers that don't send a
691 * content-length or transfer-encoding field...
692 *
693 * If there is no content-length then the connection must close
694 * after the transfer is complete...
695 */
696
697 if (!http->fields[HTTP_FIELD_CONTENT_LENGTH][0])
698 {
699 /*
700 * Default content length is 0 for errors and 2^31-1 for other
701 * successful requests...
702 */
703
704 if (http->status >= HTTP_MULTIPLE_CHOICES)
705 http->data_remaining = 0;
706 else
707 http->data_remaining = 2147483647;
708 }
709 else
710 http->data_remaining = strtoll(http->fields[HTTP_FIELD_CONTENT_LENGTH],
711 NULL, 10);
712
713 DEBUG_printf(("httpGetLength2: content_length=" CUPS_LLFMT "\n",
714 CUPS_LLCAST http->data_remaining));
715 }
716
717 if (http->data_remaining <= INT_MAX)
718 http->_data_remaining = (int)http->data_remaining;
719 else
720 http->_data_remaining = INT_MAX;
721
722 return (http->data_remaining);
723 }
724
725
726 /*
727 * 'httpGetStatus()' - Get the status of the last HTTP request.
728 *
729 * @since CUPS 1.2@
730 */
731
732 http_status_t /* O - HTTP status */
733 httpGetStatus(http_t *http) /* I - HTTP connection */
734 {
735 return (http ? http->status : HTTP_ERROR);
736 }
737
738
739 /*
740 * 'httpGetSubField()' - Get a sub-field value.
741 *
742 * @deprecated@
743 */
744
745 char * /* O - Value or NULL */
746 httpGetSubField(http_t *http, /* I - HTTP connection */
747 http_field_t field, /* I - Field index */
748 const char *name, /* I - Name of sub-field */
749 char *value) /* O - Value string */
750 {
751 return (httpGetSubField2(http, field, name, value, HTTP_MAX_VALUE));
752 }
753
754
755 /*
756 * 'httpGetSubField2()' - Get a sub-field value.
757 *
758 * @since CUPS 1.2@
759 */
760
761 char * /* O - Value or NULL */
762 httpGetSubField2(http_t *http, /* I - HTTP connection */
763 http_field_t field, /* I - Field index */
764 const char *name, /* I - Name of sub-field */
765 char *value, /* O - Value string */
766 int valuelen) /* I - Size of value buffer */
767 {
768 const char *fptr; /* Pointer into field */
769 char temp[HTTP_MAX_VALUE], /* Temporary buffer for name */
770 *ptr, /* Pointer into string buffer */
771 *end; /* End of value buffer */
772
773 DEBUG_printf(("httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)\n",
774 http, field, name, value, valuelen));
775
776 if (!http || !name || !value || valuelen < 2 ||
777 field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
778 return (NULL);
779
780 end = value + valuelen - 1;
781
782 for (fptr = http->fields[field]; *fptr;)
783 {
784 /*
785 * Skip leading whitespace...
786 */
787
788 while (isspace(*fptr & 255))
789 fptr ++;
790
791 if (*fptr == ',')
792 {
793 fptr ++;
794 continue;
795 }
796
797 /*
798 * Get the sub-field name...
799 */
800
801 for (ptr = temp;
802 *fptr && *fptr != '=' && !isspace(*fptr & 255) &&
803 ptr < (temp + sizeof(temp) - 1);
804 *ptr++ = *fptr++);
805
806 *ptr = '\0';
807
808 DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp));
809
810 /*
811 * Skip trailing chars up to the '='...
812 */
813
814 while (isspace(*fptr & 255))
815 fptr ++;
816
817 if (!*fptr)
818 break;
819
820 if (*fptr != '=')
821 continue;
822
823 /*
824 * Skip = and leading whitespace...
825 */
826
827 fptr ++;
828
829 while (isspace(*fptr & 255))
830 fptr ++;
831
832 if (*fptr == '\"')
833 {
834 /*
835 * Read quoted string...
836 */
837
838 for (ptr = value, fptr ++;
839 *fptr && *fptr != '\"' && ptr < end;
840 *ptr++ = *fptr++);
841
842 *ptr = '\0';
843
844 while (*fptr && *fptr != '\"')
845 fptr ++;
846
847 if (*fptr)
848 fptr ++;
849 }
850 else
851 {
852 /*
853 * Read unquoted string...
854 */
855
856 for (ptr = value;
857 *fptr && !isspace(*fptr & 255) && *fptr != ',' && ptr < end;
858 *ptr++ = *fptr++);
859
860 *ptr = '\0';
861
862 while (*fptr && !isspace(*fptr & 255) && *fptr != ',')
863 fptr ++;
864 }
865
866 DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value));
867
868 /*
869 * See if this is the one...
870 */
871
872 if (!strcmp(name, temp))
873 return (value);
874 }
875
876 value[0] = '\0';
877
878 return (NULL);
879 }
880
881
882 /*
883 * 'httpGets()' - Get a line of text from a HTTP connection.
884 */
885
886 char * /* O - Line or NULL */
887 httpGets(char *line, /* I - Line to read into */
888 int length, /* I - Max length of buffer */
889 http_t *http) /* I - HTTP connection */
890 {
891 char *lineptr, /* Pointer into line */
892 *lineend, /* End of line */
893 *bufptr, /* Pointer into input buffer */
894 *bufend; /* Pointer to end of buffer */
895 int bytes, /* Number of bytes read */
896 eol; /* End-of-line? */
897
898
899 DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line, length, http));
900
901 if (http == NULL || line == NULL)
902 return (NULL);
903
904 /*
905 * Read a line from the buffer...
906 */
907
908 lineptr = line;
909 lineend = line + length - 1;
910 eol = 0;
911
912 while (lineptr < lineend)
913 {
914 /*
915 * Pre-load the buffer as needed...
916 */
917
918 #ifdef WIN32
919 WSASetLastError(0);
920 #else
921 errno = 0;
922 #endif /* WIN32 */
923
924 while (http->used == 0)
925 {
926 /*
927 * No newline; see if there is more data to be read...
928 */
929
930 if (!http->blocking && !http_wait(http, 10000, 1))
931 {
932 DEBUG_puts("httpGets: Timed out!");
933 #ifdef WIN32
934 http->error = WSAETIMEDOUT;
935 #else
936 http->error = ETIMEDOUT;
937 #endif /* WIN32 */
938 return (NULL);
939 }
940
941 #ifdef HAVE_SSL
942 if (http->tls)
943 bytes = http_read_ssl(http, http->buffer + http->used,
944 HTTP_MAX_BUFFER - http->used);
945 else
946 #endif /* HAVE_SSL */
947 bytes = recv(http->fd, http->buffer + http->used,
948 HTTP_MAX_BUFFER - http->used, 0);
949
950 DEBUG_printf(("httpGets: read %d bytes...\n", bytes));
951
952 if (bytes < 0)
953 {
954 /*
955 * Nope, can't get a line this time...
956 */
957
958 #ifdef WIN32
959 if (WSAGetLastError() != http->error)
960 {
961 http->error = WSAGetLastError();
962 continue;
963 }
964
965 DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
966 #else
967 DEBUG_printf(("httpGets: recv() error %d!\n", errno));
968
969 if (errno == EINTR)
970 continue;
971 else if (errno != http->error)
972 {
973 http->error = errno;
974 continue;
975 }
976 #endif /* WIN32 */
977
978 return (NULL);
979 }
980 else if (bytes == 0)
981 {
982 http->error = EPIPE;
983
984 return (NULL);
985 }
986
987 /*
988 * Yup, update the amount used...
989 */
990
991 http->used += bytes;
992 }
993
994 /*
995 * Now copy as much of the current line as possible...
996 */
997
998 for (bufptr = http->buffer, bufend = http->buffer + http->used;
999 lineptr < lineend && bufptr < bufend;)
1000 {
1001 if (*bufptr == 0x0a)
1002 {
1003 eol = 1;
1004 bufptr ++;
1005 break;
1006 }
1007 else if (*bufptr == 0x0d)
1008 bufptr ++;
1009 else
1010 *lineptr++ = *bufptr++;
1011 }
1012
1013 http->used -= (int)(bufptr - http->buffer);
1014 if (http->used > 0)
1015 memmove(http->buffer, bufptr, http->used);
1016
1017 if (eol)
1018 {
1019 /*
1020 * End of line...
1021 */
1022
1023 http->activity = time(NULL);
1024
1025 *lineptr = '\0';
1026
1027 DEBUG_printf(("httpGets: Returning \"%s\"\n", line));
1028
1029 return (line);
1030 }
1031 }
1032
1033 DEBUG_puts("httpGets: No new line available!");
1034
1035 return (NULL);
1036 }
1037
1038
1039 /*
1040 * 'httpHead()' - Send a HEAD request to the server.
1041 */
1042
1043 int /* O - Status of call (0 = success) */
1044 httpHead(http_t *http, /* I - HTTP connection */
1045 const char *uri) /* I - URI for head */
1046 {
1047 return (http_send(http, HTTP_HEAD, uri));
1048 }
1049
1050
1051 /*
1052 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1053 * default HTTP proxy (if any).
1054 */
1055
1056 void
1057 httpInitialize(void)
1058 {
1059 #ifdef HAVE_LIBSSL
1060 # ifndef WIN32
1061 struct timeval curtime; /* Current time in microseconds */
1062 # endif /* !WIN32 */
1063 int i; /* Looping var */
1064 unsigned char data[1024]; /* Seed data */
1065 #endif /* HAVE_LIBSSL */
1066
1067 #ifdef WIN32
1068 WSADATA winsockdata; /* WinSock data */
1069 static int initialized = 0; /* Has WinSock been initialized? */
1070
1071
1072 if (!initialized)
1073 WSAStartup(MAKEWORD(1,1), &winsockdata);
1074 #elif !defined(SO_NOSIGPIPE)
1075 /*
1076 * Ignore SIGPIPE signals...
1077 */
1078
1079 # ifdef HAVE_SIGSET
1080 sigset(SIGPIPE, SIG_IGN);
1081 # elif defined(HAVE_SIGACTION)
1082 struct sigaction action; /* POSIX sigaction data */
1083
1084
1085 memset(&action, 0, sizeof(action));
1086 action.sa_handler = SIG_IGN;
1087 sigaction(SIGPIPE, &action, NULL);
1088 # else
1089 signal(SIGPIPE, SIG_IGN);
1090 # endif /* !SO_NOSIGPIPE */
1091 #endif /* WIN32 */
1092
1093 #ifdef HAVE_GNUTLS
1094 gnutls_global_init();
1095 #endif /* HAVE_GNUTLS */
1096
1097 #ifdef HAVE_LIBSSL
1098 SSL_load_error_strings();
1099 SSL_library_init();
1100
1101 /*
1102 * Using the current time is a dubious random seed, but on some systems
1103 * it is the best we can do (on others, this seed isn't even used...)
1104 */
1105
1106 #ifdef WIN32
1107 #else
1108 gettimeofday(&curtime, NULL);
1109 srand(curtime.tv_sec + curtime.tv_usec);
1110 #endif /* WIN32 */
1111
1112 for (i = 0; i < sizeof(data); i ++)
1113 data[i] = rand(); /* Yes, this is a poor source of random data... */
1114
1115 RAND_seed(&data, sizeof(data));
1116 #endif /* HAVE_LIBSSL */
1117 }
1118
1119
1120 /*
1121 * 'httpOptions()' - Send an OPTIONS request to the server.
1122 */
1123
1124 int /* O - Status of call (0 = success) */
1125 httpOptions(http_t *http, /* I - HTTP connection */
1126 const char *uri) /* I - URI for options */
1127 {
1128 return (http_send(http, HTTP_OPTIONS, uri));
1129 }
1130
1131
1132 /*
1133 * 'httpPost()' - Send a POST request to the server.
1134 */
1135
1136 int /* O - Status of call (0 = success) */
1137 httpPost(http_t *http, /* I - HTTP connection */
1138 const char *uri) /* I - URI for post */
1139 {
1140 return (http_send(http, HTTP_POST, uri));
1141 }
1142
1143
1144 /*
1145 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1146 *
1147 * @private@
1148 */
1149
1150 int /* O - Number of bytes written */
1151 httpPrintf(http_t *http, /* I - HTTP connection */
1152 const char *format, /* I - printf-style format string */
1153 ...) /* I - Additional args as needed */
1154 {
1155 int bytes; /* Number of bytes to write */
1156 char buf[16384]; /* Buffer for formatted string */
1157 va_list ap; /* Variable argument pointer */
1158
1159
1160 DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http, format));
1161
1162 va_start(ap, format);
1163 bytes = vsnprintf(buf, sizeof(buf), format, ap);
1164 va_end(ap);
1165
1166 DEBUG_printf(("httpPrintf: %s", buf));
1167
1168 if (http->data_encoding == HTTP_ENCODE_FIELDS)
1169 return (httpWrite2(http, buf, bytes));
1170 else
1171 {
1172 if (http->wused)
1173 {
1174 DEBUG_puts(" flushing existing data...");
1175
1176 if (httpFlushWrite(http) < 0)
1177 return (-1);
1178 }
1179
1180 return (http_write(http, buf, bytes));
1181 }
1182 }
1183
1184
1185 /*
1186 * 'httpPut()' - Send a PUT request to the server.
1187 */
1188
1189 int /* O - Status of call (0 = success) */
1190 httpPut(http_t *http, /* I - HTTP connection */
1191 const char *uri) /* I - URI to put */
1192 {
1193 return (http_send(http, HTTP_PUT, uri));
1194 }
1195
1196
1197 /*
1198 * 'httpRead()' - Read data from a HTTP connection.
1199 *
1200 * This function is deprecated. Use the httpRead2() function which can
1201 * read more than 2GB of data.
1202 *
1203 * @deprecated@
1204 */
1205
1206 int /* O - Number of bytes read */
1207 httpRead(http_t *http, /* I - HTTP connection */
1208 char *buffer, /* I - Buffer for data */
1209 int length) /* I - Maximum number of bytes */
1210 {
1211 return ((int)httpRead2(http, buffer, length));
1212 }
1213
1214
1215 /*
1216 * 'httpRead2()' - Read data from a HTTP connection.
1217 *
1218 * @since CUPS 1.2@
1219 */
1220
1221 ssize_t /* O - Number of bytes read */
1222 httpRead2(http_t *http, /* I - HTTP connection */
1223 char *buffer, /* I - Buffer for data */
1224 size_t length) /* I - Maximum number of bytes */
1225 {
1226 ssize_t bytes; /* Bytes read */
1227 char len[32]; /* Length string */
1228
1229
1230 DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
1231 http, buffer, length));
1232
1233 if (http == NULL || buffer == NULL)
1234 return (-1);
1235
1236 http->activity = time(NULL);
1237
1238 if (length <= 0)
1239 return (0);
1240
1241 if (http->data_encoding == HTTP_ENCODE_CHUNKED &&
1242 http->data_remaining <= 0)
1243 {
1244 DEBUG_puts("httpRead2: Getting chunk length...");
1245
1246 if (httpGets(len, sizeof(len), http) == NULL)
1247 {
1248 DEBUG_puts("httpRead2: Could not get length!");
1249 return (0);
1250 }
1251
1252 http->data_remaining = strtoll(len, NULL, 16);
1253 if (http->data_remaining < 0)
1254 {
1255 DEBUG_puts("httpRead2: Negative chunk length!");
1256 return (0);
1257 }
1258 }
1259
1260 DEBUG_printf(("httpRead2: data_remaining=" CUPS_LLFMT "\n",
1261 CUPS_LLCAST http->data_remaining));
1262
1263 if (http->data_remaining <= 0)
1264 {
1265 /*
1266 * A zero-length chunk ends a transfer; unless we are reading POST
1267 * data, go idle...
1268 */
1269
1270 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
1271 httpGets(len, sizeof(len), http);
1272
1273 if (http->state == HTTP_POST_RECV)
1274 http->state ++;
1275 else
1276 http->state = HTTP_WAITING;
1277
1278 /*
1279 * Prevent future reads for this request...
1280 */
1281
1282 http->data_encoding = HTTP_ENCODE_LENGTH;
1283
1284 return (0);
1285 }
1286 else if (length > (size_t)http->data_remaining)
1287 length = (size_t)http->data_remaining;
1288
1289 if (http->used == 0 && length <= 256)
1290 {
1291 /*
1292 * Buffer small reads for better performance...
1293 */
1294
1295 if (!http->blocking && !httpWait(http, 10000))
1296 return (0);
1297
1298 if (http->data_remaining > sizeof(http->buffer))
1299 bytes = sizeof(http->buffer);
1300 else
1301 bytes = http->data_remaining;
1302
1303 #ifdef HAVE_SSL
1304 if (http->tls)
1305 bytes = http_read_ssl(http, http->buffer, bytes);
1306 else
1307 #endif /* HAVE_SSL */
1308 {
1309 DEBUG_printf(("httpRead2: reading %d bytes from socket into buffer...\n",
1310 bytes));
1311
1312 bytes = recv(http->fd, http->buffer, bytes, 0);
1313
1314 DEBUG_printf(("httpRead2: read %d bytes from socket into buffer...\n",
1315 bytes));
1316 }
1317
1318 if (bytes > 0)
1319 http->used = bytes;
1320 else if (bytes < 0)
1321 {
1322 #ifdef WIN32
1323 http->error = WSAGetLastError();
1324 return (-1);
1325 #else
1326 if (errno != EINTR)
1327 {
1328 http->error = errno;
1329 return (-1);
1330 }
1331 #endif /* WIN32 */
1332 }
1333 else
1334 {
1335 http->error = EPIPE;
1336 return (0);
1337 }
1338 }
1339
1340 if (http->used > 0)
1341 {
1342 if (length > (size_t)http->used)
1343 length = (size_t)http->used;
1344
1345 bytes = (ssize_t)length;
1346
1347 DEBUG_printf(("httpRead2: grabbing %d bytes from input buffer...\n", bytes));
1348
1349 memcpy(buffer, http->buffer, length);
1350 http->used -= (int)length;
1351
1352 if (http->used > 0)
1353 memmove(http->buffer, http->buffer + length, http->used);
1354 }
1355 #ifdef HAVE_SSL
1356 else if (http->tls)
1357 {
1358 if (!http->blocking && !httpWait(http, 10000))
1359 return (0);
1360
1361 bytes = (ssize_t)http_read_ssl(http, buffer, (int)length);
1362 }
1363 #endif /* HAVE_SSL */
1364 else
1365 {
1366 if (!http->blocking && !httpWait(http, 10000))
1367 return (0);
1368
1369 DEBUG_printf(("httpRead2: reading %d bytes from socket...\n", length));
1370
1371 #ifdef WIN32
1372 bytes = (ssize_t)recv(http->fd, buffer, (int)length, 0);
1373 #else
1374 while ((bytes = recv(http->fd, buffer, length, 0)) < 0)
1375 if (errno != EINTR)
1376 break;
1377 #endif /* WIN32 */
1378
1379 DEBUG_printf(("httpRead2: read %d bytes from socket...\n", bytes));
1380 }
1381
1382 if (bytes > 0)
1383 {
1384 http->data_remaining -= bytes;
1385
1386 if (http->data_remaining <= INT_MAX)
1387 http->_data_remaining = (int)http->data_remaining;
1388 else
1389 http->_data_remaining = INT_MAX;
1390 }
1391 else if (bytes < 0)
1392 {
1393 #ifdef WIN32
1394 http->error = WSAGetLastError();
1395 #else
1396 if (errno == EINTR)
1397 bytes = 0;
1398 else
1399 http->error = errno;
1400 #endif /* WIN32 */
1401 }
1402 else
1403 {
1404 http->error = EPIPE;
1405 return (0);
1406 }
1407
1408 if (http->data_remaining == 0)
1409 {
1410 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
1411 httpGets(len, sizeof(len), http);
1412
1413 if (http->data_encoding != HTTP_ENCODE_CHUNKED)
1414 {
1415 if (http->state == HTTP_POST_RECV)
1416 http->state ++;
1417 else
1418 http->state = HTTP_WAITING;
1419 }
1420 }
1421
1422 #ifdef DEBUG
1423 {
1424 int i, j, ch;
1425 printf("httpRead2: Read %d bytes:\n", bytes);
1426 for (i = 0; i < bytes; i += 16)
1427 {
1428 printf(" ");
1429
1430 for (j = 0; j < 16 && (i + j) < bytes; j ++)
1431 printf(" %02X", buffer[i + j] & 255);
1432
1433 while (j < 16)
1434 {
1435 printf(" ");
1436 j ++;
1437 }
1438
1439 printf(" ");
1440 for (j = 0; j < 16 && (i + j) < bytes; j ++)
1441 {
1442 ch = buffer[i + j] & 255;
1443
1444 if (ch < ' ' || ch >= 127)
1445 ch = '.';
1446
1447 putchar(ch);
1448 }
1449 putchar('\n');
1450 }
1451 }
1452 #endif /* DEBUG */
1453
1454 return (bytes);
1455 }
1456
1457
1458 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
1459 /*
1460 * '_httpReadCDSA()' - Read function for the CDSA library.
1461 */
1462
1463 OSStatus /* O - -1 on error, 0 on success */
1464 _httpReadCDSA(
1465 SSLConnectionRef connection, /* I - SSL/TLS connection */
1466 void *data, /* I - Data buffer */
1467 size_t *dataLength) /* IO - Number of bytes */
1468 {
1469 OSStatus result; /* Return value */
1470 ssize_t bytes; /* Number of bytes read */
1471 http_t *http; /* HTTP connection */
1472
1473
1474 http = (http_t *)connection;
1475
1476 if (!http->blocking)
1477 {
1478 /*
1479 * Make sure we have data before we read...
1480 */
1481
1482 if (!http_wait(http, 10000, 0))
1483 {
1484 http->error = ETIMEDOUT;
1485 return (-1);
1486 }
1487 }
1488
1489 do
1490 {
1491 bytes = recv(http->fd, data, *dataLength, 0);
1492 }
1493 while (bytes == -1 && errno == EINTR);
1494
1495 if (bytes == *dataLength)
1496 {
1497 result = 0;
1498 }
1499 else if (bytes > 0)
1500 {
1501 *dataLength = bytes;
1502 result = errSSLWouldBlock;
1503 }
1504 else
1505 {
1506 *dataLength = 0;
1507
1508 if (bytes == 0)
1509 result = errSSLClosedGraceful;
1510 else if (errno == EAGAIN)
1511 result = errSSLWouldBlock;
1512 else
1513 result = errSSLClosedAbort;
1514 }
1515
1516 return (result);
1517 }
1518 #endif /* HAVE_SSL && HAVE_CDSASSL */
1519
1520
1521 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
1522 /*
1523 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
1524 */
1525
1526 ssize_t /* O - Number of bytes read or -1 on error */
1527 _httpReadGNUTLS(
1528 gnutls_transport_ptr ptr, /* I - HTTP connection */
1529 void *data, /* I - Buffer */
1530 size_t length) /* I - Number of bytes to read */
1531 {
1532 http_t *http; /* HTTP connection */
1533
1534
1535 http = (http_t *)ptr;
1536
1537 if (!http->blocking)
1538 {
1539 /*
1540 * Make sure we have data before we read...
1541 */
1542
1543 if (!http_wait(http, 10000, 0))
1544 {
1545 http->error = ETIMEDOUT;
1546 return (-1);
1547 }
1548 }
1549
1550 return (recv(http->fd, data, length, 0));
1551 }
1552 #endif /* HAVE_SSL && HAVE_GNUTLS */
1553
1554
1555 /*
1556 * 'httpReconnect()' - Reconnect to a HTTP server.
1557 */
1558
1559 int /* O - 0 on success, non-zero on failure */
1560 httpReconnect(http_t *http) /* I - HTTP connection */
1561 {
1562 http_addrlist_t *addr; /* Connected address */
1563
1564
1565 DEBUG_printf(("httpReconnect(http=%p)\n", http));
1566
1567 if (!http)
1568 return (-1);
1569
1570 #ifdef HAVE_SSL
1571 if (http->tls)
1572 http_shutdown_ssl(http);
1573 #endif /* HAVE_SSL */
1574
1575 /*
1576 * Close any previously open socket...
1577 */
1578
1579 if (http->fd >= 0)
1580 {
1581 #ifdef WIN32
1582 closesocket(http->fd);
1583 #else
1584 close(http->fd);
1585 #endif /* WIN32 */
1586
1587 http->fd = -1;
1588 }
1589
1590 /*
1591 * Connect to the server...
1592 */
1593
1594 if ((addr = httpAddrConnect(http->addrlist, &(http->fd))) == NULL)
1595 {
1596 /*
1597 * Unable to connect...
1598 */
1599
1600 #ifdef WIN32
1601 http->error = WSAGetLastError();
1602 #else
1603 http->error = errno;
1604 #endif /* WIN32 */
1605 http->status = HTTP_ERROR;
1606
1607 return (-1);
1608 }
1609
1610 http->hostaddr = &(addr->addr);
1611 http->error = 0;
1612 http->status = HTTP_CONTINUE;
1613
1614 #ifdef HAVE_SSL
1615 if (http->encryption == HTTP_ENCRYPT_ALWAYS)
1616 {
1617 /*
1618 * Always do encryption via SSL.
1619 */
1620
1621 if (http_setup_ssl(http) != 0)
1622 {
1623 #ifdef WIN32
1624 closesocket(http->fd);
1625 #else
1626 close(http->fd);
1627 #endif /* WIN32 */
1628
1629 return (-1);
1630 }
1631 }
1632 else if (http->encryption == HTTP_ENCRYPT_REQUIRED)
1633 return (http_upgrade(http));
1634 #endif /* HAVE_SSL */
1635
1636 return (0);
1637 }
1638
1639
1640 /*
1641 * 'httpSetCookie()' - Set the cookie value(s)...
1642 *
1643 * @since CUPS 1.1.19@
1644 */
1645
1646 void
1647 httpSetCookie(http_t *http, /* I - Connection */
1648 const char *cookie) /* I - Cookie string */
1649 {
1650 if (!http)
1651 return;
1652
1653 if (http->cookie)
1654 free(http->cookie);
1655
1656 if (cookie)
1657 http->cookie = strdup(cookie);
1658 else
1659 http->cookie = NULL;
1660 }
1661
1662
1663 /*
1664 * 'httpSetExpect()' - Set the Expect: header in a request.
1665 *
1666 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
1667 *
1668 * @since CUPS 1.2@
1669 */
1670
1671 void
1672 httpSetExpect(http_t *http, /* I - HTTP connection */
1673 http_status_t expect) /* I - HTTP status to expect (HTTP_CONTINUE) */
1674 {
1675 if (http)
1676 http->expect = expect;
1677 }
1678
1679
1680 /*
1681 * 'httpSetField()' - Set the value of an HTTP header.
1682 */
1683
1684 void
1685 httpSetField(http_t *http, /* I - HTTP connection */
1686 http_field_t field, /* I - Field index */
1687 const char *value) /* I - Value */
1688 {
1689 if (http == NULL ||
1690 field < HTTP_FIELD_ACCEPT_LANGUAGE ||
1691 field > HTTP_FIELD_WWW_AUTHENTICATE ||
1692 value == NULL)
1693 return;
1694
1695 strlcpy(http->fields[field], value, HTTP_MAX_VALUE);
1696 }
1697
1698
1699 /*
1700 * 'httpSetLength()' - Set the content-length and content-encoding.
1701 *
1702 * @since CUPS 1.2@
1703 */
1704
1705 void
1706 httpSetLength(http_t *http, /* I - HTTP connection */
1707 size_t length) /* I - Length (0 for chunked) */
1708 {
1709 if (!http)
1710 return;
1711
1712 if (!length)
1713 {
1714 strcpy(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked");
1715 http->fields[HTTP_FIELD_CONTENT_LENGTH][0] = '\0';
1716 }
1717 else
1718 {
1719 http->fields[HTTP_FIELD_TRANSFER_ENCODING][0] = '\0';
1720 snprintf(http->fields[HTTP_FIELD_CONTENT_LENGTH], HTTP_MAX_VALUE,
1721 CUPS_LLFMT, CUPS_LLCAST length);
1722 }
1723 }
1724
1725
1726 /*
1727 * 'httpTrace()' - Send an TRACE request to the server.
1728 */
1729
1730 int /* O - Status of call (0 = success) */
1731 httpTrace(http_t *http, /* I - HTTP connection */
1732 const char *uri) /* I - URI for trace */
1733 {
1734 return (http_send(http, HTTP_TRACE, uri));
1735 }
1736
1737
1738 /*
1739 * 'httpUpdate()' - Update the current HTTP state for incoming data.
1740 */
1741
1742 http_status_t /* O - HTTP status */
1743 httpUpdate(http_t *http) /* I - HTTP connection */
1744 {
1745 char line[32768], /* Line from connection... */
1746 *value; /* Pointer to value on line */
1747 http_field_t field; /* Field index */
1748 int major, minor, /* HTTP version numbers */
1749 status; /* Request status */
1750
1751
1752 DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http, http->state));
1753
1754 /*
1755 * Flush pending data, if any...
1756 */
1757
1758 if (http->wused)
1759 {
1760 DEBUG_puts(" flushing buffer...");
1761
1762 if (httpFlushWrite(http) < 0)
1763 return (HTTP_ERROR);
1764 }
1765
1766 /*
1767 * If we haven't issued any commands, then there is nothing to "update"...
1768 */
1769
1770 if (http->state == HTTP_WAITING)
1771 return (HTTP_CONTINUE);
1772
1773 /*
1774 * Grab all of the lines we can from the connection...
1775 */
1776
1777 while (httpGets(line, sizeof(line), http) != NULL)
1778 {
1779 DEBUG_printf(("httpUpdate: Got \"%s\"\n", line));
1780
1781 if (line[0] == '\0')
1782 {
1783 /*
1784 * Blank line means the start of the data section (if any). Return
1785 * the result code, too...
1786 *
1787 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
1788 * Instead, we just return HTTP_CONTINUE to the caller and keep on
1789 * tryin'...
1790 */
1791
1792 if (http->status == HTTP_CONTINUE)
1793 return (http->status);
1794
1795 if (http->status < HTTP_BAD_REQUEST)
1796 http->digest_tries = 0;
1797
1798 #ifdef HAVE_SSL
1799 if (http->status == HTTP_SWITCHING_PROTOCOLS && !http->tls)
1800 {
1801 if (http_setup_ssl(http) != 0)
1802 {
1803 # ifdef WIN32
1804 closesocket(http->fd);
1805 # else
1806 close(http->fd);
1807 # endif /* WIN32 */
1808
1809 return (HTTP_ERROR);
1810 }
1811
1812 return (HTTP_CONTINUE);
1813 }
1814 #endif /* HAVE_SSL */
1815
1816 httpGetLength2(http);
1817
1818 switch (http->state)
1819 {
1820 case HTTP_GET :
1821 case HTTP_POST :
1822 case HTTP_POST_RECV :
1823 case HTTP_PUT :
1824 http->state ++;
1825 case HTTP_POST_SEND :
1826 case HTTP_HEAD :
1827 break;
1828
1829 default :
1830 http->state = HTTP_WAITING;
1831 break;
1832 }
1833
1834 return (http->status);
1835 }
1836 else if (strncmp(line, "HTTP/", 5) == 0)
1837 {
1838 /*
1839 * Got the beginning of a response...
1840 */
1841
1842 if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, &status) != 3)
1843 return (HTTP_ERROR);
1844
1845 http->version = (http_version_t)(major * 100 + minor);
1846 http->status = (http_status_t)status;
1847 }
1848 else if ((value = strchr(line, ':')) != NULL)
1849 {
1850 /*
1851 * Got a value...
1852 */
1853
1854 *value++ = '\0';
1855 while (isspace(*value & 255))
1856 value ++;
1857
1858 /*
1859 * Be tolerants of servers that send unknown attribute fields...
1860 */
1861
1862 if (!strcasecmp(line, "expect"))
1863 {
1864 /*
1865 * "Expect: 100-continue" or similar...
1866 */
1867
1868 http->expect = (http_status_t)atoi(value);
1869 }
1870 else if (!strcasecmp(line, "cookie"))
1871 {
1872 /*
1873 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
1874 */
1875
1876 httpSetCookie(http, value);
1877 }
1878 else if ((field = http_field(line)) == HTTP_FIELD_UNKNOWN)
1879 {
1880 DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line));
1881 continue;
1882 }
1883 else
1884 httpSetField(http, field, value);
1885 }
1886 else
1887 {
1888 http->status = HTTP_ERROR;
1889 return (HTTP_ERROR);
1890 }
1891 }
1892
1893 /*
1894 * See if there was an error...
1895 */
1896
1897 if (http->error == EPIPE && http->status > HTTP_CONTINUE)
1898 return (http->status);
1899
1900 if (http->error)
1901 {
1902 DEBUG_printf(("httpUpdate: socket error %d - %s\n", http->error,
1903 strerror(http->error)));
1904 http->status = HTTP_ERROR;
1905 return (HTTP_ERROR);
1906 }
1907
1908 /*
1909 * If we haven't already returned, then there is nothing new...
1910 */
1911
1912 return (HTTP_CONTINUE);
1913 }
1914
1915
1916 /*
1917 * 'httpWait()' - Wait for data available on a connection.
1918 *
1919 * @since CUPS 1.1.19@
1920 */
1921
1922 int /* O - 1 if data is available, 0 otherwise */
1923 httpWait(http_t *http, /* I - HTTP connection */
1924 int msec) /* I - Milliseconds to wait */
1925 {
1926 /*
1927 * First see if there is data in the buffer...
1928 */
1929
1930 if (http == NULL)
1931 return (0);
1932
1933 if (http->used)
1934 return (1);
1935
1936 /*
1937 * Flush pending data, if any...
1938 */
1939
1940 if (http->wused)
1941 {
1942 if (httpFlushWrite(http) < 0)
1943 return (0);
1944 }
1945
1946 /*
1947 * If not, check the SSL/TLS buffers and do a select() on the connection...
1948 */
1949
1950 return (http_wait(http, msec, 1));
1951 }
1952
1953
1954 /*
1955 * 'httpWrite()' - Write data to a HTTP connection.
1956 *
1957 * This function is deprecated. Use the httpWrite2() function which can
1958 * write more than 2GB of data.
1959 *
1960 * @deprecated@
1961 */
1962
1963 int /* O - Number of bytes written */
1964 httpWrite(http_t *http, /* I - HTTP connection */
1965 const char *buffer, /* I - Buffer for data */
1966 int length) /* I - Number of bytes to write */
1967 {
1968 return ((int)httpWrite2(http, buffer, length));
1969 }
1970
1971
1972 /*
1973 * 'httpWrite2()' - Write data to a HTTP connection.
1974 *
1975 * @since CUPS 1.2@
1976 */
1977
1978 ssize_t /* O - Number of bytes written */
1979 httpWrite2(http_t *http, /* I - HTTP connection */
1980 const char *buffer, /* I - Buffer for data */
1981 size_t length) /* I - Number of bytes to write */
1982 {
1983 ssize_t bytes; /* Bytes written */
1984
1985
1986 DEBUG_printf(("httpWrite(http=%p, buffer=%p, length=%d)\n", http,
1987 buffer, length));
1988
1989 /*
1990 * Range check input...
1991 */
1992
1993 if (http == NULL || buffer == NULL)
1994 return (-1);
1995
1996 /*
1997 * Mark activity on the connection...
1998 */
1999
2000 http->activity = time(NULL);
2001
2002 /*
2003 * Buffer small writes for better performance...
2004 */
2005
2006 if (length > 0)
2007 {
2008 if (http->wused && (length + http->wused) > sizeof(http->wbuffer))
2009 {
2010 DEBUG_printf((" flushing buffer (wused=%d, length=%d)\n",
2011 http->wused, length));
2012
2013 httpFlushWrite(http);
2014 }
2015
2016 if ((length + http->wused) <= sizeof(http->wbuffer))
2017 {
2018 /*
2019 * Write to buffer...
2020 */
2021
2022 DEBUG_printf((" copying %d bytes to wbuffer...\n", length));
2023
2024 memcpy(http->wbuffer + http->wused, buffer, length);
2025 http->wused += (int)length;
2026 bytes = (ssize_t)length;
2027 }
2028 else
2029 {
2030 /*
2031 * Otherwise write the data directly...
2032 */
2033
2034 DEBUG_printf((" writing %d bytes to socket...\n", length));
2035
2036 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
2037 bytes = (ssize_t)http_write_chunk(http, buffer, (int)length);
2038 else
2039 bytes = (ssize_t)http_write(http, buffer, (int)length);
2040
2041 DEBUG_printf((" wrote %d bytes...\n", bytes));
2042 }
2043
2044 if (http->data_encoding == HTTP_ENCODE_LENGTH)
2045 http->data_remaining -= bytes;
2046 }
2047 else
2048 bytes = 0;
2049
2050 /*
2051 * Handle end-of-request processing...
2052 */
2053
2054 if ((http->data_encoding == HTTP_ENCODE_CHUNKED && length == 0) ||
2055 (http->data_encoding == HTTP_ENCODE_LENGTH && http->data_remaining == 0))
2056 {
2057 /*
2058 * Finished with the transfer; unless we are sending POST or PUT
2059 * data, go idle...
2060 */
2061
2062 DEBUG_puts("httpWrite: changing states...");
2063
2064 if (http->wused)
2065 httpFlushWrite(http);
2066
2067 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
2068 {
2069 /*
2070 * Send a 0-length chunk at the end of the request...
2071 */
2072
2073 http_write(http, "0\r\n\r\n", 5);
2074
2075 /*
2076 * Reset the data state...
2077 */
2078
2079 http->data_encoding = HTTP_ENCODE_LENGTH;
2080 http->data_remaining = 0;
2081 }
2082
2083 if (http->state == HTTP_POST_RECV)
2084 http->state ++;
2085 else if (http->state == HTTP_PUT_RECV)
2086 http->state = HTTP_STATUS;
2087 else
2088 http->state = HTTP_WAITING;
2089 }
2090
2091 return (bytes);
2092 }
2093
2094
2095 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2096 /*
2097 * '_httpWriteCDSA()' - Write function for the CDSA library.
2098 */
2099
2100 OSStatus /* O - -1 on error, 0 on success */
2101 _httpWriteCDSA(
2102 SSLConnectionRef connection, /* I - SSL/TLS connection */
2103 const void *data, /* I - Data buffer */
2104 size_t *dataLength) /* IO - Number of bytes */
2105 {
2106 OSStatus result; /* Return value */
2107 ssize_t bytes; /* Number of bytes read */
2108 http_t *http; /* HTTP connection */
2109
2110
2111 http = (http_t *)connection;
2112
2113 do
2114 {
2115 bytes = write(http->fd, data, *dataLength);
2116 }
2117 while (bytes == -1 && errno == EINTR);
2118
2119 if (bytes == *dataLength)
2120 {
2121 result = 0;
2122 }
2123 else if (bytes >= 0)
2124 {
2125 *dataLength = bytes;
2126 result = errSSLWouldBlock;
2127 }
2128 else
2129 {
2130 *dataLength = 0;
2131
2132 if (errno == EAGAIN)
2133 result = errSSLWouldBlock;
2134 else
2135 result = errSSLClosedAbort;
2136 }
2137
2138 return (result);
2139 }
2140 #endif /* HAVE_SSL && HAVE_CDSASSL */
2141
2142
2143 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2144 /*
2145 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
2146 */
2147
2148 ssize_t /* O - Number of bytes written or -1 on error */
2149 _httpWriteGNUTLS(
2150 gnutls_transport_ptr ptr, /* I - HTTP connection */
2151 const void *data, /* I - Data buffer */
2152 size_t length) /* I - Number of bytes to write */
2153 {
2154 return (send(((http_t *)ptr)->fd, data, length, 0));
2155 }
2156 #endif /* HAVE_SSL && HAVE_GNUTLS */
2157
2158
2159 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
2160 /*
2161 * 'http_bio_ctrl()' - Control the HTTP connection.
2162 */
2163
2164 static long /* O - Result/data */
2165 http_bio_ctrl(BIO *h, /* I - BIO data */
2166 int cmd, /* I - Control command */
2167 long arg1, /* I - First argument */
2168 void *arg2) /* I - Second argument */
2169 {
2170 switch (cmd)
2171 {
2172 default :
2173 return (0);
2174
2175 case BIO_CTRL_RESET :
2176 h->ptr = NULL;
2177 return (0);
2178
2179 case BIO_C_SET_FILE_PTR :
2180 h->ptr = arg2;
2181 h->init = 1;
2182 return (1);
2183
2184 case BIO_C_GET_FILE_PTR :
2185 if (arg2)
2186 {
2187 *((void **)arg2) = h->ptr;
2188 return (1);
2189 }
2190 else
2191 return (0);
2192
2193 case BIO_CTRL_DUP :
2194 case BIO_CTRL_FLUSH :
2195 return (1);
2196 }
2197 }
2198
2199
2200 /*
2201 * 'http_bio_free()' - Free OpenSSL data.
2202 */
2203
2204 static int /* O - 1 on success, 0 on failure */
2205 http_bio_free(BIO *h) /* I - BIO data */
2206 {
2207 if (!h)
2208 return (0);
2209
2210 if (h->shutdown)
2211 {
2212 h->init = 0;
2213 h->flags = 0;
2214 }
2215
2216 return (1);
2217 }
2218
2219
2220 /*
2221 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
2222 */
2223
2224 static int /* O - 1 on success, 0 on failure */
2225 http_bio_new(BIO *h) /* I - BIO data */
2226 {
2227 if (!h)
2228 return (0);
2229
2230 h->init = 0;
2231 h->num = 0;
2232 h->ptr = NULL;
2233 h->flags = 0;
2234
2235 return (1);
2236 }
2237
2238
2239 /*
2240 * 'http_bio_puts()' - Send a string for OpenSSL.
2241 */
2242
2243 static int /* O - Bytes written */
2244 http_bio_puts(BIO *h, /* I - BIO data */
2245 const char *str) /* I - String to write */
2246 {
2247 #ifdef WIN32
2248 return (send(((http_t *)h->ptr)->fd, str, (int)strlen(str), 0));
2249 #else
2250 return (send(((http_t *)h->ptr)->fd, str, strlen(str), 0));
2251 #endif /* WIN32 */
2252 }
2253
2254
2255 /*
2256 * 'http_bio_read()' - Read data for OpenSSL.
2257 */
2258
2259 static int /* O - Bytes read */
2260 http_bio_read(BIO *h, /* I - BIO data */
2261 char *buf, /* I - Buffer */
2262 int size) /* I - Number of bytes to read */
2263 {
2264 http_t *http; /* HTTP connection */
2265
2266
2267 http = (http_t *)h->ptr;
2268
2269 if (!http->blocking)
2270 {
2271 /*
2272 * Make sure we have data before we read...
2273 */
2274
2275 if (!http_wait(http, 10000, 0))
2276 {
2277 #ifdef WIN32
2278 http->error = WSAETIMEDOUT;
2279 #else
2280 http->error = ETIMEDOUT;
2281 #endif /* WIN32 */
2282
2283 return (-1);
2284 }
2285 }
2286
2287 return (recv(http->fd, buf, size, 0));
2288 }
2289
2290
2291 /*
2292 * 'http_bio_write()' - Write data for OpenSSL.
2293 */
2294
2295 static int /* O - Bytes written */
2296 http_bio_write(BIO *h, /* I - BIO data */
2297 const char *buf, /* I - Buffer to write */
2298 int num) /* I - Number of bytes to write */
2299 {
2300 return (send(((http_t *)h->ptr)->fd, buf, num, 0));
2301 }
2302 #endif /* HAVE_SSL && HAVE_LIBSSL */
2303
2304
2305 /*
2306 * 'http_field()' - Return the field index for a field name.
2307 */
2308
2309 static http_field_t /* O - Field index */
2310 http_field(const char *name) /* I - String name */
2311 {
2312 int i; /* Looping var */
2313
2314
2315 for (i = 0; i < HTTP_FIELD_MAX; i ++)
2316 if (strcasecmp(name, http_fields[i]) == 0)
2317 return ((http_field_t)i);
2318
2319 return (HTTP_FIELD_UNKNOWN);
2320 }
2321
2322
2323 #ifdef HAVE_SSL
2324 /*
2325 * 'http_read_ssl()' - Read from a SSL/TLS connection.
2326 */
2327
2328 static int /* O - Bytes read */
2329 http_read_ssl(http_t *http, /* I - HTTP connection */
2330 char *buf, /* I - Buffer to store data */
2331 int len) /* I - Length of buffer */
2332 {
2333 # if defined(HAVE_LIBSSL)
2334 return (SSL_read((SSL *)(http->tls), buf, len));
2335
2336 # elif defined(HAVE_GNUTLS)
2337 return (gnutls_record_recv(((http_tls_t *)(http->tls))->session, buf, len));
2338
2339 # elif defined(HAVE_CDSASSL)
2340 int result; /* Return value */
2341 OSStatus error; /* Error info */
2342 size_t processed; /* Number of bytes processed */
2343
2344
2345 error = SSLRead(((http_tls_t *)http->tls)->session, buf, len, &processed);
2346
2347 switch (error)
2348 {
2349 case 0 :
2350 result = (int)processed;
2351 break;
2352 case errSSLClosedGraceful :
2353 result = 0;
2354 break;
2355 case errSSLWouldBlock :
2356 if (processed)
2357 result = (int)processed;
2358 else
2359 {
2360 result = -1;
2361 errno = EINTR;
2362 }
2363 break;
2364 default :
2365 errno = EPIPE;
2366 result = -1;
2367 break;
2368 }
2369
2370 return (result);
2371 # endif /* HAVE_LIBSSL */
2372 }
2373 #endif /* HAVE_SSL */
2374
2375
2376 /*
2377 * 'http_send()' - Send a request with all fields and the trailing blank line.
2378 */
2379
2380 static int /* O - 0 on success, non-zero on error */
2381 http_send(http_t *http, /* I - HTTP connection */
2382 http_state_t request, /* I - Request code */
2383 const char *uri) /* I - URI */
2384 {
2385 int i; /* Looping var */
2386 char *ptr, /* Pointer in buffer */
2387 buf[1024]; /* Encoded URI buffer */
2388 static const char * const codes[] =
2389 { /* Request code strings */
2390 NULL,
2391 "OPTIONS",
2392 "GET",
2393 NULL,
2394 "HEAD",
2395 "POST",
2396 NULL,
2397 NULL,
2398 "PUT",
2399 NULL,
2400 "DELETE",
2401 "TRACE",
2402 "CLOSE"
2403 };
2404 static const char hex[] = "0123456789ABCDEF";
2405 /* Hex digits */
2406
2407
2408 DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
2409 http, codes[request], uri));
2410
2411 if (http == NULL || uri == NULL)
2412 return (-1);
2413
2414 /*
2415 * Set the User-Agent field if it isn't already...
2416 */
2417
2418 if (!http->fields[HTTP_FIELD_USER_AGENT][0])
2419 httpSetField(http, HTTP_FIELD_USER_AGENT, CUPS_MINIMAL);
2420
2421 /*
2422 * Encode the URI as needed...
2423 */
2424
2425 for (ptr = buf; *uri != '\0' && ptr < (buf + sizeof(buf) - 1); uri ++)
2426 if (*uri <= ' ' || *uri >= 127)
2427 {
2428 if (ptr < (buf + sizeof(buf) - 1))
2429 *ptr ++ = '%';
2430 if (ptr < (buf + sizeof(buf) - 1))
2431 *ptr ++ = hex[(*uri >> 4) & 15];
2432 if (ptr < (buf + sizeof(buf) - 1))
2433 *ptr ++ = hex[*uri & 15];
2434 }
2435 else
2436 *ptr ++ = *uri;
2437
2438 *ptr = '\0';
2439
2440 /*
2441 * See if we had an error the last time around; if so, reconnect...
2442 */
2443
2444 if (http->status == HTTP_ERROR || http->status >= HTTP_BAD_REQUEST)
2445 if (httpReconnect(http))
2446 return (-1);
2447
2448 /*
2449 * Flush any written data that is pending...
2450 */
2451
2452 if (http->wused)
2453 httpFlushWrite(http);
2454
2455 /*
2456 * Send the request header...
2457 */
2458
2459 http->state = request;
2460 http->data_encoding = HTTP_ENCODE_FIELDS;
2461
2462 if (request == HTTP_POST || request == HTTP_PUT)
2463 http->state ++;
2464
2465 http->status = HTTP_CONTINUE;
2466
2467 #ifdef HAVE_SSL
2468 if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
2469 {
2470 httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
2471 httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.0,SSL/2.0,SSL/3.0");
2472 }
2473 #endif /* HAVE_SSL */
2474
2475 if (httpPrintf(http, "%s %s HTTP/1.1\r\n", codes[request], buf) < 1)
2476 {
2477 http->status = HTTP_ERROR;
2478 return (-1);
2479 }
2480
2481 for (i = 0; i < HTTP_FIELD_MAX; i ++)
2482 if (http->fields[i][0] != '\0')
2483 {
2484 DEBUG_printf(("%s: %s\n", http_fields[i], http->fields[i]));
2485
2486 if (httpPrintf(http, "%s: %s\r\n", http_fields[i], http->fields[i]) < 1)
2487 {
2488 http->status = HTTP_ERROR;
2489 return (-1);
2490 }
2491 }
2492
2493 if (http->cookie)
2494 if (httpPrintf(http, "Cookie: $Version=0; %s\r\n", http->cookie) < 1)
2495 {
2496 http->status = HTTP_ERROR;
2497 return (-1);
2498 }
2499
2500 if (http->expect == HTTP_CONTINUE &&
2501 (http->state == HTTP_POST_RECV || http->state == HTTP_PUT_RECV))
2502 if (httpPrintf(http, "Expect: 100-continue\r\n") < 1)
2503 {
2504 http->status = HTTP_ERROR;
2505 return (-1);
2506 }
2507
2508 if (httpPrintf(http, "\r\n") < 1)
2509 {
2510 http->status = HTTP_ERROR;
2511 return (-1);
2512 }
2513
2514 httpFlushWrite(http);
2515 httpGetLength2(http);
2516 httpClearFields(http);
2517
2518 return (0);
2519 }
2520
2521
2522 #ifdef HAVE_SSL
2523 /*
2524 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
2525 */
2526
2527 static int /* O - Status of connection */
2528 http_setup_ssl(http_t *http) /* I - HTTP connection */
2529 {
2530 # ifdef HAVE_LIBSSL
2531 SSL_CTX *context; /* Context for encryption */
2532 SSL *conn; /* Connection for encryption */
2533 BIO *bio; /* BIO data */
2534 # elif defined(HAVE_GNUTLS)
2535 http_tls_t *conn; /* TLS session object */
2536 gnutls_certificate_client_credentials *credentials;
2537 /* TLS credentials */
2538 # elif defined(HAVE_CDSASSL)
2539 OSStatus error; /* Error code */
2540 http_tls_t *conn; /* CDSA connection information */
2541 # endif /* HAVE_LIBSSL */
2542
2543
2544 DEBUG_printf(("http_setup_ssl(http=%p)\n", http));
2545
2546 # ifdef HAVE_LIBSSL
2547 context = SSL_CTX_new(SSLv23_client_method());
2548
2549 SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); /* Only use SSLv3 or TLS */
2550
2551 bio = BIO_new(_httpBIOMethods());
2552 BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)http);
2553
2554 conn = SSL_new(context);
2555 SSL_set_bio(conn, bio, bio);
2556
2557 if (SSL_connect(conn) != 1)
2558 {
2559 # ifdef DEBUG
2560 unsigned long error; /* Error code */
2561
2562 while ((error = ERR_get_error()) != 0)
2563 printf("http_setup_ssl: %s\n", ERR_error_string(error, NULL));
2564 # endif /* DEBUG */
2565
2566 SSL_CTX_free(context);
2567 SSL_free(conn);
2568
2569 # ifdef WIN32
2570 http->error = WSAGetLastError();
2571 # else
2572 http->error = errno;
2573 # endif /* WIN32 */
2574 http->status = HTTP_ERROR;
2575
2576 return (HTTP_ERROR);
2577 }
2578
2579 # elif defined(HAVE_GNUTLS)
2580 if ((conn = (http_tls_t *)malloc(sizeof(http_tls_t))) == NULL)
2581 {
2582 http->error = errno;
2583 http->status = HTTP_ERROR;
2584
2585 return (-1);
2586 }
2587
2588 credentials = (gnutls_certificate_client_credentials *)
2589 malloc(sizeof(gnutls_certificate_client_credentials));
2590 if (credentials == NULL)
2591 {
2592 free(conn);
2593
2594 http->error = errno;
2595 http->status = HTTP_ERROR;
2596
2597 return (-1);
2598 }
2599
2600 gnutls_certificate_allocate_credentials(credentials);
2601
2602 gnutls_init(&(conn->session), GNUTLS_CLIENT);
2603 gnutls_set_default_priority(conn->session);
2604 gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
2605 gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr)http);
2606 gnutls_transport_set_pull_function(conn->session, _httpReadGNUTLS);
2607 gnutls_transport_set_push_function(conn->session, _httpWriteGNUTLS);
2608
2609 if ((gnutls_handshake(conn->session)) != GNUTLS_E_SUCCESS)
2610 {
2611 http->error = errno;
2612 http->status = HTTP_ERROR;
2613
2614 return (-1);
2615 }
2616
2617 conn->credentials = credentials;
2618
2619 # elif defined(HAVE_CDSASSL)
2620 conn = (http_tls_t *)calloc(1, sizeof(http_tls_t));
2621
2622 if (conn == NULL)
2623 return (-1);
2624
2625 if ((error = SSLNewContext(false, &conn->session)))
2626 {
2627 http->error = error;
2628 http->status = HTTP_ERROR;
2629
2630 free(conn);
2631 return (-1);
2632 }
2633
2634 /*
2635 * Use a union to resolve warnings about int/pointer size mismatches...
2636 */
2637
2638 error = SSLSetConnection(conn->session, http);
2639
2640 if (!error)
2641 error = SSLSetIOFuncs(conn->session, _httpReadCDSA, _httpWriteCDSA);
2642
2643 if (!error)
2644 error = SSLSetAllowsExpiredCerts(conn->session, true);
2645
2646 if (!error)
2647 error = SSLSetAllowsAnyRoot(conn->session, true);
2648
2649 if (!error)
2650 error = SSLSetProtocolVersionEnabled(conn->session, kSSLProtocol2, false);
2651
2652 if (!error)
2653 {
2654 while ((error = SSLHandshake(conn->session)) == errSSLWouldBlock)
2655 usleep(1000);
2656 }
2657
2658 if (error)
2659 {
2660 http->error = error;
2661 http->status = HTTP_ERROR;
2662
2663 SSLDisposeContext(conn->session);
2664
2665 free(conn);
2666
2667 return (-1);
2668 }
2669 # endif /* HAVE_CDSASSL */
2670
2671 http->tls = conn;
2672 return (0);
2673 }
2674 #endif /* HAVE_SSL */
2675
2676
2677 #ifdef HAVE_SSL
2678 /*
2679 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
2680 */
2681
2682 static void
2683 http_shutdown_ssl(http_t *http) /* I - HTTP connection */
2684 {
2685 # ifdef HAVE_LIBSSL
2686 SSL_CTX *context; /* Context for encryption */
2687 SSL *conn; /* Connection for encryption */
2688
2689
2690 conn = (SSL *)(http->tls);
2691 context = SSL_get_SSL_CTX(conn);
2692
2693 SSL_shutdown(conn);
2694 SSL_CTX_free(context);
2695 SSL_free(conn);
2696
2697 # elif defined(HAVE_GNUTLS)
2698 http_tls_t *conn; /* Encryption session */
2699 gnutls_certificate_client_credentials *credentials;
2700 /* TLS credentials */
2701
2702
2703 conn = (http_tls_t *)(http->tls);
2704 credentials = (gnutls_certificate_client_credentials *)(conn->credentials);
2705
2706 gnutls_bye(conn->session, GNUTLS_SHUT_RDWR);
2707 gnutls_deinit(conn->session);
2708 gnutls_certificate_free_credentials(*credentials);
2709 free(credentials);
2710 free(conn);
2711
2712 # elif defined(HAVE_CDSASSL)
2713 http_tls_t *conn; /* CDSA connection information */
2714
2715
2716 conn = (http_tls_t *)(http->tls);
2717
2718 while (SSLClose(conn->session) == errSSLWouldBlock)
2719 usleep(1000);
2720
2721 SSLDisposeContext(conn->session);
2722
2723 if (conn->certsArray)
2724 CFRelease(conn->certsArray);
2725
2726 free(conn);
2727 # endif /* HAVE_LIBSSL */
2728
2729 http->tls = NULL;
2730 }
2731 #endif /* HAVE_SSL */
2732
2733
2734 #ifdef HAVE_SSL
2735 /*
2736 * 'http_upgrade()' - Force upgrade to TLS encryption.
2737 */
2738
2739 static int /* O - Status of connection */
2740 http_upgrade(http_t *http) /* I - HTTP connection */
2741 {
2742 int ret; /* Return value */
2743 http_t myhttp; /* Local copy of HTTP data */
2744
2745
2746 DEBUG_printf(("http_upgrade(%p)\n", http));
2747
2748 /*
2749 * Copy the HTTP data to a local variable so we can do the OPTIONS
2750 * request without interfering with the existing request data...
2751 */
2752
2753 memcpy(&myhttp, http, sizeof(myhttp));
2754
2755 /*
2756 * Send an OPTIONS request to the server, requiring SSL or TLS
2757 * encryption on the link...
2758 */
2759
2760 httpClearFields(http);
2761 httpSetField(http, HTTP_FIELD_CONNECTION, "upgrade");
2762 httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.0, SSL/2.0, SSL/3.0");
2763
2764 if ((ret = httpOptions(http, "*")) == 0)
2765 {
2766 /*
2767 * Wait for the secure connection...
2768 */
2769
2770 while (httpUpdate(http) == HTTP_CONTINUE);
2771 }
2772
2773 httpFlush(http);
2774
2775 /*
2776 * Restore the HTTP request data...
2777 */
2778
2779 memcpy(http->fields, myhttp.fields, sizeof(http->fields));
2780 http->data_encoding = myhttp.data_encoding;
2781 http->data_remaining = myhttp.data_remaining;
2782 http->_data_remaining = myhttp._data_remaining;
2783 http->expect = myhttp.expect;
2784
2785 /*
2786 * See if we actually went secure...
2787 */
2788
2789 if (!http->tls)
2790 {
2791 /*
2792 * Server does not support HTTP upgrade...
2793 */
2794
2795 DEBUG_puts("Server does not support HTTP upgrade!");
2796
2797 # ifdef WIN32
2798 closesocket(http->fd);
2799 # else
2800 close(http->fd);
2801 # endif
2802
2803 http->fd = -1;
2804
2805 return (-1);
2806 }
2807 else
2808 return (ret);
2809 }
2810 #endif /* HAVE_SSL */
2811
2812
2813 /*
2814 * 'http_wait()' - Wait for data available on a connection.
2815 */
2816
2817 static int /* O - 1 if data is available, 0 otherwise */
2818 http_wait(http_t *http, /* I - HTTP connection */
2819 int msec, /* I - Milliseconds to wait */
2820 int usessl) /* I - Use SSL context? */
2821 {
2822 #ifndef WIN32
2823 struct rlimit limit; /* Runtime limit */
2824 int set_size; /* Size of select set */
2825 #endif /* !WIN32 */
2826 struct timeval timeout; /* Timeout */
2827 int nfds; /* Result from select() */
2828
2829
2830 DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http, msec));
2831
2832 if (http->fd < 0)
2833 return (0);
2834
2835 /*
2836 * Check the SSL/TLS buffers for data first...
2837 */
2838
2839 #ifdef HAVE_SSL
2840 if (http->tls && usessl)
2841 {
2842 # ifdef HAVE_LIBSSL
2843 if (SSL_pending((SSL *)(http->tls)))
2844 return (1);
2845 # elif defined(HAVE_GNUTLS)
2846 if (gnutls_record_check_pending(((http_tls_t *)(http->tls))->session))
2847 return (1);
2848 # elif defined(HAVE_CDSASSL)
2849 size_t bytes; /* Bytes that are available */
2850
2851 if (!SSLGetBufferedReadSize(((http_tls_t *)http->tls)->session, &bytes) && bytes > 0)
2852 return (1);
2853 # endif /* HAVE_LIBSSL */
2854 }
2855 #endif /* HAVE_SSL */
2856
2857 /*
2858 * Then try doing a select() to poll the socket...
2859 */
2860
2861 if (!http->input_set)
2862 {
2863 #ifdef WIN32
2864 /*
2865 * Windows has a fixed-size select() structure, different (surprise,
2866 * surprise!) from all UNIX implementations. Just allocate this
2867 * fixed structure...
2868 */
2869
2870 http->input_set = calloc(1, sizeof(fd_set));
2871 #else
2872 /*
2873 * Allocate the select() input set based upon the max number of file
2874 * descriptors available for this process...
2875 */
2876
2877 getrlimit(RLIMIT_NOFILE, &limit);
2878
2879 set_size = (limit.rlim_cur + 31) / 8 + 4;
2880 if (set_size < sizeof(fd_set))
2881 set_size = sizeof(fd_set);
2882
2883 http->input_set = calloc(1, set_size);
2884 #endif /* WIN32 */
2885
2886 if (!http->input_set)
2887 return (0);
2888 }
2889
2890 do
2891 {
2892 FD_SET(http->fd, http->input_set);
2893
2894 DEBUG_printf(("http_wait: msec=%d, http->fd=%d\n", msec, http->fd));
2895
2896 if (msec >= 0)
2897 {
2898 timeout.tv_sec = msec / 1000;
2899 timeout.tv_usec = (msec % 1000) * 1000;
2900
2901 nfds = select(http->fd + 1, http->input_set, NULL, NULL, &timeout);
2902 }
2903 else
2904 nfds = select(http->fd + 1, http->input_set, NULL, NULL, NULL);
2905
2906 DEBUG_printf(("http_wait: select() returned %d...\n", nfds));
2907 }
2908 #ifdef WIN32
2909 while (nfds < 0 && WSAGetLastError() == WSAEINTR);
2910 #else
2911 while (nfds < 0 && errno == EINTR);
2912 #endif /* WIN32 */
2913
2914 FD_CLR(http->fd, http->input_set);
2915
2916 DEBUG_printf(("http_wait: returning with nfds=%d...\n", nfds));
2917
2918 return (nfds > 0);
2919 }
2920
2921
2922 /*
2923 * 'http_write()' - Write a buffer to a HTTP connection.
2924 */
2925
2926 static int /* O - Number of bytes written */
2927 http_write(http_t *http, /* I - HTTP connection */
2928 const char *buffer, /* I - Buffer for data */
2929 int length) /* I - Number of bytes to write */
2930 {
2931 int tbytes, /* Total bytes sent */
2932 bytes; /* Bytes sent */
2933
2934
2935 tbytes = 0;
2936
2937 while (length > 0)
2938 {
2939 #ifdef HAVE_SSL
2940 if (http->tls)
2941 bytes = http_write_ssl(http, buffer, length);
2942 else
2943 #endif /* HAVE_SSL */
2944 bytes = send(http->fd, buffer, length, 0);
2945
2946 if (bytes < 0)
2947 {
2948 #ifdef WIN32
2949 if (WSAGetLastError() != http->error)
2950 {
2951 http->error = WSAGetLastError();
2952 continue;
2953 }
2954 #else
2955 if (errno == EINTR)
2956 continue;
2957 else if (errno != http->error && errno != ECONNRESET)
2958 {
2959 http->error = errno;
2960 continue;
2961 }
2962 #endif /* WIN32 */
2963
2964 DEBUG_puts("http_write: error writing data...\n");
2965
2966 return (-1);
2967 }
2968
2969 buffer += bytes;
2970 tbytes += bytes;
2971 length -= bytes;
2972 }
2973
2974 #ifdef DEBUG
2975 {
2976 int i, j, ch;
2977 printf("http_write: wrote %d bytes: \n", tbytes);
2978 for (i = 0, buffer -= tbytes; i < tbytes; i += 16)
2979 {
2980 printf(" ");
2981
2982 for (j = 0; j < 16 && (i + j) < tbytes; j ++)
2983 printf(" %02X", buffer[i + j] & 255);
2984
2985 while (j < 16)
2986 {
2987 printf(" ");
2988 j ++;
2989 }
2990
2991 printf(" ");
2992 for (j = 0; j < 16 && (i + j) < tbytes; j ++)
2993 {
2994 ch = buffer[i + j] & 255;
2995
2996 if (ch < ' ' || ch == 127)
2997 ch = '.';
2998
2999 putchar(ch);
3000 }
3001 putchar('\n');
3002 }
3003 }
3004 #endif /* DEBUG */
3005
3006 return (tbytes);
3007 }
3008
3009
3010 /*
3011 * 'http_write_chunk()' - Write a chunked buffer.
3012 */
3013
3014 static int /* O - Number bytes written */
3015 http_write_chunk(http_t *http, /* I - HTTP connection */
3016 const char *buffer, /* I - Buffer to write */
3017 int length) /* I - Length of buffer */
3018 {
3019 char header[255]; /* Chunk header */
3020 int bytes; /* Bytes written */
3021
3022 DEBUG_printf(("http_write_chunk(http=%p, buffer=%p, length=%d)\n",
3023 http, buffer, length));
3024
3025 /*
3026 * Write the chunk header, data, and trailer.
3027 */
3028
3029 sprintf(header, "%x\r\n", length);
3030 if (http_write(http, header, (int)strlen(header)) < 0)
3031 {
3032 DEBUG_puts(" http_write of length failed!");
3033 return (-1);
3034 }
3035
3036 if ((bytes = http_write(http, buffer, length)) < 0)
3037 {
3038 DEBUG_puts(" http_write of buffer failed!");
3039 return (-1);
3040 }
3041
3042 if (http_write(http, "\r\n", 2) < 0)
3043 {
3044 DEBUG_puts(" http_write of CR LF failed!");
3045 return (-1);
3046 }
3047
3048 return (bytes);
3049 }
3050
3051
3052 #ifdef HAVE_SSL
3053 /*
3054 * 'http_write_ssl()' - Write to a SSL/TLS connection.
3055 */
3056
3057 static int /* O - Bytes written */
3058 http_write_ssl(http_t *http, /* I - HTTP connection */
3059 const char *buf, /* I - Buffer holding data */
3060 int len) /* I - Length of buffer */
3061 {
3062 # if defined(HAVE_LIBSSL)
3063 return (SSL_write((SSL *)(http->tls), buf, len));
3064
3065 # elif defined(HAVE_GNUTLS)
3066 return (gnutls_record_send(((http_tls_t *)(http->tls))->session, buf, len));
3067 # elif defined(HAVE_CDSASSL)
3068 int result; /* Return value */
3069 OSStatus error; /* Error info */
3070 size_t processed; /* Number of bytes processed */
3071
3072
3073 error = SSLWrite(((http_tls_t *)http->tls)->session, buf, len, &processed);
3074
3075 switch (error)
3076 {
3077 case 0 :
3078 result = (int)processed;
3079 break;
3080 case errSSLClosedGraceful :
3081 result = 0;
3082 break;
3083 case errSSLWouldBlock :
3084 if (processed)
3085 result = (int)processed;
3086 else
3087 {
3088 result = -1;
3089 errno = EINTR;
3090 }
3091 break;
3092 default :
3093 errno = EPIPE;
3094 result = -1;
3095 break;
3096 }
3097
3098 return (result);
3099 # endif /* HAVE_LIBSSL */
3100 }
3101 #endif /* HAVE_SSL */
3102
3103
3104 /*
3105 * End of "$Id: http.c 6191 2007-01-10 16:48:37Z mike $".
3106 */