]> git.ipfire.org Git - thirdparty/cups.git/blob - cups/http.c
Merge changes from CUPS 1.7svn-r10578.
[thirdparty/cups.git] / cups / http.c
1 /*
2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
3 *
4 * HTTP routines for CUPS.
5 *
6 * Copyright 2007-2012 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
8 *
9 * This file contains Kerberos support code, copyright 2006 by
10 * Jelmer Vernooij.
11 *
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
17 *
18 * This file is subject to the Apple OS-Developed Software exception.
19 *
20 * Contents:
21 *
22 * httpAddCredential() - Allocates and adds a single credential to an
23 * array.
24 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP
25 * connections.
26 * httpBlocking() - Set blocking/non-blocking behavior on a
27 * connection.
28 * httpCheck() - Check to see if there is a pending response
29 * from the server.
30 * httpClearCookie() - Clear the cookie value(s).
31 * httpClearFields() - Clear HTTP request fields.
32 * httpClose() - Close an HTTP connection.
33 * httpConnect() - Connect to a HTTP server.
34 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
35 * httpCopyCredentials() - Copy the credentials associated with an
36 * encrypted connection.
37 * _httpCreate() - Create an unconnected HTTP connection.
38 * _httpCreateCredentials() - Create credentials in the internal format.
39 * httpDelete() - Send a DELETE request to the server.
40 * _httpDisconnect() - Disconnect a HTTP connection.
41 * httpEncryption() - Set the required encryption on the link.
42 * httpError() - Get the last error on a connection.
43 * httpFlush() - Flush data from a HTTP connection.
44 * httpFlushWrite() - Flush data in write buffer.
45 * _httpFreeCredentials() - Free internal credentials.
46 * httpFreeCredentials() - Free an array of credentials.
47 * httpGet() - Send a GET request to the server.
48 * httpGetAuthString() - Get the current authorization string.
49 * httpGetBlocking() - Get the blocking/non-block state of a
50 * connection.
51 * httpGetCookie() - Get any cookie data from the response.
52 * httpGetFd() - Get the file descriptor associated with a
53 * connection.
54 * httpGetField() - Get a field value from a request/response.
55 * httpGetLength() - Get the amount of data remaining from the
56 * content-length or transfer-encoding fields.
57 * httpGetLength2() - Get the amount of data remaining from the
58 * content-length or transfer-encoding fields.
59 * httpGets() - Get a line of text from a HTTP connection.
60 * httpGetState() - Get the current state of the HTTP request.
61 * httpGetStatus() - Get the status of the last HTTP request.
62 * httpGetSubField() - Get a sub-field value.
63 * httpGetSubField2() - Get a sub-field value.
64 * httpGetVersion() - Get the HTTP version at the other end.
65 * httpHead() - Send a HEAD request to the server.
66 * httpInitialize() - Initialize the HTTP interface library and set
67 * the default HTTP proxy (if any).
68 * httpOptions() - Send an OPTIONS request to the server.
69 * _httpPeek() - Peek at data from a HTTP connection.
70 * httpPost() - Send a POST request to the server.
71 * httpPrintf() - Print a formatted string to a HTTP connection.
72 * httpPut() - Send a PUT request to the server.
73 * httpRead() - Read data from a HTTP connection.
74 * httpRead2() - Read data from a HTTP connection.
75 * _httpReadCDSA() - Read function for the CDSA library.
76 * _httpReadGNUTLS() - Read function for the GNU TLS library.
77 * httpReconnect() - Reconnect to a HTTP server.
78 * httpReconnect2() - Reconnect to a HTTP server with timeout and
79 * optional cancel.
80 * httpSetAuthString() - Set the current authorization string.
81 * httpSetCredentials() - Set the credentials associated with an
82 * encrypted connection.
83 * httpSetCookie() - Set the cookie value(s).
84 * httpSetExpect() - Set the Expect: header in a request.
85 * httpSetField() - Set the value of an HTTP header.
86 * httpSetLength() - Set the content-length and content-encoding.
87 * httpSetTimeout() - Set read/write timeouts and an optional
88 * callback.
89 * httpTrace() - Send an TRACE request to the server.
90 * _httpUpdate() - Update the current HTTP status for incoming
91 * data.
92 * httpUpdate() - Update the current HTTP state for incoming
93 * data.
94 * _httpWait() - Wait for data available on a connection (no
95 * flush).
96 * httpWait() - Wait for data available on a connection.
97 * httpWrite() - Write data to a HTTP connection.
98 * httpWrite2() - Write data to a HTTP connection.
99 * _httpWriteCDSA() - Write function for the CDSA library.
100 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
101 * http_bio_ctrl() - Control the HTTP connection.
102 * http_bio_free() - Free OpenSSL data.
103 * http_bio_new() - Initialize an OpenSSL BIO structure.
104 * http_bio_puts() - Send a string for OpenSSL.
105 * http_bio_read() - Read data for OpenSSL.
106 * http_bio_write() - Write data for OpenSSL.
107 * http_debug_hex() - Do a hex dump of a buffer.
108 * http_field() - Return the field index for a field name.
109 * http_read_ssl() - Read from a SSL/TLS connection.
110 * http_send() - Send a request with all fields and the trailing
111 * blank line.
112 * http_set_credentials() - Set the SSL/TLS credentials.
113 * http_set_timeout() - Set the socket timeout values.
114 * http_set_wait() - Set the default wait value for reads.
115 * http_setup_ssl() - Set up SSL/TLS support on a connection.
116 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
117 * http_upgrade() - Force upgrade to TLS encryption.
118 * http_write() - Write a buffer to a HTTP connection.
119 * http_write_chunk() - Write a chunked buffer.
120 * http_write_ssl() - Write to a SSL/TLS connection.
121 */
122
123 /*
124 * Include necessary headers...
125 */
126
127 #include "cups-private.h"
128 #include <fcntl.h>
129 #include <math.h>
130 #ifdef WIN32
131 # include <tchar.h>
132 #else
133 # include <signal.h>
134 # include <sys/time.h>
135 # include <sys/resource.h>
136 #endif /* WIN32 */
137 #ifdef HAVE_POLL
138 # include <poll.h>
139 #endif /* HAVE_POLL */
140
141
142 /*
143 * Local functions...
144 */
145
146 #ifdef DEBUG
147 static void http_debug_hex(const char *prefix, const char *buffer,
148 int bytes);
149 #endif /* DEBUG */
150 static http_field_t http_field(const char *name);
151 static int http_send(http_t *http, http_state_t request,
152 const char *uri);
153 static int http_write(http_t *http, const char *buffer,
154 int length);
155 static int http_write_chunk(http_t *http, const char *buffer,
156 int length);
157 #ifdef HAVE_SSL
158 static int http_read_ssl(http_t *http, char *buf, int len);
159 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
160 static int http_set_credentials(http_t *http);
161 # endif /* HAVE_CDSASSL ** HAVE_SECCERTIFICATECOPYDATA */
162 #endif /* HAVE_SSL */
163 static void http_set_timeout(int fd, double timeout);
164 static void http_set_wait(http_t *http);
165 #ifdef HAVE_SSL
166 static int http_setup_ssl(http_t *http);
167 static void http_shutdown_ssl(http_t *http);
168 static int http_upgrade(http_t *http);
169 static int http_write_ssl(http_t *http, const char *buf, int len);
170 #endif /* HAVE_SSL */
171
172
173 /*
174 * Local globals...
175 */
176
177 static const char * const http_fields[] =
178 {
179 "Accept-Language",
180 "Accept-Ranges",
181 "Authorization",
182 "Connection",
183 "Content-Encoding",
184 "Content-Language",
185 "Content-Length",
186 "Content-Location",
187 "Content-MD5",
188 "Content-Range",
189 "Content-Type",
190 "Content-Version",
191 "Date",
192 "Host",
193 "If-Modified-Since",
194 "If-Unmodified-since",
195 "Keep-Alive",
196 "Last-Modified",
197 "Link",
198 "Location",
199 "Range",
200 "Referer",
201 "Retry-After",
202 "Transfer-Encoding",
203 "Upgrade",
204 "User-Agent",
205 "WWW-Authenticate"
206 };
207 #ifdef DEBUG
208 static const char * const http_states[] =
209 {
210 "HTTP_WAITING",
211 "HTTP_OPTIONS",
212 "HTTP_GET",
213 "HTTP_GET_SEND",
214 "HTTP_HEAD",
215 "HTTP_POST",
216 "HTTP_POST_RECV",
217 "HTTP_POST_SEND",
218 "HTTP_PUT",
219 "HTTP_PUT_RECV",
220 "HTTP_DELETE",
221 "HTTP_TRACE",
222 "HTTP_CLOSE",
223 "HTTP_STATUS"
224 };
225 #endif /* DEBUG */
226
227
228 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
229 /*
230 * BIO methods for OpenSSL...
231 */
232
233 static int http_bio_write(BIO *h, const char *buf, int num);
234 static int http_bio_read(BIO *h, char *buf, int size);
235 static int http_bio_puts(BIO *h, const char *str);
236 static long http_bio_ctrl(BIO *h, int cmd, long arg1, void *arg2);
237 static int http_bio_new(BIO *h);
238 static int http_bio_free(BIO *data);
239
240 static BIO_METHOD http_bio_methods =
241 {
242 BIO_TYPE_SOCKET,
243 "http",
244 http_bio_write,
245 http_bio_read,
246 http_bio_puts,
247 NULL, /* http_bio_gets, */
248 http_bio_ctrl,
249 http_bio_new,
250 http_bio_free,
251 NULL,
252 };
253 #endif /* HAVE_SSL && HAVE_LIBSSL */
254
255
256 /*
257 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
258 *
259 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
260 *
261 * @since CUPS 1.5/OS X 10.7@
262 */
263
264 int /* O - 0 on success, -1 on error */
265 httpAddCredential(
266 cups_array_t *credentials, /* I - Credentials array */
267 const void *data, /* I - PEM-encoded X.509 data */
268 size_t datalen) /* I - Length of data */
269 {
270 http_credential_t *credential; /* Credential data */
271
272
273 if ((credential = malloc(sizeof(http_credential_t))) != NULL)
274 {
275 credential->datalen = datalen;
276
277 if ((credential->data = malloc(datalen)) != NULL)
278 {
279 memcpy(credential->data, data, datalen);
280 cupsArrayAdd(credentials, credential);
281 return (0);
282 }
283
284 free(credential);
285 }
286
287 return (-1);
288 }
289
290
291 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
292 /*
293 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
294 */
295
296 BIO_METHOD * /* O - BIO methods for OpenSSL */
297 _httpBIOMethods(void)
298 {
299 return (&http_bio_methods);
300 }
301 #endif /* HAVE_SSL && HAVE_LIBSSL */
302
303
304 /*
305 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
306 */
307
308 void
309 httpBlocking(http_t *http, /* I - Connection to server */
310 int b) /* I - 1 = blocking, 0 = non-blocking */
311 {
312 if (http)
313 {
314 http->blocking = b;
315 http_set_wait(http);
316 }
317 }
318
319
320 /*
321 * 'httpCheck()' - Check to see if there is a pending response from the server.
322 */
323
324 int /* O - 0 = no data, 1 = data available */
325 httpCheck(http_t *http) /* I - Connection to server */
326 {
327 return (httpWait(http, 0));
328 }
329
330
331 /*
332 * 'httpClearCookie()' - Clear the cookie value(s).
333 *
334 * @since CUPS 1.1.19/OS X 10.3@
335 */
336
337 void
338 httpClearCookie(http_t *http) /* I - Connection to server */
339 {
340 if (!http)
341 return;
342
343 if (http->cookie)
344 {
345 free(http->cookie);
346 http->cookie = NULL;
347 }
348 }
349
350
351 /*
352 * 'httpClearFields()' - Clear HTTP request fields.
353 */
354
355 void
356 httpClearFields(http_t *http) /* I - Connection to server */
357 {
358 if (http)
359 {
360 memset(http->fields, 0, sizeof(http->fields));
361 if (http->hostname[0] == '/')
362 httpSetField(http, HTTP_FIELD_HOST, "localhost");
363 else
364 httpSetField(http, HTTP_FIELD_HOST, http->hostname);
365
366 if (http->field_authorization)
367 {
368 free(http->field_authorization);
369 http->field_authorization = NULL;
370 }
371
372 http->expect = (http_status_t)0;
373 }
374 }
375
376
377 /*
378 * 'httpClose()' - Close an HTTP connection.
379 */
380
381 void
382 httpClose(http_t *http) /* I - Connection to server */
383 {
384 #ifdef HAVE_GSSAPI
385 OM_uint32 minor_status; /* Minor status code */
386 #endif /* HAVE_GSSAPI */
387
388
389 DEBUG_printf(("httpClose(http=%p)", http));
390
391 /*
392 * Range check input...
393 */
394
395 if (!http)
396 return;
397
398 /*
399 * Close any open connection...
400 */
401
402 _httpDisconnect(http);
403
404 /*
405 * Free memory used...
406 */
407
408 httpAddrFreeList(http->addrlist);
409
410 if (http->cookie)
411 free(http->cookie);
412
413 #ifdef HAVE_GSSAPI
414 if (http->gssctx != GSS_C_NO_CONTEXT)
415 gss_delete_sec_context(&minor_status, &http->gssctx, GSS_C_NO_BUFFER);
416
417 if (http->gssname != GSS_C_NO_NAME)
418 gss_release_name(&minor_status, &http->gssname);
419 #endif /* HAVE_GSSAPI */
420
421 #ifdef HAVE_AUTHORIZATION_H
422 if (http->auth_ref)
423 AuthorizationFree(http->auth_ref, kAuthorizationFlagDefaults);
424 #endif /* HAVE_AUTHORIZATION_H */
425
426 httpClearFields(http);
427
428 if (http->authstring && http->authstring != http->_authstring)
429 free(http->authstring);
430
431 free(http);
432 }
433
434
435 /*
436 * 'httpConnect()' - Connect to a HTTP server.
437 *
438 * This function is deprecated - use @link httpConnectEncrypt@ instead.
439 *
440 * @deprecated@
441 */
442
443 http_t * /* O - New HTTP connection */
444 httpConnect(const char *host, /* I - Host to connect to */
445 int port) /* I - Port number */
446 {
447 return (httpConnectEncrypt(host, port, HTTP_ENCRYPT_IF_REQUESTED));
448 }
449
450
451 /*
452 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
453 */
454
455 http_t * /* O - New HTTP connection */
456 httpConnectEncrypt(
457 const char *host, /* I - Host to connect to */
458 int port, /* I - Port number */
459 http_encryption_t encryption) /* I - Type of encryption to use */
460 {
461 http_t *http; /* New HTTP connection */
462
463
464 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
465 host, port, encryption));
466
467 /*
468 * Create the HTTP structure...
469 */
470
471 if ((http = _httpCreate(host, port, NULL, encryption, AF_UNSPEC)) == NULL)
472 return (NULL);
473
474 /*
475 * Connect to the remote system...
476 */
477
478 if (!httpReconnect(http))
479 return (http);
480
481 /*
482 * Could not connect to any known address - bail out!
483 */
484
485 httpAddrFreeList(http->addrlist);
486
487 free(http);
488
489 return (NULL);
490 }
491
492
493 /*
494 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
495 * connection.
496 *
497 * @since CUPS 1.5/OS X 10.7@
498 */
499
500 int /* O - Status of call (0 = success) */
501 httpCopyCredentials(
502 http_t *http, /* I - Connection to server */
503 cups_array_t **credentials) /* O - Array of credentials */
504 {
505 # ifdef HAVE_LIBSSL
506 # elif defined(HAVE_GNUTLS)
507 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
508 OSStatus error; /* Error code */
509 CFIndex count; /* Number of credentials */
510 CFArrayRef peerCerts; /* Peer certificates */
511 SecCertificateRef secCert; /* Certificate reference */
512 CFDataRef data; /* Certificate data */
513 int i; /* Looping var */
514 # elif defined(HAVE_SSPISSL)
515 # endif /* HAVE_LIBSSL */
516
517
518 if (credentials)
519 *credentials = NULL;
520
521 if (!http || !http->tls || !credentials)
522 return (-1);
523
524 # ifdef HAVE_LIBSSL
525 return (-1);
526
527 # elif defined(HAVE_GNUTLS)
528 return (-1);
529
530 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
531 if (!(error = SSLCopyPeerCertificates(http->tls, &peerCerts)) && peerCerts)
532 {
533 if ((*credentials = cupsArrayNew(NULL, NULL)) != NULL)
534 {
535 for (i = 0, count = CFArrayGetCount(peerCerts); i < count; i++)
536 {
537 secCert = (SecCertificateRef)CFArrayGetValueAtIndex(peerCerts, i);
538 if ((data = SecCertificateCopyData(secCert)))
539 {
540 httpAddCredential(*credentials, CFDataGetBytePtr(data),
541 CFDataGetLength(data));
542 CFRelease(data);
543 }
544 }
545 }
546
547 CFRelease(peerCerts);
548 }
549
550 return (error);
551
552 # elif defined(HAVE_SSPISSL)
553 return (-1);
554
555 # else
556 return (-1);
557 # endif /* HAVE_LIBSSL */
558 }
559
560
561 /*
562 * '_httpCreate()' - Create an unconnected HTTP connection.
563 */
564
565 http_t * /* O - HTTP connection */
566 _httpCreate(
567 const char *host, /* I - Hostname */
568 int port, /* I - Port number */
569 http_addrlist_t *addrlist, /* I - Address list or NULL */
570 http_encryption_t encryption, /* I - Encryption to use */
571 int family) /* I - Address family or AF_UNSPEC */
572 {
573 http_t *http; /* New HTTP connection */
574 char service[255]; /* Service name */
575
576
577 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
578 host, port, encryption));
579
580 if (!host)
581 return (NULL);
582
583 httpInitialize();
584
585 /*
586 * Lookup the host...
587 */
588
589 sprintf(service, "%d", port);
590
591 if (!addrlist)
592 if ((addrlist = httpAddrGetList(host, family, service)) == NULL)
593 return (NULL);
594
595 /*
596 * Allocate memory for the structure...
597 */
598
599 if ((http = calloc(sizeof(http_t), 1)) == NULL)
600 {
601 _cupsSetError(IPP_INTERNAL_ERROR, strerror(errno), 0);
602 httpAddrFreeList(addrlist);
603 return (NULL);
604 }
605
606 /*
607 * Initialize the HTTP data...
608 */
609
610 http->activity = time(NULL);
611 http->addrlist = addrlist;
612 http->blocking = 1;
613 http->fd = -1;
614 #ifdef HAVE_GSSAPI
615 http->gssctx = GSS_C_NO_CONTEXT;
616 http->gssname = GSS_C_NO_NAME;
617 #endif /* HAVE_GSSAPI */
618 http->version = HTTP_1_1;
619
620 strlcpy(http->hostname, host, sizeof(http->hostname));
621
622 if (port == 443) /* Always use encryption for https */
623 http->encryption = HTTP_ENCRYPT_ALWAYS;
624 else
625 http->encryption = encryption;
626
627 http_set_wait(http);
628
629 /*
630 * Return the new structure...
631 */
632
633 return (http);
634 }
635
636
637 /*
638 * '_httpCreateCredentials()' - Create credentials in the internal format.
639 */
640
641 http_tls_credentials_t /* O - Internal credentials */
642 _httpCreateCredentials(
643 cups_array_t *credentials) /* I - Array of credentials */
644 {
645 if (!credentials)
646 return (NULL);
647
648 # ifdef HAVE_LIBSSL
649 return (NULL);
650
651 # elif defined(HAVE_GNUTLS)
652 return (NULL);
653
654 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
655 CFMutableArrayRef peerCerts; /* Peer credentials reference */
656 SecCertificateRef secCert; /* Certificate reference */
657 CFDataRef data; /* Credential data reference */
658 http_credential_t *credential; /* Credential data */
659
660
661 if ((peerCerts = CFArrayCreateMutable(kCFAllocatorDefault,
662 cupsArrayCount(credentials),
663 &kCFTypeArrayCallBacks)) == NULL)
664 return (NULL);
665
666 for (credential = (http_credential_t *)cupsArrayFirst(credentials);
667 credential;
668 credential = (http_credential_t *)cupsArrayNext(credentials))
669 {
670 if ((data = CFDataCreate(kCFAllocatorDefault, credential->data,
671 credential->datalen)))
672 {
673 if ((secCert = SecCertificateCreateWithData(kCFAllocatorDefault, data))
674 != NULL)
675 {
676 CFArrayAppendValue(peerCerts, secCert);
677 CFRelease(secCert);
678 }
679
680 CFRelease(data);
681 }
682 }
683
684 return (peerCerts);
685
686 # elif defined(HAVE_SSPISSL)
687 return (NULL);
688
689 # else
690 return (NULL);
691 # endif /* HAVE_LIBSSL */
692 }
693
694
695 /*
696 * 'httpDelete()' - Send a DELETE request to the server.
697 */
698
699 int /* O - Status of call (0 = success) */
700 httpDelete(http_t *http, /* I - Connection to server */
701 const char *uri) /* I - URI to delete */
702 {
703 return (http_send(http, HTTP_DELETE, uri));
704 }
705
706
707 /*
708 * '_httpDisconnect()' - Disconnect a HTTP connection.
709 */
710
711 void
712 _httpDisconnect(http_t *http) /* I - Connection to server */
713 {
714 #ifdef HAVE_SSL
715 if (http->tls)
716 http_shutdown_ssl(http);
717 #endif /* HAVE_SSL */
718
719 #ifdef WIN32
720 closesocket(http->fd);
721 #else
722 close(http->fd);
723 #endif /* WIN32 */
724
725 http->fd = -1;
726 }
727
728
729 /*
730 * 'httpEncryption()' - Set the required encryption on the link.
731 */
732
733 int /* O - -1 on error, 0 on success */
734 httpEncryption(http_t *http, /* I - Connection to server */
735 http_encryption_t e) /* I - New encryption preference */
736 {
737 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http, e));
738
739 #ifdef HAVE_SSL
740 if (!http)
741 return (0);
742
743 http->encryption = e;
744
745 if ((http->encryption == HTTP_ENCRYPT_ALWAYS && !http->tls) ||
746 (http->encryption == HTTP_ENCRYPT_NEVER && http->tls))
747 return (httpReconnect(http));
748 else if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
749 return (http_upgrade(http));
750 else
751 return (0);
752 #else
753 if (e == HTTP_ENCRYPT_ALWAYS || e == HTTP_ENCRYPT_REQUIRED)
754 return (-1);
755 else
756 return (0);
757 #endif /* HAVE_SSL */
758 }
759
760
761 /*
762 * 'httpError()' - Get the last error on a connection.
763 */
764
765 int /* O - Error code (errno) value */
766 httpError(http_t *http) /* I - Connection to server */
767 {
768 if (http)
769 return (http->error);
770 else
771 return (EINVAL);
772 }
773
774
775 /*
776 * 'httpFlush()' - Flush data from a HTTP connection.
777 */
778
779 void
780 httpFlush(http_t *http) /* I - Connection to server */
781 {
782 char buffer[8192]; /* Junk buffer */
783 int blocking; /* To block or not to block */
784 http_state_t oldstate; /* Old state */
785
786
787 DEBUG_printf(("httpFlush(http=%p), state=%s", http,
788 http_states[http->state]));
789
790 /*
791 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
792 */
793
794 blocking = http->blocking;
795 http->blocking = 0;
796
797 /*
798 * Read any data we can...
799 */
800
801 oldstate = http->state;
802 while (httpRead2(http, buffer, sizeof(buffer)) > 0);
803
804 /*
805 * Restore blocking and reset the connection if we didn't get all of
806 * the remaining data...
807 */
808
809 http->blocking = blocking;
810
811 if (http->state == oldstate && http->state != HTTP_WAITING && http->fd >= 0)
812 {
813 /*
814 * Didn't get the data back, so close the current connection.
815 */
816
817 http->state = HTTP_WAITING;
818
819 #ifdef HAVE_SSL
820 if (http->tls)
821 http_shutdown_ssl(http);
822 #endif /* HAVE_SSL */
823
824 #ifdef WIN32
825 closesocket(http->fd);
826 #else
827 close(http->fd);
828 #endif /* WIN32 */
829
830 http->fd = -1;
831 }
832 }
833
834
835 /*
836 * 'httpFlushWrite()' - Flush data in write buffer.
837 *
838 * @since CUPS 1.2/OS X 10.5@
839 */
840
841 int /* O - Bytes written or -1 on error */
842 httpFlushWrite(http_t *http) /* I - Connection to server */
843 {
844 int bytes; /* Bytes written */
845
846
847 DEBUG_printf(("httpFlushWrite(http=%p)", http));
848
849 if (!http || !http->wused)
850 {
851 DEBUG_puts(http ? "1httpFlushWrite: Write buffer is empty." :
852 "1httpFlushWrite: No connection.");
853 return (0);
854 }
855
856 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
857 bytes = http_write_chunk(http, http->wbuffer, http->wused);
858 else
859 bytes = http_write(http, http->wbuffer, http->wused);
860
861 http->wused = 0;
862
863 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes, errno));
864
865 return (bytes);
866 }
867
868
869 /*
870 * '_httpFreeCredentials()' - Free internal credentials.
871 */
872
873 void
874 _httpFreeCredentials(
875 http_tls_credentials_t credentials) /* I - Internal credentials */
876 {
877 if (!credentials)
878 return;
879
880 #ifdef HAVE_LIBSSL
881 (void)credentials;
882
883 #elif defined(HAVE_GNUTLS)
884 (void)credentials;
885
886 #elif defined(HAVE_CDSASSL)
887 CFRelease(credentials);
888
889 #elif defined(HAVE_SSPISSL)
890 (void)credentials;
891
892 #endif /* HAVE_LIBSSL */
893 }
894
895
896 /*
897 * 'httpFreeCredentials()' - Free an array of credentials.
898 */
899
900 void
901 httpFreeCredentials(
902 cups_array_t *credentials) /* I - Array of credentials */
903 {
904 http_credential_t *credential; /* Credential */
905
906
907 for (credential = (http_credential_t *)cupsArrayFirst(credentials);
908 credential;
909 credential = (http_credential_t *)cupsArrayNext(credentials))
910 {
911 cupsArrayRemove(credentials, credential);
912 free((void *)credential->data);
913 free(credential);
914 }
915
916 cupsArrayDelete(credentials);
917 }
918
919
920 /*
921 * 'httpGet()' - Send a GET request to the server.
922 */
923
924 int /* O - Status of call (0 = success) */
925 httpGet(http_t *http, /* I - Connection to server */
926 const char *uri) /* I - URI to get */
927 {
928 return (http_send(http, HTTP_GET, uri));
929 }
930
931
932 /*
933 * 'httpGetAuthString()' - Get the current authorization string.
934 *
935 * The authorization string is set by cupsDoAuthentication() and
936 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
937 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
938 * value.
939 *
940 * @since CUPS 1.3/OS X 10.5@
941 */
942
943 char * /* O - Authorization string */
944 httpGetAuthString(http_t *http) /* I - Connection to server */
945 {
946 if (http)
947 return (http->authstring);
948 else
949 return (NULL);
950 }
951
952
953 /*
954 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
955 *
956 * @since CUPS 1.2/OS X 10.5@
957 */
958
959 int /* O - 1 if blocking, 0 if non-blocking */
960 httpGetBlocking(http_t *http) /* I - Connection to server */
961 {
962 return (http ? http->blocking : 0);
963 }
964
965
966 /*
967 * 'httpGetCookie()' - Get any cookie data from the response.
968 *
969 * @since CUPS 1.1.19/OS X 10.3@
970 */
971
972 const char * /* O - Cookie data or NULL */
973 httpGetCookie(http_t *http) /* I - HTTP connecion */
974 {
975 return (http ? http->cookie : NULL);
976 }
977
978
979 /*
980 * 'httpGetFd()' - Get the file descriptor associated with a connection.
981 *
982 * @since CUPS 1.2/OS X 10.5@
983 */
984
985 int /* O - File descriptor or -1 if none */
986 httpGetFd(http_t *http) /* I - Connection to server */
987 {
988 return (http ? http->fd : -1);
989 }
990
991
992 /*
993 * 'httpGetField()' - Get a field value from a request/response.
994 */
995
996 const char * /* O - Field value */
997 httpGetField(http_t *http, /* I - Connection to server */
998 http_field_t field) /* I - Field to get */
999 {
1000 if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
1001 return (NULL);
1002 else if (field == HTTP_FIELD_AUTHORIZATION &&
1003 http->field_authorization)
1004 {
1005 /*
1006 * Special case for WWW-Authenticate: as its contents can be
1007 * longer than HTTP_MAX_VALUE...
1008 */
1009
1010 return (http->field_authorization);
1011 }
1012 else
1013 return (http->fields[field]);
1014 }
1015
1016
1017 /*
1018 * 'httpGetLength()' - Get the amount of data remaining from the
1019 * content-length or transfer-encoding fields.
1020 *
1021 * This function is deprecated and will not return lengths larger than
1022 * 2^31 - 1; use httpGetLength2() instead.
1023 *
1024 * @deprecated@
1025 */
1026
1027 int /* O - Content length */
1028 httpGetLength(http_t *http) /* I - Connection to server */
1029 {
1030 /*
1031 * Get the read content length and return the 32-bit value.
1032 */
1033
1034 if (http)
1035 {
1036 httpGetLength2(http);
1037
1038 return (http->_data_remaining);
1039 }
1040 else
1041 return (-1);
1042 }
1043
1044
1045 /*
1046 * 'httpGetLength2()' - Get the amount of data remaining from the
1047 * content-length or transfer-encoding fields.
1048 *
1049 * This function returns the complete content length, even for
1050 * content larger than 2^31 - 1.
1051 *
1052 * @since CUPS 1.2/OS X 10.5@
1053 */
1054
1055 off_t /* O - Content length */
1056 httpGetLength2(http_t *http) /* I - Connection to server */
1057 {
1058 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http,
1059 http_states[http->state]));
1060
1061 if (!http)
1062 return (-1);
1063
1064 if (!_cups_strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked"))
1065 {
1066 DEBUG_puts("4httpGetLength2: chunked request!");
1067
1068 http->data_encoding = HTTP_ENCODE_CHUNKED;
1069 http->data_remaining = 0;
1070 }
1071 else
1072 {
1073 http->data_encoding = HTTP_ENCODE_LENGTH;
1074
1075 /*
1076 * The following is a hack for HTTP servers that don't send a
1077 * content-length or transfer-encoding field...
1078 *
1079 * If there is no content-length then the connection must close
1080 * after the transfer is complete...
1081 */
1082
1083 if (!http->fields[HTTP_FIELD_CONTENT_LENGTH][0])
1084 {
1085 /*
1086 * Default content length is 0 for errors and 2^31-1 for other
1087 * successful requests...
1088 */
1089
1090 if (http->status >= HTTP_MULTIPLE_CHOICES)
1091 http->data_remaining = 0;
1092 else
1093 http->data_remaining = 2147483647;
1094 }
1095 else
1096 http->data_remaining = strtoll(http->fields[HTTP_FIELD_CONTENT_LENGTH],
1097 NULL, 10);
1098
1099 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT,
1100 CUPS_LLCAST http->data_remaining));
1101 }
1102
1103 if (http->data_remaining <= INT_MAX)
1104 http->_data_remaining = (int)http->data_remaining;
1105 else
1106 http->_data_remaining = INT_MAX;
1107
1108 return (http->data_remaining);
1109 }
1110
1111
1112 /*
1113 * 'httpGets()' - Get a line of text from a HTTP connection.
1114 */
1115
1116 char * /* O - Line or NULL */
1117 httpGets(char *line, /* I - Line to read into */
1118 int length, /* I - Max length of buffer */
1119 http_t *http) /* I - Connection to server */
1120 {
1121 char *lineptr, /* Pointer into line */
1122 *lineend, /* End of line */
1123 *bufptr, /* Pointer into input buffer */
1124 *bufend; /* Pointer to end of buffer */
1125 int bytes, /* Number of bytes read */
1126 eol; /* End-of-line? */
1127
1128
1129 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line, length, http));
1130
1131 if (http == NULL || line == NULL)
1132 return (NULL);
1133
1134 /*
1135 * Read a line from the buffer...
1136 */
1137
1138 http->error = 0;
1139 lineptr = line;
1140 lineend = line + length - 1;
1141 eol = 0;
1142
1143 while (lineptr < lineend)
1144 {
1145 /*
1146 * Pre-load the buffer as needed...
1147 */
1148
1149 #ifdef WIN32
1150 WSASetLastError(0);
1151 #else
1152 errno = 0;
1153 #endif /* WIN32 */
1154
1155 while (http->used == 0)
1156 {
1157 /*
1158 * No newline; see if there is more data to be read...
1159 */
1160
1161 while (!_httpWait(http, http->wait_value, 1))
1162 {
1163 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1164 continue;
1165
1166 DEBUG_puts("3httpGets: Timed out!");
1167 #ifdef WIN32
1168 http->error = WSAETIMEDOUT;
1169 #else
1170 http->error = ETIMEDOUT;
1171 #endif /* WIN32 */
1172 return (NULL);
1173 }
1174
1175 #ifdef HAVE_SSL
1176 if (http->tls)
1177 bytes = http_read_ssl(http, http->buffer + http->used,
1178 HTTP_MAX_BUFFER - http->used);
1179 else
1180 #endif /* HAVE_SSL */
1181 bytes = recv(http->fd, http->buffer + http->used,
1182 HTTP_MAX_BUFFER - http->used, 0);
1183
1184 DEBUG_printf(("4httpGets: read %d bytes...", bytes));
1185
1186 #ifdef DEBUG
1187 http_debug_hex("httpGets", http->buffer + http->used, bytes);
1188 #endif /* DEBUG */
1189
1190 if (bytes < 0)
1191 {
1192 /*
1193 * Nope, can't get a line this time...
1194 */
1195
1196 #ifdef WIN32
1197 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1198
1199 if (WSAGetLastError() == WSAEINTR)
1200 continue;
1201 else if (WSAGetLastError() == WSAEWOULDBLOCK)
1202 {
1203 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1204 continue;
1205
1206 http->error = WSAGetLastError();
1207 }
1208 else if (WSAGetLastError() != http->error)
1209 {
1210 http->error = WSAGetLastError();
1211 continue;
1212 }
1213
1214 #else
1215 DEBUG_printf(("3httpGets: recv() error %d!", errno));
1216
1217 if (errno == EINTR)
1218 continue;
1219 else if (errno == EWOULDBLOCK || errno == EAGAIN)
1220 {
1221 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1222 continue;
1223 else if (!http->timeout_cb && errno == EAGAIN)
1224 continue;
1225
1226 http->error = errno;
1227 }
1228 else if (errno != http->error)
1229 {
1230 http->error = errno;
1231 continue;
1232 }
1233 #endif /* WIN32 */
1234
1235 return (NULL);
1236 }
1237 else if (bytes == 0)
1238 {
1239 http->error = EPIPE;
1240
1241 return (NULL);
1242 }
1243
1244 /*
1245 * Yup, update the amount used...
1246 */
1247
1248 http->used += bytes;
1249 }
1250
1251 /*
1252 * Now copy as much of the current line as possible...
1253 */
1254
1255 for (bufptr = http->buffer, bufend = http->buffer + http->used;
1256 lineptr < lineend && bufptr < bufend;)
1257 {
1258 if (*bufptr == 0x0a)
1259 {
1260 eol = 1;
1261 bufptr ++;
1262 break;
1263 }
1264 else if (*bufptr == 0x0d)
1265 bufptr ++;
1266 else
1267 *lineptr++ = *bufptr++;
1268 }
1269
1270 http->used -= (int)(bufptr - http->buffer);
1271 if (http->used > 0)
1272 memmove(http->buffer, bufptr, http->used);
1273
1274 if (eol)
1275 {
1276 /*
1277 * End of line...
1278 */
1279
1280 http->activity = time(NULL);
1281
1282 *lineptr = '\0';
1283
1284 DEBUG_printf(("3httpGets: Returning \"%s\"", line));
1285
1286 return (line);
1287 }
1288 }
1289
1290 DEBUG_puts("3httpGets: No new line available!");
1291
1292 return (NULL);
1293 }
1294
1295
1296 /*
1297 * 'httpGetState()' - Get the current state of the HTTP request.
1298 */
1299
1300 http_state_t /* O - HTTP state */
1301 httpGetState(http_t *http) /* I - Connection to server */
1302 {
1303 return (http ? http->state : HTTP_ERROR);
1304 }
1305
1306
1307 /*
1308 * 'httpGetStatus()' - Get the status of the last HTTP request.
1309 *
1310 * @since CUPS 1.2/OS X 10.5@
1311 */
1312
1313 http_status_t /* O - HTTP status */
1314 httpGetStatus(http_t *http) /* I - Connection to server */
1315 {
1316 return (http ? http->status : HTTP_ERROR);
1317 }
1318
1319
1320 /*
1321 * 'httpGetSubField()' - Get a sub-field value.
1322 *
1323 * @deprecated@
1324 */
1325
1326 char * /* O - Value or NULL */
1327 httpGetSubField(http_t *http, /* I - Connection to server */
1328 http_field_t field, /* I - Field index */
1329 const char *name, /* I - Name of sub-field */
1330 char *value) /* O - Value string */
1331 {
1332 return (httpGetSubField2(http, field, name, value, HTTP_MAX_VALUE));
1333 }
1334
1335
1336 /*
1337 * 'httpGetSubField2()' - Get a sub-field value.
1338 *
1339 * @since CUPS 1.2/OS X 10.5@
1340 */
1341
1342 char * /* O - Value or NULL */
1343 httpGetSubField2(http_t *http, /* I - Connection to server */
1344 http_field_t field, /* I - Field index */
1345 const char *name, /* I - Name of sub-field */
1346 char *value, /* O - Value string */
1347 int valuelen) /* I - Size of value buffer */
1348 {
1349 const char *fptr; /* Pointer into field */
1350 char temp[HTTP_MAX_VALUE], /* Temporary buffer for name */
1351 *ptr, /* Pointer into string buffer */
1352 *end; /* End of value buffer */
1353
1354 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1355 "valuelen=%d)", http, field, name, value, valuelen));
1356
1357 if (!http || !name || !value || valuelen < 2 ||
1358 field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
1359 return (NULL);
1360
1361 end = value + valuelen - 1;
1362
1363 for (fptr = http->fields[field]; *fptr;)
1364 {
1365 /*
1366 * Skip leading whitespace...
1367 */
1368
1369 while (_cups_isspace(*fptr))
1370 fptr ++;
1371
1372 if (*fptr == ',')
1373 {
1374 fptr ++;
1375 continue;
1376 }
1377
1378 /*
1379 * Get the sub-field name...
1380 */
1381
1382 for (ptr = temp;
1383 *fptr && *fptr != '=' && !_cups_isspace(*fptr) &&
1384 ptr < (temp + sizeof(temp) - 1);
1385 *ptr++ = *fptr++);
1386
1387 *ptr = '\0';
1388
1389 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp));
1390
1391 /*
1392 * Skip trailing chars up to the '='...
1393 */
1394
1395 while (_cups_isspace(*fptr))
1396 fptr ++;
1397
1398 if (!*fptr)
1399 break;
1400
1401 if (*fptr != '=')
1402 continue;
1403
1404 /*
1405 * Skip = and leading whitespace...
1406 */
1407
1408 fptr ++;
1409
1410 while (_cups_isspace(*fptr))
1411 fptr ++;
1412
1413 if (*fptr == '\"')
1414 {
1415 /*
1416 * Read quoted string...
1417 */
1418
1419 for (ptr = value, fptr ++;
1420 *fptr && *fptr != '\"' && ptr < end;
1421 *ptr++ = *fptr++);
1422
1423 *ptr = '\0';
1424
1425 while (*fptr && *fptr != '\"')
1426 fptr ++;
1427
1428 if (*fptr)
1429 fptr ++;
1430 }
1431 else
1432 {
1433 /*
1434 * Read unquoted string...
1435 */
1436
1437 for (ptr = value;
1438 *fptr && !_cups_isspace(*fptr) && *fptr != ',' && ptr < end;
1439 *ptr++ = *fptr++);
1440
1441 *ptr = '\0';
1442
1443 while (*fptr && !_cups_isspace(*fptr) && *fptr != ',')
1444 fptr ++;
1445 }
1446
1447 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value));
1448
1449 /*
1450 * See if this is the one...
1451 */
1452
1453 if (!strcmp(name, temp))
1454 {
1455 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value));
1456 return (value);
1457 }
1458 }
1459
1460 value[0] = '\0';
1461
1462 DEBUG_puts("3httpGetSubField2: Returning NULL");
1463
1464 return (NULL);
1465 }
1466
1467
1468 /*
1469 * 'httpGetVersion()' - Get the HTTP version at the other end.
1470 */
1471
1472 http_version_t /* O - Version number */
1473 httpGetVersion(http_t *http) /* I - Connection to server */
1474 {
1475 return (http ? http->version : HTTP_1_0);
1476 }
1477
1478
1479 /*
1480 * 'httpHead()' - Send a HEAD request to the server.
1481 */
1482
1483 int /* O - Status of call (0 = success) */
1484 httpHead(http_t *http, /* I - Connection to server */
1485 const char *uri) /* I - URI for head */
1486 {
1487 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http, uri));
1488 return (http_send(http, HTTP_HEAD, uri));
1489 }
1490
1491
1492 /*
1493 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1494 * default HTTP proxy (if any).
1495 */
1496
1497 void
1498 httpInitialize(void)
1499 {
1500 static int initialized = 0; /* Have we been called before? */
1501 #ifdef WIN32
1502 WSADATA winsockdata; /* WinSock data */
1503 #endif /* WIN32 */
1504 #ifdef HAVE_LIBSSL
1505 int i; /* Looping var */
1506 unsigned char data[1024]; /* Seed data */
1507 #endif /* HAVE_LIBSSL */
1508
1509
1510 _cupsGlobalLock();
1511 if (initialized)
1512 {
1513 _cupsGlobalUnlock();
1514 return;
1515 }
1516
1517 #ifdef WIN32
1518 WSAStartup(MAKEWORD(2,2), &winsockdata);
1519
1520 #elif !defined(SO_NOSIGPIPE)
1521 /*
1522 * Ignore SIGPIPE signals...
1523 */
1524
1525 # ifdef HAVE_SIGSET
1526 sigset(SIGPIPE, SIG_IGN);
1527
1528 # elif defined(HAVE_SIGACTION)
1529 struct sigaction action; /* POSIX sigaction data */
1530
1531
1532 memset(&action, 0, sizeof(action));
1533 action.sa_handler = SIG_IGN;
1534 sigaction(SIGPIPE, &action, NULL);
1535
1536 # else
1537 signal(SIGPIPE, SIG_IGN);
1538 # endif /* !SO_NOSIGPIPE */
1539 #endif /* WIN32 */
1540
1541 #ifdef HAVE_GNUTLS
1542 /*
1543 * Initialize GNU TLS...
1544 */
1545
1546 gnutls_global_init();
1547
1548 #elif defined(HAVE_LIBSSL)
1549 /*
1550 * Initialize OpenSSL...
1551 */
1552
1553 SSL_load_error_strings();
1554 SSL_library_init();
1555
1556 /*
1557 * Using the current time is a dubious random seed, but on some systems
1558 * it is the best we can do (on others, this seed isn't even used...)
1559 */
1560
1561 CUPS_SRAND(time(NULL));
1562
1563 for (i = 0; i < sizeof(data); i ++)
1564 data[i] = CUPS_RAND();
1565
1566 RAND_seed(data, sizeof(data));
1567 #endif /* HAVE_GNUTLS */
1568
1569 initialized = 1;
1570 _cupsGlobalUnlock();
1571 }
1572
1573
1574 /*
1575 * 'httpOptions()' - Send an OPTIONS request to the server.
1576 */
1577
1578 int /* O - Status of call (0 = success) */
1579 httpOptions(http_t *http, /* I - Connection to server */
1580 const char *uri) /* I - URI for options */
1581 {
1582 return (http_send(http, HTTP_OPTIONS, uri));
1583 }
1584
1585
1586 /*
1587 * '_httpPeek()' - Peek at data from a HTTP connection.
1588 *
1589 * This function copies available data from the given HTTP connection, reading
1590 * a buffer as needed. The data is still available for reading using
1591 * @link httpRead@ or @link httpRead2@.
1592 *
1593 * For non-blocking connections the usual timeouts apply.
1594 */
1595
1596 ssize_t /* O - Number of bytes copied */
1597 _httpPeek(http_t *http, /* I - Connection to server */
1598 char *buffer, /* I - Buffer for data */
1599 size_t length) /* I - Maximum number of bytes */
1600 {
1601 ssize_t bytes; /* Bytes read */
1602 char len[32]; /* Length string */
1603
1604
1605 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT ")",
1606 http, buffer, CUPS_LLCAST length));
1607
1608 if (http == NULL || buffer == NULL)
1609 return (-1);
1610
1611 http->activity = time(NULL);
1612 http->error = 0;
1613
1614 if (length <= 0)
1615 return (0);
1616
1617 if (http->data_encoding == HTTP_ENCODE_CHUNKED &&
1618 http->data_remaining <= 0)
1619 {
1620 DEBUG_puts("2_httpPeek: Getting chunk length...");
1621
1622 if (httpGets(len, sizeof(len), http) == NULL)
1623 {
1624 DEBUG_puts("1_httpPeek: Could not get length!");
1625 return (0);
1626 }
1627
1628 http->data_remaining = strtoll(len, NULL, 16);
1629 if (http->data_remaining < 0)
1630 {
1631 DEBUG_puts("1_httpPeek: Negative chunk length!");
1632 return (0);
1633 }
1634 }
1635
1636 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT,
1637 CUPS_LLCAST http->data_remaining));
1638
1639 if (http->data_remaining <= 0)
1640 {
1641 /*
1642 * A zero-length chunk ends a transfer; unless we are reading POST
1643 * data, go idle...
1644 */
1645
1646 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
1647 httpGets(len, sizeof(len), http);
1648
1649 if (http->state == HTTP_POST_RECV)
1650 http->state ++;
1651 else
1652 http->state = HTTP_WAITING;
1653
1654 /*
1655 * Prevent future reads for this request...
1656 */
1657
1658 http->data_encoding = HTTP_ENCODE_LENGTH;
1659
1660 return (0);
1661 }
1662 else if (length > (size_t)http->data_remaining)
1663 length = (size_t)http->data_remaining;
1664
1665 if (http->used == 0)
1666 {
1667 /*
1668 * Buffer small reads for better performance...
1669 */
1670
1671 ssize_t buflen; /* Length of read for buffer */
1672
1673 if (!http->blocking)
1674 {
1675 while (!httpWait(http, http->wait_value))
1676 {
1677 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1678 continue;
1679
1680 return (0);
1681 }
1682 }
1683
1684 if (http->data_remaining > sizeof(http->buffer))
1685 buflen = sizeof(http->buffer);
1686 else
1687 buflen = http->data_remaining;
1688
1689 DEBUG_printf(("2_httpPeek: Reading %d bytes into buffer.", (int)buflen));
1690
1691 do
1692 {
1693 #ifdef HAVE_SSL
1694 if (http->tls)
1695 bytes = http_read_ssl(http, http->buffer, buflen);
1696 else
1697 #endif /* HAVE_SSL */
1698 bytes = recv(http->fd, http->buffer, buflen, 0);
1699
1700 if (bytes < 0)
1701 {
1702 #ifdef WIN32
1703 if (WSAGetLastError() != WSAEINTR)
1704 {
1705 http->error = WSAGetLastError();
1706 return (-1);
1707 }
1708 else if (WSAGetLastError() == WSAEWOULDBLOCK)
1709 {
1710 if (!http->timeout_cb ||
1711 !(*http->timeout_cb)(http, http->timeout_data))
1712 {
1713 http->error = WSAEWOULDBLOCK;
1714 return (-1);
1715 }
1716 }
1717 #else
1718 if (errno == EWOULDBLOCK || errno == EAGAIN)
1719 {
1720 if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
1721 {
1722 http->error = errno;
1723 return (-1);
1724 }
1725 else if (!http->timeout_cb && errno != EAGAIN)
1726 {
1727 http->error = errno;
1728 return (-1);
1729 }
1730 }
1731 else if (errno != EINTR)
1732 {
1733 http->error = errno;
1734 return (-1);
1735 }
1736 #endif /* WIN32 */
1737 }
1738 }
1739 while (bytes < 0);
1740
1741 DEBUG_printf(("2_httpPeek: Read " CUPS_LLFMT " bytes into buffer.",
1742 CUPS_LLCAST bytes));
1743 #ifdef DEBUG
1744 http_debug_hex("_httpPeek", http->buffer, (int)bytes);
1745 #endif /* DEBUG */
1746
1747 http->used = bytes;
1748 }
1749
1750 if (http->used > 0)
1751 {
1752 if (length > (size_t)http->used)
1753 length = (size_t)http->used;
1754
1755 bytes = (ssize_t)length;
1756
1757 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1758 (int)bytes));
1759
1760 memcpy(buffer, http->buffer, length);
1761 }
1762 else
1763 bytes = 0;
1764
1765 if (bytes < 0)
1766 {
1767 #ifdef WIN32
1768 if (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK)
1769 bytes = 0;
1770 else
1771 http->error = WSAGetLastError();
1772 #else
1773 if (errno == EINTR || errno == EAGAIN)
1774 bytes = 0;
1775 else
1776 http->error = errno;
1777 #endif /* WIN32 */
1778 }
1779 else if (bytes == 0)
1780 {
1781 http->error = EPIPE;
1782 return (0);
1783 }
1784
1785 #ifdef DEBUG
1786 http_debug_hex("_httpPeek", buffer, (int)bytes);
1787 #endif /* DEBUG */
1788
1789 return (bytes);
1790 }
1791
1792
1793 /*
1794 * 'httpPost()' - Send a POST request to the server.
1795 */
1796
1797 int /* O - Status of call (0 = success) */
1798 httpPost(http_t *http, /* I - Connection to server */
1799 const char *uri) /* I - URI for post */
1800 {
1801 return (http_send(http, HTTP_POST, uri));
1802 }
1803
1804
1805 /*
1806 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1807 *
1808 * @private@
1809 */
1810
1811 int /* O - Number of bytes written */
1812 httpPrintf(http_t *http, /* I - Connection to server */
1813 const char *format, /* I - printf-style format string */
1814 ...) /* I - Additional args as needed */
1815 {
1816 int bytes; /* Number of bytes to write */
1817 char buf[16384]; /* Buffer for formatted string */
1818 va_list ap; /* Variable argument pointer */
1819
1820
1821 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http, format));
1822
1823 va_start(ap, format);
1824 bytes = vsnprintf(buf, sizeof(buf), format, ap);
1825 va_end(ap);
1826
1827 DEBUG_printf(("3httpPrintf: %s", buf));
1828
1829 if (http->data_encoding == HTTP_ENCODE_FIELDS)
1830 return (httpWrite2(http, buf, bytes));
1831 else
1832 {
1833 if (http->wused)
1834 {
1835 DEBUG_puts("4httpPrintf: flushing existing data...");
1836
1837 if (httpFlushWrite(http) < 0)
1838 return (-1);
1839 }
1840
1841 return (http_write(http, buf, bytes));
1842 }
1843 }
1844
1845
1846 /*
1847 * 'httpPut()' - Send a PUT request to the server.
1848 */
1849
1850 int /* O - Status of call (0 = success) */
1851 httpPut(http_t *http, /* I - Connection to server */
1852 const char *uri) /* I - URI to put */
1853 {
1854 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http, uri));
1855 return (http_send(http, HTTP_PUT, uri));
1856 }
1857
1858
1859 /*
1860 * 'httpRead()' - Read data from a HTTP connection.
1861 *
1862 * This function is deprecated. Use the httpRead2() function which can
1863 * read more than 2GB of data.
1864 *
1865 * @deprecated@
1866 */
1867
1868 int /* O - Number of bytes read */
1869 httpRead(http_t *http, /* I - Connection to server */
1870 char *buffer, /* I - Buffer for data */
1871 int length) /* I - Maximum number of bytes */
1872 {
1873 return ((int)httpRead2(http, buffer, length));
1874 }
1875
1876
1877 /*
1878 * 'httpRead2()' - Read data from a HTTP connection.
1879 *
1880 * @since CUPS 1.2/OS X 10.5@
1881 */
1882
1883 ssize_t /* O - Number of bytes read */
1884 httpRead2(http_t *http, /* I - Connection to server */
1885 char *buffer, /* I - Buffer for data */
1886 size_t length) /* I - Maximum number of bytes */
1887 {
1888 ssize_t bytes; /* Bytes read */
1889 char len[32]; /* Length string */
1890
1891
1892 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT ")",
1893 http, buffer, CUPS_LLCAST length));
1894
1895 if (http == NULL || buffer == NULL)
1896 return (-1);
1897
1898 http->activity = time(NULL);
1899 http->error = 0;
1900
1901 if (length <= 0)
1902 return (0);
1903
1904 if (http->data_encoding == HTTP_ENCODE_CHUNKED &&
1905 http->data_remaining <= 0)
1906 {
1907 DEBUG_puts("2httpRead2: Getting chunk length...");
1908
1909 if (httpGets(len, sizeof(len), http) == NULL)
1910 {
1911 DEBUG_puts("1httpRead2: Could not get length!");
1912 return (0);
1913 }
1914
1915 http->data_remaining = strtoll(len, NULL, 16);
1916 if (http->data_remaining < 0)
1917 {
1918 DEBUG_puts("1httpRead2: Negative chunk length!");
1919 return (0);
1920 }
1921 }
1922
1923 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT,
1924 CUPS_LLCAST http->data_remaining));
1925
1926 if (http->data_remaining <= 0)
1927 {
1928 /*
1929 * A zero-length chunk ends a transfer; unless we are reading POST
1930 * data, go idle...
1931 */
1932
1933 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
1934 httpGets(len, sizeof(len), http);
1935
1936 if (http->state == HTTP_POST_RECV)
1937 http->state ++;
1938 else
1939 http->state = HTTP_WAITING;
1940
1941 /*
1942 * Prevent future reads for this request...
1943 */
1944
1945 http->data_encoding = HTTP_ENCODE_LENGTH;
1946
1947 return (0);
1948 }
1949 else if (length > (size_t)http->data_remaining)
1950 length = (size_t)http->data_remaining;
1951
1952 if (http->used == 0 && length <= 256)
1953 {
1954 /*
1955 * Buffer small reads for better performance...
1956 */
1957
1958 ssize_t buflen; /* Length of read for buffer */
1959
1960 if (!http->blocking)
1961 {
1962 while (!httpWait(http, http->wait_value))
1963 {
1964 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
1965 continue;
1966
1967 return (0);
1968 }
1969 }
1970
1971 if (http->data_remaining > sizeof(http->buffer))
1972 buflen = sizeof(http->buffer);
1973 else
1974 buflen = http->data_remaining;
1975
1976 DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen));
1977
1978 do
1979 {
1980 #ifdef HAVE_SSL
1981 if (http->tls)
1982 bytes = http_read_ssl(http, http->buffer, buflen);
1983 else
1984 #endif /* HAVE_SSL */
1985 bytes = recv(http->fd, http->buffer, buflen, 0);
1986
1987 if (bytes < 0)
1988 {
1989 #ifdef WIN32
1990 if (WSAGetLastError() != WSAEINTR)
1991 {
1992 http->error = WSAGetLastError();
1993 return (-1);
1994 }
1995 else if (WSAGetLastError() == WSAEWOULDBLOCK)
1996 {
1997 if (!http->timeout_cb ||
1998 !(*http->timeout_cb)(http, http->timeout_data))
1999 {
2000 http->error = WSAEWOULDBLOCK;
2001 return (-1);
2002 }
2003 }
2004 #else
2005 if (errno == EWOULDBLOCK || errno == EAGAIN)
2006 {
2007 if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
2008 {
2009 http->error = errno;
2010 return (-1);
2011 }
2012 else if (!http->timeout_cb && errno != EAGAIN)
2013 {
2014 http->error = errno;
2015 return (-1);
2016 }
2017 }
2018 else if (errno != EINTR)
2019 {
2020 http->error = errno;
2021 return (-1);
2022 }
2023 #endif /* WIN32 */
2024 }
2025 }
2026 while (bytes < 0);
2027
2028 DEBUG_printf(("2httpRead2: Read " CUPS_LLFMT " bytes into buffer.",
2029 CUPS_LLCAST bytes));
2030 #ifdef DEBUG
2031 http_debug_hex("httpRead2", http->buffer, (int)bytes);
2032 #endif /* DEBUG */
2033
2034 http->used = bytes;
2035 }
2036
2037 if (http->used > 0)
2038 {
2039 if (length > (size_t)http->used)
2040 length = (size_t)http->used;
2041
2042 bytes = (ssize_t)length;
2043
2044 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2045 (int)bytes));
2046
2047 memcpy(buffer, http->buffer, length);
2048 http->used -= (int)length;
2049
2050 if (http->used > 0)
2051 memmove(http->buffer, http->buffer + length, http->used);
2052 }
2053 #ifdef HAVE_SSL
2054 else if (http->tls)
2055 {
2056 if (!http->blocking)
2057 {
2058 while (!httpWait(http, http->wait_value))
2059 {
2060 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
2061 continue;
2062
2063 return (0);
2064 }
2065 }
2066
2067 while ((bytes = (ssize_t)http_read_ssl(http, buffer, (int)length)) < 0)
2068 {
2069 #ifdef WIN32
2070 if (WSAGetLastError() == WSAEWOULDBLOCK)
2071 {
2072 if (!http->timeout_cb || !(*http->timeout_cb)(http, http->timeout_data))
2073 break;
2074 }
2075 else if (WSAGetLastError() != WSAEINTR)
2076 break;
2077 #else
2078 if (errno == EWOULDBLOCK || errno == EAGAIN)
2079 {
2080 if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
2081 break;
2082 else if (!http->timeout_cb && errno != EAGAIN)
2083 break;
2084 }
2085 else if (errno != EINTR)
2086 break;
2087 #endif /* WIN32 */
2088 }
2089 }
2090 #endif /* HAVE_SSL */
2091 else
2092 {
2093 if (!http->blocking)
2094 {
2095 while (!httpWait(http, http->wait_value))
2096 {
2097 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
2098 continue;
2099
2100 return (0);
2101 }
2102 }
2103
2104 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT " bytes from socket...",
2105 CUPS_LLCAST length));
2106
2107 #ifdef WIN32
2108 while ((bytes = (ssize_t)recv(http->fd, buffer, (int)length, 0)) < 0)
2109 {
2110 if (WSAGetLastError() == WSAEWOULDBLOCK)
2111 {
2112 if (!http->timeout_cb || !(*http->timeout_cb)(http, http->timeout_data))
2113 break;
2114 }
2115 else if (WSAGetLastError() != WSAEINTR)
2116 break;
2117 }
2118 #else
2119 while ((bytes = recv(http->fd, buffer, length, 0)) < 0)
2120 {
2121 if (errno == EWOULDBLOCK || errno == EAGAIN)
2122 {
2123 if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
2124 break;
2125 else if (!http->timeout_cb && errno != EAGAIN)
2126 break;
2127 }
2128 else if (errno != EINTR)
2129 break;
2130 }
2131 #endif /* WIN32 */
2132
2133 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT " bytes from socket...",
2134 CUPS_LLCAST bytes));
2135 #ifdef DEBUG
2136 http_debug_hex("httpRead2", buffer, (int)bytes);
2137 #endif /* DEBUG */
2138 }
2139
2140 if (bytes > 0)
2141 {
2142 http->data_remaining -= bytes;
2143
2144 if (http->data_remaining <= INT_MAX)
2145 http->_data_remaining = (int)http->data_remaining;
2146 else
2147 http->_data_remaining = INT_MAX;
2148 }
2149 else if (bytes < 0)
2150 {
2151 #ifdef WIN32
2152 if (WSAGetLastError() == WSAEINTR)
2153 bytes = 0;
2154 else
2155 http->error = WSAGetLastError();
2156 #else
2157 if (errno == EINTR || (errno == EAGAIN && !http->timeout_cb))
2158 bytes = 0;
2159 else
2160 http->error = errno;
2161 #endif /* WIN32 */
2162 }
2163 else
2164 {
2165 http->error = EPIPE;
2166 return (0);
2167 }
2168
2169 if (http->data_remaining == 0)
2170 {
2171 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
2172 httpGets(len, sizeof(len), http);
2173 else if (http->state == HTTP_POST_RECV)
2174 http->state ++;
2175 else
2176 http->state = HTTP_WAITING;
2177 }
2178
2179 return (bytes);
2180 }
2181
2182
2183 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2184 /*
2185 * '_httpReadCDSA()' - Read function for the CDSA library.
2186 */
2187
2188 OSStatus /* O - -1 on error, 0 on success */
2189 _httpReadCDSA(
2190 SSLConnectionRef connection, /* I - SSL/TLS connection */
2191 void *data, /* I - Data buffer */
2192 size_t *dataLength) /* IO - Number of bytes */
2193 {
2194 OSStatus result; /* Return value */
2195 ssize_t bytes; /* Number of bytes read */
2196 http_t *http; /* HTTP connection */
2197
2198
2199 http = (http_t *)connection;
2200
2201 if (!http->blocking)
2202 {
2203 /*
2204 * Make sure we have data before we read...
2205 */
2206
2207 while (!_httpWait(http, http->wait_value, 0))
2208 {
2209 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
2210 continue;
2211
2212 http->error = ETIMEDOUT;
2213 return (-1);
2214 }
2215 }
2216
2217 do
2218 {
2219 bytes = recv(http->fd, data, *dataLength, 0);
2220 }
2221 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
2222
2223 if (bytes == *dataLength)
2224 {
2225 result = 0;
2226 }
2227 else if (bytes > 0)
2228 {
2229 *dataLength = bytes;
2230 result = errSSLWouldBlock;
2231 }
2232 else
2233 {
2234 *dataLength = 0;
2235
2236 if (bytes == 0)
2237 result = errSSLClosedGraceful;
2238 else if (errno == EAGAIN)
2239 result = errSSLWouldBlock;
2240 else
2241 result = errSSLClosedAbort;
2242 }
2243
2244 return (result);
2245 }
2246 #endif /* HAVE_SSL && HAVE_CDSASSL */
2247
2248
2249 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2250 /*
2251 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2252 */
2253
2254 ssize_t /* O - Number of bytes read or -1 on error */
2255 _httpReadGNUTLS(
2256 gnutls_transport_ptr ptr, /* I - Connection to server */
2257 void *data, /* I - Buffer */
2258 size_t length) /* I - Number of bytes to read */
2259 {
2260 http_t *http; /* HTTP connection */
2261 ssize_t bytes; /* Bytes read */
2262
2263
2264 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr, data, (int)length));
2265
2266 http = (http_t *)ptr;
2267
2268 if (!http->blocking)
2269 {
2270 /*
2271 * Make sure we have data before we read...
2272 */
2273
2274 while (!_httpWait(http, http->wait_value, 0))
2275 {
2276 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
2277 continue;
2278
2279 http->error = ETIMEDOUT;
2280 return (-1);
2281 }
2282 }
2283
2284 bytes = recv(http->fd, data, length, 0);
2285 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes));
2286 return (bytes);
2287 }
2288 #endif /* HAVE_SSL && HAVE_GNUTLS */
2289
2290
2291 /*
2292 * 'httpReconnect()' - Reconnect to a HTTP server.
2293 */
2294
2295 int /* O - 0 on success, non-zero on failure */
2296 httpReconnect(http_t *http) /* I - Connection to server */
2297 {
2298 DEBUG_printf(("httpReconnect(http=%p)", http));
2299
2300 return (httpReconnect2(http, 30000, NULL));
2301 }
2302
2303
2304 /*
2305 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2306 * cancel.
2307 */
2308
2309 int /* O - 0 on success, non-zero on failure */
2310 httpReconnect2(http_t *http, /* I - Connection to server */
2311 int msec, /* I - Timeout in milliseconds */
2312 int *cancel) /* I - Pointer to "cancel" variable */
2313 {
2314 http_addrlist_t *addr; /* Connected address */
2315 #ifdef DEBUG
2316 http_addrlist_t *current; /* Current address */
2317 char temp[256]; /* Temporary address string */
2318 #endif /* DEBUG */
2319
2320
2321 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http, msec,
2322 cancel));
2323
2324 if (!http)
2325 {
2326 _cupsSetError(IPP_INTERNAL_ERROR, strerror(EINVAL), 0);
2327 return (-1);
2328 }
2329
2330 #ifdef HAVE_SSL
2331 if (http->tls)
2332 {
2333 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2334 http_shutdown_ssl(http);
2335 }
2336 #endif /* HAVE_SSL */
2337
2338 /*
2339 * Close any previously open socket...
2340 */
2341
2342 if (http->fd >= 0)
2343 {
2344 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http->fd));
2345
2346 #ifdef WIN32
2347 closesocket(http->fd);
2348 #else
2349 close(http->fd);
2350 #endif /* WIN32 */
2351
2352 http->fd = -1;
2353 }
2354
2355 /*
2356 * Reset all state (except fields, which may be reused)...
2357 */
2358
2359 http->state = HTTP_WAITING;
2360 http->status = HTTP_CONTINUE;
2361 http->version = HTTP_1_1;
2362 http->keep_alive = HTTP_KEEPALIVE_OFF;
2363 memset(&http->_hostaddr, 0, sizeof(http->_hostaddr));
2364 http->data_encoding = HTTP_ENCODE_LENGTH;
2365 http->_data_remaining = 0;
2366 http->used = 0;
2367 http->expect = 0;
2368 http->data_remaining = 0;
2369 http->hostaddr = NULL;
2370 http->wused = 0;
2371
2372 /*
2373 * Connect to the server...
2374 */
2375
2376 #ifdef DEBUG
2377 for (current = http->addrlist; current; current = current->next)
2378 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2379 httpAddrString(&(current->addr), temp, sizeof(temp)),
2380 _httpAddrPort(&(current->addr))));
2381 #endif /* DEBUG */
2382
2383 if ((addr = httpAddrConnect2(http->addrlist, &(http->fd), msec,
2384 cancel)) == NULL)
2385 {
2386 /*
2387 * Unable to connect...
2388 */
2389
2390 #ifdef WIN32
2391 http->error = WSAGetLastError();
2392 #else
2393 http->error = errno;
2394 #endif /* WIN32 */
2395 http->status = HTTP_ERROR;
2396
2397 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2398 strerror(http->error)));
2399
2400 return (-1);
2401 }
2402
2403 DEBUG_printf(("2httpReconnect2: New socket=%d", http->fd));
2404
2405 if (http->timeout_value > 0)
2406 http_set_timeout(http->fd, http->timeout_value);
2407
2408 http->hostaddr = &(addr->addr);
2409 http->error = 0;
2410
2411 #ifdef HAVE_SSL
2412 if (http->encryption == HTTP_ENCRYPT_ALWAYS)
2413 {
2414 /*
2415 * Always do encryption via SSL.
2416 */
2417
2418 if (http_setup_ssl(http) != 0)
2419 {
2420 # ifdef WIN32
2421 closesocket(http->fd);
2422 # else
2423 close(http->fd);
2424 # endif /* WIN32 */
2425
2426 return (-1);
2427 }
2428 }
2429 else if (http->encryption == HTTP_ENCRYPT_REQUIRED)
2430 return (http_upgrade(http));
2431 #endif /* HAVE_SSL */
2432
2433 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2434 httpAddrString(http->hostaddr, temp, sizeof(temp)),
2435 _httpAddrPort(http->hostaddr)));
2436
2437 return (0);
2438 }
2439
2440
2441 /*
2442 * 'httpSetAuthString()' - Set the current authorization string.
2443 *
2444 * This function just stores a copy of the current authorization string in
2445 * the HTTP connection object. You must still call httpSetField() to set
2446 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2447 * httpHead(), httpOptions(), httpPost, or httpPut().
2448 *
2449 * @since CUPS 1.3/OS X 10.5@
2450 */
2451
2452 void
2453 httpSetAuthString(http_t *http, /* I - Connection to server */
2454 const char *scheme, /* I - Auth scheme (NULL to clear it) */
2455 const char *data) /* I - Auth data (NULL for none) */
2456 {
2457 /*
2458 * Range check input...
2459 */
2460
2461 if (!http)
2462 return;
2463
2464 if (http->authstring && http->authstring != http->_authstring)
2465 free(http->authstring);
2466
2467 http->authstring = http->_authstring;
2468
2469 if (scheme)
2470 {
2471 /*
2472 * Set the current authorization string...
2473 */
2474
2475 int len = (int)strlen(scheme) + (data ? (int)strlen(data) + 1 : 0) + 1;
2476 char *temp;
2477
2478 if (len > (int)sizeof(http->_authstring))
2479 {
2480 if ((temp = malloc(len)) == NULL)
2481 len = sizeof(http->_authstring);
2482 else
2483 http->authstring = temp;
2484 }
2485
2486 if (data)
2487 snprintf(http->authstring, len, "%s %s", scheme, data);
2488 else
2489 strlcpy(http->authstring, scheme, len);
2490 }
2491 else
2492 {
2493 /*
2494 * Clear the current authorization string...
2495 */
2496
2497 http->_authstring[0] = '\0';
2498 }
2499 }
2500
2501
2502 /*
2503 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2504 * connection.
2505 *
2506 * @since CUPS 1.5/OS X 10.7@
2507 */
2508
2509 int /* O - Status of call (0 = success) */
2510 httpSetCredentials(http_t *http, /* I - Connection to server */
2511 cups_array_t *credentials) /* I - Array of credentials */
2512 {
2513 if (!http || cupsArrayCount(credentials) < 1)
2514 return (-1);
2515
2516 _httpFreeCredentials(http->tls_credentials);
2517
2518 http->tls_credentials = _httpCreateCredentials(credentials);
2519
2520 return (http->tls_credentials ? 0 : -1);
2521 }
2522
2523
2524 /*
2525 * 'httpSetCookie()' - Set the cookie value(s).
2526 *
2527 * @since CUPS 1.1.19/OS X 10.3@
2528 */
2529
2530 void
2531 httpSetCookie(http_t *http, /* I - Connection */
2532 const char *cookie) /* I - Cookie string */
2533 {
2534 if (!http)
2535 return;
2536
2537 if (http->cookie)
2538 free(http->cookie);
2539
2540 if (cookie)
2541 http->cookie = strdup(cookie);
2542 else
2543 http->cookie = NULL;
2544 }
2545
2546
2547 /*
2548 * 'httpSetExpect()' - Set the Expect: header in a request.
2549 *
2550 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2551 *
2552 * @since CUPS 1.2/OS X 10.5@
2553 */
2554
2555 void
2556 httpSetExpect(http_t *http, /* I - Connection to server */
2557 http_status_t expect) /* I - HTTP status to expect (HTTP_CONTINUE) */
2558 {
2559 if (http)
2560 http->expect = expect;
2561 }
2562
2563
2564 /*
2565 * 'httpSetField()' - Set the value of an HTTP header.
2566 */
2567
2568 void
2569 httpSetField(http_t *http, /* I - Connection to server */
2570 http_field_t field, /* I - Field index */
2571 const char *value) /* I - Value */
2572 {
2573 if (http == NULL ||
2574 field < HTTP_FIELD_ACCEPT_LANGUAGE ||
2575 field > HTTP_FIELD_WWW_AUTHENTICATE ||
2576 value == NULL)
2577 return;
2578
2579 strlcpy(http->fields[field], value, HTTP_MAX_VALUE);
2580
2581 if (field == HTTP_FIELD_AUTHORIZATION)
2582 {
2583 /*
2584 * Special case for Authorization: as its contents can be
2585 * longer than HTTP_MAX_VALUE
2586 */
2587
2588 if (http->field_authorization)
2589 free(http->field_authorization);
2590
2591 http->field_authorization = strdup(value);
2592 }
2593 else if (field == HTTP_FIELD_HOST)
2594 {
2595 /*
2596 * Special-case for Host: as we don't want a trailing "." on the hostname and
2597 * need to bracket IPv6 numeric addresses.
2598 */
2599
2600 char *ptr = strchr(value, ':');
2601
2602 if (value[0] != '[' && ptr && strchr(ptr + 1, ':'))
2603 {
2604 /*
2605 * Bracket IPv6 numeric addresses...
2606 *
2607 * This is slightly inefficient (basically copying twice), but is an edge
2608 * case and not worth optimizing...
2609 */
2610
2611 snprintf(http->fields[HTTP_FIELD_HOST],
2612 sizeof(http->fields[HTTP_FIELD_HOST]), "[%s]", value);
2613 }
2614 else
2615 {
2616 /*
2617 * Check for a trailing dot on the hostname...
2618 */
2619
2620 ptr = http->fields[HTTP_FIELD_HOST];
2621
2622 if (*ptr)
2623 {
2624 ptr += strlen(ptr) - 1;
2625
2626 if (*ptr == '.')
2627 *ptr = '\0';
2628 }
2629 }
2630 }
2631 }
2632
2633
2634 /*
2635 * 'httpSetLength()' - Set the content-length and content-encoding.
2636 *
2637 * @since CUPS 1.2/OS X 10.5@
2638 */
2639
2640 void
2641 httpSetLength(http_t *http, /* I - Connection to server */
2642 size_t length) /* I - Length (0 for chunked) */
2643 {
2644 if (!http)
2645 return;
2646
2647 if (!length)
2648 {
2649 strcpy(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked");
2650 http->fields[HTTP_FIELD_CONTENT_LENGTH][0] = '\0';
2651 }
2652 else
2653 {
2654 http->fields[HTTP_FIELD_TRANSFER_ENCODING][0] = '\0';
2655 snprintf(http->fields[HTTP_FIELD_CONTENT_LENGTH], HTTP_MAX_VALUE,
2656 CUPS_LLFMT, CUPS_LLCAST length);
2657 }
2658 }
2659
2660
2661 /*
2662 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2663 *
2664 * The optional timeout callback receives both the HTTP connection and a user
2665 * data pointer and must return 1 to continue or 0 to error (time) out.
2666 *
2667 * @since CUPS 1.5/OS X 10.7@
2668 */
2669
2670 void
2671 httpSetTimeout(
2672 http_t *http, /* I - Connection to server */
2673 double timeout, /* I - Number of seconds for timeout,
2674 must be greater than 0 */
2675 http_timeout_cb_t cb, /* I - Callback function or NULL */
2676 void *user_data) /* I - User data pointer */
2677 {
2678 if (!http || timeout <= 0.0)
2679 return;
2680
2681 http->timeout_cb = cb;
2682 http->timeout_data = user_data;
2683 http->timeout_value = timeout;
2684
2685 if (http->fd >= 0)
2686 http_set_timeout(http->fd, timeout);
2687
2688 http_set_wait(http);
2689 }
2690
2691
2692 /*
2693 * 'httpTrace()' - Send an TRACE request to the server.
2694 */
2695
2696 int /* O - Status of call (0 = success) */
2697 httpTrace(http_t *http, /* I - Connection to server */
2698 const char *uri) /* I - URI for trace */
2699 {
2700 return (http_send(http, HTTP_TRACE, uri));
2701 }
2702
2703
2704 /*
2705 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2706 *
2707 * Note: Unlike httpUpdate(), this function does not flush pending write data
2708 * and only retrieves a single status line from the HTTP connection.
2709 */
2710
2711 int /* O - 1 to continue, 0 to stop */
2712 _httpUpdate(http_t *http, /* I - Connection to server */
2713 http_status_t *status) /* O - Current HTTP status */
2714 {
2715 char line[32768], /* Line from connection... */
2716 *value; /* Pointer to value on line */
2717 http_field_t field; /* Field index */
2718 int major, minor; /* HTTP version numbers */
2719
2720
2721 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http, status,
2722 http_states[http->state]));
2723
2724 /*
2725 * Grab a single line from the connection...
2726 */
2727
2728 if (!httpGets(line, sizeof(line), http))
2729 {
2730 *status = HTTP_ERROR;
2731 return (0);
2732 }
2733
2734 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line));
2735
2736 if (line[0] == '\0')
2737 {
2738 /*
2739 * Blank line means the start of the data section (if any). Return
2740 * the result code, too...
2741 *
2742 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2743 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2744 * tryin'...
2745 */
2746
2747 if (http->status == HTTP_CONTINUE)
2748 {
2749 *status = http->status;
2750 return (0);
2751 }
2752
2753 if (http->status < HTTP_BAD_REQUEST)
2754 http->digest_tries = 0;
2755
2756 #ifdef HAVE_SSL
2757 if (http->status == HTTP_SWITCHING_PROTOCOLS && !http->tls)
2758 {
2759 if (http_setup_ssl(http) != 0)
2760 {
2761 # ifdef WIN32
2762 closesocket(http->fd);
2763 # else
2764 close(http->fd);
2765 # endif /* WIN32 */
2766
2767 *status = http->status = HTTP_ERROR;
2768 return (0);
2769 }
2770
2771 *status = HTTP_CONTINUE;
2772 return (0);
2773 }
2774 #endif /* HAVE_SSL */
2775
2776 httpGetLength2(http);
2777
2778 switch (http->state)
2779 {
2780 case HTTP_GET :
2781 case HTTP_POST :
2782 case HTTP_POST_RECV :
2783 case HTTP_PUT :
2784 http->state ++;
2785 case HTTP_POST_SEND :
2786 case HTTP_HEAD :
2787 break;
2788
2789 default :
2790 http->state = HTTP_WAITING;
2791 break;
2792 }
2793
2794 *status = http->status;
2795 return (0);
2796 }
2797 else if (!strncmp(line, "HTTP/", 5))
2798 {
2799 /*
2800 * Got the beginning of a response...
2801 */
2802
2803 int intstatus; /* Status value as an integer */
2804
2805 if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, &intstatus) != 3)
2806 {
2807 *status = http->status = HTTP_ERROR;
2808 return (0);
2809 }
2810
2811 http->version = (http_version_t)(major * 100 + minor);
2812 *status = http->status = (http_status_t)intstatus;
2813 }
2814 else if ((value = strchr(line, ':')) != NULL)
2815 {
2816 /*
2817 * Got a value...
2818 */
2819
2820 *value++ = '\0';
2821 while (_cups_isspace(*value))
2822 value ++;
2823
2824 /*
2825 * Be tolerants of servers that send unknown attribute fields...
2826 */
2827
2828 if (!_cups_strcasecmp(line, "expect"))
2829 {
2830 /*
2831 * "Expect: 100-continue" or similar...
2832 */
2833
2834 http->expect = (http_status_t)atoi(value);
2835 }
2836 else if (!_cups_strcasecmp(line, "cookie"))
2837 {
2838 /*
2839 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2840 */
2841
2842 httpSetCookie(http, value);
2843 }
2844 else if ((field = http_field(line)) != HTTP_FIELD_UNKNOWN)
2845 httpSetField(http, field, value);
2846 #ifdef DEBUG
2847 else
2848 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line));
2849 #endif /* DEBUG */
2850 }
2851 else
2852 {
2853 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line));
2854 *status = http->status = HTTP_ERROR;
2855 return (0);
2856 }
2857
2858 return (1);
2859 }
2860
2861
2862 /*
2863 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2864 */
2865
2866 http_status_t /* O - HTTP status */
2867 httpUpdate(http_t *http) /* I - Connection to server */
2868 {
2869 http_status_t status; /* Request status */
2870
2871
2872 DEBUG_printf(("httpUpdate(http=%p), state=%s", http,
2873 http_states[http->state]));
2874
2875 /*
2876 * Flush pending data, if any...
2877 */
2878
2879 if (http->wused)
2880 {
2881 DEBUG_puts("2httpUpdate: flushing buffer...");
2882
2883 if (httpFlushWrite(http) < 0)
2884 return (HTTP_ERROR);
2885 }
2886
2887 /*
2888 * If we haven't issued any commands, then there is nothing to "update"...
2889 */
2890
2891 if (http->state == HTTP_WAITING)
2892 return (HTTP_CONTINUE);
2893
2894 /*
2895 * Grab all of the lines we can from the connection...
2896 */
2897
2898 while (_httpUpdate(http, &status));
2899
2900 /*
2901 * See if there was an error...
2902 */
2903
2904 if (http->error == EPIPE && http->status > HTTP_CONTINUE)
2905 {
2906 DEBUG_printf(("1httpUpdate: Returning status %d...", http->status));
2907 return (http->status);
2908 }
2909
2910 if (http->error)
2911 {
2912 DEBUG_printf(("1httpUpdate: socket error %d - %s", http->error,
2913 strerror(http->error)));
2914 http->status = HTTP_ERROR;
2915 return (HTTP_ERROR);
2916 }
2917
2918 /*
2919 * Return the current status...
2920 */
2921
2922 return (status);
2923 }
2924
2925
2926 /*
2927 * '_httpWait()' - Wait for data available on a connection (no flush).
2928 */
2929
2930 int /* O - 1 if data is available, 0 otherwise */
2931 _httpWait(http_t *http, /* I - Connection to server */
2932 int msec, /* I - Milliseconds to wait */
2933 int usessl) /* I - Use SSL context? */
2934 {
2935 #ifdef HAVE_POLL
2936 struct pollfd pfd; /* Polled file descriptor */
2937 #else
2938 fd_set input_set; /* select() input set */
2939 struct timeval timeout; /* Timeout */
2940 #endif /* HAVE_POLL */
2941 int nfds; /* Result from select()/poll() */
2942
2943
2944 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http, msec, usessl));
2945
2946 if (http->fd < 0)
2947 {
2948 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http->fd));
2949 return (0);
2950 }
2951
2952 /*
2953 * Check the SSL/TLS buffers for data first...
2954 */
2955
2956 #ifdef HAVE_SSL
2957 if (http->tls && usessl)
2958 {
2959 # ifdef HAVE_LIBSSL
2960 if (SSL_pending(http->tls))
2961 {
2962 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2963 return (1);
2964 }
2965
2966 # elif defined(HAVE_GNUTLS)
2967 if (gnutls_record_check_pending(http->tls))
2968 {
2969 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2970 return (1);
2971 }
2972
2973 # elif defined(HAVE_CDSASSL)
2974 size_t bytes; /* Bytes that are available */
2975
2976 if (!SSLGetBufferedReadSize(http->tls, &bytes) &&
2977 bytes > 0)
2978 {
2979 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2980 return (1);
2981 }
2982 # endif /* HAVE_LIBSSL */
2983 }
2984 #endif /* HAVE_SSL */
2985
2986 /*
2987 * Then try doing a select() or poll() to poll the socket...
2988 */
2989
2990 #ifdef HAVE_POLL
2991 pfd.fd = http->fd;
2992 pfd.events = POLLIN;
2993
2994 while ((nfds = poll(&pfd, 1, msec)) < 0 &&
2995 (errno == EINTR || errno == EAGAIN));
2996
2997 #else
2998 do
2999 {
3000 FD_ZERO(&input_set);
3001 FD_SET(http->fd, &input_set);
3002
3003 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec, http->fd));
3004
3005 if (msec >= 0)
3006 {
3007 timeout.tv_sec = msec / 1000;
3008 timeout.tv_usec = (msec % 1000) * 1000;
3009
3010 nfds = select(http->fd + 1, &input_set, NULL, NULL, &timeout);
3011 }
3012 else
3013 nfds = select(http->fd + 1, &input_set, NULL, NULL, NULL);
3014
3015 DEBUG_printf(("6_httpWait: select() returned %d...", nfds));
3016 }
3017 # ifdef WIN32
3018 while (nfds < 0 && (WSAGetLastError() == WSAEINTR ||
3019 WSAGetLastError() == WSAEWOULDBLOCK));
3020 # else
3021 while (nfds < 0 && (errno == EINTR || errno == EAGAIN));
3022 # endif /* WIN32 */
3023 #endif /* HAVE_POLL */
3024
3025 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds,
3026 errno));
3027
3028 return (nfds > 0);
3029 }
3030
3031
3032 /*
3033 * 'httpWait()' - Wait for data available on a connection.
3034 *
3035 * @since CUPS 1.1.19/OS X 10.3@
3036 */
3037
3038 int /* O - 1 if data is available, 0 otherwise */
3039 httpWait(http_t *http, /* I - Connection to server */
3040 int msec) /* I - Milliseconds to wait */
3041 {
3042 /*
3043 * First see if there is data in the buffer...
3044 */
3045
3046 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http, msec));
3047
3048 if (http == NULL)
3049 return (0);
3050
3051 if (http->used)
3052 {
3053 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3054 return (1);
3055 }
3056
3057 /*
3058 * Flush pending data, if any...
3059 */
3060
3061 if (http->wused)
3062 {
3063 DEBUG_puts("3httpWait: Flushing write buffer.");
3064
3065 if (httpFlushWrite(http) < 0)
3066 return (0);
3067 }
3068
3069 /*
3070 * If not, check the SSL/TLS buffers and do a select() on the connection...
3071 */
3072
3073 return (_httpWait(http, msec, 1));
3074 }
3075
3076
3077 /*
3078 * 'httpWrite()' - Write data to a HTTP connection.
3079 *
3080 * This function is deprecated. Use the httpWrite2() function which can
3081 * write more than 2GB of data.
3082 *
3083 * @deprecated@
3084 */
3085
3086 int /* O - Number of bytes written */
3087 httpWrite(http_t *http, /* I - Connection to server */
3088 const char *buffer, /* I - Buffer for data */
3089 int length) /* I - Number of bytes to write */
3090 {
3091 return ((int)httpWrite2(http, buffer, length));
3092 }
3093
3094
3095 /*
3096 * 'httpWrite2()' - Write data to a HTTP connection.
3097 *
3098 * @since CUPS 1.2/OS X 10.5@
3099 */
3100
3101 ssize_t /* O - Number of bytes written */
3102 httpWrite2(http_t *http, /* I - Connection to server */
3103 const char *buffer, /* I - Buffer for data */
3104 size_t length) /* I - Number of bytes to write */
3105 {
3106 ssize_t bytes; /* Bytes written */
3107
3108
3109 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT ")", http,
3110 buffer, CUPS_LLCAST length));
3111
3112 /*
3113 * Range check input...
3114 */
3115
3116 if (http == NULL || buffer == NULL)
3117 return (-1);
3118
3119 /*
3120 * Mark activity on the connection...
3121 */
3122
3123 http->activity = time(NULL);
3124
3125 /*
3126 * Buffer small writes for better performance...
3127 */
3128
3129 if (length > 0)
3130 {
3131 if (http->wused && (length + http->wused) > sizeof(http->wbuffer))
3132 {
3133 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3134 CUPS_LLFMT ")", http->wused, CUPS_LLCAST length));
3135
3136 httpFlushWrite(http);
3137 }
3138
3139 if ((length + http->wused) <= sizeof(http->wbuffer) &&
3140 length < sizeof(http->wbuffer))
3141 {
3142 /*
3143 * Write to buffer...
3144 */
3145
3146 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT " bytes to wbuffer...",
3147 CUPS_LLCAST length));
3148
3149 memcpy(http->wbuffer + http->wused, buffer, length);
3150 http->wused += (int)length;
3151 bytes = (ssize_t)length;
3152 }
3153 else
3154 {
3155 /*
3156 * Otherwise write the data directly...
3157 */
3158
3159 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT " bytes to socket...",
3160 CUPS_LLCAST length));
3161
3162 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
3163 bytes = (ssize_t)http_write_chunk(http, buffer, (int)length);
3164 else
3165 bytes = (ssize_t)http_write(http, buffer, (int)length);
3166
3167 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT " bytes...",
3168 CUPS_LLCAST bytes));
3169 }
3170
3171 if (http->data_encoding == HTTP_ENCODE_LENGTH)
3172 http->data_remaining -= bytes;
3173 }
3174 else
3175 bytes = 0;
3176
3177 /*
3178 * Handle end-of-request processing...
3179 */
3180
3181 if ((http->data_encoding == HTTP_ENCODE_CHUNKED && length == 0) ||
3182 (http->data_encoding == HTTP_ENCODE_LENGTH && http->data_remaining == 0))
3183 {
3184 /*
3185 * Finished with the transfer; unless we are sending POST or PUT
3186 * data, go idle...
3187 */
3188
3189 DEBUG_puts("2httpWrite: changing states...");
3190
3191 if (http->wused)
3192 httpFlushWrite(http);
3193
3194 if (http->data_encoding == HTTP_ENCODE_CHUNKED)
3195 {
3196 /*
3197 * Send a 0-length chunk at the end of the request...
3198 */
3199
3200 http_write(http, "0\r\n\r\n", 5);
3201
3202 /*
3203 * Reset the data state...
3204 */
3205
3206 http->data_encoding = HTTP_ENCODE_LENGTH;
3207 http->data_remaining = 0;
3208 }
3209 }
3210
3211 return (bytes);
3212 }
3213
3214
3215 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3216 /*
3217 * '_httpWriteCDSA()' - Write function for the CDSA library.
3218 */
3219
3220 OSStatus /* O - -1 on error, 0 on success */
3221 _httpWriteCDSA(
3222 SSLConnectionRef connection, /* I - SSL/TLS connection */
3223 const void *data, /* I - Data buffer */
3224 size_t *dataLength) /* IO - Number of bytes */
3225 {
3226 OSStatus result; /* Return value */
3227 ssize_t bytes; /* Number of bytes read */
3228 http_t *http; /* HTTP connection */
3229
3230
3231 http = (http_t *)connection;
3232
3233 do
3234 {
3235 bytes = write(http->fd, data, *dataLength);
3236 }
3237 while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
3238
3239 if (bytes == *dataLength)
3240 {
3241 result = 0;
3242 }
3243 else if (bytes >= 0)
3244 {
3245 *dataLength = bytes;
3246 result = errSSLWouldBlock;
3247 }
3248 else
3249 {
3250 *dataLength = 0;
3251
3252 if (errno == EAGAIN)
3253 result = errSSLWouldBlock;
3254 else
3255 result = errSSLClosedAbort;
3256 }
3257
3258 return (result);
3259 }
3260 #endif /* HAVE_SSL && HAVE_CDSASSL */
3261
3262
3263 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3264 /*
3265 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3266 */
3267
3268 ssize_t /* O - Number of bytes written or -1 on error */
3269 _httpWriteGNUTLS(
3270 gnutls_transport_ptr ptr, /* I - Connection to server */
3271 const void *data, /* I - Data buffer */
3272 size_t length) /* I - Number of bytes to write */
3273 {
3274 ssize_t bytes; /* Bytes written */
3275
3276
3277 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr, data,
3278 (int)length));
3279 #ifdef DEBUG
3280 http_debug_hex("_httpWriteGNUTLS", data, (int)length);
3281 #endif /* DEBUG */
3282
3283 bytes = send(((http_t *)ptr)->fd, data, length, 0);
3284 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes));
3285
3286 return (bytes);
3287 }
3288 #endif /* HAVE_SSL && HAVE_GNUTLS */
3289
3290
3291 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3292 /*
3293 * 'http_bio_ctrl()' - Control the HTTP connection.
3294 */
3295
3296 static long /* O - Result/data */
3297 http_bio_ctrl(BIO *h, /* I - BIO data */
3298 int cmd, /* I - Control command */
3299 long arg1, /* I - First argument */
3300 void *arg2) /* I - Second argument */
3301 {
3302 switch (cmd)
3303 {
3304 default :
3305 return (0);
3306
3307 case BIO_CTRL_RESET :
3308 h->ptr = NULL;
3309 return (0);
3310
3311 case BIO_C_SET_FILE_PTR :
3312 h->ptr = arg2;
3313 h->init = 1;
3314 return (1);
3315
3316 case BIO_C_GET_FILE_PTR :
3317 if (arg2)
3318 {
3319 *((void **)arg2) = h->ptr;
3320 return (1);
3321 }
3322 else
3323 return (0);
3324
3325 case BIO_CTRL_DUP :
3326 case BIO_CTRL_FLUSH :
3327 return (1);
3328 }
3329 }
3330
3331
3332 /*
3333 * 'http_bio_free()' - Free OpenSSL data.
3334 */
3335
3336 static int /* O - 1 on success, 0 on failure */
3337 http_bio_free(BIO *h) /* I - BIO data */
3338 {
3339 if (!h)
3340 return (0);
3341
3342 if (h->shutdown)
3343 {
3344 h->init = 0;
3345 h->flags = 0;
3346 }
3347
3348 return (1);
3349 }
3350
3351
3352 /*
3353 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3354 */
3355
3356 static int /* O - 1 on success, 0 on failure */
3357 http_bio_new(BIO *h) /* I - BIO data */
3358 {
3359 if (!h)
3360 return (0);
3361
3362 h->init = 0;
3363 h->num = 0;
3364 h->ptr = NULL;
3365 h->flags = 0;
3366
3367 return (1);
3368 }
3369
3370
3371 /*
3372 * 'http_bio_puts()' - Send a string for OpenSSL.
3373 */
3374
3375 static int /* O - Bytes written */
3376 http_bio_puts(BIO *h, /* I - BIO data */
3377 const char *str) /* I - String to write */
3378 {
3379 #ifdef WIN32
3380 return (send(((http_t *)h->ptr)->fd, str, (int)strlen(str), 0));
3381 #else
3382 return (send(((http_t *)h->ptr)->fd, str, strlen(str), 0));
3383 #endif /* WIN32 */
3384 }
3385
3386
3387 /*
3388 * 'http_bio_read()' - Read data for OpenSSL.
3389 */
3390
3391 static int /* O - Bytes read */
3392 http_bio_read(BIO *h, /* I - BIO data */
3393 char *buf, /* I - Buffer */
3394 int size) /* I - Number of bytes to read */
3395 {
3396 http_t *http; /* HTTP connection */
3397
3398
3399 http = (http_t *)h->ptr;
3400
3401 if (!http->blocking)
3402 {
3403 /*
3404 * Make sure we have data before we read...
3405 */
3406
3407 while (!_httpWait(http, http->wait_value, 0))
3408 {
3409 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
3410 continue;
3411
3412 #ifdef WIN32
3413 http->error = WSAETIMEDOUT;
3414 #else
3415 http->error = ETIMEDOUT;
3416 #endif /* WIN32 */
3417
3418 return (-1);
3419 }
3420 }
3421
3422 return (recv(http->fd, buf, size, 0));
3423 }
3424
3425
3426 /*
3427 * 'http_bio_write()' - Write data for OpenSSL.
3428 */
3429
3430 static int /* O - Bytes written */
3431 http_bio_write(BIO *h, /* I - BIO data */
3432 const char *buf, /* I - Buffer to write */
3433 int num) /* I - Number of bytes to write */
3434 {
3435 return (send(((http_t *)h->ptr)->fd, buf, num, 0));
3436 }
3437 #endif /* HAVE_SSL && HAVE_LIBSSL */
3438
3439
3440 #ifdef DEBUG
3441 /*
3442 * 'http_debug_hex()' - Do a hex dump of a buffer.
3443 */
3444
3445 static void
3446 http_debug_hex(const char *prefix, /* I - Prefix for line */
3447 const char *buffer, /* I - Buffer to dump */
3448 int bytes) /* I - Bytes to dump */
3449 {
3450 int i, j, /* Looping vars */
3451 ch; /* Current character */
3452 char line[255], /* Line buffer */
3453 *start, /* Start of line after prefix */
3454 *ptr; /* Pointer into line */
3455
3456
3457 if (_cups_debug_fd < 0 || _cups_debug_level < 6)
3458 return;
3459
3460 DEBUG_printf(("6%s: %d bytes:", prefix, bytes));
3461
3462 snprintf(line, sizeof(line), "6%s: ", prefix);
3463 start = line + strlen(line);
3464
3465 for (i = 0; i < bytes; i += 16)
3466 {
3467 for (j = 0, ptr = start; j < 16 && (i + j) < bytes; j ++, ptr += 2)
3468 sprintf(ptr, "%02X", buffer[i + j] & 255);
3469
3470 while (j < 16)
3471 {
3472 strcpy(ptr, " ");
3473 ptr += 2;
3474 j ++;
3475 }
3476
3477 strcpy(ptr, " ");
3478 ptr += 2;
3479
3480 for (j = 0; j < 16 && (i + j) < bytes; j ++)
3481 {
3482 ch = buffer[i + j] & 255;
3483
3484 if (ch < ' ' || ch >= 127)
3485 ch = '.';
3486
3487 *ptr++ = ch;
3488 }
3489
3490 *ptr = '\0';
3491 DEBUG_puts(line);
3492 }
3493 }
3494 #endif /* DEBUG */
3495
3496
3497 /*
3498 * 'http_field()' - Return the field index for a field name.
3499 */
3500
3501 static http_field_t /* O - Field index */
3502 http_field(const char *name) /* I - String name */
3503 {
3504 int i; /* Looping var */
3505
3506
3507 for (i = 0; i < HTTP_FIELD_MAX; i ++)
3508 if (_cups_strcasecmp(name, http_fields[i]) == 0)
3509 return ((http_field_t)i);
3510
3511 return (HTTP_FIELD_UNKNOWN);
3512 }
3513
3514
3515 #ifdef HAVE_SSL
3516 /*
3517 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3518 */
3519
3520 static int /* O - Bytes read */
3521 http_read_ssl(http_t *http, /* I - Connection to server */
3522 char *buf, /* I - Buffer to store data */
3523 int len) /* I - Length of buffer */
3524 {
3525 # if defined(HAVE_LIBSSL)
3526 return (SSL_read((SSL *)(http->tls), buf, len));
3527
3528 # elif defined(HAVE_GNUTLS)
3529 ssize_t result; /* Return value */
3530
3531
3532 result = gnutls_record_recv(http->tls, buf, len);
3533
3534 if (result < 0 && !errno)
3535 {
3536 /*
3537 * Convert GNU TLS error to errno value...
3538 */
3539
3540 switch (result)
3541 {
3542 case GNUTLS_E_INTERRUPTED :
3543 errno = EINTR;
3544 break;
3545
3546 case GNUTLS_E_AGAIN :
3547 errno = EAGAIN;
3548 break;
3549
3550 default :
3551 errno = EPIPE;
3552 break;
3553 }
3554
3555 result = -1;
3556 }
3557
3558 return ((int)result);
3559
3560 # elif defined(HAVE_CDSASSL)
3561 int result; /* Return value */
3562 OSStatus error; /* Error info */
3563 size_t processed; /* Number of bytes processed */
3564
3565
3566 error = SSLRead(http->tls, buf, len, &processed);
3567 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error,
3568 (int)processed));
3569 switch (error)
3570 {
3571 case 0 :
3572 result = (int)processed;
3573 break;
3574
3575 case errSSLWouldBlock :
3576 if (processed)
3577 result = (int)processed;
3578 else
3579 {
3580 result = -1;
3581 errno = EINTR;
3582 }
3583 break;
3584
3585 case errSSLClosedGraceful :
3586 default :
3587 if (processed)
3588 result = (int)processed;
3589 else
3590 {
3591 result = -1;
3592 errno = EPIPE;
3593 }
3594 break;
3595 }
3596
3597 return (result);
3598
3599 # elif defined(HAVE_SSPISSL)
3600 return _sspiRead((_sspi_struct_t*) http->tls, buf, len);
3601 # endif /* HAVE_LIBSSL */
3602 }
3603 #endif /* HAVE_SSL */
3604
3605
3606 /*
3607 * 'http_send()' - Send a request with all fields and the trailing blank line.
3608 */
3609
3610 static int /* O - 0 on success, non-zero on error */
3611 http_send(http_t *http, /* I - Connection to server */
3612 http_state_t request, /* I - Request code */
3613 const char *uri) /* I - URI */
3614 {
3615 int i; /* Looping var */
3616 char buf[1024]; /* Encoded URI buffer */
3617 static const char * const codes[] =
3618 { /* Request code strings */
3619 NULL,
3620 "OPTIONS",
3621 "GET",
3622 NULL,
3623 "HEAD",
3624 "POST",
3625 NULL,
3626 NULL,
3627 "PUT",
3628 NULL,
3629 "DELETE",
3630 "TRACE",
3631 "CLOSE"
3632 };
3633
3634
3635 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3636 http, codes[request], uri));
3637
3638 if (http == NULL || uri == NULL)
3639 return (-1);
3640
3641 /*
3642 * Set the User-Agent field if it isn't already...
3643 */
3644
3645 if (!http->fields[HTTP_FIELD_USER_AGENT][0])
3646 httpSetField(http, HTTP_FIELD_USER_AGENT, CUPS_MINIMAL);
3647
3648 /*
3649 * Encode the URI as needed...
3650 */
3651
3652 _httpEncodeURI(buf, uri, sizeof(buf));
3653
3654 /*
3655 * See if we had an error the last time around; if so, reconnect...
3656 */
3657
3658 if (http->status == HTTP_ERROR || http->status >= HTTP_BAD_REQUEST)
3659 if (httpReconnect(http))
3660 return (-1);
3661
3662 /*
3663 * Flush any written data that is pending...
3664 */
3665
3666 if (http->wused)
3667 {
3668 if (httpFlushWrite(http) < 0)
3669 if (httpReconnect(http))
3670 return (-1);
3671 }
3672
3673 /*
3674 * Send the request header...
3675 */
3676
3677 http->state = request;
3678 http->data_encoding = HTTP_ENCODE_FIELDS;
3679
3680 if (request == HTTP_POST || request == HTTP_PUT)
3681 http->state ++;
3682
3683 http->status = HTTP_CONTINUE;
3684
3685 #ifdef HAVE_SSL
3686 if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
3687 {
3688 httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
3689 httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.0,SSL/2.0,SSL/3.0");
3690 }
3691 #endif /* HAVE_SSL */
3692
3693 if (httpPrintf(http, "%s %s HTTP/1.1\r\n", codes[request], buf) < 1)
3694 {
3695 http->status = HTTP_ERROR;
3696 return (-1);
3697 }
3698
3699 for (i = 0; i < HTTP_FIELD_MAX; i ++)
3700 if (http->fields[i][0] != '\0')
3701 {
3702 DEBUG_printf(("9http_send: %s: %s", http_fields[i],
3703 httpGetField(http, i)));
3704
3705 if (i == HTTP_FIELD_HOST)
3706 {
3707 if (httpPrintf(http, "Host: %s:%d\r\n", httpGetField(http, i),
3708 _httpAddrPort(http->hostaddr)) < 1)
3709 {
3710 http->status = HTTP_ERROR;
3711 return (-1);
3712 }
3713 }
3714 else if (httpPrintf(http, "%s: %s\r\n", http_fields[i],
3715 httpGetField(http, i)) < 1)
3716 {
3717 http->status = HTTP_ERROR;
3718 return (-1);
3719 }
3720 }
3721
3722 if (http->cookie)
3723 if (httpPrintf(http, "Cookie: $Version=0; %s\r\n", http->cookie) < 1)
3724 {
3725 http->status = HTTP_ERROR;
3726 return (-1);
3727 }
3728
3729 if (http->expect == HTTP_CONTINUE &&
3730 (http->state == HTTP_POST_RECV || http->state == HTTP_PUT_RECV))
3731 if (httpPrintf(http, "Expect: 100-continue\r\n") < 1)
3732 {
3733 http->status = HTTP_ERROR;
3734 return (-1);
3735 }
3736
3737 if (httpPrintf(http, "\r\n") < 1)
3738 {
3739 http->status = HTTP_ERROR;
3740 return (-1);
3741 }
3742
3743 if (httpFlushWrite(http) < 0)
3744 return (-1);
3745
3746 httpGetLength2(http);
3747 httpClearFields(http);
3748
3749 /*
3750 * The Kerberos and AuthRef authentication strings can only be used once...
3751 */
3752
3753 if (http->field_authorization && http->authstring &&
3754 (!strncmp(http->authstring, "Negotiate", 9) ||
3755 !strncmp(http->authstring, "AuthRef", 7)))
3756 {
3757 http->_authstring[0] = '\0';
3758
3759 if (http->authstring != http->_authstring)
3760 free(http->authstring);
3761
3762 http->authstring = http->_authstring;
3763 }
3764
3765 return (0);
3766 }
3767
3768
3769 #ifdef HAVE_SSL
3770 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
3771 /*
3772 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3773 */
3774
3775 static int /* O - Status of connection */
3776 http_set_credentials(http_t *http) /* I - Connection to server */
3777 {
3778 _cups_globals_t *cg = _cupsGlobals(); /* Pointer to library globals */
3779 OSStatus error = 0; /* Error code */
3780 http_tls_credentials_t credentials = NULL;
3781 /* TLS credentials */
3782
3783
3784 DEBUG_printf(("7http_set_credentials(%p)", http));
3785
3786 /*
3787 * Prefer connection specific credentials...
3788 */
3789
3790 if ((credentials = http->tls_credentials) == NULL)
3791 credentials = cg->tls_credentials;
3792
3793 # if HAVE_SECPOLICYCREATESSL
3794 /*
3795 * Otherwise root around in the user's keychain to see if one can be found...
3796 */
3797
3798 if (!credentials)
3799 {
3800 CFDictionaryRef query; /* Query dictionary */
3801 CFTypeRef matches = NULL; /* Matching credentials */
3802 CFArrayRef dn_array = NULL;/* Distinguished names array */
3803 CFTypeRef keys[] = { kSecClass,
3804 kSecMatchLimit,
3805 kSecReturnRef };
3806 /* Keys for dictionary */
3807 CFTypeRef values[] = { kSecClassCertificate,
3808 kSecMatchLimitOne,
3809 kCFBooleanTrue };
3810 /* Values for dictionary */
3811
3812 /*
3813 * Get the names associated with the server.
3814 */
3815
3816 if ((error = SSLCopyDistinguishedNames(http->tls, &dn_array)) != noErr)
3817 {
3818 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3819 (int)error));
3820 return (error);
3821 }
3822
3823 /*
3824 * Create a query which will return all identities that can sign and match
3825 * the passed in policy.
3826 */
3827
3828 query = CFDictionaryCreate(NULL,
3829 (const void**)(&keys[0]),
3830 (const void**)(&values[0]),
3831 sizeof(keys) / sizeof(keys[0]),
3832 &kCFTypeDictionaryKeyCallBacks,
3833 &kCFTypeDictionaryValueCallBacks);
3834 if (query)
3835 {
3836 error = SecItemCopyMatching(query, &matches);
3837 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3838 (int)error));
3839 CFRelease(query);
3840 }
3841
3842 if (matches)
3843 CFRelease(matches);
3844
3845 if (dn_array)
3846 CFRelease(dn_array);
3847 }
3848 # endif /* HAVE_SECPOLICYCREATESSL */
3849
3850 if (credentials)
3851 {
3852 error = SSLSetCertificate(http->tls, credentials);
3853 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3854 (int)error));
3855 }
3856 else
3857 DEBUG_puts("4http_set_credentials: No credentials to set.");
3858
3859 return (error);
3860 }
3861 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
3862 #endif /* HAVE_SSL */
3863
3864
3865 /*
3866 * 'http_set_timeout()' - Set the socket timeout values.
3867 */
3868
3869 static void
3870 http_set_timeout(int fd, /* I - File descriptor */
3871 double timeout) /* I - Timeout in seconds */
3872 {
3873 #ifdef WIN32
3874 DWORD tv = (DWORD)(timeout * 1000);
3875 /* Timeout in milliseconds */
3876
3877 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
3878 setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
3879
3880 #else
3881 struct timeval tv; /* Timeout in secs and usecs */
3882
3883 tv.tv_sec = (int)timeout;
3884 tv.tv_usec = (int)(1000000 * fmod(timeout, 1.0));
3885
3886 setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
3887 setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
3888 #endif /* WIN32 */
3889 }
3890
3891
3892 /*
3893 * 'http_set_wait()' - Set the default wait value for reads.
3894 */
3895
3896 static void
3897 http_set_wait(http_t *http) /* I - Connection to server */
3898 {
3899 if (http->blocking)
3900 {
3901 http->wait_value = (int)(http->timeout_value * 1000);
3902
3903 if (http->wait_value <= 0)
3904 http->wait_value = 60000;
3905 }
3906 else
3907 http->wait_value = 10000;
3908 }
3909
3910
3911 #ifdef HAVE_SSL
3912 /*
3913 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3914 */
3915
3916 static int /* O - 0 on success, -1 on failure */
3917 http_setup_ssl(http_t *http) /* I - Connection to server */
3918 {
3919 _cups_globals_t *cg = _cupsGlobals();
3920 /* Pointer to library globals */
3921 int any_root; /* Allow any root */
3922 char hostname[256], /* Hostname */
3923 *hostptr; /* Pointer into hostname */
3924
3925 # ifdef HAVE_LIBSSL
3926 SSL_CTX *context; /* Context for encryption */
3927 BIO *bio; /* BIO data */
3928 const char *message = NULL;/* Error message */
3929 # elif defined(HAVE_GNUTLS)
3930 int status; /* Status of handshake */
3931 gnutls_certificate_client_credentials *credentials;
3932 /* TLS credentials */
3933 # elif defined(HAVE_CDSASSL)
3934 OSStatus error; /* Error code */
3935 const char *message = NULL;/* Error message */
3936 # ifdef HAVE_SECCERTIFICATECOPYDATA
3937 cups_array_t *credentials; /* Credentials array */
3938 cups_array_t *names; /* CUPS distinguished names */
3939 CFArrayRef dn_array; /* CF distinguished names array */
3940 CFIndex count; /* Number of credentials */
3941 CFDataRef data; /* Certificate data */
3942 int i; /* Looping var */
3943 http_credential_t *credential; /* Credential data */
3944 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3945 # elif defined(HAVE_SSPISSL)
3946 TCHAR username[256]; /* Username returned from GetUserName() */
3947 TCHAR commonName[256];/* Common name for certificate */
3948 DWORD dwSize; /* 32 bit size */
3949 # endif /* HAVE_LIBSSL */
3950
3951
3952 DEBUG_printf(("7http_setup_ssl(http=%p)", http));
3953
3954 /*
3955 * Always allow self-signed certificates for the local loopback address...
3956 */
3957
3958 if (httpAddrLocalhost(http->hostaddr))
3959 {
3960 any_root = 1;
3961 strlcpy(hostname, "localhost", sizeof(hostname));
3962 }
3963 else
3964 {
3965 /*
3966 * Otherwise use the system-wide setting and make sure the hostname we have
3967 * does not end in a trailing dot.
3968 */
3969
3970 any_root = cg->any_root;
3971
3972 strlcpy(hostname, http->hostname, sizeof(hostname));
3973 if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
3974 *hostptr == '.')
3975 *hostptr = '\0';
3976 }
3977
3978 # ifdef HAVE_LIBSSL
3979 (void)any_root;
3980
3981 context = SSL_CTX_new(SSLv23_client_method());
3982
3983 SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); /* Only use SSLv3 or TLS */
3984
3985 bio = BIO_new(_httpBIOMethods());
3986 BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)http);
3987
3988 http->tls = SSL_new(context);
3989 SSL_set_bio(http->tls, bio, bio);
3990
3991 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
3992 SSL_set_tlsext_host_name(http->tls, hostname);
3993 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
3994
3995 if (SSL_connect(http->tls) != 1)
3996 {
3997 unsigned long error; /* Error code */
3998
3999 while ((error = ERR_get_error()) != 0)
4000 {
4001 message = ERR_error_string(error, NULL);
4002 DEBUG_printf(("8http_setup_ssl: %s", message));
4003 }
4004
4005 SSL_CTX_free(context);
4006 SSL_free(http->tls);
4007 http->tls = NULL;
4008
4009 # ifdef WIN32
4010 http->error = WSAGetLastError();
4011 # else
4012 http->error = errno;
4013 # endif /* WIN32 */
4014 http->status = HTTP_ERROR;
4015
4016 if (!message)
4017 message = _("Unable to establish a secure connection to host.");
4018
4019 _cupsSetError(IPP_PKI_ERROR, message, 1);
4020
4021 return (-1);
4022 }
4023
4024 # elif defined(HAVE_GNUTLS)
4025 (void)any_root;
4026
4027 credentials = (gnutls_certificate_client_credentials *)
4028 malloc(sizeof(gnutls_certificate_client_credentials));
4029 if (credentials == NULL)
4030 {
4031 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
4032 strerror(errno)));
4033 http->error = errno;
4034 http->status = HTTP_ERROR;
4035 _cupsSetHTTPError(HTTP_ERROR);
4036
4037 return (-1);
4038 }
4039
4040 gnutls_certificate_allocate_credentials(credentials);
4041
4042 gnutls_init(&http->tls, GNUTLS_CLIENT);
4043 gnutls_set_default_priority(http->tls);
4044 gnutls_server_name_set(http->tls, GNUTLS_NAME_DNS, hostname,
4045 strlen(hostname));
4046 gnutls_credentials_set(http->tls, GNUTLS_CRD_CERTIFICATE, *credentials);
4047 gnutls_transport_set_ptr(http->tls, (gnutls_transport_ptr)http);
4048 gnutls_transport_set_pull_function(http->tls, _httpReadGNUTLS);
4049 gnutls_transport_set_push_function(http->tls, _httpWriteGNUTLS);
4050
4051 while ((status = gnutls_handshake(http->tls)) != GNUTLS_E_SUCCESS)
4052 {
4053 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
4054 status, gnutls_strerror(status)));
4055
4056 if (gnutls_error_is_fatal(status))
4057 {
4058 http->error = EIO;
4059 http->status = HTTP_ERROR;
4060
4061 _cupsSetError(IPP_PKI_ERROR, gnutls_strerror(status), 0);
4062
4063 gnutls_deinit(http->tls);
4064 gnutls_certificate_free_credentials(*credentials);
4065 free(credentials);
4066 http->tls = NULL;
4067
4068 return (-1);
4069 }
4070 }
4071
4072 http->tls_credentials = credentials;
4073
4074 # elif defined(HAVE_CDSASSL)
4075 if ((error = SSLNewContext(false, &http->tls)))
4076 {
4077 http->error = errno;
4078 http->status = HTTP_ERROR;
4079 _cupsSetHTTPError(HTTP_ERROR);
4080
4081 return (-1);
4082 }
4083
4084 error = SSLSetConnection(http->tls, http);
4085 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error));
4086
4087 if (!error)
4088 {
4089 error = SSLSetIOFuncs(http->tls, _httpReadCDSA, _httpWriteCDSA);
4090 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error));
4091 }
4092
4093 if (!error)
4094 {
4095 error = SSLSetAllowsAnyRoot(http->tls, any_root);
4096 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
4097 any_root, (int)error));
4098 }
4099
4100 if (!error)
4101 {
4102 error = SSLSetAllowsExpiredCerts(http->tls, cg->expired_certs);
4103 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
4104 cg->expired_certs, (int)error));
4105 }
4106
4107 if (!error)
4108 {
4109 error = SSLSetAllowsExpiredRoots(http->tls, cg->expired_root);
4110 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
4111 cg->expired_root, (int)error));
4112 }
4113
4114 /*
4115 * In general, don't verify certificates since things like the common name
4116 * often do not match...
4117 */
4118
4119 if (!error)
4120 {
4121 error = SSLSetEnableCertVerify(http->tls, false);
4122 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
4123 (int)error));
4124 }
4125
4126 # ifdef HAVE_SECCERTIFICATECOPYDATA
4127 if (!error)
4128 {
4129 if (cg->client_cert_cb)
4130 {
4131 error = SSLSetSessionOption(http->tls,
4132 kSSLSessionOptionBreakOnCertRequested, true);
4133 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
4134 "error=%d", (int)error));
4135 }
4136 else
4137 {
4138 error = http_set_credentials(http);
4139 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
4140 (int)error));
4141 }
4142 }
4143
4144 /*
4145 * If there's a server certificate callback installed let it evaluate the
4146 * certificate(s) during the handshake...
4147 */
4148
4149 if (!error && cg->server_cert_cb != NULL)
4150 {
4151 error = SSLSetSessionOption(http->tls,
4152 kSSLSessionOptionBreakOnServerAuth, true);
4153 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
4154 "error=%d", (int)error));
4155 }
4156 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4157
4158 /*
4159 * Let the server know which hostname/domain we are trying to connect to
4160 * in case it wants to serve up a certificate with a matching common name.
4161 */
4162
4163 if (!error)
4164 {
4165 error = SSLSetPeerDomainName(http->tls, hostname, strlen(hostname));
4166
4167 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
4168 (int)error));
4169 }
4170
4171 if (!error)
4172 {
4173 int done = 0; /* Are we done yet? */
4174
4175 while (!error && !done)
4176 {
4177 error = SSLHandshake(http->tls);
4178
4179 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error));
4180
4181 switch (error)
4182 {
4183 case noErr :
4184 done = 1;
4185 break;
4186
4187 case errSSLWouldBlock :
4188 error = noErr; /* Force a retry */
4189 usleep(1000); /* in 1 millisecond */
4190 break;
4191
4192 # ifdef HAVE_SECCERTIFICATECOPYDATA
4193 case errSSLServerAuthCompleted :
4194 error = 0;
4195 if (cg->server_cert_cb)
4196 {
4197 error = httpCopyCredentials(http, &credentials);
4198 if (!error)
4199 {
4200 error = (cg->server_cert_cb)(http, http->tls, credentials,
4201 cg->server_cert_data);
4202 httpFreeCredentials(credentials);
4203 }
4204
4205 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
4206 "returned %d.", (int)error));
4207 }
4208 break;
4209
4210 case errSSLClientCertRequested :
4211 error = 0;
4212
4213 if (cg->client_cert_cb)
4214 {
4215 names = NULL;
4216 if (!(error = SSLCopyDistinguishedNames(http->tls, &dn_array)) &&
4217 dn_array)
4218 {
4219 if ((names = cupsArrayNew(NULL, NULL)) != NULL)
4220 {
4221 for (i = 0, count = CFArrayGetCount(dn_array); i < count; i++)
4222 {
4223 data = (CFDataRef)CFArrayGetValueAtIndex(dn_array, i);
4224
4225 if ((credential = malloc(sizeof(*credential))) != NULL)
4226 {
4227 credential->datalen = CFDataGetLength(data);
4228 if ((credential->data = malloc(credential->datalen)))
4229 {
4230 memcpy((void *)credential->data, CFDataGetBytePtr(data),
4231 credential->datalen);
4232 cupsArrayAdd(names, credential);
4233 }
4234 }
4235 }
4236 }
4237
4238 CFRelease(dn_array);
4239 }
4240
4241 if (!error)
4242 {
4243 error = (cg->client_cert_cb)(http, http->tls, names,
4244 cg->client_cert_data);
4245
4246 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
4247 "returned %d.", (int)error));
4248 }
4249
4250 httpFreeCredentials(names);
4251 }
4252 break;
4253 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4254
4255 case errSSLUnknownRootCert :
4256 message = _("Unable to establish a secure connection to host "
4257 "(untrusted certificate).");
4258 break;
4259
4260 case errSSLNoRootCert :
4261 message = _("Unable to establish a secure connection to host "
4262 "(self-signed certificate).");
4263 break;
4264
4265 case errSSLCertExpired :
4266 message = _("Unable to establish a secure connection to host "
4267 "(expired certificate).");
4268 break;
4269
4270 case errSSLCertNotYetValid :
4271 message = _("Unable to establish a secure connection to host "
4272 "(certificate not yet valid).");
4273 break;
4274
4275 case errSSLHostNameMismatch :
4276 message = _("Unable to establish a secure connection to host "
4277 "(host name mismatch).");
4278 break;
4279
4280 case errSSLXCertChainInvalid :
4281 message = _("Unable to establish a secure connection to host "
4282 "(certificate chain invalid).");
4283 break;
4284
4285 case errSSLConnectionRefused :
4286 message = _("Unable to establish a secure connection to host "
4287 "(peer dropped connection before responding).");
4288 break;
4289
4290 default :
4291 break;
4292 }
4293 }
4294 }
4295
4296 if (error)
4297 {
4298 http->error = error;
4299 http->status = HTTP_ERROR;
4300 errno = ECONNREFUSED;
4301
4302 SSLDisposeContext(http->tls);
4303 http->tls = NULL;
4304
4305 /*
4306 * If an error string wasn't set by the callbacks use a generic one...
4307 */
4308
4309 if (!message)
4310 #ifdef HAVE_CSSMERRORSTRING
4311 message = cssmErrorString(error);
4312 #else
4313 message = _("Unable to establish a secure connection to host.");
4314 #endif /* HAVE_CSSMERRORSTRING */
4315
4316 _cupsSetError(IPP_PKI_ERROR, message, 1);
4317
4318 return (-1);
4319 }
4320
4321 # elif defined(HAVE_SSPISSL)
4322 http->tls = _sspiAlloc();
4323
4324 if (!http->tls)
4325 {
4326 _cupsSetHTTPError(HTTP_ERROR);
4327 return (-1);
4328 }
4329
4330 http->tls->sock = http->fd;
4331 dwSize = sizeof(username) / sizeof(TCHAR);
4332 GetUserName(username, &dwSize);
4333 _sntprintf_s(commonName, sizeof(commonName) / sizeof(TCHAR),
4334 sizeof(commonName) / sizeof(TCHAR), TEXT("CN=%s"), username);
4335
4336 if (!_sspiGetCredentials(http->tls_credentials, L"ClientContainer",
4337 commonName, FALSE))
4338 {
4339 _sspiFree(http->tls_credentials);
4340 http->tls_credentials = NULL;
4341
4342 http->error = EIO;
4343 http->status = HTTP_ERROR;
4344
4345 _cupsSetError(IPP_PKI_ERROR,
4346 _("Unable to establish a secure connection to host."), 1);
4347
4348 return (-1);
4349 }
4350
4351 _sspiSetAllowsAnyRoot(http->tls_credentials, any_root);
4352 _sspiSetAllowsExpiredCerts(http->tls_credentials, TRUE);
4353
4354 if (!_sspiConnect(http->tls_credentials, hostname))
4355 {
4356 _sspiFree(http->tls_credentials);
4357 http->tls_credentials = NULL;
4358
4359 http->error = EIO;
4360 http->status = HTTP_ERROR;
4361
4362 _cupsSetError(IPP_PKI_ERROR,
4363 _("Unable to establish a secure connection to host."), 1);
4364
4365 return (-1);
4366 }
4367 # endif /* HAVE_CDSASSL */
4368
4369 return (0);
4370 }
4371
4372
4373 /*
4374 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4375 */
4376
4377 static void
4378 http_shutdown_ssl(http_t *http) /* I - Connection to server */
4379 {
4380 # ifdef HAVE_LIBSSL
4381 SSL_CTX *context; /* Context for encryption */
4382
4383 context = SSL_get_SSL_CTX(http->tls);
4384
4385 SSL_shutdown(http->tls);
4386 SSL_CTX_free(context);
4387 SSL_free(http->tls);
4388
4389 # elif defined(HAVE_GNUTLS)
4390 gnutls_certificate_client_credentials *credentials;
4391 /* TLS credentials */
4392
4393 credentials = (gnutls_certificate_client_credentials *)(http->tls_credentials);
4394
4395 gnutls_bye(http->tls, GNUTLS_SHUT_RDWR);
4396 gnutls_deinit(http->tls);
4397 gnutls_certificate_free_credentials(*credentials);
4398 free(credentials);
4399
4400 # elif defined(HAVE_CDSASSL)
4401 while (SSLClose(http->tls) == errSSLWouldBlock)
4402 usleep(1000);
4403
4404 SSLDisposeContext(http->tls);
4405
4406 if (http->tls_credentials)
4407 CFRelease(http->tls_credentials);
4408
4409 # elif defined(HAVE_SSPISSL)
4410 _sspiFree(http->tls_credentials);
4411 # endif /* HAVE_LIBSSL */
4412
4413 http->tls = NULL;
4414 http->tls_credentials = NULL;
4415 }
4416 #endif /* HAVE_SSL */
4417
4418
4419 #ifdef HAVE_SSL
4420 /*
4421 * 'http_upgrade()' - Force upgrade to TLS encryption.
4422 */
4423
4424 static int /* O - Status of connection */
4425 http_upgrade(http_t *http) /* I - Connection to server */
4426 {
4427 int ret; /* Return value */
4428 http_t myhttp; /* Local copy of HTTP data */
4429
4430
4431 DEBUG_printf(("7http_upgrade(%p)", http));
4432
4433 /*
4434 * Flush the connection to make sure any previous "Upgrade" message
4435 * has been read.
4436 */
4437
4438 httpFlush(http);
4439
4440 /*
4441 * Copy the HTTP data to a local variable so we can do the OPTIONS
4442 * request without interfering with the existing request data...
4443 */
4444
4445 memcpy(&myhttp, http, sizeof(myhttp));
4446
4447 /*
4448 * Send an OPTIONS request to the server, requiring SSL or TLS
4449 * encryption on the link...
4450 */
4451
4452 http->field_authorization = NULL; /* Don't free the auth string */
4453
4454 httpClearFields(http);
4455 httpSetField(http, HTTP_FIELD_CONNECTION, "upgrade");
4456 httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4457
4458 if ((ret = httpOptions(http, "*")) == 0)
4459 {
4460 /*
4461 * Wait for the secure connection...
4462 */
4463
4464 while (httpUpdate(http) == HTTP_CONTINUE);
4465 }
4466
4467 /*
4468 * Restore the HTTP request data...
4469 */
4470
4471 memcpy(http->fields, myhttp.fields, sizeof(http->fields));
4472 http->data_encoding = myhttp.data_encoding;
4473 http->data_remaining = myhttp.data_remaining;
4474 http->_data_remaining = myhttp._data_remaining;
4475 http->expect = myhttp.expect;
4476 http->field_authorization = myhttp.field_authorization;
4477 http->digest_tries = myhttp.digest_tries;
4478
4479 /*
4480 * See if we actually went secure...
4481 */
4482
4483 if (!http->tls)
4484 {
4485 /*
4486 * Server does not support HTTP upgrade...
4487 */
4488
4489 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4490
4491 # ifdef WIN32
4492 closesocket(http->fd);
4493 # else
4494 close(http->fd);
4495 # endif
4496
4497 http->fd = -1;
4498
4499 return (-1);
4500 }
4501 else
4502 return (ret);
4503 }
4504 #endif /* HAVE_SSL */
4505
4506
4507 /*
4508 * 'http_write()' - Write a buffer to a HTTP connection.
4509 */
4510
4511 static int /* O - Number of bytes written */
4512 http_write(http_t *http, /* I - Connection to server */
4513 const char *buffer, /* I - Buffer for data */
4514 int length) /* I - Number of bytes to write */
4515 {
4516 int tbytes, /* Total bytes sent */
4517 bytes; /* Bytes sent */
4518
4519
4520 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http, buffer,
4521 length));
4522 http->error = 0;
4523 tbytes = 0;
4524
4525 while (length > 0)
4526 {
4527 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length));
4528
4529 if (http->timeout_cb)
4530 {
4531 #ifdef HAVE_POLL
4532 struct pollfd pfd; /* Polled file descriptor */
4533 #else
4534 fd_set output_set; /* Output ready for write? */
4535 struct timeval timeout; /* Timeout value */
4536 #endif /* HAVE_POLL */
4537 int nfds; /* Result from select()/poll() */
4538
4539 do
4540 {
4541 #ifdef HAVE_POLL
4542 pfd.fd = http->fd;
4543 pfd.events = POLLOUT;
4544
4545 while ((nfds = poll(&pfd, 1, http->wait_value)) < 0 &&
4546 (errno == EINTR || errno == EAGAIN))
4547 /* do nothing */;
4548
4549 #else
4550 do
4551 {
4552 FD_ZERO(&output_set);
4553 FD_SET(http->fd, &output_set);
4554
4555 timeout.tv_sec = http->wait_value / 1000;
4556 timeout.tv_usec = 1000 * (http->wait_value % 1000);
4557
4558 nfds = select(http->fd + 1, NULL, &output_set, NULL, &timeout);
4559 }
4560 # ifdef WIN32
4561 while (nfds < 0 && (WSAGetLastError() == WSAEINTR ||
4562 WSAGetLastError() == WSAEWOULDBLOCK));
4563 # else
4564 while (nfds < 0 && (errno == EINTR || errno == EAGAIN));
4565 # endif /* WIN32 */
4566 #endif /* HAVE_POLL */
4567
4568 if (nfds < 0)
4569 {
4570 http->error = errno;
4571 return (-1);
4572 }
4573 else if (nfds == 0 && !(*http->timeout_cb)(http, http->timeout_data))
4574 {
4575 #ifdef WIN32
4576 http->error = WSAEWOULDBLOCK;
4577 #else
4578 http->error = EWOULDBLOCK;
4579 #endif /* WIN32 */
4580 return (-1);
4581 }
4582 }
4583 while (nfds <= 0);
4584 }
4585
4586 #ifdef HAVE_SSL
4587 if (http->tls)
4588 bytes = http_write_ssl(http, buffer, length);
4589 else
4590 #endif /* HAVE_SSL */
4591 bytes = send(http->fd, buffer, length, 0);
4592
4593 DEBUG_printf(("3http_write: Write of %d bytes returned %d.", (int)length,
4594 (int)bytes));
4595
4596 if (bytes < 0)
4597 {
4598 #ifdef WIN32
4599 if (WSAGetLastError() == WSAEINTR)
4600 continue;
4601 else if (WSAGetLastError() == WSAEWOULDBLOCK)
4602 {
4603 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
4604 continue;
4605
4606 http->error = WSAGetLastError();
4607 }
4608 else if (WSAGetLastError() != http->error &&
4609 WSAGetLastError() != WSAECONNRESET)
4610 {
4611 http->error = WSAGetLastError();
4612 continue;
4613 }
4614
4615 #else
4616 if (errno == EINTR)
4617 continue;
4618 else if (errno == EWOULDBLOCK || errno == EAGAIN)
4619 {
4620 if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
4621 continue;
4622 else if (!http->timeout_cb && errno == EAGAIN)
4623 continue;
4624
4625 http->error = errno;
4626 }
4627 else if (errno != http->error && errno != ECONNRESET)
4628 {
4629 http->error = errno;
4630 continue;
4631 }
4632 #endif /* WIN32 */
4633
4634 DEBUG_printf(("3http_write: error writing data (%s).",
4635 strerror(http->error)));
4636
4637 return (-1);
4638 }
4639
4640 buffer += bytes;
4641 tbytes += bytes;
4642 length -= bytes;
4643 }
4644
4645 #ifdef DEBUG
4646 http_debug_hex("http_write", buffer - tbytes, tbytes);
4647 #endif /* DEBUG */
4648
4649 DEBUG_printf(("3http_write: Returning %d.", tbytes));
4650
4651 return (tbytes);
4652 }
4653
4654
4655 /*
4656 * 'http_write_chunk()' - Write a chunked buffer.
4657 */
4658
4659 static int /* O - Number bytes written */
4660 http_write_chunk(http_t *http, /* I - Connection to server */
4661 const char *buffer, /* I - Buffer to write */
4662 int length) /* I - Length of buffer */
4663 {
4664 char header[255]; /* Chunk header */
4665 int bytes; /* Bytes written */
4666
4667
4668 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4669 http, buffer, length));
4670
4671 /*
4672 * Write the chunk header, data, and trailer.
4673 */
4674
4675 sprintf(header, "%x\r\n", length);
4676 if (http_write(http, header, (int)strlen(header)) < 0)
4677 {
4678 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4679 return (-1);
4680 }
4681
4682 if ((bytes = http_write(http, buffer, length)) < 0)
4683 {
4684 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4685 return (-1);
4686 }
4687
4688 if (http_write(http, "\r\n", 2) < 0)
4689 {
4690 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4691 return (-1);
4692 }
4693
4694 return (bytes);
4695 }
4696
4697
4698 #ifdef HAVE_SSL
4699 /*
4700 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4701 */
4702
4703 static int /* O - Bytes written */
4704 http_write_ssl(http_t *http, /* I - Connection to server */
4705 const char *buf, /* I - Buffer holding data */
4706 int len) /* I - Length of buffer */
4707 {
4708 ssize_t result; /* Return value */
4709
4710
4711 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http, buf, len));
4712
4713 # if defined(HAVE_LIBSSL)
4714 result = SSL_write((SSL *)(http->tls), buf, len);
4715
4716 # elif defined(HAVE_GNUTLS)
4717 result = gnutls_record_send(http->tls, buf, len);
4718
4719 if (result < 0 && !errno)
4720 {
4721 /*
4722 * Convert GNU TLS error to errno value...
4723 */
4724
4725 switch (result)
4726 {
4727 case GNUTLS_E_INTERRUPTED :
4728 errno = EINTR;
4729 break;
4730
4731 case GNUTLS_E_AGAIN :
4732 errno = EAGAIN;
4733 break;
4734
4735 default :
4736 errno = EPIPE;
4737 break;
4738 }
4739
4740 result = -1;
4741 }
4742
4743 # elif defined(HAVE_CDSASSL)
4744 OSStatus error; /* Error info */
4745 size_t processed; /* Number of bytes processed */
4746
4747
4748 error = SSLWrite(http->tls, buf, len, &processed);
4749
4750 switch (error)
4751 {
4752 case 0 :
4753 result = (int)processed;
4754 break;
4755
4756 case errSSLWouldBlock :
4757 if (processed)
4758 result = (int)processed;
4759 else
4760 {
4761 result = -1;
4762 errno = EINTR;
4763 }
4764 break;
4765
4766 case errSSLClosedGraceful :
4767 default :
4768 if (processed)
4769 result = (int)processed;
4770 else
4771 {
4772 result = -1;
4773 errno = EPIPE;
4774 }
4775 break;
4776 }
4777 # elif defined(HAVE_SSPISSL)
4778 return _sspiWrite((_sspi_struct_t *)http->tls, (void *)buf, len);
4779 # endif /* HAVE_LIBSSL */
4780
4781 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result));
4782
4783 return ((int)result);
4784 }
4785 #endif /* HAVE_SSL */
4786
4787
4788 /*
4789 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".
4790 */