]> git.ipfire.org Git - thirdparty/cups.git/blobdiff - cups/http.c
Merge changes from CUPS 1.6svn-r9968.
[thirdparty/cups.git] / cups / http.c
index a83fc20ccdccd7c59ffeee35ee2553c6c2085fc7..c5489e71b71ad00384f71a3e8fea0fcc47dbc737 100644 (file)
@@ -3,7 +3,7 @@
  *
  *   HTTP routines for CUPS.
  *
- *   Copyright 2007-2010 by Apple Inc.
+ *   Copyright 2007-2011 by Apple Inc.
  *   Copyright 1997-2007 by Easy Software Products, all rights reserved.
  *
  *   This file contains Kerberos support code, copyright 2006 by
  *
  * Contents:
  *
- *   _httpBIOMethods()    - Get the OpenSSL BIO methods for HTTP connections.
- *   httpBlocking()       - Set blocking/non-blocking behavior on a connection.
- *   httpCheck()          - Check to see if there is a pending response from the
- *                          server.
- *   httpClearCookie()    - Clear the cookie value(s).
- *   httpClearFields()    - Clear HTTP request fields.
- *   httpClose()          - Close an HTTP connection.
- *   httpConnect()        - Connect to a HTTP server.
- *   httpConnectEncrypt() - Connect to a HTTP server using encryption.
- *   _httpCreate()        - Create an unconnected HTTP connection.
- *   httpDelete()         - Send a DELETE request to the server.
- *   _httpDisconnect()    - Disconnect a HTTP connection.
- *   httpEncryption()     - Set the required encryption on the link.
- *   httpError()          - Get the last error on a connection.
- *   httpFlush()          - Flush data from a HTTP connection.
- *   httpFlushWrite()     - Flush data in write buffer.
- *   httpGet()            - Send a GET request to the server.
- *   httpGetAuthString()  - Get the current authorization string.
- *   httpGetBlocking()    - Get the blocking/non-block state of a connection.
- *   httpGetCookie()      - Get any cookie data from the response.
- *   httpGetFd()          - Get the file descriptor associated with a
- *                          connection.
- *   httpGetField()       - Get a field value from a request/response.
- *   httpGetLength()      - Get the amount of data remaining from the
- *                          content-length or transfer-encoding fields.
- *   httpGetLength2()     - Get the amount of data remaining from the
- *                          content-length or transfer-encoding fields.
- *   httpGetStatus()      - Get the status of the last HTTP request.
- *   httpGetSubField()    - Get a sub-field value.
- *   httpGetSubField2()   - Get a sub-field value.
- *   httpGets()           - Get a line of text from a HTTP connection.
- *   httpHead()           - Send a HEAD request to the server.
- *   httpInitialize()     - Initialize the HTTP interface library and set the
- *                          default HTTP proxy (if any).
- *   httpOptions()        - Send an OPTIONS request to the server.
- *   _httpPeek()          - Peek at data from a HTTP connection.
- *   httpPost()           - Send a POST request to the server.
- *   httpPrintf()         - Print a formatted string to a HTTP connection.
- *   httpPut()            - Send a PUT request to the server.
- *   httpRead()           - Read data from a HTTP connection.
- *   httpRead2()          - Read data from a HTTP connection.
- *   _httpReadCDSA()      - Read function for the CDSA library.
- *   _httpReadGNUTLS()    - Read function for the GNU TLS library.
- *   httpReconnect()      - Reconnect to a HTTP server.
- *   httpSetAuthString()  - Set the current authorization string.
- *   httpSetCookie()      - Set the cookie value(s).
- *   httpSetExpect()      - Set the Expect: header in a request.
- *   httpSetField()       - Set the value of an HTTP header.
- *   httpSetLength()      - Set the content-length and content-encoding.
- *   httpTrace()          - Send an TRACE request to the server.
- *   httpUpdate()         - Update the current HTTP state for incoming data.
- *   _httpWait()          - Wait for data available on a connection (no flush).
- *   httpWait()           - Wait for data available on a connection.
- *   httpWrite()          - Write data to a HTTP connection.
- *   httpWrite2()         - Write data to a HTTP connection.
- *   _httpWriteCDSA()     - Write function for the CDSA library.
- *   _httpWriteGNUTLS()   - Write function for the GNU TLS library.
- *   http_bio_ctrl()      - Control the HTTP connection.
- *   http_bio_free()      - Free OpenSSL data.
- *   http_bio_new()       - Initialize an OpenSSL BIO structure.
- *   http_bio_puts()      - Send a string for OpenSSL.
- *   http_bio_read()      - Read data for OpenSSL.
- *   http_bio_write()     - Write data for OpenSSL.
- *   http_debug_hex()     - Do a hex dump of a buffer.
- *   http_field()         - Return the field index for a field name.
- *   http_read_ssl()      - Read from a SSL/TLS connection.
- *   http_locking_cb()    - Lock/unlock a thread's mutex.
- *   http_send()          - Send a request with all fields and the trailing
- *                          blank line.
- *   http_setup_ssl()     - Set up SSL/TLS support on a connection.
- *   http_shutdown_ssl()  - Shut down SSL/TLS on a connection.
- *   http_threadid_cb()   - Return the current thread ID.
- *   http_upgrade()       - Force upgrade to TLS encryption.
- *   http_write()         - Write a buffer to a HTTP connection.
- *   http_write_chunk()   - Write a chunked buffer.
- *   http_write_ssl()     - Write to a SSL/TLS connection.
+ *   httpAddCredential()       - Allocates and adds a single credential to an
+ *                               array.
+ *   _httpBIOMethods()         - Get the OpenSSL BIO methods for HTTP
+ *                               connections.
+ *   httpBlocking()            - Set blocking/non-blocking behavior on a
+ *                               connection.
+ *   httpCheck()               - Check to see if there is a pending response
+ *                               from the server.
+ *   httpClearCookie()         - Clear the cookie value(s).
+ *   httpClearFields()         - Clear HTTP request fields.
+ *   httpClose()               - Close an HTTP connection.
+ *   httpConnect()             - Connect to a HTTP server.
+ *   httpConnectEncrypt()      - Connect to a HTTP server using encryption.
+ *   httpCopyCredentials()     - Copy the credentials associated with an
+ *                               encrypted connection.
+ *   _httpCreate()             - Create an unconnected HTTP connection.
+ *   _httpCreateCredentials()  - Create credentials in the internal format.
+ *   httpDelete()              - Send a DELETE request to the server.
+ *   _httpDisconnect()         - Disconnect a HTTP connection.
+ *   httpEncryption()          - Set the required encryption on the link.
+ *   httpError()               - Get the last error on a connection.
+ *   httpFlush()               - Flush data from a HTTP connection.
+ *   httpFlushWrite()          - Flush data in write buffer.
+ *   _httpFreeCredentials()    - Free internal credentials.
+ *   httpFreeCredentials()     - Free an array of credentials.
+ *   httpGet()                 - Send a GET request to the server.
+ *   httpGetAuthString()       - Get the current authorization string.
+ *   httpGetBlocking()         - Get the blocking/non-block state of a
+ *                               connection.
+ *   httpGetCookie()           - Get any cookie data from the response.
+ *   httpGetFd()               - Get the file descriptor associated with a
+ *                               connection.
+ *   httpGetField()            - Get a field value from a request/response.
+ *   httpGetLength()           - Get the amount of data remaining from the
+ *                               content-length or transfer-encoding fields.
+ *   httpGetLength2()          - Get the amount of data remaining from the
+ *                               content-length or transfer-encoding fields.
+ *   httpGetStatus()           - Get the status of the last HTTP request.
+ *   httpGetSubField()         - Get a sub-field value.
+ *   httpGetSubField2()        - Get a sub-field value.
+ *   httpGets()                - Get a line of text from a HTTP connection.
+ *   httpHead()                - Send a HEAD request to the server.
+ *   httpInitialize()          - Initialize the HTTP interface library and set
+ *                               the default HTTP proxy (if any).
+ *   httpOptions()             - Send an OPTIONS request to the server.
+ *   _httpPeek()               - Peek at data from a HTTP connection.
+ *   httpPost()                - Send a POST request to the server.
+ *   httpPrintf()              - Print a formatted string to a HTTP connection.
+ *   httpPut()                 - Send a PUT request to the server.
+ *   httpRead()                - Read data from a HTTP connection.
+ *   httpRead2()               - Read data from a HTTP connection.
+ *   _httpReadCDSA()           - Read function for the CDSA library.
+ *   _httpReadGNUTLS()         - Read function for the GNU TLS library.
+ *   httpReconnect()           - Reconnect to a HTTP server.
+ *   httpSetAuthString()       - Set the current authorization string.
+ *   httpSetCredentials()      - Set the credentials associated with an
+ *                               encrypted connection.
+ *   httpSetCookie()           - Set the cookie value(s).
+ *   httpSetExpect()           - Set the Expect: header in a request.
+ *   httpSetField()            - Set the value of an HTTP header.
+ *   httpSetLength()           - Set the content-length and content-encoding.
+ *   httpSetTimeout()          - Set read/write timeouts and an optional
+ *                               callback.
+ *   httpTrace()               - Send an TRACE request to the server.
+ *   _httpUpdate()             - Update the current HTTP status for incoming
+ *                               data.
+ *   httpUpdate()              - Update the current HTTP state for incoming
+ *                               data.
+ *   _httpWait()               - Wait for data available on a connection (no
+ *                               flush).
+ *   httpWait()                - Wait for data available on a connection.
+ *   httpWrite()               - Write data to a HTTP connection.
+ *   httpWrite2()              - Write data to a HTTP connection.
+ *   _httpWriteCDSA()          - Write function for the CDSA library.
+ *   _httpWriteGNUTLS()        - Write function for the GNU TLS library.
+ *   http_bio_ctrl()           - Control the HTTP connection.
+ *   http_bio_free()           - Free OpenSSL data.
+ *   http_bio_new()            - Initialize an OpenSSL BIO structure.
+ *   http_bio_puts()           - Send a string for OpenSSL.
+ *   http_bio_read()           - Read data for OpenSSL.
+ *   http_bio_write()          - Write data for OpenSSL.
+ *   http_debug_hex()          - Do a hex dump of a buffer.
+ *   http_field()              - Return the field index for a field name.
+ *   http_read_ssl()           - Read from a SSL/TLS connection.
+ *   http_locking_cb()         - Lock/unlock a thread's mutex.
+ *   http_send()               - Send a request with all fields and the trailing
+ *                               blank line.
+ *   http_set_credentials()    - Set the SSL/TLS credentials.
+ *   http_set_timeout()        - Set the socket timeout values.
+ *   http_set_wait()           - Set the default wait value for reads.
+ *   http_setup_ssl()          - Set up SSL/TLS support on a connection.
+ *   http_shutdown_ssl()       - Shut down SSL/TLS on a connection.
+ *   http_threadid_cb()        - Return the current thread ID.
+ *   http_upgrade()            - Force upgrade to TLS encryption.
+ *   http_write()              - Write a buffer to a HTTP connection.
+ *   http_write_chunk()        - Write a chunked buffer.
+ *   http_write_ssl()          - Write to a SSL/TLS connection.
  */
 
 /*
@@ -142,23 +163,15 @@ static int                http_write_chunk(http_t *http, const char *buffer,
                                         int length);
 #ifdef HAVE_SSL
 static int             http_read_ssl(http_t *http, char *buf, int len);
+#  if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
+static int             http_set_credentials(http_t *http);
+#  endif /* HAVE_CDSASSL ** HAVE_SECCERTIFICATECOPYDATA */
+static void            http_set_timeout(int fd, double timeout);
+static void            http_set_wait(http_t *http);
 static int             http_setup_ssl(http_t *http);
 static void            http_shutdown_ssl(http_t *http);
 static int             http_upgrade(http_t *http);
 static int             http_write_ssl(http_t *http, const char *buf, int len);
