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, errno=%d.", bytes
, errno
));
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 (!_httpWait(http
, http
->blocking
? 30000 : 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...
2954 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
2961 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
2966 * Flush pending data, if any...
2971 DEBUG_puts("3httpWait: Flushing write buffer.");
2973 if (httpFlushWrite(http
) < 0)
2978 * If not, check the SSL/TLS buffers and do a select() on the connection...
2981 return (_httpWait(http
, msec
, 1));
2986 * 'httpWrite()' - Write data to a HTTP connection.
2988 * This function is deprecated. Use the httpWrite2() function which can
2989 * write more than 2GB of data.
2994 int /* O - Number of bytes written */
2995 httpWrite(http_t
*http
, /* I - Connection to server */
2996 const char *buffer
, /* I - Buffer for data */
2997 int length
) /* I - Number of bytes to write */
2999 return ((int)httpWrite2(http
, buffer
, length
));
3004 * 'httpWrite2()' - Write data to a HTTP connection.
3006 * @since CUPS 1.2/Mac OS X 10.5@
3009 ssize_t
/* O - Number of bytes written */
3010 httpWrite2(http_t
*http
, /* I - Connection to server */
3011 const char *buffer
, /* I - Buffer for data */
3012 size_t length
) /* I - Number of bytes to write */
3014 ssize_t bytes
; /* Bytes written */
3017 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3018 buffer
, CUPS_LLCAST length
));
3021 * Range check input...
3024 if (http
== NULL
|| buffer
== NULL
)
3028 * Mark activity on the connection...
3031 http
->activity
= time(NULL
);
3034 * Buffer small writes for better performance...
3039 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3041 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3042 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3044 httpFlushWrite(http
);
3047 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3048 length
< sizeof(http
->wbuffer
))
3051 * Write to buffer...
3054 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3055 CUPS_LLCAST length
));
3057 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3058 http
->wused
+= (int)length
;
3059 bytes
= (ssize_t
)length
;
3064 * Otherwise write the data directly...
3067 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3068 CUPS_LLCAST length
));
3070 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3071 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3073 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3075 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3076 CUPS_LLCAST bytes
));
3079 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3080 http
->data_remaining
-= bytes
;
3086 * Handle end-of-request processing...
3089 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3090 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3093 * Finished with the transfer; unless we are sending POST or PUT
3097 DEBUG_puts("2httpWrite: changing states...");
3100 httpFlushWrite(http
);
3102 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3105 * Send a 0-length chunk at the end of the request...
3108 http_write(http
, "0\r\n\r\n", 5);
3111 * Reset the data state...
3114 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3115 http
->data_remaining
= 0;
3123 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3125 * '_httpWriteCDSA()' - Write function for the CDSA library.
3128 OSStatus
/* O - -1 on error, 0 on success */
3130 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3131 const void *data
, /* I - Data buffer */
3132 size_t *dataLength
) /* IO - Number of bytes */
3134 OSStatus result
; /* Return value */
3135 ssize_t bytes
; /* Number of bytes read */
3136 http_t
*http
; /* HTTP connection */
3139 http
= (http_t
*)connection
;
3143 bytes
= write(http
->fd
, data
, *dataLength
);
3145 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3147 if (bytes
== *dataLength
)
3151 else if (bytes
>= 0)
3153 *dataLength
= bytes
;
3154 result
= errSSLWouldBlock
;
3160 if (errno
== EAGAIN
)
3161 result
= errSSLWouldBlock
;
3163 result
= errSSLClosedAbort
;
3168 #endif /* HAVE_SSL && HAVE_CDSASSL */
3171 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3173 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3176 ssize_t
/* O - Number of bytes written or -1 on error */
3178 gnutls_transport_ptr ptr
, /* I - Connection to server */
3179 const void *data
, /* I - Data buffer */
3180 size_t length
) /* I - Number of bytes to write */
3182 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
3184 #endif /* HAVE_SSL && HAVE_GNUTLS */
3187 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3189 * 'http_bio_ctrl()' - Control the HTTP connection.
3192 static long /* O - Result/data */
3193 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3194 int cmd
, /* I - Control command */
3195 long arg1
, /* I - First argument */
3196 void *arg2
) /* I - Second argument */
3203 case BIO_CTRL_RESET
:
3207 case BIO_C_SET_FILE_PTR
:
3212 case BIO_C_GET_FILE_PTR
:
3215 *((void **)arg2
) = h
->ptr
;
3222 case BIO_CTRL_FLUSH
:
3229 * 'http_bio_free()' - Free OpenSSL data.
3232 static int /* O - 1 on success, 0 on failure */
3233 http_bio_free(BIO
*h
) /* I - BIO data */
3249 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3252 static int /* O - 1 on success, 0 on failure */
3253 http_bio_new(BIO
*h
) /* I - BIO data */
3268 * 'http_bio_puts()' - Send a string for OpenSSL.
3271 static int /* O - Bytes written */
3272 http_bio_puts(BIO
*h
, /* I - BIO data */
3273 const char *str
) /* I - String to write */
3276 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3278 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3284 * 'http_bio_read()' - Read data for OpenSSL.
3287 static int /* O - Bytes read */
3288 http_bio_read(BIO
*h
, /* I - BIO data */
3289 char *buf
, /* I - Buffer */
3290 int size
) /* I - Number of bytes to read */
3292 http_t
*http
; /* HTTP connection */
3295 http
= (http_t
*)h
->ptr
;
3297 if (!http
->blocking
)
3300 * Make sure we have data before we read...
3303 if (!_httpWait(http
, 10000, 0))
3306 http
->error
= WSAETIMEDOUT
;
3308 http
->error
= ETIMEDOUT
;
3315 return (recv(http
->fd
, buf
, size
, 0));
3320 * 'http_bio_write()' - Write data for OpenSSL.
3323 static int /* O - Bytes written */
3324 http_bio_write(BIO
*h
, /* I - BIO data */
3325 const char *buf
, /* I - Buffer to write */
3326 int num
) /* I - Number of bytes to write */
3328 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3330 #endif /* HAVE_SSL && HAVE_LIBSSL */
3335 * 'http_debug_hex()' - Do a hex dump of a buffer.
3339 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3340 const char *buffer
, /* I - Buffer to dump */
3341 int bytes
) /* I - Bytes to dump */
3343 int i
, j
, /* Looping vars */
3344 ch
; /* Current character */
3345 char line
[255], /* Line buffer */
3346 *start
, /* Start of line after prefix */
3347 *ptr
; /* Pointer into line */
3350 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3353 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
3355 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3356 start
= line
+ strlen(line
);
3358 for (i
= 0; i
< bytes
; i
+= 16)
3360 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3361 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3373 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3375 ch
= buffer
[i
+ j
] & 255;
3377 if (ch
< ' ' || ch
>= 127)
3391 * 'http_field()' - Return the field index for a field name.
3394 static http_field_t
/* O - Field index */
3395 http_field(const char *name
) /* I - String name */
3397 int i
; /* Looping var */
3400 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3401 if (strcasecmp(name
, http_fields
[i
]) == 0)
3402 return ((http_field_t
)i
);
3404 return (HTTP_FIELD_UNKNOWN
);
3410 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3413 static int /* O - Bytes read */
3414 http_read_ssl(http_t
*http
, /* I - Connection to server */
3415 char *buf
, /* I - Buffer to store data */
3416 int len
) /* I - Length of buffer */
3418 # if defined(HAVE_LIBSSL)
3419 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3421 # elif defined(HAVE_GNUTLS)
3422 ssize_t result
; /* Return value */
3425 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3427 if (result
< 0 && !errno
)
3430 * Convert GNU TLS error to errno value...
3435 case GNUTLS_E_INTERRUPTED
:
3439 case GNUTLS_E_AGAIN
:
3451 return ((int)result
);
3453 # elif defined(HAVE_CDSASSL)
3454 int result
; /* Return value */
3455 OSStatus error
; /* Error info */
3456 size_t processed
; /* Number of bytes processed */
3459 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3464 result
= (int)processed
;
3467 case errSSLWouldBlock
:
3469 result
= (int)processed
;
3477 case errSSLClosedGraceful
:
3480 result
= (int)processed
;
3490 # elif defined(HAVE_SSPISSL)
3491 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3492 # endif /* HAVE_LIBSSL */
3494 #endif /* HAVE_SSL */
3499 * 'http_locking_cb()' - Lock/unlock a thread's mutex.
3503 http_locking_cb(int mode
, /* I - Lock mode */
3504 int type
, /* I - Lock type */
3505 const char *file
, /* I - Source file */
3506 int line
) /* I - Line number */
3508 if (mode
& CRYPTO_LOCK
)
3509 _cupsMutexLock(http_locks
+ type
);
3511 _cupsMutexUnlock(http_locks
+ type
);
3513 #endif /* HAVE_LIBSSL */
3517 * 'http_send()' - Send a request with all fields and the trailing blank line.
3520 static int /* O - 0 on success, non-zero on error */
3521 http_send(http_t
*http
, /* I - Connection to server */
3522 http_state_t request
, /* I - Request code */
3523 const char *uri
) /* I - URI */
3525 int i
; /* Looping var */
3526 char buf
[1024]; /* Encoded URI buffer */
3527 static const char * const codes
[] =
3528 { /* Request code strings */
3545 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3546 http
, codes
[request
], uri
));
3548 if (http
== NULL
|| uri
== NULL
)
3552 * Set the User-Agent field if it isn't already...
3555 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3556 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3559 * Encode the URI as needed...
3562 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3565 * See if we had an error the last time around; if so, reconnect...
3568 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3569 if (httpReconnect(http
))
3573 * Flush any written data that is pending...
3578 if (httpFlushWrite(http
) < 0)
3579 if (httpReconnect(http
))
3584 * Send the request header...
3587 http
->state
= request
;
3588 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3590 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3593 http
->status
= HTTP_CONTINUE
;
3596 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3598 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3599 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3601 #endif /* HAVE_SSL */
3603 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3605 http
->status
= HTTP_ERROR
;
3609 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3610 if (http
->fields
[i
][0] != '\0')
3612 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3613 httpGetField(http
, i
)));
3615 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3616 httpGetField(http
, i
)) < 1)
3618 http
->status
= HTTP_ERROR
;
3624 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3626 http
->status
= HTTP_ERROR
;
3630 if (http
->expect
== HTTP_CONTINUE
&&
3631 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3632 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3634 http
->status
= HTTP_ERROR
;
3638 if (httpPrintf(http
, "\r\n") < 1)
3640 http
->status
= HTTP_ERROR
;
3644 if (httpFlushWrite(http
) < 0)
3647 httpGetLength2(http
);
3648 httpClearFields(http
);
3651 * The Kerberos and AuthRef authentication strings can only be used once...
3654 if (http
->field_authorization
&& http
->authstring
&&
3655 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3656 !strncmp(http
->authstring
, "AuthRef", 7)))
3658 http
->_authstring
[0] = '\0';
3660 if (http
->authstring
!= http
->_authstring
)
3661 free(http
->authstring
);
3663 http
->authstring
= http
->_authstring
;
3671 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
3673 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3676 static int /* O - Status of connection */
3677 http_set_credentials(http_t
*http
) /* I - Connection to server */
3679 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3680 OSStatus error
= 0; /* Error code */
3681 http_tls_credentials_t credentials
= NULL
;
3682 /* TLS credentials */
3685 DEBUG_printf(("7http_set_credentials(%p)", http
));
3688 * Prefer connection specific credentials...
3691 if ((credentials
= http
->tls_credentials
) == NULL
)
3692 credentials
= cg
->tls_credentials
;
3694 # if HAVE_SECPOLICYCREATESSL
3696 * Otherwise root around in the user's keychain to see if one can be found...
3701 CFDictionaryRef query
; /* Query dictionary */
3702 CFTypeRef matches
= NULL
; /* Matching credentials */
3703 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3704 CFTypeRef keys
[] = { kSecClass
,
3707 /* Keys for dictionary */
3708 CFTypeRef values
[] = { kSecClassCertificate
,
3711 /* Values for dictionary */
3714 * Get the names associated with the server.
3717 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3719 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3725 * Create a query which will return all identities that can sign and match
3726 * the passed in policy.
3729 query
= CFDictionaryCreate(NULL
,
3730 (const void**)(&keys
[0]),
3731 (const void**)(&values
[0]),
3732 sizeof(keys
) / sizeof(keys
[0]),
3733 &kCFTypeDictionaryKeyCallBacks
,
3734 &kCFTypeDictionaryValueCallBacks
);
3737 error
= SecItemCopyMatching(query
, &matches
);
3738 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3747 CFRelease(dn_array
);
3749 # endif /* HAVE_SECPOLICYCREATESSL */
3753 error
= SSLSetCertificate(http
->tls
, credentials
);
3754 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3758 DEBUG_puts("4http_set_credentials: No credentials to set.");
3762 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
3766 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3769 static int /* O - Status of connection */
3770 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3772 _cups_globals_t
*cg
= _cupsGlobals();
3773 /* Pointer to library globals */
3774 int any_root
; /* Allow any root */
3777 SSL_CTX
*context
; /* Context for encryption */
3778 BIO
*bio
; /* BIO data */
3779 # elif defined(HAVE_GNUTLS)
3780 gnutls_certificate_client_credentials
*credentials
;
3781 /* TLS credentials */
3782 # elif defined(HAVE_CDSASSL)
3783 OSStatus error
; /* Error code */
3784 const char *message
= NULL
; /* Error message */
3785 char *hostname
; /* Hostname */
3786 # ifdef HAVE_SECCERTIFICATECOPYDATA
3787 cups_array_t
*credentials
; /* Credentials array */
3788 cups_array_t
*names
; /* CUPS distinguished names */
3789 CFArrayRef dn_array
; /* CF distinguished names array */
3790 CFIndex count
; /* Number of credentials */
3791 CFDataRef data
; /* Certificate data */
3792 int i
; /* Looping var */
3794 *credential
; /* Credential data */
3795 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3796 # elif defined(HAVE_SSPISSL)
3797 TCHAR username
[256]; /* Username returned from GetUserName() */
3798 TCHAR commonName
[256]; /* Common name for certificate */
3799 DWORD dwSize
; /* 32 bit size */
3800 # endif /* HAVE_LIBSSL */
3803 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3806 * Always allow self-signed certificates for the local loopback address...
3809 if (httpAddrLocalhost(http
->hostaddr
))
3812 any_root
= cg
->any_root
;
3815 context
= SSL_CTX_new(SSLv23_client_method());
3817 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3819 bio
= BIO_new(_httpBIOMethods());
3820 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3822 http
->tls
= SSL_new(context
);
3823 SSL_set_bio(http
->tls_credentials
, bio
, bio
);
3825 if (SSL_connect(http
->tls
) != 1)
3828 unsigned long error
; /* Error code */
3830 while ((error
= ERR_get_error()) != 0)
3831 DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error
, NULL
)));
3834 SSL_CTX_free(context
);
3835 SSL_free(http
->tls
);
3839 http
->error
= WSAGetLastError();
3841 http
->error
= errno
;
3843 http
->status
= HTTP_ERROR
;
3845 return (HTTP_ERROR
);
3848 # elif defined(HAVE_GNUTLS)
3849 credentials
= (gnutls_certificate_client_credentials
*)
3850 malloc(sizeof(gnutls_certificate_client_credentials
));
3851 if (credentials
== NULL
)
3853 http
->error
= errno
;
3854 http
->status
= HTTP_ERROR
;
3859 gnutls_certificate_allocate_credentials(credentials
);
3861 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3862 gnutls_set_default_priority(http
->tls
);
3863 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3864 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3865 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3866 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3868 if ((gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3870 http
->error
= errno
;
3871 http
->status
= HTTP_ERROR
;
3873 gnutls_deinit(http
->tls
);
3874 gnutls_certificate_free_credentials(*credentials
);
3881 http
->tls_credentials
= credentials
;
3883 # elif defined(HAVE_CDSASSL)
3884 if ((error
= SSLNewContext(false, &http
->tls
)))
3886 http
->error
= error
;
3887 http
->status
= HTTP_ERROR
;
3892 error
= SSLSetConnection(http
->tls
, http
);
3893 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
3897 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
3898 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
3903 error
= SSLSetProtocolVersionEnabled(http
->tls
, kSSLProtocol2
, false);
3904 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionEnabled, error=%d",
3910 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
3911 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
3912 any_root
, (int)error
));
3917 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
3918 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
3919 cg
->expired_certs
, (int)error
));
3924 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
3925 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
3926 cg
->expired_root
, (int)error
));
3929 # ifdef HAVE_SECCERTIFICATECOPYDATA
3932 if (cg
->client_cert_cb
)
3934 error
= SSLSetSessionOption(http
->tls
,
3935 kSSLSessionOptionBreakOnCertRequested
, true);
3936 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
3937 "error=%d", (int)error
));
3941 error
= http_set_credentials(http
);
3942 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
3948 * If there's a server certificate callback installed let it evaluate the
3949 * certificate(s) during the handshake...
3952 if (!error
&& cg
->server_cert_cb
!= NULL
)
3954 error
= SSLSetEnableCertVerify(http
->tls
, false);
3955 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
3960 error
= SSLSetSessionOption(http
->tls
,
3961 kSSLSessionOptionBreakOnServerAuth
, true);
3962 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
3963 "error=%d", (int)error
));
3966 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3970 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
3971 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
3973 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
3979 int done
= 0; /* Are we done yet? */
3981 while (!error
&& !done
)
3983 error
= SSLHandshake(http
->tls
);
3985 DEBUG_printf(("4_httpWait: SSLHandshake returned %d.", (int)error
));
3993 case errSSLWouldBlock
:
3997 # ifdef HAVE_SECCERTIFICATECOPYDATA
3998 case errSSLServerAuthCompleted
:
4000 if (cg
->server_cert_cb
)
4002 error
= httpCopyCredentials(http
, &credentials
);
4005 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
4006 cg
->server_cert_data
);
4007 httpFreeCredentials(credentials
);
4010 DEBUG_printf(("4_httpWait: Server certificate callback returned "
4011 "%d.", (int)error
));
4015 case errSSLClientCertRequested
:
4018 if (cg
->client_cert_cb
)
4021 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
4024 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
4026 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
4028 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
4030 if ((credential
= malloc(sizeof(*credential
))))
4032 credential
->datalen
= CFDataGetLength(data
);
4033 if ((credential
->data
= malloc(credential
->datalen
)))
4035 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
4036 credential
->datalen
);
4037 cupsArrayAdd(names
, credential
);
4043 CFRelease(dn_array
);
4048 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
4049 cg
->client_cert_data
);
4051 DEBUG_printf(("4_httpWait: Client certificate callback "
4052 "returned %d.", (int)error
));
4055 httpFreeCredentials(names
);
4058 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4060 case errSSLUnknownRootCert
:
4061 message
= _("Unable to establish a secure connection to host "
4062 "(untrusted certificate).");
4065 case errSSLNoRootCert
:
4066 message
= _("Unable to establish a secure connection to host "
4067 "(self-signed certificate).");
4070 case errSSLCertExpired
:
4071 message
= _("Unable to establish a secure connection to host "
4072 "(expired certificate).");
4075 case errSSLCertNotYetValid
:
4076 message
= _("Unable to establish a secure connection to host "
4077 "(certificate not yet valid).");
4080 case errSSLHostNameMismatch
:
4081 message
= _("Unable to establish a secure connection to host "
4082 "(host name mismatch).");
4085 case errSSLXCertChainInvalid
:
4086 message
= _("Unable to establish a secure connection to host "
4087 "(certificate chain invalid).");
4090 case errSSLConnectionRefused
:
4091 message
= _("Unable to establish a secure connection to host "
4092 "(peer dropped connection before responding).");
4103 http
->error
= error
;
4104 http
->status
= HTTP_ERROR
;
4105 errno
= ECONNREFUSED
;
4107 SSLDisposeContext(http
->tls
);
4111 * If an error string wasn't set by the callbacks use a generic one...
4115 #ifdef HAVE_CSSMERRORSTRING
4116 message
= cssmErrorString(error
);
4118 message
= _("Unable to establish a secure connection to host.");
4119 #endif /* HAVE_CSSMERRORSTRING */
4121 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4126 # elif defined(HAVE_SSPISSL)
4127 http
->tls
= _sspiAlloc();
4132 http
->tls
->sock
= http
->fd
;
4133 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4134 GetUserName(username
, &dwSize
);
4135 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4136 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4138 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4141 _sspiFree(http
->tls_credentials
);
4142 http
->tls_credentials
= NULL
;
4146 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
4147 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4149 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
4151 _sspiFree(http
->tls_credentials
);
4152 http
->tls_credentials
= NULL
;
4155 # endif /* HAVE_CDSASSL */
4159 #endif /* HAVE_SSL */
4164 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4168 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4171 SSL_CTX
*context
; /* Context for encryption */
4173 context
= SSL_get_SSL_CTX(http
->tls_credentials
);
4175 SSL_shutdown(http
->tls_credentials
);
4176 SSL_CTX_free(context
);
4177 SSL_free(http
->tls_credentials
);
4179 # elif defined(HAVE_GNUTLS)
4180 gnutls_certificate_client_credentials
*credentials
;
4181 /* TLS credentials */
4183 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4185 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4186 gnutls_deinit(http
->tls
);
4187 gnutls_certificate_free_credentials(*credentials
);
4190 # elif defined(HAVE_CDSASSL)
4191 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4194 SSLDisposeContext(http
->tls
);
4196 if (http
->tls_credentials
)
4197 CFRelease(http
->tls_credentials
);
4199 # elif defined(HAVE_SSPISSL)
4200 _sspiFree(http
->tls_credentials
);
4201 # endif /* HAVE_LIBSSL */
4204 http
->tls_credentials
= NULL
;
4206 #endif /* HAVE_SSL */
4211 * 'http_threadid_cb()' - Return the current thread ID.
4214 static unsigned long /* O - Thread ID */
4215 http_threadid_cb(void)
4217 # ifdef HAVE_PTHREAD_H
4218 return ((unsigned long)pthread_self());
4221 # endif /* HAVE_PTHREAD_H */
4223 #endif /* HAVE_LIBSSL */
4228 * 'http_upgrade()' - Force upgrade to TLS encryption.
4231 static int /* O - Status of connection */
4232 http_upgrade(http_t
*http
) /* I - Connection to server */
4234 int ret
; /* Return value */
4235 http_t myhttp
; /* Local copy of HTTP data */
4238 DEBUG_printf(("7http_upgrade(%p)", http
));
4241 * Flush the connection to make sure any previous "Upgrade" message
4248 * Copy the HTTP data to a local variable so we can do the OPTIONS
4249 * request without interfering with the existing request data...
4252 memcpy(&myhttp
, http
, sizeof(myhttp
));
4255 * Send an OPTIONS request to the server, requiring SSL or TLS
4256 * encryption on the link...
4259 http
->field_authorization
= NULL
; /* Don't free the auth string */
4261 httpClearFields(http
);
4262 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4263 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4265 if ((ret
= httpOptions(http
, "*")) == 0)
4268 * Wait for the secure connection...
4271 while (httpUpdate(http
) == HTTP_CONTINUE
);
4275 * Restore the HTTP request data...
4278 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4279 http
->data_encoding
= myhttp
.data_encoding
;
4280 http
->data_remaining
= myhttp
.data_remaining
;
4281 http
->_data_remaining
= myhttp
._data_remaining
;
4282 http
->expect
= myhttp
.expect
;
4283 http
->field_authorization
= myhttp
.field_authorization
;
4284 http
->digest_tries
= myhttp
.digest_tries
;
4287 * See if we actually went secure...
4293 * Server does not support HTTP upgrade...
4296 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4299 closesocket(http
->fd
);
4311 #endif /* HAVE_SSL */
4315 * 'http_write()' - Write a buffer to a HTTP connection.
4318 static int /* O - Number of bytes written */
4319 http_write(http_t
*http
, /* I - Connection to server */
4320 const char *buffer
, /* I - Buffer for data */
4321 int length
) /* I - Number of bytes to write */
4323 int tbytes
, /* Total bytes sent */
4324 bytes
; /* Bytes sent */
4327 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4336 bytes
= http_write_ssl(http
, buffer
, length
);
4338 #endif /* HAVE_SSL */
4339 bytes
= send(http
->fd
, buffer
, length
, 0);
4344 if (WSAGetLastError() == WSAEINTR
)
4346 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4348 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4351 http
->error
= WSAGetLastError();
4353 else if (WSAGetLastError() != http
->error
&&
4354 WSAGetLastError() != WSAECONNRESET
)
4356 http
->error
= WSAGetLastError();
4363 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4365 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4367 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4370 http
->error
= errno
;
4372 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4374 http
->error
= errno
;
4379 DEBUG_printf(("3http_write: error writing data (%s).",
4380 strerror(http
->error
)));
4391 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4394 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4401 * 'http_write_chunk()' - Write a chunked buffer.
4404 static int /* O - Number bytes written */
4405 http_write_chunk(http_t
*http
, /* I - Connection to server */
4406 const char *buffer
, /* I - Buffer to write */
4407 int length
) /* I - Length of buffer */
4409 char header
[255]; /* Chunk header */
4410 int bytes
; /* Bytes written */
4413 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4414 http
, buffer
, length
));
4417 * Write the chunk header, data, and trailer.
4420 sprintf(header
, "%x\r\n", length
);
4421 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4423 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4427 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4429 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4433 if (http_write(http
, "\r\n", 2) < 0)
4435 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4445 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4448 static int /* O - Bytes written */
4449 http_write_ssl(http_t
*http
, /* I - Connection to server */
4450 const char *buf
, /* I - Buffer holding data */
4451 int len
) /* I - Length of buffer */
4453 ssize_t result
; /* Return value */
4456 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4458 # if defined(HAVE_LIBSSL)
4459 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4461 # elif defined(HAVE_GNUTLS)
4462 result
= gnutls_record_send(http
->tls
, buf
, len
);
4464 if (result
< 0 && !errno
)
4467 * Convert GNU TLS error to errno value...
4472 case GNUTLS_E_INTERRUPTED
:
4476 case GNUTLS_E_AGAIN
:
4488 # elif defined(HAVE_CDSASSL)
4489 OSStatus error
; /* Error info */
4490 size_t processed
; /* Number of bytes processed */
4493 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4498 result
= (int)processed
;
4501 case errSSLWouldBlock
:
4503 result
= (int)processed
;
4511 case errSSLClosedGraceful
:
4514 result
= (int)processed
;
4522 # elif defined(HAVE_SSPISSL)
4523 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
4524 # endif /* HAVE_LIBSSL */
4526 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4528 return ((int)result
);
4530 #endif /* HAVE_SSL */
4534 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".