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 * _httpConvertCredentials() - Convert credentials to the internal format.
38 * _httpCreate() - Create an unconnected HTTP connection.
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_setup_ssl() - Set up SSL/TLS support on a connection.
111 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
112 * http_threadid_cb() - Return the current thread ID.
113 * http_upgrade() - Force upgrade to TLS encryption.
114 * http_write() - Write a buffer to a HTTP connection.
115 * http_write_chunk() - Write a chunked buffer.
116 * http_write_ssl() - Write to a SSL/TLS connection.
120 * Include necessary headers...
123 #include "cups-private.h"
129 # include <sys/time.h>
130 # include <sys/resource.h>
133 # include <sys/poll.h>
134 #endif /* HAVE_POLL */
138 * Some operating systems have done away with the Fxxxx constants for
139 * the fcntl() call; this works around that "feature"...
143 # define FNONBLK O_NONBLOCK
144 #endif /* !FNONBLK */
152 static void http_debug_hex(const char *prefix
, const char *buffer
,
155 static http_field_t
http_field(const char *name
);
156 static int http_send(http_t
*http
, http_state_t request
,
158 static int http_write(http_t
*http
, const char *buffer
,
160 static int http_write_chunk(http_t
*http
, const char *buffer
,
163 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
164 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
165 static int http_set_credentials(http_t
*http
);
166 # endif /* HAVE_CDSASSL ** HAVE_SECCERTIFICATECOPYDATA */
167 static int http_setup_ssl(http_t
*http
);
168 static void http_shutdown_ssl(http_t
*http
);
169 static int http_upgrade(http_t
*http
);
170 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
173 # ifdef HAVE_PTHREAD_H
174 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
175 # endif /* HAVE_PTHREAD_H */
177 # elif defined(HAVE_LIBSSL)
178 static _cups_mutex_t
*http_locks
; /* OpenSSL lock mutexes */
180 static void http_locking_cb(int mode
, int type
, const char *file
,
182 static unsigned long http_threadid_cb(void);
183 # endif /* HAVE_GNUTLS */
184 #endif /* HAVE_SSL */
191 static const char * const http_fields
[] =
208 "If-Unmodified-since",
222 static const char * const http_states
[] =
242 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
244 * BIO methods for OpenSSL...
247 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
248 static int http_bio_read(BIO
*h
, char *buf
, int size
);
249 static int http_bio_puts(BIO
*h
, const char *str
);
250 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
251 static int http_bio_new(BIO
*h
);
252 static int http_bio_free(BIO
*data
);
254 static BIO_METHOD http_bio_methods
=
261 NULL
, /* http_bio_gets, */
267 #endif /* HAVE_SSL && HAVE_LIBSSL */
271 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
273 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
278 int /* O - 0 on success, -1 on error */
280 cups_array_t
*credentials
, /* I - Credentials array */
281 const void *data
, /* I - PEM-encoded X.509 data */
282 size_t datalen
) /* I - Length of data */
284 http_credential_t
*credential
; /* Credential data */
287 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
289 credential
->datalen
= datalen
;
291 if ((credential
->data
= malloc(datalen
)) != NULL
)
293 memcpy(credential
->data
, data
, datalen
);
294 cupsArrayAdd(credentials
, credential
);
305 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
307 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
310 BIO_METHOD
* /* O - BIO methods for OpenSSL */
311 _httpBIOMethods(void)
313 return (&http_bio_methods
);
315 #endif /* HAVE_SSL && HAVE_LIBSSL */
319 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
323 httpBlocking(http_t
*http
, /* I - Connection to server */
324 int b
) /* I - 1 = blocking, 0 = non-blocking */
332 * 'httpCheck()' - Check to see if there is a pending response from the server.
335 int /* O - 0 = no data, 1 = data available */
336 httpCheck(http_t
*http
) /* I - Connection to server */
338 return (httpWait(http
, 0));
343 * 'httpClearCookie()' - Clear the cookie value(s).
345 * @since CUPS 1.1.19/Mac OS X 10.3@
349 httpClearCookie(http_t
*http
) /* I - Connection to server */
363 * 'httpClearFields()' - Clear HTTP request fields.
367 httpClearFields(http_t
*http
) /* I - Connection to server */
371 memset(http
->fields
, 0, sizeof(http
->fields
));
372 if (http
->hostname
[0] == '/')
373 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
375 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
377 if (http
->field_authorization
)
379 free(http
->field_authorization
);
380 http
->field_authorization
= NULL
;
383 http
->expect
= (http_status_t
)0;
389 * 'httpClose()' - Close an HTTP connection.
393 httpClose(http_t
*http
) /* I - Connection to server */
396 OM_uint32 minor_status
; /* Minor status code */
397 #endif /* HAVE_GSSAPI */
400 DEBUG_printf(("httpClose(http=%p)", http
));
403 * Range check input...
410 * Close any open connection...
413 _httpDisconnect(http
);
416 * Free memory used...
419 httpAddrFreeList(http
->addrlist
);
425 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
426 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
428 if (http
->gssname
!= GSS_C_NO_NAME
)
429 gss_release_name(&minor_status
, &http
->gssname
);
430 #endif /* HAVE_GSSAPI */
432 #ifdef HAVE_AUTHORIZATION_H
434 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
435 #endif /* HAVE_AUTHORIZATION_H */
437 httpClearFields(http
);
439 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
440 free(http
->authstring
);
447 * 'httpConnect()' - Connect to a HTTP server.
449 * This function is deprecated - use @link httpConnectEncrypt@ instead.
454 http_t
* /* O - New HTTP connection */
455 httpConnect(const char *host
, /* I - Host to connect to */
456 int port
) /* I - Port number */
458 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
463 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
466 http_t
* /* O - New HTTP connection */
468 const char *host
, /* I - Host to connect to */
469 int port
, /* I - Port number */
470 http_encryption_t encryption
) /* I - Type of encryption to use */
472 http_t
*http
; /* New HTTP connection */
475 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
476 host
, port
, encryption
));
479 * Create the HTTP structure...
482 if ((http
= _httpCreate(host
, port
, NULL
, encryption
, AF_UNSPEC
)) == NULL
)
486 * Connect to the remote system...
489 if (!httpReconnect(http
))
493 * Could not connect to any known address - bail out!
496 httpAddrFreeList(http
->addrlist
);
505 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
511 int /* O - Status of call (0 = success) */
513 http_t
*http
, /* I - Connection to server */
514 cups_array_t
**credentials
) /* O - Array of credentials */
517 # elif defined(HAVE_GNUTLS)
518 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
519 OSStatus error
; /* Error code */
520 CFIndex count
; /* Number of credentials */
521 CFArrayRef peerCerts
; /* Peer certificates */
522 SecCertificateRef secCert
; /* Certificate reference */
523 CFDataRef data
; /* Certificate data */
524 int i
; /* Looping var */
525 # elif defined(HAVE_SSPISSL)
526 # endif /* HAVE_LIBSSL */
532 if (!http
|| !http
->tls
|| !credentials
)
538 # elif defined(HAVE_GNUTLS)
541 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
542 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
544 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
546 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
548 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
549 if ((data
= SecCertificateCopyData(secCert
)))
551 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
552 CFDataGetLength(data
));
558 CFRelease(peerCerts
);
563 # elif defined(HAVE_SSPISSL)
568 # endif /* HAVE_LIBSSL */
573 * '_httpConvertCredentials()' - Convert credentials to the internal format.
576 http_tls_credentials_t
/* O - Internal credentials */
577 _httpConvertCredentials(
578 cups_array_t
*credentials
) /* I - Array of credentials */
586 # elif defined(HAVE_GNUTLS)
589 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
590 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
591 SecCertificateRef secCert
; /* Certificate reference */
592 CFDataRef data
; /* Credential data reference */
593 http_credential_t
*credential
; /* Credential data */
596 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
597 cupsArrayCount(credentials
),
598 &kCFTypeArrayCallBacks
)) == NULL
)
601 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
603 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
605 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
606 credential
->datalen
)))
608 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
611 CFArrayAppendValue(peerCerts
, secCert
);
621 # elif defined(HAVE_SSPISSL)
626 # endif /* HAVE_LIBSSL */
631 * '_httpCreate()' - Create an unconnected HTTP connection.
634 http_t
* /* O - HTTP connection */
636 const char *host
, /* I - Hostname */
637 int port
, /* I - Port number */
638 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
639 http_encryption_t encryption
, /* I - Encryption to use */
640 int family
) /* I - Address family or AF_UNSPEC */
642 http_t
*http
; /* New HTTP connection */
643 char service
[255]; /* Service name */
646 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
647 host
, port
, encryption
));
658 sprintf(service
, "%d", port
);
661 if ((addrlist
= httpAddrGetList(host
, family
, service
)) == NULL
)
665 * Allocate memory for the structure...
668 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
670 httpAddrFreeList(addrlist
);
675 * Initialize the HTTP data...
678 http
->activity
= time(NULL
);
679 http
->addrlist
= addrlist
;
683 http
->gssctx
= GSS_C_NO_CONTEXT
;
684 http
->gssname
= GSS_C_NO_NAME
;
685 #endif /* HAVE_GSSAPI */
686 http
->version
= HTTP_1_1
;
688 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
690 if (port
== 443) /* Always use encryption for https */
691 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
693 http
->encryption
= encryption
;
696 * Return the new structure...
704 * 'httpDelete()' - Send a DELETE request to the server.
707 int /* O - Status of call (0 = success) */
708 httpDelete(http_t
*http
, /* I - Connection to server */
709 const char *uri
) /* I - URI to delete */
711 return (http_send(http
, HTTP_DELETE
, uri
));
716 * '_httpDisconnect()' - Disconnect a HTTP connection.
720 _httpDisconnect(http_t
*http
) /* I - Connection to server */
724 http_shutdown_ssl(http
);
725 #endif /* HAVE_SSL */
728 closesocket(http
->fd
);
738 * 'httpEncryption()' - Set the required encryption on the link.
741 int /* O - -1 on error, 0 on success */
742 httpEncryption(http_t
*http
, /* I - Connection to server */
743 http_encryption_t e
) /* I - New encryption preference */
745 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
751 http
->encryption
= e
;
753 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
754 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
755 return (httpReconnect(http
));
756 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
757 return (http_upgrade(http
));
761 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
765 #endif /* HAVE_SSL */
770 * 'httpError()' - Get the last error on a connection.
773 int /* O - Error code (errno) value */
774 httpError(http_t
*http
) /* I - Connection to server */
777 return (http
->error
);
784 * 'httpFlush()' - Flush data from a HTTP connection.
788 httpFlush(http_t
*http
) /* I - Connection to server */
790 char buffer
[8192]; /* Junk buffer */
791 int blocking
; /* To block or not to block */
792 http_state_t oldstate
; /* Old state */
795 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
796 http_states
[http
->state
]));
799 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
802 blocking
= http
->blocking
;
806 * Read any data we can...
809 oldstate
= http
->state
;
810 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
813 * Restore blocking and reset the connection if we didn't get all of
814 * the remaining data...
817 http
->blocking
= blocking
;
819 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
822 * Didn't get the data back, so close the current connection.
825 http
->state
= HTTP_WAITING
;
829 http_shutdown_ssl(http
);
830 #endif /* HAVE_SSL */
833 closesocket(http
->fd
);
844 * 'httpFlushWrite()' - Flush data in write buffer.
846 * @since CUPS 1.2/Mac OS X 10.5@
849 int /* O - Bytes written or -1 on error */
850 httpFlushWrite(http_t
*http
) /* I - Connection to server */
852 int bytes
; /* Bytes written */
855 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
857 if (!http
|| !http
->wused
)
859 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
860 "1httpFlushWrite: No connection.");
864 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
865 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
867 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
871 DEBUG_printf(("1httpFlushWrite: Returning %d.", bytes
));
878 * '_httpFreeCredentials()' - Free internal credentials.
882 _httpFreeCredentials(
883 http_tls_credentials_t credentials
) /* I - Internal credentials */
891 #elif defined(HAVE_GNUTLS)
894 #elif defined(HAVE_CDSASSL)
895 CFRelease(credentials
);
897 #elif defined(HAVE_SSPISSL)
900 #endif /* HAVE_LIBSSL */
905 * 'httpFreeCredentials()' - Free an array of credentials.
910 cups_array_t
*credentials
) /* I - Array of credentials */
912 http_credential_t
*credential
; /* Credential */
915 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
917 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
919 cupsArrayRemove(credentials
, credential
);
920 free((void *)credential
->data
);
924 cupsArrayDelete(credentials
);
929 * 'httpGet()' - Send a GET request to the server.
932 int /* O - Status of call (0 = success) */
933 httpGet(http_t
*http
, /* I - Connection to server */
934 const char *uri
) /* I - URI to get */
936 return (http_send(http
, HTTP_GET
, uri
));
941 * 'httpGetAuthString()' - Get the current authorization string.
943 * The authorization string is set by cupsDoAuthentication() and
944 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
945 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
948 * @since CUPS 1.3/Mac OS X 10.5@
951 char * /* O - Authorization string */
952 httpGetAuthString(http_t
*http
) /* I - Connection to server */
955 return (http
->authstring
);
962 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
964 * @since CUPS 1.2/Mac OS X 10.5@
967 int /* O - 1 if blocking, 0 if non-blocking */
968 httpGetBlocking(http_t
*http
) /* I - Connection to server */
970 return (http
? http
->blocking
: 0);
975 * 'httpGetCookie()' - Get any cookie data from the response.
977 * @since CUPS 1.1.19/Mac OS X 10.3@
980 const char * /* O - Cookie data or NULL */
981 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
983 return (http
? http
->cookie
: NULL
);
988 * 'httpGetFd()' - Get the file descriptor associated with a connection.
990 * @since CUPS 1.2/Mac OS X 10.5@
993 int /* O - File descriptor or -1 if none */
994 httpGetFd(http_t
*http
) /* I - Connection to server */
996 return (http
? http
->fd
: -1);
1001 * 'httpGetField()' - Get a field value from a request/response.
1004 const char * /* O - Field value */
1005 httpGetField(http_t
*http
, /* I - Connection to server */
1006 http_field_t field
) /* I - Field to get */
1008 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1010 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
1011 http
->field_authorization
)
1014 * Special case for WWW-Authenticate: as its contents can be
1015 * longer than HTTP_MAX_VALUE...
1018 return (http
->field_authorization
);
1021 return (http
->fields
[field
]);
1026 * 'httpGetLength()' - Get the amount of data remaining from the
1027 * content-length or transfer-encoding fields.
1029 * This function is deprecated and will not return lengths larger than
1030 * 2^31 - 1; use httpGetLength2() instead.
1035 int /* O - Content length */
1036 httpGetLength(http_t
*http
) /* I - Connection to server */
1039 * Get the read content length and return the 32-bit value.
1044 httpGetLength2(http
);
1046 return (http
->_data_remaining
);
1054 * 'httpGetLength2()' - Get the amount of data remaining from the
1055 * content-length or transfer-encoding fields.
1057 * This function returns the complete content length, even for
1058 * content larger than 2^31 - 1.
1060 * @since CUPS 1.2/Mac OS X 10.5@
1063 off_t
/* O - Content length */
1064 httpGetLength2(http_t
*http
) /* I - Connection to server */
1066 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1067 http_states
[http
->state
]));
1072 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1074 DEBUG_puts("4httpGetLength2: chunked request!");
1076 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1077 http
->data_remaining
= 0;
1081 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1084 * The following is a hack for HTTP servers that don't send a
1085 * content-length or transfer-encoding field...
1087 * If there is no content-length then the connection must close
1088 * after the transfer is complete...
1091 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1094 * Default content length is 0 for errors and 2^31-1 for other
1095 * successful requests...
1098 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
1099 http
->data_remaining
= 0;
1101 http
->data_remaining
= 2147483647;
1104 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1107 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1108 CUPS_LLCAST http
->data_remaining
));
1111 if (http
->data_remaining
<= INT_MAX
)
1112 http
->_data_remaining
= (int)http
->data_remaining
;
1114 http
->_data_remaining
= INT_MAX
;
1116 return (http
->data_remaining
);
1121 * 'httpGetStatus()' - Get the status of the last HTTP request.
1123 * @since CUPS 1.2/Mac OS X 10.5@
1126 http_status_t
/* O - HTTP status */
1127 httpGetStatus(http_t
*http
) /* I - Connection to server */
1129 return (http
? http
->status
: HTTP_ERROR
);
1134 * 'httpGetSubField()' - Get a sub-field value.
1139 char * /* O - Value or NULL */
1140 httpGetSubField(http_t
*http
, /* I - Connection to server */
1141 http_field_t field
, /* I - Field index */
1142 const char *name
, /* I - Name of sub-field */
1143 char *value
) /* O - Value string */
1145 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1150 * 'httpGetSubField2()' - Get a sub-field value.
1152 * @since CUPS 1.2/Mac OS X 10.5@
1155 char * /* O - Value or NULL */
1156 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1157 http_field_t field
, /* I - Field index */
1158 const char *name
, /* I - Name of sub-field */
1159 char *value
, /* O - Value string */
1160 int valuelen
) /* I - Size of value buffer */
1162 const char *fptr
; /* Pointer into field */
1163 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1164 *ptr
, /* Pointer into string buffer */
1165 *end
; /* End of value buffer */
1167 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1168 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1170 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1171 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1174 end
= value
+ valuelen
- 1;
1176 for (fptr
= http
->fields
[field
]; *fptr
;)
1179 * Skip leading whitespace...
1182 while (_cups_isspace(*fptr
))
1192 * Get the sub-field name...
1196 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1197 ptr
< (temp
+ sizeof(temp
) - 1);
1202 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1205 * Skip trailing chars up to the '='...
1208 while (_cups_isspace(*fptr
))
1218 * Skip = and leading whitespace...
1223 while (_cups_isspace(*fptr
))
1229 * Read quoted string...
1232 for (ptr
= value
, fptr
++;
1233 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1238 while (*fptr
&& *fptr
!= '\"')
1247 * Read unquoted string...
1251 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1256 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1260 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1263 * See if this is the one...
1266 if (!strcmp(name
, temp
))
1268 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1275 DEBUG_puts("3httpGetSubField2: Returning NULL");
1282 * 'httpGets()' - Get a line of text from a HTTP connection.
1285 char * /* O - Line or NULL */
1286 httpGets(char *line
, /* I - Line to read into */
1287 int length
, /* I - Max length of buffer */
1288 http_t
*http
) /* I - Connection to server */
1290 char *lineptr
, /* Pointer into line */
1291 *lineend
, /* End of line */
1292 *bufptr
, /* Pointer into input buffer */
1293 *bufend
; /* Pointer to end of buffer */
1294 int bytes
, /* Number of bytes read */
1295 eol
; /* End-of-line? */
1298 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1300 if (http
== NULL
|| line
== NULL
)
1304 * Read a line from the buffer...
1309 lineend
= line
+ length
- 1;
1312 while (lineptr
< lineend
)
1315 * Pre-load the buffer as needed...
1324 while (http
->used
== 0)
1327 * No newline; see if there is more data to be read...
1330 if (!http
->blocking
&& !_httpWait(http
, 10000, 1))
1332 DEBUG_puts("3httpGets: Timed out!");
1334 http
->error
= WSAETIMEDOUT
;
1336 http
->error
= ETIMEDOUT
;
1343 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1344 HTTP_MAX_BUFFER
- http
->used
);
1346 #endif /* HAVE_SSL */
1347 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1348 HTTP_MAX_BUFFER
- http
->used
, 0);
1350 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1355 * Nope, can't get a line this time...
1359 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1361 if (WSAGetLastError() == WSAEINTR
)
1363 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1365 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1368 http
->error
= WSAGetLastError();
1370 else if (WSAGetLastError() != http
->error
)
1372 http
->error
= WSAGetLastError();
1377 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1381 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1383 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1385 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1388 http
->error
= errno
;
1390 else if (errno
!= http
->error
)
1392 http
->error
= errno
;
1399 else if (bytes
== 0)
1401 http
->error
= EPIPE
;
1407 * Yup, update the amount used...
1410 http
->used
+= bytes
;
1414 * Now copy as much of the current line as possible...
1417 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1418 lineptr
< lineend
&& bufptr
< bufend
;)
1420 if (*bufptr
== 0x0a)
1426 else if (*bufptr
== 0x0d)
1429 *lineptr
++ = *bufptr
++;
1432 http
->used
-= (int)(bufptr
- http
->buffer
);
1434 memmove(http
->buffer
, bufptr
, http
->used
);
1442 http
->activity
= time(NULL
);
1446 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1452 DEBUG_puts("3httpGets: No new line available!");
1459 * 'httpHead()' - Send a HEAD request to the server.
1462 int /* O - Status of call (0 = success) */
1463 httpHead(http_t
*http
, /* I - Connection to server */
1464 const char *uri
) /* I - URI for head */
1466 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1467 return (http_send(http
, HTTP_HEAD
, uri
));
1472 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1473 * default HTTP proxy (if any).
1477 httpInitialize(void)
1479 static int initialized
= 0; /* Have we been called before? */
1481 WSADATA winsockdata
; /* WinSock data */
1484 int i
; /* Looping var */
1485 unsigned char data
[1024]; /* Seed data */
1486 #endif /* HAVE_LIBSSL */
1492 _cupsGlobalUnlock();
1497 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1499 #elif !defined(SO_NOSIGPIPE)
1501 * Ignore SIGPIPE signals...
1505 sigset(SIGPIPE
, SIG_IGN
);
1507 # elif defined(HAVE_SIGACTION)
1508 struct sigaction action
; /* POSIX sigaction data */
1511 memset(&action
, 0, sizeof(action
));
1512 action
.sa_handler
= SIG_IGN
;
1513 sigaction(SIGPIPE
, &action
, NULL
);
1516 signal(SIGPIPE
, SIG_IGN
);
1517 # endif /* !SO_NOSIGPIPE */
1522 * Make sure we handle threading properly...
1525 # ifdef HAVE_PTHREAD_H
1526 gcry_control(GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
1527 # endif /* HAVE_PTHREAD_H */
1530 * Initialize GNU TLS...
1533 gnutls_global_init();
1535 #elif defined(HAVE_LIBSSL)
1537 * Initialize OpenSSL...
1540 SSL_load_error_strings();
1544 * Set the threading callbacks...
1547 http_locks
= calloc(CRYPTO_num_locks(), sizeof(_cups_mutex_t
));
1548 # ifdef HAVE_PTHREAD_H
1549 for (i
= 0; i
< CRYPTO_num_locks(); i
++)
1550 pthread_mutex_init(http_locks
+ i
, NULL
);
1551 # endif /* HAVE_PTHREAD_H */
1553 CRYPTO_set_id_callback(http_threadid_cb
);
1554 CRYPTO_set_locking_callback(http_locking_cb
);
1557 * Using the current time is a dubious random seed, but on some systems
1558 * it is the best we can do (on others, this seed isn't even used...)
1561 CUPS_SRAND(time(NULL
));
1563 for (i
= 0; i
< sizeof(data
); i
++)
1564 data
[i
] = CUPS_RAND();
1566 RAND_seed(data
, sizeof(data
));
1567 #endif /* HAVE_GNUTLS */
1570 _cupsGlobalUnlock();
1575 * 'httpOptions()' - Send an OPTIONS request to the server.
1578 int /* O - Status of call (0 = success) */
1579 httpOptions(http_t
*http
, /* I - Connection to server */
1580 const char *uri
) /* I - URI for options */
1582 return (http_send(http
, HTTP_OPTIONS
, uri
));
1587 * '_httpPeek()' - Peek at data from a HTTP connection.
1589 * This function copies available data from the given HTTP connection, reading
1590 * a buffer as needed. The data is still available for reading using
1591 * @link httpRead@ or @link httpRead2@.
1593 * For non-blocking connections the usual timeouts apply.
1596 ssize_t
/* O - Number of bytes copied */
1597 _httpPeek(http_t
*http
, /* I - Connection to server */
1598 char *buffer
, /* I - Buffer for data */
1599 size_t length
) /* I - Maximum number of bytes */
1601 ssize_t bytes
; /* Bytes read */
1602 char len
[32]; /* Length string */
1605 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1606 http
, buffer
, CUPS_LLCAST length
));
1608 if (http
== NULL
|| buffer
== NULL
)
1611 http
->activity
= time(NULL
);
1617 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1618 http
->data_remaining
<= 0)
1620 DEBUG_puts("2_httpPeek: Getting chunk length...");
1622 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1624 DEBUG_puts("1_httpPeek: Could not get length!");
1628 http
->data_remaining
= strtoll(len
, NULL
, 16);
1629 if (http
->data_remaining
< 0)
1631 DEBUG_puts("1_httpPeek: Negative chunk length!");
1636 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1637 CUPS_LLCAST http
->data_remaining
));
1639 if (http
->data_remaining
<= 0)
1642 * A zero-length chunk ends a transfer; unless we are reading POST
1646 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1647 httpGets(len
, sizeof(len
), http
);
1649 if (http
->state
== HTTP_POST_RECV
)
1652 http
->state
= HTTP_WAITING
;
1655 * Prevent future reads for this request...
1658 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1662 else if (length
> (size_t)http
->data_remaining
)
1663 length
= (size_t)http
->data_remaining
;
1665 if (http
->used
== 0)
1668 * Buffer small reads for better performance...
1671 if (!http
->blocking
&& !httpWait(http
, 10000))
1674 if (http
->data_remaining
> sizeof(http
->buffer
))
1675 bytes
= sizeof(http
->buffer
);
1677 bytes
= http
->data_remaining
;
1681 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1683 #endif /* HAVE_SSL */
1685 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1688 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1690 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1699 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1701 http
->error
= WSAGetLastError();
1705 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1707 http
->error
= errno
;
1714 http
->error
= EPIPE
;
1721 if (length
> (size_t)http
->used
)
1722 length
= (size_t)http
->used
;
1724 bytes
= (ssize_t
)length
;
1726 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1729 memcpy(buffer
, http
->buffer
, length
);
1737 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1740 http
->error
= WSAGetLastError();
1742 if (errno
== EINTR
|| errno
== EAGAIN
)
1745 http
->error
= errno
;
1748 else if (bytes
== 0)
1750 http
->error
= EPIPE
;
1755 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1763 * 'httpPost()' - Send a POST request to the server.
1766 int /* O - Status of call (0 = success) */
1767 httpPost(http_t
*http
, /* I - Connection to server */
1768 const char *uri
) /* I - URI for post */
1770 return (http_send(http
, HTTP_POST
, uri
));
1775 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1780 int /* O - Number of bytes written */
1781 httpPrintf(http_t
*http
, /* I - Connection to server */
1782 const char *format
, /* I - printf-style format string */
1783 ...) /* I - Additional args as needed */
1785 int bytes
; /* Number of bytes to write */
1786 char buf
[16384]; /* Buffer for formatted string */
1787 va_list ap
; /* Variable argument pointer */
1790 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1792 va_start(ap
, format
);
1793 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1796 DEBUG_printf(("3httpPrintf: %s", buf
));
1798 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1799 return (httpWrite2(http
, buf
, bytes
));
1804 DEBUG_puts("4httpPrintf: flushing existing data...");
1806 if (httpFlushWrite(http
) < 0)
1810 return (http_write(http
, buf
, bytes
));
1816 * 'httpPut()' - Send a PUT request to the server.
1819 int /* O - Status of call (0 = success) */
1820 httpPut(http_t
*http
, /* I - Connection to server */
1821 const char *uri
) /* I - URI to put */
1823 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1824 return (http_send(http
, HTTP_PUT
, uri
));
1829 * 'httpRead()' - Read data from a HTTP connection.
1831 * This function is deprecated. Use the httpRead2() function which can
1832 * read more than 2GB of data.
1837 int /* O - Number of bytes read */
1838 httpRead(http_t
*http
, /* I - Connection to server */
1839 char *buffer
, /* I - Buffer for data */
1840 int length
) /* I - Maximum number of bytes */
1842 return ((int)httpRead2(http
, buffer
, length
));
1847 * 'httpRead2()' - Read data from a HTTP connection.
1849 * @since CUPS 1.2/Mac OS X 10.5@
1852 ssize_t
/* O - Number of bytes read */
1853 httpRead2(http_t
*http
, /* I - Connection to server */
1854 char *buffer
, /* I - Buffer for data */
1855 size_t length
) /* I - Maximum number of bytes */
1857 ssize_t bytes
; /* Bytes read */
1858 char len
[32]; /* Length string */
1861 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1862 http
, buffer
, CUPS_LLCAST length
));
1864 if (http
== NULL
|| buffer
== NULL
)
1867 http
->activity
= time(NULL
);
1873 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1874 http
->data_remaining
<= 0)
1876 DEBUG_puts("2httpRead2: Getting chunk length...");
1878 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1880 DEBUG_puts("1httpRead2: Could not get length!");
1884 http
->data_remaining
= strtoll(len
, NULL
, 16);
1885 if (http
->data_remaining
< 0)
1887 DEBUG_puts("1httpRead2: Negative chunk length!");
1892 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1893 CUPS_LLCAST http
->data_remaining
));
1895 if (http
->data_remaining
<= 0)
1898 * A zero-length chunk ends a transfer; unless we are reading POST
1902 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1903 httpGets(len
, sizeof(len
), http
);
1905 if (http
->state
== HTTP_POST_RECV
)
1908 http
->state
= HTTP_WAITING
;
1911 * Prevent future reads for this request...
1914 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1918 else if (length
> (size_t)http
->data_remaining
)
1919 length
= (size_t)http
->data_remaining
;
1921 if (http
->used
== 0 && length
<= 256)
1924 * Buffer small reads for better performance...
1927 if (!http
->blocking
&& !httpWait(http
, 10000))
1930 if (http
->data_remaining
> sizeof(http
->buffer
))
1931 bytes
= sizeof(http
->buffer
);
1933 bytes
= http
->data_remaining
;
1937 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1939 #endif /* HAVE_SSL */
1941 DEBUG_printf(("2httpRead2: reading %d bytes from socket into buffer...",
1944 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1946 DEBUG_printf(("2httpRead2: read %d bytes from socket into buffer...",
1955 if (WSAGetLastError() != WSAEINTR
)
1957 http
->error
= WSAGetLastError();
1960 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1962 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1964 http
->error
= WSAEWOULDBLOCK
;
1969 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1971 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1973 http
->error
= errno
;
1976 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1978 http
->error
= errno
;
1982 else if (errno
!= EINTR
)
1984 http
->error
= errno
;
1991 http
->error
= EPIPE
;
1998 if (length
> (size_t)http
->used
)
1999 length
= (size_t)http
->used
;
2001 bytes
= (ssize_t
)length
;
2003 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2006 memcpy(buffer
, http
->buffer
, length
);
2007 http
->used
-= (int)length
;
2010 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2015 if (!http
->blocking
&& !httpWait(http
, 10000))
2018 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
2020 #endif /* HAVE_SSL */
2023 if (!http
->blocking
&& !httpWait(http
, 10000))
2026 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2027 CUPS_LLCAST length
));
2030 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2032 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2034 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2037 else if (WSAGetLastError() != WSAEINTR
)
2041 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2043 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2045 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2047 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2050 else if (errno
!= EINTR
)
2055 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2056 CUPS_LLCAST bytes
));
2061 http
->data_remaining
-= bytes
;
2063 if (http
->data_remaining
<= INT_MAX
)
2064 http
->_data_remaining
= (int)http
->data_remaining
;
2066 http
->_data_remaining
= INT_MAX
;
2071 if (WSAGetLastError() == WSAEINTR
)
2074 http
->error
= WSAGetLastError();
2076 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2079 http
->error
= errno
;
2084 http
->error
= EPIPE
;
2088 if (http
->data_remaining
== 0)
2090 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2091 httpGets(len
, sizeof(len
), http
);
2093 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2095 if (http
->state
== HTTP_POST_RECV
)
2098 http
->state
= HTTP_WAITING
;
2103 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2110 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2112 * '_httpReadCDSA()' - Read function for the CDSA library.
2115 OSStatus
/* O - -1 on error, 0 on success */
2117 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2118 void *data
, /* I - Data buffer */
2119 size_t *dataLength
) /* IO - Number of bytes */
2121 OSStatus result
; /* Return value */
2122 ssize_t bytes
; /* Number of bytes read */
2123 http_t
*http
; /* HTTP connection */
2126 http
= (http_t
*)connection
;
2128 if (!http
->blocking
)
2131 * Make sure we have data before we read...
2134 if (!_httpWait(http
, 10000, 0))
2136 http
->error
= ETIMEDOUT
;
2143 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2145 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2147 if (bytes
== *dataLength
)
2153 *dataLength
= bytes
;
2154 result
= errSSLWouldBlock
;
2161 result
= errSSLClosedGraceful
;
2162 else if (errno
== EAGAIN
)
2163 result
= errSSLWouldBlock
;
2165 result
= errSSLClosedAbort
;
2170 #endif /* HAVE_SSL && HAVE_CDSASSL */
2173 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2175 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2178 ssize_t
/* O - Number of bytes read or -1 on error */
2180 gnutls_transport_ptr ptr
, /* I - Connection to server */
2181 void *data
, /* I - Buffer */
2182 size_t length
) /* I - Number of bytes to read */
2184 http_t
*http
; /* HTTP connection */
2187 http
= (http_t
*)ptr
;
2189 if (!http
->blocking
)
2192 * Make sure we have data before we read...
2195 if (!_httpWait(http
, 10000, 0))
2197 http
->error
= ETIMEDOUT
;
2202 return (recv(http
->fd
, data
, length
, 0));
2204 #endif /* HAVE_SSL && HAVE_GNUTLS */
2208 * 'httpReconnect()' - Reconnect to a HTTP server.
2211 int /* O - 0 on success, non-zero on failure */
2212 httpReconnect(http_t
*http
) /* I - Connection to server */
2214 http_addrlist_t
*addr
; /* Connected address */
2216 http_addrlist_t
*current
; /* Current address */
2217 char temp
[256]; /* Temporary address string */
2221 DEBUG_printf(("httpReconnect(http=%p)", http
));
2229 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2230 http_shutdown_ssl(http
);
2232 #endif /* HAVE_SSL */
2235 * Close any previously open socket...
2240 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2243 closesocket(http
->fd
);
2252 * Connect to the server...
2256 for (current
= http
->addrlist
; current
; current
= current
->next
)
2257 DEBUG_printf(("2httpReconnect: Address %s:%d",
2258 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2259 _httpAddrPort(&(current
->addr
))));
2262 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
2265 * Unable to connect...
2269 http
->error
= WSAGetLastError();
2271 http
->error
= errno
;
2273 http
->status
= HTTP_ERROR
;
2275 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2276 strerror(http
->error
)));
2281 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2283 if (http
->timeout_value
.tv_sec
> 0)
2286 DWORD timeout_value
= http
->timeout_value
.tv_sec
* 1000 +
2287 http
->timeout_value
.tv_usec
/ 1000;
2288 /* Timeout in milliseconds */
2290 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&timeout_value
,
2291 sizeof(timeout_value
));
2292 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&timeout_value
,
2293 sizeof(timeout_value
));
2295 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, &(http
->timeout_value
),
2296 sizeof(http
->timeout_value
));
2297 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, &(http
->timeout_value
),
2298 sizeof(http
->timeout_value
));
2302 http
->hostaddr
= &(addr
->addr
);
2304 http
->status
= HTTP_CONTINUE
;
2307 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2310 * Always do encryption via SSL.
2313 if (http_setup_ssl(http
) != 0)
2316 closesocket(http
->fd
);
2324 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2325 return (http_upgrade(http
));
2326 #endif /* HAVE_SSL */
2328 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2329 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2330 _httpAddrPort(http
->hostaddr
)));
2337 * 'httpSetAuthString()' - Set the current authorization string.
2339 * This function just stores a copy of the current authorization string in
2340 * the HTTP connection object. You must still call httpSetField() to set
2341 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2342 * httpHead(), httpOptions(), httpPost, or httpPut().
2344 * @since CUPS 1.3/Mac OS X 10.5@
2348 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2349 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2350 const char *data
) /* I - Auth data (NULL for none) */
2353 * Range check input...
2359 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2360 free(http
->authstring
);
2362 http
->authstring
= http
->_authstring
;
2367 * Set the current authorization string...
2370 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2373 if (len
> (int)sizeof(http
->_authstring
))
2375 if ((temp
= malloc(len
)) == NULL
)
2376 len
= sizeof(http
->_authstring
);
2378 http
->authstring
= temp
;
2382 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2384 strlcpy(http
->authstring
, scheme
, len
);
2389 * Clear the current authorization string...
2392 http
->_authstring
[0] = '\0';
2398 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2404 int /* O - Status of call (0 = success) */
2405 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2406 cups_array_t
*credentials
) /* I - Array of credentials */
2408 if (!http
|| cupsArrayCount(credentials
) < 1)
2411 _httpFreeCredentials(http
->tls_credentials
);
2413 http
->tls_credentials
= _httpConvertCredentials(credentials
);
2415 return (http
->tls_credentials
? 0 : -1);
2420 * 'httpSetCookie()' - Set the cookie value(s).
2422 * @since CUPS 1.1.19/Mac OS X 10.3@
2426 httpSetCookie(http_t
*http
, /* I - Connection */
2427 const char *cookie
) /* I - Cookie string */
2436 http
->cookie
= strdup(cookie
);
2438 http
->cookie
= NULL
;
2443 * 'httpSetExpect()' - Set the Expect: header in a request.
2445 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2447 * @since CUPS 1.2/Mac OS X 10.5@
2451 httpSetExpect(http_t
*http
, /* I - Connection to server */
2452 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2455 http
->expect
= expect
;
2460 * 'httpSetField()' - Set the value of an HTTP header.
2464 httpSetField(http_t
*http
, /* I - Connection to server */
2465 http_field_t field
, /* I - Field index */
2466 const char *value
) /* I - Value */
2469 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2470 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2474 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2476 if (field
== HTTP_FIELD_AUTHORIZATION
)
2479 * Special case for Authorization: as its contents can be
2480 * longer than HTTP_MAX_VALUE
2483 if (http
->field_authorization
)
2484 free(http
->field_authorization
);
2486 http
->field_authorization
= strdup(value
);
2488 else if (field
== HTTP_FIELD_HOST
)
2491 * Special-case for Host: as we don't want a trailing "." on the hostname and
2492 * need to bracket IPv6 numeric addresses.
2495 char *ptr
= strchr(value
, ':');
2497 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2500 * Bracket IPv6 numeric addresses...
2502 * This is slightly inefficient (basically copying twice), but is an edge
2503 * case and not worth optimizing...
2506 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2507 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2512 * Check for a trailing dot on the hostname...
2515 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2519 ptr
+= strlen(ptr
) - 1;
2530 * 'httpSetLength()' - Set the content-length and content-encoding.
2532 * @since CUPS 1.2/Mac OS X 10.5@
2536 httpSetLength(http_t
*http
, /* I - Connection to server */
2537 size_t length
) /* I - Length (0 for chunked) */
2544 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2545 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2549 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2550 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2551 CUPS_LLFMT
, CUPS_LLCAST length
);
2557 * '_httpSetTimeout()' - Set read/write timeouts and an optional callback.
2559 * The optional timeout callback receives both the HTTP connection and a user
2560 * data pointer and must return 1 to continue or 0 to error out.
2565 http_t
*http
, /* I - Connection to server */
2566 double timeout
, /* I - Number of seconds for timeout,
2567 must be greater than 0 */
2568 _http_timeout_cb_t cb
, /* I - Callback function or NULL */
2569 void *user_data
) /* I - User data pointer */
2571 if (!http
|| timeout
<= 0.0)
2574 http
->timeout_cb
= cb
;
2575 http
->timeout_data
= user_data
;
2576 http
->timeout_value
.tv_sec
= (int)timeout
;
2577 http
->timeout_value
.tv_usec
= (int)(timeout
* 1000000) % 1000000;
2582 DWORD timeout_value
= http
->timeout_value
.tv_sec
* 1000 +
2583 http
->timeout_value
.tv_usec
/ 1000;
2584 /* Timeout in milliseconds */
2586 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&timeout_value
,
2587 sizeof(timeout_value
));
2588 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&timeout_value
,
2589 sizeof(timeout_value
));
2591 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, &(http
->timeout_value
),
2592 sizeof(http
->timeout_value
));
2593 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, &(http
->timeout_value
),
2594 sizeof(http
->timeout_value
));
2601 * 'httpTrace()' - Send an TRACE request to the server.
2604 int /* O - Status of call (0 = success) */
2605 httpTrace(http_t
*http
, /* I - Connection to server */
2606 const char *uri
) /* I - URI for trace */
2608 return (http_send(http
, HTTP_TRACE
, uri
));
2613 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2615 * Note: Unlike httpUpdate(), this function does not flush pending write data
2616 * and only retrieves a single status line from the HTTP connection.
2619 int /* O - 1 to continue, 0 to stop */
2620 _httpUpdate(http_t
*http
, /* I - Connection to server */
2621 http_status_t
*status
) /* O - Current HTTP status */
2623 char line
[32768], /* Line from connection... */
2624 *value
; /* Pointer to value on line */
2625 http_field_t field
; /* Field index */
2626 int major
, minor
; /* HTTP version numbers */
2629 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2630 http_states
[http
->state
]));
2633 * Grab a single line from the connection...
2636 if (!httpGets(line
, sizeof(line
), http
))
2638 *status
= HTTP_ERROR
;
2642 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2644 if (line
[0] == '\0')
2647 * Blank line means the start of the data section (if any). Return
2648 * the result code, too...
2650 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2651 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2655 if (http
->status
== HTTP_CONTINUE
)
2657 *status
= http
->status
;
2661 if (http
->status
< HTTP_BAD_REQUEST
)
2662 http
->digest_tries
= 0;
2665 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2667 if (http_setup_ssl(http
) != 0)
2670 closesocket(http
->fd
);
2675 *status
= http
->status
= HTTP_ERROR
;
2679 *status
= HTTP_CONTINUE
;
2682 #endif /* HAVE_SSL */
2684 httpGetLength2(http
);
2686 switch (http
->state
)
2690 case HTTP_POST_RECV
:
2693 case HTTP_POST_SEND
:
2698 http
->state
= HTTP_WAITING
;
2702 *status
= http
->status
;
2705 else if (!strncmp(line
, "HTTP/", 5))
2708 * Got the beginning of a response...
2711 int intstatus
; /* Status value as an integer */
2713 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2715 *status
= http
->status
= HTTP_ERROR
;
2719 http
->version
= (http_version_t
)(major
* 100 + minor
);
2720 *status
= http
->status
= (http_status_t
)intstatus
;
2722 else if ((value
= strchr(line
, ':')) != NULL
)
2729 while (_cups_isspace(*value
))
2733 * Be tolerants of servers that send unknown attribute fields...
2736 if (!strcasecmp(line
, "expect"))
2739 * "Expect: 100-continue" or similar...
2742 http
->expect
= (http_status_t
)atoi(value
);
2744 else if (!strcasecmp(line
, "cookie"))
2747 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2750 httpSetCookie(http
, value
);
2752 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
2753 httpSetField(http
, field
, value
);
2756 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
2761 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
2762 *status
= http
->status
= HTTP_ERROR
;
2771 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2774 http_status_t
/* O - HTTP status */
2775 httpUpdate(http_t
*http
) /* I - Connection to server */
2777 http_status_t status
; /* Request status */
2780 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2781 http_states
[http
->state
]));
2784 * Flush pending data, if any...
2789 DEBUG_puts("2httpUpdate: flushing buffer...");
2791 if (httpFlushWrite(http
) < 0)
2792 return (HTTP_ERROR
);
2796 * If we haven't issued any commands, then there is nothing to "update"...
2799 if (http
->state
== HTTP_WAITING
)
2800 return (HTTP_CONTINUE
);
2803 * Grab all of the lines we can from the connection...
2806 while (_httpUpdate(http
, &status
));
2809 * See if there was an error...
2812 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2814 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2815 return (http
->status
);
2820 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2821 strerror(http
->error
)));
2822 http
->status
= HTTP_ERROR
;
2823 return (HTTP_ERROR
);
2827 * Return the current status...
2835 * '_httpWait()' - Wait for data available on a connection (no flush).
2838 int /* O - 1 if data is available, 0 otherwise */
2839 _httpWait(http_t
*http
, /* I - Connection to server */
2840 int msec
, /* I - Milliseconds to wait */
2841 int usessl
) /* I - Use SSL context? */
2844 struct pollfd pfd
; /* Polled file descriptor */
2846 fd_set input_set
; /* select() input set */
2847 struct timeval timeout
; /* Timeout */
2848 #endif /* HAVE_POLL */
2849 int nfds
; /* Result from select()/poll() */
2852 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2856 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2861 * Check the SSL/TLS buffers for data first...
2865 if (http
->tls
&& usessl
)
2868 if (SSL_pending(http
->tls
))
2870 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2874 # elif defined(HAVE_GNUTLS)
2875 if (gnutls_record_check_pending(http
->tls
))
2877 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2881 # elif defined(HAVE_CDSASSL)
2882 size_t bytes
; /* Bytes that are available */
2884 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2887 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2890 # endif /* HAVE_LIBSSL */
2892 #endif /* HAVE_SSL */
2895 * Then try doing a select() or poll() to poll the socket...
2900 pfd
.events
= POLLIN
;
2902 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2903 (errno
== EINTR
|| errno
== EAGAIN
));
2908 FD_ZERO(&input_set
);
2909 FD_SET(http
->fd
, &input_set
);
2911 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2915 timeout
.tv_sec
= msec
/ 1000;
2916 timeout
.tv_usec
= (msec
% 1000) * 1000;
2918 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2921 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2923 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2926 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2927 WSAGetLastError() == WSAEWOULDBLOCK
));
2929 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2931 #endif /* HAVE_POLL */
2933 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2941 * 'httpWait()' - Wait for data available on a connection.
2943 * @since CUPS 1.1.19/Mac OS X 10.3@
2946 int /* O - 1 if data is available, 0 otherwise */
2947 httpWait(http_t
*http
, /* I - Connection to server */
2948 int msec
) /* I - Milliseconds to wait */
2951 * First see if there is data in the buffer...
2961 * Flush pending data, if any...
2966 if (httpFlushWrite(http
) < 0)
2971 * If not, check the SSL/TLS buffers and do a select() on the connection...
2974 return (_httpWait(http
, msec
, 1));
2979 * 'httpWrite()' - Write data to a HTTP connection.
2981 * This function is deprecated. Use the httpWrite2() function which can
2982 * write more than 2GB of data.
2987 int /* O - Number of bytes written */
2988 httpWrite(http_t
*http
, /* I - Connection to server */
2989 const char *buffer
, /* I - Buffer for data */
2990 int length
) /* I - Number of bytes to write */
2992 return ((int)httpWrite2(http
, buffer
, length
));
2997 * 'httpWrite2()' - Write data to a HTTP connection.
2999 * @since CUPS 1.2/Mac OS X 10.5@
3002 ssize_t
/* O - Number of bytes written */
3003 httpWrite2(http_t
*http
, /* I - Connection to server */
3004 const char *buffer
, /* I - Buffer for data */
3005 size_t length
) /* I - Number of bytes to write */
3007 ssize_t bytes
; /* Bytes written */
3010 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3011 buffer
, CUPS_LLCAST length
));
3014 * Range check input...
3017 if (http
== NULL
|| buffer
== NULL
)
3021 * Mark activity on the connection...
3024 http
->activity
= time(NULL
);
3027 * Buffer small writes for better performance...
3032 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3034 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3035 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3037 httpFlushWrite(http
);
3040 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3041 length
< sizeof(http
->wbuffer
))
3044 * Write to buffer...
3047 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3048 CUPS_LLCAST length
));
3050 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3051 http
->wused
+= (int)length
;
3052 bytes
= (ssize_t
)length
;
3057 * Otherwise write the data directly...
3060 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3061 CUPS_LLCAST length
));
3063 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3064 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3066 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3068 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3069 CUPS_LLCAST bytes
));
3072 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3073 http
->data_remaining
-= bytes
;
3079 * Handle end-of-request processing...
3082 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3083 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3086 * Finished with the transfer; unless we are sending POST or PUT
3090 DEBUG_puts("2httpWrite: changing states...");
3093 httpFlushWrite(http
);
3095 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3098 * Send a 0-length chunk at the end of the request...
3101 http_write(http
, "0\r\n\r\n", 5);
3104 * Reset the data state...
3107 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3108 http
->data_remaining
= 0;
3116 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3118 * '_httpWriteCDSA()' - Write function for the CDSA library.
3121 OSStatus
/* O - -1 on error, 0 on success */
3123 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3124 const void *data
, /* I - Data buffer */
3125 size_t *dataLength
) /* IO - Number of bytes */
3127 OSStatus result
; /* Return value */
3128 ssize_t bytes
; /* Number of bytes read */
3129 http_t
*http
; /* HTTP connection */
3132 http
= (http_t
*)connection
;
3136 bytes
= write(http
->fd
, data
, *dataLength
);
3138 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3140 if (bytes
== *dataLength
)
3144 else if (bytes
>= 0)
3146 *dataLength
= bytes
;
3147 result
= errSSLWouldBlock
;
3153 if (errno
== EAGAIN
)
3154 result
= errSSLWouldBlock
;
3156 result
= errSSLClosedAbort
;
3161 #endif /* HAVE_SSL && HAVE_CDSASSL */
3164 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3166 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3169 ssize_t
/* O - Number of bytes written or -1 on error */
3171 gnutls_transport_ptr ptr
, /* I - Connection to server */
3172 const void *data
, /* I - Data buffer */
3173 size_t length
) /* I - Number of bytes to write */
3175 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
3177 #endif /* HAVE_SSL && HAVE_GNUTLS */
3180 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3182 * 'http_bio_ctrl()' - Control the HTTP connection.
3185 static long /* O - Result/data */
3186 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3187 int cmd
, /* I - Control command */
3188 long arg1
, /* I - First argument */
3189 void *arg2
) /* I - Second argument */
3196 case BIO_CTRL_RESET
:
3200 case BIO_C_SET_FILE_PTR
:
3205 case BIO_C_GET_FILE_PTR
:
3208 *((void **)arg2
) = h
->ptr
;
3215 case BIO_CTRL_FLUSH
:
3222 * 'http_bio_free()' - Free OpenSSL data.
3225 static int /* O - 1 on success, 0 on failure */
3226 http_bio_free(BIO
*h
) /* I - BIO data */
3242 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3245 static int /* O - 1 on success, 0 on failure */
3246 http_bio_new(BIO
*h
) /* I - BIO data */
3261 * 'http_bio_puts()' - Send a string for OpenSSL.
3264 static int /* O - Bytes written */
3265 http_bio_puts(BIO
*h
, /* I - BIO data */
3266 const char *str
) /* I - String to write */
3269 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3271 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3277 * 'http_bio_read()' - Read data for OpenSSL.
3280 static int /* O - Bytes read */
3281 http_bio_read(BIO
*h
, /* I - BIO data */
3282 char *buf
, /* I - Buffer */
3283 int size
) /* I - Number of bytes to read */
3285 http_t
*http
; /* HTTP connection */
3288 http
= (http_t
*)h
->ptr
;
3290 if (!http
->blocking
)
3293 * Make sure we have data before we read...
3296 if (!_httpWait(http
, 10000, 0))
3299 http
->error
= WSAETIMEDOUT
;
3301 http
->error
= ETIMEDOUT
;
3308 return (recv(http
->fd
, buf
, size
, 0));
3313 * 'http_bio_write()' - Write data for OpenSSL.
3316 static int /* O - Bytes written */
3317 http_bio_write(BIO
*h
, /* I - BIO data */
3318 const char *buf
, /* I - Buffer to write */
3319 int num
) /* I - Number of bytes to write */
3321 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3323 #endif /* HAVE_SSL && HAVE_LIBSSL */
3328 * 'http_debug_hex()' - Do a hex dump of a buffer.
3332 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3333 const char *buffer
, /* I - Buffer to dump */
3334 int bytes
) /* I - Bytes to dump */
3336 int i
, j
, /* Looping vars */
3337 ch
; /* Current character */
3338 char line
[255], /* Line buffer */
3339 *start
, /* Start of line after prefix */
3340 *ptr
; /* Pointer into line */
3343 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3346 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
3348 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3349 start
= line
+ strlen(line
);
3351 for (i
= 0; i
< bytes
; i
+= 16)
3353 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3354 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3366 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3368 ch
= buffer
[i
+ j
] & 255;
3370 if (ch
< ' ' || ch
>= 127)
3384 * 'http_field()' - Return the field index for a field name.
3387 static http_field_t
/* O - Field index */
3388 http_field(const char *name
) /* I - String name */
3390 int i
; /* Looping var */
3393 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3394 if (strcasecmp(name
, http_fields
[i
]) == 0)
3395 return ((http_field_t
)i
);
3397 return (HTTP_FIELD_UNKNOWN
);
3403 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3406 static int /* O - Bytes read */
3407 http_read_ssl(http_t
*http
, /* I - Connection to server */
3408 char *buf
, /* I - Buffer to store data */
3409 int len
) /* I - Length of buffer */
3411 # if defined(HAVE_LIBSSL)
3412 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3414 # elif defined(HAVE_GNUTLS)
3415 ssize_t result
; /* Return value */
3418 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3420 if (result
< 0 && !errno
)
3423 * Convert GNU TLS error to errno value...
3428 case GNUTLS_E_INTERRUPTED
:
3432 case GNUTLS_E_AGAIN
:
3444 return ((int)result
);
3446 # elif defined(HAVE_CDSASSL)
3447 int result
; /* Return value */
3448 OSStatus error
; /* Error info */
3449 size_t processed
; /* Number of bytes processed */
3452 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3457 result
= (int)processed
;
3460 case errSSLWouldBlock
:
3462 result
= (int)processed
;
3470 case errSSLClosedGraceful
:
3473 result
= (int)processed
;
3483 # elif defined(HAVE_SSPISSL)
3484 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3485 # endif /* HAVE_LIBSSL */
3487 #endif /* HAVE_SSL */
3492 * 'http_locking_cb()' - Lock/unlock a thread's mutex.
3496 http_locking_cb(int mode
, /* I - Lock mode */
3497 int type
, /* I - Lock type */
3498 const char *file
, /* I - Source file */
3499 int line
) /* I - Line number */
3501 if (mode
& CRYPTO_LOCK
)
3502 _cupsMutexLock(http_locks
+ type
);
3504 _cupsMutexUnlock(http_locks
+ type
);
3506 #endif /* HAVE_LIBSSL */
3510 * 'http_send()' - Send a request with all fields and the trailing blank line.
3513 static int /* O - 0 on success, non-zero on error */
3514 http_send(http_t
*http
, /* I - Connection to server */
3515 http_state_t request
, /* I - Request code */
3516 const char *uri
) /* I - URI */
3518 int i
; /* Looping var */
3519 char buf
[1024]; /* Encoded URI buffer */
3520 static const char * const codes
[] =
3521 { /* Request code strings */
3538 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3539 http
, codes
[request
], uri
));
3541 if (http
== NULL
|| uri
== NULL
)
3545 * Set the User-Agent field if it isn't already...
3548 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3549 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3552 * Encode the URI as needed...
3555 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3558 * See if we had an error the last time around; if so, reconnect...
3561 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3562 if (httpReconnect(http
))
3566 * Flush any written data that is pending...
3571 if (httpFlushWrite(http
) < 0)
3572 if (httpReconnect(http
))
3577 * Send the request header...
3580 http
->state
= request
;
3581 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3583 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3586 http
->status
= HTTP_CONTINUE
;
3589 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3591 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3592 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3594 #endif /* HAVE_SSL */
3596 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3598 http
->status
= HTTP_ERROR
;
3602 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3603 if (http
->fields
[i
][0] != '\0')
3605 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3606 httpGetField(http
, i
)));
3608 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3609 httpGetField(http
, i
)) < 1)
3611 http
->status
= HTTP_ERROR
;
3617 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3619 http
->status
= HTTP_ERROR
;
3623 if (http
->expect
== HTTP_CONTINUE
&&
3624 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3625 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3627 http
->status
= HTTP_ERROR
;
3631 if (httpPrintf(http
, "\r\n") < 1)
3633 http
->status
= HTTP_ERROR
;
3637 if (httpFlushWrite(http
) < 0)
3640 httpGetLength2(http
);
3641 httpClearFields(http
);
3644 * The Kerberos and AuthRef authentication strings can only be used once...
3647 if (http
->field_authorization
&& http
->authstring
&&
3648 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3649 !strncmp(http
->authstring
, "AuthRef", 7)))
3651 http
->_authstring
[0] = '\0';
3653 if (http
->authstring
!= http
->_authstring
)
3654 free(http
->authstring
);
3656 http
->authstring
= http
->_authstring
;
3664 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
3666 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3669 static int /* O - Status of connection */
3670 http_set_credentials(http_t
*http
) /* I - Connection to server */
3672 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3673 OSStatus error
= 0; /* Error code */
3674 http_tls_credentials_t credentials
= NULL
;
3675 /* TLS credentials */
3678 DEBUG_printf(("7http_set_credentials(%p)", http
));
3681 * Prefer connection specific credentials...
3684 if ((credentials
= http
->tls_credentials
) == NULL
)
3685 credentials
= cg
->tls_credentials
;
3687 # if HAVE_SECPOLICYCREATESSL
3689 * Otherwise root around in the user's keychain to see if one can be found...
3694 CFDictionaryRef query
; /* Query dictionary */
3695 CFTypeRef matches
= NULL
; /* Matching credentials */
3696 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3697 CFTypeRef keys
[] = { kSecClass
,
3700 /* Keys for dictionary */
3701 CFTypeRef values
[] = { kSecClassCertificate
,
3704 /* Values for dictionary */
3707 * Get the names associated with the server.
3710 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3712 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3718 * Create a query which will return all identities that can sign and match
3719 * the passed in policy.
3722 query
= CFDictionaryCreate(NULL
,
3723 (const void**)(&keys
[0]),
3724 (const void**)(&values
[0]),
3725 sizeof(keys
) / sizeof(keys
[0]),
3726 &kCFTypeDictionaryKeyCallBacks
,
3727 &kCFTypeDictionaryValueCallBacks
);
3730 error
= SecItemCopyMatching(query
, &matches
);
3731 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3740 CFRelease(dn_array
);
3742 # endif /* HAVE_SECPOLICYCREATESSL */
3746 error
= SSLSetCertificate(http
->tls
, credentials
);
3747 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3751 DEBUG_puts("4http_set_credentials: No credentials to set.");
3755 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
3759 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3762 static int /* O - Status of connection */
3763 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3765 _cups_globals_t
*cg
= _cupsGlobals();
3766 /* Pointer to library globals */
3767 int any_root
; /* Allow any root */
3770 SSL_CTX
*context
; /* Context for encryption */
3771 BIO
*bio
; /* BIO data */
3772 # elif defined(HAVE_GNUTLS)
3773 gnutls_certificate_client_credentials
*credentials
;
3774 /* TLS credentials */
3775 # elif defined(HAVE_CDSASSL)
3776 OSStatus error
; /* Error code */
3777 const char *message
= NULL
; /* Error message */
3778 char *hostname
; /* Hostname */
3779 # ifdef HAVE_SECCERTIFICATECOPYDATA
3780 cups_array_t
*credentials
; /* Credentials array */
3781 cups_array_t
*names
; /* CUPS distinguished names */
3782 CFArrayRef dn_array
; /* CF distinguished names array */
3783 CFIndex count
; /* Number of credentials */
3784 CFDataRef data
; /* Certificate data */
3785 int i
; /* Looping var */
3787 *credential
; /* Credential data */
3788 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3789 # elif defined(HAVE_SSPISSL)
3790 TCHAR username
[256]; /* Username returned from GetUserName() */
3791 TCHAR commonName
[256]; /* Common name for certificate */
3792 DWORD dwSize
; /* 32 bit size */
3793 # endif /* HAVE_LIBSSL */
3796 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3799 * Always allow self-signed certificates for the local loopback address...
3802 if (httpAddrLocalhost(http
->hostaddr
))
3805 any_root
= cg
->any_root
;
3808 context
= SSL_CTX_new(SSLv23_client_method());
3810 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3812 bio
= BIO_new(_httpBIOMethods());
3813 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3815 http
->tls
= SSL_new(context
);
3816 SSL_set_bio(http
->tls_credentials
, bio
, bio
);
3818 if (SSL_connect(http
->tls
) != 1)
3821 unsigned long error
; /* Error code */
3823 while ((error
= ERR_get_error()) != 0)
3824 DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error
, NULL
)));
3827 SSL_CTX_free(context
);
3828 SSL_free(http
->tls
);
3832 http
->error
= WSAGetLastError();
3834 http
->error
= errno
;
3836 http
->status
= HTTP_ERROR
;
3838 return (HTTP_ERROR
);
3841 # elif defined(HAVE_GNUTLS)
3842 credentials
= (gnutls_certificate_client_credentials
*)
3843 malloc(sizeof(gnutls_certificate_client_credentials
));
3844 if (credentials
== NULL
)
3846 http
->error
= errno
;
3847 http
->status
= HTTP_ERROR
;
3852 gnutls_certificate_allocate_credentials(credentials
);
3854 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3855 gnutls_set_default_priority(http
->tls
);
3856 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3857 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3858 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3859 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3861 if ((gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3863 http
->error
= errno
;
3864 http
->status
= HTTP_ERROR
;
3866 gnutls_deinit(http
->tls
);
3867 gnutls_certificate_free_credentials(*credentials
);
3874 http
->tls_credentials
= credentials
;
3876 # elif defined(HAVE_CDSASSL)
3877 if ((error
= SSLNewContext(false, &http
->tls
)))
3879 http
->error
= error
;
3880 http
->status
= HTTP_ERROR
;
3885 error
= SSLSetConnection(http
->tls
, http
);
3886 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
3890 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
3891 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
3896 error
= SSLSetProtocolVersionEnabled(http
->tls
, kSSLProtocol2
, false);
3897 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionEnabled, error=%d",
3903 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
3904 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
3905 any_root
, (int)error
));
3910 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
3911 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
3912 cg
->expired_certs
, (int)error
));
3917 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
3918 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
3919 cg
->expired_root
, (int)error
));
3922 # ifdef HAVE_SECCERTIFICATECOPYDATA
3925 if (cg
->client_cert_cb
)
3927 error
= SSLSetSessionOption(http
->tls
,
3928 kSSLSessionOptionBreakOnCertRequested
, true);
3929 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
3930 "error=%d", (int)error
));
3934 error
= http_set_credentials(http
);
3935 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
3941 * If there's a server certificate callback installed let it evaluate the
3942 * certificate(s) during the handshake...
3945 if (!error
&& cg
->server_cert_cb
!= NULL
)
3947 error
= SSLSetEnableCertVerify(http
->tls
, false);
3948 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
3953 error
= SSLSetSessionOption(http
->tls
,
3954 kSSLSessionOptionBreakOnServerAuth
, true);
3955 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
3956 "error=%d", (int)error
));
3959 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3963 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
3964 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
3966 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
3972 int done
= 0; /* Are we done yet? */
3974 while (!error
&& !done
)
3976 error
= SSLHandshake(http
->tls
);
3978 DEBUG_printf(("4_httpWait: SSLHandshake returned %d.", (int)error
));
3986 case errSSLWouldBlock
:
3990 # ifdef HAVE_SECCERTIFICATECOPYDATA
3991 case errSSLServerAuthCompleted
:
3993 if (cg
->server_cert_cb
)
3995 error
= httpCopyCredentials(http
, &credentials
);
3998 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
3999 cg
->server_cert_data
);
4000 httpFreeCredentials(credentials
);
4003 DEBUG_printf(("4_httpWait: Server certificate callback returned "
4004 "%d.", (int)error
));
4008 case errSSLClientCertRequested
:
4011 if (cg
->client_cert_cb
)
4014 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
4017 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
4019 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
4021 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
4023 if ((credential
= malloc(sizeof(*credential
))))
4025 credential
->datalen
= CFDataGetLength(data
);
4026 if ((credential
->data
= malloc(credential
->datalen
)))
4028 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
4029 credential
->datalen
);
4030 cupsArrayAdd(names
, credential
);
4036 CFRelease(dn_array
);
4041 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
4042 cg
->client_cert_data
);
4044 DEBUG_printf(("4_httpWait: Client certificate callback "
4045 "returned %d.", (int)error
));
4048 httpFreeCredentials(names
);
4051 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4053 case errSSLUnknownRootCert
:
4054 message
= _("Unable to establish a secure connection to host "
4055 "(untrusted certificate).");
4058 case errSSLNoRootCert
:
4059 message
= _("Unable to establish a secure connection to host "
4060 "(self-signed certificate).");
4063 case errSSLCertExpired
:
4064 message
= _("Unable to establish a secure connection to host "
4065 "(expired certificate).");
4068 case errSSLCertNotYetValid
:
4069 message
= _("Unable to establish a secure connection to host "
4070 "(certificate not yet valid).");
4073 case errSSLHostNameMismatch
:
4074 message
= _("Unable to establish a secure connection to host "
4075 "(host name mismatch).");
4078 case errSSLXCertChainInvalid
:
4079 message
= _("Unable to establish a secure connection to host "
4080 "(certificate chain invalid).");
4083 case errSSLConnectionRefused
:
4084 message
= _("Unable to establish a secure connection to host "
4085 "(peer dropped connection before responding).");
4096 http
->error
= error
;
4097 http
->status
= HTTP_ERROR
;
4098 errno
= ECONNREFUSED
;
4100 SSLDisposeContext(http
->tls
);
4104 * If an error string wasn't set by the callbacks use a generic one...
4108 #ifdef HAVE_CSSMERRORSTRING
4109 message
= cssmErrorString(error
);
4111 message
= _("Unable to establish a secure connection to host.");
4112 #endif /* HAVE_CSSMERRORSTRING */
4114 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4119 # elif defined(HAVE_SSPISSL)
4120 http
->tls
= _sspiAlloc();
4125 http
->tls
->sock
= http
->fd
;
4126 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4127 GetUserName(username
, &dwSize
);
4128 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4129 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4131 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4134 _sspiFree(http
->tls_credentials
);
4135 http
->tls_credentials
= NULL
;
4139 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
4140 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4142 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
4144 _sspiFree(http
->tls_credentials
);
4145 http
->tls_credentials
= NULL
;
4148 # endif /* HAVE_CDSASSL */
4152 #endif /* HAVE_SSL */
4157 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4161 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4164 SSL_CTX
*context
; /* Context for encryption */
4166 context
= SSL_get_SSL_CTX(http
->tls_credentials
);
4168 SSL_shutdown(http
->tls_credentials
);
4169 SSL_CTX_free(context
);
4170 SSL_free(http
->tls_credentials
);
4172 # elif defined(HAVE_GNUTLS)
4173 gnutls_certificate_client_credentials
*credentials
;
4174 /* TLS credentials */
4176 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4178 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4179 gnutls_deinit(http
->tls
);
4180 gnutls_certificate_free_credentials(*credentials
);
4183 # elif defined(HAVE_CDSASSL)
4184 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4187 SSLDisposeContext(http
->tls
);
4189 if (http
->tls_credentials
)
4190 CFRelease(http
->tls_credentials
);
4192 # elif defined(HAVE_SSPISSL)
4193 _sspiFree(http
->tls_credentials
);
4194 # endif /* HAVE_LIBSSL */
4197 http
->tls_credentials
= NULL
;
4199 #endif /* HAVE_SSL */
4204 * 'http_threadid_cb()' - Return the current thread ID.
4207 static unsigned long /* O - Thread ID */
4208 http_threadid_cb(void)
4210 # ifdef HAVE_PTHREAD_H
4211 return ((unsigned long)pthread_self());
4214 # endif /* HAVE_PTHREAD_H */
4216 #endif /* HAVE_LIBSSL */
4221 * 'http_upgrade()' - Force upgrade to TLS encryption.
4224 static int /* O - Status of connection */
4225 http_upgrade(http_t
*http
) /* I - Connection to server */
4227 int ret
; /* Return value */
4228 http_t myhttp
; /* Local copy of HTTP data */
4231 DEBUG_printf(("7http_upgrade(%p)", http
));
4234 * Flush the connection to make sure any previous "Upgrade" message
4241 * Copy the HTTP data to a local variable so we can do the OPTIONS
4242 * request without interfering with the existing request data...
4245 memcpy(&myhttp
, http
, sizeof(myhttp
));
4248 * Send an OPTIONS request to the server, requiring SSL or TLS
4249 * encryption on the link...
4252 http
->field_authorization
= NULL
; /* Don't free the auth string */
4254 httpClearFields(http
);
4255 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4256 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4258 if ((ret
= httpOptions(http
, "*")) == 0)
4261 * Wait for the secure connection...
4264 while (httpUpdate(http
) == HTTP_CONTINUE
);
4268 * Restore the HTTP request data...
4271 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4272 http
->data_encoding
= myhttp
.data_encoding
;
4273 http
->data_remaining
= myhttp
.data_remaining
;
4274 http
->_data_remaining
= myhttp
._data_remaining
;
4275 http
->expect
= myhttp
.expect
;
4276 http
->field_authorization
= myhttp
.field_authorization
;
4277 http
->digest_tries
= myhttp
.digest_tries
;
4280 * See if we actually went secure...
4286 * Server does not support HTTP upgrade...
4289 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4292 closesocket(http
->fd
);
4304 #endif /* HAVE_SSL */
4308 * 'http_write()' - Write a buffer to a HTTP connection.
4311 static int /* O - Number of bytes written */
4312 http_write(http_t
*http
, /* I - Connection to server */
4313 const char *buffer
, /* I - Buffer for data */
4314 int length
) /* I - Number of bytes to write */
4316 int tbytes
, /* Total bytes sent */
4317 bytes
; /* Bytes sent */
4320 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4329 bytes
= http_write_ssl(http
, buffer
, length
);
4331 #endif /* HAVE_SSL */
4332 bytes
= send(http
->fd
, buffer
, length
, 0);
4337 if (WSAGetLastError() == WSAEINTR
)
4339 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4341 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4344 http
->error
= WSAGetLastError();
4346 else if (WSAGetLastError() != http
->error
&&
4347 WSAGetLastError() != WSAECONNRESET
)
4349 http
->error
= WSAGetLastError();
4356 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4358 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4360 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4363 http
->error
= errno
;
4365 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4367 http
->error
= errno
;
4372 DEBUG_printf(("3http_write: error writing data (%s).",
4373 strerror(http
->error
)));
4384 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4387 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4394 * 'http_write_chunk()' - Write a chunked buffer.
4397 static int /* O - Number bytes written */
4398 http_write_chunk(http_t
*http
, /* I - Connection to server */
4399 const char *buffer
, /* I - Buffer to write */
4400 int length
) /* I - Length of buffer */
4402 char header
[255]; /* Chunk header */
4403 int bytes
; /* Bytes written */
4406 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4407 http
, buffer
, length
));
4410 * Write the chunk header, data, and trailer.
4413 sprintf(header
, "%x\r\n", length
);
4414 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4416 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4420 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4422 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4426 if (http_write(http
, "\r\n", 2) < 0)
4428 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4438 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4441 static int /* O - Bytes written */
4442 http_write_ssl(http_t
*http
, /* I - Connection to server */
4443 const char *buf
, /* I - Buffer holding data */
4444 int len
) /* I - Length of buffer */
4446 ssize_t result
; /* Return value */
4449 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4451 # if defined(HAVE_LIBSSL)
4452 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4454 # elif defined(HAVE_GNUTLS)
4455 result
= gnutls_record_send(http
->tls
, buf
, len
);
4457 if (result
< 0 && !errno
)
4460 * Convert GNU TLS error to errno value...
4465 case GNUTLS_E_INTERRUPTED
:
4469 case GNUTLS_E_AGAIN
:
4481 # elif defined(HAVE_CDSASSL)
4482 OSStatus error
; /* Error info */
4483 size_t processed
; /* Number of bytes processed */
4486 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4491 result
= (int)processed
;
4494 case errSSLWouldBlock
:
4496 result
= (int)processed
;
4504 case errSSLClosedGraceful
:
4507 result
= (int)processed
;
4515 # elif defined(HAVE_SSPISSL)
4516 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
4517 # endif /* HAVE_LIBSSL */
4519 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4521 return ((int)result
);
4523 #endif /* HAVE_SSL */
4527 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".