-
-#  ifdef HAVE_GNUTLS
-#    ifdef HAVE_PTHREAD_H
-GCRY_THREAD_OPTION_PTHREAD_IMPL;
-#    endif /* HAVE_PTHREAD_H */
-
-#  elif defined(HAVE_LIBSSL)
-static _cups_mutex_t   *http_locks;    /* OpenSSL lock mutexes */
-
-static void            http_locking_cb(int mode, int type, const char *file,
-                                       int line);
-static unsigned long   http_threadid_cb(void);
-#  endif /* HAVE_GNUTLS */
 #endif /* HAVE_SSL */
 
 
@@ -242,8 +255,45 @@ static BIO_METHOD  http_bio_methods =
                          http_bio_free,
                          NULL,
                        };
+#endif /* HAVE_SSL && HAVE_LIBSSL */
+
+
+/*
+ * 'httpAddCredential()' - Allocates and adds a single credential to an array.
+ *
+ * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
+ *
+ * @since CUPS 1.5/Mac OS X 10.7@
+ */
+
+int                                    /* O - 0 on success, -1 on error */
+httpAddCredential(
+    cups_array_t *credentials,         /* I - Credentials array */
+    const void   *data,                        /* I - PEM-encoded X.509 data */
+    size_t       datalen)              /* I - Length of data */
+{
+  http_credential_t    *credential;    /* Credential data */
+
+
+  if ((credential = malloc(sizeof(http_credential_t))) != NULL)
+  {
+    credential->datalen = datalen;
+
+    if ((credential->data = malloc(datalen)) != NULL)
+    {
+      memcpy(credential->data, data, datalen);
+      cupsArrayAdd(credentials, credential);
+      return (0);
+    }
+
+    free(credential);
+  }
+
+  return (-1);
+}
 
 
+#if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
 /*
  * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
  */
@@ -265,7 +315,10 @@ httpBlocking(http_t *http,         /* I - Connection to server */
              int    b)                 /* I - 1 = blocking, 0 = non-blocking */
 {
   if (http)
+  {
     http->blocking = b;
+    http_set_wait(http);
+  }
 }
 
 
@@ -420,7 +473,7 @@ httpConnectEncrypt(
   * Create the HTTP structure...
   */
 
-  if ((http = _httpCreate(host, port, encryption)) == NULL)
+  if ((http = _httpCreate(host, port, NULL, encryption, AF_UNSPEC)) == NULL)
     return (NULL);
 
  /*
@@ -442,6 +495,74 @@ httpConnectEncrypt(
 }
 
 
+/*
+ * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
+ *                          connection.
+ *
+ * @since CUPS 1.5/Mac OS X 10.7@
+ */
+
+int                                    /* O - Status of call (0 = success) */
+httpCopyCredentials(
+    http_t      *http,                 /* I - Connection to server */
+    cups_array_t **credentials)                /* O - Array of credentials */
+{
+#  ifdef HAVE_LIBSSL
+#  elif defined(HAVE_GNUTLS)
+#  elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
+  OSStatus             error;          /* Error code */
+  CFIndex              count;          /* Number of credentials */
+  CFArrayRef           peerCerts;      /* Peer certificates */
+  SecCertificateRef    secCert;        /* Certificate reference */
+  CFDataRef            data;           /* Certificate data */
+  int                  i;              /* Looping var */
+#  elif defined(HAVE_SSPISSL)
+#  endif /* HAVE_LIBSSL */
+
+
+  if (credentials)
+    *credentials = NULL;
+
+  if (!http || !http->tls || !credentials)
+    return (-1);
+
+#  ifdef HAVE_LIBSSL
+  return (-1);
+
+#  elif defined(HAVE_GNUTLS)
+  return (-1);
+
+#  elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
+  if (!(error = SSLCopyPeerCertificates(http->tls, &peerCerts)) && peerCerts)
+  {
+    if ((*credentials = cupsArrayNew(NULL, NULL)) != NULL)
+    {
+      for (i = 0, count = CFArrayGetCount(peerCerts); i < count; i++)
+      {
+       secCert = (SecCertificateRef)CFArrayGetValueAtIndex(peerCerts, i);
+       if ((data = SecCertificateCopyData(secCert)))
+       {
+         httpAddCredential(*credentials, CFDataGetBytePtr(data),
+                           CFDataGetLength(data));
+         CFRelease(data);
+       }
+      }
+    }
+
+    CFRelease(peerCerts);
+  }
+
+  return (error);
+
+#  elif defined(HAVE_SSPISSL)
+  return (-1);
+
+#  else
+  return (-1);
+#  endif /* HAVE_LIBSSL */
+}
+
+
 /*
  * '_httpCreate()' - Create an unconnected HTTP connection.
  */
@@ -450,11 +571,12 @@ http_t *                          /* O - HTTP connection */
 _httpCreate(
     const char        *host,           /* I - Hostname */
     int               port,            /* I - Port number */
-    http_encryption_t encryption)      /* I - Encryption to use */
+    http_addrlist_t   *addrlist,       /* I - Address list or NULL */
+    http_encryption_t encryption,      /* I - Encryption to use */
+    int               family)          /* I - Address family or AF_UNSPEC */
 {
-  http_t               *http;          /* New HTTP connection */
-  http_addrlist_t      *addrlist;      /* Host address data */
-  char                 service[255];   /* Service name */
+  http_t       *http;                  /* New HTTP connection */
+  char         service[255];           /* Service name */
 
 
   DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
@@ -471,8 +593,9 @@ _httpCreate(
 
   sprintf(service, "%d", port);
 
-  if ((addrlist = httpAddrGetList(host, AF_UNSPEC, service)) == NULL)
-    return (NULL);
+  if (!addrlist)
+    if ((addrlist = httpAddrGetList(host, family, service)) == NULL)
+      return (NULL);
 
  /*
   * Allocate memory for the structure...
@@ -505,6 +628,8 @@ _httpCreate(
   else
     http->encryption = encryption;
 
+  http_set_wait(http);
+
  /*
   * Return the new structure...
   */
@@ -513,6 +638,64 @@ _httpCreate(
 }
 
 
+/*
+ * '_httpCreateCredentials()' - Create credentials in the internal format.
+ */
+
+http_tls_credentials_t                 /* O - Internal credentials */
+_httpCreateCredentials(
+    cups_array_t *credentials)         /* I - Array of credentials */
+{
+  if (!credentials)
+    return (NULL);
+
+#  ifdef HAVE_LIBSSL
+  return (NULL);
+
+#  elif defined(HAVE_GNUTLS)
+  return (NULL);
+
+#  elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
+  CFMutableArrayRef    peerCerts;      /* Peer credentials reference */
+  SecCertificateRef    secCert;        /* Certificate reference */
+  CFDataRef            data;           /* Credential data reference */
+  http_credential_t    *credential;    /* Credential data */
+
+
+  if ((peerCerts = CFArrayCreateMutable(kCFAllocatorDefault,
+                                       cupsArrayCount(credentials),
+                                       &kCFTypeArrayCallBacks)) == NULL)
+    return (NULL);
+
+  for (credential = (http_credential_t *)cupsArrayFirst(credentials);
+       credential;
+       credential = (http_credential_t *)cupsArrayNext(credentials))
+  {
+    if ((data = CFDataCreate(kCFAllocatorDefault, credential->data,
+                            credential->datalen)))
+    {
+      if ((secCert = SecCertificateCreateWithData(kCFAllocatorDefault, data))
+              != NULL)
+      {
+       CFArrayAppendValue(peerCerts, secCert);
+       CFRelease(secCert);
+      }
+
+      CFRelease(data);
+    }
+  }
+
+  return (peerCerts);
+
+#  elif defined(HAVE_SSPISSL)
+  return (NULL);
+
+#  else
+  return (NULL);
+#  endif /* HAVE_LIBSSL */
+}
+
+
 /*
  * 'httpDelete()' - Send a DELETE request to the server.
  */
@@ -681,12 +864,63 @@ httpFlushWrite(http_t *http)              /* I - Connection to server */
 
   http->wused = 0;
 
-  DEBUG_printf(("1httpFlushWrite: Returning %d.", bytes));
+  DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes, errno));
 
   return (bytes);
 }
 
 
