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 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
);
163 static int http_set_credentials(http_t
*http
);
164 # endif /* HAVE_CDSASSL */
165 static int http_setup_ssl(http_t
*http
);
166 static void http_shutdown_ssl(http_t
*http
);
167 static int http_upgrade(http_t
*http
);
168 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
171 # ifdef HAVE_PTHREAD_H
172 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
173 # endif /* HAVE_PTHREAD_H */
175 # elif defined(HAVE_LIBSSL)
176 static _cups_mutex_t
*http_locks
; /* OpenSSL lock mutexes */
178 static void http_locking_cb(int mode
, int type
, const char *file
,
180 static unsigned long http_threadid_cb(void);
181 # endif /* HAVE_GNUTLS */
182 #endif /* HAVE_SSL */
189 static const char * const http_fields
[] =
206 "If-Unmodified-since",
220 static const char * const http_states
[] =
240 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
242 * BIO methods for OpenSSL...
245 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
246 static int http_bio_read(BIO
*h
, char *buf
, int size
);
247 static int http_bio_puts(BIO
*h
, const char *str
);
248 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
249 static int http_bio_new(BIO
*h
);
250 static int http_bio_free(BIO
*data
);
252 static BIO_METHOD http_bio_methods
=
259 NULL
, /* http_bio_gets, */
265 #endif /* HAVE_SSL && HAVE_LIBSSL */
269 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
271 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
276 int /* O - 0 on success, -1 on error */
278 cups_array_t
*credentials
, /* I - Credentials array */
279 const void *data
, /* I - PEM-encoded X.509 data */
280 size_t datalen
) /* I - Length of data */
282 http_credential_t
*credential
; /* Credential data */
285 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
287 credential
->datalen
= datalen
;
289 if ((credential
->data
= malloc(datalen
)) != NULL
)
291 memcpy(credential
->data
, data
, datalen
);
292 cupsArrayAdd(credentials
, credential
);
303 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
305 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
308 BIO_METHOD
* /* O - BIO methods for OpenSSL */
309 _httpBIOMethods(void)
311 return (&http_bio_methods
);
313 #endif /* HAVE_SSL && HAVE_LIBSSL */
317 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
321 httpBlocking(http_t
*http
, /* I - Connection to server */
322 int b
) /* I - 1 = blocking, 0 = non-blocking */
330 * 'httpCheck()' - Check to see if there is a pending response from the server.
333 int /* O - 0 = no data, 1 = data available */
334 httpCheck(http_t
*http
) /* I - Connection to server */
336 return (httpWait(http
, 0));
341 * 'httpClearCookie()' - Clear the cookie value(s).
343 * @since CUPS 1.1.19/Mac OS X 10.3@
347 httpClearCookie(http_t
*http
) /* I - Connection to server */
361 * 'httpClearFields()' - Clear HTTP request fields.
365 httpClearFields(http_t
*http
) /* I - Connection to server */
369 memset(http
->fields
, 0, sizeof(http
->fields
));
370 if (http
->hostname
[0] == '/')
371 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
373 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
375 if (http
->field_authorization
)
377 free(http
->field_authorization
);
378 http
->field_authorization
= NULL
;
381 http
->expect
= (http_status_t
)0;
387 * 'httpClose()' - Close an HTTP connection.
391 httpClose(http_t
*http
) /* I - Connection to server */
394 OM_uint32 minor_status
; /* Minor status code */
395 #endif /* HAVE_GSSAPI */
398 DEBUG_printf(("httpClose(http=%p)", http
));
401 * Range check input...
408 * Close any open connection...
411 _httpDisconnect(http
);
414 * Free memory used...
417 httpAddrFreeList(http
->addrlist
);
423 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
424 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
426 if (http
->gssname
!= GSS_C_NO_NAME
)
427 gss_release_name(&minor_status
, &http
->gssname
);
428 #endif /* HAVE_GSSAPI */
430 #ifdef HAVE_AUTHORIZATION_H
432 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
433 #endif /* HAVE_AUTHORIZATION_H */
435 httpClearFields(http
);
437 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
438 free(http
->authstring
);
445 * 'httpConnect()' - Connect to a HTTP server.
447 * This function is deprecated - use @link httpConnectEncrypt@ instead.
452 http_t
* /* O - New HTTP connection */
453 httpConnect(const char *host
, /* I - Host to connect to */
454 int port
) /* I - Port number */
456 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
461 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
464 http_t
* /* O - New HTTP connection */
466 const char *host
, /* I - Host to connect to */
467 int port
, /* I - Port number */
468 http_encryption_t encryption
) /* I - Type of encryption to use */
470 http_t
*http
; /* New HTTP connection */
473 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
474 host
, port
, encryption
));
477 * Create the HTTP structure...
480 if ((http
= _httpCreate(host
, port
, encryption
, AF_UNSPEC
)) == NULL
)
484 * Connect to the remote system...
487 if (!httpReconnect(http
))
491 * Could not connect to any known address - bail out!
494 httpAddrFreeList(http
->addrlist
);
503 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
509 int /* O - Status of call (0 = success) */
511 http_t
*http
, /* I - Connection to server */
512 cups_array_t
**credentials
) /* O - Array of credentials */
515 # elif defined(HAVE_GNUTLS)
516 # elif defined(HAVE_CDSASSL)
517 OSStatus error
; /* Error code */
518 CFIndex count
; /* Number of credentials */
519 CFArrayRef peerCerts
; /* Peer certificates */
520 SecCertificateRef secCert
; /* Certificate reference */
521 CFDataRef data
; /* Certificate data */
522 int i
; /* Looping var */
523 # elif defined(HAVE_SSPISSL)
524 # endif /* HAVE_LIBSSL */
530 if (!http
|| !http
->tls
|| !credentials
)
536 # elif defined(HAVE_GNUTLS)
539 # elif defined(HAVE_CDSASSL)
540 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
542 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
544 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
546 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
547 if ((data
= SecCertificateCopyData(secCert
)))
549 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
550 CFDataGetLength(data
));
556 CFRelease(peerCerts
);
561 # elif defined(HAVE_SSPISSL)
563 # endif /* HAVE_LIBSSL */
568 * '_httpConvertCredentials()' - Convert credentials to the internal format.
571 http_tls_credentials_t
/* O - Internal credentials */
572 _httpConvertCredentials(
573 cups_array_t
*credentials
) /* I - Array of credentials */
581 # elif defined(HAVE_GNUTLS)
584 # elif defined(HAVE_CDSASSL)
585 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
586 SecCertificateRef secCert
; /* Certificate reference */
587 CFDataRef data
; /* Credential data reference */
588 http_credential_t
*credential
; /* Credential data */
591 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
592 cupsArrayCount(credentials
),
593 &kCFTypeArrayCallBacks
)) == NULL
)
596 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
598 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
600 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
601 credential
->datalen
)))
603 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
606 CFArrayAppendValue(peerCerts
, secCert
);
616 # elif defined(HAVE_SSPISSL)
621 # endif /* HAVE_LIBSSL */
626 * '_httpCreate()' - Create an unconnected HTTP connection.
629 http_t
* /* O - HTTP connection */
631 const char *host
, /* I - Hostname */
632 int port
, /* I - Port number */
633 http_encryption_t encryption
, /* I - Encryption to use */
634 int family
) /* I - Address family or AF_UNSPEC */
636 http_t
*http
; /* New HTTP connection */
637 http_addrlist_t
*addrlist
; /* Host address data */
638 char service
[255]; /* Service name */
641 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
642 host
, port
, encryption
));
653 sprintf(service
, "%d", port
);
655 if ((addrlist
= httpAddrGetList(host
, family
, service
)) == NULL
)
659 * Allocate memory for the structure...
662 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
664 httpAddrFreeList(addrlist
);
669 * Initialize the HTTP data...
672 http
->activity
= time(NULL
);
673 http
->addrlist
= addrlist
;
677 http
->gssctx
= GSS_C_NO_CONTEXT
;
678 http
->gssname
= GSS_C_NO_NAME
;
679 #endif /* HAVE_GSSAPI */
680 http
->version
= HTTP_1_1
;
682 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
684 if (port
== 443) /* Always use encryption for https */
685 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
687 http
->encryption
= encryption
;
690 * Return the new structure...
698 * 'httpDelete()' - Send a DELETE request to the server.
701 int /* O - Status of call (0 = success) */
702 httpDelete(http_t
*http
, /* I - Connection to server */
703 const char *uri
) /* I - URI to delete */
705 return (http_send(http
, HTTP_DELETE
, uri
));
710 * '_httpDisconnect()' - Disconnect a HTTP connection.
714 _httpDisconnect(http_t
*http
) /* I - Connection to server */
718 http_shutdown_ssl(http
);
719 #endif /* HAVE_SSL */
722 closesocket(http
->fd
);
732 * 'httpEncryption()' - Set the required encryption on the link.
735 int /* O - -1 on error, 0 on success */
736 httpEncryption(http_t
*http
, /* I - Connection to server */
737 http_encryption_t e
) /* I - New encryption preference */
739 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
745 http
->encryption
= e
;
747 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
748 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
749 return (httpReconnect(http
));
750 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
751 return (http_upgrade(http
));
755 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
759 #endif /* HAVE_SSL */
764 * 'httpError()' - Get the last error on a connection.
767 int /* O - Error code (errno) value */
768 httpError(http_t
*http
) /* I - Connection to server */
771 return (http
->error
);
778 * 'httpFlush()' - Flush data from a HTTP connection.
782 httpFlush(http_t
*http
) /* I - Connection to server */
784 char buffer
[8192]; /* Junk buffer */
785 int blocking
; /* To block or not to block */
786 http_state_t oldstate
; /* Old state */
789 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
790 http_states
[http
->state
]));
793 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
796 blocking
= http
->blocking
;
800 * Read any data we can...
803 oldstate
= http
->state
;
804 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
807 * Restore blocking and reset the connection if we didn't get all of
808 * the remaining data...
811 http
->blocking
= blocking
;
813 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
816 * Didn't get the data back, so close the current connection.
819 http
->state
= HTTP_WAITING
;
823 http_shutdown_ssl(http
);
824 #endif /* HAVE_SSL */
827 closesocket(http
->fd
);
838 * 'httpFlushWrite()' - Flush data in write buffer.
840 * @since CUPS 1.2/Mac OS X 10.5@
843 int /* O - Bytes written or -1 on error */
844 httpFlushWrite(http_t
*http
) /* I - Connection to server */
846 int bytes
; /* Bytes written */
849 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
851 if (!http
|| !http
->wused
)
853 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
854 "1httpFlushWrite: No connection.");
858 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
859 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
861 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
865 DEBUG_printf(("1httpFlushWrite: Returning %d.", bytes
));
872 * '_httpFreeCredentials()' - Free internal credentials.
876 _httpFreeCredentials(
877 http_tls_credentials_t credentials
) /* I - Internal credentials */
885 #elif defined(HAVE_GNUTLS)
888 #elif defined(HAVE_CDSASSL)
889 CFRelease(credentials
);
891 #elif defined(HAVE_SSPISSL)
894 #endif /* HAVE_LIBSSL */
899 * 'httpFreeCredentials()' - Free an array of credentials.
904 cups_array_t
*credentials
) /* I - Array of credentials */
906 http_credential_t
*credential
; /* Credential */
909 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
911 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
913 cupsArrayRemove(credentials
, credential
);
914 free((void *)credential
->data
);
918 cupsArrayDelete(credentials
);
923 * 'httpGet()' - Send a GET request to the server.
926 int /* O - Status of call (0 = success) */
927 httpGet(http_t
*http
, /* I - Connection to server */
928 const char *uri
) /* I - URI to get */
930 return (http_send(http
, HTTP_GET
, uri
));
935 * 'httpGetAuthString()' - Get the current authorization string.
937 * The authorization string is set by cupsDoAuthentication() and
938 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
939 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
942 * @since CUPS 1.3/Mac OS X 10.5@
945 char * /* O - Authorization string */
946 httpGetAuthString(http_t
*http
) /* I - Connection to server */
949 return (http
->authstring
);
956 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
958 * @since CUPS 1.2/Mac OS X 10.5@
961 int /* O - 1 if blocking, 0 if non-blocking */
962 httpGetBlocking(http_t
*http
) /* I - Connection to server */
964 return (http
? http
->blocking
: 0);
969 * 'httpGetCookie()' - Get any cookie data from the response.
971 * @since CUPS 1.1.19/Mac OS X 10.3@
974 const char * /* O - Cookie data or NULL */
975 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
977 return (http
? http
->cookie
: NULL
);
982 * 'httpGetFd()' - Get the file descriptor associated with a connection.
984 * @since CUPS 1.2/Mac OS X 10.5@
987 int /* O - File descriptor or -1 if none */
988 httpGetFd(http_t
*http
) /* I - Connection to server */
990 return (http
? http
->fd
: -1);
995 * 'httpGetField()' - Get a field value from a request/response.
998 const char * /* O - Field value */
999 httpGetField(http_t
*http
, /* I - Connection to server */
1000 http_field_t field
) /* I - Field to get */
1002 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1004 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
1005 http
->field_authorization
)
1008 * Special case for WWW-Authenticate: as its contents can be
1009 * longer than HTTP_MAX_VALUE...
1012 return (http
->field_authorization
);
1015 return (http
->fields
[field
]);
1020 * 'httpGetLength()' - Get the amount of data remaining from the
1021 * content-length or transfer-encoding fields.
1023 * This function is deprecated and will not return lengths larger than
1024 * 2^31 - 1; use httpGetLength2() instead.
1029 int /* O - Content length */
1030 httpGetLength(http_t
*http
) /* I - Connection to server */
1033 * Get the read content length and return the 32-bit value.
1038 httpGetLength2(http
);
1040 return (http
->_data_remaining
);
1048 * 'httpGetLength2()' - Get the amount of data remaining from the
1049 * content-length or transfer-encoding fields.
1051 * This function returns the complete content length, even for
1052 * content larger than 2^31 - 1.
1054 * @since CUPS 1.2/Mac OS X 10.5@
1057 off_t
/* O - Content length */
1058 httpGetLength2(http_t
*http
) /* I - Connection to server */
1060 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1061 http_states
[http
->state
]));
1066 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1068 DEBUG_puts("4httpGetLength2: chunked request!");
1070 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1071 http
->data_remaining
= 0;
1075 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1078 * The following is a hack for HTTP servers that don't send a
1079 * content-length or transfer-encoding field...
1081 * If there is no content-length then the connection must close
1082 * after the transfer is complete...
1085 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1088 * Default content length is 0 for errors and 2^31-1 for other
1089 * successful requests...
1092 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
1093 http
->data_remaining
= 0;
1095 http
->data_remaining
= 2147483647;
1098 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1101 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1102 CUPS_LLCAST http
->data_remaining
));
1105 if (http
->data_remaining
<= INT_MAX
)
1106 http
->_data_remaining
= (int)http
->data_remaining
;
1108 http
->_data_remaining
= INT_MAX
;
1110 return (http
->data_remaining
);
1115 * 'httpGetStatus()' - Get the status of the last HTTP request.
1117 * @since CUPS 1.2/Mac OS X 10.5@
1120 http_status_t
/* O - HTTP status */
1121 httpGetStatus(http_t
*http
) /* I - Connection to server */
1123 return (http
? http
->status
: HTTP_ERROR
);
1128 * 'httpGetSubField()' - Get a sub-field value.
1133 char * /* O - Value or NULL */
1134 httpGetSubField(http_t
*http
, /* I - Connection to server */
1135 http_field_t field
, /* I - Field index */
1136 const char *name
, /* I - Name of sub-field */
1137 char *value
) /* O - Value string */
1139 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1144 * 'httpGetSubField2()' - Get a sub-field value.
1146 * @since CUPS 1.2/Mac OS X 10.5@
1149 char * /* O - Value or NULL */
1150 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1151 http_field_t field
, /* I - Field index */
1152 const char *name
, /* I - Name of sub-field */
1153 char *value
, /* O - Value string */
1154 int valuelen
) /* I - Size of value buffer */
1156 const char *fptr
; /* Pointer into field */
1157 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1158 *ptr
, /* Pointer into string buffer */
1159 *end
; /* End of value buffer */
1161 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1162 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1164 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1165 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1168 end
= value
+ valuelen
- 1;
1170 for (fptr
= http
->fields
[field
]; *fptr
;)
1173 * Skip leading whitespace...
1176 while (_cups_isspace(*fptr
))
1186 * Get the sub-field name...
1190 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1191 ptr
< (temp
+ sizeof(temp
) - 1);
1196 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1199 * Skip trailing chars up to the '='...
1202 while (_cups_isspace(*fptr
))
1212 * Skip = and leading whitespace...
1217 while (_cups_isspace(*fptr
))
1223 * Read quoted string...
1226 for (ptr
= value
, fptr
++;
1227 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1232 while (*fptr
&& *fptr
!= '\"')
1241 * Read unquoted string...
1245 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1250 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1254 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1257 * See if this is the one...
1260 if (!strcmp(name
, temp
))
1262 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1269 DEBUG_puts("3httpGetSubField2: Returning NULL");
1276 * 'httpGets()' - Get a line of text from a HTTP connection.
1279 char * /* O - Line or NULL */
1280 httpGets(char *line
, /* I - Line to read into */
1281 int length
, /* I - Max length of buffer */
1282 http_t
*http
) /* I - Connection to server */
1284 char *lineptr
, /* Pointer into line */
1285 *lineend
, /* End of line */
1286 *bufptr
, /* Pointer into input buffer */
1287 *bufend
; /* Pointer to end of buffer */
1288 int bytes
, /* Number of bytes read */
1289 eol
; /* End-of-line? */
1292 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1294 if (http
== NULL
|| line
== NULL
)
1298 * Read a line from the buffer...
1303 lineend
= line
+ length
- 1;
1306 while (lineptr
< lineend
)
1309 * Pre-load the buffer as needed...
1318 while (http
->used
== 0)
1321 * No newline; see if there is more data to be read...
1324 if (!http
->blocking
&& !_httpWait(http
, 10000, 1))
1326 DEBUG_puts("3httpGets: Timed out!");
1328 http
->error
= WSAETIMEDOUT
;
1330 http
->error
= ETIMEDOUT
;
1337 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1338 HTTP_MAX_BUFFER
- http
->used
);
1340 #endif /* HAVE_SSL */
1341 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1342 HTTP_MAX_BUFFER
- http
->used
, 0);
1344 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1349 * Nope, can't get a line this time...
1353 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1355 if (WSAGetLastError() == WSAEINTR
)
1357 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1359 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1362 http
->error
= WSAGetLastError();
1364 else if (WSAGetLastError() != http
->error
)
1366 http
->error
= WSAGetLastError();
1371 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1375 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1377 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1379 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1382 http
->error
= errno
;
1384 else if (errno
!= http
->error
)
1386 http
->error
= errno
;
1393 else if (bytes
== 0)
1395 http
->error
= EPIPE
;
1401 * Yup, update the amount used...
1404 http
->used
+= bytes
;
1408 * Now copy as much of the current line as possible...
1411 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1412 lineptr
< lineend
&& bufptr
< bufend
;)
1414 if (*bufptr
== 0x0a)
1420 else if (*bufptr
== 0x0d)
1423 *lineptr
++ = *bufptr
++;
1426 http
->used
-= (int)(bufptr
- http
->buffer
);
1428 memmove(http
->buffer
, bufptr
, http
->used
);
1436 http
->activity
= time(NULL
);
1440 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1446 DEBUG_puts("3httpGets: No new line available!");
1453 * 'httpHead()' - Send a HEAD request to the server.
1456 int /* O - Status of call (0 = success) */
1457 httpHead(http_t
*http
, /* I - Connection to server */
1458 const char *uri
) /* I - URI for head */
1460 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1461 return (http_send(http
, HTTP_HEAD
, uri
));
1466 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1467 * default HTTP proxy (if any).
1471 httpInitialize(void)
1473 static int initialized
= 0; /* Have we been called before? */
1475 WSADATA winsockdata
; /* WinSock data */
1478 int i
; /* Looping var */
1479 unsigned char data
[1024]; /* Seed data */
1480 #endif /* HAVE_LIBSSL */
1486 _cupsGlobalUnlock();
1491 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1493 #elif !defined(SO_NOSIGPIPE)
1495 * Ignore SIGPIPE signals...
1499 sigset(SIGPIPE
, SIG_IGN
);
1501 # elif defined(HAVE_SIGACTION)
1502 struct sigaction action
; /* POSIX sigaction data */
1505 memset(&action
, 0, sizeof(action
));
1506 action
.sa_handler
= SIG_IGN
;
1507 sigaction(SIGPIPE
, &action
, NULL
);
1510 signal(SIGPIPE
, SIG_IGN
);
1511 # endif /* !SO_NOSIGPIPE */
1516 * Make sure we handle threading properly...
1519 # ifdef HAVE_PTHREAD_H
1520 gcry_control(GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
1521 # endif /* HAVE_PTHREAD_H */
1524 * Initialize GNU TLS...
1527 gnutls_global_init();
1529 #elif defined(HAVE_LIBSSL)
1531 * Initialize OpenSSL...
1534 SSL_load_error_strings();
1538 * Set the threading callbacks...
1541 http_locks
= calloc(CRYPTO_num_locks(), sizeof(_cups_mutex_t
));
1542 # ifdef HAVE_PTHREAD_H
1543 for (i
= 0; i
< CRYPTO_num_locks(); i
++)
1544 pthread_mutex_init(http_locks
+ i
, NULL
);
1545 # endif /* HAVE_PTHREAD_H */
1547 CRYPTO_set_id_callback(http_threadid_cb
);
1548 CRYPTO_set_locking_callback(http_locking_cb
);
1551 * Using the current time is a dubious random seed, but on some systems
1552 * it is the best we can do (on others, this seed isn't even used...)
1555 CUPS_SRAND(time(NULL
));
1557 for (i
= 0; i
< sizeof(data
); i
++)
1558 data
[i
] = CUPS_RAND();
1560 RAND_seed(data
, sizeof(data
));
1561 #endif /* HAVE_GNUTLS */
1564 _cupsGlobalUnlock();
1569 * 'httpOptions()' - Send an OPTIONS request to the server.
1572 int /* O - Status of call (0 = success) */
1573 httpOptions(http_t
*http
, /* I - Connection to server */
1574 const char *uri
) /* I - URI for options */
1576 return (http_send(http
, HTTP_OPTIONS
, uri
));
1581 * '_httpPeek()' - Peek at data from a HTTP connection.
1583 * This function copies available data from the given HTTP connection, reading
1584 * a buffer as needed. The data is still available for reading using
1585 * @link httpRead@ or @link httpRead2@.
1587 * For non-blocking connections the usual timeouts apply.
1590 ssize_t
/* O - Number of bytes copied */
1591 _httpPeek(http_t
*http
, /* I - Connection to server */
1592 char *buffer
, /* I - Buffer for data */
1593 size_t length
) /* I - Maximum number of bytes */
1595 ssize_t bytes
; /* Bytes read */
1596 char len
[32]; /* Length string */
1599 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1600 http
, buffer
, CUPS_LLCAST length
));
1602 if (http
== NULL
|| buffer
== NULL
)
1605 http
->activity
= time(NULL
);
1611 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1612 http
->data_remaining
<= 0)
1614 DEBUG_puts("2_httpPeek: Getting chunk length...");
1616 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1618 DEBUG_puts("1_httpPeek: Could not get length!");
1622 http
->data_remaining
= strtoll(len
, NULL
, 16);
1623 if (http
->data_remaining
< 0)
1625 DEBUG_puts("1_httpPeek: Negative chunk length!");
1630 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1631 CUPS_LLCAST http
->data_remaining
));
1633 if (http
->data_remaining
<= 0)
1636 * A zero-length chunk ends a transfer; unless we are reading POST
1640 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1641 httpGets(len
, sizeof(len
), http
);
1643 if (http
->state
== HTTP_POST_RECV
)
1646 http
->state
= HTTP_WAITING
;
1649 * Prevent future reads for this request...
1652 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1656 else if (length
> (size_t)http
->data_remaining
)
1657 length
= (size_t)http
->data_remaining
;
1659 if (http
->used
== 0)
1662 * Buffer small reads for better performance...
1665 if (!http
->blocking
&& !httpWait(http
, 10000))
1668 if (http
->data_remaining
> sizeof(http
->buffer
))
1669 bytes
= sizeof(http
->buffer
);
1671 bytes
= http
->data_remaining
;
1675 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1677 #endif /* HAVE_SSL */
1679 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1682 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1684 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1693 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1695 http
->error
= WSAGetLastError();
1699 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1701 http
->error
= errno
;
1708 http
->error
= EPIPE
;
1715 if (length
> (size_t)http
->used
)
1716 length
= (size_t)http
->used
;
1718 bytes
= (ssize_t
)length
;
1720 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1723 memcpy(buffer
, http
->buffer
, length
);
1731 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1734 http
->error
= WSAGetLastError();
1736 if (errno
== EINTR
|| errno
== EAGAIN
)
1739 http
->error
= errno
;
1742 else if (bytes
== 0)
1744 http
->error
= EPIPE
;
1749 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1757 * 'httpPost()' - Send a POST request to the server.
1760 int /* O - Status of call (0 = success) */
1761 httpPost(http_t
*http
, /* I - Connection to server */
1762 const char *uri
) /* I - URI for post */
1764 return (http_send(http
, HTTP_POST
, uri
));
1769 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1774 int /* O - Number of bytes written */
1775 httpPrintf(http_t
*http
, /* I - Connection to server */
1776 const char *format
, /* I - printf-style format string */
1777 ...) /* I - Additional args as needed */
1779 int bytes
; /* Number of bytes to write */
1780 char buf
[16384]; /* Buffer for formatted string */
1781 va_list ap
; /* Variable argument pointer */
1784 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1786 va_start(ap
, format
);
1787 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1790 DEBUG_printf(("3httpPrintf: %s", buf
));
1792 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1793 return (httpWrite2(http
, buf
, bytes
));
1798 DEBUG_puts("4httpPrintf: flushing existing data...");
1800 if (httpFlushWrite(http
) < 0)
1804 return (http_write(http
, buf
, bytes
));
1810 * 'httpPut()' - Send a PUT request to the server.
1813 int /* O - Status of call (0 = success) */
1814 httpPut(http_t
*http
, /* I - Connection to server */
1815 const char *uri
) /* I - URI to put */
1817 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1818 return (http_send(http
, HTTP_PUT
, uri
));
1823 * 'httpRead()' - Read data from a HTTP connection.
1825 * This function is deprecated. Use the httpRead2() function which can
1826 * read more than 2GB of data.
1831 int /* O - Number of bytes read */
1832 httpRead(http_t
*http
, /* I - Connection to server */
1833 char *buffer
, /* I - Buffer for data */
1834 int length
) /* I - Maximum number of bytes */
1836 return ((int)httpRead2(http
, buffer
, length
));
1841 * 'httpRead2()' - Read data from a HTTP connection.
1843 * @since CUPS 1.2/Mac OS X 10.5@
1846 ssize_t
/* O - Number of bytes read */
1847 httpRead2(http_t
*http
, /* I - Connection to server */
1848 char *buffer
, /* I - Buffer for data */
1849 size_t length
) /* I - Maximum number of bytes */
1851 ssize_t bytes
; /* Bytes read */
1852 char len
[32]; /* Length string */
1855 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1856 http
, buffer
, CUPS_LLCAST length
));
1858 if (http
== NULL
|| buffer
== NULL
)
1861 http
->activity
= time(NULL
);
1867 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1868 http
->data_remaining
<= 0)
1870 DEBUG_puts("2httpRead2: Getting chunk length...");
1872 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1874 DEBUG_puts("1httpRead2: Could not get length!");
1878 http
->data_remaining
= strtoll(len
, NULL
, 16);
1879 if (http
->data_remaining
< 0)
1881 DEBUG_puts("1httpRead2: Negative chunk length!");
1886 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1887 CUPS_LLCAST http
->data_remaining
));
1889 if (http
->data_remaining
<= 0)
1892 * A zero-length chunk ends a transfer; unless we are reading POST
1896 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1897 httpGets(len
, sizeof(len
), http
);
1899 if (http
->state
== HTTP_POST_RECV
)
1902 http
->state
= HTTP_WAITING
;
1905 * Prevent future reads for this request...
1908 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1912 else if (length
> (size_t)http
->data_remaining
)
1913 length
= (size_t)http
->data_remaining
;
1915 if (http
->used
== 0 && length
<= 256)
1918 * Buffer small reads for better performance...
1921 if (!http
->blocking
&& !httpWait(http
, 10000))
1924 if (http
->data_remaining
> sizeof(http
->buffer
))
1925 bytes
= sizeof(http
->buffer
);
1927 bytes
= http
->data_remaining
;
1931 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1933 #endif /* HAVE_SSL */
1935 DEBUG_printf(("2httpRead2: reading %d bytes from socket into buffer...",
1938 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1940 DEBUG_printf(("2httpRead2: read %d bytes from socket into buffer...",
1949 if (WSAGetLastError() != WSAEINTR
)
1951 http
->error
= WSAGetLastError();
1954 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1956 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1958 http
->error
= WSAEWOULDBLOCK
;
1963 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1965 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1967 http
->error
= errno
;
1970 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1972 http
->error
= errno
;
1976 else if (errno
!= EINTR
)
1978 http
->error
= errno
;
1985 http
->error
= EPIPE
;
1992 if (length
> (size_t)http
->used
)
1993 length
= (size_t)http
->used
;
1995 bytes
= (ssize_t
)length
;
1997 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2000 memcpy(buffer
, http
->buffer
, length
);
2001 http
->used
-= (int)length
;
2004 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2009 if (!http
->blocking
&& !httpWait(http
, 10000))
2012 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
2014 #endif /* HAVE_SSL */
2017 if (!http
->blocking
&& !httpWait(http
, 10000))
2020 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2021 CUPS_LLCAST length
));
2024 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2026 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2028 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2031 else if (WSAGetLastError() != WSAEINTR
)
2035 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2037 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2039 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2041 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2044 else if (errno
!= EINTR
)
2049 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2050 CUPS_LLCAST bytes
));
2055 http
->data_remaining
-= bytes
;
2057 if (http
->data_remaining
<= INT_MAX
)
2058 http
->_data_remaining
= (int)http
->data_remaining
;
2060 http
->_data_remaining
= INT_MAX
;
2065 if (WSAGetLastError() == WSAEINTR
)
2068 http
->error
= WSAGetLastError();
2070 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2073 http
->error
= errno
;
2078 http
->error
= EPIPE
;
2082 if (http
->data_remaining
== 0)
2084 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2085 httpGets(len
, sizeof(len
), http
);
2087 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2089 if (http
->state
== HTTP_POST_RECV
)
2092 http
->state
= HTTP_WAITING
;
2097 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2104 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2106 * '_httpReadCDSA()' - Read function for the CDSA library.
2109 OSStatus
/* O - -1 on error, 0 on success */
2111 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2112 void *data
, /* I - Data buffer */
2113 size_t *dataLength
) /* IO - Number of bytes */
2115 OSStatus result
; /* Return value */
2116 ssize_t bytes
; /* Number of bytes read */
2117 http_t
*http
; /* HTTP connection */
2120 http
= (http_t
*)connection
;
2122 if (!http
->blocking
)
2125 * Make sure we have data before we read...
2128 if (!_httpWait(http
, 10000, 0))
2130 http
->error
= ETIMEDOUT
;
2137 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2139 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2141 if (bytes
== *dataLength
)
2147 *dataLength
= bytes
;
2148 result
= errSSLWouldBlock
;
2155 result
= errSSLClosedGraceful
;
2156 else if (errno
== EAGAIN
)
2157 result
= errSSLWouldBlock
;
2159 result
= errSSLClosedAbort
;
2164 #endif /* HAVE_SSL && HAVE_CDSASSL */
2167 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2169 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2172 ssize_t
/* O - Number of bytes read or -1 on error */
2174 gnutls_transport_ptr ptr
, /* I - Connection to server */
2175 void *data
, /* I - Buffer */
2176 size_t length
) /* I - Number of bytes to read */
2178 http_t
*http
; /* HTTP connection */
2181 http
= (http_t
*)ptr
;
2183 if (!http
->blocking
)
2186 * Make sure we have data before we read...
2189 if (!_httpWait(http
, 10000, 0))
2191 http
->error
= ETIMEDOUT
;
2196 return (recv(http
->fd
, data
, length
, 0));
2198 #endif /* HAVE_SSL && HAVE_GNUTLS */
2202 * 'httpReconnect()' - Reconnect to a HTTP server.
2205 int /* O - 0 on success, non-zero on failure */
2206 httpReconnect(http_t
*http
) /* I - Connection to server */
2208 http_addrlist_t
*addr
; /* Connected address */
2210 http_addrlist_t
*current
; /* Current address */
2211 char temp
[256]; /* Temporary address string */
2215 DEBUG_printf(("httpReconnect(http=%p)", http
));
2223 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2224 http_shutdown_ssl(http
);
2226 #endif /* HAVE_SSL */
2229 * Close any previously open socket...
2234 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2237 closesocket(http
->fd
);
2246 * Connect to the server...
2250 for (current
= http
->addrlist
; current
; current
= current
->next
)
2251 DEBUG_printf(("2httpReconnect: Address %s:%d",
2252 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2253 _httpAddrPort(&(current
->addr
))));
2256 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
2259 * Unable to connect...
2263 http
->error
= WSAGetLastError();
2265 http
->error
= errno
;
2267 http
->status
= HTTP_ERROR
;
2269 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2270 strerror(http
->error
)));
2275 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2277 if (http
->timeout_value
.tv_sec
> 0)
2279 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, &(http
->timeout_value
),
2280 sizeof(http
->timeout_value
));
2281 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, &(http
->timeout_value
),
2282 sizeof(http
->timeout_value
));
2285 http
->hostaddr
= &(addr
->addr
);
2287 http
->status
= HTTP_CONTINUE
;
2290 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2293 * Always do encryption via SSL.
2296 if (http_setup_ssl(http
) != 0)
2299 closesocket(http
->fd
);
2307 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2308 return (http_upgrade(http
));
2309 #endif /* HAVE_SSL */
2311 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2312 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2313 _httpAddrPort(http
->hostaddr
)));
2320 * 'httpSetAuthString()' - Set the current authorization string.
2322 * This function just stores a copy of the current authorization string in
2323 * the HTTP connection object. You must still call httpSetField() to set
2324 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2325 * httpHead(), httpOptions(), httpPost, or httpPut().
2327 * @since CUPS 1.3/Mac OS X 10.5@
2331 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2332 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2333 const char *data
) /* I - Auth data (NULL for none) */
2336 * Range check input...
2342 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2343 free(http
->authstring
);
2345 http
->authstring
= http
->_authstring
;
2350 * Set the current authorization string...
2353 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2356 if (len
> (int)sizeof(http
->_authstring
))
2358 if ((temp
= malloc(len
)) == NULL
)
2359 len
= sizeof(http
->_authstring
);
2361 http
->authstring
= temp
;
2365 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2367 strlcpy(http
->authstring
, scheme
, len
);
2372 * Clear the current authorization string...
2375 http
->_authstring
[0] = '\0';
2381 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2387 int /* O - Status of call (0 = success) */
2388 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2389 cups_array_t
*credentials
) /* I - Array of credentials */
2391 if (!http
|| cupsArrayCount(credentials
) < 1)
2394 _httpFreeCredentials(http
->tls_credentials
);
2396 http
->tls_credentials
= _httpConvertCredentials(credentials
);
2398 return (http
->tls_credentials
? 0 : -1);
2403 * 'httpSetCookie()' - Set the cookie value(s).
2405 * @since CUPS 1.1.19/Mac OS X 10.3@
2409 httpSetCookie(http_t
*http
, /* I - Connection */
2410 const char *cookie
) /* I - Cookie string */
2419 http
->cookie
= strdup(cookie
);
2421 http
->cookie
= NULL
;
2426 * 'httpSetExpect()' - Set the Expect: header in a request.
2428 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2430 * @since CUPS 1.2/Mac OS X 10.5@
2434 httpSetExpect(http_t
*http
, /* I - Connection to server */
2435 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2438 http
->expect
= expect
;
2443 * 'httpSetField()' - Set the value of an HTTP header.
2447 httpSetField(http_t
*http
, /* I - Connection to server */
2448 http_field_t field
, /* I - Field index */
2449 const char *value
) /* I - Value */
2452 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2453 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2457 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2459 if (field
== HTTP_FIELD_AUTHORIZATION
)
2462 * Special case for Authorization: as its contents can be
2463 * longer than HTTP_MAX_VALUE
2466 if (http
->field_authorization
)
2467 free(http
->field_authorization
);
2469 http
->field_authorization
= strdup(value
);
2471 else if (field
== HTTP_FIELD_HOST
)
2474 * Special-case for Host: as we don't want a trailing "." on the hostname and
2475 * need to bracket IPv6 numeric addresses.
2478 char *ptr
= strchr(value
, ':');
2480 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2483 * Bracket IPv6 numeric addresses...
2485 * This is slightly inefficient (basically copying twice), but is an edge
2486 * case and not worth optimizing...
2489 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2490 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2495 * Check for a trailing dot on the hostname...
2498 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2502 ptr
+= strlen(ptr
) - 1;
2513 * 'httpSetLength()' - Set the content-length and content-encoding.
2515 * @since CUPS 1.2/Mac OS X 10.5@
2519 httpSetLength(http_t
*http
, /* I - Connection to server */
2520 size_t length
) /* I - Length (0 for chunked) */
2527 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2528 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2532 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2533 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2534 CUPS_LLFMT
, CUPS_LLCAST length
);
2540 * '_httpSetTimeout()' - Set read/write timeouts and an optional callback.
2542 * The optional timeout callback receives both the HTTP connection and a user
2543 * data pointer and must return 1 to continue or 0 to error out.
2548 http_t
*http
, /* I - Connection to server */
2549 double timeout
, /* I - Number of seconds for timeout,
2550 must be greater than 0 */
2551 _http_timeout_cb_t cb
, /* I - Callback function or NULL */
2552 void *user_data
) /* I - User data pointer */
2554 if (!http
|| timeout
<= 0.0)
2557 http
->timeout_cb
= cb
;
2558 http
->timeout_data
= user_data
;
2559 http
->timeout_value
.tv_sec
= (int)timeout
;
2560 http
->timeout_value
.tv_usec
= (int)(timeout
* 1000000) % 1000000;
2564 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, &(http
->timeout_value
),
2565 sizeof(http
->timeout_value
));
2566 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, &(http
->timeout_value
),
2567 sizeof(http
->timeout_value
));
2573 * 'httpTrace()' - Send an TRACE request to the server.
2576 int /* O - Status of call (0 = success) */
2577 httpTrace(http_t
*http
, /* I - Connection to server */
2578 const char *uri
) /* I - URI for trace */
2580 return (http_send(http
, HTTP_TRACE
, uri
));
2585 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2588 http_status_t
/* O - HTTP status */
2589 httpUpdate(http_t
*http
) /* I - Connection to server */
2591 char line
[32768], /* Line from connection... */
2592 *value
; /* Pointer to value on line */
2593 http_field_t field
; /* Field index */
2594 int major
, minor
, /* HTTP version numbers */
2595 status
; /* Request status */
2598 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2599 http_states
[http
->state
]));
2602 * Flush pending data, if any...
2607 DEBUG_puts("2httpUpdate: flushing buffer...");
2609 if (httpFlushWrite(http
) < 0)
2610 return (HTTP_ERROR
);
2614 * If we haven't issued any commands, then there is nothing to "update"...
2617 if (http
->state
== HTTP_WAITING
)
2618 return (HTTP_CONTINUE
);
2621 * Grab all of the lines we can from the connection...
2624 while (httpGets(line
, sizeof(line
), http
) != NULL
)
2626 DEBUG_printf(("2httpUpdate: Got \"%s\"", line
));
2628 if (line
[0] == '\0')
2631 * Blank line means the start of the data section (if any). Return
2632 * the result code, too...
2634 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2635 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2639 if (http
->status
== HTTP_CONTINUE
)
2640 return (http
->status
);
2642 if (http
->status
< HTTP_BAD_REQUEST
)
2643 http
->digest_tries
= 0;
2646 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2648 if (http_setup_ssl(http
) != 0)
2651 closesocket(http
->fd
);
2656 return (HTTP_ERROR
);
2659 return (HTTP_CONTINUE
);
2661 #endif /* HAVE_SSL */
2663 httpGetLength2(http
);
2665 switch (http
->state
)
2669 case HTTP_POST_RECV
:
2672 case HTTP_POST_SEND
:
2677 http
->state
= HTTP_WAITING
;
2681 return (http
->status
);
2683 else if (!strncmp(line
, "HTTP/", 5))
2686 * Got the beginning of a response...
2689 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
2690 return (HTTP_ERROR
);
2692 http
->version
= (http_version_t
)(major
* 100 + minor
);
2693 http
->status
= (http_status_t
)status
;
2695 else if ((value
= strchr(line
, ':')) != NULL
)
2702 while (_cups_isspace(*value
))
2706 * Be tolerants of servers that send unknown attribute fields...
2709 if (!strcasecmp(line
, "expect"))
2712 * "Expect: 100-continue" or similar...
2715 http
->expect
= (http_status_t
)atoi(value
);
2717 else if (!strcasecmp(line
, "cookie"))
2720 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2723 httpSetCookie(http
, value
);
2725 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
2727 DEBUG_printf(("1httpUpdate: unknown field %s seen!", line
));
2731 httpSetField(http
, field
, value
);
2735 DEBUG_printf(("1httpUpdate: Bad response line \"%s\"!", line
));
2736 http
->status
= HTTP_ERROR
;
2737 return (HTTP_ERROR
);
2742 * See if there was an error...
2745 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2747 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2748 return (http
->status
);
2753 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2754 strerror(http
->error
)));
2755 http
->status
= HTTP_ERROR
;
2756 return (HTTP_ERROR
);
2760 * If we haven't already returned, then there is nothing new...
2763 return (HTTP_CONTINUE
);
2768 * '_httpWait()' - Wait for data available on a connection (no flush).
2771 int /* O - 1 if data is available, 0 otherwise */
2772 _httpWait(http_t
*http
, /* I - Connection to server */
2773 int msec
, /* I - Milliseconds to wait */
2774 int usessl
) /* I - Use SSL context? */
2777 struct pollfd pfd
; /* Polled file descriptor */
2779 fd_set input_set
; /* select() input set */
2780 struct timeval timeout
; /* Timeout */
2781 #endif /* HAVE_POLL */
2782 int nfds
; /* Result from select()/poll() */
2785 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2789 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2794 * Check the SSL/TLS buffers for data first...
2798 if (http
->tls
&& usessl
)
2801 if (SSL_pending(http
->tls
))
2803 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2807 # elif defined(HAVE_GNUTLS)
2808 if (gnutls_record_check_pending(http
->tls
))
2810 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2814 # elif defined(HAVE_CDSASSL)
2815 size_t bytes
; /* Bytes that are available */
2817 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2820 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2823 # endif /* HAVE_LIBSSL */
2825 #endif /* HAVE_SSL */
2828 * Then try doing a select() or poll() to poll the socket...
2833 pfd
.events
= POLLIN
;
2835 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2836 (errno
== EINTR
|| errno
== EAGAIN
));
2841 FD_ZERO(&input_set
);
2842 FD_SET(http
->fd
, &input_set
);
2844 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2848 timeout
.tv_sec
= msec
/ 1000;
2849 timeout
.tv_usec
= (msec
% 1000) * 1000;
2851 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2854 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2856 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2859 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2860 WSAGetLastError() == WSAEWOULDBLOCK
));
2862 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2864 #endif /* HAVE_POLL */
2866 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2874 * 'httpWait()' - Wait for data available on a connection.
2876 * @since CUPS 1.1.19/Mac OS X 10.3@
2879 int /* O - 1 if data is available, 0 otherwise */
2880 httpWait(http_t
*http
, /* I - Connection to server */
2881 int msec
) /* I - Milliseconds to wait */
2884 * First see if there is data in the buffer...
2894 * Flush pending data, if any...
2899 if (httpFlushWrite(http
) < 0)
2904 * If not, check the SSL/TLS buffers and do a select() on the connection...
2907 return (_httpWait(http
, msec
, 1));
2912 * 'httpWrite()' - Write data to a HTTP connection.
2914 * This function is deprecated. Use the httpWrite2() function which can
2915 * write more than 2GB of data.
2920 int /* O - Number of bytes written */
2921 httpWrite(http_t
*http
, /* I - Connection to server */
2922 const char *buffer
, /* I - Buffer for data */
2923 int length
) /* I - Number of bytes to write */
2925 return ((int)httpWrite2(http
, buffer
, length
));
2930 * 'httpWrite2()' - Write data to a HTTP connection.
2932 * @since CUPS 1.2/Mac OS X 10.5@
2935 ssize_t
/* O - Number of bytes written */
2936 httpWrite2(http_t
*http
, /* I - Connection to server */
2937 const char *buffer
, /* I - Buffer for data */
2938 size_t length
) /* I - Number of bytes to write */
2940 ssize_t bytes
; /* Bytes written */
2943 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
2944 buffer
, CUPS_LLCAST length
));
2947 * Range check input...
2950 if (http
== NULL
|| buffer
== NULL
)
2954 * Mark activity on the connection...
2957 http
->activity
= time(NULL
);
2960 * Buffer small writes for better performance...
2965 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2967 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
2968 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
2970 httpFlushWrite(http
);
2973 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
2974 length
< sizeof(http
->wbuffer
))
2977 * Write to buffer...
2980 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
2981 CUPS_LLCAST length
));
2983 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2984 http
->wused
+= (int)length
;
2985 bytes
= (ssize_t
)length
;
2990 * Otherwise write the data directly...
2993 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
2994 CUPS_LLCAST length
));
2996 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2997 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2999 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3001 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3002 CUPS_LLCAST bytes
));
3005 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3006 http
->data_remaining
-= bytes
;
3012 * Handle end-of-request processing...
3015 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3016 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3019 * Finished with the transfer; unless we are sending POST or PUT
3023 DEBUG_puts("2httpWrite: changing states...");
3026 httpFlushWrite(http
);
3028 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3031 * Send a 0-length chunk at the end of the request...
3034 http_write(http
, "0\r\n\r\n", 5);
3037 * Reset the data state...
3040 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3041 http
->data_remaining
= 0;
3044 if (http
->state
== HTTP_POST_RECV
)
3046 else if (http
->state
== HTTP_PUT_RECV
)
3047 http
->state
= HTTP_STATUS
;
3049 http
->state
= HTTP_WAITING
;
3056 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3058 * '_httpWriteCDSA()' - Write function for the CDSA library.
3061 OSStatus
/* O - -1 on error, 0 on success */
3063 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3064 const void *data
, /* I - Data buffer */
3065 size_t *dataLength
) /* IO - Number of bytes */
3067 OSStatus result
; /* Return value */
3068 ssize_t bytes
; /* Number of bytes read */
3069 http_t
*http
; /* HTTP connection */
3072 http
= (http_t
*)connection
;
3076 bytes
= write(http
->fd
, data
, *dataLength
);
3078 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3080 if (bytes
== *dataLength
)
3084 else if (bytes
>= 0)
3086 *dataLength
= bytes
;
3087 result
= errSSLWouldBlock
;
3093 if (errno
== EAGAIN
)
3094 result
= errSSLWouldBlock
;
3096 result
= errSSLClosedAbort
;
3101 #endif /* HAVE_SSL && HAVE_CDSASSL */
3104 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3106 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3109 ssize_t
/* O - Number of bytes written or -1 on error */
3111 gnutls_transport_ptr ptr
, /* I - Connection to server */
3112 const void *data
, /* I - Data buffer */
3113 size_t length
) /* I - Number of bytes to write */
3115 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
3117 #endif /* HAVE_SSL && HAVE_GNUTLS */
3120 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3122 * 'http_bio_ctrl()' - Control the HTTP connection.
3125 static long /* O - Result/data */
3126 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3127 int cmd
, /* I - Control command */
3128 long arg1
, /* I - First argument */
3129 void *arg2
) /* I - Second argument */
3136 case BIO_CTRL_RESET
:
3140 case BIO_C_SET_FILE_PTR
:
3145 case BIO_C_GET_FILE_PTR
:
3148 *((void **)arg2
) = h
->ptr
;
3155 case BIO_CTRL_FLUSH
:
3162 * 'http_bio_free()' - Free OpenSSL data.
3165 static int /* O - 1 on success, 0 on failure */
3166 http_bio_free(BIO
*h
) /* I - BIO data */
3182 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3185 static int /* O - 1 on success, 0 on failure */
3186 http_bio_new(BIO
*h
) /* I - BIO data */
3201 * 'http_bio_puts()' - Send a string for OpenSSL.
3204 static int /* O - Bytes written */
3205 http_bio_puts(BIO
*h
, /* I - BIO data */
3206 const char *str
) /* I - String to write */
3209 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3211 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3217 * 'http_bio_read()' - Read data for OpenSSL.
3220 static int /* O - Bytes read */
3221 http_bio_read(BIO
*h
, /* I - BIO data */
3222 char *buf
, /* I - Buffer */
3223 int size
) /* I - Number of bytes to read */
3225 http_t
*http
; /* HTTP connection */
3228 http
= (http_t
*)h
->ptr
;
3230 if (!http
->blocking
)
3233 * Make sure we have data before we read...
3236 if (!_httpWait(http
, 10000, 0))
3239 http
->error
= WSAETIMEDOUT
;
3241 http
->error
= ETIMEDOUT
;
3248 return (recv(http
->fd
, buf
, size
, 0));
3253 * 'http_bio_write()' - Write data for OpenSSL.
3256 static int /* O - Bytes written */
3257 http_bio_write(BIO
*h
, /* I - BIO data */
3258 const char *buf
, /* I - Buffer to write */
3259 int num
) /* I - Number of bytes to write */
3261 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3263 #endif /* HAVE_SSL && HAVE_LIBSSL */
3268 * 'http_debug_hex()' - Do a hex dump of a buffer.
3272 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3273 const char *buffer
, /* I - Buffer to dump */
3274 int bytes
) /* I - Bytes to dump */
3276 int i
, j
, /* Looping vars */
3277 ch
; /* Current character */
3278 char line
[255], /* Line buffer */
3279 *start
, /* Start of line after prefix */
3280 *ptr
; /* Pointer into line */
3283 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3286 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
3288 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3289 start
= line
+ strlen(line
);
3291 for (i
= 0; i
< bytes
; i
+= 16)
3293 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3294 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3306 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3308 ch
= buffer
[i
+ j
] & 255;
3310 if (ch
< ' ' || ch
>= 127)
3324 * 'http_field()' - Return the field index for a field name.
3327 static http_field_t
/* O - Field index */
3328 http_field(const char *name
) /* I - String name */
3330 int i
; /* Looping var */
3333 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3334 if (strcasecmp(name
, http_fields
[i
]) == 0)
3335 return ((http_field_t
)i
);
3337 return (HTTP_FIELD_UNKNOWN
);
3343 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3346 static int /* O - Bytes read */
3347 http_read_ssl(http_t
*http
, /* I - Connection to server */
3348 char *buf
, /* I - Buffer to store data */
3349 int len
) /* I - Length of buffer */
3351 # if defined(HAVE_LIBSSL)
3352 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3354 # elif defined(HAVE_GNUTLS)
3355 ssize_t result
; /* Return value */
3358 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3360 if (result
< 0 && !errno
)
3363 * Convert GNU TLS error to errno value...
3368 case GNUTLS_E_INTERRUPTED
:
3372 case GNUTLS_E_AGAIN
:
3384 return ((int)result
);
3386 # elif defined(HAVE_CDSASSL)
3387 int result
; /* Return value */
3388 OSStatus error
; /* Error info */
3389 size_t processed
; /* Number of bytes processed */
3392 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3397 result
= (int)processed
;
3399 case errSSLClosedGraceful
:
3402 case errSSLWouldBlock
:
3404 result
= (int)processed
;
3418 # elif defined(HAVE_SSPISSL)
3419 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3420 # endif /* HAVE_LIBSSL */
3422 #endif /* HAVE_SSL */
3427 * 'http_locking_cb()' - Lock/unlock a thread's mutex.
3431 http_locking_cb(int mode
, /* I - Lock mode */
3432 int type
, /* I - Lock type */
3433 const char *file
, /* I - Source file */
3434 int line
) /* I - Line number */
3436 if (mode
& CRYPTO_LOCK
)
3437 _cupsMutexLock(http_locks
+ type
);
3439 _cupsMutexUnlock(http_locks
+ type
);
3441 #endif /* HAVE_LIBSSL */
3445 * 'http_send()' - Send a request with all fields and the trailing blank line.
3448 static int /* O - 0 on success, non-zero on error */
3449 http_send(http_t
*http
, /* I - Connection to server */
3450 http_state_t request
, /* I - Request code */
3451 const char *uri
) /* I - URI */
3453 int i
; /* Looping var */
3454 char buf
[1024]; /* Encoded URI buffer */
3455 static const char * const codes
[] =
3456 { /* Request code strings */
3473 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3474 http
, codes
[request
], uri
));
3476 if (http
== NULL
|| uri
== NULL
)
3480 * Set the User-Agent field if it isn't already...
3483 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3484 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3487 * Encode the URI as needed...
3490 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3493 * See if we had an error the last time around; if so, reconnect...
3496 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3497 if (httpReconnect(http
))
3501 * Flush any written data that is pending...
3506 if (httpFlushWrite(http
) < 0)
3507 if (httpReconnect(http
))
3512 * Send the request header...
3515 http
->state
= request
;
3516 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3518 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3521 http
->status
= HTTP_CONTINUE
;
3524 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3526 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3527 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3529 #endif /* HAVE_SSL */
3531 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3533 http
->status
= HTTP_ERROR
;
3537 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3538 if (http
->fields
[i
][0] != '\0')
3540 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3541 httpGetField(http
, i
)));
3543 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3544 httpGetField(http
, i
)) < 1)
3546 http
->status
= HTTP_ERROR
;
3552 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3554 http
->status
= HTTP_ERROR
;
3558 if (http
->expect
== HTTP_CONTINUE
&&
3559 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3560 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3562 http
->status
= HTTP_ERROR
;
3566 if (httpPrintf(http
, "\r\n") < 1)
3568 http
->status
= HTTP_ERROR
;
3572 if (httpFlushWrite(http
) < 0)
3575 httpGetLength2(http
);
3576 httpClearFields(http
);
3579 * The Kerberos and AuthRef authentication strings can only be used once...
3582 if (http
->field_authorization
&& http
->authstring
&&
3583 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3584 !strncmp(http
->authstring
, "AuthRef", 7)))
3586 http
->_authstring
[0] = '\0';
3588 if (http
->authstring
!= http
->_authstring
)
3589 free(http
->authstring
);
3591 http
->authstring
= http
->_authstring
;
3599 # ifdef HAVE_CDSASSL
3601 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3604 static int /* O - Status of connection */
3605 http_set_credentials(http_t
*http
) /* I - Connection to server */
3607 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3608 OSStatus error
= 0; /* Error code */
3609 http_tls_credentials_t credentials
= NULL
;
3610 /* TLS credentials */
3613 DEBUG_printf(("7http_set_credentials(%p)", http
));
3616 * Prefer connection specific credentials...
3619 if ((credentials
= http
->tls_credentials
) == NULL
)
3620 credentials
= cg
->tls_credentials
;
3622 # if HAVE_SECPOLICYCREATESSL
3624 * Otherwise root around in the user's keychain to see if one can be found...
3629 CFDictionaryRef query
; /* Query dictionary */
3630 CFTypeRef matches
= NULL
; /* Matching credentials */
3631 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3632 CFTypeRef keys
[] = { kSecClass
,
3635 /* Keys for dictionary */
3636 CFTypeRef values
[] = { kSecClassCertificate
,
3639 /* Values for dictionary */
3642 * Get the names associated with the server.
3645 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3647 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3653 * Create a query which will return all identities that can sign and match
3654 * the passed in policy.
3657 query
= CFDictionaryCreate(NULL
,
3658 (const void**)(&keys
[0]),
3659 (const void**)(&values
[0]),
3660 sizeof(keys
) / sizeof(keys
[0]),
3661 &kCFTypeDictionaryKeyCallBacks
,
3662 &kCFTypeDictionaryValueCallBacks
);
3665 error
= SecItemCopyMatching(query
, &matches
);
3666 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3675 CFRelease(dn_array
);
3677 # endif /* HAVE_SECPOLICYCREATESSL */
3681 error
= SSLSetCertificate(http
->tls
, credentials
);
3682 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3686 DEBUG_puts("4http_set_credentials: No credentials to set.");
3690 # endif /* HAVE_CDSASSL */
3694 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3697 static int /* O - Status of connection */
3698 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3700 _cups_globals_t
*cg
= _cupsGlobals();
3701 /* Pointer to library globals */
3702 int any_root
; /* Allow any root */
3705 SSL_CTX
*context
; /* Context for encryption */
3706 BIO
*bio
; /* BIO data */
3707 # elif defined(HAVE_GNUTLS)
3708 gnutls_certificate_client_credentials
*credentials
;
3709 /* TLS credentials */
3710 # elif defined(HAVE_CDSASSL)
3711 OSStatus error
; /* Error code */
3712 const char *message
= NULL
; /* Error message */
3713 cups_array_t
*credentials
; /* Credentials array */
3714 char *hostname
; /* Hostname */
3715 cups_array_t
*names
; /* CUPS distinguished names */
3716 CFArrayRef dn_array
; /* CF distinguished names array */
3717 CFIndex count
; /* Number of credentials */
3718 CFDataRef data
; /* Certificate data */
3719 int i
; /* Looping var */
3721 *credential
; /* Credential data */
3722 # elif defined(HAVE_SSPISSL)
3723 TCHAR username
[256]; /* Username returned from GetUserName() */
3724 TCHAR commonName
[256]; /* Common name for certificate */
3725 DWORD dwSize
; /* 32 bit size */
3726 # endif /* HAVE_LIBSSL */
3729 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3732 * Always allow self-signed certificates for the local loopback address...
3735 if (httpAddrLocalhost(http
->hostaddr
))
3738 any_root
= cg
->any_root
;
3741 context
= SSL_CTX_new(SSLv23_client_method());
3743 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3745 bio
= BIO_new(_httpBIOMethods());
3746 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3748 http
->tls
= SSL_new(context
);
3749 SSL_set_bio(http
->tls_credentials
, bio
, bio
);
3751 if (SSL_connect(http
->tls
) != 1)
3754 unsigned long error
; /* Error code */
3756 while ((error
= ERR_get_error()) != 0)
3757 DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error
, NULL
)));
3760 SSL_CTX_free(context
);
3761 SSL_free(http
->tls
);
3765 http
->error
= WSAGetLastError();
3767 http
->error
= errno
;
3769 http
->status
= HTTP_ERROR
;
3771 return (HTTP_ERROR
);
3774 # elif defined(HAVE_GNUTLS)
3775 credentials
= (gnutls_certificate_client_credentials
*)
3776 malloc(sizeof(gnutls_certificate_client_credentials
));
3777 if (credentials
== NULL
)
3779 http
->error
= errno
;
3780 http
->status
= HTTP_ERROR
;
3785 gnutls_certificate_allocate_credentials(credentials
);
3787 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3788 gnutls_set_default_priority(http
->tls
);
3789 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3790 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3791 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3792 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3794 if ((gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3796 http
->error
= errno
;
3797 http
->status
= HTTP_ERROR
;
3799 gnutls_deinit(http
->tls
);
3800 gnutls_certificate_free_credentials(*credentials
);
3807 http
->tls_credentials
= credentials
;
3809 # elif defined(HAVE_CDSASSL)
3810 if ((error
= SSLNewContext(false, &http
->tls
)))
3812 http
->error
= error
;
3813 http
->status
= HTTP_ERROR
;
3818 error
= SSLSetConnection(http
->tls
, http
);
3819 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
3823 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
3824 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
3829 error
= SSLSetProtocolVersionEnabled(http
->tls
, kSSLProtocol2
, false);
3830 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionEnabled, error=%d",
3836 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
3837 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
3838 any_root
, (int)error
));
3843 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
3844 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
3845 cg
->expired_certs
, (int)error
));
3850 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
3851 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
3852 cg
->expired_root
, (int)error
));
3857 if (cg
->client_cert_cb
)
3859 error
= SSLSetSessionOption(http
->tls
,
3860 kSSLSessionOptionBreakOnCertRequested
, true);
3861 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
3862 "error=%d", (int)error
));
3866 error
= http_set_credentials(http
);
3867 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
3873 * If there's a server certificate callback installed let it evaluate the
3874 * certificate(s) during the handshake...
3877 if (!error
&& cg
->server_cert_cb
!= NULL
)
3879 error
= SSLSetEnableCertVerify(http
->tls
, false);
3880 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
3885 error
= SSLSetSessionOption(http
->tls
,
3886 kSSLSessionOptionBreakOnServerAuth
, true);
3887 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
3888 "error=%d", (int)error
));
3894 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
3895 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
3897 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
3903 int done
= 0; /* Are we done yet? */
3905 while (!error
&& !done
)
3907 error
= SSLHandshake(http
->tls
);
3909 DEBUG_printf(("4_httpWait: SSLHandshake returned %d.", (int)error
));
3917 case errSSLWouldBlock
:
3921 case errSSLServerAuthCompleted
:
3923 if (cg
->server_cert_cb
)
3925 error
= httpCopyCredentials(http
, &credentials
);
3928 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
3929 cg
->server_cert_data
);
3930 httpFreeCredentials(credentials
);
3933 DEBUG_printf(("4_httpWait: Server certificate callback returned "
3934 "%d.", (int)error
));
3938 case errSSLClientCertRequested
:
3941 if (cg
->client_cert_cb
)
3944 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
3947 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
3949 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
3951 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
3953 if ((credential
= malloc(sizeof(*credential
))))
3955 credential
->datalen
= CFDataGetLength(data
);
3956 if ((credential
->data
= malloc(credential
->datalen
)))
3958 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
3959 credential
->datalen
);
3960 cupsArrayAdd(names
, credential
);
3966 CFRelease(dn_array
);
3971 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
3972 cg
->client_cert_data
);
3974 DEBUG_printf(("4_httpWait: Client certificate callback "
3975 "returned %d.", (int)error
));
3978 httpFreeCredentials(names
);
3982 case errSSLUnknownRootCert
:
3983 message
= _("Unable to establish a secure connection to host "
3984 "(untrusted certificate).");
3987 case errSSLNoRootCert
:
3988 message
= _("Unable to establish a secure connection to host "
3989 "(self-signed certificate).");
3992 case errSSLCertExpired
:
3993 message
= _("Unable to establish a secure connection to host "
3994 "(expired certificate).");
3997 case errSSLCertNotYetValid
:
3998 message
= _("Unable to establish a secure connection to host "
3999 "(certificate not yet valid).");
4002 case errSSLHostNameMismatch
:
4003 message
= _("Unable to establish a secure connection to host "
4004 "(host name mismatch).");
4007 case errSSLXCertChainInvalid
:
4008 message
= _("Unable to establish a secure connection to host "
4009 "(certificate chain invalid).");
4012 case errSSLConnectionRefused
:
4013 message
= _("Unable to establish a secure connection to host "
4014 "(peer dropped connection before responding).");
4025 http
->error
= error
;
4026 http
->status
= HTTP_ERROR
;
4027 errno
= ECONNREFUSED
;
4029 SSLDisposeContext(http
->tls
);
4033 * If an error string wasn't set by the callbacks use a generic one...
4037 #ifdef HAVE_CSSMERRORSTRING
4038 message
= cssmErrorString(error
);
4040 message
= _("Unable to establish a secure connection to host.");
4041 #endif /* HAVE_CSSMERRORSTRING */
4043 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4048 # elif defined(HAVE_SSPISSL)
4049 http
->tls
= _sspiAlloc();
4054 http
->tls
->sock
= http
->fd
;
4055 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4056 GetUserName(username
, &dwSize
);
4057 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4058 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4060 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4063 _sspiFree(http
->tls_credentials
);
4064 http
->tls_credentials
= NULL
;
4068 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
4069 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4071 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
4073 _sspiFree(http
->tls_credentials
);
4074 http
->tls_credentials
= NULL
;
4077 # endif /* HAVE_CDSASSL */
4081 #endif /* HAVE_SSL */
4086 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4090 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4093 SSL_CTX
*context
; /* Context for encryption */
4095 context
= SSL_get_SSL_CTX(http
->tls_credentials
);
4097 SSL_shutdown(http
->tls_credentials
);
4098 SSL_CTX_free(context
);
4099 SSL_free(http
->tls_credentials
);
4101 # elif defined(HAVE_GNUTLS)
4102 gnutls_certificate_client_credentials
*credentials
;
4103 /* TLS credentials */
4105 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4107 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4108 gnutls_deinit(http
->tls
);
4109 gnutls_certificate_free_credentials(*credentials
);
4112 # elif defined(HAVE_CDSASSL)
4113 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4116 SSLDisposeContext(http
->tls
);
4118 if (http
->tls_credentials
)
4119 CFRelease(http
->tls_credentials
);
4121 # elif defined(HAVE_SSPISSL)
4122 _sspiFree(http
->tls_credentials
);
4123 # endif /* HAVE_LIBSSL */
4126 http
->tls_credentials
= NULL
;
4128 #endif /* HAVE_SSL */
4133 * 'http_threadid_cb()' - Return the current thread ID.
4136 static unsigned long /* O - Thread ID */
4137 http_threadid_cb(void)
4139 # ifdef HAVE_PTHREAD_H
4140 return ((unsigned long)pthread_self());
4143 # endif /* HAVE_PTHREAD_H */
4145 #endif /* HAVE_LIBSSL */
4150 * 'http_upgrade()' - Force upgrade to TLS encryption.
4153 static int /* O - Status of connection */
4154 http_upgrade(http_t
*http
) /* I - Connection to server */
4156 int ret
; /* Return value */
4157 http_t myhttp
; /* Local copy of HTTP data */
4160 DEBUG_printf(("7http_upgrade(%p)", http
));
4163 * Flush the connection to make sure any previous "Upgrade" message
4170 * Copy the HTTP data to a local variable so we can do the OPTIONS
4171 * request without interfering with the existing request data...
4174 memcpy(&myhttp
, http
, sizeof(myhttp
));
4177 * Send an OPTIONS request to the server, requiring SSL or TLS
4178 * encryption on the link...
4181 http
->field_authorization
= NULL
; /* Don't free the auth string */
4183 httpClearFields(http
);
4184 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4185 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4187 if ((ret
= httpOptions(http
, "*")) == 0)
4190 * Wait for the secure connection...
4193 while (httpUpdate(http
) == HTTP_CONTINUE
);
4197 * Restore the HTTP request data...
4200 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4201 http
->data_encoding
= myhttp
.data_encoding
;
4202 http
->data_remaining
= myhttp
.data_remaining
;
4203 http
->_data_remaining
= myhttp
._data_remaining
;
4204 http
->expect
= myhttp
.expect
;
4205 http
->field_authorization
= myhttp
.field_authorization
;
4206 http
->digest_tries
= myhttp
.digest_tries
;
4209 * See if we actually went secure...
4215 * Server does not support HTTP upgrade...
4218 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4221 closesocket(http
->fd
);
4233 #endif /* HAVE_SSL */
4237 * 'http_write()' - Write a buffer to a HTTP connection.
4240 static int /* O - Number of bytes written */
4241 http_write(http_t
*http
, /* I - Connection to server */
4242 const char *buffer
, /* I - Buffer for data */
4243 int length
) /* I - Number of bytes to write */
4245 int tbytes
, /* Total bytes sent */
4246 bytes
; /* Bytes sent */
4249 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4258 bytes
= http_write_ssl(http
, buffer
, length
);
4260 #endif /* HAVE_SSL */
4261 bytes
= send(http
->fd
, buffer
, length
, 0);
4266 if (WSAGetLastError() == WSAEINTR
)
4268 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4270 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4273 http
->error
= WSAGetLastError();
4275 else if (WSAGetLastError() != http
->error
&&
4276 WSAGetLastError() != WSAECONNRESET
)
4278 http
->error
= WSAGetLastError();
4285 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4287 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4289 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4292 http
->error
= errno
;
4294 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4296 http
->error
= errno
;
4301 DEBUG_printf(("3http_write: error writing data (%s).",
4302 strerror(http
->error
)));
4313 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4316 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4323 * 'http_write_chunk()' - Write a chunked buffer.
4326 static int /* O - Number bytes written */
4327 http_write_chunk(http_t
*http
, /* I - Connection to server */
4328 const char *buffer
, /* I - Buffer to write */
4329 int length
) /* I - Length of buffer */
4331 char header
[255]; /* Chunk header */
4332 int bytes
; /* Bytes written */
4335 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4336 http
, buffer
, length
));
4339 * Write the chunk header, data, and trailer.
4342 sprintf(header
, "%x\r\n", length
);
4343 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4345 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4349 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4351 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4355 if (http_write(http
, "\r\n", 2) < 0)
4357 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4367 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4370 static int /* O - Bytes written */
4371 http_write_ssl(http_t
*http
, /* I - Connection to server */
4372 const char *buf
, /* I - Buffer holding data */
4373 int len
) /* I - Length of buffer */
4375 ssize_t result
; /* Return value */
4378 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4380 # if defined(HAVE_LIBSSL)
4381 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4383 # elif defined(HAVE_GNUTLS)
4384 result
= gnutls_record_send(http
->tls
, buf
, len
);
4386 if (result
< 0 && !errno
)
4389 * Convert GNU TLS error to errno value...
4394 case GNUTLS_E_INTERRUPTED
:
4398 case GNUTLS_E_AGAIN
:
4410 # elif defined(HAVE_CDSASSL)
4411 OSStatus error
; /* Error info */
4412 size_t processed
; /* Number of bytes processed */
4415 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4420 result
= (int)processed
;
4422 case errSSLClosedGraceful
:
4425 case errSSLWouldBlock
:
4427 result
= (int)processed
;
4439 # elif defined(HAVE_SSPISSL)
4440 return _sspiWrite((_sspi_struct_t
*) http
->tls
, (void*) buf
, len
);
4441 # endif /* HAVE_LIBSSL */
4443 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4445 return ((int)result
);
4447 #endif /* HAVE_SSL */
4451 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".