]> git.ipfire.org Git - thirdparty/cups.git/blobdiff - cups/http.c
Use httpAddrListen and new httpAddrClose in cupsd and other places that need it.
[thirdparty/cups.git] / cups / http.c
index 12e7338ad8263b20d9d3043a3a5b9d1a044431cd..3db98fca2199eedf0beec728d55ea0223db9a8b5 100644 (file)
 /*
- * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
+ * "$Id$"
  *
- *   HTTP routines for CUPS.
+ * HTTP routines for CUPS.
  *
- *   Copyright 2007-2012 by Apple Inc.
- *   Copyright 1997-2007 by Easy Software Products, all rights reserved.
+ * Copyright 2007-2013 by Apple Inc.
+ * Copyright 1997-2007 by Easy Software Products, all rights reserved.
  *
- *   This file contains Kerberos support code, copyright 2006 by
- *   Jelmer Vernooij.
+ * This file contains Kerberos support code, copyright 2006 by
+ * Jelmer Vernooij.
  *
- *   These coded instructions, statements, and computer programs are the
- *   property of Apple Inc. and are protected by Federal copyright
- *   law.  Distribution and use rights are outlined in the file "LICENSE.txt"
- *   which should have been included with this file.  If this file is
- *   file is missing or damaged, see the license at "http://www.cups.org/".
+ * These coded instructions, statements, and computer programs are the
+ * property of Apple Inc. and are protected by Federal copyright
+ * law.  Distribution and use rights are outlined in the file "LICENSE.txt"
+ * which should have been included with this file.  If this file is
+ * file is missing or damaged, see the license at "http://www.cups.org/".
  *
- *   This file is subject to the Apple OS-Developed Software exception.
- *
- * Contents:
- *
- *   httpAcceptConnection()      - Accept a new HTTP client connection from
- *                                 the specified listening socket.
- *   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.
- *   httpConnect2()              - 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.
- *   httpGetContentEncoding()     - Get a common content encoding, if any,
- *                                  between the client and 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.
- *   httpGetExpect()              - Get the value of the Expect header, if any.
- *   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.
- *   httpGets()                  - Get a line of text from a HTTP connection.
- *   httpGetState()              - Get the current state of the HTTP request.
- *   httpGetStatus()             - Get the status of the last HTTP request.
- *   httpGetSubField()           - Get a sub-field value.
- *   httpGetSubField2()          - Get a sub-field value.
- *   httpGetVersion()            - Get the HTTP version at the other end.
- *   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.
- *   httpReadRequest()           - Read a HTTP request from a connection.
- *   httpReconnect()             - Reconnect to a HTTP server.
- *   httpReconnect2()            - Reconnect to a HTTP server with timeout and
- *                                 optional cancel.
- *   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.
- *   httpWriteResponse()         - Write a HTTP response to a client
- *                                 connection.
- *   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_content_coding_finish() - Finish doing any content encoding.
- *   http_content_coding_start()  - Start doing content encoding.
- *   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_send()                 - Send a request with all fields and the
- *                                 trailing blank line.
- *   http_set_credentials()      - Set the SSL/TLS credentials.
- *   http_set_length()            - Set the data_encoding and data_remaining
- *                                  values.
- *   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_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.
+ * This file is subject to the Apple OS-Developed Software exception.
  */
 
 /*
@@ -163,22 +46,26 @@ static void                http_content_coding_finish(http_t *http);
 static void            http_content_coding_start(http_t *http,
                                                  const char *value);
 #endif /* HAVE_LIBZ */
+static http_t          *http_create(const char *host, int port,
+                                    http_addrlist_t *addrlist, int family,
+                                    http_encryption_t encryption,
+                                    int blocking, _http_mode_t mode);
 #ifdef DEBUG
 static void            http_debug_hex(const char *prefix, const char *buffer,
                                       int bytes);
 #endif /* DEBUG */
-static http_field_t    http_field(const char *name);
+static ssize_t         http_read(http_t *http, char *buffer, size_t length);
+static ssize_t         http_read_buffered(http_t *http, char *buffer, size_t length);
+static ssize_t         http_read_chunk(http_t *http, char *buffer, size_t length);
 static int             http_send(http_t *http, http_state_t request,
                                  const char *uri);
-static int             http_write(http_t *http, const char *buffer,
-                                  int length);
-static int             http_write_chunk(http_t *http, const char *buffer,
-                                        int length);
+static ssize_t         http_write(http_t *http, const char *buffer,
+                                  size_t length);
+static ssize_t         http_write_chunk(http_t *http, const char *buffer,
+                                        size_t length);
 #ifdef HAVE_SSL
 static int             http_read_ssl(http_t *http, char *buf, int len);
-#  ifdef HAVE_CDSASSL
 static int             http_set_credentials(http_t *http);
-#  endif /* HAVE_CDSASSL */
 #endif /* HAVE_SSL */
 static off_t           http_set_length(http_t *http);
 static void            http_set_timeout(int fd, double timeout);
@@ -228,28 +115,6 @@ static const char * const http_fields[] =
                          "Allow",
                          "Server"
                        };
-#ifdef DEBUG
-static const char * const http_states[] =
-                       {
-                         "HTTP_STATE_ERROR",
-                         "HTTP_STATE_WAITING",
-                         "HTTP_STATE_OPTIONS",
-                         "HTTP_STATE_GET",
-                         "HTTP_STATE_GET_SEND",
-                         "HTTP_STATE_HEAD",
-                         "HTTP_STATE_POST",
-                         "HTTP_STATE_POST_RECV",
-                         "HTTP_STATE_POST_SEND",
-                         "HTTP_STATE_PUT",
-                         "HTTP_STATE_PUT_RECV",
-                         "HTTP_STATE_DELETE",
-                         "HTTP_STATE_TRACE",
-                         "HTTP_STATE_CONNECT",
-                         "HTTP_STATE_STATUS",
-                         "HTTP_STATE_UNKNOWN_METHOD",
-                         "HTTP_STATE_UNKNOWN_VERSION"
-                       };
-#endif /* DEBUG */
 
 
 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
@@ -284,7 +149,7 @@ static BIO_METHOD   http_bio_methods =
  * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
  *                            specified listening socket.
  *
- * @since CUPS 1.7@
+ * @since CUPS 1.7/OS X 10.9@
  */
 
 http_t *                               /* O - HTTP connection or @code NULL@ */