+/*
+ * '_httpFreeCredentials()' - Free internal credentials.
+ */
+
+void
+_httpFreeCredentials(
+    http_tls_credentials_t credentials)        /* I - Internal credentials */
+{
+  if (!credentials)
+    return;
+
+#ifdef HAVE_LIBSSL
+  (void)credentials;
+
+#elif defined(HAVE_GNUTLS)
+  (void)credentials;
+
+#elif defined(HAVE_CDSASSL)
+  CFRelease(credentials);
+
+#elif defined(HAVE_SSPISSL)
+  (void)credentials;
+
+#endif /* HAVE_LIBSSL */
+}
+
+
+/*
+ * 'httpFreeCredentials()' - Free an array of credentials.
+ */
+
+void
+httpFreeCredentials(
+    cups_array_t *credentials)         /* I - Array of credentials */
+{
+  http_credential_t    *credential;    /* Credential */
+
+
+  for (credential = (http_credential_t *)cupsArrayFirst(credentials);
+       credential;
+       credential = (http_credential_t *)cupsArrayNext(credentials))
+  {
+    cupsArrayRemove(credentials, credential);
+    free((void *)credential->data);
+    free(credential);
+  }
+
+  cupsArrayDelete(credentials);
+}
+
+
 /*
  * 'httpGet()' - Send a GET request to the server.
  */
@@ -831,7 +1065,7 @@ httpGetLength2(http_t *http)               /* I - Connection to server */
   if (!http)
     return (-1);
 
