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 * _httpConvertCredentials() - Convert credentials to the internal format.
38 * _httpCreate() - Create an unconnected HTTP connection.
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_setup_ssl() - Set up SSL/TLS support on a connection.
111 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
112 * http_threadid_cb() - Return the current thread ID.
113 * http_upgrade() - Force upgrade to TLS encryption.
114 * http_write() - Write a buffer to a HTTP connection.
115 * http_write_chunk() - Write a chunked buffer.
116 * http_write_ssl() - Write to a SSL/TLS connection.
120 * Include necessary headers...
123 #include "cups-private.h"
129 # include <sys/time.h>
130 # include <sys/resource.h>
133 # include <sys/poll.h>
134 #endif /* HAVE_POLL */
138 * Some operating systems have done away with the Fxxxx constants for
139 * the fcntl() call; this works around that "feature"...
143 # define FNONBLK O_NONBLOCK
144 #endif /* !FNONBLK */
152 static void http_debug_hex(const char *prefix
, const char *buffer
,
155 static http_field_t
http_field(const char *name
);
156 static int http_send(http_t
*http
, http_state_t request
,
158 static int http_write(http_t
*http
, const char *buffer
,
160 static int http_write_chunk(http_t
*http
, const char *buffer
,
163 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
165 static int http_set_credentials(http_t
*http
);
166 # endif /* HAVE_CDSASSL */
167 static int http_setup_ssl(http_t
*http
);
168 static void http_shutdown_ssl(http_t
*http
);
169 static int http_upgrade(http_t
*http
);
170 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
173 # ifdef HAVE_PTHREAD_H
174 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
175 # endif /* HAVE_PTHREAD_H */
177 # elif defined(HAVE_LIBSSL)
178 static _cups_mutex_t
*http_locks
; /* OpenSSL lock mutexes */
180 static void http_locking_cb(int mode
, int type
, const char *file
,
182 static unsigned long http_threadid_cb(void);
183 # endif /* HAVE_GNUTLS */
184 #endif /* HAVE_SSL */
191 static const char * const http_fields
[] =
208 "If-Unmodified-since",
222 static const char * const http_states
[] =
242 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
244 * BIO methods for OpenSSL...
247 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
248 static int http_bio_read(BIO
*h
, char *buf
, int size
);
249 static int http_bio_puts(BIO
*h
, const char *str
);
250 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
251 static int http_bio_new(BIO
*h
);
252 static int http_bio_free(BIO
*data
);
254 static BIO_METHOD http_bio_methods
=
261 NULL
, /* http_bio_gets, */
267 #endif /* HAVE_SSL && HAVE_LIBSSL */
271 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
273 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
278 int /* O - 0 on success, -1 on error */
280 cups_array_t
*credentials
, /* I - Credentials array */
281 const void *data
, /* I - PEM-encoded X.509 data */
282 size_t datalen
) /* I - Length of data */
284 http_credential_t
*credential
; /* Credential data */
287 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
289 credential
->datalen
= datalen
;
291 if ((credential
->data
= malloc(datalen
)) != NULL
)
293 memcpy(credential
->data
, data
, datalen
);
294 cupsArrayAdd(credentials
, credential
);
305 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
307 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
310 BIO_METHOD
* /* O - BIO methods for OpenSSL */
311 _httpBIOMethods(void)
313 return (&http_bio_methods
);
315 #endif /* HAVE_SSL && HAVE_LIBSSL */
319 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
323 httpBlocking(http_t
*http
, /* I - Connection to server */
324 int b
) /* I - 1 = blocking, 0 = non-blocking */
332 * 'httpCheck()' - Check to see if there is a pending response from the server.
335 int /* O - 0 = no data, 1 = data available */
336 httpCheck(http_t
*http
) /* I - Connection to server */
338 return (httpWait(http
, 0));
343 * 'httpClearCookie()' - Clear the cookie value(s).
345 * @since CUPS 1.1.19/Mac OS X 10.3@
349 httpClearCookie(http_t
*http
) /* I - Connection to server */
363 * 'httpClearFields()' - Clear HTTP request fields.
367 httpClearFields(http_t
*http
) /* I - Connection to server */
371 memset(http
->fields
, 0, sizeof(http
->fields
));
372 if (http
->hostname
[0] == '/')
373 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
375 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
377 if (http
->field_authorization
)
379 free(http
->field_authorization
);
380 http
->field_authorization
= NULL
;
383 http
->expect
= (http_status_t
)0;
389 * 'httpClose()' - Close an HTTP connection.
393 httpClose(http_t
*http
) /* I - Connection to server */
396 OM_uint32 minor_status
; /* Minor status code */
397 #endif /* HAVE_GSSAPI */
400 DEBUG_printf(("httpClose(http=%p)", http
));
403 * Range check input...
410 * Close any open connection...
413 _httpDisconnect(http
);
416 * Free memory used...
419 httpAddrFreeList(http
->addrlist
);
425 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
426 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
428 if (http
->gssname
!= GSS_C_NO_NAME
)
429 gss_release_name(&minor_status
, &http
->gssname
);
430 #endif /* HAVE_GSSAPI */
432 #ifdef HAVE_AUTHORIZATION_H
434 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
435 #endif /* HAVE_AUTHORIZATION_H */
437 httpClearFields(http
);
439 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
440 free(http
->authstring
);
447 * 'httpConnect()' - Connect to a HTTP server.
449 * This function is deprecated - use @link httpConnectEncrypt@ instead.
454 http_t
* /* O - New HTTP connection */
455 httpConnect(const char *host
, /* I - Host to connect to */
456 int port
) /* I - Port number */
458 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
463 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
466 http_t
* /* O - New HTTP connection */
468 const char *host
, /* I - Host to connect to */
469 int port
, /* I - Port number */
470 http_encryption_t encryption
) /* I - Type of encryption to use */
472 http_t
*http
; /* New HTTP connection */
475 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
476 host
, port
, encryption
));
479 * Create the HTTP structure...
482 if ((http
= _httpCreate(host
, port
, NULL
, encryption
, AF_UNSPEC
)) == NULL
)
486 * Connect to the remote system...
489 if (!httpReconnect(http
))
493 * Could not connect to any known address - bail out!
496 httpAddrFreeList(http
->addrlist
);
505 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
511 int /* O - Status of call (0 = success) */
513 http_t
*http
, /* I - Connection to server */
514 cups_array_t
**credentials
) /* O - Array of credentials */
517 # elif defined(HAVE_GNUTLS)
518 # elif defined(HAVE_CDSASSL)
519 OSStatus error
; /* Error code */
520 CFIndex count
; /* Number of credentials */
521 CFArrayRef peerCerts
; /* Peer certificates */
522 SecCertificateRef secCert
; /* Certificate reference */
523 CFDataRef data
; /* Certificate data */
524 int i
; /* Looping var */
525 # elif defined(HAVE_SSPISSL)
526 # endif /* HAVE_LIBSSL */
532 if (!http
|| !http
->tls
|| !credentials
)
538 # elif defined(HAVE_GNUTLS)
541 # elif defined(HAVE_CDSASSL)
542 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
544 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
546 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
548 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
549 if ((data
= SecCertificateCopyData(secCert
)))
551 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
552 CFDataGetLength(data
));
558 CFRelease(peerCerts
);
563 # elif defined(HAVE_SSPISSL)
565 # endif /* HAVE_LIBSSL */
570 * '_httpConvertCredentials()' - Convert credentials to the internal format.
573 http_tls_credentials_t
/* O - Internal credentials */
574 _httpConvertCredentials(
575 cups_array_t
*credentials
) /* I - Array of credentials */
583 # elif defined(HAVE_GNUTLS)
586 # elif defined(HAVE_CDSASSL)
587 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
588 SecCertificateRef secCert
; /* Certificate reference */
589 CFDataRef data
; /* Credential data reference */
590 http_credential_t
*credential
; /* Credential data */
593 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
594 cupsArrayCount(credentials
),
595 &kCFTypeArrayCallBacks
)) == NULL
)
598 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
600 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
602 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
603 credential
->datalen
)))
605 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
608 CFArrayAppendValue(peerCerts
, secCert
);
618 # elif defined(HAVE_SSPISSL)
623 # endif /* HAVE_LIBSSL */
628 * '_httpCreate()' - Create an unconnected HTTP connection.
631 http_t
* /* O - HTTP connection */
633 const char *host
, /* I - Hostname */
634 int port
, /* I - Port number */
635 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
636 http_encryption_t encryption
, /* I - Encryption to use */
637 int family
) /* I - Address family or AF_UNSPEC */
639 http_t
*http
; /* New HTTP connection */
640 char service
[255]; /* Service name */
643 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
644 host
, port
, encryption
));
655 sprintf(service
, "%d", port
);
658 if ((addrlist
= httpAddrGetList(host
, family
, service
)) == NULL
)
662 * Allocate memory for the structure...
665 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
667 httpAddrFreeList(addrlist
);
672 * Initialize the HTTP data...
675 http
->activity
= time(NULL
);
676 http
->addrlist
= addrlist
;
680 http
->gssctx
= GSS_C_NO_CONTEXT
;
681 http
->gssname
= GSS_C_NO_NAME
;
682 #endif /* HAVE_GSSAPI */
683 http
->version
= HTTP_1_1
;
685 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
687 if (port
== 443) /* Always use encryption for https */
688 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
690 http
->encryption
= encryption
;
693 * Return the new structure...
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.", bytes
));
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 (!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 if (!http
->blocking
&& !_httpWait(http
, 10000, 1))
1329 DEBUG_puts("3httpGets: Timed out!");
1331 http
->error
= WSAETIMEDOUT
;
1333 http
->error
= ETIMEDOUT
;
1340 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1341 HTTP_MAX_BUFFER
- http
->used
);
1343 #endif /* HAVE_SSL */
1344 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1345 HTTP_MAX_BUFFER
- http
->used
, 0);
1347 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1352 * Nope, can't get a line this time...
1356 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1358 if (WSAGetLastError() == WSAEINTR
)
1360 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1362 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1365 http
->error
= WSAGetLastError();
1367 else if (WSAGetLastError() != http
->error
)
1369 http
->error
= WSAGetLastError();
1374 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1378 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1380 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1382 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1385 http
->error
= errno
;
1387 else if (errno
!= http
->error
)
1389 http
->error
= errno
;
1396 else if (bytes
== 0)
1398 http
->error
= EPIPE
;
1404 * Yup, update the amount used...
1407 http
->used
+= bytes
;
1411 * Now copy as much of the current line as possible...
1414 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1415 lineptr
< lineend
&& bufptr
< bufend
;)
1417 if (*bufptr
== 0x0a)
1423 else if (*bufptr
== 0x0d)
1426 *lineptr
++ = *bufptr
++;
1429 http
->used
-= (int)(bufptr
- http
->buffer
);
1431 memmove(http
->buffer
, bufptr
, http
->used
);
1439 http
->activity
= time(NULL
);
1443 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1449 DEBUG_puts("3httpGets: No new line available!");
1456 * 'httpHead()' - Send a HEAD request to the server.
1459 int /* O - Status of call (0 = success) */
1460 httpHead(http_t
*http
, /* I - Connection to server */
1461 const char *uri
) /* I - URI for head */
1463 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1464 return (http_send(http
, HTTP_HEAD
, uri
));
1469 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1470 * default HTTP proxy (if any).
1474 httpInitialize(void)
1476 static int initialized
= 0; /* Have we been called before? */
1478 WSADATA winsockdata
; /* WinSock data */
1481 int i
; /* Looping var */
1482 unsigned char data
[1024]; /* Seed data */
1483 #endif /* HAVE_LIBSSL */
1489 _cupsGlobalUnlock();
1494 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1496 #elif !defined(SO_NOSIGPIPE)
1498 * Ignore SIGPIPE signals...
1502 sigset(SIGPIPE
, SIG_IGN
);
1504 # elif defined(HAVE_SIGACTION)
1505 struct sigaction action
; /* POSIX sigaction data */
1508 memset(&action
, 0, sizeof(action
));
1509 action
.sa_handler
= SIG_IGN
;
1510 sigaction(SIGPIPE
, &action
, NULL
);
1513 signal(SIGPIPE
, SIG_IGN
);
1514 # endif /* !SO_NOSIGPIPE */
1519 * Make sure we handle threading properly...
1522 # ifdef HAVE_PTHREAD_H
1523 gcry_control(GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
1524 # endif /* HAVE_PTHREAD_H */
1527 * Initialize GNU TLS...
1530 gnutls_global_init();
1532 #elif defined(HAVE_LIBSSL)
1534 * Initialize OpenSSL...
1537 SSL_load_error_strings();
1541 * Set the threading callbacks...
1544 http_locks
= calloc(CRYPTO_num_locks(), sizeof(_cups_mutex_t
));
1545 # ifdef HAVE_PTHREAD_H
1546 for (i
= 0; i
< CRYPTO_num_locks(); i
++)
1547 pthread_mutex_init(http_locks
+ i
, NULL
);
1548 # endif /* HAVE_PTHREAD_H */
1550 CRYPTO_set_id_callback(http_threadid_cb
);
1551 CRYPTO_set_locking_callback(http_locking_cb
);
1554 * Using the current time is a dubious random seed, but on some systems
1555 * it is the best we can do (on others, this seed isn't even used...)
1558 CUPS_SRAND(time(NULL
));
1560 for (i
= 0; i
< sizeof(data
); i
++)
1561 data
[i
] = CUPS_RAND();
1563 RAND_seed(data
, sizeof(data
));
1564 #endif /* HAVE_GNUTLS */
1567 _cupsGlobalUnlock();
1572 * 'httpOptions()' - Send an OPTIONS request to the server.
1575 int /* O - Status of call (0 = success) */
1576 httpOptions(http_t
*http
, /* I - Connection to server */
1577 const char *uri
) /* I - URI for options */
1579 return (http_send(http
, HTTP_OPTIONS
, uri
));
1584 * '_httpPeek()' - Peek at data from a HTTP connection.
1586 * This function copies available data from the given HTTP connection, reading
1587 * a buffer as needed. The data is still available for reading using
1588 * @link httpRead@ or @link httpRead2@.
1590 * For non-blocking connections the usual timeouts apply.
1593 ssize_t
/* O - Number of bytes copied */
1594 _httpPeek(http_t
*http
, /* I - Connection to server */
1595 char *buffer
, /* I - Buffer for data */
1596 size_t length
) /* I - Maximum number of bytes */
1598 ssize_t bytes
; /* Bytes read */
1599 char len
[32]; /* Length string */
1602 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1603 http
, buffer
, CUPS_LLCAST length
));
1605 if (http
== NULL
|| buffer
== NULL
)
1608 http
->activity
= time(NULL
);
1614 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1615 http
->data_remaining
<= 0)
1617 DEBUG_puts("2_httpPeek: Getting chunk length...");
1619 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1621 DEBUG_puts("1_httpPeek: Could not get length!");
1625 http
->data_remaining
= strtoll(len
, NULL
, 16);
1626 if (http
->data_remaining
< 0)
1628 DEBUG_puts("1_httpPeek: Negative chunk length!");
1633 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1634 CUPS_LLCAST http
->data_remaining
));
1636 if (http
->data_remaining
<= 0)
1639 * A zero-length chunk ends a transfer; unless we are reading POST
1643 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1644 httpGets(len
, sizeof(len
), http
);
1646 if (http
->state
== HTTP_POST_RECV
)
1649 http
->state
= HTTP_WAITING
;
1652 * Prevent future reads for this request...
1655 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1659 else if (length
> (size_t)http
->data_remaining
)
1660 length
= (size_t)http
->data_remaining
;
1662 if (http
->used
== 0)
1665 * Buffer small reads for better performance...
1668 if (!http
->blocking
&& !httpWait(http
, 10000))
1671 if (http
->data_remaining
> sizeof(http
->buffer
))
1672 bytes
= sizeof(http
->buffer
);
1674 bytes
= http
->data_remaining
;
1678 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1680 #endif /* HAVE_SSL */
1682 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1685 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1687 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1696 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1698 http
->error
= WSAGetLastError();
1702 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1704 http
->error
= errno
;
1711 http
->error
= EPIPE
;
1718 if (length
> (size_t)http
->used
)
1719 length
= (size_t)http
->used
;
1721 bytes
= (ssize_t
)length
;
1723 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1726 memcpy(buffer
, http
->buffer
, length
);
1734 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1737 http
->error
= WSAGetLastError();
1739 if (errno
== EINTR
|| errno
== EAGAIN
)
1742 http
->error
= errno
;
1745 else if (bytes
== 0)
1747 http
->error
= EPIPE
;
1752 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1760 * 'httpPost()' - Send a POST request to the server.
1763 int /* O - Status of call (0 = success) */
1764 httpPost(http_t
*http
, /* I - Connection to server */
1765 const char *uri
) /* I - URI for post */
1767 return (http_send(http
, HTTP_POST
, uri
));
1772 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1777 int /* O - Number of bytes written */
1778 httpPrintf(http_t
*http
, /* I - Connection to server */
1779 const char *format
, /* I - printf-style format string */
1780 ...) /* I - Additional args as needed */
1782 int bytes
; /* Number of bytes to write */
1783 char buf
[16384]; /* Buffer for formatted string */
1784 va_list ap
; /* Variable argument pointer */
1787 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1789 va_start(ap
, format
);
1790 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1793 DEBUG_printf(("3httpPrintf: %s", buf
));
1795 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1796 return (httpWrite2(http
, buf
, bytes
));
1801 DEBUG_puts("4httpPrintf: flushing existing data...");
1803 if (httpFlushWrite(http
) < 0)
1807 return (http_write(http
, buf
, bytes
));
1813 * 'httpPut()' - Send a PUT request to the server.
1816 int /* O - Status of call (0 = success) */
1817 httpPut(http_t
*http
, /* I - Connection to server */
1818 const char *uri
) /* I - URI to put */
1820 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1821 return (http_send(http
, HTTP_PUT
, uri
));
1826 * 'httpRead()' - Read data from a HTTP connection.
1828 * This function is deprecated. Use the httpRead2() function which can
1829 * read more than 2GB of data.
1834 int /* O - Number of bytes read */
1835 httpRead(http_t
*http
, /* I - Connection to server */
1836 char *buffer
, /* I - Buffer for data */
1837 int length
) /* I - Maximum number of bytes */
1839 return ((int)httpRead2(http
, buffer
, length
));
1844 * 'httpRead2()' - Read data from a HTTP connection.
1846 * @since CUPS 1.2/Mac OS X 10.5@
1849 ssize_t
/* O - Number of bytes read */
1850 httpRead2(http_t
*http
, /* I - Connection to server */
1851 char *buffer
, /* I - Buffer for data */
1852 size_t length
) /* I - Maximum number of bytes */
1854 ssize_t bytes
; /* Bytes read */
1855 char len
[32]; /* Length string */
1858 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1859 http
, buffer
, CUPS_LLCAST length
));
1861 if (http
== NULL
|| buffer
== NULL
)
1864 http
->activity
= time(NULL
);
1870 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1871 http
->data_remaining
<= 0)
1873 DEBUG_puts("2httpRead2: Getting chunk length...");
1875 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1877 DEBUG_puts("1httpRead2: Could not get length!");
1881 http
->data_remaining
= strtoll(len
, NULL
, 16);
1882 if (http
->data_remaining
< 0)
1884 DEBUG_puts("1httpRead2: Negative chunk length!");
1889 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1890 CUPS_LLCAST http
->data_remaining
));
1892 if (http
->data_remaining
<= 0)
1895 * A zero-length chunk ends a transfer; unless we are reading POST
1899 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1900 httpGets(len
, sizeof(len
), http
);
1902 if (http
->state
== HTTP_POST_RECV
)
1905 http
->state
= HTTP_WAITING
;
1908 * Prevent future reads for this request...
1911 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1915 else if (length
> (size_t)http
->data_remaining
)
1916 length
= (size_t)http
->data_remaining
;
1918 if (http
->used
== 0 && length
<= 256)
1921 * Buffer small reads for better performance...
1924 if (!http
->blocking
&& !httpWait(http
, 10000))
1927 if (http
->data_remaining
> sizeof(http
->buffer
))
1928 bytes
= sizeof(http
->buffer
);
1930 bytes
= http
->data_remaining
;
1934 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1936 #endif /* HAVE_SSL */
1938 DEBUG_printf(("2httpRead2: reading %d bytes from socket into buffer...",
1941 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1943 DEBUG_printf(("2httpRead2: read %d bytes from socket into buffer...",
1952 if (WSAGetLastError() != WSAEINTR
)
1954 http
->error
= WSAGetLastError();
1957 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1959 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1961 http
->error
= WSAEWOULDBLOCK
;
1966 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1968 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1970 http
->error
= errno
;
1973 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1975 http
->error
= errno
;
1979 else if (errno
!= EINTR
)
1981 http
->error
= errno
;
1988 http
->error
= EPIPE
;
1995 if (length
> (size_t)http
->used
)
1996 length
= (size_t)http
->used
;
1998 bytes
= (ssize_t
)length
;
2000 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2003 memcpy(buffer
, http
->buffer
, length
);
2004 http
->used
-= (int)length
;
2007 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2012 if (!http
->blocking
&& !httpWait(http
, 10000))
2015 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
2017 #endif /* HAVE_SSL */
2020 if (!http
->blocking
&& !httpWait(http
, 10000))
2023 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2024 CUPS_LLCAST length
));
2027 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2029 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2031 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2034 else if (WSAGetLastError() != WSAEINTR
)
2038 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2040 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2042 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2044 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2047 else if (errno
!= EINTR
)
2052 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2053 CUPS_LLCAST bytes
));
2058 http
->data_remaining
-= bytes
;
2060 if (http
->data_remaining
<= INT_MAX
)
2061 http
->_data_remaining
= (int)http
->data_remaining
;
2063 http
->_data_remaining
= INT_MAX
;
2068 if (WSAGetLastError() == WSAEINTR
)
2071 http
->error
= WSAGetLastError();
2073 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2076 http
->error
= errno
;
2081 http
->error
= EPIPE
;
2085 if (http
->data_remaining
== 0)
2087 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2088 httpGets(len
, sizeof(len
), http
);
2090 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2092 if (http
->state
== HTTP_POST_RECV
)
2095 http
->state
= HTTP_WAITING
;
2100 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2107 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2109 * '_httpReadCDSA()' - Read function for the CDSA library.
2112 OSStatus
/* O - -1 on error, 0 on success */
2114 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2115 void *data
, /* I - Data buffer */
2116 size_t *dataLength
) /* IO - Number of bytes */
2118 OSStatus result
; /* Return value */
2119 ssize_t bytes
; /* Number of bytes read */
2120 http_t
*http
; /* HTTP connection */
2123 http
= (http_t
*)connection
;
2125 if (!http
->blocking
)
2128 * Make sure we have data before we read...
2131 if (!_httpWait(http
, 10000, 0))
2133 http
->error
= ETIMEDOUT
;
2140 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2142 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2144 if (bytes
== *dataLength
)
2150 *dataLength
= bytes
;
2151 result
= errSSLWouldBlock
;
2158 result
= errSSLClosedGraceful
;
2159 else if (errno
== EAGAIN
)
2160 result
= errSSLWouldBlock
;
2162 result
= errSSLClosedAbort
;
2167 #endif /* HAVE_SSL && HAVE_CDSASSL */
2170 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2172 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2175 ssize_t
/* O - Number of bytes read or -1 on error */
2177 gnutls_transport_ptr ptr
, /* I - Connection to server */
2178 void *data
, /* I - Buffer */
2179 size_t length
) /* I - Number of bytes to read */
2181 http_t
*http
; /* HTTP connection */
2184 http
= (http_t
*)ptr
;
2186 if (!http
->blocking
)
2189 * Make sure we have data before we read...
2192 if (!_httpWait(http
, 10000, 0))
2194 http
->error
= ETIMEDOUT
;
2199 return (recv(http
->fd
, data
, length
, 0));
2201 #endif /* HAVE_SSL && HAVE_GNUTLS */
2205 * 'httpReconnect()' - Reconnect to a HTTP server.
2208 int /* O - 0 on success, non-zero on failure */
2209 httpReconnect(http_t
*http
) /* I - Connection to server */
2211 http_addrlist_t
*addr
; /* Connected address */
2213 http_addrlist_t
*current
; /* Current address */
2214 char temp
[256]; /* Temporary address string */
2218 DEBUG_printf(("httpReconnect(http=%p)", http
));
2226 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2227 http_shutdown_ssl(http
);
2229 #endif /* HAVE_SSL */
2232 * Close any previously open socket...
2237 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2240 closesocket(http
->fd
);
2249 * Connect to the server...
2253 for (current
= http
->addrlist
; current
; current
= current
->next
)
2254 DEBUG_printf(("2httpReconnect: Address %s:%d",
2255 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2256 _httpAddrPort(&(current
->addr
))));
2259 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
2262 * Unable to connect...
2266 http
->error
= WSAGetLastError();
2268 http
->error
= errno
;
2270 http
->status
= HTTP_ERROR
;
2272 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2273 strerror(http
->error
)));
2278 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2280 if (http
->timeout_value
.tv_sec
> 0)
2283 DWORD timeout_value
= http
->timeout_value
.tv_sec
* 1000 +
2284 http
->timeout_value
.tv_usec
/ 1000;
2285 /* Timeout in milliseconds */
2287 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&timeout_value
,
2288 sizeof(timeout_value
));
2289 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&timeout_value
,
2290 sizeof(timeout_value
));
2292 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, &(http
->timeout_value
),
2293 sizeof(http
->timeout_value
));
2294 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, &(http
->timeout_value
),
2295 sizeof(http
->timeout_value
));
2299 http
->hostaddr
= &(addr
->addr
);
2301 http
->status
= HTTP_CONTINUE
;
2304 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2307 * Always do encryption via SSL.
2310 if (http_setup_ssl(http
) != 0)
2313 closesocket(http
->fd
);
2321 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2322 return (http_upgrade(http
));
2323 #endif /* HAVE_SSL */
2325 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2326 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2327 _httpAddrPort(http
->hostaddr
)));
2334 * 'httpSetAuthString()' - Set the current authorization string.
2336 * This function just stores a copy of the current authorization string in
2337 * the HTTP connection object. You must still call httpSetField() to set
2338 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2339 * httpHead(), httpOptions(), httpPost, or httpPut().
2341 * @since CUPS 1.3/Mac OS X 10.5@
2345 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2346 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2347 const char *data
) /* I - Auth data (NULL for none) */
2350 * Range check input...
2356 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2357 free(http
->authstring
);
2359 http
->authstring
= http
->_authstring
;
2364 * Set the current authorization string...
2367 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2370 if (len
> (int)sizeof(http
->_authstring
))
2372 if ((temp
= malloc(len
)) == NULL
)
2373 len
= sizeof(http
->_authstring
);
2375 http
->authstring
= temp
;
2379 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2381 strlcpy(http
->authstring
, scheme
, len
);
2386 * Clear the current authorization string...
2389 http
->_authstring
[0] = '\0';
2395 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2401 int /* O - Status of call (0 = success) */
2402 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2403 cups_array_t
*credentials
) /* I - Array of credentials */
2405 if (!http
|| cupsArrayCount(credentials
) < 1)
2408 _httpFreeCredentials(http
->tls_credentials
);
2410 http
->tls_credentials
= _httpConvertCredentials(credentials
);
2412 return (http
->tls_credentials
? 0 : -1);
2417 * 'httpSetCookie()' - Set the cookie value(s).
2419 * @since CUPS 1.1.19/Mac OS X 10.3@
2423 httpSetCookie(http_t
*http
, /* I - Connection */
2424 const char *cookie
) /* I - Cookie string */
2433 http
->cookie
= strdup(cookie
);
2435 http
->cookie
= NULL
;
2440 * 'httpSetExpect()' - Set the Expect: header in a request.
2442 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2444 * @since CUPS 1.2/Mac OS X 10.5@
2448 httpSetExpect(http_t
*http
, /* I - Connection to server */
2449 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2452 http
->expect
= expect
;
2457 * 'httpSetField()' - Set the value of an HTTP header.
2461 httpSetField(http_t
*http
, /* I - Connection to server */
2462 http_field_t field
, /* I - Field index */
2463 const char *value
) /* I - Value */
2466 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2467 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2471 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2473 if (field
== HTTP_FIELD_AUTHORIZATION
)
2476 * Special case for Authorization: as its contents can be
2477 * longer than HTTP_MAX_VALUE
2480 if (http
->field_authorization
)
2481 free(http
->field_authorization
);
2483 http
->field_authorization
= strdup(value
);
2485 else if (field
== HTTP_FIELD_HOST
)
2488 * Special-case for Host: as we don't want a trailing "." on the hostname and
2489 * need to bracket IPv6 numeric addresses.
2492 char *ptr
= strchr(value
, ':');
2494 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2497 * Bracket IPv6 numeric addresses...
2499 * This is slightly inefficient (basically copying twice), but is an edge
2500 * case and not worth optimizing...
2503 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2504 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2509 * Check for a trailing dot on the hostname...
2512 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2516 ptr
+= strlen(ptr
) - 1;
2527 * 'httpSetLength()' - Set the content-length and content-encoding.
2529 * @since CUPS 1.2/Mac OS X 10.5@
2533 httpSetLength(http_t
*http
, /* I - Connection to server */
2534 size_t length
) /* I - Length (0 for chunked) */
2541 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2542 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2546 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2547 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2548 CUPS_LLFMT
, CUPS_LLCAST length
);
2554 * '_httpSetTimeout()' - Set read/write timeouts and an optional callback.
2556 * The optional timeout callback receives both the HTTP connection and a user
2557 * data pointer and must return 1 to continue or 0 to error out.
2562 http_t
*http
, /* I - Connection to server */
2563 double timeout
, /* I - Number of seconds for timeout,
2564 must be greater than 0 */
2565 _http_timeout_cb_t cb
, /* I - Callback function or NULL */
2566 void *user_data
) /* I - User data pointer */
2568 if (!http
|| timeout
<= 0.0)
2571 http
->timeout_cb
= cb
;
2572 http
->timeout_data
= user_data
;
2573 http
->timeout_value
.tv_sec
= (int)timeout
;
2574 http
->timeout_value
.tv_usec
= (int)(timeout
* 1000000) % 1000000;
2579 DWORD timeout_value
= http
->timeout_value
.tv_sec
* 1000 +
2580 http
->timeout_value
.tv_usec
/ 1000;
2581 /* Timeout in milliseconds */
2583 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&timeout_value
,
2584 sizeof(timeout_value
));
2585 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&timeout_value
,
2586 sizeof(timeout_value
));
2588 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, &(http
->timeout_value
),
2589 sizeof(http
->timeout_value
));
2590 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, &(http
->timeout_value
),
2591 sizeof(http
->timeout_value
));
2598 * 'httpTrace()' - Send an TRACE request to the server.
2601 int /* O - Status of call (0 = success) */
2602 httpTrace(http_t
*http
, /* I - Connection to server */
2603 const char *uri
) /* I - URI for trace */
2605 return (http_send(http
, HTTP_TRACE
, uri
));
2610 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2612 * Note: Unlike httpUpdate(), this function does not flush pending write data
2613 * and only retrieves a single status line from the HTTP connection.
2616 int /* O - 1 to continue, 0 to stop */
2617 _httpUpdate(http_t
*http
, /* I - Connection to server */
2618 http_status_t
*status
) /* O - Current HTTP status */
2620 char line
[32768], /* Line from connection... */
2621 *value
; /* Pointer to value on line */
2622 http_field_t field
; /* Field index */
2623 int major
, minor
; /* HTTP version numbers */
2626 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2627 http_states
[http
->state
]));
2630 * Grab a single line from the connection...
2633 if (!httpGets(line
, sizeof(line
), http
))
2635 *status
= HTTP_ERROR
;
2639 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2641 if (line
[0] == '\0')
2644 * Blank line means the start of the data section (if any). Return
2645 * the result code, too...
2647 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2648 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2652 if (http
->status
== HTTP_CONTINUE
)
2654 *status
= http
->status
;
2658 if (http
->status
< HTTP_BAD_REQUEST
)
2659 http
->digest_tries
= 0;
2662 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2664 if (http_setup_ssl(http
) != 0)
2667 closesocket(http
->fd
);
2672 *status
= http
->status
= HTTP_ERROR
;
2676 *status
= HTTP_CONTINUE
;
2679 #endif /* HAVE_SSL */
2681 httpGetLength2(http
);
2683 switch (http
->state
)
2687 case HTTP_POST_RECV
:
2690 case HTTP_POST_SEND
:
2695 http
->state
= HTTP_WAITING
;
2699 *status
= http
->status
;
2702 else if (!strncmp(line
, "HTTP/", 5))
2705 * Got the beginning of a response...
2708 int intstatus
; /* Status value as an integer */
2710 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2712 *status
= http
->status
= HTTP_ERROR
;
2716 http
->version
= (http_version_t
)(major
* 100 + minor
);
2717 *status
= http
->status
= (http_status_t
)intstatus
;
2719 else if ((value
= strchr(line
, ':')) != NULL
)
2726 while (_cups_isspace(*value
))
2730 * Be tolerants of servers that send unknown attribute fields...
2733 if (!strcasecmp(line
, "expect"))
2736 * "Expect: 100-continue" or similar...
2739 http
->expect
= (http_status_t
)atoi(value
);
2741 else if (!strcasecmp(line
, "cookie"))
2744 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2747 httpSetCookie(http
, value
);
2749 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
2750 httpSetField(http
, field
, value
);
2753 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
2758 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
2759 *status
= http
->status
= HTTP_ERROR
;
2768 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2771 http_status_t
/* O - HTTP status */
2772 httpUpdate(http_t
*http
) /* I - Connection to server */
2774 http_status_t status
; /* Request status */
2777 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2778 http_states
[http
->state
]));
2781 * Flush pending data, if any...
2786 DEBUG_puts("2httpUpdate: flushing buffer...");
2788 if (httpFlushWrite(http
) < 0)
2789 return (HTTP_ERROR
);
2793 * If we haven't issued any commands, then there is nothing to "update"...
2796 if (http
->state
== HTTP_WAITING
)
2797 return (HTTP_CONTINUE
);
2800 * Grab all of the lines we can from the connection...
2803 while (_httpUpdate(http
, &status
));
2806 * See if there was an error...
2809 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2811 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2812 return (http
->status
);
2817 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2818 strerror(http
->error
)));
2819 http
->status
= HTTP_ERROR
;
2820 return (HTTP_ERROR
);
2824 * Return the current status...
2832 * '_httpWait()' - Wait for data available on a connection (no flush).
2835 int /* O - 1 if data is available, 0 otherwise */
2836 _httpWait(http_t
*http
, /* I - Connection to server */
2837 int msec
, /* I - Milliseconds to wait */
2838 int usessl
) /* I - Use SSL context? */
2841 struct pollfd pfd
; /* Polled file descriptor */
2843 fd_set input_set
; /* select() input set */
2844 struct timeval timeout
; /* Timeout */
2845 #endif /* HAVE_POLL */
2846 int nfds
; /* Result from select()/poll() */
2849 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2853 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2858 * Check the SSL/TLS buffers for data first...
2862 if (http
->tls
&& usessl
)
2865 if (SSL_pending(http
->tls
))
2867 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2871 # elif defined(HAVE_GNUTLS)
2872 if (gnutls_record_check_pending(http
->tls
))
2874 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2878 # elif defined(HAVE_CDSASSL)
2879 size_t bytes
; /* Bytes that are available */
2881 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2884 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2887 # endif /* HAVE_LIBSSL */
2889 #endif /* HAVE_SSL */
2892 * Then try doing a select() or poll() to poll the socket...
2897 pfd
.events
= POLLIN
;
2899 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2900 (errno
== EINTR
|| errno
== EAGAIN
));
2905 FD_ZERO(&input_set
);
2906 FD_SET(http
->fd
, &input_set
);
2908 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2912 timeout
.tv_sec
= msec
/ 1000;
2913 timeout
.tv_usec
= (msec
% 1000) * 1000;
2915 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2918 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2920 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2923 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2924 WSAGetLastError() == WSAEWOULDBLOCK
));
2926 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2928 #endif /* HAVE_POLL */
2930 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2938 * 'httpWait()' - Wait for data available on a connection.
2940 * @since CUPS 1.1.19/Mac OS X 10.3@
2943 int /* O - 1 if data is available, 0 otherwise */
2944 httpWait(http_t
*http
, /* I - Connection to server */
2945 int msec
) /* I - Milliseconds to wait */
2948 * First see if there is data in the buffer...
2958 * Flush pending data, if any...
2963 if (httpFlushWrite(http
) < 0)
2968 * If not, check the SSL/TLS buffers and do a select() on the connection...
2971 return (_httpWait(http
, msec
, 1));
2976 * 'httpWrite()' - Write data to a HTTP connection.
2978 * This function is deprecated. Use the httpWrite2() function which can
2979 * write more than 2GB of data.
2984 int /* O - Number of bytes written */
2985 httpWrite(http_t
*http
, /* I - Connection to server */
2986 const char *buffer
, /* I - Buffer for data */
2987 int length
) /* I - Number of bytes to write */
2989 return ((int)httpWrite2(http
, buffer
, length
));
2994 * 'httpWrite2()' - Write data to a HTTP connection.
2996 * @since CUPS 1.2/Mac OS X 10.5@
2999 ssize_t
/* O - Number of bytes written */
3000 httpWrite2(http_t
*http
, /* I - Connection to server */
3001 const char *buffer
, /* I - Buffer for data */
3002 size_t length
) /* I - Number of bytes to write */
3004 ssize_t bytes
; /* Bytes written */
3007 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3008 buffer
, CUPS_LLCAST length
));
3011 * Range check input...
3014 if (http
== NULL
|| buffer
== NULL
)
3018 * Mark activity on the connection...
3021 http
->activity
= time(NULL
);
3024 * Buffer small writes for better performance...
3029 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3031 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3032 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3034 httpFlushWrite(http
);
3037 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3038 length
< sizeof(http
->wbuffer
))
3041 * Write to buffer...
3044 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3045 CUPS_LLCAST length
));
3047 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3048 http
->wused
+= (int)length
;
3049 bytes
= (ssize_t
)length
;
3054 * Otherwise write the data directly...
3057 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3058 CUPS_LLCAST length
));
3060 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3061 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3063 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3065 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3066 CUPS_LLCAST bytes
));
3069 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3070 http
->data_remaining
-= bytes
;
3076 * Handle end-of-request processing...
3079 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3080 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3083 * Finished with the transfer; unless we are sending POST or PUT
3087 DEBUG_puts("2httpWrite: changing states...");
3090 httpFlushWrite(http
);
3092 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3095 * Send a 0-length chunk at the end of the request...
3098 http_write(http
, "0\r\n\r\n", 5);
3101 * Reset the data state...
3104 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3105 http
->data_remaining
= 0;
3113 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3115 * '_httpWriteCDSA()' - Write function for the CDSA library.
3118 OSStatus
/* O - -1 on error, 0 on success */
3120 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3121 const void *data
, /* I - Data buffer */
3122 size_t *dataLength
) /* IO - Number of bytes */
3124 OSStatus result
; /* Return value */
3125 ssize_t bytes
; /* Number of bytes read */
3126 http_t
*http
; /* HTTP connection */
3129 http
= (http_t
*)connection
;
3133 bytes
= write(http
->fd
, data
, *dataLength
);
3135 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3137 if (bytes
== *dataLength
)
3141 else if (bytes
>= 0)
3143 *dataLength
= bytes
;
3144 result
= errSSLWouldBlock
;
3150 if (errno
== EAGAIN
)
3151 result
= errSSLWouldBlock
;
3153 result
= errSSLClosedAbort
;
3158 #endif /* HAVE_SSL && HAVE_CDSASSL */
3161 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3163 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3166 ssize_t
/* O - Number of bytes written or -1 on error */
3168 gnutls_transport_ptr ptr
, /* I - Connection to server */
3169 const void *data
, /* I - Data buffer */
3170 size_t length
) /* I - Number of bytes to write */
3172 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
3174 #endif /* HAVE_SSL && HAVE_GNUTLS */
3177 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3179 * 'http_bio_ctrl()' - Control the HTTP connection.
3182 static long /* O - Result/data */
3183 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3184 int cmd
, /* I - Control command */
3185 long arg1
, /* I - First argument */
3186 void *arg2
) /* I - Second argument */
3193 case BIO_CTRL_RESET
:
3197 case BIO_C_SET_FILE_PTR
:
3202 case BIO_C_GET_FILE_PTR
:
3205 *((void **)arg2
) = h
->ptr
;
3212 case BIO_CTRL_FLUSH
:
3219 * 'http_bio_free()' - Free OpenSSL data.
3222 static int /* O - 1 on success, 0 on failure */
3223 http_bio_free(BIO
*h
) /* I - BIO data */
3239 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3242 static int /* O - 1 on success, 0 on failure */
3243 http_bio_new(BIO
*h
) /* I - BIO data */
3258 * 'http_bio_puts()' - Send a string for OpenSSL.
3261 static int /* O - Bytes written */
3262 http_bio_puts(BIO
*h
, /* I - BIO data */
3263 const char *str
) /* I - String to write */
3266 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3268 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3274 * 'http_bio_read()' - Read data for OpenSSL.
3277 static int /* O - Bytes read */
3278 http_bio_read(BIO
*h
, /* I - BIO data */
3279 char *buf
, /* I - Buffer */
3280 int size
) /* I - Number of bytes to read */
3282 http_t
*http
; /* HTTP connection */
3285 http
= (http_t
*)h
->ptr
;
3287 if (!http
->blocking
)
3290 * Make sure we have data before we read...
3293 if (!_httpWait(http
, 10000, 0))
3296 http
->error
= WSAETIMEDOUT
;
3298 http
->error
= ETIMEDOUT
;
3305 return (recv(http
->fd
, buf
, size
, 0));
3310 * 'http_bio_write()' - Write data for OpenSSL.
3313 static int /* O - Bytes written */
3314 http_bio_write(BIO
*h
, /* I - BIO data */
3315 const char *buf
, /* I - Buffer to write */
3316 int num
) /* I - Number of bytes to write */
3318 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3320 #endif /* HAVE_SSL && HAVE_LIBSSL */
3325 * 'http_debug_hex()' - Do a hex dump of a buffer.
3329 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3330 const char *buffer
, /* I - Buffer to dump */
3331 int bytes
) /* I - Bytes to dump */
3333 int i
, j
, /* Looping vars */
3334 ch
; /* Current character */
3335 char line
[255], /* Line buffer */
3336 *start
, /* Start of line after prefix */
3337 *ptr
; /* Pointer into line */
3340 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3343 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
3345 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3346 start
= line
+ strlen(line
);
3348 for (i
= 0; i
< bytes
; i
+= 16)
3350 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3351 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3363 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3365 ch
= buffer
[i
+ j
] & 255;
3367 if (ch
< ' ' || ch
>= 127)
3381 * 'http_field()' - Return the field index for a field name.
3384 static http_field_t
/* O - Field index */
3385 http_field(const char *name
) /* I - String name */
3387 int i
; /* Looping var */
3390 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3391 if (strcasecmp(name
, http_fields
[i
]) == 0)
3392 return ((http_field_t
)i
);
3394 return (HTTP_FIELD_UNKNOWN
);
3400 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3403 static int /* O - Bytes read */
3404 http_read_ssl(http_t
*http
, /* I - Connection to server */
3405 char *buf
, /* I - Buffer to store data */
3406 int len
) /* I - Length of buffer */
3408 # if defined(HAVE_LIBSSL)
3409 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3411 # elif defined(HAVE_GNUTLS)
3412 ssize_t result
; /* Return value */
3415 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3417 if (result
< 0 && !errno
)
3420 * Convert GNU TLS error to errno value...
3425 case GNUTLS_E_INTERRUPTED
:
3429 case GNUTLS_E_AGAIN
:
3441 return ((int)result
);
3443 # elif defined(HAVE_CDSASSL)
3444 int result
; /* Return value */
3445 OSStatus error
; /* Error info */
3446 size_t processed
; /* Number of bytes processed */
3449 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3454 result
= (int)processed
;
3456 case errSSLClosedGraceful
:
3459 case errSSLWouldBlock
:
3461 result
= (int)processed
;
3475 # elif defined(HAVE_SSPISSL)
3476 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3477 # endif /* HAVE_LIBSSL */
3479 #endif /* HAVE_SSL */
3484 * 'http_locking_cb()' - Lock/unlock a thread's mutex.
3488 http_locking_cb(int mode
, /* I - Lock mode */
3489 int type
, /* I - Lock type */
3490 const char *file
, /* I - Source file */
3491 int line
) /* I - Line number */
3493 if (mode
& CRYPTO_LOCK
)
3494 _cupsMutexLock(http_locks
+ type
);
3496 _cupsMutexUnlock(http_locks
+ type
);
3498 #endif /* HAVE_LIBSSL */
3502 * 'http_send()' - Send a request with all fields and the trailing blank line.
3505 static int /* O - 0 on success, non-zero on error */
3506 http_send(http_t
*http
, /* I - Connection to server */
3507 http_state_t request
, /* I - Request code */
3508 const char *uri
) /* I - URI */
3510 int i
; /* Looping var */
3511 char buf
[1024]; /* Encoded URI buffer */
3512 static const char * const codes
[] =
3513 { /* Request code strings */
3530 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3531 http
, codes
[request
], uri
));
3533 if (http
== NULL
|| uri
== NULL
)
3537 * Set the User-Agent field if it isn't already...
3540 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3541 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3544 * Encode the URI as needed...
3547 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3550 * See if we had an error the last time around; if so, reconnect...
3553 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3554 if (httpReconnect(http
))
3558 * Flush any written data that is pending...
3563 if (httpFlushWrite(http
) < 0)
3564 if (httpReconnect(http
))
3569 * Send the request header...
3572 http
->state
= request
;
3573 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3575 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3578 http
->status
= HTTP_CONTINUE
;
3581 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3583 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3584 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3586 #endif /* HAVE_SSL */
3588 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3590 http
->status
= HTTP_ERROR
;
3594 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3595 if (http
->fields
[i
][0] != '\0')
3597 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3598 httpGetField(http
, i
)));
3600 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3601 httpGetField(http
, i
)) < 1)
3603 http
->status
= HTTP_ERROR
;
3609 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3611 http
->status
= HTTP_ERROR
;
3615 if (http
->expect
== HTTP_CONTINUE
&&
3616 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3617 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3619 http
->status
= HTTP_ERROR
;
3623 if (httpPrintf(http
, "\r\n") < 1)
3625 http
->status
= HTTP_ERROR
;
3629 if (httpFlushWrite(http
) < 0)
3632 httpGetLength2(http
);
3633 httpClearFields(http
);
3636 * The Kerberos and AuthRef authentication strings can only be used once...
3639 if (http
->field_authorization
&& http
->authstring
&&
3640 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3641 !strncmp(http
->authstring
, "AuthRef", 7)))
3643 http
->_authstring
[0] = '\0';
3645 if (http
->authstring
!= http
->_authstring
)
3646 free(http
->authstring
);
3648 http
->authstring
= http
->_authstring
;
3656 # ifdef HAVE_CDSASSL
3658 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3661 static int /* O - Status of connection */
3662 http_set_credentials(http_t
*http
) /* I - Connection to server */
3664 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3665 OSStatus error
= 0; /* Error code */
3666 http_tls_credentials_t credentials
= NULL
;
3667 /* TLS credentials */
3670 DEBUG_printf(("7http_set_credentials(%p)", http
));
3673 * Prefer connection specific credentials...
3676 if ((credentials
= http
->tls_credentials
) == NULL
)
3677 credentials
= cg
->tls_credentials
;
3679 # if HAVE_SECPOLICYCREATESSL
3681 * Otherwise root around in the user's keychain to see if one can be found...
3686 CFDictionaryRef query
; /* Query dictionary */
3687 CFTypeRef matches
= NULL
; /* Matching credentials */
3688 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3689 CFTypeRef keys
[] = { kSecClass
,
3692 /* Keys for dictionary */
3693 CFTypeRef values
[] = { kSecClassCertificate
,
3696 /* Values for dictionary */
3699 * Get the names associated with the server.
3702 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3704 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3710 * Create a query which will return all identities that can sign and match
3711 * the passed in policy.
3714 query
= CFDictionaryCreate(NULL
,
3715 (const void**)(&keys
[0]),
3716 (const void**)(&values
[0]),
3717 sizeof(keys
) / sizeof(keys
[0]),
3718 &kCFTypeDictionaryKeyCallBacks
,
3719 &kCFTypeDictionaryValueCallBacks
);
3722 error
= SecItemCopyMatching(query
, &matches
);
3723 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3732 CFRelease(dn_array
);
3734 # endif /* HAVE_SECPOLICYCREATESSL */
3738 error
= SSLSetCertificate(http
->tls
, credentials
);
3739 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3743 DEBUG_puts("4http_set_credentials: No credentials to set.");
3747 # endif /* HAVE_CDSASSL */
3751 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3754 static int /* O - Status of connection */
3755 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3757 _cups_globals_t
*cg
= _cupsGlobals();
3758 /* Pointer to library globals */
3759 int any_root
; /* Allow any root */
3762 SSL_CTX
*context
; /* Context for encryption */
3763 BIO
*bio
; /* BIO data */
3764 # elif defined(HAVE_GNUTLS)
3765 gnutls_certificate_client_credentials
*credentials
;
3766 /* TLS credentials */
3767 # elif defined(HAVE_CDSASSL)
3768 OSStatus error
; /* Error code */
3769 const char *message
= NULL
; /* Error message */
3770 cups_array_t
*credentials
; /* Credentials array */
3771 char *hostname
; /* Hostname */
3772 cups_array_t
*names
; /* CUPS distinguished names */
3773 CFArrayRef dn_array
; /* CF distinguished names array */
3774 CFIndex count
; /* Number of credentials */
3775 CFDataRef data
; /* Certificate data */
3776 int i
; /* Looping var */
3778 *credential
; /* Credential data */
3779 # elif defined(HAVE_SSPISSL)
3780 TCHAR username
[256]; /* Username returned from GetUserName() */
3781 TCHAR commonName
[256]; /* Common name for certificate */
3782 DWORD dwSize
; /* 32 bit size */
3783 # endif /* HAVE_LIBSSL */
3786 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3789 * Always allow self-signed certificates for the local loopback address...
3792 if (httpAddrLocalhost(http
->hostaddr
))
3795 any_root
= cg
->any_root
;
3798 context
= SSL_CTX_new(SSLv23_client_method());
3800 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3802 bio
= BIO_new(_httpBIOMethods());
3803 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3805 http
->tls
= SSL_new(context
);
3806 SSL_set_bio(http
->tls_credentials
, bio
, bio
);
3808 if (SSL_connect(http
->tls
) != 1)
3811 unsigned long error
; /* Error code */
3813 while ((error
= ERR_get_error()) != 0)
3814 DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error
, NULL
)));
3817 SSL_CTX_free(context
);
3818 SSL_free(http
->tls
);
3822 http
->error
= WSAGetLastError();
3824 http
->error
= errno
;
3826 http
->status
= HTTP_ERROR
;
3828 return (HTTP_ERROR
);
3831 # elif defined(HAVE_GNUTLS)
3832 credentials
= (gnutls_certificate_client_credentials
*)
3833 malloc(sizeof(gnutls_certificate_client_credentials
));
3834 if (credentials
== NULL
)
3836 http
->error
= errno
;
3837 http
->status
= HTTP_ERROR
;
3842 gnutls_certificate_allocate_credentials(credentials
);
3844 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3845 gnutls_set_default_priority(http
->tls
);
3846 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3847 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3848 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3849 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3851 if ((gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3853 http
->error
= errno
;
3854 http
->status
= HTTP_ERROR
;
3856 gnutls_deinit(http
->tls
);
3857 gnutls_certificate_free_credentials(*credentials
);
3864 http
->tls_credentials
= credentials
;
3866 # elif defined(HAVE_CDSASSL)
3867 if ((error
= SSLNewContext(false, &http
->tls
)))
3869 http
->error
= error
;
3870 http
->status
= HTTP_ERROR
;
3875 error
= SSLSetConnection(http
->tls
, http
);
3876 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
3880 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
3881 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
3886 error
= SSLSetProtocolVersionEnabled(http
->tls
, kSSLProtocol2
, false);
3887 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionEnabled, error=%d",
3893 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
3894 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
3895 any_root
, (int)error
));
3900 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
3901 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
3902 cg
->expired_certs
, (int)error
));
3907 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
3908 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
3909 cg
->expired_root
, (int)error
));
3914 if (cg
->client_cert_cb
)
3916 error
= SSLSetSessionOption(http
->tls
,
3917 kSSLSessionOptionBreakOnCertRequested
, true);
3918 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
3919 "error=%d", (int)error
));
3923 error
= http_set_credentials(http
);
3924 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
3930 * If there's a server certificate callback installed let it evaluate the
3931 * certificate(s) during the handshake...
3934 if (!error
&& cg
->server_cert_cb
!= NULL
)
3936 error
= SSLSetEnableCertVerify(http
->tls
, false);
3937 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
3942 error
= SSLSetSessionOption(http
->tls
,
3943 kSSLSessionOptionBreakOnServerAuth
, true);
3944 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
3945 "error=%d", (int)error
));
3951 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
3952 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
3954 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
3960 int done
= 0; /* Are we done yet? */
3962 while (!error
&& !done
)
3964 error
= SSLHandshake(http
->tls
);
3966 DEBUG_printf(("4_httpWait: SSLHandshake returned %d.", (int)error
));
3974 case errSSLWouldBlock
:
3978 case errSSLServerAuthCompleted
:
3980 if (cg
->server_cert_cb
)
3982 error
= httpCopyCredentials(http
, &credentials
);
3985 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
3986 cg
->server_cert_data
);
3987 httpFreeCredentials(credentials
);
3990 DEBUG_printf(("4_httpWait: Server certificate callback returned "
3991 "%d.", (int)error
));
3995 case errSSLClientCertRequested
:
3998 if (cg
->client_cert_cb
)
4001 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
4004 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
4006 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
4008 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
4010 if ((credential
= malloc(sizeof(*credential
))))
4012 credential
->datalen
= CFDataGetLength(data
);
4013 if ((credential
->data
= malloc(credential
->datalen
)))
4015 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
4016 credential
->datalen
);
4017 cupsArrayAdd(names
, credential
);
4023 CFRelease(dn_array
);
4028 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
4029 cg
->client_cert_data
);
4031 DEBUG_printf(("4_httpWait: Client certificate callback "
4032 "returned %d.", (int)error
));
4035 httpFreeCredentials(names
);
4039 case errSSLUnknownRootCert
:
4040 message
= _("Unable to establish a secure connection to host "
4041 "(untrusted certificate).");
4044 case errSSLNoRootCert
:
4045 message
= _("Unable to establish a secure connection to host "
4046 "(self-signed certificate).");
4049 case errSSLCertExpired
:
4050 message
= _("Unable to establish a secure connection to host "
4051 "(expired certificate).");
4054 case errSSLCertNotYetValid
:
4055 message
= _("Unable to establish a secure connection to host "
4056 "(certificate not yet valid).");
4059 case errSSLHostNameMismatch
:
4060 message
= _("Unable to establish a secure connection to host "
4061 "(host name mismatch).");
4064 case errSSLXCertChainInvalid
:
4065 message
= _("Unable to establish a secure connection to host "
4066 "(certificate chain invalid).");
4069 case errSSLConnectionRefused
:
4070 message
= _("Unable to establish a secure connection to host "
4071 "(peer dropped connection before responding).");
4082 http
->error
= error
;
4083 http
->status
= HTTP_ERROR
;
4084 errno
= ECONNREFUSED
;
4086 SSLDisposeContext(http
->tls
);
4090 * If an error string wasn't set by the callbacks use a generic one...
4094 #ifdef HAVE_CSSMERRORSTRING
4095 message
= cssmErrorString(error
);
4097 message
= _("Unable to establish a secure connection to host.");
4098 #endif /* HAVE_CSSMERRORSTRING */
4100 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4105 # elif defined(HAVE_SSPISSL)
4106 http
->tls
= _sspiAlloc();
4111 http
->tls
->sock
= http
->fd
;
4112 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4113 GetUserName(username
, &dwSize
);
4114 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4115 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4117 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4120 _sspiFree(http
->tls_credentials
);
4121 http
->tls_credentials
= NULL
;
4125 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
4126 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4128 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
4130 _sspiFree(http
->tls_credentials
);
4131 http
->tls_credentials
= NULL
;
4134 # endif /* HAVE_CDSASSL */
4138 #endif /* HAVE_SSL */
4143 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4147 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4150 SSL_CTX
*context
; /* Context for encryption */
4152 context
= SSL_get_SSL_CTX(http
->tls_credentials
);
4154 SSL_shutdown(http
->tls_credentials
);
4155 SSL_CTX_free(context
);
4156 SSL_free(http
->tls_credentials
);
4158 # elif defined(HAVE_GNUTLS)
4159 gnutls_certificate_client_credentials
*credentials
;
4160 /* TLS credentials */
4162 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4164 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4165 gnutls_deinit(http
->tls
);
4166 gnutls_certificate_free_credentials(*credentials
);
4169 # elif defined(HAVE_CDSASSL)
4170 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4173 SSLDisposeContext(http
->tls
);
4175 if (http
->tls_credentials
)
4176 CFRelease(http
->tls_credentials
);
4178 # elif defined(HAVE_SSPISSL)
4179 _sspiFree(http
->tls_credentials
);
4180 # endif /* HAVE_LIBSSL */
4183 http
->tls_credentials
= NULL
;
4185 #endif /* HAVE_SSL */
4190 * 'http_threadid_cb()' - Return the current thread ID.
4193 static unsigned long /* O - Thread ID */
4194 http_threadid_cb(void)
4196 # ifdef HAVE_PTHREAD_H
4197 return ((unsigned long)pthread_self());
4200 # endif /* HAVE_PTHREAD_H */
4202 #endif /* HAVE_LIBSSL */
4207 * 'http_upgrade()' - Force upgrade to TLS encryption.
4210 static int /* O - Status of connection */
4211 http_upgrade(http_t
*http
) /* I - Connection to server */
4213 int ret
; /* Return value */
4214 http_t myhttp
; /* Local copy of HTTP data */
4217 DEBUG_printf(("7http_upgrade(%p)", http
));
4220 * Flush the connection to make sure any previous "Upgrade" message
4227 * Copy the HTTP data to a local variable so we can do the OPTIONS
4228 * request without interfering with the existing request data...
4231 memcpy(&myhttp
, http
, sizeof(myhttp
));
4234 * Send an OPTIONS request to the server, requiring SSL or TLS
4235 * encryption on the link...
4238 http
->field_authorization
= NULL
; /* Don't free the auth string */
4240 httpClearFields(http
);
4241 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4242 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4244 if ((ret
= httpOptions(http
, "*")) == 0)
4247 * Wait for the secure connection...
4250 while (httpUpdate(http
) == HTTP_CONTINUE
);
4254 * Restore the HTTP request data...
4257 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4258 http
->data_encoding
= myhttp
.data_encoding
;
4259 http
->data_remaining
= myhttp
.data_remaining
;
4260 http
->_data_remaining
= myhttp
._data_remaining
;
4261 http
->expect
= myhttp
.expect
;
4262 http
->field_authorization
= myhttp
.field_authorization
;
4263 http
->digest_tries
= myhttp
.digest_tries
;
4266 * See if we actually went secure...
4272 * Server does not support HTTP upgrade...
4275 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4278 closesocket(http
->fd
);
4290 #endif /* HAVE_SSL */
4294 * 'http_write()' - Write a buffer to a HTTP connection.
4297 static int /* O - Number of bytes written */
4298 http_write(http_t
*http
, /* I - Connection to server */
4299 const char *buffer
, /* I - Buffer for data */
4300 int length
) /* I - Number of bytes to write */
4302 int tbytes
, /* Total bytes sent */
4303 bytes
; /* Bytes sent */
4306 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4315 bytes
= http_write_ssl(http
, buffer
, length
);
4317 #endif /* HAVE_SSL */
4318 bytes
= send(http
->fd
, buffer
, length
, 0);
4323 if (WSAGetLastError() == WSAEINTR
)
4325 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4327 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4330 http
->error
= WSAGetLastError();
4332 else if (WSAGetLastError() != http
->error
&&
4333 WSAGetLastError() != WSAECONNRESET
)
4335 http
->error
= WSAGetLastError();
4342 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4344 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4346 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4349 http
->error
= errno
;
4351 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4353 http
->error
= errno
;
4358 DEBUG_printf(("3http_write: error writing data (%s).",
4359 strerror(http
->error
)));
4370 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4373 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4380 * 'http_write_chunk()' - Write a chunked buffer.
4383 static int /* O - Number bytes written */
4384 http_write_chunk(http_t
*http
, /* I - Connection to server */
4385 const char *buffer
, /* I - Buffer to write */
4386 int length
) /* I - Length of buffer */
4388 char header
[255]; /* Chunk header */
4389 int bytes
; /* Bytes written */
4392 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4393 http
, buffer
, length
));
4396 * Write the chunk header, data, and trailer.
4399 sprintf(header
, "%x\r\n", length
);
4400 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4402 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4406 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4408 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4412 if (http_write(http
, "\r\n", 2) < 0)
4414 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4424 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4427 static int /* O - Bytes written */
4428 http_write_ssl(http_t
*http
, /* I - Connection to server */
4429 const char *buf
, /* I - Buffer holding data */
4430 int len
) /* I - Length of buffer */
4432 ssize_t result
; /* Return value */
4435 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4437 # if defined(HAVE_LIBSSL)
4438 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4440 # elif defined(HAVE_GNUTLS)
4441 result
= gnutls_record_send(http
->tls
, buf
, len
);
4443 if (result
< 0 && !errno
)
4446 * Convert GNU TLS error to errno value...
4451 case GNUTLS_E_INTERRUPTED
:
4455 case GNUTLS_E_AGAIN
:
4467 # elif defined(HAVE_CDSASSL)
4468 OSStatus error
; /* Error info */
4469 size_t processed
; /* Number of bytes processed */
4472 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4477 result
= (int)processed
;
4479 case errSSLClosedGraceful
:
4482 case errSSLWouldBlock
:
4484 result
= (int)processed
;
4496 # elif defined(HAVE_SSPISSL)
4497 return _sspiWrite((_sspi_struct_t
*) http
->tls
, (void*) buf
, len
);
4498 # endif /* HAVE_LIBSSL */
4500 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4502 return ((int)result
);
4504 #endif /* HAVE_SSL */
4508 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".