2 * "$Id: http.c 7850 2008-08-20 00:07:25Z mike $"
4 * HTTP routines for CUPS.
6 * Copyright 2007-2011 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * httpAddCredential() - Allocates and adds a single credential to an
24 * _httpBIOMethods() - Get the OpenSSL BIO methods for HTTP
26 * httpBlocking() - Set blocking/non-blocking behavior on a
28 * httpCheck() - Check to see if there is a pending response
30 * httpClearCookie() - Clear the cookie value(s).
31 * httpClearFields() - Clear HTTP request fields.
32 * httpClose() - Close an HTTP connection.
33 * httpConnect() - Connect to a HTTP server.
34 * httpConnectEncrypt() - Connect to a HTTP server using encryption.
35 * httpCopyCredentials() - Copy the credentials associated with an
36 * encrypted connection.
37 * _httpCreate() - Create an unconnected HTTP connection.
38 * _httpCreateCredentials() - Create credentials in the internal format.
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_set_timeout() - Set the socket timeout values.
111 * http_set_wait() - Set the default wait value for reads.
112 * http_setup_ssl() - Set up SSL/TLS support on a connection.
113 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
114 * http_threadid_cb() - Return the current thread ID.
115 * http_upgrade() - Force upgrade to TLS encryption.
116 * http_write() - Write a buffer to a HTTP connection.
117 * http_write_chunk() - Write a chunked buffer.
118 * http_write_ssl() - Write to a SSL/TLS connection.
122 * Include necessary headers...
125 #include "cups-private.h"
132 # include <sys/time.h>
133 # include <sys/resource.h>
136 # include <sys/poll.h>
137 #endif /* HAVE_POLL */
141 * Some operating systems have done away with the Fxxxx constants for
142 * the fcntl() call; this works around that "feature"...
146 # define FNONBLK O_NONBLOCK
147 #endif /* !FNONBLK */
155 static void http_debug_hex(const char *prefix
, const char *buffer
,
158 static http_field_t
http_field(const char *name
);
159 static int http_send(http_t
*http
, http_state_t request
,
161 static int http_write(http_t
*http
, const char *buffer
,
163 static int http_write_chunk(http_t
*http
, const char *buffer
,
166 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
167 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
168 static int http_set_credentials(http_t
*http
);
169 # endif /* HAVE_CDSASSL ** HAVE_SECCERTIFICATECOPYDATA */
170 #endif /* HAVE_SSL */
171 static void http_set_timeout(int fd
, double timeout
);
172 static void http_set_wait(http_t
*http
);
174 static int http_setup_ssl(http_t
*http
);
175 static void http_shutdown_ssl(http_t
*http
);
176 static int http_upgrade(http_t
*http
);
177 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
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.
269 * @since CUPS 1.5/Mac OS X 10.7@
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 */
329 * 'httpCheck()' - Check to see if there is a pending response from the server.
332 int /* O - 0 = no data, 1 = data available */
333 httpCheck(http_t
*http
) /* I - Connection to server */
335 return (httpWait(http
, 0));
340 * 'httpClearCookie()' - Clear the cookie value(s).
342 * @since CUPS 1.1.19/Mac OS X 10.3@
346 httpClearCookie(http_t
*http
) /* I - Connection to server */
360 * 'httpClearFields()' - Clear HTTP request fields.
364 httpClearFields(http_t
*http
) /* I - Connection to server */
368 memset(http
->fields
, 0, sizeof(http
->fields
));
369 if (http
->hostname
[0] == '/')
370 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
372 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
374 if (http
->field_authorization
)
376 free(http
->field_authorization
);
377 http
->field_authorization
= NULL
;
380 http
->expect
= (http_status_t
)0;
386 * 'httpClose()' - Close an HTTP connection.
390 httpClose(http_t
*http
) /* I - Connection to server */
393 OM_uint32 minor_status
; /* Minor status code */
394 #endif /* HAVE_GSSAPI */
397 DEBUG_printf(("httpClose(http=%p)", http
));
400 * Range check input...
407 * Close any open connection...
410 _httpDisconnect(http
);
413 * Free memory used...
416 httpAddrFreeList(http
->addrlist
);
422 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
423 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
425 if (http
->gssname
!= GSS_C_NO_NAME
)
426 gss_release_name(&minor_status
, &http
->gssname
);
427 #endif /* HAVE_GSSAPI */
429 #ifdef HAVE_AUTHORIZATION_H
431 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
432 #endif /* HAVE_AUTHORIZATION_H */
434 httpClearFields(http
);
436 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
437 free(http
->authstring
);
444 * 'httpConnect()' - Connect to a HTTP server.
446 * This function is deprecated - use @link httpConnectEncrypt@ instead.
451 http_t
* /* O - New HTTP connection */
452 httpConnect(const char *host
, /* I - Host to connect to */
453 int port
) /* I - Port number */
455 return (httpConnectEncrypt(host
, port
, HTTP_ENCRYPT_IF_REQUESTED
));
460 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
463 http_t
* /* O - New HTTP connection */
465 const char *host
, /* I - Host to connect to */
466 int port
, /* I - Port number */
467 http_encryption_t encryption
) /* I - Type of encryption to use */
469 http_t
*http
; /* New HTTP connection */
472 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
473 host
, port
, encryption
));
476 * Create the HTTP structure...
479 if ((http
= _httpCreate(host
, port
, NULL
, encryption
, AF_UNSPEC
)) == NULL
)
483 * Connect to the remote system...
486 if (!httpReconnect(http
))
490 * Could not connect to any known address - bail out!
493 httpAddrFreeList(http
->addrlist
);
502 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
505 * @since CUPS 1.5/Mac OS X 10.7@
508 int /* O - Status of call (0 = success) */
510 http_t
*http
, /* I - Connection to server */
511 cups_array_t
**credentials
) /* O - Array of credentials */
514 # elif defined(HAVE_GNUTLS)
515 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
516 OSStatus error
; /* Error code */
517 CFIndex count
; /* Number of credentials */
518 CFArrayRef peerCerts
; /* Peer certificates */
519 SecCertificateRef secCert
; /* Certificate reference */
520 CFDataRef data
; /* Certificate data */
521 int i
; /* Looping var */
522 # elif defined(HAVE_SSPISSL)
523 # endif /* HAVE_LIBSSL */
529 if (!http
|| !http
->tls
|| !credentials
)
535 # elif defined(HAVE_GNUTLS)
538 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
539 if (!(error
= SSLCopyPeerCertificates(http
->tls
, &peerCerts
)) && peerCerts
)
541 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
543 for (i
= 0, count
= CFArrayGetCount(peerCerts
); i
< count
; i
++)
545 secCert
= (SecCertificateRef
)CFArrayGetValueAtIndex(peerCerts
, i
);
546 if ((data
= SecCertificateCopyData(secCert
)))
548 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
549 CFDataGetLength(data
));
555 CFRelease(peerCerts
);
560 # elif defined(HAVE_SSPISSL)
565 # endif /* HAVE_LIBSSL */
570 * '_httpCreate()' - Create an unconnected HTTP connection.
573 http_t
* /* O - HTTP connection */
575 const char *host
, /* I - Hostname */
576 int port
, /* I - Port number */
577 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
578 http_encryption_t encryption
, /* I - Encryption to use */
579 int family
) /* I - Address family or AF_UNSPEC */
581 http_t
*http
; /* New HTTP connection */
582 char service
[255]; /* Service name */
585 DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
586 host
, port
, encryption
));
597 sprintf(service
, "%d", port
);
600 if ((addrlist
= httpAddrGetList(host
, family
, service
)) == NULL
)
604 * Allocate memory for the structure...
607 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
609 httpAddrFreeList(addrlist
);
614 * Initialize the HTTP data...
617 http
->activity
= time(NULL
);
618 http
->addrlist
= addrlist
;
622 http
->gssctx
= GSS_C_NO_CONTEXT
;
623 http
->gssname
= GSS_C_NO_NAME
;
624 #endif /* HAVE_GSSAPI */
625 http
->version
= HTTP_1_1
;
627 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
629 if (port
== 443) /* Always use encryption for https */
630 http
->encryption
= HTTP_ENCRYPT_ALWAYS
;
632 http
->encryption
= encryption
;
637 * Return the new structure...
645 * '_httpCreateCredentials()' - Create credentials in the internal format.
648 http_tls_credentials_t
/* O - Internal credentials */
649 _httpCreateCredentials(
650 cups_array_t
*credentials
) /* I - Array of credentials */
658 # elif defined(HAVE_GNUTLS)
661 # elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
662 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
663 SecCertificateRef secCert
; /* Certificate reference */
664 CFDataRef data
; /* Credential data reference */
665 http_credential_t
*credential
; /* Credential data */
668 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
669 cupsArrayCount(credentials
),
670 &kCFTypeArrayCallBacks
)) == NULL
)
673 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
675 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
677 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
678 credential
->datalen
)))
680 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
683 CFArrayAppendValue(peerCerts
, secCert
);
693 # elif defined(HAVE_SSPISSL)
698 # endif /* HAVE_LIBSSL */
703 * 'httpDelete()' - Send a DELETE request to the server.
706 int /* O - Status of call (0 = success) */
707 httpDelete(http_t
*http
, /* I - Connection to server */
708 const char *uri
) /* I - URI to delete */
710 return (http_send(http
, HTTP_DELETE
, uri
));
715 * '_httpDisconnect()' - Disconnect a HTTP connection.
719 _httpDisconnect(http_t
*http
) /* I - Connection to server */
723 http_shutdown_ssl(http
);
724 #endif /* HAVE_SSL */
727 closesocket(http
->fd
);
737 * 'httpEncryption()' - Set the required encryption on the link.
740 int /* O - -1 on error, 0 on success */
741 httpEncryption(http_t
*http
, /* I - Connection to server */
742 http_encryption_t e
) /* I - New encryption preference */
744 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
750 http
->encryption
= e
;
752 if ((http
->encryption
== HTTP_ENCRYPT_ALWAYS
&& !http
->tls
) ||
753 (http
->encryption
== HTTP_ENCRYPT_NEVER
&& http
->tls
))
754 return (httpReconnect(http
));
755 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
756 return (http_upgrade(http
));
760 if (e
== HTTP_ENCRYPT_ALWAYS
|| e
== HTTP_ENCRYPT_REQUIRED
)
764 #endif /* HAVE_SSL */
769 * 'httpError()' - Get the last error on a connection.
772 int /* O - Error code (errno) value */
773 httpError(http_t
*http
) /* I - Connection to server */
776 return (http
->error
);
783 * 'httpFlush()' - Flush data from a HTTP connection.
787 httpFlush(http_t
*http
) /* I - Connection to server */
789 char buffer
[8192]; /* Junk buffer */
790 int blocking
; /* To block or not to block */
791 http_state_t oldstate
; /* Old state */
794 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
795 http_states
[http
->state
]));
798 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
801 blocking
= http
->blocking
;
805 * Read any data we can...
808 oldstate
= http
->state
;
809 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
812 * Restore blocking and reset the connection if we didn't get all of
813 * the remaining data...
816 http
->blocking
= blocking
;
818 if (http
->state
== oldstate
&& http
->state
!= HTTP_WAITING
&& http
->fd
>= 0)
821 * Didn't get the data back, so close the current connection.
824 http
->state
= HTTP_WAITING
;
828 http_shutdown_ssl(http
);
829 #endif /* HAVE_SSL */
832 closesocket(http
->fd
);
843 * 'httpFlushWrite()' - Flush data in write buffer.
845 * @since CUPS 1.2/Mac OS X 10.5@
848 int /* O - Bytes written or -1 on error */
849 httpFlushWrite(http_t
*http
) /* I - Connection to server */
851 int bytes
; /* Bytes written */
854 DEBUG_printf(("httpFlushWrite(http=%p)", http
));
856 if (!http
|| !http
->wused
)
858 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
859 "1httpFlushWrite: No connection.");
863 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
864 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
866 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
870 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
877 * '_httpFreeCredentials()' - Free internal credentials.
881 _httpFreeCredentials(
882 http_tls_credentials_t credentials
) /* I - Internal credentials */
890 #elif defined(HAVE_GNUTLS)
893 #elif defined(HAVE_CDSASSL)
894 CFRelease(credentials
);
896 #elif defined(HAVE_SSPISSL)
899 #endif /* HAVE_LIBSSL */
904 * 'httpFreeCredentials()' - Free an array of credentials.
909 cups_array_t
*credentials
) /* I - Array of credentials */
911 http_credential_t
*credential
; /* Credential */
914 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
916 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
918 cupsArrayRemove(credentials
, credential
);
919 free((void *)credential
->data
);
923 cupsArrayDelete(credentials
);
928 * 'httpGet()' - Send a GET request to the server.
931 int /* O - Status of call (0 = success) */
932 httpGet(http_t
*http
, /* I - Connection to server */
933 const char *uri
) /* I - URI to get */
935 return (http_send(http
, HTTP_GET
, uri
));
940 * 'httpGetAuthString()' - Get the current authorization string.
942 * The authorization string is set by cupsDoAuthentication() and
943 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
944 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
947 * @since CUPS 1.3/Mac OS X 10.5@
950 char * /* O - Authorization string */
951 httpGetAuthString(http_t
*http
) /* I - Connection to server */
954 return (http
->authstring
);
961 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
963 * @since CUPS 1.2/Mac OS X 10.5@
966 int /* O - 1 if blocking, 0 if non-blocking */
967 httpGetBlocking(http_t
*http
) /* I - Connection to server */
969 return (http
? http
->blocking
: 0);
974 * 'httpGetCookie()' - Get any cookie data from the response.
976 * @since CUPS 1.1.19/Mac OS X 10.3@
979 const char * /* O - Cookie data or NULL */
980 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
982 return (http
? http
->cookie
: NULL
);
987 * 'httpGetFd()' - Get the file descriptor associated with a connection.
989 * @since CUPS 1.2/Mac OS X 10.5@
992 int /* O - File descriptor or -1 if none */
993 httpGetFd(http_t
*http
) /* I - Connection to server */
995 return (http
? http
->fd
: -1);
1000 * 'httpGetField()' - Get a field value from a request/response.
1003 const char * /* O - Field value */
1004 httpGetField(http_t
*http
, /* I - Connection to server */
1005 http_field_t field
) /* I - Field to get */
1007 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1009 else if (field
== HTTP_FIELD_AUTHORIZATION
&&
1010 http
->field_authorization
)
1013 * Special case for WWW-Authenticate: as its contents can be
1014 * longer than HTTP_MAX_VALUE...
1017 return (http
->field_authorization
);
1020 return (http
->fields
[field
]);
1025 * 'httpGetLength()' - Get the amount of data remaining from the
1026 * content-length or transfer-encoding fields.
1028 * This function is deprecated and will not return lengths larger than
1029 * 2^31 - 1; use httpGetLength2() instead.
1034 int /* O - Content length */
1035 httpGetLength(http_t
*http
) /* I - Connection to server */
1038 * Get the read content length and return the 32-bit value.
1043 httpGetLength2(http
);
1045 return (http
->_data_remaining
);
1053 * 'httpGetLength2()' - Get the amount of data remaining from the
1054 * content-length or transfer-encoding fields.
1056 * This function returns the complete content length, even for
1057 * content larger than 2^31 - 1.
1059 * @since CUPS 1.2/Mac OS X 10.5@
1062 off_t
/* O - Content length */
1063 httpGetLength2(http_t
*http
) /* I - Connection to server */
1065 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1066 http_states
[http
->state
]));
1071 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1073 DEBUG_puts("4httpGetLength2: chunked request!");
1075 http
->data_encoding
= HTTP_ENCODE_CHUNKED
;
1076 http
->data_remaining
= 0;
1080 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1083 * The following is a hack for HTTP servers that don't send a
1084 * content-length or transfer-encoding field...
1086 * If there is no content-length then the connection must close
1087 * after the transfer is complete...
1090 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1093 * Default content length is 0 for errors and 2^31-1 for other
1094 * successful requests...
1097 if (http
->status
>= HTTP_MULTIPLE_CHOICES
)
1098 http
->data_remaining
= 0;
1100 http
->data_remaining
= 2147483647;
1103 http
->data_remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1106 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1107 CUPS_LLCAST http
->data_remaining
));
1110 if (http
->data_remaining
<= INT_MAX
)
1111 http
->_data_remaining
= (int)http
->data_remaining
;
1113 http
->_data_remaining
= INT_MAX
;
1115 return (http
->data_remaining
);
1120 * 'httpGetStatus()' - Get the status of the last HTTP request.
1122 * @since CUPS 1.2/Mac OS X 10.5@
1125 http_status_t
/* O - HTTP status */
1126 httpGetStatus(http_t
*http
) /* I - Connection to server */
1128 return (http
? http
->status
: HTTP_ERROR
);
1133 * 'httpGetSubField()' - Get a sub-field value.
1138 char * /* O - Value or NULL */
1139 httpGetSubField(http_t
*http
, /* I - Connection to server */
1140 http_field_t field
, /* I - Field index */
1141 const char *name
, /* I - Name of sub-field */
1142 char *value
) /* O - Value string */
1144 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1149 * 'httpGetSubField2()' - Get a sub-field value.
1151 * @since CUPS 1.2/Mac OS X 10.5@
1154 char * /* O - Value or NULL */
1155 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1156 http_field_t field
, /* I - Field index */
1157 const char *name
, /* I - Name of sub-field */
1158 char *value
, /* O - Value string */
1159 int valuelen
) /* I - Size of value buffer */
1161 const char *fptr
; /* Pointer into field */
1162 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1163 *ptr
, /* Pointer into string buffer */
1164 *end
; /* End of value buffer */
1166 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1167 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1169 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1170 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1173 end
= value
+ valuelen
- 1;
1175 for (fptr
= http
->fields
[field
]; *fptr
;)
1178 * Skip leading whitespace...
1181 while (_cups_isspace(*fptr
))
1191 * Get the sub-field name...
1195 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1196 ptr
< (temp
+ sizeof(temp
) - 1);
1201 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1204 * Skip trailing chars up to the '='...
1207 while (_cups_isspace(*fptr
))
1217 * Skip = and leading whitespace...
1222 while (_cups_isspace(*fptr
))
1228 * Read quoted string...
1231 for (ptr
= value
, fptr
++;
1232 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1237 while (*fptr
&& *fptr
!= '\"')
1246 * Read unquoted string...
1250 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1255 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1259 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1262 * See if this is the one...
1265 if (!strcmp(name
, temp
))
1267 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1274 DEBUG_puts("3httpGetSubField2: Returning NULL");
1281 * 'httpGets()' - Get a line of text from a HTTP connection.
1284 char * /* O - Line or NULL */
1285 httpGets(char *line
, /* I - Line to read into */
1286 int length
, /* I - Max length of buffer */
1287 http_t
*http
) /* I - Connection to server */
1289 char *lineptr
, /* Pointer into line */
1290 *lineend
, /* End of line */
1291 *bufptr
, /* Pointer into input buffer */
1292 *bufend
; /* Pointer to end of buffer */
1293 int bytes
, /* Number of bytes read */
1294 eol
; /* End-of-line? */
1297 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1299 if (http
== NULL
|| line
== NULL
)
1303 * Read a line from the buffer...
1308 lineend
= line
+ length
- 1;
1311 while (lineptr
< lineend
)
1314 * Pre-load the buffer as needed...
1323 while (http
->used
== 0)
1326 * No newline; see if there is more data to be read...
1329 while (!_httpWait(http
, http
->wait_value
, 1))
1331 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1334 DEBUG_puts("3httpGets: Timed out!");
1336 http
->error
= WSAETIMEDOUT
;
1338 http
->error
= ETIMEDOUT
;
1345 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1346 HTTP_MAX_BUFFER
- http
->used
);
1348 #endif /* HAVE_SSL */
1349 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1350 HTTP_MAX_BUFFER
- http
->used
, 0);
1352 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1357 * Nope, can't get a line this time...
1361 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1363 if (WSAGetLastError() == WSAEINTR
)
1365 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1367 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1370 http
->error
= WSAGetLastError();
1372 else if (WSAGetLastError() != http
->error
)
1374 http
->error
= WSAGetLastError();
1379 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1383 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1385 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1387 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1390 http
->error
= errno
;
1392 else if (errno
!= http
->error
)
1394 http
->error
= errno
;
1401 else if (bytes
== 0)
1403 http
->error
= EPIPE
;
1409 * Yup, update the amount used...
1412 http
->used
+= bytes
;
1416 * Now copy as much of the current line as possible...
1419 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1420 lineptr
< lineend
&& bufptr
< bufend
;)
1422 if (*bufptr
== 0x0a)
1428 else if (*bufptr
== 0x0d)
1431 *lineptr
++ = *bufptr
++;
1434 http
->used
-= (int)(bufptr
- http
->buffer
);
1436 memmove(http
->buffer
, bufptr
, http
->used
);
1444 http
->activity
= time(NULL
);
1448 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1454 DEBUG_puts("3httpGets: No new line available!");
1461 * 'httpHead()' - Send a HEAD request to the server.
1464 int /* O - Status of call (0 = success) */
1465 httpHead(http_t
*http
, /* I - Connection to server */
1466 const char *uri
) /* I - URI for head */
1468 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1469 return (http_send(http
, HTTP_HEAD
, uri
));
1474 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1475 * default HTTP proxy (if any).
1479 httpInitialize(void)
1481 static int initialized
= 0; /* Have we been called before? */
1483 WSADATA winsockdata
; /* WinSock data */
1486 int i
; /* Looping var */
1487 unsigned char data
[1024]; /* Seed data */
1488 #endif /* HAVE_LIBSSL */
1494 _cupsGlobalUnlock();
1499 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1501 #elif !defined(SO_NOSIGPIPE)
1503 * Ignore SIGPIPE signals...
1507 sigset(SIGPIPE
, SIG_IGN
);
1509 # elif defined(HAVE_SIGACTION)
1510 struct sigaction action
; /* POSIX sigaction data */
1513 memset(&action
, 0, sizeof(action
));
1514 action
.sa_handler
= SIG_IGN
;
1515 sigaction(SIGPIPE
, &action
, NULL
);
1518 signal(SIGPIPE
, SIG_IGN
);
1519 # endif /* !SO_NOSIGPIPE */
1524 * Initialize GNU TLS...
1527 gnutls_global_init();
1529 #elif defined(HAVE_LIBSSL)
1531 * Initialize OpenSSL...
1534 SSL_load_error_strings();
1538 * Using the current time is a dubious random seed, but on some systems
1539 * it is the best we can do (on others, this seed isn't even used...)
1542 CUPS_SRAND(time(NULL
));
1544 for (i
= 0; i
< sizeof(data
); i
++)
1545 data
[i
] = CUPS_RAND();
1547 RAND_seed(data
, sizeof(data
));
1548 #endif /* HAVE_GNUTLS */
1551 _cupsGlobalUnlock();
1556 * 'httpOptions()' - Send an OPTIONS request to the server.
1559 int /* O - Status of call (0 = success) */
1560 httpOptions(http_t
*http
, /* I - Connection to server */
1561 const char *uri
) /* I - URI for options */
1563 return (http_send(http
, HTTP_OPTIONS
, uri
));
1568 * '_httpPeek()' - Peek at data from a HTTP connection.
1570 * This function copies available data from the given HTTP connection, reading
1571 * a buffer as needed. The data is still available for reading using
1572 * @link httpRead@ or @link httpRead2@.
1574 * For non-blocking connections the usual timeouts apply.
1577 ssize_t
/* O - Number of bytes copied */
1578 _httpPeek(http_t
*http
, /* I - Connection to server */
1579 char *buffer
, /* I - Buffer for data */
1580 size_t length
) /* I - Maximum number of bytes */
1582 ssize_t bytes
; /* Bytes read */
1583 char len
[32]; /* Length string */
1586 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1587 http
, buffer
, CUPS_LLCAST length
));
1589 if (http
== NULL
|| buffer
== NULL
)
1592 http
->activity
= time(NULL
);
1598 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1599 http
->data_remaining
<= 0)
1601 DEBUG_puts("2_httpPeek: Getting chunk length...");
1603 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1605 DEBUG_puts("1_httpPeek: Could not get length!");
1609 http
->data_remaining
= strtoll(len
, NULL
, 16);
1610 if (http
->data_remaining
< 0)
1612 DEBUG_puts("1_httpPeek: Negative chunk length!");
1617 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1618 CUPS_LLCAST http
->data_remaining
));
1620 if (http
->data_remaining
<= 0)
1623 * A zero-length chunk ends a transfer; unless we are reading POST
1627 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1628 httpGets(len
, sizeof(len
), http
);
1630 if (http
->state
== HTTP_POST_RECV
)
1633 http
->state
= HTTP_WAITING
;
1636 * Prevent future reads for this request...
1639 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1643 else if (length
> (size_t)http
->data_remaining
)
1644 length
= (size_t)http
->data_remaining
;
1646 if (http
->used
== 0)
1649 * Buffer small reads for better performance...
1652 if (!http
->blocking
)
1654 while (!httpWait(http
, http
->wait_value
))
1656 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1663 if (http
->data_remaining
> sizeof(http
->buffer
))
1664 bytes
= sizeof(http
->buffer
);
1666 bytes
= http
->data_remaining
;
1670 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1672 #endif /* HAVE_SSL */
1674 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1677 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1679 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1688 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1690 http
->error
= WSAGetLastError();
1694 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1696 http
->error
= errno
;
1703 http
->error
= EPIPE
;
1710 if (length
> (size_t)http
->used
)
1711 length
= (size_t)http
->used
;
1713 bytes
= (ssize_t
)length
;
1715 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1718 memcpy(buffer
, http
->buffer
, length
);
1726 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1729 http
->error
= WSAGetLastError();
1731 if (errno
== EINTR
|| errno
== EAGAIN
)
1734 http
->error
= errno
;
1737 else if (bytes
== 0)
1739 http
->error
= EPIPE
;
1744 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1752 * 'httpPost()' - Send a POST request to the server.
1755 int /* O - Status of call (0 = success) */
1756 httpPost(http_t
*http
, /* I - Connection to server */
1757 const char *uri
) /* I - URI for post */
1759 return (http_send(http
, HTTP_POST
, uri
));
1764 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1769 int /* O - Number of bytes written */
1770 httpPrintf(http_t
*http
, /* I - Connection to server */
1771 const char *format
, /* I - printf-style format string */
1772 ...) /* I - Additional args as needed */
1774 int bytes
; /* Number of bytes to write */
1775 char buf
[16384]; /* Buffer for formatted string */
1776 va_list ap
; /* Variable argument pointer */
1779 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1781 va_start(ap
, format
);
1782 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1785 DEBUG_printf(("3httpPrintf: %s", buf
));
1787 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1788 return (httpWrite2(http
, buf
, bytes
));
1793 DEBUG_puts("4httpPrintf: flushing existing data...");
1795 if (httpFlushWrite(http
) < 0)
1799 return (http_write(http
, buf
, bytes
));
1805 * 'httpPut()' - Send a PUT request to the server.
1808 int /* O - Status of call (0 = success) */
1809 httpPut(http_t
*http
, /* I - Connection to server */
1810 const char *uri
) /* I - URI to put */
1812 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1813 return (http_send(http
, HTTP_PUT
, uri
));
1818 * 'httpRead()' - Read data from a HTTP connection.
1820 * This function is deprecated. Use the httpRead2() function which can
1821 * read more than 2GB of data.
1826 int /* O - Number of bytes read */
1827 httpRead(http_t
*http
, /* I - Connection to server */
1828 char *buffer
, /* I - Buffer for data */
1829 int length
) /* I - Maximum number of bytes */
1831 return ((int)httpRead2(http
, buffer
, length
));
1836 * 'httpRead2()' - Read data from a HTTP connection.
1838 * @since CUPS 1.2/Mac OS X 10.5@
1841 ssize_t
/* O - Number of bytes read */
1842 httpRead2(http_t
*http
, /* I - Connection to server */
1843 char *buffer
, /* I - Buffer for data */
1844 size_t length
) /* I - Maximum number of bytes */
1846 ssize_t bytes
; /* Bytes read */
1847 char len
[32]; /* Length string */
1850 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1851 http
, buffer
, CUPS_LLCAST length
));
1853 if (http
== NULL
|| buffer
== NULL
)
1856 http
->activity
= time(NULL
);
1862 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1863 http
->data_remaining
<= 0)
1865 DEBUG_puts("2httpRead2: Getting chunk length...");
1867 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1869 DEBUG_puts("1httpRead2: Could not get length!");
1873 http
->data_remaining
= strtoll(len
, NULL
, 16);
1874 if (http
->data_remaining
< 0)
1876 DEBUG_puts("1httpRead2: Negative chunk length!");
1881 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1882 CUPS_LLCAST http
->data_remaining
));
1884 if (http
->data_remaining
<= 0)
1887 * A zero-length chunk ends a transfer; unless we are reading POST
1891 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1892 httpGets(len
, sizeof(len
), http
);
1894 if (http
->state
== HTTP_POST_RECV
)
1897 http
->state
= HTTP_WAITING
;
1900 * Prevent future reads for this request...
1903 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1907 else if (length
> (size_t)http
->data_remaining
)
1908 length
= (size_t)http
->data_remaining
;
1910 if (http
->used
== 0 && length
<= 256)
1913 * Buffer small reads for better performance...
1916 ssize_t buflen
; /* Length of read for buffer */
1918 if (!http
->blocking
)
1920 while (!httpWait(http
, http
->wait_value
))
1922 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1929 if (http
->data_remaining
> sizeof(http
->buffer
))
1930 buflen
= sizeof(http
->buffer
);
1932 buflen
= http
->data_remaining
;
1934 DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen
));
1940 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
1942 #endif /* HAVE_SSL */
1943 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
1948 if (WSAGetLastError() != WSAEINTR
)
1950 http
->error
= WSAGetLastError();
1953 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1955 if (!http
->timeout_cb
||
1956 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1958 http
->error
= WSAEWOULDBLOCK
;
1963 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1965 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1967 http
->error
= errno
;
1970 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1972 http
->error
= errno
;
1976 else if (errno
!= EINTR
)
1978 http
->error
= errno
;
1986 DEBUG_printf(("2httpRead2: Read %d bytes into buffer.", (int)bytes
));
1993 if (length
> (size_t)http
->used
)
1994 length
= (size_t)http
->used
;
1996 bytes
= (ssize_t
)length
;
1998 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2001 memcpy(buffer
, http
->buffer
, length
);
2002 http
->used
-= (int)length
;
2005 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2010 if (!http
->blocking
)
2012 while (!httpWait(http
, http
->wait_value
))
2014 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2021 while ((bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
)) < 0)
2024 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2026 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2029 else if (WSAGetLastError() != WSAEINTR
)
2032 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2034 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2036 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2039 else if (errno
!= EINTR
)
2044 #endif /* HAVE_SSL */
2047 if (!http
->blocking
)
2049 while (!httpWait(http
, http
->wait_value
))
2051 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2058 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2059 CUPS_LLCAST length
));
2062 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2064 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2066 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2069 else if (WSAGetLastError() != WSAEINTR
)
2073 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2075 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2077 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2079 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2082 else if (errno
!= EINTR
)
2087 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2088 CUPS_LLCAST bytes
));
2093 http
->data_remaining
-= bytes
;
2095 if (http
->data_remaining
<= INT_MAX
)
2096 http
->_data_remaining
= (int)http
->data_remaining
;
2098 http
->_data_remaining
= INT_MAX
;
2103 if (WSAGetLastError() == WSAEINTR
)
2106 http
->error
= WSAGetLastError();
2108 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2111 http
->error
= errno
;
2116 http
->error
= EPIPE
;
2120 if (http
->data_remaining
== 0)
2122 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2123 httpGets(len
, sizeof(len
), http
);
2125 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2127 if (http
->state
== HTTP_POST_RECV
)
2130 http
->state
= HTTP_WAITING
;
2135 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2142 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2144 * '_httpReadCDSA()' - Read function for the CDSA library.
2147 OSStatus
/* O - -1 on error, 0 on success */
2149 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2150 void *data
, /* I - Data buffer */
2151 size_t *dataLength
) /* IO - Number of bytes */
2153 OSStatus result
; /* Return value */
2154 ssize_t bytes
; /* Number of bytes read */
2155 http_t
*http
; /* HTTP connection */
2158 http
= (http_t
*)connection
;
2160 if (!http
->blocking
)
2163 * Make sure we have data before we read...
2166 while (!_httpWait(http
, http
->wait_value
, 0))
2168 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2171 http
->error
= ETIMEDOUT
;
2178 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2180 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2182 if (bytes
== *dataLength
)
2188 *dataLength
= bytes
;
2189 result
= errSSLWouldBlock
;
2196 result
= errSSLClosedGraceful
;
2197 else if (errno
== EAGAIN
)
2198 result
= errSSLWouldBlock
;
2200 result
= errSSLClosedAbort
;
2205 #endif /* HAVE_SSL && HAVE_CDSASSL */
2208 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2210 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2213 ssize_t
/* O - Number of bytes read or -1 on error */
2215 gnutls_transport_ptr ptr
, /* I - Connection to server */
2216 void *data
, /* I - Buffer */
2217 size_t length
) /* I - Number of bytes to read */
2219 http_t
*http
; /* HTTP connection */
2220 ssize_t bytes
; /* Bytes read */
2223 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2225 http
= (http_t
*)ptr
;
2227 if (!http
->blocking
)
2230 * Make sure we have data before we read...
2233 while (!_httpWait(http
, http
->wait_value
, 0))
2235 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2238 http
->error
= ETIMEDOUT
;
2243 bytes
= recv(http
->fd
, data
, length
, 0);
2244 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2247 #endif /* HAVE_SSL && HAVE_GNUTLS */
2251 * 'httpReconnect()' - Reconnect to a HTTP server.
2254 int /* O - 0 on success, non-zero on failure */
2255 httpReconnect(http_t
*http
) /* I - Connection to server */
2257 http_addrlist_t
*addr
; /* Connected address */
2259 http_addrlist_t
*current
; /* Current address */
2260 char temp
[256]; /* Temporary address string */
2264 DEBUG_printf(("httpReconnect(http=%p)", http
));
2272 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2273 http_shutdown_ssl(http
);
2275 #endif /* HAVE_SSL */
2278 * Close any previously open socket...
2283 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2286 closesocket(http
->fd
);
2295 * Connect to the server...
2299 for (current
= http
->addrlist
; current
; current
= current
->next
)
2300 DEBUG_printf(("2httpReconnect: Address %s:%d",
2301 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2302 _httpAddrPort(&(current
->addr
))));
2305 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
2308 * Unable to connect...
2312 http
->error
= WSAGetLastError();
2314 http
->error
= errno
;
2316 http
->status
= HTTP_ERROR
;
2318 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2319 strerror(http
->error
)));
2324 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2326 if (http
->timeout_value
> 0)
2327 http_set_timeout(http
->fd
, http
->timeout_value
);
2329 http
->hostaddr
= &(addr
->addr
);
2331 http
->status
= HTTP_CONTINUE
;
2332 http
->state
= HTTP_WAITING
;
2335 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2338 * Always do encryption via SSL.
2341 if (http_setup_ssl(http
) != 0)
2344 closesocket(http
->fd
);
2352 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2353 return (http_upgrade(http
));
2354 #endif /* HAVE_SSL */
2356 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2357 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2358 _httpAddrPort(http
->hostaddr
)));
2365 * 'httpSetAuthString()' - Set the current authorization string.
2367 * This function just stores a copy of the current authorization string in
2368 * the HTTP connection object. You must still call httpSetField() to set
2369 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2370 * httpHead(), httpOptions(), httpPost, or httpPut().
2372 * @since CUPS 1.3/Mac OS X 10.5@
2376 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2377 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2378 const char *data
) /* I - Auth data (NULL for none) */
2381 * Range check input...
2387 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2388 free(http
->authstring
);
2390 http
->authstring
= http
->_authstring
;
2395 * Set the current authorization string...
2398 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2401 if (len
> (int)sizeof(http
->_authstring
))
2403 if ((temp
= malloc(len
)) == NULL
)
2404 len
= sizeof(http
->_authstring
);
2406 http
->authstring
= temp
;
2410 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2412 strlcpy(http
->authstring
, scheme
, len
);
2417 * Clear the current authorization string...
2420 http
->_authstring
[0] = '\0';
2426 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2429 * @since CUPS 1.5/Mac OS X 10.7@
2432 int /* O - Status of call (0 = success) */
2433 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2434 cups_array_t
*credentials
) /* I - Array of credentials */
2436 if (!http
|| cupsArrayCount(credentials
) < 1)
2439 _httpFreeCredentials(http
->tls_credentials
);
2441 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2443 return (http
->tls_credentials
? 0 : -1);
2448 * 'httpSetCookie()' - Set the cookie value(s).
2450 * @since CUPS 1.1.19/Mac OS X 10.3@
2454 httpSetCookie(http_t
*http
, /* I - Connection */
2455 const char *cookie
) /* I - Cookie string */
2464 http
->cookie
= strdup(cookie
);
2466 http
->cookie
= NULL
;
2471 * 'httpSetExpect()' - Set the Expect: header in a request.
2473 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2475 * @since CUPS 1.2/Mac OS X 10.5@
2479 httpSetExpect(http_t
*http
, /* I - Connection to server */
2480 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2483 http
->expect
= expect
;
2488 * 'httpSetField()' - Set the value of an HTTP header.
2492 httpSetField(http_t
*http
, /* I - Connection to server */
2493 http_field_t field
, /* I - Field index */
2494 const char *value
) /* I - Value */
2497 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2498 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2502 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2504 if (field
== HTTP_FIELD_AUTHORIZATION
)
2507 * Special case for Authorization: as its contents can be
2508 * longer than HTTP_MAX_VALUE
2511 if (http
->field_authorization
)
2512 free(http
->field_authorization
);
2514 http
->field_authorization
= strdup(value
);
2516 else if (field
== HTTP_FIELD_HOST
)
2519 * Special-case for Host: as we don't want a trailing "." on the hostname and
2520 * need to bracket IPv6 numeric addresses.
2523 char *ptr
= strchr(value
, ':');
2525 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2528 * Bracket IPv6 numeric addresses...
2530 * This is slightly inefficient (basically copying twice), but is an edge
2531 * case and not worth optimizing...
2534 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2535 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2540 * Check for a trailing dot on the hostname...
2543 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2547 ptr
+= strlen(ptr
) - 1;
2558 * 'httpSetLength()' - Set the content-length and content-encoding.
2560 * @since CUPS 1.2/Mac OS X 10.5@
2564 httpSetLength(http_t
*http
, /* I - Connection to server */
2565 size_t length
) /* I - Length (0 for chunked) */
2572 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2573 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2577 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2578 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2579 CUPS_LLFMT
, CUPS_LLCAST length
);
2585 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2587 * The optional timeout callback receives both the HTTP connection and a user
2588 * data pointer and must return 1 to continue or 0 to error (time) out.
2590 * @since CUPS 1.5/Mac OS X 10.7@
2595 http_t
*http
, /* I - Connection to server */
2596 double timeout
, /* I - Number of seconds for timeout,
2597 must be greater than 0 */
2598 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2599 void *user_data
) /* I - User data pointer */
2601 if (!http
|| timeout
<= 0.0)
2604 http
->timeout_cb
= cb
;
2605 http
->timeout_data
= user_data
;
2606 http
->timeout_value
= timeout
;
2609 http_set_timeout(http
->fd
, timeout
);
2611 http_set_wait(http
);
2616 * 'httpTrace()' - Send an TRACE request to the server.
2619 int /* O - Status of call (0 = success) */
2620 httpTrace(http_t
*http
, /* I - Connection to server */
2621 const char *uri
) /* I - URI for trace */
2623 return (http_send(http
, HTTP_TRACE
, uri
));
2628 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2630 * Note: Unlike httpUpdate(), this function does not flush pending write data
2631 * and only retrieves a single status line from the HTTP connection.
2634 int /* O - 1 to continue, 0 to stop */
2635 _httpUpdate(http_t
*http
, /* I - Connection to server */
2636 http_status_t
*status
) /* O - Current HTTP status */
2638 char line
[32768], /* Line from connection... */
2639 *value
; /* Pointer to value on line */
2640 http_field_t field
; /* Field index */
2641 int major
, minor
; /* HTTP version numbers */
2644 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2645 http_states
[http
->state
]));
2648 * Grab a single line from the connection...
2651 if (!httpGets(line
, sizeof(line
), http
))
2653 *status
= HTTP_ERROR
;
2657 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2659 if (line
[0] == '\0')
2662 * Blank line means the start of the data section (if any). Return
2663 * the result code, too...
2665 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2666 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2670 if (http
->status
== HTTP_CONTINUE
)
2672 *status
= http
->status
;
2676 if (http
->status
< HTTP_BAD_REQUEST
)
2677 http
->digest_tries
= 0;
2680 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2682 if (http_setup_ssl(http
) != 0)
2685 closesocket(http
->fd
);
2690 *status
= http
->status
= HTTP_ERROR
;
2694 *status
= HTTP_CONTINUE
;
2697 #endif /* HAVE_SSL */
2699 httpGetLength2(http
);
2701 switch (http
->state
)
2705 case HTTP_POST_RECV
:
2708 case HTTP_POST_SEND
:
2713 http
->state
= HTTP_WAITING
;
2717 *status
= http
->status
;
2720 else if (!strncmp(line
, "HTTP/", 5))
2723 * Got the beginning of a response...
2726 int intstatus
; /* Status value as an integer */
2728 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2730 *status
= http
->status
= HTTP_ERROR
;
2734 http
->version
= (http_version_t
)(major
* 100 + minor
);
2735 *status
= http
->status
= (http_status_t
)intstatus
;
2737 else if ((value
= strchr(line
, ':')) != NULL
)
2744 while (_cups_isspace(*value
))
2748 * Be tolerants of servers that send unknown attribute fields...
2751 if (!_cups_strcasecmp(line
, "expect"))
2754 * "Expect: 100-continue" or similar...
2757 http
->expect
= (http_status_t
)atoi(value
);
2759 else if (!_cups_strcasecmp(line
, "cookie"))
2762 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2765 httpSetCookie(http
, value
);
2767 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
2768 httpSetField(http
, field
, value
);
2771 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
2776 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
2777 *status
= http
->status
= HTTP_ERROR
;
2786 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2789 http_status_t
/* O - HTTP status */
2790 httpUpdate(http_t
*http
) /* I - Connection to server */
2792 http_status_t status
; /* Request status */
2795 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2796 http_states
[http
->state
]));
2799 * Flush pending data, if any...
2804 DEBUG_puts("2httpUpdate: flushing buffer...");
2806 if (httpFlushWrite(http
) < 0)
2807 return (HTTP_ERROR
);
2811 * If we haven't issued any commands, then there is nothing to "update"...
2814 if (http
->state
== HTTP_WAITING
)
2815 return (HTTP_CONTINUE
);
2818 * Grab all of the lines we can from the connection...
2821 while (_httpUpdate(http
, &status
));
2824 * See if there was an error...
2827 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2829 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2830 return (http
->status
);
2835 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2836 strerror(http
->error
)));
2837 http
->status
= HTTP_ERROR
;
2838 return (HTTP_ERROR
);
2842 * Return the current status...
2850 * '_httpWait()' - Wait for data available on a connection (no flush).
2853 int /* O - 1 if data is available, 0 otherwise */
2854 _httpWait(http_t
*http
, /* I - Connection to server */
2855 int msec
, /* I - Milliseconds to wait */
2856 int usessl
) /* I - Use SSL context? */
2859 struct pollfd pfd
; /* Polled file descriptor */
2861 fd_set input_set
; /* select() input set */
2862 struct timeval timeout
; /* Timeout */
2863 #endif /* HAVE_POLL */
2864 int nfds
; /* Result from select()/poll() */
2867 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2871 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2876 * Check the SSL/TLS buffers for data first...
2880 if (http
->tls
&& usessl
)
2883 if (SSL_pending(http
->tls
))
2885 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2889 # elif defined(HAVE_GNUTLS)
2890 if (gnutls_record_check_pending(http
->tls
))
2892 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2896 # elif defined(HAVE_CDSASSL)
2897 size_t bytes
; /* Bytes that are available */
2899 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2902 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2905 # endif /* HAVE_LIBSSL */
2907 #endif /* HAVE_SSL */
2910 * Then try doing a select() or poll() to poll the socket...
2915 pfd
.events
= POLLIN
;
2917 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2918 (errno
== EINTR
|| errno
== EAGAIN
));
2923 FD_ZERO(&input_set
);
2924 FD_SET(http
->fd
, &input_set
);
2926 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2930 timeout
.tv_sec
= msec
/ 1000;
2931 timeout
.tv_usec
= (msec
% 1000) * 1000;
2933 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2936 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2938 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2941 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2942 WSAGetLastError() == WSAEWOULDBLOCK
));
2944 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2946 #endif /* HAVE_POLL */
2948 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2956 * 'httpWait()' - Wait for data available on a connection.
2958 * @since CUPS 1.1.19/Mac OS X 10.3@
2961 int /* O - 1 if data is available, 0 otherwise */
2962 httpWait(http_t
*http
, /* I - Connection to server */
2963 int msec
) /* I - Milliseconds to wait */
2966 * First see if there is data in the buffer...
2969 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
2976 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
2981 * Flush pending data, if any...
2986 DEBUG_puts("3httpWait: Flushing write buffer.");
2988 if (httpFlushWrite(http
) < 0)
2993 * If not, check the SSL/TLS buffers and do a select() on the connection...
2996 return (_httpWait(http
, msec
, 1));
3001 * 'httpWrite()' - Write data to a HTTP connection.
3003 * This function is deprecated. Use the httpWrite2() function which can
3004 * write more than 2GB of data.
3009 int /* O - Number of bytes written */
3010 httpWrite(http_t
*http
, /* I - Connection to server */
3011 const char *buffer
, /* I - Buffer for data */
3012 int length
) /* I - Number of bytes to write */
3014 return ((int)httpWrite2(http
, buffer
, length
));
3019 * 'httpWrite2()' - Write data to a HTTP connection.
3021 * @since CUPS 1.2/Mac OS X 10.5@
3024 ssize_t
/* O - Number of bytes written */
3025 httpWrite2(http_t
*http
, /* I - Connection to server */
3026 const char *buffer
, /* I - Buffer for data */
3027 size_t length
) /* I - Number of bytes to write */
3029 ssize_t bytes
; /* Bytes written */
3032 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3033 buffer
, CUPS_LLCAST length
));
3036 * Range check input...
3039 if (http
== NULL
|| buffer
== NULL
)
3043 * Mark activity on the connection...
3046 http
->activity
= time(NULL
);
3049 * Buffer small writes for better performance...
3054 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3056 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3057 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3059 httpFlushWrite(http
);
3062 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3063 length
< sizeof(http
->wbuffer
))
3066 * Write to buffer...
3069 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3070 CUPS_LLCAST length
));
3072 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3073 http
->wused
+= (int)length
;
3074 bytes
= (ssize_t
)length
;
3079 * Otherwise write the data directly...
3082 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3083 CUPS_LLCAST length
));
3085 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3086 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3088 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3090 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3091 CUPS_LLCAST bytes
));
3094 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3095 http
->data_remaining
-= bytes
;
3101 * Handle end-of-request processing...
3104 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3105 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3108 * Finished with the transfer; unless we are sending POST or PUT
3112 DEBUG_puts("2httpWrite: changing states...");
3115 httpFlushWrite(http
);
3117 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3120 * Send a 0-length chunk at the end of the request...
3123 http_write(http
, "0\r\n\r\n", 5);
3126 * Reset the data state...
3129 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3130 http
->data_remaining
= 0;
3138 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3140 * '_httpWriteCDSA()' - Write function for the CDSA library.
3143 OSStatus
/* O - -1 on error, 0 on success */
3145 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3146 const void *data
, /* I - Data buffer */
3147 size_t *dataLength
) /* IO - Number of bytes */
3149 OSStatus result
; /* Return value */
3150 ssize_t bytes
; /* Number of bytes read */
3151 http_t
*http
; /* HTTP connection */
3154 http
= (http_t
*)connection
;
3158 bytes
= write(http
->fd
, data
, *dataLength
);
3160 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3162 if (bytes
== *dataLength
)
3166 else if (bytes
>= 0)
3168 *dataLength
= bytes
;
3169 result
= errSSLWouldBlock
;
3175 if (errno
== EAGAIN
)
3176 result
= errSSLWouldBlock
;
3178 result
= errSSLClosedAbort
;
3183 #endif /* HAVE_SSL && HAVE_CDSASSL */
3186 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3188 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3191 ssize_t
/* O - Number of bytes written or -1 on error */
3193 gnutls_transport_ptr ptr
, /* I - Connection to server */
3194 const void *data
, /* I - Data buffer */
3195 size_t length
) /* I - Number of bytes to write */
3197 ssize_t bytes
; /* Bytes written */
3200 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3202 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3204 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3205 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3208 #endif /* HAVE_SSL && HAVE_GNUTLS */
3211 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3213 * 'http_bio_ctrl()' - Control the HTTP connection.
3216 static long /* O - Result/data */
3217 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3218 int cmd
, /* I - Control command */
3219 long arg1
, /* I - First argument */
3220 void *arg2
) /* I - Second argument */
3227 case BIO_CTRL_RESET
:
3231 case BIO_C_SET_FILE_PTR
:
3236 case BIO_C_GET_FILE_PTR
:
3239 *((void **)arg2
) = h
->ptr
;
3246 case BIO_CTRL_FLUSH
:
3253 * 'http_bio_free()' - Free OpenSSL data.
3256 static int /* O - 1 on success, 0 on failure */
3257 http_bio_free(BIO
*h
) /* I - BIO data */
3273 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3276 static int /* O - 1 on success, 0 on failure */
3277 http_bio_new(BIO
*h
) /* I - BIO data */
3292 * 'http_bio_puts()' - Send a string for OpenSSL.
3295 static int /* O - Bytes written */
3296 http_bio_puts(BIO
*h
, /* I - BIO data */
3297 const char *str
) /* I - String to write */
3300 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3302 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3308 * 'http_bio_read()' - Read data for OpenSSL.
3311 static int /* O - Bytes read */
3312 http_bio_read(BIO
*h
, /* I - BIO data */
3313 char *buf
, /* I - Buffer */
3314 int size
) /* I - Number of bytes to read */
3316 http_t
*http
; /* HTTP connection */
3319 http
= (http_t
*)h
->ptr
;
3321 if (!http
->blocking
)
3324 * Make sure we have data before we read...
3327 while (!_httpWait(http
, http
->wait_value
, 0))
3329 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
3333 http
->error
= WSAETIMEDOUT
;
3335 http
->error
= ETIMEDOUT
;
3342 return (recv(http
->fd
, buf
, size
, 0));
3347 * 'http_bio_write()' - Write data for OpenSSL.
3350 static int /* O - Bytes written */
3351 http_bio_write(BIO
*h
, /* I - BIO data */
3352 const char *buf
, /* I - Buffer to write */
3353 int num
) /* I - Number of bytes to write */
3355 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3357 #endif /* HAVE_SSL && HAVE_LIBSSL */
3362 * 'http_debug_hex()' - Do a hex dump of a buffer.
3366 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3367 const char *buffer
, /* I - Buffer to dump */
3368 int bytes
) /* I - Bytes to dump */
3370 int i
, j
, /* Looping vars */
3371 ch
; /* Current character */
3372 char line
[255], /* Line buffer */
3373 *start
, /* Start of line after prefix */
3374 *ptr
; /* Pointer into line */
3377 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3380 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
3382 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3383 start
= line
+ strlen(line
);
3385 for (i
= 0; i
< bytes
; i
+= 16)
3387 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3388 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3400 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3402 ch
= buffer
[i
+ j
] & 255;
3404 if (ch
< ' ' || ch
>= 127)
3418 * 'http_field()' - Return the field index for a field name.
3421 static http_field_t
/* O - Field index */
3422 http_field(const char *name
) /* I - String name */
3424 int i
; /* Looping var */
3427 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3428 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
3429 return ((http_field_t
)i
);
3431 return (HTTP_FIELD_UNKNOWN
);
3437 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3440 static int /* O - Bytes read */
3441 http_read_ssl(http_t
*http
, /* I - Connection to server */
3442 char *buf
, /* I - Buffer to store data */
3443 int len
) /* I - Length of buffer */
3445 # if defined(HAVE_LIBSSL)
3446 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3448 # elif defined(HAVE_GNUTLS)
3449 ssize_t result
; /* Return value */
3452 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3454 if (result
< 0 && !errno
)
3457 * Convert GNU TLS error to errno value...
3462 case GNUTLS_E_INTERRUPTED
:
3466 case GNUTLS_E_AGAIN
:
3478 return ((int)result
);
3480 # elif defined(HAVE_CDSASSL)
3481 int result
; /* Return value */
3482 OSStatus error
; /* Error info */
3483 size_t processed
; /* Number of bytes processed */
3486 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3487 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
3492 result
= (int)processed
;
3495 case errSSLWouldBlock
:
3497 result
= (int)processed
;
3505 case errSSLClosedGraceful
:
3508 result
= (int)processed
;
3519 # elif defined(HAVE_SSPISSL)
3520 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3521 # endif /* HAVE_LIBSSL */
3523 #endif /* HAVE_SSL */
3527 * 'http_send()' - Send a request with all fields and the trailing blank line.
3530 static int /* O - 0 on success, non-zero on error */
3531 http_send(http_t
*http
, /* I - Connection to server */
3532 http_state_t request
, /* I - Request code */
3533 const char *uri
) /* I - URI */
3535 int i
; /* Looping var */
3536 char buf
[1024]; /* Encoded URI buffer */
3537 static const char * const codes
[] =
3538 { /* Request code strings */
3555 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3556 http
, codes
[request
], uri
));
3558 if (http
== NULL
|| uri
== NULL
)
3562 * Set the User-Agent field if it isn't already...
3565 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3566 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3569 * Encode the URI as needed...
3572 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3575 * See if we had an error the last time around; if so, reconnect...
3578 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3579 if (httpReconnect(http
))
3583 * Flush any written data that is pending...
3588 if (httpFlushWrite(http
) < 0)
3589 if (httpReconnect(http
))
3594 * Send the request header...
3597 http
->state
= request
;
3598 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3600 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3603 http
->status
= HTTP_CONTINUE
;
3606 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3608 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3609 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3611 #endif /* HAVE_SSL */
3613 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3615 http
->status
= HTTP_ERROR
;
3619 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3620 if (http
->fields
[i
][0] != '\0')
3622 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3623 httpGetField(http
, i
)));
3625 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3626 httpGetField(http
, i
)) < 1)
3628 http
->status
= HTTP_ERROR
;
3634 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3636 http
->status
= HTTP_ERROR
;
3640 if (http
->expect
== HTTP_CONTINUE
&&
3641 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3642 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3644 http
->status
= HTTP_ERROR
;
3648 if (httpPrintf(http
, "\r\n") < 1)
3650 http
->status
= HTTP_ERROR
;
3654 if (httpFlushWrite(http
) < 0)
3657 httpGetLength2(http
);
3658 httpClearFields(http
);
3661 * The Kerberos and AuthRef authentication strings can only be used once...
3664 if (http
->field_authorization
&& http
->authstring
&&
3665 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3666 !strncmp(http
->authstring
, "AuthRef", 7)))
3668 http
->_authstring
[0] = '\0';
3670 if (http
->authstring
!= http
->_authstring
)
3671 free(http
->authstring
);
3673 http
->authstring
= http
->_authstring
;
3681 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
3683 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3686 static int /* O - Status of connection */
3687 http_set_credentials(http_t
*http
) /* I - Connection to server */
3689 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3690 OSStatus error
= 0; /* Error code */
3691 http_tls_credentials_t credentials
= NULL
;
3692 /* TLS credentials */
3695 DEBUG_printf(("7http_set_credentials(%p)", http
));
3698 * Prefer connection specific credentials...
3701 if ((credentials
= http
->tls_credentials
) == NULL
)
3702 credentials
= cg
->tls_credentials
;
3704 # if HAVE_SECPOLICYCREATESSL
3706 * Otherwise root around in the user's keychain to see if one can be found...
3711 CFDictionaryRef query
; /* Query dictionary */
3712 CFTypeRef matches
= NULL
; /* Matching credentials */
3713 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3714 CFTypeRef keys
[] = { kSecClass
,
3717 /* Keys for dictionary */
3718 CFTypeRef values
[] = { kSecClassCertificate
,
3721 /* Values for dictionary */
3724 * Get the names associated with the server.
3727 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3729 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3735 * Create a query which will return all identities that can sign and match
3736 * the passed in policy.
3739 query
= CFDictionaryCreate(NULL
,
3740 (const void**)(&keys
[0]),
3741 (const void**)(&values
[0]),
3742 sizeof(keys
) / sizeof(keys
[0]),
3743 &kCFTypeDictionaryKeyCallBacks
,
3744 &kCFTypeDictionaryValueCallBacks
);
3747 error
= SecItemCopyMatching(query
, &matches
);
3748 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3757 CFRelease(dn_array
);
3759 # endif /* HAVE_SECPOLICYCREATESSL */
3763 error
= SSLSetCertificate(http
->tls
, credentials
);
3764 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3768 DEBUG_puts("4http_set_credentials: No credentials to set.");
3772 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
3773 #endif /* HAVE_SSL */
3777 * 'http_set_timeout()' - Set the socket timeout values.
3781 http_set_timeout(int fd
, /* I - File descriptor */
3782 double timeout
) /* I - Timeout in seconds */
3785 DWORD tv
= (DWORD
)(timeout
* 1000);
3786 /* Timeout in milliseconds */
3788 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&tv
, sizeof(tv
));
3789 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&tv
, sizeof(tv
));
3792 struct timeval tv
; /* Timeout in secs and usecs */
3794 tv
.tv_sec
= (int)timeout
;
3795 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
3797 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, &tv
, sizeof(tv
));
3798 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
3804 * 'http_set_wait()' - Set the default wait value for reads.
3808 http_set_wait(http_t
*http
) /* I - Connection to server */
3812 http
->wait_value
= (int)(http
->timeout_value
* 1000);
3814 if (http
->wait_value
<= 0)
3815 http
->wait_value
= 60000;
3818 http
->wait_value
= 10000;
3824 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3827 static int /* O - 0 on success, -1 on failure */
3828 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3830 _cups_globals_t
*cg
= _cupsGlobals();
3831 /* Pointer to library globals */
3832 int any_root
; /* Allow any root */
3835 SSL_CTX
*context
; /* Context for encryption */
3836 BIO
*bio
; /* BIO data */
3837 const char *message
= NULL
;/* Error message */
3838 # elif defined(HAVE_GNUTLS)
3839 int status
; /* Status of handshake */
3840 gnutls_certificate_client_credentials
*credentials
;
3841 /* TLS credentials */
3842 # elif defined(HAVE_CDSASSL)
3843 OSStatus error
; /* Error code */
3844 char *hostname
; /* Hostname */
3845 const char *message
= NULL
;/* Error message */
3846 # ifdef HAVE_SECCERTIFICATECOPYDATA
3847 cups_array_t
*credentials
; /* Credentials array */
3848 cups_array_t
*names
; /* CUPS distinguished names */
3849 CFArrayRef dn_array
; /* CF distinguished names array */
3850 CFIndex count
; /* Number of credentials */
3851 CFDataRef data
; /* Certificate data */
3852 int i
; /* Looping var */
3853 http_credential_t
*credential
; /* Credential data */
3854 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3855 # elif defined(HAVE_SSPISSL)
3856 TCHAR username
[256]; /* Username returned from GetUserName() */
3857 TCHAR commonName
[256];/* Common name for certificate */
3858 DWORD dwSize
; /* 32 bit size */
3859 # endif /* HAVE_LIBSSL */
3862 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3865 * Always allow self-signed certificates for the local loopback address...
3868 if (httpAddrLocalhost(http
->hostaddr
))
3871 any_root
= cg
->any_root
;
3876 context
= SSL_CTX_new(SSLv23_client_method());
3878 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3880 bio
= BIO_new(_httpBIOMethods());
3881 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3883 http
->tls
= SSL_new(context
);
3884 SSL_set_bio(http
->tls
, bio
, bio
);
3886 if (SSL_connect(http
->tls
) != 1)
3888 unsigned long error
; /* Error code */
3890 while ((error
= ERR_get_error()) != 0)
3892 message
= ERR_error_string(error
, NULL
);
3893 DEBUG_printf(("8http_setup_ssl: %s", message
));
3896 SSL_CTX_free(context
);
3897 SSL_free(http
->tls
);
3901 http
->error
= WSAGetLastError();
3903 http
->error
= errno
;
3905 http
->status
= HTTP_ERROR
;
3908 message
= _("Unable to establish a secure connection to host.");
3910 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
3915 # elif defined(HAVE_GNUTLS)
3918 credentials
= (gnutls_certificate_client_credentials
*)
3919 malloc(sizeof(gnutls_certificate_client_credentials
));
3920 if (credentials
== NULL
)
3922 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
3924 http
->error
= errno
;
3925 http
->status
= HTTP_ERROR
;
3926 _cupsSetHTTPError(HTTP_ERROR
);
3931 gnutls_certificate_allocate_credentials(credentials
);
3933 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3934 gnutls_set_default_priority(http
->tls
);
3935 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, http
->hostname
, strlen(http
->hostname
));
3936 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3937 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3938 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3939 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3941 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3943 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
3944 status
, gnutls_strerror(status
)));
3946 if (gnutls_error_is_fatal(status
))
3949 http
->status
= HTTP_ERROR
;
3951 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
3953 gnutls_deinit(http
->tls
);
3954 gnutls_certificate_free_credentials(*credentials
);
3962 http
->tls_credentials
= credentials
;
3964 # elif defined(HAVE_CDSASSL)
3965 if ((error
= SSLNewContext(false, &http
->tls
)))
3967 http
->error
= errno
;
3968 http
->status
= HTTP_ERROR
;
3969 _cupsSetHTTPError(HTTP_ERROR
);
3974 error
= SSLSetConnection(http
->tls
, http
);
3975 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
3979 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
3980 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
3985 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
3986 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
3987 any_root
, (int)error
));
3992 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
3993 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
3994 cg
->expired_certs
, (int)error
));
3999 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
4000 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
4001 cg
->expired_root
, (int)error
));
4004 # ifdef HAVE_SSLSETPROTOCOLVERSIONMAX
4007 error
= SSLSetProtocolVersionMax(http
->tls
, kTLSProtocol1
);
4008 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionMax(kTLSProtocol1), "
4009 "error=%d", (int)error
));
4011 # endif /* HAVE_SSLSETPROTOCOLVERSIONMAX */
4014 * In general, don't verify certificates since things like the common name
4015 * often do not match...
4020 error
= SSLSetEnableCertVerify(http
->tls
, false);
4021 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
4025 # ifdef HAVE_SECCERTIFICATECOPYDATA
4028 if (cg
->client_cert_cb
)
4030 error
= SSLSetSessionOption(http
->tls
,
4031 kSSLSessionOptionBreakOnCertRequested
, true);
4032 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
4033 "error=%d", (int)error
));
4037 error
= http_set_credentials(http
);
4038 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
4044 * If there's a server certificate callback installed let it evaluate the
4045 * certificate(s) during the handshake...
4048 if (!error
&& cg
->server_cert_cb
!= NULL
)
4050 error
= SSLSetSessionOption(http
->tls
,
4051 kSSLSessionOptionBreakOnServerAuth
, true);
4052 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
4053 "error=%d", (int)error
));
4055 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4058 * Let the server know which hostname/domain we are trying to connect to
4059 * in case it wants to serve up a certificate with a matching common name.
4064 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
4065 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
4067 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
4073 int done
= 0; /* Are we done yet? */
4075 while (!error
&& !done
)
4077 error
= SSLHandshake(http
->tls
);
4079 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
4087 case errSSLWouldBlock
:
4091 # ifdef HAVE_SECCERTIFICATECOPYDATA
4092 case errSSLServerAuthCompleted
:
4094 if (cg
->server_cert_cb
)
4096 error
= httpCopyCredentials(http
, &credentials
);
4099 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
4100 cg
->server_cert_data
);
4101 httpFreeCredentials(credentials
);
4104 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
4105 "returned %d.", (int)error
));
4109 case errSSLClientCertRequested
:
4112 if (cg
->client_cert_cb
)
4115 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
4118 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
4120 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
4122 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
4124 if ((credential
= malloc(sizeof(*credential
))))
4126 credential
->datalen
= CFDataGetLength(data
);
4127 if ((credential
->data
= malloc(credential
->datalen
)))
4129 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
4130 credential
->datalen
);
4131 cupsArrayAdd(names
, credential
);
4137 CFRelease(dn_array
);
4142 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
4143 cg
->client_cert_data
);
4145 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
4146 "returned %d.", (int)error
));
4149 httpFreeCredentials(names
);
4152 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4154 case errSSLUnknownRootCert
:
4155 message
= _("Unable to establish a secure connection to host "
4156 "(untrusted certificate).");
4159 case errSSLNoRootCert
:
4160 message
= _("Unable to establish a secure connection to host "
4161 "(self-signed certificate).");
4164 case errSSLCertExpired
:
4165 message
= _("Unable to establish a secure connection to host "
4166 "(expired certificate).");
4169 case errSSLCertNotYetValid
:
4170 message
= _("Unable to establish a secure connection to host "
4171 "(certificate not yet valid).");
4174 case errSSLHostNameMismatch
:
4175 message
= _("Unable to establish a secure connection to host "
4176 "(host name mismatch).");
4179 case errSSLXCertChainInvalid
:
4180 message
= _("Unable to establish a secure connection to host "
4181 "(certificate chain invalid).");
4184 case errSSLConnectionRefused
:
4185 message
= _("Unable to establish a secure connection to host "
4186 "(peer dropped connection before responding).");
4197 http
->error
= error
;
4198 http
->status
= HTTP_ERROR
;
4199 errno
= ECONNREFUSED
;
4201 SSLDisposeContext(http
->tls
);
4205 * If an error string wasn't set by the callbacks use a generic one...
4209 #ifdef HAVE_CSSMERRORSTRING
4210 message
= cssmErrorString(error
);
4212 message
= _("Unable to establish a secure connection to host.");
4213 #endif /* HAVE_CSSMERRORSTRING */
4215 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4220 # elif defined(HAVE_SSPISSL)
4221 http
->tls
= _sspiAlloc();
4225 _cupsSetHTTPError(HTTP_ERROR
);
4229 http
->tls
->sock
= http
->fd
;
4230 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4231 GetUserName(username
, &dwSize
);
4232 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4233 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4235 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4238 _sspiFree(http
->tls_credentials
);
4239 http
->tls_credentials
= NULL
;
4242 http
->status
= HTTP_ERROR
;
4244 _cupsSetError(IPP_PKI_ERROR
,
4245 _("Unable to establish a secure connection to host."), 1);
4250 _sspiSetAllowsAnyRoot(http
->tls_credentials
, any_root
);
4251 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4253 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
4255 _sspiFree(http
->tls_credentials
);
4256 http
->tls_credentials
= NULL
;
4259 http
->status
= HTTP_ERROR
;
4261 _cupsSetError(IPP_PKI_ERROR
,
4262 _("Unable to establish a secure connection to host."), 1);
4266 # endif /* HAVE_CDSASSL */
4273 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4277 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4280 SSL_CTX
*context
; /* Context for encryption */
4282 context
= SSL_get_SSL_CTX(http
->tls
);
4284 SSL_shutdown(http
->tls
);
4285 SSL_CTX_free(context
);
4286 SSL_free(http
->tls
);
4288 # elif defined(HAVE_GNUTLS)
4289 gnutls_certificate_client_credentials
*credentials
;
4290 /* TLS credentials */
4292 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4294 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4295 gnutls_deinit(http
->tls
);
4296 gnutls_certificate_free_credentials(*credentials
);
4299 # elif defined(HAVE_CDSASSL)
4300 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4303 SSLDisposeContext(http
->tls
);
4305 if (http
->tls_credentials
)
4306 CFRelease(http
->tls_credentials
);
4308 # elif defined(HAVE_SSPISSL)
4309 _sspiFree(http
->tls_credentials
);
4310 # endif /* HAVE_LIBSSL */
4313 http
->tls_credentials
= NULL
;
4315 #endif /* HAVE_SSL */
4320 * 'http_upgrade()' - Force upgrade to TLS encryption.
4323 static int /* O - Status of connection */
4324 http_upgrade(http_t
*http
) /* I - Connection to server */
4326 int ret
; /* Return value */
4327 http_t myhttp
; /* Local copy of HTTP data */
4330 DEBUG_printf(("7http_upgrade(%p)", http
));
4333 * Flush the connection to make sure any previous "Upgrade" message
4340 * Copy the HTTP data to a local variable so we can do the OPTIONS
4341 * request without interfering with the existing request data...
4344 memcpy(&myhttp
, http
, sizeof(myhttp
));
4347 * Send an OPTIONS request to the server, requiring SSL or TLS
4348 * encryption on the link...
4351 http
->field_authorization
= NULL
; /* Don't free the auth string */
4353 httpClearFields(http
);
4354 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4355 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4357 if ((ret
= httpOptions(http
, "*")) == 0)
4360 * Wait for the secure connection...
4363 while (httpUpdate(http
) == HTTP_CONTINUE
);
4367 * Restore the HTTP request data...
4370 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4371 http
->data_encoding
= myhttp
.data_encoding
;
4372 http
->data_remaining
= myhttp
.data_remaining
;
4373 http
->_data_remaining
= myhttp
._data_remaining
;
4374 http
->expect
= myhttp
.expect
;
4375 http
->field_authorization
= myhttp
.field_authorization
;
4376 http
->digest_tries
= myhttp
.digest_tries
;
4379 * See if we actually went secure...
4385 * Server does not support HTTP upgrade...
4388 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4391 closesocket(http
->fd
);
4403 #endif /* HAVE_SSL */
4407 * 'http_write()' - Write a buffer to a HTTP connection.
4410 static int /* O - Number of bytes written */
4411 http_write(http_t
*http
, /* I - Connection to server */
4412 const char *buffer
, /* I - Buffer for data */
4413 int length
) /* I - Number of bytes to write */
4415 int tbytes
, /* Total bytes sent */
4416 bytes
; /* Bytes sent */
4419 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4426 if (http
->timeout_cb
)
4429 struct pollfd pfd
; /* Polled file descriptor */
4431 fd_set output_set
; /* Output ready for write? */
4432 struct timeval timeout
; /* Timeout value */
4433 #endif /* HAVE_POLL */
4434 int nfds
; /* Result from select()/poll() */
4440 pfd
.events
= POLLOUT
;
4442 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
4443 (errno
== EINTR
|| errno
== EAGAIN
));
4448 FD_ZERO(&output_set
);
4449 FD_SET(http
->fd
, &output_set
);
4451 timeout
.tv_sec
= http
->wait_value
/ 1000;
4452 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
4454 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
4457 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
4458 WSAGetLastError() == WSAEWOULDBLOCK
));
4460 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
4462 #endif /* HAVE_POLL */
4466 http
->error
= errno
;
4469 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4472 http
->error
= WSAEWOULDBLOCK
;
4474 http
->error
= EWOULDBLOCK
;
4484 bytes
= http_write_ssl(http
, buffer
, length
);
4486 #endif /* HAVE_SSL */
4487 bytes
= send(http
->fd
, buffer
, length
, 0);
4492 if (WSAGetLastError() == WSAEINTR
)
4494 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4496 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4499 http
->error
= WSAGetLastError();
4501 else if (WSAGetLastError() != http
->error
&&
4502 WSAGetLastError() != WSAECONNRESET
)
4504 http
->error
= WSAGetLastError();
4511 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4513 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4515 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4518 http
->error
= errno
;
4520 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4522 http
->error
= errno
;
4527 DEBUG_printf(("3http_write: error writing data (%s).",
4528 strerror(http
->error
)));
4539 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4542 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4549 * 'http_write_chunk()' - Write a chunked buffer.
4552 static int /* O - Number bytes written */
4553 http_write_chunk(http_t
*http
, /* I - Connection to server */
4554 const char *buffer
, /* I - Buffer to write */
4555 int length
) /* I - Length of buffer */
4557 char header
[255]; /* Chunk header */
4558 int bytes
; /* Bytes written */
4561 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4562 http
, buffer
, length
));
4565 * Write the chunk header, data, and trailer.
4568 sprintf(header
, "%x\r\n", length
);
4569 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4571 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4575 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4577 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4581 if (http_write(http
, "\r\n", 2) < 0)
4583 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4593 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4596 static int /* O - Bytes written */
4597 http_write_ssl(http_t
*http
, /* I - Connection to server */
4598 const char *buf
, /* I - Buffer holding data */
4599 int len
) /* I - Length of buffer */
4601 ssize_t result
; /* Return value */
4604 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4606 # if defined(HAVE_LIBSSL)
4607 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4609 # elif defined(HAVE_GNUTLS)
4610 result
= gnutls_record_send(http
->tls
, buf
, len
);
4612 if (result
< 0 && !errno
)
4615 * Convert GNU TLS error to errno value...
4620 case GNUTLS_E_INTERRUPTED
:
4624 case GNUTLS_E_AGAIN
:
4636 # elif defined(HAVE_CDSASSL)
4637 OSStatus error
; /* Error info */
4638 size_t processed
; /* Number of bytes processed */
4641 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4646 result
= (int)processed
;
4649 case errSSLWouldBlock
:
4651 result
= (int)processed
;
4659 case errSSLClosedGraceful
:
4662 result
= (int)processed
;
4670 # elif defined(HAVE_SSPISSL)
4671 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
4672 # endif /* HAVE_LIBSSL */
4674 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4676 return ((int)result
);
4678 #endif /* HAVE_SSL */
4682 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".