2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for CUPS.
6 * Copyright 2007-2011 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 * httpGetStatus() - Get the status of the last HTTP request.
60 * httpGetSubField() - Get a sub-field value.
61 * httpGetSubField2() - Get a sub-field value.
62 * httpGets() - Get a line of text from a HTTP connection.
63 * httpHead() - Send a HEAD request to the server.
64 * httpInitialize() - Initialize the HTTP interface library and set
65 * the default HTTP proxy (if any).
66 * httpOptions() - Send an OPTIONS request to the server.
67 * _httpPeek() - Peek at data from a HTTP connection.
68 * httpPost() - Send a POST request to the server.
69 * httpPrintf() - Print a formatted string to a HTTP connection.
70 * httpPut() - Send a PUT request to the server.
71 * httpRead() - Read data from a HTTP connection.
72 * httpRead2() - Read data from a HTTP connection.
73 * _httpReadCDSA() - Read function for the CDSA library.
74 * _httpReadGNUTLS() - Read function for the GNU TLS library.
75 * httpReconnect() - Reconnect to a HTTP server.
76 * httpSetAuthString() - Set the current authorization string.
77 * httpSetCredentials() - Set the credentials associated with an
78 * encrypted connection.
79 * httpSetCookie() - Set the cookie value(s).
80 * httpSetExpect() - Set the Expect: header in a request.
81 * httpSetField() - Set the value of an HTTP header.
82 * httpSetLength() - Set the content-length and content-encoding.
83 * httpSetTimeout() - Set read/write timeouts and an optional
85 * httpTrace() - Send an TRACE request to the server.
86 * _httpUpdate() - Update the current HTTP status for incoming
88 * httpUpdate() - Update the current HTTP state for incoming
90 * _httpWait() - Wait for data available on a connection (no
92 * httpWait() - Wait for data available on a connection.
93 * httpWrite() - Write data to a HTTP connection.
94 * httpWrite2() - Write data to a HTTP connection.
95 * _httpWriteCDSA() - Write function for the CDSA library.
96 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
97 * http_bio_ctrl() - Control the HTTP connection.
98 * http_bio_free() - Free OpenSSL data.
99 * http_bio_new() - Initialize an OpenSSL BIO structure.
100 * http_bio_puts() - Send a string for OpenSSL.
101 * http_bio_read() - Read data for OpenSSL.
102 * http_bio_write() - Write data for OpenSSL.
103 * http_debug_hex() - Do a hex dump of a buffer.
104 * http_field() - Return the field index for a field name.
105 * http_read_ssl() - Read from a SSL/TLS connection.
106 * http_locking_cb() - Lock/unlock a thread's mutex.
107 * http_send() - Send a request with all fields and the trailing
109 * http_set_credentials() - Set the SSL/TLS credentials.
110 * http_set_timeout() - Set the socket timeout values.
111 * http_set_wait() - Set the default wait value for reads.
112 * http_setup_ssl() - Set up SSL/TLS support on a connection.
113 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
114 * http_threadid_cb() - Return the current thread ID.
115 * http_upgrade() - Force upgrade to TLS encryption.
116 * http_write() - Write a buffer to a HTTP connection.
117 * http_write_chunk() - Write a chunked buffer.
118 * http_write_ssl() - Write to a SSL/TLS connection.
122 * Include necessary headers...
125 #include "cups-private.h"
131 # include <sys/time.h>
132 # include <sys/resource.h>
135 # include <sys/poll.h>
136 #endif /* HAVE_POLL */
140 * Some operating systems have done away with the Fxxxx constants for
141 * the fcntl() call; this works around that "feature"...
145 # define FNONBLK O_NONBLOCK
146 #endif /* !FNONBLK */
154 static void http_debug_hex(const char *prefix
, const char *buffer
,
157 static http_field_t
http_field(const char *name
);
158 static int http_send(http_t
*http
, http_state_t request
,
160 static int http_write(http_t
*http
, const char *buffer
,
162 static int http_write_chunk(http_t
*http
, const char *buffer
,
165 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
166 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
167 static int http_set_credentials(http_t
*http
);
168 # endif /* HAVE_CDSASSL ** HAVE_SECCERTIFICATECOPYDATA */
169 static void http_set_timeout(int fd
, double timeout
);
170 static void http_set_wait(http_t
*http
);
171 static int http_setup_ssl(http_t
*http
);
172 static void http_shutdown_ssl(http_t
*http
);
173 static int http_upgrade(http_t
*http
);
174 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
175 #endif /* HAVE_SSL */
182 static const char * const http_fields
[] =
199 "If-Unmodified-since",
213 static const char * const http_states
[] =
233 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
235 * BIO methods for OpenSSL...
238 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
239 static int http_bio_read(BIO
*h
, char *buf
, int size
);
240 static int http_bio_puts(BIO
*h
, const char *str
);
241 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
242 static int http_bio_new(BIO
*h
);
243 static int http_bio_free(BIO
*data
);
245 static BIO_METHOD http_bio_methods
=
252 NULL
, /* http_bio_gets, */
258 #endif /* HAVE_SSL && HAVE_LIBSSL */
262 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
264 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
266 * @since CUPS 1.5/Mac OS X 10.7@
269 int /* O - 0 on success, -1 on error */
271 cups_array_t
*credentials
, /* I - Credentials array */
272 const void *data
, /* I - PEM-encoded X.509 data */
273 size_t datalen
) /* I - Length of data */
275 http_credential_t
*credential
; /* Credential data */
278 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
280 credential
->datalen
= datalen
;
282 if ((credential
->data
= malloc(datalen
)) != NULL
)
284 memcpy(credential
->data
, data
, datalen
);
285 cupsArrayAdd(credentials
, credential
);
296 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
298 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
301 BIO_METHOD
* /* O - BIO methods for OpenSSL */
302 _httpBIOMethods(void)
304 return (&http_bio_methods
);
306 #endif /* HAVE_SSL && HAVE_LIBSSL */
310 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
314 httpBlocking(http_t
*http
, /* I - Connection to server */
315 int b
) /* I - 1 = blocking, 0 = non-blocking */
326 * 'httpCheck()' - Check to see if there is a pending response from the server.
329 int /* O - 0 = no data, 1 = data available */
330 httpCheck(http_t
*http
) /* I - Connection to server */
332 return (httpWait(http
, 0));
337 * 'httpClearCookie()' - Clear the cookie value(s).
339 * @since CUPS 1.1.19/Mac OS X 10.3@
343 httpClearCookie(http_t
*http
) /* I - Connection to server */
357 * 'httpClearFields()' - Clear HTTP request fields.
361 httpClearFields(http_t
*http
) /* I - Connection to server */
365 memset(http
->fields
, 0, sizeof(http
->fields
));
366 if (http
->hostname
[0] == '/')
367 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
369 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
371 if (http
->field_authorization
)
373 free(http
->field_authorization
);
374 http
->field_authorization
= NULL
;
377 http
->expect
= (http_status_t
)0;
383 * 'httpClose()' - Close an HTTP connection.
387 httpClose(http_t
*http
) /* I - Connection to server */
390 OM_uint32 minor_status
; /* Minor status code */
391 #endif /* HAVE_GSSAPI */
394 DEBUG_printf(("httpClose(http=%p)", http
));
397 * Range check input...
404 * Close any open connection...
407 _httpDisconnect(http
);
410 * Free memory used...
413 httpAddrFreeList(http
->addrlist
);
419 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
420 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
422 if (http
->gssname
!= GSS_C_NO_NAME
)
423 gss_release_name(&minor_status
, &http
->gssname
);
424 #endif /* HAVE_GSSAPI */
426 #ifdef HAVE_AUTHORIZATION_H
428 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
429 #endif /* HAVE_AUTHORIZATION_H */
431 httpClearFields(http
);
433 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
434 free(http
->authstring
);
441 * 'httpConnect()' - Connect to a HTTP server.
443 * This function is deprecated - use @link httpConnectEncrypt@ instead.
448 http_t
* /* O - New HTTP connection */
449 httpConnect(const char *host
, /* I - Host to connect to */
450 int port
) /* I - Port number */
452 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
457 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
460 http_t
* /* O - New HTTP connection */
462 const char *host
, /* I - Host to connect to */
463 int port
, /* I - Port number */
464 http_encryption_t encryption
) /* I - Type of encryption to use */
466 http_t
*http
; /* New HTTP connection */
469 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
470 host
, port
, encryption
));
473 * Create the HTTP structure...
476 if ((http
= _httpCreate(host
, port
, NULL
, encryption
, AF_UNSPEC
)) == NULL
)
480 * Connect to the remote system...
483 if (!httpReconnect(http
))
487 * Could not connect to any known address - bail out!
490 httpAddrFreeList(http
->addrlist
);
499 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
502 * @since CUPS 1.5/Mac OS X 10.7@
505 int /* O - Status of call (0 = success) */
507 http_t
*http
, /* I - Connection to server */
508 cups_array_t
**credentials
) /* O - Array of credentials */
511 # elif defined(HAVE_GNUTLS)
512 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
513 OSStatus error
; /* Error code */
514 CFIndex count
; /* Number of credentials */
515 CFArrayRef peerCerts
; /* Peer certificates */
516 SecCertificateRef secCert
; /* Certificate reference */
517 CFDataRef data
; /* Certificate data */
518 int i
; /* Looping var */
519 # elif defined(HAVE_SSPISSL)
520 # endif /* HAVE_LIBSSL */
526 if (!http
|| !http
->tls
|| !credentials
)
532 # elif defined(HAVE_GNUTLS)
535 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
536 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
538 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
540 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
542 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
543 if ((data
= SecCertificateCopyData(secCert
)))
545 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
546 CFDataGetLength(data
));
552 CFRelease(peerCerts
);
557 # elif defined(HAVE_SSPISSL)
562 # endif /* HAVE_LIBSSL */
567 * '_httpCreate()' - Create an unconnected HTTP connection.
570 http_t
* /* O - HTTP connection */
572 const char *host
, /* I - Hostname */
573 int port
, /* I - Port number */
574 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
575 http_encryption_t encryption
, /* I - Encryption to use */
576 int family
) /* I - Address family or AF_UNSPEC */
578 http_t
*http
; /* New HTTP connection */
579 char service
[255]; /* Service name */
582 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
583 host
, port
, encryption
));
594 sprintf(service
, "%d", port
);
597 if ((addrlist
= httpAddrGetList(host
, family
, service
)) == NULL
)
601 * Allocate memory for the structure...
604 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
606 httpAddrFreeList(addrlist
);
611 * Initialize the HTTP data...
614 http
->activity
= time(NULL
);
615 http
->addrlist
= addrlist
;
619 http
->gssctx
= GSS_C_NO_CONTEXT
;
620 http
->gssname
= GSS_C_NO_NAME
;
621 #endif /* HAVE_GSSAPI */
622 http
->version
= HTTP_1_1
;
624 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
626 if (port
== 443) /* Always use encryption for https */
627 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
629 http
->encryption
= encryption
;
634 * Return the new structure...
642 * '_httpCreateCredentials()' - Create credentials in the internal format.
645 http_tls_credentials_t
/* O - Internal credentials */
646 _httpCreateCredentials(
647 cups_array_t
*credentials
) /* I - Array of credentials */
655 # elif defined(HAVE_GNUTLS)
658 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
659 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
660 SecCertificateRef secCert
; /* Certificate reference */
661 CFDataRef data
; /* Credential data reference */
662 http_credential_t
*credential
; /* Credential data */
665 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
666 cupsArrayCount(credentials
),
667 &kCFTypeArrayCallBacks
)) == NULL
)
670 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
672 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
674 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
675 credential
->datalen
)))
677 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
680 CFArrayAppendValue(peerCerts
, secCert
);
690 # elif defined(HAVE_SSPISSL)
695 # endif /* HAVE_LIBSSL */
700 * 'httpDelete()' - Send a DELETE request to the server.
703 int /* O - Status of call (0 = success) */
704 httpDelete(http_t
*http
, /* I - Connection to server */
705 const char *uri
) /* I - URI to delete */
707 return (http_send(http
, HTTP_DELETE
, uri
));
712 * '_httpDisconnect()' - Disconnect a HTTP connection.
716 _httpDisconnect(http_t
*http
) /* I - Connection to server */
720 http_shutdown_ssl(http
);
721 #endif /* HAVE_SSL */
724 closesocket(http
->fd
);
734 * 'httpEncryption()' - Set the required encryption on the link.
737 int /* O - -1 on error, 0 on success */
738 httpEncryption(http_t
*http
, /* I - Connection to server */
739 http_encryption_t e
) /* I - New encryption preference */
741 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
747 http
->encryption
= e
;
749 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
750 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
751 return (httpReconnect(http
));
752 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
753 return (http_upgrade(http
));
757 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
761 #endif /* HAVE_SSL */
766 * 'httpError()' - Get the last error on a connection.
769 int /* O - Error code (errno) value */
770 httpError(http_t
*http
) /* I - Connection to server */
773 return (http
->error
);
780 * 'httpFlush()' - Flush data from a HTTP connection.
784 httpFlush(http_t
*http
) /* I - Connection to server */
786 char buffer
[8192]; /* Junk buffer */
787 int blocking
; /* To block or not to block */
788 http_state_t oldstate
; /* Old state */
791 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
792 http_states
[http
->state
]));
795 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
798 blocking
= http
->blocking
;
802 * Read any data we can...
805 oldstate
= http
->state
;
806 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
809 * Restore blocking and reset the connection if we didn't get all of
810 * the remaining data...
813 http
->blocking
= blocking
;
815 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
818 * Didn't get the data back, so close the current connection.
821 http
->state
= HTTP_WAITING
;
825 http_shutdown_ssl(http
);
826 #endif /* HAVE_SSL */
829 closesocket(http
->fd
);
840 * 'httpFlushWrite()' - Flush data in write buffer.
842 * @since CUPS 1.2/Mac OS X 10.5@
845 int /* O - Bytes written or -1 on error */
846 httpFlushWrite(http_t
*http
) /* I - Connection to server */
848 int bytes
; /* Bytes written */
851 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
853 if (!http
|| !http
->wused
)
855 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
856 "1httpFlushWrite: No connection.");
860 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
861 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
863 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
867 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
874 * '_httpFreeCredentials()' - Free internal credentials.
878 _httpFreeCredentials(
879 http_tls_credentials_t credentials
) /* I - Internal credentials */
887 #elif defined(HAVE_GNUTLS)
890 #elif defined(HAVE_CDSASSL)
891 CFRelease(credentials
);
893 #elif defined(HAVE_SSPISSL)
896 #endif /* HAVE_LIBSSL */
901 * 'httpFreeCredentials()' - Free an array of credentials.
906 cups_array_t
*credentials
) /* I - Array of credentials */
908 http_credential_t
*credential
; /* Credential */
911 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
913 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
915 cupsArrayRemove(credentials
, credential
);
916 free((void *)credential
->data
);
920 cupsArrayDelete(credentials
);
925 * 'httpGet()' - Send a GET request to the server.
928 int /* O - Status of call (0 = success) */
929 httpGet(http_t
*http
, /* I - Connection to server */
930 const char *uri
) /* I - URI to get */
932 return (http_send(http
, HTTP_GET
, uri
));
937 * 'httpGetAuthString()' - Get the current authorization string.
939 * The authorization string is set by cupsDoAuthentication() and
940 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
941 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
944 * @since CUPS 1.3/Mac OS X 10.5@
947 char * /* O - Authorization string */
948 httpGetAuthString(http_t
*http
) /* I - Connection to server */
951 return (http
->authstring
);
958 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
960 * @since CUPS 1.2/Mac OS X 10.5@
963 int /* O - 1 if blocking, 0 if non-blocking */
964 httpGetBlocking(http_t
*http
) /* I - Connection to server */
966 return (http
? http
->blocking
: 0);
971 * 'httpGetCookie()' - Get any cookie data from the response.
973 * @since CUPS 1.1.19/Mac OS X 10.3@
976 const char * /* O - Cookie data or NULL */
977 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
979 return (http
? http
->cookie
: NULL
);
984 * 'httpGetFd()' - Get the file descriptor associated with a connection.
986 * @since CUPS 1.2/Mac OS X 10.5@
989 int /* O - File descriptor or -1 if none */
990 httpGetFd(http_t
*http
) /* I - Connection to server */
992 return (http
? http
->fd
: -1);
997 * 'httpGetField()' - Get a field value from a request/response.
1000 const char * /* O - Field value */
1001 httpGetField(http_t
*http
, /* I - Connection to server */
1002 http_field_t field
) /* I - Field to get */
1004 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1006 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
1007 http
->field_authorization
)
1010 * Special case for WWW-Authenticate: as its contents can be
1011 * longer than HTTP_MAX_VALUE...
1014 return (http
->field_authorization
);
1017 return (http
->fields
[field
]);
1022 * 'httpGetLength()' - Get the amount of data remaining from the
1023 * content-length or transfer-encoding fields.
1025 * This function is deprecated and will not return lengths larger than
1026 * 2^31 - 1; use httpGetLength2() instead.
1031 int /* O - Content length */
1032 httpGetLength(http_t
*http
) /* I - Connection to server */
1035 * Get the read content length and return the 32-bit value.
1040 httpGetLength2(http
);
1042 return (http
->_data_remaining
);
1050 * 'httpGetLength2()' - Get the amount of data remaining from the
1051 * content-length or transfer-encoding fields.
1053 * This function returns the complete content length, even for
1054 * content larger than 2^31 - 1.
1056 * @since CUPS 1.2/Mac OS X 10.5@
1059 off_t
/* O - Content length */
1060 httpGetLength2(http_t
*http
) /* I - Connection to server */
1062 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1063 http_states
[http
->state
]));
1068 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1070 DEBUG_puts("4httpGetLength2: chunked request!");
1072 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1073 http
->data_remaining
= 0;
1077 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1080 * The following is a hack for HTTP servers that don't send a
1081 * content-length or transfer-encoding field...
1083 * If there is no content-length then the connection must close
1084 * after the transfer is complete...
1087 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1090 * Default content length is 0 for errors and 2^31-1 for other
1091 * successful requests...
1094 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
1095 http
->data_remaining
= 0;
1097 http
->data_remaining
= 2147483647;
1100 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1103 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1104 CUPS_LLCAST http
->data_remaining
));
1107 if (http
->data_remaining
<= INT_MAX
)
1108 http
->_data_remaining
= (int)http
->data_remaining
;
1110 http
->_data_remaining
= INT_MAX
;
1112 return (http
->data_remaining
);
1117 * 'httpGetStatus()' - Get the status of the last HTTP request.
1119 * @since CUPS 1.2/Mac OS X 10.5@
1122 http_status_t
/* O - HTTP status */
1123 httpGetStatus(http_t
*http
) /* I - Connection to server */
1125 return (http
? http
->status
: HTTP_ERROR
);
1130 * 'httpGetSubField()' - Get a sub-field value.
1135 char * /* O - Value or NULL */
1136 httpGetSubField(http_t
*http
, /* I - Connection to server */
1137 http_field_t field
, /* I - Field index */
1138 const char *name
, /* I - Name of sub-field */
1139 char *value
) /* O - Value string */
1141 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1146 * 'httpGetSubField2()' - Get a sub-field value.
1148 * @since CUPS 1.2/Mac OS X 10.5@
1151 char * /* O - Value or NULL */
1152 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1153 http_field_t field
, /* I - Field index */
1154 const char *name
, /* I - Name of sub-field */
1155 char *value
, /* O - Value string */
1156 int valuelen
) /* I - Size of value buffer */
1158 const char *fptr
; /* Pointer into field */
1159 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1160 *ptr
, /* Pointer into string buffer */
1161 *end
; /* End of value buffer */
1163 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1164 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1166 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1167 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1170 end
= value
+ valuelen
- 1;
1172 for (fptr
= http
->fields
[field
]; *fptr
;)
1175 * Skip leading whitespace...
1178 while (_cups_isspace(*fptr
))
1188 * Get the sub-field name...
1192 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1193 ptr
< (temp
+ sizeof(temp
) - 1);
1198 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1201 * Skip trailing chars up to the '='...
1204 while (_cups_isspace(*fptr
))
1214 * Skip = and leading whitespace...
1219 while (_cups_isspace(*fptr
))
1225 * Read quoted string...
1228 for (ptr
= value
, fptr
++;
1229 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1234 while (*fptr
&& *fptr
!= '\"')
1243 * Read unquoted string...
1247 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1252 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1256 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1259 * See if this is the one...
1262 if (!strcmp(name
, temp
))
1264 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1271 DEBUG_puts("3httpGetSubField2: Returning NULL");
1278 * 'httpGets()' - Get a line of text from a HTTP connection.
1281 char * /* O - Line or NULL */
1282 httpGets(char *line
, /* I - Line to read into */
1283 int length
, /* I - Max length of buffer */
1284 http_t
*http
) /* I - Connection to server */
1286 char *lineptr
, /* Pointer into line */
1287 *lineend
, /* End of line */
1288 *bufptr
, /* Pointer into input buffer */
1289 *bufend
; /* Pointer to end of buffer */
1290 int bytes
, /* Number of bytes read */
1291 eol
; /* End-of-line? */
1294 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1296 if (http
== NULL
|| line
== NULL
)
1300 * Read a line from the buffer...
1305 lineend
= line
+ length
- 1;
1308 while (lineptr
< lineend
)
1311 * Pre-load the buffer as needed...
1320 while (http
->used
== 0)
1323 * No newline; see if there is more data to be read...
1326 while (!_httpWait(http
, http
->wait_value
, 1))
1328 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1331 DEBUG_puts("3httpGets: Timed out!");
1333 http
->error
= WSAETIMEDOUT
;
1335 http
->error
= ETIMEDOUT
;
1342 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1343 HTTP_MAX_BUFFER
- http
->used
);
1345 #endif /* HAVE_SSL */
1346 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1347 HTTP_MAX_BUFFER
- http
->used
, 0);
1349 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1354 * Nope, can't get a line this time...
1358 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1360 if (WSAGetLastError() == WSAEINTR
)
1362 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1364 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1367 http
->error
= WSAGetLastError();
1369 else if (WSAGetLastError() != http
->error
)
1371 http
->error
= WSAGetLastError();
1376 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1380 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1382 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1384 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1387 http
->error
= errno
;
1389 else if (errno
!= http
->error
)
1391 http
->error
= errno
;
1398 else if (bytes
== 0)
1400 http
->error
= EPIPE
;
1406 * Yup, update the amount used...
1409 http
->used
+= bytes
;
1413 * Now copy as much of the current line as possible...
1416 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1417 lineptr
< lineend
&& bufptr
< bufend
;)
1419 if (*bufptr
== 0x0a)
1425 else if (*bufptr
== 0x0d)
1428 *lineptr
++ = *bufptr
++;
1431 http
->used
-= (int)(bufptr
- http
->buffer
);
1433 memmove(http
->buffer
, bufptr
, http
->used
);
1441 http
->activity
= time(NULL
);
1445 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1451 DEBUG_puts("3httpGets: No new line available!");
1458 * 'httpHead()' - Send a HEAD request to the server.
1461 int /* O - Status of call (0 = success) */
1462 httpHead(http_t
*http
, /* I - Connection to server */
1463 const char *uri
) /* I - URI for head */
1465 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1466 return (http_send(http
, HTTP_HEAD
, uri
));
1471 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1472 * default HTTP proxy (if any).
1476 httpInitialize(void)
1478 static int initialized
= 0; /* Have we been called before? */
1480 WSADATA winsockdata
; /* WinSock data */
1483 int i
; /* Looping var */
1484 unsigned char data
[1024]; /* Seed data */
1485 #endif /* HAVE_LIBSSL */
1491 _cupsGlobalUnlock();
1496 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1498 #elif !defined(SO_NOSIGPIPE)
1500 * Ignore SIGPIPE signals...
1504 sigset(SIGPIPE
, SIG_IGN
);
1506 # elif defined(HAVE_SIGACTION)
1507 struct sigaction action
; /* POSIX sigaction data */
1510 memset(&action
, 0, sizeof(action
));
1511 action
.sa_handler
= SIG_IGN
;
1512 sigaction(SIGPIPE
, &action
, NULL
);
1515 signal(SIGPIPE
, SIG_IGN
);
1516 # endif /* !SO_NOSIGPIPE */
1521 * Initialize GNU TLS...
1524 gnutls_global_init();
1526 #elif defined(HAVE_LIBSSL)
1528 * Initialize OpenSSL...
1531 SSL_load_error_strings();
1535 * Using the current time is a dubious random seed, but on some systems
1536 * it is the best we can do (on others, this seed isn't even used...)
1539 CUPS_SRAND(time(NULL
));
1541 for (i
= 0; i
< sizeof(data
); i
++)
1542 data
[i
] = CUPS_RAND();
1544 RAND_seed(data
, sizeof(data
));
1545 #endif /* HAVE_GNUTLS */
1548 _cupsGlobalUnlock();
1553 * 'httpOptions()' - Send an OPTIONS request to the server.
1556 int /* O - Status of call (0 = success) */
1557 httpOptions(http_t
*http
, /* I - Connection to server */
1558 const char *uri
) /* I - URI for options */
1560 return (http_send(http
, HTTP_OPTIONS
, uri
));
1565 * '_httpPeek()' - Peek at data from a HTTP connection.
1567 * This function copies available data from the given HTTP connection, reading
1568 * a buffer as needed. The data is still available for reading using
1569 * @link httpRead@ or @link httpRead2@.
1571 * For non-blocking connections the usual timeouts apply.
1574 ssize_t
/* O - Number of bytes copied */
1575 _httpPeek(http_t
*http
, /* I - Connection to server */
1576 char *buffer
, /* I - Buffer for data */
1577 size_t length
) /* I - Maximum number of bytes */
1579 ssize_t bytes
; /* Bytes read */
1580 char len
[32]; /* Length string */
1583 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1584 http
, buffer
, CUPS_LLCAST length
));
1586 if (http
== NULL
|| buffer
== NULL
)
1589 http
->activity
= time(NULL
);
1595 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1596 http
->data_remaining
<= 0)
1598 DEBUG_puts("2_httpPeek: Getting chunk length...");
1600 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1602 DEBUG_puts("1_httpPeek: Could not get length!");
1606 http
->data_remaining
= strtoll(len
, NULL
, 16);
1607 if (http
->data_remaining
< 0)
1609 DEBUG_puts("1_httpPeek: Negative chunk length!");
1614 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1615 CUPS_LLCAST http
->data_remaining
));
1617 if (http
->data_remaining
<= 0)
1620 * A zero-length chunk ends a transfer; unless we are reading POST
1624 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1625 httpGets(len
, sizeof(len
), http
);
1627 if (http
->state
== HTTP_POST_RECV
)
1630 http
->state
= HTTP_WAITING
;
1633 * Prevent future reads for this request...
1636 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1640 else if (length
> (size_t)http
->data_remaining
)
1641 length
= (size_t)http
->data_remaining
;
1643 if (http
->used
== 0)
1646 * Buffer small reads for better performance...
1649 if (!http
->blocking
)
1651 while (!httpWait(http
, http
->wait_value
))
1653 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1660 if (http
->data_remaining
> sizeof(http
->buffer
))
1661 bytes
= sizeof(http
->buffer
);
1663 bytes
= http
->data_remaining
;
1667 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1669 #endif /* HAVE_SSL */
1671 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1674 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1676 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1685 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1687 http
->error
= WSAGetLastError();
1691 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1693 http
->error
= errno
;
1700 http
->error
= EPIPE
;
1707 if (length
> (size_t)http
->used
)
1708 length
= (size_t)http
->used
;
1710 bytes
= (ssize_t
)length
;
1712 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1715 memcpy(buffer
, http
->buffer
, length
);
1723 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1726 http
->error
= WSAGetLastError();
1728 if (errno
== EINTR
|| errno
== EAGAIN
)
1731 http
->error
= errno
;
1734 else if (bytes
== 0)
1736 http
->error
= EPIPE
;
1741 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1749 * 'httpPost()' - Send a POST request to the server.
1752 int /* O - Status of call (0 = success) */
1753 httpPost(http_t
*http
, /* I - Connection to server */
1754 const char *uri
) /* I - URI for post */
1756 return (http_send(http
, HTTP_POST
, uri
));
1761 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1766 int /* O - Number of bytes written */
1767 httpPrintf(http_t
*http
, /* I - Connection to server */
1768 const char *format
, /* I - printf-style format string */
1769 ...) /* I - Additional args as needed */
1771 int bytes
; /* Number of bytes to write */
1772 char buf
[16384]; /* Buffer for formatted string */
1773 va_list ap
; /* Variable argument pointer */
1776 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1778 va_start(ap
, format
);
1779 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1782 DEBUG_printf(("3httpPrintf: %s", buf
));
1784 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1785 return (httpWrite2(http
, buf
, bytes
));
1790 DEBUG_puts("4httpPrintf: flushing existing data...");
1792 if (httpFlushWrite(http
) < 0)
1796 return (http_write(http
, buf
, bytes
));
1802 * 'httpPut()' - Send a PUT request to the server.
1805 int /* O - Status of call (0 = success) */
1806 httpPut(http_t
*http
, /* I - Connection to server */
1807 const char *uri
) /* I - URI to put */
1809 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1810 return (http_send(http
, HTTP_PUT
, uri
));
1815 * 'httpRead()' - Read data from a HTTP connection.
1817 * This function is deprecated. Use the httpRead2() function which can
1818 * read more than 2GB of data.
1823 int /* O - Number of bytes read */
1824 httpRead(http_t
*http
, /* I - Connection to server */
1825 char *buffer
, /* I - Buffer for data */
1826 int length
) /* I - Maximum number of bytes */
1828 return ((int)httpRead2(http
, buffer
, length
));
1833 * 'httpRead2()' - Read data from a HTTP connection.
1835 * @since CUPS 1.2/Mac OS X 10.5@
1838 ssize_t
/* O - Number of bytes read */
1839 httpRead2(http_t
*http
, /* I - Connection to server */
1840 char *buffer
, /* I - Buffer for data */
1841 size_t length
) /* I - Maximum number of bytes */
1843 ssize_t bytes
; /* Bytes read */
1844 char len
[32]; /* Length string */
1847 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1848 http
, buffer
, CUPS_LLCAST length
));
1850 if (http
== NULL
|| buffer
== NULL
)
1853 http
->activity
= time(NULL
);
1859 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1860 http
->data_remaining
<= 0)
1862 DEBUG_puts("2httpRead2: Getting chunk length...");
1864 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1866 DEBUG_puts("1httpRead2: Could not get length!");
1870 http
->data_remaining
= strtoll(len
, NULL
, 16);
1871 if (http
->data_remaining
< 0)
1873 DEBUG_puts("1httpRead2: Negative chunk length!");
1878 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1879 CUPS_LLCAST http
->data_remaining
));
1881 if (http
->data_remaining
<= 0)
1884 * A zero-length chunk ends a transfer; unless we are reading POST
1888 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1889 httpGets(len
, sizeof(len
), http
);
1891 if (http
->state
== HTTP_POST_RECV
)
1894 http
->state
= HTTP_WAITING
;
1897 * Prevent future reads for this request...
1900 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1904 else if (length
> (size_t)http
->data_remaining
)
1905 length
= (size_t)http
->data_remaining
;
1907 if (http
->used
== 0 && length
<= 256)
1910 * Buffer small reads for better performance...
1913 if (!http
->blocking
)
1915 while (!httpWait(http
, http
->wait_value
))
1917 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1924 if (http
->data_remaining
> sizeof(http
->buffer
))
1925 bytes
= sizeof(http
->buffer
);
1927 bytes
= http
->data_remaining
;
1931 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1933 #endif /* HAVE_SSL */
1935 DEBUG_printf(("2httpRead2: reading %d bytes from socket into buffer...",
1938 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1940 DEBUG_printf(("2httpRead2: read %d bytes from socket into buffer...",
1949 if (WSAGetLastError() != WSAEINTR
)
1951 http
->error
= WSAGetLastError();
1954 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1956 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1958 http
->error
= WSAEWOULDBLOCK
;
1963 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1965 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1967 http
->error
= errno
;
1970 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1972 http
->error
= errno
;
1976 else if (errno
!= EINTR
)
1978 http
->error
= errno
;
1985 http
->error
= EPIPE
;
1992 if (length
> (size_t)http
->used
)
1993 length
= (size_t)http
->used
;
1995 bytes
= (ssize_t
)length
;
1997 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2000 memcpy(buffer
, http
->buffer
, length
);
2001 http
->used
-= (int)length
;
2004 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2009 if (!http
->blocking
)
2011 while (!httpWait(http
, http
->wait_value
))
2013 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2020 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
2022 #endif /* HAVE_SSL */
2025 if (!http
->blocking
)
2027 while (!httpWait(http
, http
->wait_value
))
2029 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2036 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2037 CUPS_LLCAST length
));
2040 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2042 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2044 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2047 else if (WSAGetLastError() != WSAEINTR
)
2051 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2053 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2055 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2057 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2060 else if (errno
!= EINTR
)
2065 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2066 CUPS_LLCAST bytes
));
2071 http
->data_remaining
-= bytes
;
2073 if (http
->data_remaining
<= INT_MAX
)
2074 http
->_data_remaining
= (int)http
->data_remaining
;
2076 http
->_data_remaining
= INT_MAX
;
2081 if (WSAGetLastError() == WSAEINTR
)
2084 http
->error
= WSAGetLastError();
2086 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2089 http
->error
= errno
;
2094 http
->error
= EPIPE
;
2098 if (http
->data_remaining
== 0)
2100 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2101 httpGets(len
, sizeof(len
), http
);
2103 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2105 if (http
->state
== HTTP_POST_RECV
)
2108 http
->state
= HTTP_WAITING
;
2113 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2120 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2122 * '_httpReadCDSA()' - Read function for the CDSA library.
2125 OSStatus
/* O - -1 on error, 0 on success */
2127 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2128 void *data
, /* I - Data buffer */
2129 size_t *dataLength
) /* IO - Number of bytes */
2131 OSStatus result
; /* Return value */
2132 ssize_t bytes
; /* Number of bytes read */
2133 http_t
*http
; /* HTTP connection */
2136 http
= (http_t
*)connection
;
2138 if (!http
->blocking
)
2141 * Make sure we have data before we read...
2144 while (!_httpWait(http
, http
->wait_value
, 0))
2146 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2149 http
->error
= ETIMEDOUT
;
2156 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2158 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2160 if (bytes
== *dataLength
)
2166 *dataLength
= bytes
;
2167 result
= errSSLWouldBlock
;
2174 result
= errSSLClosedGraceful
;
2175 else if (errno
== EAGAIN
)
2176 result
= errSSLWouldBlock
;
2178 result
= errSSLClosedAbort
;
2183 #endif /* HAVE_SSL && HAVE_CDSASSL */
2186 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2188 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2191 ssize_t
/* O - Number of bytes read or -1 on error */
2193 gnutls_transport_ptr ptr
, /* I - Connection to server */
2194 void *data
, /* I - Buffer */
2195 size_t length
) /* I - Number of bytes to read */
2197 http_t
*http
; /* HTTP connection */
2198 ssize_t bytes
; /* Bytes read */
2201 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2203 http
= (http_t
*)ptr
;
2205 if (!http
->blocking
)
2208 * Make sure we have data before we read...
2211 while (!_httpWait(http
, http
->wait_value
, 0))
2213 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2216 http
->error
= ETIMEDOUT
;
2221 bytes
= recv(http
->fd
, data
, length
, 0);
2222 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2225 #endif /* HAVE_SSL && HAVE_GNUTLS */
2229 * 'httpReconnect()' - Reconnect to a HTTP server.
2232 int /* O - 0 on success, non-zero on failure */
2233 httpReconnect(http_t
*http
) /* I - Connection to server */
2235 http_addrlist_t
*addr
; /* Connected address */
2237 http_addrlist_t
*current
; /* Current address */
2238 char temp
[256]; /* Temporary address string */
2242 DEBUG_printf(("httpReconnect(http=%p)", http
));
2250 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2251 http_shutdown_ssl(http
);
2253 #endif /* HAVE_SSL */
2256 * Close any previously open socket...
2261 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2264 closesocket(http
->fd
);
2273 * Connect to the server...
2277 for (current
= http
->addrlist
; current
; current
= current
->next
)
2278 DEBUG_printf(("2httpReconnect: Address %s:%d",
2279 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2280 _httpAddrPort(&(current
->addr
))));
2283 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
2286 * Unable to connect...
2290 http
->error
= WSAGetLastError();
2292 http
->error
= errno
;
2294 http
->status
= HTTP_ERROR
;
2296 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2297 strerror(http
->error
)));
2302 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2304 if (http
->timeout_value
> 0)
2305 http_set_timeout(http
->fd
, http
->timeout_value
);
2307 http
->hostaddr
= &(addr
->addr
);
2309 http
->status
= HTTP_CONTINUE
;
2312 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2315 * Always do encryption via SSL.
2318 if (http_setup_ssl(http
) != 0)
2321 closesocket(http
->fd
);
2329 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2330 return (http_upgrade(http
));
2331 #endif /* HAVE_SSL */
2333 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2334 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2335 _httpAddrPort(http
->hostaddr
)));
2342 * 'httpSetAuthString()' - Set the current authorization string.
2344 * This function just stores a copy of the current authorization string in
2345 * the HTTP connection object. You must still call httpSetField() to set
2346 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2347 * httpHead(), httpOptions(), httpPost, or httpPut().
2349 * @since CUPS 1.3/Mac OS X 10.5@
2353 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2354 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2355 const char *data
) /* I - Auth data (NULL for none) */
2358 * Range check input...
2364 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2365 free(http
->authstring
);
2367 http
->authstring
= http
->_authstring
;
2372 * Set the current authorization string...
2375 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2378 if (len
> (int)sizeof(http
->_authstring
))
2380 if ((temp
= malloc(len
)) == NULL
)
2381 len
= sizeof(http
->_authstring
);
2383 http
->authstring
= temp
;
2387 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2389 strlcpy(http
->authstring
, scheme
, len
);
2394 * Clear the current authorization string...
2397 http
->_authstring
[0] = '\0';
2403 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2406 * @since CUPS 1.5/Mac OS X 10.7@
2409 int /* O - Status of call (0 = success) */
2410 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2411 cups_array_t
*credentials
) /* I - Array of credentials */
2413 if (!http
|| cupsArrayCount(credentials
) < 1)
2416 _httpFreeCredentials(http
->tls_credentials
);
2418 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2420 return (http
->tls_credentials
? 0 : -1);
2425 * 'httpSetCookie()' - Set the cookie value(s).
2427 * @since CUPS 1.1.19/Mac OS X 10.3@
2431 httpSetCookie(http_t
*http
, /* I - Connection */
2432 const char *cookie
) /* I - Cookie string */
2441 http
->cookie
= strdup(cookie
);
2443 http
->cookie
= NULL
;
2448 * 'httpSetExpect()' - Set the Expect: header in a request.
2450 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2452 * @since CUPS 1.2/Mac OS X 10.5@
2456 httpSetExpect(http_t
*http
, /* I - Connection to server */
2457 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2460 http
->expect
= expect
;
2465 * 'httpSetField()' - Set the value of an HTTP header.
2469 httpSetField(http_t
*http
, /* I - Connection to server */
2470 http_field_t field
, /* I - Field index */
2471 const char *value
) /* I - Value */
2474 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2475 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2479 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2481 if (field
== HTTP_FIELD_AUTHORIZATION
)
2484 * Special case for Authorization: as its contents can be
2485 * longer than HTTP_MAX_VALUE
2488 if (http
->field_authorization
)
2489 free(http
->field_authorization
);
2491 http
->field_authorization
= strdup(value
);
2493 else if (field
== HTTP_FIELD_HOST
)
2496 * Special-case for Host: as we don't want a trailing "." on the hostname and
2497 * need to bracket IPv6 numeric addresses.
2500 char *ptr
= strchr(value
, ':');
2502 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2505 * Bracket IPv6 numeric addresses...
2507 * This is slightly inefficient (basically copying twice), but is an edge
2508 * case and not worth optimizing...
2511 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2512 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2517 * Check for a trailing dot on the hostname...
2520 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2524 ptr
+= strlen(ptr
) - 1;
2535 * 'httpSetLength()' - Set the content-length and content-encoding.
2537 * @since CUPS 1.2/Mac OS X 10.5@
2541 httpSetLength(http_t
*http
, /* I - Connection to server */
2542 size_t length
) /* I - Length (0 for chunked) */
2549 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2550 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2554 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2555 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2556 CUPS_LLFMT
, CUPS_LLCAST length
);
2562 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2564 * The optional timeout callback receives both the HTTP connection and a user
2565 * data pointer and must return 1 to continue or 0 to error (time) out.
2567 * @since CUPS 1.5/Mac OS X 10.7@
2572 http_t
*http
, /* I - Connection to server */
2573 double timeout
, /* I - Number of seconds for timeout,
2574 must be greater than 0 */
2575 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2576 void *user_data
) /* I - User data pointer */
2578 if (!http
|| timeout
<= 0.0)
2581 http
->timeout_cb
= cb
;
2582 http
->timeout_data
= user_data
;
2583 http
->timeout_value
= timeout
;
2586 http_set_timeout(http
->fd
, timeout
);
2588 http_set_wait(http
);
2593 * 'httpTrace()' - Send an TRACE request to the server.
2596 int /* O - Status of call (0 = success) */
2597 httpTrace(http_t
*http
, /* I - Connection to server */
2598 const char *uri
) /* I - URI for trace */
2600 return (http_send(http
, HTTP_TRACE
, uri
));
2605 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2607 * Note: Unlike httpUpdate(), this function does not flush pending write data
2608 * and only retrieves a single status line from the HTTP connection.
2611 int /* O - 1 to continue, 0 to stop */
2612 _httpUpdate(http_t
*http
, /* I - Connection to server */
2613 http_status_t
*status
) /* O - Current HTTP status */
2615 char line
[32768], /* Line from connection... */
2616 *value
; /* Pointer to value on line */
2617 http_field_t field
; /* Field index */
2618 int major
, minor
; /* HTTP version numbers */
2621 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2622 http_states
[http
->state
]));
2625 * Grab a single line from the connection...
2628 if (!httpGets(line
, sizeof(line
), http
))
2630 *status
= HTTP_ERROR
;
2634 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2636 if (line
[0] == '\0')
2639 * Blank line means the start of the data section (if any). Return
2640 * the result code, too...
2642 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2643 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2647 if (http
->status
== HTTP_CONTINUE
)
2649 *status
= http
->status
;
2653 if (http
->status
< HTTP_BAD_REQUEST
)
2654 http
->digest_tries
= 0;
2657 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2659 if (http_setup_ssl(http
) != 0)
2662 closesocket(http
->fd
);
2667 *status
= http
->status
= HTTP_ERROR
;
2671 *status
= HTTP_CONTINUE
;
2674 #endif /* HAVE_SSL */
2676 httpGetLength2(http
);
2678 switch (http
->state
)
2682 case HTTP_POST_RECV
:
2685 case HTTP_POST_SEND
:
2690 http
->state
= HTTP_WAITING
;
2694 *status
= http
->status
;
2697 else if (!strncmp(line
, "HTTP/", 5))
2700 * Got the beginning of a response...
2703 int intstatus
; /* Status value as an integer */
2705 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2707 *status
= http
->status
= HTTP_ERROR
;
2711 http
->version
= (http_version_t
)(major
* 100 + minor
);
2712 *status
= http
->status
= (http_status_t
)intstatus
;
2714 else if ((value
= strchr(line
, ':')) != NULL
)
2721 while (_cups_isspace(*value
))
2725 * Be tolerants of servers that send unknown attribute fields...
2728 if (!_cups_strcasecmp(line
, "expect"))
2731 * "Expect: 100-continue" or similar...
2734 http
->expect
= (http_status_t
)atoi(value
);
2736 else if (!_cups_strcasecmp(line
, "cookie"))
2739 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2742 httpSetCookie(http
, value
);
2744 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
2745 httpSetField(http
, field
, value
);
2748 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
2753 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
2754 *status
= http
->status
= HTTP_ERROR
;
2763 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2766 http_status_t
/* O - HTTP status */
2767 httpUpdate(http_t
*http
) /* I - Connection to server */
2769 http_status_t status
; /* Request status */
2772 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2773 http_states
[http
->state
]));
2776 * Flush pending data, if any...
2781 DEBUG_puts("2httpUpdate: flushing buffer...");
2783 if (httpFlushWrite(http
) < 0)
2784 return (HTTP_ERROR
);
2788 * If we haven't issued any commands, then there is nothing to "update"...
2791 if (http
->state
== HTTP_WAITING
)
2792 return (HTTP_CONTINUE
);
2795 * Grab all of the lines we can from the connection...
2798 while (_httpUpdate(http
, &status
));
2801 * See if there was an error...
2804 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2806 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2807 return (http
->status
);
2812 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2813 strerror(http
->error
)));
2814 http
->status
= HTTP_ERROR
;
2815 return (HTTP_ERROR
);
2819 * Return the current status...
2827 * '_httpWait()' - Wait for data available on a connection (no flush).
2830 int /* O - 1 if data is available, 0 otherwise */
2831 _httpWait(http_t
*http
, /* I - Connection to server */
2832 int msec
, /* I - Milliseconds to wait */
2833 int usessl
) /* I - Use SSL context? */
2836 struct pollfd pfd
; /* Polled file descriptor */
2838 fd_set input_set
; /* select() input set */
2839 struct timeval timeout
; /* Timeout */
2840 #endif /* HAVE_POLL */
2841 int nfds
; /* Result from select()/poll() */
2844 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2848 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2853 * Check the SSL/TLS buffers for data first...
2857 if (http
->tls
&& usessl
)
2860 if (SSL_pending(http
->tls
))
2862 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2866 # elif defined(HAVE_GNUTLS)
2867 if (gnutls_record_check_pending(http
->tls
))
2869 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2873 # elif defined(HAVE_CDSASSL)
2874 size_t bytes
; /* Bytes that are available */
2876 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2879 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2882 # endif /* HAVE_LIBSSL */
2884 #endif /* HAVE_SSL */
2887 * Then try doing a select() or poll() to poll the socket...
2892 pfd
.events
= POLLIN
;
2894 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2895 (errno
== EINTR
|| errno
== EAGAIN
));
2900 FD_ZERO(&input_set
);
2901 FD_SET(http
->fd
, &input_set
);
2903 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2907 timeout
.tv_sec
= msec
/ 1000;
2908 timeout
.tv_usec
= (msec
% 1000) * 1000;
2910 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2913 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2915 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2918 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2919 WSAGetLastError() == WSAEWOULDBLOCK
));
2921 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2923 #endif /* HAVE_POLL */
2925 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2933 * 'httpWait()' - Wait for data available on a connection.
2935 * @since CUPS 1.1.19/Mac OS X 10.3@
2938 int /* O - 1 if data is available, 0 otherwise */
2939 httpWait(http_t
*http
, /* I - Connection to server */
2940 int msec
) /* I - Milliseconds to wait */
2943 * First see if there is data in the buffer...
2946 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
2953 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
2958 * Flush pending data, if any...
2963 DEBUG_puts("3httpWait: Flushing write buffer.");
2965 if (httpFlushWrite(http
) < 0)
2970 * If not, check the SSL/TLS buffers and do a select() on the connection...
2973 return (_httpWait(http
, msec
, 1));
2978 * 'httpWrite()' - Write data to a HTTP connection.
2980 * This function is deprecated. Use the httpWrite2() function which can
2981 * write more than 2GB of data.
2986 int /* O - Number of bytes written */
2987 httpWrite(http_t
*http
, /* I - Connection to server */
2988 const char *buffer
, /* I - Buffer for data */
2989 int length
) /* I - Number of bytes to write */
2991 return ((int)httpWrite2(http
, buffer
, length
));
2996 * 'httpWrite2()' - Write data to a HTTP connection.
2998 * @since CUPS 1.2/Mac OS X 10.5@
3001 ssize_t
/* O - Number of bytes written */
3002 httpWrite2(http_t
*http
, /* I - Connection to server */
3003 const char *buffer
, /* I - Buffer for data */
3004 size_t length
) /* I - Number of bytes to write */
3006 ssize_t bytes
; /* Bytes written */
3009 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3010 buffer
, CUPS_LLCAST length
));
3013 * Range check input...
3016 if (http
== NULL
|| buffer
== NULL
)
3020 * Mark activity on the connection...
3023 http
->activity
= time(NULL
);
3026 * Buffer small writes for better performance...
3031 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3033 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3034 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3036 httpFlushWrite(http
);
3039 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3040 length
< sizeof(http
->wbuffer
))
3043 * Write to buffer...
3046 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3047 CUPS_LLCAST length
));
3049 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3050 http
->wused
+= (int)length
;
3051 bytes
= (ssize_t
)length
;
3056 * Otherwise write the data directly...
3059 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3060 CUPS_LLCAST length
));
3062 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3063 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3065 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3067 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3068 CUPS_LLCAST bytes
));
3071 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3072 http
->data_remaining
-= bytes
;
3078 * Handle end-of-request processing...
3081 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3082 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3085 * Finished with the transfer; unless we are sending POST or PUT
3089 DEBUG_puts("2httpWrite: changing states...");
3092 httpFlushWrite(http
);
3094 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3097 * Send a 0-length chunk at the end of the request...
3100 http_write(http
, "0\r\n\r\n", 5);
3103 * Reset the data state...
3106 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3107 http
->data_remaining
= 0;
3115 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3117 * '_httpWriteCDSA()' - Write function for the CDSA library.
3120 OSStatus
/* O - -1 on error, 0 on success */
3122 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3123 const void *data
, /* I - Data buffer */
3124 size_t *dataLength
) /* IO - Number of bytes */
3126 OSStatus result
; /* Return value */
3127 ssize_t bytes
; /* Number of bytes read */
3128 http_t
*http
; /* HTTP connection */
3131 http
= (http_t
*)connection
;
3135 bytes
= write(http
->fd
, data
, *dataLength
);
3137 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3139 if (bytes
== *dataLength
)
3143 else if (bytes
>= 0)
3145 *dataLength
= bytes
;
3146 result
= errSSLWouldBlock
;
3152 if (errno
== EAGAIN
)
3153 result
= errSSLWouldBlock
;
3155 result
= errSSLClosedAbort
;
3160 #endif /* HAVE_SSL && HAVE_CDSASSL */
3163 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3165 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3168 ssize_t
/* O - Number of bytes written or -1 on error */
3170 gnutls_transport_ptr ptr
, /* I - Connection to server */
3171 const void *data
, /* I - Data buffer */
3172 size_t length
) /* I - Number of bytes to write */
3174 ssize_t bytes
; /* Bytes written */
3177 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3179 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3181 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3182 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3185 #endif /* HAVE_SSL && HAVE_GNUTLS */
3188 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3190 * 'http_bio_ctrl()' - Control the HTTP connection.
3193 static long /* O - Result/data */
3194 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3195 int cmd
, /* I - Control command */
3196 long arg1
, /* I - First argument */
3197 void *arg2
) /* I - Second argument */
3204 case BIO_CTRL_RESET
:
3208 case BIO_C_SET_FILE_PTR
:
3213 case BIO_C_GET_FILE_PTR
:
3216 *((void **)arg2
) = h
->ptr
;
3223 case BIO_CTRL_FLUSH
:
3230 * 'http_bio_free()' - Free OpenSSL data.
3233 static int /* O - 1 on success, 0 on failure */
3234 http_bio_free(BIO
*h
) /* I - BIO data */
3250 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3253 static int /* O - 1 on success, 0 on failure */
3254 http_bio_new(BIO
*h
) /* I - BIO data */
3269 * 'http_bio_puts()' - Send a string for OpenSSL.
3272 static int /* O - Bytes written */
3273 http_bio_puts(BIO
*h
, /* I - BIO data */
3274 const char *str
) /* I - String to write */
3277 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3279 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3285 * 'http_bio_read()' - Read data for OpenSSL.
3288 static int /* O - Bytes read */
3289 http_bio_read(BIO
*h
, /* I - BIO data */
3290 char *buf
, /* I - Buffer */
3291 int size
) /* I - Number of bytes to read */
3293 http_t
*http
; /* HTTP connection */
3296 http
= (http_t
*)h
->ptr
;
3298 if (!http
->blocking
)
3301 * Make sure we have data before we read...
3304 while (!_httpWait(http
, http
->wait_value
, 0))
3306 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
3310 http
->error
= WSAETIMEDOUT
;
3312 http
->error
= ETIMEDOUT
;
3319 return (recv(http
->fd
, buf
, size
, 0));
3324 * 'http_bio_write()' - Write data for OpenSSL.
3327 static int /* O - Bytes written */
3328 http_bio_write(BIO
*h
, /* I - BIO data */
3329 const char *buf
, /* I - Buffer to write */
3330 int num
) /* I - Number of bytes to write */
3332 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3334 #endif /* HAVE_SSL && HAVE_LIBSSL */
3339 * 'http_debug_hex()' - Do a hex dump of a buffer.
3343 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3344 const char *buffer
, /* I - Buffer to dump */
3345 int bytes
) /* I - Bytes to dump */
3347 int i
, j
, /* Looping vars */
3348 ch
; /* Current character */
3349 char line
[255], /* Line buffer */
3350 *start
, /* Start of line after prefix */
3351 *ptr
; /* Pointer into line */
3354 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3357 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
3359 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3360 start
= line
+ strlen(line
);
3362 for (i
= 0; i
< bytes
; i
+= 16)
3364 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3365 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3377 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3379 ch
= buffer
[i
+ j
] & 255;
3381 if (ch
< ' ' || ch
>= 127)
3395 * 'http_field()' - Return the field index for a field name.
3398 static http_field_t
/* O - Field index */
3399 http_field(const char *name
) /* I - String name */
3401 int i
; /* Looping var */
3404 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3405 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
3406 return ((http_field_t
)i
);
3408 return (HTTP_FIELD_UNKNOWN
);
3414 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3417 static int /* O - Bytes read */
3418 http_read_ssl(http_t
*http
, /* I - Connection to server */
3419 char *buf
, /* I - Buffer to store data */
3420 int len
) /* I - Length of buffer */
3422 # if defined(HAVE_LIBSSL)
3423 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3425 # elif defined(HAVE_GNUTLS)
3426 ssize_t result
; /* Return value */
3429 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3431 if (result
< 0 && !errno
)
3434 * Convert GNU TLS error to errno value...
3439 case GNUTLS_E_INTERRUPTED
:
3443 case GNUTLS_E_AGAIN
:
3455 return ((int)result
);
3457 # elif defined(HAVE_CDSASSL)
3458 int result
; /* Return value */
3459 OSStatus error
; /* Error info */
3460 size_t processed
; /* Number of bytes processed */
3463 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3468 result
= (int)processed
;
3471 case errSSLWouldBlock
:
3473 result
= (int)processed
;
3481 case errSSLClosedGraceful
:
3484 result
= (int)processed
;
3494 # elif defined(HAVE_SSPISSL)
3495 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3496 # endif /* HAVE_LIBSSL */
3498 #endif /* HAVE_SSL */
3502 * 'http_send()' - Send a request with all fields and the trailing blank line.
3505 static int /* O - 0 on success, non-zero on error */
3506 http_send(http_t
*http
, /* I - Connection to server */
3507 http_state_t request
, /* I - Request code */
3508 const char *uri
) /* I - URI */
3510 int i
; /* Looping var */
3511 char buf
[1024]; /* Encoded URI buffer */
3512 static const char * const codes
[] =
3513 { /* Request code strings */
3530 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3531 http
, codes
[request
], uri
));
3533 if (http
== NULL
|| uri
== NULL
)
3537 * Set the User-Agent field if it isn't already...
3540 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3541 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3544 * Encode the URI as needed...
3547 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3550 * See if we had an error the last time around; if so, reconnect...
3553 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3554 if (httpReconnect(http
))
3558 * Flush any written data that is pending...
3563 if (httpFlushWrite(http
) < 0)
3564 if (httpReconnect(http
))
3569 * Send the request header...
3572 http
->state
= request
;
3573 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3575 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3578 http
->status
= HTTP_CONTINUE
;
3581 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3583 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3584 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3586 #endif /* HAVE_SSL */
3588 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3590 http
->status
= HTTP_ERROR
;
3594 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3595 if (http
->fields
[i
][0] != '\0')
3597 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3598 httpGetField(http
, i
)));
3600 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3601 httpGetField(http
, i
)) < 1)
3603 http
->status
= HTTP_ERROR
;
3609 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3611 http
->status
= HTTP_ERROR
;
3615 if (http
->expect
== HTTP_CONTINUE
&&
3616 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3617 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3619 http
->status
= HTTP_ERROR
;
3623 if (httpPrintf(http
, "\r\n") < 1)
3625 http
->status
= HTTP_ERROR
;
3629 if (httpFlushWrite(http
) < 0)
3632 httpGetLength2(http
);
3633 httpClearFields(http
);
3636 * The Kerberos and AuthRef authentication strings can only be used once...
3639 if (http
->field_authorization
&& http
->authstring
&&
3640 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3641 !strncmp(http
->authstring
, "AuthRef", 7)))
3643 http
->_authstring
[0] = '\0';
3645 if (http
->authstring
!= http
->_authstring
)
3646 free(http
->authstring
);
3648 http
->authstring
= http
->_authstring
;
3656 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
3658 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3661 static int /* O - Status of connection */
3662 http_set_credentials(http_t
*http
) /* I - Connection to server */
3664 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3665 OSStatus error
= 0; /* Error code */
3666 http_tls_credentials_t credentials
= NULL
;
3667 /* TLS credentials */
3670 DEBUG_printf(("7http_set_credentials(%p)", http
));
3673 * Prefer connection specific credentials...
3676 if ((credentials
= http
->tls_credentials
) == NULL
)
3677 credentials
= cg
->tls_credentials
;
3679 # if HAVE_SECPOLICYCREATESSL
3681 * Otherwise root around in the user's keychain to see if one can be found...
3686 CFDictionaryRef query
; /* Query dictionary */
3687 CFTypeRef matches
= NULL
; /* Matching credentials */
3688 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3689 CFTypeRef keys
[] = { kSecClass
,
3692 /* Keys for dictionary */
3693 CFTypeRef values
[] = { kSecClassCertificate
,
3696 /* Values for dictionary */
3699 * Get the names associated with the server.
3702 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3704 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3710 * Create a query which will return all identities that can sign and match
3711 * the passed in policy.
3714 query
= CFDictionaryCreate(NULL
,
3715 (const void**)(&keys
[0]),
3716 (const void**)(&values
[0]),
3717 sizeof(keys
) / sizeof(keys
[0]),
3718 &kCFTypeDictionaryKeyCallBacks
,
3719 &kCFTypeDictionaryValueCallBacks
);
3722 error
= SecItemCopyMatching(query
, &matches
);
3723 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3732 CFRelease(dn_array
);
3734 # endif /* HAVE_SECPOLICYCREATESSL */
3738 error
= SSLSetCertificate(http
->tls
, credentials
);
3739 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3743 DEBUG_puts("4http_set_credentials: No credentials to set.");
3747 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
3751 * 'http_set_timeout()' - Set the socket timeout values.
3755 http_set_timeout(int fd
, /* I - File descriptor */
3756 double timeout
) /* I - Timeout in seconds */
3759 DWORD tv
= (DWORD
)(timeout
* 1000);
3760 /* Timeout in milliseconds */
3762 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&tv
, sizeof(tv
));
3763 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&tv
, sizeof(tv
));
3766 struct timeval tv
; /* Timeout in secs and usecs */
3768 tv
.tv_sec
= (int)timeout
;
3769 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
3771 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, &tv
, sizeof(tv
));
3772 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
3778 * 'http_set_wait()' - Set the default wait value for reads.
3782 http_set_wait(http_t
*http
) /* I - Connection to server */
3786 http
->wait_value
= (int)(http
->timeout_value
* 1000);
3788 if (http
->wait_value
<= 0)
3789 http
->wait_value
= 60000;
3792 http
->wait_value
= 10000;
3797 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3800 static int /* O - 0 on success, -1 on failure */
3801 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3803 _cups_globals_t
*cg
= _cupsGlobals();
3804 /* Pointer to library globals */
3805 int any_root
; /* Allow any root */
3808 SSL_CTX
*context
; /* Context for encryption */
3809 BIO
*bio
; /* BIO data */
3810 const char *message
= NULL
;/* Error message */
3811 # elif defined(HAVE_GNUTLS)
3812 int status
; /* Status of handshake */
3813 gnutls_certificate_client_credentials
*credentials
;
3814 /* TLS credentials */
3815 # elif defined(HAVE_CDSASSL)
3816 OSStatus error
; /* Error code */
3817 char *hostname
; /* Hostname */
3818 const char *message
= NULL
;/* Error message */
3819 # ifdef HAVE_SECCERTIFICATECOPYDATA
3820 cups_array_t
*credentials
; /* Credentials array */
3821 cups_array_t
*names
; /* CUPS distinguished names */
3822 CFArrayRef dn_array
; /* CF distinguished names array */
3823 CFIndex count
; /* Number of credentials */
3824 CFDataRef data
; /* Certificate data */
3825 int i
; /* Looping var */
3826 http_credential_t
*credential
; /* Credential data */
3827 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3828 # elif defined(HAVE_SSPISSL)
3829 TCHAR username
[256]; /* Username returned from GetUserName() */
3830 TCHAR commonName
[256];/* Common name for certificate */
3831 DWORD dwSize
; /* 32 bit size */
3832 # endif /* HAVE_LIBSSL */
3835 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3838 * Always allow self-signed certificates for the local loopback address...
3841 if (httpAddrLocalhost(http
->hostaddr
))
3844 any_root
= cg
->any_root
;
3849 context
= SSL_CTX_new(SSLv23_client_method());
3851 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3853 bio
= BIO_new(_httpBIOMethods());
3854 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3856 http
->tls
= SSL_new(context
);
3857 SSL_set_bio(http
->tls
, bio
, bio
);
3859 if (SSL_connect(http
->tls
) != 1)
3861 unsigned long error
; /* Error code */
3863 while ((error
= ERR_get_error()) != 0)
3865 message
= ERR_error_string(error
, NULL
);
3866 DEBUG_printf(("8http_setup_ssl: %s", message
));
3869 SSL_CTX_free(context
);
3870 SSL_free(http
->tls
);
3874 http
->error
= WSAGetLastError();
3876 http
->error
= errno
;
3878 http
->status
= HTTP_ERROR
;
3881 message
= _("Unable to establish a secure connection to host.");
3883 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
3888 # elif defined(HAVE_GNUTLS)
3889 credentials
= (gnutls_certificate_client_credentials
*)
3890 malloc(sizeof(gnutls_certificate_client_credentials
));
3891 if (credentials
== NULL
)
3893 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
3895 http
->error
= errno
;
3896 http
->status
= HTTP_ERROR
;
3897 _cupsSetHTTPError(HTTP_ERROR
);
3902 gnutls_certificate_allocate_credentials(credentials
);
3904 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3905 gnutls_set_default_priority(http
->tls
);
3906 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, http
->hostname
, strlen(http
->hostname
));
3907 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3908 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3909 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3910 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3912 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3914 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
3915 status
, gnutls_strerror(status
)));
3917 if (gnutls_error_is_fatal(status
))
3920 http
->status
= HTTP_ERROR
;
3922 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
3924 gnutls_deinit(http
->tls
);
3925 gnutls_certificate_free_credentials(*credentials
);
3933 http
->tls_credentials
= credentials
;
3935 # elif defined(HAVE_CDSASSL)
3936 if ((error
= SSLNewContext(false, &http
->tls
)))
3938 http
->error
= errno
;
3939 http
->status
= HTTP_ERROR
;
3940 _cupsSetHTTPError(HTTP_ERROR
);
3945 error
= SSLSetConnection(http
->tls
, http
);
3946 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
3950 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
3951 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
3956 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
3957 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
3958 any_root
, (int)error
));
3963 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
3964 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
3965 cg
->expired_certs
, (int)error
));
3970 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
3971 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
3972 cg
->expired_root
, (int)error
));
3975 # ifdef HAVE_SSLSETPROTOCOLVERSIONMAX
3978 error
= SSLSetProtocolVersionMax(http
->tls
, kTLSProtocol1
);
3979 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionMax(kTLSProtocol1), "
3980 "error=%d", (int)error
));
3982 # endif /* HAVE_SSLSETPROTOCOLVERSIONMAX */
3984 # ifdef HAVE_SECCERTIFICATECOPYDATA
3987 if (cg
->client_cert_cb
)
3989 error
= SSLSetSessionOption(http
->tls
,
3990 kSSLSessionOptionBreakOnCertRequested
, true);
3991 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
3992 "error=%d", (int)error
));
3996 error
= http_set_credentials(http
);
3997 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
4003 * If there's a server certificate callback installed let it evaluate the
4004 * certificate(s) during the handshake...
4007 if (!error
&& cg
->server_cert_cb
!= NULL
)
4009 error
= SSLSetEnableCertVerify(http
->tls
, false);
4010 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
4015 error
= SSLSetSessionOption(http
->tls
,
4016 kSSLSessionOptionBreakOnServerAuth
, true);
4017 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
4018 "error=%d", (int)error
));
4021 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4025 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
4026 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
4028 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
4034 int done
= 0; /* Are we done yet? */
4036 while (!error
&& !done
)
4038 error
= SSLHandshake(http
->tls
);
4040 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
4048 case errSSLWouldBlock
:
4052 # ifdef HAVE_SECCERTIFICATECOPYDATA
4053 case errSSLServerAuthCompleted
:
4055 if (cg
->server_cert_cb
)
4057 error
= httpCopyCredentials(http
, &credentials
);
4060 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
4061 cg
->server_cert_data
);
4062 httpFreeCredentials(credentials
);
4065 DEBUG_printf(("4http_setup_ssl: Server certificate callback returned "
4066 "%d.", (int)error
));
4070 case errSSLClientCertRequested
:
4073 if (cg
->client_cert_cb
)
4076 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
4079 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
4081 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
4083 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
4085 if ((credential
= malloc(sizeof(*credential
))))
4087 credential
->datalen
= CFDataGetLength(data
);
4088 if ((credential
->data
= malloc(credential
->datalen
)))
4090 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
4091 credential
->datalen
);
4092 cupsArrayAdd(names
, credential
);
4098 CFRelease(dn_array
);
4103 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
4104 cg
->client_cert_data
);
4106 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
4107 "returned %d.", (int)error
));
4110 httpFreeCredentials(names
);
4113 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4115 case errSSLUnknownRootCert
:
4116 message
= _("Unable to establish a secure connection to host "
4117 "(untrusted certificate).");
4120 case errSSLNoRootCert
:
4121 message
= _("Unable to establish a secure connection to host "
4122 "(self-signed certificate).");
4125 case errSSLCertExpired
:
4126 message
= _("Unable to establish a secure connection to host "
4127 "(expired certificate).");
4130 case errSSLCertNotYetValid
:
4131 message
= _("Unable to establish a secure connection to host "
4132 "(certificate not yet valid).");
4135 case errSSLHostNameMismatch
:
4136 message
= _("Unable to establish a secure connection to host "
4137 "(host name mismatch).");
4140 case errSSLXCertChainInvalid
:
4141 message
= _("Unable to establish a secure connection to host "
4142 "(certificate chain invalid).");
4145 case errSSLConnectionRefused
:
4146 message
= _("Unable to establish a secure connection to host "
4147 "(peer dropped connection before responding).");
4158 http
->error
= error
;
4159 http
->status
= HTTP_ERROR
;
4160 errno
= ECONNREFUSED
;
4162 SSLDisposeContext(http
->tls
);
4166 * If an error string wasn't set by the callbacks use a generic one...
4170 #ifdef HAVE_CSSMERRORSTRING
4171 message
= cssmErrorString(error
);
4173 message
= _("Unable to establish a secure connection to host.");
4174 #endif /* HAVE_CSSMERRORSTRING */
4176 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4181 # elif defined(HAVE_SSPISSL)
4182 http
->tls
= _sspiAlloc();
4188 http
->tls
->sock
= http
->fd
;
4189 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4190 GetUserName(username
, &dwSize
);
4191 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4192 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4194 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4197 _sspiFree(http
->tls_credentials
);
4198 http
->tls_credentials
= NULL
;
4201 http
->status
= HTTP_ERROR
;
4203 _cupsSetError(IPP_PKI_ERROR
,
4204 _("Unable to establish a secure connection to host."), 1);
4209 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
4210 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4212 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
4214 _sspiFree(http
->tls_credentials
);
4215 http
->tls_credentials
= NULL
;
4218 http
->status
= HTTP_ERROR
;
4220 _cupsSetError(IPP_PKI_ERROR
,
4221 _("Unable to establish a secure connection to host."), 1);
4225 # endif /* HAVE_CDSASSL */
4229 #endif /* HAVE_SSL */
4234 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4238 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4241 SSL_CTX
*context
; /* Context for encryption */
4243 context
= SSL_get_SSL_CTX(http
->tls
);
4245 SSL_shutdown(http
->tls
);
4246 SSL_CTX_free(context
);
4247 SSL_free(http
->tls
);
4249 # elif defined(HAVE_GNUTLS)
4250 gnutls_certificate_client_credentials
*credentials
;
4251 /* TLS credentials */
4253 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4255 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4256 gnutls_deinit(http
->tls
);
4257 gnutls_certificate_free_credentials(*credentials
);
4260 # elif defined(HAVE_CDSASSL)
4261 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4264 SSLDisposeContext(http
->tls
);
4266 if (http
->tls_credentials
)
4267 CFRelease(http
->tls_credentials
);
4269 # elif defined(HAVE_SSPISSL)
4270 _sspiFree(http
->tls_credentials
);
4271 # endif /* HAVE_LIBSSL */
4274 http
->tls_credentials
= NULL
;
4276 #endif /* HAVE_SSL */
4281 * 'http_upgrade()' - Force upgrade to TLS encryption.
4284 static int /* O - Status of connection */
4285 http_upgrade(http_t
*http
) /* I - Connection to server */
4287 int ret
; /* Return value */
4288 http_t myhttp
; /* Local copy of HTTP data */
4291 DEBUG_printf(("7http_upgrade(%p)", http
));
4294 * Flush the connection to make sure any previous "Upgrade" message
4301 * Copy the HTTP data to a local variable so we can do the OPTIONS
4302 * request without interfering with the existing request data...
4305 memcpy(&myhttp
, http
, sizeof(myhttp
));
4308 * Send an OPTIONS request to the server, requiring SSL or TLS
4309 * encryption on the link...
4312 http
->field_authorization
= NULL
; /* Don't free the auth string */
4314 httpClearFields(http
);
4315 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4316 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4318 if ((ret
= httpOptions(http
, "*")) == 0)
4321 * Wait for the secure connection...
4324 while (httpUpdate(http
) == HTTP_CONTINUE
);
4328 * Restore the HTTP request data...
4331 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4332 http
->data_encoding
= myhttp
.data_encoding
;
4333 http
->data_remaining
= myhttp
.data_remaining
;
4334 http
->_data_remaining
= myhttp
._data_remaining
;
4335 http
->expect
= myhttp
.expect
;
4336 http
->field_authorization
= myhttp
.field_authorization
;
4337 http
->digest_tries
= myhttp
.digest_tries
;
4340 * See if we actually went secure...
4346 * Server does not support HTTP upgrade...
4349 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4352 closesocket(http
->fd
);
4364 #endif /* HAVE_SSL */
4368 * 'http_write()' - Write a buffer to a HTTP connection.
4371 static int /* O - Number of bytes written */
4372 http_write(http_t
*http
, /* I - Connection to server */
4373 const char *buffer
, /* I - Buffer for data */
4374 int length
) /* I - Number of bytes to write */
4376 int tbytes
, /* Total bytes sent */
4377 bytes
; /* Bytes sent */
4380 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4387 if (http
->timeout_cb
)
4390 struct pollfd pfd
; /* Polled file descriptor */
4392 fd_set output_set
; /* Output ready for write? */
4393 struct timeval timeout
; /* Timeout value */
4394 #endif /* HAVE_POLL */
4395 int nfds
; /* Result from select()/poll() */
4401 pfd
.events
= POLLOUT
;
4403 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
4404 (errno
== EINTR
|| errno
== EAGAIN
));
4409 FD_ZERO(&output_set
);
4410 FD_SET(http
->fd
, &output_set
);
4412 timeout
.tv_sec
= http
->wait_value
/ 1000;
4413 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
4415 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
4418 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
4419 WSAGetLastError() == WSAEWOULDBLOCK
));
4421 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
4423 #endif /* HAVE_POLL */
4427 http
->error
= errno
;
4430 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4433 http
->error
= ESAEWOULDBLOCK
;
4435 http
->error
= EWOULDBLOCK
;
4445 bytes
= http_write_ssl(http
, buffer
, length
);
4447 #endif /* HAVE_SSL */
4448 bytes
= send(http
->fd
, buffer
, length
, 0);
4453 if (WSAGetLastError() == WSAEINTR
)
4455 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4457 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4460 http
->error
= WSAGetLastError();
4462 else if (WSAGetLastError() != http
->error
&&
4463 WSAGetLastError() != WSAECONNRESET
)
4465 http
->error
= WSAGetLastError();
4472 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4474 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4476 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4479 http
->error
= errno
;
4481 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4483 http
->error
= errno
;
4488 DEBUG_printf(("3http_write: error writing data (%s).",
4489 strerror(http
->error
)));
4500 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4503 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4510 * 'http_write_chunk()' - Write a chunked buffer.
4513 static int /* O - Number bytes written */
4514 http_write_chunk(http_t
*http
, /* I - Connection to server */
4515 const char *buffer
, /* I - Buffer to write */
4516 int length
) /* I - Length of buffer */
4518 char header
[255]; /* Chunk header */
4519 int bytes
; /* Bytes written */
4522 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4523 http
, buffer
, length
));
4526 * Write the chunk header, data, and trailer.
4529 sprintf(header
, "%x\r\n", length
);
4530 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4532 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4536 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4538 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4542 if (http_write(http
, "\r\n", 2) < 0)
4544 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4554 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4557 static int /* O - Bytes written */
4558 http_write_ssl(http_t
*http
, /* I - Connection to server */
4559 const char *buf
, /* I - Buffer holding data */
4560 int len
) /* I - Length of buffer */
4562 ssize_t result
; /* Return value */
4565 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4567 # if defined(HAVE_LIBSSL)
4568 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4570 # elif defined(HAVE_GNUTLS)
4571 result
= gnutls_record_send(http
->tls
, buf
, len
);
4573 if (result
< 0 && !errno
)
4576 * Convert GNU TLS error to errno value...
4581 case GNUTLS_E_INTERRUPTED
:
4585 case GNUTLS_E_AGAIN
:
4597 # elif defined(HAVE_CDSASSL)
4598 OSStatus error
; /* Error info */
4599 size_t processed
; /* Number of bytes processed */
4602 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4607 result
= (int)processed
;
4610 case errSSLWouldBlock
:
4612 result
= (int)processed
;
4620 case errSSLClosedGraceful
:
4623 result
= (int)processed
;
4631 # elif defined(HAVE_SSPISSL)
4632 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
4633 # endif /* HAVE_LIBSSL */
4635 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4637 return ((int)result
);
4639 #endif /* HAVE_SSL */
4643 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".