2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for CUPS.
6 * Copyright 2007-2012 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * httpAcceptConnection() - Accept a new HTTP client connection from
23 * the specified listening socket.
24 * httpAddCredential() - Allocates and adds a single credential to
26 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP
28 * httpBlocking() - Set blocking/non-blocking behavior on a
30 * httpCheck() - Check to see if there is a pending response
32 * httpClearCookie() - Clear the cookie value(s).
33 * httpClearFields() - Clear HTTP request fields.
34 * httpClose() - Close an HTTP connection.
35 * httpConnect() - Connect to a HTTP server.
36 * httpConnect2() - Connect to a HTTP server.
37 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
38 * httpCopyCredentials() - Copy the credentials associated with an
39 * encrypted connection.
40 * _httpCreate() - Create an unconnected HTTP connection.
41 * _httpCreateCredentials() - Create credentials in the internal format.
42 * httpDelete() - Send a DELETE request to the server.
43 * _httpDisconnect() - Disconnect a HTTP connection.
44 * httpEncryption() - Set the required encryption on the link.
45 * httpError() - Get the last error on a connection.
46 * httpFlush() - Flush data from a HTTP connection.
47 * httpFlushWrite() - Flush data in write buffer.
48 * _httpFreeCredentials() - Free internal credentials.
49 * httpFreeCredentials() - Free an array of credentials.
50 * httpGet() - Send a GET request to the server.
51 * httpGetContentEncoding() - Get a common content encoding, if any,
52 * between the client and server.
53 * httpGetAuthString() - Get the current authorization string.
54 * httpGetBlocking() - Get the blocking/non-block state of a
56 * httpGetCookie() - Get any cookie data from the response.
57 * httpGetExpect() - Get the value of the Expect header, if any.
58 * httpGetFd() - Get the file descriptor associated with a
60 * httpGetField() - Get a field value from a request/response.
61 * httpGetLength() - Get the amount of data remaining from the
62 * content-length or transfer-encoding fields.
63 * httpGetLength2() - Get the amount of data remaining from the
64 * content-length or transfer-encoding fields.
65 * httpGets() - Get a line of text from a HTTP connection.
66 * httpGetState() - Get the current state of the HTTP request.
67 * httpGetStatus() - Get the status of the last HTTP request.
68 * httpGetSubField() - Get a sub-field value.
69 * httpGetSubField2() - Get a sub-field value.
70 * httpGetVersion() - Get the HTTP version at the other end.
71 * httpHead() - Send a HEAD request to the server.
72 * httpInitialize() - Initialize the HTTP interface library and
73 * set the default HTTP proxy (if any).
74 * httpOptions() - Send an OPTIONS request to the server.
75 * httpPeek() - Peek at data from a HTTP connection.
76 * httpPost() - Send a POST request to the server.
77 * httpPrintf() - Print a formatted string to a HTTP
79 * httpPut() - Send a PUT request to the server.
80 * httpRead() - Read data from a HTTP connection.
81 * httpRead2() - Read data from a HTTP connection.
82 * _httpReadCDSA() - Read function for the CDSA library.
83 * _httpReadGNUTLS() - Read function for the GNU TLS library.
84 * httpReadRequest() - Read a HTTP request from a connection.
85 * httpReconnect() - Reconnect to a HTTP server.
86 * httpReconnect2() - Reconnect to a HTTP server with timeout and
88 * httpSetAuthString() - Set the current authorization string.
89 * httpSetCredentials() - Set the credentials associated with an
90 * encrypted connection.
91 * httpSetCookie() - Set the cookie value(s).
92 * httpSetExpect() - Set the Expect: header in a request.
93 * httpSetField() - Set the value of an HTTP header.
94 * httpSetLength() - Set the content-length and
96 * httpSetTimeout() - Set read/write timeouts and an optional
98 * httpTrace() - Send an TRACE request to the server.
99 * _httpUpdate() - Update the current HTTP status for incoming
101 * httpUpdate() - Update the current HTTP state for incoming
103 * _httpWait() - Wait for data available on a connection (no
105 * httpWait() - Wait for data available on a connection.
106 * httpWrite() - Write data to a HTTP connection.
107 * httpWrite2() - Write data to a HTTP connection.
108 * _httpWriteCDSA() - Write function for the CDSA library.
109 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
110 * httpWriteResponse() - Write a HTTP response to a client
112 * http_bio_ctrl() - Control the HTTP connection.
113 * http_bio_free() - Free OpenSSL data.
114 * http_bio_new() - Initialize an OpenSSL BIO structure.
115 * http_bio_puts() - Send a string for OpenSSL.
116 * http_bio_read() - Read data for OpenSSL.
117 * http_bio_write() - Write data for OpenSSL.
118 * http_content_coding_finish() - Finish doing any content encoding.
119 * http_content_coding_start() - Start doing content encoding.
120 * http_debug_hex() - Do a hex dump of a buffer.
121 * http_field() - Return the field index for a field name.
122 * http_read_ssl() - Read from a SSL/TLS connection.
123 * http_send() - Send a request with all fields and the
124 * trailing blank line.
125 * http_set_credentials() - Set the SSL/TLS credentials.
126 * http_set_length() - Set the data_encoding and data_remaining
128 * http_set_timeout() - Set the socket timeout values.
129 * http_set_wait() - Set the default wait value for reads.
130 * http_setup_ssl() - Set up SSL/TLS support on a connection.
131 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
132 * http_upgrade() - Force upgrade to TLS encryption.
133 * http_write() - Write a buffer to a HTTP connection.
134 * http_write_chunk() - Write a chunked buffer.
135 * http_write_ssl() - Write to a SSL/TLS connection.
139 * Include necessary headers...
142 #include "cups-private.h"
149 # include <sys/time.h>
150 # include <sys/resource.h>
154 #endif /* HAVE_POLL */
162 static void http_content_coding_finish(http_t
*http
);
163 static void http_content_coding_start(http_t
*http
,
165 #endif /* HAVE_LIBZ */
167 static void http_debug_hex(const char *prefix
, const char *buffer
,
170 static http_field_t
http_field(const char *name
);
171 static int http_send(http_t
*http
, http_state_t request
,
173 static int http_write(http_t
*http
, const char *buffer
,
175 static int http_write_chunk(http_t
*http
, const char *buffer
,
178 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
179 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
180 static int http_set_credentials(http_t
*http
);
181 # endif /* HAVE_CDSASSL ** HAVE_SECCERTIFICATECOPYDATA */
182 #endif /* HAVE_SSL */
183 static off_t
http_set_length(http_t
*http
);
184 static void http_set_timeout(int fd
, double timeout
);
185 static void http_set_wait(http_t
*http
);
187 static int http_setup_ssl(http_t
*http
);
188 static void http_shutdown_ssl(http_t
*http
);
189 static int http_upgrade(http_t
*http
);
190 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
191 #endif /* HAVE_SSL */
198 static const char * const http_fields
[] =
215 "If-Unmodified-since",
232 static const char * const http_states
[] =
235 "HTTP_STATE_WAITING",
236 "HTTP_STATE_OPTIONS",
238 "HTTP_STATE_GET_SEND",
241 "HTTP_STATE_POST_RECV",
242 "HTTP_STATE_POST_SEND",
244 "HTTP_STATE_PUT_RECV",
247 "HTTP_STATE_CONNECT",
249 "HTTP_STATE_UNKNOWN_METHOD",
250 "HTTP_STATE_UNKNOWN_VERSION"
255 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
257 * BIO methods for OpenSSL...
260 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
261 static int http_bio_read(BIO
*h
, char *buf
, int size
);
262 static int http_bio_puts(BIO
*h
, const char *str
);
263 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
264 static int http_bio_new(BIO
*h
);
265 static int http_bio_free(BIO
*data
);
267 static BIO_METHOD http_bio_methods
=
274 NULL
, /* http_bio_gets, */
280 #endif /* HAVE_SSL && HAVE_LIBSSL */
284 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
285 * specified listening socket.
290 http_t
* /* O - HTTP connection or @code NULL@ */
291 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
292 int blocking
) /* I - 1 if the connection should be
293 blocking, 0 otherwise */
295 http_t
*http
; /* HTTP connection */
296 http_addrlist_t addrlist
; /* Dummy address list */
297 socklen_t addrlen
; /* Length of address */
298 int val
; /* Socket option value */
302 * Range check input...
309 * Create the client connection...
312 memset(&addrlist
, 0, sizeof(addrlist
));
314 if ((http
= _httpCreate(NULL
, 0, &addrlist
, AF_UNSPEC
,
315 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
316 _HTTP_MODE_SERVER
)) == NULL
)
320 * Accept the client and get the remote address...
323 addrlen
= sizeof(http_addr_t
);
325 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
328 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
334 httpAddrString(&(http
->addrlist
->addr
), http
->hostname
,
335 sizeof(http
->hostname
));
339 * Disable SIGPIPE for this socket.
343 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, &val
, sizeof(val
));
344 #endif /* SO_NOSIGPIPE */
347 * Using TCP_NODELAY improves responsiveness, especially on systems
348 * with a slow loopback interface. Since we write large buffers
349 * when sending print files and requests, there shouldn't be any
350 * performance penalty for this...
354 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
358 * Close this socket when starting another process...
361 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
362 #endif /* FD_CLOEXEC */
369 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
371 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
373 * @since CUPS 1.5/OS X 10.7@
376 int /* O - 0 on success, -1 on error */
378 cups_array_t
*credentials
, /* I - Credentials array */
379 const void *data
, /* I - PEM-encoded X.509 data */
380 size_t datalen
) /* I - Length of data */
382 http_credential_t
*credential
; /* Credential data */
385 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
387 credential
->datalen
= datalen
;
389 if ((credential
->data
= malloc(datalen
)) != NULL
)
391 memcpy(credential
->data
, data
, datalen
);
392 cupsArrayAdd(credentials
, credential
);
403 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
405 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
408 BIO_METHOD
* /* O - BIO methods for OpenSSL */
409 _httpBIOMethods(void)
411 return (&http_bio_methods
);
413 #endif /* HAVE_SSL && HAVE_LIBSSL */
417 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
421 httpBlocking(http_t
*http
, /* I - Connection to server */
422 int b
) /* I - 1 = blocking, 0 = non-blocking */
433 * 'httpCheck()' - Check to see if there is a pending response from the server.
436 int /* O - 0 = no data, 1 = data available */
437 httpCheck(http_t
*http
) /* I - Connection to server */
439 return (httpWait(http
, 0));
444 * 'httpClearCookie()' - Clear the cookie value(s).
446 * @since CUPS 1.1.19/OS X 10.3@
450 httpClearCookie(http_t
*http
) /* I - Connection to server */
464 * 'httpClearFields()' - Clear HTTP request fields.
468 httpClearFields(http_t
*http
) /* I - Connection to server */
470 DEBUG_printf(("httpClearFields(http=%p)", http
));
474 memset(http
->fields
, 0, sizeof(http
->fields
));
476 if (http
->mode
== _HTTP_MODE_CLIENT
)
478 if (http
->hostname
[0] == '/')
479 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
481 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
484 if (http
->field_authorization
)
486 free(http
->field_authorization
);
487 http
->field_authorization
= NULL
;
490 if (http
->accept_encoding
)
492 _cupsStrFree(http
->accept_encoding
);
493 http
->accept_encoding
= NULL
;
498 _cupsStrFree(http
->allow
);
504 _cupsStrFree(http
->server
);
508 http
->expect
= (http_status_t
)0;
514 * 'httpClose()' - Close an HTTP connection.
518 httpClose(http_t
*http
) /* I - Connection to server */
521 OM_uint32 minor_status
; /* Minor status code */
522 #endif /* HAVE_GSSAPI */
525 DEBUG_printf(("httpClose(http=%p)", http
));
528 * Range check input...
535 * Close any open connection...
538 _httpDisconnect(http
);
541 * Free memory used...
544 httpAddrFreeList(http
->addrlist
);
550 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
551 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
553 if (http
->gssname
!= GSS_C_NO_NAME
)
554 gss_release_name(&minor_status
, &http
->gssname
);
555 #endif /* HAVE_GSSAPI */
557 #ifdef HAVE_AUTHORIZATION_H
559 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
560 #endif /* HAVE_AUTHORIZATION_H */
562 httpClearFields(http
);
564 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
565 free(http
->authstring
);
572 * 'httpConnect()' - Connect to a HTTP server.
574 * This function is deprecated - use @link httpConnect2@ instead.
579 http_t
* /* O - New HTTP connection */
580 httpConnect(const char *host
, /* I - Host to connect to */
581 int port
) /* I - Port number */
583 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, HTTP_ENCRYPT_IF_REQUESTED
,
589 * 'httpConnect2()' - Connect to a HTTP server.
594 http_t
* /* O - New HTTP connection */
596 const char *host
, /* I - Host to connect to */
597 int port
, /* I - Port number */
598 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
599 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
600 http_encryption_t encryption
, /* I - Type of encryption to use */
601 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
602 int msec
, /* I - Connection timeout in milliseconds */
603 int *cancel
) /* I - Pointer to "cancel" variable */
605 http_t
*http
; /* New HTTP connection */
608 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
609 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
610 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
613 * Create the HTTP structure...
616 if ((http
= _httpCreate(host
, port
, addrlist
, family
, encryption
, blocking
,
617 _HTTP_MODE_CLIENT
)) == NULL
)
621 * Connect to the remote system...
624 if (!httpReconnect2(http
, msec
, cancel
))
628 * Could not connect to any known address - bail out!
638 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
640 * This function is now deprecated. Please use the @link httpConnect2@ function
646 http_t
* /* O - New HTTP connection */
648 const char *host
, /* I - Host to connect to */
649 int port
, /* I - Port number */
650 http_encryption_t encryption
) /* I - Type of encryption to use */
652 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
653 host
, port
, encryption
));
655 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
661 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
664 * @since CUPS 1.5/OS X 10.7@
667 int /* O - Status of call (0 = success) */
669 http_t
*http
, /* I - Connection to server */
670 cups_array_t
**credentials
) /* O - Array of credentials */
673 # elif defined(HAVE_GNUTLS)
674 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
675 OSStatus error
; /* Error code */
676 CFIndex count
; /* Number of credentials */
677 CFArrayRef peerCerts
; /* Peer certificates */
678 SecCertificateRef secCert
; /* Certificate reference */
679 CFDataRef data
; /* Certificate data */
680 int i
; /* Looping var */
681 # elif defined(HAVE_SSPISSL)
682 # endif /* HAVE_LIBSSL */
688 if (!http
|| !http
->tls
|| !credentials
)
694 # elif defined(HAVE_GNUTLS)
697 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
698 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
700 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
702 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
704 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
705 if ((data
= SecCertificateCopyData(secCert
)))
707 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
708 CFDataGetLength(data
));
714 CFRelease(peerCerts
);
719 # elif defined(HAVE_SSPISSL)
724 # endif /* HAVE_LIBSSL */
729 * '_httpCreate()' - Create an unconnected HTTP connection.
732 http_t
* /* O - HTTP connection */
734 const char *host
, /* I - Hostname */
735 int port
, /* I - Port number */
736 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
737 int family
, /* I - Address family or AF_UNSPEC */
738 http_encryption_t encryption
, /* I - Encryption to use */
739 int blocking
, /* I - 1 for blocking mode */
740 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
742 http_t
*http
; /* New HTTP connection */
743 char service
[255]; /* Service name */
744 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
747 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, addrlist=%p, family=%d, "
748 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
749 family
, encryption
, blocking
, mode
));
751 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
762 myaddrlist
= httpAddrCopyList(addrlist
);
766 snprintf(service
, sizeof(service
), "%d", port
);
768 myaddrlist
= httpAddrGetList(host
, family
, service
);
775 * Allocate memory for the structure...
778 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
780 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(errno
), 0);
781 httpAddrFreeList(addrlist
);
786 * Initialize the HTTP data...
790 http
->activity
= time(NULL
);
791 http
->addrlist
= myaddrlist
;
792 http
->blocking
= blocking
;
795 http
->gssctx
= GSS_C_NO_CONTEXT
;
796 http
->gssname
= GSS_C_NO_NAME
;
797 #endif /* HAVE_GSSAPI */
798 http
->version
= HTTP_VERSION_1_1
;
801 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
803 if (port
== 443) /* Always use encryption for https */
804 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
806 http
->encryption
= encryption
;
811 * Return the new structure...
819 * '_httpCreateCredentials()' - Create credentials in the internal format.
822 http_tls_credentials_t
/* O - Internal credentials */
823 _httpCreateCredentials(
824 cups_array_t
*credentials
) /* I - Array of credentials */
832 # elif defined(HAVE_GNUTLS)
835 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
836 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
837 SecCertificateRef secCert
; /* Certificate reference */
838 CFDataRef data
; /* Credential data reference */
839 http_credential_t
*credential
; /* Credential data */
842 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
843 cupsArrayCount(credentials
),
844 &kCFTypeArrayCallBacks
)) == NULL
)
847 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
849 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
851 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
852 credential
->datalen
)))
854 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
857 CFArrayAppendValue(peerCerts
, secCert
);
867 # elif defined(HAVE_SSPISSL)
872 # endif /* HAVE_LIBSSL */
877 * 'httpDelete()' - Send a DELETE request to the server.
880 int /* O - Status of call (0 = success) */
881 httpDelete(http_t
*http
, /* I - Connection to server */
882 const char *uri
) /* I - URI to delete */
884 return (http_send(http
, HTTP_DELETE
, uri
));
889 * '_httpDisconnect()' - Disconnect a HTTP connection.
893 _httpDisconnect(http_t
*http
) /* I - Connection to server */
897 http_shutdown_ssl(http
);
898 #endif /* HAVE_SSL */
901 closesocket(http
->fd
);
911 * 'httpEncryption()' - Set the required encryption on the link.
914 int /* O - -1 on error, 0 on success */
915 httpEncryption(http_t
*http
, /* I - Connection to server */
916 http_encryption_t e
) /* I - New encryption preference */
918 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
924 http
->encryption
= e
;
926 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
927 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
928 return (httpReconnect(http
));
929 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
930 return (http_upgrade(http
));
934 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
938 #endif /* HAVE_SSL */
943 * 'httpError()' - Get the last error on a connection.
946 int /* O - Error code (errno) value */
947 httpError(http_t
*http
) /* I - Connection to server */
950 return (http
->error
);
957 * 'httpFlush()' - Flush data from a HTTP connection.
961 httpFlush(http_t
*http
) /* I - Connection to server */
963 char buffer
[8192]; /* Junk buffer */
964 int blocking
; /* To block or not to block */
965 http_state_t oldstate
; /* Old state */
968 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
969 http_states
[http
->state
+ 1]));
972 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
975 blocking
= http
->blocking
;
979 * Read any data we can...
982 oldstate
= http
->state
;
983 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
986 * Restore blocking and reset the connection if we didn't get all of
987 * the remaining data...
990 http
->blocking
= blocking
;
992 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
996 * Didn't get the data back, so close the current connection.
999 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
1001 http
->state
= HTTP_STATE_WAITING
;
1005 http_shutdown_ssl(http
);
1006 #endif /* HAVE_SSL */
1009 closesocket(http
->fd
);
1020 * 'httpFlushWrite()' - Flush data in write buffer.
1022 * @since CUPS 1.2/OS X 10.5@
1025 int /* O - Bytes written or -1 on error */
1026 httpFlushWrite(http_t
*http
) /* I - Connection to server */
1028 int bytes
; /* Bytes written */
1031 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
1032 http
? http
->data_encoding
: -1));
1034 if (!http
|| !http
->wused
)
1036 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
1037 "1httpFlushWrite: No connection.");
1041 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1042 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
1044 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
1048 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
1055 * '_httpFreeCredentials()' - Free internal credentials.
1059 _httpFreeCredentials(
1060 http_tls_credentials_t credentials
) /* I - Internal credentials */
1068 #elif defined(HAVE_GNUTLS)
1071 #elif defined(HAVE_CDSASSL)
1072 CFRelease(credentials
);
1074 #elif defined(HAVE_SSPISSL)
1077 #endif /* HAVE_LIBSSL */
1082 * 'httpFreeCredentials()' - Free an array of credentials.
1086 httpFreeCredentials(
1087 cups_array_t
*credentials
) /* I - Array of credentials */
1089 http_credential_t
*credential
; /* Credential */
1092 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
1094 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
1096 cupsArrayRemove(credentials
, credential
);
1097 free((void *)credential
->data
);
1101 cupsArrayDelete(credentials
);
1106 * 'httpGet()' - Send a GET request to the server.
1109 int /* O - Status of call (0 = success) */
1110 httpGet(http_t
*http
, /* I - Connection to server */
1111 const char *uri
) /* I - URI to get */
1113 return (http_send(http
, HTTP_GET
, uri
));
1118 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
1119 * the client and server.
1121 * This function uses the value of the Accepts-Encoding HTTP header and must be
1122 * called after receiving a response from the server or a request from the
1123 * client. The value returned can be use in subsequent requests (for clients)
1124 * or in the response (for servers) in order to compress the content stream.
1129 const char * /* O - Content-Coding value or
1130 @code NULL@ for the identity
1132 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
1135 if (http
&& http
->accept_encoding
)
1137 int i
; /* Looping var */
1138 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
1139 *start
, /* Start of coding value */
1140 *end
; /* End of coding value */
1141 double qvalue
; /* "qvalue" for coding */
1142 struct lconv
*loc
= localeconv(); /* Locale data */
1143 static const char * const codings
[] =
1144 { /* Supported content codings */
1151 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
1153 for (start
= temp
; *start
; start
= end
)
1156 * Find the end of the coding name...
1161 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
1167 * Grab the qvalue as needed...
1170 if (!strncmp(end
, ";q=", 3))
1171 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1174 * Skip past all attributes...
1178 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1184 while (*end
&& isspace(*end
& 255))
1188 * Check value if it matches something we support...
1194 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1195 if (!strcmp(start
, codings
[i
]))
1196 return (codings
[i
]);
1199 #endif /* HAVE_LIBZ */
1206 * 'httpGetAuthString()' - Get the current authorization string.
1208 * The authorization string is set by cupsDoAuthentication() and
1209 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
1210 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
1213 * @since CUPS 1.3/OS X 10.5@
1216 char * /* O - Authorization string */
1217 httpGetAuthString(http_t
*http
) /* I - Connection to server */
1220 return (http
->authstring
);
1227 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
1229 * @since CUPS 1.2/OS X 10.5@
1232 int /* O - 1 if blocking, 0 if non-blocking */
1233 httpGetBlocking(http_t
*http
) /* I - Connection to server */
1235 return (http
? http
->blocking
: 0);
1240 * 'httpGetCookie()' - Get any cookie data from the response.
1242 * @since CUPS 1.1.19/OS X 10.3@
1245 const char * /* O - Cookie data or NULL */
1246 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1248 return (http
? http
->cookie
: NULL
);
1253 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1255 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1256 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1261 http_status_t
/* O - Expect: status, if any */
1262 httpGetExpect(http_t
*http
) /* I - Connection to client */
1265 return (HTTP_STATUS_ERROR
);
1267 return (http
->expect
);
1272 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1274 * @since CUPS 1.2/OS X 10.5@
1277 int /* O - File descriptor or -1 if none */
1278 httpGetFd(http_t
*http
) /* I - Connection to server */
1280 return (http
? http
->fd
: -1);
1285 * 'httpGetField()' - Get a field value from a request/response.
1288 const char * /* O - Field value */
1289 httpGetField(http_t
*http
, /* I - Connection to server */
1290 http_field_t field
) /* I - Field to get */
1292 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1297 case HTTP_FIELD_ACCEPT_ENCODING
:
1298 return (http
->accept_encoding
);
1300 case HTTP_FIELD_ALLOW
:
1301 return (http
->allow
);
1303 case HTTP_FIELD_SERVER
:
1304 return (http
->server
);
1306 case HTTP_FIELD_AUTHORIZATION
:
1307 if (http
->field_authorization
)
1310 * Special case for WWW-Authenticate: as its contents can be
1311 * longer than HTTP_MAX_VALUE...
1314 return (http
->field_authorization
);
1318 return (http
->fields
[field
]);
1324 * 'httpGetLength()' - Get the amount of data remaining from the
1325 * content-length or transfer-encoding fields.
1327 * This function is deprecated and will not return lengths larger than
1328 * 2^31 - 1; use httpGetLength2() instead.
1333 int /* O - Content length */
1334 httpGetLength(http_t
*http
) /* I - Connection to server */
1337 * Get the read content length and return the 32-bit value.
1342 httpGetLength2(http
);
1344 return (http
->_data_remaining
);
1352 * 'httpGetLength2()' - Get the amount of data remaining from the
1353 * content-length or transfer-encoding fields.
1355 * This function returns the complete content length, even for
1356 * content larger than 2^31 - 1.
1358 * @since CUPS 1.2/OS X 10.5@
1361 off_t
/* O - Content length */
1362 httpGetLength2(http_t
*http
) /* I - Connection to server */
1364 off_t remaining
; /* Remaining length */
1367 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1368 http_states
[http
->state
+ 1]));
1373 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1375 DEBUG_puts("4httpGetLength2: chunked request!");
1381 * The following is a hack for HTTP servers that don't send a
1382 * Content-Length or Transfer-Encoding field...
1384 * If there is no Content-Length then the connection must close
1385 * after the transfer is complete...
1388 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1391 * Default content length is 0 for errors and certain types of operations,
1392 * and 2^31-1 for other successful requests...
1395 if (http
->status
>= HTTP_MULTIPLE_CHOICES
||
1396 http
->state
== HTTP_STATE_OPTIONS
||
1397 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1398 http
->state
== HTTP_STATE_HEAD
||
1399 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1400 http
->state
== HTTP_STATE_DELETE
||
1401 http
->state
== HTTP_STATE_TRACE
||
1402 http
->state
== HTTP_STATE_CONNECT
)
1405 remaining
= 2147483647;
1407 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1411 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1412 CUPS_LLCAST remaining
));
1420 * 'httpGets()' - Get a line of text from a HTTP connection.
1423 char * /* O - Line or NULL */
1424 httpGets(char *line
, /* I - Line to read into */
1425 int length
, /* I - Max length of buffer */
1426 http_t
*http
) /* I - Connection to server */
1428 char *lineptr
, /* Pointer into line */
1429 *lineend
, /* End of line */
1430 *bufptr
, /* Pointer into input buffer */
1431 *bufend
; /* Pointer to end of buffer */
1432 int bytes
, /* Number of bytes read */
1433 eol
; /* End-of-line? */
1436 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1438 if (http
== NULL
|| line
== NULL
)
1442 * Read a line from the buffer...
1447 lineend
= line
+ length
- 1;
1450 while (lineptr
< lineend
)
1453 * Pre-load the buffer as needed...
1462 while (http
->used
== 0)
1465 * No newline; see if there is more data to be read...
1468 while (!_httpWait(http
, http
->wait_value
, 1))
1470 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1473 DEBUG_puts("3httpGets: Timed out!");
1475 http
->error
= WSAETIMEDOUT
;
1477 http
->error
= ETIMEDOUT
;
1484 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1485 HTTP_MAX_BUFFER
- http
->used
);
1487 #endif /* HAVE_SSL */
1488 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1489 HTTP_MAX_BUFFER
- http
->used
, 0);
1491 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1494 http_debug_hex("httpGets", http
->buffer
+ http
->used
, bytes
);
1500 * Nope, can't get a line this time...
1504 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1506 if (WSAGetLastError() == WSAEINTR
)
1508 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1510 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1513 http
->error
= WSAGetLastError();
1515 else if (WSAGetLastError() != http
->error
)
1517 http
->error
= WSAGetLastError();
1522 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1526 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1528 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1530 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1533 http
->error
= errno
;
1535 else if (errno
!= http
->error
)
1537 http
->error
= errno
;
1544 else if (bytes
== 0)
1546 http
->error
= EPIPE
;
1552 * Yup, update the amount used...
1555 http
->used
+= bytes
;
1559 * Now copy as much of the current line as possible...
1562 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1563 lineptr
< lineend
&& bufptr
< bufend
;)
1565 if (*bufptr
== 0x0a)
1571 else if (*bufptr
== 0x0d)
1574 *lineptr
++ = *bufptr
++;
1577 http
->used
-= (int)(bufptr
- http
->buffer
);
1579 memmove(http
->buffer
, bufptr
, http
->used
);
1587 http
->activity
= time(NULL
);
1591 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1597 DEBUG_puts("3httpGets: No new line available!");
1604 * 'httpGetState()' - Get the current state of the HTTP request.
1607 http_state_t
/* O - HTTP state */
1608 httpGetState(http_t
*http
) /* I - Connection to server */
1610 return (http
? http
->state
: HTTP_STATE_ERROR
);
1615 * 'httpGetStatus()' - Get the status of the last HTTP request.
1617 * @since CUPS 1.2/OS X 10.5@
1620 http_status_t
/* O - HTTP status */
1621 httpGetStatus(http_t
*http
) /* I - Connection to server */
1623 return (http
? http
->status
: HTTP_ERROR
);
1628 * 'httpGetSubField()' - Get a sub-field value.
1633 char * /* O - Value or NULL */
1634 httpGetSubField(http_t
*http
, /* I - Connection to server */
1635 http_field_t field
, /* I - Field index */
1636 const char *name
, /* I - Name of sub-field */
1637 char *value
) /* O - Value string */
1639 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1644 * 'httpGetSubField2()' - Get a sub-field value.
1646 * @since CUPS 1.2/OS X 10.5@
1649 char * /* O - Value or NULL */
1650 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1651 http_field_t field
, /* I - Field index */
1652 const char *name
, /* I - Name of sub-field */
1653 char *value
, /* O - Value string */
1654 int valuelen
) /* I - Size of value buffer */
1656 const char *fptr
; /* Pointer into field */
1657 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1658 *ptr
, /* Pointer into string buffer */
1659 *end
; /* End of value buffer */
1661 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1662 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1664 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1665 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1668 end
= value
+ valuelen
- 1;
1670 for (fptr
= http
->fields
[field
]; *fptr
;)
1673 * Skip leading whitespace...
1676 while (_cups_isspace(*fptr
))
1686 * Get the sub-field name...
1690 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1691 ptr
< (temp
+ sizeof(temp
) - 1);
1696 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1699 * Skip trailing chars up to the '='...
1702 while (_cups_isspace(*fptr
))
1712 * Skip = and leading whitespace...
1717 while (_cups_isspace(*fptr
))
1723 * Read quoted string...
1726 for (ptr
= value
, fptr
++;
1727 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1732 while (*fptr
&& *fptr
!= '\"')
1741 * Read unquoted string...
1745 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1750 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1754 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1757 * See if this is the one...
1760 if (!strcmp(name
, temp
))
1762 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1769 DEBUG_puts("3httpGetSubField2: Returning NULL");
1776 * 'httpGetVersion()' - Get the HTTP version at the other end.
1779 http_version_t
/* O - Version number */
1780 httpGetVersion(http_t
*http
) /* I - Connection to server */
1782 return (http
? http
->version
: HTTP_VERSION_1_0
);
1787 * 'httpHead()' - Send a HEAD request to the server.
1790 int /* O - Status of call (0 = success) */
1791 httpHead(http_t
*http
, /* I - Connection to server */
1792 const char *uri
) /* I - URI for head */
1794 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1795 return (http_send(http
, HTTP_HEAD
, uri
));
1800 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1801 * default HTTP proxy (if any).
1805 httpInitialize(void)
1807 static int initialized
= 0; /* Have we been called before? */
1809 WSADATA winsockdata
; /* WinSock data */
1812 int i
; /* Looping var */
1813 unsigned char data
[1024]; /* Seed data */
1814 #endif /* HAVE_LIBSSL */
1820 _cupsGlobalUnlock();
1825 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1827 #elif !defined(SO_NOSIGPIPE)
1829 * Ignore SIGPIPE signals...
1833 sigset(SIGPIPE
, SIG_IGN
);
1835 # elif defined(HAVE_SIGACTION)
1836 struct sigaction action
; /* POSIX sigaction data */
1839 memset(&action
, 0, sizeof(action
));
1840 action
.sa_handler
= SIG_IGN
;
1841 sigaction(SIGPIPE
, &action
, NULL
);
1844 signal(SIGPIPE
, SIG_IGN
);
1845 # endif /* !SO_NOSIGPIPE */
1850 * Initialize GNU TLS...
1853 gnutls_global_init();
1855 #elif defined(HAVE_LIBSSL)
1857 * Initialize OpenSSL...
1860 SSL_load_error_strings();
1864 * Using the current time is a dubious random seed, but on some systems
1865 * it is the best we can do (on others, this seed isn't even used...)
1868 CUPS_SRAND(time(NULL
));
1870 for (i
= 0; i
< sizeof(data
); i
++)
1871 data
[i
] = CUPS_RAND();
1873 RAND_seed(data
, sizeof(data
));
1874 #endif /* HAVE_GNUTLS */
1877 _cupsGlobalUnlock();
1882 * 'httpOptions()' - Send an OPTIONS request to the server.
1885 int /* O - Status of call (0 = success) */
1886 httpOptions(http_t
*http
, /* I - Connection to server */
1887 const char *uri
) /* I - URI for options */
1889 return (http_send(http
, HTTP_OPTIONS
, uri
));
1894 * 'httpPeek()' - Peek at data from a HTTP connection.
1896 * This function copies available data from the given HTTP connection, reading
1897 * a buffer as needed. The data is still available for reading using
1898 * @link httpRead@ or @link httpRead2@.
1900 * For non-blocking connections the usual timeouts apply.
1905 ssize_t
/* O - Number of bytes copied */
1906 httpPeek(http_t
*http
, /* I - Connection to server */
1907 char *buffer
, /* I - Buffer for data */
1908 size_t length
) /* I - Maximum number of bytes */
1910 ssize_t bytes
; /* Bytes read */
1911 char len
[32]; /* Length string */
1914 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1915 http
, buffer
, CUPS_LLCAST length
));
1917 if (http
== NULL
|| buffer
== NULL
)
1920 http
->activity
= time(NULL
);
1926 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1927 http
->data_remaining
<= 0)
1929 DEBUG_puts("2httpPeek: Getting chunk length...");
1931 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1933 DEBUG_puts("1httpPeek: Could not get length!");
1937 http
->data_remaining
= strtoll(len
, NULL
, 16);
1938 if (http
->data_remaining
< 0)
1940 DEBUG_puts("1httpPeek: Negative chunk length!");
1945 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1946 CUPS_LLCAST http
->data_remaining
));
1948 if (http
->data_remaining
<= 0)
1951 * A zero-length chunk ends a transfer; unless we are reading POST
1955 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1956 httpGets(len
, sizeof(len
), http
);
1958 if (http
->state
== HTTP_STATE_POST_RECV
)
1961 http
->state
= HTTP_STATE_WAITING
;
1963 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1964 http_states
[http
->state
+ 1]));
1967 * Prevent future reads for this request...
1970 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1974 else if (length
> (size_t)http
->data_remaining
)
1975 length
= (size_t)http
->data_remaining
;
1977 if (http
->used
== 0)
1980 * Buffer small reads for better performance...
1983 ssize_t buflen
; /* Length of read for buffer */
1985 if (!http
->blocking
)
1987 while (!httpWait(http
, http
->wait_value
))
1989 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1996 if (http
->data_remaining
> sizeof(http
->buffer
))
1997 buflen
= sizeof(http
->buffer
);
1999 buflen
= http
->data_remaining
;
2001 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
2007 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
2009 #endif /* HAVE_SSL */
2010 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
2015 if (WSAGetLastError() != WSAEINTR
)
2017 http
->error
= WSAGetLastError();
2020 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
2022 if (!http
->timeout_cb
||
2023 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2025 http
->error
= WSAEWOULDBLOCK
;
2030 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2032 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2034 http
->error
= errno
;
2037 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2039 http
->error
= errno
;
2043 else if (errno
!= EINTR
)
2045 http
->error
= errno
;
2053 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
2054 CUPS_LLCAST bytes
));
2056 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
2064 if (length
> (size_t)http
->used
)
2065 length
= (size_t)http
->used
;
2067 bytes
= (ssize_t
)length
;
2069 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
2072 memcpy(buffer
, http
->buffer
, length
);
2080 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2083 http
->error
= WSAGetLastError();
2085 if (errno
== EINTR
|| errno
== EAGAIN
)
2088 http
->error
= errno
;
2091 else if (bytes
== 0)
2093 http
->error
= EPIPE
;
2098 http_debug_hex("httpPeek", buffer
, (int)bytes
);
2104 ssize_t
/* O - Number of bytes copied */
2105 _httpPeek(http_t
*http
, /* I - Connection to server */
2106 char *buffer
, /* I - Buffer for data */
2107 size_t length
) /* I - Maximum number of bytes */
2109 /* TODO: Remove in CUPS 1.8 */
2110 return (httpPeek(http
, buffer
, length
));
2115 * 'httpPost()' - Send a POST request to the server.
2118 int /* O - Status of call (0 = success) */
2119 httpPost(http_t
*http
, /* I - Connection to server */
2120 const char *uri
) /* I - URI for post */
2122 return (http_send(http
, HTTP_POST
, uri
));
2127 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
2132 int /* O - Number of bytes written */
2133 httpPrintf(http_t
*http
, /* I - Connection to server */
2134 const char *format
, /* I - printf-style format string */
2135 ...) /* I - Additional args as needed */
2137 int bytes
; /* Number of bytes to write */
2138 char buf
[16384]; /* Buffer for formatted string */
2139 va_list ap
; /* Variable argument pointer */
2142 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
2144 va_start(ap
, format
);
2145 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
2148 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
2150 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
2151 return (httpWrite2(http
, buf
, bytes
));
2156 DEBUG_puts("4httpPrintf: flushing existing data...");
2158 if (httpFlushWrite(http
) < 0)
2162 return (http_write(http
, buf
, bytes
));
2168 * 'httpPut()' - Send a PUT request to the server.
2171 int /* O - Status of call (0 = success) */
2172 httpPut(http_t
*http
, /* I - Connection to server */
2173 const char *uri
) /* I - URI to put */
2175 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2176 return (http_send(http
, HTTP_PUT
, uri
));
2181 * 'httpRead()' - Read data from a HTTP connection.
2183 * This function is deprecated. Use the httpRead2() function which can
2184 * read more than 2GB of data.
2189 int /* O - Number of bytes read */
2190 httpRead(http_t
*http
, /* I - Connection to server */
2191 char *buffer
, /* I - Buffer for data */
2192 int length
) /* I - Maximum number of bytes */
2194 return ((int)httpRead2(http
, buffer
, length
));
2199 * 'httpRead2()' - Read data from a HTTP connection.
2201 * @since CUPS 1.2/OS X 10.5@
2204 ssize_t
/* O - Number of bytes read */
2205 httpRead2(http_t
*http
, /* I - Connection to server */
2206 char *buffer
, /* I - Buffer for data */
2207 size_t length
) /* I - Maximum number of bytes */
2209 ssize_t bytes
; /* Bytes read */
2210 char len
[32]; /* Length string */
2213 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2214 ") coding=%d", http
, buffer
, CUPS_LLCAST length
,
2217 if (http
== NULL
|| buffer
== NULL
)
2220 http
->activity
= time(NULL
);
2226 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
2227 http
->data_remaining
<= 0)
2229 DEBUG_puts("2httpRead2: Getting chunk length...");
2231 if (httpGets(len
, sizeof(len
), http
) == NULL
)
2233 DEBUG_puts("1httpRead2: Could not get length!");
2237 http
->data_remaining
= strtoll(len
, NULL
, 16);
2238 if (http
->data_remaining
< 0)
2240 DEBUG_puts("1httpRead2: Negative chunk length!");
2245 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
", used=%d",
2246 CUPS_LLCAST http
->data_remaining
, http
->used
));
2248 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
2251 * A zero-length chunk ends a transfer; unless we are reading POST
2257 http_content_coding_finish(http
);
2258 #endif /* HAVE_LIBZ */
2260 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2261 httpGets(len
, sizeof(len
), http
);
2263 if (http
->state
== HTTP_STATE_POST_RECV
)
2266 http
->state
= HTTP_STATE_WAITING
;
2268 DEBUG_printf(("1httpRead2: 0-length chunk, set state to %s.",
2269 http_states
[http
->state
+ 1]));
2272 * Prevent future reads for this request...
2275 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2279 else if ((http
->data_encoding
== HTTP_ENCODING_LENGTH
||
2280 http
->coding
== _HTTP_CODING_IDENTITY
) &&
2281 length
> (size_t)http
->data_remaining
)
2282 length
= (size_t)http
->data_remaining
;
2285 if (http
->used
== 0 && (length
<= 256 || http
->coding
))
2287 if (http
->used
== 0 && length
<= 256)
2288 #endif /* HAVE_LIBZ */
2291 * Buffer small/compressed reads for better performance...
2294 ssize_t buflen
; /* Length of read for buffer */
2296 if (!http
->blocking
)
2298 while (!httpWait(http
, http
->wait_value
))
2300 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2307 if (http
->data_remaining
> sizeof(http
->buffer
))
2308 buflen
= sizeof(http
->buffer
);
2310 buflen
= http
->data_remaining
;
2312 DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen
));
2318 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
2320 #endif /* HAVE_SSL */
2321 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
2326 if (WSAGetLastError() != WSAEINTR
)
2328 http
->error
= WSAGetLastError();
2331 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
2333 if (!http
->timeout_cb
||
2334 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2336 http
->error
= WSAEWOULDBLOCK
;
2341 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2343 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2345 http
->error
= errno
;
2348 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2350 http
->error
= errno
;
2354 else if (errno
!= EINTR
)
2356 http
->error
= errno
;
2364 DEBUG_printf(("2httpRead2: Read " CUPS_LLFMT
" bytes into buffer.",
2365 CUPS_LLCAST bytes
));
2367 http_debug_hex("httpRead2", http
->buffer
, (int)bytes
);
2376 int zerr
; /* Decompressor error */
2377 off_t comp_avail
, /* Maximum bytes for decompression */
2378 comp_bytes
; /* Compressed bytes "used" */
2380 if (http
->used
> http
->data_remaining
)
2381 comp_avail
= http
->data_remaining
;
2383 comp_avail
= http
->used
;
2385 DEBUG_printf(("2httpRead2: length=%d, avail_in=%d", (int)length
,
2388 http
->stream
.next_in
= (Bytef
*)http
->buffer
;
2389 http
->stream
.avail_in
= comp_avail
;
2390 http
->stream
.next_out
= (Bytef
*)buffer
;
2391 http
->stream
.avail_out
= length
;
2393 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2395 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2400 bytes
= length
- http
->stream
.avail_out
;
2401 comp_bytes
= comp_avail
- http
->stream
.avail_in
;
2403 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d, "
2404 "comp_bytes=%d", http
->stream
.avail_in
,
2405 http
->stream
.avail_out
, (int)bytes
, (int)comp_bytes
));
2407 if ((http
->used
- comp_bytes
) > 0)
2409 http
->used
-= comp_bytes
;
2410 memmove(http
->buffer
, http
->stream
.next_in
, http
->used
);
2416 * Adjust remaining bytes since chunk/content lengths are compressed while
2417 * CUPS HTTP APIs return uncompressed sizes...
2420 http
->data_remaining
+= bytes
- comp_bytes
;
2423 #endif /* HAVE_LIBZ */
2426 if (length
> (size_t)http
->used
)
2427 length
= (size_t)http
->used
;
2429 bytes
= (ssize_t
)length
;
2431 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2434 memcpy(buffer
, http
->buffer
, length
);
2435 http
->used
-= (int)length
;
2438 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2443 if (!http
->blocking
)
2445 while (!httpWait(http
, http
->wait_value
))
2447 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2454 while ((bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
)) < 0)
2457 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2459 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2462 else if (WSAGetLastError() != WSAEINTR
)
2465 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2467 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2469 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2472 else if (errno
!= EINTR
)
2477 #endif /* HAVE_SSL */
2480 if (!http
->blocking
)
2482 while (!httpWait(http
, http
->wait_value
))
2484 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2491 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2492 CUPS_LLCAST length
));
2495 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2497 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2499 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2502 else if (WSAGetLastError() != WSAEINTR
)
2506 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2508 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2510 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2512 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2515 else if (errno
!= EINTR
)
2520 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2521 CUPS_LLCAST bytes
));
2523 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2529 http
->data_remaining
-= bytes
;
2531 if (http
->data_remaining
<= INT_MAX
)
2532 http
->_data_remaining
= (int)http
->data_remaining
;
2534 http
->_data_remaining
= INT_MAX
;
2539 if (WSAGetLastError() == WSAEINTR
)
2542 http
->error
= WSAGetLastError();
2544 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2547 http
->error
= errno
;
2552 http
->error
= EPIPE
;
2556 if (http
->data_remaining
== 0)
2558 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2559 httpGets(len
, sizeof(len
), http
);
2564 http_content_coding_finish(http
);
2565 #endif /* HAVE_LIBZ */
2567 if (http
->state
== HTTP_STATE_POST_RECV
)
2570 http
->state
= HTTP_STATE_WAITING
;
2572 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2573 http_states
[http
->state
+ 1]));
2581 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2583 * '_httpReadCDSA()' - Read function for the CDSA library.
2586 OSStatus
/* O - -1 on error, 0 on success */
2588 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2589 void *data
, /* I - Data buffer */
2590 size_t *dataLength
) /* IO - Number of bytes */
2592 OSStatus result
; /* Return value */
2593 ssize_t bytes
; /* Number of bytes read */
2594 http_t
*http
; /* HTTP connection */
2597 http
= (http_t
*)connection
;
2599 if (!http
->blocking
)
2602 * Make sure we have data before we read...
2605 while (!_httpWait(http
, http
->wait_value
, 0))
2607 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2610 http
->error
= ETIMEDOUT
;
2617 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2619 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2621 if (bytes
== *dataLength
)
2627 *dataLength
= bytes
;
2628 result
= errSSLWouldBlock
;
2635 result
= errSSLClosedGraceful
;
2636 else if (errno
== EAGAIN
)
2637 result
= errSSLWouldBlock
;
2639 result
= errSSLClosedAbort
;
2644 #endif /* HAVE_SSL && HAVE_CDSASSL */
2647 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2649 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2652 ssize_t
/* O - Number of bytes read or -1 on error */
2654 gnutls_transport_ptr ptr
, /* I - Connection to server */
2655 void *data
, /* I - Buffer */
2656 size_t length
) /* I - Number of bytes to read */
2658 http_t
*http
; /* HTTP connection */
2659 ssize_t bytes
; /* Bytes read */
2662 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2664 http
= (http_t
*)ptr
;
2666 if (!http
->blocking
)
2669 * Make sure we have data before we read...
2672 while (!_httpWait(http
, http
->wait_value
, 0))
2674 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2677 http
->error
= ETIMEDOUT
;
2682 bytes
= recv(http
->fd
, data
, length
, 0);
2683 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2686 #endif /* HAVE_SSL && HAVE_GNUTLS */
2690 * 'httpReadRequest()' - Read a HTTP request from a connection.
2695 http_state_t
/* O - New state of connection */
2696 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2697 char *uri
, /* I - URI buffer */
2698 size_t urilen
) /* I - Size of URI buffer */
2700 char line
[4096], /* HTTP request line */
2701 *req_method
, /* HTTP request method */
2702 *req_uri
, /* HTTP request URI */
2703 *req_version
; /* HTTP request version number string */
2707 * Range check input...
2710 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2711 http
, uri
, CUPS_LLCAST urilen
));
2716 if (!http
|| !uri
|| urilen
< 1)
2718 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2719 return (HTTP_STATE_ERROR
);
2721 else if (http
->state
!= HTTP_STATE_WAITING
)
2723 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2724 http_states
[http
->state
+ 1]));
2725 return (HTTP_STATE_ERROR
);
2732 httpClearFields(http
);
2734 http
->activity
= time(NULL
);
2735 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2736 http
->data_remaining
= 0;
2737 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2738 http
->status
= HTTP_STATUS_OK
;
2739 http
->version
= HTTP_VERSION_1_1
;
2742 * Read a line from the socket...
2745 if (!httpGets(line
, sizeof(line
), http
))
2747 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2748 return (HTTP_STATE_ERROR
);
2753 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2754 return (HTTP_STATE_WAITING
);
2757 DEBUG_printf(("1httpReadRequest: %s", line
));
2766 while (*req_uri
&& !isspace(*req_uri
& 255))
2771 DEBUG_puts("1httpReadRequest: No request URI.");
2772 return (HTTP_STATE_ERROR
);
2777 while (*req_uri
&& isspace(*req_uri
& 255))
2780 req_version
= req_uri
;
2782 while (*req_version
&& !isspace(*req_version
& 255))
2787 DEBUG_puts("1httpReadRequest: No request protocol version.");
2788 return (HTTP_STATE_ERROR
);
2791 *req_version
++ = '\0';
2793 while (*req_version
&& isspace(*req_version
& 255))
2800 if (!strcmp(req_method
, "OPTIONS"))
2801 http
->state
= HTTP_STATE_OPTIONS
;
2802 else if (!strcmp(req_method
, "GET"))
2803 http
->state
= HTTP_STATE_GET
;
2804 else if (!strcmp(req_method
, "HEAD"))
2805 http
->state
= HTTP_STATE_HEAD
;
2806 else if (!strcmp(req_method
, "POST"))
2807 http
->state
= HTTP_STATE_POST
;
2808 else if (!strcmp(req_method
, "PUT"))
2809 http
->state
= HTTP_STATE_PUT
;
2810 else if (!strcmp(req_method
, "DELETE"))
2811 http
->state
= HTTP_STATE_DELETE
;
2812 else if (!strcmp(req_method
, "TRACE"))
2813 http
->state
= HTTP_STATE_TRACE
;
2814 else if (!strcmp(req_method
, "CONNECT"))
2815 http
->state
= HTTP_STATE_CONNECT
;
2818 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2819 return (HTTP_STATE_UNKNOWN_METHOD
);
2822 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2823 http_states
[http
->state
+ 1]));
2825 if (!strcmp(req_version
, "HTTP/1.0"))
2827 http
->version
= HTTP_VERSION_1_0
;
2828 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2830 else if (!strcmp(req_version
, "HTTP/1.1"))
2832 http
->version
= HTTP_VERSION_1_1
;
2833 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2837 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2838 return (HTTP_STATE_UNKNOWN_VERSION
);
2841 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2842 strlcpy(uri
, req_uri
, urilen
);
2844 return (http
->state
);
2849 * 'httpReconnect()' - Reconnect to a HTTP server.
2851 * This function is deprecated. Please use the @link httpReconnect2@ function
2857 int /* O - 0 on success, non-zero on failure */
2858 httpReconnect(http_t
*http
) /* I - Connection to server */
2860 DEBUG_printf(("httpReconnect(http=%p)", http
));
2862 return (httpReconnect2(http
, 30000, NULL
));
2867 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2871 int /* O - 0 on success, non-zero on failure */
2872 httpReconnect2(http_t
*http
, /* I - Connection to server */
2873 int msec
, /* I - Timeout in milliseconds */
2874 int *cancel
) /* I - Pointer to "cancel" variable */
2876 http_addrlist_t
*addr
; /* Connected address */
2878 http_addrlist_t
*current
; /* Current address */
2879 char temp
[256]; /* Temporary address string */
2883 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2888 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
2895 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2896 http_shutdown_ssl(http
);
2898 #endif /* HAVE_SSL */
2901 * Close any previously open socket...
2906 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2909 closesocket(http
->fd
);
2918 * Reset all state (except fields, which may be reused)...
2921 http
->state
= HTTP_STATE_WAITING
;
2922 http
->status
= HTTP_STATUS_CONTINUE
;
2923 http
->version
= HTTP_VERSION_1_1
;
2924 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2925 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2926 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2927 http
->_data_remaining
= 0;
2930 http
->data_remaining
= 0;
2931 http
->hostaddr
= NULL
;
2935 * Connect to the server...
2939 for (current
= http
->addrlist
; current
; current
= current
->next
)
2940 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2941 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2942 httpAddrPort(&(current
->addr
))));
2945 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2949 * Unable to connect...
2953 http
->error
= WSAGetLastError();
2955 http
->error
= errno
;
2957 http
->status
= HTTP_ERROR
;
2959 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2960 strerror(http
->error
)));
2965 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2967 if (http
->timeout_value
> 0)
2968 http_set_timeout(http
->fd
, http
->timeout_value
);
2970 http
->hostaddr
= &(addr
->addr
);
2974 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2977 * Always do encryption via SSL.
2980 if (http_setup_ssl(http
) != 0)
2983 closesocket(http
->fd
);
2991 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2992 return (http_upgrade(http
));
2993 #endif /* HAVE_SSL */
2995 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2996 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2997 httpAddrPort(http
->hostaddr
)));
3004 * 'httpSetAuthString()' - Set the current authorization string.
3006 * This function just stores a copy of the current authorization string in
3007 * the HTTP connection object. You must still call httpSetField() to set
3008 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
3009 * httpHead(), httpOptions(), httpPost, or httpPut().
3011 * @since CUPS 1.3/OS X 10.5@
3015 httpSetAuthString(http_t
*http
, /* I - Connection to server */
3016 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
3017 const char *data
) /* I - Auth data (NULL for none) */
3020 * Range check input...
3026 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
3027 free(http
->authstring
);
3029 http
->authstring
= http
->_authstring
;
3034 * Set the current authorization string...
3037 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
3040 if (len
> (int)sizeof(http
->_authstring
))
3042 if ((temp
= malloc(len
)) == NULL
)
3043 len
= sizeof(http
->_authstring
);
3045 http
->authstring
= temp
;
3049 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
3051 strlcpy(http
->authstring
, scheme
, len
);
3056 * Clear the current authorization string...
3059 http
->_authstring
[0] = '\0';
3065 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
3068 * @since CUPS 1.5/OS X 10.7@
3071 int /* O - Status of call (0 = success) */
3072 httpSetCredentials(http_t
*http
, /* I - Connection to server */
3073 cups_array_t
*credentials
) /* I - Array of credentials */
3075 if (!http
|| cupsArrayCount(credentials
) < 1)
3078 _httpFreeCredentials(http
->tls_credentials
);
3080 http
->tls_credentials
= _httpCreateCredentials(credentials
);
3082 return (http
->tls_credentials
? 0 : -1);
3087 * 'httpSetCookie()' - Set the cookie value(s).
3089 * @since CUPS 1.1.19/OS X 10.3@
3093 httpSetCookie(http_t
*http
, /* I - Connection */
3094 const char *cookie
) /* I - Cookie string */
3103 http
->cookie
= strdup(cookie
);
3105 http
->cookie
= NULL
;
3110 * 'httpSetExpect()' - Set the Expect: header in a request.
3112 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
3115 * @since CUPS 1.2/OS X 10.5@
3119 httpSetExpect(http_t
*http
, /* I - Connection to server */
3120 http_status_t expect
) /* I - HTTP status to expect
3121 (@code HTTP_CONTINUE@) */
3124 http
->expect
= expect
;
3129 * 'httpSetField()' - Set the value of an HTTP header.
3133 httpSetField(http_t
*http
, /* I - Connection to server */
3134 http_field_t field
, /* I - Field index */
3135 const char *value
) /* I - Value */
3137 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
3138 field
, http_fields
[field
], value
));
3141 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
3142 field
>= HTTP_FIELD_MAX
||
3148 case HTTP_FIELD_ACCEPT_ENCODING
:
3149 if (http
->accept_encoding
)
3150 _cupsStrFree(http
->accept_encoding
);
3152 http
->accept_encoding
= _cupsStrAlloc(value
);
3155 case HTTP_FIELD_ALLOW
:
3157 _cupsStrFree(http
->allow
);
3159 http
->allow
= _cupsStrAlloc(value
);
3162 case HTTP_FIELD_SERVER
:
3164 _cupsStrFree(http
->server
);
3166 http
->server
= _cupsStrAlloc(value
);
3170 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
3174 if (field
== HTTP_FIELD_AUTHORIZATION
)
3177 * Special case for Authorization: as its contents can be
3178 * longer than HTTP_MAX_VALUE
3181 if (http
->field_authorization
)
3182 free(http
->field_authorization
);
3184 http
->field_authorization
= strdup(value
);
3186 else if (field
== HTTP_FIELD_HOST
)
3189 * Special-case for Host: as we don't want a trailing "." on the hostname and
3190 * need to bracket IPv6 numeric addresses.
3193 char *ptr
= strchr(value
, ':');
3195 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
3198 * Bracket IPv6 numeric addresses...
3200 * This is slightly inefficient (basically copying twice), but is an edge
3201 * case and not worth optimizing...
3204 snprintf(http
->fields
[HTTP_FIELD_HOST
],
3205 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
3210 * Check for a trailing dot on the hostname...
3213 ptr
= http
->fields
[HTTP_FIELD_HOST
];
3217 ptr
+= strlen(ptr
) - 1;
3225 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
3226 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
3228 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
3229 http_content_coding_start(http
, value
);
3231 #endif /* HAVE_LIBZ */
3236 * 'httpSetLength()' - Set the content-length and content-encoding.
3238 * @since CUPS 1.2/OS X 10.5@
3242 httpSetLength(http_t
*http
, /* I - Connection to server */
3243 size_t length
) /* I - Length (0 for chunked) */
3245 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
3246 CUPS_LLCAST length
));
3253 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
3255 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
3259 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
3260 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
3261 CUPS_LLFMT
, CUPS_LLCAST length
);
3267 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
3269 * The optional timeout callback receives both the HTTP connection and a user
3270 * data pointer and must return 1 to continue or 0 to error (time) out.
3272 * @since CUPS 1.5/OS X 10.7@
3277 http_t
*http
, /* I - Connection to server */
3278 double timeout
, /* I - Number of seconds for timeout,
3279 must be greater than 0 */
3280 http_timeout_cb_t cb
, /* I - Callback function or NULL */
3281 void *user_data
) /* I - User data pointer */
3283 if (!http
|| timeout
<= 0.0)
3286 http
->timeout_cb
= cb
;
3287 http
->timeout_data
= user_data
;
3288 http
->timeout_value
= timeout
;
3291 http_set_timeout(http
->fd
, timeout
);
3293 http_set_wait(http
);
3298 * 'httpTrace()' - Send an TRACE request to the server.
3301 int /* O - Status of call (0 = success) */
3302 httpTrace(http_t
*http
, /* I - Connection to server */
3303 const char *uri
) /* I - URI for trace */
3305 return (http_send(http
, HTTP_TRACE
, uri
));
3310 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3312 * Note: Unlike httpUpdate(), this function does not flush pending write data
3313 * and only retrieves a single status line from the HTTP connection.
3316 int /* O - 1 to continue, 0 to stop */
3317 _httpUpdate(http_t
*http
, /* I - Connection to server */
3318 http_status_t
*status
) /* O - Current HTTP status */
3320 char line
[32768], /* Line from connection... */
3321 *value
; /* Pointer to value on line */
3322 http_field_t field
; /* Field index */
3323 int major
, minor
; /* HTTP version numbers */
3326 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3327 http_states
[http
->state
+ 1]));
3330 * Grab a single line from the connection...
3333 if (!httpGets(line
, sizeof(line
), http
))
3335 *status
= HTTP_ERROR
;
3339 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3341 if (line
[0] == '\0')
3344 * Blank line means the start of the data section (if any). Return
3345 * the result code, too...
3347 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3348 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3352 if (http
->status
== HTTP_STATUS_CONTINUE
)
3354 *status
= http
->status
;
3358 if (http
->status
< HTTP_BAD_REQUEST
)
3359 http
->digest_tries
= 0;
3362 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
3364 if (http_setup_ssl(http
) != 0)
3367 closesocket(http
->fd
);
3372 *status
= http
->status
= HTTP_ERROR
;
3376 *status
= HTTP_STATUS_CONTINUE
;
3379 #endif /* HAVE_SSL */
3381 if (http_set_length(http
) < 0)
3383 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3384 http
->error
= EINVAL
;
3385 http
->status
= *status
= HTTP_ERROR
;
3389 switch (http
->state
)
3393 case HTTP_STATE_POST_RECV
:
3397 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3398 http_states
[http
->state
+ 1]));
3400 case HTTP_POST_SEND
:
3405 http
->state
= HTTP_STATE_WAITING
;
3407 DEBUG_puts("1_httpUpdate: Unknown state, reset state to "
3408 "HTTP_STATE_WAITING.");
3413 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3414 http_content_coding_start(http
,
3415 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3416 #endif /* HAVE_LIBZ */
3418 *status
= http
->status
;
3421 else if (!strncmp(line
, "HTTP/", 5))
3424 * Got the beginning of a response...
3427 int intstatus
; /* Status value as an integer */
3429 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3431 *status
= http
->status
= HTTP_ERROR
;
3435 httpClearFields(http
);
3437 http
->version
= (http_version_t
)(major
* 100 + minor
);
3438 *status
= http
->status
= (http_status_t
)intstatus
;
3440 else if ((value
= strchr(line
, ':')) != NULL
)
3447 while (_cups_isspace(*value
))
3450 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3453 * Be tolerants of servers that send unknown attribute fields...
3456 if (!_cups_strcasecmp(line
, "expect"))
3459 * "Expect: 100-continue" or similar...
3462 http
->expect
= (http_status_t
)atoi(value
);
3464 else if (!_cups_strcasecmp(line
, "cookie"))
3467 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3470 httpSetCookie(http
, value
);
3472 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
3473 httpSetField(http
, field
, value
);
3476 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3481 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3482 http
->error
= EINVAL
;
3483 http
->status
= *status
= HTTP_ERROR
;
3492 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3495 http_status_t
/* O - HTTP status */
3496 httpUpdate(http_t
*http
) /* I - Connection to server */
3498 http_status_t status
; /* Request status */
3501 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3502 http_states
[http
->state
+ 1]));
3505 * Flush pending data, if any...
3510 DEBUG_puts("2httpUpdate: flushing buffer...");
3512 if (httpFlushWrite(http
) < 0)
3513 return (HTTP_ERROR
);
3517 * If we haven't issued any commands, then there is nothing to "update"...
3520 if (http
->state
== HTTP_STATE_WAITING
)
3521 return (HTTP_CONTINUE
);
3524 * Grab all of the lines we can from the connection...
3527 while (_httpUpdate(http
, &status
));
3530 * See if there was an error...
3533 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
3535 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3536 return (http
->status
);
3541 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3542 strerror(http
->error
)));
3543 http
->status
= HTTP_ERROR
;
3544 return (HTTP_ERROR
);
3548 * Return the current status...
3556 * '_httpWait()' - Wait for data available on a connection (no flush).
3559 int /* O - 1 if data is available, 0 otherwise */
3560 _httpWait(http_t
*http
, /* I - Connection to server */
3561 int msec
, /* I - Milliseconds to wait */
3562 int usessl
) /* I - Use SSL context? */
3565 struct pollfd pfd
; /* Polled file descriptor */
3567 fd_set input_set
; /* select() input set */
3568 struct timeval timeout
; /* Timeout */
3569 #endif /* HAVE_POLL */
3570 int nfds
; /* Result from select()/poll() */
3573 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3577 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3582 * Check the SSL/TLS buffers for data first...
3586 if (http
->tls
&& usessl
)
3589 if (SSL_pending(http
->tls
))
3591 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3595 # elif defined(HAVE_GNUTLS)
3596 if (gnutls_record_check_pending(http
->tls
))
3598 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3602 # elif defined(HAVE_CDSASSL)
3603 size_t bytes
; /* Bytes that are available */
3605 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3608 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3611 # endif /* HAVE_LIBSSL */
3613 #endif /* HAVE_SSL */
3616 * Then try doing a select() or poll() to poll the socket...
3621 pfd
.events
= POLLIN
;
3625 nfds
= poll(&pfd
, 1, msec
);
3627 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3632 FD_ZERO(&input_set
);
3633 FD_SET(http
->fd
, &input_set
);
3635 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3639 timeout
.tv_sec
= msec
/ 1000;
3640 timeout
.tv_usec
= (msec
% 1000) * 1000;
3642 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3645 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3647 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3650 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3651 WSAGetLastError() == WSAEWOULDBLOCK
));
3653 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3655 #endif /* HAVE_POLL */
3657 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3665 * 'httpWait()' - Wait for data available on a connection.
3667 * @since CUPS 1.1.19/OS X 10.3@
3670 int /* O - 1 if data is available, 0 otherwise */
3671 httpWait(http_t
*http
, /* I - Connection to server */
3672 int msec
) /* I - Milliseconds to wait */
3675 * First see if there is data in the buffer...
3678 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3685 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3690 * Flush pending data, if any...
3695 DEBUG_puts("3httpWait: Flushing write buffer.");
3697 if (httpFlushWrite(http
) < 0)
3702 * If not, check the SSL/TLS buffers and do a select() on the connection...
3705 return (_httpWait(http
, msec
, 1));
3710 * 'httpWrite()' - Write data to a HTTP connection.
3712 * This function is deprecated. Use the httpWrite2() function which can
3713 * write more than 2GB of data.
3718 int /* O - Number of bytes written */
3719 httpWrite(http_t
*http
, /* I - Connection to server */
3720 const char *buffer
, /* I - Buffer for data */
3721 int length
) /* I - Number of bytes to write */
3723 return ((int)httpWrite2(http
, buffer
, length
));
3728 * 'httpWrite2()' - Write data to a HTTP connection.
3730 * @since CUPS 1.2/OS X 10.5@
3733 ssize_t
/* O - Number of bytes written */
3734 httpWrite2(http_t
*http
, /* I - Connection to server */
3735 const char *buffer
, /* I - Buffer for data */
3736 size_t length
) /* I - Number of bytes to write */
3738 ssize_t bytes
; /* Bytes written */
3741 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3742 buffer
, CUPS_LLCAST length
));
3745 * Range check input...
3748 if (!http
|| !buffer
)
3750 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3755 * Mark activity on the connection...
3758 http
->activity
= time(NULL
);
3761 * Buffer small writes for better performance...
3767 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3771 http_content_coding_finish(http
);
3776 http
->stream
.next_in
= (Bytef
*)buffer
;
3777 http
->stream
.avail_in
= length
;
3778 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3779 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3781 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3783 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3785 if (http
->stream
.avail_out
== 0)
3787 if (httpFlushWrite(http
) < 0)
3789 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3793 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3794 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3798 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3803 #endif /* HAVE_LIBZ */
3806 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3808 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3809 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3811 httpFlushWrite(http
);
3814 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3815 length
< sizeof(http
->wbuffer
))
3818 * Write to buffer...
3821 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3822 CUPS_LLCAST length
));
3824 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3825 http
->wused
+= (int)length
;
3826 bytes
= (ssize_t
)length
;
3831 * Otherwise write the data directly...
3834 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3835 CUPS_LLCAST length
));
3837 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3838 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3840 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3842 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3843 CUPS_LLCAST bytes
));
3846 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3847 http
->data_remaining
-= bytes
;
3853 * Handle end-of-request processing...
3856 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3857 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3860 * Finished with the transfer; unless we are sending POST or PUT
3864 DEBUG_puts("2httpWrite2: Changing states.");
3868 if (httpFlushWrite(http
) < 0)
3872 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3875 * Send a 0-length chunk at the end of the request...
3878 http_write(http
, "0\r\n\r\n", 5);
3881 * Reset the data state...
3884 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3885 http
->data_remaining
= 0;
3888 if (http
->state
== HTTP_STATE_POST_RECV
)
3891 http
->state
= HTTP_STATE_WAITING
;
3893 DEBUG_printf(("2httpWrite2: New state is %s.",
3894 http_states
[http
->state
+ 1]));
3897 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3903 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3905 * '_httpWriteCDSA()' - Write function for the CDSA library.
3908 OSStatus
/* O - -1 on error, 0 on success */
3910 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3911 const void *data
, /* I - Data buffer */
3912 size_t *dataLength
) /* IO - Number of bytes */
3914 OSStatus result
; /* Return value */
3915 ssize_t bytes
; /* Number of bytes read */
3916 http_t
*http
; /* HTTP connection */
3919 http
= (http_t
*)connection
;
3923 bytes
= write(http
->fd
, data
, *dataLength
);
3925 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3927 if (bytes
== *dataLength
)
3931 else if (bytes
>= 0)
3933 *dataLength
= bytes
;
3934 result
= errSSLWouldBlock
;
3940 if (errno
== EAGAIN
)
3941 result
= errSSLWouldBlock
;
3943 result
= errSSLClosedAbort
;
3948 #endif /* HAVE_SSL && HAVE_CDSASSL */
3951 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3953 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3956 ssize_t
/* O - Number of bytes written or -1 on error */
3958 gnutls_transport_ptr ptr
, /* I - Connection to server */
3959 const void *data
, /* I - Data buffer */
3960 size_t length
) /* I - Number of bytes to write */
3962 ssize_t bytes
; /* Bytes written */
3965 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3968 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3971 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3972 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3976 #endif /* HAVE_SSL && HAVE_GNUTLS */
3980 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3985 int /* O - 0 on success, -1 on error */
3986 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3987 http_status_t status
) /* I - Status code */
3989 http_encoding_t old_encoding
; /* Old data_encoding value */
3990 off_t old_remaining
; /* Old data_remaining value */
3994 * Range check input...
3997 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3999 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
4001 DEBUG_puts("1httpWriteResponse: Bad input.");
4006 * Set the various standard fields if they aren't already...
4009 if (!http
->fields
[HTTP_FIELD_DATE
][0])
4010 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
4012 if (status
>= HTTP_BAD_REQUEST
&& http
->keep_alive
)
4014 http
->keep_alive
= 0;
4015 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
4018 if (http
->version
== HTTP_VERSION_1_1
)
4020 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
4022 if (http
->keep_alive
)
4023 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
4025 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
4028 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
4029 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
4033 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
)
4035 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
4036 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4038 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
4039 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4041 #endif /* HAVE_SSL */
4044 httpSetField(http
, HTTP_FIELD_SERVER
, CUPS_MINIMAL
);
4048 * Set the Accept-Encoding field if it isn't already...
4051 if (!http
->accept_encoding
)
4052 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
, "gzip, deflate, identity");
4053 #endif /* HAVE_LIBZ */
4056 * Send the response header...
4059 old_encoding
= http
->data_encoding
;
4060 old_remaining
= http
->data_remaining
;
4061 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4063 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
4064 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
4066 http
->status
= HTTP_STATUS_ERROR
;
4070 if (status
!= HTTP_STATUS_CONTINUE
)
4073 * 100 Continue doesn't have the rest of the response headers...
4076 int i
; /* Looping var */
4077 const char *value
; /* Field value */
4079 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4081 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4083 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4085 http
->status
= HTTP_STATUS_ERROR
;
4093 if (httpPrintf(http
, "Set-Cookie: %s path=/%s\r\n", http
->cookie
,
4094 http
->tls
? " secure" : "") < 1)
4096 http
->status
= HTTP_ERROR
;
4102 if (httpWrite2(http
, "\r\n", 2) < 2)
4104 http
->status
= HTTP_ERROR
;
4108 if (httpFlushWrite(http
) < 0)
4110 http
->status
= HTTP_ERROR
;
4114 if (status
== HTTP_STATUS_CONTINUE
)
4117 * Restore the old data_encoding and data_length values...
4120 http
->data_encoding
= old_encoding
;
4121 http
->data_remaining
= old_remaining
;
4123 if (old_remaining
<= INT_MAX
)
4124 http
->_data_remaining
= (int)old_remaining
;
4126 http
->_data_remaining
= INT_MAX
;
4128 else if (http
->state
== HTTP_STATE_OPTIONS
||
4129 http
->state
== HTTP_STATE_HEAD
||
4130 http
->state
== HTTP_STATE_PUT
||
4131 http
->state
== HTTP_STATE_TRACE
||
4132 http
->state
== HTTP_STATE_CONNECT
)
4134 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
4135 "was %s.", http_states
[http
->state
+ 1]));
4136 http
->state
= HTTP_STATE_WAITING
;
4141 * Force data_encoding and data_length to be set according to the response
4145 http_set_length(http
);
4148 * Then start any content encoding...
4151 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
4152 http_content_coding_start(http
,
4153 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
4160 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
4162 * 'http_bio_ctrl()' - Control the HTTP connection.
4165 static long /* O - Result/data */
4166 http_bio_ctrl(BIO
*h
, /* I - BIO data */
4167 int cmd
, /* I - Control command */
4168 long arg1
, /* I - First argument */
4169 void *arg2
) /* I - Second argument */
4176 case BIO_CTRL_RESET
:
4180 case BIO_C_SET_FILE_PTR
:
4185 case BIO_C_GET_FILE_PTR
:
4188 *((void **)arg2
) = h
->ptr
;
4195 case BIO_CTRL_FLUSH
:
4202 * 'http_bio_free()' - Free OpenSSL data.
4205 static int /* O - 1 on success, 0 on failure */
4206 http_bio_free(BIO
*h
) /* I - BIO data */
4222 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
4225 static int /* O - 1 on success, 0 on failure */
4226 http_bio_new(BIO
*h
) /* I - BIO data */
4241 * 'http_bio_puts()' - Send a string for OpenSSL.
4244 static int /* O - Bytes written */
4245 http_bio_puts(BIO
*h
, /* I - BIO data */
4246 const char *str
) /* I - String to write */
4249 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
4251 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
4257 * 'http_bio_read()' - Read data for OpenSSL.
4260 static int /* O - Bytes read */
4261 http_bio_read(BIO
*h
, /* I - BIO data */
4262 char *buf
, /* I - Buffer */
4263 int size
) /* I - Number of bytes to read */
4265 http_t
*http
; /* HTTP connection */
4268 http
= (http_t
*)h
->ptr
;
4270 if (!http
->blocking
)
4273 * Make sure we have data before we read...
4276 while (!_httpWait(http
, http
->wait_value
, 0))
4278 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4282 http
->error
= WSAETIMEDOUT
;
4284 http
->error
= ETIMEDOUT
;
4291 return (recv(http
->fd
, buf
, size
, 0));
4296 * 'http_bio_write()' - Write data for OpenSSL.
4299 static int /* O - Bytes written */
4300 http_bio_write(BIO
*h
, /* I - BIO data */
4301 const char *buf
, /* I - Buffer to write */
4302 int num
) /* I - Number of bytes to write */
4304 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4306 #endif /* HAVE_SSL && HAVE_LIBSSL */
4311 * 'http_content_coding_finish()' - Finish doing any content encoding.
4315 http_content_coding_finish(
4316 http_t
*http
) /* I - HTTP connection */
4318 int zerr
; /* Compression status */
4321 switch (http
->coding
)
4323 case _HTTP_CODING_DEFLATE
:
4324 case _HTTP_CODING_GZIP
:
4327 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4328 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4330 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4332 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4333 if (http
->wused
== sizeof(http
->wbuffer
))
4334 httpFlushWrite(http
);
4336 while (zerr
== Z_OK
);
4338 deflateEnd(&(http
->stream
));
4341 httpFlushWrite(http
);
4344 case _HTTP_CODING_INFLATE
:
4345 case _HTTP_CODING_GUNZIP
:
4346 inflateEnd(&(http
->stream
));
4353 http
->coding
= _HTTP_CODING_IDENTITY
;
4358 * 'http_content_coding_start()' - Start doing content encoding.
4362 http_content_coding_start(
4363 http_t
*http
, /* I - HTTP connection */
4364 const char *value
) /* I - Value of Content-Encoding */
4366 int zerr
; /* Error/status */
4367 _http_coding_t coding
; /* Content coding value */
4370 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4373 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4375 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4379 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4381 if (http
->state
== HTTP_GET_SEND
|| http
->state
== HTTP_POST_SEND
)
4382 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4383 _HTTP_CODING_GUNZIP
;
4384 else if (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
)
4385 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4386 _HTTP_CODING_GUNZIP
;
4389 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4393 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4395 if (http
->state
== HTTP_GET_SEND
|| http
->state
== HTTP_POST_SEND
)
4396 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4397 _HTTP_CODING_INFLATE
;
4398 else if (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
)
4399 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4400 _HTTP_CODING_INFLATE
;
4403 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4409 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4413 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4417 case _HTTP_CODING_DEFLATE
:
4418 case _HTTP_CODING_GZIP
:
4420 httpFlushWrite(http
);
4422 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4424 coding
== _HTTP_CODING_DEFLATE
? 11 : 27, 7,
4425 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4427 http
->status
= HTTP_ERROR
;
4428 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4433 case _HTTP_CODING_INFLATE
:
4434 case _HTTP_CODING_GUNZIP
:
4435 if ((zerr
= inflateInit2(&(http
->stream
), 32 + 15)) < Z_OK
)
4437 http
->status
= HTTP_ERROR
;
4438 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4447 http
->coding
= coding
;
4449 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4452 #endif /* HAVE_LIBZ */
4457 * 'http_debug_hex()' - Do a hex dump of a buffer.
4461 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4462 const char *buffer
, /* I - Buffer to dump */
4463 int bytes
) /* I - Bytes to dump */
4465 int i
, j
, /* Looping vars */
4466 ch
; /* Current character */
4467 char line
[255], /* Line buffer */
4468 *start
, /* Start of line after prefix */
4469 *ptr
; /* Pointer into line */
4472 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4475 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4477 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4478 start
= line
+ strlen(line
);
4480 for (i
= 0; i
< bytes
; i
+= 16)
4482 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4483 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4487 memcpy(ptr
, " ", 3);
4492 memcpy(ptr
, " ", 3);
4495 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4497 ch
= buffer
[i
+ j
] & 255;
4499 if (ch
< ' ' || ch
>= 127)
4513 * 'http_field()' - Return the field index for a field name.
4516 static http_field_t
/* O - Field index */
4517 http_field(const char *name
) /* I - String name */
4519 int i
; /* Looping var */
4522 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4523 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
4524 return ((http_field_t
)i
);
4526 return (HTTP_FIELD_UNKNOWN
);
4532 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4535 static int /* O - Bytes read */
4536 http_read_ssl(http_t
*http
, /* I - Connection to server */
4537 char *buf
, /* I - Buffer to store data */
4538 int len
) /* I - Length of buffer */
4540 # if defined(HAVE_LIBSSL)
4541 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4543 # elif defined(HAVE_GNUTLS)
4544 ssize_t result
; /* Return value */
4547 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4549 if (result
< 0 && !errno
)
4552 * Convert GNU TLS error to errno value...
4557 case GNUTLS_E_INTERRUPTED
:
4561 case GNUTLS_E_AGAIN
:
4573 return ((int)result
);
4575 # elif defined(HAVE_CDSASSL)
4576 int result
; /* Return value */
4577 OSStatus error
; /* Error info */
4578 size_t processed
; /* Number of bytes processed */
4581 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4582 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4587 result
= (int)processed
;
4590 case errSSLWouldBlock
:
4592 result
= (int)processed
;
4600 case errSSLClosedGraceful
:
4603 result
= (int)processed
;
4614 # elif defined(HAVE_SSPISSL)
4615 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4616 # endif /* HAVE_LIBSSL */
4618 #endif /* HAVE_SSL */
4622 * 'http_send()' - Send a request with all fields and the trailing blank line.
4625 static int /* O - 0 on success, non-zero on error */
4626 http_send(http_t
*http
, /* I - Connection to server */
4627 http_state_t request
, /* I - Request code */
4628 const char *uri
) /* I - URI */
4630 int i
; /* Looping var */
4631 char buf
[1024]; /* Encoded URI buffer */
4632 const char *value
; /* Field value */
4633 static const char * const codes
[] = /* Request code strings */
4653 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4654 http
, codes
[request
], uri
));
4656 if (http
== NULL
|| uri
== NULL
)
4660 * Set the User-Agent field if it isn't already...
4663 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4664 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
4668 * Set the Accept-Encoding field if it isn't already...
4671 if (!http
->accept_encoding
)
4672 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
, "gzip, deflate, identity");
4673 #endif /* HAVE_LIBZ */
4676 * Encode the URI as needed...
4679 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4682 * See if we had an error the last time around; if so, reconnect...
4685 if (http
->fd
< 0 || http
->status
== HTTP_ERROR
||
4686 http
->status
>= HTTP_BAD_REQUEST
)
4687 if (httpReconnect(http
))
4691 * Flush any written data that is pending...
4696 if (httpFlushWrite(http
) < 0)
4697 if (httpReconnect(http
))
4702 * Send the request header...
4705 http
->state
= request
;
4706 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4708 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
4711 http
->status
= HTTP_CONTINUE
;
4714 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
4716 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4717 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4719 #endif /* HAVE_SSL */
4721 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4723 http
->status
= HTTP_ERROR
;
4727 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4728 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4730 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
], value
));
4732 if (i
== HTTP_FIELD_HOST
)
4734 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4735 httpAddrPort(http
->hostaddr
)) < 1)
4737 http
->status
= HTTP_ERROR
;
4741 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4743 http
->status
= HTTP_ERROR
;
4749 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4751 http
->status
= HTTP_ERROR
;
4755 if (http
->expect
== HTTP_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4756 (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
4757 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4759 http
->status
= HTTP_ERROR
;
4763 if (httpPrintf(http
, "\r\n") < 1)
4765 http
->status
= HTTP_ERROR
;
4769 if (httpFlushWrite(http
) < 0)
4772 http_set_length(http
);
4773 httpClearFields(http
);
4776 * The Kerberos and AuthRef authentication strings can only be used once...
4779 if (http
->field_authorization
&& http
->authstring
&&
4780 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4781 !strncmp(http
->authstring
, "AuthRef", 7)))
4783 http
->_authstring
[0] = '\0';
4785 if (http
->authstring
!= http
->_authstring
)
4786 free(http
->authstring
);
4788 http
->authstring
= http
->_authstring
;
4796 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
4798 * 'http_set_credentials()' - Set the SSL/TLS credentials.
4801 static int /* O - Status of connection */
4802 http_set_credentials(http_t
*http
) /* I - Connection to server */
4804 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
4805 OSStatus error
= 0; /* Error code */
4806 http_tls_credentials_t credentials
= NULL
;
4807 /* TLS credentials */
4810 DEBUG_printf(("7http_set_credentials(%p)", http
));
4813 * Prefer connection specific credentials...
4816 if ((credentials
= http
->tls_credentials
) == NULL
)
4817 credentials
= cg
->tls_credentials
;
4819 # if HAVE_SECPOLICYCREATESSL
4821 * Otherwise root around in the user's keychain to see if one can be found...
4826 CFDictionaryRef query
; /* Query dictionary */
4827 CFTypeRef matches
= NULL
; /* Matching credentials */
4828 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
4829 CFTypeRef keys
[] = { kSecClass
,
4832 /* Keys for dictionary */
4833 CFTypeRef values
[] = { kSecClassCertificate
,
4836 /* Values for dictionary */
4839 * Get the names associated with the server.
4842 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
4844 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
4850 * Create a query which will return all identities that can sign and match
4851 * the passed in policy.
4854 query
= CFDictionaryCreate(NULL
,
4855 (const void**)(&keys
[0]),
4856 (const void**)(&values
[0]),
4857 sizeof(keys
) / sizeof(keys
[0]),
4858 &kCFTypeDictionaryKeyCallBacks
,
4859 &kCFTypeDictionaryValueCallBacks
);
4862 error
= SecItemCopyMatching(query
, &matches
);
4863 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
4872 CFRelease(dn_array
);
4874 # endif /* HAVE_SECPOLICYCREATESSL */
4878 error
= SSLSetCertificate(http
->tls
, credentials
);
4879 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
4883 DEBUG_puts("4http_set_credentials: No credentials to set.");
4887 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
4888 #endif /* HAVE_SSL */
4892 * 'http_set_length()' - Set the data_encoding and data_remaining values.
4895 static off_t
/* O - Remainder or -1 on error */
4896 http_set_length(http_t
*http
) /* I - Connection */
4898 off_t remaining
; /* Remainder */
4901 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
4902 http_states
[http
->state
+ 1]));
4904 if ((remaining
= httpGetLength2(http
)) >= 0)
4906 if (http
->mode
== _HTTP_MODE_SERVER
&&
4907 http
->state
!= HTTP_STATE_GET_SEND
&&
4908 http
->state
!= HTTP_STATE_POST
&&
4909 http
->state
!= HTTP_STATE_POST_SEND
)
4911 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
4915 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
4918 DEBUG_puts("1http_set_length: Setting data_encoding to "
4919 "HTTP_ENCODING_CHUNKED.");
4920 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
4924 DEBUG_puts("1http_set_length: Setting data_encoding to "
4925 "HTTP_ENCODING_LENGTH.");
4926 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4929 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
4930 CUPS_LLCAST remaining
));
4931 http
->data_remaining
= remaining
;
4933 if (remaining
<= INT_MAX
)
4934 http
->_data_remaining
= remaining
;
4936 http
->_data_remaining
= INT_MAX
;
4943 * 'http_set_timeout()' - Set the socket timeout values.
4947 http_set_timeout(int fd
, /* I - File descriptor */
4948 double timeout
) /* I - Timeout in seconds */
4951 DWORD tv
= (DWORD
)(timeout
* 1000);
4952 /* Timeout in milliseconds */
4954 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&tv
, sizeof(tv
));
4955 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&tv
, sizeof(tv
));
4958 struct timeval tv
; /* Timeout in secs and usecs */
4960 tv
.tv_sec
= (int)timeout
;
4961 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
4963 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, &tv
, sizeof(tv
));
4964 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
4970 * 'http_set_wait()' - Set the default wait value for reads.
4974 http_set_wait(http_t
*http
) /* I - Connection to server */
4978 http
->wait_value
= (int)(http
->timeout_value
* 1000);
4980 if (http
->wait_value
<= 0)
4981 http
->wait_value
= 60000;
4984 http
->wait_value
= 10000;
4990 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
4993 static int /* O - 0 on success, -1 on failure */
4994 http_setup_ssl(http_t
*http
) /* I - Connection to server */
4996 _cups_globals_t
*cg
= _cupsGlobals();
4997 /* Pointer to library globals */
4998 int any_root
; /* Allow any root */
4999 char hostname
[256], /* Hostname */
5000 *hostptr
; /* Pointer into hostname */
5003 SSL_CTX
*context
; /* Context for encryption */
5004 BIO
*bio
; /* BIO data */
5005 const char *message
= NULL
;/* Error message */
5006 # elif defined(HAVE_GNUTLS)
5007 int status
; /* Status of handshake */
5008 gnutls_certificate_client_credentials
*credentials
;
5009 /* TLS credentials */
5010 # elif defined(HAVE_CDSASSL)
5011 OSStatus error
; /* Error code */
5012 const char *message
= NULL
;/* Error message */
5013 # ifdef HAVE_SECCERTIFICATECOPYDATA
5014 cups_array_t
*credentials
; /* Credentials array */
5015 cups_array_t
*names
; /* CUPS distinguished names */
5016 CFArrayRef dn_array
; /* CF distinguished names array */
5017 CFIndex count
; /* Number of credentials */
5018 CFDataRef data
; /* Certificate data */
5019 int i
; /* Looping var */
5020 http_credential_t
*credential
; /* Credential data */
5021 # endif /* HAVE_SECCERTIFICATECOPYDATA */
5022 # elif defined(HAVE_SSPISSL)
5023 TCHAR username
[256]; /* Username returned from GetUserName() */
5024 TCHAR commonName
[256];/* Common name for certificate */
5025 DWORD dwSize
; /* 32 bit size */
5026 # endif /* HAVE_LIBSSL */
5029 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5032 * Always allow self-signed certificates for the local loopback address...
5035 if (httpAddrLocalhost(http
->hostaddr
))
5038 strlcpy(hostname
, "localhost", sizeof(hostname
));
5043 * Otherwise use the system-wide setting and make sure the hostname we have
5044 * does not end in a trailing dot.
5047 any_root
= cg
->any_root
;
5049 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5050 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5058 context
= SSL_CTX_new(SSLv23_client_method());
5060 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5062 bio
= BIO_new(_httpBIOMethods());
5063 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5065 http
->tls
= SSL_new(context
);
5066 SSL_set_bio(http
->tls
, bio
, bio
);
5068 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5069 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5070 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5072 if (SSL_connect(http
->tls
) != 1)
5074 unsigned long error
; /* Error code */
5076 while ((error
= ERR_get_error()) != 0)
5078 message
= ERR_error_string(error
, NULL
);
5079 DEBUG_printf(("8http_setup_ssl: %s", message
));
5082 SSL_CTX_free(context
);
5083 SSL_free(http
->tls
);
5087 http
->error
= WSAGetLastError();
5089 http
->error
= errno
;
5091 http
->status
= HTTP_ERROR
;
5094 message
= _("Unable to establish a secure connection to host.");
5096 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5101 # elif defined(HAVE_GNUTLS)
5104 credentials
= (gnutls_certificate_client_credentials
*)
5105 malloc(sizeof(gnutls_certificate_client_credentials
));
5106 if (credentials
== NULL
)
5108 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5110 http
->error
= errno
;
5111 http
->status
= HTTP_ERROR
;
5112 _cupsSetHTTPError(HTTP_ERROR
);
5117 gnutls_certificate_allocate_credentials(credentials
);
5119 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5120 gnutls_set_default_priority(http
->tls
);
5121 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5123 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5124 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5125 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5126 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5128 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5130 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5131 status
, gnutls_strerror(status
)));
5133 if (gnutls_error_is_fatal(status
))
5136 http
->status
= HTTP_ERROR
;
5138 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
5140 gnutls_deinit(http
->tls
);
5141 gnutls_certificate_free_credentials(*credentials
);
5149 http
->tls_credentials
= credentials
;
5151 # elif defined(HAVE_CDSASSL)
5152 if ((error
= SSLNewContext(false, &http
->tls
)))
5154 http
->error
= errno
;
5155 http
->status
= HTTP_ERROR
;
5156 _cupsSetHTTPError(HTTP_ERROR
);
5161 error
= SSLSetConnection(http
->tls
, http
);
5162 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5166 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5167 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5172 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
5173 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
5174 any_root
, (int)error
));
5179 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
5180 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
5181 cg
->expired_certs
, (int)error
));
5186 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
5187 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
5188 cg
->expired_root
, (int)error
));
5192 * In general, don't verify certificates since things like the common name
5193 * often do not match...
5198 error
= SSLSetEnableCertVerify(http
->tls
, false);
5199 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
5203 # ifdef HAVE_SECCERTIFICATECOPYDATA
5206 if (cg
->client_cert_cb
)
5208 error
= SSLSetSessionOption(http
->tls
,
5209 kSSLSessionOptionBreakOnCertRequested
, true);
5210 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5211 "error=%d", (int)error
));
5215 error
= http_set_credentials(http
);
5216 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5222 * If there's a server certificate callback installed let it evaluate the
5223 * certificate(s) during the handshake...
5226 if (!error
&& cg
->server_cert_cb
!= NULL
)
5228 error
= SSLSetSessionOption(http
->tls
,
5229 kSSLSessionOptionBreakOnServerAuth
, true);
5230 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
5231 "error=%d", (int)error
));
5233 # endif /* HAVE_SECCERTIFICATECOPYDATA */
5236 * Let the server know which hostname/domain we are trying to connect to
5237 * in case it wants to serve up a certificate with a matching common name.
5242 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5244 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5250 int done
= 0; /* Are we done yet? */
5252 while (!error
&& !done
)
5254 error
= SSLHandshake(http
->tls
);
5256 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5264 case errSSLWouldBlock
:
5265 error
= noErr
; /* Force a retry */
5266 usleep(1000); /* in 1 millisecond */
5269 # ifdef HAVE_SECCERTIFICATECOPYDATA
5270 case errSSLServerAuthCompleted
:
5272 if (cg
->server_cert_cb
)
5274 error
= httpCopyCredentials(http
, &credentials
);
5277 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5278 cg
->server_cert_data
);
5279 httpFreeCredentials(credentials
);
5282 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5283 "returned %d.", (int)error
));
5287 case errSSLClientCertRequested
:
5290 if (cg
->client_cert_cb
)
5293 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5296 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5298 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5300 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5302 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5304 credential
->datalen
= CFDataGetLength(data
);
5305 if ((credential
->data
= malloc(credential
->datalen
)))
5307 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5308 credential
->datalen
);
5309 cupsArrayAdd(names
, credential
);
5317 CFRelease(dn_array
);
5322 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5323 cg
->client_cert_data
);
5325 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5326 "returned %d.", (int)error
));
5329 httpFreeCredentials(names
);
5332 # endif /* HAVE_SECCERTIFICATECOPYDATA */
5334 case errSSLUnknownRootCert
:
5335 message
= _("Unable to establish a secure connection to host "
5336 "(untrusted certificate).");
5339 case errSSLNoRootCert
:
5340 message
= _("Unable to establish a secure connection to host "
5341 "(self-signed certificate).");
5344 case errSSLCertExpired
:
5345 message
= _("Unable to establish a secure connection to host "
5346 "(expired certificate).");
5349 case errSSLCertNotYetValid
:
5350 message
= _("Unable to establish a secure connection to host "
5351 "(certificate not yet valid).");
5354 case errSSLHostNameMismatch
:
5355 message
= _("Unable to establish a secure connection to host "
5356 "(host name mismatch).");
5359 case errSSLXCertChainInvalid
:
5360 message
= _("Unable to establish a secure connection to host "
5361 "(certificate chain invalid).");
5364 case errSSLConnectionRefused
:
5365 message
= _("Unable to establish a secure connection to host "
5366 "(peer dropped connection before responding).");
5377 http
->error
= error
;
5378 http
->status
= HTTP_ERROR
;
5379 errno
= ECONNREFUSED
;
5381 SSLDisposeContext(http
->tls
);
5385 * If an error string wasn't set by the callbacks use a generic one...
5389 #ifdef HAVE_CSSMERRORSTRING
5390 message
= cssmErrorString(error
);
5392 message
= _("Unable to establish a secure connection to host.");
5393 #endif /* HAVE_CSSMERRORSTRING */
5395 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5400 # elif defined(HAVE_SSPISSL)
5401 http
->tls
= _sspiAlloc();
5405 _cupsSetHTTPError(HTTP_ERROR
);
5409 http
->tls
->sock
= http
->fd
;
5410 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5411 GetUserName(username
, &dwSize
);
5412 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5413 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5415 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5418 _sspiFree(http
->tls_credentials
);
5419 http
->tls_credentials
= NULL
;
5422 http
->status
= HTTP_ERROR
;
5424 _cupsSetError(IPP_PKI_ERROR
,
5425 _("Unable to establish a secure connection to host."), 1);
5430 _sspiSetAllowsAnyRoot(http
->tls_credentials
, any_root
);
5431 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5433 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5435 _sspiFree(http
->tls_credentials
);
5436 http
->tls_credentials
= NULL
;
5439 http
->status
= HTTP_ERROR
;
5441 _cupsSetError(IPP_PKI_ERROR
,
5442 _("Unable to establish a secure connection to host."), 1);
5446 # endif /* HAVE_CDSASSL */
5453 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5457 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
5460 SSL_CTX
*context
; /* Context for encryption */
5462 context
= SSL_get_SSL_CTX(http
->tls
);
5464 SSL_shutdown(http
->tls
);
5465 SSL_CTX_free(context
);
5466 SSL_free(http
->tls
);
5468 # elif defined(HAVE_GNUTLS)
5469 gnutls_certificate_client_credentials
*credentials
;
5470 /* TLS credentials */
5472 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5474 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5475 gnutls_deinit(http
->tls
);
5476 gnutls_certificate_free_credentials(*credentials
);
5479 # elif defined(HAVE_CDSASSL)
5480 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5483 SSLDisposeContext(http
->tls
);
5485 if (http
->tls_credentials
)
5486 CFRelease(http
->tls_credentials
);
5488 # elif defined(HAVE_SSPISSL)
5489 _sspiFree(http
->tls_credentials
);
5490 # endif /* HAVE_LIBSSL */
5493 http
->tls_credentials
= NULL
;
5495 #endif /* HAVE_SSL */
5500 * 'http_upgrade()' - Force upgrade to TLS encryption.
5503 static int /* O - Status of connection */
5504 http_upgrade(http_t
*http
) /* I - Connection to server */
5506 int ret
; /* Return value */
5507 http_t myhttp
; /* Local copy of HTTP data */
5510 DEBUG_printf(("7http_upgrade(%p)", http
));
5513 * Flush the connection to make sure any previous "Upgrade" message
5520 * Copy the HTTP data to a local variable so we can do the OPTIONS
5521 * request without interfering with the existing request data...
5524 memcpy(&myhttp
, http
, sizeof(myhttp
));
5527 * Send an OPTIONS request to the server, requiring SSL or TLS
5528 * encryption on the link...
5531 http
->field_authorization
= NULL
; /* Don't free the auth string */
5533 httpClearFields(http
);
5534 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5535 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5537 if ((ret
= httpOptions(http
, "*")) == 0)
5540 * Wait for the secure connection...
5543 while (httpUpdate(http
) == HTTP_CONTINUE
);
5547 * Restore the HTTP request data...
5550 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5551 http
->data_encoding
= myhttp
.data_encoding
;
5552 http
->data_remaining
= myhttp
.data_remaining
;
5553 http
->_data_remaining
= myhttp
._data_remaining
;
5554 http
->expect
= myhttp
.expect
;
5555 http
->field_authorization
= myhttp
.field_authorization
;
5556 http
->digest_tries
= myhttp
.digest_tries
;
5559 * See if we actually went secure...
5565 * Server does not support HTTP upgrade...
5568 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5571 closesocket(http
->fd
);
5583 #endif /* HAVE_SSL */
5587 * 'http_write()' - Write a buffer to a HTTP connection.
5590 static int /* O - Number of bytes written */
5591 http_write(http_t
*http
, /* I - Connection to server */
5592 const char *buffer
, /* I - Buffer for data */
5593 int length
) /* I - Number of bytes to write */
5595 int tbytes
, /* Total bytes sent */
5596 bytes
; /* Bytes sent */
5599 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
5606 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5608 if (http
->timeout_cb
)
5611 struct pollfd pfd
; /* Polled file descriptor */
5613 fd_set output_set
; /* Output ready for write? */
5614 struct timeval timeout
; /* Timeout value */
5615 #endif /* HAVE_POLL */
5616 int nfds
; /* Result from select()/poll() */
5622 pfd
.events
= POLLOUT
;
5624 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5625 (errno
== EINTR
|| errno
== EAGAIN
))
5631 FD_ZERO(&output_set
);
5632 FD_SET(http
->fd
, &output_set
);
5634 timeout
.tv_sec
= http
->wait_value
/ 1000;
5635 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5637 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5640 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5641 WSAGetLastError() == WSAEWOULDBLOCK
));
5643 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5645 #endif /* HAVE_POLL */
5649 http
->error
= errno
;
5652 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5655 http
->error
= WSAEWOULDBLOCK
;
5657 http
->error
= EWOULDBLOCK
;
5667 bytes
= http_write_ssl(http
, buffer
, length
);
5669 #endif /* HAVE_SSL */
5670 bytes
= send(http
->fd
, buffer
, length
, 0);
5672 DEBUG_printf(("3http_write: Write of %d bytes returned %d.", (int)length
,
5678 if (WSAGetLastError() == WSAEINTR
)
5680 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5682 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5685 http
->error
= WSAGetLastError();
5687 else if (WSAGetLastError() != http
->error
&&
5688 WSAGetLastError() != WSAECONNRESET
)
5690 http
->error
= WSAGetLastError();
5697 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5699 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5701 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5704 http
->error
= errno
;
5706 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5708 http
->error
= errno
;
5713 DEBUG_printf(("3http_write: error writing data (%s).",
5714 strerror(http
->error
)));
5725 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5728 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
5735 * 'http_write_chunk()' - Write a chunked buffer.
5738 static int /* O - Number bytes written */
5739 http_write_chunk(http_t
*http
, /* I - Connection to server */
5740 const char *buffer
, /* I - Buffer to write */
5741 int length
) /* I - Length of buffer */
5743 char header
[255]; /* Chunk header */
5744 int bytes
; /* Bytes written */
5747 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
5748 http
, buffer
, length
));
5751 * Write the chunk header, data, and trailer.
5754 sprintf(header
, "%x\r\n", length
);
5755 if (http_write(http
, header
, (int)strlen(header
)) < 0)
5757 DEBUG_puts("8http_write_chunk: http_write of length failed!");
5761 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5763 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
5767 if (http_write(http
, "\r\n", 2) < 0)
5769 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
5779 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5782 static int /* O - Bytes written */
5783 http_write_ssl(http_t
*http
, /* I - Connection to server */
5784 const char *buf
, /* I - Buffer holding data */
5785 int len
) /* I - Length of buffer */
5787 ssize_t result
; /* Return value */
5790 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5792 # if defined(HAVE_LIBSSL)
5793 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5795 # elif defined(HAVE_GNUTLS)
5796 result
= gnutls_record_send(http
->tls
, buf
, len
);
5798 if (result
< 0 && !errno
)
5801 * Convert GNU TLS error to errno value...
5806 case GNUTLS_E_INTERRUPTED
:
5810 case GNUTLS_E_AGAIN
:
5822 # elif defined(HAVE_CDSASSL)
5823 OSStatus error
; /* Error info */
5824 size_t processed
; /* Number of bytes processed */
5827 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5832 result
= (int)processed
;
5835 case errSSLWouldBlock
:
5837 result
= (int)processed
;
5845 case errSSLClosedGraceful
:
5848 result
= (int)processed
;
5856 # elif defined(HAVE_SSPISSL)
5857 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
5858 # endif /* HAVE_LIBSSL */
5860 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
5862 return ((int)result
);
5864 #endif /* HAVE_SSL */
5868 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".