@@ -311,7 +176,7 @@ httpAcceptConnection(int fd,                /* I - Listen socket file descriptor */
 
   memset(&addrlist, 0, sizeof(addrlist));
 
-  if ((http = _httpCreate(NULL, 0, &addrlist, AF_UNSPEC,
+  if ((http = http_create(NULL, 0, &addrlist, AF_UNSPEC,
                           HTTP_ENCRYPTION_IF_REQUESTED, blocking,
                           _HTTP_MODE_SERVER)) == NULL)
     return (NULL);
@@ -331,8 +196,12 @@ httpAcceptConnection(int fd,               /* I - Listen socket file descriptor */
     return (NULL);
   }
 
-  httpAddrString(&(http->addrlist->addr), http->hostname,
-                sizeof(http->hostname));
+  http->hostaddr = &(http->addrlist->addr);
+
+  if (httpAddrLocalhost(http->hostaddr))
+    strlcpy(http->hostname, "localhost", sizeof(http->hostname));
+  else
+    httpAddrString(http->hostaddr, http->hostname, sizeof(http->hostname));
 
 #ifdef SO_NOSIGPIPE
  /*
@@ -340,7 +209,7 @@ httpAcceptConnection(int fd,                /* I - Listen socket file descriptor */
   */
 
   val = 1;
-  setsockopt(http->fd, SOL_SOCKET, SO_NOSIGPIPE, &val, sizeof(val));
+  setsockopt(http->fd, SOL_SOCKET, SO_NOSIGPIPE, CUPS_SOCAST &val, sizeof(val));
 #endif /* SO_NOSIGPIPE */
 
  /*
@@ -351,7 +220,7 @@ httpAcceptConnection(int fd,                /* I - Listen socket file descriptor */
   */
 
   val = 1;
-  setsockopt(http->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
+  setsockopt(http->fd, IPPROTO_TCP, TCP_NODELAY, CUPS_SOCAST &val, sizeof(val));
 
 #ifdef FD_CLOEXEC
  /*
@@ -418,7 +287,7 @@ _httpBIOMethods(void)
  */
 
 void
-httpBlocking(http_t *http,             /* I - Connection to server */
+httpBlocking(http_t *http,             /* I - HTTP connection */
              int    b)                 /* I - 1 = blocking, 0 = non-blocking */
 {
   if (http)
@@ -434,7 +303,7 @@ httpBlocking(http_t *http,          /* I - Connection to server */
  */
 
 int                                    /* O - 0 = no data, 1 = data available */
-httpCheck(http_t *http)                        /* I - Connection to server */
+httpCheck(http_t *http)                        /* I - HTTP connection */
 {
   return (httpWait(http, 0));
 }
@@ -447,7 +316,7 @@ httpCheck(http_t *http)                     /* I - Connection to server */
  */
 
 void
-httpClearCookie(http_t *http)          /* I - Connection to server */
+httpClearCookie(http_t *http)          /* I - HTTP connection */
 {
   if (!http)
     return;
@@ -465,7 +334,7 @@ httpClearCookie(http_t *http)               /* I - Connection to server */
  */
 
 void
-httpClearFields(http_t *http)          /* I - Connection to server */
+httpClearFields(http_t *http)          /* I - HTTP connection */
 {
   DEBUG_printf(("httpClearFields(http=%p)", http));
 
@@ -515,7 +384,7 @@ httpClearFields(http_t *http)               /* I - Connection to server */
  */
 
 void
-httpClose(http_t *http)                        /* I - Connection to server */
+httpClose(http_t *http)                        /* I - HTTP connection */
 {
 #ifdef HAVE_GSSAPI
   OM_uint32    minor_status;           /* Minor status code */
@@ -580,7 +449,7 @@ http_t *                            /* O - New HTTP connection */
 httpConnect(const char *host,          /* I - Host to connect to */
             int        port)           /* I - Port number */
 {
-  return (httpConnect2(host, port, NULL, AF_UNSPEC, HTTP_ENCRYPT_IF_REQUESTED,
+  return (httpConnect2(host, port, NULL, AF_UNSPEC, HTTP_ENCRYPTION_IF_REQUESTED,
                        1, 30000, NULL));
 }
 
@@ -588,7 +457,7 @@ httpConnect(const char *host,               /* I - Host to connect to */
 /*
  * 'httpConnect2()' - Connect to a HTTP server.
  *
- * @since CUPS 1.7@
+ * @since CUPS 1.7/OS X 10.9@
  */
 
 http_t *                               /* O - New HTTP connection */
@@ -599,7 +468,7 @@ httpConnect2(
     int               family,          /* I - Address family to use or @code AF_UNSPEC@ for any */
     http_encryption_t encryption,      /* I - Type of encryption to use */
     int               blocking,                /* I - 1 for blocking connection, 0 for non-blocking */
-    int               msec,            /* I - Connection timeout in milliseconds */
+    int               msec,            /* I - Connection timeout in milliseconds, 0 means don't connect */
     int               *cancel)         /* I - Pointer to "cancel" variable */
 {
   http_t       *http;                  /* New HTTP connection */
@@ -613,15 +482,15 @@ httpConnect2(
   * Create the HTTP structure...
   */
 
-  if ((http = _httpCreate(host, port, addrlist, family, encryption, blocking,
+  if ((http = http_create(host, port, addrlist, family, encryption, blocking,
                           _HTTP_MODE_CLIENT)) == NULL)
     return (NULL);
 
  /*
-  * Connect to the remote system...
+  * Optionally connect to the remote system...
   */
 
-  if (!httpReconnect2(http, msec, cancel))
+  if (msec == 0 || !httpReconnect2(http, msec, cancel))
     return (http);
 
  /*
@@ -666,7 +535,7 @@ httpConnectEncrypt(
 
 int                                    /* O - Status of call (0 = success) */
 httpCopyCredentials(
-    http_t      *http,                 /* I - Connection to server */
+    http_t      *http,                 /* I - HTTP connection */
     cups_array_t **credentials)                /* O - Array of credentials */
 {
 #  ifdef HAVE_LIBSSL
@@ -727,96 +596,6 @@ httpCopyCredentials(
 }
 
 
-/*
- * '_httpCreate()' - Create an unconnected HTTP connection.
- */
-
-http_t *                               /* O - HTTP connection */
-_httpCreate(
-    const char        *host,           /* I - Hostname */
-    int               port,            /* I - Port number */
-    http_addrlist_t   *addrlist,       /* I - Address list or NULL */
-    int               family,          /* I - Address family or AF_UNSPEC */
-    http_encryption_t encryption,      /* I - Encryption to use */
-    int               blocking,                /* I - 1 for blocking mode */
-    _http_mode_t      mode)            /* I - _HTTP_MODE_CLIENT or _SERVER */
-{
-  http_t       *http;                  /* New HTTP connection */
-  char         service[255];           /* Service name */
-  http_addrlist_t *myaddrlist = NULL;  /* My address list */
-
-
-  DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, addrlist=%p, family=%d, "
-                "encryption=%d, blocking=%d, mode=%d)", host, port, addrlist,
-                family, encryption, blocking, mode));
-
-  if (!host && mode == _HTTP_MODE_CLIENT)
-    return (NULL);
-
-  httpInitialize();
-
- /*
-  * Lookup the host...
-  */
-
-  if (addrlist)
-  {
-    myaddrlist = httpAddrCopyList(addrlist);
-  }
-  else
-  {
-    snprintf(service, sizeof(service), "%d", port);
-
-    myaddrlist = httpAddrGetList(host, family, service);
-  }
-
-  if (!myaddrlist)
-    return (NULL);
-
- /*
-  * Allocate memory for the structure...
-  */
-
-  if ((http = calloc(sizeof(http_t), 1)) == NULL)
-  {
-    _cupsSetError(IPP_INTERNAL_ERROR, strerror(errno), 0);
-    httpAddrFreeList(addrlist);
-    return (NULL);
-  }
-
- /*
-  * Initialize the HTTP data...
-  */
-
-  http->mode     = mode;
-  http->activity = time(NULL);
-  http->addrlist = myaddrlist;
-  http->blocking = blocking;
-  http->fd       = -1;
-#ifdef HAVE_GSSAPI
-  http->gssctx   = GSS_C_NO_CONTEXT;
-  http->gssname  = GSS_C_NO_NAME;
-#endif /* HAVE_GSSAPI */
-  http->version  = HTTP_VERSION_1_1;
-
-  if (host)
-    strlcpy(http->hostname, host, sizeof(http->hostname));
-
-  if (port == 443)                     /* Always use encryption for https */
-    http->encryption = HTTP_ENCRYPTION_ALWAYS;
-  else
-    http->encryption = encryption;
-
-  http_set_wait(http);
-
- /*
-  * Return the new structure...
-  */
-
-  return (http);
-}
-
-
 /*
  * '_httpCreateCredentials()' - Create credentials in the internal format.
  */
@@ -880,10 +659,10 @@ _httpCreateCredentials(
  */
 
 int                                    /* O - Status of call (0 = success) */
-httpDelete(http_t     *http,           /* I - Connection to server */
+httpDelete(http_t     *http,           /* I - HTTP connection */
            const char *uri)            /* I - URI to delete */
 {
-  return (http_send(http, HTTP_DELETE, uri));
+  return (http_send(http, HTTP_STATE_DELETE, uri));
 }
 
 
@@ -892,18 +671,14 @@ httpDelete(http_t     *http,              /* I - Connection to server */
  */
 
 void
-_httpDisconnect(http_t *http)          /* I - Connection to server */
+_httpDisconnect(http_t *http)          /* I - HTTP connection */
 {
 #ifdef HAVE_SSL
   if (http->tls)
     http_shutdown_ssl(http);
 #endif /* HAVE_SSL */
 
-#ifdef WIN32
-  closesocket(http->fd);
-#else
-  close(http->fd);
-#endif /* WIN32 */
+  httpAddrClose(NULL, http->fd);
 
   http->fd = -1;
 }
@@ -914,7 +689,7 @@ _httpDisconnect(http_t *http)               /* I - Connection to server */
  */
 
 int                                    /* O - -1 on error, 0 on success */
-httpEncryption(http_t            *http,        /* I - Connection to server */
+httpEncryption(http_t            *http,        /* I - HTTP connection */
                http_encryption_t e)    /* I - New encryption preference */
 {
   DEBUG_printf(("httpEncryption(http=%p, e=%d)", http, e));
@@ -925,15 +700,15 @@ httpEncryption(http_t            *http,   /* I - Connection to server */
 
   http->encryption = e;
 
-  if ((http->encryption == HTTP_ENCRYPT_ALWAYS && !http->tls) ||
-      (http->encryption == HTTP_ENCRYPT_NEVER && http->tls))
-    return (httpReconnect(http));
-  else if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
+  if ((http->encryption == HTTP_ENCRYPTION_ALWAYS && !http->tls) ||
+      (http->encryption == HTTP_ENCRYPTION_NEVER && http->tls))
+    return (httpReconnect2(http, 30000, NULL));
+  else if (http->encryption == HTTP_ENCRYPTION_REQUIRED && !http->tls)
     return (http_upgrade(http));
   else
     return (0);
 #else
-  if (e == HTTP_ENCRYPT_ALWAYS || e == HTTP_ENCRYPT_REQUIRED)
+  if (e == HTTP_ENCRYPTION_ALWAYS || e == HTTP_ENCRYPTION_REQUIRED)
     return (-1);
   else
     return (0);
@@ -946,7 +721,7 @@ httpEncryption(http_t            *http,     /* I - Connection to server */
  */
 
 int                                    /* O - Error code (errno) value */
-httpError(http_t *http)                        /* I - Connection to server */
+httpError(http_t *http)                        /* I - HTTP connection */
 {
   if (http)
     return (http->error);
@@ -955,12 +730,31 @@ httpError(http_t *http)                   /* I - Connection to server */
 }
 
 
+/*
+ * 'httpFieldValue()' - Return the HTTP field enumeration value for a field
+ *                      name.
+ */
+
+http_field_t                           /* O - Field index */
+httpFieldValue(const char *name)       /* I - String name */
+{
+  int  i;                              /* Looping var */
+
+
+  for (i = 0; i < HTTP_FIELD_MAX; i ++)
+    if (!_cups_strcasecmp(name, http_fields[i]))
+      return ((http_field_t)i);
+
+  return (HTTP_FIELD_UNKNOWN);
+}
+
+
 /*
  * 'httpFlush()' - Flush data from a HTTP connection.
  */
 
 void
-httpFlush(http_t *http)                        /* I - Connection to server */
+httpFlush(http_t *http)                        /* I - HTTP connection */
 {
   char         buffer[8192];           /* Junk buffer */
   int          blocking;               /* To block or not to block */
@@ -968,7 +762,7 @@ httpFlush(http_t *http)                     /* I - Connection to server */
 
 
   DEBUG_printf(("httpFlush(http=%p), state=%s", http,
-                http_states[http->state + 1]));
+                httpStateString(http->state)));
 
  /*
   * Nothing to do if we are in the "waiting" state...
@@ -1019,11 +813,7 @@ httpFlush(http_t *http)                   /* I - Connection to server */
       http_shutdown_ssl(http);
 #endif /* HAVE_SSL */
 
-#ifdef WIN32
-    closesocket(http->fd);
-#else
-    close(http->fd);
-#endif /* WIN32 */
+    httpAddrClose(NULL, http->fd);
 
     http->fd = -1;
   }
@@ -1037,7 +827,7 @@ httpFlush(http_t *http)                    /* I - Connection to server */
  */
 
 int                                    /* O - Bytes written or -1 on error */
-httpFlushWrite(http_t *http)           /* I - Connection to server */
+httpFlushWrite(http_t *http)           /* I - HTTP connection */
 {
   int  bytes;                          /* Bytes written */
 
@@ -1121,10 +911,59 @@ httpFreeCredentials(
  */
 
 int                                    /* O - Status of call (0 = success) */
-httpGet(http_t     *http,              /* I - Connection to server */
+httpGet(http_t     *http,              /* I - HTTP connection */
         const char *uri)               /* I - URI to get */
 {
-  return (http_send(http, HTTP_GET, uri));
+  return (http_send(http, HTTP_STATE_GET, uri));
+}
+
+
+/*
+ * 'httpGetActivity()' - Get the most recent activity for a connection.
+ *
+ * The return value is the UNIX time of the last read or write.
+ *
+ * @since CUPS 2.0@
+ */
+
+time_t                                 /* O - Time of last read or write */
+httpGetActivity(http_t *http)          /* I - HTTP connection */
+{
+  return (http ? http->activity : 0);
+}
+
+
+/*
+ * 'httpGetAuthString()' - Get the current authorization string.
+ *
+ * The authorization string is set by cupsDoAuthentication() and
+ * httpSetAuthString().  Use httpGetAuthString() to retrieve the
+ * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
+ * value.
+ *
+ * @since CUPS 1.3/OS X 10.5@
+ */
+
+char *                                 /* O - Authorization string */
+httpGetAuthString(http_t *http)                /* I - HTTP connection */
+{
+  if (http)
+    return (http->authstring);
+  else
+    return (NULL);
+}
+
+
+/*
+ * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
+ *
+ * @since CUPS 1.2/OS X 10.5@
+ */
+
+int                                    /* O - 1 if blocking, 0 if non-blocking */
+httpGetBlocking(http_t *http)          /* I - HTTP connection */
+{
+  return (http ? http->blocking : 0);
 }
 
 
@@ -1137,7 +976,7 @@ httpGet(http_t     *http,          /* I - Connection to server */
  * client.  The value returned can be use in subsequent requests (for clients)
  * or in the response (for servers) in order to compress the content stream.
  *
- * @since CUPS 1.7@
+ * @since CUPS 1.7/OS X 10.9@
  */
 
 const char *                           /* O - Content-Coding value or
@@ -1217,49 +1056,32 @@ httpGetContentEncoding(http_t *http)    /* I - Connection to client/server */
 
 
 /*
- * 'httpGetAuthString()' - Get the current authorization string.
- *
- * The authorization string is set by cupsDoAuthentication() and
- * httpSetAuthString().  Use httpGetAuthString() to retrieve the
- * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
- * value.
+ * 'httpGetCookie()' - Get any cookie data from the response.
  *
- * @since CUPS 1.3/OS X 10.5@
+ * @since CUPS 1.1.19/OS X 10.3@
  */
 
-char *                                 /* O - Authorization string */
-httpGetAuthString(http_t *http)                /* I - Connection to server */
+const char *                           /* O - Cookie data or NULL */
+httpGetCookie(http_t *http)            /* I - HTTP connecion */
 {
-  if (http)
-    return (http->authstring);
-  else
-    return (NULL);
+  return (http ? http->cookie : NULL);
 }
 
 
 /*
- * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
+ * 'httpGetEncryption()' - Get the current encryption mode of a connection.
  *
- * @since CUPS 1.2/OS X 10.5@
- */
-
-int                                    /* O - 1 if blocking, 0 if non-blocking */
-httpGetBlocking(http_t *http)          /* I - Connection to server */
-{
-  return (http ? http->blocking : 0);
-}
-
-
-/*
- * 'httpGetCookie()' - Get any cookie data from the response.
+ * This function returns the encryption mode for the connection. Use the
+ * @link httpIsEncrypted@ function to determine whether a TLS session has
+ * been established.
  *
- * @since CUPS 1.1.19/OS X 10.3@
+ * @since CUPS 2.0@
  */
 
-const char *                           /* O - Cookie data or NULL */
-httpGetCookie(http_t *http)            /* I - HTTP connecion */
+http_encryption_t                      /* O - Current encryption mode */
+httpGetEncryption(http_t *http)                /* I - HTTP connection */
 {
-  return (http ? http->cookie : NULL);
+  return (http ? http->encryption : HTTP_ENCRYPTION_IF_REQUESTED);
 }
 
 
@@ -1269,7 +1091,7 @@ httpGetCookie(http_t *http)               /* I - HTTP connecion */
  * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
  * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
  *
- * @since CUPS 1.7@
+ * @since CUPS 1.7/OS X 10.9@
  */
 
 http_status_t                          /* O - Expect: status, if any */
@@ -1289,7 +1111,7 @@ httpGetExpect(http_t *http)               /* I - Connection to client */
  */
 
 int                                    /* O - File descriptor or -1 if none */
-httpGetFd(http_t *http)                        /* I - Connection to server */
+httpGetFd(http_t *http)                        /* I - HTTP connection */
 {
   return (http ? http->fd : -1);
 }
@@ -1300,7 +1122,7 @@ httpGetFd(http_t *http)                   /* I - Connection to server */
  */
 
 const char *                           /* O - Field value */
-httpGetField(http_t       *http,       /* I - Connection to server */
+httpGetField(http_t       *http,       /* I - HTTP connection */
              http_field_t field)       /* I - Field to get */
 {
   if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
@@ -1334,6 +1156,19 @@ httpGetField(http_t       *http, /* I - Connection to server */
 }
 
 
+/*
+ * 'httpGetKeepAlive()' - Get the current Keep-Alive state of the connection.
+ *
+ * @since CUPS 2.0@
+ */
+
+http_keepalive_t                       /* O - Keep-Alive state */
+httpGetKeepAlive(http_t *http)         /* I - HTTP connection */
+{
+  return (http ? http->keep_alive : HTTP_KEEPALIVE_OFF);
+}
+
+
 /*
  * 'httpGetLength()' - Get the amount of data remaining from the
  *                     content-length or transfer-encoding fields.
@@ -1345,7 +1180,7 @@ httpGetField(http_t       *http,  /* I - Connection to server */
  */
 
 int                                    /* O - Content length */
-httpGetLength(http_t *http)            /* I - Connection to server */
+httpGetLength(http_t *http)            /* I - HTTP connection */
 {
  /*
   * Get the read content length and return the 32-bit value.
@@ -1373,13 +1208,13 @@ httpGetLength(http_t *http)             /* I - Connection to server */
  */
 
 off_t                                  /* O - Content length */
-httpGetLength2(http_t *http)           /* I - Connection to server */
+httpGetLength2(http_t *http)           /* I - HTTP connection */
 {
   off_t                        remaining;      /* Remaining length */
 
 
   DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http,
-                http_states[http->state + 1]));
+                httpStateString(http->state)));
 
   if (!http)
     return (-1);
@@ -1406,7 +1241,7 @@ httpGetLength2(http_t *http)              /* I - Connection to server */
       * and 2^31-1 for other successful requests...
       */
 
-      if (http->status >= HTTP_MULTIPLE_CHOICES ||
+      if (http->status >= HTTP_STATUS_MULTIPLE_CHOICES ||
           http->state == HTTP_STATE_OPTIONS ||
           (http->state == HTTP_STATE_GET && http->mode == _HTTP_MODE_SERVER) ||
           http->state == HTTP_STATE_HEAD ||
@@ -1430,6 +1265,71 @@ httpGetLength2(http_t *http)             /* I - Connection to server */
 }
 
 
+/*
+ * 'httpGetPending()' - Get the number of bytes that are buffered for writing.
+ *
+ * @since CUPS 2.0@
+ */
+
+size_t                                 /* O - Number of bytes buffered */
+httpGetPending(http_t *http)           /* I - HTTP connection */
+{
+  return (http ? http->wused : 0);
+}
+
+
+/*
+ * 'httpGetReady()' - Get the number of bytes that can be read without blocking.
+ *
+ * @since CUPS 2.0@
+ */
+
+size_t                                 /* O - Number of bytes available */
+httpGetReady(http_t *http)             /* I - HTTP connection */
+{
+  if (!http)
+    return (0);
+  else if (http->used > 0)
+    return (http->used);
+#ifdef HAVE_SSL
+  else if (http->tls)
+  {
+    size_t     ready;                  /* Ready bytes */
+
+#  ifdef HAVE_LIBSSL
+    if ((ready = SSL_pending((SSL *)(http->tls))) > 0)
+      return (ready);
+#  elif defined(HAVE_GNUTLS)
+    if ((ready = gnutls_record_check_pending(http->tls)) > 0)
+      return (ready);
+#  elif defined(HAVE_CDSASSL)
+    if (!SSLGetBufferedReadSize(http->tls, &ready) && ready > 0)
+      return (ready);
+#  endif /* HAVE_LIBSSL */
+  }
+#endif /* HAVE_SSL */
+
+  return (0);
+}
+
+
+/*
+ * 'httpGetRemaining()' - Get the number of remaining bytes in the message
+ *                        body or current chunk.
+ *
+ * The @link httpIsChunked@ function can be used to determine whether the
+ * message body is chunked or fixed-length.
+ *
+ * @since CUPS 2.0@
+ */
+
+size_t                                 /* O - Remaining bytes */
+httpGetRemaining(http_t *http)         /* I - HTTP connection */
+{
+  return (http ? http->data_remaining : 0);
+}
+
+
 /*
  * 'httpGets()' - Get a line of text from a HTTP connection.
  */
@@ -1437,7 +1337,7 @@ httpGetLength2(http_t *http)              /* I - Connection to server */
 char *                                 /* O - Line or NULL */
 httpGets(char   *line,                 /* I - Line to read into */
          int    length,                        /* I - Max length of buffer */
-        http_t *http)                  /* I - Connection to server */
+        http_t *http)                  /* I - HTTP connection */
 {
   char *lineptr,                       /* Pointer into line */
        *lineend,                       /* End of line */
@@ -1449,7 +1349,7 @@ httpGets(char   *line,                    /* I - Line to read into */
 
   DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line, length, http));
 
-  if (http == NULL || line == NULL)
+  if (!http || !line || length <= 1)
     return (NULL);
 
  /*
@@ -1493,20 +1393,10 @@ httpGets(char   *line,                  /* I - Line to read into */
         return (NULL);
       }
 
-#ifdef HAVE_SSL
-      if (http->tls)
-       bytes = http_read_ssl(http, http->buffer + http->used,
-                             HTTP_MAX_BUFFER - http->used);
-      else
-#endif /* HAVE_SSL */
-        bytes = recv(http->fd, http->buffer + http->used,
-                    HTTP_MAX_BUFFER - http->used, 0);
-
-      DEBUG_printf(("4httpGets: read %d bytes...", bytes));
+      bytes = http_read(http, http->buffer + http->used,
+                        HTTP_MAX_BUFFER - http->used);
 
-#ifdef DEBUG
-      http_debug_hex("httpGets", http->buffer + http->used, bytes);
-#endif /* DEBUG */
+      DEBUG_printf(("4httpGets: read %d bytes.", bytes));
 
       if (bytes < 0)
       {
@@ -1619,7 +1509,7 @@ httpGets(char   *line,                    /* I - Line to read into */
  */
 
 http_state_t                           /* O - HTTP state */
-httpGetState(http_t *http)             /* I - Connection to server */
+httpGetState(http_t *http)             /* I - HTTP connection */
 {
   return (http ? http->state : HTTP_STATE_ERROR);
 }
@@ -1632,9 +1522,9 @@ httpGetState(http_t *http)                /* I - Connection to server */
  */
 
 http_status_t                          /* O - HTTP status */
-httpGetStatus(http_t *http)            /* I - Connection to server */
+httpGetStatus(http_t *http)            /* I - HTTP connection */
 {
-  return (http ? http->status : HTTP_ERROR);
+  return (http ? http->status : HTTP_STATUS_ERROR);
 }
 
 
@@ -1645,7 +1535,7 @@ httpGetStatus(http_t *http)               /* I - Connection to server */
  */
 
 char *                                 /* O - Value or NULL */
-httpGetSubField(http_t       *http,    /* I - Connection to server */
+httpGetSubField(http_t       *http,    /* I - HTTP connection */
                 http_field_t field,    /* I - Field index */
                 const char   *name,    /* I - Name of sub-field */
                char         *value)    /* O - Value string */
@@ -1661,7 +1551,7 @@ httpGetSubField(http_t       *http,       /* I - Connection to server */
  */
 
 char *                                 /* O - Value or NULL */
-httpGetSubField2(http_t       *http,   /* I - Connection to server */
+httpGetSubField2(http_t       *http,   /* I - HTTP connection */
                  http_field_t field,   /* I - Field index */
                  const char   *name,   /* I - Name of sub-field */
                 char         *value,   /* O - Value string */
@@ -1791,7 +1681,7 @@ httpGetSubField2(http_t       *http,      /* I - Connection to server */
  */
 
 http_version_t                         /* O - Version number */
-httpGetVersion(http_t *http)           /* I - Connection to server */
+httpGetVersion(http_t *http)           /* I - HTTP connection */
 {
   return (http ? http->version : HTTP_VERSION_1_0);
 }
@@ -1802,11 +1692,11 @@ httpGetVersion(http_t *http)            /* I - Connection to server */
  */
 
 int                                    /* O - Status of call (0 = success) */
-httpHead(http_t     *http,             /* I - Connection to server */
+httpHead(http_t     *http,             /* I - HTTP connection */
          const char *uri)              /* I - URI for head */
 {
   DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http, uri));
-  return (http_send(http, HTTP_HEAD, uri));
+  return (http_send(http, HTTP_STATE_HEAD, uri));
 }
 
 
@@ -1893,33 +1783,64 @@ httpInitialize(void)
 
 
 /*
- * 'httpOptions()' - Send an OPTIONS request to the server.
+ * 'httpIsChunked()' - Report whether a message body is chunked.
+ *
+ * This function returns non-zero if the message body is composed of
+ * variable-length chunks.
+ *
+ * @since CUPS 2.0@
  */
 
-int                                    /* O - Status of call (0 = success) */
-httpOptions(http_t     *http,          /* I - Connection to server */
-            const char *uri)           /* I - URI for options */
+int                                    /* O - 1 if chunked, 0 if not */
+httpIsChunked(http_t *http)            /* I - HTTP connection */
 {
-  return (http_send(http, HTTP_OPTIONS, uri));
+  return (http ? http->data_encoding == HTTP_ENCODING_CHUNKED : 0);
 }
 
 
 /*
- * 'httpPeek()' - Peek at data from a HTTP connection.
+ * 'httpIsEncrypted()' - Report whether a connection is encrypted.
  *
- * This function copies available data from the given HTTP connection, reading
- * a buffer as needed.  The data is still available for reading using
- * @link httpRead@ or @link httpRead2@.
- *
- * For non-blocking connections the usual timeouts apply.
+ * This function returns non-zero if the connection is currently encrypted.
  *
- * @since CUPS 1.7@
+ * @since CUPS 2.0@
  */
 
-ssize_t                                        /* O - Number of bytes copied */
-httpPeek(http_t *http,                 /* I - Connection to server */
-          char   *buffer,              /* I - Buffer for data */
-         size_t length)                /* I - Maximum number of bytes */
+int                                    /* O - 1 if encrypted, 0 if not */
+httpIsEncrypted(http_t *http)          /* I - HTTP connection */
+{
+  return (http ? http->tls != NULL : 0);
+}
+
+
+/*
+ * 'httpOptions()' - Send an OPTIONS request to the server.
+ */
+
+int                                    /* O - Status of call (0 = success) */
+httpOptions(http_t     *http,          /* I - HTTP connection */
+            const char *uri)           /* I - URI for options */
+{
+  return (http_send(http, HTTP_STATE_OPTIONS, uri));
+}
+
+
+/*
+ * 'httpPeek()' - Peek at data from a HTTP connection.
+ *
+ * This function copies available data from the given HTTP connection, reading
+ * a buffer as needed.  The data is still available for reading using
+ * @link httpRead@ or @link httpRead2@.
+ *
+ * For non-blocking connections the usual timeouts apply.
+ *
+ * @since CUPS 1.7/OS X 10.9@
+ */
+
+ssize_t                                        /* O - Number of bytes copied */
+httpPeek(http_t *http,                 /* I - HTTP connection */
+         char   *buffer,               /* I - Buffer for data */
+        size_t length)                 /* I - Maximum number of bytes */
 {
   ssize_t      bytes;                  /* Bytes read */
   char         len[32];                /* Length string */
@@ -1948,7 +1869,18 @@ httpPeek(http_t *http,                   /* I - Connection to server */
       return (0);
     }
 
+    if (!len[0])
+    {
+      DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
+      if (!httpGets(len, sizeof(len), http))
+      {
+       DEBUG_puts("1httpPeek: Could not get chunk length.");
+       return (0);
+      }
+    }
+
     http->data_remaining = strtoll(len, NULL, 16);
+
     if (http->data_remaining < 0)
     {
       DEBUG_puts("1httpPeek: Negative chunk length!");
@@ -1959,28 +1891,28 @@ httpPeek(http_t *http,                  /* I - Connection to server */
   DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT,
                 CUPS_LLCAST http->data_remaining));
 
-  if (http->data_remaining <= 0)
+  if (http->data_remaining <= 0 && http->data_encoding != HTTP_ENCODING_FIELDS)
   {
    /*
     * A zero-length chunk ends a transfer; unless we are reading POST
     * data, go idle...
     */
 
-    if (http->data_encoding == HTTP_ENCODING_CHUNKED)
-      httpGets(len, sizeof(len), http);
-
 #ifdef HAVE_LIBZ
     if (http->coding)
       http_content_coding_finish(http);
 #endif /* HAVE_LIBZ */
 
+    if (http->data_encoding == HTTP_ENCODING_CHUNKED)
+      httpGets(len, sizeof(len), http);
+
     if (http->state == HTTP_STATE_POST_RECV)
       http->state ++;
     else
-      http->state = HTTP_STATE_WAITING;
+      http->state = HTTP_STATE_STATUS;
 
     DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
-                  http_states[http->state + 1]));
+                  httpStateString(http->state)));
 
    /*
     * Prevent future reads for this request...
@@ -1990,12 +1922,15 @@ httpPeek(http_t *http,                  /* I - Connection to server */
 
     return (0);
   }
-  else if ((http->data_encoding == HTTP_ENCODING_LENGTH ||
-            http->coding == _HTTP_CODING_IDENTITY) &&
-           length > (size_t)http->data_remaining)
+  else if (length > (size_t)http->data_remaining)
     length = (size_t)http->data_remaining;
 
+#ifdef HAVE_LIBZ
+  if (http->used == 0 &&
+      (http->coding == _HTTP_CODING_IDENTITY || http->stream.avail_in == 0))
+#else
   if (http->used == 0)
+#endif /* HAVE_LIBZ */
   {
    /*
     * Buffer small reads for better performance...
@@ -2020,80 +1955,58 @@ httpPeek(http_t *http,                  /* I - Connection to server */
       buflen = http->data_remaining;
 
     DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen));
-
-    do
-    {
-#ifdef HAVE_SSL
-      if (http->tls)
-       bytes = http_read_ssl(http, http->buffer, buflen);
-      else
-#endif /* HAVE_SSL */
-      bytes = recv(http->fd, http->buffer, buflen, 0);
-
-      if (bytes < 0)
-      {
-#ifdef WIN32
-       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 == 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);
-       }
-#endif /* WIN32 */
-      }
-    }
-    while (bytes < 0);
+    bytes = http_read(http, http->buffer, buflen);
 
     DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT " bytes into buffer.",
                   CUPS_LLCAST bytes));
+    if (bytes > 0)
+    {
 #ifdef DEBUG
-    http_debug_hex("httpPeek", http->buffer, (int)bytes);
+      http_debug_hex("httpPeek", http->buffer, (int)bytes);
 #endif /* DEBUG */
 
-    http->used = bytes;
+      http->used = bytes;
+    }
   }
 
 #ifdef HAVE_LIBZ
   if (http->coding)
   {
+#  ifdef HAVE_INFLATECOPY
     int                zerr;                   /* Decompressor error */
-    off_t      comp_avail;             /* Maximum bytes for decompression */
     z_stream   stream;                 /* Copy of decompressor stream */
 
-    if (http->used > http->data_remaining)
-      comp_avail = http->data_remaining;
-    else
-      comp_avail = http->used;
+    if (http->used > 0 && http->stream.avail_in < HTTP_MAX_BUFFER)
+    {
+      size_t buflen = buflen = HTTP_MAX_BUFFER - http->stream.avail_in;
+                                       /* Number of bytes to copy */
+
+      if (http->stream.avail_in > 0 &&
+         http->stream.next_in > http->dbuffer)
+        memmove(http->dbuffer, http->stream.next_in, http->stream.avail_in);
+
+      http->stream.next_in = http->dbuffer;
+
+      if (buflen > http->data_remaining)
+        buflen = http->data_remaining;
+
+      if (buflen > http->used)
+        buflen = http->used;
+
+      DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
+                   "decompression buffer.", (int)buflen));
+
+      memcpy(http->dbuffer + http->stream.avail_in, http->buffer, buflen);
+      http->stream.avail_in += buflen;
+      http->used            -= buflen;
+      http->data_remaining  -= buflen;
+
+      if (http->used > 0)
+        memmove(http->buffer, http->buffer + buflen, http->used);
+    }
 
     DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length,
-                  (int)comp_avail));
+                  (int)http->stream.avail_in));
 
     if (inflateCopy(&stream, &(http->stream)) != Z_OK)
     {
@@ -2102,8 +2015,6 @@ httpPeek(http_t *http,                    /* I - Connection to server */
       return (-1);
     }
 
-    stream.next_in   = (Bytef *)http->buffer;
-    stream.avail_in  = comp_avail;
     stream.next_out  = (Bytef *)buffer;
     stream.avail_out = length;
 
@@ -2113,11 +2024,22 @@ httpPeek(http_t *http,                  /* I - Connection to server */
     if (zerr < Z_OK)
     {
       DEBUG_printf(("2httpPeek: zerr=%d", zerr));
+#ifdef DEBUG
+      http_debug_hex("2httpPeek", (char *)http->dbuffer,
+                    http->stream.avail_in);
+#endif /* DEBUG */
+
       http->error = EIO;
       return (-1);
     }
 
     bytes = length - http->stream.avail_out;
+
+#  else
+    DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
+               "work with compressed streams.");
+    return (-1);
+#  endif /* HAVE_INFLATECOPY */
   }
   else
 #endif /* HAVE_LIBZ */
@@ -2156,10 +2078,6 @@ httpPeek(http_t *http,                   /* I - Connection to server */
     return (0);
   }
 
-#ifdef DEBUG
-  http_debug_hex("httpPeek", buffer, (int)bytes);
-#endif /* DEBUG */
-
   return (bytes);
 }
 
@@ -2173,10 +2091,10 @@ ssize_t _httpPeek(http_t *http, char *buffer, size_t length)
  */
 
 int                                    /* O - Status of call (0 = success) */
-httpPost(http_t     *http,             /* I - Connection to server */
+httpPost(http_t     *http,             /* I - HTTP connection */
          const char *uri)              /* I - URI for post */
 {
-  return (http_send(http, HTTP_POST, uri));
+  return (http_send(http, HTTP_STATE_POST, uri));
 }
 
 
@@ -2187,7 +2105,7 @@ httpPost(http_t     *http,                /* I - Connection to server */
  */
 
 int                                    /* O - Number of bytes written */
-httpPrintf(http_t     *http,           /* I - Connection to server */
+httpPrintf(http_t     *http,           /* I - HTTP connection */
            const char *format,         /* I - printf-style format string */
           ...)                         /* I - Additional args as needed */
 {
@@ -2226,11 +2144,11 @@ httpPrintf(http_t     *http,            /* I - Connection to server */
  */
 
 int                                    /* O - Status of call (0 = success) */
-httpPut(http_t     *http,              /* I - Connection to server */
+httpPut(http_t     *http,              /* I - HTTP connection */
         const char *uri)               /* I - URI to put */
 {
   DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http, uri));
-  return (http_send(http, HTTP_PUT, uri));
+  return (http_send(http, HTTP_STATE_PUT, uri));
 }
 
 
@@ -2244,7 +2162,7 @@ httpPut(http_t     *http,         /* I - Connection to server */
  */
 
 int                                    /* O - Number of bytes read */
-httpRead(http_t *http,                 /* I - Connection to server */
+httpRead(http_t *http,                 /* I - HTTP connection */
          char   *buffer,               /* I - Buffer for data */
         int    length)                 /* I - Maximum number of bytes */
 {
@@ -2259,17 +2177,25 @@ httpRead(http_t *http,                  /* I - Connection to server */
  */
 
 ssize_t                                        /* O - Number of bytes read */
-httpRead2(http_t *http,                        /* I - Connection to server */
+httpRead2(http_t *http,                        /* I - HTTP connection */
           char   *buffer,              /* I - Buffer for data */
          size_t length)                /* I - Maximum number of bytes */
 {
   ssize_t      bytes;                  /* Bytes read */
-  char         len[32];                /* Length string */
 
 
+#ifdef HAVE_LIBZ
   DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
-                ") coding=%d", http, buffer, CUPS_LLCAST length,
-                http->coding));
+                ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT,
+                http, buffer, CUPS_LLCAST length,
+                http->coding,
+                http->data_encoding, CUPS_LLCAST http->data_remaining));
+#else
+  DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
+                ") data_encoding=%d data_remaining=" CUPS_LLFMT,
+                http, buffer, CUPS_LLCAST length,
+                http->data_encoding, CUPS_LLCAST http->data_remaining));
+#endif /* HAVE_LIBZ */
 
   if (http == NULL || buffer == NULL)
     return (-1);
@@ -2280,371 +2206,182 @@ httpRead2(http_t *http,                       /* I - Connection to server */
   if (length <= 0)
     return (0);
 
-  if (http->data_encoding == HTTP_ENCODING_CHUNKED &&
-      http->data_remaining <= 0)
-  {
-    if (!httpGets(len, sizeof(len), http))
-    {
-      DEBUG_puts("1httpRead2: Could not get chunk length.");
-      return (0);
-    }
-
-    if (!len[0])
-    {
-      DEBUG_puts("1httpRead2: Blank chunk length, trying again...");
-      if (!httpGets(len, sizeof(len), http))
-      {
-       DEBUG_puts("1httpRead2: Could not get chunk length.");
-       return (0);
-      }
-    }
-
-    http->data_remaining = strtoll(len, NULL, 16);
-
-    if (http->data_remaining < 0)
-    {
-      DEBUG_printf(("1httpRead2: Negative chunk length \"%s\" (" CUPS_LLFMT ")",
-                    len, CUPS_LLCAST http->data_remaining));
-      return (0);
-    }
-
-    DEBUG_printf(("2httpRead2: Got chunk length \"%s\" (" CUPS_LLFMT ")", len,
-                  CUPS_LLCAST http->data_remaining));
-  }
-
-  DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT ", used=%d",
-                CUPS_LLCAST http->data_remaining, http->used));
-
-  if (http->data_remaining <= 0 && http->data_encoding != HTTP_ENCODING_FIELDS)
-  {
-   /*
-    * A zero-length chunk ends a transfer; unless we are reading POST
-    * data, go idle...
-    */
-
-#ifdef HAVE_LIBZ
-    if (http->coding)
-      http_content_coding_finish(http);
-#endif /* HAVE_LIBZ */
-
-    if (http->data_encoding == HTTP_ENCODING_CHUNKED)
-      httpGets(len, sizeof(len), http);
-
-    if (http->state == HTTP_STATE_POST_RECV)
-      http->state ++;
-    else
-      http->state = HTTP_STATE_WAITING;
-
-    DEBUG_printf(("1httpRead2: 0-length chunk, set state to %s.",
-                  http_states[http->state + 1]));
-
-   /*
-    * Prevent future reads for this request...
-    */
-
-    http->data_encoding = HTTP_ENCODING_FIELDS;
-
-    return (0);
-  }
-  else if ((http->data_encoding == HTTP_ENCODING_LENGTH ||
-            http->coding == _HTTP_CODING_IDENTITY) &&
-           length > (size_t)http->data_remaining)
-    length = (size_t)http->data_remaining;
-
 #ifdef HAVE_LIBZ
-  if (http->used == 0 && (length <= 256 || http->coding))
-#else
-  if (http->used == 0 && length <= 256)
-#endif /* HAVE_LIBZ */
+  if (http->coding)
   {
-   /*
-    * Buffer small/compressed reads for better performance...
-    */
-
-    ssize_t    buflen;                 /* Length of read for buffer */
-
-    if (!http->blocking)
+    do
     {
-      while (!httpWait(http, http->wait_value))
+      if (http->stream.avail_in > 0)
       {
-       if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
-         continue;
-
-       return (0);
-      }
-    }
-
-    if (http->data_remaining > sizeof(http->buffer))
-      buflen = sizeof(http->buffer);
-    else
-      buflen = http->data_remaining;
+       int     zerr;                   /* Decompressor error */
 
-    DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen));
+       DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
+                     (int)http->stream.avail_in, (int)length));
 
-    do
-    {
-#ifdef HAVE_SSL
-      if (http->tls)
-       bytes = http_read_ssl(http, http->buffer, buflen);
-      else
-#endif /* HAVE_SSL */
-      bytes = recv(http->fd, http->buffer, buflen, 0);
+       http->stream.next_out  = (Bytef *)buffer;
+       http->stream.avail_out = length;
 
-      if (bytes < 0)
-      {
-#ifdef WIN32
-       if (WSAGetLastError() != WSAEINTR)
+       if ((zerr = inflate(&(http->stream), Z_SYNC_FLUSH)) < Z_OK)
        {
-         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 == 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);
-       }
-#endif /* WIN32 */
-      }
-    }
-    while (bytes < 0);
-
-    DEBUG_printf(("2httpRead2: Read " CUPS_LLFMT " bytes into buffer.",
-                  CUPS_LLCAST bytes));
+         DEBUG_printf(("2httpRead2: zerr=%d", zerr));
 #ifdef DEBUG
-    http_debug_hex("httpRead2", http->buffer, (int)bytes);
+          http_debug_hex("2httpRead2", (char *)http->dbuffer,
+                         http->stream.avail_in);
 #endif /* DEBUG */
 
-    http->used = bytes;
-  }
-
-#ifdef HAVE_LIBZ
-  if (http->coding)
-  {
-    int                zerr;                   /* Decompressor error */
-    off_t      comp_avail,             /* Maximum bytes for decompression */
-               comp_bytes;             /* Compressed bytes "used" */
-
-    if (http->used > http->data_remaining)
-      comp_avail = http->data_remaining;
-    else
-      comp_avail = http->used;
-
-    DEBUG_printf(("2httpRead2: length=%d, avail_in=%d", (int)length,
-                  (int)comp_avail));
-
-    http->stream.next_in   = (Bytef *)http->buffer;
-    http->stream.avail_in  = comp_avail;
-    http->stream.next_out  = (Bytef *)buffer;
-    http->stream.avail_out = length;
-
-    if ((zerr = inflate(&(http->stream), Z_SYNC_FLUSH)) < Z_OK)
-    {
-      DEBUG_printf(("2httpRead2: zerr=%d", zerr));
-      http->error = EIO;
-      return (-1);
-    }
-
-    bytes      = length - http->stream.avail_out;
-    comp_bytes = comp_avail - http->stream.avail_in;
-
-    DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d, "
-                  "comp_bytes=%d", http->stream.avail_in,
-                  http->stream.avail_out, (int)bytes, (int)comp_bytes));
-
-    if ((http->used - comp_bytes) > 0)
-    {
-      http->used -= comp_bytes;
-      memmove(http->buffer, http->stream.next_in, http->used);
-    }
-    else
-      http->used = 0;
-
-   /*
-    * Adjust remaining bytes since chunk/content lengths are compressed while
-    * CUPS HTTP APIs return uncompressed sizes...
-    */
-
-    http->data_remaining += bytes - comp_bytes;
-  }
-  else
-#endif /* HAVE_LIBZ */
-  if (http->used > 0)
-  {
-    if (length > (size_t)http->used)
-      length = (size_t)http->used;
-
-    bytes = (ssize_t)length;
-
-    DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
-                  (int)bytes));
+         http->error = EIO;
+         return (-1);
+       }
 
-    memcpy(buffer, http->buffer, length);
-    http->used -= (int)length;
+       bytes = length - http->stream.avail_out;
 
-    if (http->used > 0)
-      memmove(http->buffer, http->buffer + length, http->used);
-  }
-#ifdef HAVE_SSL
-  else if (http->tls)
-  {
-    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: avail_in=%d, avail_out=%d, bytes=%d",
+                     http->stream.avail_in, http->stream.avail_out,
+                     (int)bytes));
       }
-    }
+      else
+        bytes = 0;
 
-    while ((bytes = (ssize_t)http_read_ssl(http, buffer, (int)length)) < 0)
-    {
-#ifdef WIN32
-      if (WSAGetLastError() == WSAEWOULDBLOCK)
-      {
-        if (!http->timeout_cb || !(*http->timeout_cb)(http, http->timeout_data))
-         break;
-      }
-      else if (WSAGetLastError() != WSAEINTR)
-        break;
-#else
-      if (errno == EWOULDBLOCK || errno == EAGAIN)
+      if (bytes == 0)
       {
-        if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
-         break;
-        else if (!http->timeout_cb && errno != EAGAIN)
-         break;
+        ssize_t buflen = HTTP_MAX_BUFFER - http->stream.avail_in;
+                                       /* Additional bytes for buffer */
+
+        if (buflen > 0)
+        {
+          if (http->stream.avail_in > 0 &&
+              http->stream.next_in > http->dbuffer)
+            memmove(http->dbuffer, http->stream.next_in, http->stream.avail_in);
+
+         http->stream.next_in = http->dbuffer;
+
+          DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
+                        "decompression buffer.", (int)buflen));
+
+          if (http->data_remaining > 0)
+          {
+           if (buflen > http->data_remaining)
+             buflen = http->data_remaining;
+
+           bytes = http_read_buffered(http,
+                                      (char *)http->dbuffer +
+                                              http->stream.avail_in, buflen);
+          }
+          else if (http->data_encoding == HTTP_ENCODING_CHUNKED)
+            bytes = http_read_chunk(http,
+                                   (char *)http->dbuffer +
+                                       http->stream.avail_in, buflen);
+          else
+            bytes = 0;
+
+          if (bytes < 0)
+            return (bytes);
+          else if (bytes == 0)
+            break;
+
+          DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT " bytes to "
+                        "decompression buffer.", CUPS_LLCAST bytes));
+
+          http->data_remaining  -= bytes;
+          http->stream.avail_in += bytes;
+
+         if (http->data_remaining <= 0 &&
+             http->data_encoding == HTTP_ENCODING_CHUNKED)
+         {
+          /*
+           * Read the trailing blank line now...
+           */
+
+           char        len[32];                /* Length string */
+
+           httpGets(len, sizeof(len), http);
+         }
+
+          bytes = 0;
+        }
+        else
+          return (0);
       }
-      else if (errno != EINTR)
-        break;
-#endif /* WIN32 */
     }
+    while (bytes == 0);
   }
-#endif /* HAVE_SSL */
   else
+#endif /* HAVE_LIBZ */
+  if (http->data_remaining == 0 && http->data_encoding == HTTP_ENCODING_CHUNKED)
   {
-    if (!http->blocking)
+    if ((bytes = http_read_chunk(http, buffer, length)) > 0)
     {
-      while (!httpWait(http, http->wait_value))
-      {
-       if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
-         continue;
+      http->data_remaining -= bytes;
 
-       return (0);
-      }
-    }
+      if (http->data_remaining <= 0)
+      {
+       /*
+        * Read the trailing blank line now...
+        */
 
-    DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT " bytes from socket...",
-                  CUPS_LLCAST length));
+        char   len[32];                /* Length string */
 
-#ifdef WIN32
-    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 == EWOULDBLOCK || errno == EAGAIN)
-      {
-        if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
-         break;
-        else if (!http->timeout_cb && errno != EAGAIN)
-         break;
+        httpGets(len, sizeof(len), http);
       }
-      else if (errno != EINTR)
-        break;
     }
