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 * httpTrace() - Send an TRACE request to the server.
84 * httpUpdate() - Update the current HTTP state for incoming
86 * _httpWait() - Wait for data available on a connection (no
88 * httpWait() - Wait for data available on a connection.
89 * httpWrite() - Write data to a HTTP connection.
90 * httpWrite2() - Write data to a HTTP connection.
91 * _httpWriteCDSA() - Write function for the CDSA library.
92 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
93 * http_bio_ctrl() - Control the HTTP connection.
94 * http_bio_free() - Free OpenSSL data.
95 * http_bio_new() - Initialize an OpenSSL BIO structure.
96 * http_bio_puts() - Send a string for OpenSSL.
97 * http_bio_read() - Read data for OpenSSL.
98 * http_bio_write() - Write data for OpenSSL.
99 * http_debug_hex() - Do a hex dump of a buffer.
100 * http_field() - Return the field index for a field name.
101 * http_read_ssl() - Read from a SSL/TLS connection.
102 * http_locking_cb() - Lock/unlock a thread's mutex.
103 * http_send() - Send a request with all fields and the trailing
105 * http_set_credentials() - Set the SSL/TLS credentials.
106 * http_setup_ssl() - Set up SSL/TLS support on a connection.
107 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
108 * http_threadid_cb() - Return the current thread ID.
109 * http_upgrade() - Force upgrade to TLS encryption.
110 * http_write() - Write a buffer to a HTTP connection.
111 * http_write_chunk() - Write a chunked buffer.
112 * http_write_ssl() - Write to a SSL/TLS connection.
116 * Include necessary headers...
119 #include "cups-private.h"
125 # include <sys/time.h>
126 # include <sys/resource.h>
129 # include <sys/poll.h>
130 #endif /* HAVE_POLL */
134 * Some operating systems have done away with the Fxxxx constants for
135 * the fcntl() call; this works around that "feature"...
139 # define FNONBLK O_NONBLOCK
140 #endif /* !FNONBLK */
148 static void http_debug_hex(const char *prefix
, const char *buffer
,
151 static http_field_t
http_field(const char *name
);
152 static int http_send(http_t
*http
, http_state_t request
,
154 static int http_write(http_t
*http
, const char *buffer
,
156 static int http_write_chunk(http_t
*http
, const char *buffer
,
159 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
160 static int http_set_credentials(http_t
*http
);
161 static int http_setup_ssl(http_t
*http
);
162 static void http_shutdown_ssl(http_t
*http
);
163 static int http_upgrade(http_t
*http
);
164 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
167 # ifdef HAVE_PTHREAD_H
168 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
169 # endif /* HAVE_PTHREAD_H */
171 # elif defined(HAVE_LIBSSL)
172 static _cups_mutex_t
*http_locks
; /* OpenSSL lock mutexes */
174 static void http_locking_cb(int mode
, int type
, const char *file
,
176 static unsigned long http_threadid_cb(void);
177 # endif /* HAVE_GNUTLS */
178 #endif /* HAVE_SSL */
185 static const char * const http_fields
[] =
202 "If-Unmodified-since",
216 static const char * const http_states
[] =
236 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
238 * BIO methods for OpenSSL...
241 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
242 static int http_bio_read(BIO
*h
, char *buf
, int size
);
243 static int http_bio_puts(BIO
*h
, const char *str
);
244 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
245 static int http_bio_new(BIO
*h
);
246 static int http_bio_free(BIO
*data
);
248 static BIO_METHOD http_bio_methods
=
255 NULL
, /* http_bio_gets, */
261 #endif /* HAVE_SSL && HAVE_LIBSSL */
265 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
267 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
272 int /* O - 0 on success, -1 on error */
274 cups_array_t
*credentials
, /* I - Credentials array */
275 const void *data
, /* I - PEM-encoded X.509 data */
276 size_t datalen
) /* I - Length of data */
278 http_credential_t
*credential
; /* Credential data */
281 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
283 credential
->datalen
= datalen
;
285 if ((credential
->data
= malloc(datalen
)) != NULL
)
287 memcpy(credential
->data
, data
, datalen
);
288 cupsArrayAdd(credentials
, credential
);
299 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
301 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
304 BIO_METHOD
* /* O - BIO methods for OpenSSL */
305 _httpBIOMethods(void)
307 return (&http_bio_methods
);
309 #endif /* HAVE_SSL && HAVE_LIBSSL */
313 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
317 httpBlocking(http_t
*http
, /* I - Connection to server */
318 int b
) /* I - 1 = blocking, 0 = non-blocking */
326 * 'httpCheck()' - Check to see if there is a pending response from the server.
329 int /* O - 0 = no data, 1 = data available */
330 httpCheck(http_t
*http
) /* I - Connection to server */
332 return (httpWait(http
, 0));
337 * 'httpClearCookie()' - Clear the cookie value(s).
339 * @since CUPS 1.1.19/Mac OS X 10.3@
343 httpClearCookie(http_t
*http
) /* I - Connection to server */
357 * 'httpClearFields()' - Clear HTTP request fields.
361 httpClearFields(http_t
*http
) /* I - Connection to server */
365 memset(http
->fields
, 0, sizeof(http
->fields
));
366 if (http
->hostname
[0] == '/')
367 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
369 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
371 if (http
->field_authorization
)
373 free(http
->field_authorization
);
374 http
->field_authorization
= NULL
;
377 http
->expect
= (http_status_t
)0;
383 * 'httpClose()' - Close an HTTP connection.
387 httpClose(http_t
*http
) /* I - Connection to server */
390 OM_uint32 minor_status
; /* Minor status code */
391 #endif /* HAVE_GSSAPI */
394 DEBUG_printf(("httpClose(http=%p)", http
));
397 * Range check input...
404 * Close any open connection...
407 _httpDisconnect(http
);
410 * Free memory used...
413 httpAddrFreeList(http
->addrlist
);
419 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
420 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
422 if (http
->gssname
!= GSS_C_NO_NAME
)
423 gss_release_name(&minor_status
, &http
->gssname
);
424 #endif /* HAVE_GSSAPI */
426 #ifdef HAVE_AUTHORIZATION_H
428 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
429 #endif /* HAVE_AUTHORIZATION_H */
431 httpClearFields(http
);
433 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
434 free(http
->authstring
);
441 * 'httpConnect()' - Connect to a HTTP server.
443 * This function is deprecated - use @link httpConnectEncrypt@ instead.
448 http_t
* /* O - New HTTP connection */
449 httpConnect(const char *host
, /* I - Host to connect to */
450 int port
) /* I - Port number */
452 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
457 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
460 http_t
* /* O - New HTTP connection */
462 const char *host
, /* I - Host to connect to */
463 int port
, /* I - Port number */
464 http_encryption_t encryption
) /* I - Type of encryption to use */
466 http_t
*http
; /* New HTTP connection */
469 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
470 host
, port
, encryption
));
473 * Create the HTTP structure...
476 if ((http
= _httpCreate(host
, port
, encryption
)) == NULL
)
480 * Connect to the remote system...
483 if (!httpReconnect(http
))
487 * Could not connect to any known address - bail out!
490 httpAddrFreeList(http
->addrlist
);
499 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
505 int /* O - Status of call (0 = success) */
507 http_t
*http
, /* I - Connection to server */
508 cups_array_t
**credentials
) /* O - Array of credentials */
511 # elif defined(HAVE_GNUTLS)
512 # elif defined(HAVE_CDSASSL)
513 OSStatus error
; /* Error code */
514 CFIndex count
; /* Number of credentials */
515 CFArrayRef peerCerts
; /* Peer certificates */
516 SecCertificateRef secCert
; /* Certificate reference */
517 CFDataRef data
; /* Certificate data */
518 int i
; /* Looping var */
519 # elif defined(HAVE_SSPISSL)
520 # endif /* HAVE_LIBSSL */
526 if (!http
|| !http
->tls
|| !credentials
)
532 # elif defined(HAVE_GNUTLS)
535 # elif defined(HAVE_CDSASSL)
536 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
538 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
540 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
542 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
543 if ((data
= SecCertificateCopyData(secCert
)))
545 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
546 CFDataGetLength(data
));
552 CFRelease(peerCerts
);
557 # elif defined(HAVE_SSPISSL)
559 # endif /* HAVE_LIBSSL */
564 * '_httpConvertCredentials()' - Convert credentials to the internal format.
567 http_tls_credentials_t
/* O - Internal credentials */
568 _httpConvertCredentials(
569 cups_array_t
*credentials
) /* I - Array of credentials */
577 # elif defined(HAVE_GNUTLS)
580 # elif defined(HAVE_CDSASSL)
581 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
582 SecCertificateRef secCert
; /* Certificate reference */
583 CFDataRef data
; /* Credential data reference */
584 http_credential_t
*credential
; /* Credential data */
587 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
588 cupsArrayCount(credentials
),
589 &kCFTypeArrayCallBacks
)) == NULL
)
592 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
594 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
596 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
597 credential
->datalen
)))
599 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
602 CFArrayAppendValue(peerCerts
, secCert
);
612 # elif defined(HAVE_SSPISSL)
617 # endif /* HAVE_LIBSSL */
622 * '_httpCreate()' - Create an unconnected HTTP connection.
625 http_t
* /* O - HTTP connection */
627 const char *host
, /* I - Hostname */
628 int port
, /* I - Port number */
629 http_encryption_t encryption
) /* I - Encryption to use */
631 http_t
*http
; /* New HTTP connection */
632 http_addrlist_t
*addrlist
; /* Host address data */
633 char service
[255]; /* Service name */
636 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
637 host
, port
, encryption
));
648 sprintf(service
, "%d", port
);
650 if ((addrlist
= httpAddrGetList(host
, AF_UNSPEC
, service
)) == NULL
)
654 * Allocate memory for the structure...
657 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
659 httpAddrFreeList(addrlist
);
664 * Initialize the HTTP data...
667 http
->activity
= time(NULL
);
668 http
->addrlist
= addrlist
;
672 http
->gssctx
= GSS_C_NO_CONTEXT
;
673 http
->gssname
= GSS_C_NO_NAME
;
674 #endif /* HAVE_GSSAPI */
675 http
->version
= HTTP_1_1
;
677 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
679 if (port
== 443) /* Always use encryption for https */
680 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
682 http
->encryption
= encryption
;
685 * Return the new structure...
693 * 'httpDelete()' - Send a DELETE request to the server.
696 int /* O - Status of call (0 = success) */
697 httpDelete(http_t
*http
, /* I - Connection to server */
698 const char *uri
) /* I - URI to delete */
700 return (http_send(http
, HTTP_DELETE
, uri
));
705 * '_httpDisconnect()' - Disconnect a HTTP connection.
709 _httpDisconnect(http_t
*http
) /* I - Connection to server */
713 http_shutdown_ssl(http
);
714 #endif /* HAVE_SSL */
717 closesocket(http
->fd
);
727 * 'httpEncryption()' - Set the required encryption on the link.
730 int /* O - -1 on error, 0 on success */
731 httpEncryption(http_t
*http
, /* I - Connection to server */
732 http_encryption_t e
) /* I - New encryption preference */
734 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
740 http
->encryption
= e
;
742 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
743 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
744 return (httpReconnect(http
));
745 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
746 return (http_upgrade(http
));
750 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
754 #endif /* HAVE_SSL */
759 * 'httpError()' - Get the last error on a connection.
762 int /* O - Error code (errno) value */
763 httpError(http_t
*http
) /* I - Connection to server */
766 return (http
->error
);
773 * 'httpFlush()' - Flush data from a HTTP connection.
777 httpFlush(http_t
*http
) /* I - Connection to server */
779 char buffer
[8192]; /* Junk buffer */
780 int blocking
; /* To block or not to block */
781 http_state_t oldstate
; /* Old state */
784 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
785 http_states
[http
->state
]));
788 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
791 blocking
= http
->blocking
;
795 * Read any data we can...
798 oldstate
= http
->state
;
799 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
802 * Restore blocking and reset the connection if we didn't get all of
803 * the remaining data...
806 http
->blocking
= blocking
;
808 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
811 * Didn't get the data back, so close the current connection.
814 http
->state
= HTTP_WAITING
;
818 http_shutdown_ssl(http
);
819 #endif /* HAVE_SSL */
822 closesocket(http
->fd
);
833 * 'httpFlushWrite()' - Flush data in write buffer.
835 * @since CUPS 1.2/Mac OS X 10.5@
838 int /* O - Bytes written or -1 on error */
839 httpFlushWrite(http_t
*http
) /* I - Connection to server */
841 int bytes
; /* Bytes written */
844 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
846 if (!http
|| !http
->wused
)
848 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
849 "1httpFlushWrite: No connection.");
853 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
854 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
856 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
860 DEBUG_printf(("1httpFlushWrite: Returning %d.", bytes
));
867 * '_httpFreeCredentials()' - Free internal credentials.
871 _httpFreeCredentials(
872 http_tls_credentials_t credentials
) /* I - Internal credentials */
880 #elif defined(HAVE_GNUTLS)
883 #elif defined(HAVE_CDSASSL)
884 CFRelease(credentials
);
886 #elif defined(HAVE_SSPISSL)
889 #endif /* HAVE_LIBSSL */
894 * 'httpFreeCredentials()' - Free an array of credentials.
899 cups_array_t
*credentials
) /* I - Array of credentials */
901 http_credential_t
*credential
; /* Credential */
904 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
906 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
908 cupsArrayRemove(credentials
, credential
);
909 free((void *)credential
->data
);
913 cupsArrayDelete(credentials
);
918 * 'httpGet()' - Send a GET request to the server.
921 int /* O - Status of call (0 = success) */
922 httpGet(http_t
*http
, /* I - Connection to server */
923 const char *uri
) /* I - URI to get */
925 return (http_send(http
, HTTP_GET
, uri
));
930 * 'httpGetAuthString()' - Get the current authorization string.
932 * The authorization string is set by cupsDoAuthentication() and
933 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
934 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
937 * @since CUPS 1.3/Mac OS X 10.5@
940 char * /* O - Authorization string */
941 httpGetAuthString(http_t
*http
) /* I - Connection to server */
944 return (http
->authstring
);
951 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
953 * @since CUPS 1.2/Mac OS X 10.5@
956 int /* O - 1 if blocking, 0 if non-blocking */
957 httpGetBlocking(http_t
*http
) /* I - Connection to server */
959 return (http
? http
->blocking
: 0);
964 * 'httpGetCookie()' - Get any cookie data from the response.
966 * @since CUPS 1.1.19/Mac OS X 10.3@
969 const char * /* O - Cookie data or NULL */
970 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
972 return (http
? http
->cookie
: NULL
);
977 * 'httpGetFd()' - Get the file descriptor associated with a connection.
979 * @since CUPS 1.2/Mac OS X 10.5@
982 int /* O - File descriptor or -1 if none */
983 httpGetFd(http_t
*http
) /* I - Connection to server */
985 return (http
? http
->fd
: -1);
990 * 'httpGetField()' - Get a field value from a request/response.
993 const char * /* O - Field value */
994 httpGetField(http_t
*http
, /* I - Connection to server */
995 http_field_t field
) /* I - Field to get */
997 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
999 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
1000 http
->field_authorization
)
1003 * Special case for WWW-Authenticate: as its contents can be
1004 * longer than HTTP_MAX_VALUE...
1007 return (http
->field_authorization
);
1010 return (http
->fields
[field
]);
1015 * 'httpGetLength()' - Get the amount of data remaining from the
1016 * content-length or transfer-encoding fields.
1018 * This function is deprecated and will not return lengths larger than
1019 * 2^31 - 1; use httpGetLength2() instead.
1024 int /* O - Content length */
1025 httpGetLength(http_t
*http
) /* I - Connection to server */
1028 * Get the read content length and return the 32-bit value.
1033 httpGetLength2(http
);
1035 return (http
->_data_remaining
);
1043 * 'httpGetLength2()' - Get the amount of data remaining from the
1044 * content-length or transfer-encoding fields.
1046 * This function returns the complete content length, even for
1047 * content larger than 2^31 - 1.
1049 * @since CUPS 1.2/Mac OS X 10.5@
1052 off_t
/* O - Content length */
1053 httpGetLength2(http_t
*http
) /* I - Connection to server */
1055 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1056 http_states
[http
->state
]));
1061 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1063 DEBUG_puts("4httpGetLength2: chunked request!");
1065 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1066 http
->data_remaining
= 0;
1070 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1073 * The following is a hack for HTTP servers that don't send a
1074 * content-length or transfer-encoding field...
1076 * If there is no content-length then the connection must close
1077 * after the transfer is complete...
1080 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1083 * Default content length is 0 for errors and 2^31-1 for other
1084 * successful requests...
1087 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
1088 http
->data_remaining
= 0;
1090 http
->data_remaining
= 2147483647;
1093 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1096 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1097 CUPS_LLCAST http
->data_remaining
));
1100 if (http
->data_remaining
<= INT_MAX
)
1101 http
->_data_remaining
= (int)http
->data_remaining
;
1103 http
->_data_remaining
= INT_MAX
;
1105 return (http
->data_remaining
);
1110 * 'httpGetStatus()' - Get the status of the last HTTP request.
1112 * @since CUPS 1.2/Mac OS X 10.5@
1115 http_status_t
/* O - HTTP status */
1116 httpGetStatus(http_t
*http
) /* I - Connection to server */
1118 return (http
? http
->status
: HTTP_ERROR
);
1123 * 'httpGetSubField()' - Get a sub-field value.
1128 char * /* O - Value or NULL */
1129 httpGetSubField(http_t
*http
, /* I - Connection to server */
1130 http_field_t field
, /* I - Field index */
1131 const char *name
, /* I - Name of sub-field */
1132 char *value
) /* O - Value string */
1134 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1139 * 'httpGetSubField2()' - Get a sub-field value.
1141 * @since CUPS 1.2/Mac OS X 10.5@
1144 char * /* O - Value or NULL */
1145 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1146 http_field_t field
, /* I - Field index */
1147 const char *name
, /* I - Name of sub-field */
1148 char *value
, /* O - Value string */
1149 int valuelen
) /* I - Size of value buffer */
1151 const char *fptr
; /* Pointer into field */
1152 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1153 *ptr
, /* Pointer into string buffer */
1154 *end
; /* End of value buffer */
1156 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1157 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1159 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1160 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1163 end
= value
+ valuelen
- 1;
1165 for (fptr
= http
->fields
[field
]; *fptr
;)
1168 * Skip leading whitespace...
1171 while (_cups_isspace(*fptr
))
1181 * Get the sub-field name...
1185 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1186 ptr
< (temp
+ sizeof(temp
) - 1);
1191 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1194 * Skip trailing chars up to the '='...
1197 while (_cups_isspace(*fptr
))
1207 * Skip = and leading whitespace...
1212 while (_cups_isspace(*fptr
))
1218 * Read quoted string...
1221 for (ptr
= value
, fptr
++;
1222 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1227 while (*fptr
&& *fptr
!= '\"')
1236 * Read unquoted string...
1240 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1245 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1249 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1252 * See if this is the one...
1255 if (!strcmp(name
, temp
))
1257 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1264 DEBUG_puts("3httpGetSubField2: Returning NULL");
1271 * 'httpGets()' - Get a line of text from a HTTP connection.
1274 char * /* O - Line or NULL */
1275 httpGets(char *line
, /* I - Line to read into */
1276 int length
, /* I - Max length of buffer */
1277 http_t
*http
) /* I - Connection to server */
1279 char *lineptr
, /* Pointer into line */
1280 *lineend
, /* End of line */
1281 *bufptr
, /* Pointer into input buffer */
1282 *bufend
; /* Pointer to end of buffer */
1283 int bytes
, /* Number of bytes read */
1284 eol
; /* End-of-line? */
1287 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1289 if (http
== NULL
|| line
== NULL
)
1293 * Read a line from the buffer...
1298 lineend
= line
+ length
- 1;
1301 while (lineptr
< lineend
)
1304 * Pre-load the buffer as needed...
1313 while (http
->used
== 0)
1316 * No newline; see if there is more data to be read...
1319 if (!http
->blocking
&& !_httpWait(http
, 10000, 1))
1321 DEBUG_puts("3httpGets: Timed out!");
1323 http
->error
= WSAETIMEDOUT
;
1325 http
->error
= ETIMEDOUT
;
1332 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1333 HTTP_MAX_BUFFER
- http
->used
);
1335 #endif /* HAVE_SSL */
1336 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1337 HTTP_MAX_BUFFER
- http
->used
, 0);
1339 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1344 * Nope, can't get a line this time...
1348 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1350 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1352 else if (WSAGetLastError() != http
->error
)
1354 http
->error
= WSAGetLastError();
1359 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1361 if (errno
== EINTR
|| errno
== EAGAIN
)
1363 else if (errno
!= http
->error
)
1365 http
->error
= errno
;
1372 else if (bytes
== 0)
1374 http
->error
= EPIPE
;
1380 * Yup, update the amount used...
1383 http
->used
+= bytes
;
1387 * Now copy as much of the current line as possible...
1390 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1391 lineptr
< lineend
&& bufptr
< bufend
;)
1393 if (*bufptr
== 0x0a)
1399 else if (*bufptr
== 0x0d)
1402 *lineptr
++ = *bufptr
++;
1405 http
->used
-= (int)(bufptr
- http
->buffer
);
1407 memmove(http
->buffer
, bufptr
, http
->used
);
1415 http
->activity
= time(NULL
);
1419 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1425 DEBUG_puts("3httpGets: No new line available!");
1432 * 'httpHead()' - Send a HEAD request to the server.
1435 int /* O - Status of call (0 = success) */
1436 httpHead(http_t
*http
, /* I - Connection to server */
1437 const char *uri
) /* I - URI for head */
1439 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1440 return (http_send(http
, HTTP_HEAD
, uri
));
1445 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1446 * default HTTP proxy (if any).
1450 httpInitialize(void)
1452 static int initialized
= 0; /* Have we been called before? */
1454 WSADATA winsockdata
; /* WinSock data */
1457 int i
; /* Looping var */
1458 unsigned char data
[1024]; /* Seed data */
1459 #endif /* HAVE_LIBSSL */
1465 _cupsGlobalUnlock();
1470 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1472 #elif !defined(SO_NOSIGPIPE)
1474 * Ignore SIGPIPE signals...
1478 sigset(SIGPIPE
, SIG_IGN
);
1480 # elif defined(HAVE_SIGACTION)
1481 struct sigaction action
; /* POSIX sigaction data */
1484 memset(&action
, 0, sizeof(action
));
1485 action
.sa_handler
= SIG_IGN
;
1486 sigaction(SIGPIPE
, &action
, NULL
);
1489 signal(SIGPIPE
, SIG_IGN
);
1490 # endif /* !SO_NOSIGPIPE */
1495 * Make sure we handle threading properly...
1498 # ifdef HAVE_PTHREAD_H
1499 gcry_control(GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
1500 # endif /* HAVE_PTHREAD_H */
1503 * Initialize GNU TLS...
1506 gnutls_global_init();
1508 #elif defined(HAVE_LIBSSL)
1510 * Initialize OpenSSL...
1513 SSL_load_error_strings();
1517 * Set the threading callbacks...
1520 http_locks
= calloc(CRYPTO_num_locks(), sizeof(_cups_mutex_t
));
1521 # ifdef HAVE_PTHREAD_H
1522 for (i
= 0; i
< CRYPTO_num_locks(); i
++)
1523 pthread_mutex_init(http_locks
+ i
, NULL
);
1524 # endif /* HAVE_PTHREAD_H */
1526 CRYPTO_set_id_callback(http_threadid_cb
);
1527 CRYPTO_set_locking_callback(http_locking_cb
);
1530 * Using the current time is a dubious random seed, but on some systems
1531 * it is the best we can do (on others, this seed isn't even used...)
1534 CUPS_SRAND(time(NULL
));
1536 for (i
= 0; i
< sizeof(data
); i
++)
1537 data
[i
] = CUPS_RAND();
1539 RAND_seed(data
, sizeof(data
));
1540 #endif /* HAVE_GNUTLS */
1543 _cupsGlobalUnlock();
1548 * 'httpOptions()' - Send an OPTIONS request to the server.
1551 int /* O - Status of call (0 = success) */
1552 httpOptions(http_t
*http
, /* I - Connection to server */
1553 const char *uri
) /* I - URI for options */
1555 return (http_send(http
, HTTP_OPTIONS
, uri
));
1560 * '_httpPeek()' - Peek at data from a HTTP connection.
1562 * This function copies available data from the given HTTP connection, reading
1563 * a buffer as needed. The data is still available for reading using
1564 * @link httpRead@ or @link httpRead2@.
1566 * For non-blocking connections the usual timeouts apply.
1569 ssize_t
/* O - Number of bytes copied */
1570 _httpPeek(http_t
*http
, /* I - Connection to server */
1571 char *buffer
, /* I - Buffer for data */
1572 size_t length
) /* I - Maximum number of bytes */
1574 ssize_t bytes
; /* Bytes read */
1575 char len
[32]; /* Length string */
1578 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1579 http
, buffer
, CUPS_LLCAST length
));
1581 if (http
== NULL
|| buffer
== NULL
)
1584 http
->activity
= time(NULL
);
1590 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1591 http
->data_remaining
<= 0)
1593 DEBUG_puts("2_httpPeek: Getting chunk length...");
1595 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1597 DEBUG_puts("1_httpPeek: Could not get length!");
1601 http
->data_remaining
= strtoll(len
, NULL
, 16);
1602 if (http
->data_remaining
< 0)
1604 DEBUG_puts("1_httpPeek: Negative chunk length!");
1609 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1610 CUPS_LLCAST http
->data_remaining
));
1612 if (http
->data_remaining
<= 0)
1615 * A zero-length chunk ends a transfer; unless we are reading POST
1619 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1620 httpGets(len
, sizeof(len
), http
);
1622 if (http
->state
== HTTP_POST_RECV
)
1625 http
->state
= HTTP_WAITING
;
1628 * Prevent future reads for this request...
1631 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1635 else if (length
> (size_t)http
->data_remaining
)
1636 length
= (size_t)http
->data_remaining
;
1638 if (http
->used
== 0)
1641 * Buffer small reads for better performance...
1644 if (!http
->blocking
&& !httpWait(http
, 10000))
1647 if (http
->data_remaining
> sizeof(http
->buffer
))
1648 bytes
= sizeof(http
->buffer
);
1650 bytes
= http
->data_remaining
;
1654 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1656 #endif /* HAVE_SSL */
1658 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1661 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1663 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1672 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1674 http
->error
= WSAGetLastError();
1678 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1680 http
->error
= errno
;
1687 http
->error
= EPIPE
;
1694 if (length
> (size_t)http
->used
)
1695 length
= (size_t)http
->used
;
1697 bytes
= (ssize_t
)length
;
1699 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1702 memcpy(buffer
, http
->buffer
, length
);
1710 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1713 http
->error
= WSAGetLastError();
1715 if (errno
== EINTR
|| errno
== EAGAIN
)
1718 http
->error
= errno
;
1721 else if (bytes
== 0)
1723 http
->error
= EPIPE
;
1728 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1736 * 'httpPost()' - Send a POST request to the server.
1739 int /* O - Status of call (0 = success) */
1740 httpPost(http_t
*http
, /* I - Connection to server */
1741 const char *uri
) /* I - URI for post */
1743 return (http_send(http
, HTTP_POST
, uri
));
1748 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1753 int /* O - Number of bytes written */
1754 httpPrintf(http_t
*http
, /* I - Connection to server */
1755 const char *format
, /* I - printf-style format string */
1756 ...) /* I - Additional args as needed */
1758 int bytes
; /* Number of bytes to write */
1759 char buf
[16384]; /* Buffer for formatted string */
1760 va_list ap
; /* Variable argument pointer */
1763 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1765 va_start(ap
, format
);
1766 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1769 DEBUG_printf(("3httpPrintf: %s", buf
));
1771 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1772 return (httpWrite2(http
, buf
, bytes
));
1777 DEBUG_puts("4httpPrintf: flushing existing data...");
1779 if (httpFlushWrite(http
) < 0)
1783 return (http_write(http
, buf
, bytes
));
1789 * 'httpPut()' - Send a PUT request to the server.
1792 int /* O - Status of call (0 = success) */
1793 httpPut(http_t
*http
, /* I - Connection to server */
1794 const char *uri
) /* I - URI to put */
1796 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1797 return (http_send(http
, HTTP_PUT
, uri
));
1802 * 'httpRead()' - Read data from a HTTP connection.
1804 * This function is deprecated. Use the httpRead2() function which can
1805 * read more than 2GB of data.
1810 int /* O - Number of bytes read */
1811 httpRead(http_t
*http
, /* I - Connection to server */
1812 char *buffer
, /* I - Buffer for data */
1813 int length
) /* I - Maximum number of bytes */
1815 return ((int)httpRead2(http
, buffer
, length
));
1820 * 'httpRead2()' - Read data from a HTTP connection.
1822 * @since CUPS 1.2/Mac OS X 10.5@
1825 ssize_t
/* O - Number of bytes read */
1826 httpRead2(http_t
*http
, /* I - Connection to server */
1827 char *buffer
, /* I - Buffer for data */
1828 size_t length
) /* I - Maximum number of bytes */
1830 ssize_t bytes
; /* Bytes read */
1831 char len
[32]; /* Length string */
1834 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1835 http
, buffer
, CUPS_LLCAST length
));
1837 if (http
== NULL
|| buffer
== NULL
)
1840 http
->activity
= time(NULL
);
1846 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1847 http
->data_remaining
<= 0)
1849 DEBUG_puts("2httpRead2: Getting chunk length...");
1851 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1853 DEBUG_puts("1httpRead2: Could not get length!");
1857 http
->data_remaining
= strtoll(len
, NULL
, 16);
1858 if (http
->data_remaining
< 0)
1860 DEBUG_puts("1httpRead2: Negative chunk length!");
1865 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1866 CUPS_LLCAST http
->data_remaining
));
1868 if (http
->data_remaining
<= 0)
1871 * A zero-length chunk ends a transfer; unless we are reading POST
1875 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1876 httpGets(len
, sizeof(len
), http
);
1878 if (http
->state
== HTTP_POST_RECV
)
1881 http
->state
= HTTP_WAITING
;
1884 * Prevent future reads for this request...
1887 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1891 else if (length
> (size_t)http
->data_remaining
)
1892 length
= (size_t)http
->data_remaining
;
1894 if (http
->used
== 0 && length
<= 256)
1897 * Buffer small reads for better performance...
1900 if (!http
->blocking
&& !httpWait(http
, 10000))
1903 if (http
->data_remaining
> sizeof(http
->buffer
))
1904 bytes
= sizeof(http
->buffer
);
1906 bytes
= http
->data_remaining
;
1910 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1912 #endif /* HAVE_SSL */
1914 DEBUG_printf(("2httpRead2: reading %d bytes from socket into buffer...",
1917 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1919 DEBUG_printf(("2httpRead2: read %d bytes from socket into buffer...",
1928 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1930 http
->error
= WSAGetLastError();
1934 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1936 http
->error
= errno
;
1943 http
->error
= EPIPE
;
1950 if (length
> (size_t)http
->used
)
1951 length
= (size_t)http
->used
;
1953 bytes
= (ssize_t
)length
;
1955 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
1958 memcpy(buffer
, http
->buffer
, length
);
1959 http
->used
-= (int)length
;
1962 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1967 if (!http
->blocking
&& !httpWait(http
, 10000))
1970 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1972 #endif /* HAVE_SSL */
1975 if (!http
->blocking
&& !httpWait(http
, 10000))
1978 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
1979 CUPS_LLCAST length
));
1982 while ((bytes
= (ssize_t
) recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
1983 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1986 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
1987 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1991 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
1992 CUPS_LLCAST bytes
));
1997 http
->data_remaining
-= bytes
;
1999 if (http
->data_remaining
<= INT_MAX
)
2000 http
->_data_remaining
= (int)http
->data_remaining
;
2002 http
->_data_remaining
= INT_MAX
;
2007 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2010 http
->error
= WSAGetLastError();
2012 if (errno
== EINTR
|| errno
== EAGAIN
)
2015 http
->error
= errno
;
2020 http
->error
= EPIPE
;
2024 if (http
->data_remaining
== 0)
2026 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2027 httpGets(len
, sizeof(len
), http
);
2029 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2031 if (http
->state
== HTTP_POST_RECV
)
2034 http
->state
= HTTP_WAITING
;
2039 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2046 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2048 * '_httpReadCDSA()' - Read function for the CDSA library.
2051 OSStatus
/* O - -1 on error, 0 on success */
2053 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2054 void *data
, /* I - Data buffer */
2055 size_t *dataLength
) /* IO - Number of bytes */
2057 OSStatus result
; /* Return value */
2058 ssize_t bytes
; /* Number of bytes read */
2059 http_t
*http
; /* HTTP connection */
2062 http
= (http_t
*)connection
;
2064 if (!http
->blocking
)
2067 * Make sure we have data before we read...
2070 if (!_httpWait(http
, 10000, 0))
2072 http
->error
= ETIMEDOUT
;
2079 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2081 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2083 if (bytes
== *dataLength
)
2089 *dataLength
= bytes
;
2090 result
= errSSLWouldBlock
;
2097 result
= errSSLClosedGraceful
;
2098 else if (errno
== EAGAIN
)
2099 result
= errSSLWouldBlock
;
2101 result
= errSSLClosedAbort
;
2106 #endif /* HAVE_SSL && HAVE_CDSASSL */
2109 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2111 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2114 ssize_t
/* O - Number of bytes read or -1 on error */
2116 gnutls_transport_ptr ptr
, /* I - Connection to server */
2117 void *data
, /* I - Buffer */
2118 size_t length
) /* I - Number of bytes to read */
2120 http_t
*http
; /* HTTP connection */
2123 http
= (http_t
*)ptr
;
2125 if (!http
->blocking
)
2128 * Make sure we have data before we read...
2131 if (!_httpWait(http
, 10000, 0))
2133 http
->error
= ETIMEDOUT
;
2138 return (recv(http
->fd
, data
, length
, 0));
2140 #endif /* HAVE_SSL && HAVE_GNUTLS */
2144 * 'httpReconnect()' - Reconnect to a HTTP server.
2147 int /* O - 0 on success, non-zero on failure */
2148 httpReconnect(http_t
*http
) /* I - Connection to server */
2150 http_addrlist_t
*addr
; /* Connected address */
2152 http_addrlist_t
*current
; /* Current address */
2153 char temp
[256]; /* Temporary address string */
2157 DEBUG_printf(("httpReconnect(http=%p)", http
));
2165 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2166 http_shutdown_ssl(http
);
2168 #endif /* HAVE_SSL */
2171 * Close any previously open socket...
2176 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2179 closesocket(http
->fd
);
2188 * Connect to the server...
2192 for (current
= http
->addrlist
; current
; current
= current
->next
)
2193 DEBUG_printf(("2httpReconnect: Address %s:%d",
2194 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2195 _httpAddrPort(&(current
->addr
))));
2198 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
2201 * Unable to connect...
2205 http
->error
= WSAGetLastError();
2207 http
->error
= errno
;
2209 http
->status
= HTTP_ERROR
;
2211 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2212 strerror(http
->error
)));
2217 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2219 http
->hostaddr
= &(addr
->addr
);
2221 http
->status
= HTTP_CONTINUE
;
2224 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2227 * Always do encryption via SSL.
2230 if (http_setup_ssl(http
) != 0)
2233 closesocket(http
->fd
);
2241 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2242 return (http_upgrade(http
));
2243 #endif /* HAVE_SSL */
2245 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2246 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2247 _httpAddrPort(http
->hostaddr
)));
2254 * 'httpSetAuthString()' - Set the current authorization string.
2256 * This function just stores a copy of the current authorization string in
2257 * the HTTP connection object. You must still call httpSetField() to set
2258 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2259 * httpHead(), httpOptions(), httpPost, or httpPut().
2261 * @since CUPS 1.3/Mac OS X 10.5@
2265 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2266 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2267 const char *data
) /* I - Auth data (NULL for none) */
2270 * Range check input...
2276 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2277 free(http
->authstring
);
2279 http
->authstring
= http
->_authstring
;
2284 * Set the current authorization string...
2287 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2290 if (len
> (int)sizeof(http
->_authstring
))
2292 if ((temp
= malloc(len
)) == NULL
)
2293 len
= sizeof(http
->_authstring
);
2295 http
->authstring
= temp
;
2299 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2301 strlcpy(http
->authstring
, scheme
, len
);
2306 * Clear the current authorization string...
2309 http
->_authstring
[0] = '\0';
2315 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2321 int /* O - Status of call (0 = success) */
2322 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2323 cups_array_t
*credentials
) /* I - Array of credentials */
2325 if (!http
|| cupsArrayCount(credentials
) < 1)
2328 _httpFreeCredentials(http
->tls_credentials
);
2330 http
->tls_credentials
= _httpConvertCredentials(credentials
);
2332 return (http
->tls_credentials
? 0 : -1);
2337 * 'httpSetCookie()' - Set the cookie value(s).
2339 * @since CUPS 1.1.19/Mac OS X 10.3@
2343 httpSetCookie(http_t
*http
, /* I - Connection */
2344 const char *cookie
) /* I - Cookie string */
2353 http
->cookie
= strdup(cookie
);
2355 http
->cookie
= NULL
;
2360 * 'httpSetExpect()' - Set the Expect: header in a request.
2362 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2364 * @since CUPS 1.2/Mac OS X 10.5@
2368 httpSetExpect(http_t
*http
, /* I - Connection to server */
2369 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2372 http
->expect
= expect
;
2377 * 'httpSetField()' - Set the value of an HTTP header.
2381 httpSetField(http_t
*http
, /* I - Connection to server */
2382 http_field_t field
, /* I - Field index */
2383 const char *value
) /* I - Value */
2386 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2387 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2391 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2393 if (field
== HTTP_FIELD_AUTHORIZATION
)
2396 * Special case for Authorization: as its contents can be
2397 * longer than HTTP_MAX_VALUE
2400 if (http
->field_authorization
)
2401 free(http
->field_authorization
);
2403 http
->field_authorization
= strdup(value
);
2405 else if (field
== HTTP_FIELD_HOST
)
2408 * Special-case for Host: as we don't want a trailing "." on the hostname and
2409 * need to bracket IPv6 numeric addresses.
2412 char *ptr
= strchr(value
, ':');
2414 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2417 * Bracket IPv6 numeric addresses...
2419 * This is slightly inefficient (basically copying twice), but is an edge
2420 * case and not worth optimizing...
2423 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2424 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2429 * Check for a trailing dot on the hostname...
2432 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2436 ptr
+= strlen(ptr
) - 1;
2447 * 'httpSetLength()' - Set the content-length and content-encoding.
2449 * @since CUPS 1.2/Mac OS X 10.5@
2453 httpSetLength(http_t
*http
, /* I - Connection to server */
2454 size_t length
) /* I - Length (0 for chunked) */
2461 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2462 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2466 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2467 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2468 CUPS_LLFMT
, CUPS_LLCAST length
);
2474 * 'httpTrace()' - Send an TRACE request to the server.
2477 int /* O - Status of call (0 = success) */
2478 httpTrace(http_t
*http
, /* I - Connection to server */
2479 const char *uri
) /* I - URI for trace */
2481 return (http_send(http
, HTTP_TRACE
, uri
));
2486 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2489 http_status_t
/* O - HTTP status */
2490 httpUpdate(http_t
*http
) /* I - Connection to server */
2492 char line
[32768], /* Line from connection... */
2493 *value
; /* Pointer to value on line */
2494 http_field_t field
; /* Field index */
2495 int major
, minor
, /* HTTP version numbers */
2496 status
; /* Request status */
2499 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2500 http_states
[http
->state
]));
2503 * Flush pending data, if any...
2508 DEBUG_puts("2httpUpdate: flushing buffer...");
2510 if (httpFlushWrite(http
) < 0)
2511 return (HTTP_ERROR
);
2515 * If we haven't issued any commands, then there is nothing to "update"...
2518 if (http
->state
== HTTP_WAITING
)
2519 return (HTTP_CONTINUE
);
2522 * Grab all of the lines we can from the connection...
2525 while (httpGets(line
, sizeof(line
), http
) != NULL
)
2527 DEBUG_printf(("2httpUpdate: Got \"%s\"", line
));
2529 if (line
[0] == '\0')
2532 * Blank line means the start of the data section (if any). Return
2533 * the result code, too...
2535 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2536 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2540 if (http
->status
== HTTP_CONTINUE
)
2541 return (http
->status
);
2543 if (http
->status
< HTTP_BAD_REQUEST
)
2544 http
->digest_tries
= 0;
2547 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2549 if (http_setup_ssl(http
) != 0)
2552 closesocket(http
->fd
);
2557 return (HTTP_ERROR
);
2560 return (HTTP_CONTINUE
);
2562 #endif /* HAVE_SSL */
2564 httpGetLength2(http
);
2566 switch (http
->state
)
2570 case HTTP_POST_RECV
:
2573 case HTTP_POST_SEND
:
2578 http
->state
= HTTP_WAITING
;
2582 return (http
->status
);
2584 else if (!strncmp(line
, "HTTP/", 5))
2587 * Got the beginning of a response...
2590 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &status
) != 3)
2591 return (HTTP_ERROR
);
2593 http
->version
= (http_version_t
)(major
* 100 + minor
);
2594 http
->status
= (http_status_t
)status
;
2596 else if ((value
= strchr(line
, ':')) != NULL
)
2603 while (_cups_isspace(*value
))
2607 * Be tolerants of servers that send unknown attribute fields...
2610 if (!strcasecmp(line
, "expect"))
2613 * "Expect: 100-continue" or similar...
2616 http
->expect
= (http_status_t
)atoi(value
);
2618 else if (!strcasecmp(line
, "cookie"))
2621 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2624 httpSetCookie(http
, value
);
2626 else if ((field
= http_field(line
)) == HTTP_FIELD_UNKNOWN
)
2628 DEBUG_printf(("1httpUpdate: unknown field %s seen!", line
));
2632 httpSetField(http
, field
, value
);
2636 DEBUG_printf(("1httpUpdate: Bad response line \"%s\"!", line
));
2637 http
->status
= HTTP_ERROR
;
2638 return (HTTP_ERROR
);
2643 * See if there was an error...
2646 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2648 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2649 return (http
->status
);
2654 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2655 strerror(http
->error
)));
2656 http
->status
= HTTP_ERROR
;
2657 return (HTTP_ERROR
);
2661 * If we haven't already returned, then there is nothing new...
2664 return (HTTP_CONTINUE
);
2669 * '_httpWait()' - Wait for data available on a connection (no flush).
2672 int /* O - 1 if data is available, 0 otherwise */
2673 _httpWait(http_t
*http
, /* I - Connection to server */
2674 int msec
, /* I - Milliseconds to wait */
2675 int usessl
) /* I - Use SSL context? */
2678 struct pollfd pfd
; /* Polled file descriptor */
2680 fd_set input_set
; /* select() input set */
2681 struct timeval timeout
; /* Timeout */
2682 #endif /* HAVE_POLL */
2683 int nfds
; /* Result from select()/poll() */
2686 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2690 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2695 * Check the SSL/TLS buffers for data first...
2699 if (http
->tls
&& usessl
)
2702 if (SSL_pending(http
->tls
))
2704 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2708 # elif defined(HAVE_GNUTLS)
2709 if (gnutls_record_check_pending(http
->tls
))
2711 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2715 # elif defined(HAVE_CDSASSL)
2716 size_t bytes
; /* Bytes that are available */
2718 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2721 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2724 # endif /* HAVE_LIBSSL */
2726 #endif /* HAVE_SSL */
2729 * Then try doing a select() or poll() to poll the socket...
2734 pfd
.events
= POLLIN
;
2736 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2737 (errno
== EINTR
|| errno
== EAGAIN
));
2742 FD_ZERO(&input_set
);
2743 FD_SET(http
->fd
, &input_set
);
2745 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2749 timeout
.tv_sec
= msec
/ 1000;
2750 timeout
.tv_usec
= (msec
% 1000) * 1000;
2752 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2755 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2757 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2760 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2761 WSAGetLastError() == WSAEWOULDBLOCK
));
2763 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2765 #endif /* HAVE_POLL */
2767 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2775 * 'httpWait()' - Wait for data available on a connection.
2777 * @since CUPS 1.1.19/Mac OS X 10.3@
2780 int /* O - 1 if data is available, 0 otherwise */
2781 httpWait(http_t
*http
, /* I - Connection to server */
2782 int msec
) /* I - Milliseconds to wait */
2785 * First see if there is data in the buffer...
2795 * Flush pending data, if any...
2800 if (httpFlushWrite(http
) < 0)
2805 * If not, check the SSL/TLS buffers and do a select() on the connection...
2808 return (_httpWait(http
, msec
, 1));
2813 * 'httpWrite()' - Write data to a HTTP connection.
2815 * This function is deprecated. Use the httpWrite2() function which can
2816 * write more than 2GB of data.
2821 int /* O - Number of bytes written */
2822 httpWrite(http_t
*http
, /* I - Connection to server */
2823 const char *buffer
, /* I - Buffer for data */
2824 int length
) /* I - Number of bytes to write */
2826 return ((int)httpWrite2(http
, buffer
, length
));
2831 * 'httpWrite2()' - Write data to a HTTP connection.
2833 * @since CUPS 1.2/Mac OS X 10.5@
2836 ssize_t
/* O - Number of bytes written */
2837 httpWrite2(http_t
*http
, /* I - Connection to server */
2838 const char *buffer
, /* I - Buffer for data */
2839 size_t length
) /* I - Number of bytes to write */
2841 ssize_t bytes
; /* Bytes written */
2844 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
2845 buffer
, CUPS_LLCAST length
));
2848 * Range check input...
2851 if (http
== NULL
|| buffer
== NULL
)
2855 * Mark activity on the connection...
2858 http
->activity
= time(NULL
);
2861 * Buffer small writes for better performance...
2866 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
2868 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
2869 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
2871 httpFlushWrite(http
);
2874 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
2875 length
< sizeof(http
->wbuffer
))
2878 * Write to buffer...
2881 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
2882 CUPS_LLCAST length
));
2884 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
2885 http
->wused
+= (int)length
;
2886 bytes
= (ssize_t
)length
;
2891 * Otherwise write the data directly...
2894 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
2895 CUPS_LLCAST length
));
2897 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2898 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
2900 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
2902 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
2903 CUPS_LLCAST bytes
));
2906 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
2907 http
->data_remaining
-= bytes
;
2913 * Handle end-of-request processing...
2916 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
2917 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
2920 * Finished with the transfer; unless we are sending POST or PUT
2924 DEBUG_puts("2httpWrite: changing states...");
2927 httpFlushWrite(http
);
2929 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2932 * Send a 0-length chunk at the end of the request...
2935 http_write(http
, "0\r\n\r\n", 5);
2938 * Reset the data state...
2941 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
2942 http
->data_remaining
= 0;
2945 if (http
->state
== HTTP_POST_RECV
)
2947 else if (http
->state
== HTTP_PUT_RECV
)
2948 http
->state
= HTTP_STATUS
;
2950 http
->state
= HTTP_WAITING
;
2957 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2959 * '_httpWriteCDSA()' - Write function for the CDSA library.
2962 OSStatus
/* O - -1 on error, 0 on success */
2964 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2965 const void *data
, /* I - Data buffer */
2966 size_t *dataLength
) /* IO - Number of bytes */
2968 OSStatus result
; /* Return value */
2969 ssize_t bytes
; /* Number of bytes read */
2970 http_t
*http
; /* HTTP connection */
2973 http
= (http_t
*)connection
;
2977 bytes
= write(http
->fd
, data
, *dataLength
);
2979 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2981 if (bytes
== *dataLength
)
2985 else if (bytes
>= 0)
2987 *dataLength
= bytes
;
2988 result
= errSSLWouldBlock
;
2994 if (errno
== EAGAIN
)
2995 result
= errSSLWouldBlock
;
2997 result
= errSSLClosedAbort
;
3002 #endif /* HAVE_SSL && HAVE_CDSASSL */
3005 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3007 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3010 ssize_t
/* O - Number of bytes written or -1 on error */
3012 gnutls_transport_ptr ptr
, /* I - Connection to server */
3013 const void *data
, /* I - Data buffer */
3014 size_t length
) /* I - Number of bytes to write */
3016 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
3018 #endif /* HAVE_SSL && HAVE_GNUTLS */
3021 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3023 * 'http_bio_ctrl()' - Control the HTTP connection.
3026 static long /* O - Result/data */
3027 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3028 int cmd
, /* I - Control command */
3029 long arg1
, /* I - First argument */
3030 void *arg2
) /* I - Second argument */
3037 case BIO_CTRL_RESET
:
3041 case BIO_C_SET_FILE_PTR
:
3046 case BIO_C_GET_FILE_PTR
:
3049 *((void **)arg2
) = h
->ptr
;
3056 case BIO_CTRL_FLUSH
:
3063 * 'http_bio_free()' - Free OpenSSL data.
3066 static int /* O - 1 on success, 0 on failure */
3067 http_bio_free(BIO
*h
) /* I - BIO data */
3083 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3086 static int /* O - 1 on success, 0 on failure */
3087 http_bio_new(BIO
*h
) /* I - BIO data */
3102 * 'http_bio_puts()' - Send a string for OpenSSL.
3105 static int /* O - Bytes written */
3106 http_bio_puts(BIO
*h
, /* I - BIO data */
3107 const char *str
) /* I - String to write */
3110 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3112 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3118 * 'http_bio_read()' - Read data for OpenSSL.
3121 static int /* O - Bytes read */
3122 http_bio_read(BIO
*h
, /* I - BIO data */
3123 char *buf
, /* I - Buffer */
3124 int size
) /* I - Number of bytes to read */
3126 http_t
*http
; /* HTTP connection */
3129 http
= (http_t
*)h
->ptr
;
3131 if (!http
->blocking
)
3134 * Make sure we have data before we read...
3137 if (!_httpWait(http
, 10000, 0))
3140 http
->error
= WSAETIMEDOUT
;
3142 http
->error
= ETIMEDOUT
;
3149 return (recv(http
->fd
, buf
, size
, 0));
3154 * 'http_bio_write()' - Write data for OpenSSL.
3157 static int /* O - Bytes written */
3158 http_bio_write(BIO
*h
, /* I - BIO data */
3159 const char *buf
, /* I - Buffer to write */
3160 int num
) /* I - Number of bytes to write */
3162 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3164 #endif /* HAVE_SSL && HAVE_LIBSSL */
3169 * 'http_debug_hex()' - Do a hex dump of a buffer.
3173 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3174 const char *buffer
, /* I - Buffer to dump */
3175 int bytes
) /* I - Bytes to dump */
3177 int i
, j
, /* Looping vars */
3178 ch
; /* Current character */
3179 char line
[255], /* Line buffer */
3180 *start
, /* Start of line after prefix */
3181 *ptr
; /* Pointer into line */
3184 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3187 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
3189 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3190 start
= line
+ strlen(line
);
3192 for (i
= 0; i
< bytes
; i
+= 16)
3194 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3195 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3207 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3209 ch
= buffer
[i
+ j
] & 255;
3211 if (ch
< ' ' || ch
>= 127)
3225 * 'http_field()' - Return the field index for a field name.
3228 static http_field_t
/* O - Field index */
3229 http_field(const char *name
) /* I - String name */
3231 int i
; /* Looping var */
3234 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3235 if (strcasecmp(name
, http_fields
[i
]) == 0)
3236 return ((http_field_t
)i
);
3238 return (HTTP_FIELD_UNKNOWN
);
3244 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3247 static int /* O - Bytes read */
3248 http_read_ssl(http_t
*http
, /* I - Connection to server */
3249 char *buf
, /* I - Buffer to store data */
3250 int len
) /* I - Length of buffer */
3252 # if defined(HAVE_LIBSSL)
3253 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3255 # elif defined(HAVE_GNUTLS)
3256 ssize_t result
; /* Return value */
3259 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3261 if (result
< 0 && !errno
)
3264 * Convert GNU TLS error to errno value...
3269 case GNUTLS_E_INTERRUPTED
:
3273 case GNUTLS_E_AGAIN
:
3285 return ((int)result
);
3287 # elif defined(HAVE_CDSASSL)
3288 int result
; /* Return value */
3289 OSStatus error
; /* Error info */
3290 size_t processed
; /* Number of bytes processed */
3293 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3298 result
= (int)processed
;
3300 case errSSLClosedGraceful
:
3303 case errSSLWouldBlock
:
3305 result
= (int)processed
;
3319 # elif defined(HAVE_SSPISSL)
3320 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3321 # endif /* HAVE_LIBSSL */
3323 #endif /* HAVE_SSL */
3328 * 'http_locking_cb()' - Lock/unlock a thread's mutex.
3332 http_locking_cb(int mode
, /* I - Lock mode */
3333 int type
, /* I - Lock type */
3334 const char *file
, /* I - Source file */
3335 int line
) /* I - Line number */
3337 if (mode
& CRYPTO_LOCK
)
3338 _cupsMutexLock(http_locks
+ type
);
3340 _cupsMutexUnlock(http_locks
+ type
);
3342 #endif /* HAVE_LIBSSL */
3346 * 'http_send()' - Send a request with all fields and the trailing blank line.
3349 static int /* O - 0 on success, non-zero on error */
3350 http_send(http_t
*http
, /* I - Connection to server */
3351 http_state_t request
, /* I - Request code */
3352 const char *uri
) /* I - URI */
3354 int i
; /* Looping var */
3355 char buf
[1024]; /* Encoded URI buffer */
3356 static const char * const codes
[] =
3357 { /* Request code strings */
3374 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3375 http
, codes
[request
], uri
));
3377 if (http
== NULL
|| uri
== NULL
)
3381 * Set the User-Agent field if it isn't already...
3384 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3385 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3388 * Encode the URI as needed...
3391 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3394 * See if we had an error the last time around; if so, reconnect...
3397 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3398 if (httpReconnect(http
))
3402 * Flush any written data that is pending...
3407 if (httpFlushWrite(http
) < 0)
3408 if (httpReconnect(http
))
3413 * Send the request header...
3416 http
->state
= request
;
3417 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3419 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3422 http
->status
= HTTP_CONTINUE
;
3425 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3427 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3428 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3430 #endif /* HAVE_SSL */
3432 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3434 http
->status
= HTTP_ERROR
;
3438 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3439 if (http
->fields
[i
][0] != '\0')
3441 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3442 httpGetField(http
, i
)));
3444 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3445 httpGetField(http
, i
)) < 1)
3447 http
->status
= HTTP_ERROR
;
3453 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3455 http
->status
= HTTP_ERROR
;
3459 if (http
->expect
== HTTP_CONTINUE
&&
3460 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3461 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3463 http
->status
= HTTP_ERROR
;
3467 if (httpPrintf(http
, "\r\n") < 1)
3469 http
->status
= HTTP_ERROR
;
3473 if (httpFlushWrite(http
) < 0)
3476 httpGetLength2(http
);
3477 httpClearFields(http
);
3480 * The Kerberos and AuthRef authentication strings can only be used once...
3483 if (http
->field_authorization
&& http
->authstring
&&
3484 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3485 !strncmp(http
->authstring
, "AuthRef", 7)))
3487 http
->_authstring
[0] = '\0';
3489 if (http
->authstring
!= http
->_authstring
)
3490 free(http
->authstring
);
3492 http
->authstring
= http
->_authstring
;
3501 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3504 static int /* O - Status of connection */
3505 http_set_credentials(http_t
*http
) /* I - Connection to server */
3507 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3508 # ifdef HAVE_CDSASSL
3509 OSStatus error
= 0; /* Error code */
3510 http_tls_credentials_t credentials
= NULL
;
3511 /* TLS credentials */
3512 # endif /* HAVE_CDSASSL */
3515 DEBUG_printf(("7http_set_credentials(%p)", http
));
3520 # elif defined(HAVE_GNUTLS)
3523 # elif defined(HAVE_CDSASSL)
3525 * Prefer connection specific credentials...
3528 if ((credentials
= http
->tls_credentials
) == NULL
)
3529 credentials
= cg
->tls_credentials
;
3531 # if HAVE_SECPOLICYCREATESSL
3533 * Otherwise root around in the user's keychain to see if one can be found...
3538 CFDictionaryRef query
; /* Query dictionary */
3539 CFTypeRef matches
= NULL
; /* Matching credentials */
3540 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3541 CFTypeRef keys
[] = { kSecClass
,
3544 /* Keys for dictionary */
3545 CFTypeRef values
[] = { kSecClassCertificate
,
3548 /* Values for dictionary */
3551 * Get the names associated with the server.
3554 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3556 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3562 * Create a query which will return all identities that can sign and match
3563 * the passed in policy.
3566 query
= CFDictionaryCreate(NULL
,
3567 (const void**)(&keys
[0]),
3568 (const void**)(&values
[0]),
3569 sizeof(keys
) / sizeof(keys
[0]),
3570 &kCFTypeDictionaryKeyCallBacks
,
3571 &kCFTypeDictionaryValueCallBacks
);
3574 error
= SecItemCopyMatching(query
, &matches
);
3575 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3584 CFRelease(dn_array
);
3586 # endif /* HAVE_SECPOLICYCREATESSL */
3590 error
= SSLSetCertificate(http
->tls
, credentials
);
3591 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3595 DEBUG_puts("4http_set_credentials: No credentials to set.");
3599 # elif defined(HAVE_SSPISSL)
3601 # endif /* HAVE_LIBSSL */
3606 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3609 static int /* O - Status of connection */
3610 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3612 _cups_globals_t
*cg
= _cupsGlobals();
3613 /* Pointer to library globals */
3614 int any_root
; /* Allow any root */
3617 SSL_CTX
*context
; /* Context for encryption */
3618 BIO
*bio
; /* BIO data */
3619 # elif defined(HAVE_GNUTLS)
3620 gnutls_certificate_client_credentials
*credentials
;
3621 /* TLS credentials */
3622 # elif defined(HAVE_CDSASSL)
3623 OSStatus error
; /* Error code */
3624 const char *message
= NULL
; /* Error message */
3625 cups_array_t
*credentials
; /* Credentials array */
3626 char *hostname
; /* Hostname */
3627 cups_array_t
*names
; /* CUPS distinguished names */
3628 CFArrayRef dn_array
; /* CF distinguished names array */
3629 CFIndex count
; /* Number of credentials */
3630 CFDataRef data
; /* Certificate data */
3631 int i
; /* Looping var */
3633 *credential
; /* Credential data */
3634 # elif defined(HAVE_SSPISSL)
3635 TCHAR username
[256]; /* Username returned from GetUserName() */
3636 TCHAR commonName
[256]; /* Common name for certificate */
3637 DWORD dwSize
; /* 32 bit size */
3638 # endif /* HAVE_LIBSSL */
3641 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3644 * Always allow self-signed certificates for the local loopback address...
3647 if (httpAddrLocalhost(http
->hostaddr
))
3650 any_root
= cg
->any_root
;
3653 context
= SSL_CTX_new(SSLv23_client_method());
3655 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3657 bio
= BIO_new(_httpBIOMethods());
3658 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3660 http
->tls
= SSL_new(context
);
3661 SSL_set_bio(http
->tls_credentials
, bio
, bio
);
3663 if (SSL_connect(http
->tls
) != 1)
3666 unsigned long error
; /* Error code */
3668 while ((error
= ERR_get_error()) != 0)
3669 DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error
, NULL
)));
3672 SSL_CTX_free(context
);
3673 SSL_free(http
->tls
);
3677 http
->error
= WSAGetLastError();
3679 http
->error
= errno
;
3681 http
->status
= HTTP_ERROR
;
3683 return (HTTP_ERROR
);
3686 # elif defined(HAVE_GNUTLS)
3687 credentials
= (gnutls_certificate_client_credentials
*)
3688 malloc(sizeof(gnutls_certificate_client_credentials
));
3689 if (credentials
== NULL
)
3691 http
->error
= errno
;
3692 http
->status
= HTTP_ERROR
;
3697 gnutls_certificate_allocate_credentials(credentials
);
3699 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3700 gnutls_set_default_priority(http
->tls
);
3701 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3702 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3703 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3704 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3706 if ((gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3708 http
->error
= errno
;
3709 http
->status
= HTTP_ERROR
;
3711 gnutls_deinit(http
->tls
);
3712 gnutls_certificate_free_credentials(*credentials
);
3719 http
->tls_credentials
= credentials
;
3721 # elif defined(HAVE_CDSASSL)
3722 if ((error
= SSLNewContext(false, &http
->tls
)))
3724 http
->error
= error
;
3725 http
->status
= HTTP_ERROR
;
3730 error
= SSLSetConnection(http
->tls
, http
);
3731 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
3735 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
3736 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
3741 error
= SSLSetProtocolVersionEnabled(http
->tls
, kSSLProtocol2
, false);
3742 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionEnabled, error=%d",
3748 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
3749 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
3750 any_root
, (int)error
));
3755 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
3756 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
3757 cg
->expired_certs
, (int)error
));
3762 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
3763 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
3764 cg
->expired_root
, (int)error
));
3769 if (cg
->client_cert_cb
)
3771 error
= SSLSetSessionOption(http
->tls
,
3772 kSSLSessionOptionBreakOnCertRequested
, true);
3773 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
3774 "error=%d", (int)error
));
3778 error
= http_set_credentials(http
);
3779 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
3785 * If there's a server certificate callback installed let it evaluate the
3786 * certificate(s) during the handshake...
3789 if (!error
&& cg
->server_cert_cb
!= NULL
)
3791 error
= SSLSetEnableCertVerify(http
->tls
, false);
3792 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
3797 error
= SSLSetSessionOption(http
->tls
,
3798 kSSLSessionOptionBreakOnServerAuth
, true);
3799 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
3800 "error=%d", (int)error
));
3806 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
3807 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
3809 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
3815 int done
= 0; /* Are we done yet? */
3817 while (!error
&& !done
)
3819 error
= SSLHandshake(http
->tls
);
3821 DEBUG_printf(("4_httpWait: SSLHandshake returned %d.", (int)error
));
3829 case errSSLWouldBlock
:
3833 case errSSLServerAuthCompleted
:
3835 if (cg
->server_cert_cb
)
3837 error
= httpCopyCredentials(http
, &credentials
);
3840 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
3841 cg
->server_cert_data
);
3842 httpFreeCredentials(credentials
);
3845 DEBUG_printf(("4_httpWait: Server certificate callback returned "
3846 "%d.", (int)error
));
3850 case errSSLClientCertRequested
:
3853 if (cg
->client_cert_cb
)
3856 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
3859 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
3861 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
3863 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
3865 if ((credential
= malloc(sizeof(*credential
))))
3867 credential
->datalen
= CFDataGetLength(data
);
3868 if ((credential
->data
= malloc(credential
->datalen
)))
3870 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
3871 credential
->datalen
);
3872 cupsArrayAdd(names
, credential
);
3878 CFRelease(dn_array
);
3883 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
3884 cg
->client_cert_data
);
3886 DEBUG_printf(("4_httpWait: Client certificate callback "
3887 "returned %d.", (int)error
));
3890 httpFreeCredentials(names
);
3894 case errSSLUnknownRootCert
:
3895 message
= _("Unable to establish a secure connection to host "
3896 "(untrusted certificate).");
3899 case errSSLNoRootCert
:
3900 message
= _("Unable to establish a secure connection to host "
3901 "(self-signed certificate).");
3904 case errSSLCertExpired
:
3905 message
= _("Unable to establish a secure connection to host "
3906 "(expired certificate).");
3909 case errSSLCertNotYetValid
:
3910 message
= _("Unable to establish a secure connection to host "
3911 "(certificate not yet valid).");
3914 case errSSLHostNameMismatch
:
3915 message
= _("Unable to establish a secure connection to host "
3916 "(host name mismatch).");
3919 case errSSLXCertChainInvalid
:
3920 message
= _("Unable to establish a secure connection to host "
3921 "(certificate chain invalid).");
3924 case errSSLConnectionRefused
:
3925 message
= _("Unable to establish a secure connection to host "
3926 "(peer dropped connection before responding).");
3937 http
->error
= error
;
3938 http
->status
= HTTP_ERROR
;
3939 errno
= ECONNREFUSED
;
3941 SSLDisposeContext(http
->tls
);
3945 * If an error string wasn't set by the callbacks use a generic one...
3949 #ifdef HAVE_CSSMERRORSTRING
3950 message
= cssmErrorString(error
);
3952 message
= _("Unable to establish a secure connection to host.");
3953 #endif /* HAVE_CSSMERRORSTRING */
3955 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
3960 # elif defined(HAVE_SSPISSL)
3961 http
->tls
= _sspiAlloc();
3966 http
->tls
->sock
= http
->fd
;
3967 dwSize
= sizeof(username
) / sizeof(TCHAR
);
3968 GetUserName(username
, &dwSize
);
3969 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
3970 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
3972 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
3975 _sspiFree(http
->tls_credentials
);
3976 http
->tls_credentials
= NULL
;
3980 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
3981 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
3983 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
3985 _sspiFree(http
->tls_credentials
);
3986 http
->tls_credentials
= NULL
;
3989 # endif /* HAVE_CDSASSL */
3993 #endif /* HAVE_SSL */
3998 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4002 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4005 SSL_CTX
*context
; /* Context for encryption */
4007 context
= SSL_get_SSL_CTX(http
->tls_credentials
);
4009 SSL_shutdown(http
->tls_credentials
);
4010 SSL_CTX_free(context
);
4011 SSL_free(http
->tls_credentials
);
4013 # elif defined(HAVE_GNUTLS)
4014 gnutls_certificate_client_credentials
*credentials
;
4015 /* TLS credentials */
4017 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4019 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4020 gnutls_deinit(http
->tls
);
4021 gnutls_certificate_free_credentials(*credentials
);
4024 # elif defined(HAVE_CDSASSL)
4025 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4028 SSLDisposeContext(http
->tls
);
4030 if (http
->tls_credentials
)
4031 CFRelease(http
->tls_credentials
);
4033 # elif defined(HAVE_SSPISSL)
4034 _sspiFree(http
->tls_credentials
);
4035 # endif /* HAVE_LIBSSL */
4038 http
->tls_credentials
= NULL
;
4040 #endif /* HAVE_SSL */
4045 * 'http_threadid_cb()' - Return the current thread ID.
4048 static unsigned long /* O - Thread ID */
4049 http_threadid_cb(void)
4051 # ifdef HAVE_PTHREAD_H
4052 return ((unsigned long)pthread_self());
4055 # endif /* HAVE_PTHREAD_H */
4057 #endif /* HAVE_LIBSSL */
4062 * 'http_upgrade()' - Force upgrade to TLS encryption.
4065 static int /* O - Status of connection */
4066 http_upgrade(http_t
*http
) /* I - Connection to server */
4068 int ret
; /* Return value */
4069 http_t myhttp
; /* Local copy of HTTP data */
4072 DEBUG_printf(("7http_upgrade(%p)", http
));
4075 * Flush the connection to make sure any previous "Upgrade" message
4082 * Copy the HTTP data to a local variable so we can do the OPTIONS
4083 * request without interfering with the existing request data...
4086 memcpy(&myhttp
, http
, sizeof(myhttp
));
4089 * Send an OPTIONS request to the server, requiring SSL or TLS
4090 * encryption on the link...
4093 http
->field_authorization
= NULL
; /* Don't free the auth string */
4095 httpClearFields(http
);
4096 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4097 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4099 if ((ret
= httpOptions(http
, "*")) == 0)
4102 * Wait for the secure connection...
4105 while (httpUpdate(http
) == HTTP_CONTINUE
);
4109 * Restore the HTTP request data...
4112 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4113 http
->data_encoding
= myhttp
.data_encoding
;
4114 http
->data_remaining
= myhttp
.data_remaining
;
4115 http
->_data_remaining
= myhttp
._data_remaining
;
4116 http
->expect
= myhttp
.expect
;
4117 http
->field_authorization
= myhttp
.field_authorization
;
4118 http
->digest_tries
= myhttp
.digest_tries
;
4121 * See if we actually went secure...
4127 * Server does not support HTTP upgrade...
4130 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4133 closesocket(http
->fd
);
4145 #endif /* HAVE_SSL */
4149 * 'http_write()' - Write a buffer to a HTTP connection.
4152 static int /* O - Number of bytes written */
4153 http_write(http_t
*http
, /* I - Connection to server */
4154 const char *buffer
, /* I - Buffer for data */
4155 int length
) /* I - Number of bytes to write */
4157 int tbytes
, /* Total bytes sent */
4158 bytes
; /* Bytes sent */
4161 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4170 bytes
= http_write_ssl(http
, buffer
, length
);
4172 #endif /* HAVE_SSL */
4173 bytes
= send(http
->fd
, buffer
, length
, 0);
4178 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
4180 else if (WSAGetLastError() != http
->error
&& WSAGetLastError() != WSAECONNRESET
)
4182 http
->error
= WSAGetLastError();
4186 if (errno
== EINTR
|| errno
== EAGAIN
)
4188 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4190 http
->error
= errno
;
4195 DEBUG_printf(("3http_write: error writing data (%s).",
4196 strerror(http
->error
)));
4207 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4210 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4217 * 'http_write_chunk()' - Write a chunked buffer.
4220 static int /* O - Number bytes written */
4221 http_write_chunk(http_t
*http
, /* I - Connection to server */
4222 const char *buffer
, /* I - Buffer to write */
4223 int length
) /* I - Length of buffer */
4225 char header
[255]; /* Chunk header */
4226 int bytes
; /* Bytes written */
4229 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4230 http
, buffer
, length
));
4233 * Write the chunk header, data, and trailer.
4236 sprintf(header
, "%x\r\n", length
);
4237 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4239 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4243 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4245 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4249 if (http_write(http
, "\r\n", 2) < 0)
4251 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4261 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4264 static int /* O - Bytes written */
4265 http_write_ssl(http_t
*http
, /* I - Connection to server */
4266 const char *buf
, /* I - Buffer holding data */
4267 int len
) /* I - Length of buffer */
4269 ssize_t result
; /* Return value */
4272 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4274 # if defined(HAVE_LIBSSL)
4275 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4277 # elif defined(HAVE_GNUTLS)
4278 result
= gnutls_record_send(http
->tls
, buf
, len
);
4280 if (result
< 0 && !errno
)
4283 * Convert GNU TLS error to errno value...
4288 case GNUTLS_E_INTERRUPTED
:
4292 case GNUTLS_E_AGAIN
:
4304 # elif defined(HAVE_CDSASSL)
4305 OSStatus error
; /* Error info */
4306 size_t processed
; /* Number of bytes processed */
4309 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4314 result
= (int)processed
;
4316 case errSSLClosedGraceful
:
4319 case errSSLWouldBlock
:
4321 result
= (int)processed
;
4333 # elif defined(HAVE_SSPISSL)
4334 return _sspiWrite((_sspi_struct_t
*) http
->tls
, (void*) buf
, len
);
4335 # endif /* HAVE_LIBSSL */
4337 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4339 return ((int)result
);
4341 #endif /* HAVE_SSL */
4345 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".