2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for CUPS.
6 * Copyright 2007-2010 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 state for incoming
88 * _httpWait() - Wait for data available on a connection (no
90 * httpWait() - Wait for data available on a connection.
91 * httpWrite() - Write data to a HTTP connection.
92 * httpWrite2() - Write data to a HTTP connection.
93 * _httpWriteCDSA() - Write function for the CDSA library.
94 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
95 * http_bio_ctrl() - Control the HTTP connection.
96 * http_bio_free() - Free OpenSSL data.
97 * http_bio_new() - Initialize an OpenSSL BIO structure.
98 * http_bio_puts() - Send a string for OpenSSL.
99 * http_bio_read() - Read data for OpenSSL.
100 * http_bio_write() - Write data for OpenSSL.
101 * http_debug_hex() - Do a hex dump of a buffer.
102 * http_field() - Return the field index for a field name.
103 * http_read_ssl() - Read from a SSL/TLS connection.
104 * http_locking_cb() - Lock/unlock a thread's mutex.
105 * http_send() - Send a request with all fields and the trailing
107 * http_set_credentials() - Set the SSL/TLS credentials.
108 * http_setup_ssl() - Set up SSL/TLS support on a connection.
109 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
110 * http_threadid_cb() - Return the current thread ID.
111 * http_upgrade() - Force upgrade to TLS encryption.
112 * http_write() - Write a buffer to a HTTP connection.
113 * http_write_chunk() - Write a chunked buffer.
114 * http_write_ssl() - Write to a SSL/TLS connection.
118 * Include necessary headers...
121 #include "cups-private.h"
127 # include <sys/time.h>
128 # include <sys/resource.h>
131 # include <sys/poll.h>
132 #endif /* HAVE_POLL */
136 * Some operating systems have done away with the Fxxxx constants for
137 * the fcntl() call; this works around that "feature"...
141 # define FNONBLK O_NONBLOCK
142 #endif /* !FNONBLK */
150 static void http_debug_hex(const char *prefix
, const char *buffer
,
153 static http_field_t
http_field(const char *name
);
154 static int http_send(http_t
*http
, http_state_t request
,
156 static int http_write(http_t
*http
, const char *buffer
,
158 static int http_write_chunk(http_t
*http
, const char *buffer
,
161 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
162 static int http_set_credentials(http_t
*http
);
163 static int http_setup_ssl(http_t
*http
);
164 static void http_shutdown_ssl(http_t
*http
);
165 static int http_upgrade(http_t
*http
);
166 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
169 # ifdef HAVE_PTHREAD_H
170 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
171 # endif /* HAVE_PTHREAD_H */
173 # elif defined(HAVE_LIBSSL)
174 static _cups_mutex_t
*http_locks
; /* OpenSSL lock mutexes */
176 static void http_locking_cb(int mode
, int type
, const char *file
,
178 static unsigned long http_threadid_cb(void);
179 # endif /* HAVE_GNUTLS */
180 #endif /* HAVE_SSL */
187 static const char * const http_fields
[] =
204 "If-Unmodified-since",
218 static const char * const http_states
[] =
238 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
240 * BIO methods for OpenSSL...
243 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
244 static int http_bio_read(BIO
*h
, char *buf
, int size
);
245 static int http_bio_puts(BIO
*h
, const char *str
);
246 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
247 static int http_bio_new(BIO
*h
);
248 static int http_bio_free(BIO
*data
);
250 static BIO_METHOD http_bio_methods
=
257 NULL
, /* http_bio_gets, */
263 #endif /* HAVE_SSL && HAVE_LIBSSL */
267 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
269 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
274 int /* O - 0 on success, -1 on error */
276 cups_array_t
*credentials
, /* I - Credentials array */
277 const void *data
, /* I - PEM-encoded X.509 data */
278 size_t datalen
) /* I - Length of data */
280 http_credential_t
*credential
; /* Credential data */
283 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
285 credential
->datalen
= datalen
;
287 if ((credential
->data
= malloc(datalen
)) != NULL
)
289 memcpy(credential
->data
, data
, datalen
);
290 cupsArrayAdd(credentials
, credential
);
301 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
303 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
306 BIO_METHOD
* /* O - BIO methods for OpenSSL */
307 _httpBIOMethods(void)
309 return (&http_bio_methods
);
311 #endif /* HAVE_SSL && HAVE_LIBSSL */
315 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
319 httpBlocking(http_t
*http
, /* I - Connection to server */
320 int b
) /* I - 1 = blocking, 0 = non-blocking */
328 * 'httpCheck()' - Check to see if there is a pending response from the server.
331 int /* O - 0 = no data, 1 = data available */
332 httpCheck(http_t
*http
) /* I - Connection to server */
334 return (httpWait(http
, 0));
339 * 'httpClearCookie()' - Clear the cookie value(s).
341 * @since CUPS 1.1.19/Mac OS X 10.3@
345 httpClearCookie(http_t
*http
) /* I - Connection to server */
359 * 'httpClearFields()' - Clear HTTP request fields.
363 httpClearFields(http_t
*http
) /* I - Connection to server */
367 memset(http
->fields
, 0, sizeof(http
->fields
));
368 if (http
->hostname
[0] == '/')
369 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
371 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
373 if (http
->field_authorization
)
375 free(http
->field_authorization
);
376 http
->field_authorization
= NULL
;
379 http
->expect
= (http_status_t
)0;
385 * 'httpClose()' - Close an HTTP connection.
389 httpClose(http_t
*http
) /* I - Connection to server */
392 OM_uint32 minor_status
; /* Minor status code */
393 #endif /* HAVE_GSSAPI */
396 DEBUG_printf(("httpClose(http=%p)", http
));
399 * Range check input...
406 * Close any open connection...
409 _httpDisconnect(http
);
412 * Free memory used...
415 httpAddrFreeList(http
->addrlist
);
421 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
422 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
424 if (http
->gssname
!= GSS_C_NO_NAME
)
425 gss_release_name(&minor_status
, &http
->gssname
);
426 #endif /* HAVE_GSSAPI */
428 #ifdef HAVE_AUTHORIZATION_H
430 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
431 #endif /* HAVE_AUTHORIZATION_H */
433 httpClearFields(http
);
435 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
436 free(http
->authstring
);
443 * 'httpConnect()' - Connect to a HTTP server.
445 * This function is deprecated - use @link httpConnectEncrypt@ instead.
450 http_t
* /* O - New HTTP connection */
451 httpConnect(const char *host
, /* I - Host to connect to */
452 int port
) /* I - Port number */
454 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
459 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
462 http_t
* /* O - New HTTP connection */
464 const char *host
, /* I - Host to connect to */
465 int port
, /* I - Port number */
466 http_encryption_t encryption
) /* I - Type of encryption to use */
468 http_t
*http
; /* New HTTP connection */
471 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
472 host
, port
, encryption
));
475 * Create the HTTP structure...
478 if ((http
= _httpCreate(host
, port
, encryption
)) == NULL
)
482 * Connect to the remote system...
485 if (!httpReconnect(http
))
489 * Could not connect to any known address - bail out!
492 httpAddrFreeList(http
->addrlist
);
501 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
507 int /* O - Status of call (0 = success) */
509 http_t
*http
, /* I - Connection to server */
510 cups_array_t
**credentials
) /* O - Array of credentials */
513 # elif defined(HAVE_GNUTLS)
514 # elif defined(HAVE_CDSASSL)
515 OSStatus error
; /* Error code */
516 CFIndex count
; /* Number of credentials */
517 CFArrayRef peerCerts
; /* Peer certificates */
518 SecCertificateRef secCert
; /* Certificate reference */
519 CFDataRef data
; /* Certificate data */
520 int i
; /* Looping var */
521 # elif defined(HAVE_SSPISSL)
522 # endif /* HAVE_LIBSSL */
528 if (!http
|| !http
->tls
|| !credentials
)
534 # elif defined(HAVE_GNUTLS)
537 # elif defined(HAVE_CDSASSL)
538 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
540 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
542 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
544 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
545 if ((data
= SecCertificateCopyData(secCert
)))
547 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
548 CFDataGetLength(data
));
554 CFRelease(peerCerts
);
559 # elif defined(HAVE_SSPISSL)
561 # endif /* HAVE_LIBSSL */
566 * '_httpConvertCredentials()' - Convert credentials to the internal format.
569 http_tls_credentials_t
/* O - Internal credentials */
570 _httpConvertCredentials(
571 cups_array_t
*credentials
) /* I - Array of credentials */
579 # elif defined(HAVE_GNUTLS)
582 # elif defined(HAVE_CDSASSL)
583 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
584 SecCertificateRef secCert
; /* Certificate reference */
585 CFDataRef data
; /* Credential data reference */
586 http_credential_t
*credential
; /* Credential data */
589 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
590 cupsArrayCount(credentials
),
591 &kCFTypeArrayCallBacks
)) == NULL
)
594 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
596 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
598 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
599 credential
->datalen
)))
601 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
604 CFArrayAppendValue(peerCerts
, secCert
);
614 # elif defined(HAVE_SSPISSL)
619 # endif /* HAVE_LIBSSL */
624 * '_httpCreate()' - Create an unconnected HTTP connection.
627 http_t
* /* O - HTTP connection */
629 const char *host
, /* I - Hostname */
630 int port
, /* I - Port number */
631 http_encryption_t encryption
) /* I - Encryption to use */
633 http_t
*http
; /* New HTTP connection */
634 http_addrlist_t
*addrlist
; /* Host address data */
635 char service
[255]; /* Service name */
638 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
639 host
, port
, encryption
));
650 sprintf(service
, "%d", port
);
652 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
656 * Allocate memory for the structure...
659 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
661 httpAddrFreeList(addrlist
);
666 * Initialize the HTTP data...
669 http
->activity
= time(NULL
);
670 http
->addrlist
= addrlist
;
674 http
->gssctx
= GSS_C_NO_CONTEXT
;
675 http
->gssname
= GSS_C_NO_NAME
;
676 #endif /* HAVE_GSSAPI */
677 http
->version
= HTTP_1_1
;
679 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
681 if (port
== 443) /* Always use encryption for https */
682 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
684 http
->encryption
= encryption
;
687 * Return the new structure...
695 * 'httpDelete()' - Send a DELETE request to the server.
698 int /* O - Status of call (0 = success) */
699 httpDelete(http_t
*http
, /* I - Connection to server */
700 const char *uri
) /* I - URI to delete */
702 return (http_send(http
, HTTP_DELETE
, uri
));
707 * '_httpDisconnect()' - Disconnect a HTTP connection.
711 _httpDisconnect(http_t
*http
) /* I - Connection to server */
715 http_shutdown_ssl(http
);
716 #endif /* HAVE_SSL */
719 closesocket(http
->fd
);
729 * 'httpEncryption()' - Set the required encryption on the link.
732 int /* O - -1 on error, 0 on success */
733 httpEncryption(http_t
*http
, /* I - Connection to server */
734 http_encryption_t e
) /* I - New encryption preference */
736 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
742 http
->encryption
= e
;
744 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
745 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
746 return (httpReconnect(http
));
747 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
748 return (http_upgrade(http
));
752 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
756 #endif /* HAVE_SSL */
761 * 'httpError()' - Get the last error on a connection.
764 int /* O - Error code (errno) value */
765 httpError(http_t
*http
) /* I - Connection to server */
768 return (http
->error
);
775 * 'httpFlush()' - Flush data from a HTTP connection.
779 httpFlush(http_t
*http
) /* I - Connection to server */
781 char buffer
[8192]; /* Junk buffer */
782 int blocking
; /* To block or not to block */
783 http_state_t oldstate
; /* Old state */
786 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
787 http_states
[http
->state
]));
790 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
793 blocking
= http
->blocking
;
797 * Read any data we can...
800 oldstate
= http
->state
;
801 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
804 * Restore blocking and reset the connection if we didn't get all of
805 * the remaining data...
808 http
->blocking
= blocking
;
810 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
813 * Didn't get the data back, so close the current connection.
816 http
->state
= HTTP_WAITING
;
820 http_shutdown_ssl(http
);
821 #endif /* HAVE_SSL */
824 closesocket(http
->fd
);
835 * 'httpFlushWrite()' - Flush data in write buffer.
837 * @since CUPS 1.2/Mac OS X 10.5@
840 int /* O - Bytes written or -1 on error */
841 httpFlushWrite(http_t
*http
) /* I - Connection to server */
843 int bytes
; /* Bytes written */
846 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
848 if (!http
|| !http
->wused
)
850 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
851 "1httpFlushWrite: No connection.");
855 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
856 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
858 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
862 DEBUG_printf(("1httpFlushWrite: Returning %d.", bytes
));
869 * '_httpFreeCredentials()' - Free internal credentials.
873 _httpFreeCredentials(
874 http_tls_credentials_t credentials
) /* I - Internal credentials */
882 #elif defined(HAVE_GNUTLS)
885 #elif defined(HAVE_CDSASSL)
886 CFRelease(credentials
);
888 #elif defined(HAVE_SSPISSL)
891 #endif /* HAVE_LIBSSL */
896 * 'httpFreeCredentials()' - Free an array of credentials.
901 cups_array_t
*credentials
) /* I - Array of credentials */
903 http_credential_t
*credential
; /* Credential */
906 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
908 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
910 cupsArrayRemove(credentials
, credential
);
911 free((void *)credential
->data
);
915 cupsArrayDelete(credentials
);
920 * 'httpGet()' - Send a GET request to the server.
923 int /* O - Status of call (0 = success) */
924 httpGet(http_t
*http
, /* I - Connection to server */
925 const char *uri
) /* I - URI to get */
927 return (http_send(http
, HTTP_GET
, uri
));
932 * 'httpGetAuthString()' - Get the current authorization string.
934 * The authorization string is set by cupsDoAuthentication() and
935 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
936 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
939 * @since CUPS 1.3/Mac OS X 10.5@
942 char * /* O - Authorization string */
943 httpGetAuthString(http_t
*http
) /* I - Connection to server */
946 return (http
->authstring
);
953 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
955 * @since CUPS 1.2/Mac OS X 10.5@
958 int /* O - 1 if blocking, 0 if non-blocking */
959 httpGetBlocking(http_t
*http
) /* I - Connection to server */
961 return (http
? http
->blocking
: 0);
966 * 'httpGetCookie()' - Get any cookie data from the response.
968 * @since CUPS 1.1.19/Mac OS X 10.3@
971 const char * /* O - Cookie data or NULL */
972 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
974 return (http
? http
->cookie
: NULL
);
979 * 'httpGetFd()' - Get the file descriptor associated with a connection.
981 * @since CUPS 1.2/Mac OS X 10.5@
984 int /* O - File descriptor or -1 if none */
985 httpGetFd(http_t
*http
) /* I - Connection to server */
987 return (http
? http
->fd
: -1);
992 * 'httpGetField()' - Get a field value from a request/response.
995 const char * /* O - Field value */
996 httpGetField(http_t
*http
, /* I - Connection to server */
997 http_field_t field
) /* I - Field to get */
999 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1001 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
1002 http
->field_authorization
)
1005 * Special case for WWW-Authenticate: as its contents can be
1006 * longer than HTTP_MAX_VALUE...
1009 return (http
->field_authorization
);
1012 return (http
->fields
[field
]);
1017 * 'httpGetLength()' - Get the amount of data remaining from the
1018 * content-length or transfer-encoding fields.
1020 * This function is deprecated and will not return lengths larger than
1021 * 2^31 - 1; use httpGetLength2() instead.
1026 int /* O - Content length */
1027 httpGetLength(http_t
*http
) /* I - Connection to server */
1030 * Get the read content length and return the 32-bit value.
1035 httpGetLength2(http
);
1037 return (http
->_data_remaining
);
1045 * 'httpGetLength2()' - Get the amount of data remaining from the
1046 * content-length or transfer-encoding fields.
1048 * This function returns the complete content length, even for
1049 * content larger than 2^31 - 1.
1051 * @since CUPS 1.2/Mac OS X 10.5@
1054 off_t
/* O - Content length */
1055 httpGetLength2(http_t
*http
) /* I - Connection to server */
1057 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1058 http_states
[http
->state
]));
1063 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1065 DEBUG_puts("4httpGetLength2: chunked request!");
1067 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1068 http
->data_remaining
= 0;
1072 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1075 * The following is a hack for HTTP servers that don't send a
1076 * content-length or transfer-encoding field...
1078 * If there is no content-length then the connection must close
1079 * after the transfer is complete...
1082 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1085 * Default content length is 0 for errors and 2^31-1 for other
1086 * successful requests...
1089 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
1090 http
->data_remaining
= 0;
1092 http
->data_remaining
= 2147483647;
1095 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1098 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1099 CUPS_LLCAST http
->data_remaining
));
1102 if (http
->data_remaining
<= INT_MAX
)
1103 http
->_data_remaining
= (int)http
->data_remaining
;
1105 http
->_data_remaining
= INT_MAX
;
1107 return (http
->data_remaining
);
1112 * 'httpGetStatus()' - Get the status of the last HTTP request.
1114 * @since CUPS 1.2/Mac OS X 10.5@
1117 http_status_t
/* O - HTTP status */
1118 httpGetStatus(http_t
*http
) /* I - Connection to server */
1120 return (http
? http
->status
: HTTP_ERROR
);
1125 * 'httpGetSubField()' - Get a sub-field value.
1130 char * /* O - Value or NULL */
1131 httpGetSubField(http_t
*http
, /* I - Connection to server */
1132 http_field_t field
, /* I - Field index */
1133 const char *name
, /* I - Name of sub-field */
1134 char *value
) /* O - Value string */
1136 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1141 * 'httpGetSubField2()' - Get a sub-field value.
1143 * @since CUPS 1.2/Mac OS X 10.5@
1146 char * /* O - Value or NULL */
1147 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1148 http_field_t field
, /* I - Field index */
1149 const char *name
, /* I - Name of sub-field */
1150 char *value
, /* O - Value string */
1151 int valuelen
) /* I - Size of value buffer */
1153 const char *fptr
; /* Pointer into field */
1154 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1155 *ptr
, /* Pointer into string buffer */
1156 *end
; /* End of value buffer */
1158 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1159 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1161 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1162 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1165 end
= value
+ valuelen
- 1;
1167 for (fptr
= http
->fields
[field
]; *fptr
;)
1170 * Skip leading whitespace...
1173 while (_cups_isspace(*fptr
))
1183 * Get the sub-field name...
1187 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1188 ptr
< (temp
+ sizeof(temp
) - 1);
1193 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1196 * Skip trailing chars up to the '='...
1199 while (_cups_isspace(*fptr
))
1209 * Skip = and leading whitespace...
1214 while (_cups_isspace(*fptr
))
1220 * Read quoted string...
1223 for (ptr
= value
, fptr
++;
1224 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1229 while (*fptr
&& *fptr
!= '\"')
1238 * Read unquoted string...
1242 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1247 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1251 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1254 * See if this is the one...
1257 if (!strcmp(name
, temp
))
1259 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1266 DEBUG_puts("3httpGetSubField2: Returning NULL");
1273 * 'httpGets()' - Get a line of text from a HTTP connection.
1276 char * /* O - Line or NULL */
1277 httpGets(char *line
, /* I - Line to read into */
1278 int length
, /* I - Max length of buffer */
1279 http_t
*http
) /* I - Connection to server */
1281 char *lineptr
, /* Pointer into line */
1282 *lineend
, /* End of line */
1283 *bufptr
, /* Pointer into input buffer */
1284 *bufend
; /* Pointer to end of buffer */
1285 int bytes
, /* Number of bytes read */
1286 eol
; /* End-of-line? */
1289 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1291 if (http
== NULL
|| line
== NULL
)
1295 * Read a line from the buffer...
1300 lineend
= line
+ length
- 1;
1303 while (lineptr
< lineend
)
1306 * Pre-load the buffer as needed...
1315 while (http
->used
== 0)
1318 * No newline; see if there is more data to be read...
1321 if (!http
->blocking
&& !_httpWait(http
, 10000, 1))
1323 DEBUG_puts("3httpGets: Timed out!");
1325 http
->error
= WSAETIMEDOUT
;
1327 http
->error
= ETIMEDOUT
;
1334 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1335 HTTP_MAX_BUFFER
- http
->used
);
1337 #endif /* HAVE_SSL */
1338 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1339 HTTP_MAX_BUFFER
- http
->used
, 0);
1341 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1346 * Nope, can't get a line this time...
1350 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1352 if (WSAGetLastError() == WSAEINTR
)
1354 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1356 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1359 http
->error
= WSAGetLastError();
1361 else if (WSAGetLastError() != http
->error
)
1363 http
->error
= WSAGetLastError();
1368 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1372 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1374 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1376 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1379 http
->error
= errno
;
1381 else if (errno
!= http
->error
)
1383 http
->error
= errno
;
1390 else if (bytes
== 0)
1392 http
->error
= EPIPE
;
1398 * Yup, update the amount used...
1401 http
->used
+= bytes
;
1405 * Now copy as much of the current line as possible...
1408 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1409 lineptr
< lineend
&& bufptr
< bufend
;)
1411 if (*bufptr
== 0x0a)
1417 else if (*bufptr
== 0x0d)
1420 *lineptr
++ = *bufptr
++;
1423 http
->used
-= (int)(bufptr
- http
->buffer
);
1425 memmove(http
->buffer
, bufptr
, http
->used
);
1433 http
->activity
= time(NULL
);
1437 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1443 DEBUG_puts("3httpGets: No new line available!");
1450 * 'httpHead()' - Send a HEAD request to the server.
1453 int /* O - Status of call (0 = success) */
1454 httpHead(http_t
*http
, /* I - Connection to server */
1455 const char *uri
) /* I - URI for head */
1457 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1458 return (http_send(http
, HTTP_HEAD
, uri
));
1463 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1464 * default HTTP proxy (if any).
1468 httpInitialize(void)
1470 static int initialized
= 0; /* Have we been called before? */
1472 WSADATA winsockdata
; /* WinSock data */
1475 int i
; /* Looping var */
1476 unsigned char data
[1024]; /* Seed data */
1477 #endif /* HAVE_LIBSSL */
1483 _cupsGlobalUnlock();
1488 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1490 #elif !defined(SO_NOSIGPIPE)
1492 * Ignore SIGPIPE signals...
1496 sigset(SIGPIPE
, SIG_IGN
);
1498 # elif defined(HAVE_SIGACTION)
1499 struct sigaction action
; /* POSIX sigaction data */
1502 memset(&action
, 0, sizeof(action
));
1503 action
.sa_handler
= SIG_IGN
;
1504 sigaction(SIGPIPE
, &action
, NULL
);
1507 signal(SIGPIPE
, SIG_IGN
);
1508 # endif /* !SO_NOSIGPIPE */
1513 * Make sure we handle threading properly...
1516 # ifdef HAVE_PTHREAD_H
1517 gcry_control(GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
1518 # endif /* HAVE_PTHREAD_H */
1521 * Initialize GNU TLS...
1524 gnutls_global_init();
1526 #elif defined(HAVE_LIBSSL)
1528 * Initialize OpenSSL...
1531 SSL_load_error_strings();
1535 * Set the threading callbacks...
1538 http_locks
= calloc(CRYPTO_num_locks(), sizeof(_cups_mutex_t
));
1539 # ifdef HAVE_PTHREAD_H
1540 for (i
= 0; i
< CRYPTO_num_locks(); i
++)
1541 pthread_mutex_init(http_locks
+ i
, NULL
);
1542 # endif /* HAVE_PTHREAD_H */
1544 CRYPTO_set_id_callback(http_threadid_cb
);
1545 CRYPTO_set_locking_callback(http_locking_cb
);
1548 * Using the current time is a dubious random seed, but on some systems
1549 * it is the best we can do (on others, this seed isn't even used...)
1552 CUPS_SRAND(time(NULL
));
1554 for (i
= 0; i
< sizeof(data
); i
++)
1555 data
[i
] = CUPS_RAND();
1557 RAND_seed(data
, sizeof(data
));
1558 #endif /* HAVE_GNUTLS */
1561 _cupsGlobalUnlock();
1566 * 'httpOptions()' - Send an OPTIONS request to the server.
1569 int /* O - Status of call (0 = success) */
1570 httpOptions(http_t
*http
, /* I - Connection to server */
1571 const char *uri
) /* I - URI for options */
1573 return (http_send(http
, HTTP_OPTIONS
, uri
));
1578 * '_httpPeek()' - Peek at data from a HTTP connection.
1580 * This function copies available data from the given HTTP connection, reading
1581 * a buffer as needed. The data is still available for reading using
1582 * @link httpRead@ or @link httpRead2@.
1584 * For non-blocking connections the usual timeouts apply.
1587 ssize_t
/* O - Number of bytes copied */
1588 _httpPeek(http_t
*http
, /* I - Connection to server */
1589 char *buffer
, /* I - Buffer for data */
1590 size_t length
) /* I - Maximum number of bytes */
1592 ssize_t bytes
; /* Bytes read */
1593 char len
[32]; /* Length string */
1596 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1597 http
, buffer
, CUPS_LLCAST length
));
1599 if (http
== NULL
|| buffer
== NULL
)
1602 http
->activity
= time(NULL
);
1608 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1609 http
->data_remaining
<= 0)
1611 DEBUG_puts("2_httpPeek: Getting chunk length...");
1613 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1615 DEBUG_puts("1_httpPeek: Could not get length!");
1619 http
->data_remaining
= strtoll(len
, NULL
, 16);
1620 if (http
->data_remaining
< 0)
1622 DEBUG_puts("1_httpPeek: Negative chunk length!");
1627 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1628 CUPS_LLCAST http
->data_remaining
));
1630 if (http
->data_remaining
<= 0)
1633 * A zero-length chunk ends a transfer; unless we are reading POST
1637 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1638 httpGets(len
, sizeof(len
), http
);
1640 if (http
->state
== HTTP_POST_RECV
)
1643 http
->state
= HTTP_WAITING
;
1646 * Prevent future reads for this request...
1649 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1653 else if (length
> (size_t)http
->data_remaining
)
1654 length
= (size_t)http
->data_remaining
;
1656 if (http
->used
== 0)
1659 * Buffer small reads for better performance...
1662 if (!http
->blocking
&& !httpWait(http
, 10000))
1665 if (http
->data_remaining
> sizeof(http
->buffer
))
1666 bytes
= sizeof(http
->buffer
);
1668 bytes
= http
->data_remaining
;
1672 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1674 #endif /* HAVE_SSL */
1676 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1679 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1681 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1690 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1692 http
->error
= WSAGetLastError();
1696 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1698 http
->error
= errno
;
1705 http
->error
= EPIPE
;
1712 if (length
> (size_t)http
->used
)
1713 length
= (size_t)http
->used
;
1715 bytes
= (ssize_t
)length
;
1717 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1720 memcpy(buffer
, http
->buffer
, length
);
1728 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1731 http
->error
= WSAGetLastError();
1733 if (errno
== EINTR
|| errno
== EAGAIN
)
1736 http
->error
= errno
;
1739 else if (bytes
== 0)
1741 http
->error
= EPIPE
;
1746 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1754 * 'httpPost()' - Send a POST request to the server.
1757 int /* O - Status of call (0 = success) */
1758 httpPost(http_t
*http
, /* I - Connection to server */
1759 const char *uri
) /* I - URI for post */
1761 return (http_send(http
, HTTP_POST
, uri
));
1766 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1771 int /* O - Number of bytes written */
1772 httpPrintf(http_t
*http
, /* I - Connection to server */
1773 const char *format
, /* I - printf-style format string */
1774 ...) /* I - Additional args as needed */
1776 int bytes
; /* Number of bytes to write */
1777 char buf
[16384]; /* Buffer for formatted string */
1778 va_list ap
; /* Variable argument pointer */
1781 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1783 va_start(ap
, format
);
1784 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1787 DEBUG_printf(("3httpPrintf: %s", buf
));
1789 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1790 return (httpWrite2(http
, buf
, bytes
));
1795 DEBUG_puts("4httpPrintf: flushing existing data...");
1797 if (httpFlushWrite(http
) < 0)
1801 return (http_write(http
, buf
, bytes
));
1807 * 'httpPut()' - Send a PUT request to the server.
1810 int /* O - Status of call (0 = success) */
1811 httpPut(http_t
*http
, /* I - Connection to server */
1812 const char *uri
) /* I - URI to put */
1814 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1815 return (http_send(http
, HTTP_PUT
, uri
));
1820 * 'httpRead()' - Read data from a HTTP connection.
1822 * This function is deprecated. Use the httpRead2() function which can
1823 * read more than 2GB of data.
1828 int /* O - Number of bytes read */
1829 httpRead(http_t
*http
, /* I - Connection to server */
1830 char *buffer
, /* I - Buffer for data */
1831 int length
) /* I - Maximum number of bytes */
1833 return ((int)httpRead2(http
, buffer
, length
));
1838 * 'httpRead2()' - Read data from a HTTP connection.
1840 * @since CUPS 1.2/Mac OS X 10.5@
1843 ssize_t
/* O - Number of bytes read */
1844 httpRead2(http_t
*http
, /* I - Connection to server */
1845 char *buffer
, /* I - Buffer for data */
1846 size_t length
) /* I - Maximum number of bytes */
1848 ssize_t bytes
; /* Bytes read */
1849 char len
[32]; /* Length string */
1852 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1853 http
, buffer
, CUPS_LLCAST length
));
1855 if (http
== NULL
|| buffer
== NULL
)
1858 http
->activity
= time(NULL
);
1864 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1865 http
->data_remaining
<= 0)
1867 DEBUG_puts("2httpRead2: Getting chunk length...");
1869 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1871 DEBUG_puts("1httpRead2: Could not get length!");
1875 http
->data_remaining
= strtoll(len
, NULL
, 16);
1876 if (http
->data_remaining
< 0)
1878 DEBUG_puts("1httpRead2: Negative chunk length!");
1883 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1884 CUPS_LLCAST http
->data_remaining
));
1886 if (http
->data_remaining
<= 0)
1889 * A zero-length chunk ends a transfer; unless we are reading POST
1893 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1894 httpGets(len
, sizeof(len
), http
);
1896 if (http
->state
== HTTP_POST_RECV
)
1899 http
->state
= HTTP_WAITING
;
1902 * Prevent future reads for this request...
1905 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1909 else if (length
> (size_t)http
->data_remaining
)
1910 length
= (size_t)http
->data_remaining
;
1912 if (http
->used
== 0 && length
<= 256)
1915 * Buffer small reads for better performance...
1918 if (!http
->blocking
&& !httpWait(http
, 10000))
1921 if (http
->data_remaining
> sizeof(http
->buffer
))
1922 bytes
= sizeof(http
->buffer
);
1924 bytes
= http
->data_remaining
;
1928 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1930 #endif /* HAVE_SSL */
1932 DEBUG_printf(("2httpRead2: reading %d bytes from socket into buffer...",
1935 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1937 DEBUG_printf(("2httpRead2: read %d bytes from socket into buffer...",
1946 if (WSAGetLastError() != WSAEINTR
)
1948 http
->error
= WSAGetLastError();
1951 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1953 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1955 http
->error
= WSAEWOULDBLOCK
;
1960 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1962 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1964 http
->error
= errno
;
1967 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1969 http
->error
= errno
;
1973 else if (errno
!= EINTR
)
1975 http
->error
= errno
;
1982 http
->error
= EPIPE
;
1989 if (length
> (size_t)http
->used
)
1990 length
= (size_t)http
->used
;
1992 bytes
= (ssize_t
)length
;
1994 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
1997 memcpy(buffer
, http
->buffer
, length
);
1998 http
->used
-= (int)length
;
2001 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2006 if (!http
->blocking
&& !httpWait(http
, 10000))
2009 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
2011 #endif /* HAVE_SSL */
2014 if (!http
->blocking
&& !httpWait(http
, 10000))
2017 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2018 CUPS_LLCAST length
));
2021 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2023 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2025 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2028 else if (WSAGetLastError() != WSAEINTR
)
2032 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2034 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2036 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2038 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2041 else if (errno
!= EINTR
)
2046 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2047 CUPS_LLCAST bytes
));
2052 http
->data_remaining
-= bytes
;
2054 if (http
->data_remaining
<= INT_MAX
)
2055 http
->_data_remaining
= (int)http
->data_remaining
;
2057 http
->_data_remaining
= INT_MAX
;
2062 if (WSAGetLastError() == WSAEINTR
)
2065 http
->error
= WSAGetLastError();
2067 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2070 http
->error
= errno
;
2075 http
->error
= EPIPE
;
2079 if (http
->data_remaining
== 0)
2081 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2082 httpGets(len
, sizeof(len
), http
);
2084 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2086 if (http
->state
== HTTP_POST_RECV
)
2089 http
->state
= HTTP_WAITING
;
2094 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2101 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2103 * '_httpReadCDSA()' - Read function for the CDSA library.
2106 OSStatus
/* O - -1 on error, 0 on success */
2108 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2109 void *data
, /* I - Data buffer */
2110 size_t *dataLength
) /* IO - Number of bytes */
2112 OSStatus result
; /* Return value */
2113 ssize_t bytes
; /* Number of bytes read */
2114 http_t
*http
; /* HTTP connection */
2117 http
= (http_t
*)connection
;
2119 if (!http
->blocking
)
2122 * Make sure we have data before we read...
2125 if (!_httpWait(http
, 10000, 0))
2127 http
->error
= ETIMEDOUT
;
2134 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2136 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2138 if (bytes
== *dataLength
)
2144 *dataLength
= bytes
;
2145 result
= errSSLWouldBlock
;
2152 result
= errSSLClosedGraceful
;
2153 else if (errno
== EAGAIN
)
2154 result
= errSSLWouldBlock
;
2156 result
= errSSLClosedAbort
;
2161 #endif /* HAVE_SSL && HAVE_CDSASSL */
2164 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2166 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2169 ssize_t
/* O - Number of bytes read or -1 on error */
2171 gnutls_transport_ptr ptr
, /* I - Connection to server */
2172 void *data
, /* I - Buffer */
2173 size_t length
) /* I - Number of bytes to read */
2175 http_t
*http
; /* HTTP connection */
2178 http
= (http_t
*)ptr
;
2180 if (!http
->blocking
)
2183 * Make sure we have data before we read...
2186 if (!_httpWait(http
, 10000, 0))
2188 http
->error
= ETIMEDOUT
;
2193 return (recv(http
->fd
, data
, length
, 0));
2195 #endif /* HAVE_SSL && HAVE_GNUTLS */
2199 * 'httpReconnect()' - Reconnect to a HTTP server.
2202 int /* O - 0 on success, non-zero on failure */
2203 httpReconnect(http_t
*http
) /* I - Connection to server */
2205 http_addrlist_t
*addr
; /* Connected address */
2207 http_addrlist_t
*current
; /* Current address */
2208 char temp
[256]; /* Temporary address string */
2212 DEBUG_printf(("httpReconnect(http=%p)", http
));
2220 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2221 http_shutdown_ssl(http
);
2223 #endif /* HAVE_SSL */
2226 * Close any previously open socket...
2231 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2234 closesocket(http
->fd
);
2243 * Connect to the server...
2247 for (current
= http
->addrlist
; current
; current
= current
->next
)
2248 DEBUG_printf(("2httpReconnect: Address %s:%d",
2249 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2250 _httpAddrPort(&(current
->addr
))));
2253 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
2256 * Unable to connect...
2260 http
->error
= WSAGetLastError();
2262 http
->error
= errno
;
2264 http
->status
= HTTP_ERROR
;
2266 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2267 strerror(http
->error
)));
2272 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2274 if (http
->timeout_value
.tv_sec
> 0)
2276 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, &(http
->timeout_value
),
2277 sizeof(http
->timeout_value
));
2278 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, &(http
->timeout_value
),
2279 sizeof(http
->timeout_value
));
2282 http
->hostaddr
= &(addr
->addr
);
2284 http
->status
= HTTP_CONTINUE
;
2287 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2290 * Always do encryption via SSL.
2293 if (http_setup_ssl(http
) != 0)
2296 closesocket(http
->fd
);
2304 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2305 return (http_upgrade(http
));
2306 #endif /* HAVE_SSL */
2308 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2309 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2310 _httpAddrPort(http
->hostaddr
)));
2317 * 'httpSetAuthString()' - Set the current authorization string.
2319 * This function just stores a copy of the current authorization string in
2320 * the HTTP connection object. You must still call httpSetField() to set
2321 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2322 * httpHead(), httpOptions(), httpPost, or httpPut().
2324 * @since CUPS 1.3/Mac OS X 10.5@
2328 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2329 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2330 const char *data
) /* I - Auth data (NULL for none) */
2333 * Range check input...
2339 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2340 free(http
->authstring
);
2342 http
->authstring
= http
->_authstring
;
2347 * Set the current authorization string...
2350 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2353 if (len
> (int)sizeof(http
->_authstring
))
2355 if ((temp
= malloc(len
)) == NULL
)
2356 len
= sizeof(http
->_authstring
);
2358 http
->authstring
= temp
;
2362 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2364 strlcpy(http
->authstring
, scheme
, len
);
2369 * Clear the current authorization string...
2372 http
->_authstring
[0] = '\0';
2378 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2384 int /* O - Status of call (0 = success) */
2385 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2386 cups_array_t
*credentials
) /* I - Array of credentials */
2388 if (!http
|| cupsArrayCount(credentials
) < 1)
2391 _httpFreeCredentials(http
->tls_credentials
);
2393 http
->tls_credentials
= _httpConvertCredentials(credentials
);
2395 return (http
->tls_credentials
? 0 : -1);
2400 * 'httpSetCookie()' - Set the cookie value(s).
2402 * @since CUPS 1.1.19/Mac OS X 10.3@
2406 httpSetCookie(http_t
*http
, /* I - Connection */
2407 const char *cookie
) /* I - Cookie string */
2416 http
->cookie
= strdup(cookie
);
2418 http
->cookie
= NULL
;
2423 * 'httpSetExpect()' - Set the Expect: header in a request.
2425 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2427 * @since CUPS 1.2/Mac OS X 10.5@
2431 httpSetExpect(http_t
*http
, /* I - Connection to server */
2432 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2435 http
->expect
= expect
;
2440 * 'httpSetField()' - Set the value of an HTTP header.
2444 httpSetField(http_t
*http
, /* I - Connection to server */
2445 http_field_t field
, /* I - Field index */
2446 const char *value
) /* I - Value */
2449 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2450 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2454 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2456 if (field
== HTTP_FIELD_AUTHORIZATION
)
2459 * Special case for Authorization: as its contents can be
2460 * longer than HTTP_MAX_VALUE
2463 if (http
->field_authorization
)
2464 free(http
->field_authorization
);
2466 http
->field_authorization
= strdup(value
);
2468 else if (field
== HTTP_FIELD_HOST
)
2471 * Special-case for Host: as we don't want a trailing "." on the hostname and
2472 * need to bracket IPv6 numeric addresses.
2475 char *ptr
= strchr(value
, ':');
2477 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2480 * Bracket IPv6 numeric addresses...
2482 * This is slightly inefficient (basically copying twice), but is an edge
2483 * case and not worth optimizing...
2486 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2487 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2492 * Check for a trailing dot on the hostname...
2495 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2499 ptr
+= strlen(ptr
) - 1;
2510 * 'httpSetLength()' - Set the content-length and content-encoding.
2512 * @since CUPS 1.2/Mac OS X 10.5@
2516 httpSetLength(http_t
*http
, /* I - Connection to server */
2517 size_t length
) /* I - Length (0 for chunked) */
2524 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2525 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2529 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2530 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2531 CUPS_LLFMT
, CUPS_LLCAST length
);
2537 * '_httpSetTimeout()' - Set read/write timeouts and an optional callback.
2539 * The optional timeout callback receives both the HTTP connection and a user
2540 * data pointer and must return 1 to continue or 0 to error out.
2545 http_t
*http
, /* I - Connection to server */
2546 double timeout
, /* I - Number of seconds for timeout,
2547 must be greater than 0 */
2548 _http_timeout_cb_t cb
, /* I - Callback function or NULL */
2549 void *user_data
) /* I - User data pointer */
2551 if (!http
|| timeout
<= 0.0)
2554 http
->timeout_cb
= cb
;
2555 http
->timeout_data
= user_data
;
2556 http
->timeout_value
.tv_sec
= (int)timeout
;
2557 http
->timeout_value
.tv_usec
= (int)(timeout
* 1000000) % 1000000;
2561 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, &(http
->timeout_value
),
2562 sizeof(http
->timeout_value
));
2563 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, &(http
->timeout_value
),
2564 sizeof(http
->timeout_value
));
2570 * 'httpTrace()' - Send an TRACE request to the server.
2573 int /* O - Status of call (0 = success) */
2574 httpTrace(http_t
*http
, /* I - Connection to server */
2575 const char *uri
) /* I - URI for trace */
2577 return (http_send(http
, HTTP_TRACE
, uri
));
2582 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2585 http_status_t
/* O - HTTP status */
2586 httpUpdate(http_t
*http
) /* I - Connection to server */
2588 char line
[32768], /* Line from connection... */
2589 *value
; /* Pointer to value on line */
2590 http_field_t field
; /* Field index */
2591 int major
, minor
, /* HTTP version numbers */
2592 status
; /* Request status */
2595 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2596 http_states
[http
->state
]));
2599 * Flush pending data, if any...
2604 DEBUG_puts("2httpUpdate: flushing buffer...");
2606 if (httpFlushWrite(http
) < 0)
2607 return (HTTP_ERROR
);
2611 * If we haven't issued any commands, then there is nothing to "update"...
2614 if (http
->state
== HTTP_WAITING
)
2615 return (HTTP_CONTINUE
);
2618 * Grab all of the lines we can from the connection...
2621 while (httpGets(line
, sizeof(line
), http
) != NULL
)
2623 DEBUG_printf(("2httpUpdate: Got \"%s\"", line
));
2625 if (line
[0] == '\0')
2628 * Blank line means the start of the data section (if any). Return
2629 * the result code, too...
2631 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2632 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2636 if (http
->status
== HTTP_CONTINUE
)
2637 return (http
->status
);
2639 if (http
->status
< HTTP_BAD_REQUEST
)
2640 http
->digest_tries
= 0;
2643 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2645 if (http_setup_ssl(http
) != 0)
2648 closesocket(http
->fd
);
2653 return (HTTP_ERROR
);
2656 return (HTTP_CONTINUE
);
2658 #endif /* HAVE_SSL */
2660 httpGetLength2(http
);
2662 switch (http
->state
)
2666 case HTTP_POST_RECV
:
2669 case HTTP_POST_SEND
:
2674 http
->state
= HTTP_WAITING
;
2678 return (http
->status
);
2680 else if (!strncmp(line
, "HTTP/", 5))
2683 * Got the beginning of a response...
2686 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
2687 return (HTTP_ERROR
);
2689 http
->version
= (http_version_t
)(major
* 100 + minor
);
2690 http
->status
= (http_status_t
)status
;
2692 else if ((value
= strchr(line
, ':')) != NULL
)
2699 while (_cups_isspace(*value
))
2703 * Be tolerants of servers that send unknown attribute fields...
2706 if (!strcasecmp(line
, "expect"))
2709 * "Expect: 100-continue" or similar...
2712 http
->expect
= (http_status_t
)atoi(value
);
2714 else if (!strcasecmp(line
, "cookie"))
2717 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2720 httpSetCookie(http
, value
);
2722 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
2724 DEBUG_printf(("1httpUpdate: unknown field %s seen!", line
));
2728 httpSetField(http
, field
, value
);
2732 DEBUG_printf(("1httpUpdate: Bad response line \"%s\"!", line
));
2733 http
->status
= HTTP_ERROR
;
2734 return (HTTP_ERROR
);
2739 * See if there was an error...
2742 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2744 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2745 return (http
->status
);
2750 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2751 strerror(http
->error
)));
2752 http
->status
= HTTP_ERROR
;
2753 return (HTTP_ERROR
);
2757 * If we haven't already returned, then there is nothing new...
2760 return (HTTP_CONTINUE
);
2765 * '_httpWait()' - Wait for data available on a connection (no flush).
2768 int /* O - 1 if data is available, 0 otherwise */
2769 _httpWait(http_t
*http
, /* I - Connection to server */
2770 int msec
, /* I - Milliseconds to wait */
2771 int usessl
) /* I - Use SSL context? */
2774 struct pollfd pfd
; /* Polled file descriptor */
2776 fd_set input_set
; /* select() input set */
2777 struct timeval timeout
; /* Timeout */
2778 #endif /* HAVE_POLL */
2779 int nfds
; /* Result from select()/poll() */
2782 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2786 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2791 * Check the SSL/TLS buffers for data first...
2795 if (http
->tls
&& usessl
)
2798 if (SSL_pending(http
->tls
))
2800 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2804 # elif defined(HAVE_GNUTLS)
2805 if (gnutls_record_check_pending(http
->tls
))
2807 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2811 # elif defined(HAVE_CDSASSL)
2812 size_t bytes
; /* Bytes that are available */
2814 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2817 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2820 # endif /* HAVE_LIBSSL */
2822 #endif /* HAVE_SSL */
2825 * Then try doing a select() or poll() to poll the socket...
2830 pfd
.events
= POLLIN
;
2832 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2833 (errno
== EINTR
|| errno
== EAGAIN
));
2838 FD_ZERO(&input_set
);
2839 FD_SET(http
->fd
, &input_set
);
2841 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2845 timeout
.tv_sec
= msec
/ 1000;
2846 timeout
.tv_usec
= (msec
% 1000) * 1000;
2848 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2851 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2853 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2856 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2857 WSAGetLastError() == WSAEWOULDBLOCK
));
2859 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2861 #endif /* HAVE_POLL */
2863 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2871 * 'httpWait()' - Wait for data available on a connection.
2873 * @since CUPS 1.1.19/Mac OS X 10.3@
2876 int /* O - 1 if data is available, 0 otherwise */
2877 httpWait(http_t
*http
, /* I - Connection to server */
2878 int msec
) /* I - Milliseconds to wait */
2881 * First see if there is data in the buffer...
2891 * Flush pending data, if any...
2896 if (httpFlushWrite(http
) < 0)
2901 * If not, check the SSL/TLS buffers and do a select() on the connection...
2904 return (_httpWait(http
, msec
, 1));
2909 * 'httpWrite()' - Write data to a HTTP connection.
2911 * This function is deprecated. Use the httpWrite2() function which can
2912 * write more than 2GB of data.
2917 int /* O - Number of bytes written */
2918 httpWrite(http_t
*http
, /* I - Connection to server */
2919 const char *buffer
, /* I - Buffer for data */
2920 int length
) /* I - Number of bytes to write */
2922 return ((int)httpWrite2(http
, buffer
, length
));
2927 * 'httpWrite2()' - Write data to a HTTP connection.
2929 * @since CUPS 1.2/Mac OS X 10.5@
2932 ssize_t
/* O - Number of bytes written */
2933 httpWrite2(http_t
*http
, /* I - Connection to server */
2934 const char *buffer
, /* I - Buffer for data */
2935 size_t length
) /* I - Number of bytes to write */
2937 ssize_t bytes
; /* Bytes written */
2940 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
2941 buffer
, CUPS_LLCAST length
));
2944 * Range check input...
2947 if (http
== NULL
|| buffer
== NULL
)
2951 * Mark activity on the connection...
2954 http
->activity
= time(NULL
);
2957 * Buffer small writes for better performance...
2962 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2964 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
2965 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
2967 httpFlushWrite(http
);
2970 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
2971 length
< sizeof(http
->wbuffer
))
2974 * Write to buffer...
2977 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
2978 CUPS_LLCAST length
));
2980 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2981 http
->wused
+= (int)length
;
2982 bytes
= (ssize_t
)length
;
2987 * Otherwise write the data directly...
2990 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
2991 CUPS_LLCAST length
));
2993 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2994 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2996 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2998 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
2999 CUPS_LLCAST bytes
));
3002 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3003 http
->data_remaining
-= bytes
;
3009 * Handle end-of-request processing...
3012 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3013 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3016 * Finished with the transfer; unless we are sending POST or PUT
3020 DEBUG_puts("2httpWrite: changing states...");
3023 httpFlushWrite(http
);
3025 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3028 * Send a 0-length chunk at the end of the request...
3031 http_write(http
, "0\r\n\r\n", 5);
3034 * Reset the data state...
3037 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3038 http
->data_remaining
= 0;
3041 if (http
->state
== HTTP_POST_RECV
)
3043 else if (http
->state
== HTTP_PUT_RECV
)
3044 http
->state
= HTTP_STATUS
;
3046 http
->state
= HTTP_WAITING
;
3053 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3055 * '_httpWriteCDSA()' - Write function for the CDSA library.
3058 OSStatus
/* O - -1 on error, 0 on success */
3060 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3061 const void *data
, /* I - Data buffer */
3062 size_t *dataLength
) /* IO - Number of bytes */
3064 OSStatus result
; /* Return value */
3065 ssize_t bytes
; /* Number of bytes read */
3066 http_t
*http
; /* HTTP connection */
3069 http
= (http_t
*)connection
;
3073 bytes
= write(http
->fd
, data
, *dataLength
);
3075 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3077 if (bytes
== *dataLength
)
3081 else if (bytes
>= 0)
3083 *dataLength
= bytes
;
3084 result
= errSSLWouldBlock
;
3090 if (errno
== EAGAIN
)
3091 result
= errSSLWouldBlock
;
3093 result
= errSSLClosedAbort
;
3098 #endif /* HAVE_SSL && HAVE_CDSASSL */
3101 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3103 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3106 ssize_t
/* O - Number of bytes written or -1 on error */
3108 gnutls_transport_ptr ptr
, /* I - Connection to server */
3109 const void *data
, /* I - Data buffer */
3110 size_t length
) /* I - Number of bytes to write */
3112 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
3114 #endif /* HAVE_SSL && HAVE_GNUTLS */
3117 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3119 * 'http_bio_ctrl()' - Control the HTTP connection.
3122 static long /* O - Result/data */
3123 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3124 int cmd
, /* I - Control command */
3125 long arg1
, /* I - First argument */
3126 void *arg2
) /* I - Second argument */
3133 case BIO_CTRL_RESET
:
3137 case BIO_C_SET_FILE_PTR
:
3142 case BIO_C_GET_FILE_PTR
:
3145 *((void **)arg2
) = h
->ptr
;
3152 case BIO_CTRL_FLUSH
:
3159 * 'http_bio_free()' - Free OpenSSL data.
3162 static int /* O - 1 on success, 0 on failure */
3163 http_bio_free(BIO
*h
) /* I - BIO data */
3179 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3182 static int /* O - 1 on success, 0 on failure */
3183 http_bio_new(BIO
*h
) /* I - BIO data */
3198 * 'http_bio_puts()' - Send a string for OpenSSL.
3201 static int /* O - Bytes written */
3202 http_bio_puts(BIO
*h
, /* I - BIO data */
3203 const char *str
) /* I - String to write */
3206 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3208 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3214 * 'http_bio_read()' - Read data for OpenSSL.
3217 static int /* O - Bytes read */
3218 http_bio_read(BIO
*h
, /* I - BIO data */
3219 char *buf
, /* I - Buffer */
3220 int size
) /* I - Number of bytes to read */
3222 http_t
*http
; /* HTTP connection */
3225 http
= (http_t
*)h
->ptr
;
3227 if (!http
->blocking
)
3230 * Make sure we have data before we read...
3233 if (!_httpWait(http
, 10000, 0))
3236 http
->error
= WSAETIMEDOUT
;
3238 http
->error
= ETIMEDOUT
;
3245 return (recv(http
->fd
, buf
, size
, 0));
3250 * 'http_bio_write()' - Write data for OpenSSL.
3253 static int /* O - Bytes written */
3254 http_bio_write(BIO
*h
, /* I - BIO data */
3255 const char *buf
, /* I - Buffer to write */
3256 int num
) /* I - Number of bytes to write */
3258 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3260 #endif /* HAVE_SSL && HAVE_LIBSSL */
3265 * 'http_debug_hex()' - Do a hex dump of a buffer.
3269 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3270 const char *buffer
, /* I - Buffer to dump */
3271 int bytes
) /* I - Bytes to dump */
3273 int i
, j
, /* Looping vars */
3274 ch
; /* Current character */
3275 char line
[255], /* Line buffer */
3276 *start
, /* Start of line after prefix */
3277 *ptr
; /* Pointer into line */
3280 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3283 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
3285 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3286 start
= line
+ strlen(line
);
3288 for (i
= 0; i
< bytes
; i
+= 16)
3290 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3291 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3303 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3305 ch
= buffer
[i
+ j
] & 255;
3307 if (ch
< ' ' || ch
>= 127)
3321 * 'http_field()' - Return the field index for a field name.
3324 static http_field_t
/* O - Field index */
3325 http_field(const char *name
) /* I - String name */
3327 int i
; /* Looping var */
3330 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3331 if (strcasecmp(name
, http_fields
[i
]) == 0)
3332 return ((http_field_t
)i
);
3334 return (HTTP_FIELD_UNKNOWN
);
3340 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3343 static int /* O - Bytes read */
3344 http_read_ssl(http_t
*http
, /* I - Connection to server */
3345 char *buf
, /* I - Buffer to store data */
3346 int len
) /* I - Length of buffer */
3348 # if defined(HAVE_LIBSSL)
3349 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3351 # elif defined(HAVE_GNUTLS)
3352 ssize_t result
; /* Return value */
3355 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3357 if (result
< 0 && !errno
)
3360 * Convert GNU TLS error to errno value...
3365 case GNUTLS_E_INTERRUPTED
:
3369 case GNUTLS_E_AGAIN
:
3381 return ((int)result
);
3383 # elif defined(HAVE_CDSASSL)
3384 int result
; /* Return value */
3385 OSStatus error
; /* Error info */
3386 size_t processed
; /* Number of bytes processed */
3389 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3394 result
= (int)processed
;
3396 case errSSLClosedGraceful
:
3399 case errSSLWouldBlock
:
3401 result
= (int)processed
;
3415 # elif defined(HAVE_SSPISSL)
3416 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3417 # endif /* HAVE_LIBSSL */
3419 #endif /* HAVE_SSL */
3424 * 'http_locking_cb()' - Lock/unlock a thread's mutex.
3428 http_locking_cb(int mode
, /* I - Lock mode */
3429 int type
, /* I - Lock type */
3430 const char *file
, /* I - Source file */
3431 int line
) /* I - Line number */
3433 if (mode
& CRYPTO_LOCK
)
3434 _cupsMutexLock(http_locks
+ type
);
3436 _cupsMutexUnlock(http_locks
+ type
);
3438 #endif /* HAVE_LIBSSL */
3442 * 'http_send()' - Send a request with all fields and the trailing blank line.
3445 static int /* O - 0 on success, non-zero on error */
3446 http_send(http_t
*http
, /* I - Connection to server */
3447 http_state_t request
, /* I - Request code */
3448 const char *uri
) /* I - URI */
3450 int i
; /* Looping var */
3451 char buf
[1024]; /* Encoded URI buffer */
3452 static const char * const codes
[] =
3453 { /* Request code strings */
3470 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3471 http
, codes
[request
], uri
));
3473 if (http
== NULL
|| uri
== NULL
)
3477 * Set the User-Agent field if it isn't already...
3480 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3481 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3484 * Encode the URI as needed...
3487 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3490 * See if we had an error the last time around; if so, reconnect...
3493 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3494 if (httpReconnect(http
))
3498 * Flush any written data that is pending...
3503 if (httpFlushWrite(http
) < 0)
3504 if (httpReconnect(http
))
3509 * Send the request header...
3512 http
->state
= request
;
3513 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3515 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3518 http
->status
= HTTP_CONTINUE
;
3521 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3523 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3524 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3526 #endif /* HAVE_SSL */
3528 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3530 http
->status
= HTTP_ERROR
;
3534 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3535 if (http
->fields
[i
][0] != '\0')
3537 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3538 httpGetField(http
, i
)));
3540 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3541 httpGetField(http
, i
)) < 1)
3543 http
->status
= HTTP_ERROR
;
3549 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3551 http
->status
= HTTP_ERROR
;
3555 if (http
->expect
== HTTP_CONTINUE
&&
3556 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3557 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3559 http
->status
= HTTP_ERROR
;
3563 if (httpPrintf(http
, "\r\n") < 1)
3565 http
->status
= HTTP_ERROR
;
3569 if (httpFlushWrite(http
) < 0)
3572 httpGetLength2(http
);
3573 httpClearFields(http
);
3576 * The Kerberos and AuthRef authentication strings can only be used once...
3579 if (http
->field_authorization
&& http
->authstring
&&
3580 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3581 !strncmp(http
->authstring
, "AuthRef", 7)))
3583 http
->_authstring
[0] = '\0';
3585 if (http
->authstring
!= http
->_authstring
)
3586 free(http
->authstring
);
3588 http
->authstring
= http
->_authstring
;
3597 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3600 static int /* O - Status of connection */
3601 http_set_credentials(http_t
*http
) /* I - Connection to server */
3603 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3604 # ifdef HAVE_CDSASSL
3605 OSStatus error
= 0; /* Error code */
3606 http_tls_credentials_t credentials
= NULL
;
3607 /* TLS credentials */
3608 # endif /* HAVE_CDSASSL */
3611 DEBUG_printf(("7http_set_credentials(%p)", http
));
3616 # elif defined(HAVE_GNUTLS)
3619 # elif defined(HAVE_CDSASSL)
3621 * Prefer connection specific credentials...
3624 if ((credentials
= http
->tls_credentials
) == NULL
)
3625 credentials
= cg
->tls_credentials
;
3627 # if HAVE_SECPOLICYCREATESSL
3629 * Otherwise root around in the user's keychain to see if one can be found...
3634 CFDictionaryRef query
; /* Query dictionary */
3635 CFTypeRef matches
= NULL
; /* Matching credentials */
3636 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3637 CFTypeRef keys
[] = { kSecClass
,
3640 /* Keys for dictionary */
3641 CFTypeRef values
[] = { kSecClassCertificate
,
3644 /* Values for dictionary */
3647 * Get the names associated with the server.
3650 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3652 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3658 * Create a query which will return all identities that can sign and match
3659 * the passed in policy.
3662 query
= CFDictionaryCreate(NULL
,
3663 (const void**)(&keys
[0]),
3664 (const void**)(&values
[0]),
3665 sizeof(keys
) / sizeof(keys
[0]),
3666 &kCFTypeDictionaryKeyCallBacks
,
3667 &kCFTypeDictionaryValueCallBacks
);
3670 error
= SecItemCopyMatching(query
, &matches
);
3671 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3680 CFRelease(dn_array
);
3682 # endif /* HAVE_SECPOLICYCREATESSL */
3686 error
= SSLSetCertificate(http
->tls
, credentials
);
3687 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3691 DEBUG_puts("4http_set_credentials: No credentials to set.");
3695 # elif defined(HAVE_SSPISSL)
3697 # endif /* HAVE_LIBSSL */
3702 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3705 static int /* O - Status of connection */
3706 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3708 _cups_globals_t
*cg
= _cupsGlobals();
3709 /* Pointer to library globals */
3710 int any_root
; /* Allow any root */
3713 SSL_CTX
*context
; /* Context for encryption */
3714 BIO
*bio
; /* BIO data */
3715 # elif defined(HAVE_GNUTLS)
3716 gnutls_certificate_client_credentials
*credentials
;
3717 /* TLS credentials */
3718 # elif defined(HAVE_CDSASSL)
3719 OSStatus error
; /* Error code */
3720 const char *message
= NULL
; /* Error message */
3721 cups_array_t
*credentials
; /* Credentials array */
3722 char *hostname
; /* Hostname */
3723 cups_array_t
*names
; /* CUPS distinguished names */
3724 CFArrayRef dn_array
; /* CF distinguished names array */
3725 CFIndex count
; /* Number of credentials */
3726 CFDataRef data
; /* Certificate data */
3727 int i
; /* Looping var */
3729 *credential
; /* Credential data */
3730 # elif defined(HAVE_SSPISSL)
3731 TCHAR username
[256]; /* Username returned from GetUserName() */
3732 TCHAR commonName
[256]; /* Common name for certificate */
3733 DWORD dwSize
; /* 32 bit size */
3734 # endif /* HAVE_LIBSSL */
3737 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3740 * Always allow self-signed certificates for the local loopback address...
3743 if (httpAddrLocalhost(http
->hostaddr
))
3746 any_root
= cg
->any_root
;
3749 context
= SSL_CTX_new(SSLv23_client_method());
3751 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3753 bio
= BIO_new(_httpBIOMethods());
3754 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3756 http
->tls
= SSL_new(context
);
3757 SSL_set_bio(http
->tls_credentials
, bio
, bio
);
3759 if (SSL_connect(http
->tls
) != 1)
3762 unsigned long error
; /* Error code */
3764 while ((error
= ERR_get_error()) != 0)
3765 DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error
, NULL
)));
3768 SSL_CTX_free(context
);
3769 SSL_free(http
->tls
);
3773 http
->error
= WSAGetLastError();
3775 http
->error
= errno
;
3777 http
->status
= HTTP_ERROR
;
3779 return (HTTP_ERROR
);
3782 # elif defined(HAVE_GNUTLS)
3783 credentials
= (gnutls_certificate_client_credentials
*)
3784 malloc(sizeof(gnutls_certificate_client_credentials
));
3785 if (credentials
== NULL
)
3787 http
->error
= errno
;
3788 http
->status
= HTTP_ERROR
;
3793 gnutls_certificate_allocate_credentials(credentials
);
3795 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3796 gnutls_set_default_priority(http
->tls
);
3797 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3798 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3799 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3800 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3802 if ((gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3804 http
->error
= errno
;
3805 http
->status
= HTTP_ERROR
;
3807 gnutls_deinit(http
->tls
);
3808 gnutls_certificate_free_credentials(*credentials
);
3815 http
->tls_credentials
= credentials
;
3817 # elif defined(HAVE_CDSASSL)
3818 if ((error
= SSLNewContext(false, &http
->tls
)))
3820 http
->error
= error
;
3821 http
->status
= HTTP_ERROR
;
3826 error
= SSLSetConnection(http
->tls
, http
);
3827 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
3831 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
3832 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
3837 error
= SSLSetProtocolVersionEnabled(http
->tls
, kSSLProtocol2
, false);
3838 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionEnabled, error=%d",
3844 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
3845 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
3846 any_root
, (int)error
));
3851 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
3852 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
3853 cg
->expired_certs
, (int)error
));
3858 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
3859 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
3860 cg
->expired_root
, (int)error
));
3865 if (cg
->client_cert_cb
)
3867 error
= SSLSetSessionOption(http
->tls
,
3868 kSSLSessionOptionBreakOnCertRequested
, true);
3869 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
3870 "error=%d", (int)error
));
3874 error
= http_set_credentials(http
);
3875 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
3881 * If there's a server certificate callback installed let it evaluate the
3882 * certificate(s) during the handshake...
3885 if (!error
&& cg
->server_cert_cb
!= NULL
)
3887 error
= SSLSetEnableCertVerify(http
->tls
, false);
3888 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
3893 error
= SSLSetSessionOption(http
->tls
,
3894 kSSLSessionOptionBreakOnServerAuth
, true);
3895 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
3896 "error=%d", (int)error
));
3902 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
3903 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
3905 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
3911 int done
= 0; /* Are we done yet? */
3913 while (!error
&& !done
)
3915 error
= SSLHandshake(http
->tls
);
3917 DEBUG_printf(("4_httpWait: SSLHandshake returned %d.", (int)error
));
3925 case errSSLWouldBlock
:
3929 case errSSLServerAuthCompleted
:
3931 if (cg
->server_cert_cb
)
3933 error
= httpCopyCredentials(http
, &credentials
);
3936 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
3937 cg
->server_cert_data
);
3938 httpFreeCredentials(credentials
);
3941 DEBUG_printf(("4_httpWait: Server certificate callback returned "
3942 "%d.", (int)error
));
3946 case errSSLClientCertRequested
:
3949 if (cg
->client_cert_cb
)
3952 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
3955 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
3957 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
3959 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
3961 if ((credential
= malloc(sizeof(*credential
))))
3963 credential
->datalen
= CFDataGetLength(data
);
3964 if ((credential
->data
= malloc(credential
->datalen
)))
3966 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
3967 credential
->datalen
);
3968 cupsArrayAdd(names
, credential
);
3974 CFRelease(dn_array
);
3979 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
3980 cg
->client_cert_data
);
3982 DEBUG_printf(("4_httpWait: Client certificate callback "
3983 "returned %d.", (int)error
));
3986 httpFreeCredentials(names
);
3990 case errSSLUnknownRootCert
:
3991 message
= _("Unable to establish a secure connection to host "
3992 "(untrusted certificate).");
3995 case errSSLNoRootCert
:
3996 message
= _("Unable to establish a secure connection to host "
3997 "(self-signed certificate).");
4000 case errSSLCertExpired
:
4001 message
= _("Unable to establish a secure connection to host "
4002 "(expired certificate).");
4005 case errSSLCertNotYetValid
:
4006 message
= _("Unable to establish a secure connection to host "
4007 "(certificate not yet valid).");
4010 case errSSLHostNameMismatch
:
4011 message
= _("Unable to establish a secure connection to host "
4012 "(host name mismatch).");
4015 case errSSLXCertChainInvalid
:
4016 message
= _("Unable to establish a secure connection to host "
4017 "(certificate chain invalid).");
4020 case errSSLConnectionRefused
:
4021 message
= _("Unable to establish a secure connection to host "
4022 "(peer dropped connection before responding).");
4033 http
->error
= error
;
4034 http
->status
= HTTP_ERROR
;
4035 errno
= ECONNREFUSED
;
4037 SSLDisposeContext(http
->tls
);
4041 * If an error string wasn't set by the callbacks use a generic one...
4045 #ifdef HAVE_CSSMERRORSTRING
4046 message
= cssmErrorString(error
);
4048 message
= _("Unable to establish a secure connection to host.");
4049 #endif /* HAVE_CSSMERRORSTRING */
4051 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4056 # elif defined(HAVE_SSPISSL)
4057 http
->tls
= _sspiAlloc();
4062 http
->tls
->sock
= http
->fd
;
4063 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4064 GetUserName(username
, &dwSize
);
4065 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4066 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4068 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4071 _sspiFree(http
->tls_credentials
);
4072 http
->tls_credentials
= NULL
;
4076 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
4077 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4079 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
4081 _sspiFree(http
->tls_credentials
);
4082 http
->tls_credentials
= NULL
;
4085 # endif /* HAVE_CDSASSL */
4089 #endif /* HAVE_SSL */
4094 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4098 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4101 SSL_CTX
*context
; /* Context for encryption */
4103 context
= SSL_get_SSL_CTX(http
->tls_credentials
);
4105 SSL_shutdown(http
->tls_credentials
);
4106 SSL_CTX_free(context
);
4107 SSL_free(http
->tls_credentials
);
4109 # elif defined(HAVE_GNUTLS)
4110 gnutls_certificate_client_credentials
*credentials
;
4111 /* TLS credentials */
4113 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4115 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4116 gnutls_deinit(http
->tls
);
4117 gnutls_certificate_free_credentials(*credentials
);
4120 # elif defined(HAVE_CDSASSL)
4121 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4124 SSLDisposeContext(http
->tls
);
4126 if (http
->tls_credentials
)
4127 CFRelease(http
->tls_credentials
);
4129 # elif defined(HAVE_SSPISSL)
4130 _sspiFree(http
->tls_credentials
);
4131 # endif /* HAVE_LIBSSL */
4134 http
->tls_credentials
= NULL
;
4136 #endif /* HAVE_SSL */
4141 * 'http_threadid_cb()' - Return the current thread ID.
4144 static unsigned long /* O - Thread ID */
4145 http_threadid_cb(void)
4147 # ifdef HAVE_PTHREAD_H
4148 return ((unsigned long)pthread_self());
4151 # endif /* HAVE_PTHREAD_H */
4153 #endif /* HAVE_LIBSSL */
4158 * 'http_upgrade()' - Force upgrade to TLS encryption.
4161 static int /* O - Status of connection */
4162 http_upgrade(http_t
*http
) /* I - Connection to server */
4164 int ret
; /* Return value */
4165 http_t myhttp
; /* Local copy of HTTP data */
4168 DEBUG_printf(("7http_upgrade(%p)", http
));
4171 * Flush the connection to make sure any previous "Upgrade" message
4178 * Copy the HTTP data to a local variable so we can do the OPTIONS
4179 * request without interfering with the existing request data...
4182 memcpy(&myhttp
, http
, sizeof(myhttp
));
4185 * Send an OPTIONS request to the server, requiring SSL or TLS
4186 * encryption on the link...
4189 http
->field_authorization
= NULL
; /* Don't free the auth string */
4191 httpClearFields(http
);
4192 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4193 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4195 if ((ret
= httpOptions(http
, "*")) == 0)
4198 * Wait for the secure connection...
4201 while (httpUpdate(http
) == HTTP_CONTINUE
);
4205 * Restore the HTTP request data...
4208 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4209 http
->data_encoding
= myhttp
.data_encoding
;
4210 http
->data_remaining
= myhttp
.data_remaining
;
4211 http
->_data_remaining
= myhttp
._data_remaining
;
4212 http
->expect
= myhttp
.expect
;
4213 http
->field_authorization
= myhttp
.field_authorization
;
4214 http
->digest_tries
= myhttp
.digest_tries
;
4217 * See if we actually went secure...
4223 * Server does not support HTTP upgrade...
4226 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4229 closesocket(http
->fd
);
4241 #endif /* HAVE_SSL */
4245 * 'http_write()' - Write a buffer to a HTTP connection.
4248 static int /* O - Number of bytes written */
4249 http_write(http_t
*http
, /* I - Connection to server */
4250 const char *buffer
, /* I - Buffer for data */
4251 int length
) /* I - Number of bytes to write */
4253 int tbytes
, /* Total bytes sent */
4254 bytes
; /* Bytes sent */
4257 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4266 bytes
= http_write_ssl(http
, buffer
, length
);
4268 #endif /* HAVE_SSL */
4269 bytes
= send(http
->fd
, buffer
, length
, 0);
4274 if (WSAGetLastError() == WSAEINTR
)
4276 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4278 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4281 http
->error
= WSAGetLastError();
4283 else if (WSAGetLastError() != http
->error
&&
4284 WSAGetLastError() != WSAECONNRESET
)
4286 http
->error
= WSAGetLastError();
4293 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4295 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4297 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4300 http
->error
= errno
;
4302 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4304 http
->error
= errno
;
4309 DEBUG_printf(("3http_write: error writing data (%s).",
4310 strerror(http
->error
)));
4321 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4324 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4331 * 'http_write_chunk()' - Write a chunked buffer.
4334 static int /* O - Number bytes written */
4335 http_write_chunk(http_t
*http
, /* I - Connection to server */
4336 const char *buffer
, /* I - Buffer to write */
4337 int length
) /* I - Length of buffer */
4339 char header
[255]; /* Chunk header */
4340 int bytes
; /* Bytes written */
4343 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4344 http
, buffer
, length
));
4347 * Write the chunk header, data, and trailer.
4350 sprintf(header
, "%x\r\n", length
);
4351 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4353 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4357 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4359 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4363 if (http_write(http
, "\r\n", 2) < 0)
4365 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4375 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4378 static int /* O - Bytes written */
4379 http_write_ssl(http_t
*http
, /* I - Connection to server */
4380 const char *buf
, /* I - Buffer holding data */
4381 int len
) /* I - Length of buffer */
4383 ssize_t result
; /* Return value */
4386 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4388 # if defined(HAVE_LIBSSL)
4389 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4391 # elif defined(HAVE_GNUTLS)
4392 result
= gnutls_record_send(http
->tls
, buf
, len
);
4394 if (result
< 0 && !errno
)
4397 * Convert GNU TLS error to errno value...
4402 case GNUTLS_E_INTERRUPTED
:
4406 case GNUTLS_E_AGAIN
:
4418 # elif defined(HAVE_CDSASSL)
4419 OSStatus error
; /* Error info */
4420 size_t processed
; /* Number of bytes processed */
4423 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4428 result
= (int)processed
;
4430 case errSSLClosedGraceful
:
4433 case errSSLWouldBlock
:
4435 result
= (int)processed
;
4447 # elif defined(HAVE_SSPISSL)
4448 return _sspiWrite((_sspi_struct_t
*) http
->tls
, (void*) buf
, len
);
4449 # endif /* HAVE_LIBSSL */
4451 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4453 return ((int)result
);
4455 #endif /* HAVE_SSL */
4459 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".