2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for CUPS.
6 * Copyright 2007-2012 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * httpAcceptConnection() - Accept a new HTTP client connection from
23 * the specified listening socket.
24 * httpAddCredential() - Allocates and adds a single credential to
26 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP
28 * httpBlocking() - Set blocking/non-blocking behavior on a
30 * httpCheck() - Check to see if there is a pending response
32 * httpClearCookie() - Clear the cookie value(s).
33 * httpClearFields() - Clear HTTP request fields.
34 * httpClose() - Close an HTTP connection.
35 * httpConnect() - Connect to a HTTP server.
36 * httpConnect2() - Connect to a HTTP server.
37 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
38 * httpCopyCredentials() - Copy the credentials associated with an
39 * encrypted connection.
40 * _httpCreate() - Create an unconnected HTTP connection.
41 * _httpCreateCredentials() - Create credentials in the internal format.
42 * httpDelete() - Send a DELETE request to the server.
43 * _httpDisconnect() - Disconnect a HTTP connection.
44 * httpEncryption() - Set the required encryption on the link.
45 * httpError() - Get the last error on a connection.
46 * httpFlush() - Flush data from a HTTP connection.
47 * httpFlushWrite() - Flush data in write buffer.
48 * _httpFreeCredentials() - Free internal credentials.
49 * httpFreeCredentials() - Free an array of credentials.
50 * httpGet() - Send a GET request to the server.
51 * httpGetContentEncoding() - Get a common content encoding, if any,
52 * between the client and server.
53 * httpGetAuthString() - Get the current authorization string.
54 * httpGetBlocking() - Get the blocking/non-block state of a
56 * httpGetCookie() - Get any cookie data from the response.
57 * httpGetExpect() - Get the value of the Expect header, if any.
58 * httpGetFd() - Get the file descriptor associated with a
60 * httpGetField() - Get a field value from a request/response.
61 * httpGetLength() - Get the amount of data remaining from the
62 * content-length or transfer-encoding fields.
63 * httpGetLength2() - Get the amount of data remaining from the
64 * content-length or transfer-encoding fields.
65 * httpGets() - Get a line of text from a HTTP connection.
66 * httpGetState() - Get the current state of the HTTP request.
67 * httpGetStatus() - Get the status of the last HTTP request.
68 * httpGetSubField() - Get a sub-field value.
69 * httpGetSubField2() - Get a sub-field value.
70 * httpGetVersion() - Get the HTTP version at the other end.
71 * httpHead() - Send a HEAD request to the server.
72 * httpInitialize() - Initialize the HTTP interface library and
73 * set the default HTTP proxy (if any).
74 * httpOptions() - Send an OPTIONS request to the server.
75 * httpPeek() - Peek at data from a HTTP connection.
76 * httpPost() - Send a POST request to the server.
77 * httpPrintf() - Print a formatted string to a HTTP
79 * httpPut() - Send a PUT request to the server.
80 * httpRead() - Read data from a HTTP connection.
81 * httpRead2() - Read data from a HTTP connection.
82 * _httpReadCDSA() - Read function for the CDSA library.
83 * _httpReadGNUTLS() - Read function for the GNU TLS library.
84 * httpReadRequest() - Read a HTTP request from a connection.
85 * httpReconnect() - Reconnect to a HTTP server.
86 * httpReconnect2() - Reconnect to a HTTP server with timeout and
88 * httpSetAuthString() - Set the current authorization string.
89 * httpSetCredentials() - Set the credentials associated with an
90 * encrypted connection.
91 * httpSetCookie() - Set the cookie value(s).
92 * httpSetDefaultField() - Set the default value of an HTTP header.
93 * httpSetExpect() - Set the Expect: header in a request.
94 * httpSetField() - Set the value of an HTTP header.
95 * httpSetLength() - Set the content-length and
97 * httpSetTimeout() - Set read/write timeouts and an optional
99 * httpTrace() - Send an TRACE request to the server.
100 * _httpUpdate() - Update the current HTTP status for incoming
102 * httpUpdate() - Update the current HTTP state for incoming
104 * _httpWait() - Wait for data available on a connection (no
106 * httpWait() - Wait for data available on a connection.
107 * httpWrite() - Write data to a HTTP connection.
108 * httpWrite2() - Write data to a HTTP connection.
109 * _httpWriteCDSA() - Write function for the CDSA library.
110 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
111 * httpWriteResponse() - Write a HTTP response to a client
113 * http_bio_ctrl() - Control the HTTP connection.
114 * http_bio_free() - Free OpenSSL data.
115 * http_bio_new() - Initialize an OpenSSL BIO structure.
116 * http_bio_puts() - Send a string for OpenSSL.
117 * http_bio_read() - Read data for OpenSSL.
118 * http_bio_write() - Write data for OpenSSL.
119 * http_content_coding_finish() - Finish doing any content encoding.
120 * http_content_coding_start() - Start doing content encoding.
121 * http_debug_hex() - Do a hex dump of a buffer.
122 * http_field() - Return the field index for a field name.
123 * http_read() - Read a buffer from a HTTP connection.
124 * http_read_buffered() - Do a buffered read from a HTTP connection.
125 * http_read_chunk() - Read a chunk from a HTTP connection.
126 * http_read_ssl() - Read from a SSL/TLS connection.
127 * http_send() - Send a request with all fields and the
128 * trailing blank line.
129 * http_set_credentials() - Set the SSL/TLS credentials.
130 * http_set_length() - Set the data_encoding and data_remaining
132 * http_set_timeout() - Set the socket timeout values.
133 * http_set_wait() - Set the default wait value for reads.
134 * http_setup_ssl() - Set up SSL/TLS support on a connection.
135 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
136 * http_upgrade() - Force upgrade to TLS encryption.
137 * http_write() - Write a buffer to a HTTP connection.
138 * http_write_chunk() - Write a chunked buffer.
139 * http_write_ssl() - Write to a SSL/TLS connection.
143 * Include necessary headers...
146 #include "cups-private.h"
153 # include <sys/time.h>
154 # include <sys/resource.h>
158 #endif /* HAVE_POLL */
166 static void http_content_coding_finish(http_t
*http
);
167 static void http_content_coding_start(http_t
*http
,
169 #endif /* HAVE_LIBZ */
171 static void http_debug_hex(const char *prefix
, const char *buffer
,
174 static http_field_t
http_field(const char *name
);
175 static ssize_t
http_read(http_t
*http
, char *buffer
, size_t length
);
176 static ssize_t
http_read_buffered(http_t
*http
, char *buffer
, size_t length
);
177 static ssize_t
http_read_chunk(http_t
*http
, char *buffer
, size_t length
);
178 static int http_send(http_t
*http
, http_state_t request
,
180 static ssize_t
http_write(http_t
*http
, const char *buffer
,
182 static ssize_t
http_write_chunk(http_t
*http
, const char *buffer
,
185 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
187 static int http_set_credentials(http_t
*http
);
188 # endif /* HAVE_CDSASSL */
189 #endif /* HAVE_SSL */
190 static off_t
http_set_length(http_t
*http
);
191 static void http_set_timeout(int fd
, double timeout
);
192 static void http_set_wait(http_t
*http
);
194 static int http_setup_ssl(http_t
*http
);
195 static void http_shutdown_ssl(http_t
*http
);
196 static int http_upgrade(http_t
*http
);
197 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
198 #endif /* HAVE_SSL */
205 static const char * const http_fields
[] =
222 "If-Unmodified-since",
239 static const char * const http_states
[] =
242 "HTTP_STATE_WAITING",
243 "HTTP_STATE_OPTIONS",
245 "HTTP_STATE_GET_SEND",
248 "HTTP_STATE_POST_RECV",
249 "HTTP_STATE_POST_SEND",
251 "HTTP_STATE_PUT_RECV",
254 "HTTP_STATE_CONNECT",
256 "HTTP_STATE_UNKNOWN_METHOD",
257 "HTTP_STATE_UNKNOWN_VERSION"
262 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
264 * BIO methods for OpenSSL...
267 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
268 static int http_bio_read(BIO
*h
, char *buf
, int size
);
269 static int http_bio_puts(BIO
*h
, const char *str
);
270 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
271 static int http_bio_new(BIO
*h
);
272 static int http_bio_free(BIO
*data
);
274 static BIO_METHOD http_bio_methods
=
281 NULL
, /* http_bio_gets, */
287 #endif /* HAVE_SSL && HAVE_LIBSSL */
291 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
292 * specified listening socket.
297 http_t
* /* O - HTTP connection or @code NULL@ */
298 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
299 int blocking
) /* I - 1 if the connection should be
300 blocking, 0 otherwise */
302 http_t
*http
; /* HTTP connection */
303 http_addrlist_t addrlist
; /* Dummy address list */
304 socklen_t addrlen
; /* Length of address */
305 int val
; /* Socket option value */
309 * Range check input...
316 * Create the client connection...
319 memset(&addrlist
, 0, sizeof(addrlist
));
321 if ((http
= _httpCreate(NULL
, 0, &addrlist
, AF_UNSPEC
,
322 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
323 _HTTP_MODE_SERVER
)) == NULL
)
327 * Accept the client and get the remote address...
330 addrlen
= sizeof(http_addr_t
);
332 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
335 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
341 httpAddrString(&(http
->addrlist
->addr
), http
->hostname
,
342 sizeof(http
->hostname
));
346 * Disable SIGPIPE for this socket.
350 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, &val
, sizeof(val
));
351 #endif /* SO_NOSIGPIPE */
354 * Using TCP_NODELAY improves responsiveness, especially on systems
355 * with a slow loopback interface. Since we write large buffers
356 * when sending print files and requests, there shouldn't be any
357 * performance penalty for this...
361 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
365 * Close this socket when starting another process...
368 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
369 #endif /* FD_CLOEXEC */
376 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
378 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
380 * @since CUPS 1.5/OS X 10.7@
383 int /* O - 0 on success, -1 on error */
385 cups_array_t
*credentials
, /* I - Credentials array */
386 const void *data
, /* I - PEM-encoded X.509 data */
387 size_t datalen
) /* I - Length of data */
389 http_credential_t
*credential
; /* Credential data */
392 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
394 credential
->datalen
= datalen
;
396 if ((credential
->data
= malloc(datalen
)) != NULL
)
398 memcpy(credential
->data
, data
, datalen
);
399 cupsArrayAdd(credentials
, credential
);
410 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
412 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
415 BIO_METHOD
* /* O - BIO methods for OpenSSL */
416 _httpBIOMethods(void)
418 return (&http_bio_methods
);
420 #endif /* HAVE_SSL && HAVE_LIBSSL */
424 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
428 httpBlocking(http_t
*http
, /* I - Connection to server */
429 int b
) /* I - 1 = blocking, 0 = non-blocking */
440 * 'httpCheck()' - Check to see if there is a pending response from the server.
443 int /* O - 0 = no data, 1 = data available */
444 httpCheck(http_t
*http
) /* I - Connection to server */
446 return (httpWait(http
, 0));
451 * 'httpClearCookie()' - Clear the cookie value(s).
453 * @since CUPS 1.1.19/OS X 10.3@
457 httpClearCookie(http_t
*http
) /* I - Connection to server */
471 * 'httpClearFields()' - Clear HTTP request fields.
475 httpClearFields(http_t
*http
) /* I - Connection to server */
477 DEBUG_printf(("httpClearFields(http=%p)", http
));
481 memset(http
->fields
, 0, sizeof(http
->fields
));
483 if (http
->mode
== _HTTP_MODE_CLIENT
)
485 if (http
->hostname
[0] == '/')
486 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
488 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
491 if (http
->field_authorization
)
493 free(http
->field_authorization
);
494 http
->field_authorization
= NULL
;
497 if (http
->accept_encoding
)
499 _cupsStrFree(http
->accept_encoding
);
500 http
->accept_encoding
= NULL
;
505 _cupsStrFree(http
->allow
);
511 _cupsStrFree(http
->server
);
515 http
->expect
= (http_status_t
)0;
521 * 'httpClose()' - Close an HTTP connection.
525 httpClose(http_t
*http
) /* I - Connection to server */
528 OM_uint32 minor_status
; /* Minor status code */
529 #endif /* HAVE_GSSAPI */
532 DEBUG_printf(("httpClose(http=%p)", http
));
535 * Range check input...
542 * Close any open connection...
545 _httpDisconnect(http
);
548 * Free memory used...
551 httpAddrFreeList(http
->addrlist
);
557 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
558 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
560 if (http
->gssname
!= GSS_C_NO_NAME
)
561 gss_release_name(&minor_status
, &http
->gssname
);
562 #endif /* HAVE_GSSAPI */
564 #ifdef HAVE_AUTHORIZATION_H
566 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
567 #endif /* HAVE_AUTHORIZATION_H */
569 httpClearFields(http
);
571 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
572 free(http
->authstring
);
579 * 'httpConnect()' - Connect to a HTTP server.
581 * This function is deprecated - use @link httpConnect2@ instead.
586 http_t
* /* O - New HTTP connection */
587 httpConnect(const char *host
, /* I - Host to connect to */
588 int port
) /* I - Port number */
590 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, HTTP_ENCRYPT_IF_REQUESTED
,
596 * 'httpConnect2()' - Connect to a HTTP server.
601 http_t
* /* O - New HTTP connection */
603 const char *host
, /* I - Host to connect to */
604 int port
, /* I - Port number */
605 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
606 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
607 http_encryption_t encryption
, /* I - Type of encryption to use */
608 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
609 int msec
, /* I - Connection timeout in milliseconds */
610 int *cancel
) /* I - Pointer to "cancel" variable */
612 http_t
*http
; /* New HTTP connection */
615 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
616 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
617 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
620 * Create the HTTP structure...
623 if ((http
= _httpCreate(host
, port
, addrlist
, family
, encryption
, blocking
,
624 _HTTP_MODE_CLIENT
)) == NULL
)
628 * Connect to the remote system...
631 if (!httpReconnect2(http
, msec
, cancel
))
635 * Could not connect to any known address - bail out!
645 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
647 * This function is now deprecated. Please use the @link httpConnect2@ function
653 http_t
* /* O - New HTTP connection */
655 const char *host
, /* I - Host to connect to */
656 int port
, /* I - Port number */
657 http_encryption_t encryption
) /* I - Type of encryption to use */
659 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
660 host
, port
, encryption
));
662 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
668 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
671 * @since CUPS 1.5/OS X 10.7@
674 int /* O - Status of call (0 = success) */
676 http_t
*http
, /* I - Connection to server */
677 cups_array_t
**credentials
) /* O - Array of credentials */
680 # elif defined(HAVE_GNUTLS)
681 # elif defined(HAVE_CDSASSL)
682 OSStatus error
; /* Error code */
683 SecTrustRef peerTrust
; /* Peer trust reference */
684 CFIndex count
; /* Number of credentials */
685 SecCertificateRef secCert
; /* Certificate reference */
686 CFDataRef data
; /* Certificate data */
687 int i
; /* Looping var */
688 # elif defined(HAVE_SSPISSL)
689 # endif /* HAVE_LIBSSL */
695 if (!http
|| !http
->tls
|| !credentials
)
701 # elif defined(HAVE_GNUTLS)
704 # elif defined(HAVE_CDSASSL)
705 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
707 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
709 count
= SecTrustGetCertificateCount(peerTrust
);
711 for (i
= 0; i
< count
; i
++)
713 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
714 if ((data
= SecCertificateCopyData(secCert
)))
716 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
717 CFDataGetLength(data
));
723 CFRelease(peerTrust
);
728 # elif defined(HAVE_SSPISSL)
733 # endif /* HAVE_LIBSSL */
738 * '_httpCreate()' - Create an unconnected HTTP connection.
741 http_t
* /* O - HTTP connection */
743 const char *host
, /* I - Hostname */
744 int port
, /* I - Port number */
745 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
746 int family
, /* I - Address family or AF_UNSPEC */
747 http_encryption_t encryption
, /* I - Encryption to use */
748 int blocking
, /* I - 1 for blocking mode */
749 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
751 http_t
*http
; /* New HTTP connection */
752 char service
[255]; /* Service name */
753 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
756 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, addrlist=%p, family=%d, "
757 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
758 family
, encryption
, blocking
, mode
));
760 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
771 myaddrlist
= httpAddrCopyList(addrlist
);
775 snprintf(service
, sizeof(service
), "%d", port
);
777 myaddrlist
= httpAddrGetList(host
, family
, service
);
784 * Allocate memory for the structure...
787 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
789 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(errno
), 0);
790 httpAddrFreeList(addrlist
);
795 * Initialize the HTTP data...
799 http
->activity
= time(NULL
);
800 http
->addrlist
= myaddrlist
;
801 http
->blocking
= blocking
;
804 http
->gssctx
= GSS_C_NO_CONTEXT
;
805 http
->gssname
= GSS_C_NO_NAME
;
806 #endif /* HAVE_GSSAPI */
807 http
->version
= HTTP_VERSION_1_1
;
810 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
812 if (port
== 443) /* Always use encryption for https */
813 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
815 http
->encryption
= encryption
;
820 * Return the new structure...
828 * '_httpCreateCredentials()' - Create credentials in the internal format.
831 http_tls_credentials_t
/* O - Internal credentials */
832 _httpCreateCredentials(
833 cups_array_t
*credentials
) /* I - Array of credentials */
841 # elif defined(HAVE_GNUTLS)
844 # elif defined(HAVE_CDSASSL)
845 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
846 SecCertificateRef secCert
; /* Certificate reference */
847 CFDataRef data
; /* Credential data reference */
848 http_credential_t
*credential
; /* Credential data */
851 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
852 cupsArrayCount(credentials
),
853 &kCFTypeArrayCallBacks
)) == NULL
)
856 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
858 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
860 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
861 credential
->datalen
)))
863 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
866 CFArrayAppendValue(peerCerts
, secCert
);
876 # elif defined(HAVE_SSPISSL)
881 # endif /* HAVE_LIBSSL */
886 * 'httpDelete()' - Send a DELETE request to the server.
889 int /* O - Status of call (0 = success) */
890 httpDelete(http_t
*http
, /* I - Connection to server */
891 const char *uri
) /* I - URI to delete */
893 return (http_send(http
, HTTP_DELETE
, uri
));
898 * '_httpDisconnect()' - Disconnect a HTTP connection.
902 _httpDisconnect(http_t
*http
) /* I - Connection to server */
906 http_shutdown_ssl(http
);
907 #endif /* HAVE_SSL */
910 closesocket(http
->fd
);
920 * 'httpEncryption()' - Set the required encryption on the link.
923 int /* O - -1 on error, 0 on success */
924 httpEncryption(http_t
*http
, /* I - Connection to server */
925 http_encryption_t e
) /* I - New encryption preference */
927 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
933 http
->encryption
= e
;
935 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
936 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
937 return (httpReconnect(http
));
938 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
939 return (http_upgrade(http
));
943 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
947 #endif /* HAVE_SSL */
952 * 'httpError()' - Get the last error on a connection.
955 int /* O - Error code (errno) value */
956 httpError(http_t
*http
) /* I - Connection to server */
959 return (http
->error
);
966 * 'httpFlush()' - Flush data from a HTTP connection.
970 httpFlush(http_t
*http
) /* I - Connection to server */
972 char buffer
[8192]; /* Junk buffer */
973 int blocking
; /* To block or not to block */
974 http_state_t oldstate
; /* Old state */
977 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
978 http_states
[http
->state
+ 1]));
981 * Nothing to do if we are in the "waiting" state...
984 if (http
->state
== HTTP_STATE_WAITING
)
988 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
991 blocking
= http
->blocking
;
995 * Read any data we can...
998 oldstate
= http
->state
;
999 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
1002 * Restore blocking and reset the connection if we didn't get all of
1003 * the remaining data...
1006 http
->blocking
= blocking
;
1008 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
1012 * Didn't get the data back, so close the current connection.
1017 http_content_coding_finish(http
);
1018 #endif /* HAVE_LIBZ */
1020 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
1022 http
->state
= HTTP_STATE_WAITING
;
1026 http_shutdown_ssl(http
);
1027 #endif /* HAVE_SSL */
1030 closesocket(http
->fd
);
1041 * 'httpFlushWrite()' - Flush data in write buffer.
1043 * @since CUPS 1.2/OS X 10.5@
1046 int /* O - Bytes written or -1 on error */
1047 httpFlushWrite(http_t
*http
) /* I - Connection to server */
1049 int bytes
; /* Bytes written */
1052 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
1053 http
? http
->data_encoding
: -1));
1055 if (!http
|| !http
->wused
)
1057 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
1058 "1httpFlushWrite: No connection.");
1062 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1063 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
1065 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
1069 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
1076 * '_httpFreeCredentials()' - Free internal credentials.
1080 _httpFreeCredentials(
1081 http_tls_credentials_t credentials
) /* I - Internal credentials */
1089 #elif defined(HAVE_GNUTLS)
1092 #elif defined(HAVE_CDSASSL)
1093 CFRelease(credentials
);
1095 #elif defined(HAVE_SSPISSL)
1098 #endif /* HAVE_LIBSSL */
1103 * 'httpFreeCredentials()' - Free an array of credentials.
1107 httpFreeCredentials(
1108 cups_array_t
*credentials
) /* I - Array of credentials */
1110 http_credential_t
*credential
; /* Credential */
1113 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
1115 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
1117 cupsArrayRemove(credentials
, credential
);
1118 free((void *)credential
->data
);
1122 cupsArrayDelete(credentials
);
1127 * 'httpGet()' - Send a GET request to the server.
1130 int /* O - Status of call (0 = success) */
1131 httpGet(http_t
*http
, /* I - Connection to server */
1132 const char *uri
) /* I - URI to get */
1134 return (http_send(http
, HTTP_GET
, uri
));
1139 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
1140 * the client and server.
1142 * This function uses the value of the Accepts-Encoding HTTP header and must be
1143 * called after receiving a response from the server or a request from the
1144 * client. The value returned can be use in subsequent requests (for clients)
1145 * or in the response (for servers) in order to compress the content stream.
1150 const char * /* O - Content-Coding value or
1151 @code NULL@ for the identity
1153 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
1156 if (http
&& http
->accept_encoding
)
1158 int i
; /* Looping var */
1159 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
1160 *start
, /* Start of coding value */
1161 *end
; /* End of coding value */
1162 double qvalue
; /* "qvalue" for coding */
1163 struct lconv
*loc
= localeconv(); /* Locale data */
1164 static const char * const codings
[] =
1165 { /* Supported content codings */
1172 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
1174 for (start
= temp
; *start
; start
= end
)
1177 * Find the end of the coding name...
1182 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
1188 * Grab the qvalue as needed...
1191 if (!strncmp(end
, ";q=", 3))
1192 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1195 * Skip past all attributes...
1199 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1205 while (*end
&& isspace(*end
& 255))
1209 * Check value if it matches something we support...
1215 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1216 if (!strcmp(start
, codings
[i
]))
1217 return (codings
[i
]);
1220 #endif /* HAVE_LIBZ */
1227 * 'httpGetAuthString()' - Get the current authorization string.
1229 * The authorization string is set by cupsDoAuthentication() and
1230 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
1231 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
1234 * @since CUPS 1.3/OS X 10.5@
1237 char * /* O - Authorization string */
1238 httpGetAuthString(http_t
*http
) /* I - Connection to server */
1241 return (http
->authstring
);
1248 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
1250 * @since CUPS 1.2/OS X 10.5@
1253 int /* O - 1 if blocking, 0 if non-blocking */
1254 httpGetBlocking(http_t
*http
) /* I - Connection to server */
1256 return (http
? http
->blocking
: 0);
1261 * 'httpGetCookie()' - Get any cookie data from the response.
1263 * @since CUPS 1.1.19/OS X 10.3@
1266 const char * /* O - Cookie data or NULL */
1267 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1269 return (http
? http
->cookie
: NULL
);
1274 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1276 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1277 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1282 http_status_t
/* O - Expect: status, if any */
1283 httpGetExpect(http_t
*http
) /* I - Connection to client */
1286 return (HTTP_STATUS_ERROR
);
1288 return (http
->expect
);
1293 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1295 * @since CUPS 1.2/OS X 10.5@
1298 int /* O - File descriptor or -1 if none */
1299 httpGetFd(http_t
*http
) /* I - Connection to server */
1301 return (http
? http
->fd
: -1);
1306 * 'httpGetField()' - Get a field value from a request/response.
1309 const char * /* O - Field value */
1310 httpGetField(http_t
*http
, /* I - Connection to server */
1311 http_field_t field
) /* I - Field to get */
1313 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1318 case HTTP_FIELD_ACCEPT_ENCODING
:
1319 return (http
->accept_encoding
);
1321 case HTTP_FIELD_ALLOW
:
1322 return (http
->allow
);
1324 case HTTP_FIELD_SERVER
:
1325 return (http
->server
);
1327 case HTTP_FIELD_AUTHORIZATION
:
1328 if (http
->field_authorization
)
1331 * Special case for WWW-Authenticate: as its contents can be
1332 * longer than HTTP_MAX_VALUE...
1335 return (http
->field_authorization
);
1339 return (http
->fields
[field
]);
1345 * 'httpGetLength()' - Get the amount of data remaining from the
1346 * content-length or transfer-encoding fields.
1348 * This function is deprecated and will not return lengths larger than
1349 * 2^31 - 1; use httpGetLength2() instead.
1354 int /* O - Content length */
1355 httpGetLength(http_t
*http
) /* I - Connection to server */
1358 * Get the read content length and return the 32-bit value.
1363 httpGetLength2(http
);
1365 return (http
->_data_remaining
);
1373 * 'httpGetLength2()' - Get the amount of data remaining from the
1374 * content-length or transfer-encoding fields.
1376 * This function returns the complete content length, even for
1377 * content larger than 2^31 - 1.
1379 * @since CUPS 1.2/OS X 10.5@
1382 off_t
/* O - Content length */
1383 httpGetLength2(http_t
*http
) /* I - Connection to server */
1385 off_t remaining
; /* Remaining length */
1388 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1389 http_states
[http
->state
+ 1]));
1394 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1396 DEBUG_puts("4httpGetLength2: chunked request!");
1402 * The following is a hack for HTTP servers that don't send a
1403 * Content-Length or Transfer-Encoding field...
1405 * If there is no Content-Length then the connection must close
1406 * after the transfer is complete...
1409 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1412 * Default content length is 0 for errors and certain types of operations,
1413 * and 2^31-1 for other successful requests...
1416 if (http
->status
>= HTTP_MULTIPLE_CHOICES
||
1417 http
->state
== HTTP_STATE_OPTIONS
||
1418 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1419 http
->state
== HTTP_STATE_HEAD
||
1420 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1421 http
->state
== HTTP_STATE_DELETE
||
1422 http
->state
== HTTP_STATE_TRACE
||
1423 http
->state
== HTTP_STATE_CONNECT
)
1426 remaining
= 2147483647;
1428 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1432 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1433 CUPS_LLCAST remaining
));
1441 * 'httpGets()' - Get a line of text from a HTTP connection.
1444 char * /* O - Line or NULL */
1445 httpGets(char *line
, /* I - Line to read into */
1446 int length
, /* I - Max length of buffer */
1447 http_t
*http
) /* I - Connection to server */
1449 char *lineptr
, /* Pointer into line */
1450 *lineend
, /* End of line */
1451 *bufptr
, /* Pointer into input buffer */
1452 *bufend
; /* Pointer to end of buffer */
1453 int bytes
, /* Number of bytes read */
1454 eol
; /* End-of-line? */
1457 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1459 if (!http
|| !line
|| length
<= 1)
1463 * Read a line from the buffer...
1468 lineend
= line
+ length
- 1;
1471 while (lineptr
< lineend
)
1474 * Pre-load the buffer as needed...
1483 while (http
->used
== 0)
1486 * No newline; see if there is more data to be read...
1489 while (!_httpWait(http
, http
->wait_value
, 1))
1491 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1494 DEBUG_puts("3httpGets: Timed out!");
1496 http
->error
= WSAETIMEDOUT
;
1498 http
->error
= ETIMEDOUT
;
1503 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1504 HTTP_MAX_BUFFER
- http
->used
);
1506 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1511 * Nope, can't get a line this time...
1515 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1517 if (WSAGetLastError() == WSAEINTR
)
1519 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1521 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1524 http
->error
= WSAGetLastError();
1526 else if (WSAGetLastError() != http
->error
)
1528 http
->error
= WSAGetLastError();
1533 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1537 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1539 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1541 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1544 http
->error
= errno
;
1546 else if (errno
!= http
->error
)
1548 http
->error
= errno
;
1555 else if (bytes
== 0)
1557 http
->error
= EPIPE
;
1563 * Yup, update the amount used...
1566 http
->used
+= bytes
;
1570 * Now copy as much of the current line as possible...
1573 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1574 lineptr
< lineend
&& bufptr
< bufend
;)
1576 if (*bufptr
== 0x0a)
1582 else if (*bufptr
== 0x0d)
1585 *lineptr
++ = *bufptr
++;
1588 http
->used
-= (int)(bufptr
- http
->buffer
);
1590 memmove(http
->buffer
, bufptr
, http
->used
);
1598 http
->activity
= time(NULL
);
1602 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1608 DEBUG_puts("3httpGets: No new line available!");
1615 * 'httpGetState()' - Get the current state of the HTTP request.
1618 http_state_t
/* O - HTTP state */
1619 httpGetState(http_t
*http
) /* I - Connection to server */
1621 return (http
? http
->state
: HTTP_STATE_ERROR
);
1626 * 'httpGetStatus()' - Get the status of the last HTTP request.
1628 * @since CUPS 1.2/OS X 10.5@
1631 http_status_t
/* O - HTTP status */
1632 httpGetStatus(http_t
*http
) /* I - Connection to server */
1634 return (http
? http
->status
: HTTP_ERROR
);
1639 * 'httpGetSubField()' - Get a sub-field value.
1644 char * /* O - Value or NULL */
1645 httpGetSubField(http_t
*http
, /* I - Connection to server */
1646 http_field_t field
, /* I - Field index */
1647 const char *name
, /* I - Name of sub-field */
1648 char *value
) /* O - Value string */
1650 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1655 * 'httpGetSubField2()' - Get a sub-field value.
1657 * @since CUPS 1.2/OS X 10.5@
1660 char * /* O - Value or NULL */
1661 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1662 http_field_t field
, /* I - Field index */
1663 const char *name
, /* I - Name of sub-field */
1664 char *value
, /* O - Value string */
1665 int valuelen
) /* I - Size of value buffer */
1667 const char *fptr
; /* Pointer into field */
1668 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1669 *ptr
, /* Pointer into string buffer */
1670 *end
; /* End of value buffer */
1672 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1673 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1675 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1676 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1679 end
= value
+ valuelen
- 1;
1681 for (fptr
= http
->fields
[field
]; *fptr
;)
1684 * Skip leading whitespace...
1687 while (_cups_isspace(*fptr
))
1697 * Get the sub-field name...
1701 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1702 ptr
< (temp
+ sizeof(temp
) - 1);
1707 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1710 * Skip trailing chars up to the '='...
1713 while (_cups_isspace(*fptr
))
1723 * Skip = and leading whitespace...
1728 while (_cups_isspace(*fptr
))
1734 * Read quoted string...
1737 for (ptr
= value
, fptr
++;
1738 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1743 while (*fptr
&& *fptr
!= '\"')
1752 * Read unquoted string...
1756 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1761 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1765 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1768 * See if this is the one...
1771 if (!strcmp(name
, temp
))
1773 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1780 DEBUG_puts("3httpGetSubField2: Returning NULL");
1787 * 'httpGetVersion()' - Get the HTTP version at the other end.
1790 http_version_t
/* O - Version number */
1791 httpGetVersion(http_t
*http
) /* I - Connection to server */
1793 return (http
? http
->version
: HTTP_VERSION_1_0
);
1798 * 'httpHead()' - Send a HEAD request to the server.
1801 int /* O - Status of call (0 = success) */
1802 httpHead(http_t
*http
, /* I - Connection to server */
1803 const char *uri
) /* I - URI for head */
1805 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1806 return (http_send(http
, HTTP_HEAD
, uri
));
1811 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1812 * default HTTP proxy (if any).
1816 httpInitialize(void)
1818 static int initialized
= 0; /* Have we been called before? */
1820 WSADATA winsockdata
; /* WinSock data */
1823 int i
; /* Looping var */
1824 unsigned char data
[1024]; /* Seed data */
1825 #endif /* HAVE_LIBSSL */
1831 _cupsGlobalUnlock();
1836 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1838 #elif !defined(SO_NOSIGPIPE)
1840 * Ignore SIGPIPE signals...
1844 sigset(SIGPIPE
, SIG_IGN
);
1846 # elif defined(HAVE_SIGACTION)
1847 struct sigaction action
; /* POSIX sigaction data */
1850 memset(&action
, 0, sizeof(action
));
1851 action
.sa_handler
= SIG_IGN
;
1852 sigaction(SIGPIPE
, &action
, NULL
);
1855 signal(SIGPIPE
, SIG_IGN
);
1856 # endif /* !SO_NOSIGPIPE */
1861 * Initialize GNU TLS...
1864 gnutls_global_init();
1866 #elif defined(HAVE_LIBSSL)
1868 * Initialize OpenSSL...
1871 SSL_load_error_strings();
1875 * Using the current time is a dubious random seed, but on some systems
1876 * it is the best we can do (on others, this seed isn't even used...)
1879 CUPS_SRAND(time(NULL
));
1881 for (i
= 0; i
< sizeof(data
); i
++)
1882 data
[i
] = CUPS_RAND();
1884 RAND_seed(data
, sizeof(data
));
1885 #endif /* HAVE_GNUTLS */
1888 _cupsGlobalUnlock();
1893 * 'httpOptions()' - Send an OPTIONS request to the server.
1896 int /* O - Status of call (0 = success) */
1897 httpOptions(http_t
*http
, /* I - Connection to server */
1898 const char *uri
) /* I - URI for options */
1900 return (http_send(http
, HTTP_OPTIONS
, uri
));
1905 * 'httpPeek()' - Peek at data from a HTTP connection.
1907 * This function copies available data from the given HTTP connection, reading
1908 * a buffer as needed. The data is still available for reading using
1909 * @link httpRead@ or @link httpRead2@.
1911 * For non-blocking connections the usual timeouts apply.
1916 ssize_t
/* O - Number of bytes copied */
1917 httpPeek(http_t
*http
, /* I - Connection to server */
1918 char *buffer
, /* I - Buffer for data */
1919 size_t length
) /* I - Maximum number of bytes */
1921 ssize_t bytes
; /* Bytes read */
1922 char len
[32]; /* Length string */
1925 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1926 http
, buffer
, CUPS_LLCAST length
));
1928 if (http
== NULL
|| buffer
== NULL
)
1931 http
->activity
= time(NULL
);
1937 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1938 http
->data_remaining
<= 0)
1940 DEBUG_puts("2httpPeek: Getting chunk length...");
1942 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1944 DEBUG_puts("1httpPeek: Could not get length!");
1948 http
->data_remaining
= strtoll(len
, NULL
, 16);
1949 if (http
->data_remaining
< 0)
1951 DEBUG_puts("1httpPeek: Negative chunk length!");
1956 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1957 CUPS_LLCAST http
->data_remaining
));
1959 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1962 * A zero-length chunk ends a transfer; unless we are reading POST
1968 http_content_coding_finish(http
);
1969 #endif /* HAVE_LIBZ */
1971 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1972 httpGets(len
, sizeof(len
), http
);
1974 if (http
->state
== HTTP_STATE_POST_RECV
)
1977 http
->state
= HTTP_STATE_WAITING
;
1979 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1980 http_states
[http
->state
+ 1]));
1983 * Prevent future reads for this request...
1986 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1990 else if (length
> (size_t)http
->data_remaining
)
1991 length
= (size_t)http
->data_remaining
;
1994 if (http
->used
== 0 &&
1995 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1997 if (http
->used
== 0)
1998 #endif /* HAVE_LIBZ */
2001 * Buffer small reads for better performance...
2004 ssize_t buflen
; /* Length of read for buffer */
2006 if (!http
->blocking
)
2008 while (!httpWait(http
, http
->wait_value
))
2010 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2017 if (http
->data_remaining
> sizeof(http
->buffer
))
2018 buflen
= sizeof(http
->buffer
);
2020 buflen
= http
->data_remaining
;
2022 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
2028 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
2030 #endif /* HAVE_SSL */
2031 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
2036 if (WSAGetLastError() != WSAEINTR
)
2038 http
->error
= WSAGetLastError();
2041 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
2043 if (!http
->timeout_cb
||
2044 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2046 http
->error
= WSAEWOULDBLOCK
;
2051 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2053 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2055 http
->error
= errno
;
2058 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2060 http
->error
= errno
;
2064 else if (errno
!= EINTR
)
2066 http
->error
= errno
;
2074 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
2075 CUPS_LLCAST bytes
));
2077 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
2086 int zerr
; /* Decompressor error */
2087 z_stream stream
; /* Copy of decompressor stream */
2089 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
2091 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2092 /* Number of bytes to copy */
2094 if (http
->stream
.avail_in
> 0 &&
2095 http
->stream
.next_in
> http
->dbuffer
)
2096 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2098 http
->stream
.next_in
= http
->dbuffer
;
2100 if (buflen
> http
->data_remaining
)
2101 buflen
= http
->data_remaining
;
2103 if (buflen
> http
->used
)
2104 buflen
= http
->used
;
2106 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
2107 "decompression buffer.", (int)buflen
));
2109 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
2110 http
->stream
.avail_in
+= buflen
;
2111 http
->used
-= buflen
;
2112 http
->data_remaining
-= buflen
;
2115 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
2118 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
2119 (int)http
->stream
.avail_in
));
2121 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
2123 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
2124 http
->error
= ENOMEM
;
2128 stream
.next_out
= (Bytef
*)buffer
;
2129 stream
.avail_out
= length
;
2131 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
2132 inflateEnd(&stream
);
2136 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
2138 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
2139 http
->stream
.avail_in
);
2146 bytes
= length
- http
->stream
.avail_out
;
2149 #endif /* HAVE_LIBZ */
2152 if (length
> (size_t)http
->used
)
2153 length
= (size_t)http
->used
;
2155 bytes
= (ssize_t
)length
;
2157 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
2160 memcpy(buffer
, http
->buffer
, length
);
2168 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2171 http
->error
= WSAGetLastError();
2173 if (errno
== EINTR
|| errno
== EAGAIN
)
2176 http
->error
= errno
;
2179 else if (bytes
== 0)
2181 http
->error
= EPIPE
;
2186 http_debug_hex("httpPeek", buffer
, (int)bytes
);
2192 /* For OS X 10.8 and earlier */
2193 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
2194 { return (httpPeek(http
, buffer
, length
)); }
2198 * 'httpPost()' - Send a POST request to the server.
2201 int /* O - Status of call (0 = success) */
2202 httpPost(http_t
*http
, /* I - Connection to server */
2203 const char *uri
) /* I - URI for post */
2205 return (http_send(http
, HTTP_POST
, uri
));
2210 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
2215 int /* O - Number of bytes written */
2216 httpPrintf(http_t
*http
, /* I - Connection to server */
2217 const char *format
, /* I - printf-style format string */
2218 ...) /* I - Additional args as needed */
2220 int bytes
; /* Number of bytes to write */
2221 char buf
[16384]; /* Buffer for formatted string */
2222 va_list ap
; /* Variable argument pointer */
2225 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
2227 va_start(ap
, format
);
2228 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
2231 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
2233 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
2234 return (httpWrite2(http
, buf
, bytes
));
2239 DEBUG_puts("4httpPrintf: flushing existing data...");
2241 if (httpFlushWrite(http
) < 0)
2245 return (http_write(http
, buf
, bytes
));
2251 * 'httpPut()' - Send a PUT request to the server.
2254 int /* O - Status of call (0 = success) */
2255 httpPut(http_t
*http
, /* I - Connection to server */
2256 const char *uri
) /* I - URI to put */
2258 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2259 return (http_send(http
, HTTP_PUT
, uri
));
2264 * 'httpRead()' - Read data from a HTTP connection.
2266 * This function is deprecated. Use the httpRead2() function which can
2267 * read more than 2GB of data.
2272 int /* O - Number of bytes read */
2273 httpRead(http_t
*http
, /* I - Connection to server */
2274 char *buffer
, /* I - Buffer for data */
2275 int length
) /* I - Maximum number of bytes */
2277 return ((int)httpRead2(http
, buffer
, length
));
2282 * 'httpRead2()' - Read data from a HTTP connection.
2284 * @since CUPS 1.2/OS X 10.5@
2287 ssize_t
/* O - Number of bytes read */
2288 httpRead2(http_t
*http
, /* I - Connection to server */
2289 char *buffer
, /* I - Buffer for data */
2290 size_t length
) /* I - Maximum number of bytes */
2292 ssize_t bytes
; /* Bytes read */
2295 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2296 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
2297 http
, buffer
, CUPS_LLCAST length
, http
->coding
,
2298 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2300 if (http
== NULL
|| buffer
== NULL
)
2303 http
->activity
= time(NULL
);
2314 if (http
->stream
.avail_in
> 0)
2316 int zerr
; /* Decompressor error */
2318 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2319 (int)http
->stream
.avail_in
, (int)length
));
2321 http
->stream
.next_out
= (Bytef
*)buffer
;
2322 http
->stream
.avail_out
= length
;
2324 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2326 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2328 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2329 http
->stream
.avail_in
);
2336 bytes
= length
- http
->stream
.avail_out
;
2338 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2339 http
->stream
.avail_in
, http
->stream
.avail_out
,
2347 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2348 /* Additional bytes for buffer */
2352 if (http
->stream
.avail_in
> 0 &&
2353 http
->stream
.next_in
> http
->dbuffer
)
2354 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2356 http
->stream
.next_in
= http
->dbuffer
;
2358 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2359 "decompression buffer.", (int)buflen
));
2361 if (http
->data_remaining
> 0)
2363 if (buflen
> http
->data_remaining
)
2364 buflen
= http
->data_remaining
;
2366 bytes
= http_read_buffered(http
,
2367 (char *)http
->dbuffer
+
2368 http
->stream
.avail_in
, buflen
);
2370 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2371 bytes
= http_read_chunk(http
,
2372 (char *)http
->dbuffer
+
2373 http
->stream
.avail_in
, buflen
);
2379 else if (bytes
== 0)
2382 http
->data_remaining
-= bytes
;
2383 http
->stream
.avail_in
+= bytes
;
2392 #endif /* HAVE_LIBZ */
2393 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2395 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2396 http
->data_remaining
-= bytes
;
2398 else if (http
->data_remaining
<= 0)
2401 * No more data to read...
2408 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2411 if (length
> http
->data_remaining
)
2412 length
= http
->data_remaining
;
2414 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2415 http
->data_remaining
-= bytes
;
2420 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2421 #endif /* HAVE_LIBZ */
2422 ((http
->data_remaining
<= 0 &&
2423 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2424 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2428 http_content_coding_finish(http
);
2429 #endif /* HAVE_LIBZ */
2431 if (http
->state
== HTTP_STATE_POST_RECV
)
2434 http
->state
= HTTP_STATE_WAITING
;
2436 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2437 http_states
[http
->state
+ 1]));
2444 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2446 * '_httpReadCDSA()' - Read function for the CDSA library.
2449 OSStatus
/* O - -1 on error, 0 on success */
2451 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2452 void *data
, /* I - Data buffer */
2453 size_t *dataLength
) /* IO - Number of bytes */
2455 OSStatus result
; /* Return value */
2456 ssize_t bytes
; /* Number of bytes read */
2457 http_t
*http
; /* HTTP connection */
2460 http
= (http_t
*)connection
;
2462 if (!http
->blocking
)
2465 * Make sure we have data before we read...
2468 while (!_httpWait(http
, http
->wait_value
, 0))
2470 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2473 http
->error
= ETIMEDOUT
;
2480 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2482 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2484 if (bytes
== *dataLength
)
2490 *dataLength
= bytes
;
2491 result
= errSSLWouldBlock
;
2498 result
= errSSLClosedGraceful
;
2499 else if (errno
== EAGAIN
)
2500 result
= errSSLWouldBlock
;
2502 result
= errSSLClosedAbort
;
2507 #endif /* HAVE_SSL && HAVE_CDSASSL */
2510 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2512 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2515 ssize_t
/* O - Number of bytes read or -1 on error */
2517 gnutls_transport_ptr ptr
, /* I - Connection to server */
2518 void *data
, /* I - Buffer */
2519 size_t length
) /* I - Number of bytes to read */
2521 http_t
*http
; /* HTTP connection */
2522 ssize_t bytes
; /* Bytes read */
2525 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2527 http
= (http_t
*)ptr
;
2529 if (!http
->blocking
)
2532 * Make sure we have data before we read...
2535 while (!_httpWait(http
, http
->wait_value
, 0))
2537 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2540 http
->error
= ETIMEDOUT
;
2545 bytes
= recv(http
->fd
, data
, length
, 0);
2546 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2549 #endif /* HAVE_SSL && HAVE_GNUTLS */
2553 * 'httpReadRequest()' - Read a HTTP request from a connection.
2558 http_state_t
/* O - New state of connection */
2559 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2560 char *uri
, /* I - URI buffer */
2561 size_t urilen
) /* I - Size of URI buffer */
2563 char line
[4096], /* HTTP request line */
2564 *req_method
, /* HTTP request method */
2565 *req_uri
, /* HTTP request URI */
2566 *req_version
; /* HTTP request version number string */
2570 * Range check input...
2573 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2574 http
, uri
, CUPS_LLCAST urilen
));
2579 if (!http
|| !uri
|| urilen
< 1)
2581 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2582 return (HTTP_STATE_ERROR
);
2584 else if (http
->state
!= HTTP_STATE_WAITING
)
2586 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2587 http_states
[http
->state
+ 1]));
2588 return (HTTP_STATE_ERROR
);
2595 httpClearFields(http
);
2597 http
->activity
= time(NULL
);
2598 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2599 http
->data_remaining
= 0;
2600 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2601 http
->status
= HTTP_STATUS_OK
;
2602 http
->version
= HTTP_VERSION_1_1
;
2605 * Read a line from the socket...
2608 if (!httpGets(line
, sizeof(line
), http
))
2610 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2611 return (HTTP_STATE_ERROR
);
2616 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2617 return (HTTP_STATE_WAITING
);
2620 DEBUG_printf(("1httpReadRequest: %s", line
));
2629 while (*req_uri
&& !isspace(*req_uri
& 255))
2634 DEBUG_puts("1httpReadRequest: No request URI.");
2635 return (HTTP_STATE_ERROR
);
2640 while (*req_uri
&& isspace(*req_uri
& 255))
2643 req_version
= req_uri
;
2645 while (*req_version
&& !isspace(*req_version
& 255))
2650 DEBUG_puts("1httpReadRequest: No request protocol version.");
2651 return (HTTP_STATE_ERROR
);
2654 *req_version
++ = '\0';
2656 while (*req_version
&& isspace(*req_version
& 255))
2663 if (!strcmp(req_method
, "OPTIONS"))
2664 http
->state
= HTTP_STATE_OPTIONS
;
2665 else if (!strcmp(req_method
, "GET"))
2666 http
->state
= HTTP_STATE_GET
;
2667 else if (!strcmp(req_method
, "HEAD"))
2668 http
->state
= HTTP_STATE_HEAD
;
2669 else if (!strcmp(req_method
, "POST"))
2670 http
->state
= HTTP_STATE_POST
;
2671 else if (!strcmp(req_method
, "PUT"))
2672 http
->state
= HTTP_STATE_PUT
;
2673 else if (!strcmp(req_method
, "DELETE"))
2674 http
->state
= HTTP_STATE_DELETE
;
2675 else if (!strcmp(req_method
, "TRACE"))
2676 http
->state
= HTTP_STATE_TRACE
;
2677 else if (!strcmp(req_method
, "CONNECT"))
2678 http
->state
= HTTP_STATE_CONNECT
;
2681 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2682 return (HTTP_STATE_UNKNOWN_METHOD
);
2685 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2686 http_states
[http
->state
+ 1]));
2688 if (!strcmp(req_version
, "HTTP/1.0"))
2690 http
->version
= HTTP_VERSION_1_0
;
2691 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2693 else if (!strcmp(req_version
, "HTTP/1.1"))
2695 http
->version
= HTTP_VERSION_1_1
;
2696 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2700 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2701 return (HTTP_STATE_UNKNOWN_VERSION
);
2704 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2705 strlcpy(uri
, req_uri
, urilen
);
2707 return (http
->state
);
2712 * 'httpReconnect()' - Reconnect to a HTTP server.
2714 * This function is deprecated. Please use the @link httpReconnect2@ function
2720 int /* O - 0 on success, non-zero on failure */
2721 httpReconnect(http_t
*http
) /* I - Connection to server */
2723 DEBUG_printf(("httpReconnect(http=%p)", http
));
2725 return (httpReconnect2(http
, 30000, NULL
));
2730 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2734 int /* O - 0 on success, non-zero on failure */
2735 httpReconnect2(http_t
*http
, /* I - Connection to server */
2736 int msec
, /* I - Timeout in milliseconds */
2737 int *cancel
) /* I - Pointer to "cancel" variable */
2739 http_addrlist_t
*addr
; /* Connected address */
2741 http_addrlist_t
*current
; /* Current address */
2742 char temp
[256]; /* Temporary address string */
2746 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2751 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
2758 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2759 http_shutdown_ssl(http
);
2761 #endif /* HAVE_SSL */
2764 * Close any previously open socket...
2769 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2772 closesocket(http
->fd
);
2781 * Reset all state (except fields, which may be reused)...
2784 http
->state
= HTTP_STATE_WAITING
;
2785 http
->status
= HTTP_STATUS_CONTINUE
;
2786 http
->version
= HTTP_VERSION_1_1
;
2787 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2788 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2789 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2790 http
->_data_remaining
= 0;
2793 http
->data_remaining
= 0;
2794 http
->hostaddr
= NULL
;
2798 * Connect to the server...
2802 for (current
= http
->addrlist
; current
; current
= current
->next
)
2803 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2804 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2805 httpAddrPort(&(current
->addr
))));
2808 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2812 * Unable to connect...
2816 http
->error
= WSAGetLastError();
2818 http
->error
= errno
;
2820 http
->status
= HTTP_ERROR
;
2822 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2823 strerror(http
->error
)));
2828 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2830 if (http
->timeout_value
> 0)
2831 http_set_timeout(http
->fd
, http
->timeout_value
);
2833 http
->hostaddr
= &(addr
->addr
);
2837 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2840 * Always do encryption via SSL.
2843 if (http_setup_ssl(http
) != 0)
2846 closesocket(http
->fd
);
2854 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2855 return (http_upgrade(http
));
2856 #endif /* HAVE_SSL */
2858 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2859 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2860 httpAddrPort(http
->hostaddr
)));
2867 * 'httpSetAuthString()' - Set the current authorization string.
2869 * This function just stores a copy of the current authorization string in
2870 * the HTTP connection object. You must still call httpSetField() to set
2871 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2872 * httpHead(), httpOptions(), httpPost, or httpPut().
2874 * @since CUPS 1.3/OS X 10.5@
2878 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2879 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2880 const char *data
) /* I - Auth data (NULL for none) */
2883 * Range check input...
2889 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2890 free(http
->authstring
);
2892 http
->authstring
= http
->_authstring
;
2897 * Set the current authorization string...
2900 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2903 if (len
> (int)sizeof(http
->_authstring
))
2905 if ((temp
= malloc(len
)) == NULL
)
2906 len
= sizeof(http
->_authstring
);
2908 http
->authstring
= temp
;
2912 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2914 strlcpy(http
->authstring
, scheme
, len
);
2919 * Clear the current authorization string...
2922 http
->_authstring
[0] = '\0';
2928 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2931 * @since CUPS 1.5/OS X 10.7@
2934 int /* O - Status of call (0 = success) */
2935 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2936 cups_array_t
*credentials
) /* I - Array of credentials */
2938 if (!http
|| cupsArrayCount(credentials
) < 1)
2941 _httpFreeCredentials(http
->tls_credentials
);
2943 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2945 return (http
->tls_credentials
? 0 : -1);
2950 * 'httpSetCookie()' - Set the cookie value(s).
2952 * @since CUPS 1.1.19/OS X 10.3@
2956 httpSetCookie(http_t
*http
, /* I - Connection */
2957 const char *cookie
) /* I - Cookie string */
2966 http
->cookie
= strdup(cookie
);
2968 http
->cookie
= NULL
;
2973 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2975 * Currently only HTTP_FIELD_ACCEPT_ENCODING, HTTP_FIELD_SERVER, and
2976 * HTTP_FIELD_USER_AGENT can be set.
2982 httpSetDefaultField(http_t
*http
, /* I - Connection to server */
2983 http_field_t field
, /* I - Field index */
2984 const char *value
)/* I - Value */
2986 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2987 http
, field
, http_fields
[field
], value
));
2994 case HTTP_FIELD_ACCEPT_ENCODING
:
2995 if (http
->default_accept_encoding
)
2996 _cupsStrFree(http
->default_accept_encoding
);
2998 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
3001 case HTTP_FIELD_SERVER
:
3002 if (http
->default_server
)
3003 _cupsStrFree(http
->default_server
);
3005 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
3008 case HTTP_FIELD_USER_AGENT
:
3009 if (http
->default_user_agent
)
3010 _cupsStrFree(http
->default_user_agent
);
3012 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
3016 DEBUG_puts("1httpSetDefaultField: Ignored.");
3023 * 'httpSetExpect()' - Set the Expect: header in a request.
3025 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
3028 * @since CUPS 1.2/OS X 10.5@
3032 httpSetExpect(http_t
*http
, /* I - Connection to server */
3033 http_status_t expect
) /* I - HTTP status to expect
3034 (@code HTTP_CONTINUE@) */
3037 http
->expect
= expect
;
3042 * 'httpSetField()' - Set the value of an HTTP header.
3046 httpSetField(http_t
*http
, /* I - Connection to server */
3047 http_field_t field
, /* I - Field index */
3048 const char *value
) /* I - Value */
3050 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
3051 field
, http_fields
[field
], value
));
3054 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
3055 field
>= HTTP_FIELD_MAX
||
3061 case HTTP_FIELD_ACCEPT_ENCODING
:
3062 if (http
->accept_encoding
)
3063 _cupsStrFree(http
->accept_encoding
);
3065 http
->accept_encoding
= _cupsStrAlloc(value
);
3068 case HTTP_FIELD_ALLOW
:
3070 _cupsStrFree(http
->allow
);
3072 http
->allow
= _cupsStrAlloc(value
);
3075 case HTTP_FIELD_SERVER
:
3077 _cupsStrFree(http
->server
);
3079 http
->server
= _cupsStrAlloc(value
);
3083 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
3087 if (field
== HTTP_FIELD_AUTHORIZATION
)
3090 * Special case for Authorization: as its contents can be
3091 * longer than HTTP_MAX_VALUE
3094 if (http
->field_authorization
)
3095 free(http
->field_authorization
);
3097 http
->field_authorization
= strdup(value
);
3099 else if (field
== HTTP_FIELD_HOST
)
3102 * Special-case for Host: as we don't want a trailing "." on the hostname and
3103 * need to bracket IPv6 numeric addresses.
3106 char *ptr
= strchr(value
, ':');
3108 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
3111 * Bracket IPv6 numeric addresses...
3113 * This is slightly inefficient (basically copying twice), but is an edge
3114 * case and not worth optimizing...
3117 snprintf(http
->fields
[HTTP_FIELD_HOST
],
3118 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
3123 * Check for a trailing dot on the hostname...
3126 ptr
= http
->fields
[HTTP_FIELD_HOST
];
3130 ptr
+= strlen(ptr
) - 1;
3138 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
3139 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
3141 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
3142 http_content_coding_start(http
, value
);
3144 #endif /* HAVE_LIBZ */
3149 * 'httpSetLength()' - Set the content-length and content-encoding.
3151 * @since CUPS 1.2/OS X 10.5@
3155 httpSetLength(http_t
*http
, /* I - Connection to server */
3156 size_t length
) /* I - Length (0 for chunked) */
3158 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
3159 CUPS_LLCAST length
));
3166 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
3168 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
3172 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
3173 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
3174 CUPS_LLFMT
, CUPS_LLCAST length
);
3180 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
3182 * The optional timeout callback receives both the HTTP connection and a user
3183 * data pointer and must return 1 to continue or 0 to error (time) out.
3185 * @since CUPS 1.5/OS X 10.7@
3190 http_t
*http
, /* I - Connection to server */
3191 double timeout
, /* I - Number of seconds for timeout,
3192 must be greater than 0 */
3193 http_timeout_cb_t cb
, /* I - Callback function or NULL */
3194 void *user_data
) /* I - User data pointer */
3196 if (!http
|| timeout
<= 0.0)
3199 http
->timeout_cb
= cb
;
3200 http
->timeout_data
= user_data
;
3201 http
->timeout_value
= timeout
;
3204 http_set_timeout(http
->fd
, timeout
);
3206 http_set_wait(http
);
3211 * 'httpTrace()' - Send an TRACE request to the server.
3214 int /* O - Status of call (0 = success) */
3215 httpTrace(http_t
*http
, /* I - Connection to server */
3216 const char *uri
) /* I - URI for trace */
3218 return (http_send(http
, HTTP_TRACE
, uri
));
3223 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3225 * Note: Unlike httpUpdate(), this function does not flush pending write data
3226 * and only retrieves a single status line from the HTTP connection.
3229 int /* O - 1 to continue, 0 to stop */
3230 _httpUpdate(http_t
*http
, /* I - Connection to server */
3231 http_status_t
*status
) /* O - Current HTTP status */
3233 char line
[32768], /* Line from connection... */
3234 *value
; /* Pointer to value on line */
3235 http_field_t field
; /* Field index */
3236 int major
, minor
; /* HTTP version numbers */
3239 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3240 http_states
[http
->state
+ 1]));
3243 * Grab a single line from the connection...
3246 if (!httpGets(line
, sizeof(line
), http
))
3248 *status
= HTTP_ERROR
;
3252 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3254 if (line
[0] == '\0')
3257 * Blank line means the start of the data section (if any). Return
3258 * the result code, too...
3260 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3261 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3265 if (http
->status
== HTTP_STATUS_CONTINUE
)
3267 *status
= http
->status
;
3271 if (http
->status
< HTTP_BAD_REQUEST
)
3272 http
->digest_tries
= 0;
3275 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
3277 if (http_setup_ssl(http
) != 0)
3280 closesocket(http
->fd
);
3285 *status
= http
->status
= HTTP_ERROR
;
3289 *status
= HTTP_STATUS_CONTINUE
;
3292 #endif /* HAVE_SSL */
3294 if (http_set_length(http
) < 0)
3296 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3297 http
->error
= EINVAL
;
3298 http
->status
= *status
= HTTP_ERROR
;
3302 switch (http
->state
)
3304 case HTTP_STATE_GET
:
3305 case HTTP_STATE_POST
:
3306 case HTTP_STATE_POST_RECV
:
3307 case HTTP_STATE_PUT
:
3310 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3311 http_states
[http
->state
+ 1]));
3313 case HTTP_STATE_POST_SEND
:
3314 case HTTP_STATE_HEAD
:
3318 http
->state
= HTTP_STATE_WAITING
;
3320 DEBUG_puts("1_httpUpdate: Unknown state, reset state to "
3321 "HTTP_STATE_WAITING.");
3326 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3327 http_content_coding_start(http
,
3328 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3329 #endif /* HAVE_LIBZ */
3331 *status
= http
->status
;
3334 else if (!strncmp(line
, "HTTP/", 5))
3337 * Got the beginning of a response...
3340 int intstatus
; /* Status value as an integer */
3342 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3344 *status
= http
->status
= HTTP_ERROR
;
3348 httpClearFields(http
);
3350 http
->version
= (http_version_t
)(major
* 100 + minor
);
3351 *status
= http
->status
= (http_status_t
)intstatus
;
3353 else if ((value
= strchr(line
, ':')) != NULL
)
3360 while (_cups_isspace(*value
))
3363 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3366 * Be tolerants of servers that send unknown attribute fields...
3369 if (!_cups_strcasecmp(line
, "expect"))
3372 * "Expect: 100-continue" or similar...
3375 http
->expect
= (http_status_t
)atoi(value
);
3377 else if (!_cups_strcasecmp(line
, "cookie"))
3380 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3383 httpSetCookie(http
, value
);
3385 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
3386 httpSetField(http
, field
, value
);
3389 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3394 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3395 http
->error
= EINVAL
;
3396 http
->status
= *status
= HTTP_ERROR
;
3405 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3408 http_status_t
/* O - HTTP status */
3409 httpUpdate(http_t
*http
) /* I - Connection to server */
3411 http_status_t status
; /* Request status */
3414 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3415 http_states
[http
->state
+ 1]));
3418 * Flush pending data, if any...
3423 DEBUG_puts("2httpUpdate: flushing buffer...");
3425 if (httpFlushWrite(http
) < 0)
3426 return (HTTP_ERROR
);
3430 * If we haven't issued any commands, then there is nothing to "update"...
3433 if (http
->state
== HTTP_STATE_WAITING
)
3434 return (HTTP_CONTINUE
);
3437 * Grab all of the lines we can from the connection...
3440 while (_httpUpdate(http
, &status
));
3443 * See if there was an error...
3446 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
3448 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3449 return (http
->status
);
3454 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3455 strerror(http
->error
)));
3456 http
->status
= HTTP_ERROR
;
3457 return (HTTP_ERROR
);
3461 * Return the current status...
3469 * '_httpWait()' - Wait for data available on a connection (no flush).
3472 int /* O - 1 if data is available, 0 otherwise */
3473 _httpWait(http_t
*http
, /* I - Connection to server */
3474 int msec
, /* I - Milliseconds to wait */
3475 int usessl
) /* I - Use SSL context? */
3478 struct pollfd pfd
; /* Polled file descriptor */
3480 fd_set input_set
; /* select() input set */
3481 struct timeval timeout
; /* Timeout */
3482 #endif /* HAVE_POLL */
3483 int nfds
; /* Result from select()/poll() */
3486 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3490 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3495 * Check the SSL/TLS buffers for data first...
3499 if (http
->tls
&& usessl
)
3502 if (SSL_pending(http
->tls
))
3504 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3508 # elif defined(HAVE_GNUTLS)
3509 if (gnutls_record_check_pending(http
->tls
))
3511 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3515 # elif defined(HAVE_CDSASSL)
3516 size_t bytes
; /* Bytes that are available */
3518 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3521 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3524 # endif /* HAVE_LIBSSL */
3526 #endif /* HAVE_SSL */
3529 * Then try doing a select() or poll() to poll the socket...
3534 pfd
.events
= POLLIN
;
3538 nfds
= poll(&pfd
, 1, msec
);
3540 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3545 FD_ZERO(&input_set
);
3546 FD_SET(http
->fd
, &input_set
);
3548 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3552 timeout
.tv_sec
= msec
/ 1000;
3553 timeout
.tv_usec
= (msec
% 1000) * 1000;
3555 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3558 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3560 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3563 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3564 WSAGetLastError() == WSAEWOULDBLOCK
));
3566 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3568 #endif /* HAVE_POLL */
3570 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3578 * 'httpWait()' - Wait for data available on a connection.
3580 * @since CUPS 1.1.19/OS X 10.3@
3583 int /* O - 1 if data is available, 0 otherwise */
3584 httpWait(http_t
*http
, /* I - Connection to server */
3585 int msec
) /* I - Milliseconds to wait */
3588 * First see if there is data in the buffer...
3591 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3598 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3603 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3605 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3608 #endif /* HAVE_LIBZ */
3611 * Flush pending data, if any...
3616 DEBUG_puts("3httpWait: Flushing write buffer.");
3618 if (httpFlushWrite(http
) < 0)
3623 * If not, check the SSL/TLS buffers and do a select() on the connection...
3626 return (_httpWait(http
, msec
, 1));
3631 * 'httpWrite()' - Write data to a HTTP connection.
3633 * This function is deprecated. Use the httpWrite2() function which can
3634 * write more than 2GB of data.
3639 int /* O - Number of bytes written */
3640 httpWrite(http_t
*http
, /* I - Connection to server */
3641 const char *buffer
, /* I - Buffer for data */
3642 int length
) /* I - Number of bytes to write */
3644 return ((int)httpWrite2(http
, buffer
, length
));
3649 * 'httpWrite2()' - Write data to a HTTP connection.
3651 * @since CUPS 1.2/OS X 10.5@
3654 ssize_t
/* O - Number of bytes written */
3655 httpWrite2(http_t
*http
, /* I - Connection to server */
3656 const char *buffer
, /* I - Buffer for data */
3657 size_t length
) /* I - Number of bytes to write */
3659 ssize_t bytes
; /* Bytes written */
3662 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3663 buffer
, CUPS_LLCAST length
));
3666 * Range check input...
3669 if (!http
|| !buffer
)
3671 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3676 * Mark activity on the connection...
3679 http
->activity
= time(NULL
);
3682 * Buffer small writes for better performance...
3688 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3692 http_content_coding_finish(http
);
3697 http
->stream
.next_in
= (Bytef
*)buffer
;
3698 http
->stream
.avail_in
= length
;
3699 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3700 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3702 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3704 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3706 if (http
->stream
.avail_out
== 0)
3708 if (httpFlushWrite(http
) < 0)
3710 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3714 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3715 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3719 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3724 #endif /* HAVE_LIBZ */
3727 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3729 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3730 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3732 httpFlushWrite(http
);
3735 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3736 length
< sizeof(http
->wbuffer
))
3739 * Write to buffer...
3742 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3743 CUPS_LLCAST length
));
3745 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3746 http
->wused
+= (int)length
;
3747 bytes
= (ssize_t
)length
;
3752 * Otherwise write the data directly...
3755 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3756 CUPS_LLCAST length
));
3758 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3759 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3761 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3763 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3764 CUPS_LLCAST bytes
));
3767 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3768 http
->data_remaining
-= bytes
;
3774 * Handle end-of-request processing...
3777 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3778 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3781 * Finished with the transfer; unless we are sending POST or PUT
3787 if (httpFlushWrite(http
) < 0)
3791 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3794 * Send a 0-length chunk at the end of the request...
3797 http_write(http
, "0\r\n\r\n", 5);
3800 * Reset the data state...
3803 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3804 http
->data_remaining
= 0;
3807 if (http
->state
== HTTP_STATE_POST_RECV
)
3811 http_content_coding_finish(http
);
3812 #endif /* HAVE_LIBZ */
3816 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3817 http_states
[http
->state
+ 1]));
3821 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3827 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3829 * '_httpWriteCDSA()' - Write function for the CDSA library.
3832 OSStatus
/* O - -1 on error, 0 on success */
3834 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3835 const void *data
, /* I - Data buffer */
3836 size_t *dataLength
) /* IO - Number of bytes */
3838 OSStatus result
; /* Return value */
3839 ssize_t bytes
; /* Number of bytes read */
3840 http_t
*http
; /* HTTP connection */
3843 http
= (http_t
*)connection
;
3847 bytes
= write(http
->fd
, data
, *dataLength
);
3849 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3851 if (bytes
== *dataLength
)
3855 else if (bytes
>= 0)
3857 *dataLength
= bytes
;
3858 result
= errSSLWouldBlock
;
3864 if (errno
== EAGAIN
)
3865 result
= errSSLWouldBlock
;
3867 result
= errSSLClosedAbort
;
3872 #endif /* HAVE_SSL && HAVE_CDSASSL */
3875 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3877 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3880 ssize_t
/* O - Number of bytes written or -1 on error */
3882 gnutls_transport_ptr ptr
, /* I - Connection to server */
3883 const void *data
, /* I - Data buffer */
3884 size_t length
) /* I - Number of bytes to write */
3886 ssize_t bytes
; /* Bytes written */
3889 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3892 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3895 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3896 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3900 #endif /* HAVE_SSL && HAVE_GNUTLS */
3904 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3909 int /* O - 0 on success, -1 on error */
3910 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3911 http_status_t status
) /* I - Status code */
3913 http_encoding_t old_encoding
; /* Old data_encoding value */
3914 off_t old_remaining
; /* Old data_remaining value */
3918 * Range check input...
3921 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3923 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3925 DEBUG_puts("1httpWriteResponse: Bad input.");
3930 * Set the various standard fields if they aren't already...
3933 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3934 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3936 if (status
>= HTTP_BAD_REQUEST
&& http
->keep_alive
)
3938 http
->keep_alive
= 0;
3939 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3942 if (http
->version
== HTTP_VERSION_1_1
)
3944 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3946 if (http
->keep_alive
)
3947 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3949 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3952 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3953 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3957 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
)
3959 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3960 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3962 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3963 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3965 #endif /* HAVE_SSL */
3968 httpSetField(http
, HTTP_FIELD_SERVER
,
3969 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3972 * Set the Accept-Encoding field if it isn't already...
3975 if (!http
->accept_encoding
)
3976 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3977 http
->default_accept_encoding
? http
->default_accept_encoding
:
3979 "gzip, deflate, identity");
3982 #endif /* HAVE_LIBZ */
3985 * Send the response header...
3988 old_encoding
= http
->data_encoding
;
3989 old_remaining
= http
->data_remaining
;
3990 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3992 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3993 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3995 http
->status
= HTTP_STATUS_ERROR
;
3999 if (status
!= HTTP_STATUS_CONTINUE
)
4002 * 100 Continue doesn't have the rest of the response headers...
4005 int i
; /* Looping var */
4006 const char *value
; /* Field value */
4008 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4010 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4012 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4014 http
->status
= HTTP_STATUS_ERROR
;
4022 if (httpPrintf(http
, "Set-Cookie: %s path=/%s\r\n", http
->cookie
,
4023 http
->tls
? " secure" : "") < 1)
4025 http
->status
= HTTP_ERROR
;
4031 if (httpWrite2(http
, "\r\n", 2) < 2)
4033 http
->status
= HTTP_ERROR
;
4037 if (httpFlushWrite(http
) < 0)
4039 http
->status
= HTTP_ERROR
;
4043 if (status
== HTTP_STATUS_CONTINUE
)
4046 * Restore the old data_encoding and data_length values...
4049 http
->data_encoding
= old_encoding
;
4050 http
->data_remaining
= old_remaining
;
4052 if (old_remaining
<= INT_MAX
)
4053 http
->_data_remaining
= (int)old_remaining
;
4055 http
->_data_remaining
= INT_MAX
;
4057 else if (http
->state
== HTTP_STATE_OPTIONS
||
4058 http
->state
== HTTP_STATE_HEAD
||
4059 http
->state
== HTTP_STATE_PUT
||
4060 http
->state
== HTTP_STATE_TRACE
||
4061 http
->state
== HTTP_STATE_CONNECT
)
4063 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
4064 "was %s.", http_states
[http
->state
+ 1]));
4065 http
->state
= HTTP_STATE_WAITING
;
4070 * Force data_encoding and data_length to be set according to the response
4074 http_set_length(http
);
4077 * Then start any content encoding...
4080 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
4081 http_content_coding_start(http
,
4082 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
4089 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
4091 * 'http_bio_ctrl()' - Control the HTTP connection.
4094 static long /* O - Result/data */
4095 http_bio_ctrl(BIO
*h
, /* I - BIO data */
4096 int cmd
, /* I - Control command */
4097 long arg1
, /* I - First argument */
4098 void *arg2
) /* I - Second argument */
4105 case BIO_CTRL_RESET
:
4109 case BIO_C_SET_FILE_PTR
:
4114 case BIO_C_GET_FILE_PTR
:
4117 *((void **)arg2
) = h
->ptr
;
4124 case BIO_CTRL_FLUSH
:
4131 * 'http_bio_free()' - Free OpenSSL data.
4134 static int /* O - 1 on success, 0 on failure */
4135 http_bio_free(BIO
*h
) /* I - BIO data */
4151 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
4154 static int /* O - 1 on success, 0 on failure */
4155 http_bio_new(BIO
*h
) /* I - BIO data */
4170 * 'http_bio_puts()' - Send a string for OpenSSL.
4173 static int /* O - Bytes written */
4174 http_bio_puts(BIO
*h
, /* I - BIO data */
4175 const char *str
) /* I - String to write */
4178 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
4180 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
4186 * 'http_bio_read()' - Read data for OpenSSL.
4189 static int /* O - Bytes read */
4190 http_bio_read(BIO
*h
, /* I - BIO data */
4191 char *buf
, /* I - Buffer */
4192 int size
) /* I - Number of bytes to read */
4194 http_t
*http
; /* HTTP connection */
4197 http
= (http_t
*)h
->ptr
;
4199 if (!http
->blocking
)
4202 * Make sure we have data before we read...
4205 while (!_httpWait(http
, http
->wait_value
, 0))
4207 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4211 http
->error
= WSAETIMEDOUT
;
4213 http
->error
= ETIMEDOUT
;
4220 return (recv(http
->fd
, buf
, size
, 0));
4225 * 'http_bio_write()' - Write data for OpenSSL.
4228 static int /* O - Bytes written */
4229 http_bio_write(BIO
*h
, /* I - BIO data */
4230 const char *buf
, /* I - Buffer to write */
4231 int num
) /* I - Number of bytes to write */
4233 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4235 #endif /* HAVE_SSL && HAVE_LIBSSL */
4240 * 'http_content_coding_finish()' - Finish doing any content encoding.
4244 http_content_coding_finish(
4245 http_t
*http
) /* I - HTTP connection */
4247 int zerr
; /* Compression status */
4250 switch (http
->coding
)
4252 case _HTTP_CODING_DEFLATE
:
4253 case _HTTP_CODING_GZIP
:
4256 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4257 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4259 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4261 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4262 if (http
->wused
== sizeof(http
->wbuffer
))
4263 httpFlushWrite(http
);
4265 while (zerr
== Z_OK
);
4267 deflateEnd(&(http
->stream
));
4270 httpFlushWrite(http
);
4273 case _HTTP_CODING_INFLATE
:
4274 case _HTTP_CODING_GUNZIP
:
4275 inflateEnd(&(http
->stream
));
4276 free(http
->dbuffer
);
4277 http
->dbuffer
= NULL
;
4284 http
->coding
= _HTTP_CODING_IDENTITY
;
4289 * 'http_content_coding_start()' - Start doing content encoding.
4293 http_content_coding_start(
4294 http_t
*http
, /* I - HTTP connection */
4295 const char *value
) /* I - Value of Content-Encoding */
4297 int zerr
; /* Error/status */
4298 _http_coding_t coding
; /* Content coding value */
4301 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4304 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4306 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4310 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4312 if (http
->state
== HTTP_GET_SEND
|| http
->state
== HTTP_POST_SEND
)
4313 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4314 _HTTP_CODING_GUNZIP
;
4315 else if (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
)
4316 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4317 _HTTP_CODING_GUNZIP
;
4320 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4324 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4326 if (http
->state
== HTTP_GET_SEND
|| http
->state
== HTTP_POST_SEND
)
4327 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4328 _HTTP_CODING_INFLATE
;
4329 else if (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
)
4330 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4331 _HTTP_CODING_INFLATE
;
4334 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4340 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4344 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4348 case _HTTP_CODING_DEFLATE
:
4349 case _HTTP_CODING_GZIP
:
4351 httpFlushWrite(http
);
4353 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4355 coding
== _HTTP_CODING_DEFLATE
? 11 : 27, 7,
4356 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4358 http
->status
= HTTP_ERROR
;
4359 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4364 case _HTTP_CODING_INFLATE
:
4365 case _HTTP_CODING_GUNZIP
:
4366 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
4368 http
->status
= HTTP_ERROR
;
4369 http
->error
= errno
;
4373 if ((zerr
= inflateInit2(&(http
->stream
),
4374 coding
== _HTTP_CODING_INFLATE
? 15 : 31))
4377 free(http
->dbuffer
);
4378 http
->dbuffer
= NULL
;
4379 http
->status
= HTTP_ERROR
;
4380 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4384 http
->stream
.avail_in
= 0;
4385 http
->stream
.next_in
= http
->dbuffer
;
4392 http
->coding
= coding
;
4394 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4397 #endif /* HAVE_LIBZ */
4402 * 'http_debug_hex()' - Do a hex dump of a buffer.
4406 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4407 const char *buffer
, /* I - Buffer to dump */
4408 int bytes
) /* I - Bytes to dump */
4410 int i
, j
, /* Looping vars */
4411 ch
; /* Current character */
4412 char line
[255], /* Line buffer */
4413 *start
, /* Start of line after prefix */
4414 *ptr
; /* Pointer into line */
4417 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4420 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4422 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4423 start
= line
+ strlen(line
);
4425 for (i
= 0; i
< bytes
; i
+= 16)
4427 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4428 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4432 memcpy(ptr
, " ", 3);
4437 memcpy(ptr
, " ", 3);
4440 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4442 ch
= buffer
[i
+ j
] & 255;
4444 if (ch
< ' ' || ch
>= 127)
4458 * 'http_field()' - Return the field index for a field name.
4461 static http_field_t
/* O - Field index */
4462 http_field(const char *name
) /* I - String name */
4464 int i
; /* Looping var */
4467 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4468 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
4469 return ((http_field_t
)i
);
4471 return (HTTP_FIELD_UNKNOWN
);
4476 * 'http_read()' - Read a buffer from a HTTP connection.
4478 * This function does the low-level read from the socket, retrying and timing
4482 static ssize_t
/* O - Number of bytes read or -1 on error */
4483 http_read(http_t
*http
, /* I - Connection to server */
4484 char *buffer
, /* I - Buffer */
4485 size_t length
) /* I - Maximum bytes to read */
4487 ssize_t bytes
; /* Bytes read */
4490 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4491 buffer
, CUPS_LLCAST length
));
4493 if (!http
->blocking
)
4495 while (!httpWait(http
, http
->wait_value
))
4497 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4500 DEBUG_puts("2http_read: Timeout.");
4505 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4511 bytes
= http_read_ssl(http
, buffer
, length
);
4513 #endif /* HAVE_SSL */
4514 bytes
= recv(http
->fd
, buffer
, length
, 0);
4519 if (WSAGetLastError() != WSAEINTR
)
4521 http
->error
= WSAGetLastError();
4524 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4526 if (!http
->timeout_cb
||
4527 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4529 http
->error
= WSAEWOULDBLOCK
;
4534 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4536 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4538 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4540 http
->error
= errno
;
4543 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4545 http
->error
= errno
;
4549 else if (errno
!= EINTR
)
4551 http
->error
= errno
;
4559 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4560 CUPS_LLCAST bytes
));
4563 http_debug_hex("http_read", http
->buffer
, (int)bytes
);
4569 if (WSAGetLastError() == WSAEINTR
)
4572 http
->error
= WSAGetLastError();
4574 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4577 http
->error
= errno
;
4580 else if (bytes
== 0)
4582 http
->error
= EPIPE
;
4591 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4593 * This function reads data from the HTTP buffer or from the socket, as needed.
4596 static ssize_t
/* O - Number of bytes read or -1 on error */
4597 http_read_buffered(http_t
*http
, /* I - Connection to server */
4598 char *buffer
, /* I - Buffer */
4599 size_t length
) /* I - Maximum bytes to read */
4601 ssize_t bytes
; /* Bytes read */
4604 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4606 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4610 if (length
> (size_t)http
->used
)
4611 bytes
= (size_t)http
->used
;
4615 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4618 memcpy(buffer
, http
->buffer
, bytes
);
4619 http
->used
-= (int)bytes
;
4622 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4625 bytes
= http_read(http
, buffer
, length
);
4632 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4634 * This function reads and validates the chunk length, then does a buffered read
4635 * returning the number of bytes placed in the buffer.
4638 static ssize_t
/* O - Number of bytes read or -1 on error */
4639 http_read_chunk(http_t
*http
, /* I - Connection to server */
4640 char *buffer
, /* I - Buffer */
4641 size_t length
) /* I - Maximum bytes to read */
4643 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4644 http
, buffer
, CUPS_LLCAST length
));
4646 if (http
->data_remaining
<= 0)
4648 char len
[32]; /* Length string */
4650 if (!httpGets(len
, sizeof(len
), http
))
4652 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4658 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4659 if (!httpGets(len
, sizeof(len
), http
))
4661 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4666 http
->data_remaining
= strtoll(len
, NULL
, 16);
4668 if (http
->data_remaining
< 0)
4670 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4671 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4675 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4676 len
, CUPS_LLCAST http
->data_remaining
));
4678 if (http
->data_remaining
== 0)
4681 * 0-length chunk, grab trailing blank line...
4684 httpGets(len
, sizeof(len
), http
);
4688 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4689 CUPS_LLCAST http
->data_remaining
));
4691 if (http
->data_remaining
<= 0)
4693 else if (length
> (size_t)http
->data_remaining
)
4694 length
= (size_t)http
->data_remaining
;
4696 return (http_read_buffered(http
, buffer
, length
));
4702 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4705 static int /* O - Bytes read */
4706 http_read_ssl(http_t
*http
, /* I - Connection to server */
4707 char *buf
, /* I - Buffer to store data */
4708 int len
) /* I - Length of buffer */
4710 # if defined(HAVE_LIBSSL)
4711 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4713 # elif defined(HAVE_GNUTLS)
4714 ssize_t result
; /* Return value */
4717 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4719 if (result
< 0 && !errno
)
4722 * Convert GNU TLS error to errno value...
4727 case GNUTLS_E_INTERRUPTED
:
4731 case GNUTLS_E_AGAIN
:
4743 return ((int)result
);
4745 # elif defined(HAVE_CDSASSL)
4746 int result
; /* Return value */
4747 OSStatus error
; /* Error info */
4748 size_t processed
; /* Number of bytes processed */
4751 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4752 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4757 result
= (int)processed
;
4760 case errSSLWouldBlock
:
4762 result
= (int)processed
;
4770 case errSSLClosedGraceful
:
4773 result
= (int)processed
;
4784 # elif defined(HAVE_SSPISSL)
4785 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4786 # endif /* HAVE_LIBSSL */
4788 #endif /* HAVE_SSL */
4792 * 'http_send()' - Send a request with all fields and the trailing blank line.
4795 static int /* O - 0 on success, non-zero on error */
4796 http_send(http_t
*http
, /* I - Connection to server */
4797 http_state_t request
, /* I - Request code */
4798 const char *uri
) /* I - URI */
4800 int i
; /* Looping var */
4801 char buf
[1024]; /* Encoded URI buffer */
4802 const char *value
; /* Field value */
4803 static const char * const codes
[] = /* Request code strings */
4823 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4824 http
, codes
[request
], uri
));
4826 if (http
== NULL
|| uri
== NULL
)
4830 * Set the User-Agent field if it isn't already...
4833 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4834 httpSetField(http
, HTTP_FIELD_USER_AGENT
,
4835 http
->default_user_agent
? http
->default_user_agent
:
4839 * Set the Accept-Encoding field if it isn't already...
4842 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4843 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4844 http
->default_accept_encoding
);
4847 * Encode the URI as needed...
4850 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4853 * See if we had an error the last time around; if so, reconnect...
4856 if (http
->fd
< 0 || http
->status
== HTTP_ERROR
||
4857 http
->status
>= HTTP_BAD_REQUEST
)
4858 if (httpReconnect(http
))
4862 * Flush any written data that is pending...
4867 if (httpFlushWrite(http
) < 0)
4868 if (httpReconnect(http
))
4873 * Send the request header...
4876 http
->state
= request
;
4877 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4879 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
4882 http
->status
= HTTP_CONTINUE
;
4885 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
4887 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4888 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4890 #endif /* HAVE_SSL */
4892 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4894 http
->status
= HTTP_ERROR
;
4898 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4899 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4901 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
], value
));
4903 if (i
== HTTP_FIELD_HOST
)
4905 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4906 httpAddrPort(http
->hostaddr
)) < 1)
4908 http
->status
= HTTP_ERROR
;
4912 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4914 http
->status
= HTTP_ERROR
;
4920 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4922 http
->status
= HTTP_ERROR
;
4926 if (http
->expect
== HTTP_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4927 (http
->state
== HTTP_STATE_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
4928 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4930 http
->status
= HTTP_ERROR
;
4934 if (httpPrintf(http
, "\r\n") < 1)
4936 http
->status
= HTTP_ERROR
;
4940 if (httpFlushWrite(http
) < 0)
4943 http_set_length(http
);
4944 httpClearFields(http
);
4947 * The Kerberos and AuthRef authentication strings can only be used once...
4950 if (http
->field_authorization
&& http
->authstring
&&
4951 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4952 !strncmp(http
->authstring
, "AuthRef", 7)))
4954 http
->_authstring
[0] = '\0';
4956 if (http
->authstring
!= http
->_authstring
)
4957 free(http
->authstring
);
4959 http
->authstring
= http
->_authstring
;
4967 # if defined(HAVE_CDSASSL)
4969 * 'http_set_credentials()' - Set the SSL/TLS credentials.
4972 static int /* O - Status of connection */
4973 http_set_credentials(http_t
*http
) /* I - Connection to server */
4975 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
4976 OSStatus error
= 0; /* Error code */
4977 http_tls_credentials_t credentials
= NULL
;
4978 /* TLS credentials */
4981 DEBUG_printf(("7http_set_credentials(%p)", http
));
4984 * Prefer connection specific credentials...
4987 if ((credentials
= http
->tls_credentials
) == NULL
)
4988 credentials
= cg
->tls_credentials
;
4991 * Otherwise root around in the user's keychain to see if one can be found...
4996 CFDictionaryRef query
; /* Query dictionary */
4997 CFTypeRef matches
= NULL
; /* Matching credentials */
4998 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
4999 CFTypeRef keys
[] = { kSecClass
,
5002 /* Keys for dictionary */
5003 CFTypeRef values
[] = { kSecClassCertificate
,
5006 /* Values for dictionary */
5009 * Get the names associated with the server.
5012 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
5014 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
5020 * Create a query which will return all identities that can sign and match
5021 * the passed in policy.
5024 query
= CFDictionaryCreate(NULL
,
5025 (const void**)(&keys
[0]),
5026 (const void**)(&values
[0]),
5027 sizeof(keys
) / sizeof(keys
[0]),
5028 &kCFTypeDictionaryKeyCallBacks
,
5029 &kCFTypeDictionaryValueCallBacks
);
5032 error
= SecItemCopyMatching(query
, &matches
);
5033 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
5042 CFRelease(dn_array
);
5047 error
= SSLSetCertificate(http
->tls
, credentials
);
5048 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
5052 DEBUG_puts("4http_set_credentials: No credentials to set.");
5056 # endif /* HAVE_CDSASSL */
5057 #endif /* HAVE_SSL */
5061 * 'http_set_length()' - Set the data_encoding and data_remaining values.
5064 static off_t
/* O - Remainder or -1 on error */
5065 http_set_length(http_t
*http
) /* I - Connection */
5067 off_t remaining
; /* Remainder */
5070 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
5071 http_states
[http
->state
+ 1]));
5073 if ((remaining
= httpGetLength2(http
)) >= 0)
5075 if (http
->mode
== _HTTP_MODE_SERVER
&&
5076 http
->state
!= HTTP_STATE_GET_SEND
&&
5077 http
->state
!= HTTP_STATE_PUT
&&
5078 http
->state
!= HTTP_STATE_POST
&&
5079 http
->state
!= HTTP_STATE_POST_SEND
)
5081 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
5085 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
5088 DEBUG_puts("1http_set_length: Setting data_encoding to "
5089 "HTTP_ENCODING_CHUNKED.");
5090 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
5094 DEBUG_puts("1http_set_length: Setting data_encoding to "
5095 "HTTP_ENCODING_LENGTH.");
5096 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
5099 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
5100 CUPS_LLCAST remaining
));
5101 http
->data_remaining
= remaining
;
5103 if (remaining
<= INT_MAX
)
5104 http
->_data_remaining
= remaining
;
5106 http
->_data_remaining
= INT_MAX
;
5113 * 'http_set_timeout()' - Set the socket timeout values.
5117 http_set_timeout(int fd
, /* I - File descriptor */
5118 double timeout
) /* I - Timeout in seconds */
5121 DWORD tv
= (DWORD
)(timeout
* 1000);
5122 /* Timeout in milliseconds */
5124 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&tv
, sizeof(tv
));
5125 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&tv
, sizeof(tv
));
5128 struct timeval tv
; /* Timeout in secs and usecs */
5130 tv
.tv_sec
= (int)timeout
;
5131 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
5133 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, &tv
, sizeof(tv
));
5134 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
5140 * 'http_set_wait()' - Set the default wait value for reads.
5144 http_set_wait(http_t
*http
) /* I - Connection to server */
5148 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5150 if (http
->wait_value
<= 0)
5151 http
->wait_value
= 60000;
5154 http
->wait_value
= 10000;
5160 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5163 static int /* O - 0 on success, -1 on failure */
5164 http_setup_ssl(http_t
*http
) /* I - Connection to server */
5166 char hostname
[256], /* Hostname */
5167 *hostptr
; /* Pointer into hostname */
5170 SSL_CTX
*context
; /* Context for encryption */
5171 BIO
*bio
; /* BIO data */
5172 const char *message
= NULL
;/* Error message */
5173 # elif defined(HAVE_GNUTLS)
5174 int status
; /* Status of handshake */
5175 gnutls_certificate_client_credentials
*credentials
;
5176 /* TLS credentials */
5177 # elif defined(HAVE_CDSASSL)
5178 _cups_globals_t
*cg
= _cupsGlobals();
5179 /* Pointer to library globals */
5180 OSStatus error
; /* Error code */
5181 const char *message
= NULL
;/* Error message */
5182 cups_array_t
*credentials
; /* Credentials array */
5183 cups_array_t
*names
; /* CUPS distinguished names */
5184 CFArrayRef dn_array
; /* CF distinguished names array */
5185 CFIndex count
; /* Number of credentials */
5186 CFDataRef data
; /* Certificate data */
5187 int i
; /* Looping var */
5188 http_credential_t
*credential
; /* Credential data */
5189 # elif defined(HAVE_SSPISSL)
5190 TCHAR username
[256]; /* Username returned from GetUserName() */
5191 TCHAR commonName
[256];/* Common name for certificate */
5192 DWORD dwSize
; /* 32 bit size */
5193 # endif /* HAVE_LIBSSL */
5196 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5199 * Get the hostname to use for SSL...
5202 if (httpAddrLocalhost(http
->hostaddr
))
5204 strlcpy(hostname
, "localhost", sizeof(hostname
));
5209 * Otherwise make sure the hostname we have does not end in a trailing dot.
5212 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5213 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5219 context
= SSL_CTX_new(SSLv23_client_method());
5221 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5223 bio
= BIO_new(_httpBIOMethods());
5224 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5226 http
->tls
= SSL_new(context
);
5227 SSL_set_bio(http
->tls
, bio
, bio
);
5229 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5230 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5231 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5233 if (SSL_connect(http
->tls
) != 1)
5235 unsigned long error
; /* Error code */
5237 while ((error
= ERR_get_error()) != 0)
5239 message
= ERR_error_string(error
, NULL
);
5240 DEBUG_printf(("8http_setup_ssl: %s", message
));
5243 SSL_CTX_free(context
);
5244 SSL_free(http
->tls
);
5248 http
->error
= WSAGetLastError();
5250 http
->error
= errno
;
5252 http
->status
= HTTP_ERROR
;
5255 message
= _("Unable to establish a secure connection to host.");
5257 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5262 # elif defined(HAVE_GNUTLS)
5263 credentials
= (gnutls_certificate_client_credentials
*)
5264 malloc(sizeof(gnutls_certificate_client_credentials
));
5265 if (credentials
== NULL
)
5267 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5269 http
->error
= errno
;
5270 http
->status
= HTTP_ERROR
;
5271 _cupsSetHTTPError(HTTP_ERROR
);
5276 gnutls_certificate_allocate_credentials(credentials
);
5278 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5279 gnutls_set_default_priority(http
->tls
);
5280 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5282 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5283 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5284 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5285 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5287 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5289 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5290 status
, gnutls_strerror(status
)));
5292 if (gnutls_error_is_fatal(status
))
5295 http
->status
= HTTP_ERROR
;
5297 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
5299 gnutls_deinit(http
->tls
);
5300 gnutls_certificate_free_credentials(*credentials
);
5308 http
->tls_credentials
= credentials
;
5310 # elif defined(HAVE_CDSASSL)
5311 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, kSSLClientSide
,
5312 kSSLStreamType
)) == NULL
)
5314 DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
5315 http
->error
= errno
= ENOMEM
;
5316 http
->status
= HTTP_ERROR
;
5317 _cupsSetHTTPError(HTTP_ERROR
);
5322 error
= SSLSetConnection(http
->tls
, http
);
5323 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5327 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5328 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5333 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
5335 DEBUG_printf(("4http_setup_ssl: SSLSetSessionOption, error=%d",
5341 if (cg
->client_cert_cb
)
5343 error
= SSLSetSessionOption(http
->tls
,
5344 kSSLSessionOptionBreakOnCertRequested
, true);
5345 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5346 "error=%d", (int)error
));
5350 error
= http_set_credentials(http
);
5351 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5357 * Let the server know which hostname/domain we are trying to connect to
5358 * in case it wants to serve up a certificate with a matching common name.
5363 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5365 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5371 int done
= 0; /* Are we done yet? */
5373 while (!error
&& !done
)
5375 error
= SSLHandshake(http
->tls
);
5377 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5385 case errSSLWouldBlock
:
5386 error
= noErr
; /* Force a retry */
5387 usleep(1000); /* in 1 millisecond */
5390 case errSSLServerAuthCompleted
:
5392 if (cg
->server_cert_cb
)
5394 error
= httpCopyCredentials(http
, &credentials
);
5397 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5398 cg
->server_cert_data
);
5399 httpFreeCredentials(credentials
);
5402 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5403 "returned %d.", (int)error
));
5407 case errSSLClientCertRequested
:
5410 if (cg
->client_cert_cb
)
5413 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5416 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5418 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5420 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5422 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5424 credential
->datalen
= CFDataGetLength(data
);
5425 if ((credential
->data
= malloc(credential
->datalen
)))
5427 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5428 credential
->datalen
);
5429 cupsArrayAdd(names
, credential
);
5437 CFRelease(dn_array
);
5442 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5443 cg
->client_cert_data
);
5445 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5446 "returned %d.", (int)error
));
5449 httpFreeCredentials(names
);
5453 case errSSLUnknownRootCert
:
5454 message
= _("Unable to establish a secure connection to host "
5455 "(untrusted certificate).");
5458 case errSSLNoRootCert
:
5459 message
= _("Unable to establish a secure connection to host "
5460 "(self-signed certificate).");
5463 case errSSLCertExpired
:
5464 message
= _("Unable to establish a secure connection to host "
5465 "(expired certificate).");
5468 case errSSLCertNotYetValid
:
5469 message
= _("Unable to establish a secure connection to host "
5470 "(certificate not yet valid).");
5473 case errSSLHostNameMismatch
:
5474 message
= _("Unable to establish a secure connection to host "
5475 "(host name mismatch).");
5478 case errSSLXCertChainInvalid
:
5479 message
= _("Unable to establish a secure connection to host "
5480 "(certificate chain invalid).");
5483 case errSSLConnectionRefused
:
5484 message
= _("Unable to establish a secure connection to host "
5485 "(peer dropped connection before responding).");
5496 http
->error
= error
;
5497 http
->status
= HTTP_ERROR
;
5498 errno
= ECONNREFUSED
;
5500 CFRelease(http
->tls
);
5504 * If an error string wasn't set by the callbacks use a generic one...
5508 #ifdef HAVE_CSSMERRORSTRING
5509 message
= cssmErrorString(error
);
5511 message
= _("Unable to establish a secure connection to host.");
5512 #endif /* HAVE_CSSMERRORSTRING */
5514 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
5519 # elif defined(HAVE_SSPISSL)
5520 http
->tls
= _sspiAlloc();
5524 _cupsSetHTTPError(HTTP_ERROR
);
5528 http
->tls
->sock
= http
->fd
;
5529 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5530 GetUserName(username
, &dwSize
);
5531 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5532 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5534 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5537 _sspiFree(http
->tls_credentials
);
5538 http
->tls_credentials
= NULL
;
5541 http
->status
= HTTP_ERROR
;
5543 _cupsSetError(IPP_PKI_ERROR
,
5544 _("Unable to establish a secure connection to host."), 1);
5549 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
5550 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5552 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5554 _sspiFree(http
->tls_credentials
);
5555 http
->tls_credentials
= NULL
;
5558 http
->status
= HTTP_ERROR
;
5560 _cupsSetError(IPP_PKI_ERROR
,
5561 _("Unable to establish a secure connection to host."), 1);
5565 # endif /* HAVE_CDSASSL */
5572 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5576 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
5579 SSL_CTX
*context
; /* Context for encryption */
5581 context
= SSL_get_SSL_CTX(http
->tls
);
5583 SSL_shutdown(http
->tls
);
5584 SSL_CTX_free(context
);
5585 SSL_free(http
->tls
);
5587 # elif defined(HAVE_GNUTLS)
5588 gnutls_certificate_client_credentials
*credentials
;
5589 /* TLS credentials */
5591 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5593 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5594 gnutls_deinit(http
->tls
);
5595 gnutls_certificate_free_credentials(*credentials
);
5598 # elif defined(HAVE_CDSASSL)
5599 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5602 CFRelease(http
->tls
);
5604 if (http
->tls_credentials
)
5605 CFRelease(http
->tls_credentials
);
5607 # elif defined(HAVE_SSPISSL)
5608 _sspiFree(http
->tls_credentials
);
5609 # endif /* HAVE_LIBSSL */
5612 http
->tls_credentials
= NULL
;
5614 #endif /* HAVE_SSL */
5619 * 'http_upgrade()' - Force upgrade to TLS encryption.
5622 static int /* O - Status of connection */
5623 http_upgrade(http_t
*http
) /* I - Connection to server */
5625 int ret
; /* Return value */
5626 http_t myhttp
; /* Local copy of HTTP data */
5629 DEBUG_printf(("7http_upgrade(%p)", http
));
5632 * Flush the connection to make sure any previous "Upgrade" message
5639 * Copy the HTTP data to a local variable so we can do the OPTIONS
5640 * request without interfering with the existing request data...
5643 memcpy(&myhttp
, http
, sizeof(myhttp
));
5646 * Send an OPTIONS request to the server, requiring SSL or TLS
5647 * encryption on the link...
5650 http
->field_authorization
= NULL
; /* Don't free the auth string */
5652 httpClearFields(http
);
5653 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5654 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5656 if ((ret
= httpOptions(http
, "*")) == 0)
5659 * Wait for the secure connection...
5662 while (httpUpdate(http
) == HTTP_CONTINUE
);
5666 * Restore the HTTP request data...
5669 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5670 http
->data_encoding
= myhttp
.data_encoding
;
5671 http
->data_remaining
= myhttp
.data_remaining
;
5672 http
->_data_remaining
= myhttp
._data_remaining
;
5673 http
->expect
= myhttp
.expect
;
5674 http
->field_authorization
= myhttp
.field_authorization
;
5675 http
->digest_tries
= myhttp
.digest_tries
;
5678 * See if we actually went secure...
5684 * Server does not support HTTP upgrade...
5687 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5690 closesocket(http
->fd
);
5702 #endif /* HAVE_SSL */
5706 * 'http_write()' - Write a buffer to a HTTP connection.
5709 static ssize_t
/* O - Number of bytes written */
5710 http_write(http_t
*http
, /* I - Connection to server */
5711 const char *buffer
, /* I - Buffer for data */
5712 size_t length
) /* I - Number of bytes to write */
5714 ssize_t tbytes
, /* Total bytes sent */
5715 bytes
; /* Bytes sent */
5718 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
5719 buffer
, CUPS_LLCAST length
));
5725 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5727 if (http
->timeout_cb
)
5730 struct pollfd pfd
; /* Polled file descriptor */
5732 fd_set output_set
; /* Output ready for write? */
5733 struct timeval timeout
; /* Timeout value */
5734 #endif /* HAVE_POLL */
5735 int nfds
; /* Result from select()/poll() */
5741 pfd
.events
= POLLOUT
;
5743 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5744 (errno
== EINTR
|| errno
== EAGAIN
))
5750 FD_ZERO(&output_set
);
5751 FD_SET(http
->fd
, &output_set
);
5753 timeout
.tv_sec
= http
->wait_value
/ 1000;
5754 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5756 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5759 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5760 WSAGetLastError() == WSAEWOULDBLOCK
));
5762 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5764 #endif /* HAVE_POLL */
5768 http
->error
= errno
;
5771 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5774 http
->error
= WSAEWOULDBLOCK
;
5776 http
->error
= EWOULDBLOCK
;
5786 bytes
= http_write_ssl(http
, buffer
, length
);
5788 #endif /* HAVE_SSL */
5789 bytes
= send(http
->fd
, buffer
, length
, 0);
5791 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
5792 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
5797 if (WSAGetLastError() == WSAEINTR
)
5799 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5801 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5804 http
->error
= WSAGetLastError();
5806 else if (WSAGetLastError() != http
->error
&&
5807 WSAGetLastError() != WSAECONNRESET
)
5809 http
->error
= WSAGetLastError();
5816 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5818 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5820 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5823 http
->error
= errno
;
5825 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5827 http
->error
= errno
;
5832 DEBUG_printf(("3http_write: error writing data (%s).",
5833 strerror(http
->error
)));
5844 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5847 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
5854 * 'http_write_chunk()' - Write a chunked buffer.
5857 static ssize_t
/* O - Number bytes written */
5858 http_write_chunk(http_t
*http
, /* I - Connection to server */
5859 const char *buffer
, /* I - Buffer to write */
5860 size_t length
) /* I - Length of buffer */
5862 char header
[16]; /* Chunk header */
5863 ssize_t bytes
; /* Bytes written */
5866 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
5867 http
, buffer
, CUPS_LLCAST length
));
5870 * Write the chunk header, data, and trailer.
5873 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
5874 if (http_write(http
, header
, strlen(header
)) < 0)
5876 DEBUG_puts("8http_write_chunk: http_write of length failed.");
5880 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5882 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
5886 if (http_write(http
, "\r\n", 2) < 0)
5888 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
5898 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5901 static int /* O - Bytes written */
5902 http_write_ssl(http_t
*http
, /* I - Connection to server */
5903 const char *buf
, /* I - Buffer holding data */
5904 int len
) /* I - Length of buffer */
5906 ssize_t result
; /* Return value */
5909 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5911 # if defined(HAVE_LIBSSL)
5912 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5914 # elif defined(HAVE_GNUTLS)
5915 result
= gnutls_record_send(http
->tls
, buf
, len
);
5917 if (result
< 0 && !errno
)
5920 * Convert GNU TLS error to errno value...
5925 case GNUTLS_E_INTERRUPTED
:
5929 case GNUTLS_E_AGAIN
:
5941 # elif defined(HAVE_CDSASSL)
5942 OSStatus error
; /* Error info */
5943 size_t processed
; /* Number of bytes processed */
5946 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5951 result
= (int)processed
;
5954 case errSSLWouldBlock
:
5956 result
= (int)processed
;
5964 case errSSLClosedGraceful
:
5967 result
= (int)processed
;
5975 # elif defined(HAVE_SSPISSL)
5976 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
5977 # endif /* HAVE_LIBSSL */
5979 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
5981 return ((int)result
);
5983 #endif /* HAVE_SSL */
5987 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".