-#endif /* WIN32 */
-
-    DEBUG_printf(("2httpRead2: read " CUPS_LLFMT " bytes from socket...",
-                  CUPS_LLCAST bytes));
-#ifdef DEBUG
-    http_debug_hex("httpRead2", buffer, (int)bytes);
-#endif /* DEBUG */
   }
-
-  if (bytes > 0)
+  else if (http->data_remaining <= 0)
   {
-    http->data_remaining -= bytes;
+   /*
+    * No more data to read...
+    */
 
-    if (http->data_remaining <= INT_MAX)
-      http->_data_remaining = (int)http->data_remaining;
-    else
-      http->_data_remaining = INT_MAX;
-  }
-  else if (bytes < 0)
-  {
-#ifdef WIN32
-    if (WSAGetLastError() == WSAEINTR)
-      bytes = 0;
-    else
-      http->error = WSAGetLastError();
-#else
-    if (errno == EINTR || (errno == EAGAIN && !http->timeout_cb))
-      bytes = 0;
-    else
-      http->error = errno;
-#endif /* WIN32 */
+    return (0);
   }
   else
   {
-    http->error = EPIPE;
-    return (0);
-  }
+    DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
+                  (int)length));
 
-  if (http->data_remaining <= 0)
-  {
-    if (http->data_encoding == HTTP_ENCODING_CHUNKED)
+    if (length > (size_t)http->data_remaining)
+      length = (size_t)http->data_remaining;
+
+    if ((bytes = http_read_buffered(http, buffer, length)) > 0)
     {
-      DEBUG_puts("1httpRead2: Reading trailing line for chunk.");
-      httpGets(len, sizeof(len), http);
+      http->data_remaining -= bytes;
+
+      if (http->data_remaining <= 0 &&
+          http->data_encoding == HTTP_ENCODING_CHUNKED)
+      {
+       /*
+        * Read the trailing blank line now...
+        */
+
+        char   len[32];                /* Length string */
+
+        httpGets(len, sizeof(len), http);
+      }
     }
-    else
-    {
+  }
+
+  if (
+#ifdef HAVE_LIBZ
+      (http->coding == _HTTP_CODING_IDENTITY || http->stream.avail_in == 0) &&
+#endif /* HAVE_LIBZ */
+      ((http->data_remaining <= 0 &&
+        http->data_encoding == HTTP_ENCODING_LENGTH) ||
+       (http->data_encoding == HTTP_ENCODING_CHUNKED && bytes == 0)))
+  {
 #ifdef HAVE_LIBZ
-      if (http->coding)
-       http_content_coding_finish(http);
+    if (http->coding)
+      http_content_coding_finish(http);
 #endif /* HAVE_LIBZ */
 
-      if (http->state == HTTP_STATE_POST_RECV)
-        http->state ++;
-      else
-        http->state = HTTP_STATE_WAITING;
+    if (http->state == HTTP_STATE_POST_RECV)
+      http->state ++;
+    else if (http->state == HTTP_STATE_GET_SEND ||
+             http->state == HTTP_STATE_POST_SEND)
+      http->state = HTTP_STATE_WAITING;
+    else
+      http->state = HTTP_STATE_STATUS;
 
-      DEBUG_printf(("1httpRead2: End of content, set state to %s.",
-                    http_states[http->state + 1]));
-    }
+    DEBUG_printf(("1httpRead2: End of content, set state to %s.",
+                 httpStateString(http->state)));
   }
 
   return (bytes);
