2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for CUPS.
6 * Copyright 2007-2013 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * httpAcceptConnection() - Accept a new HTTP client connection from
23 * the specified listening socket.
24 * httpAddCredential() - Allocates and adds a single credential to
26 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP
28 * httpBlocking() - Set blocking/non-blocking behavior on a
30 * httpCheck() - Check to see if there is a pending response
32 * httpClearCookie() - Clear the cookie value(s).
33 * httpClearFields() - Clear HTTP request fields.
34 * httpClose() - Close an HTTP connection.
35 * httpConnect() - Connect to a HTTP server.
36 * httpConnect2() - Connect to a HTTP server.
37 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
38 * httpCopyCredentials() - Copy the credentials associated with an
39 * encrypted connection.
40 * _httpCreateCredentials() - Create credentials in the internal format.
41 * httpDelete() - Send a DELETE request to the server.
42 * _httpDisconnect() - Disconnect a HTTP connection.
43 * httpEncryption() - Set the required encryption on the link.
44 * httpError() - Get the last error on a connection.
45 * httpFlush() - Flush data from a HTTP connection.
46 * httpFlushWrite() - Flush data in write buffer.
47 * _httpFreeCredentials() - Free internal credentials.
48 * httpFreeCredentials() - Free an array of credentials.
49 * httpGet() - Send a GET request to the server.
50 * 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
);
963 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
965 if (bytes
> 0 && http
->data_encoding
== HTTP_ENCODING_LENGTH
)
967 http
->data_remaining
-= bytes
;
969 if (http
->data_remaining
<= 0)
977 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
984 * '_httpFreeCredentials()' - Free internal credentials.
988 _httpFreeCredentials(
989 http_tls_credentials_t credentials
) /* I - Internal credentials */
997 #elif defined(HAVE_GNUTLS)
1000 #elif defined(HAVE_CDSASSL)
1001 CFRelease(credentials
);
1003 #elif defined(HAVE_SSPISSL)
1006 #endif /* HAVE_LIBSSL */
1011 * 'httpFreeCredentials()' - Free an array of credentials.
1015 httpFreeCredentials(
1016 cups_array_t
*credentials
) /* I - Array of credentials */
1018 http_credential_t
*credential
; /* Credential */
1021 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
1023 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
1025 cupsArrayRemove(credentials
, credential
);
1026 free((void *)credential
->data
);
1030 cupsArrayDelete(credentials
);
1035 * 'httpGet()' - Send a GET request to the server.
1038 int /* O - Status of call (0 = success) */
1039 httpGet(http_t
*http
, /* I - Connection to server */
1040 const char *uri
) /* I - URI to get */
1042 return (http_send(http
, HTTP_STATE_GET
, uri
));
1047 * 'httpGetAuthString()' - Get the current authorization string.
1049 * The authorization string is set by cupsDoAuthentication() and
1050 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
1051 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
1054 * @since CUPS 1.3/OS X 10.5@
1057 char * /* O - Authorization string */
1058 httpGetAuthString(http_t
*http
) /* I - Connection to server */
1061 return (http
->authstring
);
1068 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
1070 * @since CUPS 1.2/OS X 10.5@
1073 int /* O - 1 if blocking, 0 if non-blocking */
1074 httpGetBlocking(http_t
*http
) /* I - Connection to server */
1076 return (http
? http
->blocking
: 0);
1081 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
1082 * the client and server.
1084 * This function uses the value of the Accepts-Encoding HTTP header and must be
1085 * called after receiving a response from the server or a request from the
1086 * client. The value returned can be use in subsequent requests (for clients)
1087 * or in the response (for servers) in order to compress the content stream.
1092 const char * /* O - Content-Coding value or
1093 @code NULL@ for the identity
1095 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
1098 if (http
&& http
->accept_encoding
)
1100 int i
; /* Looping var */
1101 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
1102 *start
, /* Start of coding value */
1103 *end
; /* End of coding value */
1104 double qvalue
; /* "qvalue" for coding */
1105 struct lconv
*loc
= localeconv(); /* Locale data */
1106 static const char * const codings
[] =
1107 { /* Supported content codings */
1114 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
1116 for (start
= temp
; *start
; start
= end
)
1119 * Find the end of the coding name...
1124 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
1130 * Grab the qvalue as needed...
1133 if (!strncmp(end
, ";q=", 3))
1134 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1137 * Skip past all attributes...
1141 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1147 while (*end
&& isspace(*end
& 255))
1151 * Check value if it matches something we support...
1157 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1158 if (!strcmp(start
, codings
[i
]))
1159 return (codings
[i
]);
1162 #endif /* HAVE_LIBZ */
1169 * 'httpGetCookie()' - Get any cookie data from the response.
1171 * @since CUPS 1.1.19/OS X 10.3@
1174 const char * /* O - Cookie data or NULL */
1175 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1177 return (http
? http
->cookie
: NULL
);
1182 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1184 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1185 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1190 http_status_t
/* O - Expect: status, if any */
1191 httpGetExpect(http_t
*http
) /* I - Connection to client */
1194 return (HTTP_STATUS_ERROR
);
1196 return (http
->expect
);
1201 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1203 * @since CUPS 1.2/OS X 10.5@
1206 int /* O - File descriptor or -1 if none */
1207 httpGetFd(http_t
*http
) /* I - Connection to server */
1209 return (http
? http
->fd
: -1);
1214 * 'httpGetField()' - Get a field value from a request/response.
1217 const char * /* O - Field value */
1218 httpGetField(http_t
*http
, /* I - Connection to server */
1219 http_field_t field
) /* I - Field to get */
1221 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1226 case HTTP_FIELD_ACCEPT_ENCODING
:
1227 return (http
->accept_encoding
);
1229 case HTTP_FIELD_ALLOW
:
1230 return (http
->allow
);
1232 case HTTP_FIELD_SERVER
:
1233 return (http
->server
);
1235 case HTTP_FIELD_AUTHORIZATION
:
1236 if (http
->field_authorization
)
1239 * Special case for WWW-Authenticate: as its contents can be
1240 * longer than HTTP_MAX_VALUE...
1243 return (http
->field_authorization
);
1247 return (http
->fields
[field
]);
1253 * 'httpGetLength()' - Get the amount of data remaining from the
1254 * content-length or transfer-encoding fields.
1256 * This function is deprecated and will not return lengths larger than
1257 * 2^31 - 1; use httpGetLength2() instead.
1262 int /* O - Content length */
1263 httpGetLength(http_t
*http
) /* I - Connection to server */
1266 * Get the read content length and return the 32-bit value.
1271 httpGetLength2(http
);
1273 return (http
->_data_remaining
);
1281 * 'httpGetLength2()' - Get the amount of data remaining from the
1282 * content-length or transfer-encoding fields.
1284 * This function returns the complete content length, even for
1285 * content larger than 2^31 - 1.
1287 * @since CUPS 1.2/OS X 10.5@
1290 off_t
/* O - Content length */
1291 httpGetLength2(http_t
*http
) /* I - Connection to server */
1293 off_t remaining
; /* Remaining length */
1296 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1297 http_state_string(http
->state
)));
1302 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1304 DEBUG_puts("4httpGetLength2: chunked request!");
1310 * The following is a hack for HTTP servers that don't send a
1311 * Content-Length or Transfer-Encoding field...
1313 * If there is no Content-Length then the connection must close
1314 * after the transfer is complete...
1317 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1320 * Default content length is 0 for errors and certain types of operations,
1321 * and 2^31-1 for other successful requests...
1324 if (http
->status
>= HTTP_STATUS_MULTIPLE_CHOICES
||
1325 http
->state
== HTTP_STATE_OPTIONS
||
1326 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1327 http
->state
== HTTP_STATE_HEAD
||
1328 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1329 http
->state
== HTTP_STATE_DELETE
||
1330 http
->state
== HTTP_STATE_TRACE
||
1331 http
->state
== HTTP_STATE_CONNECT
)
1334 remaining
= 2147483647;
1336 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1340 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1341 CUPS_LLCAST remaining
));
1349 * 'httpGets()' - Get a line of text from a HTTP connection.
1352 char * /* O - Line or NULL */
1353 httpGets(char *line
, /* I - Line to read into */
1354 int length
, /* I - Max length of buffer */
1355 http_t
*http
) /* I - Connection to server */
1357 char *lineptr
, /* Pointer into line */
1358 *lineend
, /* End of line */
1359 *bufptr
, /* Pointer into input buffer */
1360 *bufend
; /* Pointer to end of buffer */
1361 int bytes
, /* Number of bytes read */
1362 eol
; /* End-of-line? */
1365 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1367 if (!http
|| !line
|| length
<= 1)
1371 * Read a line from the buffer...
1376 lineend
= line
+ length
- 1;
1379 while (lineptr
< lineend
)
1382 * Pre-load the buffer as needed...
1391 while (http
->used
== 0)
1394 * No newline; see if there is more data to be read...
1397 while (!_httpWait(http
, http
->wait_value
, 1))
1399 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1402 DEBUG_puts("3httpGets: Timed out!");
1404 http
->error
= WSAETIMEDOUT
;
1406 http
->error
= ETIMEDOUT
;
1411 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1412 HTTP_MAX_BUFFER
- http
->used
);
1414 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1419 * Nope, can't get a line this time...
1423 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1425 if (WSAGetLastError() == WSAEINTR
)
1427 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1429 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1432 http
->error
= WSAGetLastError();
1434 else if (WSAGetLastError() != http
->error
)
1436 http
->error
= WSAGetLastError();
1441 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1445 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1447 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1449 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1452 http
->error
= errno
;
1454 else if (errno
!= http
->error
)
1456 http
->error
= errno
;
1463 else if (bytes
== 0)
1465 http
->error
= EPIPE
;
1471 * Yup, update the amount used...
1474 http
->used
+= bytes
;
1478 * Now copy as much of the current line as possible...
1481 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1482 lineptr
< lineend
&& bufptr
< bufend
;)
1484 if (*bufptr
== 0x0a)
1490 else if (*bufptr
== 0x0d)
1493 *lineptr
++ = *bufptr
++;
1496 http
->used
-= (int)(bufptr
- http
->buffer
);
1498 memmove(http
->buffer
, bufptr
, http
->used
);
1506 http
->activity
= time(NULL
);
1510 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1516 DEBUG_puts("3httpGets: No new line available!");
1523 * 'httpGetState()' - Get the current state of the HTTP request.
1526 http_state_t
/* O - HTTP state */
1527 httpGetState(http_t
*http
) /* I - Connection to server */
1529 return (http
? http
->state
: HTTP_STATE_ERROR
);
1534 * 'httpGetStatus()' - Get the status of the last HTTP request.
1536 * @since CUPS 1.2/OS X 10.5@
1539 http_status_t
/* O - HTTP status */
1540 httpGetStatus(http_t
*http
) /* I - Connection to server */
1542 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1547 * 'httpGetSubField()' - Get a sub-field value.
1552 char * /* O - Value or NULL */
1553 httpGetSubField(http_t
*http
, /* I - Connection to server */
1554 http_field_t field
, /* I - Field index */
1555 const char *name
, /* I - Name of sub-field */
1556 char *value
) /* O - Value string */
1558 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1563 * 'httpGetSubField2()' - Get a sub-field value.
1565 * @since CUPS 1.2/OS X 10.5@
1568 char * /* O - Value or NULL */
1569 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1570 http_field_t field
, /* I - Field index */
1571 const char *name
, /* I - Name of sub-field */
1572 char *value
, /* O - Value string */
1573 int valuelen
) /* I - Size of value buffer */
1575 const char *fptr
; /* Pointer into field */
1576 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1577 *ptr
, /* Pointer into string buffer */
1578 *end
; /* End of value buffer */
1580 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1581 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1583 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1584 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1587 end
= value
+ valuelen
- 1;
1589 for (fptr
= http
->fields
[field
]; *fptr
;)
1592 * Skip leading whitespace...
1595 while (_cups_isspace(*fptr
))
1605 * Get the sub-field name...
1609 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1610 ptr
< (temp
+ sizeof(temp
) - 1);
1615 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1618 * Skip trailing chars up to the '='...
1621 while (_cups_isspace(*fptr
))
1631 * Skip = and leading whitespace...
1636 while (_cups_isspace(*fptr
))
1642 * Read quoted string...
1645 for (ptr
= value
, fptr
++;
1646 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1651 while (*fptr
&& *fptr
!= '\"')
1660 * Read unquoted string...
1664 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1669 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1673 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1676 * See if this is the one...
1679 if (!strcmp(name
, temp
))
1681 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1688 DEBUG_puts("3httpGetSubField2: Returning NULL");
1695 * 'httpGetVersion()' - Get the HTTP version at the other end.
1698 http_version_t
/* O - Version number */
1699 httpGetVersion(http_t
*http
) /* I - Connection to server */
1701 return (http
? http
->version
: HTTP_VERSION_1_0
);
1706 * 'httpHead()' - Send a HEAD request to the server.
1709 int /* O - Status of call (0 = success) */
1710 httpHead(http_t
*http
, /* I - Connection to server */
1711 const char *uri
) /* I - URI for head */
1713 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1714 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1719 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1720 * default HTTP proxy (if any).
1724 httpInitialize(void)
1726 static int initialized
= 0; /* Have we been called before? */
1728 WSADATA winsockdata
; /* WinSock data */
1731 int i
; /* Looping var */
1732 unsigned char data
[1024]; /* Seed data */
1733 #endif /* HAVE_LIBSSL */
1739 _cupsGlobalUnlock();
1744 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1746 #elif !defined(SO_NOSIGPIPE)
1748 * Ignore SIGPIPE signals...
1752 sigset(SIGPIPE
, SIG_IGN
);
1754 # elif defined(HAVE_SIGACTION)
1755 struct sigaction action
; /* POSIX sigaction data */
1758 memset(&action
, 0, sizeof(action
));
1759 action
.sa_handler
= SIG_IGN
;
1760 sigaction(SIGPIPE
, &action
, NULL
);
1763 signal(SIGPIPE
, SIG_IGN
);
1764 # endif /* !SO_NOSIGPIPE */
1769 * Initialize GNU TLS...
1772 gnutls_global_init();
1774 #elif defined(HAVE_LIBSSL)
1776 * Initialize OpenSSL...
1779 SSL_load_error_strings();
1783 * Using the current time is a dubious random seed, but on some systems
1784 * it is the best we can do (on others, this seed isn't even used...)
1787 CUPS_SRAND(time(NULL
));
1789 for (i
= 0; i
< sizeof(data
); i
++)
1790 data
[i
] = CUPS_RAND();
1792 RAND_seed(data
, sizeof(data
));
1793 #endif /* HAVE_GNUTLS */
1796 _cupsGlobalUnlock();
1801 * 'httpOptions()' - Send an OPTIONS request to the server.
1804 int /* O - Status of call (0 = success) */
1805 httpOptions(http_t
*http
, /* I - Connection to server */
1806 const char *uri
) /* I - URI for options */
1808 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1813 * 'httpPeek()' - Peek at data from a HTTP connection.
1815 * This function copies available data from the given HTTP connection, reading
1816 * a buffer as needed. The data is still available for reading using
1817 * @link httpRead@ or @link httpRead2@.
1819 * For non-blocking connections the usual timeouts apply.
1824 ssize_t
/* O - Number of bytes copied */
1825 httpPeek(http_t
*http
, /* I - Connection to server */
1826 char *buffer
, /* I - Buffer for data */
1827 size_t length
) /* I - Maximum number of bytes */
1829 ssize_t bytes
; /* Bytes read */
1830 char len
[32]; /* Length string */
1833 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1834 http
, buffer
, CUPS_LLCAST length
));
1836 if (http
== NULL
|| buffer
== NULL
)
1839 http
->activity
= time(NULL
);
1845 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1846 http
->data_remaining
<= 0)
1848 DEBUG_puts("2httpPeek: Getting chunk length...");
1850 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1852 DEBUG_puts("1httpPeek: Could not get length!");
1858 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1859 if (!httpGets(len
, sizeof(len
), http
))
1861 DEBUG_puts("1httpPeek: Could not get chunk length.");
1866 http
->data_remaining
= strtoll(len
, NULL
, 16);
1868 if (http
->data_remaining
< 0)
1870 DEBUG_puts("1httpPeek: Negative chunk length!");
1875 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1876 CUPS_LLCAST http
->data_remaining
));
1878 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1881 * A zero-length chunk ends a transfer; unless we are reading POST
1887 http_content_coding_finish(http
);
1888 #endif /* HAVE_LIBZ */
1890 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1891 httpGets(len
, sizeof(len
), http
);
1893 if (http
->state
== HTTP_STATE_POST_RECV
)
1896 http
->state
= HTTP_STATE_STATUS
;
1898 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1899 http_state_string(http
->state
)));
1902 * Prevent future reads for this request...
1905 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1909 else if (length
> (size_t)http
->data_remaining
)
1910 length
= (size_t)http
->data_remaining
;
1913 if (http
->used
== 0 &&
1914 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1916 if (http
->used
== 0)
1917 #endif /* HAVE_LIBZ */
1920 * Buffer small reads for better performance...
1923 ssize_t buflen
; /* Length of read for buffer */
1925 if (!http
->blocking
)
1927 while (!httpWait(http
, http
->wait_value
))
1929 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1936 if (http
->data_remaining
> sizeof(http
->buffer
))
1937 buflen
= sizeof(http
->buffer
);
1939 buflen
= http
->data_remaining
;
1941 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1942 bytes
= http_read(http
, http
->buffer
, buflen
);
1944 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1945 CUPS_LLCAST bytes
));
1949 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1959 # ifdef HAVE_INFLATECOPY
1960 int zerr
; /* Decompressor error */
1961 z_stream stream
; /* Copy of decompressor stream */
1963 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1965 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1966 /* Number of bytes to copy */
1968 if (http
->stream
.avail_in
> 0 &&
1969 http
->stream
.next_in
> http
->dbuffer
)
1970 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1972 http
->stream
.next_in
= http
->dbuffer
;
1974 if (buflen
> http
->data_remaining
)
1975 buflen
= http
->data_remaining
;
1977 if (buflen
> http
->used
)
1978 buflen
= http
->used
;
1980 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1981 "decompression buffer.", (int)buflen
));
1983 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
1984 http
->stream
.avail_in
+= buflen
;
1985 http
->used
-= buflen
;
1986 http
->data_remaining
-= buflen
;
1989 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
1992 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
1993 (int)http
->stream
.avail_in
));
1995 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
1997 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
1998 http
->error
= ENOMEM
;
2002 stream
.next_out
= (Bytef
*)buffer
;
2003 stream
.avail_out
= length
;
2005 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
2006 inflateEnd(&stream
);
2010 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
2012 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
2013 http
->stream
.avail_in
);
2020 bytes
= length
- http
->stream
.avail_out
;
2023 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
2024 "work with compressed streams.");
2026 # endif /* HAVE_INFLATECOPY */
2029 #endif /* HAVE_LIBZ */
2032 if (length
> (size_t)http
->used
)
2033 length
= (size_t)http
->used
;
2035 bytes
= (ssize_t
)length
;
2037 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
2040 memcpy(buffer
, http
->buffer
, length
);
2048 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2051 http
->error
= WSAGetLastError();
2053 if (errno
== EINTR
|| errno
== EAGAIN
)
2056 http
->error
= errno
;
2059 else if (bytes
== 0)
2061 http
->error
= EPIPE
;
2068 /* For OS X 10.8 and earlier */
2069 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
2070 { return (httpPeek(http
, buffer
, length
)); }
2074 * 'httpPost()' - Send a POST request to the server.
2077 int /* O - Status of call (0 = success) */
2078 httpPost(http_t
*http
, /* I - Connection to server */
2079 const char *uri
) /* I - URI for post */
2081 return (http_send(http
, HTTP_STATE_POST
, uri
));
2086 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
2091 int /* O - Number of bytes written */
2092 httpPrintf(http_t
*http
, /* I - Connection to server */
2093 const char *format
, /* I - printf-style format string */
2094 ...) /* I - Additional args as needed */
2096 int bytes
; /* Number of bytes to write */
2097 char buf
[16384]; /* Buffer for formatted string */
2098 va_list ap
; /* Variable argument pointer */
2101 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
2103 va_start(ap
, format
);
2104 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
2107 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
2109 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
2110 return (httpWrite2(http
, buf
, bytes
));
2115 DEBUG_puts("4httpPrintf: flushing existing data...");
2117 if (httpFlushWrite(http
) < 0)
2121 return (http_write(http
, buf
, bytes
));
2127 * 'httpPut()' - Send a PUT request to the server.
2130 int /* O - Status of call (0 = success) */
2131 httpPut(http_t
*http
, /* I - Connection to server */
2132 const char *uri
) /* I - URI to put */
2134 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2135 return (http_send(http
, HTTP_STATE_PUT
, uri
));
2140 * 'httpRead()' - Read data from a HTTP connection.
2142 * This function is deprecated. Use the httpRead2() function which can
2143 * read more than 2GB of data.
2148 int /* O - Number of bytes read */
2149 httpRead(http_t
*http
, /* I - Connection to server */
2150 char *buffer
, /* I - Buffer for data */
2151 int length
) /* I - Maximum number of bytes */
2153 return ((int)httpRead2(http
, buffer
, length
));
2158 * 'httpRead2()' - Read data from a HTTP connection.
2160 * @since CUPS 1.2/OS X 10.5@
2163 ssize_t
/* O - Number of bytes read */
2164 httpRead2(http_t
*http
, /* I - Connection to server */
2165 char *buffer
, /* I - Buffer for data */
2166 size_t length
) /* I - Maximum number of bytes */
2168 ssize_t bytes
; /* Bytes read */
2172 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2173 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
2174 http
, buffer
, CUPS_LLCAST length
,
2176 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2178 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2179 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
2180 http
, buffer
, CUPS_LLCAST length
,
2181 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2182 #endif /* HAVE_LIBZ */
2184 if (http
== NULL
|| buffer
== NULL
)
2187 http
->activity
= time(NULL
);
2198 if (http
->stream
.avail_in
> 0)
2200 int zerr
; /* Decompressor error */
2202 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2203 (int)http
->stream
.avail_in
, (int)length
));
2205 http
->stream
.next_out
= (Bytef
*)buffer
;
2206 http
->stream
.avail_out
= length
;
2208 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2210 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2212 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2213 http
->stream
.avail_in
);
2220 bytes
= length
- http
->stream
.avail_out
;
2222 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2223 http
->stream
.avail_in
, http
->stream
.avail_out
,
2231 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2232 /* Additional bytes for buffer */
2236 if (http
->stream
.avail_in
> 0 &&
2237 http
->stream
.next_in
> http
->dbuffer
)
2238 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2240 http
->stream
.next_in
= http
->dbuffer
;
2242 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2243 "decompression buffer.", (int)buflen
));
2245 if (http
->data_remaining
> 0)
2247 if (buflen
> http
->data_remaining
)
2248 buflen
= http
->data_remaining
;
2250 bytes
= http_read_buffered(http
,
2251 (char *)http
->dbuffer
+
2252 http
->stream
.avail_in
, buflen
);
2254 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2255 bytes
= http_read_chunk(http
,
2256 (char *)http
->dbuffer
+
2257 http
->stream
.avail_in
, buflen
);
2263 else if (bytes
== 0)
2266 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2267 "decompression buffer.", CUPS_LLCAST bytes
));
2269 http
->data_remaining
-= bytes
;
2270 http
->stream
.avail_in
+= bytes
;
2272 if (http
->data_remaining
<= 0 &&
2273 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2276 * Read the trailing blank line now...
2279 char len
[32]; /* Length string */
2281 httpGets(len
, sizeof(len
), http
);
2293 #endif /* HAVE_LIBZ */
2294 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2296 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2298 http
->data_remaining
-= bytes
;
2300 if (http
->data_remaining
<= 0)
2303 * Read the trailing blank line now...
2306 char len
[32]; /* Length string */
2308 httpGets(len
, sizeof(len
), http
);
2312 else if (http
->data_remaining
<= 0)
2315 * No more data to read...
2322 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2325 if (length
> (size_t)http
->data_remaining
)
2326 length
= (size_t)http
->data_remaining
;
2328 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2330 http
->data_remaining
-= bytes
;
2332 if (http
->data_remaining
<= 0 &&
2333 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2336 * Read the trailing blank line now...
2339 char len
[32]; /* Length string */
2341 httpGets(len
, sizeof(len
), http
);
2348 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2349 #endif /* HAVE_LIBZ */
2350 ((http
->data_remaining
<= 0 &&
2351 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2352 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2356 http_content_coding_finish(http
);
2357 #endif /* HAVE_LIBZ */
2359 if (http
->state
== HTTP_STATE_POST_RECV
)
2361 else if (http
->state
== HTTP_STATE_GET_SEND
||
2362 http
->state
== HTTP_STATE_POST_SEND
)
2363 http
->state
= HTTP_STATE_WAITING
;
2365 http
->state
= HTTP_STATE_STATUS
;
2367 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2368 http_state_string(http
->state
)));
2375 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2377 * '_httpReadCDSA()' - Read function for the CDSA library.
2380 OSStatus
/* O - -1 on error, 0 on success */
2382 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2383 void *data
, /* I - Data buffer */
2384 size_t *dataLength
) /* IO - Number of bytes */
2386 OSStatus result
; /* Return value */
2387 ssize_t bytes
; /* Number of bytes read */
2388 http_t
*http
; /* HTTP connection */
2391 http
= (http_t
*)connection
;
2393 if (!http
->blocking
)
2396 * Make sure we have data before we read...
2399 while (!_httpWait(http
, http
->wait_value
, 0))
2401 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2404 http
->error
= ETIMEDOUT
;
2411 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2413 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2415 if (bytes
== *dataLength
)
2421 *dataLength
= bytes
;
2422 result
= errSSLWouldBlock
;
2429 result
= errSSLClosedGraceful
;
2430 else if (errno
== EAGAIN
)
2431 result
= errSSLWouldBlock
;
2433 result
= errSSLClosedAbort
;
2438 #endif /* HAVE_SSL && HAVE_CDSASSL */
2441 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2443 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2446 ssize_t
/* O - Number of bytes read or -1 on error */
2448 gnutls_transport_ptr ptr
, /* I - Connection to server */
2449 void *data
, /* I - Buffer */
2450 size_t length
) /* I - Number of bytes to read */
2452 http_t
*http
; /* HTTP connection */
2453 ssize_t bytes
; /* Bytes read */
2456 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2458 http
= (http_t
*)ptr
;
2460 if (!http
->blocking
)
2463 * Make sure we have data before we read...
2466 while (!_httpWait(http
, http
->wait_value
, 0))
2468 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2471 http
->error
= ETIMEDOUT
;
2476 bytes
= recv(http
->fd
, data
, length
, 0);
2477 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2480 #endif /* HAVE_SSL && HAVE_GNUTLS */
2484 * 'httpReadRequest()' - Read a HTTP request from a connection.
2489 http_state_t
/* O - New state of connection */
2490 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2491 char *uri
, /* I - URI buffer */
2492 size_t urilen
) /* I - Size of URI buffer */
2494 char line
[4096], /* HTTP request line */
2495 *req_method
, /* HTTP request method */
2496 *req_uri
, /* HTTP request URI */
2497 *req_version
; /* HTTP request version number string */
2501 * Range check input...
2504 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2505 http
, uri
, CUPS_LLCAST urilen
));
2510 if (!http
|| !uri
|| urilen
< 1)
2512 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2513 return (HTTP_STATE_ERROR
);
2515 else if (http
->state
!= HTTP_STATE_WAITING
)
2517 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2518 http_state_string(http
->state
)));
2519 return (HTTP_STATE_ERROR
);
2526 httpClearFields(http
);
2528 http
->activity
= time(NULL
);
2529 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2530 http
->data_remaining
= 0;
2531 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2532 http
->status
= HTTP_STATUS_OK
;
2533 http
->version
= HTTP_VERSION_1_1
;
2536 * Read a line from the socket...
2539 if (!httpGets(line
, sizeof(line
), http
))
2541 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2542 return (HTTP_STATE_ERROR
);
2547 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2548 return (HTTP_STATE_WAITING
);
2551 DEBUG_printf(("1httpReadRequest: %s", line
));
2560 while (*req_uri
&& !isspace(*req_uri
& 255))
2565 DEBUG_puts("1httpReadRequest: No request URI.");
2566 return (HTTP_STATE_ERROR
);
2571 while (*req_uri
&& isspace(*req_uri
& 255))
2574 req_version
= req_uri
;
2576 while (*req_version
&& !isspace(*req_version
& 255))
2581 DEBUG_puts("1httpReadRequest: No request protocol version.");
2582 return (HTTP_STATE_ERROR
);
2585 *req_version
++ = '\0';
2587 while (*req_version
&& isspace(*req_version
& 255))
2594 if (!strcmp(req_method
, "OPTIONS"))
2595 http
->state
= HTTP_STATE_OPTIONS
;
2596 else if (!strcmp(req_method
, "GET"))
2597 http
->state
= HTTP_STATE_GET
;
2598 else if (!strcmp(req_method
, "HEAD"))
2599 http
->state
= HTTP_STATE_HEAD
;
2600 else if (!strcmp(req_method
, "POST"))
2601 http
->state
= HTTP_STATE_POST
;
2602 else if (!strcmp(req_method
, "PUT"))
2603 http
->state
= HTTP_STATE_PUT
;
2604 else if (!strcmp(req_method
, "DELETE"))
2605 http
->state
= HTTP_STATE_DELETE
;
2606 else if (!strcmp(req_method
, "TRACE"))
2607 http
->state
= HTTP_STATE_TRACE
;
2608 else if (!strcmp(req_method
, "CONNECT"))
2609 http
->state
= HTTP_STATE_CONNECT
;
2612 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2613 return (HTTP_STATE_UNKNOWN_METHOD
);
2616 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2617 http_state_string(http
->state
)));
2619 if (!strcmp(req_version
, "HTTP/1.0"))
2621 http
->version
= HTTP_VERSION_1_0
;
2622 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2624 else if (!strcmp(req_version
, "HTTP/1.1"))
2626 http
->version
= HTTP_VERSION_1_1
;
2627 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2631 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2632 return (HTTP_STATE_UNKNOWN_VERSION
);
2635 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2636 strlcpy(uri
, req_uri
, urilen
);
2638 return (http
->state
);
2643 * 'httpReconnect()' - Reconnect to a HTTP server.
2645 * This function is deprecated. Please use the @link httpReconnect2@ function
2651 int /* O - 0 on success, non-zero on failure */
2652 httpReconnect(http_t
*http
) /* I - Connection to server */
2654 DEBUG_printf(("httpReconnect(http=%p)", http
));
2656 return (httpReconnect2(http
, 30000, NULL
));
2661 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2665 int /* O - 0 on success, non-zero on failure */
2666 httpReconnect2(http_t
*http
, /* I - Connection to server */
2667 int msec
, /* I - Timeout in milliseconds */
2668 int *cancel
) /* I - Pointer to "cancel" variable */
2670 http_addrlist_t
*addr
; /* Connected address */
2672 http_addrlist_t
*current
; /* Current address */
2673 char temp
[256]; /* Temporary address string */
2677 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2682 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2689 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2690 http_shutdown_ssl(http
);
2692 #endif /* HAVE_SSL */
2695 * Close any previously open socket...
2700 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2703 closesocket(http
->fd
);
2712 * Reset all state (except fields, which may be reused)...
2715 http
->state
= HTTP_STATE_WAITING
;
2716 http
->version
= HTTP_VERSION_1_1
;
2717 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2718 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2719 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2720 http
->_data_remaining
= 0;
2722 http
->data_remaining
= 0;
2723 http
->hostaddr
= NULL
;
2727 * Connect to the server...
2731 for (current
= http
->addrlist
; current
; current
= current
->next
)
2732 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2733 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2734 httpAddrPort(&(current
->addr
))));
2737 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2741 * Unable to connect...
2745 http
->error
= WSAGetLastError();
2747 http
->error
= errno
;
2749 http
->status
= HTTP_STATUS_ERROR
;
2751 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2752 strerror(http
->error
)));
2757 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2759 if (http
->timeout_value
> 0)
2760 http_set_timeout(http
->fd
, http
->timeout_value
);
2762 http
->hostaddr
= &(addr
->addr
);
2766 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2769 * Always do encryption via SSL.
2772 if (http_setup_ssl(http
) != 0)
2775 closesocket(http
->fd
);
2783 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2784 return (http_upgrade(http
));
2785 #endif /* HAVE_SSL */
2787 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2788 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2789 httpAddrPort(http
->hostaddr
)));
2796 * 'httpSetAuthString()' - Set the current authorization string.
2798 * This function just stores a copy of the current authorization string in
2799 * the HTTP connection object. You must still call httpSetField() to set
2800 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2801 * httpHead(), httpOptions(), httpPost, or httpPut().
2803 * @since CUPS 1.3/OS X 10.5@
2807 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2808 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2809 const char *data
) /* I - Auth data (NULL for none) */
2812 * Range check input...
2818 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2819 free(http
->authstring
);
2821 http
->authstring
= http
->_authstring
;
2826 * Set the current authorization string...
2829 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2832 if (len
> (int)sizeof(http
->_authstring
))
2834 if ((temp
= malloc(len
)) == NULL
)
2835 len
= sizeof(http
->_authstring
);
2837 http
->authstring
= temp
;
2841 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2843 strlcpy(http
->authstring
, scheme
, len
);
2848 * Clear the current authorization string...
2851 http
->_authstring
[0] = '\0';
2857 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2860 * @since CUPS 1.5/OS X 10.7@
2863 int /* O - Status of call (0 = success) */
2864 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2865 cups_array_t
*credentials
) /* I - Array of credentials */
2867 if (!http
|| cupsArrayCount(credentials
) < 1)
2870 _httpFreeCredentials(http
->tls_credentials
);
2872 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2874 return (http
->tls_credentials
? 0 : -1);
2879 * 'httpSetCookie()' - Set the cookie value(s).
2881 * @since CUPS 1.1.19/OS X 10.3@
2885 httpSetCookie(http_t
*http
, /* I - Connection */
2886 const char *cookie
) /* I - Cookie string */
2895 http
->cookie
= strdup(cookie
);
2897 http
->cookie
= NULL
;
2902 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2904 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2905 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2911 httpSetDefaultField(http_t
*http
, /* I - Connection to server */
2912 http_field_t field
, /* I - Field index */
2913 const char *value
)/* I - Value */
2915 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2916 http
, field
, http_fields
[field
], value
));
2923 case HTTP_FIELD_ACCEPT_ENCODING
:
2924 if (http
->default_accept_encoding
)
2925 _cupsStrFree(http
->default_accept_encoding
);
2927 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2930 case HTTP_FIELD_SERVER
:
2931 if (http
->default_server
)
2932 _cupsStrFree(http
->default_server
);
2934 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2937 case HTTP_FIELD_USER_AGENT
:
2938 if (http
->default_user_agent
)
2939 _cupsStrFree(http
->default_user_agent
);
2941 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2945 DEBUG_puts("1httpSetDefaultField: Ignored.");
2952 * 'httpSetExpect()' - Set the Expect: header in a request.
2954 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2957 * @since CUPS 1.2/OS X 10.5@
2961 httpSetExpect(http_t
*http
, /* I - Connection to server */
2962 http_status_t expect
) /* I - HTTP status to expect
2963 (@code HTTP_STATUS_CONTINUE@) */
2965 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2968 http
->expect
= expect
;
2973 * 'httpSetField()' - Set the value of an HTTP header.
2977 httpSetField(http_t
*http
, /* I - Connection to server */
2978 http_field_t field
, /* I - Field index */
2979 const char *value
) /* I - Value */
2981 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2982 field
, http_fields
[field
], value
));
2985 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2986 field
>= HTTP_FIELD_MAX
||
2992 case HTTP_FIELD_ACCEPT_ENCODING
:
2993 if (http
->accept_encoding
)
2994 _cupsStrFree(http
->accept_encoding
);
2996 http
->accept_encoding
= _cupsStrAlloc(value
);
2999 case HTTP_FIELD_ALLOW
:
3001 _cupsStrFree(http
->allow
);
3003 http
->allow
= _cupsStrAlloc(value
);
3006 case HTTP_FIELD_SERVER
:
3008 _cupsStrFree(http
->server
);
3010 http
->server
= _cupsStrAlloc(value
);
3014 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
3018 if (field
== HTTP_FIELD_AUTHORIZATION
)
3021 * Special case for Authorization: as its contents can be
3022 * longer than HTTP_MAX_VALUE
3025 if (http
->field_authorization
)
3026 free(http
->field_authorization
);
3028 http
->field_authorization
= strdup(value
);
3030 else if (field
== HTTP_FIELD_HOST
)
3033 * Special-case for Host: as we don't want a trailing "." on the hostname and
3034 * need to bracket IPv6 numeric addresses.
3037 char *ptr
= strchr(value
, ':');
3039 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
3042 * Bracket IPv6 numeric addresses...
3044 * This is slightly inefficient (basically copying twice), but is an edge
3045 * case and not worth optimizing...
3048 snprintf(http
->fields
[HTTP_FIELD_HOST
],
3049 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
3054 * Check for a trailing dot on the hostname...
3057 ptr
= http
->fields
[HTTP_FIELD_HOST
];
3061 ptr
+= strlen(ptr
) - 1;
3069 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
3070 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
3072 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
3073 http_content_coding_start(http
, value
);
3075 #endif /* HAVE_LIBZ */
3080 * 'httpSetLength()' - Set the content-length and content-encoding.
3082 * @since CUPS 1.2/OS X 10.5@
3086 httpSetLength(http_t
*http
, /* I - Connection to server */
3087 size_t length
) /* I - Length (0 for chunked) */
3089 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
3090 CUPS_LLCAST length
));
3097 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
3099 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
3103 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
3104 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
3105 CUPS_LLFMT
, CUPS_LLCAST length
);
3111 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
3113 * The optional timeout callback receives both the HTTP connection and a user
3114 * data pointer and must return 1 to continue or 0 to error (time) out.
3116 * @since CUPS 1.5/OS X 10.7@
3121 http_t
*http
, /* I - Connection to server */
3122 double timeout
, /* I - Number of seconds for timeout,
3123 must be greater than 0 */
3124 http_timeout_cb_t cb
, /* I - Callback function or NULL */
3125 void *user_data
) /* I - User data pointer */
3127 if (!http
|| timeout
<= 0.0)
3130 http
->timeout_cb
= cb
;
3131 http
->timeout_data
= user_data
;
3132 http
->timeout_value
= timeout
;
3135 http_set_timeout(http
->fd
, timeout
);
3137 http_set_wait(http
);
3142 * 'httpTrace()' - Send an TRACE request to the server.
3145 int /* O - Status of call (0 = success) */
3146 httpTrace(http_t
*http
, /* I - Connection to server */
3147 const char *uri
) /* I - URI for trace */
3149 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
3154 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3156 * Note: Unlike httpUpdate(), this function does not flush pending write data
3157 * and only retrieves a single status line from the HTTP connection.
3160 int /* O - 1 to continue, 0 to stop */
3161 _httpUpdate(http_t
*http
, /* I - Connection to server */
3162 http_status_t
*status
) /* O - Current HTTP status */
3164 char line
[32768], /* Line from connection... */
3165 *value
; /* Pointer to value on line */
3166 http_field_t field
; /* Field index */
3167 int major
, minor
; /* HTTP version numbers */
3170 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3171 http_state_string(http
->state
)));
3174 * Grab a single line from the connection...
3177 if (!httpGets(line
, sizeof(line
), http
))
3179 *status
= HTTP_STATUS_ERROR
;
3183 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3185 if (line
[0] == '\0')
3188 * Blank line means the start of the data section (if any). Return
3189 * the result code, too...
3191 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3192 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3196 if (http
->status
== HTTP_STATUS_CONTINUE
)
3198 *status
= http
->status
;
3202 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
3203 http
->digest_tries
= 0;
3206 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
3208 if (http_setup_ssl(http
) != 0)
3211 closesocket(http
->fd
);
3216 *status
= http
->status
= HTTP_STATUS_ERROR
;
3220 *status
= HTTP_STATUS_CONTINUE
;
3223 #endif /* HAVE_SSL */
3225 if (http_set_length(http
) < 0)
3227 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3228 http
->error
= EINVAL
;
3229 http
->status
= *status
= HTTP_STATUS_ERROR
;
3233 switch (http
->state
)
3235 case HTTP_STATE_GET
:
3236 case HTTP_STATE_POST
:
3237 case HTTP_STATE_POST_RECV
:
3238 case HTTP_STATE_PUT
:
3241 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3242 http_state_string(http
->state
)));
3244 case HTTP_STATE_POST_SEND
:
3245 case HTTP_STATE_HEAD
:
3249 http
->state
= HTTP_STATE_WAITING
;
3251 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
3256 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3257 http_content_coding_start(http
,
3258 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3259 #endif /* HAVE_LIBZ */
3261 *status
= http
->status
;
3264 else if (!strncmp(line
, "HTTP/", 5))
3267 * Got the beginning of a response...
3270 int intstatus
; /* Status value as an integer */
3272 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3274 *status
= http
->status
= HTTP_STATUS_ERROR
;
3278 httpClearFields(http
);
3280 http
->version
= (http_version_t
)(major
* 100 + minor
);
3281 *status
= http
->status
= (http_status_t
)intstatus
;
3283 else if ((value
= strchr(line
, ':')) != NULL
)
3290 while (_cups_isspace(*value
))
3293 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3296 * Be tolerants of servers that send unknown attribute fields...
3299 if (!_cups_strcasecmp(line
, "expect"))
3302 * "Expect: 100-continue" or similar...
3305 http
->expect
= (http_status_t
)atoi(value
);
3307 else if (!_cups_strcasecmp(line
, "cookie"))
3310 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3313 httpSetCookie(http
, value
);
3315 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
3316 httpSetField(http
, field
, value
);
3319 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3324 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3325 http
->error
= EINVAL
;
3326 http
->status
= *status
= HTTP_STATUS_ERROR
;
3335 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3338 http_status_t
/* O - HTTP status */
3339 httpUpdate(http_t
*http
) /* I - Connection to server */
3341 http_status_t status
; /* Request status */
3344 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3345 http_state_string(http
->state
)));
3348 * Flush pending data, if any...
3353 DEBUG_puts("2httpUpdate: flushing buffer...");
3355 if (httpFlushWrite(http
) < 0)
3356 return (HTTP_STATUS_ERROR
);
3360 * If we haven't issued any commands, then there is nothing to "update"...
3363 if (http
->state
== HTTP_STATE_WAITING
)
3364 return (HTTP_STATUS_CONTINUE
);
3367 * Grab all of the lines we can from the connection...
3370 while (_httpUpdate(http
, &status
));
3373 * See if there was an error...
3376 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3378 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3379 return (http
->status
);
3384 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3385 strerror(http
->error
)));
3386 http
->status
= HTTP_STATUS_ERROR
;
3387 return (HTTP_STATUS_ERROR
);
3391 * Return the current status...
3399 * '_httpWait()' - Wait for data available on a connection (no flush).
3402 int /* O - 1 if data is available, 0 otherwise */
3403 _httpWait(http_t
*http
, /* I - Connection to server */
3404 int msec
, /* I - Milliseconds to wait */
3405 int usessl
) /* I - Use SSL context? */
3408 struct pollfd pfd
; /* Polled file descriptor */
3410 fd_set input_set
; /* select() input set */
3411 struct timeval timeout
; /* Timeout */
3412 #endif /* HAVE_POLL */
3413 int nfds
; /* Result from select()/poll() */
3416 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3420 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3425 * Check the SSL/TLS buffers for data first...
3429 if (http
->tls
&& usessl
)
3432 if (SSL_pending(http
->tls
))
3434 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3438 # elif defined(HAVE_GNUTLS)
3439 if (gnutls_record_check_pending(http
->tls
))
3441 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3445 # elif defined(HAVE_CDSASSL)
3446 size_t bytes
; /* Bytes that are available */
3448 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3451 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3454 # endif /* HAVE_LIBSSL */
3456 #endif /* HAVE_SSL */
3459 * Then try doing a select() or poll() to poll the socket...
3464 pfd
.events
= POLLIN
;
3468 nfds
= poll(&pfd
, 1, msec
);
3470 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3475 FD_ZERO(&input_set
);
3476 FD_SET(http
->fd
, &input_set
);
3478 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3482 timeout
.tv_sec
= msec
/ 1000;
3483 timeout
.tv_usec
= (msec
% 1000) * 1000;
3485 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3488 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3490 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3493 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3494 WSAGetLastError() == WSAEWOULDBLOCK
));
3496 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3498 #endif /* HAVE_POLL */
3500 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3508 * 'httpWait()' - Wait for data available on a connection.
3510 * @since CUPS 1.1.19/OS X 10.3@
3513 int /* O - 1 if data is available, 0 otherwise */
3514 httpWait(http_t
*http
, /* I - Connection to server */
3515 int msec
) /* I - Milliseconds to wait */
3518 * First see if there is data in the buffer...
3521 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3528 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3533 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3535 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3538 #endif /* HAVE_LIBZ */
3541 * Flush pending data, if any...
3546 DEBUG_puts("3httpWait: Flushing write buffer.");
3548 if (httpFlushWrite(http
) < 0)
3553 * If not, check the SSL/TLS buffers and do a select() on the connection...
3556 return (_httpWait(http
, msec
, 1));
3561 * 'httpWrite()' - Write data to a HTTP connection.
3563 * This function is deprecated. Use the httpWrite2() function which can
3564 * write more than 2GB of data.
3569 int /* O - Number of bytes written */
3570 httpWrite(http_t
*http
, /* I - Connection to server */
3571 const char *buffer
, /* I - Buffer for data */
3572 int length
) /* I - Number of bytes to write */
3574 return ((int)httpWrite2(http
, buffer
, length
));
3579 * 'httpWrite2()' - Write data to a HTTP connection.
3581 * @since CUPS 1.2/OS X 10.5@
3584 ssize_t
/* O - Number of bytes written */
3585 httpWrite2(http_t
*http
, /* I - Connection to server */
3586 const char *buffer
, /* I - Buffer for data */
3587 size_t length
) /* I - Number of bytes to write */
3589 ssize_t bytes
; /* Bytes written */
3592 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3593 buffer
, CUPS_LLCAST length
));
3596 * Range check input...
3599 if (!http
|| !buffer
)
3601 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3606 * Mark activity on the connection...
3609 http
->activity
= time(NULL
);
3612 * Buffer small writes for better performance...
3618 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3622 http_content_coding_finish(http
);
3627 http
->stream
.next_in
= (Bytef
*)buffer
;
3628 http
->stream
.avail_in
= length
;
3629 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3630 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3632 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3634 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3636 if (http
->stream
.avail_out
== 0)
3638 if (httpFlushWrite(http
) < 0)
3640 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3644 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3645 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3649 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3654 #endif /* HAVE_LIBZ */
3657 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3659 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3660 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3662 httpFlushWrite(http
);
3665 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3666 length
< sizeof(http
->wbuffer
))
3669 * Write to buffer...
3672 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3673 CUPS_LLCAST length
));
3675 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3676 http
->wused
+= (int)length
;
3677 bytes
= (ssize_t
)length
;
3682 * Otherwise write the data directly...
3685 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3686 CUPS_LLCAST length
));
3688 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3689 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3691 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3693 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3694 CUPS_LLCAST bytes
));
3697 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3698 http
->data_remaining
-= bytes
;
3704 * Handle end-of-request processing...
3707 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3708 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3711 * Finished with the transfer; unless we are sending POST or PUT
3717 http_content_coding_finish(http
);
3718 #endif /* HAVE_LIBZ */
3722 if (httpFlushWrite(http
) < 0)
3726 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3729 * Send a 0-length chunk at the end of the request...
3732 http_write(http
, "0\r\n\r\n", 5);
3735 * Reset the data state...
3738 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3739 http
->data_remaining
= 0;
3742 if (http
->state
== HTTP_STATE_POST_RECV
)
3745 http
->state
= HTTP_STATE_STATUS
;
3747 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3748 http_state_string(http
->state
)));
3751 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3757 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3759 * '_httpWriteCDSA()' - Write function for the CDSA library.
3762 OSStatus
/* O - -1 on error, 0 on success */
3764 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3765 const void *data
, /* I - Data buffer */
3766 size_t *dataLength
) /* IO - Number of bytes */
3768 OSStatus result
; /* Return value */
3769 ssize_t bytes
; /* Number of bytes read */
3770 http_t
*http
; /* HTTP connection */
3773 http
= (http_t
*)connection
;
3777 bytes
= write(http
->fd
, data
, *dataLength
);
3779 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3781 if (bytes
== *dataLength
)
3785 else if (bytes
>= 0)
3787 *dataLength
= bytes
;
3788 result
= errSSLWouldBlock
;
3794 if (errno
== EAGAIN
)
3795 result
= errSSLWouldBlock
;
3797 result
= errSSLClosedAbort
;
3802 #endif /* HAVE_SSL && HAVE_CDSASSL */
3805 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3807 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3810 ssize_t
/* O - Number of bytes written or -1 on error */
3812 gnutls_transport_ptr ptr
, /* I - Connection to server */
3813 const void *data
, /* I - Data buffer */
3814 size_t length
) /* I - Number of bytes to write */
3816 ssize_t bytes
; /* Bytes written */
3819 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3822 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3825 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3826 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3830 #endif /* HAVE_SSL && HAVE_GNUTLS */
3834 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3839 int /* O - 0 on success, -1 on error */
3840 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3841 http_status_t status
) /* I - Status code */
3843 http_encoding_t old_encoding
; /* Old data_encoding value */
3844 off_t old_remaining
; /* Old data_remaining value */
3848 * Range check input...
3851 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3853 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3855 DEBUG_puts("1httpWriteResponse: Bad input.");
3860 * Set the various standard fields if they aren't already...
3863 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3864 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3866 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3868 http
->keep_alive
= 0;
3869 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3872 if (http
->version
== HTTP_VERSION_1_1
)
3874 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3876 if (http
->keep_alive
)
3877 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3879 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3882 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3883 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3887 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
)
3889 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3890 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3892 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3893 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3895 #endif /* HAVE_SSL */
3898 httpSetField(http
, HTTP_FIELD_SERVER
,
3899 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3902 * Set the Accept-Encoding field if it isn't already...
3905 if (!http
->accept_encoding
)
3906 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3907 http
->default_accept_encoding
? http
->default_accept_encoding
:
3909 "gzip, deflate, identity");
3912 #endif /* HAVE_LIBZ */
3915 * Send the response header...
3918 old_encoding
= http
->data_encoding
;
3919 old_remaining
= http
->data_remaining
;
3920 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3922 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3923 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3925 http
->status
= HTTP_STATUS_ERROR
;
3929 if (status
!= HTTP_STATUS_CONTINUE
)
3932 * 100 Continue doesn't have the rest of the response headers...
3935 int i
; /* Looping var */
3936 const char *value
; /* Field value */
3938 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3940 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3942 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3944 http
->status
= HTTP_STATUS_ERROR
;
3952 if (httpPrintf(http
, "Set-Cookie: %s path=/%s\r\n", http
->cookie
,
3953 http
->tls
? " secure" : "") < 1)
3955 http
->status
= HTTP_STATUS_ERROR
;
3961 if (httpWrite2(http
, "\r\n", 2) < 2)
3963 http
->status
= HTTP_STATUS_ERROR
;
3967 if (httpFlushWrite(http
) < 0)
3969 http
->status
= HTTP_STATUS_ERROR
;
3973 if (status
== HTTP_STATUS_CONTINUE
)
3976 * Restore the old data_encoding and data_length values...
3979 http
->data_encoding
= old_encoding
;
3980 http
->data_remaining
= old_remaining
;
3982 if (old_remaining
<= INT_MAX
)
3983 http
->_data_remaining
= (int)old_remaining
;
3985 http
->_data_remaining
= INT_MAX
;
3987 else if (http
->state
== HTTP_STATE_OPTIONS
||
3988 http
->state
== HTTP_STATE_HEAD
||
3989 http
->state
== HTTP_STATE_PUT
||
3990 http
->state
== HTTP_STATE_TRACE
||
3991 http
->state
== HTTP_STATE_CONNECT
||
3992 http
->state
== HTTP_STATE_STATUS
)
3994 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3995 "was %s.", http_state_string(http
->state
)));
3996 http
->state
= HTTP_STATE_WAITING
;
4001 * Force data_encoding and data_length to be set according to the response
4005 http_set_length(http
);
4009 * Then start any content encoding...
4012 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
4013 http_content_coding_start(http
,
4014 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
4015 #endif /* HAVE_LIBZ */
4022 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
4024 * 'http_bio_ctrl()' - Control the HTTP connection.
4027 static long /* O - Result/data */
4028 http_bio_ctrl(BIO
*h
, /* I - BIO data */
4029 int cmd
, /* I - Control command */
4030 long arg1
, /* I - First argument */
4031 void *arg2
) /* I - Second argument */
4038 case BIO_CTRL_RESET
:
4042 case BIO_C_SET_FILE_PTR
:
4047 case BIO_C_GET_FILE_PTR
:
4050 *((void **)arg2
) = h
->ptr
;
4057 case BIO_CTRL_FLUSH
:
4064 * 'http_bio_free()' - Free OpenSSL data.
4067 static int /* O - 1 on success, 0 on failure */
4068 http_bio_free(BIO
*h
) /* I - BIO data */
4084 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
4087 static int /* O - 1 on success, 0 on failure */
4088 http_bio_new(BIO
*h
) /* I - BIO data */
4103 * 'http_bio_puts()' - Send a string for OpenSSL.
4106 static int /* O - Bytes written */
4107 http_bio_puts(BIO
*h
, /* I - BIO data */
4108 const char *str
) /* I - String to write */
4111 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
4113 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
4119 * 'http_bio_read()' - Read data for OpenSSL.
4122 static int /* O - Bytes read */
4123 http_bio_read(BIO
*h
, /* I - BIO data */
4124 char *buf
, /* I - Buffer */
4125 int size
) /* I - Number of bytes to read */
4127 http_t
*http
; /* HTTP connection */
4130 http
= (http_t
*)h
->ptr
;
4132 if (!http
->blocking
)
4135 * Make sure we have data before we read...
4138 while (!_httpWait(http
, http
->wait_value
, 0))
4140 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4144 http
->error
= WSAETIMEDOUT
;
4146 http
->error
= ETIMEDOUT
;
4153 return (recv(http
->fd
, buf
, size
, 0));
4158 * 'http_bio_write()' - Write data for OpenSSL.
4161 static int /* O - Bytes written */
4162 http_bio_write(BIO
*h
, /* I - BIO data */
4163 const char *buf
, /* I - Buffer to write */
4164 int num
) /* I - Number of bytes to write */
4166 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4168 #endif /* HAVE_SSL && HAVE_LIBSSL */
4173 * 'http_content_coding_finish()' - Finish doing any content encoding.
4177 http_content_coding_finish(
4178 http_t
*http
) /* I - HTTP connection */
4180 int zerr
; /* Compression status */
4183 switch (http
->coding
)
4185 case _HTTP_CODING_DEFLATE
:
4186 case _HTTP_CODING_GZIP
:
4189 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4190 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4192 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4194 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4195 if (http
->wused
== sizeof(http
->wbuffer
))
4196 httpFlushWrite(http
);
4198 while (zerr
== Z_OK
);
4200 deflateEnd(&(http
->stream
));
4203 httpFlushWrite(http
);
4206 case _HTTP_CODING_INFLATE
:
4207 case _HTTP_CODING_GUNZIP
:
4208 inflateEnd(&(http
->stream
));
4209 free(http
->dbuffer
);
4210 http
->dbuffer
= NULL
;
4217 http
->coding
= _HTTP_CODING_IDENTITY
;
4222 * 'http_content_coding_start()' - Start doing content encoding.
4226 http_content_coding_start(
4227 http_t
*http
, /* I - HTTP connection */
4228 const char *value
) /* I - Value of Content-Encoding */
4230 int zerr
; /* Error/status */
4231 _http_coding_t coding
; /* Content coding value */
4234 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4237 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4239 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4243 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4245 if (http
->state
== HTTP_STATE_GET_SEND
||
4246 http
->state
== HTTP_STATE_POST_SEND
)
4247 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4248 _HTTP_CODING_GUNZIP
;
4249 else if (http
->state
== HTTP_STATE_POST_RECV
||
4250 http
->state
== HTTP_STATE_PUT_RECV
)
4251 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4252 _HTTP_CODING_GUNZIP
;
4255 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4259 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4261 if (http
->state
== HTTP_STATE_GET_SEND
||
4262 http
->state
== HTTP_STATE_POST_SEND
)
4263 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4264 _HTTP_CODING_INFLATE
;
4265 else if (http
->state
== HTTP_STATE_POST_RECV
||
4266 http
->state
== HTTP_STATE_PUT_RECV
)
4267 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4268 _HTTP_CODING_INFLATE
;
4271 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4277 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4281 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4285 case _HTTP_CODING_DEFLATE
:
4286 case _HTTP_CODING_GZIP
:
4288 httpFlushWrite(http
);
4291 * Window size for compression is 11 bits - optimal based on PWG Raster
4292 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
4296 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4298 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
4299 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4301 http
->status
= HTTP_STATUS_ERROR
;
4302 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4307 case _HTTP_CODING_INFLATE
:
4308 case _HTTP_CODING_GUNZIP
:
4309 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
4311 http
->status
= HTTP_STATUS_ERROR
;
4312 http
->error
= errno
;
4317 * Window size for decompression is up to 15 bits (maximum supported).
4318 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
4321 if ((zerr
= inflateInit2(&(http
->stream
),
4322 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
4325 free(http
->dbuffer
);
4326 http
->dbuffer
= NULL
;
4327 http
->status
= HTTP_STATUS_ERROR
;
4328 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4332 http
->stream
.avail_in
= 0;
4333 http
->stream
.next_in
= http
->dbuffer
;
4340 http
->coding
= coding
;
4342 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4345 #endif /* HAVE_LIBZ */
4349 * 'http_create()' - Create an unconnected HTTP connection.
4352 static http_t
* /* O - HTTP connection */
4354 const char *host
, /* I - Hostname */
4355 int port
, /* I - Port number */
4356 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
4357 int family
, /* I - Address family or AF_UNSPEC */
4358 http_encryption_t encryption
, /* I - Encryption to use */
4359 int blocking
, /* I - 1 for blocking mode */
4360 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
4362 http_t
*http
; /* New HTTP connection */
4363 char service
[255]; /* Service name */
4364 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
4367 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
4368 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
4369 family
, encryption
, blocking
, mode
));
4371 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
4377 * Lookup the host...
4382 myaddrlist
= httpAddrCopyList(addrlist
);
4386 snprintf(service
, sizeof(service
), "%d", port
);
4388 myaddrlist
= httpAddrGetList(host
, family
, service
);
4395 * Allocate memory for the structure...
4398 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
4400 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
4401 httpAddrFreeList(addrlist
);
4406 * Initialize the HTTP data...
4410 http
->activity
= time(NULL
);
4411 http
->addrlist
= myaddrlist
;
4412 http
->blocking
= blocking
;
4415 http
->gssctx
= GSS_C_NO_CONTEXT
;
4416 http
->gssname
= GSS_C_NO_NAME
;
4417 #endif /* HAVE_GSSAPI */
4418 http
->status
= HTTP_STATUS_CONTINUE
;
4419 http
->version
= HTTP_VERSION_1_1
;
4422 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
4424 if (port
== 443) /* Always use encryption for https */
4425 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
4427 http
->encryption
= encryption
;
4429 http_set_wait(http
);
4432 * Return the new structure...
4438 /* For OS X 10.8 and earlier */
4439 http_t
*_httpCreate(const char *host
, int port
, http_addrlist_t
*addrlist
,
4440 http_encryption_t encryption
, int family
)
4441 { return (http_create(host
, port
, addrlist
, family
, encryption
, 1,
4442 _HTTP_MODE_CLIENT
)); }
4447 * 'http_debug_hex()' - Do a hex dump of a buffer.
4451 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4452 const char *buffer
, /* I - Buffer to dump */
4453 int bytes
) /* I - Bytes to dump */
4455 int i
, j
, /* Looping vars */
4456 ch
; /* Current character */
4457 char line
[255], /* Line buffer */
4458 *start
, /* Start of line after prefix */
4459 *ptr
; /* Pointer into line */
4462 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4465 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4467 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4468 start
= line
+ strlen(line
);
4470 for (i
= 0; i
< bytes
; i
+= 16)
4472 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4473 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4477 memcpy(ptr
, " ", 3);
4482 memcpy(ptr
, " ", 3);
4485 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4487 ch
= buffer
[i
+ j
] & 255;
4489 if (ch
< ' ' || ch
>= 127)
4503 * 'http_field()' - Return the field index for a field name.
4506 static http_field_t
/* O - Field index */
4507 http_field(const char *name
) /* I - String name */
4509 int i
; /* Looping var */
4512 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4513 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
4514 return ((http_field_t
)i
);
4516 return (HTTP_FIELD_UNKNOWN
);
4521 * 'http_read()' - Read a buffer from a HTTP connection.
4523 * This function does the low-level read from the socket, retrying and timing
4527 static ssize_t
/* O - Number of bytes read or -1 on error */
4528 http_read(http_t
*http
, /* I - Connection to server */
4529 char *buffer
, /* I - Buffer */
4530 size_t length
) /* I - Maximum bytes to read */
4532 ssize_t bytes
; /* Bytes read */
4535 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4536 buffer
, CUPS_LLCAST length
));
4538 if (!http
->blocking
)
4540 while (!httpWait(http
, http
->wait_value
))
4542 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4545 DEBUG_puts("2http_read: Timeout.");
4550 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4556 bytes
= http_read_ssl(http
, buffer
, length
);
4558 #endif /* HAVE_SSL */
4559 bytes
= recv(http
->fd
, buffer
, length
, 0);
4564 if (WSAGetLastError() != WSAEINTR
)
4566 http
->error
= WSAGetLastError();
4569 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4571 if (!http
->timeout_cb
||
4572 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4574 http
->error
= WSAEWOULDBLOCK
;
4579 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4581 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4583 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4585 http
->error
= errno
;
4588 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4590 http
->error
= errno
;
4594 else if (errno
!= EINTR
)
4596 http
->error
= errno
;
4604 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4605 CUPS_LLCAST bytes
));
4608 http_debug_hex("http_read", buffer
, (int)bytes
);
4614 if (WSAGetLastError() == WSAEINTR
)
4617 http
->error
= WSAGetLastError();
4619 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4622 http
->error
= errno
;
4625 else if (bytes
== 0)
4627 http
->error
= EPIPE
;
4636 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4638 * This function reads data from the HTTP buffer or from the socket, as needed.
4641 static ssize_t
/* O - Number of bytes read or -1 on error */
4642 http_read_buffered(http_t
*http
, /* I - Connection to server */
4643 char *buffer
, /* I - Buffer */
4644 size_t length
) /* I - Maximum bytes to read */
4646 ssize_t bytes
; /* Bytes read */
4649 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4651 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4655 if (length
> (size_t)http
->used
)
4656 bytes
= (size_t)http
->used
;
4660 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4663 memcpy(buffer
, http
->buffer
, bytes
);
4664 http
->used
-= (int)bytes
;
4667 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4670 bytes
= http_read(http
, buffer
, length
);
4677 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4679 * This function reads and validates the chunk length, then does a buffered read
4680 * returning the number of bytes placed in the buffer.
4683 static ssize_t
/* O - Number of bytes read or -1 on error */
4684 http_read_chunk(http_t
*http
, /* I - Connection to server */
4685 char *buffer
, /* I - Buffer */
4686 size_t length
) /* I - Maximum bytes to read */
4688 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4689 http
, buffer
, CUPS_LLCAST length
));
4691 if (http
->data_remaining
<= 0)
4693 char len
[32]; /* Length string */
4695 if (!httpGets(len
, sizeof(len
), http
))
4697 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4703 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4704 if (!httpGets(len
, sizeof(len
), http
))
4706 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4711 http
->data_remaining
= strtoll(len
, NULL
, 16);
4713 if (http
->data_remaining
< 0)
4715 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4716 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4720 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4721 len
, CUPS_LLCAST http
->data_remaining
));
4723 if (http
->data_remaining
== 0)
4726 * 0-length chunk, grab trailing blank line...
4729 httpGets(len
, sizeof(len
), http
);
4733 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4734 CUPS_LLCAST http
->data_remaining
));
4736 if (http
->data_remaining
<= 0)
4738 else if (length
> (size_t)http
->data_remaining
)
4739 length
= (size_t)http
->data_remaining
;
4741 return (http_read_buffered(http
, buffer
, length
));
4747 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4750 static int /* O - Bytes read */
4751 http_read_ssl(http_t
*http
, /* I - Connection to server */
4752 char *buf
, /* I - Buffer to store data */
4753 int len
) /* I - Length of buffer */
4755 # if defined(HAVE_LIBSSL)
4756 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4758 # elif defined(HAVE_GNUTLS)
4759 ssize_t result
; /* Return value */
4762 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4764 if (result
< 0 && !errno
)
4767 * Convert GNU TLS error to errno value...
4772 case GNUTLS_E_INTERRUPTED
:
4776 case GNUTLS_E_AGAIN
:
4788 return ((int)result
);
4790 # elif defined(HAVE_CDSASSL)
4791 int result
; /* Return value */
4792 OSStatus error
; /* Error info */
4793 size_t processed
; /* Number of bytes processed */
4796 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4797 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4802 result
= (int)processed
;
4805 case errSSLWouldBlock
:
4807 result
= (int)processed
;
4815 case errSSLClosedGraceful
:
4818 result
= (int)processed
;
4829 # elif defined(HAVE_SSPISSL)
4830 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4831 # endif /* HAVE_LIBSSL */
4833 #endif /* HAVE_SSL */
4837 * 'http_send()' - Send a request with all fields and the trailing blank line.
4840 static int /* O - 0 on success, non-zero on error */
4841 http_send(http_t
*http
, /* I - Connection to server */
4842 http_state_t request
, /* I - Request code */
4843 const char *uri
) /* I - URI */
4845 int i
; /* Looping var */
4846 char buf
[1024]; /* Encoded URI buffer */
4847 const char *value
; /* Field value */
4848 static const char * const codes
[] = /* Request code strings */
4868 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4869 http
, codes
[request
], uri
));
4871 if (http
== NULL
|| uri
== NULL
)
4875 * Set the User-Agent field if it isn't already...
4878 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4880 if (http
->default_user_agent
)
4881 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4883 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4887 * Set the Accept-Encoding field if it isn't already...
4890 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4891 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4892 http
->default_accept_encoding
);
4895 * Encode the URI as needed...
4898 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4901 * See if we had an error the last time around; if so, reconnect...
4904 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4905 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4907 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4908 http
->fd
, http
->status
, http
->tls_upgrade
));
4910 if (httpReconnect2(http
, 30000, NULL
))
4915 * Flush any written data that is pending...
4920 if (httpFlushWrite(http
) < 0)
4921 if (httpReconnect2(http
, 30000, NULL
))
4926 * Send the request header...
4929 http
->state
= request
;
4930 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4932 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4935 http
->status
= HTTP_STATUS_CONTINUE
;
4938 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4940 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4941 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4943 #endif /* HAVE_SSL */
4945 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4947 http
->status
= HTTP_STATUS_ERROR
;
4951 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4952 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4954 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
4956 if (i
== HTTP_FIELD_HOST
)
4958 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4959 httpAddrPort(http
->hostaddr
)) < 1)
4961 http
->status
= HTTP_STATUS_ERROR
;
4965 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4967 http
->status
= HTTP_STATUS_ERROR
;
4973 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4975 http
->status
= HTTP_STATUS_ERROR
;
4979 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
4980 http
->mode
, http
->state
));
4982 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4983 (http
->state
== HTTP_STATE_POST_RECV
||
4984 http
->state
== HTTP_STATE_PUT_RECV
))
4985 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4987 http
->status
= HTTP_STATUS_ERROR
;
4991 if (httpPrintf(http
, "\r\n") < 1)
4993 http
->status
= HTTP_STATUS_ERROR
;
4997 if (httpFlushWrite(http
) < 0)
5000 http_set_length(http
);
5001 httpClearFields(http
);
5004 * The Kerberos and AuthRef authentication strings can only be used once...
5007 if (http
->field_authorization
&& http
->authstring
&&
5008 (!strncmp(http
->authstring
, "Negotiate", 9) ||
5009 !strncmp(http
->authstring
, "AuthRef", 7)))
5011 http
->_authstring
[0] = '\0';
5013 if (http
->authstring
!= http
->_authstring
)
5014 free(http
->authstring
);
5016 http
->authstring
= http
->_authstring
;
5024 # if defined(HAVE_CDSASSL)
5026 * 'http_set_credentials()' - Set the SSL/TLS credentials.
5029 static int /* O - Status of connection */
5030 http_set_credentials(http_t
*http
) /* I - Connection to server */
5032 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
5033 OSStatus error
= 0; /* Error code */
5034 http_tls_credentials_t credentials
= NULL
;
5035 /* TLS credentials */
5038 DEBUG_printf(("7http_set_credentials(%p)", http
));
5041 * Prefer connection specific credentials...
5044 if ((credentials
= http
->tls_credentials
) == NULL
)
5045 credentials
= cg
->tls_credentials
;
5049 error
= SSLSetCertificate(http
->tls
, credentials
);
5050 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
5054 DEBUG_puts("4http_set_credentials: No credentials to set.");
5058 # endif /* HAVE_CDSASSL */
5059 #endif /* HAVE_SSL */
5063 * 'http_set_length()' - Set the data_encoding and data_remaining values.
5066 static off_t
/* O - Remainder or -1 on error */
5067 http_set_length(http_t
*http
) /* I - Connection */
5069 off_t remaining
; /* Remainder */
5072 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
5073 http_state_string(http
->state
)));
5075 if ((remaining
= httpGetLength2(http
)) >= 0)
5077 if (http
->mode
== _HTTP_MODE_SERVER
&&
5078 http
->state
!= HTTP_STATE_GET_SEND
&&
5079 http
->state
!= HTTP_STATE_PUT
&&
5080 http
->state
!= HTTP_STATE_POST
&&
5081 http
->state
!= HTTP_STATE_POST_SEND
)
5083 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
5087 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
5090 DEBUG_puts("1http_set_length: Setting data_encoding to "
5091 "HTTP_ENCODING_CHUNKED.");
5092 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
5096 DEBUG_puts("1http_set_length: Setting data_encoding to "
5097 "HTTP_ENCODING_LENGTH.");
5098 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
5101 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
5102 CUPS_LLCAST remaining
));
5103 http
->data_remaining
= remaining
;
5105 if (remaining
<= INT_MAX
)
5106 http
->_data_remaining
= remaining
;
5108 http
->_data_remaining
= INT_MAX
;
5115 * 'http_set_timeout()' - Set the socket timeout values.
5119 http_set_timeout(int fd
, /* I - File descriptor */
5120 double timeout
) /* I - Timeout in seconds */
5123 DWORD tv
= (DWORD
)(timeout
* 1000);
5124 /* Timeout in milliseconds */
5126 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5127 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5130 struct timeval tv
; /* Timeout in secs and usecs */
5132 tv
.tv_sec
= (int)timeout
;
5133 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
5135 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5136 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5142 * 'http_set_wait()' - Set the default wait value for reads.
5146 http_set_wait(http_t
*http
) /* I - Connection to server */
5150 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5152 if (http
->wait_value
<= 0)
5153 http
->wait_value
= 60000;
5156 http
->wait_value
= 10000;
5162 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5165 static int /* O - 0 on success, -1 on failure */
5166 http_setup_ssl(http_t
*http
) /* I - Connection to server */
5168 char hostname
[256], /* Hostname */
5169 *hostptr
; /* Pointer into hostname */
5172 SSL_CTX
*context
; /* Context for encryption */
5173 BIO
*bio
; /* BIO data */
5174 const char *message
= NULL
;/* Error message */
5175 # elif defined(HAVE_GNUTLS)
5176 int status
; /* Status of handshake */
5177 gnutls_certificate_client_credentials
*credentials
;
5178 /* TLS credentials */
5179 # elif defined(HAVE_CDSASSL)
5180 _cups_globals_t
*cg
= _cupsGlobals();
5181 /* Pointer to library globals */
5182 OSStatus error
; /* Error code */
5183 const char *message
= NULL
;/* Error message */
5184 cups_array_t
*credentials
; /* Credentials array */
5185 cups_array_t
*names
; /* CUPS distinguished names */
5186 CFArrayRef dn_array
; /* CF distinguished names array */
5187 CFIndex count
; /* Number of credentials */
5188 CFDataRef data
; /* Certificate data */
5189 int i
; /* Looping var */
5190 http_credential_t
*credential
; /* Credential data */
5191 # elif defined(HAVE_SSPISSL)
5192 TCHAR username
[256]; /* Username returned from GetUserName() */
5193 TCHAR commonName
[256];/* Common name for certificate */
5194 DWORD dwSize
; /* 32 bit size */
5195 # endif /* HAVE_LIBSSL */
5198 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5201 * Get the hostname to use for SSL...
5204 if (httpAddrLocalhost(http
->hostaddr
))
5206 strlcpy(hostname
, "localhost", sizeof(hostname
));
5211 * Otherwise make sure the hostname we have does not end in a trailing dot.
5214 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5215 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5221 context
= SSL_CTX_new(SSLv23_client_method());
5223 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5225 bio
= BIO_new(_httpBIOMethods());
5226 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5228 http
->tls
= SSL_new(context
);
5229 SSL_set_bio(http
->tls
, bio
, bio
);
5231 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5232 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5233 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5235 if (SSL_connect(http
->tls
) != 1)
5237 unsigned long error
; /* Error code */
5239 while ((error
= ERR_get_error()) != 0)
5241 message
= ERR_error_string(error
, NULL
);
5242 DEBUG_printf(("8http_setup_ssl: %s", message
));
5245 SSL_CTX_free(context
);
5246 SSL_free(http
->tls
);
5250 http
->error
= WSAGetLastError();
5252 http
->error
= errno
;
5254 http
->status
= HTTP_STATUS_ERROR
;
5257 message
= _("Unable to establish a secure connection to host.");
5259 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5264 # elif defined(HAVE_GNUTLS)
5265 credentials
= (gnutls_certificate_client_credentials
*)
5266 malloc(sizeof(gnutls_certificate_client_credentials
));
5267 if (credentials
== NULL
)
5269 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5271 http
->error
= errno
;
5272 http
->status
= HTTP_STATUS_ERROR
;
5273 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5278 gnutls_certificate_allocate_credentials(credentials
);
5280 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5281 gnutls_set_default_priority(http
->tls
);
5282 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5284 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5285 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5286 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5287 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5289 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5291 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5292 status
, gnutls_strerror(status
)));
5294 if (gnutls_error_is_fatal(status
))
5297 http
->status
= HTTP_STATUS_ERROR
;
5299 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
5301 gnutls_deinit(http
->tls
);
5302 gnutls_certificate_free_credentials(*credentials
);
5310 http
->tls_credentials
= credentials
;
5312 # elif defined(HAVE_CDSASSL)
5313 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, kSSLClientSide
,
5314 kSSLStreamType
)) == NULL
)
5316 DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
5317 http
->error
= errno
= ENOMEM
;
5318 http
->status
= HTTP_STATUS_ERROR
;
5319 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5324 error
= SSLSetConnection(http
->tls
, http
);
5325 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5329 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5330 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5335 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
5337 DEBUG_printf(("4http_setup_ssl: SSLSetSessionOption, error=%d",
5343 if (cg
->client_cert_cb
)
5345 error
= SSLSetSessionOption(http
->tls
,
5346 kSSLSessionOptionBreakOnCertRequested
, true);
5347 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5348 "error=%d", (int)error
));
5352 error
= http_set_credentials(http
);
5353 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5359 * Let the server know which hostname/domain we are trying to connect to
5360 * in case it wants to serve up a certificate with a matching common name.
5365 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5367 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5373 int done
= 0; /* Are we done yet? */
5375 while (!error
&& !done
)
5377 error
= SSLHandshake(http
->tls
);
5379 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5387 case errSSLWouldBlock
:
5388 error
= noErr
; /* Force a retry */
5389 usleep(1000); /* in 1 millisecond */
5392 case errSSLServerAuthCompleted
:
5394 if (cg
->server_cert_cb
)
5396 error
= httpCopyCredentials(http
, &credentials
);
5399 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5400 cg
->server_cert_data
);
5401 httpFreeCredentials(credentials
);
5404 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5405 "returned %d.", (int)error
));
5409 case errSSLClientCertRequested
:
5412 if (cg
->client_cert_cb
)
5415 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5418 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5420 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5422 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5424 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5426 credential
->datalen
= CFDataGetLength(data
);
5427 if ((credential
->data
= malloc(credential
->datalen
)))
5429 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5430 credential
->datalen
);
5431 cupsArrayAdd(names
, credential
);
5439 CFRelease(dn_array
);
5444 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5445 cg
->client_cert_data
);
5447 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5448 "returned %d.", (int)error
));
5451 httpFreeCredentials(names
);
5455 case errSSLUnknownRootCert
:
5456 message
= _("Unable to establish a secure connection to host "
5457 "(untrusted certificate).");
5460 case errSSLNoRootCert
:
5461 message
= _("Unable to establish a secure connection to host "
5462 "(self-signed certificate).");
5465 case errSSLCertExpired
:
5466 message
= _("Unable to establish a secure connection to host "
5467 "(expired certificate).");
5470 case errSSLCertNotYetValid
:
5471 message
= _("Unable to establish a secure connection to host "
5472 "(certificate not yet valid).");
5475 case errSSLHostNameMismatch
:
5476 message
= _("Unable to establish a secure connection to host "
5477 "(host name mismatch).");
5480 case errSSLXCertChainInvalid
:
5481 message
= _("Unable to establish a secure connection to host "
5482 "(certificate chain invalid).");
5485 case errSSLConnectionRefused
:
5486 message
= _("Unable to establish a secure connection to host "
5487 "(peer dropped connection before responding).");
5498 http
->error
= error
;
5499 http
->status
= HTTP_STATUS_ERROR
;
5500 errno
= ECONNREFUSED
;
5502 CFRelease(http
->tls
);
5506 * If an error string wasn't set by the callbacks use a generic one...
5510 #ifdef HAVE_CSSMERRORSTRING
5511 message
= cssmErrorString(error
);
5513 message
= _("Unable to establish a secure connection to host.");
5514 #endif /* HAVE_CSSMERRORSTRING */
5516 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5521 # elif defined(HAVE_SSPISSL)
5522 http
->tls
= _sspiAlloc();
5526 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5530 http
->tls
->sock
= http
->fd
;
5531 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5532 GetUserName(username
, &dwSize
);
5533 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5534 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5536 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5539 _sspiFree(http
->tls_credentials
);
5540 http
->tls_credentials
= NULL
;
5543 http
->status
= HTTP_STATUS_ERROR
;
5545 _cupsSetError(IPP_PKI_ERROR
,
5546 _("Unable to establish a secure connection to host."), 1);
5551 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
5552 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5554 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5556 _sspiFree(http
->tls_credentials
);
5557 http
->tls_credentials
= NULL
;
5560 http
->status
= HTTP_STATUS_ERROR
;
5562 _cupsSetError(IPP_PKI_ERROR
,
5563 _("Unable to establish a secure connection to host."), 1);
5567 # endif /* HAVE_CDSASSL */
5574 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5578 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
5581 SSL_CTX
*context
; /* Context for encryption */
5583 context
= SSL_get_SSL_CTX(http
->tls
);
5585 SSL_shutdown(http
->tls
);
5586 SSL_CTX_free(context
);
5587 SSL_free(http
->tls
);
5589 # elif defined(HAVE_GNUTLS)
5590 gnutls_certificate_client_credentials
*credentials
;
5591 /* TLS credentials */
5593 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5595 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5596 gnutls_deinit(http
->tls
);
5597 gnutls_certificate_free_credentials(*credentials
);
5600 # elif defined(HAVE_CDSASSL)
5601 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5604 CFRelease(http
->tls
);
5606 if (http
->tls_credentials
)
5607 CFRelease(http
->tls_credentials
);
5609 # elif defined(HAVE_SSPISSL)
5610 _sspiFree(http
->tls_credentials
);
5611 # endif /* HAVE_LIBSSL */
5614 http
->tls_credentials
= NULL
;
5616 #endif /* HAVE_SSL */
5621 * 'http_state_string()' - Return the string associated with a given HTTP state.
5624 static const char * /* O - State string */
5625 http_state_string(http_state_t state
) /* I - HTTP state */
5627 static char buffer
[255]; /* Unknown value buffer */
5628 static const char * const states
[] = /* State strings */
5631 "HTTP_STATE_WAITING",
5632 "HTTP_STATE_OPTIONS",
5634 "HTTP_STATE_GET_SEND",
5637 "HTTP_STATE_POST_RECV",
5638 "HTTP_STATE_POST_SEND",
5640 "HTTP_STATE_PUT_RECV",
5641 "HTTP_STATE_DELETE",
5643 "HTTP_STATE_CONNECT",
5644 "HTTP_STATE_STATUS",
5645 "HTTP_STATE_UNKNOWN_METHOD",
5646 "HTTP_STATE_UNKNOWN_VERSION"
5649 if (state
>= HTTP_STATE_ERROR
&& state
<= HTTP_STATE_UNKNOWN_VERSION
)
5650 return (states
[state
- HTTP_STATE_ERROR
]);
5652 snprintf(buffer
, sizeof(buffer
), "??? %d ???", (int)state
);
5660 * 'http_upgrade()' - Force upgrade to TLS encryption.
5663 static int /* O - Status of connection */
5664 http_upgrade(http_t
*http
) /* I - Connection to server */
5666 int ret
; /* Return value */
5667 http_t myhttp
; /* Local copy of HTTP data */
5670 DEBUG_printf(("7http_upgrade(%p)", http
));
5673 * Flush the connection to make sure any previous "Upgrade" message
5680 * Copy the HTTP data to a local variable so we can do the OPTIONS
5681 * request without interfering with the existing request data...
5684 memcpy(&myhttp
, http
, sizeof(myhttp
));
5687 * Send an OPTIONS request to the server, requiring SSL or TLS
5688 * encryption on the link...
5691 http
->tls_upgrade
= 1;
5692 http
->field_authorization
= NULL
; /* Don't free the auth string */
5694 httpClearFields(http
);
5695 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5696 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5698 if ((ret
= httpOptions(http
, "*")) == 0)
5701 * Wait for the secure connection...
5704 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
5708 * Restore the HTTP request data...
5711 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5712 http
->data_encoding
= myhttp
.data_encoding
;
5713 http
->data_remaining
= myhttp
.data_remaining
;
5714 http
->_data_remaining
= myhttp
._data_remaining
;
5715 http
->expect
= myhttp
.expect
;
5716 http
->field_authorization
= myhttp
.field_authorization
;
5717 http
->digest_tries
= myhttp
.digest_tries
;
5718 http
->tls_upgrade
= 0;
5721 * See if we actually went secure...
5727 * Server does not support HTTP upgrade...
5730 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5733 closesocket(http
->fd
);
5745 #endif /* HAVE_SSL */
5749 * 'http_write()' - Write a buffer to a HTTP connection.
5752 static ssize_t
/* O - Number of bytes written */
5753 http_write(http_t
*http
, /* I - Connection to server */
5754 const char *buffer
, /* I - Buffer for data */
5755 size_t length
) /* I - Number of bytes to write */
5757 ssize_t tbytes
, /* Total bytes sent */
5758 bytes
; /* Bytes sent */
5761 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
5762 buffer
, CUPS_LLCAST length
));
5768 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5770 if (http
->timeout_cb
)
5773 struct pollfd pfd
; /* Polled file descriptor */
5775 fd_set output_set
; /* Output ready for write? */
5776 struct timeval timeout
; /* Timeout value */
5777 #endif /* HAVE_POLL */
5778 int nfds
; /* Result from select()/poll() */
5784 pfd
.events
= POLLOUT
;
5786 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5787 (errno
== EINTR
|| errno
== EAGAIN
))
5793 FD_ZERO(&output_set
);
5794 FD_SET(http
->fd
, &output_set
);
5796 timeout
.tv_sec
= http
->wait_value
/ 1000;
5797 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5799 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5802 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5803 WSAGetLastError() == WSAEWOULDBLOCK
));
5805 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5807 #endif /* HAVE_POLL */
5811 http
->error
= errno
;
5814 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5817 http
->error
= WSAEWOULDBLOCK
;
5819 http
->error
= EWOULDBLOCK
;
5829 bytes
= http_write_ssl(http
, buffer
, length
);
5831 #endif /* HAVE_SSL */
5832 bytes
= send(http
->fd
, buffer
, length
, 0);
5834 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
5835 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
5840 if (WSAGetLastError() == WSAEINTR
)
5842 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5844 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5847 http
->error
= WSAGetLastError();
5849 else if (WSAGetLastError() != http
->error
&&
5850 WSAGetLastError() != WSAECONNRESET
)
5852 http
->error
= WSAGetLastError();
5859 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5861 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5863 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5866 http
->error
= errno
;
5868 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5870 http
->error
= errno
;
5875 DEBUG_printf(("3http_write: error writing data (%s).",
5876 strerror(http
->error
)));
5887 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5890 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
5897 * 'http_write_chunk()' - Write a chunked buffer.
5900 static ssize_t
/* O - Number bytes written */
5901 http_write_chunk(http_t
*http
, /* I - Connection to server */
5902 const char *buffer
, /* I - Buffer to write */
5903 size_t length
) /* I - Length of buffer */
5905 char header
[16]; /* Chunk header */
5906 ssize_t bytes
; /* Bytes written */
5909 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
5910 http
, buffer
, CUPS_LLCAST length
));
5913 * Write the chunk header, data, and trailer.
5916 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
5917 if (http_write(http
, header
, strlen(header
)) < 0)
5919 DEBUG_puts("8http_write_chunk: http_write of length failed.");
5923 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5925 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
5929 if (http_write(http
, "\r\n", 2) < 0)
5931 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
5941 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5944 static int /* O - Bytes written */
5945 http_write_ssl(http_t
*http
, /* I - Connection to server */
5946 const char *buf
, /* I - Buffer holding data */
5947 int len
) /* I - Length of buffer */
5949 ssize_t result
; /* Return value */
5952 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5954 # if defined(HAVE_LIBSSL)
5955 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5957 # elif defined(HAVE_GNUTLS)
5958 result
= gnutls_record_send(http
->tls
, buf
, len
);
5960 if (result
< 0 && !errno
)
5963 * Convert GNU TLS error to errno value...
5968 case GNUTLS_E_INTERRUPTED
:
5972 case GNUTLS_E_AGAIN
:
5984 # elif defined(HAVE_CDSASSL)
5985 OSStatus error
; /* Error info */
5986 size_t processed
; /* Number of bytes processed */
5989 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5994 result
= (int)processed
;
5997 case errSSLWouldBlock
:
5999 result
= (int)processed
;
6007 case errSSLClosedGraceful
:
6010 result
= (int)processed
;
6018 # elif defined(HAVE_SSPISSL)
6019 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
6020 # endif /* HAVE_LIBSSL */
6022 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
6024 return ((int)result
);
6026 #endif /* HAVE_SSL */
6030 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".