-  if (!strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked"))
+  if (!_cups_strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked"))
   {
     DEBUG_puts("4httpGetLength2: chunked request!");
 
@@ -941,7 +1175,7 @@ httpGetSubField2(http_t       *http,       /* I - Connection to server */
     * Skip leading whitespace...
     */
 
-    while (isspace(*fptr & 255))
+    while (_cups_isspace(*fptr))
       fptr ++;
 
     if (*fptr == ',')
@@ -955,7 +1189,7 @@ httpGetSubField2(http_t       *http,       /* I - Connection to server */
     */
 
     for (ptr = temp;
-         *fptr && *fptr != '=' && !isspace(*fptr & 255) &&
+         *fptr && *fptr != '=' && !_cups_isspace(*fptr) &&
             ptr < (temp + sizeof(temp) - 1);
          *ptr++ = *fptr++);
 
@@ -967,7 +1201,7 @@ httpGetSubField2(http_t       *http,       /* I - Connection to server */
     * Skip trailing chars up to the '='...
     */
 
-    while (isspace(*fptr & 255))
+    while (_cups_isspace(*fptr))
       fptr ++;
 
     if (!*fptr)
@@ -982,7 +1216,7 @@ httpGetSubField2(http_t       *http,       /* I - Connection to server */
 
     fptr ++;
 
-    while (isspace(*fptr & 255))
+    while (_cups_isspace(*fptr))
       fptr ++;
 
     if (*fptr == '\"')
@@ -1010,12 +1244,12 @@ httpGetSubField2(http_t       *http,    /* I - Connection to server */
       */
 
       for (ptr = value;
-           *fptr && !isspace(*fptr & 255) && *fptr != ',' && ptr < end;
+           *fptr && !_cups_isspace(*fptr) && *fptr != ',' && ptr < end;
           *ptr++ = *fptr++);
 
       *ptr = '\0';
 
-      while (*fptr && !isspace(*fptr & 255) && *fptr != ',')
+      while (*fptr && !_cups_isspace(*fptr) && *fptr != ',')
         fptr ++;
     }
 
@@ -1089,8 +1323,11 @@ httpGets(char   *line,                   /* I - Line to read into */
       * No newline; see if there is more data to be read...
       */
 
-      if (!http->blocking && !_httpWait(http, 10000, 1))
+      while (!_httpWait(http, http->wait_value, 1))
       {
+       if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+         continue;
+
         DEBUG_puts("3httpGets: Timed out!");
 #ifdef WIN32
         http->error = WSAETIMEDOUT;
@@ -1120,8 +1357,15 @@ httpGets(char   *line,                   /* I - Line to read into */
 #ifdef WIN32
         DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
 
-        if (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK)
+        if (WSAGetLastError() == WSAEINTR)
          continue;
+       else if (WSAGetLastError() == WSAEWOULDBLOCK)
+       {
+         if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+           continue;
+
+         http->error = WSAGetLastError();
+       }
        else if (WSAGetLastError() != http->error)
        {
          http->error = WSAGetLastError();
@@ -1131,8 +1375,17 @@ httpGets(char   *line,                   /* I - Line to read into */
 #else
         DEBUG_printf(("3httpGets: recv() error %d!", errno));
 
-        if (errno == EINTR || errno == EAGAIN)
+        if (errno == EINTR)
          continue;
+       else if (errno == EWOULDBLOCK || errno == EAGAIN)
+       {
+         if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+           continue;
+         else if (!http->timeout_cb && errno == EAGAIN)
+           continue;
+
+         http->error = errno;
+       }
        else if (errno != http->error)
        {
          http->error = errno;
@@ -1240,7 +1493,7 @@ httpInitialize(void)
   }
 
 #ifdef WIN32
-  WSAStartup(MAKEWORD(1,1), &winsockdata);
+  WSAStartup(MAKEWORD(2,2), &winsockdata);
 
 #elif !defined(SO_NOSIGPIPE)
  /*
@@ -1264,14 +1517,6 @@ httpInitialize(void)
 #endif /* WIN32 */
 
 #ifdef HAVE_GNUTLS
- /*
-  * Make sure we handle threading properly...
-  */
-
-#  ifdef HAVE_PTHREAD_H
-  gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
-#  endif /* HAVE_PTHREAD_H */
-
  /*
   * Initialize GNU TLS...
   */
@@ -1286,19 +1531,6 @@ httpInitialize(void)
   SSL_load_error_strings();
   SSL_library_init();
 
- /*
-  * Set the threading callbacks...
-  */
-
-  http_locks = calloc(CRYPTO_num_locks(), sizeof(_cups_mutex_t));
-#  ifdef HAVE_PTHREAD_H
-  for (i = 0; i < CRYPTO_num_locks(); i ++)
-    pthread_mutex_init(http_locks + i, NULL);
-#  endif /* HAVE_PTHREAD_H */
-
-  CRYPTO_set_id_callback(http_threadid_cb);
-  CRYPTO_set_locking_callback(http_locking_cb);
-
  /*
   * Using the current time is a dubious random seed, but on some systems
   * it is the best we can do (on others, this seed isn't even used...)
@@ -1414,8 +1646,16 @@ _httpPeek(http_t *http,                  /* I - Connection to server */
     * Buffer small reads for better performance...
     */
 
-    if (!http->blocking && !httpWait(http, 10000))
-      return (0);
+    if (!http->blocking)
+    {
+      while (!httpWait(http, http->wait_value))
+      {
+       if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+         continue;
+
+       return (0);
+      }
+    }
 
     if (http->data_remaining > sizeof(http->buffer))
       bytes = sizeof(http->buffer);
@@ -1670,8 +1910,16 @@ httpRead2(http_t *http,                  /* I - Connection to server */
     * Buffer small reads for better performance...
     */
 
-    if (!http->blocking && !httpWait(http, 10000))
-      return (0);
+    if (!http->blocking)
+    {
+      while (!httpWait(http, http->wait_value))
+      {
+       if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+         continue;
+
+       return (0);
+      }
+    }
 
     if (http->data_remaining > sizeof(http->buffer))
       bytes = sizeof(http->buffer);
@@ -1698,13 +1946,34 @@ httpRead2(http_t *http,                 /* I - Connection to server */
     else if (bytes < 0)
     {
 #ifdef WIN32
-      if (WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK)
+      if (WSAGetLastError() != WSAEINTR)
       {
         http->error = WSAGetLastError();
         return (-1);
       }
+      else if (WSAGetLastError() == WSAEWOULDBLOCK)
+      {
+        if (!http->timeout_cb || !(*http->timeout_cb)(http, http->timeout_data))
+       {
+         http->error = WSAEWOULDBLOCK;
+         return (-1);
+       }
+      }
 #else
-      if (errno != EINTR && errno != EAGAIN)
+      if (errno == EWOULDBLOCK || errno == EAGAIN)
+      {
+        if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
+       {
+         http->error = errno;
+         return (-1);
+       }
+       else if (!http->timeout_cb && errno != EAGAIN)
+       {
+         http->error = errno;
+         return (-1);
+       }
+      }
+      else if (errno != EINTR)
       {
         http->error = errno;
         return (-1);
@@ -1737,28 +2006,60 @@ httpRead2(http_t *http,                 /* I - Connection to server */
 #ifdef HAVE_SSL
   else if (http->tls)
   {
-    if (!http->blocking && !httpWait(http, 10000))
-      return (0);
+    if (!http->blocking)
+    {
+      while (!httpWait(http, http->wait_value))
+      {
+       if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+         continue;
+
+       return (0);
+      }
+    }
 
     bytes = (ssize_t)http_read_ssl(http, buffer, (int)length);
   }
 #endif /* HAVE_SSL */
   else
   {
-    if (!http->blocking && !httpWait(http, 10000))
-      return (0);
+    if (!http->blocking)
+    {
+      while (!httpWait(http, http->wait_value))
+      {
+       if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+         continue;
+
+       return (0);
+      }
+    }
 
     DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT " bytes from socket...",
                   CUPS_LLCAST length));
 
 #ifdef WIN32
-    while ((bytes = (ssize_t) recv(http->fd, buffer, (int)length, 0)) < 0)
-      if (WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK)
+    while ((bytes = (ssize_t)recv(http->fd, buffer, (int)length, 0)) < 0)
+    {
+      if (WSAGetLastError() == WSAEWOULDBLOCK)
+      {
+        if (!http->timeout_cb || !(*http->timeout_cb)(http, http->timeout_data))
+         break;
+      }
+      else if (WSAGetLastError() != WSAEINTR)
         break;
+    }
 #else
     while ((bytes = recv(http->fd, buffer, length, 0)) < 0)
-      if (errno != EINTR && errno != EAGAIN)
+    {
+      if (errno == EWOULDBLOCK || errno == EAGAIN)
+      {
+        if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
+         break;
+        else if (!http->timeout_cb && errno != EAGAIN)
+         break;
+      }
+      else if (errno != EINTR)
         break;
+    }
 #endif /* WIN32 */
 
     DEBUG_printf(("2httpRead2: read " CUPS_LLFMT " bytes from socket...",
@@ -1777,12 +2078,12 @@ httpRead2(http_t *http,                 /* I - Connection to server */
   else if (bytes < 0)
   {
 #ifdef WIN32
-    if (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK)
+    if (WSAGetLastError() == WSAEINTR)
       bytes = 0;
     else
       http->error = WSAGetLastError();
 #else
-    if (errno == EINTR || errno == EAGAIN)
+    if (errno == EINTR || (errno == EAGAIN && !http->timeout_cb))
       bytes = 0;
     else
       http->error = errno;
@@ -1840,8 +2141,11 @@ _httpReadCDSA(
     * Make sure we have data before we read...
     */
 
-    if (!_httpWait(http, 10000, 0))
+    while (!_httpWait(http, http->wait_value, 0))
     {
+      if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+       continue;
+
       http->error = ETIMEDOUT;
       return (-1);
     }
@@ -1891,8 +2195,11 @@ _httpReadGNUTLS(
     size_t               length)       /* I - Number of bytes to read */
 {
   http_t       *http;                  /* HTTP connection */
+  ssize_t      bytes;                  /* Bytes read */
 
 
+  DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr, data, (int)length));
+
   http = (http_t *)ptr;
 
   if (!http->blocking)
@@ -1901,14 +2208,19 @@ _httpReadGNUTLS(
     * Make sure we have data before we read...
     */
 
-    if (!_httpWait(http, 10000, 0))
+    while (!_httpWait(http, http->wait_value, 0))
     {
+      if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+       continue;
+
       http->error = ETIMEDOUT;
       return (-1);
     }
   }
 
-  return (recv(http->fd, data, length, 0));
+  bytes = recv(http->fd, data, length, 0);
+  DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes));
+  return (bytes);
 }
 #endif /* HAVE_SSL && HAVE_GNUTLS */
 
@@ -1989,6 +2301,9 @@ httpReconnect(http_t *http)               /* I - Connection to server */
 
   DEBUG_printf(("2httpReconnect: New socket=%d", http->fd));
 
+  if (http->timeout_value > 0)
+    http_set_timeout(http->fd, http->timeout_value);
+
   http->hostaddr = &(addr->addr);
   http->error    = 0;
   http->status   = HTTP_CONTINUE;
@@ -2084,6 +2399,28 @@ httpSetAuthString(http_t     *http,      /* I - Connection to server */
 }
 
 
+/*
+ * 'httpSetCredentials()' - Set the credentials associated with an encrypted
+ *                         connection.
+ *
+ * @since CUPS 1.5/Mac OS X 10.7@
+ */
+
+int                                            /* O - Status of call (0 = success) */
+httpSetCredentials(http_t      *http,          /* I - Connection to server */
+                  cups_array_t *credentials)   /* I - Array of credentials */
+{
+  if (!http || cupsArrayCount(credentials) < 1)
+    return (-1);
+
+  _httpFreeCredentials(http->tls_credentials);
+
+  http->tls_credentials = _httpCreateCredentials(credentials);
+
+  return (http->tls_credentials ? 0 : -1);
+}
+
+
 /*
  * 'httpSetCookie()' - Set the cookie value(s).
  *
@@ -2221,6 +2558,37 @@ httpSetLength(http_t *http,              /* I - Connection to server */
 }
 
 
+/*
+ * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
+ *
+ * The optional timeout callback receives both the HTTP connection and a user
+ * data pointer and must return 1 to continue or 0 to error (time) out.
+ *
+ * @since CUPS 1.5/Mac OS X 10.7@
+ */
+
+void
+httpSetTimeout(
+    http_t            *http,           /* I - Connection to server */
+    double            timeout,         /* I - Number of seconds for timeout,
+                                               must be greater than 0 */
+    http_timeout_cb_t cb,              /* I - Callback function or NULL */
+    void              *user_data)      /* I - User data pointer */
+{
+  if (!http || timeout <= 0.0)
+    return;
+
+  http->timeout_cb    = cb;
+  http->timeout_data  = user_data;
+  http->timeout_value = timeout;
+
+  if (http->fd >= 0)
+    http_set_timeout(http->fd, timeout);
+
+  http_set_wait(http);
+}
+
+
 /*
  * 'httpTrace()' - Send an TRACE request to the server.
  */
@@ -2234,162 +2602,201 @@ httpTrace(http_t     *http,           /* I - Connection to server */
 
 
 /*
- * 'httpUpdate()' - Update the current HTTP state for incoming data.
+ * '_httpUpdate()' - Update the current HTTP status for incoming data.
+ *
+ * Note: Unlike httpUpdate(), this function does not flush pending write data
+ * and only retrieves a single status line from the HTTP connection.
  */
 
-http_status_t                          /* O - HTTP status */
-httpUpdate(http_t *http)               /* I - Connection to server */
+int                                    /* O - 1 to continue, 0 to stop */
+_httpUpdate(http_t        *http,       /* I - Connection to server */
+            http_status_t *status)     /* O - Current HTTP status */
 {
   char         line[32768],            /* Line from connection... */
                *value;                 /* Pointer to value on line */
   http_field_t field;                  /* Field index */
-  int          major, minor,           /* HTTP version numbers */
-               status;                 /* Request status */
+  int          major, minor;           /* HTTP version numbers */
 
 
-  DEBUG_printf(("httpUpdate(http=%p), state=%s", http,
+  DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http, status,
                 http_states[http->state]));
 
  /*
-  * Flush pending data, if any...
+  * Grab a single line from the connection...
   */
 
-  if (http->wused)
+  if (!httpGets(line, sizeof(line), http))
   {
-    DEBUG_puts("2httpUpdate: flushing buffer...");
-
-    if (httpFlushWrite(http) < 0)
-      return (HTTP_ERROR);
+    *status = HTTP_ERROR;
+    return (0);
   }
 
- /*
-  * If we haven't issued any commands, then there is nothing to "update"...
-  */
+  DEBUG_printf(("2_httpUpdate: Got \"%s\"", line));
 
-  if (http->state == HTTP_WAITING)
-    return (HTTP_CONTINUE);
-
- /*
-  * Grab all of the lines we can from the connection...
-  */
-
-  while (httpGets(line, sizeof(line), http) != NULL)
+  if (line[0] == '\0')
   {
-    DEBUG_printf(("2httpUpdate: Got \"%s\"", line));
+   /*
+    * Blank line means the start of the data section (if any).  Return
+    * the result code, too...
+    *
+    * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
+    * Instead, we just return HTTP_CONTINUE to the caller and keep on
+    * tryin'...
+    */
 
-    if (line[0] == '\0')
+    if (http->status == HTTP_CONTINUE)
     {
-     /*
-      * Blank line means the start of the data section (if any).  Return
-      * the result code, too...
-      *
-      * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
-      * Instead, we just return HTTP_CONTINUE to the caller and keep on
-      * tryin'...
-      */
-
-      if (http->status == HTTP_CONTINUE)
-        return (http->status);
+      *status = http->status;
+      return (0);
+    }
 
-      if (http->status < HTTP_BAD_REQUEST)
-        http->digest_tries = 0;
+    if (http->status < HTTP_BAD_REQUEST)
+      http->digest_tries = 0;
 
 #ifdef HAVE_SSL
-      if (http->status == HTTP_SWITCHING_PROTOCOLS && !http->tls)
+    if (http->status == HTTP_SWITCHING_PROTOCOLS && !http->tls)
+    {
+      if (http_setup_ssl(http) != 0)
       {
-       if (http_setup_ssl(http) != 0)
-       {
 #  ifdef WIN32
-         closesocket(http->fd);
+       closesocket(http->fd);
 #  else
-         close(http->fd);
+       close(http->fd);
 #  endif /* WIN32 */
 
-         return (HTTP_ERROR);
-       }
-
-        return (HTTP_CONTINUE);
+       *status = http->status = HTTP_ERROR;
+       return (0);
       }
+
+      *status = HTTP_CONTINUE;
+      return (0);
+    }
 #endif /* HAVE_SSL */
 
-      httpGetLength2(http);
+    httpGetLength2(http);
 
-      switch (http->state)
-      {
-        case HTTP_GET :
-       case HTTP_POST :
-       case HTTP_POST_RECV :
-       case HTTP_PUT :
-           http->state ++;
-       case HTTP_POST_SEND :
-       case HTTP_HEAD :
-           break;
+    switch (http->state)
+    {
+      case HTTP_GET :
+      case HTTP_POST :
+      case HTTP_POST_RECV :
+      case HTTP_PUT :
+         http->state ++;
+      case HTTP_POST_SEND :
+      case HTTP_HEAD :
+         break;
 
-       default :
-           http->state = HTTP_WAITING;
-           break;
-      }
+      default :
+         http->state = HTTP_WAITING;
+         break;
+    }
 
-      return (http->status);
+    *status = http->status;
+    return (0);
+  }
+  else if (!strncmp(line, "HTTP/", 5))
+  {
+   /*
+    * Got the beginning of a response...
+    */
+
+    int        intstatus;                      /* Status value as an integer */
+
+    if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, &intstatus) != 3)
+    {
+      *status = http->status = HTTP_ERROR;
+      return (0);
     }
-    else if (!strncmp(line, "HTTP/", 5))
+
+    http->version = (http_version_t)(major * 100 + minor);
+    *status       = http->status = (http_status_t)intstatus;
+  }
+  else if ((value = strchr(line, ':')) != NULL)
+  {
+   /*
+    * Got a value...
+    */
+
+    *value++ = '\0';
+    while (_cups_isspace(*value))
+      value ++;
+
+   /*
+    * Be tolerants of servers that send unknown attribute fields...
+    */
+
+    if (!_cups_strcasecmp(line, "expect"))
     {
      /*
-      * Got the beginning of a response...
+      * "Expect: 100-continue" or similar...
       */
 
-      if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, &status) != 3)
-        return (HTTP_ERROR);
-
-      http->version = (http_version_t)(major * 100 + minor);
-      http->status  = (http_status_t)status;
+      http->expect = (http_status_t)atoi(value);
     }
-    else if ((value = strchr(line, ':')) != NULL)
+    else if (!_cups_strcasecmp(line, "cookie"))
     {
      /*
-      * Got a value...
+      * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
       */
 
-      *value++ = '\0';
-      while (isspace(*value & 255))
-        value ++;
+      httpSetCookie(http, value);
+    }
+    else if ((field = http_field(line)) != HTTP_FIELD_UNKNOWN)
+      httpSetField(http, field, value);
+#ifdef DEBUG
+    else
+      DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line));
+#endif /* DEBUG */
+  }
+  else
+  {
+    DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line));
+    *status = http->status = HTTP_ERROR;
+    return (0);
+  }
 
-     /*
-      * Be tolerants of servers that send unknown attribute fields...
-      */
+  return (1);
+}
 
-      if (!strcasecmp(line, "expect"))
-      {
-       /*
-        * "Expect: 100-continue" or similar...
-       */
 
-        http->expect = (http_status_t)atoi(value);
-      }
-      else if (!strcasecmp(line, "cookie"))
-      {
-       /*
-        * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
-       */
+/*
+ * 'httpUpdate()' - Update the current HTTP state for incoming data.
+ */
 
-        httpSetCookie(http, value);
-      }
-      else if ((field = http_field(line)) == HTTP_FIELD_UNKNOWN)
-      {
-        DEBUG_printf(("1httpUpdate: unknown field %s seen!", line));
-        continue;
-      }
-      else
-        httpSetField(http, field, value);
-    }
-    else
-    {
-      DEBUG_printf(("1httpUpdate: Bad response line \"%s\"!", line));
-      http->status = HTTP_ERROR;
+http_status_t                          /* O - HTTP status */
+httpUpdate(http_t *http)               /* I - Connection to server */
+{
+  http_status_t        status;                 /* Request status */
+
+
+  DEBUG_printf(("httpUpdate(http=%p), state=%s", http,
+                http_states[http->state]));
+
+ /*
+  * Flush pending data, if any...
+  */
+
+  if (http->wused)
+  {
+    DEBUG_puts("2httpUpdate: flushing buffer...");
+
+    if (httpFlushWrite(http) < 0)
       return (HTTP_ERROR);
-    }
   }
 
+ /*
+  * If we haven't issued any commands, then there is nothing to "update"...
+  */
+
+  if (http->state == HTTP_WAITING)
+    return (HTTP_CONTINUE);
+
+ /*
+  * Grab all of the lines we can from the connection...
+  */
+
+  while (_httpUpdate(http, &status));
+
  /*
   * See if there was an error...
   */
@@ -2409,10 +2816,10 @@ httpUpdate(http_t *http)                /* I - Connection to server */
   }
 
  /*
-  * If we haven't already returned, then there is nothing new...
+  * Return the current status...
   */
 
-  return (HTTP_CONTINUE);
+  return (status);
 }
 
 
@@ -2450,14 +2857,14 @@ _httpWait(http_t *http,                 /* I - Connection to server */
   if (http->tls && usessl)
   {
 #  ifdef HAVE_LIBSSL
-    if (SSL_pending((SSL *)(http->tls)))
+    if (SSL_pending(http->tls))
     {
       DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
       return (1);
     }
 
 #  elif defined(HAVE_GNUTLS)
-    if (gnutls_record_check_pending(((http_tls_t *)(http->tls))->session))
+    if (gnutls_record_check_pending(http->tls))
     {
       DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
       return (1);
@@ -2466,7 +2873,7 @@ _httpWait(http_t *http,                   /* I - Connection to server */
 #  elif defined(HAVE_CDSASSL)
     size_t bytes;                      /* Bytes that are available */
 
-    if (!SSLGetBufferedReadSize(((http_tls_t *)(http->tls))->session, &bytes) &&
+    if (!SSLGetBufferedReadSize(http->tls, &bytes) &&
         bytes > 0)
     {
       DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
@@ -2536,11 +2943,16 @@ httpWait(http_t *http,                  /* I - Connection to server */
   * First see if there is data in the buffer...
   */
 
+  DEBUG_printf(("2httpWait(http=%p, msec=%d)", http, msec));
+
   if (http == NULL)
     return (0);
 
   if (http->used)
+  {
+    DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
     return (1);
+  }
 
  /*
   * Flush pending data, if any...
@@ -2548,6 +2960,8 @@ httpWait(http_t *http,                    /* I - Connection to server */
 
   if (http->wused)
   {
+    DEBUG_puts("3httpWait: Flushing write buffer.");
+
     if (httpFlushWrite(http) < 0)
       return (0);
   }
@@ -2692,13 +3106,6 @@ httpWrite2(http_t     *http,             /* I - Connection to server */
       http->data_encoding  = HTTP_ENCODE_LENGTH;
       http->data_remaining = 0;
     }
-
-    if (http->state == HTTP_POST_RECV)
-      http->state ++;
-    else if (http->state == HTTP_PUT_RECV)
-      http->state = HTTP_STATUS;
-    else
-      http->state = HTTP_WAITING;
   }
 
   return (bytes);
@@ -2764,7 +3171,16 @@ _httpWriteGNUTLS(
     const void           *data,                /* I - Data buffer */
     size_t               length)       /* I - Number of bytes to write */
 {
-  return (send(((http_t *)ptr)->fd, data, length, 0));
+  ssize_t bytes;                       /* Bytes written */
+
+
+  DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr, data,
+                (int)length));
+  http_debug_hex("_httpWriteGNUTLS", data, (int)length);
+
+  bytes = send(((http_t *)ptr)->fd, data, length, 0);
+  DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes));
+  return (bytes);
 }
 #endif /* HAVE_SSL && HAVE_GNUTLS */
 
@@ -2885,8 +3301,11 @@ http_bio_read(BIO  *h,                   /* I - BIO data */
     * Make sure we have data before we read...
     */
 
-    if (!_httpWait(http, 10000, 0))
+    while (!_httpWait(http, http->wait_value, 0))
     {
+      if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+       continue;
+
 #ifdef WIN32
       http->error = WSAETIMEDOUT;
 #else
@@ -2983,7 +3402,7 @@ http_field(const char *name)              /* I - String name */
 
 
   for (i = 0; i < HTTP_FIELD_MAX; i ++)
-    if (strcasecmp(name, http_fields[i]) == 0)
+    if (_cups_strcasecmp(name, http_fields[i]) == 0)
       return ((http_field_t)i);
 
   return (HTTP_FIELD_UNKNOWN);
@@ -3007,7 +3426,7 @@ http_read_ssl(http_t *http,               /* I - Connection to server */
   ssize_t      result;                 /* Return value */
 
 
-  result = gnutls_record_recv(((http_tls_t *)(http->tls))->session, buf, len);
+  result = gnutls_record_recv(http->tls, buf, len);
 
   if (result < 0 && !errno)
   {
@@ -3041,16 +3460,14 @@ http_read_ssl(http_t *http,             /* I - Connection to server */
   size_t       processed;              /* Number of bytes processed */
 
 
-  error = SSLRead(((http_tls_t *)http->tls)->session, buf, len, &processed);
+  error = SSLRead(http->tls, buf, len, &processed);
 
   switch (error)
   {
     case 0 :
        result = (int)processed;
        break;
-    case errSSLClosedGraceful :
-       result = 0;
-       break;
+
     case errSSLWouldBlock :
        if (processed)
          result = (int)processed;
@@ -3060,9 +3477,16 @@ http_read_ssl(http_t *http,              /* I - Connection to server */
          errno = EINTR;
        }
        break;
+
+    case errSSLClosedGraceful :
     default :
-       errno = EPIPE;
-       result = -1;
+       if (processed)
+         result = (int)processed;
+       else
+       {
+         result = -1;
+         errno = EPIPE;
+       }
        break;
   }
 
@@ -3074,25 +3498,6 @@ http_read_ssl(http_t *http,              /* I - Connection to server */
 #endif /* HAVE_SSL */
 
 
-#ifdef HAVE_LIBSSL
-/*
- * 'http_locking_cb()' - Lock/unlock a thread's mutex.
- */
-
-static void
-http_locking_cb(int        mode,       /* I - Lock mode */
-               int        type,        /* I - Lock type */
-               const char *file,       /* I - Source file */
-               int        line)        /* I - Line number */
-{
-  if (mode & CRYPTO_LOCK)
-    _cupsMutexLock(http_locks + type);
-  else
-    _cupsMutexUnlock(http_locks + type);
-}
-#endif /* HAVE_LIBSSL */
-
-
 /*
  * 'http_send()' - Send a request with all fields and the trailing blank line.
  */
@@ -3248,35 +3653,199 @@ http_send(http_t       *http,  /* I - Connection to server */
 
 
 #ifdef HAVE_SSL
+#  if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
 /*
- * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
+ * 'http_set_credentials()' - Set the SSL/TLS credentials.
  */
 
 static int                             /* O - Status of connection */
+http_set_credentials(http_t *http)     /* I - Connection to server */
+{
+  _cups_globals_t *cg = _cupsGlobals();        /* Pointer to library globals */
+  OSStatus             error = 0;      /* Error code */
+  http_tls_credentials_t credentials = NULL;
+                                       /* TLS credentials */
+
+
+  DEBUG_printf(("7http_set_credentials(%p)", http));
+
+ /*
+  * Prefer connection specific credentials...
+  */
+
+  if ((credentials = http->tls_credentials) == NULL)
+    credentials = cg->tls_credentials;
+
+#    if HAVE_SECPOLICYCREATESSL
+ /*
+  * Otherwise root around in the user's keychain to see if one can be found...
+  */
+
+  if (!credentials)
+  {
+    CFDictionaryRef    query;          /* Query dictionary */
+    CFTypeRef          matches = NULL; /* Matching credentials */
+    CFArrayRef         dn_array = NULL;/* Distinguished names array */
+    CFTypeRef          keys[]   = { kSecClass,
+                                    kSecMatchLimit,
+                                    kSecReturnRef };
+                                       /* Keys for dictionary */
+    CFTypeRef          values[] = { kSecClassCertificate,
+                                    kSecMatchLimitOne,
+                                    kCFBooleanTrue };
+                                       /* Values for dictionary */
+
+   /*
+    * Get the names associated with the server.
+    */
+
+    if ((error = SSLCopyDistinguishedNames(http->tls, &dn_array)) != noErr)
+    {
+      DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
+                    (int)error));
+      return (error);
+    }
+
+   /*
+    * Create a query which will return all identities that can sign and match
+    * the passed in policy.
+    */
+
+    query = CFDictionaryCreate(NULL,
+                              (const void**)(&keys[0]),
+                              (const void**)(&values[0]),
+                              sizeof(keys) / sizeof(keys[0]),
+                              &kCFTypeDictionaryKeyCallBacks,
+                              &kCFTypeDictionaryValueCallBacks);
+    if (query)
+    {
+      error = SecItemCopyMatching(query, &matches);
+      DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
+                   (int)error));
+      CFRelease(query);
+    }
+
+    if (matches)
+      CFRelease(matches);
+
+    if (dn_array)
+      CFRelease(dn_array);
+  }
+#    endif /* HAVE_SECPOLICYCREATESSL */
+
+  if (credentials)
+  {
+    error = SSLSetCertificate(http->tls, credentials);
+    DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
+                 (int)error));
+  }
+  else
+    DEBUG_puts("4http_set_credentials: No credentials to set.");
+
+  return (error);
+}
+#  endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
+
+
+/*
+ * 'http_set_timeout()' - Set the socket timeout values.
+ */
+
+static void
+http_set_timeout(int    fd,            /* I - File descriptor */
+                 double timeout)       /* I - Timeout in seconds */
+{
+#ifdef WIN32
+  DWORD tv = (DWORD)(timeout * 1000);
+                                     /* Timeout in milliseconds */
+
+  setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
+  setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
+
+#else
+  struct timeval tv;                   /* Timeout in secs and usecs */
+
+  tv.tv_sec  = (int)timeout;
+  tv.tv_usec = (int)(1000000 * fmod(timeout, 1.0));
+
+  setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
+  setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
+#endif /* WIN32 */
+}
+
+
+/*
+ * 'http_set_wait()' - Set the default wait value for reads.
+ */
+
+static void
+http_set_wait(http_t *http)            /* I - Connection to server */
+{
+  if (http->blocking)
+  {
+    http->wait_value = (int)(http->timeout_value * 1000);
+
+    if (http->wait_value <= 0)
+      http->wait_value = 60000;
+  }
+  else
+    http->wait_value = 10000;
+}
+
+
+/*
+ * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
+ */
+
+static int                             /* O - 0 on success, -1 on failure */
 http_setup_ssl(http_t *http)           /* I - Connection to server */
 {
+  _cups_globals_t      *cg = _cupsGlobals();
+                                       /* Pointer to library globals */
+  int                  any_root;       /* Allow any root */
+
 #  ifdef HAVE_LIBSSL
-  SSL_CTX      *context;               /* Context for encryption */
-  SSL          *conn;                  /* Connection for encryption */
-  BIO          *bio;                   /* BIO data */
+  SSL_CTX              *context;       /* Context for encryption */
+  BIO                  *bio;           /* BIO data */
+  const char           *message = NULL;/* Error message */
 #  elif defined(HAVE_GNUTLS)
-  http_tls_t   *conn;                  /* TLS session object */
+  int                  status;         /* Status of handshake */
   gnutls_certificate_client_credentials *credentials;
                                        /* TLS credentials */
 #  elif defined(HAVE_CDSASSL)
-  OSStatus     error;                  /* Error code */
-  http_tls_t   *conn;                  /* CDSA connection information */
+  OSStatus             error;          /* Error code */
+  char                 *hostname;      /* Hostname */
+  const char           *message = NULL;/* Error message */
+#    ifdef HAVE_SECCERTIFICATECOPYDATA
+  cups_array_t         *credentials;   /* Credentials array */
+  cups_array_t         *names;         /* CUPS distinguished names */
+  CFArrayRef           dn_array;       /* CF distinguished names array */
+  CFIndex              count;          /* Number of credentials */
+  CFDataRef            data;           /* Certificate data */
+  int                  i;              /* Looping var */
+  http_credential_t    *credential;    /* Credential data */
+#    endif /* HAVE_SECCERTIFICATECOPYDATA */
 #  elif defined(HAVE_SSPISSL)
-  TCHAR                username[256];          /* Username returned from GetUserName() */
-  TCHAR                commonName[256];        /* Common name for certificate */
-  DWORD                dwSize;                 /* 32 bit size */
-  _sspi_struct_t *conn;                        /* SSPI connection information */
+  TCHAR                        username[256];  /* Username returned from GetUserName() */
+  TCHAR                        commonName[256];/* Common name for certificate */
+  DWORD                        dwSize;         /* 32 bit size */
 #  endif /* HAVE_LIBSSL */
 
 
   DEBUG_printf(("7http_setup_ssl(http=%p)", http));
 
+ /*
+  * Always allow self-signed certificates for the local loopback address...
+  */
+
+  if (httpAddrLocalhost(http->hostaddr))
+    any_root = 1;
+  else
+    any_root = cg->any_root;
+
 #  ifdef HAVE_LIBSSL
+  (void)any_root;
+
   context = SSL_CTX_new(SSLv23_client_method());
 
   SSL_CTX_set_options(context, SSL_OP_NO_SSLv2); /* Only use SSLv3 or TLS */
@@ -3284,20 +3853,22 @@ http_setup_ssl(http_t *http)            /* I - Connection to server */
   bio = BIO_new(_httpBIOMethods());
   BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)http);
 
-  conn = SSL_new(context);
-  SSL_set_bio(conn, bio, bio);
+  http->tls = SSL_new(context);
+  SSL_set_bio(http->tls, bio, bio);
 
-  if (SSL_connect(conn) != 1)
+  if (SSL_connect(http->tls) != 1)
   {
-#    ifdef DEBUG
     unsigned long      error;  /* Error code */
 
     while ((error = ERR_get_error()) != 0)
-      DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error, NULL)));
-#    endif /* DEBUG */
+    {
+      message = ERR_error_string(error, NULL);
+      DEBUG_printf(("8http_setup_ssl: %s", message));
+    }
 
     SSL_CTX_free(context);
-    SSL_free(conn);
+    SSL_free(http->tls);
+    http->tls = NULL;
 
 #    ifdef WIN32
     http->error  = WSAGetLastError();
@@ -3306,133 +3877,353 @@ http_setup_ssl(http_t *http)          /* I - Connection to server */
 #    endif /* WIN32 */
     http->status = HTTP_ERROR;
 
-    return (HTTP_ERROR);
-  }
+    if (!message)
+      message = _("Unable to establish a secure connection to host.");
 
-#  elif defined(HAVE_GNUTLS)
-  if ((conn = (http_tls_t *)malloc(sizeof(http_tls_t))) == NULL)
-  {
-    http->error  = errno;
-    http->status = HTTP_ERROR;
+    _cupsSetError(IPP_PKI_ERROR, message, 1);
 
     return (-1);
   }
 
+#  elif defined(HAVE_GNUTLS)
   credentials = (gnutls_certificate_client_credentials *)
                     malloc(sizeof(gnutls_certificate_client_credentials));
   if (credentials == NULL)
   {
-    free(conn);
-
-    http->error = errno;
+    DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
+                  strerror(errno)));
+    http->error  = errno;
     http->status = HTTP_ERROR;
+    _cupsSetHTTPError(HTTP_ERROR);
 
     return (-1);
   }
 
   gnutls_certificate_allocate_credentials(credentials);
 
-  gnutls_init(&(conn->session), GNUTLS_CLIENT);
-  gnutls_set_default_priority(conn->session);
-  gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
-  gnutls_transport_set_ptr(conn->session, (gnutls_transport_ptr)http);
-  gnutls_transport_set_pull_function(conn->session, _httpReadGNUTLS);
-  gnutls_transport_set_push_function(conn->session, _httpWriteGNUTLS);
+  gnutls_init(&http->tls, GNUTLS_CLIENT);
+  gnutls_set_default_priority(http->tls);
+  gnutls_server_name_set(http->tls, GNUTLS_NAME_DNS, http->hostname, strlen(http->hostname));
+  gnutls_credentials_set(http->tls, GNUTLS_CRD_CERTIFICATE, *credentials);
+  gnutls_transport_set_ptr(http->tls, (gnutls_transport_ptr)http);
+  gnutls_transport_set_pull_function(http->tls, _httpReadGNUTLS);
+  gnutls_transport_set_push_function(http->tls, _httpWriteGNUTLS);
 
-  if ((gnutls_handshake(conn->session)) != GNUTLS_E_SUCCESS)
+  while ((status = gnutls_handshake(http->tls)) != GNUTLS_E_SUCCESS)
   {
-    http->error  = errno;
-    http->status = HTTP_ERROR;
+    DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
+                  status, gnutls_strerror(status)));
 
-    gnutls_deinit(conn->session);
-    gnutls_certificate_free_credentials(*credentials);
-    free(credentials);
-    free(conn);
+    if (gnutls_error_is_fatal(status))
+    {
+      http->error  = EIO;
+      http->status = HTTP_ERROR;
 
-    return (-1);
-  }
+      _cupsSetError(IPP_PKI_ERROR, gnutls_strerror(status), 0);
 
-  conn->credentials = credentials;
+      gnutls_deinit(http->tls);
+      gnutls_certificate_free_credentials(*credentials);
+      free(credentials);
+      http->tls = NULL;
 
-#  elif defined(HAVE_CDSASSL)
-  conn = (http_tls_t *)calloc(1, sizeof(http_tls_t));
+      return (-1);
+    }
+  }
 
-  if (conn == NULL)
-    return (-1);
+  http->tls_credentials = credentials;
 
-  if ((error = SSLNewContext(false, &conn->session)))
+#  elif defined(HAVE_CDSASSL)
+  if ((error = SSLNewContext(false, &http->tls)))
   {
-    http->error  = error;
+    http->error  = errno;
     http->status = HTTP_ERROR;
+    _cupsSetHTTPError(HTTP_ERROR);
 
-    free(conn);
     return (-1);
   }
 
- /*
-  * Use a union to resolve warnings about int/pointer size mismatches...
-  */
+  error = SSLSetConnection(http->tls, http);
+  DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error));
 
