2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for CUPS.
6 * Copyright 2007-2013 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 * _httpCreateCredentials() - Create credentials in the internal format.
41 * httpDelete() - Send a DELETE request to the server.
42 * _httpDisconnect() - Disconnect a HTTP connection.
43 * httpEncryption() - Set the required encryption on the link.
44 * httpError() - Get the last error on a connection.
45 * httpFlush() - Flush data from a HTTP connection.
46 * httpFlushWrite() - Flush data in write buffer.
47 * _httpFreeCredentials() - Free internal credentials.
48 * httpFreeCredentials() - Free an array of credentials.
49 * httpGet() - Send a GET request to the server.
50 * httpGetContentEncoding() - Get a common content encoding, if any,
51 * between the client and server.
52 * httpGetAuthString() - Get the current authorization string.
53 * httpGetBlocking() - Get the blocking/non-block state of a
55 * httpGetCookie() - Get any cookie data from the response.
56 * httpGetExpect() - Get the value of the Expect header, if any.
57 * httpGetFd() - Get the file descriptor associated with a
59 * httpGetField() - Get a field value from a request/response.
60 * httpGetLength() - Get the amount of data remaining from the
61 * content-length or transfer-encoding fields.
62 * httpGetLength2() - Get the amount of data remaining from the
63 * content-length or transfer-encoding fields.
64 * httpGets() - Get a line of text from a HTTP connection.
65 * httpGetState() - Get the current state of the HTTP request.
66 * httpGetStatus() - Get the status of the last HTTP request.
67 * httpGetSubField() - Get a sub-field value.
68 * httpGetSubField2() - Get a sub-field value.
69 * httpGetVersion() - Get the HTTP version at the other end.
70 * httpHead() - Send a HEAD request to the server.
71 * httpInitialize() - Initialize the HTTP interface library and
72 * set the default HTTP proxy (if any).
73 * httpOptions() - Send an OPTIONS request to the server.
74 * httpPeek() - Peek at data from a HTTP connection.
75 * httpPost() - Send a POST request to the server.
76 * httpPrintf() - Print a formatted string to a HTTP
78 * httpPut() - Send a PUT request to the server.
79 * httpRead() - Read data from a HTTP connection.
80 * httpRead2() - Read data from a HTTP connection.
81 * _httpReadCDSA() - Read function for the CDSA library.
82 * _httpReadGNUTLS() - Read function for the GNU TLS library.
83 * httpReadRequest() - Read a HTTP request from a connection.
84 * httpReconnect() - Reconnect to a HTTP server.
85 * httpReconnect2() - Reconnect to a HTTP server with timeout and
87 * httpSetAuthString() - Set the current authorization string.
88 * httpSetCredentials() - Set the credentials associated with an
89 * encrypted connection.
90 * httpSetCookie() - Set the cookie value(s).
91 * httpSetDefaultField() - Set the default value of an HTTP header.
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_create() - Create an unconnected HTTP connection.
121 * http_debug_hex() - Do a hex dump of a buffer.
122 * http_field() - Return the field index for a field name.
123 * http_read() - Read a buffer from a HTTP connection.
124 * http_read_buffered() - Do a buffered read from a HTTP connection.
125 * http_read_chunk() - Read a chunk from a HTTP connection.
126 * http_read_ssl() - Read from a SSL/TLS connection.
127 * http_send() - Send a request with all fields and the
128 * trailing blank line.
129 * http_set_credentials() - Set the SSL/TLS credentials.
130 * http_set_length() - Set the data_encoding and data_remaining
132 * http_set_timeout() - Set the socket timeout values.
133 * http_set_wait() - Set the default wait value for reads.
134 * http_setup_ssl() - Set up SSL/TLS support on a connection.
135 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
136 * http_upgrade() - Force upgrade to TLS encryption.
137 * http_write() - Write a buffer to a HTTP connection.
138 * http_write_chunk() - Write a chunked buffer.
139 * http_write_ssl() - Write to a SSL/TLS connection.
143 * Include necessary headers...
146 #include "cups-private.h"
153 # include <sys/time.h>
154 # include <sys/resource.h>
158 #endif /* HAVE_POLL */
166 static void http_content_coding_finish(http_t
*http
);
167 static void http_content_coding_start(http_t
*http
,
169 #endif /* HAVE_LIBZ */
170 static http_t
*http_create(const char *host
, int port
,
171 http_addrlist_t
*addrlist
, int family
,
172 http_encryption_t encryption
,
173 int blocking
, _http_mode_t mode
);
175 static void http_debug_hex(const char *prefix
, const char *buffer
,
178 static http_field_t
http_field(const char *name
);
179 static ssize_t
http_read(http_t
*http
, char *buffer
, size_t length
);
180 static ssize_t
http_read_buffered(http_t
*http
, char *buffer
, size_t length
);
181 static ssize_t
http_read_chunk(http_t
*http
, char *buffer
, size_t length
);
182 static int http_send(http_t
*http
, http_state_t request
,
184 static ssize_t
http_write(http_t
*http
, const char *buffer
,
186 static ssize_t
http_write_chunk(http_t
*http
, const char *buffer
,
189 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
191 static int http_set_credentials(http_t
*http
);
192 # endif /* HAVE_CDSASSL */
193 #endif /* HAVE_SSL */
194 static off_t
http_set_length(http_t
*http
);
195 static void http_set_timeout(int fd
, double timeout
);
196 static void http_set_wait(http_t
*http
);
198 static int http_setup_ssl(http_t
*http
);
199 static void http_shutdown_ssl(http_t
*http
);
200 static int http_upgrade(http_t
*http
);
201 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
202 #endif /* HAVE_SSL */
209 static const char * const http_fields
[] =
226 "If-Unmodified-since",
243 static const char * const http_states
[] =
246 "HTTP_STATE_WAITING",
247 "HTTP_STATE_OPTIONS",
249 "HTTP_STATE_GET_SEND",
252 "HTTP_STATE_POST_RECV",
253 "HTTP_STATE_POST_SEND",
255 "HTTP_STATE_PUT_RECV",
258 "HTTP_STATE_CONNECT",
260 "HTTP_STATE_UNKNOWN_METHOD",
261 "HTTP_STATE_UNKNOWN_VERSION"
266 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
268 * BIO methods for OpenSSL...
271 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
272 static int http_bio_read(BIO
*h
, char *buf
, int size
);
273 static int http_bio_puts(BIO
*h
, const char *str
);
274 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
275 static int http_bio_new(BIO
*h
);
276 static int http_bio_free(BIO
*data
);
278 static BIO_METHOD http_bio_methods
=
285 NULL
, /* http_bio_gets, */
291 #endif /* HAVE_SSL && HAVE_LIBSSL */
295 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
296 * specified listening socket.
301 http_t
* /* O - HTTP connection or @code NULL@ */
302 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
303 int blocking
) /* I - 1 if the connection should be
304 blocking, 0 otherwise */
306 http_t
*http
; /* HTTP connection */
307 http_addrlist_t addrlist
; /* Dummy address list */
308 socklen_t addrlen
; /* Length of address */
309 int val
; /* Socket option value */
313 * Range check input...
320 * Create the client connection...
323 memset(&addrlist
, 0, sizeof(addrlist
));
325 if ((http
= http_create(NULL
, 0, &addrlist
, AF_UNSPEC
,
326 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
327 _HTTP_MODE_SERVER
)) == NULL
)
331 * Accept the client and get the remote address...
334 addrlen
= sizeof(http_addr_t
);
336 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
339 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
345 httpAddrString(&(http
->addrlist
->addr
), http
->hostname
,
346 sizeof(http
->hostname
));
350 * Disable SIGPIPE for this socket.
354 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
355 #endif /* SO_NOSIGPIPE */
358 * Using TCP_NODELAY improves responsiveness, especially on systems
359 * with a slow loopback interface. Since we write large buffers
360 * when sending print files and requests, there shouldn't be any
361 * performance penalty for this...
365 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
369 * Close this socket when starting another process...
372 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
373 #endif /* FD_CLOEXEC */
380 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
382 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
384 * @since CUPS 1.5/OS X 10.7@
387 int /* O - 0 on success, -1 on error */
389 cups_array_t
*credentials
, /* I - Credentials array */
390 const void *data
, /* I - PEM-encoded X.509 data */
391 size_t datalen
) /* I - Length of data */
393 http_credential_t
*credential
; /* Credential data */
396 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
398 credential
->datalen
= datalen
;
400 if ((credential
->data
= malloc(datalen
)) != NULL
)
402 memcpy(credential
->data
, data
, datalen
);
403 cupsArrayAdd(credentials
, credential
);
414 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
416 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
419 BIO_METHOD
* /* O - BIO methods for OpenSSL */
420 _httpBIOMethods(void)
422 return (&http_bio_methods
);
424 #endif /* HAVE_SSL && HAVE_LIBSSL */
428 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
432 httpBlocking(http_t
*http
, /* I - Connection to server */
433 int b
) /* I - 1 = blocking, 0 = non-blocking */
444 * 'httpCheck()' - Check to see if there is a pending response from the server.
447 int /* O - 0 = no data, 1 = data available */
448 httpCheck(http_t
*http
) /* I - Connection to server */
450 return (httpWait(http
, 0));
455 * 'httpClearCookie()' - Clear the cookie value(s).
457 * @since CUPS 1.1.19/OS X 10.3@
461 httpClearCookie(http_t
*http
) /* I - Connection to server */
475 * 'httpClearFields()' - Clear HTTP request fields.
479 httpClearFields(http_t
*http
) /* I - Connection to server */
481 DEBUG_printf(("httpClearFields(http=%p)", http
));
485 memset(http
->fields
, 0, sizeof(http
->fields
));
487 if (http
->mode
== _HTTP_MODE_CLIENT
)
489 if (http
->hostname
[0] == '/')
490 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
492 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
495 if (http
->field_authorization
)
497 free(http
->field_authorization
);
498 http
->field_authorization
= NULL
;
501 if (http
->accept_encoding
)
503 _cupsStrFree(http
->accept_encoding
);
504 http
->accept_encoding
= NULL
;
509 _cupsStrFree(http
->allow
);
515 _cupsStrFree(http
->server
);
519 http
->expect
= (http_status_t
)0;
525 * 'httpClose()' - Close an HTTP connection.
529 httpClose(http_t
*http
) /* I - Connection to server */
532 OM_uint32 minor_status
; /* Minor status code */
533 #endif /* HAVE_GSSAPI */
536 DEBUG_printf(("httpClose(http=%p)", http
));
539 * Range check input...
546 * Close any open connection...
549 _httpDisconnect(http
);
552 * Free memory used...
555 httpAddrFreeList(http
->addrlist
);
561 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
562 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
564 if (http
->gssname
!= GSS_C_NO_NAME
)
565 gss_release_name(&minor_status
, &http
->gssname
);
566 #endif /* HAVE_GSSAPI */
568 #ifdef HAVE_AUTHORIZATION_H
570 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
571 #endif /* HAVE_AUTHORIZATION_H */
573 httpClearFields(http
);
575 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
576 free(http
->authstring
);
583 * 'httpConnect()' - Connect to a HTTP server.
585 * This function is deprecated - use @link httpConnect2@ instead.
590 http_t
* /* O - New HTTP connection */
591 httpConnect(const char *host
, /* I - Host to connect to */
592 int port
) /* I - Port number */
594 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, HTTP_ENCRYPT_IF_REQUESTED
,
600 * 'httpConnect2()' - Connect to a HTTP server.
605 http_t
* /* O - New HTTP connection */
607 const char *host
, /* I - Host to connect to */
608 int port
, /* I - Port number */
609 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
610 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
611 http_encryption_t encryption
, /* I - Type of encryption to use */
612 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
613 int msec
, /* I - Connection timeout in milliseconds, 0 means don't connect */
614 int *cancel
) /* I - Pointer to "cancel" variable */
616 http_t
*http
; /* New HTTP connection */
619 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
620 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
621 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
624 * Create the HTTP structure...
627 if ((http
= http_create(host
, port
, addrlist
, family
, encryption
, blocking
,
628 _HTTP_MODE_CLIENT
)) == NULL
)
632 * Optionally connect to the remote system...
635 if (msec
== 0 || !httpReconnect2(http
, msec
, cancel
))
639 * Could not connect to any known address - bail out!
649 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
651 * This function is now deprecated. Please use the @link httpConnect2@ function
657 http_t
* /* O - New HTTP connection */
659 const char *host
, /* I - Host to connect to */
660 int port
, /* I - Port number */
661 http_encryption_t encryption
) /* I - Type of encryption to use */
663 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
664 host
, port
, encryption
));
666 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
672 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
675 * @since CUPS 1.5/OS X 10.7@
678 int /* O - Status of call (0 = success) */
680 http_t
*http
, /* I - Connection to server */
681 cups_array_t
**credentials
) /* O - Array of credentials */
684 # elif defined(HAVE_GNUTLS)
685 # elif defined(HAVE_CDSASSL)
686 OSStatus error
; /* Error code */
687 SecTrustRef peerTrust
; /* Peer trust reference */
688 CFIndex count
; /* Number of credentials */
689 SecCertificateRef secCert
; /* Certificate reference */
690 CFDataRef data
; /* Certificate data */
691 int i
; /* Looping var */
692 # elif defined(HAVE_SSPISSL)
693 # endif /* HAVE_LIBSSL */
699 if (!http
|| !http
->tls
|| !credentials
)
705 # elif defined(HAVE_GNUTLS)
708 # elif defined(HAVE_CDSASSL)
709 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
711 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
713 count
= SecTrustGetCertificateCount(peerTrust
);
715 for (i
= 0; i
< count
; i
++)
717 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
718 if ((data
= SecCertificateCopyData(secCert
)))
720 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
721 CFDataGetLength(data
));
727 CFRelease(peerTrust
);
732 # elif defined(HAVE_SSPISSL)
737 # endif /* HAVE_LIBSSL */
742 * '_httpCreateCredentials()' - Create credentials in the internal format.
745 http_tls_credentials_t
/* O - Internal credentials */
746 _httpCreateCredentials(
747 cups_array_t
*credentials
) /* I - Array of credentials */
755 # elif defined(HAVE_GNUTLS)
758 # elif defined(HAVE_CDSASSL)
759 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
760 SecCertificateRef secCert
; /* Certificate reference */
761 CFDataRef data
; /* Credential data reference */
762 http_credential_t
*credential
; /* Credential data */
765 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
766 cupsArrayCount(credentials
),
767 &kCFTypeArrayCallBacks
)) == NULL
)
770 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
772 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
774 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
775 credential
->datalen
)))
777 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
780 CFArrayAppendValue(peerCerts
, secCert
);
790 # elif defined(HAVE_SSPISSL)
795 # endif /* HAVE_LIBSSL */
800 * 'httpDelete()' - Send a DELETE request to the server.
803 int /* O - Status of call (0 = success) */
804 httpDelete(http_t
*http
, /* I - Connection to server */
805 const char *uri
) /* I - URI to delete */
807 return (http_send(http
, HTTP_DELETE
, uri
));
812 * '_httpDisconnect()' - Disconnect a HTTP connection.
816 _httpDisconnect(http_t
*http
) /* I - Connection to server */
820 http_shutdown_ssl(http
);
821 #endif /* HAVE_SSL */
824 closesocket(http
->fd
);
834 * 'httpEncryption()' - Set the required encryption on the link.
837 int /* O - -1 on error, 0 on success */
838 httpEncryption(http_t
*http
, /* I - Connection to server */
839 http_encryption_t e
) /* I - New encryption preference */
841 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
847 http
->encryption
= e
;
849 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
850 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
851 return (httpReconnect(http
));
852 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
853 return (http_upgrade(http
));
857 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
861 #endif /* HAVE_SSL */
866 * 'httpError()' - Get the last error on a connection.
869 int /* O - Error code (errno) value */
870 httpError(http_t
*http
) /* I - Connection to server */
873 return (http
->error
);
880 * 'httpFlush()' - Flush data from a HTTP connection.
884 httpFlush(http_t
*http
) /* I - Connection to server */
886 char buffer
[8192]; /* Junk buffer */
887 int blocking
; /* To block or not to block */
888 http_state_t oldstate
; /* Old state */
891 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
892 http_states
[http
->state
+ 1]));
895 * Nothing to do if we are in the "waiting" state...
898 if (http
->state
== HTTP_STATE_WAITING
)
902 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
905 blocking
= http
->blocking
;
909 * Read any data we can...
912 oldstate
= http
->state
;
913 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
916 * Restore blocking and reset the connection if we didn't get all of
917 * the remaining data...
920 http
->blocking
= blocking
;
922 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
926 * Didn't get the data back, so close the current connection.
931 http_content_coding_finish(http
);
932 #endif /* HAVE_LIBZ */
934 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
936 http
->state
= HTTP_STATE_WAITING
;
940 http_shutdown_ssl(http
);
941 #endif /* HAVE_SSL */
944 closesocket(http
->fd
);
955 * 'httpFlushWrite()' - Flush data in write buffer.
957 * @since CUPS 1.2/OS X 10.5@
960 int /* O - Bytes written or -1 on error */
961 httpFlushWrite(http_t
*http
) /* I - Connection to server */
963 int bytes
; /* Bytes written */
966 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
967 http
? http
->data_encoding
: -1));
969 if (!http
|| !http
->wused
)
971 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
972 "1httpFlushWrite: No connection.");
976 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
977 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
980 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
982 if (bytes
> 0 && http
->data_encoding
== HTTP_ENCODING_LENGTH
)
984 http
->data_remaining
-= bytes
;
986 if (http
->data_remaining
<= 0)
994 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
1001 * '_httpFreeCredentials()' - Free internal credentials.
1005 _httpFreeCredentials(
1006 http_tls_credentials_t credentials
) /* I - Internal credentials */
1014 #elif defined(HAVE_GNUTLS)
1017 #elif defined(HAVE_CDSASSL)
1018 CFRelease(credentials
);
1020 #elif defined(HAVE_SSPISSL)
1023 #endif /* HAVE_LIBSSL */
1028 * 'httpFreeCredentials()' - Free an array of credentials.
1032 httpFreeCredentials(
1033 cups_array_t
*credentials
) /* I - Array of credentials */
1035 http_credential_t
*credential
; /* Credential */
1038 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
1040 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
1042 cupsArrayRemove(credentials
, credential
);
1043 free((void *)credential
->data
);
1047 cupsArrayDelete(credentials
);
1052 * 'httpGet()' - Send a GET request to the server.
1055 int /* O - Status of call (0 = success) */
1056 httpGet(http_t
*http
, /* I - Connection to server */
1057 const char *uri
) /* I - URI to get */
1059 return (http_send(http
, HTTP_GET
, uri
));
1064 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
1065 * the client and server.
1067 * This function uses the value of the Accepts-Encoding HTTP header and must be
1068 * called after receiving a response from the server or a request from the
1069 * client. The value returned can be use in subsequent requests (for clients)
1070 * or in the response (for servers) in order to compress the content stream.
1075 const char * /* O - Content-Coding value or
1076 @code NULL@ for the identity
1078 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
1081 if (http
&& http
->accept_encoding
)
1083 int i
; /* Looping var */
1084 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
1085 *start
, /* Start of coding value */
1086 *end
; /* End of coding value */
1087 double qvalue
; /* "qvalue" for coding */
1088 struct lconv
*loc
= localeconv(); /* Locale data */
1089 static const char * const codings
[] =
1090 { /* Supported content codings */
1097 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
1099 for (start
= temp
; *start
; start
= end
)
1102 * Find the end of the coding name...
1107 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
1113 * Grab the qvalue as needed...
1116 if (!strncmp(end
, ";q=", 3))
1117 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1120 * Skip past all attributes...
1124 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1130 while (*end
&& isspace(*end
& 255))
1134 * Check value if it matches something we support...
1140 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1141 if (!strcmp(start
, codings
[i
]))
1142 return (codings
[i
]);
1145 #endif /* HAVE_LIBZ */
1152 * 'httpGetAuthString()' - Get the current authorization string.
1154 * The authorization string is set by cupsDoAuthentication() and
1155 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
1156 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
1159 * @since CUPS 1.3/OS X 10.5@
1162 char * /* O - Authorization string */
1163 httpGetAuthString(http_t
*http
) /* I - Connection to server */
1166 return (http
->authstring
);
1173 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
1175 * @since CUPS 1.2/OS X 10.5@
1178 int /* O - 1 if blocking, 0 if non-blocking */
1179 httpGetBlocking(http_t
*http
) /* I - Connection to server */
1181 return (http
? http
->blocking
: 0);
1186 * 'httpGetCookie()' - Get any cookie data from the response.
1188 * @since CUPS 1.1.19/OS X 10.3@
1191 const char * /* O - Cookie data or NULL */
1192 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1194 return (http
? http
->cookie
: NULL
);
1199 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1201 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1202 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1207 http_status_t
/* O - Expect: status, if any */
1208 httpGetExpect(http_t
*http
) /* I - Connection to client */
1211 return (HTTP_STATUS_ERROR
);
1213 return (http
->expect
);
1218 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1220 * @since CUPS 1.2/OS X 10.5@
1223 int /* O - File descriptor or -1 if none */
1224 httpGetFd(http_t
*http
) /* I - Connection to server */
1226 return (http
? http
->fd
: -1);
1231 * 'httpGetField()' - Get a field value from a request/response.
1234 const char * /* O - Field value */
1235 httpGetField(http_t
*http
, /* I - Connection to server */
1236 http_field_t field
) /* I - Field to get */
1238 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1243 case HTTP_FIELD_ACCEPT_ENCODING
:
1244 return (http
->accept_encoding
);
1246 case HTTP_FIELD_ALLOW
:
1247 return (http
->allow
);
1249 case HTTP_FIELD_SERVER
:
1250 return (http
->server
);
1252 case HTTP_FIELD_AUTHORIZATION
:
1253 if (http
->field_authorization
)
1256 * Special case for WWW-Authenticate: as its contents can be
1257 * longer than HTTP_MAX_VALUE...
1260 return (http
->field_authorization
);
1264 return (http
->fields
[field
]);
1270 * 'httpGetLength()' - Get the amount of data remaining from the
1271 * content-length or transfer-encoding fields.
1273 * This function is deprecated and will not return lengths larger than
1274 * 2^31 - 1; use httpGetLength2() instead.
1279 int /* O - Content length */
1280 httpGetLength(http_t
*http
) /* I - Connection to server */
1283 * Get the read content length and return the 32-bit value.
1288 httpGetLength2(http
);
1290 return (http
->_data_remaining
);
1298 * 'httpGetLength2()' - Get the amount of data remaining from the
1299 * content-length or transfer-encoding fields.
1301 * This function returns the complete content length, even for
1302 * content larger than 2^31 - 1.
1304 * @since CUPS 1.2/OS X 10.5@
1307 off_t
/* O - Content length */
1308 httpGetLength2(http_t
*http
) /* I - Connection to server */
1310 off_t remaining
; /* Remaining length */
1313 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1314 http_states
[http
->state
+ 1]));
1319 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1321 DEBUG_puts("4httpGetLength2: chunked request!");
1327 * The following is a hack for HTTP servers that don't send a
1328 * Content-Length or Transfer-Encoding field...
1330 * If there is no Content-Length then the connection must close
1331 * after the transfer is complete...
1334 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1337 * Default content length is 0 for errors and certain types of operations,
1338 * and 2^31-1 for other successful requests...
1341 if (http
->status
>= HTTP_MULTIPLE_CHOICES
||
1342 http
->state
== HTTP_STATE_OPTIONS
||
1343 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1344 http
->state
== HTTP_STATE_HEAD
||
1345 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1346 http
->state
== HTTP_STATE_DELETE
||
1347 http
->state
== HTTP_STATE_TRACE
||
1348 http
->state
== HTTP_STATE_CONNECT
)
1351 remaining
= 2147483647;
1353 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1357 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1358 CUPS_LLCAST remaining
));
1366 * 'httpGets()' - Get a line of text from a HTTP connection.
1369 char * /* O - Line or NULL */
1370 httpGets(char *line
, /* I - Line to read into */
1371 int length
, /* I - Max length of buffer */
1372 http_t
*http
) /* I - Connection to server */
1374 char *lineptr
, /* Pointer into line */
1375 *lineend
, /* End of line */
1376 *bufptr
, /* Pointer into input buffer */
1377 *bufend
; /* Pointer to end of buffer */
1378 int bytes
, /* Number of bytes read */
1379 eol
; /* End-of-line? */
1382 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1384 if (!http
|| !line
|| length
<= 1)
1388 * Read a line from the buffer...
1393 lineend
= line
+ length
- 1;
1396 while (lineptr
< lineend
)
1399 * Pre-load the buffer as needed...
1408 while (http
->used
== 0)
1411 * No newline; see if there is more data to be read...
1414 while (!_httpWait(http
, http
->wait_value
, 1))
1416 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1419 DEBUG_puts("3httpGets: Timed out!");
1421 http
->error
= WSAETIMEDOUT
;
1423 http
->error
= ETIMEDOUT
;
1428 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1429 HTTP_MAX_BUFFER
- http
->used
);
1431 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1436 * Nope, can't get a line this time...
1440 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1442 if (WSAGetLastError() == WSAEINTR
)
1444 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1446 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1449 http
->error
= WSAGetLastError();
1451 else if (WSAGetLastError() != http
->error
)
1453 http
->error
= WSAGetLastError();
1458 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1462 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1464 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1466 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1469 http
->error
= errno
;
1471 else if (errno
!= http
->error
)
1473 http
->error
= errno
;
1480 else if (bytes
== 0)
1482 http
->error
= EPIPE
;
1488 * Yup, update the amount used...
1491 http
->used
+= bytes
;
1495 * Now copy as much of the current line as possible...
1498 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1499 lineptr
< lineend
&& bufptr
< bufend
;)
1501 if (*bufptr
== 0x0a)
1507 else if (*bufptr
== 0x0d)
1510 *lineptr
++ = *bufptr
++;
1513 http
->used
-= (int)(bufptr
- http
->buffer
);
1515 memmove(http
->buffer
, bufptr
, http
->used
);
1523 http
->activity
= time(NULL
);
1527 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1533 DEBUG_puts("3httpGets: No new line available!");
1540 * 'httpGetState()' - Get the current state of the HTTP request.
1543 http_state_t
/* O - HTTP state */
1544 httpGetState(http_t
*http
) /* I - Connection to server */
1546 return (http
? http
->state
: HTTP_STATE_ERROR
);
1551 * 'httpGetStatus()' - Get the status of the last HTTP request.
1553 * @since CUPS 1.2/OS X 10.5@
1556 http_status_t
/* O - HTTP status */
1557 httpGetStatus(http_t
*http
) /* I - Connection to server */
1559 return (http
? http
->status
: HTTP_ERROR
);
1564 * 'httpGetSubField()' - Get a sub-field value.
1569 char * /* O - Value or NULL */
1570 httpGetSubField(http_t
*http
, /* I - Connection to server */
1571 http_field_t field
, /* I - Field index */
1572 const char *name
, /* I - Name of sub-field */
1573 char *value
) /* O - Value string */
1575 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1580 * 'httpGetSubField2()' - Get a sub-field value.
1582 * @since CUPS 1.2/OS X 10.5@
1585 char * /* O - Value or NULL */
1586 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1587 http_field_t field
, /* I - Field index */
1588 const char *name
, /* I - Name of sub-field */
1589 char *value
, /* O - Value string */
1590 int valuelen
) /* I - Size of value buffer */
1592 const char *fptr
; /* Pointer into field */
1593 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1594 *ptr
, /* Pointer into string buffer */
1595 *end
; /* End of value buffer */
1597 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1598 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1600 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1601 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1604 end
= value
+ valuelen
- 1;
1606 for (fptr
= http
->fields
[field
]; *fptr
;)
1609 * Skip leading whitespace...
1612 while (_cups_isspace(*fptr
))
1622 * Get the sub-field name...
1626 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1627 ptr
< (temp
+ sizeof(temp
) - 1);
1632 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1635 * Skip trailing chars up to the '='...
1638 while (_cups_isspace(*fptr
))
1648 * Skip = and leading whitespace...
1653 while (_cups_isspace(*fptr
))
1659 * Read quoted string...
1662 for (ptr
= value
, fptr
++;
1663 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1668 while (*fptr
&& *fptr
!= '\"')
1677 * Read unquoted string...
1681 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1686 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1690 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1693 * See if this is the one...
1696 if (!strcmp(name
, temp
))
1698 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1705 DEBUG_puts("3httpGetSubField2: Returning NULL");
1712 * 'httpGetVersion()' - Get the HTTP version at the other end.
1715 http_version_t
/* O - Version number */
1716 httpGetVersion(http_t
*http
) /* I - Connection to server */
1718 return (http
? http
->version
: HTTP_VERSION_1_0
);
1723 * 'httpHead()' - Send a HEAD request to the server.
1726 int /* O - Status of call (0 = success) */
1727 httpHead(http_t
*http
, /* I - Connection to server */
1728 const char *uri
) /* I - URI for head */
1730 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1731 return (http_send(http
, HTTP_HEAD
, uri
));
1736 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1737 * default HTTP proxy (if any).
1741 httpInitialize(void)
1743 static int initialized
= 0; /* Have we been called before? */
1745 WSADATA winsockdata
; /* WinSock data */
1748 int i
; /* Looping var */
1749 unsigned char data
[1024]; /* Seed data */
1750 #endif /* HAVE_LIBSSL */
1756 _cupsGlobalUnlock();
1761 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1763 #elif !defined(SO_NOSIGPIPE)
1765 * Ignore SIGPIPE signals...
1769 sigset(SIGPIPE
, SIG_IGN
);
1771 # elif defined(HAVE_SIGACTION)
1772 struct sigaction action
; /* POSIX sigaction data */
1775 memset(&action
, 0, sizeof(action
));
1776 action
.sa_handler
= SIG_IGN
;
1777 sigaction(SIGPIPE
, &action
, NULL
);
1780 signal(SIGPIPE
, SIG_IGN
);
1781 # endif /* !SO_NOSIGPIPE */
1786 * Initialize GNU TLS...
1789 gnutls_global_init();
1791 #elif defined(HAVE_LIBSSL)
1793 * Initialize OpenSSL...
1796 SSL_load_error_strings();
1800 * Using the current time is a dubious random seed, but on some systems
1801 * it is the best we can do (on others, this seed isn't even used...)
1804 CUPS_SRAND(time(NULL
));
1806 for (i
= 0; i
< sizeof(data
); i
++)
1807 data
[i
] = CUPS_RAND();
1809 RAND_seed(data
, sizeof(data
));
1810 #endif /* HAVE_GNUTLS */
1813 _cupsGlobalUnlock();
1818 * 'httpOptions()' - Send an OPTIONS request to the server.
1821 int /* O - Status of call (0 = success) */
1822 httpOptions(http_t
*http
, /* I - Connection to server */
1823 const char *uri
) /* I - URI for options */
1825 return (http_send(http
, HTTP_OPTIONS
, uri
));
1830 * 'httpPeek()' - Peek at data from a HTTP connection.
1832 * This function copies available data from the given HTTP connection, reading
1833 * a buffer as needed. The data is still available for reading using
1834 * @link httpRead@ or @link httpRead2@.
1836 * For non-blocking connections the usual timeouts apply.
1841 ssize_t
/* O - Number of bytes copied */
1842 httpPeek(http_t
*http
, /* I - Connection to server */
1843 char *buffer
, /* I - Buffer for data */
1844 size_t length
) /* I - Maximum number of bytes */
1846 ssize_t bytes
; /* Bytes read */
1847 char len
[32]; /* Length string */
1850 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1851 http
, buffer
, CUPS_LLCAST length
));
1853 if (http
== NULL
|| buffer
== NULL
)
1856 http
->activity
= time(NULL
);
1862 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1863 http
->data_remaining
<= 0)
1865 DEBUG_puts("2httpPeek: Getting chunk length...");
1867 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1869 DEBUG_puts("1httpPeek: Could not get length!");
1875 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1876 if (!httpGets(len
, sizeof(len
), http
))
1878 DEBUG_puts("1httpPeek: Could not get chunk length.");
1883 http
->data_remaining
= strtoll(len
, NULL
, 16);
1885 if (http
->data_remaining
< 0)
1887 DEBUG_puts("1httpPeek: Negative chunk length!");
1892 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1893 CUPS_LLCAST http
->data_remaining
));
1895 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1898 * A zero-length chunk ends a transfer; unless we are reading POST
1904 http_content_coding_finish(http
);
1905 #endif /* HAVE_LIBZ */
1907 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1908 httpGets(len
, sizeof(len
), http
);
1910 if (http
->state
== HTTP_STATE_POST_RECV
)
1913 http
->state
= HTTP_STATE_WAITING
;
1915 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1916 http_states
[http
->state
+ 1]));
1919 * Prevent future reads for this request...
1922 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1926 else if (length
> (size_t)http
->data_remaining
)
1927 length
= (size_t)http
->data_remaining
;
1930 if (http
->used
== 0 &&
1931 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1933 if (http
->used
== 0)
1934 #endif /* HAVE_LIBZ */
1937 * Buffer small reads for better performance...
1940 ssize_t buflen
; /* Length of read for buffer */
1942 if (!http
->blocking
)
1944 while (!httpWait(http
, http
->wait_value
))
1946 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1953 if (http
->data_remaining
> sizeof(http
->buffer
))
1954 buflen
= sizeof(http
->buffer
);
1956 buflen
= http
->data_remaining
;
1958 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1959 bytes
= http_read(http
, http
->buffer
, buflen
);
1961 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1962 CUPS_LLCAST bytes
));
1966 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1976 # ifdef HAVE_INFLATECOPY
1977 int zerr
; /* Decompressor error */
1978 z_stream stream
; /* Copy of decompressor stream */
1980 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1982 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1983 /* Number of bytes to copy */
1985 if (http
->stream
.avail_in
> 0 &&
1986 http
->stream
.next_in
> http
->dbuffer
)
1987 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1989 http
->stream
.next_in
= http
->dbuffer
;
1991 if (buflen
> http
->data_remaining
)
1992 buflen
= http
->data_remaining
;
1994 if (buflen
> http
->used
)
1995 buflen
= http
->used
;
1997 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1998 "decompression buffer.", (int)buflen
));
2000 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
2001 http
->stream
.avail_in
+= buflen
;
2002 http
->used
-= buflen
;
2003 http
->data_remaining
-= buflen
;
2006 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
2009 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
2010 (int)http
->stream
.avail_in
));
2012 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
2014 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
2015 http
->error
= ENOMEM
;
2019 stream
.next_out
= (Bytef
*)buffer
;
2020 stream
.avail_out
= length
;
2022 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
2023 inflateEnd(&stream
);
2027 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
2029 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
2030 http
->stream
.avail_in
);
2037 bytes
= length
- http
->stream
.avail_out
;
2040 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
2041 "work with compressed streams.");
2043 # endif /* HAVE_INFLATECOPY */
2046 #endif /* HAVE_LIBZ */
2049 if (length
> (size_t)http
->used
)
2050 length
= (size_t)http
->used
;
2052 bytes
= (ssize_t
)length
;
2054 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
2057 memcpy(buffer
, http
->buffer
, length
);
2065 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2068 http
->error
= WSAGetLastError();
2070 if (errno
== EINTR
|| errno
== EAGAIN
)
2073 http
->error
= errno
;
2076 else if (bytes
== 0)
2078 http
->error
= EPIPE
;
2085 /* For OS X 10.8 and earlier */
2086 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
2087 { return (httpPeek(http
, buffer
, length
)); }
2091 * 'httpPost()' - Send a POST request to the server.
2094 int /* O - Status of call (0 = success) */
2095 httpPost(http_t
*http
, /* I - Connection to server */
2096 const char *uri
) /* I - URI for post */
2098 return (http_send(http
, HTTP_POST
, uri
));
2103 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
2108 int /* O - Number of bytes written */
2109 httpPrintf(http_t
*http
, /* I - Connection to server */
2110 const char *format
, /* I - printf-style format string */
2111 ...) /* I - Additional args as needed */
2113 int bytes
; /* Number of bytes to write */
2114 char buf
[16384]; /* Buffer for formatted string */
2115 va_list ap
; /* Variable argument pointer */
2118 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
2120 va_start(ap
, format
);
2121 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
2124 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
2126 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
2127 return (httpWrite2(http
, buf
, bytes
));
2132 DEBUG_puts("4httpPrintf: flushing existing data...");
2134 if (httpFlushWrite(http
) < 0)
2138 return (http_write(http
, buf
, bytes
));
2144 * 'httpPut()' - Send a PUT request to the server.
2147 int /* O - Status of call (0 = success) */
2148 httpPut(http_t
*http
, /* I - Connection to server */
2149 const char *uri
) /* I - URI to put */
2151 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2152 return (http_send(http
, HTTP_PUT
, uri
));
2157 * 'httpRead()' - Read data from a HTTP connection.
2159 * This function is deprecated. Use the httpRead2() function which can
2160 * read more than 2GB of data.
2165 int /* O - Number of bytes read */
2166 httpRead(http_t
*http
, /* I - Connection to server */
2167 char *buffer
, /* I - Buffer for data */
2168 int length
) /* I - Maximum number of bytes */
2170 return ((int)httpRead2(http
, buffer
, length
));
2175 * 'httpRead2()' - Read data from a HTTP connection.
2177 * @since CUPS 1.2/OS X 10.5@
2180 ssize_t
/* O - Number of bytes read */
2181 httpRead2(http_t
*http
, /* I - Connection to server */
2182 char *buffer
, /* I - Buffer for data */
2183 size_t length
) /* I - Maximum number of bytes */
2185 ssize_t bytes
; /* Bytes read */
2189 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2190 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
2191 http
, buffer
, CUPS_LLCAST length
,
2193 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2195 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2196 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
2197 http
, buffer
, CUPS_LLCAST length
,
2198 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2199 #endif /* HAVE_LIBZ */
2201 if (http
== NULL
|| buffer
== NULL
)
2204 http
->activity
= time(NULL
);
2215 if (http
->stream
.avail_in
> 0)
2217 int zerr
; /* Decompressor error */
2219 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2220 (int)http
->stream
.avail_in
, (int)length
));
2222 http
->stream
.next_out
= (Bytef
*)buffer
;
2223 http
->stream
.avail_out
= length
;
2225 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2227 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2229 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2230 http
->stream
.avail_in
);
2237 bytes
= length
- http
->stream
.avail_out
;
2239 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2240 http
->stream
.avail_in
, http
->stream
.avail_out
,
2248 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2249 /* Additional bytes for buffer */
2253 if (http
->stream
.avail_in
> 0 &&
2254 http
->stream
.next_in
> http
->dbuffer
)
2255 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2257 http
->stream
.next_in
= http
->dbuffer
;
2259 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2260 "decompression buffer.", (int)buflen
));
2262 if (http
->data_remaining
> 0)
2264 if (buflen
> http
->data_remaining
)
2265 buflen
= http
->data_remaining
;
2267 bytes
= http_read_buffered(http
,
2268 (char *)http
->dbuffer
+
2269 http
->stream
.avail_in
, buflen
);
2271 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2272 bytes
= http_read_chunk(http
,
2273 (char *)http
->dbuffer
+
2274 http
->stream
.avail_in
, buflen
);
2280 else if (bytes
== 0)
2283 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2284 "decompression buffer.", CUPS_LLCAST bytes
));
2286 http
->data_remaining
-= bytes
;
2287 http
->stream
.avail_in
+= bytes
;
2298 #endif /* HAVE_LIBZ */
2299 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2301 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2302 http
->data_remaining
-= bytes
;
2304 else if (http
->data_remaining
<= 0)
2307 * No more data to read...
2314 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2317 if (length
> (size_t)http
->data_remaining
)
2318 length
= (size_t)http
->data_remaining
;
2320 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2321 http
->data_remaining
-= bytes
;
2326 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2327 #endif /* HAVE_LIBZ */
2328 ((http
->data_remaining
<= 0 &&
2329 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2330 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2334 http_content_coding_finish(http
);
2335 #endif /* HAVE_LIBZ */
2337 if (http
->state
== HTTP_STATE_POST_RECV
)
2340 http
->state
= HTTP_STATE_WAITING
;
2342 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2343 http_states
[http
->state
+ 1]));
2350 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2352 * '_httpReadCDSA()' - Read function for the CDSA library.
2355 OSStatus
/* O - -1 on error, 0 on success */
2357 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2358 void *data
, /* I - Data buffer */
2359 size_t *dataLength
) /* IO - Number of bytes */
2361 OSStatus result
; /* Return value */
2362 ssize_t bytes
; /* Number of bytes read */
2363 http_t
*http
; /* HTTP connection */
2366 http
= (http_t
*)connection
;
2368 if (!http
->blocking
)
2371 * Make sure we have data before we read...
2374 while (!_httpWait(http
, http
->wait_value
, 0))
2376 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2379 http
->error
= ETIMEDOUT
;
2386 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2388 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2390 if (bytes
== *dataLength
)
2396 *dataLength
= bytes
;
2397 result
= errSSLWouldBlock
;
2404 result
= errSSLClosedGraceful
;
2405 else if (errno
== EAGAIN
)
2406 result
= errSSLWouldBlock
;
2408 result
= errSSLClosedAbort
;
2413 #endif /* HAVE_SSL && HAVE_CDSASSL */
2416 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2418 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2421 ssize_t
/* O - Number of bytes read or -1 on error */
2423 gnutls_transport_ptr ptr
, /* I - Connection to server */
2424 void *data
, /* I - Buffer */
2425 size_t length
) /* I - Number of bytes to read */
2427 http_t
*http
; /* HTTP connection */
2428 ssize_t bytes
; /* Bytes read */
2431 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2433 http
= (http_t
*)ptr
;
2435 if (!http
->blocking
)
2438 * Make sure we have data before we read...
2441 while (!_httpWait(http
, http
->wait_value
, 0))
2443 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2446 http
->error
= ETIMEDOUT
;
2451 bytes
= recv(http
->fd
, data
, length
, 0);
2452 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2455 #endif /* HAVE_SSL && HAVE_GNUTLS */
2459 * 'httpReadRequest()' - Read a HTTP request from a connection.
2464 http_state_t
/* O - New state of connection */
2465 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2466 char *uri
, /* I - URI buffer */
2467 size_t urilen
) /* I - Size of URI buffer */
2469 char line
[4096], /* HTTP request line */
2470 *req_method
, /* HTTP request method */
2471 *req_uri
, /* HTTP request URI */
2472 *req_version
; /* HTTP request version number string */
2476 * Range check input...
2479 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2480 http
, uri
, CUPS_LLCAST urilen
));
2485 if (!http
|| !uri
|| urilen
< 1)
2487 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2488 return (HTTP_STATE_ERROR
);
2490 else if (http
->state
!= HTTP_STATE_WAITING
)
2492 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2493 http_states
[http
->state
+ 1]));
2494 return (HTTP_STATE_ERROR
);
2501 httpClearFields(http
);
2503 http
->activity
= time(NULL
);
2504 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2505 http
->data_remaining
= 0;
2506 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2507 http
->status
= HTTP_STATUS_OK
;
2508 http
->version
= HTTP_VERSION_1_1
;
2511 * Read a line from the socket...
2514 if (!httpGets(line
, sizeof(line
), http
))
2516 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2517 return (HTTP_STATE_ERROR
);
2522 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2523 return (HTTP_STATE_WAITING
);
2526 DEBUG_printf(("1httpReadRequest: %s", line
));
2535 while (*req_uri
&& !isspace(*req_uri
& 255))
2540 DEBUG_puts("1httpReadRequest: No request URI.");
2541 return (HTTP_STATE_ERROR
);
2546 while (*req_uri
&& isspace(*req_uri
& 255))
2549 req_version
= req_uri
;
2551 while (*req_version
&& !isspace(*req_version
& 255))
2556 DEBUG_puts("1httpReadRequest: No request protocol version.");
2557 return (HTTP_STATE_ERROR
);
2560 *req_version
++ = '\0';
2562 while (*req_version
&& isspace(*req_version
& 255))
2569 if (!strcmp(req_method
, "OPTIONS"))
2570 http
->state
= HTTP_STATE_OPTIONS
;
2571 else if (!strcmp(req_method
, "GET"))
2572 http
->state
= HTTP_STATE_GET
;
2573 else if (!strcmp(req_method
, "HEAD"))
2574 http
->state
= HTTP_STATE_HEAD
;
2575 else if (!strcmp(req_method
, "POST"))
2576 http
->state
= HTTP_STATE_POST
;
2577 else if (!strcmp(req_method
, "PUT"))
2578 http
->state
= HTTP_STATE_PUT
;
2579 else if (!strcmp(req_method
, "DELETE"))
2580 http
->state
= HTTP_STATE_DELETE
;
2581 else if (!strcmp(req_method
, "TRACE"))
2582 http
->state
= HTTP_STATE_TRACE
;
2583 else if (!strcmp(req_method
, "CONNECT"))
2584 http
->state
= HTTP_STATE_CONNECT
;
2587 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2588 return (HTTP_STATE_UNKNOWN_METHOD
);
2591 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2592 http_states
[http
->state
+ 1]));
2594 if (!strcmp(req_version
, "HTTP/1.0"))
2596 http
->version
= HTTP_VERSION_1_0
;
2597 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2599 else if (!strcmp(req_version
, "HTTP/1.1"))
2601 http
->version
= HTTP_VERSION_1_1
;
2602 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2606 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2607 return (HTTP_STATE_UNKNOWN_VERSION
);
2610 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2611 strlcpy(uri
, req_uri
, urilen
);
2613 return (http
->state
);
2618 * 'httpReconnect()' - Reconnect to a HTTP server.
2620 * This function is deprecated. Please use the @link httpReconnect2@ function
2626 int /* O - 0 on success, non-zero on failure */
2627 httpReconnect(http_t
*http
) /* I - Connection to server */
2629 DEBUG_printf(("httpReconnect(http=%p)", http
));
2631 return (httpReconnect2(http
, 30000, NULL
));
2636 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2640 int /* O - 0 on success, non-zero on failure */
2641 httpReconnect2(http_t
*http
, /* I - Connection to server */
2642 int msec
, /* I - Timeout in milliseconds */
2643 int *cancel
) /* I - Pointer to "cancel" variable */
2645 http_addrlist_t
*addr
; /* Connected address */
2647 http_addrlist_t
*current
; /* Current address */
2648 char temp
[256]; /* Temporary address string */
2652 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2657 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
2664 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2665 http_shutdown_ssl(http
);
2667 #endif /* HAVE_SSL */
2670 * Close any previously open socket...
2675 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2678 closesocket(http
->fd
);
2687 * Reset all state (except fields, which may be reused)...
2690 http
->state
= HTTP_STATE_WAITING
;
2691 http
->status
= HTTP_STATUS_CONTINUE
;
2692 http
->version
= HTTP_VERSION_1_1
;
2693 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2694 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2695 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2696 http
->_data_remaining
= 0;
2699 http
->data_remaining
= 0;
2700 http
->hostaddr
= NULL
;
2704 * Connect to the server...
2708 for (current
= http
->addrlist
; current
; current
= current
->next
)
2709 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2710 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2711 httpAddrPort(&(current
->addr
))));
2714 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2718 * Unable to connect...
2722 http
->error
= WSAGetLastError();
2724 http
->error
= errno
;
2726 http
->status
= HTTP_ERROR
;
2728 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2729 strerror(http
->error
)));
2734 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2736 if (http
->timeout_value
> 0)
2737 http_set_timeout(http
->fd
, http
->timeout_value
);
2739 http
->hostaddr
= &(addr
->addr
);
2743 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2746 * Always do encryption via SSL.
2749 if (http_setup_ssl(http
) != 0)
2752 closesocket(http
->fd
);
2760 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2761 return (http_upgrade(http
));
2762 #endif /* HAVE_SSL */
2764 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2765 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2766 httpAddrPort(http
->hostaddr
)));
2773 * 'httpSetAuthString()' - Set the current authorization string.
2775 * This function just stores a copy of the current authorization string in
2776 * the HTTP connection object. You must still call httpSetField() to set
2777 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2778 * httpHead(), httpOptions(), httpPost, or httpPut().
2780 * @since CUPS 1.3/OS X 10.5@
2784 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2785 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2786 const char *data
) /* I - Auth data (NULL for none) */
2789 * Range check input...
2795 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2796 free(http
->authstring
);
2798 http
->authstring
= http
->_authstring
;
2803 * Set the current authorization string...
2806 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2809 if (len
> (int)sizeof(http
->_authstring
))
2811 if ((temp
= malloc(len
)) == NULL
)
2812 len
= sizeof(http
->_authstring
);
2814 http
->authstring
= temp
;
2818 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2820 strlcpy(http
->authstring
, scheme
, len
);
2825 * Clear the current authorization string...
2828 http
->_authstring
[0] = '\0';
2834 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2837 * @since CUPS 1.5/OS X 10.7@
2840 int /* O - Status of call (0 = success) */
2841 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2842 cups_array_t
*credentials
) /* I - Array of credentials */
2844 if (!http
|| cupsArrayCount(credentials
) < 1)
2847 _httpFreeCredentials(http
->tls_credentials
);
2849 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2851 return (http
->tls_credentials
? 0 : -1);
2856 * 'httpSetCookie()' - Set the cookie value(s).
2858 * @since CUPS 1.1.19/OS X 10.3@
2862 httpSetCookie(http_t
*http
, /* I - Connection */
2863 const char *cookie
) /* I - Cookie string */
2872 http
->cookie
= strdup(cookie
);
2874 http
->cookie
= NULL
;
2879 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2881 * Currently only HTTP_FIELD_ACCEPT_ENCODING, HTTP_FIELD_SERVER, and
2882 * HTTP_FIELD_USER_AGENT can be set.
2888 httpSetDefaultField(http_t
*http
, /* I - Connection to server */
2889 http_field_t field
, /* I - Field index */
2890 const char *value
)/* I - Value */
2892 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2893 http
, field
, http_fields
[field
], value
));
2900 case HTTP_FIELD_ACCEPT_ENCODING
:
2901 if (http
->default_accept_encoding
)
2902 _cupsStrFree(http
->default_accept_encoding
);
2904 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2907 case HTTP_FIELD_SERVER
:
2908 if (http
->default_server
)
2909 _cupsStrFree(http
->default_server
);
2911 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2914 case HTTP_FIELD_USER_AGENT
:
2915 if (http
->default_user_agent
)
2916 _cupsStrFree(http
->default_user_agent
);
2918 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2922 DEBUG_puts("1httpSetDefaultField: Ignored.");
2929 * 'httpSetExpect()' - Set the Expect: header in a request.
2931 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2934 * @since CUPS 1.2/OS X 10.5@
2938 httpSetExpect(http_t
*http
, /* I - Connection to server */
2939 http_status_t expect
) /* I - HTTP status to expect
2940 (@code HTTP_CONTINUE@) */
2943 http
->expect
= expect
;
2948 * 'httpSetField()' - Set the value of an HTTP header.
2952 httpSetField(http_t
*http
, /* I - Connection to server */
2953 http_field_t field
, /* I - Field index */
2954 const char *value
) /* I - Value */
2956 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2957 field
, http_fields
[field
], value
));
2960 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2961 field
>= HTTP_FIELD_MAX
||
2967 case HTTP_FIELD_ACCEPT_ENCODING
:
2968 if (http
->accept_encoding
)
2969 _cupsStrFree(http
->accept_encoding
);
2971 http
->accept_encoding
= _cupsStrAlloc(value
);
2974 case HTTP_FIELD_ALLOW
:
2976 _cupsStrFree(http
->allow
);
2978 http
->allow
= _cupsStrAlloc(value
);
2981 case HTTP_FIELD_SERVER
:
2983 _cupsStrFree(http
->server
);
2985 http
->server
= _cupsStrAlloc(value
);
2989 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2993 if (field
== HTTP_FIELD_AUTHORIZATION
)
2996 * Special case for Authorization: as its contents can be
2997 * longer than HTTP_MAX_VALUE
3000 if (http
->field_authorization
)
3001 free(http
->field_authorization
);
3003 http
->field_authorization
= strdup(value
);
3005 else if (field
== HTTP_FIELD_HOST
)
3008 * Special-case for Host: as we don't want a trailing "." on the hostname and
3009 * need to bracket IPv6 numeric addresses.
3012 char *ptr
= strchr(value
, ':');
3014 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
3017 * Bracket IPv6 numeric addresses...
3019 * This is slightly inefficient (basically copying twice), but is an edge
3020 * case and not worth optimizing...
3023 snprintf(http
->fields
[HTTP_FIELD_HOST
],
3024 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
3029 * Check for a trailing dot on the hostname...
3032 ptr
= http
->fields
[HTTP_FIELD_HOST
];
3036 ptr
+= strlen(ptr
) - 1;
3044 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
3045 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
3047 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
3048 http_content_coding_start(http
, value
);
3050 #endif /* HAVE_LIBZ */
3055 * 'httpSetLength()' - Set the content-length and content-encoding.
3057 * @since CUPS 1.2/OS X 10.5@
3061 httpSetLength(http_t
*http
, /* I - Connection to server */
3062 size_t length
) /* I - Length (0 for chunked) */
3064 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
3065 CUPS_LLCAST length
));
3072 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
3074 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
3078 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
3079 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
3080 CUPS_LLFMT
, CUPS_LLCAST length
);
3086 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
3088 * The optional timeout callback receives both the HTTP connection and a user
3089 * data pointer and must return 1 to continue or 0 to error (time) out.
3091 * @since CUPS 1.5/OS X 10.7@
3096 http_t
*http
, /* I - Connection to server */
3097 double timeout
, /* I - Number of seconds for timeout,
3098 must be greater than 0 */
3099 http_timeout_cb_t cb
, /* I - Callback function or NULL */
3100 void *user_data
) /* I - User data pointer */
3102 if (!http
|| timeout
<= 0.0)
3105 http
->timeout_cb
= cb
;
3106 http
->timeout_data
= user_data
;
3107 http
->timeout_value
= timeout
;
3110 http_set_timeout(http
->fd
, timeout
);
3112 http_set_wait(http
);
3117 * 'httpTrace()' - Send an TRACE request to the server.
3120 int /* O - Status of call (0 = success) */
3121 httpTrace(http_t
*http
, /* I - Connection to server */
3122 const char *uri
) /* I - URI for trace */
3124 return (http_send(http
, HTTP_TRACE
, uri
));
3129 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3131 * Note: Unlike httpUpdate(), this function does not flush pending write data
3132 * and only retrieves a single status line from the HTTP connection.
3135 int /* O - 1 to continue, 0 to stop */
3136 _httpUpdate(http_t
*http
, /* I - Connection to server */
3137 http_status_t
*status
) /* O - Current HTTP status */
3139 char line
[32768], /* Line from connection... */
3140 *value
; /* Pointer to value on line */
3141 http_field_t field
; /* Field index */
3142 int major
, minor
; /* HTTP version numbers */
3145 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3146 http_states
[http
->state
+ 1]));
3149 * Grab a single line from the connection...
3152 if (!httpGets(line
, sizeof(line
), http
))
3154 *status
= HTTP_ERROR
;
3158 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3160 if (line
[0] == '\0')
3163 * Blank line means the start of the data section (if any). Return
3164 * the result code, too...
3166 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3167 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3171 if (http
->status
== HTTP_STATUS_CONTINUE
)
3173 *status
= http
->status
;
3177 if (http
->status
< HTTP_BAD_REQUEST
)
3178 http
->digest_tries
= 0;
3181 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
3183 if (http_setup_ssl(http
) != 0)
3186 closesocket(http
->fd
);
3191 *status
= http
->status
= HTTP_ERROR
;
3195 *status
= HTTP_STATUS_CONTINUE
;
3198 #endif /* HAVE_SSL */
3200 if (http_set_length(http
) < 0)
3202 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3203 http
->error
= EINVAL
;
3204 http
->status
= *status
= HTTP_ERROR
;
3208 switch (http
->state
)
3210 case HTTP_STATE_GET
:
3211 case HTTP_STATE_POST
:
3212 case HTTP_STATE_POST_RECV
:
3213 case HTTP_STATE_PUT
:
3216 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3217 http_states
[http
->state
+ 1]));
3219 case HTTP_STATE_POST_SEND
:
3220 case HTTP_STATE_HEAD
:
3224 http
->state
= HTTP_STATE_WAITING
;
3226 DEBUG_puts("1_httpUpdate: Unknown state, reset state to "
3227 "HTTP_STATE_WAITING.");
3232 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3233 http_content_coding_start(http
,
3234 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3235 #endif /* HAVE_LIBZ */
3237 *status
= http
->status
;
3240 else if (!strncmp(line
, "HTTP/", 5))
3243 * Got the beginning of a response...
3246 int intstatus
; /* Status value as an integer */
3248 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3250 *status
= http
->status
= HTTP_ERROR
;
3254 httpClearFields(http
);
3256 http
->version
= (http_version_t
)(major
* 100 + minor
);
3257 *status
= http
->status
= (http_status_t
)intstatus
;
3259 else if ((value
= strchr(line
, ':')) != NULL
)
3266 while (_cups_isspace(*value
))
3269 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3272 * Be tolerants of servers that send unknown attribute fields...
3275 if (!_cups_strcasecmp(line
, "expect"))
3278 * "Expect: 100-continue" or similar...
3281 http
->expect
= (http_status_t
)atoi(value
);
3283 else if (!_cups_strcasecmp(line
, "cookie"))
3286 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3289 httpSetCookie(http
, value
);
3291 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
3292 httpSetField(http
, field
, value
);
3295 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3300 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3301 http
->error
= EINVAL
;
3302 http
->status
= *status
= HTTP_ERROR
;
3311 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3314 http_status_t
/* O - HTTP status */
3315 httpUpdate(http_t
*http
) /* I - Connection to server */
3317 http_status_t status
; /* Request status */
3320 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3321 http_states
[http
->state
+ 1]));
3324 * Flush pending data, if any...
3329 DEBUG_puts("2httpUpdate: flushing buffer...");
3331 if (httpFlushWrite(http
) < 0)
3332 return (HTTP_ERROR
);
3336 * If we haven't issued any commands, then there is nothing to "update"...
3339 if (http
->state
== HTTP_STATE_WAITING
)
3340 return (HTTP_CONTINUE
);
3343 * Grab all of the lines we can from the connection...
3346 while (_httpUpdate(http
, &status
));
3349 * See if there was an error...
3352 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
3354 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3355 return (http
->status
);
3360 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3361 strerror(http
->error
)));
3362 http
->status
= HTTP_ERROR
;
3363 return (HTTP_ERROR
);
3367 * Return the current status...
3375 * '_httpWait()' - Wait for data available on a connection (no flush).
3378 int /* O - 1 if data is available, 0 otherwise */
3379 _httpWait(http_t
*http
, /* I - Connection to server */
3380 int msec
, /* I - Milliseconds to wait */
3381 int usessl
) /* I - Use SSL context? */
3384 struct pollfd pfd
; /* Polled file descriptor */
3386 fd_set input_set
; /* select() input set */
3387 struct timeval timeout
; /* Timeout */
3388 #endif /* HAVE_POLL */
3389 int nfds
; /* Result from select()/poll() */
3392 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3396 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3401 * Check the SSL/TLS buffers for data first...
3405 if (http
->tls
&& usessl
)
3408 if (SSL_pending(http
->tls
))
3410 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3414 # elif defined(HAVE_GNUTLS)
3415 if (gnutls_record_check_pending(http
->tls
))
3417 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3421 # elif defined(HAVE_CDSASSL)
3422 size_t bytes
; /* Bytes that are available */
3424 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3427 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3430 # endif /* HAVE_LIBSSL */
3432 #endif /* HAVE_SSL */
3435 * Then try doing a select() or poll() to poll the socket...
3440 pfd
.events
= POLLIN
;
3444 nfds
= poll(&pfd
, 1, msec
);
3446 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3451 FD_ZERO(&input_set
);
3452 FD_SET(http
->fd
, &input_set
);
3454 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3458 timeout
.tv_sec
= msec
/ 1000;
3459 timeout
.tv_usec
= (msec
% 1000) * 1000;
3461 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3464 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3466 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3469 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3470 WSAGetLastError() == WSAEWOULDBLOCK
));
3472 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3474 #endif /* HAVE_POLL */
3476 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3484 * 'httpWait()' - Wait for data available on a connection.
3486 * @since CUPS 1.1.19/OS X 10.3@
3489 int /* O - 1 if data is available, 0 otherwise */
3490 httpWait(http_t
*http
, /* I - Connection to server */
3491 int msec
) /* I - Milliseconds to wait */
3494 * First see if there is data in the buffer...
3497 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3504 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3509 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3511 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3514 #endif /* HAVE_LIBZ */
3517 * Flush pending data, if any...
3522 DEBUG_puts("3httpWait: Flushing write buffer.");
3524 if (httpFlushWrite(http
) < 0)
3529 * If not, check the SSL/TLS buffers and do a select() on the connection...
3532 return (_httpWait(http
, msec
, 1));
3537 * 'httpWrite()' - Write data to a HTTP connection.
3539 * This function is deprecated. Use the httpWrite2() function which can
3540 * write more than 2GB of data.
3545 int /* O - Number of bytes written */
3546 httpWrite(http_t
*http
, /* I - Connection to server */
3547 const char *buffer
, /* I - Buffer for data */
3548 int length
) /* I - Number of bytes to write */
3550 return ((int)httpWrite2(http
, buffer
, length
));
3555 * 'httpWrite2()' - Write data to a HTTP connection.
3557 * @since CUPS 1.2/OS X 10.5@
3560 ssize_t
/* O - Number of bytes written */
3561 httpWrite2(http_t
*http
, /* I - Connection to server */
3562 const char *buffer
, /* I - Buffer for data */
3563 size_t length
) /* I - Number of bytes to write */
3565 ssize_t bytes
; /* Bytes written */
3568 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3569 buffer
, CUPS_LLCAST length
));
3572 * Range check input...
3575 if (!http
|| !buffer
)
3577 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3582 * Mark activity on the connection...
3585 http
->activity
= time(NULL
);
3588 * Buffer small writes for better performance...
3594 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3598 http_content_coding_finish(http
);
3603 http
->stream
.next_in
= (Bytef
*)buffer
;
3604 http
->stream
.avail_in
= length
;
3605 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3606 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3608 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3610 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3612 if (http
->stream
.avail_out
== 0)
3614 if (httpFlushWrite(http
) < 0)
3616 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3620 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3621 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3625 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3630 #endif /* HAVE_LIBZ */
3633 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3635 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3636 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3638 httpFlushWrite(http
);
3641 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3642 length
< sizeof(http
->wbuffer
))
3645 * Write to buffer...
3648 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3649 CUPS_LLCAST length
));
3651 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3652 http
->wused
+= (int)length
;
3653 bytes
= (ssize_t
)length
;
3658 * Otherwise write the data directly...
3661 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3662 CUPS_LLCAST length
));
3664 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3665 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3667 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3669 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3670 CUPS_LLCAST bytes
));
3673 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3674 http
->data_remaining
-= bytes
;
3680 * Handle end-of-request processing...
3683 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3684 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3687 * Finished with the transfer; unless we are sending POST or PUT
3693 http_content_coding_finish(http
);
3694 #endif /* HAVE_LIBZ */
3698 if (httpFlushWrite(http
) < 0)
3702 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3705 * Send a 0-length chunk at the end of the request...
3708 http_write(http
, "0\r\n\r\n", 5);
3711 * Reset the data state...
3714 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3715 http
->data_remaining
= 0;
3718 if (http
->state
== HTTP_STATE_POST_RECV
)
3721 http
->state
= HTTP_STATE_WAITING
;
3723 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3724 http_states
[http
->state
+ 1]));
3727 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3733 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3735 * '_httpWriteCDSA()' - Write function for the CDSA library.
3738 OSStatus
/* O - -1 on error, 0 on success */
3740 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3741 const void *data
, /* I - Data buffer */
3742 size_t *dataLength
) /* IO - Number of bytes */
3744 OSStatus result
; /* Return value */
3745 ssize_t bytes
; /* Number of bytes read */
3746 http_t
*http
; /* HTTP connection */
3749 http
= (http_t
*)connection
;
3753 bytes
= write(http
->fd
, data
, *dataLength
);
3755 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3757 if (bytes
== *dataLength
)
3761 else if (bytes
>= 0)
3763 *dataLength
= bytes
;
3764 result
= errSSLWouldBlock
;
3770 if (errno
== EAGAIN
)
3771 result
= errSSLWouldBlock
;
3773 result
= errSSLClosedAbort
;
3778 #endif /* HAVE_SSL && HAVE_CDSASSL */
3781 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3783 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3786 ssize_t
/* O - Number of bytes written or -1 on error */
3788 gnutls_transport_ptr ptr
, /* I - Connection to server */
3789 const void *data
, /* I - Data buffer */
3790 size_t length
) /* I - Number of bytes to write */
3792 ssize_t bytes
; /* Bytes written */
3795 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3798 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3801 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3802 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3806 #endif /* HAVE_SSL && HAVE_GNUTLS */
3810 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3815 int /* O - 0 on success, -1 on error */
3816 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3817 http_status_t status
) /* I - Status code */
3819 http_encoding_t old_encoding
; /* Old data_encoding value */
3820 off_t old_remaining
; /* Old data_remaining value */
3824 * Range check input...
3827 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3829 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3831 DEBUG_puts("1httpWriteResponse: Bad input.");
3836 * Set the various standard fields if they aren't already...
3839 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3840 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3842 if (status
>= HTTP_BAD_REQUEST
&& http
->keep_alive
)
3844 http
->keep_alive
= 0;
3845 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3848 if (http
->version
== HTTP_VERSION_1_1
)
3850 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3852 if (http
->keep_alive
)
3853 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3855 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3858 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3859 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3863 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
)
3865 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3866 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3868 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3869 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3871 #endif /* HAVE_SSL */
3874 httpSetField(http
, HTTP_FIELD_SERVER
,
3875 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3878 * Set the Accept-Encoding field if it isn't already...
3881 if (!http
->accept_encoding
)
3882 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3883 http
->default_accept_encoding
? http
->default_accept_encoding
:
3885 "gzip, deflate, identity");
3888 #endif /* HAVE_LIBZ */
3891 * Send the response header...
3894 old_encoding
= http
->data_encoding
;
3895 old_remaining
= http
->data_remaining
;
3896 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3898 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3899 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3901 http
->status
= HTTP_STATUS_ERROR
;
3905 if (status
!= HTTP_STATUS_CONTINUE
)
3908 * 100 Continue doesn't have the rest of the response headers...
3911 int i
; /* Looping var */
3912 const char *value
; /* Field value */
3914 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3916 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3918 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3920 http
->status
= HTTP_STATUS_ERROR
;
3928 if (httpPrintf(http
, "Set-Cookie: %s path=/%s\r\n", http
->cookie
,
3929 http
->tls
? " secure" : "") < 1)
3931 http
->status
= HTTP_ERROR
;
3937 if (httpWrite2(http
, "\r\n", 2) < 2)
3939 http
->status
= HTTP_ERROR
;
3943 if (httpFlushWrite(http
) < 0)
3945 http
->status
= HTTP_ERROR
;
3949 if (status
== HTTP_STATUS_CONTINUE
)
3952 * Restore the old data_encoding and data_length values...
3955 http
->data_encoding
= old_encoding
;
3956 http
->data_remaining
= old_remaining
;
3958 if (old_remaining
<= INT_MAX
)
3959 http
->_data_remaining
= (int)old_remaining
;
3961 http
->_data_remaining
= INT_MAX
;
3963 else if (http
->state
== HTTP_STATE_OPTIONS
||
3964 http
->state
== HTTP_STATE_HEAD
||
3965 http
->state
== HTTP_STATE_PUT
||
3966 http
->state
== HTTP_STATE_TRACE
||
3967 http
->state
== HTTP_STATE_CONNECT
)
3969 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3970 "was %s.", http_states
[http
->state
+ 1]));
3971 http
->state
= HTTP_STATE_WAITING
;
3976 * Force data_encoding and data_length to be set according to the response
3980 http_set_length(http
);
3984 * Then start any content encoding...
3987 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
3988 http_content_coding_start(http
,
3989 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3990 #endif /* HAVE_LIBZ */
3997 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3999 * 'http_bio_ctrl()' - Control the HTTP connection.
4002 static long /* O - Result/data */
4003 http_bio_ctrl(BIO
*h
, /* I - BIO data */
4004 int cmd
, /* I - Control command */
4005 long arg1
, /* I - First argument */
4006 void *arg2
) /* I - Second argument */
4013 case BIO_CTRL_RESET
:
4017 case BIO_C_SET_FILE_PTR
:
4022 case BIO_C_GET_FILE_PTR
:
4025 *((void **)arg2
) = h
->ptr
;
4032 case BIO_CTRL_FLUSH
:
4039 * 'http_bio_free()' - Free OpenSSL data.
4042 static int /* O - 1 on success, 0 on failure */
4043 http_bio_free(BIO
*h
) /* I - BIO data */
4059 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
4062 static int /* O - 1 on success, 0 on failure */
4063 http_bio_new(BIO
*h
) /* I - BIO data */
4078 * 'http_bio_puts()' - Send a string for OpenSSL.
4081 static int /* O - Bytes written */
4082 http_bio_puts(BIO
*h
, /* I - BIO data */
4083 const char *str
) /* I - String to write */
4086 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
4088 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
4094 * 'http_bio_read()' - Read data for OpenSSL.
4097 static int /* O - Bytes read */
4098 http_bio_read(BIO
*h
, /* I - BIO data */
4099 char *buf
, /* I - Buffer */
4100 int size
) /* I - Number of bytes to read */
4102 http_t
*http
; /* HTTP connection */
4105 http
= (http_t
*)h
->ptr
;
4107 if (!http
->blocking
)
4110 * Make sure we have data before we read...
4113 while (!_httpWait(http
, http
->wait_value
, 0))
4115 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4119 http
->error
= WSAETIMEDOUT
;
4121 http
->error
= ETIMEDOUT
;
4128 return (recv(http
->fd
, buf
, size
, 0));
4133 * 'http_bio_write()' - Write data for OpenSSL.
4136 static int /* O - Bytes written */
4137 http_bio_write(BIO
*h
, /* I - BIO data */
4138 const char *buf
, /* I - Buffer to write */
4139 int num
) /* I - Number of bytes to write */
4141 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4143 #endif /* HAVE_SSL && HAVE_LIBSSL */
4148 * 'http_content_coding_finish()' - Finish doing any content encoding.
4152 http_content_coding_finish(
4153 http_t
*http
) /* I - HTTP connection */
4155 int zerr
; /* Compression status */
4158 switch (http
->coding
)
4160 case _HTTP_CODING_DEFLATE
:
4161 case _HTTP_CODING_GZIP
:
4164 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4165 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4167 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4169 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4170 if (http
->wused
== sizeof(http
->wbuffer
))
4171 httpFlushWrite(http
);
4173 while (zerr
== Z_OK
);
4175 deflateEnd(&(http
->stream
));
4178 httpFlushWrite(http
);
4181 case _HTTP_CODING_INFLATE
:
4182 case _HTTP_CODING_GUNZIP
:
4183 inflateEnd(&(http
->stream
));
4184 free(http
->dbuffer
);
4185 http
->dbuffer
= NULL
;
4192 http
->coding
= _HTTP_CODING_IDENTITY
;
4197 * 'http_content_coding_start()' - Start doing content encoding.
4201 http_content_coding_start(
4202 http_t
*http
, /* I - HTTP connection */
4203 const char *value
) /* I - Value of Content-Encoding */
4205 int zerr
; /* Error/status */
4206 _http_coding_t coding
; /* Content coding value */
4209 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4212 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4214 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4218 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4220 if (http
->state
== HTTP_GET_SEND
|| http
->state
== HTTP_POST_SEND
)
4221 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4222 _HTTP_CODING_GUNZIP
;
4223 else if (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
)
4224 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4225 _HTTP_CODING_GUNZIP
;
4228 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4232 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4234 if (http
->state
== HTTP_GET_SEND
|| http
->state
== HTTP_POST_SEND
)
4235 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4236 _HTTP_CODING_INFLATE
;
4237 else if (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
)
4238 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4239 _HTTP_CODING_INFLATE
;
4242 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4248 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4252 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4256 case _HTTP_CODING_DEFLATE
:
4257 case _HTTP_CODING_GZIP
:
4259 httpFlushWrite(http
);
4262 * Window size for compression is 11 bits - optimal based on PWG Raster
4263 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
4267 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4269 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
4270 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4272 http
->status
= HTTP_ERROR
;
4273 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4278 case _HTTP_CODING_INFLATE
:
4279 case _HTTP_CODING_GUNZIP
:
4280 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
4282 http
->status
= HTTP_ERROR
;
4283 http
->error
= errno
;
4288 * Window size for decompression is up to 15 bits (maximum supported).
4289 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
4292 if ((zerr
= inflateInit2(&(http
->stream
),
4293 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
4296 free(http
->dbuffer
);
4297 http
->dbuffer
= NULL
;
4298 http
->status
= HTTP_ERROR
;
4299 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4303 http
->stream
.avail_in
= 0;
4304 http
->stream
.next_in
= http
->dbuffer
;
4311 http
->coding
= coding
;
4313 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4316 #endif /* HAVE_LIBZ */
4320 * 'http_create()' - Create an unconnected HTTP connection.
4323 static http_t
* /* O - HTTP connection */
4325 const char *host
, /* I - Hostname */
4326 int port
, /* I - Port number */
4327 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
4328 int family
, /* I - Address family or AF_UNSPEC */
4329 http_encryption_t encryption
, /* I - Encryption to use */
4330 int blocking
, /* I - 1 for blocking mode */
4331 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
4333 http_t
*http
; /* New HTTP connection */
4334 char service
[255]; /* Service name */
4335 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
4338 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
4339 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
4340 family
, encryption
, blocking
, mode
));
4342 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
4348 * Lookup the host...
4353 myaddrlist
= httpAddrCopyList(addrlist
);
4357 snprintf(service
, sizeof(service
), "%d", port
);
4359 myaddrlist
= httpAddrGetList(host
, family
, service
);
4366 * Allocate memory for the structure...
4369 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
4371 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(errno
), 0);
4372 httpAddrFreeList(addrlist
);
4377 * Initialize the HTTP data...
4381 http
->activity
= time(NULL
);
4382 http
->addrlist
= myaddrlist
;
4383 http
->blocking
= blocking
;
4386 http
->gssctx
= GSS_C_NO_CONTEXT
;
4387 http
->gssname
= GSS_C_NO_NAME
;
4388 #endif /* HAVE_GSSAPI */
4389 http
->version
= HTTP_VERSION_1_1
;
4392 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
4394 if (port
== 443) /* Always use encryption for https */
4395 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
4397 http
->encryption
= encryption
;
4399 http_set_wait(http
);
4402 * Return the new structure...
4408 /* For OS X 10.8 and earlier */
4409 http_t
*_httpCreate(const char *host
, int port
, http_addrlist_t
*addrlist
,
4410 http_encryption_t encryption
, int family
)
4411 { return (http_create(host
, port
, addrlist
, family
, encryption
, 1,
4412 _HTTP_MODE_CLIENT
)); }
4417 * 'http_debug_hex()' - Do a hex dump of a buffer.
4421 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4422 const char *buffer
, /* I - Buffer to dump */
4423 int bytes
) /* I - Bytes to dump */
4425 int i
, j
, /* Looping vars */
4426 ch
; /* Current character */
4427 char line
[255], /* Line buffer */
4428 *start
, /* Start of line after prefix */
4429 *ptr
; /* Pointer into line */
4432 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4435 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4437 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4438 start
= line
+ strlen(line
);
4440 for (i
= 0; i
< bytes
; i
+= 16)
4442 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4443 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4447 memcpy(ptr
, " ", 3);
4452 memcpy(ptr
, " ", 3);
4455 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4457 ch
= buffer
[i
+ j
] & 255;
4459 if (ch
< ' ' || ch
>= 127)
4473 * 'http_field()' - Return the field index for a field name.
4476 static http_field_t
/* O - Field index */
4477 http_field(const char *name
) /* I - String name */
4479 int i
; /* Looping var */
4482 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4483 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
4484 return ((http_field_t
)i
);
4486 return (HTTP_FIELD_UNKNOWN
);
4491 * 'http_read()' - Read a buffer from a HTTP connection.
4493 * This function does the low-level read from the socket, retrying and timing
4497 static ssize_t
/* O - Number of bytes read or -1 on error */
4498 http_read(http_t
*http
, /* I - Connection to server */
4499 char *buffer
, /* I - Buffer */
4500 size_t length
) /* I - Maximum bytes to read */
4502 ssize_t bytes
; /* Bytes read */
4505 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4506 buffer
, CUPS_LLCAST length
));
4508 if (!http
->blocking
)
4510 while (!httpWait(http
, http
->wait_value
))
4512 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4515 DEBUG_puts("2http_read: Timeout.");
4520 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4526 bytes
= http_read_ssl(http
, buffer
, length
);
4528 #endif /* HAVE_SSL */
4529 bytes
= recv(http
->fd
, buffer
, length
, 0);
4534 if (WSAGetLastError() != WSAEINTR
)
4536 http
->error
= WSAGetLastError();
4539 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4541 if (!http
->timeout_cb
||
4542 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4544 http
->error
= WSAEWOULDBLOCK
;
4549 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4551 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4553 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4555 http
->error
= errno
;
4558 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4560 http
->error
= errno
;
4564 else if (errno
!= EINTR
)
4566 http
->error
= errno
;
4574 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4575 CUPS_LLCAST bytes
));
4578 http_debug_hex("http_read", http
->buffer
, (int)bytes
);
4584 if (WSAGetLastError() == WSAEINTR
)
4587 http
->error
= WSAGetLastError();
4589 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4592 http
->error
= errno
;
4595 else if (bytes
== 0)
4597 http
->error
= EPIPE
;
4606 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4608 * This function reads data from the HTTP buffer or from the socket, as needed.
4611 static ssize_t
/* O - Number of bytes read or -1 on error */
4612 http_read_buffered(http_t
*http
, /* I - Connection to server */
4613 char *buffer
, /* I - Buffer */
4614 size_t length
) /* I - Maximum bytes to read */
4616 ssize_t bytes
; /* Bytes read */
4619 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4621 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4625 if (length
> (size_t)http
->used
)
4626 bytes
= (size_t)http
->used
;
4630 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4633 memcpy(buffer
, http
->buffer
, bytes
);
4634 http
->used
-= (int)bytes
;
4637 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4640 bytes
= http_read(http
, buffer
, length
);
4647 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4649 * This function reads and validates the chunk length, then does a buffered read
4650 * returning the number of bytes placed in the buffer.
4653 static ssize_t
/* O - Number of bytes read or -1 on error */
4654 http_read_chunk(http_t
*http
, /* I - Connection to server */
4655 char *buffer
, /* I - Buffer */
4656 size_t length
) /* I - Maximum bytes to read */
4658 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4659 http
, buffer
, CUPS_LLCAST length
));
4661 if (http
->data_remaining
<= 0)
4663 char len
[32]; /* Length string */
4665 if (!httpGets(len
, sizeof(len
), http
))
4667 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4673 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4674 if (!httpGets(len
, sizeof(len
), http
))
4676 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4681 http
->data_remaining
= strtoll(len
, NULL
, 16);
4683 if (http
->data_remaining
< 0)
4685 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4686 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4690 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4691 len
, CUPS_LLCAST http
->data_remaining
));
4693 if (http
->data_remaining
== 0)
4696 * 0-length chunk, grab trailing blank line...
4699 httpGets(len
, sizeof(len
), http
);
4703 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4704 CUPS_LLCAST http
->data_remaining
));
4706 if (http
->data_remaining
<= 0)
4708 else if (length
> (size_t)http
->data_remaining
)
4709 length
= (size_t)http
->data_remaining
;
4711 return (http_read_buffered(http
, buffer
, length
));
4717 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4720 static int /* O - Bytes read */
4721 http_read_ssl(http_t
*http
, /* I - Connection to server */
4722 char *buf
, /* I - Buffer to store data */
4723 int len
) /* I - Length of buffer */
4725 # if defined(HAVE_LIBSSL)
4726 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4728 # elif defined(HAVE_GNUTLS)
4729 ssize_t result
; /* Return value */
4732 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4734 if (result
< 0 && !errno
)
4737 * Convert GNU TLS error to errno value...
4742 case GNUTLS_E_INTERRUPTED
:
4746 case GNUTLS_E_AGAIN
:
4758 return ((int)result
);
4760 # elif defined(HAVE_CDSASSL)
4761 int result
; /* Return value */
4762 OSStatus error
; /* Error info */
4763 size_t processed
; /* Number of bytes processed */
4766 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4767 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4772 result
= (int)processed
;
4775 case errSSLWouldBlock
:
4777 result
= (int)processed
;
4785 case errSSLClosedGraceful
:
4788 result
= (int)processed
;
4799 # elif defined(HAVE_SSPISSL)
4800 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4801 # endif /* HAVE_LIBSSL */
4803 #endif /* HAVE_SSL */
4807 * 'http_send()' - Send a request with all fields and the trailing blank line.
4810 static int /* O - 0 on success, non-zero on error */
4811 http_send(http_t
*http
, /* I - Connection to server */
4812 http_state_t request
, /* I - Request code */
4813 const char *uri
) /* I - URI */
4815 int i
; /* Looping var */
4816 char buf
[1024]; /* Encoded URI buffer */
4817 const char *value
; /* Field value */
4818 static const char * const codes
[] = /* Request code strings */
4838 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4839 http
, codes
[request
], uri
));
4841 if (http
== NULL
|| uri
== NULL
)
4845 * Set the User-Agent field if it isn't already...
4848 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4850 if (http
->default_user_agent
)
4851 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4853 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4857 * Set the Accept-Encoding field if it isn't already...
4860 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4861 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4862 http
->default_accept_encoding
);
4865 * Encode the URI as needed...
4868 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4871 * See if we had an error the last time around; if so, reconnect...
4874 if (http
->fd
< 0 || http
->status
== HTTP_ERROR
||
4875 http
->status
>= HTTP_BAD_REQUEST
)
4876 if (httpReconnect(http
))
4880 * Flush any written data that is pending...
4885 if (httpFlushWrite(http
) < 0)
4886 if (httpReconnect(http
))
4891 * Send the request header...
4894 http
->state
= request
;
4895 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4897 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
4900 http
->status
= HTTP_CONTINUE
;
4903 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
4905 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4906 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4908 #endif /* HAVE_SSL */
4910 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4912 http
->status
= HTTP_ERROR
;
4916 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4917 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4919 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
], value
));
4921 if (i
== HTTP_FIELD_HOST
)
4923 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4924 httpAddrPort(http
->hostaddr
)) < 1)
4926 http
->status
= HTTP_ERROR
;
4930 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4932 http
->status
= HTTP_ERROR
;
4938 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4940 http
->status
= HTTP_ERROR
;
4944 if (http
->expect
== HTTP_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4945 (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
4946 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4948 http
->status
= HTTP_ERROR
;
4952 if (httpPrintf(http
, "\r\n") < 1)
4954 http
->status
= HTTP_ERROR
;
4958 if (httpFlushWrite(http
) < 0)
4961 http_set_length(http
);
4962 httpClearFields(http
);
4965 * The Kerberos and AuthRef authentication strings can only be used once...
4968 if (http
->field_authorization
&& http
->authstring
&&
4969 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4970 !strncmp(http
->authstring
, "AuthRef", 7)))
4972 http
->_authstring
[0] = '\0';
4974 if (http
->authstring
!= http
->_authstring
)
4975 free(http
->authstring
);
4977 http
->authstring
= http
->_authstring
;
4985 # if defined(HAVE_CDSASSL)
4987 * 'http_set_credentials()' - Set the SSL/TLS credentials.
4990 static int /* O - Status of connection */
4991 http_set_credentials(http_t
*http
) /* I - Connection to server */
4993 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
4994 OSStatus error
= 0; /* Error code */
4995 http_tls_credentials_t credentials
= NULL
;
4996 /* TLS credentials */
4999 DEBUG_printf(("7http_set_credentials(%p)", http
));
5002 * Prefer connection specific credentials...
5005 if ((credentials
= http
->tls_credentials
) == NULL
)
5006 credentials
= cg
->tls_credentials
;
5010 error
= SSLSetCertificate(http
->tls
, credentials
);
5011 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
5015 DEBUG_puts("4http_set_credentials: No credentials to set.");
5019 # endif /* HAVE_CDSASSL */
5020 #endif /* HAVE_SSL */
5024 * 'http_set_length()' - Set the data_encoding and data_remaining values.
5027 static off_t
/* O - Remainder or -1 on error */
5028 http_set_length(http_t
*http
) /* I - Connection */
5030 off_t remaining
; /* Remainder */
5033 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
5034 http_states
[http
->state
+ 1]));
5036 if ((remaining
= httpGetLength2(http
)) >= 0)
5038 if (http
->mode
== _HTTP_MODE_SERVER
&&
5039 http
->state
!= HTTP_STATE_GET_SEND
&&
5040 http
->state
!= HTTP_STATE_PUT
&&
5041 http
->state
!= HTTP_STATE_POST
&&
5042 http
->state
!= HTTP_STATE_POST_SEND
)
5044 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
5048 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
5051 DEBUG_puts("1http_set_length: Setting data_encoding to "
5052 "HTTP_ENCODING_CHUNKED.");
5053 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
5057 DEBUG_puts("1http_set_length: Setting data_encoding to "
5058 "HTTP_ENCODING_LENGTH.");
5059 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
5062 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
5063 CUPS_LLCAST remaining
));
5064 http
->data_remaining
= remaining
;
5066 if (remaining
<= INT_MAX
)
5067 http
->_data_remaining
= remaining
;
5069 http
->_data_remaining
= INT_MAX
;
5076 * 'http_set_timeout()' - Set the socket timeout values.
5080 http_set_timeout(int fd
, /* I - File descriptor */
5081 double timeout
) /* I - Timeout in seconds */
5084 DWORD tv
= (DWORD
)(timeout
* 1000);
5085 /* Timeout in milliseconds */
5087 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5088 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5091 struct timeval tv
; /* Timeout in secs and usecs */
5093 tv
.tv_sec
= (int)timeout
;
5094 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
5096 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5097 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5103 * 'http_set_wait()' - Set the default wait value for reads.
5107 http_set_wait(http_t
*http
) /* I - Connection to server */
5111 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5113 if (http
->wait_value
<= 0)
5114 http
->wait_value
= 60000;
5117 http
->wait_value
= 10000;
5123 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5126 static int /* O - 0 on success, -1 on failure */
5127 http_setup_ssl(http_t
*http
) /* I - Connection to server */
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 _cups_globals_t
*cg
= _cupsGlobals();
5142 /* Pointer to library globals */
5143 OSStatus error
; /* Error code */
5144 const char *message
= NULL
;/* Error message */
5145 cups_array_t
*credentials
; /* Credentials array */
5146 cups_array_t
*names
; /* CUPS distinguished names */
5147 CFArrayRef dn_array
; /* CF distinguished names array */
5148 CFIndex count
; /* Number of credentials */
5149 CFDataRef data
; /* Certificate data */
5150 int i
; /* Looping var */
5151 http_credential_t
*credential
; /* Credential data */
5152 # elif defined(HAVE_SSPISSL)
5153 TCHAR username
[256]; /* Username returned from GetUserName() */
5154 TCHAR commonName
[256];/* Common name for certificate */
5155 DWORD dwSize
; /* 32 bit size */
5156 # endif /* HAVE_LIBSSL */
5159 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5162 * Get the hostname to use for SSL...
5165 if (httpAddrLocalhost(http
->hostaddr
))
5167 strlcpy(hostname
, "localhost", sizeof(hostname
));
5172 * Otherwise make sure the hostname we have does not end in a trailing dot.
5175 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5176 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5182 context
= SSL_CTX_new(SSLv23_client_method());
5184 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5186 bio
= BIO_new(_httpBIOMethods());
5187 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5189 http
->tls
= SSL_new(context
);
5190 SSL_set_bio(http
->tls
, bio
, bio
);
5192 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5193 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5194 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5196 if (SSL_connect(http
->tls
) != 1)
5198 unsigned long error
; /* Error code */
5200 while ((error
= ERR_get_error()) != 0)
5202 message
= ERR_error_string(error
, NULL
);
5203 DEBUG_printf(("8http_setup_ssl: %s", message
));
5206 SSL_CTX_free(context
);
5207 SSL_free(http
->tls
);
5211 http
->error
= WSAGetLastError();
5213 http
->error
= errno
;
5215 http
->status
= HTTP_ERROR
;
5218 message
= _("Unable to establish a secure connection to host.");
5220 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5225 # elif defined(HAVE_GNUTLS)
5226 credentials
= (gnutls_certificate_client_credentials
*)
5227 malloc(sizeof(gnutls_certificate_client_credentials
));
5228 if (credentials
== NULL
)
5230 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5232 http
->error
= errno
;
5233 http
->status
= HTTP_ERROR
;
5234 _cupsSetHTTPError(HTTP_ERROR
);
5239 gnutls_certificate_allocate_credentials(credentials
);
5241 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5242 gnutls_set_default_priority(http
->tls
);
5243 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5245 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5246 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5247 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5248 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5250 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5252 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5253 status
, gnutls_strerror(status
)));
5255 if (gnutls_error_is_fatal(status
))
5258 http
->status
= HTTP_ERROR
;
5260 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
5262 gnutls_deinit(http
->tls
);
5263 gnutls_certificate_free_credentials(*credentials
);
5271 http
->tls_credentials
= credentials
;
5273 # elif defined(HAVE_CDSASSL)
5274 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, kSSLClientSide
,
5275 kSSLStreamType
)) == NULL
)
5277 DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
5278 http
->error
= errno
= ENOMEM
;
5279 http
->status
= HTTP_ERROR
;
5280 _cupsSetHTTPError(HTTP_ERROR
);
5285 error
= SSLSetConnection(http
->tls
, http
);
5286 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5290 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5291 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5296 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
5298 DEBUG_printf(("4http_setup_ssl: SSLSetSessionOption, error=%d",
5304 if (cg
->client_cert_cb
)
5306 error
= SSLSetSessionOption(http
->tls
,
5307 kSSLSessionOptionBreakOnCertRequested
, true);
5308 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5309 "error=%d", (int)error
));
5313 error
= http_set_credentials(http
);
5314 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5320 * Let the server know which hostname/domain we are trying to connect to
5321 * in case it wants to serve up a certificate with a matching common name.
5326 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5328 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5334 int done
= 0; /* Are we done yet? */
5336 while (!error
&& !done
)
5338 error
= SSLHandshake(http
->tls
);
5340 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5348 case errSSLWouldBlock
:
5349 error
= noErr
; /* Force a retry */
5350 usleep(1000); /* in 1 millisecond */
5353 case errSSLServerAuthCompleted
:
5355 if (cg
->server_cert_cb
)
5357 error
= httpCopyCredentials(http
, &credentials
);
5360 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5361 cg
->server_cert_data
);
5362 httpFreeCredentials(credentials
);
5365 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5366 "returned %d.", (int)error
));
5370 case errSSLClientCertRequested
:
5373 if (cg
->client_cert_cb
)
5376 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5379 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5381 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5383 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5385 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5387 credential
->datalen
= CFDataGetLength(data
);
5388 if ((credential
->data
= malloc(credential
->datalen
)))
5390 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5391 credential
->datalen
);
5392 cupsArrayAdd(names
, credential
);
5400 CFRelease(dn_array
);
5405 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5406 cg
->client_cert_data
);
5408 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5409 "returned %d.", (int)error
));
5412 httpFreeCredentials(names
);
5416 case errSSLUnknownRootCert
:
5417 message
= _("Unable to establish a secure connection to host "
5418 "(untrusted certificate).");
5421 case errSSLNoRootCert
:
5422 message
= _("Unable to establish a secure connection to host "
5423 "(self-signed certificate).");
5426 case errSSLCertExpired
:
5427 message
= _("Unable to establish a secure connection to host "
5428 "(expired certificate).");
5431 case errSSLCertNotYetValid
:
5432 message
= _("Unable to establish a secure connection to host "
5433 "(certificate not yet valid).");
5436 case errSSLHostNameMismatch
:
5437 message
= _("Unable to establish a secure connection to host "
5438 "(host name mismatch).");
5441 case errSSLXCertChainInvalid
:
5442 message
= _("Unable to establish a secure connection to host "
5443 "(certificate chain invalid).");
5446 case errSSLConnectionRefused
:
5447 message
= _("Unable to establish a secure connection to host "
5448 "(peer dropped connection before responding).");
5459 http
->error
= error
;
5460 http
->status
= HTTP_ERROR
;
5461 errno
= ECONNREFUSED
;
5463 CFRelease(http
->tls
);
5467 * If an error string wasn't set by the callbacks use a generic one...
5471 #ifdef HAVE_CSSMERRORSTRING
5472 message
= cssmErrorString(error
);
5474 message
= _("Unable to establish a secure connection to host.");
5475 #endif /* HAVE_CSSMERRORSTRING */
5477 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5482 # elif defined(HAVE_SSPISSL)
5483 http
->tls
= _sspiAlloc();
5487 _cupsSetHTTPError(HTTP_ERROR
);
5491 http
->tls
->sock
= http
->fd
;
5492 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5493 GetUserName(username
, &dwSize
);
5494 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5495 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5497 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5500 _sspiFree(http
->tls_credentials
);
5501 http
->tls_credentials
= NULL
;
5504 http
->status
= HTTP_ERROR
;
5506 _cupsSetError(IPP_PKI_ERROR
,
5507 _("Unable to establish a secure connection to host."), 1);
5512 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
5513 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5515 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5517 _sspiFree(http
->tls_credentials
);
5518 http
->tls_credentials
= NULL
;
5521 http
->status
= HTTP_ERROR
;
5523 _cupsSetError(IPP_PKI_ERROR
,
5524 _("Unable to establish a secure connection to host."), 1);
5528 # endif /* HAVE_CDSASSL */
5535 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5539 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
5542 SSL_CTX
*context
; /* Context for encryption */
5544 context
= SSL_get_SSL_CTX(http
->tls
);
5546 SSL_shutdown(http
->tls
);
5547 SSL_CTX_free(context
);
5548 SSL_free(http
->tls
);
5550 # elif defined(HAVE_GNUTLS)
5551 gnutls_certificate_client_credentials
*credentials
;
5552 /* TLS credentials */
5554 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5556 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5557 gnutls_deinit(http
->tls
);
5558 gnutls_certificate_free_credentials(*credentials
);
5561 # elif defined(HAVE_CDSASSL)
5562 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5565 CFRelease(http
->tls
);
5567 if (http
->tls_credentials
)
5568 CFRelease(http
->tls_credentials
);
5570 # elif defined(HAVE_SSPISSL)
5571 _sspiFree(http
->tls_credentials
);
5572 # endif /* HAVE_LIBSSL */
5575 http
->tls_credentials
= NULL
;
5577 #endif /* HAVE_SSL */
5582 * 'http_upgrade()' - Force upgrade to TLS encryption.
5585 static int /* O - Status of connection */
5586 http_upgrade(http_t
*http
) /* I - Connection to server */
5588 int ret
; /* Return value */
5589 http_t myhttp
; /* Local copy of HTTP data */
5592 DEBUG_printf(("7http_upgrade(%p)", http
));
5595 * Flush the connection to make sure any previous "Upgrade" message
5602 * Copy the HTTP data to a local variable so we can do the OPTIONS
5603 * request without interfering with the existing request data...
5606 memcpy(&myhttp
, http
, sizeof(myhttp
));
5609 * Send an OPTIONS request to the server, requiring SSL or TLS
5610 * encryption on the link...
5613 http
->field_authorization
= NULL
; /* Don't free the auth string */
5615 httpClearFields(http
);
5616 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5617 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5619 if ((ret
= httpOptions(http
, "*")) == 0)
5622 * Wait for the secure connection...
5625 while (httpUpdate(http
) == HTTP_CONTINUE
);
5629 * Restore the HTTP request data...
5632 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5633 http
->data_encoding
= myhttp
.data_encoding
;
5634 http
->data_remaining
= myhttp
.data_remaining
;
5635 http
->_data_remaining
= myhttp
._data_remaining
;
5636 http
->expect
= myhttp
.expect
;
5637 http
->field_authorization
= myhttp
.field_authorization
;
5638 http
->digest_tries
= myhttp
.digest_tries
;
5641 * See if we actually went secure...
5647 * Server does not support HTTP upgrade...
5650 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5653 closesocket(http
->fd
);
5665 #endif /* HAVE_SSL */
5669 * 'http_write()' - Write a buffer to a HTTP connection.
5672 static ssize_t
/* O - Number of bytes written */
5673 http_write(http_t
*http
, /* I - Connection to server */
5674 const char *buffer
, /* I - Buffer for data */
5675 size_t length
) /* I - Number of bytes to write */
5677 ssize_t tbytes
, /* Total bytes sent */
5678 bytes
; /* Bytes sent */
5681 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
5682 buffer
, CUPS_LLCAST length
));
5688 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5690 if (http
->timeout_cb
)
5693 struct pollfd pfd
; /* Polled file descriptor */
5695 fd_set output_set
; /* Output ready for write? */
5696 struct timeval timeout
; /* Timeout value */
5697 #endif /* HAVE_POLL */
5698 int nfds
; /* Result from select()/poll() */
5704 pfd
.events
= POLLOUT
;
5706 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5707 (errno
== EINTR
|| errno
== EAGAIN
))
5713 FD_ZERO(&output_set
);
5714 FD_SET(http
->fd
, &output_set
);
5716 timeout
.tv_sec
= http
->wait_value
/ 1000;
5717 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5719 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5722 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5723 WSAGetLastError() == WSAEWOULDBLOCK
));
5725 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5727 #endif /* HAVE_POLL */
5731 http
->error
= errno
;
5734 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5737 http
->error
= WSAEWOULDBLOCK
;
5739 http
->error
= EWOULDBLOCK
;
5749 bytes
= http_write_ssl(http
, buffer
, length
);
5751 #endif /* HAVE_SSL */
5752 bytes
= send(http
->fd
, buffer
, length
, 0);
5754 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
5755 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
5760 if (WSAGetLastError() == WSAEINTR
)
5762 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5764 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5767 http
->error
= WSAGetLastError();
5769 else if (WSAGetLastError() != http
->error
&&
5770 WSAGetLastError() != WSAECONNRESET
)
5772 http
->error
= WSAGetLastError();
5779 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5781 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5783 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5786 http
->error
= errno
;
5788 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5790 http
->error
= errno
;
5795 DEBUG_printf(("3http_write: error writing data (%s).",
5796 strerror(http
->error
)));
5807 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5810 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
5817 * 'http_write_chunk()' - Write a chunked buffer.
5820 static ssize_t
/* O - Number bytes written */
5821 http_write_chunk(http_t
*http
, /* I - Connection to server */
5822 const char *buffer
, /* I - Buffer to write */
5823 size_t length
) /* I - Length of buffer */
5825 char header
[16]; /* Chunk header */
5826 ssize_t bytes
; /* Bytes written */
5829 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
5830 http
, buffer
, CUPS_LLCAST length
));
5833 * Write the chunk header, data, and trailer.
5836 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
5837 if (http_write(http
, header
, strlen(header
)) < 0)
5839 DEBUG_puts("8http_write_chunk: http_write of length failed.");
5843 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5845 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
5849 if (http_write(http
, "\r\n", 2) < 0)
5851 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
5861 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5864 static int /* O - Bytes written */
5865 http_write_ssl(http_t
*http
, /* I - Connection to server */
5866 const char *buf
, /* I - Buffer holding data */
5867 int len
) /* I - Length of buffer */
5869 ssize_t result
; /* Return value */
5872 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5874 # if defined(HAVE_LIBSSL)
5875 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5877 # elif defined(HAVE_GNUTLS)
5878 result
= gnutls_record_send(http
->tls
, buf
, len
);
5880 if (result
< 0 && !errno
)
5883 * Convert GNU TLS error to errno value...
5888 case GNUTLS_E_INTERRUPTED
:
5892 case GNUTLS_E_AGAIN
:
5904 # elif defined(HAVE_CDSASSL)
5905 OSStatus error
; /* Error info */
5906 size_t processed
; /* Number of bytes processed */
5909 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5914 result
= (int)processed
;
5917 case errSSLWouldBlock
:
5919 result
= (int)processed
;
5927 case errSSLClosedGraceful
:
5930 result
= (int)processed
;
5938 # elif defined(HAVE_SSPISSL)
5939 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
5940 # endif /* HAVE_LIBSSL */
5942 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
5944 return ((int)result
);
5946 #endif /* HAVE_SSL */
5950 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".