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 * httpGetAuthString() - Get the current authorization string.
51 * httpGetBlocking() - Get the blocking/non-block state of a
53 * httpGetContentEncoding() - Get a common content encoding, if any,
54 * between the client and server.
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_state_string() - Return the string associated with a given
138 * http_upgrade() - Force upgrade to TLS encryption.
139 * http_write() - Write a buffer to a HTTP connection.
140 * http_write_chunk() - Write a chunked buffer.
141 * http_write_ssl() - Write to a SSL/TLS connection.
145 * Include necessary headers...
148 #include "cups-private.h"
155 # include <sys/time.h>
156 # include <sys/resource.h>
160 #endif /* HAVE_POLL */
168 static void http_content_coding_finish(http_t
*http
);
169 static void http_content_coding_start(http_t
*http
,
171 #endif /* HAVE_LIBZ */
172 static http_t
*http_create(const char *host
, int port
,
173 http_addrlist_t
*addrlist
, int family
,
174 http_encryption_t encryption
,
175 int blocking
, _http_mode_t mode
);
177 static void http_debug_hex(const char *prefix
, const char *buffer
,
180 static http_field_t
http_field(const char *name
);
181 static ssize_t
http_read(http_t
*http
, char *buffer
, size_t length
);
182 static ssize_t
http_read_buffered(http_t
*http
, char *buffer
, size_t length
);
183 static ssize_t
http_read_chunk(http_t
*http
, char *buffer
, size_t length
);
184 static int http_send(http_t
*http
, http_state_t request
,
186 static ssize_t
http_write(http_t
*http
, const char *buffer
,
188 static ssize_t
http_write_chunk(http_t
*http
, const char *buffer
,
191 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
193 static int http_set_credentials(http_t
*http
);
194 # endif /* HAVE_CDSASSL */
195 #endif /* HAVE_SSL */
196 static off_t
http_set_length(http_t
*http
);
197 static void http_set_timeout(int fd
, double timeout
);
198 static void http_set_wait(http_t
*http
);
200 static const char *http_state_string(http_state_t state
);
203 static int http_setup_ssl(http_t
*http
);
204 static void http_shutdown_ssl(http_t
*http
);
205 static int http_upgrade(http_t
*http
);
206 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
207 #endif /* HAVE_SSL */
214 static const char * const http_fields
[] =
231 "If-Unmodified-since",
249 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
251 * BIO methods for OpenSSL...
254 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
255 static int http_bio_read(BIO
*h
, char *buf
, int size
);
256 static int http_bio_puts(BIO
*h
, const char *str
);
257 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
258 static int http_bio_new(BIO
*h
);
259 static int http_bio_free(BIO
*data
);
261 static BIO_METHOD http_bio_methods
=
268 NULL
, /* http_bio_gets, */
274 #endif /* HAVE_SSL && HAVE_LIBSSL */
278 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
279 * specified listening socket.
284 http_t
* /* O - HTTP connection or @code NULL@ */
285 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
286 int blocking
) /* I - 1 if the connection should be
287 blocking, 0 otherwise */
289 http_t
*http
; /* HTTP connection */
290 http_addrlist_t addrlist
; /* Dummy address list */
291 socklen_t addrlen
; /* Length of address */
292 int val
; /* Socket option value */
296 * Range check input...
303 * Create the client connection...
306 memset(&addrlist
, 0, sizeof(addrlist
));
308 if ((http
= http_create(NULL
, 0, &addrlist
, AF_UNSPEC
,
309 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
310 _HTTP_MODE_SERVER
)) == NULL
)
314 * Accept the client and get the remote address...
317 addrlen
= sizeof(http_addr_t
);
319 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
322 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
328 httpAddrString(&(http
->addrlist
->addr
), http
->hostname
,
329 sizeof(http
->hostname
));
333 * Disable SIGPIPE for this socket.
337 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
338 #endif /* SO_NOSIGPIPE */
341 * Using TCP_NODELAY improves responsiveness, especially on systems
342 * with a slow loopback interface. Since we write large buffers
343 * when sending print files and requests, there shouldn't be any
344 * performance penalty for this...
348 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
352 * Close this socket when starting another process...
355 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
356 #endif /* FD_CLOEXEC */
363 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
365 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
367 * @since CUPS 1.5/OS X 10.7@
370 int /* O - 0 on success, -1 on error */
372 cups_array_t
*credentials
, /* I - Credentials array */
373 const void *data
, /* I - PEM-encoded X.509 data */
374 size_t datalen
) /* I - Length of data */
376 http_credential_t
*credential
; /* Credential data */
379 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
381 credential
->datalen
= datalen
;
383 if ((credential
->data
= malloc(datalen
)) != NULL
)
385 memcpy(credential
->data
, data
, datalen
);
386 cupsArrayAdd(credentials
, credential
);
397 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
399 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
402 BIO_METHOD
* /* O - BIO methods for OpenSSL */
403 _httpBIOMethods(void)
405 return (&http_bio_methods
);
407 #endif /* HAVE_SSL && HAVE_LIBSSL */
411 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
415 httpBlocking(http_t
*http
, /* I - Connection to server */
416 int b
) /* I - 1 = blocking, 0 = non-blocking */
427 * 'httpCheck()' - Check to see if there is a pending response from the server.
430 int /* O - 0 = no data, 1 = data available */
431 httpCheck(http_t
*http
) /* I - Connection to server */
433 return (httpWait(http
, 0));
438 * 'httpClearCookie()' - Clear the cookie value(s).
440 * @since CUPS 1.1.19/OS X 10.3@
444 httpClearCookie(http_t
*http
) /* I - Connection to server */
458 * 'httpClearFields()' - Clear HTTP request fields.
462 httpClearFields(http_t
*http
) /* I - Connection to server */
464 DEBUG_printf(("httpClearFields(http=%p)", http
));
468 memset(http
->fields
, 0, sizeof(http
->fields
));
470 if (http
->mode
== _HTTP_MODE_CLIENT
)
472 if (http
->hostname
[0] == '/')
473 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
475 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
478 if (http
->field_authorization
)
480 free(http
->field_authorization
);
481 http
->field_authorization
= NULL
;
484 if (http
->accept_encoding
)
486 _cupsStrFree(http
->accept_encoding
);
487 http
->accept_encoding
= NULL
;
492 _cupsStrFree(http
->allow
);
498 _cupsStrFree(http
->server
);
502 http
->expect
= (http_status_t
)0;
508 * 'httpClose()' - Close an HTTP connection.
512 httpClose(http_t
*http
) /* I - Connection to server */
515 OM_uint32 minor_status
; /* Minor status code */
516 #endif /* HAVE_GSSAPI */
519 DEBUG_printf(("httpClose(http=%p)", http
));
522 * Range check input...
529 * Close any open connection...
532 _httpDisconnect(http
);
535 * Free memory used...
538 httpAddrFreeList(http
->addrlist
);
544 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
545 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
547 if (http
->gssname
!= GSS_C_NO_NAME
)
548 gss_release_name(&minor_status
, &http
->gssname
);
549 #endif /* HAVE_GSSAPI */
551 #ifdef HAVE_AUTHORIZATION_H
553 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
554 #endif /* HAVE_AUTHORIZATION_H */
556 httpClearFields(http
);
558 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
559 free(http
->authstring
);
566 * 'httpConnect()' - Connect to a HTTP server.
568 * This function is deprecated - use @link httpConnect2@ instead.
573 http_t
* /* O - New HTTP connection */
574 httpConnect(const char *host
, /* I - Host to connect to */
575 int port
) /* I - Port number */
577 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, HTTP_ENCRYPTION_IF_REQUESTED
,
583 * 'httpConnect2()' - Connect to a HTTP server.
588 http_t
* /* O - New HTTP connection */
590 const char *host
, /* I - Host to connect to */
591 int port
, /* I - Port number */
592 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
593 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
594 http_encryption_t encryption
, /* I - Type of encryption to use */
595 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
596 int msec
, /* I - Connection timeout in milliseconds, 0 means don't connect */
597 int *cancel
) /* I - Pointer to "cancel" variable */
599 http_t
*http
; /* New HTTP connection */
602 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
603 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
604 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
607 * Create the HTTP structure...
610 if ((http
= http_create(host
, port
, addrlist
, family
, encryption
, blocking
,
611 _HTTP_MODE_CLIENT
)) == NULL
)
615 * Optionally connect to the remote system...
618 if (msec
== 0 || !httpReconnect2(http
, msec
, cancel
))
622 * Could not connect to any known address - bail out!
632 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
634 * This function is now deprecated. Please use the @link httpConnect2@ function
640 http_t
* /* O - New HTTP connection */
642 const char *host
, /* I - Host to connect to */
643 int port
, /* I - Port number */
644 http_encryption_t encryption
) /* I - Type of encryption to use */
646 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
647 host
, port
, encryption
));
649 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
655 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
658 * @since CUPS 1.5/OS X 10.7@
661 int /* O - Status of call (0 = success) */
663 http_t
*http
, /* I - Connection to server */
664 cups_array_t
**credentials
) /* O - Array of credentials */
667 # elif defined(HAVE_GNUTLS)
668 # elif defined(HAVE_CDSASSL)
669 OSStatus error
; /* Error code */
670 SecTrustRef peerTrust
; /* Peer trust reference */
671 CFIndex count
; /* Number of credentials */
672 SecCertificateRef secCert
; /* Certificate reference */
673 CFDataRef data
; /* Certificate data */
674 int i
; /* Looping var */
675 # elif defined(HAVE_SSPISSL)
676 # endif /* HAVE_LIBSSL */
682 if (!http
|| !http
->tls
|| !credentials
)
688 # elif defined(HAVE_GNUTLS)
691 # elif defined(HAVE_CDSASSL)
692 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
694 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
696 count
= SecTrustGetCertificateCount(peerTrust
);
698 for (i
= 0; i
< count
; i
++)
700 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
701 if ((data
= SecCertificateCopyData(secCert
)))
703 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
704 CFDataGetLength(data
));
710 CFRelease(peerTrust
);
715 # elif defined(HAVE_SSPISSL)
720 # endif /* HAVE_LIBSSL */
725 * '_httpCreateCredentials()' - Create credentials in the internal format.
728 http_tls_credentials_t
/* O - Internal credentials */
729 _httpCreateCredentials(
730 cups_array_t
*credentials
) /* I - Array of credentials */
738 # elif defined(HAVE_GNUTLS)
741 # elif defined(HAVE_CDSASSL)
742 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
743 SecCertificateRef secCert
; /* Certificate reference */
744 CFDataRef data
; /* Credential data reference */
745 http_credential_t
*credential
; /* Credential data */
748 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
749 cupsArrayCount(credentials
),
750 &kCFTypeArrayCallBacks
)) == NULL
)
753 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
755 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
757 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
758 credential
->datalen
)))
760 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
763 CFArrayAppendValue(peerCerts
, secCert
);
773 # elif defined(HAVE_SSPISSL)
778 # endif /* HAVE_LIBSSL */
783 * 'httpDelete()' - Send a DELETE request to the server.
786 int /* O - Status of call (0 = success) */
787 httpDelete(http_t
*http
, /* I - Connection to server */
788 const char *uri
) /* I - URI to delete */
790 return (http_send(http
, HTTP_STATE_DELETE
, uri
));
795 * '_httpDisconnect()' - Disconnect a HTTP connection.
799 _httpDisconnect(http_t
*http
) /* I - Connection to server */
803 http_shutdown_ssl(http
);
804 #endif /* HAVE_SSL */
807 closesocket(http
->fd
);
817 * 'httpEncryption()' - Set the required encryption on the link.
820 int /* O - -1 on error, 0 on success */
821 httpEncryption(http_t
*http
, /* I - Connection to server */
822 http_encryption_t e
) /* I - New encryption preference */
824 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
830 http
->encryption
= e
;
832 if ((http
->encryption
== HTTP_ENCRYPTION_ALWAYS
&& !http
->tls
) ||
833 (http
->encryption
== HTTP_ENCRYPTION_NEVER
&& http
->tls
))
834 return (httpReconnect2(http
, 30000, NULL
));
835 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
836 return (http_upgrade(http
));
840 if (e
== HTTP_ENCRYPTION_ALWAYS
|| e
== HTTP_ENCRYPTION_REQUIRED
)
844 #endif /* HAVE_SSL */
849 * 'httpError()' - Get the last error on a connection.
852 int /* O - Error code (errno) value */
853 httpError(http_t
*http
) /* I - Connection to server */
856 return (http
->error
);
863 * 'httpFlush()' - Flush data from a HTTP connection.
867 httpFlush(http_t
*http
) /* I - Connection to server */
869 char buffer
[8192]; /* Junk buffer */
870 int blocking
; /* To block or not to block */
871 http_state_t oldstate
; /* Old state */
874 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
875 http_state_string(http
->state
)));
878 * Nothing to do if we are in the "waiting" state...
881 if (http
->state
== HTTP_STATE_WAITING
)
885 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
888 blocking
= http
->blocking
;
892 * Read any data we can...
895 oldstate
= http
->state
;
896 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
899 * Restore blocking and reset the connection if we didn't get all of
900 * the remaining data...
903 http
->blocking
= blocking
;
905 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
909 * Didn't get the data back, so close the current connection.
914 http_content_coding_finish(http
);
915 #endif /* HAVE_LIBZ */
917 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
919 http
->state
= HTTP_STATE_WAITING
;
923 http_shutdown_ssl(http
);
924 #endif /* HAVE_SSL */
927 closesocket(http
->fd
);
938 * 'httpFlushWrite()' - Flush data in write buffer.
940 * @since CUPS 1.2/OS X 10.5@
943 int /* O - Bytes written or -1 on error */
944 httpFlushWrite(http_t
*http
) /* I - Connection to server */
946 int bytes
; /* Bytes written */
949 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
950 http
? http
->data_encoding
: -1));
952 if (!http
|| !http
->wused
)
954 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
955 "1httpFlushWrite: No connection.");
959 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
960 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
962 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
966 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
973 * '_httpFreeCredentials()' - Free internal credentials.
977 _httpFreeCredentials(
978 http_tls_credentials_t credentials
) /* I - Internal credentials */
986 #elif defined(HAVE_GNUTLS)
989 #elif defined(HAVE_CDSASSL)
990 CFRelease(credentials
);
992 #elif defined(HAVE_SSPISSL)
995 #endif /* HAVE_LIBSSL */
1000 * 'httpFreeCredentials()' - Free an array of credentials.
1004 httpFreeCredentials(
1005 cups_array_t
*credentials
) /* I - Array of credentials */
1007 http_credential_t
*credential
; /* Credential */
1010 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
1012 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
1014 cupsArrayRemove(credentials
, credential
);
1015 free((void *)credential
->data
);
1019 cupsArrayDelete(credentials
);
1024 * 'httpGet()' - Send a GET request to the server.
1027 int /* O - Status of call (0 = success) */
1028 httpGet(http_t
*http
, /* I - Connection to server */
1029 const char *uri
) /* I - URI to get */
1031 return (http_send(http
, HTTP_STATE_GET
, uri
));
1036 * 'httpGetAuthString()' - Get the current authorization string.
1038 * The authorization string is set by cupsDoAuthentication() and
1039 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
1040 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
1043 * @since CUPS 1.3/OS X 10.5@
1046 char * /* O - Authorization string */
1047 httpGetAuthString(http_t
*http
) /* I - Connection to server */
1050 return (http
->authstring
);
1057 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
1059 * @since CUPS 1.2/OS X 10.5@
1062 int /* O - 1 if blocking, 0 if non-blocking */
1063 httpGetBlocking(http_t
*http
) /* I - Connection to server */
1065 return (http
? http
->blocking
: 0);
1070 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
1071 * the client and server.
1073 * This function uses the value of the Accepts-Encoding HTTP header and must be
1074 * called after receiving a response from the server or a request from the
1075 * client. The value returned can be use in subsequent requests (for clients)
1076 * or in the response (for servers) in order to compress the content stream.
1081 const char * /* O - Content-Coding value or
1082 @code NULL@ for the identity
1084 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
1087 if (http
&& http
->accept_encoding
)
1089 int i
; /* Looping var */
1090 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
1091 *start
, /* Start of coding value */
1092 *end
; /* End of coding value */
1093 double qvalue
; /* "qvalue" for coding */
1094 struct lconv
*loc
= localeconv(); /* Locale data */
1095 static const char * const codings
[] =
1096 { /* Supported content codings */
1103 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
1105 for (start
= temp
; *start
; start
= end
)
1108 * Find the end of the coding name...
1113 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
1119 * Grab the qvalue as needed...
1122 if (!strncmp(end
, ";q=", 3))
1123 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1126 * Skip past all attributes...
1130 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1136 while (*end
&& isspace(*end
& 255))
1140 * Check value if it matches something we support...
1146 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1147 if (!strcmp(start
, codings
[i
]))
1148 return (codings
[i
]);
1151 #endif /* HAVE_LIBZ */
1158 * 'httpGetCookie()' - Get any cookie data from the response.
1160 * @since CUPS 1.1.19/OS X 10.3@
1163 const char * /* O - Cookie data or NULL */
1164 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1166 return (http
? http
->cookie
: NULL
);
1171 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1173 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1174 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1179 http_status_t
/* O - Expect: status, if any */
1180 httpGetExpect(http_t
*http
) /* I - Connection to client */
1183 return (HTTP_STATUS_ERROR
);
1185 return (http
->expect
);
1190 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1192 * @since CUPS 1.2/OS X 10.5@
1195 int /* O - File descriptor or -1 if none */
1196 httpGetFd(http_t
*http
) /* I - Connection to server */
1198 return (http
? http
->fd
: -1);
1203 * 'httpGetField()' - Get a field value from a request/response.
1206 const char * /* O - Field value */
1207 httpGetField(http_t
*http
, /* I - Connection to server */
1208 http_field_t field
) /* I - Field to get */
1210 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1215 case HTTP_FIELD_ACCEPT_ENCODING
:
1216 return (http
->accept_encoding
);
1218 case HTTP_FIELD_ALLOW
:
1219 return (http
->allow
);
1221 case HTTP_FIELD_SERVER
:
1222 return (http
->server
);
1224 case HTTP_FIELD_AUTHORIZATION
:
1225 if (http
->field_authorization
)
1228 * Special case for WWW-Authenticate: as its contents can be
1229 * longer than HTTP_MAX_VALUE...
1232 return (http
->field_authorization
);
1236 return (http
->fields
[field
]);
1242 * 'httpGetLength()' - Get the amount of data remaining from the
1243 * content-length or transfer-encoding fields.
1245 * This function is deprecated and will not return lengths larger than
1246 * 2^31 - 1; use httpGetLength2() instead.
1251 int /* O - Content length */
1252 httpGetLength(http_t
*http
) /* I - Connection to server */
1255 * Get the read content length and return the 32-bit value.
1260 httpGetLength2(http
);
1262 return (http
->_data_remaining
);
1270 * 'httpGetLength2()' - Get the amount of data remaining from the
1271 * content-length or transfer-encoding fields.
1273 * This function returns the complete content length, even for
1274 * content larger than 2^31 - 1.
1276 * @since CUPS 1.2/OS X 10.5@
1279 off_t
/* O - Content length */
1280 httpGetLength2(http_t
*http
) /* I - Connection to server */
1282 off_t remaining
; /* Remaining length */
1285 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1286 http_state_string(http
->state
)));
1291 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1293 DEBUG_puts("4httpGetLength2: chunked request!");
1299 * The following is a hack for HTTP servers that don't send a
1300 * Content-Length or Transfer-Encoding field...
1302 * If there is no Content-Length then the connection must close
1303 * after the transfer is complete...
1306 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1309 * Default content length is 0 for errors and certain types of operations,
1310 * and 2^31-1 for other successful requests...
1313 if (http
->status
>= HTTP_STATUS_MULTIPLE_CHOICES
||
1314 http
->state
== HTTP_STATE_OPTIONS
||
1315 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1316 http
->state
== HTTP_STATE_HEAD
||
1317 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1318 http
->state
== HTTP_STATE_DELETE
||
1319 http
->state
== HTTP_STATE_TRACE
||
1320 http
->state
== HTTP_STATE_CONNECT
)
1323 remaining
= 2147483647;
1325 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1329 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1330 CUPS_LLCAST remaining
));
1338 * 'httpGets()' - Get a line of text from a HTTP connection.
1341 char * /* O - Line or NULL */
1342 httpGets(char *line
, /* I - Line to read into */
1343 int length
, /* I - Max length of buffer */
1344 http_t
*http
) /* I - Connection to server */
1346 char *lineptr
, /* Pointer into line */
1347 *lineend
, /* End of line */
1348 *bufptr
, /* Pointer into input buffer */
1349 *bufend
; /* Pointer to end of buffer */
1350 int bytes
, /* Number of bytes read */
1351 eol
; /* End-of-line? */
1354 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1356 if (!http
|| !line
|| length
<= 1)
1360 * Read a line from the buffer...
1365 lineend
= line
+ length
- 1;
1368 while (lineptr
< lineend
)
1371 * Pre-load the buffer as needed...
1380 while (http
->used
== 0)
1383 * No newline; see if there is more data to be read...
1386 while (!_httpWait(http
, http
->wait_value
, 1))
1388 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1391 DEBUG_puts("3httpGets: Timed out!");
1393 http
->error
= WSAETIMEDOUT
;
1395 http
->error
= ETIMEDOUT
;
1400 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1401 HTTP_MAX_BUFFER
- http
->used
);
1403 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1408 * Nope, can't get a line this time...
1412 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1414 if (WSAGetLastError() == WSAEINTR
)
1416 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1418 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1421 http
->error
= WSAGetLastError();
1423 else if (WSAGetLastError() != http
->error
)
1425 http
->error
= WSAGetLastError();
1430 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1434 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1436 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1438 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1441 http
->error
= errno
;
1443 else if (errno
!= http
->error
)
1445 http
->error
= errno
;
1452 else if (bytes
== 0)
1454 http
->error
= EPIPE
;
1460 * Yup, update the amount used...
1463 http
->used
+= bytes
;
1467 * Now copy as much of the current line as possible...
1470 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1471 lineptr
< lineend
&& bufptr
< bufend
;)
1473 if (*bufptr
== 0x0a)
1479 else if (*bufptr
== 0x0d)
1482 *lineptr
++ = *bufptr
++;
1485 http
->used
-= (int)(bufptr
- http
->buffer
);
1487 memmove(http
->buffer
, bufptr
, http
->used
);
1495 http
->activity
= time(NULL
);
1499 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1505 DEBUG_puts("3httpGets: No new line available!");
1512 * 'httpGetState()' - Get the current state of the HTTP request.
1515 http_state_t
/* O - HTTP state */
1516 httpGetState(http_t
*http
) /* I - Connection to server */
1518 return (http
? http
->state
: HTTP_STATE_ERROR
);
1523 * 'httpGetStatus()' - Get the status of the last HTTP request.
1525 * @since CUPS 1.2/OS X 10.5@
1528 http_status_t
/* O - HTTP status */
1529 httpGetStatus(http_t
*http
) /* I - Connection to server */
1531 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1536 * 'httpGetSubField()' - Get a sub-field value.
1541 char * /* O - Value or NULL */
1542 httpGetSubField(http_t
*http
, /* I - Connection to server */
1543 http_field_t field
, /* I - Field index */
1544 const char *name
, /* I - Name of sub-field */
1545 char *value
) /* O - Value string */
1547 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1552 * 'httpGetSubField2()' - Get a sub-field value.
1554 * @since CUPS 1.2/OS X 10.5@
1557 char * /* O - Value or NULL */
1558 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1559 http_field_t field
, /* I - Field index */
1560 const char *name
, /* I - Name of sub-field */
1561 char *value
, /* O - Value string */
1562 int valuelen
) /* I - Size of value buffer */
1564 const char *fptr
; /* Pointer into field */
1565 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1566 *ptr
, /* Pointer into string buffer */
1567 *end
; /* End of value buffer */
1569 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1570 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1572 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1573 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1576 end
= value
+ valuelen
- 1;
1578 for (fptr
= http
->fields
[field
]; *fptr
;)
1581 * Skip leading whitespace...
1584 while (_cups_isspace(*fptr
))
1594 * Get the sub-field name...
1598 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1599 ptr
< (temp
+ sizeof(temp
) - 1);
1604 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1607 * Skip trailing chars up to the '='...
1610 while (_cups_isspace(*fptr
))
1620 * Skip = and leading whitespace...
1625 while (_cups_isspace(*fptr
))
1631 * Read quoted string...
1634 for (ptr
= value
, fptr
++;
1635 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1640 while (*fptr
&& *fptr
!= '\"')
1649 * Read unquoted string...
1653 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1658 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1662 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1665 * See if this is the one...
1668 if (!strcmp(name
, temp
))
1670 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1677 DEBUG_puts("3httpGetSubField2: Returning NULL");
1684 * 'httpGetVersion()' - Get the HTTP version at the other end.
1687 http_version_t
/* O - Version number */
1688 httpGetVersion(http_t
*http
) /* I - Connection to server */
1690 return (http
? http
->version
: HTTP_VERSION_1_0
);
1695 * 'httpHead()' - Send a HEAD request to the server.
1698 int /* O - Status of call (0 = success) */
1699 httpHead(http_t
*http
, /* I - Connection to server */
1700 const char *uri
) /* I - URI for head */
1702 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1703 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1708 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1709 * default HTTP proxy (if any).
1713 httpInitialize(void)
1715 static int initialized
= 0; /* Have we been called before? */
1717 WSADATA winsockdata
; /* WinSock data */
1720 int i
; /* Looping var */
1721 unsigned char data
[1024]; /* Seed data */
1722 #endif /* HAVE_LIBSSL */
1728 _cupsGlobalUnlock();
1733 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1735 #elif !defined(SO_NOSIGPIPE)
1737 * Ignore SIGPIPE signals...
1741 sigset(SIGPIPE
, SIG_IGN
);
1743 # elif defined(HAVE_SIGACTION)
1744 struct sigaction action
; /* POSIX sigaction data */
1747 memset(&action
, 0, sizeof(action
));
1748 action
.sa_handler
= SIG_IGN
;
1749 sigaction(SIGPIPE
, &action
, NULL
);
1752 signal(SIGPIPE
, SIG_IGN
);
1753 # endif /* !SO_NOSIGPIPE */
1758 * Initialize GNU TLS...
1761 gnutls_global_init();
1763 #elif defined(HAVE_LIBSSL)
1765 * Initialize OpenSSL...
1768 SSL_load_error_strings();
1772 * Using the current time is a dubious random seed, but on some systems
1773 * it is the best we can do (on others, this seed isn't even used...)
1776 CUPS_SRAND(time(NULL
));
1778 for (i
= 0; i
< sizeof(data
); i
++)
1779 data
[i
] = CUPS_RAND();
1781 RAND_seed(data
, sizeof(data
));
1782 #endif /* HAVE_GNUTLS */
1785 _cupsGlobalUnlock();
1790 * 'httpOptions()' - Send an OPTIONS request to the server.
1793 int /* O - Status of call (0 = success) */
1794 httpOptions(http_t
*http
, /* I - Connection to server */
1795 const char *uri
) /* I - URI for options */
1797 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1802 * 'httpPeek()' - Peek at data from a HTTP connection.
1804 * This function copies available data from the given HTTP connection, reading
1805 * a buffer as needed. The data is still available for reading using
1806 * @link httpRead@ or @link httpRead2@.
1808 * For non-blocking connections the usual timeouts apply.
1813 ssize_t
/* O - Number of bytes copied */
1814 httpPeek(http_t
*http
, /* I - Connection to server */
1815 char *buffer
, /* I - Buffer for data */
1816 size_t length
) /* I - Maximum number of bytes */
1818 ssize_t bytes
; /* Bytes read */
1819 char len
[32]; /* Length string */
1822 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1823 http
, buffer
, CUPS_LLCAST length
));
1825 if (http
== NULL
|| buffer
== NULL
)
1828 http
->activity
= time(NULL
);
1834 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1835 http
->data_remaining
<= 0)
1837 DEBUG_puts("2httpPeek: Getting chunk length...");
1839 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1841 DEBUG_puts("1httpPeek: Could not get length!");
1847 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1848 if (!httpGets(len
, sizeof(len
), http
))
1850 DEBUG_puts("1httpPeek: Could not get chunk length.");
1855 http
->data_remaining
= strtoll(len
, NULL
, 16);
1857 if (http
->data_remaining
< 0)
1859 DEBUG_puts("1httpPeek: Negative chunk length!");
1864 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1865 CUPS_LLCAST http
->data_remaining
));
1867 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1870 * A zero-length chunk ends a transfer; unless we are reading POST
1876 http_content_coding_finish(http
);
1877 #endif /* HAVE_LIBZ */
1879 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1880 httpGets(len
, sizeof(len
), http
);
1882 if (http
->state
== HTTP_STATE_POST_RECV
)
1885 http
->state
= HTTP_STATE_STATUS
;
1887 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1888 http_state_string(http
->state
)));
1891 * Prevent future reads for this request...
1894 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1898 else if (length
> (size_t)http
->data_remaining
)
1899 length
= (size_t)http
->data_remaining
;
1902 if (http
->used
== 0 &&
1903 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1905 if (http
->used
== 0)
1906 #endif /* HAVE_LIBZ */
1909 * Buffer small reads for better performance...
1912 ssize_t buflen
; /* Length of read for buffer */
1914 if (!http
->blocking
)
1916 while (!httpWait(http
, http
->wait_value
))
1918 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1925 if (http
->data_remaining
> sizeof(http
->buffer
))
1926 buflen
= sizeof(http
->buffer
);
1928 buflen
= http
->data_remaining
;
1930 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1931 bytes
= http_read(http
, http
->buffer
, buflen
);
1933 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1934 CUPS_LLCAST bytes
));
1938 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1948 # ifdef HAVE_INFLATECOPY
1949 int zerr
; /* Decompressor error */
1950 z_stream stream
; /* Copy of decompressor stream */
1952 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1954 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1955 /* Number of bytes to copy */
1957 if (http
->stream
.avail_in
> 0 &&
1958 http
->stream
.next_in
> http
->dbuffer
)
1959 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1961 http
->stream
.next_in
= http
->dbuffer
;
1963 if (buflen
> http
->data_remaining
)
1964 buflen
= http
->data_remaining
;
1966 if (buflen
> http
->used
)
1967 buflen
= http
->used
;
1969 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1970 "decompression buffer.", (int)buflen
));
1972 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
1973 http
->stream
.avail_in
+= buflen
;
1974 http
->used
-= buflen
;
1975 http
->data_remaining
-= buflen
;
1978 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
1981 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
1982 (int)http
->stream
.avail_in
));
1984 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
1986 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
1987 http
->error
= ENOMEM
;
1991 stream
.next_out
= (Bytef
*)buffer
;
1992 stream
.avail_out
= length
;
1994 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
1995 inflateEnd(&stream
);
1999 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
2001 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
2002 http
->stream
.avail_in
);
2009 bytes
= length
- http
->stream
.avail_out
;
2012 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
2013 "work with compressed streams.");
2015 # endif /* HAVE_INFLATECOPY */
2018 #endif /* HAVE_LIBZ */
2021 if (length
> (size_t)http
->used
)
2022 length
= (size_t)http
->used
;
2024 bytes
= (ssize_t
)length
;
2026 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
2029 memcpy(buffer
, http
->buffer
, length
);
2037 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2040 http
->error
= WSAGetLastError();
2042 if (errno
== EINTR
|| errno
== EAGAIN
)
2045 http
->error
= errno
;
2048 else if (bytes
== 0)
2050 http
->error
= EPIPE
;
2057 /* For OS X 10.8 and earlier */
2058 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
2059 { return (httpPeek(http
, buffer
, length
)); }
2063 * 'httpPost()' - Send a POST request to the server.
2066 int /* O - Status of call (0 = success) */
2067 httpPost(http_t
*http
, /* I - Connection to server */
2068 const char *uri
) /* I - URI for post */
2070 return (http_send(http
, HTTP_STATE_POST
, uri
));
2075 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
2080 int /* O - Number of bytes written */
2081 httpPrintf(http_t
*http
, /* I - Connection to server */
2082 const char *format
, /* I - printf-style format string */
2083 ...) /* I - Additional args as needed */
2085 int bytes
; /* Number of bytes to write */
2086 char buf
[16384]; /* Buffer for formatted string */
2087 va_list ap
; /* Variable argument pointer */
2090 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
2092 va_start(ap
, format
);
2093 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
2096 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
2098 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
2099 return (httpWrite2(http
, buf
, bytes
));
2104 DEBUG_puts("4httpPrintf: flushing existing data...");
2106 if (httpFlushWrite(http
) < 0)
2110 return (http_write(http
, buf
, bytes
));
2116 * 'httpPut()' - Send a PUT request to the server.
2119 int /* O - Status of call (0 = success) */
2120 httpPut(http_t
*http
, /* I - Connection to server */
2121 const char *uri
) /* I - URI to put */
2123 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2124 return (http_send(http
, HTTP_STATE_PUT
, uri
));
2129 * 'httpRead()' - Read data from a HTTP connection.
2131 * This function is deprecated. Use the httpRead2() function which can
2132 * read more than 2GB of data.
2137 int /* O - Number of bytes read */
2138 httpRead(http_t
*http
, /* I - Connection to server */
2139 char *buffer
, /* I - Buffer for data */
2140 int length
) /* I - Maximum number of bytes */
2142 return ((int)httpRead2(http
, buffer
, length
));
2147 * 'httpRead2()' - Read data from a HTTP connection.
2149 * @since CUPS 1.2/OS X 10.5@
2152 ssize_t
/* O - Number of bytes read */
2153 httpRead2(http_t
*http
, /* I - Connection to server */
2154 char *buffer
, /* I - Buffer for data */
2155 size_t length
) /* I - Maximum number of bytes */
2157 ssize_t bytes
; /* Bytes read */
2161 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2162 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
2163 http
, buffer
, CUPS_LLCAST length
,
2165 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2167 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2168 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
2169 http
, buffer
, CUPS_LLCAST length
,
2170 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2171 #endif /* HAVE_LIBZ */
2173 if (http
== NULL
|| buffer
== NULL
)
2176 http
->activity
= time(NULL
);
2187 if (http
->stream
.avail_in
> 0)
2189 int zerr
; /* Decompressor error */
2191 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2192 (int)http
->stream
.avail_in
, (int)length
));
2194 http
->stream
.next_out
= (Bytef
*)buffer
;
2195 http
->stream
.avail_out
= length
;
2197 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2199 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2201 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2202 http
->stream
.avail_in
);
2209 bytes
= length
- http
->stream
.avail_out
;
2211 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2212 http
->stream
.avail_in
, http
->stream
.avail_out
,
2220 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2221 /* Additional bytes for buffer */
2225 if (http
->stream
.avail_in
> 0 &&
2226 http
->stream
.next_in
> http
->dbuffer
)
2227 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2229 http
->stream
.next_in
= http
->dbuffer
;
2231 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2232 "decompression buffer.", (int)buflen
));
2234 if (http
->data_remaining
> 0)
2236 if (buflen
> http
->data_remaining
)
2237 buflen
= http
->data_remaining
;
2239 bytes
= http_read_buffered(http
,
2240 (char *)http
->dbuffer
+
2241 http
->stream
.avail_in
, buflen
);
2243 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2244 bytes
= http_read_chunk(http
,
2245 (char *)http
->dbuffer
+
2246 http
->stream
.avail_in
, buflen
);
2252 else if (bytes
== 0)
2255 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2256 "decompression buffer.", CUPS_LLCAST bytes
));
2258 http
->data_remaining
-= bytes
;
2259 http
->stream
.avail_in
+= bytes
;
2261 if (http
->data_remaining
<= 0 &&
2262 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2265 * Read the trailing blank line now...
2268 char len
[32]; /* Length string */
2270 httpGets(len
, sizeof(len
), http
);
2282 #endif /* HAVE_LIBZ */
2283 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2285 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2287 http
->data_remaining
-= bytes
;
2289 if (http
->data_remaining
<= 0)
2292 * Read the trailing blank line now...
2295 char len
[32]; /* Length string */
2297 httpGets(len
, sizeof(len
), http
);
2301 else if (http
->data_remaining
<= 0)
2304 * No more data to read...
2311 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2314 if (length
> (size_t)http
->data_remaining
)
2315 length
= (size_t)http
->data_remaining
;
2317 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2319 http
->data_remaining
-= bytes
;
2321 if (http
->data_remaining
<= 0 &&
2322 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2325 * Read the trailing blank line now...
2328 char len
[32]; /* Length string */
2330 httpGets(len
, sizeof(len
), http
);
2337 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2338 #endif /* HAVE_LIBZ */
2339 ((http
->data_remaining
<= 0 &&
2340 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2341 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2345 http_content_coding_finish(http
);
2346 #endif /* HAVE_LIBZ */
2348 if (http
->state
== HTTP_STATE_POST_RECV
)
2350 else if (http
->state
== HTTP_STATE_GET_SEND
||
2351 http
->state
== HTTP_STATE_POST_SEND
)
2352 http
->state
= HTTP_STATE_WAITING
;
2354 http
->state
= HTTP_STATE_STATUS
;
2356 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2357 http_state_string(http
->state
)));
2364 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2366 * '_httpReadCDSA()' - Read function for the CDSA library.
2369 OSStatus
/* O - -1 on error, 0 on success */
2371 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2372 void *data
, /* I - Data buffer */
2373 size_t *dataLength
) /* IO - Number of bytes */
2375 OSStatus result
; /* Return value */
2376 ssize_t bytes
; /* Number of bytes read */
2377 http_t
*http
; /* HTTP connection */
2380 http
= (http_t
*)connection
;
2382 if (!http
->blocking
)
2385 * Make sure we have data before we read...
2388 while (!_httpWait(http
, http
->wait_value
, 0))
2390 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2393 http
->error
= ETIMEDOUT
;
2400 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2402 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2404 if (bytes
== *dataLength
)
2410 *dataLength
= bytes
;
2411 result
= errSSLWouldBlock
;
2418 result
= errSSLClosedGraceful
;
2419 else if (errno
== EAGAIN
)
2420 result
= errSSLWouldBlock
;
2422 result
= errSSLClosedAbort
;
2427 #endif /* HAVE_SSL && HAVE_CDSASSL */
2430 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2432 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2435 ssize_t
/* O - Number of bytes read or -1 on error */
2437 gnutls_transport_ptr ptr
, /* I - Connection to server */
2438 void *data
, /* I - Buffer */
2439 size_t length
) /* I - Number of bytes to read */
2441 http_t
*http
; /* HTTP connection */
2442 ssize_t bytes
; /* Bytes read */
2445 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2447 http
= (http_t
*)ptr
;
2449 if (!http
->blocking
)
2452 * Make sure we have data before we read...
2455 while (!_httpWait(http
, http
->wait_value
, 0))
2457 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2460 http
->error
= ETIMEDOUT
;
2465 bytes
= recv(http
->fd
, data
, length
, 0);
2466 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2469 #endif /* HAVE_SSL && HAVE_GNUTLS */
2473 * 'httpReadRequest()' - Read a HTTP request from a connection.
2478 http_state_t
/* O - New state of connection */
2479 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2480 char *uri
, /* I - URI buffer */
2481 size_t urilen
) /* I - Size of URI buffer */
2483 char line
[4096], /* HTTP request line */
2484 *req_method
, /* HTTP request method */
2485 *req_uri
, /* HTTP request URI */
2486 *req_version
; /* HTTP request version number string */
2490 * Range check input...
2493 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2494 http
, uri
, CUPS_LLCAST urilen
));
2499 if (!http
|| !uri
|| urilen
< 1)
2501 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2502 return (HTTP_STATE_ERROR
);
2504 else if (http
->state
!= HTTP_STATE_WAITING
)
2506 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2507 http_state_string(http
->state
)));
2508 return (HTTP_STATE_ERROR
);
2515 httpClearFields(http
);
2517 http
->activity
= time(NULL
);
2518 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2519 http
->data_remaining
= 0;
2520 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2521 http
->status
= HTTP_STATUS_OK
;
2522 http
->version
= HTTP_VERSION_1_1
;
2525 * Read a line from the socket...
2528 if (!httpGets(line
, sizeof(line
), http
))
2530 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2531 return (HTTP_STATE_ERROR
);
2536 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2537 return (HTTP_STATE_WAITING
);
2540 DEBUG_printf(("1httpReadRequest: %s", line
));
2549 while (*req_uri
&& !isspace(*req_uri
& 255))
2554 DEBUG_puts("1httpReadRequest: No request URI.");
2555 return (HTTP_STATE_ERROR
);
2560 while (*req_uri
&& isspace(*req_uri
& 255))
2563 req_version
= req_uri
;
2565 while (*req_version
&& !isspace(*req_version
& 255))
2570 DEBUG_puts("1httpReadRequest: No request protocol version.");
2571 return (HTTP_STATE_ERROR
);
2574 *req_version
++ = '\0';
2576 while (*req_version
&& isspace(*req_version
& 255))
2583 if (!strcmp(req_method
, "OPTIONS"))
2584 http
->state
= HTTP_STATE_OPTIONS
;
2585 else if (!strcmp(req_method
, "GET"))
2586 http
->state
= HTTP_STATE_GET
;
2587 else if (!strcmp(req_method
, "HEAD"))
2588 http
->state
= HTTP_STATE_HEAD
;
2589 else if (!strcmp(req_method
, "POST"))
2590 http
->state
= HTTP_STATE_POST
;
2591 else if (!strcmp(req_method
, "PUT"))
2592 http
->state
= HTTP_STATE_PUT
;
2593 else if (!strcmp(req_method
, "DELETE"))
2594 http
->state
= HTTP_STATE_DELETE
;
2595 else if (!strcmp(req_method
, "TRACE"))
2596 http
->state
= HTTP_STATE_TRACE
;
2597 else if (!strcmp(req_method
, "CONNECT"))
2598 http
->state
= HTTP_STATE_CONNECT
;
2601 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2602 return (HTTP_STATE_UNKNOWN_METHOD
);
2605 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2606 http_state_string(http
->state
)));
2608 if (!strcmp(req_version
, "HTTP/1.0"))
2610 http
->version
= HTTP_VERSION_1_0
;
2611 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2613 else if (!strcmp(req_version
, "HTTP/1.1"))
2615 http
->version
= HTTP_VERSION_1_1
;
2616 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2620 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2621 return (HTTP_STATE_UNKNOWN_VERSION
);
2624 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2625 strlcpy(uri
, req_uri
, urilen
);
2627 return (http
->state
);
2632 * 'httpReconnect()' - Reconnect to a HTTP server.
2634 * This function is deprecated. Please use the @link httpReconnect2@ function
2640 int /* O - 0 on success, non-zero on failure */
2641 httpReconnect(http_t
*http
) /* I - Connection to server */
2643 DEBUG_printf(("httpReconnect(http=%p)", http
));
2645 return (httpReconnect2(http
, 30000, NULL
));
2650 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2654 int /* O - 0 on success, non-zero on failure */
2655 httpReconnect2(http_t
*http
, /* I - Connection to server */
2656 int msec
, /* I - Timeout in milliseconds */
2657 int *cancel
) /* I - Pointer to "cancel" variable */
2659 http_addrlist_t
*addr
; /* Connected address */
2661 http_addrlist_t
*current
; /* Current address */
2662 char temp
[256]; /* Temporary address string */
2666 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2671 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2678 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2679 http_shutdown_ssl(http
);
2681 #endif /* HAVE_SSL */
2684 * Close any previously open socket...
2689 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2692 closesocket(http
->fd
);
2701 * Reset all state (except fields, which may be reused)...
2704 http
->state
= HTTP_STATE_WAITING
;
2705 http
->version
= HTTP_VERSION_1_1
;
2706 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2707 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2708 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2709 http
->_data_remaining
= 0;
2711 http
->data_remaining
= 0;
2712 http
->hostaddr
= NULL
;
2716 * Connect to the server...
2720 for (current
= http
->addrlist
; current
; current
= current
->next
)
2721 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2722 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2723 httpAddrPort(&(current
->addr
))));
2726 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2730 * Unable to connect...
2734 http
->error
= WSAGetLastError();
2736 http
->error
= errno
;
2738 http
->status
= HTTP_STATUS_ERROR
;
2740 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2741 strerror(http
->error
)));
2746 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2748 if (http
->timeout_value
> 0)
2749 http_set_timeout(http
->fd
, http
->timeout_value
);
2751 http
->hostaddr
= &(addr
->addr
);
2755 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2758 * Always do encryption via SSL.
2761 if (http_setup_ssl(http
) != 0)
2764 closesocket(http
->fd
);
2772 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2773 return (http_upgrade(http
));
2774 #endif /* HAVE_SSL */
2776 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2777 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2778 httpAddrPort(http
->hostaddr
)));
2785 * 'httpSetAuthString()' - Set the current authorization string.
2787 * This function just stores a copy of the current authorization string in
2788 * the HTTP connection object. You must still call httpSetField() to set
2789 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2790 * httpHead(), httpOptions(), httpPost, or httpPut().
2792 * @since CUPS 1.3/OS X 10.5@
2796 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2797 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2798 const char *data
) /* I - Auth data (NULL for none) */
2801 * Range check input...
2807 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2808 free(http
->authstring
);
2810 http
->authstring
= http
->_authstring
;
2815 * Set the current authorization string...
2818 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2821 if (len
> (int)sizeof(http
->_authstring
))
2823 if ((temp
= malloc(len
)) == NULL
)
2824 len
= sizeof(http
->_authstring
);
2826 http
->authstring
= temp
;
2830 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2832 strlcpy(http
->authstring
, scheme
, len
);
2837 * Clear the current authorization string...
2840 http
->_authstring
[0] = '\0';
2846 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2849 * @since CUPS 1.5/OS X 10.7@
2852 int /* O - Status of call (0 = success) */
2853 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2854 cups_array_t
*credentials
) /* I - Array of credentials */
2856 if (!http
|| cupsArrayCount(credentials
) < 1)
2859 _httpFreeCredentials(http
->tls_credentials
);
2861 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2863 return (http
->tls_credentials
? 0 : -1);
2868 * 'httpSetCookie()' - Set the cookie value(s).
2870 * @since CUPS 1.1.19/OS X 10.3@
2874 httpSetCookie(http_t
*http
, /* I - Connection */
2875 const char *cookie
) /* I - Cookie string */
2884 http
->cookie
= strdup(cookie
);
2886 http
->cookie
= NULL
;
2891 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2893 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2894 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2900 httpSetDefaultField(http_t
*http
, /* I - Connection to server */
2901 http_field_t field
, /* I - Field index */
2902 const char *value
)/* I - Value */
2904 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2905 http
, field
, http_fields
[field
], value
));
2912 case HTTP_FIELD_ACCEPT_ENCODING
:
2913 if (http
->default_accept_encoding
)
2914 _cupsStrFree(http
->default_accept_encoding
);
2916 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2919 case HTTP_FIELD_SERVER
:
2920 if (http
->default_server
)
2921 _cupsStrFree(http
->default_server
);
2923 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2926 case HTTP_FIELD_USER_AGENT
:
2927 if (http
->default_user_agent
)
2928 _cupsStrFree(http
->default_user_agent
);
2930 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2934 DEBUG_puts("1httpSetDefaultField: Ignored.");
2941 * 'httpSetExpect()' - Set the Expect: header in a request.
2943 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2946 * @since CUPS 1.2/OS X 10.5@
2950 httpSetExpect(http_t
*http
, /* I - Connection to server */
2951 http_status_t expect
) /* I - HTTP status to expect
2952 (@code HTTP_STATUS_CONTINUE@) */
2954 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2957 http
->expect
= expect
;
2962 * 'httpSetField()' - Set the value of an HTTP header.
2966 httpSetField(http_t
*http
, /* I - Connection to server */
2967 http_field_t field
, /* I - Field index */
2968 const char *value
) /* I - Value */
2970 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2971 field
, http_fields
[field
], value
));
2974 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2975 field
>= HTTP_FIELD_MAX
||
2981 case HTTP_FIELD_ACCEPT_ENCODING
:
2982 if (http
->accept_encoding
)
2983 _cupsStrFree(http
->accept_encoding
);
2985 http
->accept_encoding
= _cupsStrAlloc(value
);
2988 case HTTP_FIELD_ALLOW
:
2990 _cupsStrFree(http
->allow
);
2992 http
->allow
= _cupsStrAlloc(value
);
2995 case HTTP_FIELD_SERVER
:
2997 _cupsStrFree(http
->server
);
2999 http
->server
= _cupsStrAlloc(value
);
3003 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
3007 if (field
== HTTP_FIELD_AUTHORIZATION
)
3010 * Special case for Authorization: as its contents can be
3011 * longer than HTTP_MAX_VALUE
3014 if (http
->field_authorization
)
3015 free(http
->field_authorization
);
3017 http
->field_authorization
= strdup(value
);
3019 else if (field
== HTTP_FIELD_HOST
)
3022 * Special-case for Host: as we don't want a trailing "." on the hostname and
3023 * need to bracket IPv6 numeric addresses.
3026 char *ptr
= strchr(value
, ':');
3028 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
3031 * Bracket IPv6 numeric addresses...
3033 * This is slightly inefficient (basically copying twice), but is an edge
3034 * case and not worth optimizing...
3037 snprintf(http
->fields
[HTTP_FIELD_HOST
],
3038 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
3043 * Check for a trailing dot on the hostname...
3046 ptr
= http
->fields
[HTTP_FIELD_HOST
];
3050 ptr
+= strlen(ptr
) - 1;
3058 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
3059 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
3061 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
3062 http_content_coding_start(http
, value
);
3064 #endif /* HAVE_LIBZ */
3069 * 'httpSetLength()' - Set the content-length and content-encoding.
3071 * @since CUPS 1.2/OS X 10.5@
3075 httpSetLength(http_t
*http
, /* I - Connection to server */
3076 size_t length
) /* I - Length (0 for chunked) */
3078 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
3079 CUPS_LLCAST length
));
3086 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
3088 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
3092 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
3093 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
3094 CUPS_LLFMT
, CUPS_LLCAST length
);
3100 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
3102 * The optional timeout callback receives both the HTTP connection and a user
3103 * data pointer and must return 1 to continue or 0 to error (time) out.
3105 * @since CUPS 1.5/OS X 10.7@
3110 http_t
*http
, /* I - Connection to server */
3111 double timeout
, /* I - Number of seconds for timeout,
3112 must be greater than 0 */
3113 http_timeout_cb_t cb
, /* I - Callback function or NULL */
3114 void *user_data
) /* I - User data pointer */
3116 if (!http
|| timeout
<= 0.0)
3119 http
->timeout_cb
= cb
;
3120 http
->timeout_data
= user_data
;
3121 http
->timeout_value
= timeout
;
3124 http_set_timeout(http
->fd
, timeout
);
3126 http_set_wait(http
);
3131 * 'httpTrace()' - Send an TRACE request to the server.
3134 int /* O - Status of call (0 = success) */
3135 httpTrace(http_t
*http
, /* I - Connection to server */
3136 const char *uri
) /* I - URI for trace */
3138 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
3143 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3145 * Note: Unlike httpUpdate(), this function does not flush pending write data
3146 * and only retrieves a single status line from the HTTP connection.
3149 int /* O - 1 to continue, 0 to stop */
3150 _httpUpdate(http_t
*http
, /* I - Connection to server */
3151 http_status_t
*status
) /* O - Current HTTP status */
3153 char line
[32768], /* Line from connection... */
3154 *value
; /* Pointer to value on line */
3155 http_field_t field
; /* Field index */
3156 int major
, minor
; /* HTTP version numbers */
3159 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3160 http_state_string(http
->state
)));
3163 * Grab a single line from the connection...
3166 if (!httpGets(line
, sizeof(line
), http
))
3168 *status
= HTTP_STATUS_ERROR
;
3172 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3174 if (line
[0] == '\0')
3177 * Blank line means the start of the data section (if any). Return
3178 * the result code, too...
3180 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3181 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3185 if (http
->status
== HTTP_STATUS_CONTINUE
)
3187 *status
= http
->status
;
3191 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
3192 http
->digest_tries
= 0;
3195 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
3197 if (http_setup_ssl(http
) != 0)
3200 closesocket(http
->fd
);
3205 *status
= http
->status
= HTTP_STATUS_ERROR
;
3209 *status
= HTTP_STATUS_CONTINUE
;
3212 #endif /* HAVE_SSL */
3214 if (http_set_length(http
) < 0)
3216 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3217 http
->error
= EINVAL
;
3218 http
->status
= *status
= HTTP_STATUS_ERROR
;
3222 switch (http
->state
)
3224 case HTTP_STATE_GET
:
3225 case HTTP_STATE_POST
:
3226 case HTTP_STATE_POST_RECV
:
3227 case HTTP_STATE_PUT
:
3230 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3231 http_state_string(http
->state
)));
3233 case HTTP_STATE_POST_SEND
:
3234 case HTTP_STATE_HEAD
:
3238 http
->state
= HTTP_STATE_WAITING
;
3240 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
3245 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3246 http_content_coding_start(http
,
3247 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3248 #endif /* HAVE_LIBZ */
3250 *status
= http
->status
;
3253 else if (!strncmp(line
, "HTTP/", 5))
3256 * Got the beginning of a response...
3259 int intstatus
; /* Status value as an integer */
3261 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3263 *status
= http
->status
= HTTP_STATUS_ERROR
;
3267 httpClearFields(http
);
3269 http
->version
= (http_version_t
)(major
* 100 + minor
);
3270 *status
= http
->status
= (http_status_t
)intstatus
;
3272 else if ((value
= strchr(line
, ':')) != NULL
)
3279 while (_cups_isspace(*value
))
3282 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3285 * Be tolerants of servers that send unknown attribute fields...
3288 if (!_cups_strcasecmp(line
, "expect"))
3291 * "Expect: 100-continue" or similar...
3294 http
->expect
= (http_status_t
)atoi(value
);
3296 else if (!_cups_strcasecmp(line
, "cookie"))
3299 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3302 httpSetCookie(http
, value
);
3304 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
3305 httpSetField(http
, field
, value
);
3308 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3313 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3314 http
->error
= EINVAL
;
3315 http
->status
= *status
= HTTP_STATUS_ERROR
;
3324 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3327 http_status_t
/* O - HTTP status */
3328 httpUpdate(http_t
*http
) /* I - Connection to server */
3330 http_status_t status
; /* Request status */
3333 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3334 http_state_string(http
->state
)));
3337 * Flush pending data, if any...
3342 DEBUG_puts("2httpUpdate: flushing buffer...");
3344 if (httpFlushWrite(http
) < 0)
3345 return (HTTP_STATUS_ERROR
);
3349 * If we haven't issued any commands, then there is nothing to "update"...
3352 if (http
->state
== HTTP_STATE_WAITING
)
3353 return (HTTP_STATUS_CONTINUE
);
3356 * Grab all of the lines we can from the connection...
3359 while (_httpUpdate(http
, &status
));
3362 * See if there was an error...
3365 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3367 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3368 return (http
->status
);
3373 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3374 strerror(http
->error
)));
3375 http
->status
= HTTP_STATUS_ERROR
;
3376 return (HTTP_STATUS_ERROR
);
3380 * Return the current status...
3388 * '_httpWait()' - Wait for data available on a connection (no flush).
3391 int /* O - 1 if data is available, 0 otherwise */
3392 _httpWait(http_t
*http
, /* I - Connection to server */
3393 int msec
, /* I - Milliseconds to wait */
3394 int usessl
) /* I - Use SSL context? */
3397 struct pollfd pfd
; /* Polled file descriptor */
3399 fd_set input_set
; /* select() input set */
3400 struct timeval timeout
; /* Timeout */
3401 #endif /* HAVE_POLL */
3402 int nfds
; /* Result from select()/poll() */
3405 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3409 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3414 * Check the SSL/TLS buffers for data first...
3418 if (http
->tls
&& usessl
)
3421 if (SSL_pending(http
->tls
))
3423 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3427 # elif defined(HAVE_GNUTLS)
3428 if (gnutls_record_check_pending(http
->tls
))
3430 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3434 # elif defined(HAVE_CDSASSL)
3435 size_t bytes
; /* Bytes that are available */
3437 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3440 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3443 # endif /* HAVE_LIBSSL */
3445 #endif /* HAVE_SSL */
3448 * Then try doing a select() or poll() to poll the socket...
3453 pfd
.events
= POLLIN
;
3457 nfds
= poll(&pfd
, 1, msec
);
3459 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3464 FD_ZERO(&input_set
);
3465 FD_SET(http
->fd
, &input_set
);
3467 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3471 timeout
.tv_sec
= msec
/ 1000;
3472 timeout
.tv_usec
= (msec
% 1000) * 1000;
3474 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3477 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3479 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3482 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3483 WSAGetLastError() == WSAEWOULDBLOCK
));
3485 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3487 #endif /* HAVE_POLL */
3489 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3497 * 'httpWait()' - Wait for data available on a connection.
3499 * @since CUPS 1.1.19/OS X 10.3@
3502 int /* O - 1 if data is available, 0 otherwise */
3503 httpWait(http_t
*http
, /* I - Connection to server */
3504 int msec
) /* I - Milliseconds to wait */
3507 * First see if there is data in the buffer...
3510 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3517 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3522 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3524 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3527 #endif /* HAVE_LIBZ */
3530 * Flush pending data, if any...
3535 DEBUG_puts("3httpWait: Flushing write buffer.");
3537 if (httpFlushWrite(http
) < 0)
3542 * If not, check the SSL/TLS buffers and do a select() on the connection...
3545 return (_httpWait(http
, msec
, 1));
3550 * 'httpWrite()' - Write data to a HTTP connection.
3552 * This function is deprecated. Use the httpWrite2() function which can
3553 * write more than 2GB of data.
3558 int /* O - Number of bytes written */
3559 httpWrite(http_t
*http
, /* I - Connection to server */
3560 const char *buffer
, /* I - Buffer for data */
3561 int length
) /* I - Number of bytes to write */
3563 return ((int)httpWrite2(http
, buffer
, length
));
3568 * 'httpWrite2()' - Write data to a HTTP connection.
3570 * @since CUPS 1.2/OS X 10.5@
3573 ssize_t
/* O - Number of bytes written */
3574 httpWrite2(http_t
*http
, /* I - Connection to server */
3575 const char *buffer
, /* I - Buffer for data */
3576 size_t length
) /* I - Number of bytes to write */
3578 ssize_t bytes
; /* Bytes written */
3581 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3582 buffer
, CUPS_LLCAST length
));
3585 * Range check input...
3588 if (!http
|| !buffer
)
3590 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3595 * Mark activity on the connection...
3598 http
->activity
= time(NULL
);
3601 * Buffer small writes for better performance...
3607 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3611 http_content_coding_finish(http
);
3616 http
->stream
.next_in
= (Bytef
*)buffer
;
3617 http
->stream
.avail_in
= length
;
3618 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3619 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3621 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3623 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3625 if (http
->stream
.avail_out
== 0)
3627 if (httpFlushWrite(http
) < 0)
3629 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3633 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3634 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3638 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3643 #endif /* HAVE_LIBZ */
3646 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3648 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3649 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3651 httpFlushWrite(http
);
3654 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3655 length
< sizeof(http
->wbuffer
))
3658 * Write to buffer...
3661 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3662 CUPS_LLCAST length
));
3664 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3665 http
->wused
+= (int)length
;
3666 bytes
= (ssize_t
)length
;
3671 * Otherwise write the data directly...
3674 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3675 CUPS_LLCAST length
));
3677 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3678 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3680 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3682 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3683 CUPS_LLCAST bytes
));
3686 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3687 http
->data_remaining
-= bytes
;
3693 * Handle end-of-request processing...
3696 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3697 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3700 * Finished with the transfer; unless we are sending POST or PUT
3706 http_content_coding_finish(http
);
3707 #endif /* HAVE_LIBZ */
3711 if (httpFlushWrite(http
) < 0)
3715 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3718 * Send a 0-length chunk at the end of the request...
3721 http_write(http
, "0\r\n\r\n", 5);
3724 * Reset the data state...
3727 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3728 http
->data_remaining
= 0;
3731 if (http
->state
== HTTP_STATE_POST_RECV
)
3734 http
->state
= HTTP_STATE_STATUS
;
3736 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3737 http_state_string(http
->state
)));
3740 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3746 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3748 * '_httpWriteCDSA()' - Write function for the CDSA library.
3751 OSStatus
/* O - -1 on error, 0 on success */
3753 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3754 const void *data
, /* I - Data buffer */
3755 size_t *dataLength
) /* IO - Number of bytes */
3757 OSStatus result
; /* Return value */
3758 ssize_t bytes
; /* Number of bytes read */
3759 http_t
*http
; /* HTTP connection */
3762 http
= (http_t
*)connection
;
3766 bytes
= write(http
->fd
, data
, *dataLength
);
3768 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3770 if (bytes
== *dataLength
)
3774 else if (bytes
>= 0)
3776 *dataLength
= bytes
;
3777 result
= errSSLWouldBlock
;
3783 if (errno
== EAGAIN
)
3784 result
= errSSLWouldBlock
;
3786 result
= errSSLClosedAbort
;
3791 #endif /* HAVE_SSL && HAVE_CDSASSL */
3794 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3796 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3799 ssize_t
/* O - Number of bytes written or -1 on error */
3801 gnutls_transport_ptr ptr
, /* I - Connection to server */
3802 const void *data
, /* I - Data buffer */
3803 size_t length
) /* I - Number of bytes to write */
3805 ssize_t bytes
; /* Bytes written */
3808 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3811 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3814 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3815 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3819 #endif /* HAVE_SSL && HAVE_GNUTLS */
3823 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3828 int /* O - 0 on success, -1 on error */
3829 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3830 http_status_t status
) /* I - Status code */
3832 http_encoding_t old_encoding
; /* Old data_encoding value */
3833 off_t old_remaining
; /* Old data_remaining value */
3837 * Range check input...
3840 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3842 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3844 DEBUG_puts("1httpWriteResponse: Bad input.");
3849 * Set the various standard fields if they aren't already...
3852 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3853 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3855 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3857 http
->keep_alive
= 0;
3858 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3861 if (http
->version
== HTTP_VERSION_1_1
)
3863 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3865 if (http
->keep_alive
)
3866 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3868 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3871 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3872 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3876 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
)
3878 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3879 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3881 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3882 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3884 #endif /* HAVE_SSL */
3887 httpSetField(http
, HTTP_FIELD_SERVER
,
3888 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3891 * Set the Accept-Encoding field if it isn't already...
3894 if (!http
->accept_encoding
)
3895 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3896 http
->default_accept_encoding
? http
->default_accept_encoding
:
3898 "gzip, deflate, identity");
3901 #endif /* HAVE_LIBZ */
3904 * Send the response header...
3907 old_encoding
= http
->data_encoding
;
3908 old_remaining
= http
->data_remaining
;
3909 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3911 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3912 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3914 http
->status
= HTTP_STATUS_ERROR
;
3918 if (status
!= HTTP_STATUS_CONTINUE
)
3921 * 100 Continue doesn't have the rest of the response headers...
3924 int i
; /* Looping var */
3925 const char *value
; /* Field value */
3927 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3929 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3931 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3933 http
->status
= HTTP_STATUS_ERROR
;
3941 if (httpPrintf(http
, "Set-Cookie: %s path=/%s\r\n", http
->cookie
,
3942 http
->tls
? " secure" : "") < 1)
3944 http
->status
= HTTP_STATUS_ERROR
;
3950 if (httpWrite2(http
, "\r\n", 2) < 2)
3952 http
->status
= HTTP_STATUS_ERROR
;
3956 if (httpFlushWrite(http
) < 0)
3958 http
->status
= HTTP_STATUS_ERROR
;
3962 if (status
== HTTP_STATUS_CONTINUE
)
3965 * Restore the old data_encoding and data_length values...
3968 http
->data_encoding
= old_encoding
;
3969 http
->data_remaining
= old_remaining
;
3971 if (old_remaining
<= INT_MAX
)
3972 http
->_data_remaining
= (int)old_remaining
;
3974 http
->_data_remaining
= INT_MAX
;
3976 else if (http
->state
== HTTP_STATE_OPTIONS
||
3977 http
->state
== HTTP_STATE_HEAD
||
3978 http
->state
== HTTP_STATE_PUT
||
3979 http
->state
== HTTP_STATE_TRACE
||
3980 http
->state
== HTTP_STATE_CONNECT
||
3981 http
->state
== HTTP_STATE_STATUS
)
3983 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3984 "was %s.", http_state_string(http
->state
)));
3985 http
->state
= HTTP_STATE_WAITING
;
3990 * Force data_encoding and data_length to be set according to the response
3994 http_set_length(http
);
3998 * Then start any content encoding...
4001 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
4002 http_content_coding_start(http
,
4003 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
4004 #endif /* HAVE_LIBZ */
4011 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
4013 * 'http_bio_ctrl()' - Control the HTTP connection.
4016 static long /* O - Result/data */
4017 http_bio_ctrl(BIO
*h
, /* I - BIO data */
4018 int cmd
, /* I - Control command */
4019 long arg1
, /* I - First argument */
4020 void *arg2
) /* I - Second argument */
4027 case BIO_CTRL_RESET
:
4031 case BIO_C_SET_FILE_PTR
:
4036 case BIO_C_GET_FILE_PTR
:
4039 *((void **)arg2
) = h
->ptr
;
4046 case BIO_CTRL_FLUSH
:
4053 * 'http_bio_free()' - Free OpenSSL data.
4056 static int /* O - 1 on success, 0 on failure */
4057 http_bio_free(BIO
*h
) /* I - BIO data */
4073 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
4076 static int /* O - 1 on success, 0 on failure */
4077 http_bio_new(BIO
*h
) /* I - BIO data */
4092 * 'http_bio_puts()' - Send a string for OpenSSL.
4095 static int /* O - Bytes written */
4096 http_bio_puts(BIO
*h
, /* I - BIO data */
4097 const char *str
) /* I - String to write */
4100 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
4102 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
4108 * 'http_bio_read()' - Read data for OpenSSL.
4111 static int /* O - Bytes read */
4112 http_bio_read(BIO
*h
, /* I - BIO data */
4113 char *buf
, /* I - Buffer */
4114 int size
) /* I - Number of bytes to read */
4116 http_t
*http
; /* HTTP connection */
4119 http
= (http_t
*)h
->ptr
;
4121 if (!http
->blocking
)
4124 * Make sure we have data before we read...
4127 while (!_httpWait(http
, http
->wait_value
, 0))
4129 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4133 http
->error
= WSAETIMEDOUT
;
4135 http
->error
= ETIMEDOUT
;
4142 return (recv(http
->fd
, buf
, size
, 0));
4147 * 'http_bio_write()' - Write data for OpenSSL.
4150 static int /* O - Bytes written */
4151 http_bio_write(BIO
*h
, /* I - BIO data */
4152 const char *buf
, /* I - Buffer to write */
4153 int num
) /* I - Number of bytes to write */
4155 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4157 #endif /* HAVE_SSL && HAVE_LIBSSL */
4162 * 'http_content_coding_finish()' - Finish doing any content encoding.
4166 http_content_coding_finish(
4167 http_t
*http
) /* I - HTTP connection */
4169 int zerr
; /* Compression status */
4172 switch (http
->coding
)
4174 case _HTTP_CODING_DEFLATE
:
4175 case _HTTP_CODING_GZIP
:
4178 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4179 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4181 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4183 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4184 if (http
->wused
== sizeof(http
->wbuffer
))
4185 httpFlushWrite(http
);
4187 while (zerr
== Z_OK
);
4189 deflateEnd(&(http
->stream
));
4192 httpFlushWrite(http
);
4195 case _HTTP_CODING_INFLATE
:
4196 case _HTTP_CODING_GUNZIP
:
4197 inflateEnd(&(http
->stream
));
4198 free(http
->dbuffer
);
4199 http
->dbuffer
= NULL
;
4206 http
->coding
= _HTTP_CODING_IDENTITY
;
4211 * 'http_content_coding_start()' - Start doing content encoding.
4215 http_content_coding_start(
4216 http_t
*http
, /* I - HTTP connection */
4217 const char *value
) /* I - Value of Content-Encoding */
4219 int zerr
; /* Error/status */
4220 _http_coding_t coding
; /* Content coding value */
4223 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4226 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4228 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4232 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4234 if (http
->state
== HTTP_STATE_GET_SEND
||
4235 http
->state
== HTTP_STATE_POST_SEND
)
4236 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4237 _HTTP_CODING_GUNZIP
;
4238 else if (http
->state
== HTTP_STATE_POST_RECV
||
4239 http
->state
== HTTP_STATE_PUT_RECV
)
4240 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4241 _HTTP_CODING_GUNZIP
;
4244 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4248 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4250 if (http
->state
== HTTP_STATE_GET_SEND
||
4251 http
->state
== HTTP_STATE_POST_SEND
)
4252 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4253 _HTTP_CODING_INFLATE
;
4254 else if (http
->state
== HTTP_STATE_POST_RECV
||
4255 http
->state
== HTTP_STATE_PUT_RECV
)
4256 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4257 _HTTP_CODING_INFLATE
;
4260 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4266 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4270 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4274 case _HTTP_CODING_DEFLATE
:
4275 case _HTTP_CODING_GZIP
:
4277 httpFlushWrite(http
);
4280 * Window size for compression is 11 bits - optimal based on PWG Raster
4281 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
4285 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4287 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
4288 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4290 http
->status
= HTTP_STATUS_ERROR
;
4291 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4296 case _HTTP_CODING_INFLATE
:
4297 case _HTTP_CODING_GUNZIP
:
4298 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
4300 http
->status
= HTTP_STATUS_ERROR
;
4301 http
->error
= errno
;
4306 * Window size for decompression is up to 15 bits (maximum supported).
4307 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
4310 if ((zerr
= inflateInit2(&(http
->stream
),
4311 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
4314 free(http
->dbuffer
);
4315 http
->dbuffer
= NULL
;
4316 http
->status
= HTTP_STATUS_ERROR
;
4317 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4321 http
->stream
.avail_in
= 0;
4322 http
->stream
.next_in
= http
->dbuffer
;
4329 http
->coding
= coding
;
4331 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4334 #endif /* HAVE_LIBZ */
4338 * 'http_create()' - Create an unconnected HTTP connection.
4341 static http_t
* /* O - HTTP connection */
4343 const char *host
, /* I - Hostname */
4344 int port
, /* I - Port number */
4345 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
4346 int family
, /* I - Address family or AF_UNSPEC */
4347 http_encryption_t encryption
, /* I - Encryption to use */
4348 int blocking
, /* I - 1 for blocking mode */
4349 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
4351 http_t
*http
; /* New HTTP connection */
4352 char service
[255]; /* Service name */
4353 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
4356 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
4357 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
4358 family
, encryption
, blocking
, mode
));
4360 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
4366 * Lookup the host...
4371 myaddrlist
= httpAddrCopyList(addrlist
);
4375 snprintf(service
, sizeof(service
), "%d", port
);
4377 myaddrlist
= httpAddrGetList(host
, family
, service
);
4384 * Allocate memory for the structure...
4387 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
4389 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
4390 httpAddrFreeList(addrlist
);
4395 * Initialize the HTTP data...
4399 http
->activity
= time(NULL
);
4400 http
->addrlist
= myaddrlist
;
4401 http
->blocking
= blocking
;
4404 http
->gssctx
= GSS_C_NO_CONTEXT
;
4405 http
->gssname
= GSS_C_NO_NAME
;
4406 #endif /* HAVE_GSSAPI */
4407 http
->status
= HTTP_STATUS_CONTINUE
;
4408 http
->version
= HTTP_VERSION_1_1
;
4411 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
4413 if (port
== 443) /* Always use encryption for https */
4414 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
4416 http
->encryption
= encryption
;
4418 http_set_wait(http
);
4421 * Return the new structure...
4427 /* For OS X 10.8 and earlier */
4428 http_t
*_httpCreate(const char *host
, int port
, http_addrlist_t
*addrlist
,
4429 http_encryption_t encryption
, int family
)
4430 { return (http_create(host
, port
, addrlist
, family
, encryption
, 1,
4431 _HTTP_MODE_CLIENT
)); }
4436 * 'http_debug_hex()' - Do a hex dump of a buffer.
4440 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4441 const char *buffer
, /* I - Buffer to dump */
4442 int bytes
) /* I - Bytes to dump */
4444 int i
, j
, /* Looping vars */
4445 ch
; /* Current character */
4446 char line
[255], /* Line buffer */
4447 *start
, /* Start of line after prefix */
4448 *ptr
; /* Pointer into line */
4451 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4454 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4456 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4457 start
= line
+ strlen(line
);
4459 for (i
= 0; i
< bytes
; i
+= 16)
4461 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4462 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4466 memcpy(ptr
, " ", 3);
4471 memcpy(ptr
, " ", 3);
4474 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4476 ch
= buffer
[i
+ j
] & 255;
4478 if (ch
< ' ' || ch
>= 127)
4492 * 'http_field()' - Return the field index for a field name.
4495 static http_field_t
/* O - Field index */
4496 http_field(const char *name
) /* I - String name */
4498 int i
; /* Looping var */
4501 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4502 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
4503 return ((http_field_t
)i
);
4505 return (HTTP_FIELD_UNKNOWN
);
4510 * 'http_read()' - Read a buffer from a HTTP connection.
4512 * This function does the low-level read from the socket, retrying and timing
4516 static ssize_t
/* O - Number of bytes read or -1 on error */
4517 http_read(http_t
*http
, /* I - Connection to server */
4518 char *buffer
, /* I - Buffer */
4519 size_t length
) /* I - Maximum bytes to read */
4521 ssize_t bytes
; /* Bytes read */
4524 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4525 buffer
, CUPS_LLCAST length
));
4527 if (!http
->blocking
)
4529 while (!httpWait(http
, http
->wait_value
))
4531 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4534 DEBUG_puts("2http_read: Timeout.");
4539 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4545 bytes
= http_read_ssl(http
, buffer
, length
);
4547 #endif /* HAVE_SSL */
4548 bytes
= recv(http
->fd
, buffer
, length
, 0);
4553 if (WSAGetLastError() != WSAEINTR
)
4555 http
->error
= WSAGetLastError();
4558 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4560 if (!http
->timeout_cb
||
4561 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4563 http
->error
= WSAEWOULDBLOCK
;
4568 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4570 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4572 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4574 http
->error
= errno
;
4577 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4579 http
->error
= errno
;
4583 else if (errno
!= EINTR
)
4585 http
->error
= errno
;
4593 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4594 CUPS_LLCAST bytes
));
4597 http_debug_hex("http_read", buffer
, (int)bytes
);
4603 if (WSAGetLastError() == WSAEINTR
)
4606 http
->error
= WSAGetLastError();
4608 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4611 http
->error
= errno
;
4614 else if (bytes
== 0)
4616 http
->error
= EPIPE
;
4625 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4627 * This function reads data from the HTTP buffer or from the socket, as needed.
4630 static ssize_t
/* O - Number of bytes read or -1 on error */
4631 http_read_buffered(http_t
*http
, /* I - Connection to server */
4632 char *buffer
, /* I - Buffer */
4633 size_t length
) /* I - Maximum bytes to read */
4635 ssize_t bytes
; /* Bytes read */
4638 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4640 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4644 if (length
> (size_t)http
->used
)
4645 bytes
= (size_t)http
->used
;
4649 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4652 memcpy(buffer
, http
->buffer
, bytes
);
4653 http
->used
-= (int)bytes
;
4656 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4659 bytes
= http_read(http
, buffer
, length
);
4666 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4668 * This function reads and validates the chunk length, then does a buffered read
4669 * returning the number of bytes placed in the buffer.
4672 static ssize_t
/* O - Number of bytes read or -1 on error */
4673 http_read_chunk(http_t
*http
, /* I - Connection to server */
4674 char *buffer
, /* I - Buffer */
4675 size_t length
) /* I - Maximum bytes to read */
4677 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4678 http
, buffer
, CUPS_LLCAST length
));
4680 if (http
->data_remaining
<= 0)
4682 char len
[32]; /* Length string */
4684 if (!httpGets(len
, sizeof(len
), http
))
4686 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4692 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4693 if (!httpGets(len
, sizeof(len
), http
))
4695 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4700 http
->data_remaining
= strtoll(len
, NULL
, 16);
4702 if (http
->data_remaining
< 0)
4704 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4705 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4709 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4710 len
, CUPS_LLCAST http
->data_remaining
));
4712 if (http
->data_remaining
== 0)
4715 * 0-length chunk, grab trailing blank line...
4718 httpGets(len
, sizeof(len
), http
);
4722 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4723 CUPS_LLCAST http
->data_remaining
));
4725 if (http
->data_remaining
<= 0)
4727 else if (length
> (size_t)http
->data_remaining
)
4728 length
= (size_t)http
->data_remaining
;
4730 return (http_read_buffered(http
, buffer
, length
));
4736 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4739 static int /* O - Bytes read */
4740 http_read_ssl(http_t
*http
, /* I - Connection to server */
4741 char *buf
, /* I - Buffer to store data */
4742 int len
) /* I - Length of buffer */
4744 # if defined(HAVE_LIBSSL)
4745 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4747 # elif defined(HAVE_GNUTLS)
4748 ssize_t result
; /* Return value */
4751 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4753 if (result
< 0 && !errno
)
4756 * Convert GNU TLS error to errno value...
4761 case GNUTLS_E_INTERRUPTED
:
4765 case GNUTLS_E_AGAIN
:
4777 return ((int)result
);
4779 # elif defined(HAVE_CDSASSL)
4780 int result
; /* Return value */
4781 OSStatus error
; /* Error info */
4782 size_t processed
; /* Number of bytes processed */
4785 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4786 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4791 result
= (int)processed
;
4794 case errSSLWouldBlock
:
4796 result
= (int)processed
;
4804 case errSSLClosedGraceful
:
4807 result
= (int)processed
;
4818 # elif defined(HAVE_SSPISSL)
4819 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4820 # endif /* HAVE_LIBSSL */
4822 #endif /* HAVE_SSL */
4826 * 'http_send()' - Send a request with all fields and the trailing blank line.
4829 static int /* O - 0 on success, non-zero on error */
4830 http_send(http_t
*http
, /* I - Connection to server */
4831 http_state_t request
, /* I - Request code */
4832 const char *uri
) /* I - URI */
4834 int i
; /* Looping var */
4835 char buf
[1024]; /* Encoded URI buffer */
4836 const char *value
; /* Field value */
4837 static const char * const codes
[] = /* Request code strings */
4857 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4858 http
, codes
[request
], uri
));
4860 if (http
== NULL
|| uri
== NULL
)
4864 * Set the User-Agent field if it isn't already...
4867 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4869 if (http
->default_user_agent
)
4870 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4872 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4876 * Set the Accept-Encoding field if it isn't already...
4879 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4880 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4881 http
->default_accept_encoding
);
4884 * Encode the URI as needed...
4887 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4890 * See if we had an error the last time around; if so, reconnect...
4893 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4894 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4896 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4897 http
->fd
, http
->status
, http
->tls_upgrade
));
4899 if (httpReconnect2(http
, 30000, NULL
))
4904 * Flush any written data that is pending...
4909 if (httpFlushWrite(http
) < 0)
4910 if (httpReconnect2(http
, 30000, NULL
))
4915 * Send the request header...
4918 http
->state
= request
;
4919 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4921 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4924 http
->status
= HTTP_STATUS_CONTINUE
;
4927 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4929 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4930 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4932 #endif /* HAVE_SSL */
4934 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4936 http
->status
= HTTP_STATUS_ERROR
;
4940 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4941 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4943 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
4945 if (i
== HTTP_FIELD_HOST
)
4947 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4948 httpAddrPort(http
->hostaddr
)) < 1)
4950 http
->status
= HTTP_STATUS_ERROR
;
4954 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4956 http
->status
= HTTP_STATUS_ERROR
;
4962 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4964 http
->status
= HTTP_STATUS_ERROR
;
4968 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
4969 http
->mode
, http
->state
));
4971 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4972 (http
->state
== HTTP_STATE_POST_RECV
||
4973 http
->state
== HTTP_STATE_PUT_RECV
))
4974 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4976 http
->status
= HTTP_STATUS_ERROR
;
4980 if (httpPrintf(http
, "\r\n") < 1)
4982 http
->status
= HTTP_STATUS_ERROR
;
4986 if (httpFlushWrite(http
) < 0)
4989 http_set_length(http
);
4990 httpClearFields(http
);
4993 * The Kerberos and AuthRef authentication strings can only be used once...
4996 if (http
->field_authorization
&& http
->authstring
&&
4997 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4998 !strncmp(http
->authstring
, "AuthRef", 7)))
5000 http
->_authstring
[0] = '\0';
5002 if (http
->authstring
!= http
->_authstring
)
5003 free(http
->authstring
);
5005 http
->authstring
= http
->_authstring
;
5013 # if defined(HAVE_CDSASSL)
5015 * 'http_set_credentials()' - Set the SSL/TLS credentials.
5018 static int /* O - Status of connection */
5019 http_set_credentials(http_t
*http
) /* I - Connection to server */
5021 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
5022 OSStatus error
= 0; /* Error code */
5023 http_tls_credentials_t credentials
= NULL
;
5024 /* TLS credentials */
5027 DEBUG_printf(("7http_set_credentials(%p)", http
));
5030 * Prefer connection specific credentials...
5033 if ((credentials
= http
->tls_credentials
) == NULL
)
5034 credentials
= cg
->tls_credentials
;
5038 error
= SSLSetCertificate(http
->tls
, credentials
);
5039 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
5043 DEBUG_puts("4http_set_credentials: No credentials to set.");
5047 # endif /* HAVE_CDSASSL */
5048 #endif /* HAVE_SSL */
5052 * 'http_set_length()' - Set the data_encoding and data_remaining values.
5055 static off_t
/* O - Remainder or -1 on error */
5056 http_set_length(http_t
*http
) /* I - Connection */
5058 off_t remaining
; /* Remainder */
5061 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
5062 http_state_string(http
->state
)));
5064 if ((remaining
= httpGetLength2(http
)) >= 0)
5066 if (http
->mode
== _HTTP_MODE_SERVER
&&
5067 http
->state
!= HTTP_STATE_GET_SEND
&&
5068 http
->state
!= HTTP_STATE_PUT
&&
5069 http
->state
!= HTTP_STATE_POST
&&
5070 http
->state
!= HTTP_STATE_POST_SEND
)
5072 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
5076 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
5079 DEBUG_puts("1http_set_length: Setting data_encoding to "
5080 "HTTP_ENCODING_CHUNKED.");
5081 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
5085 DEBUG_puts("1http_set_length: Setting data_encoding to "
5086 "HTTP_ENCODING_LENGTH.");
5087 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
5090 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
5091 CUPS_LLCAST remaining
));
5092 http
->data_remaining
= remaining
;
5094 if (remaining
<= INT_MAX
)
5095 http
->_data_remaining
= remaining
;
5097 http
->_data_remaining
= INT_MAX
;
5104 * 'http_set_timeout()' - Set the socket timeout values.
5108 http_set_timeout(int fd
, /* I - File descriptor */
5109 double timeout
) /* I - Timeout in seconds */
5112 DWORD tv
= (DWORD
)(timeout
* 1000);
5113 /* Timeout in milliseconds */
5115 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5116 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5119 struct timeval tv
; /* Timeout in secs and usecs */
5121 tv
.tv_sec
= (int)timeout
;
5122 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
5124 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5125 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5131 * 'http_set_wait()' - Set the default wait value for reads.
5135 http_set_wait(http_t
*http
) /* I - Connection to server */
5139 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5141 if (http
->wait_value
<= 0)
5142 http
->wait_value
= 60000;
5145 http
->wait_value
= 10000;
5151 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5154 static int /* O - 0 on success, -1 on failure */
5155 http_setup_ssl(http_t
*http
) /* I - Connection to server */
5157 char hostname
[256], /* Hostname */
5158 *hostptr
; /* Pointer into hostname */
5161 SSL_CTX
*context
; /* Context for encryption */
5162 BIO
*bio
; /* BIO data */
5163 const char *message
= NULL
;/* Error message */
5164 # elif defined(HAVE_GNUTLS)
5165 int status
; /* Status of handshake */
5166 gnutls_certificate_client_credentials
*credentials
;
5167 /* TLS credentials */
5168 # elif defined(HAVE_CDSASSL)
5169 _cups_globals_t
*cg
= _cupsGlobals();
5170 /* Pointer to library globals */
5171 OSStatus error
; /* Error code */
5172 const char *message
= NULL
;/* Error message */
5173 cups_array_t
*credentials
; /* Credentials array */
5174 cups_array_t
*names
; /* CUPS distinguished names */
5175 CFArrayRef dn_array
; /* CF distinguished names array */
5176 CFIndex count
; /* Number of credentials */
5177 CFDataRef data
; /* Certificate data */
5178 int i
; /* Looping var */
5179 http_credential_t
*credential
; /* Credential data */
5180 # elif defined(HAVE_SSPISSL)
5181 TCHAR username
[256]; /* Username returned from GetUserName() */
5182 TCHAR commonName
[256];/* Common name for certificate */
5183 DWORD dwSize
; /* 32 bit size */
5184 # endif /* HAVE_LIBSSL */
5187 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5190 * Get the hostname to use for SSL...
5193 if (httpAddrLocalhost(http
->hostaddr
))
5195 strlcpy(hostname
, "localhost", sizeof(hostname
));
5200 * Otherwise make sure the hostname we have does not end in a trailing dot.
5203 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5204 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5210 context
= SSL_CTX_new(SSLv23_client_method());
5212 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5214 bio
= BIO_new(_httpBIOMethods());
5215 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5217 http
->tls
= SSL_new(context
);
5218 SSL_set_bio(http
->tls
, bio
, bio
);
5220 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5221 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5222 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5224 if (SSL_connect(http
->tls
) != 1)
5226 unsigned long error
; /* Error code */
5228 while ((error
= ERR_get_error()) != 0)
5230 message
= ERR_error_string(error
, NULL
);
5231 DEBUG_printf(("8http_setup_ssl: %s", message
));
5234 SSL_CTX_free(context
);
5235 SSL_free(http
->tls
);
5239 http
->error
= WSAGetLastError();
5241 http
->error
= errno
;
5243 http
->status
= HTTP_STATUS_ERROR
;
5246 message
= _("Unable to establish a secure connection to host.");
5248 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5253 # elif defined(HAVE_GNUTLS)
5254 credentials
= (gnutls_certificate_client_credentials
*)
5255 malloc(sizeof(gnutls_certificate_client_credentials
));
5256 if (credentials
== NULL
)
5258 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5260 http
->error
= errno
;
5261 http
->status
= HTTP_STATUS_ERROR
;
5262 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5267 gnutls_certificate_allocate_credentials(credentials
);
5269 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5270 gnutls_set_default_priority(http
->tls
);
5271 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5273 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5274 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5275 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5276 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5278 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5280 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5281 status
, gnutls_strerror(status
)));
5283 if (gnutls_error_is_fatal(status
))
5286 http
->status
= HTTP_STATUS_ERROR
;
5288 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
5290 gnutls_deinit(http
->tls
);
5291 gnutls_certificate_free_credentials(*credentials
);
5299 http
->tls_credentials
= credentials
;
5301 # elif defined(HAVE_CDSASSL)
5302 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, kSSLClientSide
,
5303 kSSLStreamType
)) == NULL
)
5305 DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
5306 http
->error
= errno
= ENOMEM
;
5307 http
->status
= HTTP_STATUS_ERROR
;
5308 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5313 error
= SSLSetConnection(http
->tls
, http
);
5314 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5318 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5319 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5324 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
5326 DEBUG_printf(("4http_setup_ssl: SSLSetSessionOption, error=%d",
5332 if (cg
->client_cert_cb
)
5334 error
= SSLSetSessionOption(http
->tls
,
5335 kSSLSessionOptionBreakOnCertRequested
, true);
5336 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5337 "error=%d", (int)error
));
5341 error
= http_set_credentials(http
);
5342 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5348 * Let the server know which hostname/domain we are trying to connect to
5349 * in case it wants to serve up a certificate with a matching common name.
5354 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5356 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5362 int done
= 0; /* Are we done yet? */
5364 while (!error
&& !done
)
5366 error
= SSLHandshake(http
->tls
);
5368 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5376 case errSSLWouldBlock
:
5377 error
= noErr
; /* Force a retry */
5378 usleep(1000); /* in 1 millisecond */
5381 case errSSLServerAuthCompleted
:
5383 if (cg
->server_cert_cb
)
5385 error
= httpCopyCredentials(http
, &credentials
);
5388 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5389 cg
->server_cert_data
);
5390 httpFreeCredentials(credentials
);
5393 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5394 "returned %d.", (int)error
));
5398 case errSSLClientCertRequested
:
5401 if (cg
->client_cert_cb
)
5404 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5407 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5409 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5411 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5413 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5415 credential
->datalen
= CFDataGetLength(data
);
5416 if ((credential
->data
= malloc(credential
->datalen
)))
5418 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5419 credential
->datalen
);
5420 cupsArrayAdd(names
, credential
);
5428 CFRelease(dn_array
);
5433 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5434 cg
->client_cert_data
);
5436 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5437 "returned %d.", (int)error
));
5440 httpFreeCredentials(names
);
5444 case errSSLUnknownRootCert
:
5445 message
= _("Unable to establish a secure connection to host "
5446 "(untrusted certificate).");
5449 case errSSLNoRootCert
:
5450 message
= _("Unable to establish a secure connection to host "
5451 "(self-signed certificate).");
5454 case errSSLCertExpired
:
5455 message
= _("Unable to establish a secure connection to host "
5456 "(expired certificate).");
5459 case errSSLCertNotYetValid
:
5460 message
= _("Unable to establish a secure connection to host "
5461 "(certificate not yet valid).");
5464 case errSSLHostNameMismatch
:
5465 message
= _("Unable to establish a secure connection to host "
5466 "(host name mismatch).");
5469 case errSSLXCertChainInvalid
:
5470 message
= _("Unable to establish a secure connection to host "
5471 "(certificate chain invalid).");
5474 case errSSLConnectionRefused
:
5475 message
= _("Unable to establish a secure connection to host "
5476 "(peer dropped connection before responding).");
5487 http
->error
= error
;
5488 http
->status
= HTTP_STATUS_ERROR
;
5489 errno
= ECONNREFUSED
;
5491 CFRelease(http
->tls
);
5495 * If an error string wasn't set by the callbacks use a generic one...
5499 #ifdef HAVE_CSSMERRORSTRING
5500 message
= cssmErrorString(error
);
5502 message
= _("Unable to establish a secure connection to host.");
5503 #endif /* HAVE_CSSMERRORSTRING */
5505 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5510 # elif defined(HAVE_SSPISSL)
5511 http
->tls
= _sspiAlloc();
5515 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5519 http
->tls
->sock
= http
->fd
;
5520 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5521 GetUserName(username
, &dwSize
);
5522 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5523 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5525 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5528 _sspiFree(http
->tls_credentials
);
5529 http
->tls_credentials
= NULL
;
5532 http
->status
= HTTP_STATUS_ERROR
;
5534 _cupsSetError(IPP_PKI_ERROR
,
5535 _("Unable to establish a secure connection to host."), 1);
5540 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
5541 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5543 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5545 _sspiFree(http
->tls_credentials
);
5546 http
->tls_credentials
= NULL
;
5549 http
->status
= HTTP_STATUS_ERROR
;
5551 _cupsSetError(IPP_PKI_ERROR
,
5552 _("Unable to establish a secure connection to host."), 1);
5556 # endif /* HAVE_CDSASSL */
5563 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5567 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
5570 SSL_CTX
*context
; /* Context for encryption */
5572 context
= SSL_get_SSL_CTX(http
->tls
);
5574 SSL_shutdown(http
->tls
);
5575 SSL_CTX_free(context
);
5576 SSL_free(http
->tls
);
5578 # elif defined(HAVE_GNUTLS)
5579 gnutls_certificate_client_credentials
*credentials
;
5580 /* TLS credentials */
5582 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5584 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5585 gnutls_deinit(http
->tls
);
5586 gnutls_certificate_free_credentials(*credentials
);
5589 # elif defined(HAVE_CDSASSL)
5590 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5593 CFRelease(http
->tls
);
5595 if (http
->tls_credentials
)
5596 CFRelease(http
->tls_credentials
);
5598 # elif defined(HAVE_SSPISSL)
5599 _sspiFree(http
->tls_credentials
);
5600 # endif /* HAVE_LIBSSL */
5603 http
->tls_credentials
= NULL
;
5605 #endif /* HAVE_SSL */
5610 * 'http_state_string()' - Return the string associated with a given HTTP state.
5613 static const char * /* O - State string */
5614 http_state_string(http_state_t state
) /* I - HTTP state */
5616 static char buffer
[255]; /* Unknown value buffer */
5617 static const char * const states
[] = /* State strings */
5620 "HTTP_STATE_WAITING",
5621 "HTTP_STATE_OPTIONS",
5623 "HTTP_STATE_GET_SEND",
5626 "HTTP_STATE_POST_RECV",
5627 "HTTP_STATE_POST_SEND",
5629 "HTTP_STATE_PUT_RECV",
5630 "HTTP_STATE_DELETE",
5632 "HTTP_STATE_CONNECT",
5633 "HTTP_STATE_STATUS",
5634 "HTTP_STATE_UNKNOWN_METHOD",
5635 "HTTP_STATE_UNKNOWN_VERSION"
5638 if (state
>= HTTP_STATE_ERROR
&& state
<= HTTP_STATE_UNKNOWN_VERSION
)
5639 return (states
[state
- HTTP_STATE_ERROR
]);
5641 snprintf(buffer
, sizeof(buffer
), "??? %d ???", (int)state
);
5649 * 'http_upgrade()' - Force upgrade to TLS encryption.
5652 static int /* O - Status of connection */
5653 http_upgrade(http_t
*http
) /* I - Connection to server */
5655 int ret
; /* Return value */
5656 http_t myhttp
; /* Local copy of HTTP data */
5659 DEBUG_printf(("7http_upgrade(%p)", http
));
5662 * Flush the connection to make sure any previous "Upgrade" message
5669 * Copy the HTTP data to a local variable so we can do the OPTIONS
5670 * request without interfering with the existing request data...
5673 memcpy(&myhttp
, http
, sizeof(myhttp
));
5676 * Send an OPTIONS request to the server, requiring SSL or TLS
5677 * encryption on the link...
5680 http
->tls_upgrade
= 1;
5681 http
->field_authorization
= NULL
; /* Don't free the auth string */
5683 httpClearFields(http
);
5684 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5685 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5687 if ((ret
= httpOptions(http
, "*")) == 0)
5690 * Wait for the secure connection...
5693 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
5697 * Restore the HTTP request data...
5700 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5701 http
->data_encoding
= myhttp
.data_encoding
;
5702 http
->data_remaining
= myhttp
.data_remaining
;
5703 http
->_data_remaining
= myhttp
._data_remaining
;
5704 http
->expect
= myhttp
.expect
;
5705 http
->field_authorization
= myhttp
.field_authorization
;
5706 http
->digest_tries
= myhttp
.digest_tries
;
5707 http
->tls_upgrade
= 0;
5710 * See if we actually went secure...
5716 * Server does not support HTTP upgrade...
5719 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5722 closesocket(http
->fd
);
5734 #endif /* HAVE_SSL */
5738 * 'http_write()' - Write a buffer to a HTTP connection.
5741 static ssize_t
/* O - Number of bytes written */
5742 http_write(http_t
*http
, /* I - Connection to server */
5743 const char *buffer
, /* I - Buffer for data */
5744 size_t length
) /* I - Number of bytes to write */
5746 ssize_t tbytes
, /* Total bytes sent */
5747 bytes
; /* Bytes sent */
5750 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
5751 buffer
, CUPS_LLCAST length
));
5757 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5759 if (http
->timeout_cb
)
5762 struct pollfd pfd
; /* Polled file descriptor */
5764 fd_set output_set
; /* Output ready for write? */
5765 struct timeval timeout
; /* Timeout value */
5766 #endif /* HAVE_POLL */
5767 int nfds
; /* Result from select()/poll() */
5773 pfd
.events
= POLLOUT
;
5775 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5776 (errno
== EINTR
|| errno
== EAGAIN
))
5782 FD_ZERO(&output_set
);
5783 FD_SET(http
->fd
, &output_set
);
5785 timeout
.tv_sec
= http
->wait_value
/ 1000;
5786 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5788 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5791 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5792 WSAGetLastError() == WSAEWOULDBLOCK
));
5794 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5796 #endif /* HAVE_POLL */
5800 http
->error
= errno
;
5803 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5806 http
->error
= WSAEWOULDBLOCK
;
5808 http
->error
= EWOULDBLOCK
;
5818 bytes
= http_write_ssl(http
, buffer
, length
);
5820 #endif /* HAVE_SSL */
5821 bytes
= send(http
->fd
, buffer
, length
, 0);
5823 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
5824 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
5829 if (WSAGetLastError() == WSAEINTR
)
5831 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5833 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5836 http
->error
= WSAGetLastError();
5838 else if (WSAGetLastError() != http
->error
&&
5839 WSAGetLastError() != WSAECONNRESET
)
5841 http
->error
= WSAGetLastError();
5848 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5850 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5852 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5855 http
->error
= errno
;
5857 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5859 http
->error
= errno
;
5864 DEBUG_printf(("3http_write: error writing data (%s).",
5865 strerror(http
->error
)));
5876 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5879 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
5886 * 'http_write_chunk()' - Write a chunked buffer.
5889 static ssize_t
/* O - Number bytes written */
5890 http_write_chunk(http_t
*http
, /* I - Connection to server */
5891 const char *buffer
, /* I - Buffer to write */
5892 size_t length
) /* I - Length of buffer */
5894 char header
[16]; /* Chunk header */
5895 ssize_t bytes
; /* Bytes written */
5898 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
5899 http
, buffer
, CUPS_LLCAST length
));
5902 * Write the chunk header, data, and trailer.
5905 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
5906 if (http_write(http
, header
, strlen(header
)) < 0)
5908 DEBUG_puts("8http_write_chunk: http_write of length failed.");
5912 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5914 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
5918 if (http_write(http
, "\r\n", 2) < 0)
5920 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
5930 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5933 static int /* O - Bytes written */
5934 http_write_ssl(http_t
*http
, /* I - Connection to server */
5935 const char *buf
, /* I - Buffer holding data */
5936 int len
) /* I - Length of buffer */
5938 ssize_t result
; /* Return value */
5941 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5943 # if defined(HAVE_LIBSSL)
5944 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5946 # elif defined(HAVE_GNUTLS)
5947 result
= gnutls_record_send(http
->tls
, buf
, len
);
5949 if (result
< 0 && !errno
)
5952 * Convert GNU TLS error to errno value...
5957 case GNUTLS_E_INTERRUPTED
:
5961 case GNUTLS_E_AGAIN
:
5973 # elif defined(HAVE_CDSASSL)
5974 OSStatus error
; /* Error info */
5975 size_t processed
; /* Number of bytes processed */
5978 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5983 result
= (int)processed
;
5986 case errSSLWouldBlock
:
5988 result
= (int)processed
;
5996 case errSSLClosedGraceful
:
5999 result
= (int)processed
;
6007 # elif defined(HAVE_SSPISSL)
6008 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
6009 # endif /* HAVE_LIBSSL */
6011 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
6013 return ((int)result
);
6015 #endif /* HAVE_SSL */