-  error = SSLSetConnection(conn->session, http);
+  if (!error)
+  {
+    error = SSLSetIOFuncs(http->tls, _httpReadCDSA, _httpWriteCDSA);
+    DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error));
+  }
 
   if (!error)
-    error = SSLSetIOFuncs(conn->session, _httpReadCDSA, _httpWriteCDSA);
+  {
+    error = SSLSetAllowsAnyRoot(http->tls, any_root);
+    DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
+                  any_root, (int)error));
+  }
 
   if (!error)
-    error = SSLSetAllowsExpiredCerts(conn->session, true);
+  {
+    error = SSLSetAllowsExpiredCerts(http->tls, cg->expired_certs);
+    DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
+                  cg->expired_certs, (int)error));
+  }
 
   if (!error)
-    error = SSLSetAllowsAnyRoot(conn->session, true);
+  {
+    error = SSLSetAllowsExpiredRoots(http->tls, cg->expired_root);
+    DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
+                  cg->expired_root, (int)error));
+  }
 
+#    ifdef HAVE_SSLSETPROTOCOLVERSIONMAX
   if (!error)
-    error = SSLSetProtocolVersionEnabled(conn->session, kSSLProtocol2, false);
+  {
+    error = SSLSetProtocolVersionMax(http->tls, kTLSProtocol1);
+    DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionMax(kTLSProtocol1), "
+                  "error=%d", (int)error));
+  }
+#    endif /* HAVE_SSLSETPROTOCOLVERSIONMAX */
 