@@ -2724,7 +2461,7 @@ _httpReadCDSA(
 
 ssize_t                                        /* O - Number of bytes read or -1 on error */
 _httpReadGNUTLS(
-    gnutls_transport_ptr ptr,          /* I - Connection to server */
+    gnutls_transport_ptr ptr,          /* I - HTTP connection */
     void                 *data,                /* I - Buffer */
     size_t               length)       /* I - Number of bytes to read */
 {
@@ -2762,7 +2499,7 @@ _httpReadGNUTLS(
 /*
  * 'httpReadRequest()' - Read a HTTP request from a connection.
  *
- * @since CUPS 1.7@
+ * @since CUPS 1.7/OS X 10.9@
  */
 
 http_state_t                           /* O - New state of connection */
@@ -2794,7 +2531,7 @@ httpReadRequest(http_t *http,             /* I - HTTP connection */
   else if (http->state != HTTP_STATE_WAITING)
   {
     DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
-                  http_states[http->state + 1]));
+                  httpStateString(http->state)));
     return (HTTP_STATE_ERROR);
   }
 
@@ -2842,6 +2579,7 @@ httpReadRequest(http_t *http,             /* I - HTTP connection */
   if (!*req_uri)
   {
     DEBUG_puts("1httpReadRequest: No request URI.");
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No request URI."), 1);
     return (HTTP_STATE_ERROR);
   }
 
@@ -2858,6 +2596,7 @@ httpReadRequest(http_t *http,             /* I - HTTP connection */
   if (!*req_version)
   {
     DEBUG_puts("1httpReadRequest: No request protocol version.");
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No request protocol version."), 1);
     return (HTTP_STATE_ERROR);
   }
 
@@ -2889,11 +2628,12 @@ httpReadRequest(http_t *http,           /* I - HTTP connection */
   else
   {
     DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method));
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unknown request method."), 1);
     return (HTTP_STATE_UNKNOWN_METHOD);
   }
 
   DEBUG_printf(("1httpReadRequest: Set state to %s.",
-                http_states[http->state + 1]));
+                httpStateString(http->state)));
 
   if (!strcmp(req_version, "HTTP/1.0"))
   {
@@ -2908,6 +2648,7 @@ httpReadRequest(http_t *http,             /* I - HTTP connection */
   else
   {
     DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version));
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unknown request version."), 1);
     return (HTTP_STATE_UNKNOWN_VERSION);
   }
 
