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.
1001 http_content_coding_finish(http
);
1002 #endif /* HAVE_LIBZ */
1004 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
1006 http
->state
= HTTP_STATE_WAITING
;
1010 http_shutdown_ssl(http
);
1011 #endif /* HAVE_SSL */
1014 closesocket(http
->fd
);
1025 * 'httpFlushWrite()' - Flush data in write buffer.
1027 * @since CUPS 1.2/OS X 10.5@
1030 int /* O - Bytes written or -1 on error */
1031 httpFlushWrite(http_t
*http
) /* I - Connection to server */
1033 int bytes
; /* Bytes written */
1036 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
1037 http
? http
->data_encoding
: -1));
1039 if (!http
|| !http
->wused
)
1041 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
1042 "1httpFlushWrite: No connection.");
1046 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1047 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
1049 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
1053 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
1060 * '_httpFreeCredentials()' - Free internal credentials.
1064 _httpFreeCredentials(
1065 http_tls_credentials_t credentials
) /* I - Internal credentials */
1073 #elif defined(HAVE_GNUTLS)
1076 #elif defined(HAVE_CDSASSL)
1077 CFRelease(credentials
);
1079 #elif defined(HAVE_SSPISSL)
1082 #endif /* HAVE_LIBSSL */
1087 * 'httpFreeCredentials()' - Free an array of credentials.
1091 httpFreeCredentials(
1092 cups_array_t
*credentials
) /* I - Array of credentials */
1094 http_credential_t
*credential
; /* Credential */
1097 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
1099 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
1101 cupsArrayRemove(credentials
, credential
);
1102 free((void *)credential
->data
);
1106 cupsArrayDelete(credentials
);
1111 * 'httpGet()' - Send a GET request to the server.
1114 int /* O - Status of call (0 = success) */
1115 httpGet(http_t
*http
, /* I - Connection to server */
1116 const char *uri
) /* I - URI to get */
1118 return (http_send(http
, HTTP_GET
, uri
));
1123 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
1124 * the client and server.
1126 * This function uses the value of the Accepts-Encoding HTTP header and must be
1127 * called after receiving a response from the server or a request from the
1128 * client. The value returned can be use in subsequent requests (for clients)
1129 * or in the response (for servers) in order to compress the content stream.
1134 const char * /* O - Content-Coding value or
1135 @code NULL@ for the identity
1137 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
1140 if (http
&& http
->accept_encoding
)
1142 int i
; /* Looping var */
1143 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
1144 *start
, /* Start of coding value */
1145 *end
; /* End of coding value */
1146 double qvalue
; /* "qvalue" for coding */
1147 struct lconv
*loc
= localeconv(); /* Locale data */
1148 static const char * const codings
[] =
1149 { /* Supported content codings */
1156 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
1158 for (start
= temp
; *start
; start
= end
)
1161 * Find the end of the coding name...
1166 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
1172 * Grab the qvalue as needed...
1175 if (!strncmp(end
, ";q=", 3))
1176 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1179 * Skip past all attributes...
1183 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1189 while (*end
&& isspace(*end
& 255))
1193 * Check value if it matches something we support...
1199 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1200 if (!strcmp(start
, codings
[i
]))
1201 return (codings
[i
]);
1204 #endif /* HAVE_LIBZ */
1211 * 'httpGetAuthString()' - Get the current authorization string.
1213 * The authorization string is set by cupsDoAuthentication() and
1214 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
1215 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
1218 * @since CUPS 1.3/OS X 10.5@
1221 char * /* O - Authorization string */
1222 httpGetAuthString(http_t
*http
) /* I - Connection to server */
1225 return (http
->authstring
);
1232 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
1234 * @since CUPS 1.2/OS X 10.5@
1237 int /* O - 1 if blocking, 0 if non-blocking */
1238 httpGetBlocking(http_t
*http
) /* I - Connection to server */
1240 return (http
? http
->blocking
: 0);
1245 * 'httpGetCookie()' - Get any cookie data from the response.
1247 * @since CUPS 1.1.19/OS X 10.3@
1250 const char * /* O - Cookie data or NULL */
1251 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1253 return (http
? http
->cookie
: NULL
);
1258 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1260 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1261 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1266 http_status_t
/* O - Expect: status, if any */
1267 httpGetExpect(http_t
*http
) /* I - Connection to client */
1270 return (HTTP_STATUS_ERROR
);
1272 return (http
->expect
);
1277 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1279 * @since CUPS 1.2/OS X 10.5@
1282 int /* O - File descriptor or -1 if none */
1283 httpGetFd(http_t
*http
) /* I - Connection to server */
1285 return (http
? http
->fd
: -1);
1290 * 'httpGetField()' - Get a field value from a request/response.
1293 const char * /* O - Field value */
1294 httpGetField(http_t
*http
, /* I - Connection to server */
1295 http_field_t field
) /* I - Field to get */
1297 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1302 case HTTP_FIELD_ACCEPT_ENCODING
:
1303 return (http
->accept_encoding
);
1305 case HTTP_FIELD_ALLOW
:
1306 return (http
->allow
);
1308 case HTTP_FIELD_SERVER
:
1309 return (http
->server
);
1311 case HTTP_FIELD_AUTHORIZATION
:
1312 if (http
->field_authorization
)
1315 * Special case for WWW-Authenticate: as its contents can be
1316 * longer than HTTP_MAX_VALUE...
1319 return (http
->field_authorization
);
1323 return (http
->fields
[field
]);
1329 * 'httpGetLength()' - Get the amount of data remaining from the
1330 * content-length or transfer-encoding fields.
1332 * This function is deprecated and will not return lengths larger than
1333 * 2^31 - 1; use httpGetLength2() instead.
1338 int /* O - Content length */
1339 httpGetLength(http_t
*http
) /* I - Connection to server */
1342 * Get the read content length and return the 32-bit value.
1347 httpGetLength2(http
);
1349 return (http
->_data_remaining
);
1357 * 'httpGetLength2()' - Get the amount of data remaining from the
1358 * content-length or transfer-encoding fields.
1360 * This function returns the complete content length, even for
1361 * content larger than 2^31 - 1.
1363 * @since CUPS 1.2/OS X 10.5@
1366 off_t
/* O - Content length */
1367 httpGetLength2(http_t
*http
) /* I - Connection to server */
1369 off_t remaining
; /* Remaining length */
1372 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1373 http_states
[http
->state
+ 1]));
1378 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1380 DEBUG_puts("4httpGetLength2: chunked request!");
1386 * The following is a hack for HTTP servers that don't send a
1387 * Content-Length or Transfer-Encoding field...
1389 * If there is no Content-Length then the connection must close
1390 * after the transfer is complete...
1393 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1396 * Default content length is 0 for errors and certain types of operations,
1397 * and 2^31-1 for other successful requests...
1400 if (http
->status
>= HTTP_MULTIPLE_CHOICES
||
1401 http
->state
== HTTP_STATE_OPTIONS
||
1402 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1403 http
->state
== HTTP_STATE_HEAD
||
1404 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1405 http
->state
== HTTP_STATE_DELETE
||
1406 http
->state
== HTTP_STATE_TRACE
||
1407 http
->state
== HTTP_STATE_CONNECT
)
1410 remaining
= 2147483647;
1412 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1416 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1417 CUPS_LLCAST remaining
));
1425 * 'httpGets()' - Get a line of text from a HTTP connection.
1428 char * /* O - Line or NULL */
1429 httpGets(char *line
, /* I - Line to read into */
1430 int length
, /* I - Max length of buffer */
1431 http_t
*http
) /* I - Connection to server */
1433 char *lineptr
, /* Pointer into line */
1434 *lineend
, /* End of line */
1435 *bufptr
, /* Pointer into input buffer */
1436 *bufend
; /* Pointer to end of buffer */
1437 int bytes
, /* Number of bytes read */
1438 eol
; /* End-of-line? */
1441 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1443 if (http
== NULL
|| line
== NULL
)
1447 * Read a line from the buffer...
1452 lineend
= line
+ length
- 1;
1455 while (lineptr
< lineend
)
1458 * Pre-load the buffer as needed...
1467 while (http
->used
== 0)
1470 * No newline; see if there is more data to be read...
1473 while (!_httpWait(http
, http
->wait_value
, 1))
1475 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1478 DEBUG_puts("3httpGets: Timed out!");
1480 http
->error
= WSAETIMEDOUT
;
1482 http
->error
= ETIMEDOUT
;
1489 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1490 HTTP_MAX_BUFFER
- http
->used
);
1492 #endif /* HAVE_SSL */
1493 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1494 HTTP_MAX_BUFFER
- http
->used
, 0);
1496 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1499 http_debug_hex("httpGets", http
->buffer
+ http
->used
, bytes
);
1505 * Nope, can't get a line this time...
1509 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1511 if (WSAGetLastError() == WSAEINTR
)
1513 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1515 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1518 http
->error
= WSAGetLastError();
1520 else if (WSAGetLastError() != http
->error
)
1522 http
->error
= WSAGetLastError();
1527 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1531 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1533 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1535 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1538 http
->error
= errno
;
1540 else if (errno
!= http
->error
)
1542 http
->error
= errno
;
1549 else if (bytes
== 0)
1551 http
->error
= EPIPE
;
1557 * Yup, update the amount used...
1560 http
->used
+= bytes
;
1564 * Now copy as much of the current line as possible...
1567 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1568 lineptr
< lineend
&& bufptr
< bufend
;)
1570 if (*bufptr
== 0x0a)
1576 else if (*bufptr
== 0x0d)
1579 *lineptr
++ = *bufptr
++;
1582 http
->used
-= (int)(bufptr
- http
->buffer
);
1584 memmove(http
->buffer
, bufptr
, http
->used
);
1592 http
->activity
= time(NULL
);
1596 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1602 DEBUG_puts("3httpGets: No new line available!");
1609 * 'httpGetState()' - Get the current state of the HTTP request.
1612 http_state_t
/* O - HTTP state */
1613 httpGetState(http_t
*http
) /* I - Connection to server */
1615 return (http
? http
->state
: HTTP_STATE_ERROR
);
1620 * 'httpGetStatus()' - Get the status of the last HTTP request.
1622 * @since CUPS 1.2/OS X 10.5@
1625 http_status_t
/* O - HTTP status */
1626 httpGetStatus(http_t
*http
) /* I - Connection to server */
1628 return (http
? http
->status
: HTTP_ERROR
);
1633 * 'httpGetSubField()' - Get a sub-field value.
1638 char * /* O - Value or NULL */
1639 httpGetSubField(http_t
*http
, /* I - Connection to server */
1640 http_field_t field
, /* I - Field index */
1641 const char *name
, /* I - Name of sub-field */
1642 char *value
) /* O - Value string */
1644 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1649 * 'httpGetSubField2()' - Get a sub-field value.
1651 * @since CUPS 1.2/OS X 10.5@
1654 char * /* O - Value or NULL */
1655 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1656 http_field_t field
, /* I - Field index */
1657 const char *name
, /* I - Name of sub-field */
1658 char *value
, /* O - Value string */
1659 int valuelen
) /* I - Size of value buffer */
1661 const char *fptr
; /* Pointer into field */
1662 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1663 *ptr
, /* Pointer into string buffer */
1664 *end
; /* End of value buffer */
1666 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1667 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1669 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1670 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1673 end
= value
+ valuelen
- 1;
1675 for (fptr
= http
->fields
[field
]; *fptr
;)
1678 * Skip leading whitespace...
1681 while (_cups_isspace(*fptr
))
1691 * Get the sub-field name...
1695 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1696 ptr
< (temp
+ sizeof(temp
) - 1);
1701 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1704 * Skip trailing chars up to the '='...
1707 while (_cups_isspace(*fptr
))
1717 * Skip = and leading whitespace...
1722 while (_cups_isspace(*fptr
))
1728 * Read quoted string...
1731 for (ptr
= value
, fptr
++;
1732 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1737 while (*fptr
&& *fptr
!= '\"')
1746 * Read unquoted string...
1750 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1755 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1759 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1762 * See if this is the one...
1765 if (!strcmp(name
, temp
))
1767 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1774 DEBUG_puts("3httpGetSubField2: Returning NULL");
1781 * 'httpGetVersion()' - Get the HTTP version at the other end.
1784 http_version_t
/* O - Version number */
1785 httpGetVersion(http_t
*http
) /* I - Connection to server */
1787 return (http
? http
->version
: HTTP_VERSION_1_0
);
1792 * 'httpHead()' - Send a HEAD request to the server.
1795 int /* O - Status of call (0 = success) */
1796 httpHead(http_t
*http
, /* I - Connection to server */
1797 const char *uri
) /* I - URI for head */
1799 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1800 return (http_send(http
, HTTP_HEAD
, uri
));
1805 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1806 * default HTTP proxy (if any).
1810 httpInitialize(void)
1812 static int initialized
= 0; /* Have we been called before? */
1814 WSADATA winsockdata
; /* WinSock data */
1817 int i
; /* Looping var */
1818 unsigned char data
[1024]; /* Seed data */
1819 #endif /* HAVE_LIBSSL */
1825 _cupsGlobalUnlock();
1830 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1832 #elif !defined(SO_NOSIGPIPE)
1834 * Ignore SIGPIPE signals...
1838 sigset(SIGPIPE
, SIG_IGN
);
1840 # elif defined(HAVE_SIGACTION)
1841 struct sigaction action
; /* POSIX sigaction data */
1844 memset(&action
, 0, sizeof(action
));
1845 action
.sa_handler
= SIG_IGN
;
1846 sigaction(SIGPIPE
, &action
, NULL
);
1849 signal(SIGPIPE
, SIG_IGN
);
1850 # endif /* !SO_NOSIGPIPE */
1855 * Initialize GNU TLS...
1858 gnutls_global_init();
1860 #elif defined(HAVE_LIBSSL)
1862 * Initialize OpenSSL...
1865 SSL_load_error_strings();
1869 * Using the current time is a dubious random seed, but on some systems
1870 * it is the best we can do (on others, this seed isn't even used...)
1873 CUPS_SRAND(time(NULL
));
1875 for (i
= 0; i
< sizeof(data
); i
++)
1876 data
[i
] = CUPS_RAND();
1878 RAND_seed(data
, sizeof(data
));
1879 #endif /* HAVE_GNUTLS */
1882 _cupsGlobalUnlock();
1887 * 'httpOptions()' - Send an OPTIONS request to the server.
1890 int /* O - Status of call (0 = success) */
1891 httpOptions(http_t
*http
, /* I - Connection to server */
1892 const char *uri
) /* I - URI for options */
1894 return (http_send(http
, HTTP_OPTIONS
, uri
));
1899 * 'httpPeek()' - Peek at data from a HTTP connection.
1901 * This function copies available data from the given HTTP connection, reading
1902 * a buffer as needed. The data is still available for reading using
1903 * @link httpRead@ or @link httpRead2@.
1905 * For non-blocking connections the usual timeouts apply.
1910 ssize_t
/* O - Number of bytes copied */
1911 httpPeek(http_t
*http
, /* I - Connection to server */
1912 char *buffer
, /* I - Buffer for data */
1913 size_t length
) /* I - Maximum number of bytes */
1915 ssize_t bytes
; /* Bytes read */
1916 char len
[32]; /* Length string */
1919 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1920 http
, buffer
, CUPS_LLCAST length
));
1922 if (http
== NULL
|| buffer
== NULL
)
1925 http
->activity
= time(NULL
);
1931 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1932 http
->data_remaining
<= 0)
1934 DEBUG_puts("2httpPeek: Getting chunk length...");
1936 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1938 DEBUG_puts("1httpPeek: Could not get length!");
1942 http
->data_remaining
= strtoll(len
, NULL
, 16);
1943 if (http
->data_remaining
< 0)
1945 DEBUG_puts("1httpPeek: Negative chunk length!");
1950 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1951 CUPS_LLCAST http
->data_remaining
));
1953 if (http
->data_remaining
<= 0)
1956 * A zero-length chunk ends a transfer; unless we are reading POST
1960 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1961 httpGets(len
, sizeof(len
), http
);
1965 http_content_coding_finish(http
);
1966 #endif /* HAVE_LIBZ */
1968 if (http
->state
== HTTP_STATE_POST_RECV
)
1971 http
->state
= HTTP_STATE_WAITING
;
1973 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1974 http_states
[http
->state
+ 1]));
1977 * Prevent future reads for this request...
1980 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1984 else if (length
> (size_t)http
->data_remaining
)
1985 length
= (size_t)http
->data_remaining
;
1987 if (http
->used
== 0)
1990 * Buffer small reads for better performance...
1993 ssize_t buflen
; /* Length of read for buffer */
1995 if (!http
->blocking
)
1997 while (!httpWait(http
, http
->wait_value
))
1999 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2006 if (http
->data_remaining
> sizeof(http
->buffer
))
2007 buflen
= sizeof(http
->buffer
);
2009 buflen
= http
->data_remaining
;
2011 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
2017 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
2019 #endif /* HAVE_SSL */
2020 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
2025 if (WSAGetLastError() != WSAEINTR
)
2027 http
->error
= WSAGetLastError();
2030 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
2032 if (!http
->timeout_cb
||
2033 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2035 http
->error
= WSAEWOULDBLOCK
;
2040 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2042 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2044 http
->error
= errno
;
2047 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2049 http
->error
= errno
;
2053 else if (errno
!= EINTR
)
2055 http
->error
= errno
;
2063 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
2064 CUPS_LLCAST bytes
));
2066 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
2074 if (length
> (size_t)http
->used
)
2075 length
= (size_t)http
->used
;
2077 bytes
= (ssize_t
)length
;
2079 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
2082 memcpy(buffer
, http
->buffer
, length
);
2090 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2093 http
->error
= WSAGetLastError();
2095 if (errno
== EINTR
|| errno
== EAGAIN
)
2098 http
->error
= errno
;
2101 else if (bytes
== 0)
2103 http
->error
= EPIPE
;
2108 http_debug_hex("httpPeek", buffer
, (int)bytes
);
2116 * 'httpPost()' - Send a POST request to the server.
2119 int /* O - Status of call (0 = success) */
2120 httpPost(http_t
*http
, /* I - Connection to server */
2121 const char *uri
) /* I - URI for post */
2123 return (http_send(http
, HTTP_POST
, uri
));
2128 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
2133 int /* O - Number of bytes written */
2134 httpPrintf(http_t
*http
, /* I - Connection to server */
2135 const char *format
, /* I - printf-style format string */
2136 ...) /* I - Additional args as needed */
2138 int bytes
; /* Number of bytes to write */
2139 char buf
[16384]; /* Buffer for formatted string */
2140 va_list ap
; /* Variable argument pointer */
2143 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
2145 va_start(ap
, format
);
2146 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
2149 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
2151 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
2152 return (httpWrite2(http
, buf
, bytes
));
2157 DEBUG_puts("4httpPrintf: flushing existing data...");
2159 if (httpFlushWrite(http
) < 0)
2163 return (http_write(http
, buf
, bytes
));
2169 * 'httpPut()' - Send a PUT request to the server.
2172 int /* O - Status of call (0 = success) */
2173 httpPut(http_t
*http
, /* I - Connection to server */
2174 const char *uri
) /* I - URI to put */
2176 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2177 return (http_send(http
, HTTP_PUT
, uri
));
2182 * 'httpRead()' - Read data from a HTTP connection.
2184 * This function is deprecated. Use the httpRead2() function which can
2185 * read more than 2GB of data.
2190 int /* O - Number of bytes read */
2191 httpRead(http_t
*http
, /* I - Connection to server */
2192 char *buffer
, /* I - Buffer for data */
2193 int length
) /* I - Maximum number of bytes */
2195 return ((int)httpRead2(http
, buffer
, length
));
2200 * 'httpRead2()' - Read data from a HTTP connection.
2202 * @since CUPS 1.2/OS X 10.5@
2205 ssize_t
/* O - Number of bytes read */
2206 httpRead2(http_t
*http
, /* I - Connection to server */
2207 char *buffer
, /* I - Buffer for data */
2208 size_t length
) /* I - Maximum number of bytes */
2210 ssize_t bytes
; /* Bytes read */
2211 char len
[32]; /* Length string */
2214 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2215 ") coding=%d", http
, buffer
, CUPS_LLCAST length
,
2218 if (http
== NULL
|| buffer
== NULL
)
2221 http
->activity
= time(NULL
);
2227 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
2228 http
->data_remaining
<= 0)
2230 if (!httpGets(len
, sizeof(len
), http
))
2232 DEBUG_puts("1httpRead2: Could not get chunk length.");
2238 DEBUG_puts("1httpRead2: Blank chunk length, trying again...");
2239 if (!httpGets(len
, sizeof(len
), http
))
2241 DEBUG_puts("1httpRead2: Could not get chunk length.");
2246 http
->data_remaining
= strtoll(len
, NULL
, 16);
2248 if (http
->data_remaining
< 0)
2250 DEBUG_printf(("1httpRead2: Negative chunk length \"%s\" (" CUPS_LLFMT
")",
2251 len
, CUPS_LLCAST http
->data_remaining
));
2255 DEBUG_printf(("2httpRead2: Got chunk length \"%s\" (" CUPS_LLFMT
")", len
,
2256 CUPS_LLCAST http
->data_remaining
));
2259 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
", used=%d",
2260 CUPS_LLCAST http
->data_remaining
, http
->used
));
2262 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
2265 * A zero-length chunk ends a transfer; unless we are reading POST
2271 http_content_coding_finish(http
);
2272 #endif /* HAVE_LIBZ */
2274 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2275 httpGets(len
, sizeof(len
), http
);
2277 if (http
->state
== HTTP_STATE_POST_RECV
)
2280 http
->state
= HTTP_STATE_WAITING
;
2282 DEBUG_printf(("1httpRead2: 0-length chunk, set state to %s.",
2283 http_states
[http
->state
+ 1]));
2286 * Prevent future reads for this request...
2289 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2293 else if ((http
->data_encoding
== HTTP_ENCODING_LENGTH
||
2294 http
->coding
== _HTTP_CODING_IDENTITY
) &&
2295 length
> (size_t)http
->data_remaining
)
2296 length
= (size_t)http
->data_remaining
;
2299 if (http
->used
== 0 && (length
<= 256 || http
->coding
))
2301 if (http
->used
== 0 && length
<= 256)
2302 #endif /* HAVE_LIBZ */
2305 * Buffer small/compressed reads for better performance...
2308 ssize_t buflen
; /* Length of read for buffer */
2310 if (!http
->blocking
)
2312 while (!httpWait(http
, http
->wait_value
))
2314 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2321 if (http
->data_remaining
> sizeof(http
->buffer
))
2322 buflen
= sizeof(http
->buffer
);
2324 buflen
= http
->data_remaining
;
2326 DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen
));
2332 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
2334 #endif /* HAVE_SSL */
2335 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
2340 if (WSAGetLastError() != WSAEINTR
)
2342 http
->error
= WSAGetLastError();
2345 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
2347 if (!http
->timeout_cb
||
2348 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2350 http
->error
= WSAEWOULDBLOCK
;
2355 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2357 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2359 http
->error
= errno
;
2362 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2364 http
->error
= errno
;
2368 else if (errno
!= EINTR
)
2370 http
->error
= errno
;
2378 DEBUG_printf(("2httpRead2: Read " CUPS_LLFMT
" bytes into buffer.",
2379 CUPS_LLCAST bytes
));
2381 http_debug_hex("httpRead2", http
->buffer
, (int)bytes
);
2390 int zerr
; /* Decompressor error */
2391 off_t comp_avail
, /* Maximum bytes for decompression */
2392 comp_bytes
; /* Compressed bytes "used" */
2394 if (http
->used
> http
->data_remaining
)
2395 comp_avail
= http
->data_remaining
;
2397 comp_avail
= http
->used
;
2399 DEBUG_printf(("2httpRead2: length=%d, avail_in=%d", (int)length
,
2402 http
->stream
.next_in
= (Bytef
*)http
->buffer
;
2403 http
->stream
.avail_in
= comp_avail
;
2404 http
->stream
.next_out
= (Bytef
*)buffer
;
2405 http
->stream
.avail_out
= length
;
2407 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2409 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2414 bytes
= length
- http
->stream
.avail_out
;
2415 comp_bytes
= comp_avail
- http
->stream
.avail_in
;
2417 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d, "
2418 "comp_bytes=%d", http
->stream
.avail_in
,
2419 http
->stream
.avail_out
, (int)bytes
, (int)comp_bytes
));
2421 if ((http
->used
- comp_bytes
) > 0)
2423 http
->used
-= comp_bytes
;
2424 memmove(http
->buffer
, http
->stream
.next_in
, http
->used
);
2430 * Adjust remaining bytes since chunk/content lengths are compressed while
2431 * CUPS HTTP APIs return uncompressed sizes...
2434 http
->data_remaining
+= bytes
- comp_bytes
;
2437 #endif /* HAVE_LIBZ */
2440 if (length
> (size_t)http
->used
)
2441 length
= (size_t)http
->used
;
2443 bytes
= (ssize_t
)length
;
2445 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2448 memcpy(buffer
, http
->buffer
, length
);
2449 http
->used
-= (int)length
;
2452 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2457 if (!http
->blocking
)
2459 while (!httpWait(http
, http
->wait_value
))
2461 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2468 while ((bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
)) < 0)
2471 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2473 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2476 else if (WSAGetLastError() != WSAEINTR
)
2479 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2481 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2483 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2486 else if (errno
!= EINTR
)
2491 #endif /* HAVE_SSL */
2494 if (!http
->blocking
)
2496 while (!httpWait(http
, http
->wait_value
))
2498 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2505 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2506 CUPS_LLCAST length
));
2509 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2511 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2513 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2516 else if (WSAGetLastError() != WSAEINTR
)
2520 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2522 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2524 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2526 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2529 else if (errno
!= EINTR
)
2534 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2535 CUPS_LLCAST bytes
));
2537 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2543 http
->data_remaining
-= bytes
;
2545 if (http
->data_remaining
<= INT_MAX
)
2546 http
->_data_remaining
= (int)http
->data_remaining
;
2548 http
->_data_remaining
= INT_MAX
;
2553 if (WSAGetLastError() == WSAEINTR
)
2556 http
->error
= WSAGetLastError();
2558 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2561 http
->error
= errno
;
2566 http
->error
= EPIPE
;
2570 if (http
->data_remaining
<= 0)
2572 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2574 DEBUG_puts("1httpRead2: Reading trailing line for chunk.");
2575 httpGets(len
, sizeof(len
), http
);
2581 http_content_coding_finish(http
);
2582 #endif /* HAVE_LIBZ */
2584 if (http
->state
== HTTP_STATE_POST_RECV
)
2587 http
->state
= HTTP_STATE_WAITING
;
2589 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2590 http_states
[http
->state
+ 1]));
2598 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2600 * '_httpReadCDSA()' - Read function for the CDSA library.
2603 OSStatus
/* O - -1 on error, 0 on success */
2605 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2606 void *data
, /* I - Data buffer */
2607 size_t *dataLength
) /* IO - Number of bytes */
2609 OSStatus result
; /* Return value */
2610 ssize_t bytes
; /* Number of bytes read */
2611 http_t
*http
; /* HTTP connection */
2614 http
= (http_t
*)connection
;
2616 if (!http
->blocking
)
2619 * Make sure we have data before we read...
2622 while (!_httpWait(http
, http
->wait_value
, 0))
2624 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2627 http
->error
= ETIMEDOUT
;
2634 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2636 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2638 if (bytes
== *dataLength
)
2644 *dataLength
= bytes
;
2645 result
= errSSLWouldBlock
;
2652 result
= errSSLClosedGraceful
;
2653 else if (errno
== EAGAIN
)
2654 result
= errSSLWouldBlock
;
2656 result
= errSSLClosedAbort
;
2661 #endif /* HAVE_SSL && HAVE_CDSASSL */
2664 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2666 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2669 ssize_t
/* O - Number of bytes read or -1 on error */
2671 gnutls_transport_ptr ptr
, /* I - Connection to server */
2672 void *data
, /* I - Buffer */
2673 size_t length
) /* I - Number of bytes to read */
2675 http_t
*http
; /* HTTP connection */
2676 ssize_t bytes
; /* Bytes read */
2679 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2681 http
= (http_t
*)ptr
;
2683 if (!http
->blocking
)
2686 * Make sure we have data before we read...
2689 while (!_httpWait(http
, http
->wait_value
, 0))
2691 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2694 http
->error
= ETIMEDOUT
;
2699 bytes
= recv(http
->fd
, data
, length
, 0);
2700 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2703 #endif /* HAVE_SSL && HAVE_GNUTLS */
2707 * 'httpReadRequest()' - Read a HTTP request from a connection.
2712 http_state_t
/* O - New state of connection */
2713 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2714 char *uri
, /* I - URI buffer */
2715 size_t urilen
) /* I - Size of URI buffer */
2717 char line
[4096], /* HTTP request line */
2718 *req_method
, /* HTTP request method */
2719 *req_uri
, /* HTTP request URI */
2720 *req_version
; /* HTTP request version number string */
2724 * Range check input...
2727 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2728 http
, uri
, CUPS_LLCAST urilen
));
2733 if (!http
|| !uri
|| urilen
< 1)
2735 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2736 return (HTTP_STATE_ERROR
);
2738 else if (http
->state
!= HTTP_STATE_WAITING
)
2740 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2741 http_states
[http
->state
+ 1]));
2742 return (HTTP_STATE_ERROR
);
2749 httpClearFields(http
);
2751 http
->activity
= time(NULL
);
2752 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2753 http
->data_remaining
= 0;
2754 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2755 http
->status
= HTTP_STATUS_OK
;
2756 http
->version
= HTTP_VERSION_1_1
;
2759 * Read a line from the socket...
2762 if (!httpGets(line
, sizeof(line
), http
))
2764 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2765 return (HTTP_STATE_ERROR
);
2770 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2771 return (HTTP_STATE_WAITING
);
2774 DEBUG_printf(("1httpReadRequest: %s", line
));
2783 while (*req_uri
&& !isspace(*req_uri
& 255))
2788 DEBUG_puts("1httpReadRequest: No request URI.");
2789 return (HTTP_STATE_ERROR
);
2794 while (*req_uri
&& isspace(*req_uri
& 255))
2797 req_version
= req_uri
;
2799 while (*req_version
&& !isspace(*req_version
& 255))
2804 DEBUG_puts("1httpReadRequest: No request protocol version.");
2805 return (HTTP_STATE_ERROR
);
2808 *req_version
++ = '\0';
2810 while (*req_version
&& isspace(*req_version
& 255))
2817 if (!strcmp(req_method
, "OPTIONS"))
2818 http
->state
= HTTP_STATE_OPTIONS
;
2819 else if (!strcmp(req_method
, "GET"))
2820 http
->state
= HTTP_STATE_GET
;
2821 else if (!strcmp(req_method
, "HEAD"))
2822 http
->state
= HTTP_STATE_HEAD
;
2823 else if (!strcmp(req_method
, "POST"))
2824 http
->state
= HTTP_STATE_POST
;
2825 else if (!strcmp(req_method
, "PUT"))
2826 http
->state
= HTTP_STATE_PUT
;
2827 else if (!strcmp(req_method
, "DELETE"))
2828 http
->state
= HTTP_STATE_DELETE
;
2829 else if (!strcmp(req_method
, "TRACE"))
2830 http
->state
= HTTP_STATE_TRACE
;
2831 else if (!strcmp(req_method
, "CONNECT"))
2832 http
->state
= HTTP_STATE_CONNECT
;
2835 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2836 return (HTTP_STATE_UNKNOWN_METHOD
);
2839 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2840 http_states
[http
->state
+ 1]));
2842 if (!strcmp(req_version
, "HTTP/1.0"))
2844 http
->version
= HTTP_VERSION_1_0
;
2845 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2847 else if (!strcmp(req_version
, "HTTP/1.1"))
2849 http
->version
= HTTP_VERSION_1_1
;
2850 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2854 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2855 return (HTTP_STATE_UNKNOWN_VERSION
);
2858 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2859 strlcpy(uri
, req_uri
, urilen
);
2861 return (http
->state
);
2866 * 'httpReconnect()' - Reconnect to a HTTP server.
2868 * This function is deprecated. Please use the @link httpReconnect2@ function
2874 int /* O - 0 on success, non-zero on failure */
2875 httpReconnect(http_t
*http
) /* I - Connection to server */
2877 DEBUG_printf(("httpReconnect(http=%p)", http
));
2879 return (httpReconnect2(http
, 30000, NULL
));
2884 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2888 int /* O - 0 on success, non-zero on failure */
2889 httpReconnect2(http_t
*http
, /* I - Connection to server */
2890 int msec
, /* I - Timeout in milliseconds */
2891 int *cancel
) /* I - Pointer to "cancel" variable */
2893 http_addrlist_t
*addr
; /* Connected address */
2895 http_addrlist_t
*current
; /* Current address */
2896 char temp
[256]; /* Temporary address string */
2900 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2905 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
2912 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2913 http_shutdown_ssl(http
);
2915 #endif /* HAVE_SSL */
2918 * Close any previously open socket...
2923 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2926 closesocket(http
->fd
);
2935 * Reset all state (except fields, which may be reused)...
2938 http
->state
= HTTP_STATE_WAITING
;
2939 http
->status
= HTTP_STATUS_CONTINUE
;
2940 http
->version
= HTTP_VERSION_1_1
;
2941 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2942 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2943 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2944 http
->_data_remaining
= 0;
2947 http
->data_remaining
= 0;
2948 http
->hostaddr
= NULL
;
2952 * Connect to the server...
2956 for (current
= http
->addrlist
; current
; current
= current
->next
)
2957 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2958 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2959 httpAddrPort(&(current
->addr
))));
2962 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2966 * Unable to connect...
2970 http
->error
= WSAGetLastError();
2972 http
->error
= errno
;
2974 http
->status
= HTTP_ERROR
;
2976 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2977 strerror(http
->error
)));
2982 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2984 if (http
->timeout_value
> 0)
2985 http_set_timeout(http
->fd
, http
->timeout_value
);
2987 http
->hostaddr
= &(addr
->addr
);
2991 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2994 * Always do encryption via SSL.
2997 if (http_setup_ssl(http
) != 0)
3000 closesocket(http
->fd
);
3008 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
3009 return (http_upgrade(http
));
3010 #endif /* HAVE_SSL */
3012 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
3013 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
3014 httpAddrPort(http
->hostaddr
)));
3021 * 'httpSetAuthString()' - Set the current authorization string.
3023 * This function just stores a copy of the current authorization string in
3024 * the HTTP connection object. You must still call httpSetField() to set
3025 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
3026 * httpHead(), httpOptions(), httpPost, or httpPut().
3028 * @since CUPS 1.3/OS X 10.5@
3032 httpSetAuthString(http_t
*http
, /* I - Connection to server */
3033 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
3034 const char *data
) /* I - Auth data (NULL for none) */
3037 * Range check input...
3043 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
3044 free(http
->authstring
);
3046 http
->authstring
= http
->_authstring
;
3051 * Set the current authorization string...
3054 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
3057 if (len
> (int)sizeof(http
->_authstring
))
3059 if ((temp
= malloc(len
)) == NULL
)
3060 len
= sizeof(http
->_authstring
);
3062 http
->authstring
= temp
;
3066 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
3068 strlcpy(http
->authstring
, scheme
, len
);
3073 * Clear the current authorization string...
3076 http
->_authstring
[0] = '\0';
3082 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
3085 * @since CUPS 1.5/OS X 10.7@
3088 int /* O - Status of call (0 = success) */
3089 httpSetCredentials(http_t
*http
, /* I - Connection to server */
3090 cups_array_t
*credentials
) /* I - Array of credentials */
3092 if (!http
|| cupsArrayCount(credentials
) < 1)
3095 _httpFreeCredentials(http
->tls_credentials
);
3097 http
->tls_credentials
= _httpCreateCredentials(credentials
);
3099 return (http
->tls_credentials
? 0 : -1);
3104 * 'httpSetCookie()' - Set the cookie value(s).
3106 * @since CUPS 1.1.19/OS X 10.3@
3110 httpSetCookie(http_t
*http
, /* I - Connection */
3111 const char *cookie
) /* I - Cookie string */
3120 http
->cookie
= strdup(cookie
);
3122 http
->cookie
= NULL
;
3127 * 'httpSetExpect()' - Set the Expect: header in a request.
3129 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
3132 * @since CUPS 1.2/OS X 10.5@
3136 httpSetExpect(http_t
*http
, /* I - Connection to server */
3137 http_status_t expect
) /* I - HTTP status to expect
3138 (@code HTTP_CONTINUE@) */
3141 http
->expect
= expect
;
3146 * 'httpSetField()' - Set the value of an HTTP header.
3150 httpSetField(http_t
*http
, /* I - Connection to server */
3151 http_field_t field
, /* I - Field index */
3152 const char *value
) /* I - Value */
3154 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
3155 field
, http_fields
[field
], value
));
3158 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
3159 field
>= HTTP_FIELD_MAX
||
3165 case HTTP_FIELD_ACCEPT_ENCODING
:
3166 if (http
->accept_encoding
)
3167 _cupsStrFree(http
->accept_encoding
);
3169 http
->accept_encoding
= _cupsStrAlloc(value
);
3172 case HTTP_FIELD_ALLOW
:
3174 _cupsStrFree(http
->allow
);
3176 http
->allow
= _cupsStrAlloc(value
);
3179 case HTTP_FIELD_SERVER
:
3181 _cupsStrFree(http
->server
);
3183 http
->server
= _cupsStrAlloc(value
);
3187 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
3191 if (field
== HTTP_FIELD_AUTHORIZATION
)
3194 * Special case for Authorization: as its contents can be
3195 * longer than HTTP_MAX_VALUE
3198 if (http
->field_authorization
)
3199 free(http
->field_authorization
);
3201 http
->field_authorization
= strdup(value
);
3203 else if (field
== HTTP_FIELD_HOST
)
3206 * Special-case for Host: as we don't want a trailing "." on the hostname and
3207 * need to bracket IPv6 numeric addresses.
3210 char *ptr
= strchr(value
, ':');
3212 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
3215 * Bracket IPv6 numeric addresses...
3217 * This is slightly inefficient (basically copying twice), but is an edge
3218 * case and not worth optimizing...
3221 snprintf(http
->fields
[HTTP_FIELD_HOST
],
3222 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
3227 * Check for a trailing dot on the hostname...
3230 ptr
= http
->fields
[HTTP_FIELD_HOST
];
3234 ptr
+= strlen(ptr
) - 1;
3242 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
3243 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
3245 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
3246 http_content_coding_start(http
, value
);
3248 #endif /* HAVE_LIBZ */
3253 * 'httpSetLength()' - Set the content-length and content-encoding.
3255 * @since CUPS 1.2/OS X 10.5@
3259 httpSetLength(http_t
*http
, /* I - Connection to server */
3260 size_t length
) /* I - Length (0 for chunked) */
3262 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
3263 CUPS_LLCAST length
));
3270 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
3272 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
3276 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
3277 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
3278 CUPS_LLFMT
, CUPS_LLCAST length
);
3284 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
3286 * The optional timeout callback receives both the HTTP connection and a user
3287 * data pointer and must return 1 to continue or 0 to error (time) out.
3289 * @since CUPS 1.5/OS X 10.7@
3294 http_t
*http
, /* I - Connection to server */
3295 double timeout
, /* I - Number of seconds for timeout,
3296 must be greater than 0 */
3297 http_timeout_cb_t cb
, /* I - Callback function or NULL */
3298 void *user_data
) /* I - User data pointer */
3300 if (!http
|| timeout
<= 0.0)
3303 http
->timeout_cb
= cb
;
3304 http
->timeout_data
= user_data
;
3305 http
->timeout_value
= timeout
;
3308 http_set_timeout(http
->fd
, timeout
);
3310 http_set_wait(http
);
3315 * 'httpTrace()' - Send an TRACE request to the server.
3318 int /* O - Status of call (0 = success) */
3319 httpTrace(http_t
*http
, /* I - Connection to server */
3320 const char *uri
) /* I - URI for trace */
3322 return (http_send(http
, HTTP_TRACE
, uri
));
3327 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3329 * Note: Unlike httpUpdate(), this function does not flush pending write data
3330 * and only retrieves a single status line from the HTTP connection.
3333 int /* O - 1 to continue, 0 to stop */
3334 _httpUpdate(http_t
*http
, /* I - Connection to server */
3335 http_status_t
*status
) /* O - Current HTTP status */
3337 char line
[32768], /* Line from connection... */
3338 *value
; /* Pointer to value on line */
3339 http_field_t field
; /* Field index */
3340 int major
, minor
; /* HTTP version numbers */
3343 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3344 http_states
[http
->state
+ 1]));
3347 * Grab a single line from the connection...
3350 if (!httpGets(line
, sizeof(line
), http
))
3352 *status
= HTTP_ERROR
;
3356 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3358 if (line
[0] == '\0')
3361 * Blank line means the start of the data section (if any). Return
3362 * the result code, too...
3364 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3365 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3369 if (http
->status
== HTTP_STATUS_CONTINUE
)
3371 *status
= http
->status
;
3375 if (http
->status
< HTTP_BAD_REQUEST
)
3376 http
->digest_tries
= 0;
3379 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
3381 if (http_setup_ssl(http
) != 0)
3384 closesocket(http
->fd
);
3389 *status
= http
->status
= HTTP_ERROR
;
3393 *status
= HTTP_STATUS_CONTINUE
;
3396 #endif /* HAVE_SSL */
3398 if (http_set_length(http
) < 0)
3400 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3401 http
->error
= EINVAL
;
3402 http
->status
= *status
= HTTP_ERROR
;
3406 switch (http
->state
)
3408 case HTTP_STATE_GET
:
3409 case HTTP_STATE_POST
:
3410 case HTTP_STATE_POST_RECV
:
3411 case HTTP_STATE_PUT
:
3414 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3415 http_states
[http
->state
+ 1]));
3417 case HTTP_STATE_POST_SEND
:
3418 case HTTP_STATE_HEAD
:
3422 http
->state
= HTTP_STATE_WAITING
;
3424 DEBUG_puts("1_httpUpdate: Unknown state, reset state to "
3425 "HTTP_STATE_WAITING.");
3430 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3431 http_content_coding_start(http
,
3432 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3433 #endif /* HAVE_LIBZ */
3435 *status
= http
->status
;
3438 else if (!strncmp(line
, "HTTP/", 5))
3441 * Got the beginning of a response...
3444 int intstatus
; /* Status value as an integer */
3446 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3448 *status
= http
->status
= HTTP_ERROR
;
3452 httpClearFields(http
);
3454 http
->version
= (http_version_t
)(major
* 100 + minor
);
3455 *status
= http
->status
= (http_status_t
)intstatus
;
3457 else if ((value
= strchr(line
, ':')) != NULL
)
3464 while (_cups_isspace(*value
))
3467 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3470 * Be tolerants of servers that send unknown attribute fields...
3473 if (!_cups_strcasecmp(line
, "expect"))
3476 * "Expect: 100-continue" or similar...
3479 http
->expect
= (http_status_t
)atoi(value
);
3481 else if (!_cups_strcasecmp(line
, "cookie"))
3484 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3487 httpSetCookie(http
, value
);
3489 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
3490 httpSetField(http
, field
, value
);
3493 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3498 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3499 http
->error
= EINVAL
;
3500 http
->status
= *status
= HTTP_ERROR
;
3509 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3512 http_status_t
/* O - HTTP status */
3513 httpUpdate(http_t
*http
) /* I - Connection to server */
3515 http_status_t status
; /* Request status */
3518 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3519 http_states
[http
->state
+ 1]));
3522 * Flush pending data, if any...
3527 DEBUG_puts("2httpUpdate: flushing buffer...");
3529 if (httpFlushWrite(http
) < 0)
3530 return (HTTP_ERROR
);
3534 * If we haven't issued any commands, then there is nothing to "update"...
3537 if (http
->state
== HTTP_STATE_WAITING
)
3538 return (HTTP_CONTINUE
);
3541 * Grab all of the lines we can from the connection...
3544 while (_httpUpdate(http
, &status
));
3547 * See if there was an error...
3550 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
3552 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3553 return (http
->status
);
3558 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3559 strerror(http
->error
)));
3560 http
->status
= HTTP_ERROR
;
3561 return (HTTP_ERROR
);
3565 * Return the current status...
3573 * '_httpWait()' - Wait for data available on a connection (no flush).
3576 int /* O - 1 if data is available, 0 otherwise */
3577 _httpWait(http_t
*http
, /* I - Connection to server */
3578 int msec
, /* I - Milliseconds to wait */
3579 int usessl
) /* I - Use SSL context? */
3582 struct pollfd pfd
; /* Polled file descriptor */
3584 fd_set input_set
; /* select() input set */
3585 struct timeval timeout
; /* Timeout */
3586 #endif /* HAVE_POLL */
3587 int nfds
; /* Result from select()/poll() */
3590 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3594 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3599 * Check the SSL/TLS buffers for data first...
3603 if (http
->tls
&& usessl
)
3606 if (SSL_pending(http
->tls
))
3608 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3612 # elif defined(HAVE_GNUTLS)
3613 if (gnutls_record_check_pending(http
->tls
))
3615 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3619 # elif defined(HAVE_CDSASSL)
3620 size_t bytes
; /* Bytes that are available */
3622 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3625 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3628 # endif /* HAVE_LIBSSL */
3630 #endif /* HAVE_SSL */
3633 * Then try doing a select() or poll() to poll the socket...
3638 pfd
.events
= POLLIN
;
3642 nfds
= poll(&pfd
, 1, msec
);
3644 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3649 FD_ZERO(&input_set
);
3650 FD_SET(http
->fd
, &input_set
);
3652 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3656 timeout
.tv_sec
= msec
/ 1000;
3657 timeout
.tv_usec
= (msec
% 1000) * 1000;
3659 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3662 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3664 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3667 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3668 WSAGetLastError() == WSAEWOULDBLOCK
));
3670 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3672 #endif /* HAVE_POLL */
3674 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3682 * 'httpWait()' - Wait for data available on a connection.
3684 * @since CUPS 1.1.19/OS X 10.3@
3687 int /* O - 1 if data is available, 0 otherwise */
3688 httpWait(http_t
*http
, /* I - Connection to server */
3689 int msec
) /* I - Milliseconds to wait */
3692 * First see if there is data in the buffer...
3695 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3702 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3707 * Flush pending data, if any...
3712 DEBUG_puts("3httpWait: Flushing write buffer.");
3714 if (httpFlushWrite(http
) < 0)
3719 * If not, check the SSL/TLS buffers and do a select() on the connection...
3722 return (_httpWait(http
, msec
, 1));
3727 * 'httpWrite()' - Write data to a HTTP connection.
3729 * This function is deprecated. Use the httpWrite2() function which can
3730 * write more than 2GB of data.
3735 int /* O - Number of bytes written */
3736 httpWrite(http_t
*http
, /* I - Connection to server */
3737 const char *buffer
, /* I - Buffer for data */
3738 int length
) /* I - Number of bytes to write */
3740 return ((int)httpWrite2(http
, buffer
, length
));
3745 * 'httpWrite2()' - Write data to a HTTP connection.
3747 * @since CUPS 1.2/OS X 10.5@
3750 ssize_t
/* O - Number of bytes written */
3751 httpWrite2(http_t
*http
, /* I - Connection to server */
3752 const char *buffer
, /* I - Buffer for data */
3753 size_t length
) /* I - Number of bytes to write */
3755 ssize_t bytes
; /* Bytes written */
3758 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3759 buffer
, CUPS_LLCAST length
));
3762 * Range check input...
3765 if (!http
|| !buffer
)
3767 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3772 * Mark activity on the connection...
3775 http
->activity
= time(NULL
);
3778 * Buffer small writes for better performance...
3784 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3788 http_content_coding_finish(http
);
3793 http
->stream
.next_in
= (Bytef
*)buffer
;
3794 http
->stream
.avail_in
= length
;
3795 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3796 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3798 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3800 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3802 if (http
->stream
.avail_out
== 0)
3804 if (httpFlushWrite(http
) < 0)
3806 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3810 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3811 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3815 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3820 #endif /* HAVE_LIBZ */
3823 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3825 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3826 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3828 httpFlushWrite(http
);
3831 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3832 length
< sizeof(http
->wbuffer
))
3835 * Write to buffer...
3838 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3839 CUPS_LLCAST length
));
3841 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3842 http
->wused
+= (int)length
;
3843 bytes
= (ssize_t
)length
;
3848 * Otherwise write the data directly...
3851 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3852 CUPS_LLCAST length
));
3854 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3855 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3857 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3859 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3860 CUPS_LLCAST bytes
));
3863 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3864 http
->data_remaining
-= bytes
;
3870 * Handle end-of-request processing...
3873 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3874 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3877 * Finished with the transfer; unless we are sending POST or PUT
3883 if (httpFlushWrite(http
) < 0)
3887 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3890 * Send a 0-length chunk at the end of the request...
3893 http_write(http
, "0\r\n\r\n", 5);
3896 * Reset the data state...
3899 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3900 http
->data_remaining
= 0;
3903 if (http
->state
== HTTP_STATE_POST_RECV
)
3907 http_content_coding_finish(http
);
3908 #endif /* HAVE_LIBZ */
3912 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3913 http_states
[http
->state
+ 1]));
3917 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3923 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3925 * '_httpWriteCDSA()' - Write function for the CDSA library.
3928 OSStatus
/* O - -1 on error, 0 on success */
3930 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3931 const void *data
, /* I - Data buffer */
3932 size_t *dataLength
) /* IO - Number of bytes */
3934 OSStatus result
; /* Return value */
3935 ssize_t bytes
; /* Number of bytes read */
3936 http_t
*http
; /* HTTP connection */
3939 http
= (http_t
*)connection
;
3943 bytes
= write(http
->fd
, data
, *dataLength
);
3945 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3947 if (bytes
== *dataLength
)
3951 else if (bytes
>= 0)
3953 *dataLength
= bytes
;
3954 result
= errSSLWouldBlock
;
3960 if (errno
== EAGAIN
)
3961 result
= errSSLWouldBlock
;
3963 result
= errSSLClosedAbort
;
3968 #endif /* HAVE_SSL && HAVE_CDSASSL */
3971 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3973 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3976 ssize_t
/* O - Number of bytes written or -1 on error */
3978 gnutls_transport_ptr ptr
, /* I - Connection to server */
3979 const void *data
, /* I - Data buffer */
3980 size_t length
) /* I - Number of bytes to write */
3982 ssize_t bytes
; /* Bytes written */
3985 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3988 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3991 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3992 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3996 #endif /* HAVE_SSL && HAVE_GNUTLS */
4000 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
4005 int /* O - 0 on success, -1 on error */
4006 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
4007 http_status_t status
) /* I - Status code */
4009 http_encoding_t old_encoding
; /* Old data_encoding value */
4010 off_t old_remaining
; /* Old data_remaining value */
4014 * Range check input...
4017 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
4019 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
4021 DEBUG_puts("1httpWriteResponse: Bad input.");
4026 * Set the various standard fields if they aren't already...
4029 if (!http
->fields
[HTTP_FIELD_DATE
][0])
4030 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
4032 if (status
>= HTTP_BAD_REQUEST
&& http
->keep_alive
)
4034 http
->keep_alive
= 0;
4035 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
4038 if (http
->version
== HTTP_VERSION_1_1
)
4040 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
4042 if (http
->keep_alive
)
4043 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
4045 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
4048 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
4049 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
4053 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
)
4055 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
4056 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4058 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
4059 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4061 #endif /* HAVE_SSL */
4064 httpSetField(http
, HTTP_FIELD_SERVER
, CUPS_MINIMAL
);
4068 * Set the Accept-Encoding field if it isn't already...
4071 if (!http
->accept_encoding
)
4072 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
, "gzip, deflate, identity");
4073 #endif /* HAVE_LIBZ */
4076 * Send the response header...
4079 old_encoding
= http
->data_encoding
;
4080 old_remaining
= http
->data_remaining
;
4081 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4083 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
4084 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
4086 http
->status
= HTTP_STATUS_ERROR
;
4090 if (status
!= HTTP_STATUS_CONTINUE
)
4093 * 100 Continue doesn't have the rest of the response headers...
4096 int i
; /* Looping var */
4097 const char *value
; /* Field value */
4099 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4101 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4103 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4105 http
->status
= HTTP_STATUS_ERROR
;
4113 if (httpPrintf(http
, "Set-Cookie: %s path=/%s\r\n", http
->cookie
,
4114 http
->tls
? " secure" : "") < 1)
4116 http
->status
= HTTP_ERROR
;
4122 if (httpWrite2(http
, "\r\n", 2) < 2)
4124 http
->status
= HTTP_ERROR
;
4128 if (httpFlushWrite(http
) < 0)
4130 http
->status
= HTTP_ERROR
;
4134 if (status
== HTTP_STATUS_CONTINUE
)
4137 * Restore the old data_encoding and data_length values...
4140 http
->data_encoding
= old_encoding
;
4141 http
->data_remaining
= old_remaining
;
4143 if (old_remaining
<= INT_MAX
)
4144 http
->_data_remaining
= (int)old_remaining
;
4146 http
->_data_remaining
= INT_MAX
;
4148 else if (http
->state
== HTTP_STATE_OPTIONS
||
4149 http
->state
== HTTP_STATE_HEAD
||
4150 http
->state
== HTTP_STATE_PUT
||
4151 http
->state
== HTTP_STATE_TRACE
||
4152 http
->state
== HTTP_STATE_CONNECT
)
4154 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
4155 "was %s.", http_states
[http
->state
+ 1]));
4156 http
->state
= HTTP_STATE_WAITING
;
4161 * Force data_encoding and data_length to be set according to the response
4165 http_set_length(http
);
4168 * Then start any content encoding...
4171 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
4172 http_content_coding_start(http
,
4173 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
4180 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
4182 * 'http_bio_ctrl()' - Control the HTTP connection.
4185 static long /* O - Result/data */
4186 http_bio_ctrl(BIO
*h
, /* I - BIO data */
4187 int cmd
, /* I - Control command */
4188 long arg1
, /* I - First argument */
4189 void *arg2
) /* I - Second argument */
4196 case BIO_CTRL_RESET
:
4200 case BIO_C_SET_FILE_PTR
:
4205 case BIO_C_GET_FILE_PTR
:
4208 *((void **)arg2
) = h
->ptr
;
4215 case BIO_CTRL_FLUSH
:
4222 * 'http_bio_free()' - Free OpenSSL data.
4225 static int /* O - 1 on success, 0 on failure */
4226 http_bio_free(BIO
*h
) /* I - BIO data */
4242 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
4245 static int /* O - 1 on success, 0 on failure */
4246 http_bio_new(BIO
*h
) /* I - BIO data */
4261 * 'http_bio_puts()' - Send a string for OpenSSL.
4264 static int /* O - Bytes written */
4265 http_bio_puts(BIO
*h
, /* I - BIO data */
4266 const char *str
) /* I - String to write */
4269 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
4271 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
4277 * 'http_bio_read()' - Read data for OpenSSL.
4280 static int /* O - Bytes read */
4281 http_bio_read(BIO
*h
, /* I - BIO data */
4282 char *buf
, /* I - Buffer */
4283 int size
) /* I - Number of bytes to read */
4285 http_t
*http
; /* HTTP connection */
4288 http
= (http_t
*)h
->ptr
;
4290 if (!http
->blocking
)
4293 * Make sure we have data before we read...
4296 while (!_httpWait(http
, http
->wait_value
, 0))
4298 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4302 http
->error
= WSAETIMEDOUT
;
4304 http
->error
= ETIMEDOUT
;
4311 return (recv(http
->fd
, buf
, size
, 0));
4316 * 'http_bio_write()' - Write data for OpenSSL.
4319 static int /* O - Bytes written */
4320 http_bio_write(BIO
*h
, /* I - BIO data */
4321 const char *buf
, /* I - Buffer to write */
4322 int num
) /* I - Number of bytes to write */
4324 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4326 #endif /* HAVE_SSL && HAVE_LIBSSL */
4331 * 'http_content_coding_finish()' - Finish doing any content encoding.
4335 http_content_coding_finish(
4336 http_t
*http
) /* I - HTTP connection */
4338 int zerr
; /* Compression status */
4341 switch (http
->coding
)
4343 case _HTTP_CODING_DEFLATE
:
4344 case _HTTP_CODING_GZIP
:
4347 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4348 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4350 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4352 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4353 if (http
->wused
== sizeof(http
->wbuffer
))
4354 httpFlushWrite(http
);
4356 while (zerr
== Z_OK
);
4358 deflateEnd(&(http
->stream
));
4361 httpFlushWrite(http
);
4364 case _HTTP_CODING_INFLATE
:
4365 case _HTTP_CODING_GUNZIP
:
4366 inflateEnd(&(http
->stream
));
4373 http
->coding
= _HTTP_CODING_IDENTITY
;
4378 * 'http_content_coding_start()' - Start doing content encoding.
4382 http_content_coding_start(
4383 http_t
*http
, /* I - HTTP connection */
4384 const char *value
) /* I - Value of Content-Encoding */
4386 int zerr
; /* Error/status */
4387 _http_coding_t coding
; /* Content coding value */
4390 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4393 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4395 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4399 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4401 if (http
->state
== HTTP_GET_SEND
|| http
->state
== HTTP_POST_SEND
)
4402 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4403 _HTTP_CODING_GUNZIP
;
4404 else if (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
)
4405 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4406 _HTTP_CODING_GUNZIP
;
4409 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4413 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4415 if (http
->state
== HTTP_GET_SEND
|| http
->state
== HTTP_POST_SEND
)
4416 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4417 _HTTP_CODING_INFLATE
;
4418 else if (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
)
4419 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4420 _HTTP_CODING_INFLATE
;
4423 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4429 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4433 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4437 case _HTTP_CODING_DEFLATE
:
4438 case _HTTP_CODING_GZIP
:
4440 httpFlushWrite(http
);
4442 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4444 coding
== _HTTP_CODING_DEFLATE
? 11 : 27, 7,
4445 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4447 http
->status
= HTTP_ERROR
;
4448 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4453 case _HTTP_CODING_INFLATE
:
4454 case _HTTP_CODING_GUNZIP
:
4455 if ((zerr
= inflateInit2(&(http
->stream
), 32 + 15)) < Z_OK
)
4457 http
->status
= HTTP_ERROR
;
4458 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4467 http
->coding
= coding
;
4469 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4472 #endif /* HAVE_LIBZ */
4477 * 'http_debug_hex()' - Do a hex dump of a buffer.
4481 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4482 const char *buffer
, /* I - Buffer to dump */
4483 int bytes
) /* I - Bytes to dump */
4485 int i
, j
, /* Looping vars */
4486 ch
; /* Current character */
4487 char line
[255], /* Line buffer */
4488 *start
, /* Start of line after prefix */
4489 *ptr
; /* Pointer into line */
4492 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4495 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4497 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4498 start
= line
+ strlen(line
);
4500 for (i
= 0; i
< bytes
; i
+= 16)
4502 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4503 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4507 memcpy(ptr
, " ", 3);
4512 memcpy(ptr
, " ", 3);
4515 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4517 ch
= buffer
[i
+ j
] & 255;
4519 if (ch
< ' ' || ch
>= 127)
4533 * 'http_field()' - Return the field index for a field name.
4536 static http_field_t
/* O - Field index */
4537 http_field(const char *name
) /* I - String name */
4539 int i
; /* Looping var */
4542 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4543 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
4544 return ((http_field_t
)i
);
4546 return (HTTP_FIELD_UNKNOWN
);
4552 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4555 static int /* O - Bytes read */
4556 http_read_ssl(http_t
*http
, /* I - Connection to server */
4557 char *buf
, /* I - Buffer to store data */
4558 int len
) /* I - Length of buffer */
4560 # if defined(HAVE_LIBSSL)
4561 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4563 # elif defined(HAVE_GNUTLS)
4564 ssize_t result
; /* Return value */
4567 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4569 if (result
< 0 && !errno
)
4572 * Convert GNU TLS error to errno value...
4577 case GNUTLS_E_INTERRUPTED
:
4581 case GNUTLS_E_AGAIN
:
4593 return ((int)result
);
4595 # elif defined(HAVE_CDSASSL)
4596 int result
; /* Return value */
4597 OSStatus error
; /* Error info */
4598 size_t processed
; /* Number of bytes processed */
4601 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4602 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4607 result
= (int)processed
;
4610 case errSSLWouldBlock
:
4612 result
= (int)processed
;
4620 case errSSLClosedGraceful
:
4623 result
= (int)processed
;
4634 # elif defined(HAVE_SSPISSL)
4635 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4636 # endif /* HAVE_LIBSSL */
4638 #endif /* HAVE_SSL */
4642 * 'http_send()' - Send a request with all fields and the trailing blank line.
4645 static int /* O - 0 on success, non-zero on error */
4646 http_send(http_t
*http
, /* I - Connection to server */
4647 http_state_t request
, /* I - Request code */
4648 const char *uri
) /* I - URI */
4650 int i
; /* Looping var */
4651 char buf
[1024]; /* Encoded URI buffer */
4652 const char *value
; /* Field value */
4653 static const char * const codes
[] = /* Request code strings */
4673 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4674 http
, codes
[request
], uri
));
4676 if (http
== NULL
|| uri
== NULL
)
4680 * Set the User-Agent field if it isn't already...
4683 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4684 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
4688 * Set the Accept-Encoding field if it isn't already...
4691 if (!http
->accept_encoding
)
4692 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
, "gzip, deflate, identity");
4693 #endif /* HAVE_LIBZ */
4696 * Encode the URI as needed...
4699 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4702 * See if we had an error the last time around; if so, reconnect...
4705 if (http
->fd
< 0 || http
->status
== HTTP_ERROR
||
4706 http
->status
>= HTTP_BAD_REQUEST
)
4707 if (httpReconnect(http
))
4711 * Flush any written data that is pending...
4716 if (httpFlushWrite(http
) < 0)
4717 if (httpReconnect(http
))
4722 * Send the request header...
4725 http
->state
= request
;
4726 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4728 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
4731 http
->status
= HTTP_CONTINUE
;
4734 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
4736 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4737 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4739 #endif /* HAVE_SSL */
4741 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4743 http
->status
= HTTP_ERROR
;
4747 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4748 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4750 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
], value
));
4752 if (i
== HTTP_FIELD_HOST
)
4754 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4755 httpAddrPort(http
->hostaddr
)) < 1)
4757 http
->status
= HTTP_ERROR
;
4761 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4763 http
->status
= HTTP_ERROR
;
4769 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4771 http
->status
= HTTP_ERROR
;
4775 if (http
->expect
== HTTP_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4776 (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
4777 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4779 http
->status
= HTTP_ERROR
;
4783 if (httpPrintf(http
, "\r\n") < 1)
4785 http
->status
= HTTP_ERROR
;
4789 if (httpFlushWrite(http
) < 0)
4792 http_set_length(http
);
4793 httpClearFields(http
);
4796 * The Kerberos and AuthRef authentication strings can only be used once...
4799 if (http
->field_authorization
&& http
->authstring
&&
4800 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4801 !strncmp(http
->authstring
, "AuthRef", 7)))
4803 http
->_authstring
[0] = '\0';
4805 if (http
->authstring
!= http
->_authstring
)
4806 free(http
->authstring
);
4808 http
->authstring
= http
->_authstring
;
4816 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
4818 * 'http_set_credentials()' - Set the SSL/TLS credentials.
4821 static int /* O - Status of connection */
4822 http_set_credentials(http_t
*http
) /* I - Connection to server */
4824 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
4825 OSStatus error
= 0; /* Error code */
4826 http_tls_credentials_t credentials
= NULL
;
4827 /* TLS credentials */
4830 DEBUG_printf(("7http_set_credentials(%p)", http
));
4833 * Prefer connection specific credentials...
4836 if ((credentials
= http
->tls_credentials
) == NULL
)
4837 credentials
= cg
->tls_credentials
;
4839 # if HAVE_SECPOLICYCREATESSL
4841 * Otherwise root around in the user's keychain to see if one can be found...
4846 CFDictionaryRef query
; /* Query dictionary */
4847 CFTypeRef matches
= NULL
; /* Matching credentials */
4848 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
4849 CFTypeRef keys
[] = { kSecClass
,
4852 /* Keys for dictionary */
4853 CFTypeRef values
[] = { kSecClassCertificate
,
4856 /* Values for dictionary */
4859 * Get the names associated with the server.
4862 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
4864 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
4870 * Create a query which will return all identities that can sign and match
4871 * the passed in policy.
4874 query
= CFDictionaryCreate(NULL
,
4875 (const void**)(&keys
[0]),
4876 (const void**)(&values
[0]),
4877 sizeof(keys
) / sizeof(keys
[0]),
4878 &kCFTypeDictionaryKeyCallBacks
,
4879 &kCFTypeDictionaryValueCallBacks
);
4882 error
= SecItemCopyMatching(query
, &matches
);
4883 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
4892 CFRelease(dn_array
);
4894 # endif /* HAVE_SECPOLICYCREATESSL */
4898 error
= SSLSetCertificate(http
->tls
, credentials
);
4899 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
4903 DEBUG_puts("4http_set_credentials: No credentials to set.");
4907 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
4908 #endif /* HAVE_SSL */
4912 * 'http_set_length()' - Set the data_encoding and data_remaining values.
4915 static off_t
/* O - Remainder or -1 on error */
4916 http_set_length(http_t
*http
) /* I - Connection */
4918 off_t remaining
; /* Remainder */
4921 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
4922 http_states
[http
->state
+ 1]));
4924 if ((remaining
= httpGetLength2(http
)) >= 0)
4926 if (http
->mode
== _HTTP_MODE_SERVER
&&
4927 http
->state
!= HTTP_STATE_GET_SEND
&&
4928 http
->state
!= HTTP_STATE_PUT
&&
4929 http
->state
!= HTTP_STATE_POST
&&
4930 http
->state
!= HTTP_STATE_POST_SEND
)
4932 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
4936 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
4939 DEBUG_puts("1http_set_length: Setting data_encoding to "
4940 "HTTP_ENCODING_CHUNKED.");
4941 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
4945 DEBUG_puts("1http_set_length: Setting data_encoding to "
4946 "HTTP_ENCODING_LENGTH.");
4947 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4950 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
4951 CUPS_LLCAST remaining
));
4952 http
->data_remaining
= remaining
;
4954 if (remaining
<= INT_MAX
)
4955 http
->_data_remaining
= remaining
;
4957 http
->_data_remaining
= INT_MAX
;
4964 * 'http_set_timeout()' - Set the socket timeout values.
4968 http_set_timeout(int fd
, /* I - File descriptor */
4969 double timeout
) /* I - Timeout in seconds */
4972 DWORD tv
= (DWORD
)(timeout
* 1000);
4973 /* Timeout in milliseconds */
4975 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&tv
, sizeof(tv
));
4976 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&tv
, sizeof(tv
));
4979 struct timeval tv
; /* Timeout in secs and usecs */
4981 tv
.tv_sec
= (int)timeout
;
4982 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
4984 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, &tv
, sizeof(tv
));
4985 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
4991 * 'http_set_wait()' - Set the default wait value for reads.
4995 http_set_wait(http_t
*http
) /* I - Connection to server */
4999 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5001 if (http
->wait_value
<= 0)
5002 http
->wait_value
= 60000;
5005 http
->wait_value
= 10000;
5011 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5014 static int /* O - 0 on success, -1 on failure */
5015 http_setup_ssl(http_t
*http
) /* I - Connection to server */
5017 _cups_globals_t
*cg
= _cupsGlobals();
5018 /* Pointer to library globals */
5019 int any_root
; /* Allow any root */
5020 char hostname
[256], /* Hostname */
5021 *hostptr
; /* Pointer into hostname */
5024 SSL_CTX
*context
; /* Context for encryption */
5025 BIO
*bio
; /* BIO data */
5026 const char *message
= NULL
;/* Error message */
5027 # elif defined(HAVE_GNUTLS)
5028 int status
; /* Status of handshake */
5029 gnutls_certificate_client_credentials
*credentials
;
5030 /* TLS credentials */
5031 # elif defined(HAVE_CDSASSL)
5032 OSStatus error
; /* Error code */
5033 const char *message
= NULL
;/* Error message */
5034 # ifdef HAVE_SECCERTIFICATECOPYDATA
5035 cups_array_t
*credentials
; /* Credentials array */
5036 cups_array_t
*names
; /* CUPS distinguished names */
5037 CFArrayRef dn_array
; /* CF distinguished names array */
5038 CFIndex count
; /* Number of credentials */
5039 CFDataRef data
; /* Certificate data */
5040 int i
; /* Looping var */
5041 http_credential_t
*credential
; /* Credential data */
5042 # endif /* HAVE_SECCERTIFICATECOPYDATA */
5043 # elif defined(HAVE_SSPISSL)
5044 TCHAR username
[256]; /* Username returned from GetUserName() */
5045 TCHAR commonName
[256];/* Common name for certificate */
5046 DWORD dwSize
; /* 32 bit size */
5047 # endif /* HAVE_LIBSSL */
5050 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5053 * Always allow self-signed certificates for the local loopback address...
5056 if (httpAddrLocalhost(http
->hostaddr
))
5059 strlcpy(hostname
, "localhost", sizeof(hostname
));
5064 * Otherwise use the system-wide setting and make sure the hostname we have
5065 * does not end in a trailing dot.
5068 any_root
= cg
->any_root
;
5070 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5071 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5079 context
= SSL_CTX_new(SSLv23_client_method());
5081 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5083 bio
= BIO_new(_httpBIOMethods());
5084 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5086 http
->tls
= SSL_new(context
);
5087 SSL_set_bio(http
->tls
, bio
, bio
);
5089 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5090 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5091 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5093 if (SSL_connect(http
->tls
) != 1)
5095 unsigned long error
; /* Error code */
5097 while ((error
= ERR_get_error()) != 0)
5099 message
= ERR_error_string(error
, NULL
);
5100 DEBUG_printf(("8http_setup_ssl: %s", message
));
5103 SSL_CTX_free(context
);
5104 SSL_free(http
->tls
);
5108 http
->error
= WSAGetLastError();
5110 http
->error
= errno
;
5112 http
->status
= HTTP_ERROR
;
5115 message
= _("Unable to establish a secure connection to host.");
5117 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5122 # elif defined(HAVE_GNUTLS)
5125 credentials
= (gnutls_certificate_client_credentials
*)
5126 malloc(sizeof(gnutls_certificate_client_credentials
));
5127 if (credentials
== NULL
)
5129 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5131 http
->error
= errno
;
5132 http
->status
= HTTP_ERROR
;
5133 _cupsSetHTTPError(HTTP_ERROR
);
5138 gnutls_certificate_allocate_credentials(credentials
);
5140 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5141 gnutls_set_default_priority(http
->tls
);
5142 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5144 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5145 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5146 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5147 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5149 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5151 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5152 status
, gnutls_strerror(status
)));
5154 if (gnutls_error_is_fatal(status
))
5157 http
->status
= HTTP_ERROR
;
5159 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
5161 gnutls_deinit(http
->tls
);
5162 gnutls_certificate_free_credentials(*credentials
);
5170 http
->tls_credentials
= credentials
;
5172 # elif defined(HAVE_CDSASSL)
5173 if ((error
= SSLNewContext(false, &http
->tls
)))
5175 http
->error
= errno
;
5176 http
->status
= HTTP_ERROR
;
5177 _cupsSetHTTPError(HTTP_ERROR
);
5182 error
= SSLSetConnection(http
->tls
, http
);
5183 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5187 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5188 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5193 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
5194 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
5195 any_root
, (int)error
));
5200 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
5201 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
5202 cg
->expired_certs
, (int)error
));
5207 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
5208 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
5209 cg
->expired_root
, (int)error
));
5213 * In general, don't verify certificates since things like the common name
5214 * often do not match...
5219 error
= SSLSetEnableCertVerify(http
->tls
, false);
5220 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
5224 # ifdef HAVE_SECCERTIFICATECOPYDATA
5227 if (cg
->client_cert_cb
)
5229 error
= SSLSetSessionOption(http
->tls
,
5230 kSSLSessionOptionBreakOnCertRequested
, true);
5231 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5232 "error=%d", (int)error
));
5236 error
= http_set_credentials(http
);
5237 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5243 * If there's a server certificate callback installed let it evaluate the
5244 * certificate(s) during the handshake...
5247 if (!error
&& cg
->server_cert_cb
!= NULL
)
5249 error
= SSLSetSessionOption(http
->tls
,
5250 kSSLSessionOptionBreakOnServerAuth
, true);
5251 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
5252 "error=%d", (int)error
));
5254 # endif /* HAVE_SECCERTIFICATECOPYDATA */
5257 * Let the server know which hostname/domain we are trying to connect to
5258 * in case it wants to serve up a certificate with a matching common name.
5263 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5265 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5271 int done
= 0; /* Are we done yet? */
5273 while (!error
&& !done
)
5275 error
= SSLHandshake(http
->tls
);
5277 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5285 case errSSLWouldBlock
:
5286 error
= noErr
; /* Force a retry */
5287 usleep(1000); /* in 1 millisecond */
5290 # ifdef HAVE_SECCERTIFICATECOPYDATA
5291 case errSSLServerAuthCompleted
:
5293 if (cg
->server_cert_cb
)
5295 error
= httpCopyCredentials(http
, &credentials
);
5298 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5299 cg
->server_cert_data
);
5300 httpFreeCredentials(credentials
);
5303 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5304 "returned %d.", (int)error
));
5308 case errSSLClientCertRequested
:
5311 if (cg
->client_cert_cb
)
5314 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5317 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5319 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5321 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5323 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5325 credential
->datalen
= CFDataGetLength(data
);
5326 if ((credential
->data
= malloc(credential
->datalen
)))
5328 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5329 credential
->datalen
);
5330 cupsArrayAdd(names
, credential
);
5338 CFRelease(dn_array
);
5343 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5344 cg
->client_cert_data
);
5346 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5347 "returned %d.", (int)error
));
5350 httpFreeCredentials(names
);
5353 # endif /* HAVE_SECCERTIFICATECOPYDATA */
5355 case errSSLUnknownRootCert
:
5356 message
= _("Unable to establish a secure connection to host "
5357 "(untrusted certificate).");
5360 case errSSLNoRootCert
:
5361 message
= _("Unable to establish a secure connection to host "
5362 "(self-signed certificate).");
5365 case errSSLCertExpired
:
5366 message
= _("Unable to establish a secure connection to host "
5367 "(expired certificate).");
5370 case errSSLCertNotYetValid
:
5371 message
= _("Unable to establish a secure connection to host "
5372 "(certificate not yet valid).");
5375 case errSSLHostNameMismatch
:
5376 message
= _("Unable to establish a secure connection to host "
5377 "(host name mismatch).");
5380 case errSSLXCertChainInvalid
:
5381 message
= _("Unable to establish a secure connection to host "
5382 "(certificate chain invalid).");
5385 case errSSLConnectionRefused
:
5386 message
= _("Unable to establish a secure connection to host "
5387 "(peer dropped connection before responding).");
5398 http
->error
= error
;
5399 http
->status
= HTTP_ERROR
;
5400 errno
= ECONNREFUSED
;
5402 SSLDisposeContext(http
->tls
);
5406 * If an error string wasn't set by the callbacks use a generic one...
5410 #ifdef HAVE_CSSMERRORSTRING
5411 message
= cssmErrorString(error
);
5413 message
= _("Unable to establish a secure connection to host.");
5414 #endif /* HAVE_CSSMERRORSTRING */
5416 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5421 # elif defined(HAVE_SSPISSL)
5422 http
->tls
= _sspiAlloc();
5426 _cupsSetHTTPError(HTTP_ERROR
);
5430 http
->tls
->sock
= http
->fd
;
5431 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5432 GetUserName(username
, &dwSize
);
5433 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5434 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5436 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5439 _sspiFree(http
->tls_credentials
);
5440 http
->tls_credentials
= NULL
;
5443 http
->status
= HTTP_ERROR
;
5445 _cupsSetError(IPP_PKI_ERROR
,
5446 _("Unable to establish a secure connection to host."), 1);
5451 _sspiSetAllowsAnyRoot(http
->tls_credentials
, any_root
);
5452 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5454 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5456 _sspiFree(http
->tls_credentials
);
5457 http
->tls_credentials
= NULL
;
5460 http
->status
= HTTP_ERROR
;
5462 _cupsSetError(IPP_PKI_ERROR
,
5463 _("Unable to establish a secure connection to host."), 1);
5467 # endif /* HAVE_CDSASSL */
5474 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5478 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
5481 SSL_CTX
*context
; /* Context for encryption */
5483 context
= SSL_get_SSL_CTX(http
->tls
);
5485 SSL_shutdown(http
->tls
);
5486 SSL_CTX_free(context
);
5487 SSL_free(http
->tls
);
5489 # elif defined(HAVE_GNUTLS)
5490 gnutls_certificate_client_credentials
*credentials
;
5491 /* TLS credentials */
5493 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5495 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5496 gnutls_deinit(http
->tls
);
5497 gnutls_certificate_free_credentials(*credentials
);
5500 # elif defined(HAVE_CDSASSL)
5501 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5504 SSLDisposeContext(http
->tls
);
5506 if (http
->tls_credentials
)
5507 CFRelease(http
->tls_credentials
);
5509 # elif defined(HAVE_SSPISSL)
5510 _sspiFree(http
->tls_credentials
);
5511 # endif /* HAVE_LIBSSL */
5514 http
->tls_credentials
= NULL
;
5516 #endif /* HAVE_SSL */
5521 * 'http_upgrade()' - Force upgrade to TLS encryption.
5524 static int /* O - Status of connection */
5525 http_upgrade(http_t
*http
) /* I - Connection to server */
5527 int ret
; /* Return value */
5528 http_t myhttp
; /* Local copy of HTTP data */
5531 DEBUG_printf(("7http_upgrade(%p)", http
));
5534 * Flush the connection to make sure any previous "Upgrade" message
5541 * Copy the HTTP data to a local variable so we can do the OPTIONS
5542 * request without interfering with the existing request data...
5545 memcpy(&myhttp
, http
, sizeof(myhttp
));
5548 * Send an OPTIONS request to the server, requiring SSL or TLS
5549 * encryption on the link...
5552 http
->field_authorization
= NULL
; /* Don't free the auth string */
5554 httpClearFields(http
);
5555 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5556 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5558 if ((ret
= httpOptions(http
, "*")) == 0)
5561 * Wait for the secure connection...
5564 while (httpUpdate(http
) == HTTP_CONTINUE
);
5568 * Restore the HTTP request data...
5571 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5572 http
->data_encoding
= myhttp
.data_encoding
;
5573 http
->data_remaining
= myhttp
.data_remaining
;
5574 http
->_data_remaining
= myhttp
._data_remaining
;
5575 http
->expect
= myhttp
.expect
;
5576 http
->field_authorization
= myhttp
.field_authorization
;
5577 http
->digest_tries
= myhttp
.digest_tries
;
5580 * See if we actually went secure...
5586 * Server does not support HTTP upgrade...
5589 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5592 closesocket(http
->fd
);
5604 #endif /* HAVE_SSL */
5608 * 'http_write()' - Write a buffer to a HTTP connection.
5611 static int /* O - Number of bytes written */
5612 http_write(http_t
*http
, /* I - Connection to server */
5613 const char *buffer
, /* I - Buffer for data */
5614 int length
) /* I - Number of bytes to write */
5616 int tbytes
, /* Total bytes sent */
5617 bytes
; /* Bytes sent */
5620 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
5627 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5629 if (http
->timeout_cb
)
5632 struct pollfd pfd
; /* Polled file descriptor */
5634 fd_set output_set
; /* Output ready for write? */
5635 struct timeval timeout
; /* Timeout value */
5636 #endif /* HAVE_POLL */
5637 int nfds
; /* Result from select()/poll() */
5643 pfd
.events
= POLLOUT
;
5645 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5646 (errno
== EINTR
|| errno
== EAGAIN
))
5652 FD_ZERO(&output_set
);
5653 FD_SET(http
->fd
, &output_set
);
5655 timeout
.tv_sec
= http
->wait_value
/ 1000;
5656 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5658 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5661 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5662 WSAGetLastError() == WSAEWOULDBLOCK
));
5664 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5666 #endif /* HAVE_POLL */
5670 http
->error
= errno
;
5673 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5676 http
->error
= WSAEWOULDBLOCK
;
5678 http
->error
= EWOULDBLOCK
;
5688 bytes
= http_write_ssl(http
, buffer
, length
);
5690 #endif /* HAVE_SSL */
5691 bytes
= send(http
->fd
, buffer
, length
, 0);
5693 DEBUG_printf(("3http_write: Write of %d bytes returned %d.", (int)length
,
5699 if (WSAGetLastError() == WSAEINTR
)
5701 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5703 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5706 http
->error
= WSAGetLastError();
5708 else if (WSAGetLastError() != http
->error
&&
5709 WSAGetLastError() != WSAECONNRESET
)
5711 http
->error
= WSAGetLastError();
5718 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5720 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5722 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5725 http
->error
= errno
;
5727 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5729 http
->error
= errno
;
5734 DEBUG_printf(("3http_write: error writing data (%s).",
5735 strerror(http
->error
)));
5746 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5749 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
5756 * 'http_write_chunk()' - Write a chunked buffer.
5759 static int /* O - Number bytes written */
5760 http_write_chunk(http_t
*http
, /* I - Connection to server */
5761 const char *buffer
, /* I - Buffer to write */
5762 int length
) /* I - Length of buffer */
5764 char header
[255]; /* Chunk header */
5765 int bytes
; /* Bytes written */
5768 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
5769 http
, buffer
, length
));
5772 * Write the chunk header, data, and trailer.
5775 sprintf(header
, "%x\r\n", length
);
5776 if (http_write(http
, header
, (int)strlen(header
)) < 0)
5778 DEBUG_puts("8http_write_chunk: http_write of length failed!");
5782 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5784 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
5788 if (http_write(http
, "\r\n", 2) < 0)
5790 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
5800 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5803 static int /* O - Bytes written */
5804 http_write_ssl(http_t
*http
, /* I - Connection to server */
5805 const char *buf
, /* I - Buffer holding data */
5806 int len
) /* I - Length of buffer */
5808 ssize_t result
; /* Return value */
5811 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5813 # if defined(HAVE_LIBSSL)
5814 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5816 # elif defined(HAVE_GNUTLS)
5817 result
= gnutls_record_send(http
->tls
, buf
, len
);
5819 if (result
< 0 && !errno
)
5822 * Convert GNU TLS error to errno value...
5827 case GNUTLS_E_INTERRUPTED
:
5831 case GNUTLS_E_AGAIN
:
5843 # elif defined(HAVE_CDSASSL)
5844 OSStatus error
; /* Error info */
5845 size_t processed
; /* Number of bytes processed */
5848 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5853 result
= (int)processed
;
5856 case errSSLWouldBlock
:
5858 result
= (int)processed
;
5866 case errSSLClosedGraceful
:
5869 result
= (int)processed
;
5877 # elif defined(HAVE_SSPISSL)
5878 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
5879 # endif /* HAVE_LIBSSL */
5881 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
5883 return ((int)result
);
5885 #endif /* HAVE_SSL */
5889 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".