+#    ifdef HAVE_SECCERTIFICATECOPYDATA
   if (!error)
   {
-    while ((error = SSLHandshake(conn->session)) == errSSLWouldBlock)
-      usleep(1000);
+    if (cg->client_cert_cb)
+    {
+      error = SSLSetSessionOption(http->tls,
+                                 kSSLSessionOptionBreakOnCertRequested, true);
+      DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
+                    "error=%d", (int)error));
+    }
+    else
+    {
+      error = http_set_credentials(http);
+      DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
+                    (int)error));
+    }
+  }
+
+ /*
+  * If there's a server certificate callback installed let it evaluate the
+  * certificate(s) during the handshake...
+  */
+
+  if (!error && cg->server_cert_cb != NULL)
+  {
+    error = SSLSetEnableCertVerify(http->tls, false);
+    DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
+                  (int)error));
+
+    if (!error)
+    {
+      error = SSLSetSessionOption(http->tls,
+                                 kSSLSessionOptionBreakOnServerAuth, true);
+      DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
+                    "error=%d", (int)error));
+    }
+  }
+#    endif /* HAVE_SECCERTIFICATECOPYDATA */
+
+  if (!error)
+  {
+    hostname = httpAddrLocalhost(http->hostaddr) ? "localhost" : http->hostname;
+    error    = SSLSetPeerDomainName(http->tls, hostname, strlen(hostname));
+
+    DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
+                  (int)error));
+  }
+
+  if (!error)
+  {
+    int done = 0;                      /* Are we done yet? */
+
+    while (!error && !done)
+    {
+      error = SSLHandshake(http->tls);
+
+      DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error));
+
+      switch (error)
+      {
+       case noErr :
+           done = 1;
+           break;
+
+       case errSSLWouldBlock :
+           usleep(1000);
+           break;
+
+#    ifdef HAVE_SECCERTIFICATECOPYDATA
+       case errSSLServerAuthCompleted :
+           error = 0;
+           if (cg->server_cert_cb)
+           {
+             error = httpCopyCredentials(http, &credentials);
+             if (!error)
+             {
+               error = (cg->server_cert_cb)(http, http->tls, credentials,
+                                            cg->server_cert_data);
+               httpFreeCredentials(credentials);
+             }
+
+             DEBUG_printf(("4http_setup_ssl: Server certificate callback returned "
+                           "%d.", (int)error));
+           }
+           break;
+
+       case errSSLClientCertRequested :
+           error = 0;
+
+           if (cg->client_cert_cb)
+           {
+             names = NULL;
+             if (!(error = SSLCopyDistinguishedNames(http->tls, &dn_array)) &&
+                 dn_array)
+             {
+               if ((names = cupsArrayNew(NULL, NULL)) != NULL)
+               {
+                 for (i = 0, count = CFArrayGetCount(dn_array); i < count; i++)
+                 {
+                   data = (CFDataRef)CFArrayGetValueAtIndex(dn_array, i);
+
+                   if ((credential = malloc(sizeof(*credential))))
+                   {
+                     credential->datalen = CFDataGetLength(data);
+                     if ((credential->data = malloc(credential->datalen)))
+                     {
+                       memcpy((void *)credential->data, CFDataGetBytePtr(data),
+                              credential->datalen);
+                       cupsArrayAdd(names, credential);
+                     }
+                   }
+                 }
+               }
+
+               CFRelease(dn_array);
+             }
+
+             if (!error)
+             {
+               error = (cg->client_cert_cb)(http, http->tls, names,
+                                            cg->client_cert_data);
+
+               DEBUG_printf(("4http_setup_ssl: Client certificate callback "
+                             "returned %d.", (int)error));
+             }
+
+             httpFreeCredentials(names);
+           }
+           break;
+#    endif /* HAVE_SECCERTIFICATECOPYDATA */
+
+       case errSSLUnknownRootCert :
+           message = _("Unable to establish a secure connection to host "
+                       "(untrusted certificate).");
+           break;
+
+       case errSSLNoRootCert :
+           message = _("Unable to establish a secure connection to host "
+                       "(self-signed certificate).");
+           break;
+
+       case errSSLCertExpired :
+           message = _("Unable to establish a secure connection to host "
+                       "(expired certificate).");
+           break;
+
+       case errSSLCertNotYetValid :
+           message = _("Unable to establish a secure connection to host "
+                       "(certificate not yet valid).");
+           break;
+
+       case errSSLHostNameMismatch :
+           message = _("Unable to establish a secure connection to host "
+                       "(host name mismatch).");
+           break;
+
+       case errSSLXCertChainInvalid :
+           message = _("Unable to establish a secure connection to host "
+                       "(certificate chain invalid).");
+           break;
+
+       case errSSLConnectionRefused :
+           message = _("Unable to establish a secure connection to host "
+                       "(peer dropped connection before responding).");
+           break;
+
+       default :
+           break;
+      }
+    }
   }
 
   if (error)
   {
     http->error  = error;
     http->status = HTTP_ERROR;
+    errno        = ECONNREFUSED;
 
-    SSLDisposeContext(conn->session);
+    SSLDisposeContext(http->tls);
+    http->tls = NULL;
 
-    free(conn);
+   /*
+    * If an error string wasn't set by the callbacks use a generic one...
+    */
+
+    if (!message)
+#ifdef HAVE_CSSMERRORSTRING
+      message = cssmErrorString(error);
+#else
+      message = _("Unable to establish a secure connection to host.");
+#endif /* HAVE_CSSMERRORSTRING */
+
+    _cupsSetError(IPP_PKI_ERROR, message, 1);
 
     return (-1);
   }
