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
);
180 static int http_set_credentials(http_t
*http
);
181 # endif /* HAVE_CDSASSL */
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)
675 OSStatus error
; /* Error code */
676 SecTrustRef peerTrust
; /* Peer trust reference */
677 CFIndex count
; /* Number of credentials */
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)
698 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
700 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
702 count
= SecTrustGetCertificateCount(peerTrust
);
704 for (i
= 0; i
< count
; i
++)
706 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
707 if ((data
= SecCertificateCopyData(secCert
)))
709 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
710 CFDataGetLength(data
));
716 CFRelease(peerTrust
);
721 # elif defined(HAVE_SSPISSL)
726 # endif /* HAVE_LIBSSL */
731 * '_httpCreate()' - Create an unconnected HTTP connection.
734 http_t
* /* O - HTTP connection */
736 const char *host
, /* I - Hostname */
737 int port
, /* I - Port number */
738 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
739 int family
, /* I - Address family or AF_UNSPEC */
740 http_encryption_t encryption
, /* I - Encryption to use */
741 int blocking
, /* I - 1 for blocking mode */
742 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
744 http_t
*http
; /* New HTTP connection */
745 char service
[255]; /* Service name */
746 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
749 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, addrlist=%p, family=%d, "
750 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
751 family
, encryption
, blocking
, mode
));
753 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
764 myaddrlist
= httpAddrCopyList(addrlist
);
768 snprintf(service
, sizeof(service
), "%d", port
);
770 myaddrlist
= httpAddrGetList(host
, family
, service
);
777 * Allocate memory for the structure...
780 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
782 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(errno
), 0);
783 httpAddrFreeList(addrlist
);
788 * Initialize the HTTP data...
792 http
->activity
= time(NULL
);
793 http
->addrlist
= myaddrlist
;
794 http
->blocking
= blocking
;
797 http
->gssctx
= GSS_C_NO_CONTEXT
;
798 http
->gssname
= GSS_C_NO_NAME
;
799 #endif /* HAVE_GSSAPI */
800 http
->version
= HTTP_VERSION_1_1
;
803 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
805 if (port
== 443) /* Always use encryption for https */
806 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
808 http
->encryption
= encryption
;
813 * Return the new structure...
821 * '_httpCreateCredentials()' - Create credentials in the internal format.
824 http_tls_credentials_t
/* O - Internal credentials */
825 _httpCreateCredentials(
826 cups_array_t
*credentials
) /* I - Array of credentials */
834 # elif defined(HAVE_GNUTLS)
837 # elif defined(HAVE_CDSASSL)
838 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
839 SecCertificateRef secCert
; /* Certificate reference */
840 CFDataRef data
; /* Credential data reference */
841 http_credential_t
*credential
; /* Credential data */
844 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
845 cupsArrayCount(credentials
),
846 &kCFTypeArrayCallBacks
)) == NULL
)
849 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
851 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
853 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
854 credential
->datalen
)))
856 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
859 CFArrayAppendValue(peerCerts
, secCert
);
869 # elif defined(HAVE_SSPISSL)
874 # endif /* HAVE_LIBSSL */
879 * 'httpDelete()' - Send a DELETE request to the server.
882 int /* O - Status of call (0 = success) */
883 httpDelete(http_t
*http
, /* I - Connection to server */
884 const char *uri
) /* I - URI to delete */
886 return (http_send(http
, HTTP_DELETE
, uri
));
891 * '_httpDisconnect()' - Disconnect a HTTP connection.
895 _httpDisconnect(http_t
*http
) /* I - Connection to server */
899 http_shutdown_ssl(http
);
900 #endif /* HAVE_SSL */
903 closesocket(http
->fd
);
913 * 'httpEncryption()' - Set the required encryption on the link.
916 int /* O - -1 on error, 0 on success */
917 httpEncryption(http_t
*http
, /* I - Connection to server */
918 http_encryption_t e
) /* I - New encryption preference */
920 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
926 http
->encryption
= e
;
928 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
929 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
930 return (httpReconnect(http
));
931 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
932 return (http_upgrade(http
));
936 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
940 #endif /* HAVE_SSL */
945 * 'httpError()' - Get the last error on a connection.
948 int /* O - Error code (errno) value */
949 httpError(http_t
*http
) /* I - Connection to server */
952 return (http
->error
);
959 * 'httpFlush()' - Flush data from a HTTP connection.
963 httpFlush(http_t
*http
) /* I - Connection to server */
965 char buffer
[8192]; /* Junk buffer */
966 int blocking
; /* To block or not to block */
967 http_state_t oldstate
; /* Old state */
970 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
971 http_states
[http
->state
+ 1]));
974 * Nothing to do if we are in the "waiting" state...
977 if (http
->state
== HTTP_STATE_WAITING
)
981 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
984 blocking
= http
->blocking
;
988 * Read any data we can...
991 oldstate
= http
->state
;
992 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
995 * Restore blocking and reset the connection if we didn't get all of
996 * the remaining data...
999 http
->blocking
= blocking
;
1001 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
1005 * Didn't get the data back, so close the current connection.
1010 http_content_coding_finish(http
);
1011 #endif /* HAVE_LIBZ */
1013 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
1015 http
->state
= HTTP_STATE_WAITING
;
1019 http_shutdown_ssl(http
);
1020 #endif /* HAVE_SSL */
1023 closesocket(http
->fd
);
1034 * 'httpFlushWrite()' - Flush data in write buffer.
1036 * @since CUPS 1.2/OS X 10.5@
1039 int /* O - Bytes written or -1 on error */
1040 httpFlushWrite(http_t
*http
) /* I - Connection to server */
1042 int bytes
; /* Bytes written */
1045 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
1046 http
? http
->data_encoding
: -1));
1048 if (!http
|| !http
->wused
)
1050 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
1051 "1httpFlushWrite: No connection.");
1055 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1056 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
1058 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
1062 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
1069 * '_httpFreeCredentials()' - Free internal credentials.
1073 _httpFreeCredentials(
1074 http_tls_credentials_t credentials
) /* I - Internal credentials */
1082 #elif defined(HAVE_GNUTLS)
1085 #elif defined(HAVE_CDSASSL)
1086 CFRelease(credentials
);
1088 #elif defined(HAVE_SSPISSL)
1091 #endif /* HAVE_LIBSSL */
1096 * 'httpFreeCredentials()' - Free an array of credentials.
1100 httpFreeCredentials(
1101 cups_array_t
*credentials
) /* I - Array of credentials */
1103 http_credential_t
*credential
; /* Credential */
1106 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
1108 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
1110 cupsArrayRemove(credentials
, credential
);
1111 free((void *)credential
->data
);
1115 cupsArrayDelete(credentials
);
1120 * 'httpGet()' - Send a GET request to the server.
1123 int /* O - Status of call (0 = success) */
1124 httpGet(http_t
*http
, /* I - Connection to server */
1125 const char *uri
) /* I - URI to get */
1127 return (http_send(http
, HTTP_GET
, uri
));
1132 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
1133 * the client and server.
1135 * This function uses the value of the Accepts-Encoding HTTP header and must be
1136 * called after receiving a response from the server or a request from the
1137 * client. The value returned can be use in subsequent requests (for clients)
1138 * or in the response (for servers) in order to compress the content stream.
1143 const char * /* O - Content-Coding value or
1144 @code NULL@ for the identity
1146 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
1149 if (http
&& http
->accept_encoding
)
1151 int i
; /* Looping var */
1152 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
1153 *start
, /* Start of coding value */
1154 *end
; /* End of coding value */
1155 double qvalue
; /* "qvalue" for coding */
1156 struct lconv
*loc
= localeconv(); /* Locale data */
1157 static const char * const codings
[] =
1158 { /* Supported content codings */
1165 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
1167 for (start
= temp
; *start
; start
= end
)
1170 * Find the end of the coding name...
1175 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
1181 * Grab the qvalue as needed...
1184 if (!strncmp(end
, ";q=", 3))
1185 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1188 * Skip past all attributes...
1192 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1198 while (*end
&& isspace(*end
& 255))
1202 * Check value if it matches something we support...
1208 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1209 if (!strcmp(start
, codings
[i
]))
1210 return (codings
[i
]);
1213 #endif /* HAVE_LIBZ */
1220 * 'httpGetAuthString()' - Get the current authorization string.
1222 * The authorization string is set by cupsDoAuthentication() and
1223 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
1224 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
1227 * @since CUPS 1.3/OS X 10.5@
1230 char * /* O - Authorization string */
1231 httpGetAuthString(http_t
*http
) /* I - Connection to server */
1234 return (http
->authstring
);
1241 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
1243 * @since CUPS 1.2/OS X 10.5@
1246 int /* O - 1 if blocking, 0 if non-blocking */
1247 httpGetBlocking(http_t
*http
) /* I - Connection to server */
1249 return (http
? http
->blocking
: 0);
1254 * 'httpGetCookie()' - Get any cookie data from the response.
1256 * @since CUPS 1.1.19/OS X 10.3@
1259 const char * /* O - Cookie data or NULL */
1260 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1262 return (http
? http
->cookie
: NULL
);
1267 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1269 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1270 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1275 http_status_t
/* O - Expect: status, if any */
1276 httpGetExpect(http_t
*http
) /* I - Connection to client */
1279 return (HTTP_STATUS_ERROR
);
1281 return (http
->expect
);
1286 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1288 * @since CUPS 1.2/OS X 10.5@
1291 int /* O - File descriptor or -1 if none */
1292 httpGetFd(http_t
*http
) /* I - Connection to server */
1294 return (http
? http
->fd
: -1);
1299 * 'httpGetField()' - Get a field value from a request/response.
1302 const char * /* O - Field value */
1303 httpGetField(http_t
*http
, /* I - Connection to server */
1304 http_field_t field
) /* I - Field to get */
1306 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1311 case HTTP_FIELD_ACCEPT_ENCODING
:
1312 return (http
->accept_encoding
);
1314 case HTTP_FIELD_ALLOW
:
1315 return (http
->allow
);
1317 case HTTP_FIELD_SERVER
:
1318 return (http
->server
);
1320 case HTTP_FIELD_AUTHORIZATION
:
1321 if (http
->field_authorization
)
1324 * Special case for WWW-Authenticate: as its contents can be
1325 * longer than HTTP_MAX_VALUE...
1328 return (http
->field_authorization
);
1332 return (http
->fields
[field
]);
1338 * 'httpGetLength()' - Get the amount of data remaining from the
1339 * content-length or transfer-encoding fields.
1341 * This function is deprecated and will not return lengths larger than
1342 * 2^31 - 1; use httpGetLength2() instead.
1347 int /* O - Content length */
1348 httpGetLength(http_t
*http
) /* I - Connection to server */
1351 * Get the read content length and return the 32-bit value.
1356 httpGetLength2(http
);
1358 return (http
->_data_remaining
);
1366 * 'httpGetLength2()' - Get the amount of data remaining from the
1367 * content-length or transfer-encoding fields.
1369 * This function returns the complete content length, even for
1370 * content larger than 2^31 - 1.
1372 * @since CUPS 1.2/OS X 10.5@
1375 off_t
/* O - Content length */
1376 httpGetLength2(http_t
*http
) /* I - Connection to server */
1378 off_t remaining
; /* Remaining length */
1381 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1382 http_states
[http
->state
+ 1]));
1387 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1389 DEBUG_puts("4httpGetLength2: chunked request!");
1395 * The following is a hack for HTTP servers that don't send a
1396 * Content-Length or Transfer-Encoding field...
1398 * If there is no Content-Length then the connection must close
1399 * after the transfer is complete...
1402 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1405 * Default content length is 0 for errors and certain types of operations,
1406 * and 2^31-1 for other successful requests...
1409 if (http
->status
>= HTTP_MULTIPLE_CHOICES
||
1410 http
->state
== HTTP_STATE_OPTIONS
||
1411 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1412 http
->state
== HTTP_STATE_HEAD
||
1413 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1414 http
->state
== HTTP_STATE_DELETE
||
1415 http
->state
== HTTP_STATE_TRACE
||
1416 http
->state
== HTTP_STATE_CONNECT
)
1419 remaining
= 2147483647;
1421 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1425 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1426 CUPS_LLCAST remaining
));
1434 * 'httpGets()' - Get a line of text from a HTTP connection.
1437 char * /* O - Line or NULL */
1438 httpGets(char *line
, /* I - Line to read into */
1439 int length
, /* I - Max length of buffer */
1440 http_t
*http
) /* I - Connection to server */
1442 char *lineptr
, /* Pointer into line */
1443 *lineend
, /* End of line */
1444 *bufptr
, /* Pointer into input buffer */
1445 *bufend
; /* Pointer to end of buffer */
1446 int bytes
, /* Number of bytes read */
1447 eol
; /* End-of-line? */
1450 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1452 if (http
== NULL
|| line
== NULL
)
1456 * Read a line from the buffer...
1461 lineend
= line
+ length
- 1;
1464 while (lineptr
< lineend
)
1467 * Pre-load the buffer as needed...
1476 while (http
->used
== 0)
1479 * No newline; see if there is more data to be read...
1482 while (!_httpWait(http
, http
->wait_value
, 1))
1484 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1487 DEBUG_puts("3httpGets: Timed out!");
1489 http
->error
= WSAETIMEDOUT
;
1491 http
->error
= ETIMEDOUT
;
1498 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1499 HTTP_MAX_BUFFER
- http
->used
);
1501 #endif /* HAVE_SSL */
1502 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1503 HTTP_MAX_BUFFER
- http
->used
, 0);
1505 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1508 http_debug_hex("httpGets", http
->buffer
+ http
->used
, bytes
);
1514 * Nope, can't get a line this time...
1518 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1520 if (WSAGetLastError() == WSAEINTR
)
1522 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1524 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1527 http
->error
= WSAGetLastError();
1529 else if (WSAGetLastError() != http
->error
)
1531 http
->error
= WSAGetLastError();
1536 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1540 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1542 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1544 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1547 http
->error
= errno
;
1549 else if (errno
!= http
->error
)
1551 http
->error
= errno
;
1558 else if (bytes
== 0)
1560 http
->error
= EPIPE
;
1566 * Yup, update the amount used...
1569 http
->used
+= bytes
;
1573 * Now copy as much of the current line as possible...
1576 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1577 lineptr
< lineend
&& bufptr
< bufend
;)
1579 if (*bufptr
== 0x0a)
1585 else if (*bufptr
== 0x0d)
1588 *lineptr
++ = *bufptr
++;
1591 http
->used
-= (int)(bufptr
- http
->buffer
);
1593 memmove(http
->buffer
, bufptr
, http
->used
);
1601 http
->activity
= time(NULL
);
1605 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1611 DEBUG_puts("3httpGets: No new line available!");
1618 * 'httpGetState()' - Get the current state of the HTTP request.
1621 http_state_t
/* O - HTTP state */
1622 httpGetState(http_t
*http
) /* I - Connection to server */
1624 return (http
? http
->state
: HTTP_STATE_ERROR
);
1629 * 'httpGetStatus()' - Get the status of the last HTTP request.
1631 * @since CUPS 1.2/OS X 10.5@
1634 http_status_t
/* O - HTTP status */
1635 httpGetStatus(http_t
*http
) /* I - Connection to server */
1637 return (http
? http
->status
: HTTP_ERROR
);
1642 * 'httpGetSubField()' - Get a sub-field value.
1647 char * /* O - Value or NULL */
1648 httpGetSubField(http_t
*http
, /* I - Connection to server */
1649 http_field_t field
, /* I - Field index */
1650 const char *name
, /* I - Name of sub-field */
1651 char *value
) /* O - Value string */
1653 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1658 * 'httpGetSubField2()' - Get a sub-field value.
1660 * @since CUPS 1.2/OS X 10.5@
1663 char * /* O - Value or NULL */
1664 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1665 http_field_t field
, /* I - Field index */
1666 const char *name
, /* I - Name of sub-field */
1667 char *value
, /* O - Value string */
1668 int valuelen
) /* I - Size of value buffer */
1670 const char *fptr
; /* Pointer into field */
1671 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1672 *ptr
, /* Pointer into string buffer */
1673 *end
; /* End of value buffer */
1675 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1676 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1678 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1679 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1682 end
= value
+ valuelen
- 1;
1684 for (fptr
= http
->fields
[field
]; *fptr
;)
1687 * Skip leading whitespace...
1690 while (_cups_isspace(*fptr
))
1700 * Get the sub-field name...
1704 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1705 ptr
< (temp
+ sizeof(temp
) - 1);
1710 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1713 * Skip trailing chars up to the '='...
1716 while (_cups_isspace(*fptr
))
1726 * Skip = and leading whitespace...
1731 while (_cups_isspace(*fptr
))
1737 * Read quoted string...
1740 for (ptr
= value
, fptr
++;
1741 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1746 while (*fptr
&& *fptr
!= '\"')
1755 * Read unquoted string...
1759 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1764 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1768 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1771 * See if this is the one...
1774 if (!strcmp(name
, temp
))
1776 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1783 DEBUG_puts("3httpGetSubField2: Returning NULL");
1790 * 'httpGetVersion()' - Get the HTTP version at the other end.
1793 http_version_t
/* O - Version number */
1794 httpGetVersion(http_t
*http
) /* I - Connection to server */
1796 return (http
? http
->version
: HTTP_VERSION_1_0
);
1801 * 'httpHead()' - Send a HEAD request to the server.
1804 int /* O - Status of call (0 = success) */
1805 httpHead(http_t
*http
, /* I - Connection to server */
1806 const char *uri
) /* I - URI for head */
1808 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1809 return (http_send(http
, HTTP_HEAD
, uri
));
1814 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1815 * default HTTP proxy (if any).
1819 httpInitialize(void)
1821 static int initialized
= 0; /* Have we been called before? */
1823 WSADATA winsockdata
; /* WinSock data */
1826 int i
; /* Looping var */
1827 unsigned char data
[1024]; /* Seed data */
1828 #endif /* HAVE_LIBSSL */
1834 _cupsGlobalUnlock();
1839 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1841 #elif !defined(SO_NOSIGPIPE)
1843 * Ignore SIGPIPE signals...
1847 sigset(SIGPIPE
, SIG_IGN
);
1849 # elif defined(HAVE_SIGACTION)
1850 struct sigaction action
; /* POSIX sigaction data */
1853 memset(&action
, 0, sizeof(action
));
1854 action
.sa_handler
= SIG_IGN
;
1855 sigaction(SIGPIPE
, &action
, NULL
);
1858 signal(SIGPIPE
, SIG_IGN
);
1859 # endif /* !SO_NOSIGPIPE */
1864 * Initialize GNU TLS...
1867 gnutls_global_init();
1869 #elif defined(HAVE_LIBSSL)
1871 * Initialize OpenSSL...
1874 SSL_load_error_strings();
1878 * Using the current time is a dubious random seed, but on some systems
1879 * it is the best we can do (on others, this seed isn't even used...)
1882 CUPS_SRAND(time(NULL
));
1884 for (i
= 0; i
< sizeof(data
); i
++)
1885 data
[i
] = CUPS_RAND();
1887 RAND_seed(data
, sizeof(data
));
1888 #endif /* HAVE_GNUTLS */
1891 _cupsGlobalUnlock();
1896 * 'httpOptions()' - Send an OPTIONS request to the server.
1899 int /* O - Status of call (0 = success) */
1900 httpOptions(http_t
*http
, /* I - Connection to server */
1901 const char *uri
) /* I - URI for options */
1903 return (http_send(http
, HTTP_OPTIONS
, uri
));
1908 * 'httpPeek()' - Peek at data from a HTTP connection.
1910 * This function copies available data from the given HTTP connection, reading
1911 * a buffer as needed. The data is still available for reading using
1912 * @link httpRead@ or @link httpRead2@.
1914 * For non-blocking connections the usual timeouts apply.
1919 ssize_t
/* O - Number of bytes copied */
1920 httpPeek(http_t
*http
, /* I - Connection to server */
1921 char *buffer
, /* I - Buffer for data */
1922 size_t length
) /* I - Maximum number of bytes */
1924 ssize_t bytes
; /* Bytes read */
1925 char len
[32]; /* Length string */
1928 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1929 http
, buffer
, CUPS_LLCAST length
));
1931 if (http
== NULL
|| buffer
== NULL
)
1934 http
->activity
= time(NULL
);
1940 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1941 http
->data_remaining
<= 0)
1943 DEBUG_puts("2httpPeek: Getting chunk length...");
1945 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1947 DEBUG_puts("1httpPeek: Could not get length!");
1951 http
->data_remaining
= strtoll(len
, NULL
, 16);
1952 if (http
->data_remaining
< 0)
1954 DEBUG_puts("1httpPeek: Negative chunk length!");
1959 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1960 CUPS_LLCAST http
->data_remaining
));
1962 if (http
->data_remaining
<= 0)
1965 * A zero-length chunk ends a transfer; unless we are reading POST
1969 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1970 httpGets(len
, sizeof(len
), http
);
1974 http_content_coding_finish(http
);
1975 #endif /* HAVE_LIBZ */
1977 if (http
->state
== HTTP_STATE_POST_RECV
)
1980 http
->state
= HTTP_STATE_WAITING
;
1982 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1983 http_states
[http
->state
+ 1]));
1986 * Prevent future reads for this request...
1989 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1993 else if ((http
->data_encoding
== HTTP_ENCODING_LENGTH
||
1994 http
->coding
== _HTTP_CODING_IDENTITY
) &&
1995 length
> (size_t)http
->data_remaining
)
1996 length
= (size_t)http
->data_remaining
;
1998 if (http
->used
== 0)
2001 * Buffer small reads for better performance...
2004 ssize_t buflen
; /* Length of read for buffer */
2006 if (!http
->blocking
)
2008 while (!httpWait(http
, http
->wait_value
))
2010 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2017 if (http
->data_remaining
> sizeof(http
->buffer
))
2018 buflen
= sizeof(http
->buffer
);
2020 buflen
= http
->data_remaining
;
2022 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
2028 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
2030 #endif /* HAVE_SSL */
2031 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
2036 if (WSAGetLastError() != WSAEINTR
)
2038 http
->error
= WSAGetLastError();
2041 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
2043 if (!http
->timeout_cb
||
2044 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2046 http
->error
= WSAEWOULDBLOCK
;
2051 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2053 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2055 http
->error
= errno
;
2058 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2060 http
->error
= errno
;
2064 else if (errno
!= EINTR
)
2066 http
->error
= errno
;
2074 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
2075 CUPS_LLCAST bytes
));
2077 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
2086 int zerr
; /* Decompressor error */
2087 off_t comp_avail
; /* Maximum bytes for decompression */
2088 z_stream stream
; /* Copy of decompressor stream */
2090 if (http
->used
> http
->data_remaining
)
2091 comp_avail
= http
->data_remaining
;
2093 comp_avail
= http
->used
;
2095 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
2098 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
2100 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
2101 http
->error
= ENOMEM
;
2105 stream
.next_in
= (Bytef
*)http
->buffer
;
2106 stream
.avail_in
= comp_avail
;
2107 stream
.next_out
= (Bytef
*)buffer
;
2108 stream
.avail_out
= length
;
2110 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
2111 inflateEnd(&stream
);
2115 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
2120 bytes
= length
- http
->stream
.avail_out
;
2123 #endif /* HAVE_LIBZ */
2126 if (length
> (size_t)http
->used
)
2127 length
= (size_t)http
->used
;
2129 bytes
= (ssize_t
)length
;
2131 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
2134 memcpy(buffer
, http
->buffer
, length
);
2142 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2145 http
->error
= WSAGetLastError();
2147 if (errno
== EINTR
|| errno
== EAGAIN
)
2150 http
->error
= errno
;
2153 else if (bytes
== 0)
2155 http
->error
= EPIPE
;
2160 http_debug_hex("httpPeek", buffer
, (int)bytes
);
2166 /* For OS X 10.8 and earlier */
2167 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
2168 { return (httpPeek(http
, buffer
, length
)); }
2172 * 'httpPost()' - Send a POST request to the server.
2175 int /* O - Status of call (0 = success) */
2176 httpPost(http_t
*http
, /* I - Connection to server */
2177 const char *uri
) /* I - URI for post */
2179 return (http_send(http
, HTTP_POST
, uri
));
2184 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
2189 int /* O - Number of bytes written */
2190 httpPrintf(http_t
*http
, /* I - Connection to server */
2191 const char *format
, /* I - printf-style format string */
2192 ...) /* I - Additional args as needed */
2194 int bytes
; /* Number of bytes to write */
2195 char buf
[16384]; /* Buffer for formatted string */
2196 va_list ap
; /* Variable argument pointer */
2199 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
2201 va_start(ap
, format
);
2202 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
2205 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
2207 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
2208 return (httpWrite2(http
, buf
, bytes
));
2213 DEBUG_puts("4httpPrintf: flushing existing data...");
2215 if (httpFlushWrite(http
) < 0)
2219 return (http_write(http
, buf
, bytes
));
2225 * 'httpPut()' - Send a PUT request to the server.
2228 int /* O - Status of call (0 = success) */
2229 httpPut(http_t
*http
, /* I - Connection to server */
2230 const char *uri
) /* I - URI to put */
2232 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2233 return (http_send(http
, HTTP_PUT
, uri
));
2238 * 'httpRead()' - Read data from a HTTP connection.
2240 * This function is deprecated. Use the httpRead2() function which can
2241 * read more than 2GB of data.
2246 int /* O - Number of bytes read */
2247 httpRead(http_t
*http
, /* I - Connection to server */
2248 char *buffer
, /* I - Buffer for data */
2249 int length
) /* I - Maximum number of bytes */
2251 return ((int)httpRead2(http
, buffer
, length
));
2256 * 'httpRead2()' - Read data from a HTTP connection.
2258 * @since CUPS 1.2/OS X 10.5@
2261 ssize_t
/* O - Number of bytes read */
2262 httpRead2(http_t
*http
, /* I - Connection to server */
2263 char *buffer
, /* I - Buffer for data */
2264 size_t length
) /* I - Maximum number of bytes */
2266 ssize_t bytes
; /* Bytes read */
2267 char len
[32]; /* Length string */
2270 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2271 ") coding=%d", http
, buffer
, CUPS_LLCAST length
,
2274 if (http
== NULL
|| buffer
== NULL
)
2277 http
->activity
= time(NULL
);
2283 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
2284 http
->data_remaining
<= 0)
2286 if (!httpGets(len
, sizeof(len
), http
))
2288 DEBUG_puts("1httpRead2: Could not get chunk length.");
2294 DEBUG_puts("1httpRead2: Blank chunk length, trying again...");
2295 if (!httpGets(len
, sizeof(len
), http
))
2297 DEBUG_puts("1httpRead2: Could not get chunk length.");
2302 http
->data_remaining
= strtoll(len
, NULL
, 16);
2304 if (http
->data_remaining
< 0)
2306 DEBUG_printf(("1httpRead2: Negative chunk length \"%s\" (" CUPS_LLFMT
")",
2307 len
, CUPS_LLCAST http
->data_remaining
));
2311 DEBUG_printf(("2httpRead2: Got chunk length \"%s\" (" CUPS_LLFMT
")", len
,
2312 CUPS_LLCAST http
->data_remaining
));
2315 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
", used=%d",
2316 CUPS_LLCAST http
->data_remaining
, http
->used
));
2318 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
2321 * A zero-length chunk ends a transfer; unless we are reading POST
2327 http_content_coding_finish(http
);
2328 #endif /* HAVE_LIBZ */
2330 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2331 httpGets(len
, sizeof(len
), http
);
2333 if (http
->state
== HTTP_STATE_POST_RECV
)
2336 http
->state
= HTTP_STATE_WAITING
;
2338 DEBUG_printf(("1httpRead2: 0-length chunk, set state to %s.",
2339 http_states
[http
->state
+ 1]));
2342 * Prevent future reads for this request...
2345 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2349 else if ((http
->data_encoding
== HTTP_ENCODING_LENGTH
||
2350 http
->coding
== _HTTP_CODING_IDENTITY
) &&
2351 length
> (size_t)http
->data_remaining
)
2352 length
= (size_t)http
->data_remaining
;
2355 if (http
->used
== 0 && (length
<= 256 || http
->coding
))
2357 if (http
->used
== 0 && length
<= 256)
2358 #endif /* HAVE_LIBZ */
2361 * Buffer small/compressed reads for better performance...
2364 ssize_t buflen
; /* Length of read for buffer */
2366 if (!http
->blocking
)
2368 while (!httpWait(http
, http
->wait_value
))
2370 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2377 if (http
->data_remaining
> sizeof(http
->buffer
))
2378 buflen
= sizeof(http
->buffer
);
2380 buflen
= http
->data_remaining
;
2382 DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen
));
2388 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
2390 #endif /* HAVE_SSL */
2391 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
2396 if (WSAGetLastError() != WSAEINTR
)
2398 http
->error
= WSAGetLastError();
2401 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
2403 if (!http
->timeout_cb
||
2404 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2406 http
->error
= WSAEWOULDBLOCK
;
2411 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2413 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2415 http
->error
= errno
;
2418 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2420 http
->error
= errno
;
2424 else if (errno
!= EINTR
)
2426 http
->error
= errno
;
2434 DEBUG_printf(("2httpRead2: Read " CUPS_LLFMT
" bytes into buffer.",
2435 CUPS_LLCAST bytes
));
2437 http_debug_hex("httpRead2", http
->buffer
, (int)bytes
);
2446 int zerr
; /* Decompressor error */
2447 off_t comp_avail
, /* Maximum bytes for decompression */
2448 comp_bytes
; /* Compressed bytes "used" */
2450 if (http
->used
> http
->data_remaining
)
2451 comp_avail
= http
->data_remaining
;
2453 comp_avail
= http
->used
;
2455 DEBUG_printf(("2httpRead2: length=%d, avail_in=%d", (int)length
,
2458 http
->stream
.next_in
= (Bytef
*)http
->buffer
;
2459 http
->stream
.avail_in
= comp_avail
;
2460 http
->stream
.next_out
= (Bytef
*)buffer
;
2461 http
->stream
.avail_out
= length
;
2463 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2465 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2470 bytes
= length
- http
->stream
.avail_out
;
2471 comp_bytes
= comp_avail
- http
->stream
.avail_in
;
2473 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d, "
2474 "comp_bytes=%d", http
->stream
.avail_in
,
2475 http
->stream
.avail_out
, (int)bytes
, (int)comp_bytes
));
2477 if ((http
->used
- comp_bytes
) > 0)
2479 http
->used
-= comp_bytes
;
2480 memmove(http
->buffer
, http
->stream
.next_in
, http
->used
);
2486 * Adjust remaining bytes since chunk/content lengths are compressed while
2487 * CUPS HTTP APIs return uncompressed sizes...
2490 http
->data_remaining
+= bytes
- comp_bytes
;
2493 #endif /* HAVE_LIBZ */
2496 if (length
> (size_t)http
->used
)
2497 length
= (size_t)http
->used
;
2499 bytes
= (ssize_t
)length
;
2501 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2504 memcpy(buffer
, http
->buffer
, length
);
2505 http
->used
-= (int)length
;
2508 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2513 if (!http
->blocking
)
2515 while (!httpWait(http
, http
->wait_value
))
2517 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2524 while ((bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
)) < 0)
2527 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2529 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2532 else if (WSAGetLastError() != WSAEINTR
)
2535 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2537 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2539 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2542 else if (errno
!= EINTR
)
2547 #endif /* HAVE_SSL */
2550 if (!http
->blocking
)
2552 while (!httpWait(http
, http
->wait_value
))
2554 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2561 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2562 CUPS_LLCAST length
));
2565 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2567 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2569 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2572 else if (WSAGetLastError() != WSAEINTR
)
2576 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2578 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2580 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2582 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2585 else if (errno
!= EINTR
)
2590 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2591 CUPS_LLCAST bytes
));
2593 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2599 http
->data_remaining
-= bytes
;
2601 if (http
->data_remaining
<= INT_MAX
)
2602 http
->_data_remaining
= (int)http
->data_remaining
;
2604 http
->_data_remaining
= INT_MAX
;
2609 if (WSAGetLastError() == WSAEINTR
)
2612 http
->error
= WSAGetLastError();
2614 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2617 http
->error
= errno
;
2622 http
->error
= EPIPE
;
2626 if (http
->data_remaining
<= 0)
2628 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2630 DEBUG_puts("1httpRead2: Reading trailing line for chunk.");
2631 httpGets(len
, sizeof(len
), http
);
2637 http_content_coding_finish(http
);
2638 #endif /* HAVE_LIBZ */
2640 if (http
->state
== HTTP_STATE_POST_RECV
)
2643 http
->state
= HTTP_STATE_WAITING
;
2645 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2646 http_states
[http
->state
+ 1]));
2654 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2656 * '_httpReadCDSA()' - Read function for the CDSA library.
2659 OSStatus
/* O - -1 on error, 0 on success */
2661 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2662 void *data
, /* I - Data buffer */
2663 size_t *dataLength
) /* IO - Number of bytes */
2665 OSStatus result
; /* Return value */
2666 ssize_t bytes
; /* Number of bytes read */
2667 http_t
*http
; /* HTTP connection */
2670 http
= (http_t
*)connection
;
2672 if (!http
->blocking
)
2675 * Make sure we have data before we read...
2678 while (!_httpWait(http
, http
->wait_value
, 0))
2680 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2683 http
->error
= ETIMEDOUT
;
2690 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2692 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2694 if (bytes
== *dataLength
)
2700 *dataLength
= bytes
;
2701 result
= errSSLWouldBlock
;
2708 result
= errSSLClosedGraceful
;
2709 else if (errno
== EAGAIN
)
2710 result
= errSSLWouldBlock
;
2712 result
= errSSLClosedAbort
;
2717 #endif /* HAVE_SSL && HAVE_CDSASSL */
2720 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2722 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2725 ssize_t
/* O - Number of bytes read or -1 on error */
2727 gnutls_transport_ptr ptr
, /* I - Connection to server */
2728 void *data
, /* I - Buffer */
2729 size_t length
) /* I - Number of bytes to read */
2731 http_t
*http
; /* HTTP connection */
2732 ssize_t bytes
; /* Bytes read */
2735 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2737 http
= (http_t
*)ptr
;
2739 if (!http
->blocking
)
2742 * Make sure we have data before we read...
2745 while (!_httpWait(http
, http
->wait_value
, 0))
2747 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2750 http
->error
= ETIMEDOUT
;
2755 bytes
= recv(http
->fd
, data
, length
, 0);
2756 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2759 #endif /* HAVE_SSL && HAVE_GNUTLS */
2763 * 'httpReadRequest()' - Read a HTTP request from a connection.
2768 http_state_t
/* O - New state of connection */
2769 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2770 char *uri
, /* I - URI buffer */
2771 size_t urilen
) /* I - Size of URI buffer */
2773 char line
[4096], /* HTTP request line */
2774 *req_method
, /* HTTP request method */
2775 *req_uri
, /* HTTP request URI */
2776 *req_version
; /* HTTP request version number string */
2780 * Range check input...
2783 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2784 http
, uri
, CUPS_LLCAST urilen
));
2789 if (!http
|| !uri
|| urilen
< 1)
2791 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2792 return (HTTP_STATE_ERROR
);
2794 else if (http
->state
!= HTTP_STATE_WAITING
)
2796 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2797 http_states
[http
->state
+ 1]));
2798 return (HTTP_STATE_ERROR
);
2805 httpClearFields(http
);
2807 http
->activity
= time(NULL
);
2808 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2809 http
->data_remaining
= 0;
2810 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2811 http
->status
= HTTP_STATUS_OK
;
2812 http
->version
= HTTP_VERSION_1_1
;
2815 * Read a line from the socket...
2818 if (!httpGets(line
, sizeof(line
), http
))
2820 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2821 return (HTTP_STATE_ERROR
);
2826 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2827 return (HTTP_STATE_WAITING
);
2830 DEBUG_printf(("1httpReadRequest: %s", line
));
2839 while (*req_uri
&& !isspace(*req_uri
& 255))
2844 DEBUG_puts("1httpReadRequest: No request URI.");
2845 return (HTTP_STATE_ERROR
);
2850 while (*req_uri
&& isspace(*req_uri
& 255))
2853 req_version
= req_uri
;
2855 while (*req_version
&& !isspace(*req_version
& 255))
2860 DEBUG_puts("1httpReadRequest: No request protocol version.");
2861 return (HTTP_STATE_ERROR
);
2864 *req_version
++ = '\0';
2866 while (*req_version
&& isspace(*req_version
& 255))
2873 if (!strcmp(req_method
, "OPTIONS"))
2874 http
->state
= HTTP_STATE_OPTIONS
;
2875 else if (!strcmp(req_method
, "GET"))
2876 http
->state
= HTTP_STATE_GET
;
2877 else if (!strcmp(req_method
, "HEAD"))
2878 http
->state
= HTTP_STATE_HEAD
;
2879 else if (!strcmp(req_method
, "POST"))
2880 http
->state
= HTTP_STATE_POST
;
2881 else if (!strcmp(req_method
, "PUT"))
2882 http
->state
= HTTP_STATE_PUT
;
2883 else if (!strcmp(req_method
, "DELETE"))
2884 http
->state
= HTTP_STATE_DELETE
;
2885 else if (!strcmp(req_method
, "TRACE"))
2886 http
->state
= HTTP_STATE_TRACE
;
2887 else if (!strcmp(req_method
, "CONNECT"))
2888 http
->state
= HTTP_STATE_CONNECT
;
2891 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2892 return (HTTP_STATE_UNKNOWN_METHOD
);
2895 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2896 http_states
[http
->state
+ 1]));
2898 if (!strcmp(req_version
, "HTTP/1.0"))
2900 http
->version
= HTTP_VERSION_1_0
;
2901 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2903 else if (!strcmp(req_version
, "HTTP/1.1"))
2905 http
->version
= HTTP_VERSION_1_1
;
2906 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2910 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2911 return (HTTP_STATE_UNKNOWN_VERSION
);
2914 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2915 strlcpy(uri
, req_uri
, urilen
);
2917 return (http
->state
);
2922 * 'httpReconnect()' - Reconnect to a HTTP server.
2924 * This function is deprecated. Please use the @link httpReconnect2@ function
2930 int /* O - 0 on success, non-zero on failure */
2931 httpReconnect(http_t
*http
) /* I - Connection to server */
2933 DEBUG_printf(("httpReconnect(http=%p)", http
));
2935 return (httpReconnect2(http
, 30000, NULL
));
2940 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2944 int /* O - 0 on success, non-zero on failure */
2945 httpReconnect2(http_t
*http
, /* I - Connection to server */
2946 int msec
, /* I - Timeout in milliseconds */
2947 int *cancel
) /* I - Pointer to "cancel" variable */
2949 http_addrlist_t
*addr
; /* Connected address */
2951 http_addrlist_t
*current
; /* Current address */
2952 char temp
[256]; /* Temporary address string */
2956 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2961 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
2968 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2969 http_shutdown_ssl(http
);
2971 #endif /* HAVE_SSL */
2974 * Close any previously open socket...
2979 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2982 closesocket(http
->fd
);
2991 * Reset all state (except fields, which may be reused)...
2994 http
->state
= HTTP_STATE_WAITING
;
2995 http
->status
= HTTP_STATUS_CONTINUE
;
2996 http
->version
= HTTP_VERSION_1_1
;
2997 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2998 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2999 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3000 http
->_data_remaining
= 0;
3003 http
->data_remaining
= 0;
3004 http
->hostaddr
= NULL
;
3008 * Connect to the server...
3012 for (current
= http
->addrlist
; current
; current
= current
->next
)
3013 DEBUG_printf(("2httpReconnect2: Address %s:%d",
3014 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
3015 httpAddrPort(&(current
->addr
))));
3018 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
3022 * Unable to connect...
3026 http
->error
= WSAGetLastError();
3028 http
->error
= errno
;
3030 http
->status
= HTTP_ERROR
;
3032 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
3033 strerror(http
->error
)));
3038 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
3040 if (http
->timeout_value
> 0)
3041 http_set_timeout(http
->fd
, http
->timeout_value
);
3043 http
->hostaddr
= &(addr
->addr
);
3047 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
3050 * Always do encryption via SSL.
3053 if (http_setup_ssl(http
) != 0)
3056 closesocket(http
->fd
);
3064 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
3065 return (http_upgrade(http
));
3066 #endif /* HAVE_SSL */
3068 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
3069 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
3070 httpAddrPort(http
->hostaddr
)));
3077 * 'httpSetAuthString()' - Set the current authorization string.
3079 * This function just stores a copy of the current authorization string in
3080 * the HTTP connection object. You must still call httpSetField() to set
3081 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
3082 * httpHead(), httpOptions(), httpPost, or httpPut().
3084 * @since CUPS 1.3/OS X 10.5@
3088 httpSetAuthString(http_t
*http
, /* I - Connection to server */
3089 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
3090 const char *data
) /* I - Auth data (NULL for none) */
3093 * Range check input...
3099 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
3100 free(http
->authstring
);
3102 http
->authstring
= http
->_authstring
;
3107 * Set the current authorization string...
3110 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
3113 if (len
> (int)sizeof(http
->_authstring
))
3115 if ((temp
= malloc(len
)) == NULL
)
3116 len
= sizeof(http
->_authstring
);
3118 http
->authstring
= temp
;
3122 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
3124 strlcpy(http
->authstring
, scheme
, len
);
3129 * Clear the current authorization string...
3132 http
->_authstring
[0] = '\0';
3138 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
3141 * @since CUPS 1.5/OS X 10.7@
3144 int /* O - Status of call (0 = success) */
3145 httpSetCredentials(http_t
*http
, /* I - Connection to server */
3146 cups_array_t
*credentials
) /* I - Array of credentials */
3148 if (!http
|| cupsArrayCount(credentials
) < 1)
3151 _httpFreeCredentials(http
->tls_credentials
);
3153 http
->tls_credentials
= _httpCreateCredentials(credentials
);
3155 return (http
->tls_credentials
? 0 : -1);
3160 * 'httpSetCookie()' - Set the cookie value(s).
3162 * @since CUPS 1.1.19/OS X 10.3@
3166 httpSetCookie(http_t
*http
, /* I - Connection */
3167 const char *cookie
) /* I - Cookie string */
3176 http
->cookie
= strdup(cookie
);
3178 http
->cookie
= NULL
;
3183 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
3185 * Currently only HTTP_FIELD_ACCEPT_ENCODING, HTTP_FIELD_SERVER, and
3186 * HTTP_FIELD_USER_AGENT can be set.
3192 httpSetDefaultField(http_t
*http
, /* I - Connection to server */
3193 http_field_t field
, /* I - Field index */
3194 const char *value
)/* I - Value */
3196 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
3197 http
, field
, http_fields
[field
], value
));
3204 case HTTP_FIELD_ACCEPT_ENCODING
:
3205 if (http
->default_accept_encoding
)
3206 _cupsStrFree(http
->default_accept_encoding
);
3208 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
3211 case HTTP_FIELD_SERVER
:
3212 if (http
->default_server
)
3213 _cupsStrFree(http
->default_server
);
3215 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
3218 case HTTP_FIELD_USER_AGENT
:
3219 if (http
->default_user_agent
)
3220 _cupsStrFree(http
->default_user_agent
);
3222 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
3226 DEBUG_puts("1httpSetDefaultField: Ignored.");
3233 * 'httpSetExpect()' - Set the Expect: header in a request.
3235 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
3238 * @since CUPS 1.2/OS X 10.5@
3242 httpSetExpect(http_t
*http
, /* I - Connection to server */
3243 http_status_t expect
) /* I - HTTP status to expect
3244 (@code HTTP_CONTINUE@) */
3247 http
->expect
= expect
;
3252 * 'httpSetField()' - Set the value of an HTTP header.
3256 httpSetField(http_t
*http
, /* I - Connection to server */
3257 http_field_t field
, /* I - Field index */
3258 const char *value
) /* I - Value */
3260 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
3261 field
, http_fields
[field
], value
));
3264 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
3265 field
>= HTTP_FIELD_MAX
||
3271 case HTTP_FIELD_ACCEPT_ENCODING
:
3272 if (http
->accept_encoding
)
3273 _cupsStrFree(http
->accept_encoding
);
3275 http
->accept_encoding
= _cupsStrAlloc(value
);
3278 case HTTP_FIELD_ALLOW
:
3280 _cupsStrFree(http
->allow
);
3282 http
->allow
= _cupsStrAlloc(value
);
3285 case HTTP_FIELD_SERVER
:
3287 _cupsStrFree(http
->server
);
3289 http
->server
= _cupsStrAlloc(value
);
3293 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
3297 if (field
== HTTP_FIELD_AUTHORIZATION
)
3300 * Special case for Authorization: as its contents can be
3301 * longer than HTTP_MAX_VALUE
3304 if (http
->field_authorization
)
3305 free(http
->field_authorization
);
3307 http
->field_authorization
= strdup(value
);
3309 else if (field
== HTTP_FIELD_HOST
)
3312 * Special-case for Host: as we don't want a trailing "." on the hostname and
3313 * need to bracket IPv6 numeric addresses.
3316 char *ptr
= strchr(value
, ':');
3318 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
3321 * Bracket IPv6 numeric addresses...
3323 * This is slightly inefficient (basically copying twice), but is an edge
3324 * case and not worth optimizing...
3327 snprintf(http
->fields
[HTTP_FIELD_HOST
],
3328 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
3333 * Check for a trailing dot on the hostname...
3336 ptr
= http
->fields
[HTTP_FIELD_HOST
];
3340 ptr
+= strlen(ptr
) - 1;
3348 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
3349 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
3351 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
3352 http_content_coding_start(http
, value
);
3354 #endif /* HAVE_LIBZ */
3359 * 'httpSetLength()' - Set the content-length and content-encoding.
3361 * @since CUPS 1.2/OS X 10.5@
3365 httpSetLength(http_t
*http
, /* I - Connection to server */
3366 size_t length
) /* I - Length (0 for chunked) */
3368 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
3369 CUPS_LLCAST length
));
3376 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
3378 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
3382 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
3383 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
3384 CUPS_LLFMT
, CUPS_LLCAST length
);
3390 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
3392 * The optional timeout callback receives both the HTTP connection and a user
3393 * data pointer and must return 1 to continue or 0 to error (time) out.
3395 * @since CUPS 1.5/OS X 10.7@
3400 http_t
*http
, /* I - Connection to server */
3401 double timeout
, /* I - Number of seconds for timeout,
3402 must be greater than 0 */
3403 http_timeout_cb_t cb
, /* I - Callback function or NULL */
3404 void *user_data
) /* I - User data pointer */
3406 if (!http
|| timeout
<= 0.0)
3409 http
->timeout_cb
= cb
;
3410 http
->timeout_data
= user_data
;
3411 http
->timeout_value
= timeout
;
3414 http_set_timeout(http
->fd
, timeout
);
3416 http_set_wait(http
);
3421 * 'httpTrace()' - Send an TRACE request to the server.
3424 int /* O - Status of call (0 = success) */
3425 httpTrace(http_t
*http
, /* I - Connection to server */
3426 const char *uri
) /* I - URI for trace */
3428 return (http_send(http
, HTTP_TRACE
, uri
));
3433 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3435 * Note: Unlike httpUpdate(), this function does not flush pending write data
3436 * and only retrieves a single status line from the HTTP connection.
3439 int /* O - 1 to continue, 0 to stop */
3440 _httpUpdate(http_t
*http
, /* I - Connection to server */
3441 http_status_t
*status
) /* O - Current HTTP status */
3443 char line
[32768], /* Line from connection... */
3444 *value
; /* Pointer to value on line */
3445 http_field_t field
; /* Field index */
3446 int major
, minor
; /* HTTP version numbers */
3449 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3450 http_states
[http
->state
+ 1]));
3453 * Grab a single line from the connection...
3456 if (!httpGets(line
, sizeof(line
), http
))
3458 *status
= HTTP_ERROR
;
3462 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3464 if (line
[0] == '\0')
3467 * Blank line means the start of the data section (if any). Return
3468 * the result code, too...
3470 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3471 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3475 if (http
->status
== HTTP_STATUS_CONTINUE
)
3477 *status
= http
->status
;
3481 if (http
->status
< HTTP_BAD_REQUEST
)
3482 http
->digest_tries
= 0;
3485 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
3487 if (http_setup_ssl(http
) != 0)
3490 closesocket(http
->fd
);
3495 *status
= http
->status
= HTTP_ERROR
;
3499 *status
= HTTP_STATUS_CONTINUE
;
3502 #endif /* HAVE_SSL */
3504 if (http_set_length(http
) < 0)
3506 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3507 http
->error
= EINVAL
;
3508 http
->status
= *status
= HTTP_ERROR
;
3512 switch (http
->state
)
3514 case HTTP_STATE_GET
:
3515 case HTTP_STATE_POST
:
3516 case HTTP_STATE_POST_RECV
:
3517 case HTTP_STATE_PUT
:
3520 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3521 http_states
[http
->state
+ 1]));
3523 case HTTP_STATE_POST_SEND
:
3524 case HTTP_STATE_HEAD
:
3528 http
->state
= HTTP_STATE_WAITING
;
3530 DEBUG_puts("1_httpUpdate: Unknown state, reset state to "
3531 "HTTP_STATE_WAITING.");
3536 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3537 http_content_coding_start(http
,
3538 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3539 #endif /* HAVE_LIBZ */
3541 *status
= http
->status
;
3544 else if (!strncmp(line
, "HTTP/", 5))
3547 * Got the beginning of a response...
3550 int intstatus
; /* Status value as an integer */
3552 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3554 *status
= http
->status
= HTTP_ERROR
;
3558 httpClearFields(http
);
3560 http
->version
= (http_version_t
)(major
* 100 + minor
);
3561 *status
= http
->status
= (http_status_t
)intstatus
;
3563 else if ((value
= strchr(line
, ':')) != NULL
)
3570 while (_cups_isspace(*value
))
3573 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3576 * Be tolerants of servers that send unknown attribute fields...
3579 if (!_cups_strcasecmp(line
, "expect"))
3582 * "Expect: 100-continue" or similar...
3585 http
->expect
= (http_status_t
)atoi(value
);
3587 else if (!_cups_strcasecmp(line
, "cookie"))
3590 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3593 httpSetCookie(http
, value
);
3595 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
3596 httpSetField(http
, field
, value
);
3599 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3604 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3605 http
->error
= EINVAL
;
3606 http
->status
= *status
= HTTP_ERROR
;
3615 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3618 http_status_t
/* O - HTTP status */
3619 httpUpdate(http_t
*http
) /* I - Connection to server */
3621 http_status_t status
; /* Request status */
3624 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3625 http_states
[http
->state
+ 1]));
3628 * Flush pending data, if any...
3633 DEBUG_puts("2httpUpdate: flushing buffer...");
3635 if (httpFlushWrite(http
) < 0)
3636 return (HTTP_ERROR
);
3640 * If we haven't issued any commands, then there is nothing to "update"...
3643 if (http
->state
== HTTP_STATE_WAITING
)
3644 return (HTTP_CONTINUE
);
3647 * Grab all of the lines we can from the connection...
3650 while (_httpUpdate(http
, &status
));
3653 * See if there was an error...
3656 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
3658 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3659 return (http
->status
);
3664 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3665 strerror(http
->error
)));
3666 http
->status
= HTTP_ERROR
;
3667 return (HTTP_ERROR
);
3671 * Return the current status...
3679 * '_httpWait()' - Wait for data available on a connection (no flush).
3682 int /* O - 1 if data is available, 0 otherwise */
3683 _httpWait(http_t
*http
, /* I - Connection to server */
3684 int msec
, /* I - Milliseconds to wait */
3685 int usessl
) /* I - Use SSL context? */
3688 struct pollfd pfd
; /* Polled file descriptor */
3690 fd_set input_set
; /* select() input set */
3691 struct timeval timeout
; /* Timeout */
3692 #endif /* HAVE_POLL */
3693 int nfds
; /* Result from select()/poll() */
3696 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3700 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3705 * Check the SSL/TLS buffers for data first...
3709 if (http
->tls
&& usessl
)
3712 if (SSL_pending(http
->tls
))
3714 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3718 # elif defined(HAVE_GNUTLS)
3719 if (gnutls_record_check_pending(http
->tls
))
3721 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3725 # elif defined(HAVE_CDSASSL)
3726 size_t bytes
; /* Bytes that are available */
3728 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3731 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3734 # endif /* HAVE_LIBSSL */
3736 #endif /* HAVE_SSL */
3739 * Then try doing a select() or poll() to poll the socket...
3744 pfd
.events
= POLLIN
;
3748 nfds
= poll(&pfd
, 1, msec
);
3750 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3755 FD_ZERO(&input_set
);
3756 FD_SET(http
->fd
, &input_set
);
3758 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3762 timeout
.tv_sec
= msec
/ 1000;
3763 timeout
.tv_usec
= (msec
% 1000) * 1000;
3765 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3768 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3770 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3773 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3774 WSAGetLastError() == WSAEWOULDBLOCK
));
3776 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3778 #endif /* HAVE_POLL */
3780 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3788 * 'httpWait()' - Wait for data available on a connection.
3790 * @since CUPS 1.1.19/OS X 10.3@
3793 int /* O - 1 if data is available, 0 otherwise */
3794 httpWait(http_t
*http
, /* I - Connection to server */
3795 int msec
) /* I - Milliseconds to wait */
3798 * First see if there is data in the buffer...
3801 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3808 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3813 * Flush pending data, if any...
3818 DEBUG_puts("3httpWait: Flushing write buffer.");
3820 if (httpFlushWrite(http
) < 0)
3825 * If not, check the SSL/TLS buffers and do a select() on the connection...
3828 return (_httpWait(http
, msec
, 1));
3833 * 'httpWrite()' - Write data to a HTTP connection.
3835 * This function is deprecated. Use the httpWrite2() function which can
3836 * write more than 2GB of data.
3841 int /* O - Number of bytes written */
3842 httpWrite(http_t
*http
, /* I - Connection to server */
3843 const char *buffer
, /* I - Buffer for data */
3844 int length
) /* I - Number of bytes to write */
3846 return ((int)httpWrite2(http
, buffer
, length
));
3851 * 'httpWrite2()' - Write data to a HTTP connection.
3853 * @since CUPS 1.2/OS X 10.5@
3856 ssize_t
/* O - Number of bytes written */
3857 httpWrite2(http_t
*http
, /* I - Connection to server */
3858 const char *buffer
, /* I - Buffer for data */
3859 size_t length
) /* I - Number of bytes to write */
3861 ssize_t bytes
; /* Bytes written */
3864 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3865 buffer
, CUPS_LLCAST length
));
3868 * Range check input...
3871 if (!http
|| !buffer
)
3873 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3878 * Mark activity on the connection...
3881 http
->activity
= time(NULL
);
3884 * Buffer small writes for better performance...
3890 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3894 http_content_coding_finish(http
);
3899 http
->stream
.next_in
= (Bytef
*)buffer
;
3900 http
->stream
.avail_in
= length
;
3901 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3902 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3904 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3906 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3908 if (http
->stream
.avail_out
== 0)
3910 if (httpFlushWrite(http
) < 0)
3912 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3916 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3917 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3921 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3926 #endif /* HAVE_LIBZ */
3929 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3931 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3932 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3934 httpFlushWrite(http
);
3937 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3938 length
< sizeof(http
->wbuffer
))
3941 * Write to buffer...
3944 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3945 CUPS_LLCAST length
));
3947 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3948 http
->wused
+= (int)length
;
3949 bytes
= (ssize_t
)length
;
3954 * Otherwise write the data directly...
3957 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3958 CUPS_LLCAST length
));
3960 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3961 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3963 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3965 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3966 CUPS_LLCAST bytes
));
3969 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3970 http
->data_remaining
-= bytes
;
3976 * Handle end-of-request processing...
3979 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3980 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3983 * Finished with the transfer; unless we are sending POST or PUT
3989 if (httpFlushWrite(http
) < 0)
3993 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3996 * Send a 0-length chunk at the end of the request...
3999 http_write(http
, "0\r\n\r\n", 5);
4002 * Reset the data state...
4005 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4006 http
->data_remaining
= 0;
4009 if (http
->state
== HTTP_STATE_POST_RECV
)
4013 http_content_coding_finish(http
);
4014 #endif /* HAVE_LIBZ */
4018 DEBUG_printf(("2httpWrite2: Changed state to %s.",
4019 http_states
[http
->state
+ 1]));
4023 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
4029 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
4031 * '_httpWriteCDSA()' - Write function for the CDSA library.
4034 OSStatus
/* O - -1 on error, 0 on success */
4036 SSLConnectionRef connection
, /* I - SSL/TLS connection */
4037 const void *data
, /* I - Data buffer */
4038 size_t *dataLength
) /* IO - Number of bytes */
4040 OSStatus result
; /* Return value */
4041 ssize_t bytes
; /* Number of bytes read */
4042 http_t
*http
; /* HTTP connection */
4045 http
= (http_t
*)connection
;
4049 bytes
= write(http
->fd
, data
, *dataLength
);
4051 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
4053 if (bytes
== *dataLength
)
4057 else if (bytes
>= 0)
4059 *dataLength
= bytes
;
4060 result
= errSSLWouldBlock
;
4066 if (errno
== EAGAIN
)
4067 result
= errSSLWouldBlock
;
4069 result
= errSSLClosedAbort
;
4074 #endif /* HAVE_SSL && HAVE_CDSASSL */
4077 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
4079 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
4082 ssize_t
/* O - Number of bytes written or -1 on error */
4084 gnutls_transport_ptr ptr
, /* I - Connection to server */
4085 const void *data
, /* I - Data buffer */
4086 size_t length
) /* I - Number of bytes to write */
4088 ssize_t bytes
; /* Bytes written */
4091 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
4094 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
4097 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
4098 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
4102 #endif /* HAVE_SSL && HAVE_GNUTLS */
4106 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
4111 int /* O - 0 on success, -1 on error */
4112 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
4113 http_status_t status
) /* I - Status code */
4115 http_encoding_t old_encoding
; /* Old data_encoding value */
4116 off_t old_remaining
; /* Old data_remaining value */
4120 * Range check input...
4123 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
4125 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
4127 DEBUG_puts("1httpWriteResponse: Bad input.");
4132 * Set the various standard fields if they aren't already...
4135 if (!http
->fields
[HTTP_FIELD_DATE
][0])
4136 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
4138 if (status
>= HTTP_BAD_REQUEST
&& http
->keep_alive
)
4140 http
->keep_alive
= 0;
4141 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
4144 if (http
->version
== HTTP_VERSION_1_1
)
4146 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
4148 if (http
->keep_alive
)
4149 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
4151 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
4154 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
4155 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
4159 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
)
4161 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
4162 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4164 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
4165 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4167 #endif /* HAVE_SSL */
4170 httpSetField(http
, HTTP_FIELD_SERVER
,
4171 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
4174 * Set the Accept-Encoding field if it isn't already...
4177 if (!http
->accept_encoding
)
4178 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4179 http
->default_accept_encoding
? http
->default_accept_encoding
:
4181 "gzip, deflate, identity");
4184 #endif /* HAVE_LIBZ */
4187 * Send the response header...
4190 old_encoding
= http
->data_encoding
;
4191 old_remaining
= http
->data_remaining
;
4192 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4194 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
4195 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
4197 http
->status
= HTTP_STATUS_ERROR
;
4201 if (status
!= HTTP_STATUS_CONTINUE
)
4204 * 100 Continue doesn't have the rest of the response headers...
4207 int i
; /* Looping var */
4208 const char *value
; /* Field value */
4210 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4212 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4214 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4216 http
->status
= HTTP_STATUS_ERROR
;
4224 if (httpPrintf(http
, "Set-Cookie: %s path=/%s\r\n", http
->cookie
,
4225 http
->tls
? " secure" : "") < 1)
4227 http
->status
= HTTP_ERROR
;
4233 if (httpWrite2(http
, "\r\n", 2) < 2)
4235 http
->status
= HTTP_ERROR
;
4239 if (httpFlushWrite(http
) < 0)
4241 http
->status
= HTTP_ERROR
;
4245 if (status
== HTTP_STATUS_CONTINUE
)
4248 * Restore the old data_encoding and data_length values...
4251 http
->data_encoding
= old_encoding
;
4252 http
->data_remaining
= old_remaining
;
4254 if (old_remaining
<= INT_MAX
)
4255 http
->_data_remaining
= (int)old_remaining
;
4257 http
->_data_remaining
= INT_MAX
;
4259 else if (http
->state
== HTTP_STATE_OPTIONS
||
4260 http
->state
== HTTP_STATE_HEAD
||
4261 http
->state
== HTTP_STATE_PUT
||
4262 http
->state
== HTTP_STATE_TRACE
||
4263 http
->state
== HTTP_STATE_CONNECT
)
4265 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
4266 "was %s.", http_states
[http
->state
+ 1]));
4267 http
->state
= HTTP_STATE_WAITING
;
4272 * Force data_encoding and data_length to be set according to the response
4276 http_set_length(http
);
4279 * Then start any content encoding...
4282 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
4283 http_content_coding_start(http
,
4284 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
4291 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
4293 * 'http_bio_ctrl()' - Control the HTTP connection.
4296 static long /* O - Result/data */
4297 http_bio_ctrl(BIO
*h
, /* I - BIO data */
4298 int cmd
, /* I - Control command */
4299 long arg1
, /* I - First argument */
4300 void *arg2
) /* I - Second argument */
4307 case BIO_CTRL_RESET
:
4311 case BIO_C_SET_FILE_PTR
:
4316 case BIO_C_GET_FILE_PTR
:
4319 *((void **)arg2
) = h
->ptr
;
4326 case BIO_CTRL_FLUSH
:
4333 * 'http_bio_free()' - Free OpenSSL data.
4336 static int /* O - 1 on success, 0 on failure */
4337 http_bio_free(BIO
*h
) /* I - BIO data */
4353 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
4356 static int /* O - 1 on success, 0 on failure */
4357 http_bio_new(BIO
*h
) /* I - BIO data */
4372 * 'http_bio_puts()' - Send a string for OpenSSL.
4375 static int /* O - Bytes written */
4376 http_bio_puts(BIO
*h
, /* I - BIO data */
4377 const char *str
) /* I - String to write */
4380 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
4382 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
4388 * 'http_bio_read()' - Read data for OpenSSL.
4391 static int /* O - Bytes read */
4392 http_bio_read(BIO
*h
, /* I - BIO data */
4393 char *buf
, /* I - Buffer */
4394 int size
) /* I - Number of bytes to read */
4396 http_t
*http
; /* HTTP connection */
4399 http
= (http_t
*)h
->ptr
;
4401 if (!http
->blocking
)
4404 * Make sure we have data before we read...
4407 while (!_httpWait(http
, http
->wait_value
, 0))
4409 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4413 http
->error
= WSAETIMEDOUT
;
4415 http
->error
= ETIMEDOUT
;
4422 return (recv(http
->fd
, buf
, size
, 0));
4427 * 'http_bio_write()' - Write data for OpenSSL.
4430 static int /* O - Bytes written */
4431 http_bio_write(BIO
*h
, /* I - BIO data */
4432 const char *buf
, /* I - Buffer to write */
4433 int num
) /* I - Number of bytes to write */
4435 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4437 #endif /* HAVE_SSL && HAVE_LIBSSL */
4442 * 'http_content_coding_finish()' - Finish doing any content encoding.
4446 http_content_coding_finish(
4447 http_t
*http
) /* I - HTTP connection */
4449 int zerr
; /* Compression status */
4452 switch (http
->coding
)
4454 case _HTTP_CODING_DEFLATE
:
4455 case _HTTP_CODING_GZIP
:
4458 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4459 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4461 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4463 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4464 if (http
->wused
== sizeof(http
->wbuffer
))
4465 httpFlushWrite(http
);
4467 while (zerr
== Z_OK
);
4469 deflateEnd(&(http
->stream
));
4472 httpFlushWrite(http
);
4475 case _HTTP_CODING_INFLATE
:
4476 case _HTTP_CODING_GUNZIP
:
4477 inflateEnd(&(http
->stream
));
4484 http
->coding
= _HTTP_CODING_IDENTITY
;
4489 * 'http_content_coding_start()' - Start doing content encoding.
4493 http_content_coding_start(
4494 http_t
*http
, /* I - HTTP connection */
4495 const char *value
) /* I - Value of Content-Encoding */
4497 int zerr
; /* Error/status */
4498 _http_coding_t coding
; /* Content coding value */
4501 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4504 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4506 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4510 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4512 if (http
->state
== HTTP_GET_SEND
|| http
->state
== HTTP_POST_SEND
)
4513 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4514 _HTTP_CODING_GUNZIP
;
4515 else if (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
)
4516 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4517 _HTTP_CODING_GUNZIP
;
4520 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4524 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4526 if (http
->state
== HTTP_GET_SEND
|| http
->state
== HTTP_POST_SEND
)
4527 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4528 _HTTP_CODING_INFLATE
;
4529 else if (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
)
4530 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4531 _HTTP_CODING_INFLATE
;
4534 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4540 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4544 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4548 case _HTTP_CODING_DEFLATE
:
4549 case _HTTP_CODING_GZIP
:
4551 httpFlushWrite(http
);
4553 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4555 coding
== _HTTP_CODING_DEFLATE
? 11 : 27, 7,
4556 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4558 http
->status
= HTTP_ERROR
;
4559 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4564 case _HTTP_CODING_INFLATE
:
4565 case _HTTP_CODING_GUNZIP
:
4566 if ((zerr
= inflateInit2(&(http
->stream
), 32 + 15)) < Z_OK
)
4568 http
->status
= HTTP_ERROR
;
4569 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4578 http
->coding
= coding
;
4580 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4583 #endif /* HAVE_LIBZ */
4588 * 'http_debug_hex()' - Do a hex dump of a buffer.
4592 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4593 const char *buffer
, /* I - Buffer to dump */
4594 int bytes
) /* I - Bytes to dump */
4596 int i
, j
, /* Looping vars */
4597 ch
; /* Current character */
4598 char line
[255], /* Line buffer */
4599 *start
, /* Start of line after prefix */
4600 *ptr
; /* Pointer into line */
4603 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4606 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4608 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4609 start
= line
+ strlen(line
);
4611 for (i
= 0; i
< bytes
; i
+= 16)
4613 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4614 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4618 memcpy(ptr
, " ", 3);
4623 memcpy(ptr
, " ", 3);
4626 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4628 ch
= buffer
[i
+ j
] & 255;
4630 if (ch
< ' ' || ch
>= 127)
4644 * 'http_field()' - Return the field index for a field name.
4647 static http_field_t
/* O - Field index */
4648 http_field(const char *name
) /* I - String name */
4650 int i
; /* Looping var */
4653 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4654 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
4655 return ((http_field_t
)i
);
4657 return (HTTP_FIELD_UNKNOWN
);
4663 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4666 static int /* O - Bytes read */
4667 http_read_ssl(http_t
*http
, /* I - Connection to server */
4668 char *buf
, /* I - Buffer to store data */
4669 int len
) /* I - Length of buffer */
4671 # if defined(HAVE_LIBSSL)
4672 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4674 # elif defined(HAVE_GNUTLS)
4675 ssize_t result
; /* Return value */
4678 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4680 if (result
< 0 && !errno
)
4683 * Convert GNU TLS error to errno value...
4688 case GNUTLS_E_INTERRUPTED
:
4692 case GNUTLS_E_AGAIN
:
4704 return ((int)result
);
4706 # elif defined(HAVE_CDSASSL)
4707 int result
; /* Return value */
4708 OSStatus error
; /* Error info */
4709 size_t processed
; /* Number of bytes processed */
4712 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4713 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4718 result
= (int)processed
;
4721 case errSSLWouldBlock
:
4723 result
= (int)processed
;
4731 case errSSLClosedGraceful
:
4734 result
= (int)processed
;
4745 # elif defined(HAVE_SSPISSL)
4746 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4747 # endif /* HAVE_LIBSSL */
4749 #endif /* HAVE_SSL */
4753 * 'http_send()' - Send a request with all fields and the trailing blank line.
4756 static int /* O - 0 on success, non-zero on error */
4757 http_send(http_t
*http
, /* I - Connection to server */
4758 http_state_t request
, /* I - Request code */
4759 const char *uri
) /* I - URI */
4761 int i
; /* Looping var */
4762 char buf
[1024]; /* Encoded URI buffer */
4763 const char *value
; /* Field value */
4764 static const char * const codes
[] = /* Request code strings */
4784 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4785 http
, codes
[request
], uri
));
4787 if (http
== NULL
|| uri
== NULL
)
4791 * Set the User-Agent field if it isn't already...
4794 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4795 httpSetField(http
, HTTP_FIELD_USER_AGENT
,
4796 http
->default_user_agent
? http
->default_user_agent
:
4800 * Set the Accept-Encoding field if it isn't already...
4803 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4804 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4805 http
->default_accept_encoding
);
4808 * Encode the URI as needed...
4811 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4814 * See if we had an error the last time around; if so, reconnect...
4817 if (http
->fd
< 0 || http
->status
== HTTP_ERROR
||
4818 http
->status
>= HTTP_BAD_REQUEST
)
4819 if (httpReconnect(http
))
4823 * Flush any written data that is pending...
4828 if (httpFlushWrite(http
) < 0)
4829 if (httpReconnect(http
))
4834 * Send the request header...
4837 http
->state
= request
;
4838 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4840 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
4843 http
->status
= HTTP_CONTINUE
;
4846 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
4848 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4849 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4851 #endif /* HAVE_SSL */
4853 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4855 http
->status
= HTTP_ERROR
;
4859 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4860 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4862 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
], value
));
4864 if (i
== HTTP_FIELD_HOST
)
4866 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4867 httpAddrPort(http
->hostaddr
)) < 1)
4869 http
->status
= HTTP_ERROR
;
4873 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4875 http
->status
= HTTP_ERROR
;
4881 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4883 http
->status
= HTTP_ERROR
;
4887 if (http
->expect
== HTTP_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4888 (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
4889 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4891 http
->status
= HTTP_ERROR
;
4895 if (httpPrintf(http
, "\r\n") < 1)
4897 http
->status
= HTTP_ERROR
;
4901 if (httpFlushWrite(http
) < 0)
4904 http_set_length(http
);
4905 httpClearFields(http
);
4908 * The Kerberos and AuthRef authentication strings can only be used once...
4911 if (http
->field_authorization
&& http
->authstring
&&
4912 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4913 !strncmp(http
->authstring
, "AuthRef", 7)))
4915 http
->_authstring
[0] = '\0';
4917 if (http
->authstring
!= http
->_authstring
)
4918 free(http
->authstring
);
4920 http
->authstring
= http
->_authstring
;
4928 # if defined(HAVE_CDSASSL)
4930 * 'http_set_credentials()' - Set the SSL/TLS credentials.
4933 static int /* O - Status of connection */
4934 http_set_credentials(http_t
*http
) /* I - Connection to server */
4936 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
4937 OSStatus error
= 0; /* Error code */
4938 http_tls_credentials_t credentials
= NULL
;
4939 /* TLS credentials */
4942 DEBUG_printf(("7http_set_credentials(%p)", http
));
4945 * Prefer connection specific credentials...
4948 if ((credentials
= http
->tls_credentials
) == NULL
)
4949 credentials
= cg
->tls_credentials
;
4952 * Otherwise root around in the user's keychain to see if one can be found...
4957 CFDictionaryRef query
; /* Query dictionary */
4958 CFTypeRef matches
= NULL
; /* Matching credentials */
4959 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
4960 CFTypeRef keys
[] = { kSecClass
,
4963 /* Keys for dictionary */
4964 CFTypeRef values
[] = { kSecClassCertificate
,
4967 /* Values for dictionary */
4970 * Get the names associated with the server.
4973 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
4975 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
4981 * Create a query which will return all identities that can sign and match
4982 * the passed in policy.
4985 query
= CFDictionaryCreate(NULL
,
4986 (const void**)(&keys
[0]),
4987 (const void**)(&values
[0]),
4988 sizeof(keys
) / sizeof(keys
[0]),
4989 &kCFTypeDictionaryKeyCallBacks
,
4990 &kCFTypeDictionaryValueCallBacks
);
4993 error
= SecItemCopyMatching(query
, &matches
);
4994 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
5003 CFRelease(dn_array
);
5008 error
= SSLSetCertificate(http
->tls
, credentials
);
5009 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
5013 DEBUG_puts("4http_set_credentials: No credentials to set.");
5017 # endif /* HAVE_CDSASSL */
5018 #endif /* HAVE_SSL */
5022 * 'http_set_length()' - Set the data_encoding and data_remaining values.
5025 static off_t
/* O - Remainder or -1 on error */
5026 http_set_length(http_t
*http
) /* I - Connection */
5028 off_t remaining
; /* Remainder */
5031 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
5032 http_states
[http
->state
+ 1]));
5034 if ((remaining
= httpGetLength2(http
)) >= 0)
5036 if (http
->mode
== _HTTP_MODE_SERVER
&&
5037 http
->state
!= HTTP_STATE_GET_SEND
&&
5038 http
->state
!= HTTP_STATE_PUT
&&
5039 http
->state
!= HTTP_STATE_POST
&&
5040 http
->state
!= HTTP_STATE_POST_SEND
)
5042 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
5046 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
5049 DEBUG_puts("1http_set_length: Setting data_encoding to "
5050 "HTTP_ENCODING_CHUNKED.");
5051 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
5055 DEBUG_puts("1http_set_length: Setting data_encoding to "
5056 "HTTP_ENCODING_LENGTH.");
5057 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
5060 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
5061 CUPS_LLCAST remaining
));
5062 http
->data_remaining
= remaining
;
5064 if (remaining
<= INT_MAX
)
5065 http
->_data_remaining
= remaining
;
5067 http
->_data_remaining
= INT_MAX
;
5074 * 'http_set_timeout()' - Set the socket timeout values.
5078 http_set_timeout(int fd
, /* I - File descriptor */
5079 double timeout
) /* I - Timeout in seconds */
5082 DWORD tv
= (DWORD
)(timeout
* 1000);
5083 /* Timeout in milliseconds */
5085 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&tv
, sizeof(tv
));
5086 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&tv
, sizeof(tv
));
5089 struct timeval tv
; /* Timeout in secs and usecs */
5091 tv
.tv_sec
= (int)timeout
;
5092 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
5094 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, &tv
, sizeof(tv
));
5095 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
5101 * 'http_set_wait()' - Set the default wait value for reads.
5105 http_set_wait(http_t
*http
) /* I - Connection to server */
5109 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5111 if (http
->wait_value
<= 0)
5112 http
->wait_value
= 60000;
5115 http
->wait_value
= 10000;
5121 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5124 static int /* O - 0 on success, -1 on failure */
5125 http_setup_ssl(http_t
*http
) /* I - Connection to server */
5127 _cups_globals_t
*cg
= _cupsGlobals();
5128 /* Pointer to library globals */
5129 char hostname
[256], /* Hostname */
5130 *hostptr
; /* Pointer into hostname */
5133 SSL_CTX
*context
; /* Context for encryption */
5134 BIO
*bio
; /* BIO data */
5135 const char *message
= NULL
;/* Error message */
5136 # elif defined(HAVE_GNUTLS)
5137 int status
; /* Status of handshake */
5138 gnutls_certificate_client_credentials
*credentials
;
5139 /* TLS credentials */
5140 # elif defined(HAVE_CDSASSL)
5141 OSStatus error
; /* Error code */
5142 const char *message
= NULL
;/* Error message */
5143 cups_array_t
*credentials
; /* Credentials array */
5144 cups_array_t
*names
; /* CUPS distinguished names */
5145 CFArrayRef dn_array
; /* CF distinguished names array */
5146 CFIndex count
; /* Number of credentials */
5147 CFDataRef data
; /* Certificate data */
5148 int i
; /* Looping var */
5149 http_credential_t
*credential
; /* Credential data */
5150 # elif defined(HAVE_SSPISSL)
5151 TCHAR username
[256]; /* Username returned from GetUserName() */
5152 TCHAR commonName
[256];/* Common name for certificate */
5153 DWORD dwSize
; /* 32 bit size */
5154 # endif /* HAVE_LIBSSL */
5157 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5160 * Get the hostname to use for SSL...
5163 if (httpAddrLocalhost(http
->hostaddr
))
5165 strlcpy(hostname
, "localhost", sizeof(hostname
));
5170 * Otherwise make sure the hostname we have does not end in a trailing dot.
5173 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5174 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5180 context
= SSL_CTX_new(SSLv23_client_method());
5182 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5184 bio
= BIO_new(_httpBIOMethods());
5185 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5187 http
->tls
= SSL_new(context
);
5188 SSL_set_bio(http
->tls
, bio
, bio
);
5190 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5191 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5192 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5194 if (SSL_connect(http
->tls
) != 1)
5196 unsigned long error
; /* Error code */
5198 while ((error
= ERR_get_error()) != 0)
5200 message
= ERR_error_string(error
, NULL
);
5201 DEBUG_printf(("8http_setup_ssl: %s", message
));
5204 SSL_CTX_free(context
);
5205 SSL_free(http
->tls
);
5209 http
->error
= WSAGetLastError();
5211 http
->error
= errno
;
5213 http
->status
= HTTP_ERROR
;
5216 message
= _("Unable to establish a secure connection to host.");
5218 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5223 # elif defined(HAVE_GNUTLS)
5224 credentials
= (gnutls_certificate_client_credentials
*)
5225 malloc(sizeof(gnutls_certificate_client_credentials
));
5226 if (credentials
== NULL
)
5228 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5230 http
->error
= errno
;
5231 http
->status
= HTTP_ERROR
;
5232 _cupsSetHTTPError(HTTP_ERROR
);
5237 gnutls_certificate_allocate_credentials(credentials
);
5239 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5240 gnutls_set_default_priority(http
->tls
);
5241 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5243 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5244 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5245 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5246 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5248 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5250 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5251 status
, gnutls_strerror(status
)));
5253 if (gnutls_error_is_fatal(status
))
5256 http
->status
= HTTP_ERROR
;
5258 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
5260 gnutls_deinit(http
->tls
);
5261 gnutls_certificate_free_credentials(*credentials
);
5269 http
->tls_credentials
= credentials
;
5271 # elif defined(HAVE_CDSASSL)
5272 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, kSSLClientSide
,
5273 kSSLStreamType
)) == NULL
)
5275 DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
5276 http
->error
= errno
= ENOMEM
;
5277 http
->status
= HTTP_ERROR
;
5278 _cupsSetHTTPError(HTTP_ERROR
);
5283 error
= SSLSetConnection(http
->tls
, http
);
5284 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5288 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5289 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5294 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
5296 DEBUG_printf(("4http_setup_ssl: SSLSetSessionOption, error=%d",
5302 if (cg
->client_cert_cb
)
5304 error
= SSLSetSessionOption(http
->tls
,
5305 kSSLSessionOptionBreakOnCertRequested
, true);
5306 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5307 "error=%d", (int)error
));
5311 error
= http_set_credentials(http
);
5312 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5318 * Let the server know which hostname/domain we are trying to connect to
5319 * in case it wants to serve up a certificate with a matching common name.
5324 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5326 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5332 int done
= 0; /* Are we done yet? */
5334 while (!error
&& !done
)
5336 error
= SSLHandshake(http
->tls
);
5338 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5346 case errSSLWouldBlock
:
5347 error
= noErr
; /* Force a retry */
5348 usleep(1000); /* in 1 millisecond */
5351 case errSSLServerAuthCompleted
:
5353 if (cg
->server_cert_cb
)
5355 error
= httpCopyCredentials(http
, &credentials
);
5358 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5359 cg
->server_cert_data
);
5360 httpFreeCredentials(credentials
);
5363 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5364 "returned %d.", (int)error
));
5368 case errSSLClientCertRequested
:
5371 if (cg
->client_cert_cb
)
5374 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5377 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5379 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5381 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5383 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5385 credential
->datalen
= CFDataGetLength(data
);
5386 if ((credential
->data
= malloc(credential
->datalen
)))
5388 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5389 credential
->datalen
);
5390 cupsArrayAdd(names
, credential
);
5398 CFRelease(dn_array
);
5403 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5404 cg
->client_cert_data
);
5406 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5407 "returned %d.", (int)error
));
5410 httpFreeCredentials(names
);
5414 case errSSLUnknownRootCert
:
5415 message
= _("Unable to establish a secure connection to host "
5416 "(untrusted certificate).");
5419 case errSSLNoRootCert
:
5420 message
= _("Unable to establish a secure connection to host "
5421 "(self-signed certificate).");
5424 case errSSLCertExpired
:
5425 message
= _("Unable to establish a secure connection to host "
5426 "(expired certificate).");
5429 case errSSLCertNotYetValid
:
5430 message
= _("Unable to establish a secure connection to host "
5431 "(certificate not yet valid).");
5434 case errSSLHostNameMismatch
:
5435 message
= _("Unable to establish a secure connection to host "
5436 "(host name mismatch).");
5439 case errSSLXCertChainInvalid
:
5440 message
= _("Unable to establish a secure connection to host "
5441 "(certificate chain invalid).");
5444 case errSSLConnectionRefused
:
5445 message
= _("Unable to establish a secure connection to host "
5446 "(peer dropped connection before responding).");
5457 http
->error
= error
;
5458 http
->status
= HTTP_ERROR
;
5459 errno
= ECONNREFUSED
;
5461 CFRelease(http
->tls
);
5465 * If an error string wasn't set by the callbacks use a generic one...
5469 #ifdef HAVE_CSSMERRORSTRING
5470 message
= cssmErrorString(error
);
5472 message
= _("Unable to establish a secure connection to host.");
5473 #endif /* HAVE_CSSMERRORSTRING */
5475 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5480 # elif defined(HAVE_SSPISSL)
5481 http
->tls
= _sspiAlloc();
5485 _cupsSetHTTPError(HTTP_ERROR
);
5489 http
->tls
->sock
= http
->fd
;
5490 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5491 GetUserName(username
, &dwSize
);
5492 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5493 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5495 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5498 _sspiFree(http
->tls_credentials
);
5499 http
->tls_credentials
= NULL
;
5502 http
->status
= HTTP_ERROR
;
5504 _cupsSetError(IPP_PKI_ERROR
,
5505 _("Unable to establish a secure connection to host."), 1);
5510 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
5511 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5513 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5515 _sspiFree(http
->tls_credentials
);
5516 http
->tls_credentials
= NULL
;
5519 http
->status
= HTTP_ERROR
;
5521 _cupsSetError(IPP_PKI_ERROR
,
5522 _("Unable to establish a secure connection to host."), 1);
5526 # endif /* HAVE_CDSASSL */
5533 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5537 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
5540 SSL_CTX
*context
; /* Context for encryption */
5542 context
= SSL_get_SSL_CTX(http
->tls
);
5544 SSL_shutdown(http
->tls
);
5545 SSL_CTX_free(context
);
5546 SSL_free(http
->tls
);
5548 # elif defined(HAVE_GNUTLS)
5549 gnutls_certificate_client_credentials
*credentials
;
5550 /* TLS credentials */
5552 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5554 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5555 gnutls_deinit(http
->tls
);
5556 gnutls_certificate_free_credentials(*credentials
);
5559 # elif defined(HAVE_CDSASSL)
5560 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5563 CFRelease(http
->tls
);
5565 if (http
->tls_credentials
)
5566 CFRelease(http
->tls_credentials
);
5568 # elif defined(HAVE_SSPISSL)
5569 _sspiFree(http
->tls_credentials
);
5570 # endif /* HAVE_LIBSSL */
5573 http
->tls_credentials
= NULL
;
5575 #endif /* HAVE_SSL */
5580 * 'http_upgrade()' - Force upgrade to TLS encryption.
5583 static int /* O - Status of connection */
5584 http_upgrade(http_t
*http
) /* I - Connection to server */
5586 int ret
; /* Return value */
5587 http_t myhttp
; /* Local copy of HTTP data */
5590 DEBUG_printf(("7http_upgrade(%p)", http
));
5593 * Flush the connection to make sure any previous "Upgrade" message
5600 * Copy the HTTP data to a local variable so we can do the OPTIONS
5601 * request without interfering with the existing request data...
5604 memcpy(&myhttp
, http
, sizeof(myhttp
));
5607 * Send an OPTIONS request to the server, requiring SSL or TLS
5608 * encryption on the link...
5611 http
->field_authorization
= NULL
; /* Don't free the auth string */
5613 httpClearFields(http
);
5614 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5615 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5617 if ((ret
= httpOptions(http
, "*")) == 0)
5620 * Wait for the secure connection...
5623 while (httpUpdate(http
) == HTTP_CONTINUE
);
5627 * Restore the HTTP request data...
5630 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5631 http
->data_encoding
= myhttp
.data_encoding
;
5632 http
->data_remaining
= myhttp
.data_remaining
;
5633 http
->_data_remaining
= myhttp
._data_remaining
;
5634 http
->expect
= myhttp
.expect
;
5635 http
->field_authorization
= myhttp
.field_authorization
;
5636 http
->digest_tries
= myhttp
.digest_tries
;
5639 * See if we actually went secure...
5645 * Server does not support HTTP upgrade...
5648 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5651 closesocket(http
->fd
);
5663 #endif /* HAVE_SSL */
5667 * 'http_write()' - Write a buffer to a HTTP connection.
5670 static int /* O - Number of bytes written */
5671 http_write(http_t
*http
, /* I - Connection to server */
5672 const char *buffer
, /* I - Buffer for data */
5673 int length
) /* I - Number of bytes to write */
5675 int tbytes
, /* Total bytes sent */
5676 bytes
; /* Bytes sent */
5679 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
5686 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5688 if (http
->timeout_cb
)
5691 struct pollfd pfd
; /* Polled file descriptor */
5693 fd_set output_set
; /* Output ready for write? */
5694 struct timeval timeout
; /* Timeout value */
5695 #endif /* HAVE_POLL */
5696 int nfds
; /* Result from select()/poll() */
5702 pfd
.events
= POLLOUT
;
5704 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5705 (errno
== EINTR
|| errno
== EAGAIN
))
5711 FD_ZERO(&output_set
);
5712 FD_SET(http
->fd
, &output_set
);
5714 timeout
.tv_sec
= http
->wait_value
/ 1000;
5715 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5717 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5720 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5721 WSAGetLastError() == WSAEWOULDBLOCK
));
5723 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5725 #endif /* HAVE_POLL */
5729 http
->error
= errno
;
5732 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5735 http
->error
= WSAEWOULDBLOCK
;
5737 http
->error
= EWOULDBLOCK
;
5747 bytes
= http_write_ssl(http
, buffer
, length
);
5749 #endif /* HAVE_SSL */
5750 bytes
= send(http
->fd
, buffer
, length
, 0);
5752 DEBUG_printf(("3http_write: Write of %d bytes returned %d.", (int)length
,
5758 if (WSAGetLastError() == WSAEINTR
)
5760 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5762 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5765 http
->error
= WSAGetLastError();
5767 else if (WSAGetLastError() != http
->error
&&
5768 WSAGetLastError() != WSAECONNRESET
)
5770 http
->error
= WSAGetLastError();
5777 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5779 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5781 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5784 http
->error
= errno
;
5786 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5788 http
->error
= errno
;
5793 DEBUG_printf(("3http_write: error writing data (%s).",
5794 strerror(http
->error
)));
5805 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5808 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
5815 * 'http_write_chunk()' - Write a chunked buffer.
5818 static int /* O - Number bytes written */
5819 http_write_chunk(http_t
*http
, /* I - Connection to server */
5820 const char *buffer
, /* I - Buffer to write */
5821 int length
) /* I - Length of buffer */
5823 char header
[255]; /* Chunk header */
5824 int bytes
; /* Bytes written */
5827 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
5828 http
, buffer
, length
));
5831 * Write the chunk header, data, and trailer.
5834 sprintf(header
, "%x\r\n", length
);
5835 if (http_write(http
, header
, (int)strlen(header
)) < 0)
5837 DEBUG_puts("8http_write_chunk: http_write of length failed!");
5841 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5843 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
5847 if (http_write(http
, "\r\n", 2) < 0)
5849 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
5859 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5862 static int /* O - Bytes written */
5863 http_write_ssl(http_t
*http
, /* I - Connection to server */
5864 const char *buf
, /* I - Buffer holding data */
5865 int len
) /* I - Length of buffer */
5867 ssize_t result
; /* Return value */
5870 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5872 # if defined(HAVE_LIBSSL)
5873 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5875 # elif defined(HAVE_GNUTLS)
5876 result
= gnutls_record_send(http
->tls
, buf
, len
);
5878 if (result
< 0 && !errno
)
5881 * Convert GNU TLS error to errno value...
5886 case GNUTLS_E_INTERRUPTED
:
5890 case GNUTLS_E_AGAIN
:
5902 # elif defined(HAVE_CDSASSL)
5903 OSStatus error
; /* Error info */
5904 size_t processed
; /* Number of bytes processed */
5907 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5912 result
= (int)processed
;
5915 case errSSLWouldBlock
:
5917 result
= (int)processed
;
5925 case errSSLClosedGraceful
:
5928 result
= (int)processed
;
5936 # elif defined(HAVE_SSPISSL)
5937 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
5938 # endif /* HAVE_LIBSSL */
5940 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
5942 return ((int)result
);
5944 #endif /* HAVE_SSL */
5948 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".