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 * httpGets() - Get a line of text from a HTTP connection.
60 * httpGetState() - Get the current state of the HTTP request.
61 * httpGetStatus() - Get the status of the last HTTP request.
62 * httpGetSubField() - Get a sub-field value.
63 * httpGetSubField2() - Get a sub-field value.
64 * httpGetVersion() - Get the HTTP version at the other end.
65 * httpHead() - Send a HEAD request to the server.
66 * httpInitialize() - Initialize the HTTP interface library and set
67 * the default HTTP proxy (if any).
68 * httpOptions() - Send an OPTIONS request to the server.
69 * _httpPeek() - Peek at data from a HTTP connection.
70 * httpPost() - Send a POST request to the server.
71 * httpPrintf() - Print a formatted string to a HTTP connection.
72 * httpPut() - Send a PUT request to the server.
73 * httpRead() - Read data from a HTTP connection.
74 * httpRead2() - Read data from a HTTP connection.
75 * _httpReadCDSA() - Read function for the CDSA library.
76 * _httpReadGNUTLS() - Read function for the GNU TLS library.
77 * httpReconnect() - Reconnect to a HTTP server.
78 * httpSetAuthString() - Set the current authorization string.
79 * httpSetCredentials() - Set the credentials associated with an
80 * encrypted connection.
81 * httpSetCookie() - Set the cookie value(s).
82 * httpSetExpect() - Set the Expect: header in a request.
83 * httpSetField() - Set the value of an HTTP header.
84 * httpSetLength() - Set the content-length and content-encoding.
85 * httpSetTimeout() - Set read/write timeouts and an optional
87 * httpTrace() - Send an TRACE request to the server.
88 * _httpUpdate() - Update the current HTTP status for incoming
90 * httpUpdate() - Update the current HTTP state for incoming
92 * _httpWait() - Wait for data available on a connection (no
94 * httpWait() - Wait for data available on a connection.
95 * httpWrite() - Write data to a HTTP connection.
96 * httpWrite2() - Write data to a HTTP connection.
97 * _httpWriteCDSA() - Write function for the CDSA library.
98 * _httpWriteGNUTLS() - Write function for the GNU TLS library.
99 * http_bio_ctrl() - Control the HTTP connection.
100 * http_bio_free() - Free OpenSSL data.
101 * http_bio_new() - Initialize an OpenSSL BIO structure.
102 * http_bio_puts() - Send a string for OpenSSL.
103 * http_bio_read() - Read data for OpenSSL.
104 * http_bio_write() - Write data for OpenSSL.
105 * http_debug_hex() - Do a hex dump of a buffer.
106 * http_field() - Return the field index for a field name.
107 * http_read_ssl() - Read from a SSL/TLS connection.
108 * http_send() - Send a request with all fields and the trailing
110 * http_set_credentials() - Set the SSL/TLS credentials.
111 * http_set_timeout() - Set the socket timeout values.
112 * http_set_wait() - Set the default wait value for reads.
113 * http_setup_ssl() - Set up SSL/TLS support on a connection.
114 * http_shutdown_ssl() - Shut down SSL/TLS on a connection.
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 * 'httpGets()' - Get a line of text from a HTTP connection.
1123 char * /* O - Line or NULL */
1124 httpGets(char *line
, /* I - Line to read into */
1125 int length
, /* I - Max length of buffer */
1126 http_t
*http
) /* I - Connection to server */
1128 char *lineptr
, /* Pointer into line */
1129 *lineend
, /* End of line */
1130 *bufptr
, /* Pointer into input buffer */
1131 *bufend
; /* Pointer to end of buffer */
1132 int bytes
, /* Number of bytes read */
1133 eol
; /* End-of-line? */
1136 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1138 if (http
== NULL
|| line
== NULL
)
1142 * Read a line from the buffer...
1147 lineend
= line
+ length
- 1;
1150 while (lineptr
< lineend
)
1153 * Pre-load the buffer as needed...
1162 while (http
->used
== 0)
1165 * No newline; see if there is more data to be read...
1168 while (!_httpWait(http
, http
->wait_value
, 1))
1170 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1173 DEBUG_puts("3httpGets: Timed out!");
1175 http
->error
= WSAETIMEDOUT
;
1177 http
->error
= ETIMEDOUT
;
1184 bytes
= http_read_ssl(http
, http
->buffer
+ http
->used
,
1185 HTTP_MAX_BUFFER
- http
->used
);
1187 #endif /* HAVE_SSL */
1188 bytes
= recv(http
->fd
, http
->buffer
+ http
->used
,
1189 HTTP_MAX_BUFFER
- http
->used
, 0);
1191 DEBUG_printf(("4httpGets: read %d bytes...", bytes
));
1196 * Nope, can't get a line this time...
1200 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1202 if (WSAGetLastError() == WSAEINTR
)
1204 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1206 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1209 http
->error
= WSAGetLastError();
1211 else if (WSAGetLastError() != http
->error
)
1213 http
->error
= WSAGetLastError();
1218 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1222 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1224 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1226 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1229 http
->error
= errno
;
1231 else if (errno
!= http
->error
)
1233 http
->error
= errno
;
1240 else if (bytes
== 0)
1242 http
->error
= EPIPE
;
1248 * Yup, update the amount used...
1251 http
->used
+= bytes
;
1255 * Now copy as much of the current line as possible...
1258 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1259 lineptr
< lineend
&& bufptr
< bufend
;)
1261 if (*bufptr
== 0x0a)
1267 else if (*bufptr
== 0x0d)
1270 *lineptr
++ = *bufptr
++;
1273 http
->used
-= (int)(bufptr
- http
->buffer
);
1275 memmove(http
->buffer
, bufptr
, http
->used
);
1283 http
->activity
= time(NULL
);
1287 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1293 DEBUG_puts("3httpGets: No new line available!");
1300 * 'httpGetState()' - Get the current state of the HTTP request.
1303 http_state_t
/* O - HTTP state */
1304 httpGetState(http_t
*http
) /* I - Connection to server */
1306 return (http
? http
->state
: HTTP_ERROR
);
1311 * 'httpGetStatus()' - Get the status of the last HTTP request.
1313 * @since CUPS 1.2/Mac OS X 10.5@
1316 http_status_t
/* O - HTTP status */
1317 httpGetStatus(http_t
*http
) /* I - Connection to server */
1319 return (http
? http
->status
: HTTP_ERROR
);
1324 * 'httpGetSubField()' - Get a sub-field value.
1329 char * /* O - Value or NULL */
1330 httpGetSubField(http_t
*http
, /* I - Connection to server */
1331 http_field_t field
, /* I - Field index */
1332 const char *name
, /* I - Name of sub-field */
1333 char *value
) /* O - Value string */
1335 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1340 * 'httpGetSubField2()' - Get a sub-field value.
1342 * @since CUPS 1.2/Mac OS X 10.5@
1345 char * /* O - Value or NULL */
1346 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1347 http_field_t field
, /* I - Field index */
1348 const char *name
, /* I - Name of sub-field */
1349 char *value
, /* O - Value string */
1350 int valuelen
) /* I - Size of value buffer */
1352 const char *fptr
; /* Pointer into field */
1353 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1354 *ptr
, /* Pointer into string buffer */
1355 *end
; /* End of value buffer */
1357 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1358 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1360 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1361 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1364 end
= value
+ valuelen
- 1;
1366 for (fptr
= http
->fields
[field
]; *fptr
;)
1369 * Skip leading whitespace...
1372 while (_cups_isspace(*fptr
))
1382 * Get the sub-field name...
1386 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1387 ptr
< (temp
+ sizeof(temp
) - 1);
1392 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1395 * Skip trailing chars up to the '='...
1398 while (_cups_isspace(*fptr
))
1408 * Skip = and leading whitespace...
1413 while (_cups_isspace(*fptr
))
1419 * Read quoted string...
1422 for (ptr
= value
, fptr
++;
1423 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1428 while (*fptr
&& *fptr
!= '\"')
1437 * Read unquoted string...
1441 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1446 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1450 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1453 * See if this is the one...
1456 if (!strcmp(name
, temp
))
1458 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1465 DEBUG_puts("3httpGetSubField2: Returning NULL");
1472 * 'httpGetVersion()' - Get the HTTP version at the other end.
1475 http_version_t
/* O - Version number */
1476 httpGetVersion(http_t
*http
) /* I - Connection to server */
1478 return (http
? http
->version
: HTTP_1_0
);
1483 * 'httpHead()' - Send a HEAD request to the server.
1486 int /* O - Status of call (0 = success) */
1487 httpHead(http_t
*http
, /* I - Connection to server */
1488 const char *uri
) /* I - URI for head */
1490 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1491 return (http_send(http
, HTTP_HEAD
, uri
));
1496 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1497 * default HTTP proxy (if any).
1501 httpInitialize(void)
1503 static int initialized
= 0; /* Have we been called before? */
1505 WSADATA winsockdata
; /* WinSock data */
1508 int i
; /* Looping var */
1509 unsigned char data
[1024]; /* Seed data */
1510 #endif /* HAVE_LIBSSL */
1516 _cupsGlobalUnlock();
1521 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1523 #elif !defined(SO_NOSIGPIPE)
1525 * Ignore SIGPIPE signals...
1529 sigset(SIGPIPE
, SIG_IGN
);
1531 # elif defined(HAVE_SIGACTION)
1532 struct sigaction action
; /* POSIX sigaction data */
1535 memset(&action
, 0, sizeof(action
));
1536 action
.sa_handler
= SIG_IGN
;
1537 sigaction(SIGPIPE
, &action
, NULL
);
1540 signal(SIGPIPE
, SIG_IGN
);
1541 # endif /* !SO_NOSIGPIPE */
1546 * Initialize GNU TLS...
1549 gnutls_global_init();
1551 #elif defined(HAVE_LIBSSL)
1553 * Initialize OpenSSL...
1556 SSL_load_error_strings();
1560 * Using the current time is a dubious random seed, but on some systems
1561 * it is the best we can do (on others, this seed isn't even used...)
1564 CUPS_SRAND(time(NULL
));
1566 for (i
= 0; i
< sizeof(data
); i
++)
1567 data
[i
] = CUPS_RAND();
1569 RAND_seed(data
, sizeof(data
));
1570 #endif /* HAVE_GNUTLS */
1573 _cupsGlobalUnlock();
1578 * 'httpOptions()' - Send an OPTIONS request to the server.
1581 int /* O - Status of call (0 = success) */
1582 httpOptions(http_t
*http
, /* I - Connection to server */
1583 const char *uri
) /* I - URI for options */
1585 return (http_send(http
, HTTP_OPTIONS
, uri
));
1590 * '_httpPeek()' - Peek at data from a HTTP connection.
1592 * This function copies available data from the given HTTP connection, reading
1593 * a buffer as needed. The data is still available for reading using
1594 * @link httpRead@ or @link httpRead2@.
1596 * For non-blocking connections the usual timeouts apply.
1599 ssize_t
/* O - Number of bytes copied */
1600 _httpPeek(http_t
*http
, /* I - Connection to server */
1601 char *buffer
, /* I - Buffer for data */
1602 size_t length
) /* I - Maximum number of bytes */
1604 ssize_t bytes
; /* Bytes read */
1605 char len
[32]; /* Length string */
1608 DEBUG_printf(("_httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1609 http
, buffer
, CUPS_LLCAST length
));
1611 if (http
== NULL
|| buffer
== NULL
)
1614 http
->activity
= time(NULL
);
1620 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1621 http
->data_remaining
<= 0)
1623 DEBUG_puts("2_httpPeek: Getting chunk length...");
1625 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1627 DEBUG_puts("1_httpPeek: Could not get length!");
1631 http
->data_remaining
= strtoll(len
, NULL
, 16);
1632 if (http
->data_remaining
< 0)
1634 DEBUG_puts("1_httpPeek: Negative chunk length!");
1639 DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT
,
1640 CUPS_LLCAST http
->data_remaining
));
1642 if (http
->data_remaining
<= 0)
1645 * A zero-length chunk ends a transfer; unless we are reading POST
1649 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1650 httpGets(len
, sizeof(len
), http
);
1652 if (http
->state
== HTTP_POST_RECV
)
1655 http
->state
= HTTP_WAITING
;
1658 * Prevent future reads for this request...
1661 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1665 else if (length
> (size_t)http
->data_remaining
)
1666 length
= (size_t)http
->data_remaining
;
1668 if (http
->used
== 0)
1671 * Buffer small reads for better performance...
1674 if (!http
->blocking
)
1676 while (!httpWait(http
, http
->wait_value
))
1678 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1685 if (http
->data_remaining
> sizeof(http
->buffer
))
1686 bytes
= sizeof(http
->buffer
);
1688 bytes
= http
->data_remaining
;
1692 bytes
= http_read_ssl(http
, http
->buffer
, bytes
);
1694 #endif /* HAVE_SSL */
1696 DEBUG_printf(("2_httpPeek: reading %d bytes from socket into buffer...",
1699 bytes
= recv(http
->fd
, http
->buffer
, bytes
, 0);
1701 DEBUG_printf(("2_httpPeek: read %d bytes from socket into buffer...",
1710 if (WSAGetLastError() != WSAEINTR
&& WSAGetLastError() != WSAEWOULDBLOCK
)
1712 http
->error
= WSAGetLastError();
1716 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1718 http
->error
= errno
;
1725 http
->error
= EPIPE
;
1732 if (length
> (size_t)http
->used
)
1733 length
= (size_t)http
->used
;
1735 bytes
= (ssize_t
)length
;
1737 DEBUG_printf(("2_httpPeek: grabbing %d bytes from input buffer...",
1740 memcpy(buffer
, http
->buffer
, length
);
1748 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1751 http
->error
= WSAGetLastError();
1753 if (errno
== EINTR
|| errno
== EAGAIN
)
1756 http
->error
= errno
;
1759 else if (bytes
== 0)
1761 http
->error
= EPIPE
;
1766 http_debug_hex("_httpPeek", buffer
, (int)bytes
);
1774 * 'httpPost()' - Send a POST request to the server.
1777 int /* O - Status of call (0 = success) */
1778 httpPost(http_t
*http
, /* I - Connection to server */
1779 const char *uri
) /* I - URI for post */
1781 return (http_send(http
, HTTP_POST
, uri
));
1786 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1791 int /* O - Number of bytes written */
1792 httpPrintf(http_t
*http
, /* I - Connection to server */
1793 const char *format
, /* I - printf-style format string */
1794 ...) /* I - Additional args as needed */
1796 int bytes
; /* Number of bytes to write */
1797 char buf
[16384]; /* Buffer for formatted string */
1798 va_list ap
; /* Variable argument pointer */
1801 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1803 va_start(ap
, format
);
1804 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1807 DEBUG_printf(("3httpPrintf: %s", buf
));
1809 if (http
->data_encoding
== HTTP_ENCODE_FIELDS
)
1810 return (httpWrite2(http
, buf
, bytes
));
1815 DEBUG_puts("4httpPrintf: flushing existing data...");
1817 if (httpFlushWrite(http
) < 0)
1821 return (http_write(http
, buf
, bytes
));
1827 * 'httpPut()' - Send a PUT request to the server.
1830 int /* O - Status of call (0 = success) */
1831 httpPut(http_t
*http
, /* I - Connection to server */
1832 const char *uri
) /* I - URI to put */
1834 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1835 return (http_send(http
, HTTP_PUT
, uri
));
1840 * 'httpRead()' - Read data from a HTTP connection.
1842 * This function is deprecated. Use the httpRead2() function which can
1843 * read more than 2GB of data.
1848 int /* O - Number of bytes read */
1849 httpRead(http_t
*http
, /* I - Connection to server */
1850 char *buffer
, /* I - Buffer for data */
1851 int length
) /* I - Maximum number of bytes */
1853 return ((int)httpRead2(http
, buffer
, length
));
1858 * 'httpRead2()' - Read data from a HTTP connection.
1860 * @since CUPS 1.2/Mac OS X 10.5@
1863 ssize_t
/* O - Number of bytes read */
1864 httpRead2(http_t
*http
, /* I - Connection to server */
1865 char *buffer
, /* I - Buffer for data */
1866 size_t length
) /* I - Maximum number of bytes */
1868 ssize_t bytes
; /* Bytes read */
1869 char len
[32]; /* Length string */
1872 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1873 http
, buffer
, CUPS_LLCAST length
));
1875 if (http
== NULL
|| buffer
== NULL
)
1878 http
->activity
= time(NULL
);
1884 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
&&
1885 http
->data_remaining
<= 0)
1887 DEBUG_puts("2httpRead2: Getting chunk length...");
1889 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1891 DEBUG_puts("1httpRead2: Could not get length!");
1895 http
->data_remaining
= strtoll(len
, NULL
, 16);
1896 if (http
->data_remaining
< 0)
1898 DEBUG_puts("1httpRead2: Negative chunk length!");
1903 DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT
,
1904 CUPS_LLCAST http
->data_remaining
));
1906 if (http
->data_remaining
<= 0)
1909 * A zero-length chunk ends a transfer; unless we are reading POST
1913 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
1914 httpGets(len
, sizeof(len
), http
);
1916 if (http
->state
== HTTP_POST_RECV
)
1919 http
->state
= HTTP_WAITING
;
1922 * Prevent future reads for this request...
1925 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
1929 else if (length
> (size_t)http
->data_remaining
)
1930 length
= (size_t)http
->data_remaining
;
1932 if (http
->used
== 0 && length
<= 256)
1935 * Buffer small reads for better performance...
1938 ssize_t buflen
; /* Length of read for buffer */
1940 if (!http
->blocking
)
1942 while (!httpWait(http
, http
->wait_value
))
1944 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1951 if (http
->data_remaining
> sizeof(http
->buffer
))
1952 buflen
= sizeof(http
->buffer
);
1954 buflen
= http
->data_remaining
;
1956 DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen
));
1962 bytes
= http_read_ssl(http
, http
->buffer
, buflen
);
1964 #endif /* HAVE_SSL */
1965 bytes
= recv(http
->fd
, http
->buffer
, buflen
, 0);
1970 if (WSAGetLastError() != WSAEINTR
)
1972 http
->error
= WSAGetLastError();
1975 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1977 if (!http
->timeout_cb
||
1978 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1980 http
->error
= WSAEWOULDBLOCK
;
1985 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1987 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
1989 http
->error
= errno
;
1992 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
1994 http
->error
= errno
;
1998 else if (errno
!= EINTR
)
2000 http
->error
= errno
;
2008 DEBUG_printf(("2httpRead2: Read %d bytes into buffer.", (int)bytes
));
2015 if (length
> (size_t)http
->used
)
2016 length
= (size_t)http
->used
;
2018 bytes
= (ssize_t
)length
;
2020 DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
2023 memcpy(buffer
, http
->buffer
, length
);
2024 http
->used
-= (int)length
;
2027 memmove(http
->buffer
, http
->buffer
+ length
, http
->used
);
2032 if (!http
->blocking
)
2034 while (!httpWait(http
, http
->wait_value
))
2036 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2043 while ((bytes
= (ssize_t
)http_read_ssl(http
, buffer
, (int)length
)) < 0)
2046 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2048 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2051 else if (WSAGetLastError() != WSAEINTR
)
2054 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2056 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2058 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2061 else if (errno
!= EINTR
)
2066 #endif /* HAVE_SSL */
2069 if (!http
->blocking
)
2071 while (!httpWait(http
, http
->wait_value
))
2073 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2080 DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT
" bytes from socket...",
2081 CUPS_LLCAST length
));
2084 while ((bytes
= (ssize_t
)recv(http
->fd
, buffer
, (int)length
, 0)) < 0)
2086 if (WSAGetLastError() == WSAEWOULDBLOCK
)
2088 if (!http
->timeout_cb
|| !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2091 else if (WSAGetLastError() != WSAEINTR
)
2095 while ((bytes
= recv(http
->fd
, buffer
, length
, 0)) < 0)
2097 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
2099 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
2101 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
2104 else if (errno
!= EINTR
)
2109 DEBUG_printf(("2httpRead2: read " CUPS_LLFMT
" bytes from socket...",
2110 CUPS_LLCAST bytes
));
2115 http
->data_remaining
-= bytes
;
2117 if (http
->data_remaining
<= INT_MAX
)
2118 http
->_data_remaining
= (int)http
->data_remaining
;
2120 http
->_data_remaining
= INT_MAX
;
2125 if (WSAGetLastError() == WSAEINTR
)
2128 http
->error
= WSAGetLastError();
2130 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
2133 http
->error
= errno
;
2138 http
->error
= EPIPE
;
2142 if (http
->data_remaining
== 0)
2144 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
2145 httpGets(len
, sizeof(len
), http
);
2147 if (http
->data_encoding
!= HTTP_ENCODE_CHUNKED
)
2149 if (http
->state
== HTTP_POST_RECV
)
2152 http
->state
= HTTP_WAITING
;
2157 http_debug_hex("httpRead2", buffer
, (int)bytes
);
2164 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2166 * '_httpReadCDSA()' - Read function for the CDSA library.
2169 OSStatus
/* O - -1 on error, 0 on success */
2171 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2172 void *data
, /* I - Data buffer */
2173 size_t *dataLength
) /* IO - Number of bytes */
2175 OSStatus result
; /* Return value */
2176 ssize_t bytes
; /* Number of bytes read */
2177 http_t
*http
; /* HTTP connection */
2180 http
= (http_t
*)connection
;
2182 if (!http
->blocking
)
2185 * Make sure we have data before we read...
2188 while (!_httpWait(http
, http
->wait_value
, 0))
2190 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2193 http
->error
= ETIMEDOUT
;
2200 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2202 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2204 if (bytes
== *dataLength
)
2210 *dataLength
= bytes
;
2211 result
= errSSLWouldBlock
;
2218 result
= errSSLClosedGraceful
;
2219 else if (errno
== EAGAIN
)
2220 result
= errSSLWouldBlock
;
2222 result
= errSSLClosedAbort
;
2227 #endif /* HAVE_SSL && HAVE_CDSASSL */
2230 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2232 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2235 ssize_t
/* O - Number of bytes read or -1 on error */
2237 gnutls_transport_ptr ptr
, /* I - Connection to server */
2238 void *data
, /* I - Buffer */
2239 size_t length
) /* I - Number of bytes to read */
2241 http_t
*http
; /* HTTP connection */
2242 ssize_t bytes
; /* Bytes read */
2245 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2247 http
= (http_t
*)ptr
;
2249 if (!http
->blocking
)
2252 * Make sure we have data before we read...
2255 while (!_httpWait(http
, http
->wait_value
, 0))
2257 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2260 http
->error
= ETIMEDOUT
;
2265 bytes
= recv(http
->fd
, data
, length
, 0);
2266 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2269 #endif /* HAVE_SSL && HAVE_GNUTLS */
2273 * 'httpReconnect()' - Reconnect to a HTTP server.
2276 int /* O - 0 on success, non-zero on failure */
2277 httpReconnect(http_t
*http
) /* I - Connection to server */
2279 http_addrlist_t
*addr
; /* Connected address */
2281 http_addrlist_t
*current
; /* Current address */
2282 char temp
[256]; /* Temporary address string */
2286 DEBUG_printf(("httpReconnect(http=%p)", http
));
2294 DEBUG_puts("2httpReconnect: Shutting down SSL/TLS...");
2295 http_shutdown_ssl(http
);
2297 #endif /* HAVE_SSL */
2300 * Close any previously open socket...
2305 DEBUG_printf(("2httpReconnect: Closing socket %d...", http
->fd
));
2308 closesocket(http
->fd
);
2317 * Connect to the server...
2321 for (current
= http
->addrlist
; current
; current
= current
->next
)
2322 DEBUG_printf(("2httpReconnect: Address %s:%d",
2323 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2324 _httpAddrPort(&(current
->addr
))));
2327 if ((addr
= httpAddrConnect(http
->addrlist
, &(http
->fd
))) == NULL
)
2330 * Unable to connect...
2334 http
->error
= WSAGetLastError();
2336 http
->error
= errno
;
2338 http
->status
= HTTP_ERROR
;
2340 DEBUG_printf(("1httpReconnect: httpAddrConnect failed: %s",
2341 strerror(http
->error
)));
2346 DEBUG_printf(("2httpReconnect: New socket=%d", http
->fd
));
2348 if (http
->timeout_value
> 0)
2349 http_set_timeout(http
->fd
, http
->timeout_value
);
2351 http
->hostaddr
= &(addr
->addr
);
2353 http
->status
= HTTP_CONTINUE
;
2354 http
->state
= HTTP_WAITING
;
2357 if (http
->encryption
== HTTP_ENCRYPT_ALWAYS
)
2360 * Always do encryption via SSL.
2363 if (http_setup_ssl(http
) != 0)
2366 closesocket(http
->fd
);
2374 else if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
)
2375 return (http_upgrade(http
));
2376 #endif /* HAVE_SSL */
2378 DEBUG_printf(("1httpReconnect: Connected to %s:%d...",
2379 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2380 _httpAddrPort(http
->hostaddr
)));
2387 * 'httpSetAuthString()' - Set the current authorization string.
2389 * This function just stores a copy of the current authorization string in
2390 * the HTTP connection object. You must still call httpSetField() to set
2391 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2392 * httpHead(), httpOptions(), httpPost, or httpPut().
2394 * @since CUPS 1.3/Mac OS X 10.5@
2398 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2399 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2400 const char *data
) /* I - Auth data (NULL for none) */
2403 * Range check input...
2409 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2410 free(http
->authstring
);
2412 http
->authstring
= http
->_authstring
;
2417 * Set the current authorization string...
2420 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2423 if (len
> (int)sizeof(http
->_authstring
))
2425 if ((temp
= malloc(len
)) == NULL
)
2426 len
= sizeof(http
->_authstring
);
2428 http
->authstring
= temp
;
2432 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2434 strlcpy(http
->authstring
, scheme
, len
);
2439 * Clear the current authorization string...
2442 http
->_authstring
[0] = '\0';
2448 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2451 * @since CUPS 1.5/Mac OS X 10.7@
2454 int /* O - Status of call (0 = success) */
2455 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2456 cups_array_t
*credentials
) /* I - Array of credentials */
2458 if (!http
|| cupsArrayCount(credentials
) < 1)
2461 _httpFreeCredentials(http
->tls_credentials
);
2463 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2465 return (http
->tls_credentials
? 0 : -1);
2470 * 'httpSetCookie()' - Set the cookie value(s).
2472 * @since CUPS 1.1.19/Mac OS X 10.3@
2476 httpSetCookie(http_t
*http
, /* I - Connection */
2477 const char *cookie
) /* I - Cookie string */
2486 http
->cookie
= strdup(cookie
);
2488 http
->cookie
= NULL
;
2493 * 'httpSetExpect()' - Set the Expect: header in a request.
2495 * Currently only HTTP_CONTINUE is supported for the "expect" argument.
2497 * @since CUPS 1.2/Mac OS X 10.5@
2501 httpSetExpect(http_t
*http
, /* I - Connection to server */
2502 http_status_t expect
) /* I - HTTP status to expect (HTTP_CONTINUE) */
2505 http
->expect
= expect
;
2510 * 'httpSetField()' - Set the value of an HTTP header.
2514 httpSetField(http_t
*http
, /* I - Connection to server */
2515 http_field_t field
, /* I - Field index */
2516 const char *value
) /* I - Value */
2519 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2520 field
> HTTP_FIELD_WWW_AUTHENTICATE
||
2524 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2526 if (field
== HTTP_FIELD_AUTHORIZATION
)
2529 * Special case for Authorization: as its contents can be
2530 * longer than HTTP_MAX_VALUE
2533 if (http
->field_authorization
)
2534 free(http
->field_authorization
);
2536 http
->field_authorization
= strdup(value
);
2538 else if (field
== HTTP_FIELD_HOST
)
2541 * Special-case for Host: as we don't want a trailing "." on the hostname and
2542 * need to bracket IPv6 numeric addresses.
2545 char *ptr
= strchr(value
, ':');
2547 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2550 * Bracket IPv6 numeric addresses...
2552 * This is slightly inefficient (basically copying twice), but is an edge
2553 * case and not worth optimizing...
2556 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2557 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2562 * Check for a trailing dot on the hostname...
2565 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2569 ptr
+= strlen(ptr
) - 1;
2580 * 'httpSetLength()' - Set the content-length and content-encoding.
2582 * @since CUPS 1.2/Mac OS X 10.5@
2586 httpSetLength(http_t
*http
, /* I - Connection to server */
2587 size_t length
) /* I - Length (0 for chunked) */
2594 strcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked");
2595 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2599 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2600 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2601 CUPS_LLFMT
, CUPS_LLCAST length
);
2607 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2609 * The optional timeout callback receives both the HTTP connection and a user
2610 * data pointer and must return 1 to continue or 0 to error (time) out.
2612 * @since CUPS 1.5/Mac OS X 10.7@
2617 http_t
*http
, /* I - Connection to server */
2618 double timeout
, /* I - Number of seconds for timeout,
2619 must be greater than 0 */
2620 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2621 void *user_data
) /* I - User data pointer */
2623 if (!http
|| timeout
<= 0.0)
2626 http
->timeout_cb
= cb
;
2627 http
->timeout_data
= user_data
;
2628 http
->timeout_value
= timeout
;
2631 http_set_timeout(http
->fd
, timeout
);
2633 http_set_wait(http
);
2638 * 'httpTrace()' - Send an TRACE request to the server.
2641 int /* O - Status of call (0 = success) */
2642 httpTrace(http_t
*http
, /* I - Connection to server */
2643 const char *uri
) /* I - URI for trace */
2645 return (http_send(http
, HTTP_TRACE
, uri
));
2650 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2652 * Note: Unlike httpUpdate(), this function does not flush pending write data
2653 * and only retrieves a single status line from the HTTP connection.
2656 int /* O - 1 to continue, 0 to stop */
2657 _httpUpdate(http_t
*http
, /* I - Connection to server */
2658 http_status_t
*status
) /* O - Current HTTP status */
2660 char line
[32768], /* Line from connection... */
2661 *value
; /* Pointer to value on line */
2662 http_field_t field
; /* Field index */
2663 int major
, minor
; /* HTTP version numbers */
2666 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2667 http_states
[http
->state
]));
2670 * Grab a single line from the connection...
2673 if (!httpGets(line
, sizeof(line
), http
))
2675 *status
= HTTP_ERROR
;
2679 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2681 if (line
[0] == '\0')
2684 * Blank line means the start of the data section (if any). Return
2685 * the result code, too...
2687 * If we get status 100 (HTTP_CONTINUE), then we *don't* change states.
2688 * Instead, we just return HTTP_CONTINUE to the caller and keep on
2692 if (http
->status
== HTTP_CONTINUE
)
2694 *status
= http
->status
;
2698 if (http
->status
< HTTP_BAD_REQUEST
)
2699 http
->digest_tries
= 0;
2702 if (http
->status
== HTTP_SWITCHING_PROTOCOLS
&& !http
->tls
)
2704 if (http_setup_ssl(http
) != 0)
2707 closesocket(http
->fd
);
2712 *status
= http
->status
= HTTP_ERROR
;
2716 *status
= HTTP_CONTINUE
;
2719 #endif /* HAVE_SSL */
2721 httpGetLength2(http
);
2723 switch (http
->state
)
2727 case HTTP_POST_RECV
:
2730 case HTTP_POST_SEND
:
2735 http
->state
= HTTP_WAITING
;
2739 *status
= http
->status
;
2742 else if (!strncmp(line
, "HTTP/", 5))
2745 * Got the beginning of a response...
2748 int intstatus
; /* Status value as an integer */
2750 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2752 *status
= http
->status
= HTTP_ERROR
;
2756 http
->version
= (http_version_t
)(major
* 100 + minor
);
2757 *status
= http
->status
= (http_status_t
)intstatus
;
2759 else if ((value
= strchr(line
, ':')) != NULL
)
2766 while (_cups_isspace(*value
))
2770 * Be tolerants of servers that send unknown attribute fields...
2773 if (!_cups_strcasecmp(line
, "expect"))
2776 * "Expect: 100-continue" or similar...
2779 http
->expect
= (http_status_t
)atoi(value
);
2781 else if (!_cups_strcasecmp(line
, "cookie"))
2784 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
2787 httpSetCookie(http
, value
);
2789 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
2790 httpSetField(http
, field
, value
);
2793 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
2798 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
2799 *status
= http
->status
= HTTP_ERROR
;
2808 * 'httpUpdate()' - Update the current HTTP state for incoming data.
2811 http_status_t
/* O - HTTP status */
2812 httpUpdate(http_t
*http
) /* I - Connection to server */
2814 http_status_t status
; /* Request status */
2817 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
2818 http_states
[http
->state
]));
2821 * Flush pending data, if any...
2826 DEBUG_puts("2httpUpdate: flushing buffer...");
2828 if (httpFlushWrite(http
) < 0)
2829 return (HTTP_ERROR
);
2833 * If we haven't issued any commands, then there is nothing to "update"...
2836 if (http
->state
== HTTP_WAITING
)
2837 return (HTTP_CONTINUE
);
2840 * Grab all of the lines we can from the connection...
2843 while (_httpUpdate(http
, &status
));
2846 * See if there was an error...
2849 if (http
->error
== EPIPE
&& http
->status
> HTTP_CONTINUE
)
2851 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
2852 return (http
->status
);
2857 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
2858 strerror(http
->error
)));
2859 http
->status
= HTTP_ERROR
;
2860 return (HTTP_ERROR
);
2864 * Return the current status...
2872 * '_httpWait()' - Wait for data available on a connection (no flush).
2875 int /* O - 1 if data is available, 0 otherwise */
2876 _httpWait(http_t
*http
, /* I - Connection to server */
2877 int msec
, /* I - Milliseconds to wait */
2878 int usessl
) /* I - Use SSL context? */
2881 struct pollfd pfd
; /* Polled file descriptor */
2883 fd_set input_set
; /* select() input set */
2884 struct timeval timeout
; /* Timeout */
2885 #endif /* HAVE_POLL */
2886 int nfds
; /* Result from select()/poll() */
2889 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
2893 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
2898 * Check the SSL/TLS buffers for data first...
2902 if (http
->tls
&& usessl
)
2905 if (SSL_pending(http
->tls
))
2907 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2911 # elif defined(HAVE_GNUTLS)
2912 if (gnutls_record_check_pending(http
->tls
))
2914 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2918 # elif defined(HAVE_CDSASSL)
2919 size_t bytes
; /* Bytes that are available */
2921 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
2924 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
2927 # endif /* HAVE_LIBSSL */
2929 #endif /* HAVE_SSL */
2932 * Then try doing a select() or poll() to poll the socket...
2937 pfd
.events
= POLLIN
;
2939 while ((nfds
= poll(&pfd
, 1, msec
)) < 0 &&
2940 (errno
== EINTR
|| errno
== EAGAIN
));
2945 FD_ZERO(&input_set
);
2946 FD_SET(http
->fd
, &input_set
);
2948 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
2952 timeout
.tv_sec
= msec
/ 1000;
2953 timeout
.tv_usec
= (msec
% 1000) * 1000;
2955 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
2958 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
2960 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
2963 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
2964 WSAGetLastError() == WSAEWOULDBLOCK
));
2966 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
2968 #endif /* HAVE_POLL */
2970 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
2978 * 'httpWait()' - Wait for data available on a connection.
2980 * @since CUPS 1.1.19/Mac OS X 10.3@
2983 int /* O - 1 if data is available, 0 otherwise */
2984 httpWait(http_t
*http
, /* I - Connection to server */
2985 int msec
) /* I - Milliseconds to wait */
2988 * First see if there is data in the buffer...
2991 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
2998 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3003 * Flush pending data, if any...
3008 DEBUG_puts("3httpWait: Flushing write buffer.");
3010 if (httpFlushWrite(http
) < 0)
3015 * If not, check the SSL/TLS buffers and do a select() on the connection...
3018 return (_httpWait(http
, msec
, 1));
3023 * 'httpWrite()' - Write data to a HTTP connection.
3025 * This function is deprecated. Use the httpWrite2() function which can
3026 * write more than 2GB of data.
3031 int /* O - Number of bytes written */
3032 httpWrite(http_t
*http
, /* I - Connection to server */
3033 const char *buffer
, /* I - Buffer for data */
3034 int length
) /* I - Number of bytes to write */
3036 return ((int)httpWrite2(http
, buffer
, length
));
3041 * 'httpWrite2()' - Write data to a HTTP connection.
3043 * @since CUPS 1.2/Mac OS X 10.5@
3046 ssize_t
/* O - Number of bytes written */
3047 httpWrite2(http_t
*http
, /* I - Connection to server */
3048 const char *buffer
, /* I - Buffer for data */
3049 size_t length
) /* I - Number of bytes to write */
3051 ssize_t bytes
; /* Bytes written */
3054 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3055 buffer
, CUPS_LLCAST length
));
3058 * Range check input...
3061 if (http
== NULL
|| buffer
== NULL
)
3065 * Mark activity on the connection...
3068 http
->activity
= time(NULL
);
3071 * Buffer small writes for better performance...
3076 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3078 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3079 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3081 httpFlushWrite(http
);
3084 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3085 length
< sizeof(http
->wbuffer
))
3088 * Write to buffer...
3091 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3092 CUPS_LLCAST length
));
3094 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3095 http
->wused
+= (int)length
;
3096 bytes
= (ssize_t
)length
;
3101 * Otherwise write the data directly...
3104 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3105 CUPS_LLCAST length
));
3107 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3108 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3110 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3112 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3113 CUPS_LLCAST bytes
));
3116 if (http
->data_encoding
== HTTP_ENCODE_LENGTH
)
3117 http
->data_remaining
-= bytes
;
3123 * Handle end-of-request processing...
3126 if ((http
->data_encoding
== HTTP_ENCODE_CHUNKED
&& length
== 0) ||
3127 (http
->data_encoding
== HTTP_ENCODE_LENGTH
&& http
->data_remaining
== 0))
3130 * Finished with the transfer; unless we are sending POST or PUT
3134 DEBUG_puts("2httpWrite: changing states...");
3137 httpFlushWrite(http
);
3139 if (http
->data_encoding
== HTTP_ENCODE_CHUNKED
)
3142 * Send a 0-length chunk at the end of the request...
3145 http_write(http
, "0\r\n\r\n", 5);
3148 * Reset the data state...
3151 http
->data_encoding
= HTTP_ENCODE_LENGTH
;
3152 http
->data_remaining
= 0;
3160 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3162 * '_httpWriteCDSA()' - Write function for the CDSA library.
3165 OSStatus
/* O - -1 on error, 0 on success */
3167 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3168 const void *data
, /* I - Data buffer */
3169 size_t *dataLength
) /* IO - Number of bytes */
3171 OSStatus result
; /* Return value */
3172 ssize_t bytes
; /* Number of bytes read */
3173 http_t
*http
; /* HTTP connection */
3176 http
= (http_t
*)connection
;
3180 bytes
= write(http
->fd
, data
, *dataLength
);
3182 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3184 if (bytes
== *dataLength
)
3188 else if (bytes
>= 0)
3190 *dataLength
= bytes
;
3191 result
= errSSLWouldBlock
;
3197 if (errno
== EAGAIN
)
3198 result
= errSSLWouldBlock
;
3200 result
= errSSLClosedAbort
;
3205 #endif /* HAVE_SSL && HAVE_CDSASSL */
3208 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3210 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3213 ssize_t
/* O - Number of bytes written or -1 on error */
3215 gnutls_transport_ptr ptr
, /* I - Connection to server */
3216 const void *data
, /* I - Data buffer */
3217 size_t length
) /* I - Number of bytes to write */
3219 ssize_t bytes
; /* Bytes written */
3222 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3225 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3228 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3229 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3233 #endif /* HAVE_SSL && HAVE_GNUTLS */
3236 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3238 * 'http_bio_ctrl()' - Control the HTTP connection.
3241 static long /* O - Result/data */
3242 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3243 int cmd
, /* I - Control command */
3244 long arg1
, /* I - First argument */
3245 void *arg2
) /* I - Second argument */
3252 case BIO_CTRL_RESET
:
3256 case BIO_C_SET_FILE_PTR
:
3261 case BIO_C_GET_FILE_PTR
:
3264 *((void **)arg2
) = h
->ptr
;
3271 case BIO_CTRL_FLUSH
:
3278 * 'http_bio_free()' - Free OpenSSL data.
3281 static int /* O - 1 on success, 0 on failure */
3282 http_bio_free(BIO
*h
) /* I - BIO data */
3298 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3301 static int /* O - 1 on success, 0 on failure */
3302 http_bio_new(BIO
*h
) /* I - BIO data */
3317 * 'http_bio_puts()' - Send a string for OpenSSL.
3320 static int /* O - Bytes written */
3321 http_bio_puts(BIO
*h
, /* I - BIO data */
3322 const char *str
) /* I - String to write */
3325 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3327 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3333 * 'http_bio_read()' - Read data for OpenSSL.
3336 static int /* O - Bytes read */
3337 http_bio_read(BIO
*h
, /* I - BIO data */
3338 char *buf
, /* I - Buffer */
3339 int size
) /* I - Number of bytes to read */
3341 http_t
*http
; /* HTTP connection */
3344 http
= (http_t
*)h
->ptr
;
3346 if (!http
->blocking
)
3349 * Make sure we have data before we read...
3352 while (!_httpWait(http
, http
->wait_value
, 0))
3354 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
3358 http
->error
= WSAETIMEDOUT
;
3360 http
->error
= ETIMEDOUT
;
3367 return (recv(http
->fd
, buf
, size
, 0));
3372 * 'http_bio_write()' - Write data for OpenSSL.
3375 static int /* O - Bytes written */
3376 http_bio_write(BIO
*h
, /* I - BIO data */
3377 const char *buf
, /* I - Buffer to write */
3378 int num
) /* I - Number of bytes to write */
3380 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
3382 #endif /* HAVE_SSL && HAVE_LIBSSL */
3387 * 'http_debug_hex()' - Do a hex dump of a buffer.
3391 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3392 const char *buffer
, /* I - Buffer to dump */
3393 int bytes
) /* I - Bytes to dump */
3395 int i
, j
, /* Looping vars */
3396 ch
; /* Current character */
3397 char line
[255], /* Line buffer */
3398 *start
, /* Start of line after prefix */
3399 *ptr
; /* Pointer into line */
3402 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3405 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
3407 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3408 start
= line
+ strlen(line
);
3410 for (i
= 0; i
< bytes
; i
+= 16)
3412 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3413 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3425 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3427 ch
= buffer
[i
+ j
] & 255;
3429 if (ch
< ' ' || ch
>= 127)
3443 * 'http_field()' - Return the field index for a field name.
3446 static http_field_t
/* O - Field index */
3447 http_field(const char *name
) /* I - String name */
3449 int i
; /* Looping var */
3452 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3453 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
3454 return ((http_field_t
)i
);
3456 return (HTTP_FIELD_UNKNOWN
);
3462 * 'http_read_ssl()' - Read from a SSL/TLS connection.
3465 static int /* O - Bytes read */
3466 http_read_ssl(http_t
*http
, /* I - Connection to server */
3467 char *buf
, /* I - Buffer to store data */
3468 int len
) /* I - Length of buffer */
3470 # if defined(HAVE_LIBSSL)
3471 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
3473 # elif defined(HAVE_GNUTLS)
3474 ssize_t result
; /* Return value */
3477 result
= gnutls_record_recv(http
->tls
, buf
, len
);
3479 if (result
< 0 && !errno
)
3482 * Convert GNU TLS error to errno value...
3487 case GNUTLS_E_INTERRUPTED
:
3491 case GNUTLS_E_AGAIN
:
3503 return ((int)result
);
3505 # elif defined(HAVE_CDSASSL)
3506 int result
; /* Return value */
3507 OSStatus error
; /* Error info */
3508 size_t processed
; /* Number of bytes processed */
3511 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
3512 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
3517 result
= (int)processed
;
3520 case errSSLWouldBlock
:
3522 result
= (int)processed
;
3530 case errSSLClosedGraceful
:
3533 result
= (int)processed
;
3544 # elif defined(HAVE_SSPISSL)
3545 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
3546 # endif /* HAVE_LIBSSL */
3548 #endif /* HAVE_SSL */
3552 * 'http_send()' - Send a request with all fields and the trailing blank line.
3555 static int /* O - 0 on success, non-zero on error */
3556 http_send(http_t
*http
, /* I - Connection to server */
3557 http_state_t request
, /* I - Request code */
3558 const char *uri
) /* I - URI */
3560 int i
; /* Looping var */
3561 char buf
[1024]; /* Encoded URI buffer */
3562 static const char * const codes
[] =
3563 { /* Request code strings */
3580 DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
3581 http
, codes
[request
], uri
));
3583 if (http
== NULL
|| uri
== NULL
)
3587 * Set the User-Agent field if it isn't already...
3590 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
3591 httpSetField(http
, HTTP_FIELD_USER_AGENT
, CUPS_MINIMAL
);
3594 * Encode the URI as needed...
3597 _httpEncodeURI(buf
, uri
, sizeof(buf
));
3600 * See if we had an error the last time around; if so, reconnect...
3603 if (http
->status
== HTTP_ERROR
|| http
->status
>= HTTP_BAD_REQUEST
)
3604 if (httpReconnect(http
))
3608 * Flush any written data that is pending...
3613 if (httpFlushWrite(http
) < 0)
3614 if (httpReconnect(http
))
3619 * Send the request header...
3622 http
->state
= request
;
3623 http
->data_encoding
= HTTP_ENCODE_FIELDS
;
3625 if (request
== HTTP_POST
|| request
== HTTP_PUT
)
3628 http
->status
= HTTP_CONTINUE
;
3631 if (http
->encryption
== HTTP_ENCRYPT_REQUIRED
&& !http
->tls
)
3633 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3634 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.0,SSL/2.0,SSL/3.0");
3636 #endif /* HAVE_SSL */
3638 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
3640 http
->status
= HTTP_ERROR
;
3644 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3645 if (http
->fields
[i
][0] != '\0')
3647 DEBUG_printf(("9http_send: %s: %s", http_fields
[i
],
3648 httpGetField(http
, i
)));
3650 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
],
3651 httpGetField(http
, i
)) < 1)
3653 http
->status
= HTTP_ERROR
;
3659 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
3661 http
->status
= HTTP_ERROR
;
3665 if (http
->expect
== HTTP_CONTINUE
&&
3666 (http
->state
== HTTP_POST_RECV
|| http
->state
== HTTP_PUT_RECV
))
3667 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
3669 http
->status
= HTTP_ERROR
;
3673 if (httpPrintf(http
, "\r\n") < 1)
3675 http
->status
= HTTP_ERROR
;
3679 if (httpFlushWrite(http
) < 0)
3682 httpGetLength2(http
);
3683 httpClearFields(http
);
3686 * The Kerberos and AuthRef authentication strings can only be used once...
3689 if (http
->field_authorization
&& http
->authstring
&&
3690 (!strncmp(http
->authstring
, "Negotiate", 9) ||
3691 !strncmp(http
->authstring
, "AuthRef", 7)))
3693 http
->_authstring
[0] = '\0';
3695 if (http
->authstring
!= http
->_authstring
)
3696 free(http
->authstring
);
3698 http
->authstring
= http
->_authstring
;
3706 # if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
3708 * 'http_set_credentials()' - Set the SSL/TLS credentials.
3711 static int /* O - Status of connection */
3712 http_set_credentials(http_t
*http
) /* I - Connection to server */
3714 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
3715 OSStatus error
= 0; /* Error code */
3716 http_tls_credentials_t credentials
= NULL
;
3717 /* TLS credentials */
3720 DEBUG_printf(("7http_set_credentials(%p)", http
));
3723 * Prefer connection specific credentials...
3726 if ((credentials
= http
->tls_credentials
) == NULL
)
3727 credentials
= cg
->tls_credentials
;
3729 # if HAVE_SECPOLICYCREATESSL
3731 * Otherwise root around in the user's keychain to see if one can be found...
3736 CFDictionaryRef query
; /* Query dictionary */
3737 CFTypeRef matches
= NULL
; /* Matching credentials */
3738 CFArrayRef dn_array
= NULL
;/* Distinguished names array */
3739 CFTypeRef keys
[] = { kSecClass
,
3742 /* Keys for dictionary */
3743 CFTypeRef values
[] = { kSecClassCertificate
,
3746 /* Values for dictionary */
3749 * Get the names associated with the server.
3752 if ((error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) != noErr
)
3754 DEBUG_printf(("4http_set_credentials: SSLCopyDistinguishedNames, error=%d",
3760 * Create a query which will return all identities that can sign and match
3761 * the passed in policy.
3764 query
= CFDictionaryCreate(NULL
,
3765 (const void**)(&keys
[0]),
3766 (const void**)(&values
[0]),
3767 sizeof(keys
) / sizeof(keys
[0]),
3768 &kCFTypeDictionaryKeyCallBacks
,
3769 &kCFTypeDictionaryValueCallBacks
);
3772 error
= SecItemCopyMatching(query
, &matches
);
3773 DEBUG_printf(("4http_set_credentials: SecItemCopyMatching, error=%d",
3782 CFRelease(dn_array
);
3784 # endif /* HAVE_SECPOLICYCREATESSL */
3788 error
= SSLSetCertificate(http
->tls
, credentials
);
3789 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
3793 DEBUG_puts("4http_set_credentials: No credentials to set.");
3797 # endif /* HAVE_CDSASSL && HAVE_SECCERTIFICATECOPYDATA */
3798 #endif /* HAVE_SSL */
3802 * 'http_set_timeout()' - Set the socket timeout values.
3806 http_set_timeout(int fd
, /* I - File descriptor */
3807 double timeout
) /* I - Timeout in seconds */
3810 DWORD tv
= (DWORD
)(timeout
* 1000);
3811 /* Timeout in milliseconds */
3813 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, (char *)&tv
, sizeof(tv
));
3814 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, (char *)&tv
, sizeof(tv
));
3817 struct timeval tv
; /* Timeout in secs and usecs */
3819 tv
.tv_sec
= (int)timeout
;
3820 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
3822 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, &tv
, sizeof(tv
));
3823 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, &tv
, sizeof(tv
));
3829 * 'http_set_wait()' - Set the default wait value for reads.
3833 http_set_wait(http_t
*http
) /* I - Connection to server */
3837 http
->wait_value
= (int)(http
->timeout_value
* 1000);
3839 if (http
->wait_value
<= 0)
3840 http
->wait_value
= 60000;
3843 http
->wait_value
= 10000;
3849 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
3852 static int /* O - 0 on success, -1 on failure */
3853 http_setup_ssl(http_t
*http
) /* I - Connection to server */
3855 _cups_globals_t
*cg
= _cupsGlobals();
3856 /* Pointer to library globals */
3857 int any_root
; /* Allow any root */
3860 SSL_CTX
*context
; /* Context for encryption */
3861 BIO
*bio
; /* BIO data */
3862 const char *message
= NULL
;/* Error message */
3863 # elif defined(HAVE_GNUTLS)
3864 int status
; /* Status of handshake */
3865 gnutls_certificate_client_credentials
*credentials
;
3866 /* TLS credentials */
3867 # elif defined(HAVE_CDSASSL)
3868 OSStatus error
; /* Error code */
3869 char *hostname
; /* Hostname */
3870 const char *message
= NULL
;/* Error message */
3871 # ifdef HAVE_SECCERTIFICATECOPYDATA
3872 cups_array_t
*credentials
; /* Credentials array */
3873 cups_array_t
*names
; /* CUPS distinguished names */
3874 CFArrayRef dn_array
; /* CF distinguished names array */
3875 CFIndex count
; /* Number of credentials */
3876 CFDataRef data
; /* Certificate data */
3877 int i
; /* Looping var */
3878 http_credential_t
*credential
; /* Credential data */
3879 # endif /* HAVE_SECCERTIFICATECOPYDATA */
3880 # elif defined(HAVE_SSPISSL)
3881 TCHAR username
[256]; /* Username returned from GetUserName() */
3882 TCHAR commonName
[256];/* Common name for certificate */
3883 DWORD dwSize
; /* 32 bit size */
3884 # endif /* HAVE_LIBSSL */
3887 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
3890 * Always allow self-signed certificates for the local loopback address...
3893 if (httpAddrLocalhost(http
->hostaddr
))
3896 any_root
= cg
->any_root
;
3901 context
= SSL_CTX_new(SSLv23_client_method());
3903 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
3905 bio
= BIO_new(_httpBIOMethods());
3906 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
3908 http
->tls
= SSL_new(context
);
3909 SSL_set_bio(http
->tls
, bio
, bio
);
3911 if (SSL_connect(http
->tls
) != 1)
3913 unsigned long error
; /* Error code */
3915 while ((error
= ERR_get_error()) != 0)
3917 message
= ERR_error_string(error
, NULL
);
3918 DEBUG_printf(("8http_setup_ssl: %s", message
));
3921 SSL_CTX_free(context
);
3922 SSL_free(http
->tls
);
3926 http
->error
= WSAGetLastError();
3928 http
->error
= errno
;
3930 http
->status
= HTTP_ERROR
;
3933 message
= _("Unable to establish a secure connection to host.");
3935 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
3940 # elif defined(HAVE_GNUTLS)
3943 credentials
= (gnutls_certificate_client_credentials
*)
3944 malloc(sizeof(gnutls_certificate_client_credentials
));
3945 if (credentials
== NULL
)
3947 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
3949 http
->error
= errno
;
3950 http
->status
= HTTP_ERROR
;
3951 _cupsSetHTTPError(HTTP_ERROR
);
3956 gnutls_certificate_allocate_credentials(credentials
);
3958 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
3959 gnutls_set_default_priority(http
->tls
);
3960 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, http
->hostname
, strlen(http
->hostname
));
3961 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
3962 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
3963 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
3964 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
3966 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
3968 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
3969 status
, gnutls_strerror(status
)));
3971 if (gnutls_error_is_fatal(status
))
3974 http
->status
= HTTP_ERROR
;
3976 _cupsSetError(IPP_PKI_ERROR
, gnutls_strerror(status
), 0);
3978 gnutls_deinit(http
->tls
);
3979 gnutls_certificate_free_credentials(*credentials
);
3987 http
->tls_credentials
= credentials
;
3989 # elif defined(HAVE_CDSASSL)
3990 if ((error
= SSLNewContext(false, &http
->tls
)))
3992 http
->error
= errno
;
3993 http
->status
= HTTP_ERROR
;
3994 _cupsSetHTTPError(HTTP_ERROR
);
3999 error
= SSLSetConnection(http
->tls
, http
);
4000 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
4004 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
4005 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
4010 error
= SSLSetAllowsAnyRoot(http
->tls
, any_root
);
4011 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
4012 any_root
, (int)error
));
4017 error
= SSLSetAllowsExpiredCerts(http
->tls
, cg
->expired_certs
);
4018 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
4019 cg
->expired_certs
, (int)error
));
4024 error
= SSLSetAllowsExpiredRoots(http
->tls
, cg
->expired_root
);
4025 DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
4026 cg
->expired_root
, (int)error
));
4029 # ifdef HAVE_SSLSETPROTOCOLVERSIONMAX
4032 error
= SSLSetProtocolVersionMax(http
->tls
, kTLSProtocol1
);
4033 DEBUG_printf(("4http_setup_ssl: SSLSetProtocolVersionMax(kTLSProtocol1), "
4034 "error=%d", (int)error
));
4036 # endif /* HAVE_SSLSETPROTOCOLVERSIONMAX */
4039 * In general, don't verify certificates since things like the common name
4040 * often do not match...
4045 error
= SSLSetEnableCertVerify(http
->tls
, false);
4046 DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
4050 # ifdef HAVE_SECCERTIFICATECOPYDATA
4053 if (cg
->client_cert_cb
)
4055 error
= SSLSetSessionOption(http
->tls
,
4056 kSSLSessionOptionBreakOnCertRequested
, true);
4057 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
4058 "error=%d", (int)error
));
4062 error
= http_set_credentials(http
);
4063 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
4069 * If there's a server certificate callback installed let it evaluate the
4070 * certificate(s) during the handshake...
4073 if (!error
&& cg
->server_cert_cb
!= NULL
)
4075 error
= SSLSetSessionOption(http
->tls
,
4076 kSSLSessionOptionBreakOnServerAuth
, true);
4077 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
4078 "error=%d", (int)error
));
4080 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4083 * Let the server know which hostname/domain we are trying to connect to
4084 * in case it wants to serve up a certificate with a matching common name.
4089 hostname
= httpAddrLocalhost(http
->hostaddr
) ? "localhost" : http
->hostname
;
4090 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
4092 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
4098 int done
= 0; /* Are we done yet? */
4100 while (!error
&& !done
)
4102 error
= SSLHandshake(http
->tls
);
4104 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
4112 case errSSLWouldBlock
:
4116 # ifdef HAVE_SECCERTIFICATECOPYDATA
4117 case errSSLServerAuthCompleted
:
4119 if (cg
->server_cert_cb
)
4121 error
= httpCopyCredentials(http
, &credentials
);
4124 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
4125 cg
->server_cert_data
);
4126 httpFreeCredentials(credentials
);
4129 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
4130 "returned %d.", (int)error
));
4134 case errSSLClientCertRequested
:
4137 if (cg
->client_cert_cb
)
4140 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
4143 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
4145 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
4147 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
4149 if ((credential
= malloc(sizeof(*credential
))))
4151 credential
->datalen
= CFDataGetLength(data
);
4152 if ((credential
->data
= malloc(credential
->datalen
)))
4154 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
4155 credential
->datalen
);
4156 cupsArrayAdd(names
, credential
);
4162 CFRelease(dn_array
);
4167 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
4168 cg
->client_cert_data
);
4170 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
4171 "returned %d.", (int)error
));
4174 httpFreeCredentials(names
);
4177 # endif /* HAVE_SECCERTIFICATECOPYDATA */
4179 case errSSLUnknownRootCert
:
4180 message
= _("Unable to establish a secure connection to host "
4181 "(untrusted certificate).");
4184 case errSSLNoRootCert
:
4185 message
= _("Unable to establish a secure connection to host "
4186 "(self-signed certificate).");
4189 case errSSLCertExpired
:
4190 message
= _("Unable to establish a secure connection to host "
4191 "(expired certificate).");
4194 case errSSLCertNotYetValid
:
4195 message
= _("Unable to establish a secure connection to host "
4196 "(certificate not yet valid).");
4199 case errSSLHostNameMismatch
:
4200 message
= _("Unable to establish a secure connection to host "
4201 "(host name mismatch).");
4204 case errSSLXCertChainInvalid
:
4205 message
= _("Unable to establish a secure connection to host "
4206 "(certificate chain invalid).");
4209 case errSSLConnectionRefused
:
4210 message
= _("Unable to establish a secure connection to host "
4211 "(peer dropped connection before responding).");
4222 http
->error
= error
;
4223 http
->status
= HTTP_ERROR
;
4224 errno
= ECONNREFUSED
;
4226 SSLDisposeContext(http
->tls
);
4230 * If an error string wasn't set by the callbacks use a generic one...
4234 #ifdef HAVE_CSSMERRORSTRING
4235 message
= cssmErrorString(error
);
4237 message
= _("Unable to establish a secure connection to host.");
4238 #endif /* HAVE_CSSMERRORSTRING */
4240 _cupsSetError(IPP_PKI_ERROR
, message
, 1);
4245 # elif defined(HAVE_SSPISSL)
4246 http
->tls
= _sspiAlloc();
4250 _cupsSetHTTPError(HTTP_ERROR
);
4254 http
->tls
->sock
= http
->fd
;
4255 dwSize
= sizeof(username
) / sizeof(TCHAR
);
4256 GetUserName(username
, &dwSize
);
4257 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
4258 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
4260 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
4263 _sspiFree(http
->tls_credentials
);
4264 http
->tls_credentials
= NULL
;
4267 http
->status
= HTTP_ERROR
;
4269 _cupsSetError(IPP_PKI_ERROR
,
4270 _("Unable to establish a secure connection to host."), 1);
4275 _sspiSetAllowsAnyRoot(http
->tls_credentials
, any_root
);
4276 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
4278 if (!_sspiConnect(http
->tls_credentials
, http
->hostname
))
4280 _sspiFree(http
->tls_credentials
);
4281 http
->tls_credentials
= NULL
;
4284 http
->status
= HTTP_ERROR
;
4286 _cupsSetError(IPP_PKI_ERROR
,
4287 _("Unable to establish a secure connection to host."), 1);
4291 # endif /* HAVE_CDSASSL */
4298 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
4302 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
4305 SSL_CTX
*context
; /* Context for encryption */
4307 context
= SSL_get_SSL_CTX(http
->tls
);
4309 SSL_shutdown(http
->tls
);
4310 SSL_CTX_free(context
);
4311 SSL_free(http
->tls
);
4313 # elif defined(HAVE_GNUTLS)
4314 gnutls_certificate_client_credentials
*credentials
;
4315 /* TLS credentials */
4317 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
4319 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
4320 gnutls_deinit(http
->tls
);
4321 gnutls_certificate_free_credentials(*credentials
);
4324 # elif defined(HAVE_CDSASSL)
4325 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
4328 SSLDisposeContext(http
->tls
);
4330 if (http
->tls_credentials
)
4331 CFRelease(http
->tls_credentials
);
4333 # elif defined(HAVE_SSPISSL)
4334 _sspiFree(http
->tls_credentials
);
4335 # endif /* HAVE_LIBSSL */
4338 http
->tls_credentials
= NULL
;
4340 #endif /* HAVE_SSL */
4345 * 'http_upgrade()' - Force upgrade to TLS encryption.
4348 static int /* O - Status of connection */
4349 http_upgrade(http_t
*http
) /* I - Connection to server */
4351 int ret
; /* Return value */
4352 http_t myhttp
; /* Local copy of HTTP data */
4355 DEBUG_printf(("7http_upgrade(%p)", http
));
4358 * Flush the connection to make sure any previous "Upgrade" message
4365 * Copy the HTTP data to a local variable so we can do the OPTIONS
4366 * request without interfering with the existing request data...
4369 memcpy(&myhttp
, http
, sizeof(myhttp
));
4372 * Send an OPTIONS request to the server, requiring SSL or TLS
4373 * encryption on the link...
4376 http
->field_authorization
= NULL
; /* Don't free the auth string */
4378 httpClearFields(http
);
4379 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4380 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
4382 if ((ret
= httpOptions(http
, "*")) == 0)
4385 * Wait for the secure connection...
4388 while (httpUpdate(http
) == HTTP_CONTINUE
);
4392 * Restore the HTTP request data...
4395 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4396 http
->data_encoding
= myhttp
.data_encoding
;
4397 http
->data_remaining
= myhttp
.data_remaining
;
4398 http
->_data_remaining
= myhttp
._data_remaining
;
4399 http
->expect
= myhttp
.expect
;
4400 http
->field_authorization
= myhttp
.field_authorization
;
4401 http
->digest_tries
= myhttp
.digest_tries
;
4404 * See if we actually went secure...
4410 * Server does not support HTTP upgrade...
4413 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
4416 closesocket(http
->fd
);
4428 #endif /* HAVE_SSL */
4432 * 'http_write()' - Write a buffer to a HTTP connection.
4435 static int /* O - Number of bytes written */
4436 http_write(http_t
*http
, /* I - Connection to server */
4437 const char *buffer
, /* I - Buffer for data */
4438 int length
) /* I - Number of bytes to write */
4440 int tbytes
, /* Total bytes sent */
4441 bytes
; /* Bytes sent */
4444 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http
, buffer
,
4451 if (http
->timeout_cb
)
4454 struct pollfd pfd
; /* Polled file descriptor */
4456 fd_set output_set
; /* Output ready for write? */
4457 struct timeval timeout
; /* Timeout value */
4458 #endif /* HAVE_POLL */
4459 int nfds
; /* Result from select()/poll() */
4465 pfd
.events
= POLLOUT
;
4467 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
4468 (errno
== EINTR
|| errno
== EAGAIN
));
4473 FD_ZERO(&output_set
);
4474 FD_SET(http
->fd
, &output_set
);
4476 timeout
.tv_sec
= http
->wait_value
/ 1000;
4477 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
4479 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
4482 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
4483 WSAGetLastError() == WSAEWOULDBLOCK
));
4485 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
4487 #endif /* HAVE_POLL */
4491 http
->error
= errno
;
4494 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4497 http
->error
= WSAEWOULDBLOCK
;
4499 http
->error
= EWOULDBLOCK
;
4509 bytes
= http_write_ssl(http
, buffer
, length
);
4511 #endif /* HAVE_SSL */
4512 bytes
= send(http
->fd
, buffer
, length
, 0);
4517 if (WSAGetLastError() == WSAEINTR
)
4519 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4521 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4524 http
->error
= WSAGetLastError();
4526 else if (WSAGetLastError() != http
->error
&&
4527 WSAGetLastError() != WSAECONNRESET
)
4529 http
->error
= WSAGetLastError();
4536 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4538 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4540 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4543 http
->error
= errno
;
4545 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4547 http
->error
= errno
;
4552 DEBUG_printf(("3http_write: error writing data (%s).",
4553 strerror(http
->error
)));
4564 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4567 DEBUG_printf(("3http_write: Returning %d.", tbytes
));
4574 * 'http_write_chunk()' - Write a chunked buffer.
4577 static int /* O - Number bytes written */
4578 http_write_chunk(http_t
*http
, /* I - Connection to server */
4579 const char *buffer
, /* I - Buffer to write */
4580 int length
) /* I - Length of buffer */
4582 char header
[255]; /* Chunk header */
4583 int bytes
; /* Bytes written */
4586 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
4587 http
, buffer
, length
));
4590 * Write the chunk header, data, and trailer.
4593 sprintf(header
, "%x\r\n", length
);
4594 if (http_write(http
, header
, (int)strlen(header
)) < 0)
4596 DEBUG_puts("8http_write_chunk: http_write of length failed!");
4600 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4602 DEBUG_puts("8http_write_chunk: http_write of buffer failed!");
4606 if (http_write(http
, "\r\n", 2) < 0)
4608 DEBUG_puts("8http_write_chunk: http_write of CR LF failed!");
4618 * 'http_write_ssl()' - Write to a SSL/TLS connection.
4621 static int /* O - Bytes written */
4622 http_write_ssl(http_t
*http
, /* I - Connection to server */
4623 const char *buf
, /* I - Buffer holding data */
4624 int len
) /* I - Length of buffer */
4626 ssize_t result
; /* Return value */
4629 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
4631 # if defined(HAVE_LIBSSL)
4632 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
4634 # elif defined(HAVE_GNUTLS)
4635 result
= gnutls_record_send(http
->tls
, buf
, len
);
4637 if (result
< 0 && !errno
)
4640 * Convert GNU TLS error to errno value...
4645 case GNUTLS_E_INTERRUPTED
:
4649 case GNUTLS_E_AGAIN
:
4661 # elif defined(HAVE_CDSASSL)
4662 OSStatus error
; /* Error info */
4663 size_t processed
; /* Number of bytes processed */
4666 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
4671 result
= (int)processed
;
4674 case errSSLWouldBlock
:
4676 result
= (int)processed
;
4684 case errSSLClosedGraceful
:
4687 result
= (int)processed
;
4695 # elif defined(HAVE_SSPISSL)
4696 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
4697 # endif /* HAVE_LIBSSL */
4699 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
4701 return ((int)result
);
4703 #endif /* HAVE_SSL */
4707 * End of "$Id: http.c 7850 2008-08-20 00:07:25Z mike $".