+
 #  elif defined(HAVE_SSPISSL)
-  conn = _sspiAlloc();
+  http->tls = _sspiAlloc();
 
-  if (!conn)
+  if (!http->tls)
+  {
     return (-1);
 
-  conn->sock = http->fd;
-  dwSize     = sizeof(username) / sizeof(TCHAR);
+  http->tls->sock = http->fd;
+  dwSize          = sizeof(username) / sizeof(TCHAR);
   GetUserName(username, &dwSize);
   _sntprintf_s(commonName, sizeof(commonName) / sizeof(TCHAR),
                sizeof(commonName) / sizeof(TCHAR), TEXT("CN=%s"), username);
 
-  if (!_sspiGetCredentials(conn, L"ClientContainer", commonName, FALSE))
+  if (!_sspiGetCredentials(http->tls_credentials, L"ClientContainer",
+                           commonName, FALSE))
   {
-    _sspiFree(conn);
+    _sspiFree(http->tls_credentials);
+    http->tls_credentials = NULL;
+
+    http->error  = EIO;
+    http->status = HTTP_ERROR;
+
+    _cupsSetError(IPP_PKI_ERROR,
+                  _("Unable to establish a secure connection to host."), 1);
+
     return (-1);
   }
 
-  _sspiSetAllowsAnyRoot(conn, TRUE);
-  _sspiSetAllowsExpiredCerts(conn, TRUE);
+  _sspiSetAllowsAnyRoot(http->tls_credentials, TRUE);
+  _sspiSetAllowsExpiredCerts(http->tls_credentials, TRUE);
 
-  if (!_sspiConnect(conn, http->hostname))
+  if (!_sspiConnect(http->tls_credentials, http->hostname))
   {
-    _sspiFree(conn);
+    _sspiFree(http->tls_credentials);
+    http->tls_credentials = NULL;
+
+    http->error  = EIO;
+    http->status = HTTP_ERROR;
+
+    _cupsSetError(IPP_PKI_ERROR,
+                  _("Unable to establish a secure connection to host."), 1);
+
     return (-1);
   }
 #  endif /* HAVE_CDSASSL */
 
-  http->tls = conn;
   return (0);
 }
 #endif /* HAVE_SSL */
