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 * httpAddCredential() - Allocates and adds a single credential to an
24 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP
26 * httpBlocking() - Set blocking/non-blocking behavior on a
28 * httpCheck() - Check to see if there is a pending response
30 * httpClearCookie() - Clear the cookie value(s).
31 * httpClearFields() - Clear HTTP request fields.
32 * httpClose() - Close an HTTP connection.
33 * httpConnect() - Connect to a HTTP server.
34 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
35 * httpCopyCredentials() - Copy the credentials associated with an
36 * encrypted connection.
37 * _httpCreate() - Create an unconnected HTTP connection.
38 * _httpCreateCredentials() - Create credentials in the internal format.
39 * httpDelete() - Send a DELETE request to the server.
40 * _httpDisconnect() - Disconnect a HTTP connection.
41 * httpEncryption() - Set the required encryption on the link.
42 * httpError() - Get the last error on a connection.
43 * httpFlush() - Flush data from a HTTP connection.
44 * httpFlushWrite() - Flush data in write buffer.
45 * _httpFreeCredentials() - Free internal credentials.
46 * httpFreeCredentials() - Free an array of credentials.
47 * httpGet() - Send a GET request to the server.
48 * httpGetAuthString() - Get the current authorization string.
49 * httpGetBlocking() - Get the blocking/non-block state of a
51 * httpGetCookie() - Get any cookie data from the response.
52 * httpGetFd() - Get the file descriptor associated with a
54 * httpGetField() - Get a field value from a request/response.
55 * httpGetLength() - Get the amount of data remaining from the
56 * content-length or transfer-encoding fields.
57 * httpGetLength2() - Get the amount of data remaining from the
58 * content-length or transfer-encoding fields.
59 * httpGets() - Get a line of text from a HTTP connection.
60 * httpGetState() - Get the current state of the HTTP request.
61 * httpGetStatus() - Get the status of the last HTTP request.
62 * httpGetSubField() - Get a sub-field value.
63 * httpGetSubField2() - Get a sub-field value.
64 * httpGetVersion() - Get the HTTP version at the other end.
65 * httpHead() - Send a HEAD request to the server.
66 * httpInitialize() - Initialize the HTTP interface library and set
67 * the default HTTP proxy (if any).
68 * httpOptions() - Send an OPTIONS request to the server.
69 * _httpPeek() - Peek at data from a HTTP connection.
70 * httpPost() - Send a POST request to the server.
71 * httpPrintf() - Print a formatted string to a HTTP connection.
72 * httpPut() - Send a PUT request to the server.
73 * httpRead() - Read data from a HTTP connection.
74 * httpRead2() - Read data from a HTTP connection.
75 * _httpReadCDSA() - Read function for the CDSA library.
76 * _httpReadGNUTLS() - Read function for the GNU TLS library.
77 * httpReconnect() - Reconnect to a HTTP server.
78 * httpReconnect2() - Reconnect to a HTTP server with timeout and
80 * httpSetAuthString() - Set the current authorization string.
81 * httpSetCredentials() - Set the credentials associated with an
82 * encrypted connection.
83 * httpSetCookie() - Set the cookie value(s).
84 * httpSetExpect() - Set the Expect: header in a request.
85 * httpSetField() - Set the value of an HTTP header.
86 * httpSetLength() - Set the content-length and content-encoding.
87 * httpSetTimeout() - Set read/write timeouts and an optional
89 * httpTrace() - Send an TRACE request to the server.
90 * _httpUpdate() - Update the current HTTP status for incoming
92 * httpUpdate() - Update the current HTTP state for incoming
94 * _httpWait() - Wait for data available on a connection (no
96 * httpWait() - Wait for data available on a connection.
97 * httpWrite() - Write data to a HTTP connection.
98 * httpWrite2() - Write data to a HTTP connection.
99 * _httpWriteCDSA() - Write function for the CDSA library.
100 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
101 * http_bio_ctrl() - Control the HTTP connection.
102 * http_bio_free() - Free OpenSSL data.
103 * http_bio_new() - Initialize an OpenSSL BIO structure.
104 * http_bio_puts() - Send a string for OpenSSL.
105 * http_bio_read() - Read data for OpenSSL.
106 * http_bio_write() - Write data for OpenSSL.
107 * http_debug_hex() - Do a hex dump of a buffer.
108 * http_field() - Return the field index for a field name.
109 * http_read_ssl() - Read from a SSL/TLS connection.
110 * http_send() - Send a request with all fields and the trailing
112 * http_set_credentials() - Set the SSL/TLS credentials.
113 * http_set_timeout() - Set the socket timeout values.
114 * http_set_wait() - Set the default wait value for reads.
115 * http_setup_ssl() - Set up SSL/TLS support on a connection.
116 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
117 * http_upgrade() - Force upgrade to TLS encryption.
118 * http_write() - Write a buffer to a HTTP connection.
119 * http_write_chunk() - Write a chunked buffer.
120 * http_write_ssl() - Write to a SSL/TLS connection.
124 * Include necessary headers...
127 #include "cups-private.h"
134 # include <sys/time.h>
135 # include <sys/resource.h>
139 #endif /* HAVE_POLL */
147 static void http_debug_hex(const char *prefix
, const char *buffer
,
150 static http_field_t
http_field(const char *name
);
151 static int http_send(http_t
*http
, http_state_t request
,
153 static int http_write(http_t
*http
, const char *buffer
,
155 static int http_write_chunk(http_t
*http
, const char *buffer
,
158 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
159 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
160 static int http_set_credentials(http_t
*http
);
161 # endif /* HAVE_CDSASSL ** HAVE_SECCERTIFICATECOPYDATA */
162 #endif /* HAVE_SSL */
163 static void http_set_timeout(int fd
, double timeout
);
164 static void http_set_wait(http_t
*http
);
166 static int http_setup_ssl(http_t
*http
);
167 static void http_shutdown_ssl(http_t
*http
);
168 static int http_upgrade(http_t
*http
);
169 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
170 #endif /* HAVE_SSL */
177 static const char * const http_fields
[] =
194 "If-Unmodified-since",
208 static const char * const http_states
[] =
228 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
230 * BIO methods for OpenSSL...
233 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
234 static int http_bio_read(BIO
*h
, char *buf
, int size
);
235 static int http_bio_puts(BIO
*h
, const char *str
);
236 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
237 static int http_bio_new(BIO
*h
);
238 static int http_bio_free(BIO
*data
);
240 static BIO_METHOD http_bio_methods
=
247 NULL
, /* http_bio_gets, */
253 #endif /* HAVE_SSL && HAVE_LIBSSL */
257 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
259 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
261 * @since CUPS 1.5/OS X 10.7@
264 int /* O - 0 on success, -1 on error */
266 cups_array_t
*credentials
, /* I - Credentials array */
267 const void *data
, /* I - PEM-encoded X.509 data */
268 size_t datalen
) /* I - Length of data */
270 http_credential_t
*credential
; /* Credential data */
273 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
275 credential
->datalen
= datalen
;
277 if ((credential
->data
= malloc(datalen
)) != NULL
)
279 memcpy(credential
->data
, data
, datalen
);
280 cupsArrayAdd(credentials
, credential
);
291 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
293 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
296 BIO_METHOD
* /* O - BIO methods for OpenSSL */
297 _httpBIOMethods(void)
299 return (&http_bio_methods
);
301 #endif /* HAVE_SSL && HAVE_LIBSSL */
305 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
309 httpBlocking(http_t
*http
, /* I - Connection to server */
310 int b
) /* I - 1 = blocking, 0 = non-blocking */
321 * 'httpCheck()' - Check to see if there is a pending response from the server.
324 int /* O - 0 = no data, 1 = data available */
325 httpCheck(http_t
*http
) /* I - Connection to server */
327 return (httpWait(http
, 0));
332 * 'httpClearCookie()' - Clear the cookie value(s).
334 * @since CUPS 1.1.19/OS X 10.3@
338 httpClearCookie(http_t
*http
) /* I - Connection to server */
352 * 'httpClearFields()' - Clear HTTP request fields.
356 httpClearFields(http_t
*http
) /* I - Connection to server */
360 memset(http
->fields
, 0, sizeof(http
->fields
));
361 if (http
->hostname
[0] == '/')
362 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
364 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
366 if (http
->field_authorization
)
368 free(http
->field_authorization
);
369 http
->field_authorization
= NULL
;
372 http
->expect
= (http_status_t
)0;
378 * 'httpClose()' - Close an HTTP connection.
382 httpClose(http_t
*http
) /* I - Connection to server */
385 OM_uint32 minor_status
; /* Minor status code */
386 #endif /* HAVE_GSSAPI */
389 DEBUG_printf(("httpClose(http=%p)", http
));
392 * Range check input...
399 * Close any open connection...
402 _httpDisconnect(http
);
405 * Free memory used...
408 httpAddrFreeList(http
->addrlist
);
414 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
415 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
417 if (http
->gssname
!= GSS_C_NO_NAME
)
418 gss_release_name(&minor_status
, &http
->gssname
);
419 #endif /* HAVE_GSSAPI */
421 #ifdef HAVE_AUTHORIZATION_H
423 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
424 #endif /* HAVE_AUTHORIZATION_H */
426 httpClearFields(http
);
428 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
429 free(http
->authstring
);
436 * 'httpConnect()' - Connect to a HTTP server.
438 * This function is deprecated - use @link httpConnectEncrypt@ instead.
443 http_t
* /* O - New HTTP connection */
444 httpConnect(const char *host
, /* I - Host to connect to */
445 int port
) /* I - Port number */
447 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
452 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
455 http_t
* /* O - New HTTP connection */
457 const char *host
, /* I - Host to connect to */
458 int port
, /* I - Port number */
459 http_encryption_t encryption
) /* I - Type of encryption to use */
461 http_t
*http
; /* New HTTP connection */
464 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
465 host
, port
, encryption
));
468 * Create the HTTP structure...
471 if ((http
= _httpCreate(host
, port
, NULL
, encryption
, AF_UNSPEC
)) == NULL
)
475 * Connect to the remote system...
478 if (!httpReconnect(http
))
482 * Could not connect to any known address - bail out!
485 httpAddrFreeList(http
->addrlist
);
494 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
497 * @since CUPS 1.5/OS X 10.7@
500 int /* O - Status of call (0 = success) */
502 http_t
*http
, /* I - Connection to server */
503 cups_array_t
**credentials
) /* O - Array of credentials */
506 # elif defined(HAVE_GNUTLS)
507 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
508 OSStatus error
; /* Error code */
509 CFIndex count
; /* Number of credentials */
510 CFArrayRef peerCerts
; /* Peer certificates */
511 SecCertificateRef secCert
; /* Certificate reference */
512 CFDataRef data
; /* Certificate data */
513 int i
; /* Looping var */
514 # elif defined(HAVE_SSPISSL)
515 # endif /* HAVE_LIBSSL */
521 if (!http
|| !http
->tls
|| !credentials
)
527 # elif defined(HAVE_GNUTLS)
530 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
531 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
533 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
535 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
537 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
538 if ((data
= SecCertificateCopyData(secCert
)))
540 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
541 CFDataGetLength(data
));
547 CFRelease(peerCerts
);
552 # elif defined(HAVE_SSPISSL)
557 # endif /* HAVE_LIBSSL */
562 * '_httpCreate()' - Create an unconnected HTTP connection.
565 http_t
* /* O - HTTP connection */
567 const char *host
, /* I - Hostname */
568 int port
, /* I - Port number */
569 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
570 http_encryption_t encryption
, /* I - Encryption to use */
571 int family
) /* I - Address family or AF_UNSPEC */
573 http_t
*http
; /* New HTTP connection */
574 char service
[255]; /* Service name */
577 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
578 host
, port
, encryption
));
589 sprintf(service
, "%d", port
);
592 if ((addrlist
= httpAddrGetList(host
, family
, service
)) == NULL
)
596 * Allocate memory for the structure...
599 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
601 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(errno
), 0);
602 httpAddrFreeList(addrlist
);
607 * Initialize the HTTP data...
610 http
->activity
= time(NULL
);
611 http
->addrlist
= addrlist
;
615 http
->gssctx
= GSS_C_NO_CONTEXT
;
616 http
->gssname
= GSS_C_NO_NAME
;
617 #endif /* HAVE_GSSAPI */
618 http
->version
= HTTP_1_1
;
620 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
622 if (port
== 443) /* Always use encryption for https */
623 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
625 http
->encryption
= encryption
;
630 * Return the new structure...
638 * '_httpCreateCredentials()' - Create credentials in the internal format.
641 http_tls_credentials_t
/* O - Internal credentials */
642 _httpCreateCredentials(
643 cups_array_t
*credentials
) /* I - Array of credentials */
651 # elif defined(HAVE_GNUTLS)
654 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
655 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
656 SecCertificateRef secCert
; /* Certificate reference */
657 CFDataRef data
; /* Credential data reference */
658 http_credential_t
*credential
; /* Credential data */
661 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
662 cupsArrayCount(credentials
),
663 &kCFTypeArrayCallBacks
)) == NULL
)
666 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
668 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
670 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
671 credential
->datalen
)))
673 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
676 CFArrayAppendValue(peerCerts
, secCert
);
686 # elif defined(HAVE_SSPISSL)
691 # endif /* HAVE_LIBSSL */
696 * 'httpDelete()' - Send a DELETE request to the server.
699 int /* O - Status of call (0 = success) */
700 httpDelete(http_t
*http
, /* I - Connection to server */
701 const char *uri
) /* I - URI to delete */
703 return (http_send(http
, HTTP_DELETE
, uri
));
708 * '_httpDisconnect()' - Disconnect a HTTP connection.
712 _httpDisconnect(http_t
*http
) /* I - Connection to server */
716 http_shutdown_ssl(http
);
717 #endif /* HAVE_SSL */
720 closesocket(http
->fd
);
730 * 'httpEncryption()' - Set the required encryption on the link.
733 int /* O - -1 on error, 0 on success */
734 httpEncryption(http_t
*http
, /* I - Connection to server */
735 http_encryption_t e
) /* I - New encryption preference */
737 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
743 http
->encryption
= e
;
745 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
746 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
747 return (httpReconnect(http
));
748 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
749 return (http_upgrade(http
));
753 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
757 #endif /* HAVE_SSL */
762 * 'httpError()' - Get the last error on a connection.
765 int /* O - Error code (errno) value */
766 httpError(http_t
*http
) /* I - Connection to server */
769 return (http
->error
);
776 * 'httpFlush()' - Flush data from a HTTP connection.
780 httpFlush(http_t
*http
) /* I - Connection to server */
782 char buffer
[8192]; /* Junk buffer */
783 int blocking
; /* To block or not to block */
784 http_state_t oldstate
; /* Old state */
787 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
788 http_states
[http
->state
]));
791 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
794 blocking
= http
->blocking
;
798 * Read any data we can...
801 oldstate
= http
->state
;
802 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
805 * Restore blocking and reset the connection if we didn't get all of
806 * the remaining data...
809 http
->blocking
= blocking
;
811 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
814 * Didn't get the data back, so close the current connection.
817 http
->state
= HTTP_WAITING
;
821 http_shutdown_ssl(http
);
822 #endif /* HAVE_SSL */
825 closesocket(http
->fd
);
836 * 'httpFlushWrite()' - Flush data in write buffer.
838 * @since CUPS 1.2/OS X 10.5@
841 int /* O - Bytes written or -1 on error */
842 httpFlushWrite(http_t
*http
) /* I - Connection to server */
844 int bytes
; /* Bytes written */
847 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
849 if (!http
|| !http
->wused
)
851 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
852 "1httpFlushWrite: No connection.");
856 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
857 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
859 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
863 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
870 * '_httpFreeCredentials()' - Free internal credentials.
874 _httpFreeCredentials(
875 http_tls_credentials_t credentials
) /* I - Internal credentials */
883 #elif defined(HAVE_GNUTLS)
886 #elif defined(HAVE_CDSASSL)
887 CFRelease(credentials
);
889 #elif defined(HAVE_SSPISSL)
892 #endif /* HAVE_LIBSSL */
897 * 'httpFreeCredentials()' - Free an array of credentials.
902 cups_array_t
*credentials
) /* I - Array of credentials */
904 http_credential_t
*credential
; /* Credential */
907 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
909 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
911 cupsArrayRemove(credentials
, credential
);
912 free((void *)credential
->data
);
916 cupsArrayDelete(credentials
);
921 * 'httpGet()' - Send a GET request to the server.
924 int /* O - Status of call (0 = success) */
925 httpGet(http_t
*http
, /* I - Connection to server */
926 const char *uri
) /* I - URI to get */
928 return (http_send(http
, HTTP_GET
, uri
));
933 * 'httpGetAuthString()' - Get the current authorization string.
935 * The authorization string is set by cupsDoAuthentication() and
936 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
937 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
940 * @since CUPS 1.3/OS X 10.5@
943 char * /* O - Authorization string */
944 httpGetAuthString(http_t
*http
) /* I - Connection to server */
947 return (http
->authstring
);
954 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
956 * @since CUPS 1.2/OS X 10.5@
959 int /* O - 1 if blocking, 0 if non-blocking */
960 httpGetBlocking(http_t
*http
) /* I - Connection to server */
962 return (http
? http
->blocking
: 0);
967 * 'httpGetCookie()' - Get any cookie data from the response.
969 * @since CUPS 1.1.19/OS X 10.3@
972 const char * /* O - Cookie data or NULL */
973 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
975 return (http
? http
->cookie
: NULL
);
980 * 'httpGetFd()' - Get the file descriptor associated with a connection.
982 * @since CUPS 1.2/OS X 10.5@
985 int /* O - File descriptor or -1 if none */
986 httpGetFd(http_t
*http
) /* I - Connection to server */
988 return (http
? http
->fd
: -1);
993 * 'httpGetField()' - Get a field value from a request/response.
996 const char * /* O - Field value */
997 httpGetField(http_t
*http
, /* I - Connection to server */
998 http_field_t field
) /* I - Field to get */
1000 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1002 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
1003 http
->field_authorization
)
1006 * Special case for WWW-Authenticate: as its contents can be
1007 * longer than HTTP_MAX_VALUE...
1010 return (http
->field_authorization
);
1013 return (http
->fields
[field
]);
1018 * 'httpGetLength()' - Get the amount of data remaining from the
1019 * content-length or transfer-encoding fields.
1021 * This function is deprecated and will not return lengths larger than
1022 * 2^31 - 1; use httpGetLength2() instead.
1027 int /* O - Content length */
1028 httpGetLength(http_t
*http
) /* I - Connection to server */
1031 * Get the read content length and return the 32-bit value.
1036 httpGetLength2(http
);
1038 return (http
->_data_remaining
);
1046 * 'httpGetLength2()' - Get the amount of data remaining from the
1047 * content-length or transfer-encoding fields.
1049 * This function returns the complete content length, even for
1050 * content larger than 2^31 - 1.
1052 * @since CUPS 1.2/OS X 10.5@
1055 off_t
/* O - Content length */
1056 httpGetLength2(http_t
*http
) /* I - Connection to server */
1058 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1059 http_states
[http
->state
]));
1064 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1066 DEBUG_puts("4httpGetLength2: chunked request!");
1068 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1069 http
->data_remaining
= 0;
1073 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1076 * The following is a hack for HTTP servers that don't send a
1077 * content-length or transfer-encoding field...
1079 * If there is no content-length then the connection must close
1080 * after the transfer is complete...
1083 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1086 * Default content length is 0 for errors and 2^31-1 for other
1087 * successful requests...
1090 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
1091 http
->data_remaining
= 0;
1093 http
->data_remaining
= 2147483647;
1096 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1099 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1100 CUPS_LLCAST http
->data_remaining
));
1103 if (http
->data_remaining
<= INT_MAX
)
1104 http
->_data_remaining
= (int)http
->data_remaining
;
1106 http
->_data_remaining
= INT_MAX
;
1108 return (http
->data_remaining
);
1113 * 'httpGets()' - Get a line of text from a HTTP connection.
1116 char * /* O - Line or NULL */
1117 httpGets(char *line
, /* I - Line to read into */
1118 int length
, /* I - Max length of buffer */
1119 http_t
*http
) /* I - Connection to server */
1121 char *lineptr
, /* Pointer into line */
1122 *lineend
, /* End of line */
1123 *bufptr
, /* Pointer into input buffer */
1124 *bufend
; /* Pointer to end of buffer */
1125 int bytes
, /* Number of bytes read */
1126 eol
; /* End-of-line? */
1129 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1131 if (http
== NULL
|| line
== NULL
)
1135 * Read a line from the buffer...
1140 lineend
= line
+ length
- 1;
1143 while (lineptr
< lineend
)
1146 * Pre-load the buffer as needed...
1155 while (http
->used
== 0)
1158 * No newline; see if there is more data to be read...
1161 while (!_httpWait(http
, http
->wait_value
, 1))
1163 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1166 DEBUG_puts("3httpGets: Timed out!");
1168 http
->error
= WSAETIMEDOUT
;
1170 http
->error
= ETIMEDOUT
;
1177 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1178 HTTP_MAX_BUFFER
- http
->used
);
1180 #endif /* HAVE_SSL */
1181 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1182 HTTP_MAX_BUFFER
- http
->used
, 0);
1184 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1187 http_debug_hex("httpGets", http
->buffer
+ http
->used
, bytes
);
1193 * Nope, can't get a line this time...
1197 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1199 if (WSAGetLastError() == WSAEINTR
)
1201 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1203 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1206 http
->error
= WSAGetLastError();
1208 else if (WSAGetLastError() != http
->error
)
1210 http
->error
= WSAGetLastError();
1215 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1219 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1221 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1223 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1226 http
->error
= errno
;
1228 else if (errno
!= http
->error
)
1230 http
->error
= errno
;
1237 else if (bytes
== 0)
1239 http
->error
= EPIPE
;
1245 * Yup, update the amount used...
1248 http
->used
+= bytes
;
1252 * Now copy as much of the current line as possible...
1255 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1256 lineptr
< lineend
&& bufptr
< bufend
;)
1258 if (*bufptr
== 0x0a)
1264 else if (*bufptr
== 0x0d)
1267 *lineptr
++ = *bufptr
++;
1270 http
->used
-= (int)(bufptr
- http
->buffer
);
1272 memmove(http
->buffer
, bufptr
, http
->used
);
1280 http
->activity
= time(NULL
);
1284 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1290 DEBUG_puts("3httpGets: No new line available!");
1297 * 'httpGetState()' - Get the current state of the HTTP request.
1300 http_state_t
/* O - HTTP state */
1301 httpGetState(http_t
*http
) /* I - Connection to server */
1303 return (http
? http
->state
: HTTP_ERROR
);
1308 * 'httpGetStatus()' - Get the status of the last HTTP request.
1310 * @since CUPS 1.2/OS X 10.5@
1313 http_status_t
/* O - HTTP status */
1314 httpGetStatus(http_t
*http
) /* I - Connection to server */
1316 return (http
? http
->status
: HTTP_ERROR
);
1321 * 'httpGetSubField()' - Get a sub-field value.
1326 char * /* O - Value or NULL */
1327 httpGetSubField(http_t
*http
, /* I - Connection to server */
1328 http_field_t field
, /* I - Field index */
1329 const char *name
, /* I - Name of sub-field */
1330 char *value
) /* O - Value string */
1332 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1337 * 'httpGetSubField2()' - Get a sub-field value.
1339 * @since CUPS 1.2/OS X 10.5@
1342 char * /* O - Value or NULL */
1343 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1344 http_field_t field
, /* I - Field index */
1345 const char *name
, /* I - Name of sub-field */
1346 char *value
, /* O - Value string */
1347 int valuelen
) /* I - Size of value buffer */
1349 const char *fptr
; /* Pointer into field */
1350 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1351 *ptr
, /* Pointer into string buffer */
1352 *end
; /* End of value buffer */
1354 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1355 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1357 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1358 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1361 end
= value
+ valuelen
- 1;
1363 for (fptr
= http
->fields
[field
]; *fptr
;)
1366 * Skip leading whitespace...
1369 while (_cups_isspace(*fptr
))
1379 * Get the sub-field name...
1383 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1384 ptr
< (temp
+ sizeof(temp
) - 1);
1389 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1392 * Skip trailing chars up to the '='...
1395 while (_cups_isspace(*fptr
))
1405 * Skip = and leading whitespace...
1410 while (_cups_isspace(*fptr
))
1416 * Read quoted string...
1419 for (ptr
= value
, fptr
++;
1420 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1425 while (*fptr
&& *fptr
!= '\"')
1434 * Read unquoted string...
1438 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1443 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1447 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1450 * See if this is the one...
1453 if (!strcmp(name
, temp
))
1455 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1462 DEBUG_puts("3httpGetSubField2: Returning NULL");
1469 * 'httpGetVersion()' - Get the HTTP version at the other end.
1472 http_version_t
/* O - Version number */
1473 httpGetVersion(http_t
*http
) /* I - Connection to server */
1475 return (http
? http
->version
: HTTP_1_0
);
1480 * 'httpHead()' - Send a HEAD request to the server.
1483 int /* O - Status of call (0 = success) */
1484 httpHead(http_t
*http
, /* I - Connection to server */
1485 const char *uri
) /* I - URI for head */
1487 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1488 return (http_send(http
, HTTP_HEAD
, uri
));
1493 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1494 * default HTTP proxy (if any).
1498 httpInitialize(void)
1500 static int initialized
= 0; /* Have we been called before? */
1502 WSADATA winsockdata
; /* WinSock data */
1505 int i
; /* Looping var */
1506 unsigned char data
[1024]; /* Seed data */
1507 #endif /* HAVE_LIBSSL */
1513 _cupsGlobalUnlock();
1518 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1520 #elif !defined(SO_NOSIGPIPE)
1522 * Ignore SIGPIPE signals...
1526 sigset(SIGPIPE
, SIG_IGN
);
1528 # elif defined(HAVE_SIGACTION)
1529 struct sigaction action
; /* POSIX sigaction data */
1532 memset(&action
, 0, sizeof(action
));
1533 action
.sa_handler
= SIG_IGN
;
1534 sigaction(SIGPIPE
, &action
, NULL
);
1537 signal(SIGPIPE
, SIG_IGN
);
1538 # endif /* !SO_NOSIGPIPE */
1543 * Initialize GNU TLS...
1546 gnutls_global_init();
1548 #elif defined(HAVE_LIBSSL)
1550 * Initialize OpenSSL...
1553 SSL_load_error_strings();
1557 * Using the current time is a dubious random seed, but on some systems
1558 * it is the best we can do (on others, this seed isn't even used...)
1561 CUPS_SRAND(time(NULL
));
1563 for (i
= 0; i
< sizeof(data
); i
++)
1564 data
[i
] = CUPS_RAND();
1566 RAND_seed(data
, sizeof(data
));
1567 #endif /* HAVE_GNUTLS */
1570 _cupsGlobalUnlock();
1575 * 'httpOptions()' - Send an OPTIONS request to the server.
1578 int /* O - Status of call (0 = success) */
1579 httpOptions(http_t
*http
, /* I - Connection to server */
1580 const char *uri
) /* I - URI for options */
1582 return (http_send(http
, HTTP_OPTIONS
, uri
));
1587 * '_httpPeek()' - Peek at data from a HTTP connection.
1589 * This function copies available data from the given HTTP connection, reading
1590 * a buffer as needed. The data is still available for reading using
1591 * @link httpRead@ or @link httpRead2@.
1593 * For non-blocking connections the usual timeouts apply.
1596 ssize_t
/* O - Number of bytes copied */
1597 _httpPeek(http_t
*http
, /* I - Connection to server */
1598 char *buffer
, /* I - Buffer for data */
1599 size_t length
) /* I - Maximum number of bytes */
1601 ssize_t bytes
; /* Bytes read */
1602 char len
[32]; /* Length string */
1605 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1606 http
, buffer
, CUPS_LLCAST length
));
1608 if (http
== NULL
|| buffer
== NULL
)
1611 http
->activity
= time(NULL
);
1617 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1618 http
->data_remaining
<= 0)
1620 DEBUG_puts("2_httpPeek: Getting chunk length...");
1622 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1624 DEBUG_puts("1_httpPeek: Could not get length!");
1628 http
->data_remaining
= strtoll(len
, NULL
, 16);
1629 if (http
->data_remaining
< 0)
1631 DEBUG_puts("1_httpPeek: Negative chunk length!");
1636 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1637 CUPS_LLCAST http
->data_remaining
));
1639 if (http
->data_remaining
<= 0)
1642 * A zero-length chunk ends a transfer; unless we are reading POST
1646 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1647 httpGets(len
, sizeof(len
), http
);
1649 if (http
->state
== HTTP_POST_RECV
)
1652 http
->state
= HTTP_WAITING
;
1655 * Prevent future reads for this request...
1658 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1662 else if (length
> (size_t)http
->data_remaining
)
1663 length
= (size_t)http
->data_remaining
;
1665 if (http
->used
== 0)
1668 * Buffer small reads for better performance...
1671 ssize_t buflen
; /* Length of read for buffer */
1673 if (!http
->blocking
)
1675 while (!httpWait(http
, http
->wait_value
))
1677 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1684 if (http
->data_remaining
> sizeof(http
->buffer
))
1685 buflen
= sizeof(http
->buffer
);
1687 buflen
= http
->data_remaining
;
1689 DEBUG_printf(("2_httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1695 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
1697 #endif /* HAVE_SSL */
1698 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
1703 if (WSAGetLastError() != WSAEINTR
)
1705 http
->error
= WSAGetLastError();
1708 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1710 if (!http
->timeout_cb
||
1711 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1713 http
->error
= WSAEWOULDBLOCK
;
1718 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1720 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1722 http
->error
= errno
;
1725 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1727 http
->error
= errno
;
1731 else if (errno
!= EINTR
)
1733 http
->error
= errno
;
1741 DEBUG_printf(("2_httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1742 CUPS_LLCAST bytes
));
1744 http_debug_hex("_httpPeek", http
->buffer
, (int)bytes
);
1752 if (length
> (size_t)http
->used
)
1753 length
= (size_t)http
->used
;
1755 bytes
= (ssize_t
)length
;
1757 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1760 memcpy(buffer
, http
->buffer
, length
);
1768 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1771 http
->error
= WSAGetLastError();
1773 if (errno
== EINTR
|| errno
== EAGAIN
)
1776 http
->error
= errno
;
1779 else if (bytes
== 0)
1781 http
->error
= EPIPE
;
1786 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1794 * 'httpPost()' - Send a POST request to the server.
1797 int /* O - Status of call (0 = success) */
1798 httpPost(http_t
*http
, /* I - Connection to server */
1799 const char *uri
) /* I - URI for post */
1801 return (http_send(http
, HTTP_POST
, uri
));
1806 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1811 int /* O - Number of bytes written */
1812 httpPrintf(http_t
*http
, /* I - Connection to server */
1813 const char *format
, /* I - printf-style format string */
1814 ...) /* I - Additional args as needed */
1816 int bytes
; /* Number of bytes to write */
1817 char buf
[16384]; /* Buffer for formatted string */
1818 va_list ap
; /* Variable argument pointer */
1821 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1823 va_start(ap
, format
);
1824 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1827 DEBUG_printf(("3httpPrintf: %s", buf
));
1829 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1830 return (httpWrite2(http
, buf
, bytes
));
1835 DEBUG_puts("4httpPrintf: flushing existing data...");
1837 if (httpFlushWrite(http
) < 0)
1841 return (http_write(http
, buf
, bytes
));
1847 * 'httpPut()' - Send a PUT request to the server.
1850 int /* O - Status of call (0 = success) */
1851 httpPut(http_t
*http
, /* I - Connection to server */
1852 const char *uri
) /* I - URI to put */
1854 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1855 return (http_send(http
, HTTP_PUT
, uri
));
1860 * 'httpRead()' - Read data from a HTTP connection.
1862 * This function is deprecated. Use the httpRead2() function which can
1863 * read more than 2GB of data.
1868 int /* O - Number of bytes read */
1869 httpRead(http_t
*http
, /* I - Connection to server */
1870 char *buffer
, /* I - Buffer for data */
1871 int length
) /* I - Maximum number of bytes */
1873 return ((int)httpRead2(http
, buffer
, length
));
1878 * 'httpRead2()' - Read data from a HTTP connection.
1880 * @since CUPS 1.2/OS X 10.5@
1883 ssize_t
/* O - Number of bytes read */
1884 httpRead2(http_t
*http
, /* I - Connection to server */
1885 char *buffer
, /* I - Buffer for data */
1886 size_t length
) /* I - Maximum number of bytes */
1888 ssize_t bytes
; /* Bytes read */
1889 char len
[32]; /* Length string */
1892 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1893 http
, buffer
, CUPS_LLCAST length
));
1895 if (http
== NULL
|| buffer
== NULL
)
1898 http
->activity
= time(NULL
);
1904 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1905 http
->data_remaining
<= 0)
1907 DEBUG_puts("2httpRead2: Getting chunk length...");
1909 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1911 DEBUG_puts("1httpRead2: Could not get length!");
1915 http
->data_remaining
= strtoll(len
, NULL
, 16);
1916 if (http
->data_remaining
< 0)
1918 DEBUG_puts("1httpRead2: Negative chunk length!");
1923 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1924 CUPS_LLCAST http
->data_remaining
));
1926 if (http
->data_remaining
<= 0)
1929 * A zero-length chunk ends a transfer; unless we are reading POST
1933 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1934 httpGets(len
, sizeof(len
), http
);
1936 if (http
->state
== HTTP_POST_RECV
)
1939 http
->state
= HTTP_WAITING
;
1942 * Prevent future reads for this request...
1945 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1949 else if (length
> (size_t)http
->data_remaining
)
1950 length
= (size_t)http
->data_remaining
;
1952 if (http
->used
== 0 && length
<= 256)
1955 * Buffer small reads for better performance...
1958 ssize_t buflen
; /* Length of read for buffer */
1960 if (!http
->blocking
)
1962 while (!httpWait(http
, http
->wait_value
))
1964 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1971 if (http
->data_remaining
> sizeof(http
->buffer
))
1972 buflen
= sizeof(http
->buffer
);
1974 buflen
= http
->data_remaining
;
1976 DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen
));
1982 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
1984 #endif /* HAVE_SSL */
1985 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
1990 if (WSAGetLastError() != WSAEINTR
)
1992 http
->error
= WSAGetLastError();
1995 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1997 if (!http
->timeout_cb
||
1998 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2000 http
->error
= WSAEWOULDBLOCK
;
2005 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2007 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2009 http
->error
= errno
;
2012 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2014 http
->error
= errno
;
2018 else if (errno
!= EINTR
)
2020 http
->error
= errno
;
2028 DEBUG_printf(("2httpRead2: Read " CUPS_LLFMT
" bytes into buffer.",
2029 CUPS_LLCAST bytes
));
2031 http_debug_hex("httpRead2", http
->buffer
, (int)bytes
);
2039 if (length
> (size_t)http
->used
)
2040 length
= (size_t)http
->used
;
2042 bytes
= (ssize_t
)length
;
2044 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2047 memcpy(buffer
, http
->buffer
, length
);
2048 http
->used
-= (int)length
;
2051 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2056 if (!http
->blocking
)
2058 while (!httpWait(http
, http
->wait_value
))
2060 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2067 while ((bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
)) < 0)
2070 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2072 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2075 else if (WSAGetLastError() != WSAEINTR
)
2078 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2080 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2082 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2085 else if (errno
!= EINTR
)
2090 #endif /* HAVE_SSL */
2093 if (!http
->blocking
)
2095 while (!httpWait(http
, http
->wait_value
))
2097 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2104 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2105 CUPS_LLCAST length
));
2108 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2110 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2112 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2115 else if (WSAGetLastError() != WSAEINTR
)
2119 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2121 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2123 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2125 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2128 else if (errno
!= EINTR
)
2133 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2134 CUPS_LLCAST bytes
));
2136 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2142 http
->data_remaining
-= bytes
;
2144 if (http
->data_remaining
<= INT_MAX
)
2145 http
->_data_remaining
= (int)http
->data_remaining
;
2147 http
->_data_remaining
= INT_MAX
;
2152 if (WSAGetLastError() == WSAEINTR
)
2155 http
->error
= WSAGetLastError();
2157 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2160 http
->error
= errno
;
2165 http
->error
= EPIPE
;
2169 if (http
->data_remaining
== 0)
2171 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2172 httpGets(len
, sizeof(len
), http
);
2173 else if (http
->state
== HTTP_POST_RECV
)
2176 http
->state
= HTTP_WAITING
;
2183 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2185 * '_httpReadCDSA()' - Read function for the CDSA library.
2188 OSStatus
/* O - -1 on error, 0 on success */
2190 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2191 void *data
, /* I - Data buffer */
2192 size_t *dataLength
) /* IO - Number of bytes */
2194 OSStatus result
; /* Return value */
2195 ssize_t bytes
; /* Number of bytes read */
2196 http_t
*http
; /* HTTP connection */
2199 http
= (http_t
*)connection
;
2201 if (!http
->blocking
)
2204 * Make sure we have data before we read...
2207 while (!_httpWait(http
, http
->wait_value
, 0))
2209 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2212 http
->error
= ETIMEDOUT
;
2219 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2221 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2223 if (bytes
== *dataLength
)
2229 *dataLength
= bytes
;
2230 result
= errSSLWouldBlock
;
2237 result
= errSSLClosedGraceful
;
2238 else if (errno
== EAGAIN
)
2239 result
= errSSLWouldBlock
;
2241 result
= errSSLClosedAbort
;
2246 #endif /* HAVE_SSL && HAVE_CDSASSL */
2249 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2251 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2254 ssize_t
/* O - Number of bytes read or -1 on error */
2256 gnutls_transport_ptr ptr
, /* I - Connection to server */
2257 void *data
, /* I - Buffer */
2258 size_t length
) /* I - Number of bytes to read */
2260 http_t
*http
; /* HTTP connection */
2261 ssize_t bytes
; /* Bytes read */
2264 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2266 http
= (http_t
*)ptr
;
2268 if (!http
->blocking
)
2271 * Make sure we have data before we read...
2274 while (!_httpWait(http
, http
->wait_value
, 0))
2276 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2279 http
->error
= ETIMEDOUT
;
2284 bytes
= recv(http
->fd
, data
, length
, 0);
2285 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2288 #endif /* HAVE_SSL && HAVE_GNUTLS */
2292 * 'httpReconnect()' - Reconnect to a HTTP server.
2295 int /* O - 0 on success, non-zero on failure */
2296 httpReconnect(http_t
*http
) /* I - Connection to server */
2298 DEBUG_printf(("httpReconnect(http=%p)", http
));
2300 return (httpReconnect2(http
, 30000, NULL
));
2305 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2309 int /* O - 0 on success, non-zero on failure */
2310 httpReconnect2(http_t
*http
, /* I - Connection to server */
2311 int msec
, /* I - Timeout in milliseconds */
2312 int *cancel
) /* I - Pointer to "cancel" variable */
2314 http_addrlist_t
*addr
; /* Connected address */
2316 http_addrlist_t
*current
; /* Current address */
2317 char temp
[256]; /* Temporary address string */
2321 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2326 _cupsSetError(IPP_INTERNAL_ERROR
, strerror(EINVAL
), 0);
2333 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2334 http_shutdown_ssl(http
);
2336 #endif /* HAVE_SSL */
2339 * Close any previously open socket...
2344 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2347 closesocket(http
->fd
);
2356 * Reset all state (except fields, which may be reused)...
2359 http
->state
= HTTP_WAITING
;
2360 http
->status
= HTTP_CONTINUE
;
2361 http
->version
= HTTP_1_1
;
2362 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2363 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2364 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2365 http
->_data_remaining
= 0;
2368 http
->data_remaining
= 0;
2369 http
->hostaddr
= NULL
;
2373 * Connect to the server...
2377 for (current
= http
->addrlist
; current
; current
= current
->next
)
2378 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2379 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2380 _httpAddrPort(&(current
->addr
))));
2383 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2387 * Unable to connect...
2391 http
->error
= WSAGetLastError();
2393 http
->error
= errno
;
2395 http
->status
= HTTP_ERROR
;
2397 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2398 strerror(http
->error
)));
2403 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2405 if (http
->timeout_value
> 0)
2406 http_set_timeout(http
->fd
, http
->timeout_value
);
2408 http
->hostaddr
= &(addr
->addr
);
2412 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2415 * Always do encryption via SSL.
2418 if (http_setup_ssl(http
) != 0)
2421 closesocket(http
->fd
);
2429 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2430 return (http_upgrade(http
));
2431 #endif /* HAVE_SSL */
2433 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2434 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2435 _httpAddrPort(http
->hostaddr
)));
2442 * 'httpSetAuthString()' - Set the current authorization string.
2444 * This function just stores a copy of the current authorization string in
2445 * the HTTP connection object. You must still call httpSetField() to set
2446 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2447 * httpHead(), httpOptions(), httpPost, or httpPut().
2449 * @since CUPS 1.3/OS X 10.5@
2453 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2454 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2455 const char *data
) /* I - Auth data (NULL for none) */
2458 * Range check input...
2464 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2465 free(http
->authstring
);
2467 http
->authstring
= http
->_authstring
;
2472 * Set the current authorization string...
2475 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2478 if (len
> (int)sizeof(http
->_authstring
))
2480 if ((temp
= malloc(len
)) == NULL
)
2481 len
= sizeof(http
->_authstring
);
2483 http
->authstring
= temp
;
2487 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2489 strlcpy(http
->authstring
, scheme
, len
);
2494 * Clear the current authorization string...
2497 http
->_authstring
[0] = '\0';
2503 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2506 * @since CUPS 1.5/OS X 10.7@
2509 int /* O - Status of call (0 = success) */
2510 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2511 cups_array_t
*credentials
) /* I - Array of credentials */
2513 if (!http
|| cupsArrayCount(credentials
) < 1)
2516 _httpFreeCredentials(http
->tls_credentials
);
2518 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2520 return (http
->tls_credentials
? 0 : -1);
2525 * 'httpSetCookie()' - Set the cookie value(s).
2527 * @since CUPS 1.1.19/OS X 10.3@
2531 httpSetCookie(http_t
*http
, /* I - Connection */
2532 const char *cookie
) /* I - Cookie string */
2541 http
->cookie
= strdup(cookie
);
2543 http
->cookie
= NULL
;
2548 * 'httpSetExpect()' - Set the Expect: header in a request.
2550 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2552 * @since CUPS 1.2/OS X 10.5@
2556 httpSetExpect(http_t
*http
, /* I - Connection to server */
2557 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2560 http
->expect
= expect
;
2565 * 'httpSetField()' - Set the value of an HTTP header.
2569 httpSetField(http_t
*http
, /* I - Connection to server */
2570 http_field_t field
, /* I - Field index */
2571 const char *value
) /* I - Value */
2574 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2575 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2579 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2581 if (field
== HTTP_FIELD_AUTHORIZATION
)
2584 * Special case for Authorization: as its contents can be
2585 * longer than HTTP_MAX_VALUE
2588 if (http
->field_authorization
)
2589 free(http
->field_authorization
);
2591 http
->field_authorization
= strdup(value
);
2593 else if (field
== HTTP_FIELD_HOST
)
2596 * Special-case for Host: as we don't want a trailing "." on the hostname and
2597 * need to bracket IPv6 numeric addresses.
2600 char *ptr
= strchr(value
, ':');
2602 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2605 * Bracket IPv6 numeric addresses...
2607 * This is slightly inefficient (basically copying twice), but is an edge
2608 * case and not worth optimizing...
2611 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2612 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2617 * Check for a trailing dot on the hostname...
2620 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2624 ptr
+= strlen(ptr
) - 1;
2635 * 'httpSetLength()' - Set the content-length and content-encoding.
2637 * @since CUPS 1.2/OS X 10.5@
2641 httpSetLength(http_t
*http
, /* I - Connection to server */
2642 size_t length
) /* I - Length (0 for chunked) */
2649 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
2651 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2655 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2656 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2657 CUPS_LLFMT
, CUPS_LLCAST length
);
2663 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2665 * The optional timeout callback receives both the HTTP connection and a user
2666 * data pointer and must return 1 to continue or 0 to error (time) out.
2668 * @since CUPS 1.5/OS X 10.7@
2673 http_t
*http
, /* I - Connection to server */
2674 double timeout
, /* I - Number of seconds for timeout,
2675 must be greater than 0 */
2676 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2677 void *user_data
) /* I - User data pointer */
2679 if (!http
|| timeout
<= 0.0)
2682 http
->timeout_cb
= cb
;
2683 http
->timeout_data
= user_data
;
2684 http
->timeout_value
= timeout
;
2687 http_set_timeout(http
->fd
, timeout
);
2689 http_set_wait(http
);
2694 * 'httpTrace()' - Send an TRACE request to the server.
2697 int /* O - Status of call (0 = success) */
2698 httpTrace(http_t
*http
, /* I - Connection to server */
2699 const char *uri
) /* I - URI for trace */
2701 return (http_send(http
, HTTP_TRACE
, uri
));
2706 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2708 * Note: Unlike httpUpdate(), this function does not flush pending write data
2709 * and only retrieves a single status line from the HTTP connection.
2712 int /* O - 1 to continue, 0 to stop */
2713 _httpUpdate(http_t
*http
, /* I - Connection to server */
2714 http_status_t
*status
) /* O - Current HTTP status */
2716 char line
[32768], /* Line from connection... */
2717 *value
; /* Pointer to value on line */
2718 http_field_t field
; /* Field index */
2719 int major
, minor
; /* HTTP version numbers */
2722 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2723 http_states
[http
->state
]));
2726 * Grab a single line from the connection...
2729 if (!httpGets(line
, sizeof(line
), http
))
2731 *status
= HTTP_ERROR
;
2735 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2737 if (line
[0] == '\0')
2740 * Blank line means the start of the data section (if any). Return
2741 * the result code, too...
2743 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2744 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2748 if (http
->status
== HTTP_CONTINUE
)
2750 *status
= http
->status
;
2754 if (http
->status
< HTTP_BAD_REQUEST
)
2755 http
->digest_tries
= 0;
2758 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2760 if (http_setup_ssl(http
) != 0)
2763 closesocket(http
->fd
);
2768 *status
= http
->status
= HTTP_ERROR
;
2772 *status
= HTTP_CONTINUE
;
2775 #endif /* HAVE_SSL */
2777 httpGetLength2(http
);
2779 switch (http
->state
)
2783 case HTTP_POST_RECV
:
2786 case HTTP_POST_SEND
:
2791 http
->state
= HTTP_WAITING
;
2795 *status
= http
->status
;
2798 else if (!strncmp(line
, "HTTP/", 5))
2801 * Got the beginning of a response...
2804 int intstatus
; /* Status value as an integer */
2806 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2808 *status
= http
->status
= HTTP_ERROR
;
2812 http
->version
= (http_version_t
)(major
* 100 + minor
);
2813 *status
= http
->status
= (http_status_t
)intstatus
;
2815 else if ((value
= strchr(line
, ':')) != NULL
)
2822 while (_cups_isspace(*value
))
2826 * Be tolerants of servers that send unknown attribute fields...
2829 if (!_cups_strcasecmp(line
, "expect"))
2832 * "Expect: 100-continue" or similar...
2835 http
->expect
= (http_status_t
)atoi(value
);
2837 else if (!_cups_strcasecmp(line
, "cookie"))
2840 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2843 httpSetCookie(http
, value
);
2845 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
2846 httpSetField(http
, field
, value
);
2849 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
2854 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
2855 *status
= http
->status
= HTTP_ERROR
;
2864 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2867 http_status_t
/* O - HTTP status */
2868 httpUpdate(http_t
*http
) /* I - Connection to server */
2870 http_status_t status
; /* Request status */
2873 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2874 http_states
[http
->state
]));
2877 * Flush pending data, if any...
2882 DEBUG_puts("2httpUpdate: flushing buffer...");
2884 if (httpFlushWrite(http
) < 0)
2885 return (HTTP_ERROR
);
2889 * If we haven't issued any commands, then there is nothing to "update"...
2892 if (http
->state
== HTTP_WAITING
)
2893 return (HTTP_CONTINUE
);
2896 * Grab all of the lines we can from the connection...
2899 while (_httpUpdate(http
, &status
));
2902 * See if there was an error...
2905 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2907 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2908 return (http
->status
);
2913 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2914 strerror(http
->error
)));
2915 http
->status
= HTTP_ERROR
;
2916 return (HTTP_ERROR
);
2920 * Return the current status...
2928 * '_httpWait()' - Wait for data available on a connection (no flush).
2931 int /* O - 1 if data is available, 0 otherwise */
2932 _httpWait(http_t
*http
, /* I - Connection to server */
2933 int msec
, /* I - Milliseconds to wait */
2934 int usessl
) /* I - Use SSL context? */
2937 struct pollfd pfd
; /* Polled file descriptor */
2939 fd_set input_set
; /* select() input set */
2940 struct timeval timeout
; /* Timeout */
2941 #endif /* HAVE_POLL */
2942 int nfds
; /* Result from select()/poll() */
2945 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2949 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2954 * Check the SSL/TLS buffers for data first...
2958 if (http
->tls
&& usessl
)
2961 if (SSL_pending(http
->tls
))
2963 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2967 # elif defined(HAVE_GNUTLS)
2968 if (gnutls_record_check_pending(http
->tls
))
2970 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2974 # elif defined(HAVE_CDSASSL)
2975 size_t bytes
; /* Bytes that are available */
2977 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2980 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2983 # endif /* HAVE_LIBSSL */
2985 #endif /* HAVE_SSL */
2988 * Then try doing a select() or poll() to poll the socket...
2993 pfd
.events
= POLLIN
;
2997 nfds
= poll(&pfd
, 1, msec
);
2999 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3004 FD_ZERO(&input_set
);
3005 FD_SET(http
->fd
, &input_set
);
3007 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3011 timeout
.tv_sec
= msec
/ 1000;
3012 timeout
.tv_usec
= (msec
% 1000) * 1000;
3014 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3017 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3019 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3022 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3023 WSAGetLastError() == WSAEWOULDBLOCK
));
3025 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3027 #endif /* HAVE_POLL */
3029 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3037 * 'httpWait()' - Wait for data available on a connection.
3039 * @since CUPS 1.1.19/OS X 10.3@
3042 int /* O - 1 if data is available, 0 otherwise */
3043 httpWait(http_t
*http
, /* I - Connection to server */
3044 int msec
) /* I - Milliseconds to wait */
3047 * First see if there is data in the buffer...
3050 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3057 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3062 * Flush pending data, if any...
3067 DEBUG_puts("3httpWait: Flushing write buffer.");
3069 if (httpFlushWrite(http
) < 0)
3074 * If not, check the SSL/TLS buffers and do a select() on the connection...
3077 return (_httpWait(http
, msec
, 1));
3082 * 'httpWrite()' - Write data to a HTTP connection.
3084 * This function is deprecated. Use the httpWrite2() function which can
3085 * write more than 2GB of data.
3090 int /* O - Number of bytes written */
3091 httpWrite(http_t
*http
, /* I - Connection to server */
3092 const char *buffer
, /* I - Buffer for data */
3093 int length
) /* I - Number of bytes to write */
3095 return ((int)httpWrite2(http
, buffer
, length
));
3100 * 'httpWrite2()' - Write data to a HTTP connection.
3102 * @since CUPS 1.2/OS X 10.5@
3105 ssize_t
/* O - Number of bytes written */
3106 httpWrite2(http_t
*http
, /* I - Connection to server */
3107 const char *buffer
, /* I - Buffer for data */
3108 size_t length
) /* I - Number of bytes to write */
3110 ssize_t bytes
; /* Bytes written */
3113 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3114 buffer
, CUPS_LLCAST length
));
3117 * Range check input...
3120 if (http
== NULL
|| buffer
== NULL
)
3124 * Mark activity on the connection...
3127 http
->activity
= time(NULL
);
3130 * Buffer small writes for better performance...
3135 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3137 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3138 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3140 httpFlushWrite(http
);
3143 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3144 length
< sizeof(http
->wbuffer
))
3147 * Write to buffer...
3150 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3151 CUPS_LLCAST length
));
3153 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3154 http
->wused
+= (int)length
;
3155 bytes
= (ssize_t
)length
;
3160 * Otherwise write the data directly...
3163 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3164 CUPS_LLCAST length
));
3166 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3167 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3169 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3171 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3172 CUPS_LLCAST bytes
));
3175 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3176 http
->data_remaining
-= bytes
;
3182 * Handle end-of-request processing...
3185 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3186 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3189 * Finished with the transfer; unless we are sending POST or PUT
3193 DEBUG_puts("2httpWrite: changing states...");
3196 httpFlushWrite(http
);
3198 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3201 * Send a 0-length chunk at the end of the request...
3204 http_write(http
, "0\r\n\r\n", 5);
3207 * Reset the data state...
3210 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3211 http
->data_remaining
= 0;
3219 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3221 * '_httpWriteCDSA()' - Write function for the CDSA library.
3224 OSStatus
/* O - -1 on error, 0 on success */
3226 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3227 const void *data
, /* I - Data buffer */
3228 size_t *dataLength
) /* IO - Number of bytes */
3230 OSStatus result
; /* Return value */
3231 ssize_t bytes
; /* Number of bytes read */
3232 http_t
*http
; /* HTTP connection */
3235 http
= (http_t
*)connection
;
3239 bytes
= write(http
->fd
, data
, *dataLength
);
3241 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3243 if (bytes
== *dataLength
)
3247 else if (bytes
>= 0)
3249 *dataLength
= bytes
;
3250 result
= errSSLWouldBlock
;
3256 if (errno
== EAGAIN
)
3257 result
= errSSLWouldBlock
;
3259 result
= errSSLClosedAbort
;
3264 #endif /* HAVE_SSL && HAVE_CDSASSL */
3267 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3269 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3272 ssize_t
/* O - Number of bytes written or -1 on error */
3274 gnutls_transport_ptr ptr
, /* I - Connection to server */
3275 const void *data
, /* I - Data buffer */
3276 size_t length
) /* I - Number of bytes to write */
3278 ssize_t bytes
; /* Bytes written */
3281 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3284 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3287 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3288 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3292 #endif /* HAVE_SSL && HAVE_GNUTLS */
3295 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3297 * 'http_bio_ctrl()' - Control the HTTP connection.
3300 static long /* O - Result/data */
3301 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3302 int cmd
, /* I - Control command */
3303 long arg1
, /* I - First argument */
3304 void *arg2
) /* I - Second argument */
3311 case BIO_CTRL_RESET
:
3315 case BIO_C_SET_FILE_PTR
:
3320 case BIO_C_GET_FILE_PTR
:
3323 *((void **)arg2
) = h
->ptr
;
3330 case BIO_CTRL_FLUSH
:
3337 * 'http_bio_free()' - Free OpenSSL data.
3340 static int /* O - 1 on success, 0 on failure */
3341 http_bio_free(BIO
*h
) /* I - BIO data */
3357 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3360 static int /* O - 1 on success, 0 on failure */
3361 http_bio_new(BIO
*h
) /* I - BIO data */
3376 * 'http_bio_puts()' - Send a string for OpenSSL.
3379 static int /* O - Bytes written */
3380 http_bio_puts(BIO
*h
, /* I - BIO data */
3381 const char *str
) /* I - String to write */
3384 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3386 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3392 * 'http_bio_read()' - Read data for OpenSSL.
3395 static int /* O - Bytes read */
3396 http_bio_read(BIO
*h
, /* I - BIO data */
3397 char *buf
, /* I - Buffer */
3398 int size
) /* I - Number of bytes to read */
3400 http_t
*http
; /* HTTP connection */
3403 http
= (http_t
*)h
->ptr
;
3405 if (!http
->blocking
)
3408 * Make sure we have data before we read...
3411 while (!_httpWait(http
, http
->wait_value
, 0))
3413 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
3417 http
->error
= WSAETIMEDOUT
;
3419 http
->error
= ETIMEDOUT
;
3426 return (recv(http
->fd
, buf
, size
, 0));
3431 * 'http_bio_write()' - Write data for OpenSSL.
3434 static int /* O - Bytes written */
3435 http_bio_write(BIO
*h
, /* I - BIO data */
3436 const char *buf
, /* I - Buffer to write */
3437 int num
) /* I - Number of bytes to write */
3439 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3441 #endif /* HAVE_SSL && HAVE_LIBSSL */
3446 * 'http_debug_hex()' - Do a hex dump of a buffer.
3450 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3451 const char *buffer
, /* I - Buffer to dump */
3452 int bytes
) /* I - Bytes to dump */
3454 int i
, j
, /* Looping vars */
3455 ch
; /* Current character */
3456 char line
[255], /* Line buffer */
3457 *start
, /* Start of line after prefix */
3458 *ptr
; /* Pointer into line */
3461 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3464 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
3466 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3467 start
= line
+ strlen(line
);
3469 for (i
= 0; i
< bytes
; i
+= 16)
3471 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3472 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3476 memcpy(ptr
, " ", 3);
3481 memcpy(ptr
, " ", 3);
3484 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3486 ch
= buffer
[i
+ j
] & 255;
3488 if (ch
< ' ' || ch
>= 127)
3502 * 'http_field()' - Return the field index for a field name.
3505 static http_field_t
/* O - Field index */
3506 http_field(const char *name
) /* I - String name */
3508 int i
; /* Looping var */
3511 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3512 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
3513 return ((http_field_t
)i
);
3515 return (HTTP_FIELD_UNKNOWN
);
3521 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3524 static int /* O - Bytes read */
3525 http_read_ssl(http_t
*http
, /* I - Connection to server */
3526 char *buf
, /* I - Buffer to store data */
3527 int len
) /* I - Length of buffer */
3529 # if defined(HAVE_LIBSSL)
3530 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3532 # elif defined(HAVE_GNUTLS)
3533 ssize_t result
; /* Return value */
3536 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3538 if (result
< 0 && !errno
)
3541 * Convert GNU TLS error to errno value...
3546 case GNUTLS_E_INTERRUPTED
:
3550 case GNUTLS_E_AGAIN
:
3562 return ((int)result
);
3564 # elif defined(HAVE_CDSASSL)
3565 int result
; /* Return value */
3566 OSStatus error
; /* Error info */
3567 size_t processed
; /* Number of bytes processed */
3570 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3571 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
3576 result
= (int)processed
;
3579 case errSSLWouldBlock
:
3581 result
= (int)processed
;
3589 case errSSLClosedGraceful
:
3592 result
= (int)processed
;
3603 # elif defined(HAVE_SSPISSL)
3604 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3605 # endif /* HAVE_LIBSSL */
3607 #endif /* HAVE_SSL */
3611 * 'http_send()' - Send a request with all fields and the trailing blank line.
3614 static int /* O - 0 on success, non-zero on error */
3615 http_send(http_t
*http
, /* I - Connection to server */
3616 http_state_t request
, /* I - Request code */
3617 const char *uri
) /* I - URI */
3619 int i
; /* Looping var */
3620 char buf
[1024]; /* Encoded URI buffer */
3621 static const char * const codes
[] =
3622 { /* Request code strings */
3639 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3640 http
, codes
[request
], uri
));
3642 if (http
== NULL
|| uri
== NULL
)
3646 * Set the User-Agent field if it isn't already...
3649 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3650 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3653 * Encode the URI as needed...
3656 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3659 * See if we had an error the last time around; if so, reconnect...
3662 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3663 if (httpReconnect(http
))
3667 * Flush any written data that is pending...
3672 if (httpFlushWrite(http
) < 0)
3673 if (httpReconnect(http
))
3678 * Send the request header...
3681 http
->state
= request
;
3682 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3684 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3687 http
->status
= HTTP_CONTINUE
;
3690 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3692 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3693 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3695 #endif /* HAVE_SSL */
3697 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3699 http
->status
= HTTP_ERROR
;
3703 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3704 if (http
->fields
[i
][0] != '\0')
3706 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3707 httpGetField(http
, i
)));
3709 if (i
== HTTP_FIELD_HOST
)
3711 if (httpPrintf(http
, "Host: %s:%d\r\n", httpGetField(http
, i
),
3712 _httpAddrPort(http
->hostaddr
)) < 1)
3714 http
->status
= HTTP_ERROR
;
3718 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3719 httpGetField(http
, i
)) < 1)
3721 http
->status
= HTTP_ERROR
;
3727 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3729 http
->status
= HTTP_ERROR
;
3733 if (http
->expect
== HTTP_CONTINUE
&&
3734 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3735 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3737 http
->status
= HTTP_ERROR
;
3741 if (httpPrintf(http
, "\r\n") < 1)
3743 http
->status
= HTTP_ERROR
;
3747 if (httpFlushWrite(http
) < 0)
3750 httpGetLength2(http
);
3751 httpClearFields(http
);
3754 * The Kerberos and AuthRef authentication strings can only be used once...
3757 if (http
->field_authorization
&& http
->authstring
&&
3758 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3759 !strncmp(http
->authstring
, "AuthRef", 7)))
3761 http
->_authstring
[0] = '\0';
3763 if (http
->authstring
!= http
->_authstring
)
3764 free(http
->authstring
);
3766 http
->authstring
= http
->_authstring
;
3774 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
3776 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3779 static int /* O - Status of connection */
3780 http_set_credentials(http_t
*http
) /* I - Connection to server */
3782 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3783 OSStatus error
= 0; /* Error code */
3784 http_tls_credentials_t credentials
= NULL
;
3785 /* TLS credentials */
3788 DEBUG_printf(("7http_set_credentials(%p)", http
));
3791 * Prefer connection specific credentials...
3794 if ((credentials
= http
->tls_credentials
) == NULL
)
3795 credentials
= cg
->tls_credentials
;
3797 # if HAVE_SECPOLICYCREATESSL
3799 * Otherwise root around in the user's keychain to see if one can be found...
3804 CFDictionaryRef query
; /* Query dictionary */
3805 CFTypeRef matches
= NULL
; /* Matching credentials */
3806 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3807 CFTypeRef keys
[] = { kSecClass
,
3810 /* Keys for dictionary */
3811 CFTypeRef values
[] = { kSecClassCertificate
,
3814 /* Values for dictionary */
3817 * Get the names associated with the server.
3820 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3822 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3828 * Create a query which will return all identities that can sign and match
3829 * the passed in policy.
3832 query
= CFDictionaryCreate(NULL
,
3833 (const void**)(&keys
[0]),
3834 (const void**)(&values
[0]),
3835 sizeof(keys
) / sizeof(keys
[0]),
3836 &kCFTypeDictionaryKeyCallBacks
,
3837 &kCFTypeDictionaryValueCallBacks
);
3840 error
= SecItemCopyMatching(query
, &matches
);
3841 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3850 CFRelease(dn_array
);
3852 # endif /* HAVE_SECPOLICYCREATESSL */
3856 error
= SSLSetCertificate(http
->tls
, credentials
);
3857 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3861 DEBUG_puts("4http_set_credentials: No credentials to set.");
3865 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
3866 #endif /* HAVE_SSL */
3870 * 'http_set_timeout()' - Set the socket timeout values.
3874 http_set_timeout(int fd
, /* I - File descriptor */
3875 double timeout
) /* I - Timeout in seconds */
3878 DWORD tv
= (DWORD
)(timeout
* 1000);
3879 /* Timeout in milliseconds */
3881 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&tv
, sizeof(tv
));
3882 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&tv
, sizeof(tv
));
3885 struct timeval tv
; /* Timeout in secs and usecs */
3887 tv
.tv_sec
= (int)timeout
;
3888 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
3890 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, &tv
, sizeof(tv
));
3891 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
3897 * 'http_set_wait()' - Set the default wait value for reads.
3901 http_set_wait(http_t
*http
) /* I - Connection to server */
3905 http
->wait_value
= (int)(http
->timeout_value
* 1000);
3907 if (http
->wait_value
<= 0)
3908 http
->wait_value
= 60000;
3911 http
->wait_value
= 10000;
3917 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3920 static int /* O - 0 on success, -1 on failure */
3921 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3923 _cups_globals_t
*cg
= _cupsGlobals();
3924 /* Pointer to library globals */
3925 int any_root
; /* Allow any root */
3926 char hostname
[256], /* Hostname */
3927 *hostptr
; /* Pointer into hostname */
3930 SSL_CTX
*context
; /* Context for encryption */
3931 BIO
*bio
; /* BIO data */
3932 const char *message
= NULL
;/* Error message */
3933 # elif defined(HAVE_GNUTLS)
3934 int status
; /* Status of handshake */
3935 gnutls_certificate_client_credentials
*credentials
;
3936 /* TLS credentials */
3937 # elif defined(HAVE_CDSASSL)
3938 OSStatus error
; /* Error code */
3939 const char *message
= NULL
;/* Error message */
3940 # ifdef HAVE_SECCERTIFICATECOPYDATA
3941 cups_array_t
*credentials
; /* Credentials array */
3942 cups_array_t
*names
; /* CUPS distinguished names */
3943 CFArrayRef dn_array
; /* CF distinguished names array */
3944 CFIndex count
; /* Number of credentials */
3945 CFDataRef data
; /* Certificate data */
3946 int i
; /* Looping var */
3947 http_credential_t
*credential
; /* Credential data */
3948 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3949 # elif defined(HAVE_SSPISSL)
3950 TCHAR username
[256]; /* Username returned from GetUserName() */
3951 TCHAR commonName
[256];/* Common name for certificate */
3952 DWORD dwSize
; /* 32 bit size */
3953 # endif /* HAVE_LIBSSL */
3956 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3959 * Always allow self-signed certificates for the local loopback address...
3962 if (httpAddrLocalhost(http
->hostaddr
))
3965 strlcpy(hostname
, "localhost", sizeof(hostname
));
3970 * Otherwise use the system-wide setting and make sure the hostname we have
3971 * does not end in a trailing dot.
3974 any_root
= cg
->any_root
;
3976 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
3977 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
3985 context
= SSL_CTX_new(SSLv23_client_method());
3987 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3989 bio
= BIO_new(_httpBIOMethods());
3990 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3992 http
->tls
= SSL_new(context
);
3993 SSL_set_bio(http
->tls
, bio
, bio
);
3995 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
3996 SSL_set_tlsext_host_name(http
->tls
, hostname
);
3997 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
3999 if (SSL_connect(http
->tls
) != 1)
4001 unsigned long error
; /* Error code */
4003 while ((error
= ERR_get_error()) != 0)
4005 message
= ERR_error_string(error
, NULL
);
4006 DEBUG_printf(("8http_setup_ssl: %s", message
));
4009 SSL_CTX_free(context
);
4010 SSL_free(http
->tls
);
4014 http
->error
= WSAGetLastError();
4016 http
->error
= errno
;
4018 http
->status
= HTTP_ERROR
;
4021 message
= _("Unable to establish a secure connection to host.");
4023 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4028 # elif defined(HAVE_GNUTLS)
4031 credentials
= (gnutls_certificate_client_credentials
*)
4032 malloc(sizeof(gnutls_certificate_client_credentials
));
4033 if (credentials
== NULL
)
4035 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
4037 http
->error
= errno
;
4038 http
->status
= HTTP_ERROR
;
4039 _cupsSetHTTPError(HTTP_ERROR
);
4044 gnutls_certificate_allocate_credentials(credentials
);
4046 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
4047 gnutls_set_default_priority(http
->tls
);
4048 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
4050 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
4051 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
4052 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
4053 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
4055 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
4057 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
4058 status
, gnutls_strerror(status
)));
4060 if (gnutls_error_is_fatal(status
))
4063 http
->status
= HTTP_ERROR
;
4065 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
4067 gnutls_deinit(http
->tls
);
4068 gnutls_certificate_free_credentials(*credentials
);
4076 http
->tls_credentials
= credentials
;
4078 # elif defined(HAVE_CDSASSL)
4079 if ((error
= SSLNewContext(false, &http
->tls
)))
4081 http
->error
= errno
;
4082 http
->status
= HTTP_ERROR
;
4083 _cupsSetHTTPError(HTTP_ERROR
);
4088 error
= SSLSetConnection(http
->tls
, http
);
4089 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
4093 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
4094 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
4099 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
4100 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
4101 any_root
, (int)error
));
4106 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
4107 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
4108 cg
->expired_certs
, (int)error
));
4113 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
4114 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
4115 cg
->expired_root
, (int)error
));
4119 * In general, don't verify certificates since things like the common name
4120 * often do not match...
4125 error
= SSLSetEnableCertVerify(http
->tls
, false);
4126 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
4130 # ifdef HAVE_SECCERTIFICATECOPYDATA
4133 if (cg
->client_cert_cb
)
4135 error
= SSLSetSessionOption(http
->tls
,
4136 kSSLSessionOptionBreakOnCertRequested
, true);
4137 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
4138 "error=%d", (int)error
));
4142 error
= http_set_credentials(http
);
4143 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
4149 * If there's a server certificate callback installed let it evaluate the
4150 * certificate(s) during the handshake...
4153 if (!error
&& cg
->server_cert_cb
!= NULL
)
4155 error
= SSLSetSessionOption(http
->tls
,
4156 kSSLSessionOptionBreakOnServerAuth
, true);
4157 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
4158 "error=%d", (int)error
));
4160 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4163 * Let the server know which hostname/domain we are trying to connect to
4164 * in case it wants to serve up a certificate with a matching common name.
4169 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
4171 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
4177 int done
= 0; /* Are we done yet? */
4179 while (!error
&& !done
)
4181 error
= SSLHandshake(http
->tls
);
4183 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
4191 case errSSLWouldBlock
:
4192 error
= noErr
; /* Force a retry */
4193 usleep(1000); /* in 1 millisecond */
4196 # ifdef HAVE_SECCERTIFICATECOPYDATA
4197 case errSSLServerAuthCompleted
:
4199 if (cg
->server_cert_cb
)
4201 error
= httpCopyCredentials(http
, &credentials
);
4204 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
4205 cg
->server_cert_data
);
4206 httpFreeCredentials(credentials
);
4209 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
4210 "returned %d.", (int)error
));
4214 case errSSLClientCertRequested
:
4217 if (cg
->client_cert_cb
)
4220 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
4223 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
4225 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
4227 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
4229 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
4231 credential
->datalen
= CFDataGetLength(data
);
4232 if ((credential
->data
= malloc(credential
->datalen
)))
4234 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
4235 credential
->datalen
);
4236 cupsArrayAdd(names
, credential
);
4244 CFRelease(dn_array
);
4249 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
4250 cg
->client_cert_data
);
4252 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
4253 "returned %d.", (int)error
));
4256 httpFreeCredentials(names
);
4259 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4261 case errSSLUnknownRootCert
:
4262 message
= _("Unable to establish a secure connection to host "
4263 "(untrusted certificate).");
4266 case errSSLNoRootCert
:
4267 message
= _("Unable to establish a secure connection to host "
4268 "(self-signed certificate).");
4271 case errSSLCertExpired
:
4272 message
= _("Unable to establish a secure connection to host "
4273 "(expired certificate).");
4276 case errSSLCertNotYetValid
:
4277 message
= _("Unable to establish a secure connection to host "
4278 "(certificate not yet valid).");
4281 case errSSLHostNameMismatch
:
4282 message
= _("Unable to establish a secure connection to host "
4283 "(host name mismatch).");
4286 case errSSLXCertChainInvalid
:
4287 message
= _("Unable to establish a secure connection to host "
4288 "(certificate chain invalid).");
4291 case errSSLConnectionRefused
:
4292 message
= _("Unable to establish a secure connection to host "
4293 "(peer dropped connection before responding).");
4304 http
->error
= error
;
4305 http
->status
= HTTP_ERROR
;
4306 errno
= ECONNREFUSED
;
4308 SSLDisposeContext(http
->tls
);
4312 * If an error string wasn't set by the callbacks use a generic one...
4316 #ifdef HAVE_CSSMERRORSTRING
4317 message
= cssmErrorString(error
);
4319 message
= _("Unable to establish a secure connection to host.");
4320 #endif /* HAVE_CSSMERRORSTRING */
4322 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4327 # elif defined(HAVE_SSPISSL)
4328 http
->tls
= _sspiAlloc();
4332 _cupsSetHTTPError(HTTP_ERROR
);
4336 http
->tls
->sock
= http
->fd
;
4337 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4338 GetUserName(username
, &dwSize
);
4339 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4340 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4342 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4345 _sspiFree(http
->tls_credentials
);
4346 http
->tls_credentials
= NULL
;
4349 http
->status
= HTTP_ERROR
;
4351 _cupsSetError(IPP_PKI_ERROR
,
4352 _("Unable to establish a secure connection to host."), 1);
4357 _sspiSetAllowsAnyRoot(http
->tls_credentials
, any_root
);
4358 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4360 if (!_sspiConnect(http
->tls_credentials
, hostname
))
4362 _sspiFree(http
->tls_credentials
);
4363 http
->tls_credentials
= NULL
;
4366 http
->status
= HTTP_ERROR
;
4368 _cupsSetError(IPP_PKI_ERROR
,
4369 _("Unable to establish a secure connection to host."), 1);
4373 # endif /* HAVE_CDSASSL */
4380 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4384 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4387 SSL_CTX
*context
; /* Context for encryption */
4389 context
= SSL_get_SSL_CTX(http
->tls
);
4391 SSL_shutdown(http
->tls
);
4392 SSL_CTX_free(context
);
4393 SSL_free(http
->tls
);
4395 # elif defined(HAVE_GNUTLS)
4396 gnutls_certificate_client_credentials
*credentials
;
4397 /* TLS credentials */
4399 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4401 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4402 gnutls_deinit(http
->tls
);
4403 gnutls_certificate_free_credentials(*credentials
);
4406 # elif defined(HAVE_CDSASSL)
4407 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4410 SSLDisposeContext(http
->tls
);
4412 if (http
->tls_credentials
)
4413 CFRelease(http
->tls_credentials
);
4415 # elif defined(HAVE_SSPISSL)
4416 _sspiFree(http
->tls_credentials
);
4417 # endif /* HAVE_LIBSSL */
4420 http
->tls_credentials
= NULL
;
4422 #endif /* HAVE_SSL */
4427 * 'http_upgrade()' - Force upgrade to TLS encryption.
4430 static int /* O - Status of connection */
4431 http_upgrade(http_t
*http
) /* I - Connection to server */
4433 int ret
; /* Return value */
4434 http_t myhttp
; /* Local copy of HTTP data */
4437 DEBUG_printf(("7http_upgrade(%p)", http
));
4440 * Flush the connection to make sure any previous "Upgrade" message
4447 * Copy the HTTP data to a local variable so we can do the OPTIONS
4448 * request without interfering with the existing request data...
4451 memcpy(&myhttp
, http
, sizeof(myhttp
));
4454 * Send an OPTIONS request to the server, requiring SSL or TLS
4455 * encryption on the link...
4458 http
->field_authorization
= NULL
; /* Don't free the auth string */
4460 httpClearFields(http
);
4461 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4462 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4464 if ((ret
= httpOptions(http
, "*")) == 0)
4467 * Wait for the secure connection...
4470 while (httpUpdate(http
) == HTTP_CONTINUE
);
4474 * Restore the HTTP request data...
4477 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4478 http
->data_encoding
= myhttp
.data_encoding
;
4479 http
->data_remaining
= myhttp
.data_remaining
;
4480 http
->_data_remaining
= myhttp
._data_remaining
;
4481 http
->expect
= myhttp
.expect
;
4482 http
->field_authorization
= myhttp
.field_authorization
;
4483 http
->digest_tries
= myhttp
.digest_tries
;
4486 * See if we actually went secure...
4492 * Server does not support HTTP upgrade...
4495 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4498 closesocket(http
->fd
);
4510 #endif /* HAVE_SSL */
4514 * 'http_write()' - Write a buffer to a HTTP connection.
4517 static int /* O - Number of bytes written */
4518 http_write(http_t
*http
, /* I - Connection to server */
4519 const char *buffer
, /* I - Buffer for data */
4520 int length
) /* I - Number of bytes to write */
4522 int tbytes
, /* Total bytes sent */
4523 bytes
; /* Bytes sent */
4526 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4533 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
4535 if (http
->timeout_cb
)
4538 struct pollfd pfd
; /* Polled file descriptor */
4540 fd_set output_set
; /* Output ready for write? */
4541 struct timeval timeout
; /* Timeout value */
4542 #endif /* HAVE_POLL */
4543 int nfds
; /* Result from select()/poll() */
4549 pfd
.events
= POLLOUT
;
4551 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
4552 (errno
== EINTR
|| errno
== EAGAIN
))
4558 FD_ZERO(&output_set
);
4559 FD_SET(http
->fd
, &output_set
);
4561 timeout
.tv_sec
= http
->wait_value
/ 1000;
4562 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
4564 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
4567 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
4568 WSAGetLastError() == WSAEWOULDBLOCK
));
4570 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
4572 #endif /* HAVE_POLL */
4576 http
->error
= errno
;
4579 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4582 http
->error
= WSAEWOULDBLOCK
;
4584 http
->error
= EWOULDBLOCK
;
4594 bytes
= http_write_ssl(http
, buffer
, length
);
4596 #endif /* HAVE_SSL */
4597 bytes
= send(http
->fd
, buffer
, length
, 0);
4599 DEBUG_printf(("3http_write: Write of %d bytes returned %d.", (int)length
,
4605 if (WSAGetLastError() == WSAEINTR
)
4607 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4609 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4612 http
->error
= WSAGetLastError();
4614 else if (WSAGetLastError() != http
->error
&&
4615 WSAGetLastError() != WSAECONNRESET
)
4617 http
->error
= WSAGetLastError();
4624 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4626 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4628 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4631 http
->error
= errno
;
4633 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4635 http
->error
= errno
;
4640 DEBUG_printf(("3http_write: error writing data (%s).",
4641 strerror(http
->error
)));
4652 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4655 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4662 * 'http_write_chunk()' - Write a chunked buffer.
4665 static int /* O - Number bytes written */
4666 http_write_chunk(http_t
*http
, /* I - Connection to server */
4667 const char *buffer
, /* I - Buffer to write */
4668 int length
) /* I - Length of buffer */
4670 char header
[255]; /* Chunk header */
4671 int bytes
; /* Bytes written */
4674 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4675 http
, buffer
, length
));
4678 * Write the chunk header, data, and trailer.
4681 sprintf(header
, "%x\r\n", length
);
4682 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4684 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4688 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4690 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4694 if (http_write(http
, "\r\n", 2) < 0)
4696 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4706 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4709 static int /* O - Bytes written */
4710 http_write_ssl(http_t
*http
, /* I - Connection to server */
4711 const char *buf
, /* I - Buffer holding data */
4712 int len
) /* I - Length of buffer */
4714 ssize_t result
; /* Return value */
4717 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4719 # if defined(HAVE_LIBSSL)
4720 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4722 # elif defined(HAVE_GNUTLS)
4723 result
= gnutls_record_send(http
->tls
, buf
, len
);
4725 if (result
< 0 && !errno
)
4728 * Convert GNU TLS error to errno value...
4733 case GNUTLS_E_INTERRUPTED
:
4737 case GNUTLS_E_AGAIN
:
4749 # elif defined(HAVE_CDSASSL)
4750 OSStatus error
; /* Error info */
4751 size_t processed
; /* Number of bytes processed */
4754 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4759 result
= (int)processed
;
4762 case errSSLWouldBlock
:
4764 result
= (int)processed
;
4772 case errSSLClosedGraceful
:
4775 result
= (int)processed
;
4783 # elif defined(HAVE_SSPISSL)
4784 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
4785 # endif /* HAVE_LIBSSL */
4787 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4789 return ((int)result
);
4791 #endif /* HAVE_SSL */
4795 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".