@@ -2928,7 +2669,7 @@ httpReadRequest(http_t *http,             /* I - HTTP connection */
  */
 
 int                                    /* O - 0 on success, non-zero on failure */
-httpReconnect(http_t *http)            /* I - Connection to server */
+httpReconnect(http_t *http)            /* I - HTTP connection */
 {
   DEBUG_printf(("httpReconnect(http=%p)", http));
 
@@ -2942,7 +2683,7 @@ httpReconnect(http_t *http)               /* I - Connection to server */
  */
 
 int                                    /* O - 0 on success, non-zero on failure */
-httpReconnect2(http_t *http,           /* I - Connection to server */
+httpReconnect2(http_t *http,           /* I - HTTP connection */
               int    msec,             /* I - Timeout in milliseconds */
               int    *cancel)          /* I - Pointer to "cancel" variable */
 {
@@ -2958,7 +2699,7 @@ httpReconnect2(http_t *http,              /* I - Connection to server */
 
   if (!http)
   {
-    _cupsSetError(IPP_INTERNAL_ERROR, strerror(EINVAL), 0);
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
     return (-1);
   }
 
@@ -2978,11 +2719,7 @@ httpReconnect2(http_t *http,             /* I - Connection to server */
   {
     DEBUG_printf(("2httpReconnect2: Closing socket %d...", http->fd));
 
-#ifdef WIN32
-    closesocket(http->fd);
-#else
-    close(http->fd);
-#endif /* WIN32 */
+    httpAddrClose(NULL, http->fd);
 
     http->fd = -1;
   }
@@ -2992,14 +2729,12 @@ httpReconnect2(http_t *http,            /* I - Connection to server */
   */
 
   http->state           = HTTP_STATE_WAITING;
-  http->status          = HTTP_STATUS_CONTINUE;
   http->version         = HTTP_VERSION_1_1;
   http->keep_alive      = HTTP_KEEPALIVE_OFF;
   memset(&http->_hostaddr, 0, sizeof(http->_hostaddr));
   http->data_encoding   = HTTP_ENCODING_FIELDS;
   http->_data_remaining = 0;
   http->used            = 0;
-  http->expect          = 0;
   http->data_remaining  = 0;
   http->hostaddr        = NULL;
   http->wused           = 0;
@@ -3027,7 +2762,7 @@ httpReconnect2(http_t *http,              /* I - Connection to server */
 #else
     http->error  = errno;
 #endif /* WIN32 */
-    http->status = HTTP_ERROR;
+    http->status = HTTP_STATUS_ERROR;
 
     DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
                   strerror(http->error)));
@@ -3044,7 +2779,7 @@ httpReconnect2(http_t *http,              /* I - Connection to server */
   http->error    = 0;
 
 #ifdef HAVE_SSL
-  if (http->encryption == HTTP_ENCRYPT_ALWAYS)
+  if (http->encryption == HTTP_ENCRYPTION_ALWAYS)
   {
    /*
     * Always do encryption via SSL.
@@ -3052,16 +2787,12 @@ httpReconnect2(http_t *http,            /* I - Connection to server */
 
     if (http_setup_ssl(http) != 0)
     {
-#  ifdef WIN32
-      closesocket(http->fd);
-#  else
-      close(http->fd);
-#  endif /* WIN32 */
+      httpAddrClose(NULL, http->fd);
 
       return (-1);
     }
   }
-  else if (http->encryption == HTTP_ENCRYPT_REQUIRED)
+  else if (http->encryption == HTTP_ENCRYPTION_REQUIRED && !http->tls_upgrade)
     return (http_upgrade(http));
 #endif /* HAVE_SSL */
 
@@ -3085,7 +2816,7 @@ httpReconnect2(http_t *http,              /* I - Connection to server */
  */
 
 void
-httpSetAuthString(http_t     *http,    /* I - Connection to server */
+httpSetAuthString(http_t     *http,    /* I - HTTP connection */
                   const char *scheme,  /* I - Auth scheme (NULL to clear it) */
                  const char *data)     /* I - Auth data (NULL for none) */
 {
@@ -3142,7 +2873,7 @@ httpSetAuthString(http_t     *http,       /* I - Connection to server */
  */
 
 int                                            /* O - Status of call (0 = success) */
-httpSetCredentials(http_t      *http,          /* I - Connection to server */
+httpSetCredentials(http_t      *http,          /* I - HTTP connection */
                   cups_array_t *credentials)   /* I - Array of credentials */
 {
   if (!http || cupsArrayCount(credentials) < 1)
@@ -3182,14 +2913,14 @@ httpSetCookie(http_t     *http,         /* I - Connection */
 /*
  * 'httpSetDefaultField()' - Set the default value of an HTTP header.
  *
- * Currently only HTTP_FIELD_ACCEPT_ENCODING, HTTP_FIELD_SERVER, and
- * HTTP_FIELD_USER_AGENT can be set.
+ * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
+ * and @code HTTP_FIELD_USER_AGENT@ can be set.
  *
- * @since CUPS 1.7@
+ * @since CUPS 1.7/OS X 10.9@
  */
 
 void
-httpSetDefaultField(http_t       *http,        /* I - Connection to server */
+httpSetDefaultField(http_t       *http,        /* I - HTTP connection */
                     http_field_t field,        /* I - Field index */
                    const char   *value)/* I - Value */
 {
@@ -3239,10 +2970,12 @@ httpSetDefaultField(http_t       *http, /* I - Connection to server */
  */
 
 void
-httpSetExpect(http_t        *http,     /* I - Connection to server */
+httpSetExpect(http_t        *http,     /* I - HTTP connection */
               http_status_t expect)    /* I - HTTP status to expect
-                                              (@code HTTP_CONTINUE@) */
+                                              (@code HTTP_STATUS_CONTINUE@) */
 {
+  DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http, expect));
+
   if (http)
     http->expect = expect;
 }
@@ -3253,7 +2986,7 @@ httpSetExpect(http_t        *http,        /* I - Connection to server */
  */
 
 void
-httpSetField(http_t       *http,       /* I - Connection to server */
+httpSetField(http_t       *http,       /* I - HTTP connection */
              http_field_t field,       /* I - Field index */
             const char   *value)       /* I - Value */
 {
@@ -3355,6 +3088,22 @@ httpSetField(http_t       *http, /* I - Connection to server */
 }
 
 
+/*
+ * 'httpSetKeepAlive()' - Set the current Keep-Alive state of a connection.
+ *
+ * @since CUPS 2.0@
+ */
+
+void
+httpSetKeepAlive(
+    http_t           *http,            /* I - HTTP connection */
+    http_keepalive_t keep_alive)       /* I - New Keep-Alive value */
+{
+  if (http)
+    http->keep_alive = keep_alive;
+}
+
+
 /*
  * 'httpSetLength()' - Set the content-length and content-encoding.
  *
@@ -3362,7 +3111,7 @@ httpSetField(http_t       *http,  /* I - Connection to server */
  */
 
 void
-httpSetLength(http_t *http,            /* I - Connection to server */
+httpSetLength(http_t *http,            /* I - HTTP connection */
               size_t length)           /* I - Length (0 for chunked) */
 {
   DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT ")", http,
@@ -3397,7 +3146,7 @@ httpSetLength(http_t *http,               /* I - Connection to server */
 
 void
 httpSetTimeout(
-    http_t            *http,           /* I - Connection to server */
+    http_t            *http,           /* I - HTTP connection */
     double            timeout,         /* I - Number of seconds for timeout,
                                                must be greater than 0 */
     http_timeout_cb_t cb,              /* I - Callback function or NULL */
@@ -3417,15 +3166,34 @@ httpSetTimeout(
 }
 
 
+/*
+ * 'httpShutdown()' - Shutdown one side of an HTTP connection.
+ *
+ * @since CUPS 2.0@
+ */
+
+void
+httpShutdown(http_t *http)             /* I - HTTP connection */
+{
+  if (!http || http->fd < 0)
+    return;
+
+  if (http->tls)
+    http_shutdown_ssl(http);
+
+  shutdown(http->fd, SHUT_RD);
+}
+
+
 /*
  * 'httpTrace()' - Send an TRACE request to the server.
  */
 
 int                                    /* O - Status of call (0 = success) */
-httpTrace(http_t     *http,            /* I - Connection to server */
+httpTrace(http_t     *http,            /* I - HTTP connection */
           const char *uri)             /* I - URI for trace */
 {
-  return (http_send(http, HTTP_TRACE, uri));
+  return (http_send(http, HTTP_STATE_TRACE, uri));
 }
 
 
@@ -3437,7 +3205,7 @@ httpTrace(http_t     *http,               /* I - Connection to server */
  */
 
 int                                    /* O - 1 to continue, 0 to stop */
-_httpUpdate(http_t        *http,       /* I - Connection to server */
+_httpUpdate(http_t        *http,       /* I - HTTP connection */
             http_status_t *status)     /* O - Current HTTP status */
 {
   char         line[32768],            /* Line from connection... */
@@ -3447,7 +3215,7 @@ _httpUpdate(http_t        *http,  /* I - Connection to server */
 
 
   DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http, status,
-                http_states[http->state + 1]));
+                httpStateString(http->state)));
 
  /*
   * Grab a single line from the connection...
@@ -3455,7 +3223,7 @@ _httpUpdate(http_t        *http,  /* I - Connection to server */
 
   if (!httpGets(line, sizeof(line), http))
   {
-    *status = HTTP_ERROR;
+    *status = HTTP_STATUS_ERROR;
     return (0);
   }
 
@@ -3478,21 +3246,17 @@ _httpUpdate(http_t        *http,        /* I - Connection to server */
       return (0);
     }
 
-    if (http->status < HTTP_BAD_REQUEST)
+    if (http->status < HTTP_STATUS_BAD_REQUEST)
       http->digest_tries = 0;
 
 #ifdef HAVE_SSL
-    if (http->status == HTTP_SWITCHING_PROTOCOLS && !http->tls)
+    if (http->status == HTTP_STATUS_SWITCHING_PROTOCOLS && !http->tls)
     {
       if (http_setup_ssl(http) != 0)
       {
-#  ifdef WIN32
-       closesocket(http->fd);
-#  else
-       close(http->fd);
-#  endif /* WIN32 */
+        httpAddrClose(NULL, http->fd);
 
-       *status = http->status = HTTP_ERROR;
+       *status = http->status = HTTP_STATUS_ERROR;
        return (0);
       }
 
@@ -3505,7 +3269,7 @@ _httpUpdate(http_t        *http,  /* I - Connection to server */
     {
       DEBUG_puts("1_httpUpdate: Bad Content-Length.");
       http->error  = EINVAL;
-      http->status = *status = HTTP_ERROR;
+      http->status = *status = HTTP_STATUS_ERROR;
       return (0);
     }
 
@@ -3518,7 +3282,7 @@ _httpUpdate(http_t        *http,  /* I - Connection to server */
          http->state ++;
 
          DEBUG_printf(("1_httpUpdate: Set state to %s.",
-                       http_states[http->state + 1]));
+                       httpStateString(http->state)));
 
       case HTTP_STATE_POST_SEND :
       case HTTP_STATE_HEAD :
@@ -3527,8 +3291,7 @@ _httpUpdate(http_t        *http,  /* I - Connection to server */
       default :
          http->state = HTTP_STATE_WAITING;
 
-         DEBUG_puts("1_httpUpdate: Unknown state, reset state to "
-                    "HTTP_STATE_WAITING.");
+         DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
          break;
     }
 
@@ -3551,7 +3314,7 @@ _httpUpdate(http_t        *http,  /* I - Connection to server */
 
     if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, &intstatus) != 3)
     {
-      *status = http->status = HTTP_ERROR;
+      *status = http->status = HTTP_STATUS_ERROR;
       return (0);
     }
 
@@ -3592,7 +3355,7 @@ _httpUpdate(http_t        *http,  /* I - Connection to server */
 
       httpSetCookie(http, value);
     }
-    else if ((field = http_field(line)) != HTTP_FIELD_UNKNOWN)
+    else if ((field = httpFieldValue(line)) != HTTP_FIELD_UNKNOWN)
       httpSetField(http, field, value);
 #ifdef DEBUG
     else
@@ -3603,7 +3366,7 @@ _httpUpdate(http_t        *http,  /* I - Connection to server */
   {
     DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line));
     http->error  = EINVAL;
-    http->status = *status = HTTP_ERROR;
+    http->status = *status = HTTP_STATUS_ERROR;
     return (0);
   }
 
@@ -3616,13 +3379,13 @@ _httpUpdate(http_t        *http,        /* I - Connection to server */
  */
 
 http_status_t                          /* O - HTTP status */
-httpUpdate(http_t *http)               /* I - Connection to server */
+httpUpdate(http_t *http)               /* I - HTTP connection */
 {
   http_status_t        status;                 /* Request status */
 
 
   DEBUG_printf(("httpUpdate(http=%p), state=%s", http,
-                http_states[http->state + 1]));
+                httpStateString(http->state)));
 
  /*
   * Flush pending data, if any...
@@ -3633,7 +3396,7 @@ httpUpdate(http_t *http)          /* I - Connection to server */
     DEBUG_puts("2httpUpdate: flushing buffer...");
 
     if (httpFlushWrite(http) < 0)
-      return (HTTP_ERROR);
+      return (HTTP_STATUS_ERROR);
   }
 
  /*
@@ -3641,7 +3404,7 @@ httpUpdate(http_t *http)          /* I - Connection to server */
   */
 
   if (http->state == HTTP_STATE_WAITING)
-    return (HTTP_CONTINUE);
+    return (HTTP_STATUS_CONTINUE);
 
  /*
   * Grab all of the lines we can from the connection...
@@ -3653,7 +3416,7 @@ httpUpdate(http_t *http)          /* I - Connection to server */
   * See if there was an error...
   */
 
-  if (http->error == EPIPE && http->status > HTTP_CONTINUE)
+  if (http->error == EPIPE && http->status > HTTP_STATUS_CONTINUE)
   {
     DEBUG_printf(("1httpUpdate: Returning status %d...", http->status));
     return (http->status);
@@ -3663,8 +3426,8 @@ httpUpdate(http_t *http)          /* I - Connection to server */
   {
     DEBUG_printf(("1httpUpdate: socket error %d - %s", http->error,
                   strerror(http->error)));
-    http->status = HTTP_ERROR;
-    return (HTTP_ERROR);
+    http->status = HTTP_STATUS_ERROR;
+    return (HTTP_STATUS_ERROR);
   }
 
  /*
@@ -3680,7 +3443,7 @@ httpUpdate(http_t *http)          /* I - Connection to server */
  */
 
 int                                    /* O - 1 if data is available, 0 otherwise */
-_httpWait(http_t *http,                        /* I - Connection to server */
+_httpWait(http_t *http,                        /* I - HTTP connection */
           int    msec,                 /* I - Milliseconds to wait */
          int    usessl)                /* I - Use SSL context? */
 {
@@ -3791,7 +3554,7 @@ _httpWait(http_t *http,                   /* I - Connection to server */
  */
 
 int                                    /* O - 1 if data is available, 0 otherwise */
-httpWait(http_t *http,                 /* I - Connection to server */
+httpWait(http_t *http,                 /* I - HTTP connection */
          int    msec)                  /* I - Milliseconds to wait */
 {
  /*
@@ -3809,6 +3572,14 @@ httpWait(http_t *http,                   /* I - Connection to server */
     return (1);
   }
 
+#ifdef HAVE_LIBZ
+  if (http->coding >= _HTTP_CODING_GUNZIP && http->stream.avail_in > 0)
+  {
+    DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
+    return (1);
+  }
+#endif /* HAVE_LIBZ */
+
  /*
   * Flush pending data, if any...
   */
@@ -3839,7 +3610,7 @@ httpWait(http_t *http,                    /* I - Connection to server */
  */
 
 int                                    /* O - Number of bytes written */
-httpWrite(http_t     *http,            /* I - Connection to server */
+httpWrite(http_t     *http,            /* I - HTTP connection */
           const char *buffer,          /* I - Buffer for data */
          int        length)            /* I - Number of bytes to write */
 {
@@ -3854,7 +3625,7 @@ httpWrite(http_t     *http,               /* I - Connection to server */
  */
 
 ssize_t                                        /* O - Number of bytes written */
-httpWrite2(http_t     *http,           /* I - Connection to server */
+httpWrite2(http_t     *http,           /* I - HTTP connection */
            const char *buffer,         /* I - Buffer for data */
           size_t     length)           /* I - Number of bytes to write */
 {
@@ -3984,6 +3755,11 @@ httpWrite2(http_t     *http,             /* I - Connection to server */
     * data, go idle...
     */
 
+#ifdef HAVE_LIBZ
+    if (http->coding)
+      http_content_coding_finish(http);
+#endif /* HAVE_LIBZ */
+
     if (http->wused)
     {
       if (httpFlushWrite(http) < 0)
@@ -4007,17 +3783,14 @@ httpWrite2(http_t     *http,            /* I - Connection to server */
     }
 
     if (http->state == HTTP_STATE_POST_RECV)
-    {
-#ifdef HAVE_LIBZ
-      if (http->coding)
-        http_content_coding_finish(http);
-#endif /* HAVE_LIBZ */
-
       http->state ++;
+    else if (http->state == HTTP_STATE_POST_SEND)
+      http->state = HTTP_STATE_WAITING;
+    else
+      http->state = HTTP_STATE_STATUS;
 
-      DEBUG_printf(("2httpWrite2: Changed state to %s.",
-                   http_states[http->state + 1]));
-    }
+    DEBUG_printf(("2httpWrite2: Changed state to %s.",
+                 httpStateString(http->state)));
   }
 
   DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT ".", CUPS_LLCAST bytes));
@@ -4081,7 +3854,7 @@ _httpWriteCDSA(
 
 ssize_t                                        /* O - Number of bytes written or -1 on error */
 _httpWriteGNUTLS(
-    gnutls_transport_ptr ptr,          /* I - Connection to server */
+    gnutls_transport_ptr ptr,          /* I - HTTP connection */
     const void           *data,                /* I - Data buffer */
     size_t               length)       /* I - Number of bytes to write */
 {
@@ -4105,7 +3878,7 @@ _httpWriteGNUTLS(
 /*
  * 'httpWriteResponse()' - Write a HTTP response to a client connection.
  *
- * @since CUPS 1.7@
+ * @since CUPS 1.7/OS X 10.9@
  */
 
 int                                    /* O - 0 on success, -1 on error */
@@ -4135,9 +3908,9 @@ httpWriteResponse(http_t        *http,    /* I - HTTP connection */
   if (!http->fields[HTTP_FIELD_DATE][0])
     httpSetField(http, HTTP_FIELD_DATE, httpGetDateString(time(NULL)));
 
-  if (status >= HTTP_BAD_REQUEST && http->keep_alive)
+  if (status >= HTTP_STATUS_BAD_REQUEST && http->keep_alive)
   {
-    http->keep_alive = 0;
+    http->keep_alive = HTTP_KEEPALIVE_OFF;
     httpSetField(http, HTTP_FIELD_KEEP_ALIVE, "");
   }
 
@@ -4156,13 +3929,17 @@ httpWriteResponse(http_t        *http,  /* I - HTTP connection */
   }
 
 #ifdef HAVE_SSL
-  if (status == HTTP_STATUS_UPGRADE_REQUIRED)
+  if (status == HTTP_STATUS_UPGRADE_REQUIRED ||
+      status == HTTP_STATUS_SWITCHING_PROTOCOLS)
   {
     if (!http->fields[HTTP_FIELD_CONNECTION][0])
       httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
 
     if (!http->fields[HTTP_FIELD_UPGRADE][0])
       httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.2,TLS/1.1,TLS/1.0");
+
+    if (!http->fields[HTTP_FIELD_CONTENT_LENGTH][0])
+      httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, "0");
   }
 #endif /* HAVE_SSL */
 
@@ -4221,10 +3998,10 @@ httpWriteResponse(http_t        *http,  /* I - HTTP connection */
 
     if (http->cookie)
     {
-      if (httpPrintf(http, "Set-Cookie: %s path=/%s\r\n", http->cookie,
-                     http->tls ? " secure" : "") < 1)
+      if (httpPrintf(http, "Set-Cookie: %s path=/ httponly%s\r\n",
+                    http->cookie, http->tls ? " secure" : "") < 1)
       {
-       http->status = HTTP_ERROR;
+       http->status = HTTP_STATUS_ERROR;
        return (-1);
       }
     }
@@ -4232,17 +4009,18 @@ httpWriteResponse(http_t        *http,  /* I - HTTP connection */
 
   if (httpWrite2(http, "\r\n", 2) < 2)
   {
-    http->status = HTTP_ERROR;
+    http->status = HTTP_STATUS_ERROR;
     return (-1);
   }
 
   if (httpFlushWrite(http) < 0)
   {
-    http->status = HTTP_ERROR;
+    http->status = HTTP_STATUS_ERROR;
     return (-1);
   }
 
-  if (status == HTTP_STATUS_CONTINUE)
+  if (status == HTTP_STATUS_CONTINUE ||
+      status == HTTP_STATUS_SWITCHING_PROTOCOLS)
   {
    /*
     * Restore the old data_encoding and data_length values...
@@ -4260,10 +4038,11 @@ httpWriteResponse(http_t        *http,  /* I - HTTP connection */
            http->state == HTTP_STATE_HEAD ||
            http->state == HTTP_STATE_PUT ||
            http->state == HTTP_STATE_TRACE ||
-           http->state == HTTP_STATE_CONNECT)
+           http->state == HTTP_STATE_CONNECT ||
+           http->state == HTTP_STATE_STATUS)
   {
     DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
-                  "was %s.", http_states[http->state + 1]));
+                  "was %s.", httpStateString(http->state)));
     http->state = HTTP_STATE_WAITING;
   }
   else
@@ -4275,6 +4054,7 @@ httpWriteResponse(http_t        *http,    /* I - HTTP connection */
 
     http_set_length(http);
 
+#ifdef HAVE_LIBZ
    /*
     * Then start any content encoding...
     */
@@ -4282,6 +4062,7 @@ httpWriteResponse(http_t        *http,    /* I - HTTP connection */
     DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
     http_content_coding_start(http,
                              httpGetField(http, HTTP_FIELD_CONTENT_ENCODING));
+#endif /* HAVE_LIBZ */
   }
 
   return (0);
@@ -4475,6 +4256,8 @@ http_content_coding_finish(
     case _HTTP_CODING_INFLATE :
     case _HTTP_CODING_GUNZIP :
         inflateEnd(&(http->stream));
+        free(http->dbuffer);
+        http->dbuffer = NULL;
         break;
 
     default :
@@ -4509,10 +4292,12 @@ http_content_coding_start(
   }
   else if (!strcmp(value, "x-gzip") || !strcmp(value, "gzip"))
   {
-    if (http->state == HTTP_GET_SEND || http->state == HTTP_POST_SEND)
+    if (http->state == HTTP_STATE_GET_SEND ||
+        http->state == HTTP_STATE_POST_SEND)
       coding = http->mode == _HTTP_MODE_SERVER ? _HTTP_CODING_GZIP :
                                                  _HTTP_CODING_GUNZIP;
-    else if (http->state == HTTP_STATE_POST_RECV || http->state == HTTP_PUT_RECV)
+    else if (http->state == HTTP_STATE_POST_RECV ||
+             http->state == HTTP_STATE_PUT_RECV)
       coding = http->mode == _HTTP_MODE_CLIENT ? _HTTP_CODING_GZIP :
                                                  _HTTP_CODING_GUNZIP;
     else
@@ -4523,10 +4308,12 @@ http_content_coding_start(
   }
   else if (!strcmp(value, "x-deflate") || !strcmp(value, "deflate"))
   {
-    if (http->state == HTTP_GET_SEND || http->state == HTTP_POST_SEND)
+    if (http->state == HTTP_STATE_GET_SEND ||
+        http->state == HTTP_STATE_POST_SEND)
       coding = http->mode == _HTTP_MODE_SERVER ? _HTTP_CODING_DEFLATE :
                                                  _HTTP_CODING_INFLATE;
-    else if (http->state == HTTP_STATE_POST_RECV || http->state == HTTP_PUT_RECV)
+    else if (http->state == HTTP_STATE_POST_RECV ||
+             http->state == HTTP_STATE_PUT_RECV)
       coding = http->mode == _HTTP_MODE_CLIENT ? _HTTP_CODING_DEFLATE :
                                                  _HTTP_CODING_INFLATE;
     else
@@ -4550,37 +4337,159 @@ http_content_coding_start(
         if (http->wused)
           httpFlushWrite(http);
 
-        if ((zerr = deflateInit2(&(http->stream), Z_DEFAULT_COMPRESSION,
-                                 Z_DEFLATED,
-                                coding == _HTTP_CODING_DEFLATE ? 11 : 27, 7,
-                                Z_DEFAULT_STRATEGY)) < Z_OK)
-        {
-          http->status = HTTP_ERROR;
-          http->error  = zerr == Z_MEM_ERROR ? ENOMEM : EINVAL;
-          return;
-        }
-        break;
+       /*
+        * Window size for compression is 11 bits - optimal based on PWG Raster
+        * sample files on pwg.org.  -11 is raw deflate, 27 is gzip, per ZLIB
+        * documentation.
+        */
+
+        if ((zerr = deflateInit2(&(http->stream), Z_DEFAULT_COMPRESSION,
+                                 Z_DEFLATED,
+                                coding == _HTTP_CODING_DEFLATE ? -11 : 27, 7,
+                                Z_DEFAULT_STRATEGY)) < Z_OK)
+        {
+          http->status = HTTP_STATUS_ERROR;
+          http->error  = zerr == Z_MEM_ERROR ? ENOMEM : EINVAL;
+          return;
+        }
+        break;
+
+    case _HTTP_CODING_INFLATE :
+    case _HTTP_CODING_GUNZIP :
+        if ((http->dbuffer = malloc(HTTP_MAX_BUFFER)) == NULL)
+        {
+          http->status = HTTP_STATUS_ERROR;
+          http->error  = errno;
+          return;
+        }
+
+       /*
+        * Window size for decompression is up to 15 bits (maximum supported).
+        * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
+        */
+
+        if ((zerr = inflateInit2(&(http->stream),
+                                 coding == _HTTP_CODING_INFLATE ? -15 : 31))
+               < Z_OK)
+        {
+          free(http->dbuffer);
+          http->dbuffer = NULL;
+          http->status  = HTTP_STATUS_ERROR;
+          http->error   = zerr == Z_MEM_ERROR ? ENOMEM : EINVAL;
+          return;
+        }
+
+        http->stream.avail_in = 0;
+        http->stream.next_in  = http->dbuffer;
+        break;
+
+    default :
+        break;
+  }
+
+  http->coding = coding;
+
+  DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
+               http->coding));
+}
+#endif /* HAVE_LIBZ */
+
+
+/*
+ * 'http_create()' - Create an unconnected HTTP connection.
+ */
+
+static http_t *                                /* O - HTTP connection */
+http_create(
+    const char        *host,           /* I - Hostname */
+    int               port,            /* I - Port number */
+    http_addrlist_t   *addrlist,       /* I - Address list or NULL */
+    int               family,          /* I - Address family or AF_UNSPEC */
+    http_encryption_t encryption,      /* I - Encryption to use */
+    int               blocking,                /* I - 1 for blocking mode */
+    _http_mode_t      mode)            /* I - _HTTP_MODE_CLIENT or _SERVER */
+{
+  http_t       *http;                  /* New HTTP connection */
+  char         service[255];           /* Service name */
+  http_addrlist_t *myaddrlist = NULL;  /* My address list */
+
+
+  DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
+                "encryption=%d, blocking=%d, mode=%d)", host, port, addrlist,
+                family, encryption, blocking, mode));
+
+  if (!host && mode == _HTTP_MODE_CLIENT)
+    return (NULL);
+
+  httpInitialize();
+
+ /*
+  * Lookup the host...
+  */
+
+  if (addrlist)
+  {
+    myaddrlist = httpAddrCopyList(addrlist);
+  }
+  else
+  {
+    snprintf(service, sizeof(service), "%d", port);
+
+    myaddrlist = httpAddrGetList(host, family, service);
+  }
+
+  if (!myaddrlist)
+    return (NULL);
+
+ /*
+  * Allocate memory for the structure...
+  */
+
+  if ((http = calloc(sizeof(http_t), 1)) == NULL)
+  {
+    _cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
+    httpAddrFreeList(addrlist);
+    return (NULL);
+  }
+
+ /*
+  * Initialize the HTTP data...
+  */
+
+  http->mode     = mode;
+  http->activity = time(NULL);
+  http->addrlist = myaddrlist;
+  http->blocking = blocking;
+  http->fd       = -1;
+#ifdef HAVE_GSSAPI
+  http->gssctx   = GSS_C_NO_CONTEXT;
+  http->gssname  = GSS_C_NO_NAME;
+#endif /* HAVE_GSSAPI */
+  http->status   = HTTP_STATUS_CONTINUE;
+  http->version  = HTTP_VERSION_1_1;
 
-    case _HTTP_CODING_INFLATE :
-    case _HTTP_CODING_GUNZIP :
-        if ((zerr = inflateInit2(&(http->stream), 32 + 15)) < Z_OK)
-        {
-          http->status = HTTP_ERROR;
-          http->error  = zerr == Z_MEM_ERROR ? ENOMEM : EINVAL;
-          return;
-        }
-        break;
+  if (host)
+    strlcpy(http->hostname, host, sizeof(http->hostname));
 
-    default :
-        break;
-  }
+  if (port == 443)                     /* Always use encryption for https */
+    http->encryption = HTTP_ENCRYPTION_ALWAYS;
+  else
+    http->encryption = encryption;
 
-  http->coding = coding;
+  http_set_wait(http);
 
-  DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
-               http->coding));
+ /*
+  * Return the new structure...
+  */
+
+  return (http);
 }
-#endif /* HAVE_LIBZ */
+
+/* For OS X 10.8 and earlier */
+http_t *_httpCreate(const char *host, int port, http_addrlist_t *addrlist,
+                   http_encryption_t encryption, int family)
+{ return (http_create(host, port, addrlist, family, encryption, 1,
+                      _HTTP_MODE_CLIENT)); }
 
 
 #ifdef DEBUG
@@ -4641,20 +4550,227 @@ http_debug_hex(const char *prefix,     /* I - Prefix for line */
 
 
 /*
- * 'http_field()' - Return the field index for a field name.
+ * 'http_read()' - Read a buffer from a HTTP connection.
+ *
+ * This function does the low-level read from the socket, retrying and timing
+ * out as needed.
  */
 
-static http_field_t                    /* O - Field index */
-http_field(const char *name)           /* I - String name */
+static ssize_t                         /* O - Number of bytes read or -1 on error */
+http_read(http_t *http,                        /* I - HTTP connection */
+          char   *buffer,              /* I - Buffer */
+          size_t length)               /* I - Maximum bytes to read */
 {
-  int  i;                              /* Looping var */
+  ssize_t      bytes;                  /* Bytes read */
 
 
-  for (i = 0; i < HTTP_FIELD_MAX; i ++)
-    if (_cups_strcasecmp(name, http_fields[i]) == 0)
-      return ((http_field_t)i);
+  DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT ")", http,
+                buffer, CUPS_LLCAST length));
 
-  return (HTTP_FIELD_UNKNOWN);
+  if (!http->blocking)
+  {
+    while (!httpWait(http, http->wait_value))
+    {
+      if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
+       continue;
+
+      DEBUG_puts("2http_read: Timeout.");
+      return (0);
+    }
+  }
+
+  DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length));
+
+  do
+  {
+#ifdef HAVE_SSL
+    if (http->tls)
+      bytes = http_read_ssl(http, buffer, length);
+    else
+#endif /* HAVE_SSL */
+    bytes = recv(http->fd, buffer, length, 0);
+
+    if (bytes < 0)
+    {
+#ifdef WIN32
+      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
+      DEBUG_printf(("2http_read: %s", strerror(errno)));
+
+      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);
+      }
+#endif /* WIN32 */
+    }
+  }
+  while (bytes < 0);
+
+  DEBUG_printf(("2http_read: Read " CUPS_LLFMT " bytes into buffer.",
+               CUPS_LLCAST bytes));
+#ifdef DEBUG
+  if (bytes > 0)
+    http_debug_hex("http_read", buffer, (int)bytes);
+#endif /* DEBUG */
+
+  if (bytes < 0)
+  {
+#ifdef WIN32
+    if (WSAGetLastError() == WSAEINTR)
+      bytes = 0;
+    else
+      http->error = WSAGetLastError();
+#else
+    if (errno == EINTR || (errno == EAGAIN && !http->timeout_cb))
+      bytes = 0;
+    else
+      http->error = errno;
+#endif /* WIN32 */
+  }
+  else if (bytes == 0)
+  {
+    http->error = EPIPE;
+    return (0);
+  }
+
+  return (bytes);
+}
+
+
+/*
+ * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
+ *
+ * This function reads data from the HTTP buffer or from the socket, as needed.
+ */
+
+static ssize_t                         /* O - Number of bytes read or -1 on error */
+http_read_buffered(http_t *http,       /* I - HTTP connection */
+                   char   *buffer,     /* I - Buffer */
+                   size_t length)      /* I - Maximum bytes to read */
+{
+  ssize_t      bytes;                  /* Bytes read */
+
+
+  DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
+                ") used=%d",
+                http, buffer, CUPS_LLCAST length, http->used));
+
+  if (http->used > 0)
+  {
+    if (length > (size_t)http->used)
+      bytes = (size_t)http->used;
+    else
+      bytes = length;
+
+    DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
+                  (int)bytes));
+
+    memcpy(buffer, http->buffer, bytes);
+    http->used -= (int)bytes;
+
+    if (http->used > 0)
+      memmove(http->buffer, http->buffer + bytes, http->used);
+  }
+  else
+    bytes = http_read(http, buffer, length);
+
+  return (bytes);
+}
+
+
+/*
+ * 'http_read_chunk()' - Read a chunk from a HTTP connection.
+ *
+ * This function reads and validates the chunk length, then does a buffered read
+ * returning the number of bytes placed in the buffer.
+ */
+
+static ssize_t                         /* O - Number of bytes read or -1 on error */
+http_read_chunk(http_t *http,          /* I - HTTP connection */
+               char   *buffer,         /* I - Buffer */
+               size_t length)          /* I - Maximum bytes to read */
+{
+  DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT ")",
+                http, buffer, CUPS_LLCAST length));
+
+  if (http->data_remaining <= 0)
+  {
+    char       len[32];                /* Length string */
+
+    if (!httpGets(len, sizeof(len), http))
+    {
+      DEBUG_puts("1http_read_chunk: Could not get chunk length.");
+      return (0);
+    }
+
+    if (!len[0])
+    {
+      DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
+      if (!httpGets(len, sizeof(len), http))
+      {
+       DEBUG_puts("1http_read_chunk: Could not get chunk length.");
+       return (0);
+      }
+    }
+
+    http->data_remaining = strtoll(len, NULL, 16);
+
+    if (http->data_remaining < 0)
+    {
+      DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
+                    CUPS_LLFMT ")", len, CUPS_LLCAST http->data_remaining));
+      return (0);
+    }
+
+    DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT ")",
+                  len, CUPS_LLCAST http->data_remaining));
+
+    if (http->data_remaining == 0)
+    {
+     /*
+      * 0-length chunk, grab trailing blank line...
+      */
+
+      httpGets(len, sizeof(len), http);
+    }
+  }
+
+  DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT,
+                CUPS_LLCAST http->data_remaining));
+
+  if (http->data_remaining <= 0)
+    return (0);
+  else if (length > (size_t)http->data_remaining)
+    length = (size_t)http->data_remaining;
+
+  return (http_read_buffered(http, buffer, length));
 }
 
 
@@ -4664,7 +4780,7 @@ http_field(const char *name)              /* I - String name */
  */
 
 static int                             /* O - Bytes read */
-http_read_ssl(http_t *http,            /* I - Connection to server */
+http_read_ssl(http_t *http,            /* I - HTTP connection */
              char   *buf,              /* I - Buffer to store data */
              int    len)               /* I - Length of buffer */
 {
@@ -4754,7 +4870,7 @@ http_read_ssl(http_t *http,               /* I - Connection to server */
  */
 
 static int                             /* O - 0 on success, non-zero on error */
-http_send(http_t       *http,          /* I - Connection to server */
+http_send(http_t       *http,          /* I - HTTP connection */
           http_state_t request,                /* I - Request code */
          const char   *uri)            /* I - URI */
 {
@@ -4781,7 +4897,7 @@ http_send(http_t       *http,             /* I - Connection to server */
                };
 
 
-  DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
+  DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
                 http, codes[request], uri));
 
   if (http == NULL || uri == NULL)
@@ -4792,9 +4908,12 @@ http_send(http_t       *http,            /* I - Connection to server */
   */
 
   if (!http->fields[HTTP_FIELD_USER_AGENT][0])
-    httpSetField(http, HTTP_FIELD_USER_AGENT,
-                 http->default_user_agent ? http->default_user_agent :
-                                            CUPS_MINIMAL);
+  {
+    if (http->default_user_agent)
+      httpSetField(http, HTTP_FIELD_USER_AGENT, http->default_user_agent);
+    else
+      httpSetField(http, HTTP_FIELD_USER_AGENT, cupsUserAgent());
+  }
 
  /*
   * Set the Accept-Encoding field if it isn't already...
@@ -4814,10 +4933,15 @@ http_send(http_t       *http,           /* I - Connection to server */
   * See if we had an error the last time around; if so, reconnect...
   */
 
-  if (http->fd < 0 || http->status == HTTP_ERROR ||
-      http->status >= HTTP_BAD_REQUEST)
-    if (httpReconnect(http))
+  if (http->fd < 0 || http->status == HTTP_STATUS_ERROR ||
+      http->status >= HTTP_STATUS_BAD_REQUEST)
+  {
+    DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
+                  http->fd, http->status, http->tls_upgrade));
+
+    if (httpReconnect2(http, 30000, NULL))
       return (-1);
+  }
 
  /*
   * Flush any written data that is pending...
@@ -4826,7 +4950,7 @@ http_send(http_t       *http,             /* I - Connection to server */
   if (http->wused)
   {
     if (httpFlushWrite(http) < 0)
-      if (httpReconnect(http))
+      if (httpReconnect2(http, 30000, NULL))
         return (-1);
   }
 
@@ -4837,13 +4961,13 @@ http_send(http_t       *http,           /* I - Connection to server */
   http->state         = request;
   http->data_encoding = HTTP_ENCODING_FIELDS;
 
-  if (request == HTTP_POST || request == HTTP_PUT)
+  if (request == HTTP_STATE_POST || request == HTTP_STATE_PUT)
     http->state ++;
 
-  http->status = HTTP_CONTINUE;
+  http->status = HTTP_STATUS_CONTINUE;
 
 #ifdef HAVE_SSL
-  if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
+  if (http->encryption == HTTP_ENCRYPTION_REQUIRED && !http->tls)
   {
     httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
     httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.2,TLS/1.1,TLS/1.0");
@@ -4852,27 +4976,27 @@ http_send(http_t       *http,           /* I - Connection to server */
 
   if (httpPrintf(http, "%s %s HTTP/1.1\r\n", codes[request], buf) < 1)
   {
-    http->status = HTTP_ERROR;
+    http->status = HTTP_STATUS_ERROR;
     return (-1);
   }
 
   for (i = 0; i < HTTP_FIELD_MAX; i ++)
     if ((value = httpGetField(http, i)) != NULL && *value)
     {
-      DEBUG_printf(("9http_send: %s: %s", http_fields[i], value));
+      DEBUG_printf(("5http_send: %s: %s", http_fields[i], value));
 
       if (i == HTTP_FIELD_HOST)
       {
        if (httpPrintf(http, "Host: %s:%d\r\n", value,
                       httpAddrPort(http->hostaddr)) < 1)
        {
-         http->status = HTTP_ERROR;
+         http->status = HTTP_STATUS_ERROR;
          return (-1);
        }
       }
       else if (httpPrintf(http, "%s: %s\r\n", http_fields[i], value) < 1)
       {
-       http->status = HTTP_ERROR;
+       http->status = HTTP_STATUS_ERROR;
        return (-1);
       }
     }
@@ -4880,21 +5004,25 @@ http_send(http_t       *http,           /* I - Connection to server */
   if (http->cookie)
     if (httpPrintf(http, "Cookie: $Version=0; %s\r\n", http->cookie) < 1)
     {
-      http->status = HTTP_ERROR;
+      http->status = HTTP_STATUS_ERROR;
       return (-1);
     }
 
-  if (http->expect == HTTP_CONTINUE && http->mode == _HTTP_MODE_CLIENT &&
-      (http->state == HTTP_STATE_POST_RECV || http->state == HTTP_PUT_RECV))
+  DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http->expect,
+                http->mode, http->state));
+
+  if (http->expect == HTTP_STATUS_CONTINUE && http->mode == _HTTP_MODE_CLIENT &&
+      (http->state == HTTP_STATE_POST_RECV ||
+       http->state == HTTP_STATE_PUT_RECV))
     if (httpPrintf(http, "Expect: 100-continue\r\n") < 1)
     {
-      http->status = HTTP_ERROR;
+      http->status = HTTP_STATUS_ERROR;
       return (-1);
     }
 
   if (httpPrintf(http, "\r\n") < 1)
   {
-    http->status = HTTP_ERROR;
+    http->status = HTTP_STATUS_ERROR;
     return (-1);
   }
 
@@ -4931,7 +5059,7 @@ http_send(http_t       *http,             /* I - Connection to server */
  */
 
 static int                             /* O - Status of connection */
-http_set_credentials(http_t *http)     /* I - Connection to server */
+http_set_credentials(http_t *http)     /* I - HTTP connection */
 {
   _cups_globals_t *cg = _cupsGlobals();        /* Pointer to library globals */
   OSStatus             error = 0;      /* Error code */
@@ -4948,61 +5076,6 @@ http_set_credentials(http_t *http)       /* I - Connection to server */
   if ((credentials = http->tls_credentials) == NULL)
     credentials = cg->tls_credentials;
 
- /*
-  * 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);
-  }
-
   if (credentials)
   {
     error = SSLSetCertificate(http->tls, credentials);
@@ -5029,7 +5102,7 @@ http_set_length(http_t *http)             /* I - Connection */
 
 
   DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http, http->mode,
-                http_states[http->state + 1]));
+                httpStateString(http->state)));
 
   if ((remaining = httpGetLength2(http)) >= 0)
   {
@@ -5082,8 +5155,8 @@ http_set_timeout(int    fd,               /* I - File descriptor */
   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));
+  setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CUPS_SOCAST &tv, sizeof(tv));
+  setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, CUPS_SOCAST &tv, sizeof(tv));
 
 #else
   struct timeval tv;                   /* Timeout in secs and usecs */
@@ -5091,8 +5164,8 @@ http_set_timeout(int    fd,               /* I - File descriptor */
   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));
+  setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CUPS_SOCAST &tv, sizeof(tv));
+  setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, CUPS_SOCAST &tv, sizeof(tv));
 #endif /* WIN32 */
 }
 
@@ -5102,7 +5175,7 @@ http_set_timeout(int    fd,               /* I - File descriptor */
  */
 
 static void
-http_set_wait(http_t *http)            /* I - Connection to server */
+http_set_wait(http_t *http)            /* I - HTTP connection */
 {
   if (http->blocking)
   {
@@ -5122,10 +5195,8 @@ http_set_wait(http_t *http)              /* I - Connection to server */
  */
 
 static int                             /* O - 0 on success, -1 on failure */
-http_setup_ssl(http_t *http)           /* I - Connection to server */
+http_setup_ssl(http_t *http)           /* I - HTTP connection */
 {
-  _cups_globals_t      *cg = _cupsGlobals();
-                                       /* Pointer to library globals */
   char                 hostname[256],  /* Hostname */
                        *hostptr;       /* Pointer into hostname */
 
@@ -5138,6 +5209,8 @@ http_setup_ssl(http_t *http)              /* I - Connection to server */
   gnutls_certificate_client_credentials *credentials;
                                        /* TLS credentials */
 #  elif defined(HAVE_CDSASSL)
+  _cups_globals_t      *cg = _cupsGlobals();
+                                       /* Pointer to library globals */
   OSStatus             error;          /* Error code */
   const char           *message = NULL;/* Error message */
   cups_array_t         *credentials;   /* Credentials array */
@@ -5210,12 +5283,12 @@ http_setup_ssl(http_t *http)            /* I - Connection to server */
 #    else
     http->error  = errno;
 #    endif /* WIN32 */
-    http->status = HTTP_ERROR;
+    http->status = HTTP_STATUS_ERROR;
 
     if (!message)
       message = _("Unable to establish a secure connection to host.");
 
-    _cupsSetError(IPP_PKI_ERROR, message, 1);
+    _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, message, 1);
 
     return (-1);
   }
@@ -5228,8 +5301,8 @@ http_setup_ssl(http_t *http)              /* I - Connection to server */
     DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
                   strerror(errno)));
     http->error  = errno;
-    http->status = HTTP_ERROR;
-    _cupsSetHTTPError(HTTP_ERROR);
+    http->status = HTTP_STATUS_ERROR;
+    _cupsSetHTTPError(HTTP_STATUS_ERROR);
 
     return (-1);
   }
@@ -5253,9 +5326,9 @@ http_setup_ssl(http_t *http)              /* I - Connection to server */
     if (gnutls_error_is_fatal(status))
     {
       http->error  = EIO;
-      http->status = HTTP_ERROR;
+      http->status = HTTP_STATUS_ERROR;
 
-      _cupsSetError(IPP_PKI_ERROR, gnutls_strerror(status), 0);
+      _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, gnutls_strerror(status), 0);
 
       gnutls_deinit(http->tls);
       gnutls_certificate_free_credentials(*credentials);
@@ -5274,8 +5347,8 @@ http_setup_ssl(http_t *http)              /* I - Connection to server */
   {
     DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
     http->error  = errno = ENOMEM;
-    http->status = HTTP_ERROR;
-    _cupsSetHTTPError(HTTP_ERROR);
+    http->status = HTTP_STATUS_ERROR;
+    _cupsSetHTTPError(HTTP_STATUS_ERROR);
 
     return (-1);
   }
@@ -5455,7 +5528,7 @@ http_setup_ssl(http_t *http)              /* I - Connection to server */
   if (error)
   {
     http->error  = error;
-    http->status = HTTP_ERROR;
+    http->status = HTTP_STATUS_ERROR;
     errno        = ECONNREFUSED;
 
     CFRelease(http->tls);
@@ -5472,7 +5545,7 @@ http_setup_ssl(http_t *http)              /* I - Connection to server */
       message = _("Unable to establish a secure connection to host.");
 #endif /* HAVE_CSSMERRORSTRING */
 
-    _cupsSetError(IPP_PKI_ERROR, message, 1);
+    _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, message, 1);
 
     return (-1);
   }
@@ -5482,7 +5555,7 @@ http_setup_ssl(http_t *http)              /* I - Connection to server */
 
   if (!http->tls)
   {
-    _cupsSetHTTPError(HTTP_ERROR);
+    _cupsSetHTTPError(HTTP_STATUS_ERROR);
     return (-1);
   }
 
@@ -5499,9 +5572,9 @@ http_setup_ssl(http_t *http)              /* I - Connection to server */
     http->tls_credentials = NULL;
 
     http->error  = EIO;
-    http->status = HTTP_ERROR;
+    http->status = HTTP_STATUS_ERROR;
 
-    _cupsSetError(IPP_PKI_ERROR,
+    _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI,
                   _("Unable to establish a secure connection to host."), 1);
 
     return (-1);
@@ -5516,9 +5589,9 @@ http_setup_ssl(http_t *http)              /* I - Connection to server */
     http->tls_credentials = NULL;
 
     http->error  = EIO;
-    http->status = HTTP_ERROR;
+    http->status = HTTP_STATUS_ERROR;
 
-    _cupsSetError(IPP_PKI_ERROR,
+    _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI,
                   _("Unable to establish a secure connection to host."), 1);
 
     return (-1);
@@ -5534,7 +5607,7 @@ http_setup_ssl(http_t *http)              /* I - Connection to server */
  */
 
 static void
-http_shutdown_ssl(http_t *http)                /* I - Connection to server */
+http_shutdown_ssl(http_t *http)                /* I - HTTP connection */
 {
 #  ifdef HAVE_LIBSSL
   SSL_CTX      *context;               /* Context for encryption */
@@ -5581,7 +5654,7 @@ http_shutdown_ssl(http_t *http)           /* I - Connection to server */
  */
 
 static int                             /* O - Status of connection */
-http_upgrade(http_t *http)             /* I - Connection to server */
+http_upgrade(http_t *http)             /* I - HTTP connection */
 {
   int          ret;                    /* Return value */
   http_t       myhttp;                 /* Local copy of HTTP data */
@@ -5608,6 +5681,7 @@ http_upgrade(http_t *http)                /* I - Connection to server */
   * encryption on the link...
   */
 
+  http->tls_upgrade         = 1;
   http->field_authorization = NULL;    /* Don't free the auth string */
 
   httpClearFields(http);
@@ -5620,7 +5694,7 @@ http_upgrade(http_t *http)                /* I - Connection to server */
     * Wait for the secure connection...
     */
 
-    while (httpUpdate(http) == HTTP_CONTINUE);
+    while (httpUpdate(http) == HTTP_STATUS_CONTINUE);
   }
 
  /*
@@ -5634,6 +5708,7 @@ http_upgrade(http_t *http)                /* I - Connection to server */
   http->expect              = myhttp.expect;
   http->field_authorization = myhttp.field_authorization;
   http->digest_tries        = myhttp.digest_tries;
+  http->tls_upgrade         = 0;
 
  /*
   * See if we actually went secure...
@@ -5647,11 +5722,7 @@ http_upgrade(http_t *http)               /* I - Connection to server */
 
     DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
 
-#  ifdef WIN32
-    closesocket(http->fd);
-#  else
-    close(http->fd);
-#  endif
+    httpAddrClose(NULL, http->fd);
 
     http->fd = -1;
 
@@ -5667,17 +5738,17 @@ http_upgrade(http_t *http)              /* I - Connection to server */
  * 'http_write()' - Write a buffer to a HTTP connection.
  */
 
-static int                             /* O - Number of bytes written */
-http_write(http_t     *http,           /* I - Connection to server */
+static ssize_t                         /* O - Number of bytes written */
+http_write(http_t     *http,           /* I - HTTP connection */
            const char *buffer,         /* I - Buffer for data */
-          int        length)           /* I - Number of bytes to write */
+          size_t     length)           /* I - Number of bytes to write */
 {
-  int  tbytes,                         /* Total bytes sent */
-       bytes;                          /* Bytes sent */
+  ssize_t      tbytes,                 /* Total bytes sent */
+               bytes;                  /* Bytes sent */
 
 
-  DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http, buffer,
-                length));
+  DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT ")", http,
+                buffer, CUPS_LLCAST length));
   http->error = 0;
   tbytes      = 0;
 
@@ -5749,8 +5820,8 @@ http_write(http_t     *http,              /* I - Connection to server */
 #endif /* HAVE_SSL */
     bytes = send(http->fd, buffer, length, 0);
 
-    DEBUG_printf(("3http_write: Write of %d bytes returned %d.", (int)length,
-                  (int)bytes));
+    DEBUG_printf(("3http_write: Write of " CUPS_LLFMT " bytes returned "
+                  CUPS_LLFMT ".", CUPS_LLCAST length, CUPS_LLCAST bytes));
 
     if (bytes < 0)
     {
@@ -5805,7 +5876,7 @@ http_write(http_t     *http,              /* I - Connection to server */
   http_debug_hex("http_write", buffer - tbytes, tbytes);
 #endif /* DEBUG */
 
-  DEBUG_printf(("3http_write: Returning %d.", tbytes));
+  DEBUG_printf(("3http_write: Returning " CUPS_LLFMT ".", CUPS_LLCAST tbytes));
 
   return (tbytes);
 }
@@ -5815,38 +5886,38 @@ http_write(http_t     *http,            /* I - Connection to server */
  * 'http_write_chunk()' - Write a chunked buffer.
  */
 
-static int                             /* O - Number bytes written */
-http_write_chunk(http_t     *http,     /* I - Connection to server */
+static ssize_t                         /* O - Number bytes written */
+http_write_chunk(http_t     *http,     /* I - HTTP connection */
                  const char *buffer,   /* I - Buffer to write */
-                int        length)     /* I - Length of buffer */
+                size_t        length)  /* I - Length of buffer */
 {
-  char header[255];                    /* Chunk header */
-  int  bytes;                          /* Bytes written */
+  char         header[16];             /* Chunk header */
+  ssize_t      bytes;                  /* Bytes written */
 
 
-  DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
-                http, buffer, length));
+  DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT ")",
+                http, buffer, CUPS_LLCAST length));
 
  /*
   * Write the chunk header, data, and trailer.
   */
 
-  sprintf(header, "%x\r\n", length);
-  if (http_write(http, header, (int)strlen(header)) < 0)
+  snprintf(header, sizeof(header), "%x\r\n", (unsigned)length);
+  if (http_write(http, header, strlen(header)) < 0)
   {
-    DEBUG_puts("8http_write_chunk: http_write of length failed!");
+    DEBUG_puts("8http_write_chunk: http_write of length failed.");
     return (-1);
   }
 
   if ((bytes = http_write(http, buffer, length)) < 0)
   {
-    DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
+    DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
     return (-1);
   }
 
   if (http_write(http, "\r\n", 2) < 0)
   {
-    DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
+    DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
     return (-1);
   }
 
@@ -5860,7 +5931,7 @@ http_write_chunk(http_t     *http,        /* I - Connection to server */
  */
 
 static int                             /* O - Bytes written */
-http_write_ssl(http_t     *http,       /* I - Connection to server */
+http_write_ssl(http_t     *http,       /* I - HTTP connection */
               const char *buf,         /* I - Buffer holding data */
               int        len)          /* I - Length of buffer */
 {
@@ -5945,5 +6016,5 @@ http_write_ssl(http_t     *http,  /* I - Connection to server */
 
 
 /*
- * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".
+ * End of "$Id$".
  */