@@ -3448,75 +4239,43 @@ http_shutdown_ssl(http_t *http)         /* I - Connection to server */
 {
 #  ifdef HAVE_LIBSSL
   SSL_CTX      *context;               /* Context for encryption */
-  SSL          *conn;                  /* Connection for encryption */
 
+  context = SSL_get_SSL_CTX(http->tls);
 
-  conn    = (SSL *)(http->tls);
-  context = SSL_get_SSL_CTX(conn);
-
-  SSL_shutdown(conn);
+  SSL_shutdown(http->tls);
   SSL_CTX_free(context);
-  SSL_free(conn);
+  SSL_free(http->tls);
 
 #  elif defined(HAVE_GNUTLS)
-  http_tls_t      *conn;               /* Encryption session */
   gnutls_certificate_client_credentials *credentials;
                                        /* TLS credentials */
 
+  credentials = (gnutls_certificate_client_credentials *)(http->tls_credentials);
 
-  conn = (http_tls_t *)(http->tls);
-  credentials = (gnutls_certificate_client_credentials *)(conn->credentials);
-
-  gnutls_bye(conn->session, GNUTLS_SHUT_RDWR);
-  gnutls_deinit(conn->session);
+  gnutls_bye(http->tls, GNUTLS_SHUT_RDWR);
+  gnutls_deinit(http->tls);
   gnutls_certificate_free_credentials(*credentials);
   free(credentials);
-  free(conn);
 
 #  elif defined(HAVE_CDSASSL)
-  http_tls_t      *conn;               /* CDSA connection information */
-
-
-  conn = (http_tls_t *)(http->tls);
-
-  while (SSLClose(conn->session) == errSSLWouldBlock)
+  while (SSLClose(http->tls) == errSSLWouldBlock)
     usleep(1000);
 
-  SSLDisposeContext(conn->session);
+  SSLDisposeContext(http->tls);
 
-  if (conn->certsArray)
-    CFRelease(conn->certsArray);
+  if (http->tls_credentials)
+    CFRelease(http->tls_credentials);
 
-  free(conn);
 #  elif defined(HAVE_SSPISSL)
-  _sspi_struct_t  *conn;               /* SSPI connection information */
-
-  conn = (_sspi_struct_t*)(http->tls);
-  _sspiFree(conn);
+  _sspiFree(http->tls_credentials);
 #  endif /* HAVE_LIBSSL */
 
-  http->tls = NULL;
+  http->tls             = NULL;
+  http->tls_credentials = NULL;
 }
 #endif /* HAVE_SSL */
 
 
-#ifdef HAVE_LIBSSL
-/*
- * 'http_threadid_cb()' - Return the current thread ID.
- */
-
-static unsigned long                   /* O - Thread ID */
-http_threadid_cb(void)
-{
-#  ifdef HAVE_PTHREAD_H
-  return ((unsigned long)pthread_self());
-#  else
-  return (0);
-#  endif /* HAVE_PTHREAD_H */
-}
-#endif /* HAVE_LIBSSL */
-
-
 #ifdef HAVE_SSL
 /*
  * 'http_upgrade()' - Force upgrade to TLS encryption.
@@ -3554,7 +4313,7 @@ http_upgrade(http_t *http)                /* I - Connection to server */
 
   httpClearFields(http);
   httpSetField(http, HTTP_FIELD_CONNECTION, "upgrade");
-  httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.0, SSL/2.0, SSL/3.0");
+  httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
 
   if ((ret = httpOptions(http, "*")) == 0)
   {
@@ -3625,6 +4384,62 @@ http_write(http_t     *http,             /* I - Connection to server */
 
   while (length > 0)
   {
+    if (http->timeout_cb)
+    {
+#ifdef HAVE_POLL
+      struct pollfd    pfd;            /* Polled file descriptor */
+#else
+      fd_set           output_set;     /* Output ready for write? */
+      struct timeval   timeout;        /* Timeout value */
+#endif /* HAVE_POLL */
+      int              nfds;           /* Result from select()/poll() */
+
+      do
+      {
+#ifdef HAVE_POLL
+       pfd.fd     = http->fd;
+       pfd.events = POLLOUT;
+
+       while ((nfds = poll(&pfd, 1, http->wait_value)) < 0 &&
+              (errno == EINTR || errno == EAGAIN));
+
+#else
+       do
+       {
+         FD_ZERO(&output_set);
+         FD_SET(http->fd, &output_set);
+
+         timeout.tv_sec  = http->wait_value / 1000;
+         timeout.tv_usec = 1000 * (http->wait_value % 1000);
+
+         nfds = select(http->fd + 1, NULL, &output_set, NULL, &timeout);
+       }
+#  ifdef WIN32
+       while (nfds < 0 && (WSAGetLastError() == WSAEINTR ||
+                           WSAGetLastError() == WSAEWOULDBLOCK));
+#  else
+       while (nfds < 0 && (errno == EINTR || errno == EAGAIN));
+#  endif /* WIN32 */
+#endif /* HAVE_POLL */
+
+        if (nfds < 0)
+       {
+         http->error = errno;
+         return (-1);
+       }
+       else if (nfds == 0 && !(*http->timeout_cb)(http, http->timeout_data))
+       {
+#ifdef WIN32
+         http->error = ESAEWOULDBLOCK;
+#else
+         http->error = EWOULDBLOCK;
+#endif /* WIN32 */
+         return (-1);
+       }
+      }
+      while (nfds <= 0);
+    }
+
 #ifdef HAVE_SSL
     if (http->tls)
       bytes = http_write_ssl(http, buffer, length);
@@ -3635,16 +4450,34 @@ http_write(http_t     *http,            /* I - Connection to server */
     if (bytes < 0)
     {
 #ifdef WIN32
-      if (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK)
+      if (WSAGetLastError() == WSAEINTR)
         continue;
-      else if (WSAGetLastError() != http->error && WSAGetLastError() != WSAECONNRESET)
+      else if (WSAGetLastError() == WSAEWOULDBLOCK)
+      {
+        if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+          continue;
+
+        http->error = WSAGetLastError();
+      }
+      else if (WSAGetLastError() != http->error &&
+               WSAGetLastError() != WSAECONNRESET)
       {
         http->error = WSAGetLastError();
        continue;
       }
+
 #else
-      if (errno == EINTR || errno == EAGAIN)
+      if (errno == EINTR)
         continue;
+      else if (errno == EWOULDBLOCK || errno == EAGAIN)
+      {
+       if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+          continue;
+        else if (!http->timeout_cb && errno == EAGAIN)
+         continue;
+
+        http->error = errno;
+      }
       else if (errno != http->error && errno != ECONNRESET)
       {
         http->error = errno;
@@ -3735,7 +4568,7 @@ http_write_ssl(http_t     *http,  /* I - Connection to server */
   result = SSL_write((SSL *)(http->tls), buf, len);
 
 #  elif defined(HAVE_GNUTLS)
-  result = gnutls_record_send(((http_tls_t *)(http->tls))->session, buf, len);
+  result = gnutls_record_send(http->tls, buf, len);
 
   if (result < 0 && !errno)
   {
@@ -3766,16 +4599,14 @@ http_write_ssl(http_t     *http,        /* I - Connection to server */
   size_t       processed;              /* Number of bytes processed */
 
 
-  error = SSLWrite(((http_tls_t *)http->tls)->session, buf, len, &processed);
+  error = SSLWrite(http->tls, buf, len, &processed);
 
   switch (error)
   {
     case 0 :
        result = (int)processed;
        break;
-    case errSSLClosedGraceful :
-       result = 0;
-       break;
+
     case errSSLWouldBlock :
        if (processed)
          result = (int)processed;
@@ -3785,13 +4616,20 @@ http_write_ssl(http_t     *http,        /* I - Connection to server */
          errno  = EINTR;
        }
        break;
+
+    case errSSLClosedGraceful :
     default :
-       errno  = EPIPE;
-       result = -1;
+       if (processed)
+         result = (int)processed;
+       else
+       {
+         result = -1;
+         errno  = EPIPE;
+       }
        break;
   }
 #  elif defined(HAVE_SSPISSL)
-  return _sspiWrite((_sspi_struct_t*) http->tls, (void*) buf, len);
+  return _sspiWrite((_sspi_struct_t *)http->tls, (void *)buf, len);
 #  endif /* HAVE_LIBSSL */
 
   DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result));