2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for CUPS.
6 * Copyright 2007-2011 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 * httpGetStatus() - Get the status of the last HTTP request.
60 * httpGetSubField() - Get a sub-field value.
61 * httpGetSubField2() - Get a sub-field value.
62 * httpGets() - Get a line of text from a HTTP connection.
63 * httpHead() - Send a HEAD request to the server.
64 * httpInitialize() - Initialize the HTTP interface library and set
65 * the default HTTP proxy (if any).
66 * httpOptions() - Send an OPTIONS request to the server.
67 * _httpPeek() - Peek at data from a HTTP connection.
68 * httpPost() - Send a POST request to the server.
69 * httpPrintf() - Print a formatted string to a HTTP connection.
70 * httpPut() - Send a PUT request to the server.
71 * httpRead() - Read data from a HTTP connection.
72 * httpRead2() - Read data from a HTTP connection.
73 * _httpReadCDSA() - Read function for the CDSA library.
74 * _httpReadGNUTLS() - Read function for the GNU TLS library.
75 * httpReconnect() - Reconnect to a HTTP server.
76 * httpSetAuthString() - Set the current authorization string.
77 * httpSetCredentials() - Set the credentials associated with an
78 * encrypted connection.
79 * httpSetCookie() - Set the cookie value(s).
80 * httpSetExpect() - Set the Expect: header in a request.
81 * httpSetField() - Set the value of an HTTP header.
82 * httpSetLength() - Set the content-length and content-encoding.
83 * httpSetTimeout() - Set read/write timeouts and an optional
85 * httpTrace() - Send an TRACE request to the server.
86 * _httpUpdate() - Update the current HTTP status for incoming
88 * httpUpdate() - Update the current HTTP state for incoming
90 * _httpWait() - Wait for data available on a connection (no
92 * httpWait() - Wait for data available on a connection.
93 * httpWrite() - Write data to a HTTP connection.
94 * httpWrite2() - Write data to a HTTP connection.
95 * _httpWriteCDSA() - Write function for the CDSA library.
96 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
97 * http_bio_ctrl() - Control the HTTP connection.
98 * http_bio_free() - Free OpenSSL data.
99 * http_bio_new() - Initialize an OpenSSL BIO structure.
100 * http_bio_puts() - Send a string for OpenSSL.
101 * http_bio_read() - Read data for OpenSSL.
102 * http_bio_write() - Write data for OpenSSL.
103 * http_debug_hex() - Do a hex dump of a buffer.
104 * http_field() - Return the field index for a field name.
105 * http_read_ssl() - Read from a SSL/TLS connection.
106 * http_locking_cb() - Lock/unlock a thread's mutex.
107 * http_send() - Send a request with all fields and the trailing
109 * http_set_credentials() - Set the SSL/TLS credentials.
110 * http_set_timeout() - Set the socket timeout values.
111 * http_set_wait() - Set the default wait value for reads.
112 * http_setup_ssl() - Set up SSL/TLS support on a connection.
113 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
114 * http_threadid_cb() - Return the current thread ID.
115 * http_upgrade() - Force upgrade to TLS encryption.
116 * http_write() - Write a buffer to a HTTP connection.
117 * http_write_chunk() - Write a chunked buffer.
118 * http_write_ssl() - Write to a SSL/TLS connection.
122 * Include necessary headers...
125 #include "cups-private.h"
132 # include <sys/time.h>
133 # include <sys/resource.h>
136 # include <sys/poll.h>
137 #endif /* HAVE_POLL */
141 * Some operating systems have done away with the Fxxxx constants for
142 * the fcntl() call; this works around that "feature"...
146 # define FNONBLK O_NONBLOCK
147 #endif /* !FNONBLK */
155 static void http_debug_hex(const char *prefix
, const char *buffer
,
158 static http_field_t
http_field(const char *name
);
159 static int http_send(http_t
*http
, http_state_t request
,
161 static int http_write(http_t
*http
, const char *buffer
,
163 static int http_write_chunk(http_t
*http
, const char *buffer
,
166 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
167 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
168 static int http_set_credentials(http_t
*http
);
169 # endif /* HAVE_CDSASSL ** HAVE_SECCERTIFICATECOPYDATA */
170 static void http_set_timeout(int fd
, double timeout
);
171 static void http_set_wait(http_t
*http
);
172 static int http_setup_ssl(http_t
*http
);
173 static void http_shutdown_ssl(http_t
*http
);
174 static int http_upgrade(http_t
*http
);
175 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
176 #endif /* HAVE_SSL */
183 static const char * const http_fields
[] =
200 "If-Unmodified-since",
214 static const char * const http_states
[] =
234 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
236 * BIO methods for OpenSSL...
239 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
240 static int http_bio_read(BIO
*h
, char *buf
, int size
);
241 static int http_bio_puts(BIO
*h
, const char *str
);
242 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
243 static int http_bio_new(BIO
*h
);
244 static int http_bio_free(BIO
*data
);
246 static BIO_METHOD http_bio_methods
=
253 NULL
, /* http_bio_gets, */
259 #endif /* HAVE_SSL && HAVE_LIBSSL */
263 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
265 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
267 * @since CUPS 1.5/Mac OS X 10.7@
270 int /* O - 0 on success, -1 on error */
272 cups_array_t
*credentials
, /* I - Credentials array */
273 const void *data
, /* I - PEM-encoded X.509 data */
274 size_t datalen
) /* I - Length of data */
276 http_credential_t
*credential
; /* Credential data */
279 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
281 credential
->datalen
= datalen
;
283 if ((credential
->data
= malloc(datalen
)) != NULL
)
285 memcpy(credential
->data
, data
, datalen
);
286 cupsArrayAdd(credentials
, credential
);
297 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
299 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
302 BIO_METHOD
* /* O - BIO methods for OpenSSL */
303 _httpBIOMethods(void)
305 return (&http_bio_methods
);
307 #endif /* HAVE_SSL && HAVE_LIBSSL */
311 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
315 httpBlocking(http_t
*http
, /* I - Connection to server */
316 int b
) /* I - 1 = blocking, 0 = non-blocking */
327 * 'httpCheck()' - Check to see if there is a pending response from the server.
330 int /* O - 0 = no data, 1 = data available */
331 httpCheck(http_t
*http
) /* I - Connection to server */
333 return (httpWait(http
, 0));
338 * 'httpClearCookie()' - Clear the cookie value(s).
340 * @since CUPS 1.1.19/Mac OS X 10.3@
344 httpClearCookie(http_t
*http
) /* I - Connection to server */
358 * 'httpClearFields()' - Clear HTTP request fields.
362 httpClearFields(http_t
*http
) /* I - Connection to server */
366 memset(http
->fields
, 0, sizeof(http
->fields
));
367 if (http
->hostname
[0] == '/')
368 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
370 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
372 if (http
->field_authorization
)
374 free(http
->field_authorization
);
375 http
->field_authorization
= NULL
;
378 http
->expect
= (http_status_t
)0;
384 * 'httpClose()' - Close an HTTP connection.
388 httpClose(http_t
*http
) /* I - Connection to server */
391 OM_uint32 minor_status
; /* Minor status code */
392 #endif /* HAVE_GSSAPI */
395 DEBUG_printf(("httpClose(http=%p)", http
));
398 * Range check input...
405 * Close any open connection...
408 _httpDisconnect(http
);
411 * Free memory used...
414 httpAddrFreeList(http
->addrlist
);
420 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
421 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
423 if (http
->gssname
!= GSS_C_NO_NAME
)
424 gss_release_name(&minor_status
, &http
->gssname
);
425 #endif /* HAVE_GSSAPI */
427 #ifdef HAVE_AUTHORIZATION_H
429 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
430 #endif /* HAVE_AUTHORIZATION_H */
432 httpClearFields(http
);
434 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
435 free(http
->authstring
);
442 * 'httpConnect()' - Connect to a HTTP server.
444 * This function is deprecated - use @link httpConnectEncrypt@ instead.
449 http_t
* /* O - New HTTP connection */
450 httpConnect(const char *host
, /* I - Host to connect to */
451 int port
) /* I - Port number */
453 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
458 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
461 http_t
* /* O - New HTTP connection */
463 const char *host
, /* I - Host to connect to */
464 int port
, /* I - Port number */
465 http_encryption_t encryption
) /* I - Type of encryption to use */
467 http_t
*http
; /* New HTTP connection */
470 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
471 host
, port
, encryption
));
474 * Create the HTTP structure...
477 if ((http
= _httpCreate(host
, port
, NULL
, encryption
, AF_UNSPEC
)) == NULL
)
481 * Connect to the remote system...
484 if (!httpReconnect(http
))
488 * Could not connect to any known address - bail out!
491 httpAddrFreeList(http
->addrlist
);
500 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
503 * @since CUPS 1.5/Mac OS X 10.7@
506 int /* O - Status of call (0 = success) */
508 http_t
*http
, /* I - Connection to server */
509 cups_array_t
**credentials
) /* O - Array of credentials */
512 # elif defined(HAVE_GNUTLS)
513 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
514 OSStatus error
; /* Error code */
515 CFIndex count
; /* Number of credentials */
516 CFArrayRef peerCerts
; /* Peer certificates */
517 SecCertificateRef secCert
; /* Certificate reference */
518 CFDataRef data
; /* Certificate data */
519 int i
; /* Looping var */
520 # elif defined(HAVE_SSPISSL)
521 # endif /* HAVE_LIBSSL */
527 if (!http
|| !http
->tls
|| !credentials
)
533 # elif defined(HAVE_GNUTLS)
536 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
537 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
539 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
541 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
543 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
544 if ((data
= SecCertificateCopyData(secCert
)))
546 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
547 CFDataGetLength(data
));
553 CFRelease(peerCerts
);
558 # elif defined(HAVE_SSPISSL)
563 # endif /* HAVE_LIBSSL */
568 * '_httpCreate()' - Create an unconnected HTTP connection.
571 http_t
* /* O - HTTP connection */
573 const char *host
, /* I - Hostname */
574 int port
, /* I - Port number */
575 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
576 http_encryption_t encryption
, /* I - Encryption to use */
577 int family
) /* I - Address family or AF_UNSPEC */
579 http_t
*http
; /* New HTTP connection */
580 char service
[255]; /* Service name */
583 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
584 host
, port
, encryption
));
595 sprintf(service
, "%d", port
);
598 if ((addrlist
= httpAddrGetList(host
, family
, service
)) == NULL
)
602 * Allocate memory for the structure...
605 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
607 httpAddrFreeList(addrlist
);
612 * Initialize the HTTP data...
615 http
->activity
= time(NULL
);
616 http
->addrlist
= addrlist
;
620 http
->gssctx
= GSS_C_NO_CONTEXT
;
621 http
->gssname
= GSS_C_NO_NAME
;
622 #endif /* HAVE_GSSAPI */
623 http
->version
= HTTP_1_1
;
625 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
627 if (port
== 443) /* Always use encryption for https */
628 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
630 http
->encryption
= encryption
;
635 * Return the new structure...
643 * '_httpCreateCredentials()' - Create credentials in the internal format.
646 http_tls_credentials_t
/* O - Internal credentials */
647 _httpCreateCredentials(
648 cups_array_t
*credentials
) /* I - Array of credentials */
656 # elif defined(HAVE_GNUTLS)
659 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
660 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
661 SecCertificateRef secCert
; /* Certificate reference */
662 CFDataRef data
; /* Credential data reference */
663 http_credential_t
*credential
; /* Credential data */
666 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
667 cupsArrayCount(credentials
),
668 &kCFTypeArrayCallBacks
)) == NULL
)
671 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
673 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
675 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
676 credential
->datalen
)))
678 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
681 CFArrayAppendValue(peerCerts
, secCert
);
691 # elif defined(HAVE_SSPISSL)
696 # endif /* HAVE_LIBSSL */
701 * 'httpDelete()' - Send a DELETE request to the server.
704 int /* O - Status of call (0 = success) */
705 httpDelete(http_t
*http
, /* I - Connection to server */
706 const char *uri
) /* I - URI to delete */
708 return (http_send(http
, HTTP_DELETE
, uri
));
713 * '_httpDisconnect()' - Disconnect a HTTP connection.
717 _httpDisconnect(http_t
*http
) /* I - Connection to server */
721 http_shutdown_ssl(http
);
722 #endif /* HAVE_SSL */
725 closesocket(http
->fd
);
735 * 'httpEncryption()' - Set the required encryption on the link.
738 int /* O - -1 on error, 0 on success */
739 httpEncryption(http_t
*http
, /* I - Connection to server */
740 http_encryption_t e
) /* I - New encryption preference */
742 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
748 http
->encryption
= e
;
750 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
751 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
752 return (httpReconnect(http
));
753 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
754 return (http_upgrade(http
));
758 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
762 #endif /* HAVE_SSL */
767 * 'httpError()' - Get the last error on a connection.
770 int /* O - Error code (errno) value */
771 httpError(http_t
*http
) /* I - Connection to server */
774 return (http
->error
);
781 * 'httpFlush()' - Flush data from a HTTP connection.
785 httpFlush(http_t
*http
) /* I - Connection to server */
787 char buffer
[8192]; /* Junk buffer */
788 int blocking
; /* To block or not to block */
789 http_state_t oldstate
; /* Old state */
792 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
793 http_states
[http
->state
]));
796 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
799 blocking
= http
->blocking
;
803 * Read any data we can...
806 oldstate
= http
->state
;
807 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
810 * Restore blocking and reset the connection if we didn't get all of
811 * the remaining data...
814 http
->blocking
= blocking
;
816 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
819 * Didn't get the data back, so close the current connection.
822 http
->state
= HTTP_WAITING
;
826 http_shutdown_ssl(http
);
827 #endif /* HAVE_SSL */
830 closesocket(http
->fd
);
841 * 'httpFlushWrite()' - Flush data in write buffer.
843 * @since CUPS 1.2/Mac OS X 10.5@
846 int /* O - Bytes written or -1 on error */
847 httpFlushWrite(http_t
*http
) /* I - Connection to server */
849 int bytes
; /* Bytes written */
852 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
854 if (!http
|| !http
->wused
)
856 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
857 "1httpFlushWrite: No connection.");
861 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
862 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
864 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
868 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
875 * '_httpFreeCredentials()' - Free internal credentials.
879 _httpFreeCredentials(
880 http_tls_credentials_t credentials
) /* I - Internal credentials */
888 #elif defined(HAVE_GNUTLS)
891 #elif defined(HAVE_CDSASSL)
892 CFRelease(credentials
);
894 #elif defined(HAVE_SSPISSL)
897 #endif /* HAVE_LIBSSL */
902 * 'httpFreeCredentials()' - Free an array of credentials.
907 cups_array_t
*credentials
) /* I - Array of credentials */
909 http_credential_t
*credential
; /* Credential */
912 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
914 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
916 cupsArrayRemove(credentials
, credential
);
917 free((void *)credential
->data
);
921 cupsArrayDelete(credentials
);
926 * 'httpGet()' - Send a GET request to the server.
929 int /* O - Status of call (0 = success) */
930 httpGet(http_t
*http
, /* I - Connection to server */
931 const char *uri
) /* I - URI to get */
933 return (http_send(http
, HTTP_GET
, uri
));
938 * 'httpGetAuthString()' - Get the current authorization string.
940 * The authorization string is set by cupsDoAuthentication() and
941 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
942 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
945 * @since CUPS 1.3/Mac OS X 10.5@
948 char * /* O - Authorization string */
949 httpGetAuthString(http_t
*http
) /* I - Connection to server */
952 return (http
->authstring
);
959 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
961 * @since CUPS 1.2/Mac OS X 10.5@
964 int /* O - 1 if blocking, 0 if non-blocking */
965 httpGetBlocking(http_t
*http
) /* I - Connection to server */
967 return (http
? http
->blocking
: 0);
972 * 'httpGetCookie()' - Get any cookie data from the response.
974 * @since CUPS 1.1.19/Mac OS X 10.3@
977 const char * /* O - Cookie data or NULL */
978 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
980 return (http
? http
->cookie
: NULL
);
985 * 'httpGetFd()' - Get the file descriptor associated with a connection.
987 * @since CUPS 1.2/Mac OS X 10.5@
990 int /* O - File descriptor or -1 if none */
991 httpGetFd(http_t
*http
) /* I - Connection to server */
993 return (http
? http
->fd
: -1);
998 * 'httpGetField()' - Get a field value from a request/response.
1001 const char * /* O - Field value */
1002 httpGetField(http_t
*http
, /* I - Connection to server */
1003 http_field_t field
) /* I - Field to get */
1005 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1007 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
1008 http
->field_authorization
)
1011 * Special case for WWW-Authenticate: as its contents can be
1012 * longer than HTTP_MAX_VALUE...
1015 return (http
->field_authorization
);
1018 return (http
->fields
[field
]);
1023 * 'httpGetLength()' - Get the amount of data remaining from the
1024 * content-length or transfer-encoding fields.
1026 * This function is deprecated and will not return lengths larger than
1027 * 2^31 - 1; use httpGetLength2() instead.
1032 int /* O - Content length */
1033 httpGetLength(http_t
*http
) /* I - Connection to server */
1036 * Get the read content length and return the 32-bit value.
1041 httpGetLength2(http
);
1043 return (http
->_data_remaining
);
1051 * 'httpGetLength2()' - Get the amount of data remaining from the
1052 * content-length or transfer-encoding fields.
1054 * This function returns the complete content length, even for
1055 * content larger than 2^31 - 1.
1057 * @since CUPS 1.2/Mac OS X 10.5@
1060 off_t
/* O - Content length */
1061 httpGetLength2(http_t
*http
) /* I - Connection to server */
1063 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1064 http_states
[http
->state
]));
1069 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1071 DEBUG_puts("4httpGetLength2: chunked request!");
1073 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1074 http
->data_remaining
= 0;
1078 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1081 * The following is a hack for HTTP servers that don't send a
1082 * content-length or transfer-encoding field...
1084 * If there is no content-length then the connection must close
1085 * after the transfer is complete...
1088 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1091 * Default content length is 0 for errors and 2^31-1 for other
1092 * successful requests...
1095 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
1096 http
->data_remaining
= 0;
1098 http
->data_remaining
= 2147483647;
1101 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1104 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1105 CUPS_LLCAST http
->data_remaining
));
1108 if (http
->data_remaining
<= INT_MAX
)
1109 http
->_data_remaining
= (int)http
->data_remaining
;
1111 http
->_data_remaining
= INT_MAX
;
1113 return (http
->data_remaining
);
1118 * 'httpGetStatus()' - Get the status of the last HTTP request.
1120 * @since CUPS 1.2/Mac OS X 10.5@
1123 http_status_t
/* O - HTTP status */
1124 httpGetStatus(http_t
*http
) /* I - Connection to server */
1126 return (http
? http
->status
: HTTP_ERROR
);
1131 * 'httpGetSubField()' - Get a sub-field value.
1136 char * /* O - Value or NULL */
1137 httpGetSubField(http_t
*http
, /* I - Connection to server */
1138 http_field_t field
, /* I - Field index */
1139 const char *name
, /* I - Name of sub-field */
1140 char *value
) /* O - Value string */
1142 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1147 * 'httpGetSubField2()' - Get a sub-field value.
1149 * @since CUPS 1.2/Mac OS X 10.5@
1152 char * /* O - Value or NULL */
1153 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1154 http_field_t field
, /* I - Field index */
1155 const char *name
, /* I - Name of sub-field */
1156 char *value
, /* O - Value string */
1157 int valuelen
) /* I - Size of value buffer */
1159 const char *fptr
; /* Pointer into field */
1160 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1161 *ptr
, /* Pointer into string buffer */
1162 *end
; /* End of value buffer */
1164 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1165 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1167 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1168 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1171 end
= value
+ valuelen
- 1;
1173 for (fptr
= http
->fields
[field
]; *fptr
;)
1176 * Skip leading whitespace...
1179 while (_cups_isspace(*fptr
))
1189 * Get the sub-field name...
1193 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1194 ptr
< (temp
+ sizeof(temp
) - 1);
1199 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1202 * Skip trailing chars up to the '='...
1205 while (_cups_isspace(*fptr
))
1215 * Skip = and leading whitespace...
1220 while (_cups_isspace(*fptr
))
1226 * Read quoted string...
1229 for (ptr
= value
, fptr
++;
1230 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1235 while (*fptr
&& *fptr
!= '\"')
1244 * Read unquoted string...
1248 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1253 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1257 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1260 * See if this is the one...
1263 if (!strcmp(name
, temp
))
1265 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1272 DEBUG_puts("3httpGetSubField2: Returning NULL");
1279 * 'httpGets()' - Get a line of text from a HTTP connection.
1282 char * /* O - Line or NULL */
1283 httpGets(char *line
, /* I - Line to read into */
1284 int length
, /* I - Max length of buffer */
1285 http_t
*http
) /* I - Connection to server */
1287 char *lineptr
, /* Pointer into line */
1288 *lineend
, /* End of line */
1289 *bufptr
, /* Pointer into input buffer */
1290 *bufend
; /* Pointer to end of buffer */
1291 int bytes
, /* Number of bytes read */
1292 eol
; /* End-of-line? */
1295 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1297 if (http
== NULL
|| line
== NULL
)
1301 * Read a line from the buffer...
1306 lineend
= line
+ length
- 1;
1309 while (lineptr
< lineend
)
1312 * Pre-load the buffer as needed...
1321 while (http
->used
== 0)
1324 * No newline; see if there is more data to be read...
1327 while (!_httpWait(http
, http
->wait_value
, 1))
1329 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1332 DEBUG_puts("3httpGets: Timed out!");
1334 http
->error
= WSAETIMEDOUT
;
1336 http
->error
= ETIMEDOUT
;
1343 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1344 HTTP_MAX_BUFFER
- http
->used
);
1346 #endif /* HAVE_SSL */
1347 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1348 HTTP_MAX_BUFFER
- http
->used
, 0);
1350 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1355 * Nope, can't get a line this time...
1359 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1361 if (WSAGetLastError() == WSAEINTR
)
1363 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1365 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1368 http
->error
= WSAGetLastError();
1370 else if (WSAGetLastError() != http
->error
)
1372 http
->error
= WSAGetLastError();
1377 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1381 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1383 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1385 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1388 http
->error
= errno
;
1390 else if (errno
!= http
->error
)
1392 http
->error
= errno
;
1399 else if (bytes
== 0)
1401 http
->error
= EPIPE
;
1407 * Yup, update the amount used...
1410 http
->used
+= bytes
;
1414 * Now copy as much of the current line as possible...
1417 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1418 lineptr
< lineend
&& bufptr
< bufend
;)
1420 if (*bufptr
== 0x0a)
1426 else if (*bufptr
== 0x0d)
1429 *lineptr
++ = *bufptr
++;
1432 http
->used
-= (int)(bufptr
- http
->buffer
);
1434 memmove(http
->buffer
, bufptr
, http
->used
);
1442 http
->activity
= time(NULL
);
1446 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1452 DEBUG_puts("3httpGets: No new line available!");
1459 * 'httpHead()' - Send a HEAD request to the server.
1462 int /* O - Status of call (0 = success) */
1463 httpHead(http_t
*http
, /* I - Connection to server */
1464 const char *uri
) /* I - URI for head */
1466 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1467 return (http_send(http
, HTTP_HEAD
, uri
));
1472 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1473 * default HTTP proxy (if any).
1477 httpInitialize(void)
1479 static int initialized
= 0; /* Have we been called before? */
1481 WSADATA winsockdata
; /* WinSock data */
1484 int i
; /* Looping var */
1485 unsigned char data
[1024]; /* Seed data */
1486 #endif /* HAVE_LIBSSL */
1492 _cupsGlobalUnlock();
1497 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1499 #elif !defined(SO_NOSIGPIPE)
1501 * Ignore SIGPIPE signals...
1505 sigset(SIGPIPE
, SIG_IGN
);
1507 # elif defined(HAVE_SIGACTION)
1508 struct sigaction action
; /* POSIX sigaction data */
1511 memset(&action
, 0, sizeof(action
));
1512 action
.sa_handler
= SIG_IGN
;
1513 sigaction(SIGPIPE
, &action
, NULL
);
1516 signal(SIGPIPE
, SIG_IGN
);
1517 # endif /* !SO_NOSIGPIPE */
1522 * Initialize GNU TLS...
1525 gnutls_global_init();
1527 #elif defined(HAVE_LIBSSL)
1529 * Initialize OpenSSL...
1532 SSL_load_error_strings();
1536 * Using the current time is a dubious random seed, but on some systems
1537 * it is the best we can do (on others, this seed isn't even used...)
1540 CUPS_SRAND(time(NULL
));
1542 for (i
= 0; i
< sizeof(data
); i
++)
1543 data
[i
] = CUPS_RAND();
1545 RAND_seed(data
, sizeof(data
));
1546 #endif /* HAVE_GNUTLS */
1549 _cupsGlobalUnlock();
1554 * 'httpOptions()' - Send an OPTIONS request to the server.
1557 int /* O - Status of call (0 = success) */
1558 httpOptions(http_t
*http
, /* I - Connection to server */
1559 const char *uri
) /* I - URI for options */
1561 return (http_send(http
, HTTP_OPTIONS
, uri
));
1566 * '_httpPeek()' - Peek at data from a HTTP connection.
1568 * This function copies available data from the given HTTP connection, reading
1569 * a buffer as needed. The data is still available for reading using
1570 * @link httpRead@ or @link httpRead2@.
1572 * For non-blocking connections the usual timeouts apply.
1575 ssize_t
/* O - Number of bytes copied */
1576 _httpPeek(http_t
*http
, /* I - Connection to server */
1577 char *buffer
, /* I - Buffer for data */
1578 size_t length
) /* I - Maximum number of bytes */
1580 ssize_t bytes
; /* Bytes read */
1581 char len
[32]; /* Length string */
1584 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1585 http
, buffer
, CUPS_LLCAST length
));
1587 if (http
== NULL
|| buffer
== NULL
)
1590 http
->activity
= time(NULL
);
1596 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1597 http
->data_remaining
<= 0)
1599 DEBUG_puts("2_httpPeek: Getting chunk length...");
1601 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1603 DEBUG_puts("1_httpPeek: Could not get length!");
1607 http
->data_remaining
= strtoll(len
, NULL
, 16);
1608 if (http
->data_remaining
< 0)
1610 DEBUG_puts("1_httpPeek: Negative chunk length!");
1615 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1616 CUPS_LLCAST http
->data_remaining
));
1618 if (http
->data_remaining
<= 0)
1621 * A zero-length chunk ends a transfer; unless we are reading POST
1625 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1626 httpGets(len
, sizeof(len
), http
);
1628 if (http
->state
== HTTP_POST_RECV
)
1631 http
->state
= HTTP_WAITING
;
1634 * Prevent future reads for this request...
1637 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1641 else if (length
> (size_t)http
->data_remaining
)
1642 length
= (size_t)http
->data_remaining
;
1644 if (http
->used
== 0)
1647 * Buffer small reads for better performance...
1650 if (!http
->blocking
)
1652 while (!httpWait(http
, http
->wait_value
))
1654 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1661 if (http
->data_remaining
> sizeof(http
->buffer
))
1662 bytes
= sizeof(http
->buffer
);
1664 bytes
= http
->data_remaining
;
1668 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1670 #endif /* HAVE_SSL */
1672 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1675 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1677 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1686 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1688 http
->error
= WSAGetLastError();
1692 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1694 http
->error
= errno
;
1701 http
->error
= EPIPE
;
1708 if (length
> (size_t)http
->used
)
1709 length
= (size_t)http
->used
;
1711 bytes
= (ssize_t
)length
;
1713 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1716 memcpy(buffer
, http
->buffer
, length
);
1724 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1727 http
->error
= WSAGetLastError();
1729 if (errno
== EINTR
|| errno
== EAGAIN
)
1732 http
->error
= errno
;
1735 else if (bytes
== 0)
1737 http
->error
= EPIPE
;
1742 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1750 * 'httpPost()' - Send a POST request to the server.
1753 int /* O - Status of call (0 = success) */
1754 httpPost(http_t
*http
, /* I - Connection to server */
1755 const char *uri
) /* I - URI for post */
1757 return (http_send(http
, HTTP_POST
, uri
));
1762 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1767 int /* O - Number of bytes written */
1768 httpPrintf(http_t
*http
, /* I - Connection to server */
1769 const char *format
, /* I - printf-style format string */
1770 ...) /* I - Additional args as needed */
1772 int bytes
; /* Number of bytes to write */
1773 char buf
[16384]; /* Buffer for formatted string */
1774 va_list ap
; /* Variable argument pointer */
1777 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1779 va_start(ap
, format
);
1780 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1783 DEBUG_printf(("3httpPrintf: %s", buf
));
1785 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1786 return (httpWrite2(http
, buf
, bytes
));
1791 DEBUG_puts("4httpPrintf: flushing existing data...");
1793 if (httpFlushWrite(http
) < 0)
1797 return (http_write(http
, buf
, bytes
));
1803 * 'httpPut()' - Send a PUT request to the server.
1806 int /* O - Status of call (0 = success) */
1807 httpPut(http_t
*http
, /* I - Connection to server */
1808 const char *uri
) /* I - URI to put */
1810 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1811 return (http_send(http
, HTTP_PUT
, uri
));
1816 * 'httpRead()' - Read data from a HTTP connection.
1818 * This function is deprecated. Use the httpRead2() function which can
1819 * read more than 2GB of data.
1824 int /* O - Number of bytes read */
1825 httpRead(http_t
*http
, /* I - Connection to server */
1826 char *buffer
, /* I - Buffer for data */
1827 int length
) /* I - Maximum number of bytes */
1829 return ((int)httpRead2(http
, buffer
, length
));
1834 * 'httpRead2()' - Read data from a HTTP connection.
1836 * @since CUPS 1.2/Mac OS X 10.5@
1839 ssize_t
/* O - Number of bytes read */
1840 httpRead2(http_t
*http
, /* I - Connection to server */
1841 char *buffer
, /* I - Buffer for data */
1842 size_t length
) /* I - Maximum number of bytes */
1844 ssize_t bytes
; /* Bytes read */
1845 char len
[32]; /* Length string */
1848 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1849 http
, buffer
, CUPS_LLCAST length
));
1851 if (http
== NULL
|| buffer
== NULL
)
1854 http
->activity
= time(NULL
);
1860 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1861 http
->data_remaining
<= 0)
1863 DEBUG_puts("2httpRead2: Getting chunk length...");
1865 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1867 DEBUG_puts("1httpRead2: Could not get length!");
1871 http
->data_remaining
= strtoll(len
, NULL
, 16);
1872 if (http
->data_remaining
< 0)
1874 DEBUG_puts("1httpRead2: Negative chunk length!");
1879 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1880 CUPS_LLCAST http
->data_remaining
));
1882 if (http
->data_remaining
<= 0)
1885 * A zero-length chunk ends a transfer; unless we are reading POST
1889 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1890 httpGets(len
, sizeof(len
), http
);
1892 if (http
->state
== HTTP_POST_RECV
)
1895 http
->state
= HTTP_WAITING
;
1898 * Prevent future reads for this request...
1901 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1905 else if (length
> (size_t)http
->data_remaining
)
1906 length
= (size_t)http
->data_remaining
;
1908 if (http
->used
== 0 && length
<= 256)
1911 * Buffer small reads for better performance...
1914 ssize_t buflen
; /* Length of read for buffer */
1916 if (!http
->blocking
)
1918 while (!httpWait(http
, http
->wait_value
))
1920 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1927 if (http
->data_remaining
> sizeof(http
->buffer
))
1928 buflen
= sizeof(http
->buffer
);
1930 buflen
= http
->data_remaining
;
1932 DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen
));
1938 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
1940 #endif /* HAVE_SSL */
1941 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
1946 if (WSAGetLastError() != WSAEINTR
)
1948 http
->error
= WSAGetLastError();
1951 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1953 if (!http
->timeout_cb
||
1954 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1956 http
->error
= WSAEWOULDBLOCK
;
1961 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1963 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1965 http
->error
= errno
;
1968 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1970 http
->error
= errno
;
1974 else if (errno
!= EINTR
)
1976 http
->error
= errno
;
1984 DEBUG_printf(("2httpRead2: Read %d bytes into buffer.", (int)bytes
));
1991 if (length
> (size_t)http
->used
)
1992 length
= (size_t)http
->used
;
1994 bytes
= (ssize_t
)length
;
1996 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
1999 memcpy(buffer
, http
->buffer
, length
);
2000 http
->used
-= (int)length
;
2003 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2008 if (!http
->blocking
)
2010 while (!httpWait(http
, http
->wait_value
))
2012 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2019 while ((bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
)) < 0)
2022 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2024 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2027 else if (WSAGetLastError() != WSAEINTR
)
2030 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2032 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2034 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2037 else if (errno
!= EINTR
)
2042 #endif /* HAVE_SSL */
2045 if (!http
->blocking
)
2047 while (!httpWait(http
, http
->wait_value
))
2049 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2056 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2057 CUPS_LLCAST length
));
2060 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2062 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2064 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2067 else if (WSAGetLastError() != WSAEINTR
)
2071 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2073 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2075 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2077 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2080 else if (errno
!= EINTR
)
2085 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2086 CUPS_LLCAST bytes
));
2091 http
->data_remaining
-= bytes
;
2093 if (http
->data_remaining
<= INT_MAX
)
2094 http
->_data_remaining
= (int)http
->data_remaining
;
2096 http
->_data_remaining
= INT_MAX
;
2101 if (WSAGetLastError() == WSAEINTR
)
2104 http
->error
= WSAGetLastError();
2106 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2109 http
->error
= errno
;
2114 http
->error
= EPIPE
;
2118 if (http
->data_remaining
== 0)
2120 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2121 httpGets(len
, sizeof(len
), http
);
2123 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2125 if (http
->state
== HTTP_POST_RECV
)
2128 http
->state
= HTTP_WAITING
;
2133 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2140 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2142 * '_httpReadCDSA()' - Read function for the CDSA library.
2145 OSStatus
/* O - -1 on error, 0 on success */
2147 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2148 void *data
, /* I - Data buffer */
2149 size_t *dataLength
) /* IO - Number of bytes */
2151 OSStatus result
; /* Return value */
2152 ssize_t bytes
; /* Number of bytes read */
2153 http_t
*http
; /* HTTP connection */
2156 http
= (http_t
*)connection
;
2158 if (!http
->blocking
)
2161 * Make sure we have data before we read...
2164 while (!_httpWait(http
, http
->wait_value
, 0))
2166 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2169 http
->error
= ETIMEDOUT
;
2176 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2178 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2180 if (bytes
== *dataLength
)
2186 *dataLength
= bytes
;
2187 result
= errSSLWouldBlock
;
2194 result
= errSSLClosedGraceful
;
2195 else if (errno
== EAGAIN
)
2196 result
= errSSLWouldBlock
;
2198 result
= errSSLClosedAbort
;
2203 #endif /* HAVE_SSL && HAVE_CDSASSL */
2206 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2208 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2211 ssize_t
/* O - Number of bytes read or -1 on error */
2213 gnutls_transport_ptr ptr
, /* I - Connection to server */
2214 void *data
, /* I - Buffer */
2215 size_t length
) /* I - Number of bytes to read */
2217 http_t
*http
; /* HTTP connection */
2218 ssize_t bytes
; /* Bytes read */
2221 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2223 http
= (http_t
*)ptr
;
2225 if (!http
->blocking
)
2228 * Make sure we have data before we read...
2231 while (!_httpWait(http
, http
->wait_value
, 0))
2233 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2236 http
->error
= ETIMEDOUT
;
2241 bytes
= recv(http
->fd
, data
, length
, 0);
2242 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2245 #endif /* HAVE_SSL && HAVE_GNUTLS */
2249 * 'httpReconnect()' - Reconnect to a HTTP server.
2252 int /* O - 0 on success, non-zero on failure */
2253 httpReconnect(http_t
*http
) /* I - Connection to server */
2255 http_addrlist_t
*addr
; /* Connected address */
2257 http_addrlist_t
*current
; /* Current address */
2258 char temp
[256]; /* Temporary address string */
2262 DEBUG_printf(("httpReconnect(http=%p)", http
));
2270 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2271 http_shutdown_ssl(http
);
2273 #endif /* HAVE_SSL */
2276 * Close any previously open socket...
2281 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2284 closesocket(http
->fd
);
2293 * Connect to the server...
2297 for (current
= http
->addrlist
; current
; current
= current
->next
)
2298 DEBUG_printf(("2httpReconnect: Address %s:%d",
2299 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2300 _httpAddrPort(&(current
->addr
))));
2303 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
2306 * Unable to connect...
2310 http
->error
= WSAGetLastError();
2312 http
->error
= errno
;
2314 http
->status
= HTTP_ERROR
;
2316 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2317 strerror(http
->error
)));
2322 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2324 if (http
->timeout_value
> 0)
2325 http_set_timeout(http
->fd
, http
->timeout_value
);
2327 http
->hostaddr
= &(addr
->addr
);
2329 http
->status
= HTTP_CONTINUE
;
2332 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2335 * Always do encryption via SSL.
2338 if (http_setup_ssl(http
) != 0)
2341 closesocket(http
->fd
);
2349 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2350 return (http_upgrade(http
));
2351 #endif /* HAVE_SSL */
2353 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2354 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2355 _httpAddrPort(http
->hostaddr
)));
2362 * 'httpSetAuthString()' - Set the current authorization string.
2364 * This function just stores a copy of the current authorization string in
2365 * the HTTP connection object. You must still call httpSetField() to set
2366 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2367 * httpHead(), httpOptions(), httpPost, or httpPut().
2369 * @since CUPS 1.3/Mac OS X 10.5@
2373 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2374 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2375 const char *data
) /* I - Auth data (NULL for none) */
2378 * Range check input...
2384 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2385 free(http
->authstring
);
2387 http
->authstring
= http
->_authstring
;
2392 * Set the current authorization string...
2395 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2398 if (len
> (int)sizeof(http
->_authstring
))
2400 if ((temp
= malloc(len
)) == NULL
)
2401 len
= sizeof(http
->_authstring
);
2403 http
->authstring
= temp
;
2407 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2409 strlcpy(http
->authstring
, scheme
, len
);
2414 * Clear the current authorization string...
2417 http
->_authstring
[0] = '\0';
2423 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2426 * @since CUPS 1.5/Mac OS X 10.7@
2429 int /* O - Status of call (0 = success) */
2430 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2431 cups_array_t
*credentials
) /* I - Array of credentials */
2433 if (!http
|| cupsArrayCount(credentials
) < 1)
2436 _httpFreeCredentials(http
->tls_credentials
);
2438 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2440 return (http
->tls_credentials
? 0 : -1);
2445 * 'httpSetCookie()' - Set the cookie value(s).
2447 * @since CUPS 1.1.19/Mac OS X 10.3@
2451 httpSetCookie(http_t
*http
, /* I - Connection */
2452 const char *cookie
) /* I - Cookie string */
2461 http
->cookie
= strdup(cookie
);
2463 http
->cookie
= NULL
;
2468 * 'httpSetExpect()' - Set the Expect: header in a request.
2470 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2472 * @since CUPS 1.2/Mac OS X 10.5@
2476 httpSetExpect(http_t
*http
, /* I - Connection to server */
2477 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2480 http
->expect
= expect
;
2485 * 'httpSetField()' - Set the value of an HTTP header.
2489 httpSetField(http_t
*http
, /* I - Connection to server */
2490 http_field_t field
, /* I - Field index */
2491 const char *value
) /* I - Value */
2494 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2495 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2499 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2501 if (field
== HTTP_FIELD_AUTHORIZATION
)
2504 * Special case for Authorization: as its contents can be
2505 * longer than HTTP_MAX_VALUE
2508 if (http
->field_authorization
)
2509 free(http
->field_authorization
);
2511 http
->field_authorization
= strdup(value
);
2513 else if (field
== HTTP_FIELD_HOST
)
2516 * Special-case for Host: as we don't want a trailing "." on the hostname and
2517 * need to bracket IPv6 numeric addresses.
2520 char *ptr
= strchr(value
, ':');
2522 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2525 * Bracket IPv6 numeric addresses...
2527 * This is slightly inefficient (basically copying twice), but is an edge
2528 * case and not worth optimizing...
2531 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2532 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2537 * Check for a trailing dot on the hostname...
2540 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2544 ptr
+= strlen(ptr
) - 1;
2555 * 'httpSetLength()' - Set the content-length and content-encoding.
2557 * @since CUPS 1.2/Mac OS X 10.5@
2561 httpSetLength(http_t
*http
, /* I - Connection to server */
2562 size_t length
) /* I - Length (0 for chunked) */
2569 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2570 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2574 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2575 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2576 CUPS_LLFMT
, CUPS_LLCAST length
);
2582 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2584 * The optional timeout callback receives both the HTTP connection and a user
2585 * data pointer and must return 1 to continue or 0 to error (time) out.
2587 * @since CUPS 1.5/Mac OS X 10.7@
2592 http_t
*http
, /* I - Connection to server */
2593 double timeout
, /* I - Number of seconds for timeout,
2594 must be greater than 0 */
2595 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2596 void *user_data
) /* I - User data pointer */
2598 if (!http
|| timeout
<= 0.0)
2601 http
->timeout_cb
= cb
;
2602 http
->timeout_data
= user_data
;
2603 http
->timeout_value
= timeout
;
2606 http_set_timeout(http
->fd
, timeout
);
2608 http_set_wait(http
);
2613 * 'httpTrace()' - Send an TRACE request to the server.
2616 int /* O - Status of call (0 = success) */
2617 httpTrace(http_t
*http
, /* I - Connection to server */
2618 const char *uri
) /* I - URI for trace */
2620 return (http_send(http
, HTTP_TRACE
, uri
));
2625 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2627 * Note: Unlike httpUpdate(), this function does not flush pending write data
2628 * and only retrieves a single status line from the HTTP connection.
2631 int /* O - 1 to continue, 0 to stop */
2632 _httpUpdate(http_t
*http
, /* I - Connection to server */
2633 http_status_t
*status
) /* O - Current HTTP status */
2635 char line
[32768], /* Line from connection... */
2636 *value
; /* Pointer to value on line */
2637 http_field_t field
; /* Field index */
2638 int major
, minor
; /* HTTP version numbers */
2641 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2642 http_states
[http
->state
]));
2645 * Grab a single line from the connection...
2648 if (!httpGets(line
, sizeof(line
), http
))
2650 *status
= HTTP_ERROR
;
2654 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2656 if (line
[0] == '\0')
2659 * Blank line means the start of the data section (if any). Return
2660 * the result code, too...
2662 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2663 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2667 if (http
->status
== HTTP_CONTINUE
)
2669 *status
= http
->status
;
2673 if (http
->status
< HTTP_BAD_REQUEST
)
2674 http
->digest_tries
= 0;
2677 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2679 if (http_setup_ssl(http
) != 0)
2682 closesocket(http
->fd
);
2687 *status
= http
->status
= HTTP_ERROR
;
2691 *status
= HTTP_CONTINUE
;
2694 #endif /* HAVE_SSL */
2696 httpGetLength2(http
);
2698 switch (http
->state
)
2702 case HTTP_POST_RECV
:
2705 case HTTP_POST_SEND
:
2710 http
->state
= HTTP_WAITING
;
2714 *status
= http
->status
;
2717 else if (!strncmp(line
, "HTTP/", 5))
2720 * Got the beginning of a response...
2723 int intstatus
; /* Status value as an integer */
2725 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2727 *status
= http
->status
= HTTP_ERROR
;
2731 http
->version
= (http_version_t
)(major
* 100 + minor
);
2732 *status
= http
->status
= (http_status_t
)intstatus
;
2734 else if ((value
= strchr(line
, ':')) != NULL
)
2741 while (_cups_isspace(*value
))
2745 * Be tolerants of servers that send unknown attribute fields...
2748 if (!_cups_strcasecmp(line
, "expect"))
2751 * "Expect: 100-continue" or similar...
2754 http
->expect
= (http_status_t
)atoi(value
);
2756 else if (!_cups_strcasecmp(line
, "cookie"))
2759 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2762 httpSetCookie(http
, value
);
2764 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
2765 httpSetField(http
, field
, value
);
2768 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
2773 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
2774 *status
= http
->status
= HTTP_ERROR
;
2783 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2786 http_status_t
/* O - HTTP status */
2787 httpUpdate(http_t
*http
) /* I - Connection to server */
2789 http_status_t status
; /* Request status */
2792 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2793 http_states
[http
->state
]));
2796 * Flush pending data, if any...
2801 DEBUG_puts("2httpUpdate: flushing buffer...");
2803 if (httpFlushWrite(http
) < 0)
2804 return (HTTP_ERROR
);
2808 * If we haven't issued any commands, then there is nothing to "update"...
2811 if (http
->state
== HTTP_WAITING
)
2812 return (HTTP_CONTINUE
);
2815 * Grab all of the lines we can from the connection...
2818 while (_httpUpdate(http
, &status
));
2821 * See if there was an error...
2824 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2826 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2827 return (http
->status
);
2832 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2833 strerror(http
->error
)));
2834 http
->status
= HTTP_ERROR
;
2835 return (HTTP_ERROR
);
2839 * Return the current status...
2847 * '_httpWait()' - Wait for data available on a connection (no flush).
2850 int /* O - 1 if data is available, 0 otherwise */
2851 _httpWait(http_t
*http
, /* I - Connection to server */
2852 int msec
, /* I - Milliseconds to wait */
2853 int usessl
) /* I - Use SSL context? */
2856 struct pollfd pfd
; /* Polled file descriptor */
2858 fd_set input_set
; /* select() input set */
2859 struct timeval timeout
; /* Timeout */
2860 #endif /* HAVE_POLL */
2861 int nfds
; /* Result from select()/poll() */
2864 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2868 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2873 * Check the SSL/TLS buffers for data first...
2877 if (http
->tls
&& usessl
)
2880 if (SSL_pending(http
->tls
))
2882 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2886 # elif defined(HAVE_GNUTLS)
2887 if (gnutls_record_check_pending(http
->tls
))
2889 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2893 # elif defined(HAVE_CDSASSL)
2894 size_t bytes
; /* Bytes that are available */
2896 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2899 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2902 # endif /* HAVE_LIBSSL */
2904 #endif /* HAVE_SSL */
2907 * Then try doing a select() or poll() to poll the socket...
2912 pfd
.events
= POLLIN
;
2914 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2915 (errno
== EINTR
|| errno
== EAGAIN
));
2920 FD_ZERO(&input_set
);
2921 FD_SET(http
->fd
, &input_set
);
2923 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2927 timeout
.tv_sec
= msec
/ 1000;
2928 timeout
.tv_usec
= (msec
% 1000) * 1000;
2930 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2933 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2935 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2938 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2939 WSAGetLastError() == WSAEWOULDBLOCK
));
2941 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2943 #endif /* HAVE_POLL */
2945 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2953 * 'httpWait()' - Wait for data available on a connection.
2955 * @since CUPS 1.1.19/Mac OS X 10.3@
2958 int /* O - 1 if data is available, 0 otherwise */
2959 httpWait(http_t
*http
, /* I - Connection to server */
2960 int msec
) /* I - Milliseconds to wait */
2963 * First see if there is data in the buffer...
2966 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
2973 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
2978 * Flush pending data, if any...
2983 DEBUG_puts("3httpWait: Flushing write buffer.");
2985 if (httpFlushWrite(http
) < 0)
2990 * If not, check the SSL/TLS buffers and do a select() on the connection...
2993 return (_httpWait(http
, msec
, 1));
2998 * 'httpWrite()' - Write data to a HTTP connection.
3000 * This function is deprecated. Use the httpWrite2() function which can
3001 * write more than 2GB of data.
3006 int /* O - Number of bytes written */
3007 httpWrite(http_t
*http
, /* I - Connection to server */
3008 const char *buffer
, /* I - Buffer for data */
3009 int length
) /* I - Number of bytes to write */
3011 return ((int)httpWrite2(http
, buffer
, length
));
3016 * 'httpWrite2()' - Write data to a HTTP connection.
3018 * @since CUPS 1.2/Mac OS X 10.5@
3021 ssize_t
/* O - Number of bytes written */
3022 httpWrite2(http_t
*http
, /* I - Connection to server */
3023 const char *buffer
, /* I - Buffer for data */
3024 size_t length
) /* I - Number of bytes to write */
3026 ssize_t bytes
; /* Bytes written */
3029 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3030 buffer
, CUPS_LLCAST length
));
3033 * Range check input...
3036 if (http
== NULL
|| buffer
== NULL
)
3040 * Mark activity on the connection...
3043 http
->activity
= time(NULL
);
3046 * Buffer small writes for better performance...
3051 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3053 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3054 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3056 httpFlushWrite(http
);
3059 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3060 length
< sizeof(http
->wbuffer
))
3063 * Write to buffer...
3066 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3067 CUPS_LLCAST length
));
3069 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3070 http
->wused
+= (int)length
;
3071 bytes
= (ssize_t
)length
;
3076 * Otherwise write the data directly...
3079 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3080 CUPS_LLCAST length
));
3082 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3083 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3085 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3087 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3088 CUPS_LLCAST bytes
));
3091 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3092 http
->data_remaining
-= bytes
;
3098 * Handle end-of-request processing...
3101 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3102 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3105 * Finished with the transfer; unless we are sending POST or PUT
3109 DEBUG_puts("2httpWrite: changing states...");
3112 httpFlushWrite(http
);
3114 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3117 * Send a 0-length chunk at the end of the request...
3120 http_write(http
, "0\r\n\r\n", 5);
3123 * Reset the data state...
3126 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3127 http
->data_remaining
= 0;
3135 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3137 * '_httpWriteCDSA()' - Write function for the CDSA library.
3140 OSStatus
/* O - -1 on error, 0 on success */
3142 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3143 const void *data
, /* I - Data buffer */
3144 size_t *dataLength
) /* IO - Number of bytes */
3146 OSStatus result
; /* Return value */
3147 ssize_t bytes
; /* Number of bytes read */
3148 http_t
*http
; /* HTTP connection */
3151 http
= (http_t
*)connection
;
3155 bytes
= write(http
->fd
, data
, *dataLength
);
3157 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3159 if (bytes
== *dataLength
)
3163 else if (bytes
>= 0)
3165 *dataLength
= bytes
;
3166 result
= errSSLWouldBlock
;
3172 if (errno
== EAGAIN
)
3173 result
= errSSLWouldBlock
;
3175 result
= errSSLClosedAbort
;
3180 #endif /* HAVE_SSL && HAVE_CDSASSL */
3183 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3185 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3188 ssize_t
/* O - Number of bytes written or -1 on error */
3190 gnutls_transport_ptr ptr
, /* I - Connection to server */
3191 const void *data
, /* I - Data buffer */
3192 size_t length
) /* I - Number of bytes to write */
3194 ssize_t bytes
; /* Bytes written */
3197 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3199 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3201 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3202 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3205 #endif /* HAVE_SSL && HAVE_GNUTLS */
3208 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3210 * 'http_bio_ctrl()' - Control the HTTP connection.
3213 static long /* O - Result/data */
3214 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3215 int cmd
, /* I - Control command */
3216 long arg1
, /* I - First argument */
3217 void *arg2
) /* I - Second argument */
3224 case BIO_CTRL_RESET
:
3228 case BIO_C_SET_FILE_PTR
:
3233 case BIO_C_GET_FILE_PTR
:
3236 *((void **)arg2
) = h
->ptr
;
3243 case BIO_CTRL_FLUSH
:
3250 * 'http_bio_free()' - Free OpenSSL data.
3253 static int /* O - 1 on success, 0 on failure */
3254 http_bio_free(BIO
*h
) /* I - BIO data */
3270 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3273 static int /* O - 1 on success, 0 on failure */
3274 http_bio_new(BIO
*h
) /* I - BIO data */
3289 * 'http_bio_puts()' - Send a string for OpenSSL.
3292 static int /* O - Bytes written */
3293 http_bio_puts(BIO
*h
, /* I - BIO data */
3294 const char *str
) /* I - String to write */
3297 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3299 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3305 * 'http_bio_read()' - Read data for OpenSSL.
3308 static int /* O - Bytes read */
3309 http_bio_read(BIO
*h
, /* I - BIO data */
3310 char *buf
, /* I - Buffer */
3311 int size
) /* I - Number of bytes to read */
3313 http_t
*http
; /* HTTP connection */
3316 http
= (http_t
*)h
->ptr
;
3318 if (!http
->blocking
)
3321 * Make sure we have data before we read...
3324 while (!_httpWait(http
, http
->wait_value
, 0))
3326 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
3330 http
->error
= WSAETIMEDOUT
;
3332 http
->error
= ETIMEDOUT
;
3339 return (recv(http
->fd
, buf
, size
, 0));
3344 * 'http_bio_write()' - Write data for OpenSSL.
3347 static int /* O - Bytes written */
3348 http_bio_write(BIO
*h
, /* I - BIO data */
3349 const char *buf
, /* I - Buffer to write */
3350 int num
) /* I - Number of bytes to write */
3352 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3354 #endif /* HAVE_SSL && HAVE_LIBSSL */
3359 * 'http_debug_hex()' - Do a hex dump of a buffer.
3363 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3364 const char *buffer
, /* I - Buffer to dump */
3365 int bytes
) /* I - Bytes to dump */
3367 int i
, j
, /* Looping vars */
3368 ch
; /* Current character */
3369 char line
[255], /* Line buffer */
3370 *start
, /* Start of line after prefix */
3371 *ptr
; /* Pointer into line */
3374 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3377 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
3379 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3380 start
= line
+ strlen(line
);
3382 for (i
= 0; i
< bytes
; i
+= 16)
3384 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3385 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3397 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3399 ch
= buffer
[i
+ j
] & 255;
3401 if (ch
< ' ' || ch
>= 127)
3415 * 'http_field()' - Return the field index for a field name.
3418 static http_field_t
/* O - Field index */
3419 http_field(const char *name
) /* I - String name */
3421 int i
; /* Looping var */
3424 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3425 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
3426 return ((http_field_t
)i
);
3428 return (HTTP_FIELD_UNKNOWN
);
3434 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3437 static int /* O - Bytes read */
3438 http_read_ssl(http_t
*http
, /* I - Connection to server */
3439 char *buf
, /* I - Buffer to store data */
3440 int len
) /* I - Length of buffer */
3442 # if defined(HAVE_LIBSSL)
3443 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3445 # elif defined(HAVE_GNUTLS)
3446 ssize_t result
; /* Return value */
3449 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3451 if (result
< 0 && !errno
)
3454 * Convert GNU TLS error to errno value...
3459 case GNUTLS_E_INTERRUPTED
:
3463 case GNUTLS_E_AGAIN
:
3475 return ((int)result
);
3477 # elif defined(HAVE_CDSASSL)
3478 int result
; /* Return value */
3479 OSStatus error
; /* Error info */
3480 size_t processed
; /* Number of bytes processed */
3483 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3484 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
3489 result
= (int)processed
;
3492 case errSSLWouldBlock
:
3494 result
= (int)processed
;
3502 case errSSLClosedGraceful
:
3505 result
= (int)processed
;
3516 # elif defined(HAVE_SSPISSL)
3517 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3518 # endif /* HAVE_LIBSSL */
3520 #endif /* HAVE_SSL */
3524 * 'http_send()' - Send a request with all fields and the trailing blank line.
3527 static int /* O - 0 on success, non-zero on error */
3528 http_send(http_t
*http
, /* I - Connection to server */
3529 http_state_t request
, /* I - Request code */
3530 const char *uri
) /* I - URI */
3532 int i
; /* Looping var */
3533 char buf
[1024]; /* Encoded URI buffer */
3534 static const char * const codes
[] =
3535 { /* Request code strings */
3552 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3553 http
, codes
[request
], uri
));
3555 if (http
== NULL
|| uri
== NULL
)
3559 * Set the User-Agent field if it isn't already...
3562 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3563 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3566 * Encode the URI as needed...
3569 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3572 * See if we had an error the last time around; if so, reconnect...
3575 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3576 if (httpReconnect(http
))
3580 * Flush any written data that is pending...
3585 if (httpFlushWrite(http
) < 0)
3586 if (httpReconnect(http
))
3591 * Send the request header...
3594 http
->state
= request
;
3595 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3597 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3600 http
->status
= HTTP_CONTINUE
;
3603 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3605 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3606 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3608 #endif /* HAVE_SSL */
3610 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3612 http
->status
= HTTP_ERROR
;
3616 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3617 if (http
->fields
[i
][0] != '\0')
3619 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3620 httpGetField(http
, i
)));
3622 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3623 httpGetField(http
, i
)) < 1)
3625 http
->status
= HTTP_ERROR
;
3631 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3633 http
->status
= HTTP_ERROR
;
3637 if (http
->expect
== HTTP_CONTINUE
&&
3638 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3639 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3641 http
->status
= HTTP_ERROR
;
3645 if (httpPrintf(http
, "\r\n") < 1)
3647 http
->status
= HTTP_ERROR
;
3651 if (httpFlushWrite(http
) < 0)
3654 httpGetLength2(http
);
3655 httpClearFields(http
);
3658 * The Kerberos and AuthRef authentication strings can only be used once...
3661 if (http
->field_authorization
&& http
->authstring
&&
3662 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3663 !strncmp(http
->authstring
, "AuthRef", 7)))
3665 http
->_authstring
[0] = '\0';
3667 if (http
->authstring
!= http
->_authstring
)
3668 free(http
->authstring
);
3670 http
->authstring
= http
->_authstring
;
3678 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
3680 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3683 static int /* O - Status of connection */
3684 http_set_credentials(http_t
*http
) /* I - Connection to server */
3686 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3687 OSStatus error
= 0; /* Error code */
3688 http_tls_credentials_t credentials
= NULL
;
3689 /* TLS credentials */
3692 DEBUG_printf(("7http_set_credentials(%p)", http
));
3695 * Prefer connection specific credentials...
3698 if ((credentials
= http
->tls_credentials
) == NULL
)
3699 credentials
= cg
->tls_credentials
;
3701 # if HAVE_SECPOLICYCREATESSL
3703 * Otherwise root around in the user's keychain to see if one can be found...
3708 CFDictionaryRef query
; /* Query dictionary */
3709 CFTypeRef matches
= NULL
; /* Matching credentials */
3710 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3711 CFTypeRef keys
[] = { kSecClass
,
3714 /* Keys for dictionary */
3715 CFTypeRef values
[] = { kSecClassCertificate
,
3718 /* Values for dictionary */
3721 * Get the names associated with the server.
3724 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3726 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3732 * Create a query which will return all identities that can sign and match
3733 * the passed in policy.
3736 query
= CFDictionaryCreate(NULL
,
3737 (const void**)(&keys
[0]),
3738 (const void**)(&values
[0]),
3739 sizeof(keys
) / sizeof(keys
[0]),
3740 &kCFTypeDictionaryKeyCallBacks
,
3741 &kCFTypeDictionaryValueCallBacks
);
3744 error
= SecItemCopyMatching(query
, &matches
);
3745 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3754 CFRelease(dn_array
);
3756 # endif /* HAVE_SECPOLICYCREATESSL */
3760 error
= SSLSetCertificate(http
->tls
, credentials
);
3761 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3765 DEBUG_puts("4http_set_credentials: No credentials to set.");
3769 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
3773 * 'http_set_timeout()' - Set the socket timeout values.
3777 http_set_timeout(int fd
, /* I - File descriptor */
3778 double timeout
) /* I - Timeout in seconds */
3781 DWORD tv
= (DWORD
)(timeout
* 1000);
3782 /* Timeout in milliseconds */
3784 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&tv
, sizeof(tv
));
3785 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&tv
, sizeof(tv
));
3788 struct timeval tv
; /* Timeout in secs and usecs */
3790 tv
.tv_sec
= (int)timeout
;
3791 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
3793 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, &tv
, sizeof(tv
));
3794 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
3800 * 'http_set_wait()' - Set the default wait value for reads.
3804 http_set_wait(http_t
*http
) /* I - Connection to server */
3808 http
->wait_value
= (int)(http
->timeout_value
* 1000);
3810 if (http
->wait_value
<= 0)
3811 http
->wait_value
= 60000;
3814 http
->wait_value
= 10000;
3819 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3822 static int /* O - 0 on success, -1 on failure */
3823 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3825 _cups_globals_t
*cg
= _cupsGlobals();
3826 /* Pointer to library globals */
3827 int any_root
; /* Allow any root */
3830 SSL_CTX
*context
; /* Context for encryption */
3831 BIO
*bio
; /* BIO data */
3832 const char *message
= NULL
;/* Error message */
3833 # elif defined(HAVE_GNUTLS)
3834 int status
; /* Status of handshake */
3835 gnutls_certificate_client_credentials
*credentials
;
3836 /* TLS credentials */
3837 # elif defined(HAVE_CDSASSL)
3838 OSStatus error
; /* Error code */
3839 char *hostname
; /* Hostname */
3840 const char *message
= NULL
;/* Error message */
3841 # ifdef HAVE_SECCERTIFICATECOPYDATA
3842 cups_array_t
*credentials
; /* Credentials array */
3843 cups_array_t
*names
; /* CUPS distinguished names */
3844 CFArrayRef dn_array
; /* CF distinguished names array */
3845 CFIndex count
; /* Number of credentials */
3846 CFDataRef data
; /* Certificate data */
3847 int i
; /* Looping var */
3848 http_credential_t
*credential
; /* Credential data */
3849 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3850 # elif defined(HAVE_SSPISSL)
3851 TCHAR username
[256]; /* Username returned from GetUserName() */
3852 TCHAR commonName
[256];/* Common name for certificate */
3853 DWORD dwSize
; /* 32 bit size */
3854 # endif /* HAVE_LIBSSL */
3857 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3860 * Always allow self-signed certificates for the local loopback address...
3863 if (httpAddrLocalhost(http
->hostaddr
))
3866 any_root
= cg
->any_root
;
3871 context
= SSL_CTX_new(SSLv23_client_method());
3873 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3875 bio
= BIO_new(_httpBIOMethods());
3876 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3878 http
->tls
= SSL_new(context
);
3879 SSL_set_bio(http
->tls
, bio
, bio
);
3881 if (SSL_connect(http
->tls
) != 1)
3883 unsigned long error
; /* Error code */
3885 while ((error
= ERR_get_error()) != 0)
3887 message
= ERR_error_string(error
, NULL
);
3888 DEBUG_printf(("8http_setup_ssl: %s", message
));
3891 SSL_CTX_free(context
);
3892 SSL_free(http
->tls
);
3896 http
->error
= WSAGetLastError();
3898 http
->error
= errno
;
3900 http
->status
= HTTP_ERROR
;
3903 message
= _("Unable to establish a secure connection to host.");
3905 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
3910 # elif defined(HAVE_GNUTLS)
3913 credentials
= (gnutls_certificate_client_credentials
*)
3914 malloc(sizeof(gnutls_certificate_client_credentials
));
3915 if (credentials
== NULL
)
3917 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
3919 http
->error
= errno
;
3920 http
->status
= HTTP_ERROR
;
3921 _cupsSetHTTPError(HTTP_ERROR
);
3926 gnutls_certificate_allocate_credentials(credentials
);
3928 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3929 gnutls_set_default_priority(http
->tls
);
3930 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, http
->hostname
, strlen(http
->hostname
));
3931 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3932 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3933 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3934 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3936 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3938 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
3939 status
, gnutls_strerror(status
)));
3941 if (gnutls_error_is_fatal(status
))
3944 http
->status
= HTTP_ERROR
;
3946 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
3948 gnutls_deinit(http
->tls
);
3949 gnutls_certificate_free_credentials(*credentials
);
3957 http
->tls_credentials
= credentials
;
3959 # elif defined(HAVE_CDSASSL)
3960 if ((error
= SSLNewContext(false, &http
->tls
)))
3962 http
->error
= errno
;
3963 http
->status
= HTTP_ERROR
;
3964 _cupsSetHTTPError(HTTP_ERROR
);
3969 error
= SSLSetConnection(http
->tls
, http
);
3970 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
3974 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
3975 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
3980 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
3981 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
3982 any_root
, (int)error
));
3987 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
3988 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
3989 cg
->expired_certs
, (int)error
));
3994 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
3995 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
3996 cg
->expired_root
, (int)error
));
3999 # ifdef HAVE_SSLSETPROTOCOLVERSIONMAX
4002 error
= SSLSetProtocolVersionMax(http
->tls
, kTLSProtocol1
);
4003 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionMax(kTLSProtocol1), "
4004 "error=%d", (int)error
));
4006 # endif /* HAVE_SSLSETPROTOCOLVERSIONMAX */
4008 # ifdef HAVE_SECCERTIFICATECOPYDATA
4011 if (cg
->client_cert_cb
)
4013 error
= SSLSetSessionOption(http
->tls
,
4014 kSSLSessionOptionBreakOnCertRequested
, true);
4015 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
4016 "error=%d", (int)error
));
4020 error
= http_set_credentials(http
);
4021 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
4027 * If there's a server certificate callback installed let it evaluate the
4028 * certificate(s) during the handshake...
4031 if (!error
&& cg
->server_cert_cb
!= NULL
)
4033 error
= SSLSetEnableCertVerify(http
->tls
, false);
4034 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
4039 error
= SSLSetSessionOption(http
->tls
,
4040 kSSLSessionOptionBreakOnServerAuth
, true);
4041 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
4042 "error=%d", (int)error
));
4045 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4049 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
4050 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
4052 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
4058 int done
= 0; /* Are we done yet? */
4060 while (!error
&& !done
)
4062 error
= SSLHandshake(http
->tls
);
4064 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
4072 case errSSLWouldBlock
:
4076 # ifdef HAVE_SECCERTIFICATECOPYDATA
4077 case errSSLServerAuthCompleted
:
4079 if (cg
->server_cert_cb
)
4081 error
= httpCopyCredentials(http
, &credentials
);
4084 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
4085 cg
->server_cert_data
);
4086 httpFreeCredentials(credentials
);
4089 DEBUG_printf(("4http_setup_ssl: Server certificate callback returned "
4090 "%d.", (int)error
));
4094 case errSSLClientCertRequested
:
4097 if (cg
->client_cert_cb
)
4100 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
4103 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
4105 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
4107 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
4109 if ((credential
= malloc(sizeof(*credential
))))
4111 credential
->datalen
= CFDataGetLength(data
);
4112 if ((credential
->data
= malloc(credential
->datalen
)))
4114 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
4115 credential
->datalen
);
4116 cupsArrayAdd(names
, credential
);
4122 CFRelease(dn_array
);
4127 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
4128 cg
->client_cert_data
);
4130 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
4131 "returned %d.", (int)error
));
4134 httpFreeCredentials(names
);
4137 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4139 case errSSLUnknownRootCert
:
4140 message
= _("Unable to establish a secure connection to host "
4141 "(untrusted certificate).");
4144 case errSSLNoRootCert
:
4145 message
= _("Unable to establish a secure connection to host "
4146 "(self-signed certificate).");
4149 case errSSLCertExpired
:
4150 message
= _("Unable to establish a secure connection to host "
4151 "(expired certificate).");
4154 case errSSLCertNotYetValid
:
4155 message
= _("Unable to establish a secure connection to host "
4156 "(certificate not yet valid).");
4159 case errSSLHostNameMismatch
:
4160 message
= _("Unable to establish a secure connection to host "
4161 "(host name mismatch).");
4164 case errSSLXCertChainInvalid
:
4165 message
= _("Unable to establish a secure connection to host "
4166 "(certificate chain invalid).");
4169 case errSSLConnectionRefused
:
4170 message
= _("Unable to establish a secure connection to host "
4171 "(peer dropped connection before responding).");
4182 http
->error
= error
;
4183 http
->status
= HTTP_ERROR
;
4184 errno
= ECONNREFUSED
;
4186 SSLDisposeContext(http
->tls
);
4190 * If an error string wasn't set by the callbacks use a generic one...
4194 #ifdef HAVE_CSSMERRORSTRING
4195 message
= cssmErrorString(error
);
4197 message
= _("Unable to establish a secure connection to host.");
4198 #endif /* HAVE_CSSMERRORSTRING */
4200 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4205 # elif defined(HAVE_SSPISSL)
4206 http
->tls
= _sspiAlloc();
4210 _cupsSetHTTPError(HTTP_ERROR
);
4214 http
->tls
->sock
= http
->fd
;
4215 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4216 GetUserName(username
, &dwSize
);
4217 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4218 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4220 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4223 _sspiFree(http
->tls_credentials
);
4224 http
->tls_credentials
= NULL
;
4227 http
->status
= HTTP_ERROR
;
4229 _cupsSetError(IPP_PKI_ERROR
,
4230 _("Unable to establish a secure connection to host."), 1);
4235 _sspiSetAllowsAnyRoot(http
->tls_credentials
, any_root
);
4236 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4238 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
4240 _sspiFree(http
->tls_credentials
);
4241 http
->tls_credentials
= NULL
;
4244 http
->status
= HTTP_ERROR
;
4246 _cupsSetError(IPP_PKI_ERROR
,
4247 _("Unable to establish a secure connection to host."), 1);
4251 # endif /* HAVE_CDSASSL */
4255 #endif /* HAVE_SSL */
4260 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4264 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4267 SSL_CTX
*context
; /* Context for encryption */
4269 context
= SSL_get_SSL_CTX(http
->tls
);
4271 SSL_shutdown(http
->tls
);
4272 SSL_CTX_free(context
);
4273 SSL_free(http
->tls
);
4275 # elif defined(HAVE_GNUTLS)
4276 gnutls_certificate_client_credentials
*credentials
;
4277 /* TLS credentials */
4279 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4281 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4282 gnutls_deinit(http
->tls
);
4283 gnutls_certificate_free_credentials(*credentials
);
4286 # elif defined(HAVE_CDSASSL)
4287 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4290 SSLDisposeContext(http
->tls
);
4292 if (http
->tls_credentials
)
4293 CFRelease(http
->tls_credentials
);
4295 # elif defined(HAVE_SSPISSL)
4296 _sspiFree(http
->tls_credentials
);
4297 # endif /* HAVE_LIBSSL */
4300 http
->tls_credentials
= NULL
;
4302 #endif /* HAVE_SSL */
4307 * 'http_upgrade()' - Force upgrade to TLS encryption.
4310 static int /* O - Status of connection */
4311 http_upgrade(http_t
*http
) /* I - Connection to server */
4313 int ret
; /* Return value */
4314 http_t myhttp
; /* Local copy of HTTP data */
4317 DEBUG_printf(("7http_upgrade(%p)", http
));
4320 * Flush the connection to make sure any previous "Upgrade" message
4327 * Copy the HTTP data to a local variable so we can do the OPTIONS
4328 * request without interfering with the existing request data...
4331 memcpy(&myhttp
, http
, sizeof(myhttp
));
4334 * Send an OPTIONS request to the server, requiring SSL or TLS
4335 * encryption on the link...
4338 http
->field_authorization
= NULL
; /* Don't free the auth string */
4340 httpClearFields(http
);
4341 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4342 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4344 if ((ret
= httpOptions(http
, "*")) == 0)
4347 * Wait for the secure connection...
4350 while (httpUpdate(http
) == HTTP_CONTINUE
);
4354 * Restore the HTTP request data...
4357 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4358 http
->data_encoding
= myhttp
.data_encoding
;
4359 http
->data_remaining
= myhttp
.data_remaining
;
4360 http
->_data_remaining
= myhttp
._data_remaining
;
4361 http
->expect
= myhttp
.expect
;
4362 http
->field_authorization
= myhttp
.field_authorization
;
4363 http
->digest_tries
= myhttp
.digest_tries
;
4366 * See if we actually went secure...
4372 * Server does not support HTTP upgrade...
4375 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4378 closesocket(http
->fd
);
4390 #endif /* HAVE_SSL */
4394 * 'http_write()' - Write a buffer to a HTTP connection.
4397 static int /* O - Number of bytes written */
4398 http_write(http_t
*http
, /* I - Connection to server */
4399 const char *buffer
, /* I - Buffer for data */
4400 int length
) /* I - Number of bytes to write */
4402 int tbytes
, /* Total bytes sent */
4403 bytes
; /* Bytes sent */
4406 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4413 if (http
->timeout_cb
)
4416 struct pollfd pfd
; /* Polled file descriptor */
4418 fd_set output_set
; /* Output ready for write? */
4419 struct timeval timeout
; /* Timeout value */
4420 #endif /* HAVE_POLL */
4421 int nfds
; /* Result from select()/poll() */
4427 pfd
.events
= POLLOUT
;
4429 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
4430 (errno
== EINTR
|| errno
== EAGAIN
));
4435 FD_ZERO(&output_set
);
4436 FD_SET(http
->fd
, &output_set
);
4438 timeout
.tv_sec
= http
->wait_value
/ 1000;
4439 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
4441 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
4444 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
4445 WSAGetLastError() == WSAEWOULDBLOCK
));
4447 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
4449 #endif /* HAVE_POLL */
4453 http
->error
= errno
;
4456 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4459 http
->error
= WSAEWOULDBLOCK
;
4461 http
->error
= EWOULDBLOCK
;
4471 bytes
= http_write_ssl(http
, buffer
, length
);
4473 #endif /* HAVE_SSL */
4474 bytes
= send(http
->fd
, buffer
, length
, 0);
4479 if (WSAGetLastError() == WSAEINTR
)
4481 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4483 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4486 http
->error
= WSAGetLastError();
4488 else if (WSAGetLastError() != http
->error
&&
4489 WSAGetLastError() != WSAECONNRESET
)
4491 http
->error
= WSAGetLastError();
4498 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4500 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4502 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4505 http
->error
= errno
;
4507 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4509 http
->error
= errno
;
4514 DEBUG_printf(("3http_write: error writing data (%s).",
4515 strerror(http
->error
)));
4526 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4529 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4536 * 'http_write_chunk()' - Write a chunked buffer.
4539 static int /* O - Number bytes written */
4540 http_write_chunk(http_t
*http
, /* I - Connection to server */
4541 const char *buffer
, /* I - Buffer to write */
4542 int length
) /* I - Length of buffer */
4544 char header
[255]; /* Chunk header */
4545 int bytes
; /* Bytes written */
4548 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4549 http
, buffer
, length
));
4552 * Write the chunk header, data, and trailer.
4555 sprintf(header
, "%x\r\n", length
);
4556 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4558 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4562 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4564 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4568 if (http_write(http
, "\r\n", 2) < 0)
4570 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4580 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4583 static int /* O - Bytes written */
4584 http_write_ssl(http_t
*http
, /* I - Connection to server */
4585 const char *buf
, /* I - Buffer holding data */
4586 int len
) /* I - Length of buffer */
4588 ssize_t result
; /* Return value */
4591 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4593 # if defined(HAVE_LIBSSL)
4594 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4596 # elif defined(HAVE_GNUTLS)
4597 result
= gnutls_record_send(http
->tls
, buf
, len
);
4599 if (result
< 0 && !errno
)
4602 * Convert GNU TLS error to errno value...
4607 case GNUTLS_E_INTERRUPTED
:
4611 case GNUTLS_E_AGAIN
:
4623 # elif defined(HAVE_CDSASSL)
4624 OSStatus error
; /* Error info */
4625 size_t processed
; /* Number of bytes processed */
4628 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4633 result
= (int)processed
;
4636 case errSSLWouldBlock
:
4638 result
= (int)processed
;
4646 case errSSLClosedGraceful
:
4649 result
= (int)processed
;
4657 # elif defined(HAVE_SSPISSL)
4658 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
4659 # endif /* HAVE_LIBSSL */
4661 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4663 return ((int)result
);
4665 #endif /* HAVE_SSL */
4669 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".