4 * HTTP routines for CUPS.
6 * Copyright 2007-2011 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * httpAddCredential() - Allocates and adds a single credential to an
24 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP
26 * httpBlocking() - Set blocking/non-blocking behavior on a
28 * httpCheck() - Check to see if there is a pending response
30 * httpClearCookie() - Clear the cookie value(s).
31 * httpClearFields() - Clear HTTP request fields.
32 * httpClose() - Close an HTTP connection.
33 * httpConnect() - Connect to a HTTP server.
34 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
35 * httpCopyCredentials() - Copy the credentials associated with an
36 * encrypted connection.
37 * _httpConvertCredentials() - Convert credentials to the internal format.
38 * _httpCreate() - Create an unconnected HTTP connection.
39 * httpDelete() - Send a DELETE request to the server.
40 * _httpDisconnect() - Disconnect a HTTP connection.
41 * httpEncryption() - Set the required encryption on the link.
42 * httpError() - Get the last error on a connection.
43 * httpFlush() - Flush data from a HTTP connection.
44 * httpFlushWrite() - Flush data in write buffer.
45 * _httpFreeCredentials() - Free internal credentials.
46 * httpFreeCredentials() - Free an array of credentials.
47 * httpGet() - Send a GET request to the server.
48 * httpGetAuthString() - Get the current authorization string.
49 * httpGetBlocking() - Get the blocking/non-block state of a
51 * httpGetCookie() - Get any cookie data from the response.
52 * httpGetFd() - Get the file descriptor associated with a
54 * httpGetField() - Get a field value from a request/response.
55 * httpGetLength() - Get the amount of data remaining from the
56 * content-length or transfer-encoding fields.
57 * httpGetLength2() - Get the amount of data remaining from the
58 * content-length or transfer-encoding fields.
59 * httpGetStatus() - Get the status of the last HTTP request.
60 * httpGetSubField() - Get a sub-field value.
61 * httpGetSubField2() - Get a sub-field value.
62 * httpGets() - Get a line of text from a HTTP connection.
63 * httpHead() - Send a HEAD request to the server.
64 * httpInitialize() - Initialize the HTTP interface library and set
65 * the default HTTP proxy (if any).
66 * httpOptions() - Send an OPTIONS request to the server.
67 * _httpPeek() - Peek at data from a HTTP connection.
68 * httpPost() - Send a POST request to the server.
69 * httpPrintf() - Print a formatted string to a HTTP connection.
70 * httpPut() - Send a PUT request to the server.
71 * httpRead() - Read data from a HTTP connection.
72 * httpRead2() - Read data from a HTTP connection.
73 * _httpReadCDSA() - Read function for the CDSA library.
74 * _httpReadGNUTLS() - Read function for the GNU TLS library.
75 * httpReconnect() - Reconnect to a HTTP server.
76 * httpSetAuthString() - Set the current authorization string.
77 * httpSetCredentials() - Set the credentials associated with an
78 * encrypted connection.
79 * httpSetCookie() - Set the cookie value(s).
80 * httpSetExpect() - Set the Expect: header in a request.
81 * httpSetField() - Set the value of an HTTP header.
82 * httpSetLength() - Set the content-length and content-encoding.
83 * _httpSetTimeout() - Set read/write timeouts and an optional
85 * httpTrace() - Send an TRACE request to the server.
86 * _httpUpdate() - Update the current HTTP status for incoming
88 * httpUpdate() - Update the current HTTP state for incoming
90 * _httpWait() - Wait for data available on a connection (no
92 * httpWait() - Wait for data available on a connection.
93 * httpWrite() - Write data to a HTTP connection.
94 * httpWrite2() - Write data to a HTTP connection.
95 * _httpWriteCDSA() - Write function for the CDSA library.
96 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
97 * http_bio_ctrl() - Control the HTTP connection.
98 * http_bio_free() - Free OpenSSL data.
99 * http_bio_new() - Initialize an OpenSSL BIO structure.
100 * http_bio_puts() - Send a string for OpenSSL.
101 * http_bio_read() - Read data for OpenSSL.
102 * http_bio_write() - Write data for OpenSSL.
103 * http_debug_hex() - Do a hex dump of a buffer.
104 * http_field() - Return the field index for a field name.
105 * http_read_ssl() - Read from a SSL/TLS connection.
106 * http_locking_cb() - Lock/unlock a thread's mutex.
107 * http_send() - Send a request with all fields and the trailing
109 * http_set_credentials() - Set the SSL/TLS credentials.
110 * http_setup_ssl() - Set up SSL/TLS support on a connection.
111 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
112 * http_threadid_cb() - Return the current thread ID.
113 * http_upgrade() - Force upgrade to TLS encryption.
114 * http_write() - Write a buffer to a HTTP connection.
115 * http_write_chunk() - Write a chunked buffer.
116 * http_write_ssl() - Write to a SSL/TLS connection.
120 * Include necessary headers...
123 #include "cups-private.h"
129 # include <sys/time.h>
130 # include <sys/resource.h>
133 # include <sys/poll.h>
134 #endif /* HAVE_POLL */
138 * Some operating systems have done away with the Fxxxx constants for
139 * the fcntl() call; this works around that "feature"...
143 # define FNONBLK O_NONBLOCK
144 #endif /* !FNONBLK */
152 static void http_debug_hex(const char *prefix
, const char *buffer
,
155 static http_field_t
http_field(const char *name
);
156 static int http_send(http_t
*http
, http_state_t request
,
158 static int http_write(http_t
*http
, const char *buffer
,
160 static int http_write_chunk(http_t
*http
, const char *buffer
,
163 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
164 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
165 static int http_set_credentials(http_t
*http
);
166 # endif /* HAVE_CDSASSL ** HAVE_SECCERTIFICATECOPYDATA */
167 static int http_setup_ssl(http_t
*http
);
168 static void http_shutdown_ssl(http_t
*http
);
169 static int http_upgrade(http_t
*http
);
170 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
171 #endif /* HAVE_SSL */
178 static const char * const http_fields
[] =
195 "If-Unmodified-since",
209 static const char * const http_states
[] =
229 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
231 * BIO methods for OpenSSL...
234 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
235 static int http_bio_read(BIO
*h
, char *buf
, int size
);
236 static int http_bio_puts(BIO
*h
, const char *str
);
237 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
238 static int http_bio_new(BIO
*h
);
239 static int http_bio_free(BIO
*data
);
241 static BIO_METHOD http_bio_methods
=
248 NULL
, /* http_bio_gets, */
254 #endif /* HAVE_SSL && HAVE_LIBSSL */
258 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
260 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
265 int /* O - 0 on success, -1 on error */
267 cups_array_t
*credentials
, /* I - Credentials array */
268 const void *data
, /* I - PEM-encoded X.509 data */
269 size_t datalen
) /* I - Length of data */
271 http_credential_t
*credential
; /* Credential data */
274 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
276 credential
->datalen
= datalen
;
278 if ((credential
->data
= malloc(datalen
)) != NULL
)
280 memcpy(credential
->data
, data
, datalen
);
281 cupsArrayAdd(credentials
, credential
);
292 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
294 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
297 BIO_METHOD
* /* O - BIO methods for OpenSSL */
298 _httpBIOMethods(void)
300 return (&http_bio_methods
);
302 #endif /* HAVE_SSL && HAVE_LIBSSL */
306 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
310 httpBlocking(http_t
*http
, /* I - Connection to server */
311 int b
) /* I - 1 = blocking, 0 = non-blocking */
319 * 'httpCheck()' - Check to see if there is a pending response from the server.
322 int /* O - 0 = no data, 1 = data available */
323 httpCheck(http_t
*http
) /* I - Connection to server */
325 return (httpWait(http
, 0));
330 * 'httpClearCookie()' - Clear the cookie value(s).
332 * @since CUPS 1.1.19/Mac OS X 10.3@
336 httpClearCookie(http_t
*http
) /* I - Connection to server */
350 * 'httpClearFields()' - Clear HTTP request fields.
354 httpClearFields(http_t
*http
) /* I - Connection to server */
358 memset(http
->fields
, 0, sizeof(http
->fields
));
359 if (http
->hostname
[0] == '/')
360 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
362 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
364 if (http
->field_authorization
)
366 free(http
->field_authorization
);
367 http
->field_authorization
= NULL
;
370 http
->expect
= (http_status_t
)0;
376 * 'httpClose()' - Close an HTTP connection.
380 httpClose(http_t
*http
) /* I - Connection to server */
383 OM_uint32 minor_status
; /* Minor status code */
384 #endif /* HAVE_GSSAPI */
387 DEBUG_printf(("httpClose(http=%p)", http
));
390 * Range check input...
397 * Close any open connection...
400 _httpDisconnect(http
);
403 * Free memory used...
406 httpAddrFreeList(http
->addrlist
);
412 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
413 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
415 if (http
->gssname
!= GSS_C_NO_NAME
)
416 gss_release_name(&minor_status
, &http
->gssname
);
417 #endif /* HAVE_GSSAPI */
419 #ifdef HAVE_AUTHORIZATION_H
421 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
422 #endif /* HAVE_AUTHORIZATION_H */
424 httpClearFields(http
);
426 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
427 free(http
->authstring
);
434 * 'httpConnect()' - Connect to a HTTP server.
436 * This function is deprecated - use @link httpConnectEncrypt@ instead.
441 http_t
* /* O - New HTTP connection */
442 httpConnect(const char *host
, /* I - Host to connect to */
443 int port
) /* I - Port number */
445 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
450 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
453 http_t
* /* O - New HTTP connection */
455 const char *host
, /* I - Host to connect to */
456 int port
, /* I - Port number */
457 http_encryption_t encryption
) /* I - Type of encryption to use */
459 http_t
*http
; /* New HTTP connection */
462 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
463 host
, port
, encryption
));
466 * Create the HTTP structure...
469 if ((http
= _httpCreate(host
, port
, NULL
, encryption
, AF_UNSPEC
)) == NULL
)
473 * Connect to the remote system...
476 if (!httpReconnect(http
))
480 * Could not connect to any known address - bail out!
483 httpAddrFreeList(http
->addrlist
);
492 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
498 int /* O - Status of call (0 = success) */
500 http_t
*http
, /* I - Connection to server */
501 cups_array_t
**credentials
) /* O - Array of credentials */
504 # elif defined(HAVE_GNUTLS)
505 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
506 OSStatus error
; /* Error code */
507 CFIndex count
; /* Number of credentials */
508 CFArrayRef peerCerts
; /* Peer certificates */
509 SecCertificateRef secCert
; /* Certificate reference */
510 CFDataRef data
; /* Certificate data */
511 int i
; /* Looping var */
512 # elif defined(HAVE_SSPISSL)
513 # endif /* HAVE_LIBSSL */
519 if (!http
|| !http
->tls
|| !credentials
)
525 # elif defined(HAVE_GNUTLS)
528 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
529 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
531 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
533 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
535 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
536 if ((data
= SecCertificateCopyData(secCert
)))
538 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
539 CFDataGetLength(data
));
545 CFRelease(peerCerts
);
550 # elif defined(HAVE_SSPISSL)
555 # endif /* HAVE_LIBSSL */
560 * '_httpConvertCredentials()' - Convert credentials to the internal format.
563 http_tls_credentials_t
/* O - Internal credentials */
564 _httpConvertCredentials(
565 cups_array_t
*credentials
) /* I - Array of credentials */
573 # elif defined(HAVE_GNUTLS)
576 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
577 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
578 SecCertificateRef secCert
; /* Certificate reference */
579 CFDataRef data
; /* Credential data reference */
580 http_credential_t
*credential
; /* Credential data */
583 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
584 cupsArrayCount(credentials
),
585 &kCFTypeArrayCallBacks
)) == NULL
)
588 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
590 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
592 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
593 credential
->datalen
)))
595 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
598 CFArrayAppendValue(peerCerts
, secCert
);
608 # elif defined(HAVE_SSPISSL)
613 # endif /* HAVE_LIBSSL */
618 * '_httpCreate()' - Create an unconnected HTTP connection.
621 http_t
* /* O - HTTP connection */
623 const char *host
, /* I - Hostname */
624 int port
, /* I - Port number */
625 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
626 http_encryption_t encryption
, /* I - Encryption to use */
627 int family
) /* I - Address family or AF_UNSPEC */
629 http_t
*http
; /* New HTTP connection */
630 char service
[255]; /* Service name */
633 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
634 host
, port
, encryption
));
645 sprintf(service
, "%d", port
);
648 if ((addrlist
= httpAddrGetList(host
, family
, service
)) == NULL
)
652 * Allocate memory for the structure...
655 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
657 httpAddrFreeList(addrlist
);
662 * Initialize the HTTP data...
665 http
->activity
= time(NULL
);
666 http
->addrlist
= addrlist
;
670 http
->gssctx
= GSS_C_NO_CONTEXT
;
671 http
->gssname
= GSS_C_NO_NAME
;
672 #endif /* HAVE_GSSAPI */
673 http
->version
= HTTP_1_1
;
675 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
677 if (port
== 443) /* Always use encryption for https */
678 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
680 http
->encryption
= encryption
;
683 * Return the new structure...
691 * 'httpDelete()' - Send a DELETE request to the server.
694 int /* O - Status of call (0 = success) */
695 httpDelete(http_t
*http
, /* I - Connection to server */
696 const char *uri
) /* I - URI to delete */
698 return (http_send(http
, HTTP_DELETE
, uri
));
703 * '_httpDisconnect()' - Disconnect a HTTP connection.
707 _httpDisconnect(http_t
*http
) /* I - Connection to server */
711 http_shutdown_ssl(http
);
712 #endif /* HAVE_SSL */
715 closesocket(http
->fd
);
725 * 'httpEncryption()' - Set the required encryption on the link.
728 int /* O - -1 on error, 0 on success */
729 httpEncryption(http_t
*http
, /* I - Connection to server */
730 http_encryption_t e
) /* I - New encryption preference */
732 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
738 http
->encryption
= e
;
740 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
741 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
742 return (httpReconnect(http
));
743 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
744 return (http_upgrade(http
));
748 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
752 #endif /* HAVE_SSL */
757 * 'httpError()' - Get the last error on a connection.
760 int /* O - Error code (errno) value */
761 httpError(http_t
*http
) /* I - Connection to server */
764 return (http
->error
);
771 * 'httpFlush()' - Flush data from a HTTP connection.
775 httpFlush(http_t
*http
) /* I - Connection to server */
777 char buffer
[8192]; /* Junk buffer */
778 int blocking
; /* To block or not to block */
779 http_state_t oldstate
; /* Old state */
782 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
783 http_states
[http
->state
]));
786 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
789 blocking
= http
->blocking
;
793 * Read any data we can...
796 oldstate
= http
->state
;
797 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
800 * Restore blocking and reset the connection if we didn't get all of
801 * the remaining data...
804 http
->blocking
= blocking
;
806 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
809 * Didn't get the data back, so close the current connection.
812 http
->state
= HTTP_WAITING
;
816 http_shutdown_ssl(http
);
817 #endif /* HAVE_SSL */
820 closesocket(http
->fd
);
831 * 'httpFlushWrite()' - Flush data in write buffer.
833 * @since CUPS 1.2/Mac OS X 10.5@
836 int /* O - Bytes written or -1 on error */
837 httpFlushWrite(http_t
*http
) /* I - Connection to server */
839 int bytes
; /* Bytes written */
842 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
844 if (!http
|| !http
->wused
)
846 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
847 "1httpFlushWrite: No connection.");
851 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
852 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
854 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
858 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
865 * '_httpFreeCredentials()' - Free internal credentials.
869 _httpFreeCredentials(
870 http_tls_credentials_t credentials
) /* I - Internal credentials */
878 #elif defined(HAVE_GNUTLS)
881 #elif defined(HAVE_CDSASSL)
882 CFRelease(credentials
);
884 #elif defined(HAVE_SSPISSL)
887 #endif /* HAVE_LIBSSL */
892 * 'httpFreeCredentials()' - Free an array of credentials.
897 cups_array_t
*credentials
) /* I - Array of credentials */
899 http_credential_t
*credential
; /* Credential */
902 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
904 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
906 cupsArrayRemove(credentials
, credential
);
907 free((void *)credential
->data
);
911 cupsArrayDelete(credentials
);
916 * 'httpGet()' - Send a GET request to the server.
919 int /* O - Status of call (0 = success) */
920 httpGet(http_t
*http
, /* I - Connection to server */
921 const char *uri
) /* I - URI to get */
923 return (http_send(http
, HTTP_GET
, uri
));
928 * 'httpGetAuthString()' - Get the current authorization string.
930 * The authorization string is set by cupsDoAuthentication() and
931 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
932 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
935 * @since CUPS 1.3/Mac OS X 10.5@
938 char * /* O - Authorization string */
939 httpGetAuthString(http_t
*http
) /* I - Connection to server */
942 return (http
->authstring
);
949 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
951 * @since CUPS 1.2/Mac OS X 10.5@
954 int /* O - 1 if blocking, 0 if non-blocking */
955 httpGetBlocking(http_t
*http
) /* I - Connection to server */
957 return (http
? http
->blocking
: 0);
962 * 'httpGetCookie()' - Get any cookie data from the response.
964 * @since CUPS 1.1.19/Mac OS X 10.3@
967 const char * /* O - Cookie data or NULL */
968 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
970 return (http
? http
->cookie
: NULL
);
975 * 'httpGetFd()' - Get the file descriptor associated with a connection.
977 * @since CUPS 1.2/Mac OS X 10.5@
980 int /* O - File descriptor or -1 if none */
981 httpGetFd(http_t
*http
) /* I - Connection to server */
983 return (http
? http
->fd
: -1);
988 * 'httpGetField()' - Get a field value from a request/response.
991 const char * /* O - Field value */
992 httpGetField(http_t
*http
, /* I - Connection to server */
993 http_field_t field
) /* I - Field to get */
995 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
997 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
998 http
->field_authorization
)
1001 * Special case for WWW-Authenticate: as its contents can be
1002 * longer than HTTP_MAX_VALUE...
1005 return (http
->field_authorization
);
1008 return (http
->fields
[field
]);
1013 * 'httpGetLength()' - Get the amount of data remaining from the
1014 * content-length or transfer-encoding fields.
1016 * This function is deprecated and will not return lengths larger than
1017 * 2^31 - 1; use httpGetLength2() instead.
1022 int /* O - Content length */
1023 httpGetLength(http_t
*http
) /* I - Connection to server */
1026 * Get the read content length and return the 32-bit value.
1031 httpGetLength2(http
);
1033 return (http
->_data_remaining
);
1041 * 'httpGetLength2()' - Get the amount of data remaining from the
1042 * content-length or transfer-encoding fields.
1044 * This function returns the complete content length, even for
1045 * content larger than 2^31 - 1.
1047 * @since CUPS 1.2/Mac OS X 10.5@
1050 off_t
/* O - Content length */
1051 httpGetLength2(http_t
*http
) /* I - Connection to server */
1053 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1054 http_states
[http
->state
]));
1059 if (!strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1061 DEBUG_puts("4httpGetLength2: chunked request!");
1063 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1064 http
->data_remaining
= 0;
1068 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1071 * The following is a hack for HTTP servers that don't send a
1072 * content-length or transfer-encoding field...
1074 * If there is no content-length then the connection must close
1075 * after the transfer is complete...
1078 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1081 * Default content length is 0 for errors and 2^31-1 for other
1082 * successful requests...
1085 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
1086 http
->data_remaining
= 0;
1088 http
->data_remaining
= 2147483647;
1091 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1094 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1095 CUPS_LLCAST http
->data_remaining
));
1098 if (http
->data_remaining
<= INT_MAX
)
1099 http
->_data_remaining
= (int)http
->data_remaining
;
1101 http
->_data_remaining
= INT_MAX
;
1103 return (http
->data_remaining
);
1108 * 'httpGetStatus()' - Get the status of the last HTTP request.
1110 * @since CUPS 1.2/Mac OS X 10.5@
1113 http_status_t
/* O - HTTP status */
1114 httpGetStatus(http_t
*http
) /* I - Connection to server */
1116 return (http
? http
->status
: HTTP_ERROR
);
1121 * 'httpGetSubField()' - Get a sub-field value.
1126 char * /* O - Value or NULL */
1127 httpGetSubField(http_t
*http
, /* I - Connection to server */
1128 http_field_t field
, /* I - Field index */
1129 const char *name
, /* I - Name of sub-field */
1130 char *value
) /* O - Value string */
1132 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1137 * 'httpGetSubField2()' - Get a sub-field value.
1139 * @since CUPS 1.2/Mac OS X 10.5@
1142 char * /* O - Value or NULL */
1143 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1144 http_field_t field
, /* I - Field index */
1145 const char *name
, /* I - Name of sub-field */
1146 char *value
, /* O - Value string */
1147 int valuelen
) /* I - Size of value buffer */
1149 const char *fptr
; /* Pointer into field */
1150 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1151 *ptr
, /* Pointer into string buffer */
1152 *end
; /* End of value buffer */
1154 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1155 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1157 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1158 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1161 end
= value
+ valuelen
- 1;
1163 for (fptr
= http
->fields
[field
]; *fptr
;)
1166 * Skip leading whitespace...
1169 while (_cups_isspace(*fptr
))
1179 * Get the sub-field name...
1183 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1184 ptr
< (temp
+ sizeof(temp
) - 1);
1189 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1192 * Skip trailing chars up to the '='...
1195 while (_cups_isspace(*fptr
))
1205 * Skip = and leading whitespace...
1210 while (_cups_isspace(*fptr
))
1216 * Read quoted string...
1219 for (ptr
= value
, fptr
++;
1220 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1225 while (*fptr
&& *fptr
!= '\"')
1234 * Read unquoted string...
1238 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1243 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1247 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1250 * See if this is the one...
1253 if (!strcmp(name
, temp
))
1255 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1262 DEBUG_puts("3httpGetSubField2: Returning NULL");
1269 * 'httpGets()' - Get a line of text from a HTTP connection.
1272 char * /* O - Line or NULL */
1273 httpGets(char *line
, /* I - Line to read into */
1274 int length
, /* I - Max length of buffer */
1275 http_t
*http
) /* I - Connection to server */
1277 char *lineptr
, /* Pointer into line */
1278 *lineend
, /* End of line */
1279 *bufptr
, /* Pointer into input buffer */
1280 *bufend
; /* Pointer to end of buffer */
1281 int bytes
, /* Number of bytes read */
1282 eol
; /* End-of-line? */
1285 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1287 if (http
== NULL
|| line
== NULL
)
1291 * Read a line from the buffer...
1296 lineend
= line
+ length
- 1;
1299 while (lineptr
< lineend
)
1302 * Pre-load the buffer as needed...
1311 while (http
->used
== 0)
1314 * No newline; see if there is more data to be read...
1317 if (!_httpWait(http
, http
->blocking
? 30000 : 10000, 1))
1319 DEBUG_puts("3httpGets: Timed out!");
1321 http
->error
= WSAETIMEDOUT
;
1323 http
->error
= ETIMEDOUT
;
1330 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1331 HTTP_MAX_BUFFER
- http
->used
);
1333 #endif /* HAVE_SSL */
1334 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1335 HTTP_MAX_BUFFER
- http
->used
, 0);
1337 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1342 * Nope, can't get a line this time...
1346 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1348 if (WSAGetLastError() == WSAEINTR
)
1350 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1352 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1355 http
->error
= WSAGetLastError();
1357 else if (WSAGetLastError() != http
->error
)
1359 http
->error
= WSAGetLastError();
1364 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1368 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1370 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1372 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1375 http
->error
= errno
;
1377 else if (errno
!= http
->error
)
1379 http
->error
= errno
;
1386 else if (bytes
== 0)
1388 http
->error
= EPIPE
;
1394 * Yup, update the amount used...
1397 http
->used
+= bytes
;
1401 * Now copy as much of the current line as possible...
1404 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1405 lineptr
< lineend
&& bufptr
< bufend
;)
1407 if (*bufptr
== 0x0a)
1413 else if (*bufptr
== 0x0d)
1416 *lineptr
++ = *bufptr
++;
1419 http
->used
-= (int)(bufptr
- http
->buffer
);
1421 memmove(http
->buffer
, bufptr
, http
->used
);
1429 http
->activity
= time(NULL
);
1433 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1439 DEBUG_puts("3httpGets: No new line available!");
1446 * 'httpHead()' - Send a HEAD request to the server.
1449 int /* O - Status of call (0 = success) */
1450 httpHead(http_t
*http
, /* I - Connection to server */
1451 const char *uri
) /* I - URI for head */
1453 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1454 return (http_send(http
, HTTP_HEAD
, uri
));
1459 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1460 * default HTTP proxy (if any).
1464 httpInitialize(void)
1466 static int initialized
= 0; /* Have we been called before? */
1468 WSADATA winsockdata
; /* WinSock data */
1471 int i
; /* Looping var */
1472 unsigned char data
[1024]; /* Seed data */
1473 #endif /* HAVE_LIBSSL */
1479 _cupsGlobalUnlock();
1484 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1486 #elif !defined(SO_NOSIGPIPE)
1488 * Ignore SIGPIPE signals...
1492 sigset(SIGPIPE
, SIG_IGN
);
1494 # elif defined(HAVE_SIGACTION)
1495 struct sigaction action
; /* POSIX sigaction data */
1498 memset(&action
, 0, sizeof(action
));
1499 action
.sa_handler
= SIG_IGN
;
1500 sigaction(SIGPIPE
, &action
, NULL
);
1503 signal(SIGPIPE
, SIG_IGN
);
1504 # endif /* !SO_NOSIGPIPE */
1509 * Initialize GNU TLS...
1512 gnutls_global_init();
1514 #elif defined(HAVE_LIBSSL)
1516 * Initialize OpenSSL...
1519 SSL_load_error_strings();
1523 * Using the current time is a dubious random seed, but on some systems
1524 * it is the best we can do (on others, this seed isn't even used...)
1527 CUPS_SRAND(time(NULL
));
1529 for (i
= 0; i
< sizeof(data
); i
++)
1530 data
[i
] = CUPS_RAND();
1532 RAND_seed(data
, sizeof(data
));
1533 #endif /* HAVE_GNUTLS */
1536 _cupsGlobalUnlock();
1541 * 'httpOptions()' - Send an OPTIONS request to the server.
1544 int /* O - Status of call (0 = success) */
1545 httpOptions(http_t
*http
, /* I - Connection to server */
1546 const char *uri
) /* I - URI for options */
1548 return (http_send(http
, HTTP_OPTIONS
, uri
));
1553 * '_httpPeek()' - Peek at data from a HTTP connection.
1555 * This function copies available data from the given HTTP connection, reading
1556 * a buffer as needed. The data is still available for reading using
1557 * @link httpRead@ or @link httpRead2@.
1559 * For non-blocking connections the usual timeouts apply.
1562 ssize_t
/* O - Number of bytes copied */
1563 _httpPeek(http_t
*http
, /* I - Connection to server */
1564 char *buffer
, /* I - Buffer for data */
1565 size_t length
) /* I - Maximum number of bytes */
1567 ssize_t bytes
; /* Bytes read */
1568 char len
[32]; /* Length string */
1571 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1572 http
, buffer
, CUPS_LLCAST length
));
1574 if (http
== NULL
|| buffer
== NULL
)
1577 http
->activity
= time(NULL
);
1583 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1584 http
->data_remaining
<= 0)
1586 DEBUG_puts("2_httpPeek: Getting chunk length...");
1588 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1590 DEBUG_puts("1_httpPeek: Could not get length!");
1594 http
->data_remaining
= strtoll(len
, NULL
, 16);
1595 if (http
->data_remaining
< 0)
1597 DEBUG_puts("1_httpPeek: Negative chunk length!");
1602 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1603 CUPS_LLCAST http
->data_remaining
));
1605 if (http
->data_remaining
<= 0)
1608 * A zero-length chunk ends a transfer; unless we are reading POST
1612 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1613 httpGets(len
, sizeof(len
), http
);
1615 if (http
->state
== HTTP_POST_RECV
)
1618 http
->state
= HTTP_WAITING
;
1621 * Prevent future reads for this request...
1624 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1628 else if (length
> (size_t)http
->data_remaining
)
1629 length
= (size_t)http
->data_remaining
;
1631 if (http
->used
== 0)
1634 * Buffer small reads for better performance...
1637 if (!http
->blocking
&& !httpWait(http
, 10000))
1640 if (http
->data_remaining
> sizeof(http
->buffer
))
1641 bytes
= sizeof(http
->buffer
);
1643 bytes
= http
->data_remaining
;
1647 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1649 #endif /* HAVE_SSL */
1651 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1654 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1656 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1665 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1667 http
->error
= WSAGetLastError();
1671 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1673 http
->error
= errno
;
1680 http
->error
= EPIPE
;
1687 if (length
> (size_t)http
->used
)
1688 length
= (size_t)http
->used
;
1690 bytes
= (ssize_t
)length
;
1692 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1695 memcpy(buffer
, http
->buffer
, length
);
1703 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1706 http
->error
= WSAGetLastError();
1708 if (errno
== EINTR
|| errno
== EAGAIN
)
1711 http
->error
= errno
;
1714 else if (bytes
== 0)
1716 http
->error
= EPIPE
;
1721 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1729 * 'httpPost()' - Send a POST request to the server.
1732 int /* O - Status of call (0 = success) */
1733 httpPost(http_t
*http
, /* I - Connection to server */
1734 const char *uri
) /* I - URI for post */
1736 return (http_send(http
, HTTP_POST
, uri
));
1741 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1746 int /* O - Number of bytes written */
1747 httpPrintf(http_t
*http
, /* I - Connection to server */
1748 const char *format
, /* I - printf-style format string */
1749 ...) /* I - Additional args as needed */
1751 int bytes
; /* Number of bytes to write */
1752 char buf
[16384]; /* Buffer for formatted string */
1753 va_list ap
; /* Variable argument pointer */
1756 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1758 va_start(ap
, format
);
1759 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1762 DEBUG_printf(("3httpPrintf: %s", buf
));
1764 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1765 return (httpWrite2(http
, buf
, bytes
));
1770 DEBUG_puts("4httpPrintf: flushing existing data...");
1772 if (httpFlushWrite(http
) < 0)
1776 return (http_write(http
, buf
, bytes
));
1782 * 'httpPut()' - Send a PUT request to the server.
1785 int /* O - Status of call (0 = success) */
1786 httpPut(http_t
*http
, /* I - Connection to server */
1787 const char *uri
) /* I - URI to put */
1789 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1790 return (http_send(http
, HTTP_PUT
, uri
));
1795 * 'httpRead()' - Read data from a HTTP connection.
1797 * This function is deprecated. Use the httpRead2() function which can
1798 * read more than 2GB of data.
1803 int /* O - Number of bytes read */
1804 httpRead(http_t
*http
, /* I - Connection to server */
1805 char *buffer
, /* I - Buffer for data */
1806 int length
) /* I - Maximum number of bytes */
1808 return ((int)httpRead2(http
, buffer
, length
));
1813 * 'httpRead2()' - Read data from a HTTP connection.
1815 * @since CUPS 1.2/Mac OS X 10.5@
1818 ssize_t
/* O - Number of bytes read */
1819 httpRead2(http_t
*http
, /* I - Connection to server */
1820 char *buffer
, /* I - Buffer for data */
1821 size_t length
) /* I - Maximum number of bytes */
1823 ssize_t bytes
; /* Bytes read */
1824 char len
[32]; /* Length string */
1827 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1828 http
, buffer
, CUPS_LLCAST length
));
1830 if (http
== NULL
|| buffer
== NULL
)
1833 http
->activity
= time(NULL
);
1839 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1840 http
->data_remaining
<= 0)
1842 DEBUG_puts("2httpRead2: Getting chunk length...");
1844 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1846 DEBUG_puts("1httpRead2: Could not get length!");
1850 http
->data_remaining
= strtoll(len
, NULL
, 16);
1851 if (http
->data_remaining
< 0)
1853 DEBUG_puts("1httpRead2: Negative chunk length!");
1858 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1859 CUPS_LLCAST http
->data_remaining
));
1861 if (http
->data_remaining
<= 0)
1864 * A zero-length chunk ends a transfer; unless we are reading POST
1868 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1869 httpGets(len
, sizeof(len
), http
);
1871 if (http
->state
== HTTP_POST_RECV
)
1874 http
->state
= HTTP_WAITING
;
1877 * Prevent future reads for this request...
1880 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1884 else if (length
> (size_t)http
->data_remaining
)
1885 length
= (size_t)http
->data_remaining
;
1887 if (http
->used
== 0 && length
<= 256)
1890 * Buffer small reads for better performance...
1893 if (!http
->blocking
&& !httpWait(http
, 10000))
1896 if (http
->data_remaining
> sizeof(http
->buffer
))
1897 bytes
= sizeof(http
->buffer
);
1899 bytes
= http
->data_remaining
;
1903 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1905 #endif /* HAVE_SSL */
1907 DEBUG_printf(("2httpRead2: reading %d bytes from socket into buffer...",
1910 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1912 DEBUG_printf(("2httpRead2: read %d bytes from socket into buffer...",
1921 if (WSAGetLastError() != WSAEINTR
)
1923 http
->error
= WSAGetLastError();
1926 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1928 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1930 http
->error
= WSAEWOULDBLOCK
;
1935 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1937 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1939 http
->error
= errno
;
1942 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1944 http
->error
= errno
;
1948 else if (errno
!= EINTR
)
1950 http
->error
= errno
;
1957 http
->error
= EPIPE
;
1964 if (length
> (size_t)http
->used
)
1965 length
= (size_t)http
->used
;
1967 bytes
= (ssize_t
)length
;
1969 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
1972 memcpy(buffer
, http
->buffer
, length
);
1973 http
->used
-= (int)length
;
1976 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
1981 if (!http
->blocking
&& !httpWait(http
, 10000))
1984 bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
);
1986 #endif /* HAVE_SSL */
1989 if (!http
->blocking
&& !httpWait(http
, 10000))
1992 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
1993 CUPS_LLCAST length
));
1996 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
1998 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2000 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2003 else if (WSAGetLastError() != WSAEINTR
)
2007 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2009 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2011 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2013 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2016 else if (errno
!= EINTR
)
2021 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2022 CUPS_LLCAST bytes
));
2027 http
->data_remaining
-= bytes
;
2029 if (http
->data_remaining
<= INT_MAX
)
2030 http
->_data_remaining
= (int)http
->data_remaining
;
2032 http
->_data_remaining
= INT_MAX
;
2037 if (WSAGetLastError() == WSAEINTR
)
2040 http
->error
= WSAGetLastError();
2042 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2045 http
->error
= errno
;
2050 http
->error
= EPIPE
;
2054 if (http
->data_remaining
== 0)
2056 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2057 httpGets(len
, sizeof(len
), http
);
2059 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2061 if (http
->state
== HTTP_POST_RECV
)
2064 http
->state
= HTTP_WAITING
;
2069 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2076 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2078 * '_httpReadCDSA()' - Read function for the CDSA library.
2081 OSStatus
/* O - -1 on error, 0 on success */
2083 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2084 void *data
, /* I - Data buffer */
2085 size_t *dataLength
) /* IO - Number of bytes */
2087 OSStatus result
; /* Return value */
2088 ssize_t bytes
; /* Number of bytes read */
2089 http_t
*http
; /* HTTP connection */
2092 http
= (http_t
*)connection
;
2094 if (!http
->blocking
)
2097 * Make sure we have data before we read...
2100 if (!_httpWait(http
, 10000, 0))
2102 http
->error
= ETIMEDOUT
;
2109 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2111 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2113 if (bytes
== *dataLength
)
2119 *dataLength
= bytes
;
2120 result
= errSSLWouldBlock
;
2127 result
= errSSLClosedGraceful
;
2128 else if (errno
== EAGAIN
)
2129 result
= errSSLWouldBlock
;
2131 result
= errSSLClosedAbort
;
2136 #endif /* HAVE_SSL && HAVE_CDSASSL */
2139 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2141 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2144 ssize_t
/* O - Number of bytes read or -1 on error */
2146 gnutls_transport_ptr ptr
, /* I - Connection to server */
2147 void *data
, /* I - Buffer */
2148 size_t length
) /* I - Number of bytes to read */
2150 http_t
*http
; /* HTTP connection */
2153 http
= (http_t
*)ptr
;
2155 if (!http
->blocking
)
2158 * Make sure we have data before we read...
2161 if (!_httpWait(http
, 10000, 0))
2163 http
->error
= ETIMEDOUT
;
2168 return (recv(http
->fd
, data
, length
, 0));
2170 #endif /* HAVE_SSL && HAVE_GNUTLS */
2174 * 'httpReconnect()' - Reconnect to a HTTP server.
2177 int /* O - 0 on success, non-zero on failure */
2178 httpReconnect(http_t
*http
) /* I - Connection to server */
2180 http_addrlist_t
*addr
; /* Connected address */
2182 http_addrlist_t
*current
; /* Current address */
2183 char temp
[256]; /* Temporary address string */
2187 DEBUG_printf(("httpReconnect(http=%p)", http
));
2195 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2196 http_shutdown_ssl(http
);
2198 #endif /* HAVE_SSL */
2201 * Close any previously open socket...
2206 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2209 closesocket(http
->fd
);
2218 * Connect to the server...
2222 for (current
= http
->addrlist
; current
; current
= current
->next
)
2223 DEBUG_printf(("2httpReconnect: Address %s:%d",
2224 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2225 _httpAddrPort(&(current
->addr
))));
2228 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
2231 * Unable to connect...
2235 http
->error
= WSAGetLastError();
2237 http
->error
= errno
;
2239 http
->status
= HTTP_ERROR
;
2241 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2242 strerror(http
->error
)));
2247 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2249 if (http
->timeout_value
.tv_sec
> 0)
2252 DWORD timeout_value
= http
->timeout_value
.tv_sec
* 1000 +
2253 http
->timeout_value
.tv_usec
/ 1000;
2254 /* Timeout in milliseconds */
2256 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&timeout_value
,
2257 sizeof(timeout_value
));
2258 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&timeout_value
,
2259 sizeof(timeout_value
));
2261 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, &(http
->timeout_value
),
2262 sizeof(http
->timeout_value
));
2263 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, &(http
->timeout_value
),
2264 sizeof(http
->timeout_value
));
2268 http
->hostaddr
= &(addr
->addr
);
2270 http
->status
= HTTP_CONTINUE
;
2273 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2276 * Always do encryption via SSL.
2279 if (http_setup_ssl(http
) != 0)
2282 closesocket(http
->fd
);
2290 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2291 return (http_upgrade(http
));
2292 #endif /* HAVE_SSL */
2294 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2295 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2296 _httpAddrPort(http
->hostaddr
)));
2303 * 'httpSetAuthString()' - Set the current authorization string.
2305 * This function just stores a copy of the current authorization string in
2306 * the HTTP connection object. You must still call httpSetField() to set
2307 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2308 * httpHead(), httpOptions(), httpPost, or httpPut().
2310 * @since CUPS 1.3/Mac OS X 10.5@
2314 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2315 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2316 const char *data
) /* I - Auth data (NULL for none) */
2319 * Range check input...
2325 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2326 free(http
->authstring
);
2328 http
->authstring
= http
->_authstring
;
2333 * Set the current authorization string...
2336 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2339 if (len
> (int)sizeof(http
->_authstring
))
2341 if ((temp
= malloc(len
)) == NULL
)
2342 len
= sizeof(http
->_authstring
);
2344 http
->authstring
= temp
;
2348 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2350 strlcpy(http
->authstring
, scheme
, len
);
2355 * Clear the current authorization string...
2358 http
->_authstring
[0] = '\0';
2364 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2370 int /* O - Status of call (0 = success) */
2371 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2372 cups_array_t
*credentials
) /* I - Array of credentials */
2374 if (!http
|| cupsArrayCount(credentials
) < 1)
2377 _httpFreeCredentials(http
->tls_credentials
);
2379 http
->tls_credentials
= _httpConvertCredentials(credentials
);
2381 return (http
->tls_credentials
? 0 : -1);
2386 * 'httpSetCookie()' - Set the cookie value(s).
2388 * @since CUPS 1.1.19/Mac OS X 10.3@
2392 httpSetCookie(http_t
*http
, /* I - Connection */
2393 const char *cookie
) /* I - Cookie string */
2402 http
->cookie
= strdup(cookie
);
2404 http
->cookie
= NULL
;
2409 * 'httpSetExpect()' - Set the Expect: header in a request.
2411 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2413 * @since CUPS 1.2/Mac OS X 10.5@
2417 httpSetExpect(http_t
*http
, /* I - Connection to server */
2418 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2421 http
->expect
= expect
;
2426 * 'httpSetField()' - Set the value of an HTTP header.
2430 httpSetField(http_t
*http
, /* I - Connection to server */
2431 http_field_t field
, /* I - Field index */
2432 const char *value
) /* I - Value */
2435 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2436 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2440 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2442 if (field
== HTTP_FIELD_AUTHORIZATION
)
2445 * Special case for Authorization: as its contents can be
2446 * longer than HTTP_MAX_VALUE
2449 if (http
->field_authorization
)
2450 free(http
->field_authorization
);
2452 http
->field_authorization
= strdup(value
);
2454 else if (field
== HTTP_FIELD_HOST
)
2457 * Special-case for Host: as we don't want a trailing "." on the hostname and
2458 * need to bracket IPv6 numeric addresses.
2461 char *ptr
= strchr(value
, ':');
2463 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2466 * Bracket IPv6 numeric addresses...
2468 * This is slightly inefficient (basically copying twice), but is an edge
2469 * case and not worth optimizing...
2472 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2473 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2478 * Check for a trailing dot on the hostname...
2481 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2485 ptr
+= strlen(ptr
) - 1;
2496 * 'httpSetLength()' - Set the content-length and content-encoding.
2498 * @since CUPS 1.2/Mac OS X 10.5@
2502 httpSetLength(http_t
*http
, /* I - Connection to server */
2503 size_t length
) /* I - Length (0 for chunked) */
2510 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2511 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2515 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2516 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2517 CUPS_LLFMT
, CUPS_LLCAST length
);
2523 * '_httpSetTimeout()' - Set read/write timeouts and an optional callback.
2525 * The optional timeout callback receives both the HTTP connection and a user
2526 * data pointer and must return 1 to continue or 0 to error out.
2531 http_t
*http
, /* I - Connection to server */
2532 double timeout
, /* I - Number of seconds for timeout,
2533 must be greater than 0 */
2534 _http_timeout_cb_t cb
, /* I - Callback function or NULL */
2535 void *user_data
) /* I - User data pointer */
2537 if (!http
|| timeout
<= 0.0)
2540 http
->timeout_cb
= cb
;
2541 http
->timeout_data
= user_data
;
2542 http
->timeout_value
.tv_sec
= (int)timeout
;
2543 http
->timeout_value
.tv_usec
= (int)(timeout
* 1000000) % 1000000;
2548 DWORD timeout_value
= http
->timeout_value
.tv_sec
* 1000 +
2549 http
->timeout_value
.tv_usec
/ 1000;
2550 /* Timeout in milliseconds */
2552 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&timeout_value
,
2553 sizeof(timeout_value
));
2554 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&timeout_value
,
2555 sizeof(timeout_value
));
2557 setsockopt(http
->fd
, SOL_SOCKET
, SO_RCVTIMEO
, &(http
->timeout_value
),
2558 sizeof(http
->timeout_value
));
2559 setsockopt(http
->fd
, SOL_SOCKET
, SO_SNDTIMEO
, &(http
->timeout_value
),
2560 sizeof(http
->timeout_value
));
2567 * 'httpTrace()' - Send an TRACE request to the server.
2570 int /* O - Status of call (0 = success) */
2571 httpTrace(http_t
*http
, /* I - Connection to server */
2572 const char *uri
) /* I - URI for trace */
2574 return (http_send(http
, HTTP_TRACE
, uri
));
2579 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2581 * Note: Unlike httpUpdate(), this function does not flush pending write data
2582 * and only retrieves a single status line from the HTTP connection.
2585 int /* O - 1 to continue, 0 to stop */
2586 _httpUpdate(http_t
*http
, /* I - Connection to server */
2587 http_status_t
*status
) /* O - Current HTTP status */
2589 char line
[32768], /* Line from connection... */
2590 *value
; /* Pointer to value on line */
2591 http_field_t field
; /* Field index */
2592 int major
, minor
; /* HTTP version numbers */
2595 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2596 http_states
[http
->state
]));
2599 * Grab a single line from the connection...
2602 if (!httpGets(line
, sizeof(line
), http
))
2604 *status
= HTTP_ERROR
;
2608 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2610 if (line
[0] == '\0')
2613 * Blank line means the start of the data section (if any). Return
2614 * the result code, too...
2616 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2617 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2621 if (http
->status
== HTTP_CONTINUE
)
2623 *status
= http
->status
;
2627 if (http
->status
< HTTP_BAD_REQUEST
)
2628 http
->digest_tries
= 0;
2631 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2633 if (http_setup_ssl(http
) != 0)
2636 closesocket(http
->fd
);
2641 *status
= http
->status
= HTTP_ERROR
;
2645 *status
= HTTP_CONTINUE
;
2648 #endif /* HAVE_SSL */
2650 httpGetLength2(http
);
2652 switch (http
->state
)
2656 case HTTP_POST_RECV
:
2659 case HTTP_POST_SEND
:
2664 http
->state
= HTTP_WAITING
;
2668 *status
= http
->status
;
2671 else if (!strncmp(line
, "HTTP/", 5))
2674 * Got the beginning of a response...
2677 int intstatus
; /* Status value as an integer */
2679 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2681 *status
= http
->status
= HTTP_ERROR
;
2685 http
->version
= (http_version_t
)(major
* 100 + minor
);
2686 *status
= http
->status
= (http_status_t
)intstatus
;
2688 else if ((value
= strchr(line
, ':')) != NULL
)
2695 while (_cups_isspace(*value
))
2699 * Be tolerants of servers that send unknown attribute fields...
2702 if (!strcasecmp(line
, "expect"))
2705 * "Expect: 100-continue" or similar...
2708 http
->expect
= (http_status_t
)atoi(value
);
2710 else if (!strcasecmp(line
, "cookie"))
2713 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2716 httpSetCookie(http
, value
);
2718 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
2719 httpSetField(http
, field
, value
);
2722 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
2727 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
2728 *status
= http
->status
= HTTP_ERROR
;
2737 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2740 http_status_t
/* O - HTTP status */
2741 httpUpdate(http_t
*http
) /* I - Connection to server */
2743 http_status_t status
; /* Request status */
2746 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2747 http_states
[http
->state
]));
2750 * Flush pending data, if any...
2755 DEBUG_puts("2httpUpdate: flushing buffer...");
2757 if (httpFlushWrite(http
) < 0)
2758 return (HTTP_ERROR
);
2762 * If we haven't issued any commands, then there is nothing to "update"...
2765 if (http
->state
== HTTP_WAITING
)
2766 return (HTTP_CONTINUE
);
2769 * Grab all of the lines we can from the connection...
2772 while (_httpUpdate(http
, &status
));
2775 * See if there was an error...
2778 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2780 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2781 return (http
->status
);
2786 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2787 strerror(http
->error
)));
2788 http
->status
= HTTP_ERROR
;
2789 return (HTTP_ERROR
);
2793 * Return the current status...
2801 * '_httpWait()' - Wait for data available on a connection (no flush).
2804 int /* O - 1 if data is available, 0 otherwise */
2805 _httpWait(http_t
*http
, /* I - Connection to server */
2806 int msec
, /* I - Milliseconds to wait */
2807 int usessl
) /* I - Use SSL context? */
2810 struct pollfd pfd
; /* Polled file descriptor */
2812 fd_set input_set
; /* select() input set */
2813 struct timeval timeout
; /* Timeout */
2814 #endif /* HAVE_POLL */
2815 int nfds
; /* Result from select()/poll() */
2818 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2822 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2827 * Check the SSL/TLS buffers for data first...
2831 if (http
->tls
&& usessl
)
2834 if (SSL_pending(http
->tls
))
2836 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2840 # elif defined(HAVE_GNUTLS)
2841 if (gnutls_record_check_pending(http
->tls
))
2843 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2847 # elif defined(HAVE_CDSASSL)
2848 size_t bytes
; /* Bytes that are available */
2850 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2853 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2856 # endif /* HAVE_LIBSSL */
2858 #endif /* HAVE_SSL */
2861 * Then try doing a select() or poll() to poll the socket...
2866 pfd
.events
= POLLIN
;
2868 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2869 (errno
== EINTR
|| errno
== EAGAIN
));
2874 FD_ZERO(&input_set
);
2875 FD_SET(http
->fd
, &input_set
);
2877 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2881 timeout
.tv_sec
= msec
/ 1000;
2882 timeout
.tv_usec
= (msec
% 1000) * 1000;
2884 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2887 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2889 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2892 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2893 WSAGetLastError() == WSAEWOULDBLOCK
));
2895 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2897 #endif /* HAVE_POLL */
2899 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2907 * 'httpWait()' - Wait for data available on a connection.
2909 * @since CUPS 1.1.19/Mac OS X 10.3@
2912 int /* O - 1 if data is available, 0 otherwise */
2913 httpWait(http_t
*http
, /* I - Connection to server */
2914 int msec
) /* I - Milliseconds to wait */
2917 * First see if there is data in the buffer...
2920 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
2927 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
2932 * Flush pending data, if any...
2937 DEBUG_puts("3httpWait: Flushing write buffer.");
2939 if (httpFlushWrite(http
) < 0)
2944 * If not, check the SSL/TLS buffers and do a select() on the connection...
2947 return (_httpWait(http
, msec
, 1));
2952 * 'httpWrite()' - Write data to a HTTP connection.
2954 * This function is deprecated. Use the httpWrite2() function which can
2955 * write more than 2GB of data.
2960 int /* O - Number of bytes written */
2961 httpWrite(http_t
*http
, /* I - Connection to server */
2962 const char *buffer
, /* I - Buffer for data */
2963 int length
) /* I - Number of bytes to write */
2965 return ((int)httpWrite2(http
, buffer
, length
));
2970 * 'httpWrite2()' - Write data to a HTTP connection.
2972 * @since CUPS 1.2/Mac OS X 10.5@
2975 ssize_t
/* O - Number of bytes written */
2976 httpWrite2(http_t
*http
, /* I - Connection to server */
2977 const char *buffer
, /* I - Buffer for data */
2978 size_t length
) /* I - Number of bytes to write */
2980 ssize_t bytes
; /* Bytes written */
2983 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
2984 buffer
, CUPS_LLCAST length
));
2987 * Range check input...
2990 if (http
== NULL
|| buffer
== NULL
)
2994 * Mark activity on the connection...
2997 http
->activity
= time(NULL
);
3000 * Buffer small writes for better performance...
3005 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3007 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3008 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3010 httpFlushWrite(http
);
3013 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3014 length
< sizeof(http
->wbuffer
))
3017 * Write to buffer...
3020 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3021 CUPS_LLCAST length
));
3023 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3024 http
->wused
+= (int)length
;
3025 bytes
= (ssize_t
)length
;
3030 * Otherwise write the data directly...
3033 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3034 CUPS_LLCAST length
));
3036 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3037 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3039 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3041 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3042 CUPS_LLCAST bytes
));
3045 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3046 http
->data_remaining
-= bytes
;
3052 * Handle end-of-request processing...
3055 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3056 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3059 * Finished with the transfer; unless we are sending POST or PUT
3063 DEBUG_puts("2httpWrite: changing states...");
3066 httpFlushWrite(http
);
3068 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3071 * Send a 0-length chunk at the end of the request...
3074 http_write(http
, "0\r\n\r\n", 5);
3077 * Reset the data state...
3080 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3081 http
->data_remaining
= 0;
3089 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3091 * '_httpWriteCDSA()' - Write function for the CDSA library.
3094 OSStatus
/* O - -1 on error, 0 on success */
3096 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3097 const void *data
, /* I - Data buffer */
3098 size_t *dataLength
) /* IO - Number of bytes */
3100 OSStatus result
; /* Return value */
3101 ssize_t bytes
; /* Number of bytes read */
3102 http_t
*http
; /* HTTP connection */
3105 http
= (http_t
*)connection
;
3109 bytes
= write(http
->fd
, data
, *dataLength
);
3111 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3113 if (bytes
== *dataLength
)
3117 else if (bytes
>= 0)
3119 *dataLength
= bytes
;
3120 result
= errSSLWouldBlock
;
3126 if (errno
== EAGAIN
)
3127 result
= errSSLWouldBlock
;
3129 result
= errSSLClosedAbort
;
3134 #endif /* HAVE_SSL && HAVE_CDSASSL */
3137 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3139 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3142 ssize_t
/* O - Number of bytes written or -1 on error */
3144 gnutls_transport_ptr ptr
, /* I - Connection to server */
3145 const void *data
, /* I - Data buffer */
3146 size_t length
) /* I - Number of bytes to write */
3148 return (send(((http_t
*)ptr
)->fd
, data
, length
, 0));
3150 #endif /* HAVE_SSL && HAVE_GNUTLS */
3153 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3155 * 'http_bio_ctrl()' - Control the HTTP connection.
3158 static long /* O - Result/data */
3159 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3160 int cmd
, /* I - Control command */
3161 long arg1
, /* I - First argument */
3162 void *arg2
) /* I - Second argument */
3169 case BIO_CTRL_RESET
:
3173 case BIO_C_SET_FILE_PTR
:
3178 case BIO_C_GET_FILE_PTR
:
3181 *((void **)arg2
) = h
->ptr
;
3188 case BIO_CTRL_FLUSH
:
3195 * 'http_bio_free()' - Free OpenSSL data.
3198 static int /* O - 1 on success, 0 on failure */
3199 http_bio_free(BIO
*h
) /* I - BIO data */
3215 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3218 static int /* O - 1 on success, 0 on failure */
3219 http_bio_new(BIO
*h
) /* I - BIO data */
3234 * 'http_bio_puts()' - Send a string for OpenSSL.
3237 static int /* O - Bytes written */
3238 http_bio_puts(BIO
*h
, /* I - BIO data */
3239 const char *str
) /* I - String to write */
3242 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3244 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3250 * 'http_bio_read()' - Read data for OpenSSL.
3253 static int /* O - Bytes read */
3254 http_bio_read(BIO
*h
, /* I - BIO data */
3255 char *buf
, /* I - Buffer */
3256 int size
) /* I - Number of bytes to read */
3258 http_t
*http
; /* HTTP connection */
3261 http
= (http_t
*)h
->ptr
;
3263 if (!http
->blocking
)
3266 * Make sure we have data before we read...
3269 if (!_httpWait(http
, 10000, 0))
3272 http
->error
= WSAETIMEDOUT
;
3274 http
->error
= ETIMEDOUT
;
3281 return (recv(http
->fd
, buf
, size
, 0));
3286 * 'http_bio_write()' - Write data for OpenSSL.
3289 static int /* O - Bytes written */
3290 http_bio_write(BIO
*h
, /* I - BIO data */
3291 const char *buf
, /* I - Buffer to write */
3292 int num
) /* I - Number of bytes to write */
3294 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3296 #endif /* HAVE_SSL && HAVE_LIBSSL */
3301 * 'http_debug_hex()' - Do a hex dump of a buffer.
3305 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3306 const char *buffer
, /* I - Buffer to dump */
3307 int bytes
) /* I - Bytes to dump */
3309 int i
, j
, /* Looping vars */
3310 ch
; /* Current character */
3311 char line
[255], /* Line buffer */
3312 *start
, /* Start of line after prefix */
3313 *ptr
; /* Pointer into line */
3316 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3319 DEBUG_printf(("6%s: %d bytes:\n", prefix
, bytes
));
3321 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3322 start
= line
+ strlen(line
);
3324 for (i
= 0; i
< bytes
; i
+= 16)
3326 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3327 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3339 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3341 ch
= buffer
[i
+ j
] & 255;
3343 if (ch
< ' ' || ch
>= 127)
3357 * 'http_field()' - Return the field index for a field name.
3360 static http_field_t
/* O - Field index */
3361 http_field(const char *name
) /* I - String name */
3363 int i
; /* Looping var */
3366 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3367 if (strcasecmp(name
, http_fields
[i
]) == 0)
3368 return ((http_field_t
)i
);
3370 return (HTTP_FIELD_UNKNOWN
);
3376 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3379 static int /* O - Bytes read */
3380 http_read_ssl(http_t
*http
, /* I - Connection to server */
3381 char *buf
, /* I - Buffer to store data */
3382 int len
) /* I - Length of buffer */
3384 # if defined(HAVE_LIBSSL)
3385 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3387 # elif defined(HAVE_GNUTLS)
3388 ssize_t result
; /* Return value */
3391 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3393 if (result
< 0 && !errno
)
3396 * Convert GNU TLS error to errno value...
3401 case GNUTLS_E_INTERRUPTED
:
3405 case GNUTLS_E_AGAIN
:
3417 return ((int)result
);
3419 # elif defined(HAVE_CDSASSL)
3420 int result
; /* Return value */
3421 OSStatus error
; /* Error info */
3422 size_t processed
; /* Number of bytes processed */
3425 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3430 result
= (int)processed
;
3433 case errSSLWouldBlock
:
3435 result
= (int)processed
;
3443 case errSSLClosedGraceful
:
3446 result
= (int)processed
;
3456 # elif defined(HAVE_SSPISSL)
3457 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3458 # endif /* HAVE_LIBSSL */
3460 #endif /* HAVE_SSL */
3464 * 'http_send()' - Send a request with all fields and the trailing blank line.
3467 static int /* O - 0 on success, non-zero on error */
3468 http_send(http_t
*http
, /* I - Connection to server */
3469 http_state_t request
, /* I - Request code */
3470 const char *uri
) /* I - URI */
3472 int i
; /* Looping var */
3473 char buf
[1024]; /* Encoded URI buffer */
3474 static const char * const codes
[] =
3475 { /* Request code strings */
3492 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3493 http
, codes
[request
], uri
));
3495 if (http
== NULL
|| uri
== NULL
)
3499 * Set the User-Agent field if it isn't already...
3502 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3503 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3506 * Encode the URI as needed...
3509 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3512 * See if we had an error the last time around; if so, reconnect...
3515 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3516 if (httpReconnect(http
))
3520 * Flush any written data that is pending...
3525 if (httpFlushWrite(http
) < 0)
3526 if (httpReconnect(http
))
3531 * Send the request header...
3534 http
->state
= request
;
3535 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3537 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3540 http
->status
= HTTP_CONTINUE
;
3543 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3545 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3546 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3548 #endif /* HAVE_SSL */
3550 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3552 http
->status
= HTTP_ERROR
;
3556 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3557 if (http
->fields
[i
][0] != '\0')
3559 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3560 httpGetField(http
, i
)));
3562 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3563 httpGetField(http
, i
)) < 1)
3565 http
->status
= HTTP_ERROR
;
3571 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3573 http
->status
= HTTP_ERROR
;
3577 if (http
->expect
== HTTP_CONTINUE
&&
3578 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3579 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3581 http
->status
= HTTP_ERROR
;
3585 if (httpPrintf(http
, "\r\n") < 1)
3587 http
->status
= HTTP_ERROR
;
3591 if (httpFlushWrite(http
) < 0)
3594 httpGetLength2(http
);
3595 httpClearFields(http
);
3598 * The Kerberos and AuthRef authentication strings can only be used once...
3601 if (http
->field_authorization
&& http
->authstring
&&
3602 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3603 !strncmp(http
->authstring
, "AuthRef", 7)))
3605 http
->_authstring
[0] = '\0';
3607 if (http
->authstring
!= http
->_authstring
)
3608 free(http
->authstring
);
3610 http
->authstring
= http
->_authstring
;
3618 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
3620 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3623 static int /* O - Status of connection */
3624 http_set_credentials(http_t
*http
) /* I - Connection to server */
3626 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3627 OSStatus error
= 0; /* Error code */
3628 http_tls_credentials_t credentials
= NULL
;
3629 /* TLS credentials */
3632 DEBUG_printf(("7http_set_credentials(%p)", http
));
3635 * Prefer connection specific credentials...
3638 if ((credentials
= http
->tls_credentials
) == NULL
)
3639 credentials
= cg
->tls_credentials
;
3641 # if HAVE_SECPOLICYCREATESSL
3643 * Otherwise root around in the user's keychain to see if one can be found...
3648 CFDictionaryRef query
; /* Query dictionary */
3649 CFTypeRef matches
= NULL
; /* Matching credentials */
3650 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3651 CFTypeRef keys
[] = { kSecClass
,
3654 /* Keys for dictionary */
3655 CFTypeRef values
[] = { kSecClassCertificate
,
3658 /* Values for dictionary */
3661 * Get the names associated with the server.
3664 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3666 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3672 * Create a query which will return all identities that can sign and match
3673 * the passed in policy.
3676 query
= CFDictionaryCreate(NULL
,
3677 (const void**)(&keys
[0]),
3678 (const void**)(&values
[0]),
3679 sizeof(keys
) / sizeof(keys
[0]),
3680 &kCFTypeDictionaryKeyCallBacks
,
3681 &kCFTypeDictionaryValueCallBacks
);
3684 error
= SecItemCopyMatching(query
, &matches
);
3685 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3694 CFRelease(dn_array
);
3696 # endif /* HAVE_SECPOLICYCREATESSL */
3700 error
= SSLSetCertificate(http
->tls
, credentials
);
3701 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3705 DEBUG_puts("4http_set_credentials: No credentials to set.");
3709 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
3713 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3716 static int /* O - Status of connection */
3717 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3719 _cups_globals_t
*cg
= _cupsGlobals();
3720 /* Pointer to library globals */
3721 int any_root
; /* Allow any root */
3724 SSL_CTX
*context
; /* Context for encryption */
3725 BIO
*bio
; /* BIO data */
3726 # elif defined(HAVE_GNUTLS)
3727 gnutls_certificate_client_credentials
*credentials
;
3728 /* TLS credentials */
3729 # elif defined(HAVE_CDSASSL)
3730 OSStatus error
; /* Error code */
3731 const char *message
= NULL
; /* Error message */
3732 char *hostname
; /* Hostname */
3733 # ifdef HAVE_SECCERTIFICATECOPYDATA
3734 cups_array_t
*credentials
; /* Credentials array */
3735 cups_array_t
*names
; /* CUPS distinguished names */
3736 CFArrayRef dn_array
; /* CF distinguished names array */
3737 CFIndex count
; /* Number of credentials */
3738 CFDataRef data
; /* Certificate data */
3739 int i
; /* Looping var */
3741 *credential
; /* Credential data */
3742 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3743 # elif defined(HAVE_SSPISSL)
3744 TCHAR username
[256]; /* Username returned from GetUserName() */
3745 TCHAR commonName
[256]; /* Common name for certificate */
3746 DWORD dwSize
; /* 32 bit size */
3747 # endif /* HAVE_LIBSSL */
3750 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3753 * Always allow self-signed certificates for the local loopback address...
3756 if (httpAddrLocalhost(http
->hostaddr
))
3759 any_root
= cg
->any_root
;
3762 context
= SSL_CTX_new(SSLv23_client_method());
3764 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3766 bio
= BIO_new(_httpBIOMethods());
3767 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3769 http
->tls
= SSL_new(context
);
3770 SSL_set_bio(http
->tls_credentials
, bio
, bio
);
3772 if (SSL_connect(http
->tls
) != 1)
3775 unsigned long error
; /* Error code */
3777 while ((error
= ERR_get_error()) != 0)
3778 DEBUG_printf(("8http_setup_ssl: %s", ERR_error_string(error
, NULL
)));
3781 SSL_CTX_free(context
);
3782 SSL_free(http
->tls
);
3786 http
->error
= WSAGetLastError();
3788 http
->error
= errno
;
3790 http
->status
= HTTP_ERROR
;
3792 return (HTTP_ERROR
);
3795 # elif defined(HAVE_GNUTLS)
3796 credentials
= (gnutls_certificate_client_credentials
*)
3797 malloc(sizeof(gnutls_certificate_client_credentials
));
3798 if (credentials
== NULL
)
3800 http
->error
= errno
;
3801 http
->status
= HTTP_ERROR
;
3806 gnutls_certificate_allocate_credentials(credentials
);
3808 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3809 gnutls_set_default_priority(http
->tls
);
3810 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3811 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3812 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3813 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3815 if ((gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3817 http
->error
= errno
;
3818 http
->status
= HTTP_ERROR
;
3820 gnutls_deinit(http
->tls
);
3821 gnutls_certificate_free_credentials(*credentials
);
3828 http
->tls_credentials
= credentials
;
3830 # elif defined(HAVE_CDSASSL)
3831 if ((error
= SSLNewContext(false, &http
->tls
)))
3833 http
->error
= error
;
3834 http
->status
= HTTP_ERROR
;
3839 error
= SSLSetConnection(http
->tls
, http
);
3840 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
3844 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
3845 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
3850 error
= SSLSetProtocolVersionEnabled(http
->tls
, kSSLProtocol2
, false);
3851 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionEnabled, error=%d",
3857 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
3858 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
3859 any_root
, (int)error
));
3864 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
3865 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
3866 cg
->expired_certs
, (int)error
));
3871 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
3872 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
3873 cg
->expired_root
, (int)error
));
3876 # ifdef HAVE_SECCERTIFICATECOPYDATA
3879 if (cg
->client_cert_cb
)
3881 error
= SSLSetSessionOption(http
->tls
,
3882 kSSLSessionOptionBreakOnCertRequested
, true);
3883 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
3884 "error=%d", (int)error
));
3888 error
= http_set_credentials(http
);
3889 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
3895 * If there's a server certificate callback installed let it evaluate the
3896 * certificate(s) during the handshake...
3899 if (!error
&& cg
->server_cert_cb
!= NULL
)
3901 error
= SSLSetEnableCertVerify(http
->tls
, false);
3902 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
3907 error
= SSLSetSessionOption(http
->tls
,
3908 kSSLSessionOptionBreakOnServerAuth
, true);
3909 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
3910 "error=%d", (int)error
));
3913 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3917 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
3918 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
3920 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
3926 int done
= 0; /* Are we done yet? */
3928 while (!error
&& !done
)
3930 error
= SSLHandshake(http
->tls
);
3932 DEBUG_printf(("4_httpWait: SSLHandshake returned %d.", (int)error
));
3940 case errSSLWouldBlock
:
3944 # ifdef HAVE_SECCERTIFICATECOPYDATA
3945 case errSSLServerAuthCompleted
:
3947 if (cg
->server_cert_cb
)
3949 error
= httpCopyCredentials(http
, &credentials
);
3952 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
3953 cg
->server_cert_data
);
3954 httpFreeCredentials(credentials
);
3957 DEBUG_printf(("4_httpWait: Server certificate callback returned "
3958 "%d.", (int)error
));
3962 case errSSLClientCertRequested
:
3965 if (cg
->client_cert_cb
)
3968 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
3971 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
3973 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
3975 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
3977 if ((credential
= malloc(sizeof(*credential
))))
3979 credential
->datalen
= CFDataGetLength(data
);
3980 if ((credential
->data
= malloc(credential
->datalen
)))
3982 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
3983 credential
->datalen
);
3984 cupsArrayAdd(names
, credential
);
3990 CFRelease(dn_array
);
3995 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
3996 cg
->client_cert_data
);
3998 DEBUG_printf(("4_httpWait: Client certificate callback "
3999 "returned %d.", (int)error
));
4002 httpFreeCredentials(names
);
4005 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4007 case errSSLUnknownRootCert
:
4008 message
= _("Unable to establish a secure connection to host "
4009 "(untrusted certificate).");
4012 case errSSLNoRootCert
:
4013 message
= _("Unable to establish a secure connection to host "
4014 "(self-signed certificate).");
4017 case errSSLCertExpired
:
4018 message
= _("Unable to establish a secure connection to host "
4019 "(expired certificate).");
4022 case errSSLCertNotYetValid
:
4023 message
= _("Unable to establish a secure connection to host "
4024 "(certificate not yet valid).");
4027 case errSSLHostNameMismatch
:
4028 message
= _("Unable to establish a secure connection to host "
4029 "(host name mismatch).");
4032 case errSSLXCertChainInvalid
:
4033 message
= _("Unable to establish a secure connection to host "
4034 "(certificate chain invalid).");
4037 case errSSLConnectionRefused
:
4038 message
= _("Unable to establish a secure connection to host "
4039 "(peer dropped connection before responding).");
4050 http
->error
= error
;
4051 http
->status
= HTTP_ERROR
;
4052 errno
= ECONNREFUSED
;
4054 SSLDisposeContext(http
->tls
);
4058 * If an error string wasn't set by the callbacks use a generic one...
4062 #ifdef HAVE_CSSMERRORSTRING
4063 message
= cssmErrorString(error
);
4065 message
= _("Unable to establish a secure connection to host.");
4066 #endif /* HAVE_CSSMERRORSTRING */
4068 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4073 # elif defined(HAVE_SSPISSL)
4074 http
->tls
= _sspiAlloc();
4079 http
->tls
->sock
= http
->fd
;
4080 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4081 GetUserName(username
, &dwSize
);
4082 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4083 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4085 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4088 _sspiFree(http
->tls_credentials
);
4089 http
->tls_credentials
= NULL
;
4093 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
4094 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4096 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
4098 _sspiFree(http
->tls_credentials
);
4099 http
->tls_credentials
= NULL
;
4102 # endif /* HAVE_CDSASSL */
4106 #endif /* HAVE_SSL */
4111 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4115 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4118 SSL_CTX
*context
; /* Context for encryption */
4120 context
= SSL_get_SSL_CTX(http
->tls_credentials
);
4122 SSL_shutdown(http
->tls_credentials
);
4123 SSL_CTX_free(context
);
4124 SSL_free(http
->tls_credentials
);
4126 # elif defined(HAVE_GNUTLS)
4127 gnutls_certificate_client_credentials
*credentials
;
4128 /* TLS credentials */
4130 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4132 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4133 gnutls_deinit(http
->tls
);
4134 gnutls_certificate_free_credentials(*credentials
);
4137 # elif defined(HAVE_CDSASSL)
4138 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4141 SSLDisposeContext(http
->tls
);
4143 if (http
->tls_credentials
)
4144 CFRelease(http
->tls_credentials
);
4146 # elif defined(HAVE_SSPISSL)
4147 _sspiFree(http
->tls_credentials
);
4148 # endif /* HAVE_LIBSSL */
4151 http
->tls_credentials
= NULL
;
4153 #endif /* HAVE_SSL */
4158 * 'http_upgrade()' - Force upgrade to TLS encryption.
4161 static int /* O - Status of connection */
4162 http_upgrade(http_t
*http
) /* I - Connection to server */
4164 int ret
; /* Return value */
4165 http_t myhttp
; /* Local copy of HTTP data */
4168 DEBUG_printf(("7http_upgrade(%p)", http
));
4171 * Flush the connection to make sure any previous "Upgrade" message
4178 * Copy the HTTP data to a local variable so we can do the OPTIONS
4179 * request without interfering with the existing request data...
4182 memcpy(&myhttp
, http
, sizeof(myhttp
));
4185 * Send an OPTIONS request to the server, requiring SSL or TLS
4186 * encryption on the link...
4189 http
->field_authorization
= NULL
; /* Don't free the auth string */
4191 httpClearFields(http
);
4192 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4193 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4195 if ((ret
= httpOptions(http
, "*")) == 0)
4198 * Wait for the secure connection...
4201 while (httpUpdate(http
) == HTTP_CONTINUE
);
4205 * Restore the HTTP request data...
4208 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4209 http
->data_encoding
= myhttp
.data_encoding
;
4210 http
->data_remaining
= myhttp
.data_remaining
;
4211 http
->_data_remaining
= myhttp
._data_remaining
;
4212 http
->expect
= myhttp
.expect
;
4213 http
->field_authorization
= myhttp
.field_authorization
;
4214 http
->digest_tries
= myhttp
.digest_tries
;
4217 * See if we actually went secure...
4223 * Server does not support HTTP upgrade...
4226 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4229 closesocket(http
->fd
);
4241 #endif /* HAVE_SSL */
4245 * 'http_write()' - Write a buffer to a HTTP connection.
4248 static int /* O - Number of bytes written */
4249 http_write(http_t
*http
, /* I - Connection to server */
4250 const char *buffer
, /* I - Buffer for data */
4251 int length
) /* I - Number of bytes to write */
4253 int tbytes
, /* Total bytes sent */
4254 bytes
; /* Bytes sent */
4257 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4266 bytes
= http_write_ssl(http
, buffer
, length
);
4268 #endif /* HAVE_SSL */
4269 bytes
= send(http
->fd
, buffer
, length
, 0);
4274 if (WSAGetLastError() == WSAEINTR
)
4276 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4278 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4281 http
->error
= WSAGetLastError();
4283 else if (WSAGetLastError() != http
->error
&&
4284 WSAGetLastError() != WSAECONNRESET
)
4286 http
->error
= WSAGetLastError();
4293 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4295 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4297 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4300 http
->error
= errno
;
4302 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4304 http
->error
= errno
;
4309 DEBUG_printf(("3http_write: error writing data (%s).",
4310 strerror(http
->error
)));
4321 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4324 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4331 * 'http_write_chunk()' - Write a chunked buffer.
4334 static int /* O - Number bytes written */
4335 http_write_chunk(http_t
*http
, /* I - Connection to server */
4336 const char *buffer
, /* I - Buffer to write */
4337 int length
) /* I - Length of buffer */
4339 char header
[255]; /* Chunk header */
4340 int bytes
; /* Bytes written */
4343 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4344 http
, buffer
, length
));
4347 * Write the chunk header, data, and trailer.
4350 sprintf(header
, "%x\r\n", length
);
4351 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4353 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4357 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4359 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4363 if (http_write(http
, "\r\n", 2) < 0)
4365 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4375 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4378 static int /* O - Bytes written */
4379 http_write_ssl(http_t
*http
, /* I - Connection to server */
4380 const char *buf
, /* I - Buffer holding data */
4381 int len
) /* I - Length of buffer */
4383 ssize_t result
; /* Return value */
4386 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4388 # if defined(HAVE_LIBSSL)
4389 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4391 # elif defined(HAVE_GNUTLS)
4392 result
= gnutls_record_send(http
->tls
, buf
, len
);
4394 if (result
< 0 && !errno
)
4397 * Convert GNU TLS error to errno value...
4402 case GNUTLS_E_INTERRUPTED
:
4406 case GNUTLS_E_AGAIN
:
4418 # elif defined(HAVE_CDSASSL)
4419 OSStatus error
; /* Error info */
4420 size_t processed
; /* Number of bytes processed */
4423 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4428 result
= (int)processed
;
4431 case errSSLWouldBlock
:
4433 result
= (int)processed
;
4441 case errSSLClosedGraceful
:
4444 result
= (int)processed
;
4452 # elif defined(HAVE_SSPISSL)
4453 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
4454 # endif /* HAVE_LIBSSL */
4456 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4458 return ((int)result
);
4460 #endif /* HAVE_SSL */