2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for CUPS.
6 * Copyright 2007-2012 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
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/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * httpAddCredential() - Allocates and adds a single credential to an
24 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP
26 * httpBlocking() - Set blocking/non-blocking behavior on a
28 * httpCheck() - Check to see if there is a pending response
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
51 * httpGetCookie() - Get any cookie data from the response.
52 * httpGetFd() - Get the file descriptor associated with a
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
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
89 * httpTrace() - Send an TRACE request to the server.
90 * _httpUpdate() - Update the current HTTP status for incoming
92 * httpUpdate() - Update the current HTTP state for incoming
94 * _httpWait() - Wait for data available on a connection (no
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
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.
124 * Include necessary headers...
127 #include "cups-private.h"
134 # include <sys/time.h>
135 # include <sys/resource.h>
139 #endif /* HAVE_POLL */
147 static void http_debug_hex(const char *prefix
, const char *buffer
,
150 static http_field_t
http_field(const char *name
);
151 static int http_send(http_t
*http
, http_state_t request
,
153 static int http_write(http_t
*http
, const char *buffer
,
155 static int http_write_chunk(http_t
*http
, const char *buffer
,
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
);
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 */
177 static const char * const http_fields
[] =
194 "If-Unmodified-since",
208 static const char * const http_states
[] =
228 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
230 * BIO methods for OpenSSL...
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
);
240 static BIO_METHOD http_bio_methods
=
247 NULL
, /* http_bio_gets, */
253 #endif /* HAVE_SSL && HAVE_LIBSSL */
257 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
259 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
261 * @since CUPS 1.5/Mac OS X 10.7@
264 int /* O - 0 on success, -1 on error */
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 */
270 http_credential_t
*credential
; /* Credential data */
273 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
275 credential
->datalen
= datalen
;
277 if ((credential
->data
= malloc(datalen
)) != NULL
)
279 memcpy(credential
->data
, data
, datalen
);
280 cupsArrayAdd(credentials
, credential
);
291 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
293 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
296 BIO_METHOD
* /* O - BIO methods for OpenSSL */
297 _httpBIOMethods(void)
299 return (&http_bio_methods
);
301 #endif /* HAVE_SSL && HAVE_LIBSSL */
305 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
309 httpBlocking(http_t
*http
, /* I - Connection to server */
310 int b
) /* I - 1 = blocking, 0 = non-blocking */
321 * 'httpCheck()' - Check to see if there is a pending response from the server.
324 int /* O - 0 = no data, 1 = data available */
325 httpCheck(http_t
*http
) /* I - Connection to server */
327 return (httpWait(http
, 0));
332 * 'httpClearCookie()' - Clear the cookie value(s).
334 * @since CUPS 1.1.19/Mac OS X 10.3@
338 httpClearCookie(http_t
*http
) /* I - Connection to server */
352 * 'httpClearFields()' - Clear HTTP request fields.
356 httpClearFields(http_t
*http
) /* I - Connection to server */
360 memset(http
->fields
, 0, sizeof(http
->fields
));
361 if (http
->hostname
[0] == '/')
362 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
364 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
366 if (http
->field_authorization
)
368 free(http
->field_authorization
);
369 http
->field_authorization
= NULL
;
372 http
->expect
= (http_status_t
)0;
378 * 'httpClose()' - Close an HTTP connection.
382 httpClose(http_t
*http
) /* I - Connection to server */
385 OM_uint32 minor_status
; /* Minor status code */
386 #endif /* HAVE_GSSAPI */
389 DEBUG_printf(("httpClose(http=%p)", http
));
392 * Range check input...
399 * Close any open connection...
402 _httpDisconnect(http
);
405 * Free memory used...
408 httpAddrFreeList(http
->addrlist
);
414 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
415 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
417 if (http
->gssname
!= GSS_C_NO_NAME
)
418 gss_release_name(&minor_status
, &http
->gssname
);
419 #endif /* HAVE_GSSAPI */
421 #ifdef HAVE_AUTHORIZATION_H
423 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
424 #endif /* HAVE_AUTHORIZATION_H */
426 httpClearFields(http
);
428 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
429 free(http
->authstring
);
436 * 'httpConnect()' - Connect to a HTTP server.
438 * This function is deprecated - use @link httpConnectEncrypt@ instead.
443 http_t
* /* O - New HTTP connection */
444 httpConnect(const char *host
, /* I - Host to connect to */
445 int port
) /* I - Port number */
447 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
452 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
455 http_t
* /* O - New HTTP connection */
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 */
461 http_t
*http
; /* New HTTP connection */
464 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
465 host
, port
, encryption
));
468 * Create the HTTP structure...
471 if ((http
= _httpCreate(host
, port
, NULL
, encryption
, AF_UNSPEC
)) == NULL
)
475 * Connect to the remote system...
478 if (!httpReconnect(http
))
482 * Could not connect to any known address - bail out!
485 httpAddrFreeList(http
->addrlist
);
494 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
497 * @since CUPS 1.5/Mac OS X 10.7@
500 int /* O - Status of call (0 = success) */
502 http_t
*http
, /* I - Connection to server */
503 cups_array_t
**credentials
) /* O - Array of credentials */
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 */
521 if (!http
|| !http
->tls
|| !credentials
)
527 # elif defined(HAVE_GNUTLS)
530 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
531 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
533 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
535 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
537 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
538 if ((data
= SecCertificateCopyData(secCert
)))
540 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
541 CFDataGetLength(data
));
547 CFRelease(peerCerts
);
552 # elif defined(HAVE_SSPISSL)
557 # endif /* HAVE_LIBSSL */
562 * '_httpCreate()' - Create an unconnected HTTP connection.
565 http_t
* /* O - HTTP connection */
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 */
573 http_t
*http
; /* New HTTP connection */
574 char service
[255]; /* Service name */
577 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
578 host
, port
, encryption
));
589 sprintf(service
, "%d", port
);
592 if ((addrlist
= httpAddrGetList(host
, family
, service
)) == NULL
)
596 * Allocate memory for the structure...
599 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
601 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(errno
), 0);
602 httpAddrFreeList(addrlist
);
607 * Initialize the HTTP data...
610 http
->activity
= time(NULL
);
611 http
->addrlist
= addrlist
;
615 http
->gssctx
= GSS_C_NO_CONTEXT
;
616 http
->gssname
= GSS_C_NO_NAME
;
617 #endif /* HAVE_GSSAPI */
618 http
->version
= HTTP_1_1
;
620 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
622 if (port
== 443) /* Always use encryption for https */
623 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
625 http
->encryption
= encryption
;
630 * Return the new structure...
638 * '_httpCreateCredentials()' - Create credentials in the internal format.
641 http_tls_credentials_t
/* O - Internal credentials */
642 _httpCreateCredentials(
643 cups_array_t
*credentials
) /* I - Array of credentials */
651 # elif defined(HAVE_GNUTLS)
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 */
661 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
662 cupsArrayCount(credentials
),
663 &kCFTypeArrayCallBacks
)) == NULL
)
666 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
668 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
670 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
671 credential
->datalen
)))
673 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
676 CFArrayAppendValue(peerCerts
, secCert
);
686 # elif defined(HAVE_SSPISSL)
691 # endif /* HAVE_LIBSSL */
696 * 'httpDelete()' - Send a DELETE request to the server.
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 */
703 return (http_send(http
, HTTP_DELETE
, uri
));
708 * '_httpDisconnect()' - Disconnect a HTTP connection.
712 _httpDisconnect(http_t
*http
) /* I - Connection to server */
716 http_shutdown_ssl(http
);
717 #endif /* HAVE_SSL */
720 closesocket(http
->fd
);
730 * 'httpEncryption()' - Set the required encryption on the link.
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 */
737 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
743 http
->encryption
= e
;
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
));
753 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
757 #endif /* HAVE_SSL */
762 * 'httpError()' - Get the last error on a connection.
765 int /* O - Error code (errno) value */
766 httpError(http_t
*http
) /* I - Connection to server */
769 return (http
->error
);
776 * 'httpFlush()' - Flush data from a HTTP connection.
780 httpFlush(http_t
*http
) /* I - Connection to server */
782 char buffer
[8192]; /* Junk buffer */
783 int blocking
; /* To block or not to block */
784 http_state_t oldstate
; /* Old state */
787 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
788 http_states
[http
->state
]));
791 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
794 blocking
= http
->blocking
;
798 * Read any data we can...
801 oldstate
= http
->state
;
802 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
805 * Restore blocking and reset the connection if we didn't get all of
806 * the remaining data...
809 http
->blocking
= blocking
;
811 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
814 * Didn't get the data back, so close the current connection.
817 http
->state
= HTTP_WAITING
;
821 http_shutdown_ssl(http
);
822 #endif /* HAVE_SSL */
825 closesocket(http
->fd
);
836 * 'httpFlushWrite()' - Flush data in write buffer.
838 * @since CUPS 1.2/Mac OS X 10.5@
841 int /* O - Bytes written or -1 on error */
842 httpFlushWrite(http_t
*http
) /* I - Connection to server */
844 int bytes
; /* Bytes written */
847 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
849 if (!http
|| !http
->wused
)
851 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
852 "1httpFlushWrite: No connection.");
856 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
857 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
859 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
863 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
870 * '_httpFreeCredentials()' - Free internal credentials.
874 _httpFreeCredentials(
875 http_tls_credentials_t credentials
) /* I - Internal credentials */
883 #elif defined(HAVE_GNUTLS)
886 #elif defined(HAVE_CDSASSL)
887 CFRelease(credentials
);
889 #elif defined(HAVE_SSPISSL)
892 #endif /* HAVE_LIBSSL */
897 * 'httpFreeCredentials()' - Free an array of credentials.
902 cups_array_t
*credentials
) /* I - Array of credentials */
904 http_credential_t
*credential
; /* Credential */
907 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
909 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
911 cupsArrayRemove(credentials
, credential
);
912 free((void *)credential
->data
);
916 cupsArrayDelete(credentials
);
921 * 'httpGet()' - Send a GET request to the server.
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 */
928 return (http_send(http
, HTTP_GET
, uri
));
933 * 'httpGetAuthString()' - Get the current authorization string.
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
940 * @since CUPS 1.3/Mac OS X 10.5@
943 char * /* O - Authorization string */
944 httpGetAuthString(http_t
*http
) /* I - Connection to server */
947 return (http
->authstring
);
954 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
956 * @since CUPS 1.2/Mac OS X 10.5@
959 int /* O - 1 if blocking, 0 if non-blocking */
960 httpGetBlocking(http_t
*http
) /* I - Connection to server */
962 return (http
? http
->blocking
: 0);
967 * 'httpGetCookie()' - Get any cookie data from the response.
969 * @since CUPS 1.1.19/Mac OS X 10.3@
972 const char * /* O - Cookie data or NULL */
973 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
975 return (http
? http
->cookie
: NULL
);
980 * 'httpGetFd()' - Get the file descriptor associated with a connection.
982 * @since CUPS 1.2/Mac OS X 10.5@
985 int /* O - File descriptor or -1 if none */
986 httpGetFd(http_t
*http
) /* I - Connection to server */
988 return (http
? http
->fd
: -1);
993 * 'httpGetField()' - Get a field value from a request/response.
996 const char * /* O - Field value */
997 httpGetField(http_t
*http
, /* I - Connection to server */
998 http_field_t field
) /* I - Field to get */
1000 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1002 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
1003 http
->field_authorization
)
1006 * Special case for WWW-Authenticate: as its contents can be
1007 * longer than HTTP_MAX_VALUE...
1010 return (http
->field_authorization
);
1013 return (http
->fields
[field
]);
1018 * 'httpGetLength()' - Get the amount of data remaining from the
1019 * content-length or transfer-encoding fields.
1021 * This function is deprecated and will not return lengths larger than
1022 * 2^31 - 1; use httpGetLength2() instead.
1027 int /* O - Content length */
1028 httpGetLength(http_t
*http
) /* I - Connection to server */
1031 * Get the read content length and return the 32-bit value.
1036 httpGetLength2(http
);
1038 return (http
->_data_remaining
);
1046 * 'httpGetLength2()' - Get the amount of data remaining from the
1047 * content-length or transfer-encoding fields.
1049 * This function returns the complete content length, even for
1050 * content larger than 2^31 - 1.
1052 * @since CUPS 1.2/Mac OS X 10.5@
1055 off_t
/* O - Content length */
1056 httpGetLength2(http_t
*http
) /* I - Connection to server */
1058 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1059 http_states
[http
->state
]));
1064 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1066 DEBUG_puts("4httpGetLength2: chunked request!");
1068 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1069 http
->data_remaining
= 0;
1073 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1076 * The following is a hack for HTTP servers that don't send a
1077 * content-length or transfer-encoding field...
1079 * If there is no content-length then the connection must close
1080 * after the transfer is complete...
1083 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1086 * Default content length is 0 for errors and 2^31-1 for other
1087 * successful requests...
1090 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
1091 http
->data_remaining
= 0;
1093 http
->data_remaining
= 2147483647;
1096 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1099 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1100 CUPS_LLCAST http
->data_remaining
));
1103 if (http
->data_remaining
<= INT_MAX
)
1104 http
->_data_remaining
= (int)http
->data_remaining
;
1106 http
->_data_remaining
= INT_MAX
;
1108 return (http
->data_remaining
);
1113 * 'httpGets()' - Get a line of text from a HTTP connection.
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 */
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? */
1129 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1131 if (http
== NULL
|| line
== NULL
)
1135 * Read a line from the buffer...
1140 lineend
= line
+ length
- 1;
1143 while (lineptr
< lineend
)
1146 * Pre-load the buffer as needed...
1155 while (http
->used
== 0)
1158 * No newline; see if there is more data to be read...
1161 while (!_httpWait(http
, http
->wait_value
, 1))
1163 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1166 DEBUG_puts("3httpGets: Timed out!");
1168 http
->error
= WSAETIMEDOUT
;
1170 http
->error
= ETIMEDOUT
;
1177 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1178 HTTP_MAX_BUFFER
- http
->used
);
1180 #endif /* HAVE_SSL */
1181 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1182 HTTP_MAX_BUFFER
- http
->used
, 0);
1184 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1189 * Nope, can't get a line this time...
1193 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1195 if (WSAGetLastError() == WSAEINTR
)
1197 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1199 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1202 http
->error
= WSAGetLastError();
1204 else if (WSAGetLastError() != http
->error
)
1206 http
->error
= WSAGetLastError();
1211 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1215 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1217 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1219 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1222 http
->error
= errno
;
1224 else if (errno
!= http
->error
)
1226 http
->error
= errno
;
1233 else if (bytes
== 0)
1235 http
->error
= EPIPE
;
1241 * Yup, update the amount used...
1244 http
->used
+= bytes
;
1248 * Now copy as much of the current line as possible...
1251 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1252 lineptr
< lineend
&& bufptr
< bufend
;)
1254 if (*bufptr
== 0x0a)
1260 else if (*bufptr
== 0x0d)
1263 *lineptr
++ = *bufptr
++;
1266 http
->used
-= (int)(bufptr
- http
->buffer
);
1268 memmove(http
->buffer
, bufptr
, http
->used
);
1276 http
->activity
= time(NULL
);
1280 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1286 DEBUG_puts("3httpGets: No new line available!");
1293 * 'httpGetState()' - Get the current state of the HTTP request.
1296 http_state_t
/* O - HTTP state */
1297 httpGetState(http_t
*http
) /* I - Connection to server */
1299 return (http
? http
->state
: HTTP_ERROR
);
1304 * 'httpGetStatus()' - Get the status of the last HTTP request.
1306 * @since CUPS 1.2/Mac OS X 10.5@
1309 http_status_t
/* O - HTTP status */
1310 httpGetStatus(http_t
*http
) /* I - Connection to server */
1312 return (http
? http
->status
: HTTP_ERROR
);
1317 * 'httpGetSubField()' - Get a sub-field value.
1322 char * /* O - Value or NULL */
1323 httpGetSubField(http_t
*http
, /* I - Connection to server */
1324 http_field_t field
, /* I - Field index */
1325 const char *name
, /* I - Name of sub-field */
1326 char *value
) /* O - Value string */
1328 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1333 * 'httpGetSubField2()' - Get a sub-field value.
1335 * @since CUPS 1.2/Mac OS X 10.5@
1338 char * /* O - Value or NULL */
1339 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1340 http_field_t field
, /* I - Field index */
1341 const char *name
, /* I - Name of sub-field */
1342 char *value
, /* O - Value string */
1343 int valuelen
) /* I - Size of value buffer */
1345 const char *fptr
; /* Pointer into field */
1346 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1347 *ptr
, /* Pointer into string buffer */
1348 *end
; /* End of value buffer */
1350 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1351 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1353 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1354 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1357 end
= value
+ valuelen
- 1;
1359 for (fptr
= http
->fields
[field
]; *fptr
;)
1362 * Skip leading whitespace...
1365 while (_cups_isspace(*fptr
))
1375 * Get the sub-field name...
1379 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1380 ptr
< (temp
+ sizeof(temp
) - 1);
1385 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1388 * Skip trailing chars up to the '='...
1391 while (_cups_isspace(*fptr
))
1401 * Skip = and leading whitespace...
1406 while (_cups_isspace(*fptr
))
1412 * Read quoted string...
1415 for (ptr
= value
, fptr
++;
1416 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1421 while (*fptr
&& *fptr
!= '\"')
1430 * Read unquoted string...
1434 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1439 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1443 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1446 * See if this is the one...
1449 if (!strcmp(name
, temp
))
1451 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1458 DEBUG_puts("3httpGetSubField2: Returning NULL");
1465 * 'httpGetVersion()' - Get the HTTP version at the other end.
1468 http_version_t
/* O - Version number */
1469 httpGetVersion(http_t
*http
) /* I - Connection to server */
1471 return (http
? http
->version
: HTTP_1_0
);
1476 * 'httpHead()' - Send a HEAD request to the server.
1479 int /* O - Status of call (0 = success) */
1480 httpHead(http_t
*http
, /* I - Connection to server */
1481 const char *uri
) /* I - URI for head */
1483 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1484 return (http_send(http
, HTTP_HEAD
, uri
));
1489 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1490 * default HTTP proxy (if any).
1494 httpInitialize(void)
1496 static int initialized
= 0; /* Have we been called before? */
1498 WSADATA winsockdata
; /* WinSock data */
1501 int i
; /* Looping var */
1502 unsigned char data
[1024]; /* Seed data */
1503 #endif /* HAVE_LIBSSL */
1509 _cupsGlobalUnlock();
1514 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1516 #elif !defined(SO_NOSIGPIPE)
1518 * Ignore SIGPIPE signals...
1522 sigset(SIGPIPE
, SIG_IGN
);
1524 # elif defined(HAVE_SIGACTION)
1525 struct sigaction action
; /* POSIX sigaction data */
1528 memset(&action
, 0, sizeof(action
));
1529 action
.sa_handler
= SIG_IGN
;
1530 sigaction(SIGPIPE
, &action
, NULL
);
1533 signal(SIGPIPE
, SIG_IGN
);
1534 # endif /* !SO_NOSIGPIPE */
1539 * Initialize GNU TLS...
1542 gnutls_global_init();
1544 #elif defined(HAVE_LIBSSL)
1546 * Initialize OpenSSL...
1549 SSL_load_error_strings();
1553 * Using the current time is a dubious random seed, but on some systems
1554 * it is the best we can do (on others, this seed isn't even used...)
1557 CUPS_SRAND(time(NULL
));
1559 for (i
= 0; i
< sizeof(data
); i
++)
1560 data
[i
] = CUPS_RAND();
1562 RAND_seed(data
, sizeof(data
));
1563 #endif /* HAVE_GNUTLS */
1566 _cupsGlobalUnlock();
1571 * 'httpOptions()' - Send an OPTIONS request to the server.
1574 int /* O - Status of call (0 = success) */
1575 httpOptions(http_t
*http
, /* I - Connection to server */
1576 const char *uri
) /* I - URI for options */
1578 return (http_send(http
, HTTP_OPTIONS
, uri
));
1583 * '_httpPeek()' - Peek at data from a HTTP connection.
1585 * This function copies available data from the given HTTP connection, reading
1586 * a buffer as needed. The data is still available for reading using
1587 * @link httpRead@ or @link httpRead2@.
1589 * For non-blocking connections the usual timeouts apply.
1592 ssize_t
/* O - Number of bytes copied */
1593 _httpPeek(http_t
*http
, /* I - Connection to server */
1594 char *buffer
, /* I - Buffer for data */
1595 size_t length
) /* I - Maximum number of bytes */
1597 ssize_t bytes
; /* Bytes read */
1598 char len
[32]; /* Length string */
1601 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1602 http
, buffer
, CUPS_LLCAST length
));
1604 if (http
== NULL
|| buffer
== NULL
)
1607 http
->activity
= time(NULL
);
1613 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1614 http
->data_remaining
<= 0)
1616 DEBUG_puts("2_httpPeek: Getting chunk length...");
1618 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1620 DEBUG_puts("1_httpPeek: Could not get length!");
1624 http
->data_remaining
= strtoll(len
, NULL
, 16);
1625 if (http
->data_remaining
< 0)
1627 DEBUG_puts("1_httpPeek: Negative chunk length!");
1632 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1633 CUPS_LLCAST http
->data_remaining
));
1635 if (http
->data_remaining
<= 0)
1638 * A zero-length chunk ends a transfer; unless we are reading POST
1642 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1643 httpGets(len
, sizeof(len
), http
);
1645 if (http
->state
== HTTP_POST_RECV
)
1648 http
->state
= HTTP_WAITING
;
1651 * Prevent future reads for this request...
1654 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1658 else if (length
> (size_t)http
->data_remaining
)
1659 length
= (size_t)http
->data_remaining
;
1661 if (http
->used
== 0)
1664 * Buffer small reads for better performance...
1667 if (!http
->blocking
)
1669 while (!httpWait(http
, http
->wait_value
))
1671 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1678 if (http
->data_remaining
> sizeof(http
->buffer
))
1679 bytes
= sizeof(http
->buffer
);
1681 bytes
= http
->data_remaining
;
1685 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1687 #endif /* HAVE_SSL */
1689 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1692 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1694 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1703 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1705 http
->error
= WSAGetLastError();
1709 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1711 http
->error
= errno
;
1718 http
->error
= EPIPE
;
1725 if (length
> (size_t)http
->used
)
1726 length
= (size_t)http
->used
;
1728 bytes
= (ssize_t
)length
;
1730 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1733 memcpy(buffer
, http
->buffer
, length
);
1741 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1744 http
->error
= WSAGetLastError();
1746 if (errno
== EINTR
|| errno
== EAGAIN
)
1749 http
->error
= errno
;
1752 else if (bytes
== 0)
1754 http
->error
= EPIPE
;
1759 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1767 * 'httpPost()' - Send a POST request to the server.
1770 int /* O - Status of call (0 = success) */
1771 httpPost(http_t
*http
, /* I - Connection to server */
1772 const char *uri
) /* I - URI for post */
1774 return (http_send(http
, HTTP_POST
, uri
));
1779 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1784 int /* O - Number of bytes written */
1785 httpPrintf(http_t
*http
, /* I - Connection to server */
1786 const char *format
, /* I - printf-style format string */
1787 ...) /* I - Additional args as needed */
1789 int bytes
; /* Number of bytes to write */
1790 char buf
[16384]; /* Buffer for formatted string */
1791 va_list ap
; /* Variable argument pointer */
1794 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1796 va_start(ap
, format
);
1797 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1800 DEBUG_printf(("3httpPrintf: %s", buf
));
1802 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1803 return (httpWrite2(http
, buf
, bytes
));
1808 DEBUG_puts("4httpPrintf: flushing existing data...");
1810 if (httpFlushWrite(http
) < 0)
1814 return (http_write(http
, buf
, bytes
));
1820 * 'httpPut()' - Send a PUT request to the server.
1823 int /* O - Status of call (0 = success) */
1824 httpPut(http_t
*http
, /* I - Connection to server */
1825 const char *uri
) /* I - URI to put */
1827 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1828 return (http_send(http
, HTTP_PUT
, uri
));
1833 * 'httpRead()' - Read data from a HTTP connection.
1835 * This function is deprecated. Use the httpRead2() function which can
1836 * read more than 2GB of data.
1841 int /* O - Number of bytes read */
1842 httpRead(http_t
*http
, /* I - Connection to server */
1843 char *buffer
, /* I - Buffer for data */
1844 int length
) /* I - Maximum number of bytes */
1846 return ((int)httpRead2(http
, buffer
, length
));
1851 * 'httpRead2()' - Read data from a HTTP connection.
1853 * @since CUPS 1.2/Mac OS X 10.5@
1856 ssize_t
/* O - Number of bytes read */
1857 httpRead2(http_t
*http
, /* I - Connection to server */
1858 char *buffer
, /* I - Buffer for data */
1859 size_t length
) /* I - Maximum number of bytes */
1861 ssize_t bytes
; /* Bytes read */
1862 char len
[32]; /* Length string */
1865 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1866 http
, buffer
, CUPS_LLCAST length
));
1868 if (http
== NULL
|| buffer
== NULL
)
1871 http
->activity
= time(NULL
);
1877 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1878 http
->data_remaining
<= 0)
1880 DEBUG_puts("2httpRead2: Getting chunk length...");
1882 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1884 DEBUG_puts("1httpRead2: Could not get length!");
1888 http
->data_remaining
= strtoll(len
, NULL
, 16);
1889 if (http
->data_remaining
< 0)
1891 DEBUG_puts("1httpRead2: Negative chunk length!");
1896 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1897 CUPS_LLCAST http
->data_remaining
));
1899 if (http
->data_remaining
<= 0)
1902 * A zero-length chunk ends a transfer; unless we are reading POST
1906 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1907 httpGets(len
, sizeof(len
), http
);
1909 if (http
->state
== HTTP_POST_RECV
)
1912 http
->state
= HTTP_WAITING
;
1915 * Prevent future reads for this request...
1918 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1922 else if (length
> (size_t)http
->data_remaining
)
1923 length
= (size_t)http
->data_remaining
;
1925 if (http
->used
== 0 && length
<= 256)
1928 * Buffer small reads for better performance...
1931 ssize_t buflen
; /* Length of read for buffer */
1933 if (!http
->blocking
)
1935 while (!httpWait(http
, http
->wait_value
))
1937 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1944 if (http
->data_remaining
> sizeof(http
->buffer
))
1945 buflen
= sizeof(http
->buffer
);
1947 buflen
= http
->data_remaining
;
1949 DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen
));
1955 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
1957 #endif /* HAVE_SSL */
1958 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
1963 if (WSAGetLastError() != WSAEINTR
)
1965 http
->error
= WSAGetLastError();
1968 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1970 if (!http
->timeout_cb
||
1971 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1973 http
->error
= WSAEWOULDBLOCK
;
1978 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1980 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1982 http
->error
= errno
;
1985 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1987 http
->error
= errno
;
1991 else if (errno
!= EINTR
)
1993 http
->error
= errno
;
2001 DEBUG_printf(("2httpRead2: Read %d bytes into buffer.", (int)bytes
));
2008 if (length
> (size_t)http
->used
)
2009 length
= (size_t)http
->used
;
2011 bytes
= (ssize_t
)length
;
2013 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2016 memcpy(buffer
, http
->buffer
, length
);
2017 http
->used
-= (int)length
;
2020 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2025 if (!http
->blocking
)
2027 while (!httpWait(http
, http
->wait_value
))
2029 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2036 while ((bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
)) < 0)
2039 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2041 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2044 else if (WSAGetLastError() != WSAEINTR
)
2047 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2049 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2051 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2054 else if (errno
!= EINTR
)
2059 #endif /* HAVE_SSL */
2062 if (!http
->blocking
)
2064 while (!httpWait(http
, http
->wait_value
))
2066 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2073 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2074 CUPS_LLCAST length
));
2077 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2079 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2081 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2084 else if (WSAGetLastError() != WSAEINTR
)
2088 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2090 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2092 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2094 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2097 else if (errno
!= EINTR
)
2102 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2103 CUPS_LLCAST bytes
));
2108 http
->data_remaining
-= bytes
;
2110 if (http
->data_remaining
<= INT_MAX
)
2111 http
->_data_remaining
= (int)http
->data_remaining
;
2113 http
->_data_remaining
= INT_MAX
;
2118 if (WSAGetLastError() == WSAEINTR
)
2121 http
->error
= WSAGetLastError();
2123 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2126 http
->error
= errno
;
2131 http
->error
= EPIPE
;
2135 if (http
->data_remaining
== 0)
2137 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2138 httpGets(len
, sizeof(len
), http
);
2140 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2142 if (http
->state
== HTTP_POST_RECV
)
2145 http
->state
= HTTP_WAITING
;
2150 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2157 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2159 * '_httpReadCDSA()' - Read function for the CDSA library.
2162 OSStatus
/* O - -1 on error, 0 on success */
2164 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2165 void *data
, /* I - Data buffer */
2166 size_t *dataLength
) /* IO - Number of bytes */
2168 OSStatus result
; /* Return value */
2169 ssize_t bytes
; /* Number of bytes read */
2170 http_t
*http
; /* HTTP connection */
2173 http
= (http_t
*)connection
;
2175 if (!http
->blocking
)
2178 * Make sure we have data before we read...
2181 while (!_httpWait(http
, http
->wait_value
, 0))
2183 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2186 http
->error
= ETIMEDOUT
;
2193 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2195 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2197 if (bytes
== *dataLength
)
2203 *dataLength
= bytes
;
2204 result
= errSSLWouldBlock
;
2211 result
= errSSLClosedGraceful
;
2212 else if (errno
== EAGAIN
)
2213 result
= errSSLWouldBlock
;
2215 result
= errSSLClosedAbort
;
2220 #endif /* HAVE_SSL && HAVE_CDSASSL */
2223 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2225 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2228 ssize_t
/* O - Number of bytes read or -1 on error */
2230 gnutls_transport_ptr ptr
, /* I - Connection to server */
2231 void *data
, /* I - Buffer */
2232 size_t length
) /* I - Number of bytes to read */
2234 http_t
*http
; /* HTTP connection */
2235 ssize_t bytes
; /* Bytes read */
2238 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2240 http
= (http_t
*)ptr
;
2242 if (!http
->blocking
)
2245 * Make sure we have data before we read...
2248 while (!_httpWait(http
, http
->wait_value
, 0))
2250 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2253 http
->error
= ETIMEDOUT
;
2258 bytes
= recv(http
->fd
, data
, length
, 0);
2259 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2262 #endif /* HAVE_SSL && HAVE_GNUTLS */
2266 * 'httpReconnect()' - Reconnect to a HTTP server.
2269 int /* O - 0 on success, non-zero on failure */
2270 httpReconnect(http_t
*http
) /* I - Connection to server */
2272 DEBUG_printf(("httpReconnect(http=%p)", http
));
2274 return (httpReconnect2(http
, 30, NULL
));
2279 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2283 int /* O - 0 on success, non-zero on failure */
2284 httpReconnect2(http_t
*http
, /* I - Connection to server */
2285 int msec
, /* I - Timeout in milliseconds */
2286 int *cancel
) /* I - Pointer to "cancel" variable */
2288 http_addrlist_t
*addr
; /* Connected address */
2290 http_addrlist_t
*current
; /* Current address */
2291 char temp
[256]; /* Temporary address string */
2295 DEBUG_printf(("httpReconnect(http=%p, msec=%d, cancel=%p)", http
, msec
,
2300 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
2307 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2308 http_shutdown_ssl(http
);
2310 #endif /* HAVE_SSL */
2313 * Close any previously open socket...
2318 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2321 closesocket(http
->fd
);
2330 * Connect to the server...
2334 for (current
= http
->addrlist
; current
; current
= current
->next
)
2335 DEBUG_printf(("2httpReconnect: Address %s:%d",
2336 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2337 _httpAddrPort(&(current
->addr
))));
2340 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2344 * Unable to connect...
2348 http
->error
= WSAGetLastError();
2350 http
->error
= errno
;
2352 http
->status
= HTTP_ERROR
;
2354 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2355 strerror(http
->error
)));
2360 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2362 if (http
->timeout_value
> 0)
2363 http_set_timeout(http
->fd
, http
->timeout_value
);
2365 http
->hostaddr
= &(addr
->addr
);
2367 http
->status
= HTTP_CONTINUE
;
2368 http
->state
= HTTP_WAITING
;
2371 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2374 * Always do encryption via SSL.
2377 if (http_setup_ssl(http
) != 0)
2380 closesocket(http
->fd
);
2388 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2389 return (http_upgrade(http
));
2390 #endif /* HAVE_SSL */
2392 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2393 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2394 _httpAddrPort(http
->hostaddr
)));
2401 * 'httpSetAuthString()' - Set the current authorization string.
2403 * This function just stores a copy of the current authorization string in
2404 * the HTTP connection object. You must still call httpSetField() to set
2405 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2406 * httpHead(), httpOptions(), httpPost, or httpPut().
2408 * @since CUPS 1.3/Mac OS X 10.5@
2412 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2413 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2414 const char *data
) /* I - Auth data (NULL for none) */
2417 * Range check input...
2423 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2424 free(http
->authstring
);
2426 http
->authstring
= http
->_authstring
;
2431 * Set the current authorization string...
2434 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2437 if (len
> (int)sizeof(http
->_authstring
))
2439 if ((temp
= malloc(len
)) == NULL
)
2440 len
= sizeof(http
->_authstring
);
2442 http
->authstring
= temp
;
2446 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2448 strlcpy(http
->authstring
, scheme
, len
);
2453 * Clear the current authorization string...
2456 http
->_authstring
[0] = '\0';
2462 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2465 * @since CUPS 1.5/Mac OS X 10.7@
2468 int /* O - Status of call (0 = success) */
2469 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2470 cups_array_t
*credentials
) /* I - Array of credentials */
2472 if (!http
|| cupsArrayCount(credentials
) < 1)
2475 _httpFreeCredentials(http
->tls_credentials
);
2477 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2479 return (http
->tls_credentials
? 0 : -1);
2484 * 'httpSetCookie()' - Set the cookie value(s).
2486 * @since CUPS 1.1.19/Mac OS X 10.3@
2490 httpSetCookie(http_t
*http
, /* I - Connection */
2491 const char *cookie
) /* I - Cookie string */
2500 http
->cookie
= strdup(cookie
);
2502 http
->cookie
= NULL
;
2507 * 'httpSetExpect()' - Set the Expect: header in a request.
2509 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2511 * @since CUPS 1.2/Mac OS X 10.5@
2515 httpSetExpect(http_t
*http
, /* I - Connection to server */
2516 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2519 http
->expect
= expect
;
2524 * 'httpSetField()' - Set the value of an HTTP header.
2528 httpSetField(http_t
*http
, /* I - Connection to server */
2529 http_field_t field
, /* I - Field index */
2530 const char *value
) /* I - Value */
2533 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2534 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2538 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2540 if (field
== HTTP_FIELD_AUTHORIZATION
)
2543 * Special case for Authorization: as its contents can be
2544 * longer than HTTP_MAX_VALUE
2547 if (http
->field_authorization
)
2548 free(http
->field_authorization
);
2550 http
->field_authorization
= strdup(value
);
2552 else if (field
== HTTP_FIELD_HOST
)
2555 * Special-case for Host: as we don't want a trailing "." on the hostname and
2556 * need to bracket IPv6 numeric addresses.
2559 char *ptr
= strchr(value
, ':');
2561 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2564 * Bracket IPv6 numeric addresses...
2566 * This is slightly inefficient (basically copying twice), but is an edge
2567 * case and not worth optimizing...
2570 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2571 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2576 * Check for a trailing dot on the hostname...
2579 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2583 ptr
+= strlen(ptr
) - 1;
2594 * 'httpSetLength()' - Set the content-length and content-encoding.
2596 * @since CUPS 1.2/Mac OS X 10.5@
2600 httpSetLength(http_t
*http
, /* I - Connection to server */
2601 size_t length
) /* I - Length (0 for chunked) */
2608 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2609 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2613 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2614 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2615 CUPS_LLFMT
, CUPS_LLCAST length
);
2621 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2623 * The optional timeout callback receives both the HTTP connection and a user
2624 * data pointer and must return 1 to continue or 0 to error (time) out.
2626 * @since CUPS 1.5/Mac OS X 10.7@
2631 http_t
*http
, /* I - Connection to server */
2632 double timeout
, /* I - Number of seconds for timeout,
2633 must be greater than 0 */
2634 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2635 void *user_data
) /* I - User data pointer */
2637 if (!http
|| timeout
<= 0.0)
2640 http
->timeout_cb
= cb
;
2641 http
->timeout_data
= user_data
;
2642 http
->timeout_value
= timeout
;
2645 http_set_timeout(http
->fd
, timeout
);
2647 http_set_wait(http
);
2652 * 'httpTrace()' - Send an TRACE request to the server.
2655 int /* O - Status of call (0 = success) */
2656 httpTrace(http_t
*http
, /* I - Connection to server */
2657 const char *uri
) /* I - URI for trace */
2659 return (http_send(http
, HTTP_TRACE
, uri
));
2664 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2666 * Note: Unlike httpUpdate(), this function does not flush pending write data
2667 * and only retrieves a single status line from the HTTP connection.
2670 int /* O - 1 to continue, 0 to stop */
2671 _httpUpdate(http_t
*http
, /* I - Connection to server */
2672 http_status_t
*status
) /* O - Current HTTP status */
2674 char line
[32768], /* Line from connection... */
2675 *value
; /* Pointer to value on line */
2676 http_field_t field
; /* Field index */
2677 int major
, minor
; /* HTTP version numbers */
2680 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2681 http_states
[http
->state
]));
2684 * Grab a single line from the connection...
2687 if (!httpGets(line
, sizeof(line
), http
))
2689 *status
= HTTP_ERROR
;
2693 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2695 if (line
[0] == '\0')
2698 * Blank line means the start of the data section (if any). Return
2699 * the result code, too...
2701 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2702 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2706 if (http
->status
== HTTP_CONTINUE
)
2708 *status
= http
->status
;
2712 if (http
->status
< HTTP_BAD_REQUEST
)
2713 http
->digest_tries
= 0;
2716 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2718 if (http_setup_ssl(http
) != 0)
2721 closesocket(http
->fd
);
2726 *status
= http
->status
= HTTP_ERROR
;
2730 *status
= HTTP_CONTINUE
;
2733 #endif /* HAVE_SSL */
2735 httpGetLength2(http
);
2737 switch (http
->state
)
2741 case HTTP_POST_RECV
:
2744 case HTTP_POST_SEND
:
2749 http
->state
= HTTP_WAITING
;
2753 *status
= http
->status
;
2756 else if (!strncmp(line
, "HTTP/", 5))
2759 * Got the beginning of a response...
2762 int intstatus
; /* Status value as an integer */
2764 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2766 *status
= http
->status
= HTTP_ERROR
;
2770 http
->version
= (http_version_t
)(major
* 100 + minor
);
2771 *status
= http
->status
= (http_status_t
)intstatus
;
2773 else if ((value
= strchr(line
, ':')) != NULL
)
2780 while (_cups_isspace(*value
))
2784 * Be tolerants of servers that send unknown attribute fields...
2787 if (!_cups_strcasecmp(line
, "expect"))
2790 * "Expect: 100-continue" or similar...
2793 http
->expect
= (http_status_t
)atoi(value
);
2795 else if (!_cups_strcasecmp(line
, "cookie"))
2798 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2801 httpSetCookie(http
, value
);
2803 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
2804 httpSetField(http
, field
, value
);
2807 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
2812 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
2813 *status
= http
->status
= HTTP_ERROR
;
2822 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2825 http_status_t
/* O - HTTP status */
2826 httpUpdate(http_t
*http
) /* I - Connection to server */
2828 http_status_t status
; /* Request status */
2831 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2832 http_states
[http
->state
]));
2835 * Flush pending data, if any...
2840 DEBUG_puts("2httpUpdate: flushing buffer...");
2842 if (httpFlushWrite(http
) < 0)
2843 return (HTTP_ERROR
);
2847 * If we haven't issued any commands, then there is nothing to "update"...
2850 if (http
->state
== HTTP_WAITING
)
2851 return (HTTP_CONTINUE
);
2854 * Grab all of the lines we can from the connection...
2857 while (_httpUpdate(http
, &status
));
2860 * See if there was an error...
2863 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2865 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2866 return (http
->status
);
2871 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2872 strerror(http
->error
)));
2873 http
->status
= HTTP_ERROR
;
2874 return (HTTP_ERROR
);
2878 * Return the current status...
2886 * '_httpWait()' - Wait for data available on a connection (no flush).
2889 int /* O - 1 if data is available, 0 otherwise */
2890 _httpWait(http_t
*http
, /* I - Connection to server */
2891 int msec
, /* I - Milliseconds to wait */
2892 int usessl
) /* I - Use SSL context? */
2895 struct pollfd pfd
; /* Polled file descriptor */
2897 fd_set input_set
; /* select() input set */
2898 struct timeval timeout
; /* Timeout */
2899 #endif /* HAVE_POLL */
2900 int nfds
; /* Result from select()/poll() */
2903 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2907 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2912 * Check the SSL/TLS buffers for data first...
2916 if (http
->tls
&& usessl
)
2919 if (SSL_pending(http
->tls
))
2921 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2925 # elif defined(HAVE_GNUTLS)
2926 if (gnutls_record_check_pending(http
->tls
))
2928 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2932 # elif defined(HAVE_CDSASSL)
2933 size_t bytes
; /* Bytes that are available */
2935 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2938 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2941 # endif /* HAVE_LIBSSL */
2943 #endif /* HAVE_SSL */
2946 * Then try doing a select() or poll() to poll the socket...
2951 pfd
.events
= POLLIN
;
2953 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2954 (errno
== EINTR
|| errno
== EAGAIN
));
2959 FD_ZERO(&input_set
);
2960 FD_SET(http
->fd
, &input_set
);
2962 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2966 timeout
.tv_sec
= msec
/ 1000;
2967 timeout
.tv_usec
= (msec
% 1000) * 1000;
2969 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2972 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2974 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2977 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2978 WSAGetLastError() == WSAEWOULDBLOCK
));
2980 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2982 #endif /* HAVE_POLL */
2984 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2992 * 'httpWait()' - Wait for data available on a connection.
2994 * @since CUPS 1.1.19/Mac OS X 10.3@
2997 int /* O - 1 if data is available, 0 otherwise */
2998 httpWait(http_t
*http
, /* I - Connection to server */
2999 int msec
) /* I - Milliseconds to wait */
3002 * First see if there is data in the buffer...
3005 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3012 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3017 * Flush pending data, if any...
3022 DEBUG_puts("3httpWait: Flushing write buffer.");
3024 if (httpFlushWrite(http
) < 0)
3029 * If not, check the SSL/TLS buffers and do a select() on the connection...
3032 return (_httpWait(http
, msec
, 1));
3037 * 'httpWrite()' - Write data to a HTTP connection.
3039 * This function is deprecated. Use the httpWrite2() function which can
3040 * write more than 2GB of data.
3045 int /* O - Number of bytes written */
3046 httpWrite(http_t
*http
, /* I - Connection to server */
3047 const char *buffer
, /* I - Buffer for data */
3048 int length
) /* I - Number of bytes to write */
3050 return ((int)httpWrite2(http
, buffer
, length
));
3055 * 'httpWrite2()' - Write data to a HTTP connection.
3057 * @since CUPS 1.2/Mac OS X 10.5@
3060 ssize_t
/* O - Number of bytes written */
3061 httpWrite2(http_t
*http
, /* I - Connection to server */
3062 const char *buffer
, /* I - Buffer for data */
3063 size_t length
) /* I - Number of bytes to write */
3065 ssize_t bytes
; /* Bytes written */
3068 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3069 buffer
, CUPS_LLCAST length
));
3072 * Range check input...
3075 if (http
== NULL
|| buffer
== NULL
)
3079 * Mark activity on the connection...
3082 http
->activity
= time(NULL
);
3085 * Buffer small writes for better performance...
3090 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3092 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3093 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3095 httpFlushWrite(http
);
3098 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3099 length
< sizeof(http
->wbuffer
))
3102 * Write to buffer...
3105 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3106 CUPS_LLCAST length
));
3108 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3109 http
->wused
+= (int)length
;
3110 bytes
= (ssize_t
)length
;
3115 * Otherwise write the data directly...
3118 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3119 CUPS_LLCAST length
));
3121 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3122 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3124 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3126 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3127 CUPS_LLCAST bytes
));
3130 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3131 http
->data_remaining
-= bytes
;
3137 * Handle end-of-request processing...
3140 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3141 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3144 * Finished with the transfer; unless we are sending POST or PUT
3148 DEBUG_puts("2httpWrite: changing states...");
3151 httpFlushWrite(http
);
3153 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3156 * Send a 0-length chunk at the end of the request...
3159 http_write(http
, "0\r\n\r\n", 5);
3162 * Reset the data state...
3165 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3166 http
->data_remaining
= 0;
3174 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3176 * '_httpWriteCDSA()' - Write function for the CDSA library.
3179 OSStatus
/* O - -1 on error, 0 on success */
3181 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3182 const void *data
, /* I - Data buffer */
3183 size_t *dataLength
) /* IO - Number of bytes */
3185 OSStatus result
; /* Return value */
3186 ssize_t bytes
; /* Number of bytes read */
3187 http_t
*http
; /* HTTP connection */
3190 http
= (http_t
*)connection
;
3194 bytes
= write(http
->fd
, data
, *dataLength
);
3196 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3198 if (bytes
== *dataLength
)
3202 else if (bytes
>= 0)
3204 *dataLength
= bytes
;
3205 result
= errSSLWouldBlock
;
3211 if (errno
== EAGAIN
)
3212 result
= errSSLWouldBlock
;
3214 result
= errSSLClosedAbort
;
3219 #endif /* HAVE_SSL && HAVE_CDSASSL */
3222 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3224 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3227 ssize_t
/* O - Number of bytes written or -1 on error */
3229 gnutls_transport_ptr ptr
, /* I - Connection to server */
3230 const void *data
, /* I - Data buffer */
3231 size_t length
) /* I - Number of bytes to write */
3233 ssize_t bytes
; /* Bytes written */
3236 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3239 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3242 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3243 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3247 #endif /* HAVE_SSL && HAVE_GNUTLS */
3250 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3252 * 'http_bio_ctrl()' - Control the HTTP connection.
3255 static long /* O - Result/data */
3256 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3257 int cmd
, /* I - Control command */
3258 long arg1
, /* I - First argument */
3259 void *arg2
) /* I - Second argument */
3266 case BIO_CTRL_RESET
:
3270 case BIO_C_SET_FILE_PTR
:
3275 case BIO_C_GET_FILE_PTR
:
3278 *((void **)arg2
) = h
->ptr
;
3285 case BIO_CTRL_FLUSH
:
3292 * 'http_bio_free()' - Free OpenSSL data.
3295 static int /* O - 1 on success, 0 on failure */
3296 http_bio_free(BIO
*h
) /* I - BIO data */
3312 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3315 static int /* O - 1 on success, 0 on failure */
3316 http_bio_new(BIO
*h
) /* I - BIO data */
3331 * 'http_bio_puts()' - Send a string for OpenSSL.
3334 static int /* O - Bytes written */
3335 http_bio_puts(BIO
*h
, /* I - BIO data */
3336 const char *str
) /* I - String to write */
3339 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3341 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3347 * 'http_bio_read()' - Read data for OpenSSL.
3350 static int /* O - Bytes read */
3351 http_bio_read(BIO
*h
, /* I - BIO data */
3352 char *buf
, /* I - Buffer */
3353 int size
) /* I - Number of bytes to read */
3355 http_t
*http
; /* HTTP connection */
3358 http
= (http_t
*)h
->ptr
;
3360 if (!http
->blocking
)
3363 * Make sure we have data before we read...
3366 while (!_httpWait(http
, http
->wait_value
, 0))
3368 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
3372 http
->error
= WSAETIMEDOUT
;
3374 http
->error
= ETIMEDOUT
;
3381 return (recv(http
->fd
, buf
, size
, 0));
3386 * 'http_bio_write()' - Write data for OpenSSL.
3389 static int /* O - Bytes written */
3390 http_bio_write(BIO
*h
, /* I - BIO data */
3391 const char *buf
, /* I - Buffer to write */
3392 int num
) /* I - Number of bytes to write */
3394 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3396 #endif /* HAVE_SSL && HAVE_LIBSSL */
3401 * 'http_debug_hex()' - Do a hex dump of a buffer.
3405 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3406 const char *buffer
, /* I - Buffer to dump */
3407 int bytes
) /* I - Bytes to dump */
3409 int i
, j
, /* Looping vars */
3410 ch
; /* Current character */
3411 char line
[255], /* Line buffer */
3412 *start
, /* Start of line after prefix */
3413 *ptr
; /* Pointer into line */
3416 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3419 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
3421 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3422 start
= line
+ strlen(line
);
3424 for (i
= 0; i
< bytes
; i
+= 16)
3426 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3427 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3439 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3441 ch
= buffer
[i
+ j
] & 255;
3443 if (ch
< ' ' || ch
>= 127)
3457 * 'http_field()' - Return the field index for a field name.
3460 static http_field_t
/* O - Field index */
3461 http_field(const char *name
) /* I - String name */
3463 int i
; /* Looping var */
3466 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3467 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
3468 return ((http_field_t
)i
);
3470 return (HTTP_FIELD_UNKNOWN
);
3476 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3479 static int /* O - Bytes read */
3480 http_read_ssl(http_t
*http
, /* I - Connection to server */
3481 char *buf
, /* I - Buffer to store data */
3482 int len
) /* I - Length of buffer */
3484 # if defined(HAVE_LIBSSL)
3485 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3487 # elif defined(HAVE_GNUTLS)
3488 ssize_t result
; /* Return value */
3491 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3493 if (result
< 0 && !errno
)
3496 * Convert GNU TLS error to errno value...
3501 case GNUTLS_E_INTERRUPTED
:
3505 case GNUTLS_E_AGAIN
:
3517 return ((int)result
);
3519 # elif defined(HAVE_CDSASSL)
3520 int result
; /* Return value */
3521 OSStatus error
; /* Error info */
3522 size_t processed
; /* Number of bytes processed */
3525 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3526 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
3531 result
= (int)processed
;
3534 case errSSLWouldBlock
:
3536 result
= (int)processed
;
3544 case errSSLClosedGraceful
:
3547 result
= (int)processed
;
3558 # elif defined(HAVE_SSPISSL)
3559 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3560 # endif /* HAVE_LIBSSL */
3562 #endif /* HAVE_SSL */
3566 * 'http_send()' - Send a request with all fields and the trailing blank line.
3569 static int /* O - 0 on success, non-zero on error */
3570 http_send(http_t
*http
, /* I - Connection to server */
3571 http_state_t request
, /* I - Request code */
3572 const char *uri
) /* I - URI */
3574 int i
; /* Looping var */
3575 char buf
[1024]; /* Encoded URI buffer */
3576 static const char * const codes
[] =
3577 { /* Request code strings */
3594 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3595 http
, codes
[request
], uri
));
3597 if (http
== NULL
|| uri
== NULL
)
3601 * Set the User-Agent field if it isn't already...
3604 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3605 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3608 * Encode the URI as needed...
3611 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3614 * See if we had an error the last time around; if so, reconnect...
3617 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3618 if (httpReconnect(http
))
3622 * Flush any written data that is pending...
3627 if (httpFlushWrite(http
) < 0)
3628 if (httpReconnect(http
))
3633 * Send the request header...
3636 http
->state
= request
;
3637 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3639 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3642 http
->status
= HTTP_CONTINUE
;
3645 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3647 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3648 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3650 #endif /* HAVE_SSL */
3652 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3654 http
->status
= HTTP_ERROR
;
3658 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3659 if (http
->fields
[i
][0] != '\0')
3661 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3662 httpGetField(http
, i
)));
3664 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3665 httpGetField(http
, i
)) < 1)
3667 http
->status
= HTTP_ERROR
;
3673 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3675 http
->status
= HTTP_ERROR
;
3679 if (http
->expect
== HTTP_CONTINUE
&&
3680 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3681 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3683 http
->status
= HTTP_ERROR
;
3687 if (httpPrintf(http
, "\r\n") < 1)
3689 http
->status
= HTTP_ERROR
;
3693 if (httpFlushWrite(http
) < 0)
3696 httpGetLength2(http
);
3697 httpClearFields(http
);
3700 * The Kerberos and AuthRef authentication strings can only be used once...
3703 if (http
->field_authorization
&& http
->authstring
&&
3704 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3705 !strncmp(http
->authstring
, "AuthRef", 7)))
3707 http
->_authstring
[0] = '\0';
3709 if (http
->authstring
!= http
->_authstring
)
3710 free(http
->authstring
);
3712 http
->authstring
= http
->_authstring
;
3720 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
3722 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3725 static int /* O - Status of connection */
3726 http_set_credentials(http_t
*http
) /* I - Connection to server */
3728 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3729 OSStatus error
= 0; /* Error code */
3730 http_tls_credentials_t credentials
= NULL
;
3731 /* TLS credentials */
3734 DEBUG_printf(("7http_set_credentials(%p)", http
));
3737 * Prefer connection specific credentials...
3740 if ((credentials
= http
->tls_credentials
) == NULL
)
3741 credentials
= cg
->tls_credentials
;
3743 # if HAVE_SECPOLICYCREATESSL
3745 * Otherwise root around in the user's keychain to see if one can be found...
3750 CFDictionaryRef query
; /* Query dictionary */
3751 CFTypeRef matches
= NULL
; /* Matching credentials */
3752 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3753 CFTypeRef keys
[] = { kSecClass
,
3756 /* Keys for dictionary */
3757 CFTypeRef values
[] = { kSecClassCertificate
,
3760 /* Values for dictionary */
3763 * Get the names associated with the server.
3766 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3768 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3774 * Create a query which will return all identities that can sign and match
3775 * the passed in policy.
3778 query
= CFDictionaryCreate(NULL
,
3779 (const void**)(&keys
[0]),
3780 (const void**)(&values
[0]),
3781 sizeof(keys
) / sizeof(keys
[0]),
3782 &kCFTypeDictionaryKeyCallBacks
,
3783 &kCFTypeDictionaryValueCallBacks
);
3786 error
= SecItemCopyMatching(query
, &matches
);
3787 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3796 CFRelease(dn_array
);
3798 # endif /* HAVE_SECPOLICYCREATESSL */
3802 error
= SSLSetCertificate(http
->tls
, credentials
);
3803 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3807 DEBUG_puts("4http_set_credentials: No credentials to set.");
3811 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
3812 #endif /* HAVE_SSL */
3816 * 'http_set_timeout()' - Set the socket timeout values.
3820 http_set_timeout(int fd
, /* I - File descriptor */
3821 double timeout
) /* I - Timeout in seconds */
3824 DWORD tv
= (DWORD
)(timeout
* 1000);
3825 /* Timeout in milliseconds */
3827 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&tv
, sizeof(tv
));
3828 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&tv
, sizeof(tv
));
3831 struct timeval tv
; /* Timeout in secs and usecs */
3833 tv
.tv_sec
= (int)timeout
;
3834 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
3836 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, &tv
, sizeof(tv
));
3837 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
3843 * 'http_set_wait()' - Set the default wait value for reads.
3847 http_set_wait(http_t
*http
) /* I - Connection to server */
3851 http
->wait_value
= (int)(http
->timeout_value
* 1000);
3853 if (http
->wait_value
<= 0)
3854 http
->wait_value
= 60000;
3857 http
->wait_value
= 10000;
3863 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3866 static int /* O - 0 on success, -1 on failure */
3867 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3869 _cups_globals_t
*cg
= _cupsGlobals();
3870 /* Pointer to library globals */
3871 int any_root
; /* Allow any root */
3872 char *hostname
; /* Hostname */
3875 SSL_CTX
*context
; /* Context for encryption */
3876 BIO
*bio
; /* BIO data */
3877 const char *message
= NULL
;/* Error message */
3878 # elif defined(HAVE_GNUTLS)
3879 int status
; /* Status of handshake */
3880 gnutls_certificate_client_credentials
*credentials
;
3881 /* TLS credentials */
3882 # elif defined(HAVE_CDSASSL)
3883 OSStatus error
; /* Error code */
3884 const char *message
= NULL
;/* Error message */
3885 # ifdef HAVE_SECCERTIFICATECOPYDATA
3886 cups_array_t
*credentials
; /* Credentials array */
3887 cups_array_t
*names
; /* CUPS distinguished names */
3888 CFArrayRef dn_array
; /* CF distinguished names array */
3889 CFIndex count
; /* Number of credentials */
3890 CFDataRef data
; /* Certificate data */
3891 int i
; /* Looping var */
3892 http_credential_t
*credential
; /* Credential data */
3893 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3894 # elif defined(HAVE_SSPISSL)
3895 TCHAR username
[256]; /* Username returned from GetUserName() */
3896 TCHAR commonName
[256];/* Common name for certificate */
3897 DWORD dwSize
; /* 32 bit size */
3898 # endif /* HAVE_LIBSSL */
3901 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3904 * Always allow self-signed certificates for the local loopback address...
3907 if (httpAddrLocalhost(http
->hostaddr
))
3910 any_root
= cg
->any_root
;
3912 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
3917 context
= SSL_CTX_new(SSLv23_client_method());
3919 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3921 bio
= BIO_new(_httpBIOMethods());
3922 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3924 http
->tls
= SSL_new(context
);
3925 SSL_set_bio(http
->tls
, bio
, bio
);
3927 SSL_set_tlsext_host_name(http
->tls
, hostname
);
3929 if (SSL_connect(http
->tls
) != 1)
3931 unsigned long error
; /* Error code */
3933 while ((error
= ERR_get_error()) != 0)
3935 message
= ERR_error_string(error
, NULL
);
3936 DEBUG_printf(("8http_setup_ssl: %s", message
));
3939 SSL_CTX_free(context
);
3940 SSL_free(http
->tls
);
3944 http
->error
= WSAGetLastError();
3946 http
->error
= errno
;
3948 http
->status
= HTTP_ERROR
;
3951 message
= _("Unable to establish a secure connection to host.");
3953 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
3958 # elif defined(HAVE_GNUTLS)
3961 credentials
= (gnutls_certificate_client_credentials
*)
3962 malloc(sizeof(gnutls_certificate_client_credentials
));
3963 if (credentials
== NULL
)
3965 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
3967 http
->error
= errno
;
3968 http
->status
= HTTP_ERROR
;
3969 _cupsSetHTTPError(HTTP_ERROR
);
3974 gnutls_certificate_allocate_credentials(credentials
);
3976 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3977 gnutls_set_default_priority(http
->tls
);
3978 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
3980 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3981 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3982 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3983 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3985 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3987 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
3988 status
, gnutls_strerror(status
)));
3990 if (gnutls_error_is_fatal(status
))
3993 http
->status
= HTTP_ERROR
;
3995 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
3997 gnutls_deinit(http
->tls
);
3998 gnutls_certificate_free_credentials(*credentials
);
4006 http
->tls_credentials
= credentials
;
4008 # elif defined(HAVE_CDSASSL)
4009 if ((error
= SSLNewContext(false, &http
->tls
)))
4011 http
->error
= errno
;
4012 http
->status
= HTTP_ERROR
;
4013 _cupsSetHTTPError(HTTP_ERROR
);
4018 error
= SSLSetConnection(http
->tls
, http
);
4019 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
4023 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
4024 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
4029 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
4030 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
4031 any_root
, (int)error
));
4036 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
4037 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
4038 cg
->expired_certs
, (int)error
));
4043 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
4044 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
4045 cg
->expired_root
, (int)error
));
4048 # ifdef HAVE_SSLSETPROTOCOLVERSIONMAX
4051 error
= SSLSetProtocolVersionMax(http
->tls
, kTLSProtocol1
);
4052 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionMax(kTLSProtocol1), "
4053 "error=%d", (int)error
));
4055 # endif /* HAVE_SSLSETPROTOCOLVERSIONMAX */
4058 * In general, don't verify certificates since things like the common name
4059 * often do not match...
4064 error
= SSLSetEnableCertVerify(http
->tls
, false);
4065 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
4069 # ifdef HAVE_SECCERTIFICATECOPYDATA
4072 if (cg
->client_cert_cb
)
4074 error
= SSLSetSessionOption(http
->tls
,
4075 kSSLSessionOptionBreakOnCertRequested
, true);
4076 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
4077 "error=%d", (int)error
));
4081 error
= http_set_credentials(http
);
4082 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
4088 * If there's a server certificate callback installed let it evaluate the
4089 * certificate(s) during the handshake...
4092 if (!error
&& cg
->server_cert_cb
!= NULL
)
4094 error
= SSLSetSessionOption(http
->tls
,
4095 kSSLSessionOptionBreakOnServerAuth
, true);
4096 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
4097 "error=%d", (int)error
));
4099 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4102 * Let the server know which hostname/domain we are trying to connect to
4103 * in case it wants to serve up a certificate with a matching common name.
4108 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
4110 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
4116 int done
= 0; /* Are we done yet? */
4118 while (!error
&& !done
)
4120 error
= SSLHandshake(http
->tls
);
4122 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
4130 case errSSLWouldBlock
:
4134 # ifdef HAVE_SECCERTIFICATECOPYDATA
4135 case errSSLServerAuthCompleted
:
4137 if (cg
->server_cert_cb
)
4139 error
= httpCopyCredentials(http
, &credentials
);
4142 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
4143 cg
->server_cert_data
);
4144 httpFreeCredentials(credentials
);
4147 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
4148 "returned %d.", (int)error
));
4152 case errSSLClientCertRequested
:
4155 if (cg
->client_cert_cb
)
4158 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
4161 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
4163 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
4165 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
4167 if ((credential
= malloc(sizeof(*credential
))))
4169 credential
->datalen
= CFDataGetLength(data
);
4170 if ((credential
->data
= malloc(credential
->datalen
)))
4172 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
4173 credential
->datalen
);
4174 cupsArrayAdd(names
, credential
);
4180 CFRelease(dn_array
);
4185 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
4186 cg
->client_cert_data
);
4188 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
4189 "returned %d.", (int)error
));
4192 httpFreeCredentials(names
);
4195 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4197 case errSSLUnknownRootCert
:
4198 message
= _("Unable to establish a secure connection to host "
4199 "(untrusted certificate).");
4202 case errSSLNoRootCert
:
4203 message
= _("Unable to establish a secure connection to host "
4204 "(self-signed certificate).");
4207 case errSSLCertExpired
:
4208 message
= _("Unable to establish a secure connection to host "
4209 "(expired certificate).");
4212 case errSSLCertNotYetValid
:
4213 message
= _("Unable to establish a secure connection to host "
4214 "(certificate not yet valid).");
4217 case errSSLHostNameMismatch
:
4218 message
= _("Unable to establish a secure connection to host "
4219 "(host name mismatch).");
4222 case errSSLXCertChainInvalid
:
4223 message
= _("Unable to establish a secure connection to host "
4224 "(certificate chain invalid).");
4227 case errSSLConnectionRefused
:
4228 message
= _("Unable to establish a secure connection to host "
4229 "(peer dropped connection before responding).");
4240 http
->error
= error
;
4241 http
->status
= HTTP_ERROR
;
4242 errno
= ECONNREFUSED
;
4244 SSLDisposeContext(http
->tls
);
4248 * If an error string wasn't set by the callbacks use a generic one...
4252 #ifdef HAVE_CSSMERRORSTRING
4253 message
= cssmErrorString(error
);
4255 message
= _("Unable to establish a secure connection to host.");
4256 #endif /* HAVE_CSSMERRORSTRING */
4258 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4263 # elif defined(HAVE_SSPISSL)
4264 http
->tls
= _sspiAlloc();
4268 _cupsSetHTTPError(HTTP_ERROR
);
4272 http
->tls
->sock
= http
->fd
;
4273 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4274 GetUserName(username
, &dwSize
);
4275 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4276 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4278 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4281 _sspiFree(http
->tls_credentials
);
4282 http
->tls_credentials
= NULL
;
4285 http
->status
= HTTP_ERROR
;
4287 _cupsSetError(IPP_PKI_ERROR
,
4288 _("Unable to establish a secure connection to host."), 1);
4293 _sspiSetAllowsAnyRoot(http
->tls_credentials
, any_root
);
4294 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4296 if (!_sspiConnect(http
->tls_credentials
, hostname
))
4298 _sspiFree(http
->tls_credentials
);
4299 http
->tls_credentials
= NULL
;
4302 http
->status
= HTTP_ERROR
;
4304 _cupsSetError(IPP_PKI_ERROR
,
4305 _("Unable to establish a secure connection to host."), 1);
4309 # endif /* HAVE_CDSASSL */
4316 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4320 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4323 SSL_CTX
*context
; /* Context for encryption */
4325 context
= SSL_get_SSL_CTX(http
->tls
);
4327 SSL_shutdown(http
->tls
);
4328 SSL_CTX_free(context
);
4329 SSL_free(http
->tls
);
4331 # elif defined(HAVE_GNUTLS)
4332 gnutls_certificate_client_credentials
*credentials
;
4333 /* TLS credentials */
4335 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4337 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4338 gnutls_deinit(http
->tls
);
4339 gnutls_certificate_free_credentials(*credentials
);
4342 # elif defined(HAVE_CDSASSL)
4343 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4346 SSLDisposeContext(http
->tls
);
4348 if (http
->tls_credentials
)
4349 CFRelease(http
->tls_credentials
);
4351 # elif defined(HAVE_SSPISSL)
4352 _sspiFree(http
->tls_credentials
);
4353 # endif /* HAVE_LIBSSL */
4356 http
->tls_credentials
= NULL
;
4358 #endif /* HAVE_SSL */
4363 * 'http_upgrade()' - Force upgrade to TLS encryption.
4366 static int /* O - Status of connection */
4367 http_upgrade(http_t
*http
) /* I - Connection to server */
4369 int ret
; /* Return value */
4370 http_t myhttp
; /* Local copy of HTTP data */
4373 DEBUG_printf(("7http_upgrade(%p)", http
));
4376 * Flush the connection to make sure any previous "Upgrade" message
4383 * Copy the HTTP data to a local variable so we can do the OPTIONS
4384 * request without interfering with the existing request data...
4387 memcpy(&myhttp
, http
, sizeof(myhttp
));
4390 * Send an OPTIONS request to the server, requiring SSL or TLS
4391 * encryption on the link...
4394 http
->field_authorization
= NULL
; /* Don't free the auth string */
4396 httpClearFields(http
);
4397 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4398 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4400 if ((ret
= httpOptions(http
, "*")) == 0)
4403 * Wait for the secure connection...
4406 while (httpUpdate(http
) == HTTP_CONTINUE
);
4410 * Restore the HTTP request data...
4413 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4414 http
->data_encoding
= myhttp
.data_encoding
;
4415 http
->data_remaining
= myhttp
.data_remaining
;
4416 http
->_data_remaining
= myhttp
._data_remaining
;
4417 http
->expect
= myhttp
.expect
;
4418 http
->field_authorization
= myhttp
.field_authorization
;
4419 http
->digest_tries
= myhttp
.digest_tries
;
4422 * See if we actually went secure...
4428 * Server does not support HTTP upgrade...
4431 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4434 closesocket(http
->fd
);
4446 #endif /* HAVE_SSL */
4450 * 'http_write()' - Write a buffer to a HTTP connection.
4453 static int /* O - Number of bytes written */
4454 http_write(http_t
*http
, /* I - Connection to server */
4455 const char *buffer
, /* I - Buffer for data */
4456 int length
) /* I - Number of bytes to write */
4458 int tbytes
, /* Total bytes sent */
4459 bytes
; /* Bytes sent */
4462 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4469 if (http
->timeout_cb
)
4472 struct pollfd pfd
; /* Polled file descriptor */
4474 fd_set output_set
; /* Output ready for write? */
4475 struct timeval timeout
; /* Timeout value */
4476 #endif /* HAVE_POLL */
4477 int nfds
; /* Result from select()/poll() */
4483 pfd
.events
= POLLOUT
;
4485 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
4486 (errno
== EINTR
|| errno
== EAGAIN
));
4491 FD_ZERO(&output_set
);
4492 FD_SET(http
->fd
, &output_set
);
4494 timeout
.tv_sec
= http
->wait_value
/ 1000;
4495 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
4497 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
4500 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
4501 WSAGetLastError() == WSAEWOULDBLOCK
));
4503 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
4505 #endif /* HAVE_POLL */
4509 http
->error
= errno
;
4512 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4515 http
->error
= WSAEWOULDBLOCK
;
4517 http
->error
= EWOULDBLOCK
;
4527 bytes
= http_write_ssl(http
, buffer
, length
);
4529 #endif /* HAVE_SSL */
4530 bytes
= send(http
->fd
, buffer
, length
, 0);
4535 if (WSAGetLastError() == WSAEINTR
)
4537 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4539 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4542 http
->error
= WSAGetLastError();
4544 else if (WSAGetLastError() != http
->error
&&
4545 WSAGetLastError() != WSAECONNRESET
)
4547 http
->error
= WSAGetLastError();
4554 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4556 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4558 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4561 http
->error
= errno
;
4563 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4565 http
->error
= errno
;
4570 DEBUG_printf(("3http_write: error writing data (%s).",
4571 strerror(http
->error
)));
4582 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4585 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4592 * 'http_write_chunk()' - Write a chunked buffer.
4595 static int /* O - Number bytes written */
4596 http_write_chunk(http_t
*http
, /* I - Connection to server */
4597 const char *buffer
, /* I - Buffer to write */
4598 int length
) /* I - Length of buffer */
4600 char header
[255]; /* Chunk header */
4601 int bytes
; /* Bytes written */
4604 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4605 http
, buffer
, length
));
4608 * Write the chunk header, data, and trailer.
4611 sprintf(header
, "%x\r\n", length
);
4612 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4614 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4618 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4620 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4624 if (http_write(http
, "\r\n", 2) < 0)
4626 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4636 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4639 static int /* O - Bytes written */
4640 http_write_ssl(http_t
*http
, /* I - Connection to server */
4641 const char *buf
, /* I - Buffer holding data */
4642 int len
) /* I - Length of buffer */
4644 ssize_t result
; /* Return value */
4647 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4649 # if defined(HAVE_LIBSSL)
4650 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4652 # elif defined(HAVE_GNUTLS)
4653 result
= gnutls_record_send(http
->tls
, buf
, len
);
4655 if (result
< 0 && !errno
)
4658 * Convert GNU TLS error to errno value...
4663 case GNUTLS_E_INTERRUPTED
:
4667 case GNUTLS_E_AGAIN
:
4679 # elif defined(HAVE_CDSASSL)
4680 OSStatus error
; /* Error info */
4681 size_t processed
; /* Number of bytes processed */
4684 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4689 result
= (int)processed
;
4692 case errSSLWouldBlock
:
4694 result
= (int)processed
;
4702 case errSSLClosedGraceful
:
4705 result
= (int)processed
;
4713 # elif defined(HAVE_SSPISSL)
4714 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
4715 # endif /* HAVE_LIBSSL */
4717 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4719 return ((int)result
);
4721 #endif /* HAVE_SSL */
4725 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".