4 * HTTP routines for CUPS.
6 * Copyright 2007-2013 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 * Include necessary headers...
25 #include "cups-private.h"
32 # include <sys/time.h>
33 # include <sys/resource.h>
37 #endif /* HAVE_POLL */
45 static void http_content_coding_finish(http_t
*http
);
46 static void http_content_coding_start(http_t
*http
,
48 #endif /* HAVE_LIBZ */
49 static http_t
*http_create(const char *host
, int port
,
50 http_addrlist_t
*addrlist
, int family
,
51 http_encryption_t encryption
,
52 int blocking
, _http_mode_t mode
);
54 static void http_debug_hex(const char *prefix
, const char *buffer
,
57 static ssize_t
http_read(http_t
*http
, char *buffer
, size_t length
);
58 static ssize_t
http_read_buffered(http_t
*http
, char *buffer
, size_t length
);
59 static ssize_t
http_read_chunk(http_t
*http
, char *buffer
, size_t length
);
60 static int http_send(http_t
*http
, http_state_t request
,
62 static ssize_t
http_write(http_t
*http
, const char *buffer
,
64 static ssize_t
http_write_chunk(http_t
*http
, const char *buffer
,
67 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
68 static int http_set_credentials(http_t
*http
);
70 static off_t
http_set_length(http_t
*http
);
71 static void http_set_timeout(int fd
, double timeout
);
72 static void http_set_wait(http_t
*http
);
74 static int http_setup_ssl(http_t
*http
);
75 static void http_shutdown_ssl(http_t
*http
);
76 static int http_upgrade(http_t
*http
);
77 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
85 static const char * const http_fields
[] =
102 "If-Unmodified-since",
120 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
122 * BIO methods for OpenSSL...
125 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
126 static int http_bio_read(BIO
*h
, char *buf
, int size
);
127 static int http_bio_puts(BIO
*h
, const char *str
);
128 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
129 static int http_bio_new(BIO
*h
);
130 static int http_bio_free(BIO
*data
);
132 static BIO_METHOD http_bio_methods
=
139 NULL
, /* http_bio_gets, */
145 #endif /* HAVE_SSL && HAVE_LIBSSL */
149 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
150 * specified listening socket.
152 * @since CUPS 1.7/OS X 10.9@
155 http_t
* /* O - HTTP connection or @code NULL@ */
156 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
157 int blocking
) /* I - 1 if the connection should be
158 blocking, 0 otherwise */
160 http_t
*http
; /* HTTP connection */
161 http_addrlist_t addrlist
; /* Dummy address list */
162 socklen_t addrlen
; /* Length of address */
163 int val
; /* Socket option value */
167 * Range check input...
174 * Create the client connection...
177 memset(&addrlist
, 0, sizeof(addrlist
));
179 if ((http
= http_create(NULL
, 0, &addrlist
, AF_UNSPEC
,
180 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
181 _HTTP_MODE_SERVER
)) == NULL
)
185 * Accept the client and get the remote address...
188 addrlen
= sizeof(http_addr_t
);
190 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
193 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
199 http
->hostaddr
= &(http
->addrlist
->addr
);
201 if (httpAddrLocalhost(http
->hostaddr
))
202 strlcpy(http
->hostname
, "localhost", sizeof(http
->hostname
));
204 httpAddrString(http
->hostaddr
, http
->hostname
, sizeof(http
->hostname
));
208 * Disable SIGPIPE for this socket.
212 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
213 #endif /* SO_NOSIGPIPE */
216 * Using TCP_NODELAY improves responsiveness, especially on systems
217 * with a slow loopback interface. Since we write large buffers
218 * when sending print files and requests, there shouldn't be any
219 * performance penalty for this...
223 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
227 * Close this socket when starting another process...
230 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
231 #endif /* FD_CLOEXEC */
238 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
240 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
242 * @since CUPS 1.5/OS X 10.7@
245 int /* O - 0 on success, -1 on error */
247 cups_array_t
*credentials
, /* I - Credentials array */
248 const void *data
, /* I - PEM-encoded X.509 data */
249 size_t datalen
) /* I - Length of data */
251 http_credential_t
*credential
; /* Credential data */
254 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
256 credential
->datalen
= datalen
;
258 if ((credential
->data
= malloc(datalen
)) != NULL
)
260 memcpy(credential
->data
, data
, datalen
);
261 cupsArrayAdd(credentials
, credential
);
272 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
274 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
277 BIO_METHOD
* /* O - BIO methods for OpenSSL */
278 _httpBIOMethods(void)
280 return (&http_bio_methods
);
282 #endif /* HAVE_SSL && HAVE_LIBSSL */
286 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
290 httpBlocking(http_t
*http
, /* I - HTTP connection */
291 int b
) /* I - 1 = blocking, 0 = non-blocking */
302 * 'httpCheck()' - Check to see if there is a pending response from the server.
305 int /* O - 0 = no data, 1 = data available */
306 httpCheck(http_t
*http
) /* I - HTTP connection */
308 return (httpWait(http
, 0));
313 * 'httpClearCookie()' - Clear the cookie value(s).
315 * @since CUPS 1.1.19/OS X 10.3@
319 httpClearCookie(http_t
*http
) /* I - HTTP connection */
333 * 'httpClearFields()' - Clear HTTP request fields.
337 httpClearFields(http_t
*http
) /* I - HTTP connection */
339 DEBUG_printf(("httpClearFields(http=%p)", http
));
343 memset(http
->fields
, 0, sizeof(http
->fields
));
345 if (http
->mode
== _HTTP_MODE_CLIENT
)
347 if (http
->hostname
[0] == '/')
348 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
350 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
353 if (http
->field_authorization
)
355 free(http
->field_authorization
);
356 http
->field_authorization
= NULL
;
359 if (http
->accept_encoding
)
361 _cupsStrFree(http
->accept_encoding
);
362 http
->accept_encoding
= NULL
;
367 _cupsStrFree(http
->allow
);
373 _cupsStrFree(http
->server
);
377 http
->expect
= (http_status_t
)0;
383 * 'httpClose()' - Close an HTTP connection.
387 httpClose(http_t
*http
) /* I - HTTP connection */
390 OM_uint32 minor_status
; /* Minor status code */
391 #endif /* HAVE_GSSAPI */
394 DEBUG_printf(("httpClose(http=%p)", http
));
397 * Range check input...
404 * Close any open connection...
407 _httpDisconnect(http
);
410 * Free memory used...
413 httpAddrFreeList(http
->addrlist
);
419 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
420 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
422 if (http
->gssname
!= GSS_C_NO_NAME
)
423 gss_release_name(&minor_status
, &http
->gssname
);
424 #endif /* HAVE_GSSAPI */
426 #ifdef HAVE_AUTHORIZATION_H
428 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
429 #endif /* HAVE_AUTHORIZATION_H */
431 httpClearFields(http
);
433 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
434 free(http
->authstring
);
441 * 'httpConnect()' - Connect to a HTTP server.
443 * This function is deprecated - use @link httpConnect2@ instead.
448 http_t
* /* O - New HTTP connection */
449 httpConnect(const char *host
, /* I - Host to connect to */
450 int port
) /* I - Port number */
452 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, HTTP_ENCRYPTION_IF_REQUESTED
,
458 * 'httpConnect2()' - Connect to a HTTP server.
460 * @since CUPS 1.7/OS X 10.9@
463 http_t
* /* O - New HTTP connection */
465 const char *host
, /* I - Host to connect to */
466 int port
, /* I - Port number */
467 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
468 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
469 http_encryption_t encryption
, /* I - Type of encryption to use */
470 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
471 int msec
, /* I - Connection timeout in milliseconds, 0 means don't connect */
472 int *cancel
) /* I - Pointer to "cancel" variable */
474 http_t
*http
; /* New HTTP connection */
477 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
478 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
479 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
482 * Create the HTTP structure...
485 if ((http
= http_create(host
, port
, addrlist
, family
, encryption
, blocking
,
486 _HTTP_MODE_CLIENT
)) == NULL
)
490 * Optionally connect to the remote system...
493 if (msec
== 0 || !httpReconnect2(http
, msec
, cancel
))
497 * Could not connect to any known address - bail out!
507 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
509 * This function is now deprecated. Please use the @link httpConnect2@ function
515 http_t
* /* O - New HTTP connection */
517 const char *host
, /* I - Host to connect to */
518 int port
, /* I - Port number */
519 http_encryption_t encryption
) /* I - Type of encryption to use */
521 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
522 host
, port
, encryption
));
524 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
530 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
533 * @since CUPS 1.5/OS X 10.7@
536 int /* O - Status of call (0 = success) */
538 http_t
*http
, /* I - HTTP connection */
539 cups_array_t
**credentials
) /* O - Array of credentials */
542 # elif defined(HAVE_GNUTLS)
543 # elif defined(HAVE_CDSASSL)
544 OSStatus error
; /* Error code */
545 SecTrustRef peerTrust
; /* Peer trust reference */
546 CFIndex count
; /* Number of credentials */
547 SecCertificateRef secCert
; /* Certificate reference */
548 CFDataRef data
; /* Certificate data */
549 int i
; /* Looping var */
550 # elif defined(HAVE_SSPISSL)
551 # endif /* HAVE_LIBSSL */
557 if (!http
|| !http
->tls
|| !credentials
)
563 # elif defined(HAVE_GNUTLS)
566 # elif defined(HAVE_CDSASSL)
567 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
569 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
571 count
= SecTrustGetCertificateCount(peerTrust
);
573 for (i
= 0; i
< count
; i
++)
575 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
576 if ((data
= SecCertificateCopyData(secCert
)))
578 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
579 CFDataGetLength(data
));
585 CFRelease(peerTrust
);
590 # elif defined(HAVE_SSPISSL)
595 # endif /* HAVE_LIBSSL */
600 * '_httpCreateCredentials()' - Create credentials in the internal format.
603 http_tls_credentials_t
/* O - Internal credentials */
604 _httpCreateCredentials(
605 cups_array_t
*credentials
) /* I - Array of credentials */
613 # elif defined(HAVE_GNUTLS)
616 # elif defined(HAVE_CDSASSL)
617 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
618 SecCertificateRef secCert
; /* Certificate reference */
619 CFDataRef data
; /* Credential data reference */
620 http_credential_t
*credential
; /* Credential data */
623 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
624 cupsArrayCount(credentials
),
625 &kCFTypeArrayCallBacks
)) == NULL
)
628 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
630 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
632 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
633 credential
->datalen
)))
635 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
638 CFArrayAppendValue(peerCerts
, secCert
);
648 # elif defined(HAVE_SSPISSL)
653 # endif /* HAVE_LIBSSL */
658 * 'httpDelete()' - Send a DELETE request to the server.
661 int /* O - Status of call (0 = success) */
662 httpDelete(http_t
*http
, /* I - HTTP connection */
663 const char *uri
) /* I - URI to delete */
665 return (http_send(http
, HTTP_STATE_DELETE
, uri
));
670 * '_httpDisconnect()' - Disconnect a HTTP connection.
674 _httpDisconnect(http_t
*http
) /* I - HTTP connection */
678 http_shutdown_ssl(http
);
679 #endif /* HAVE_SSL */
682 closesocket(http
->fd
);
692 * 'httpEncryption()' - Set the required encryption on the link.
695 int /* O - -1 on error, 0 on success */
696 httpEncryption(http_t
*http
, /* I - HTTP connection */
697 http_encryption_t e
) /* I - New encryption preference */
699 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
705 http
->encryption
= e
;
707 if ((http
->encryption
== HTTP_ENCRYPTION_ALWAYS
&& !http
->tls
) ||
708 (http
->encryption
== HTTP_ENCRYPTION_NEVER
&& http
->tls
))
709 return (httpReconnect2(http
, 30000, NULL
));
710 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
711 return (http_upgrade(http
));
715 if (e
== HTTP_ENCRYPTION_ALWAYS
|| e
== HTTP_ENCRYPTION_REQUIRED
)
719 #endif /* HAVE_SSL */
724 * 'httpError()' - Get the last error on a connection.
727 int /* O - Error code (errno) value */
728 httpError(http_t
*http
) /* I - HTTP connection */
731 return (http
->error
);
738 * 'httpFieldValue()' - Return the HTTP field enumeration value for a field
742 http_field_t
/* O - Field index */
743 httpFieldValue(const char *name
) /* I - String name */
745 int i
; /* Looping var */
748 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
749 if (!_cups_strcasecmp(name
, http_fields
[i
]))
750 return ((http_field_t
)i
);
752 return (HTTP_FIELD_UNKNOWN
);
757 * 'httpFlush()' - Flush data from a HTTP connection.
761 httpFlush(http_t
*http
) /* I - HTTP connection */
763 char buffer
[8192]; /* Junk buffer */
764 int blocking
; /* To block or not to block */
765 http_state_t oldstate
; /* Old state */
768 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
769 httpStateString(http
->state
)));
772 * Nothing to do if we are in the "waiting" state...
775 if (http
->state
== HTTP_STATE_WAITING
)
779 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
782 blocking
= http
->blocking
;
786 * Read any data we can...
789 oldstate
= http
->state
;
790 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
793 * Restore blocking and reset the connection if we didn't get all of
794 * the remaining data...
797 http
->blocking
= blocking
;
799 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
803 * Didn't get the data back, so close the current connection.
808 http_content_coding_finish(http
);
809 #endif /* HAVE_LIBZ */
811 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
813 http
->state
= HTTP_STATE_WAITING
;
817 http_shutdown_ssl(http
);
818 #endif /* HAVE_SSL */
821 closesocket(http
->fd
);
832 * 'httpFlushWrite()' - Flush data in write buffer.
834 * @since CUPS 1.2/OS X 10.5@
837 int /* O - Bytes written or -1 on error */
838 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
840 int bytes
; /* Bytes written */
843 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
844 http
? http
->data_encoding
: -1));
846 if (!http
|| !http
->wused
)
848 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
849 "1httpFlushWrite: No connection.");
853 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
854 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
856 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
860 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
867 * '_httpFreeCredentials()' - Free internal credentials.
871 _httpFreeCredentials(
872 http_tls_credentials_t credentials
) /* I - Internal credentials */
880 #elif defined(HAVE_GNUTLS)
883 #elif defined(HAVE_CDSASSL)
884 CFRelease(credentials
);
886 #elif defined(HAVE_SSPISSL)
889 #endif /* HAVE_LIBSSL */
894 * 'httpFreeCredentials()' - Free an array of credentials.
899 cups_array_t
*credentials
) /* I - Array of credentials */
901 http_credential_t
*credential
; /* Credential */
904 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
906 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
908 cupsArrayRemove(credentials
, credential
);
909 free((void *)credential
->data
);
913 cupsArrayDelete(credentials
);
918 * 'httpGet()' - Send a GET request to the server.
921 int /* O - Status of call (0 = success) */
922 httpGet(http_t
*http
, /* I - HTTP connection */
923 const char *uri
) /* I - URI to get */
925 return (http_send(http
, HTTP_STATE_GET
, uri
));
930 * 'httpGetActivity()' - Get the most recent activity for a connection.
932 * The return value is the UNIX time of the last read or write.
937 time_t /* O - Time of last read or write */
938 httpGetActivity(http_t
*http
) /* I - HTTP connection */
940 return (http
? http
->activity
: 0);
945 * 'httpGetAuthString()' - Get the current authorization string.
947 * The authorization string is set by cupsDoAuthentication() and
948 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
949 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
952 * @since CUPS 1.3/OS X 10.5@
955 char * /* O - Authorization string */
956 httpGetAuthString(http_t
*http
) /* I - HTTP connection */
959 return (http
->authstring
);
966 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
968 * @since CUPS 1.2/OS X 10.5@
971 int /* O - 1 if blocking, 0 if non-blocking */
972 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
974 return (http
? http
->blocking
: 0);
979 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
980 * the client and server.
982 * This function uses the value of the Accepts-Encoding HTTP header and must be
983 * called after receiving a response from the server or a request from the
984 * client. The value returned can be use in subsequent requests (for clients)
985 * or in the response (for servers) in order to compress the content stream.
987 * @since CUPS 1.7/OS X 10.9@
990 const char * /* O - Content-Coding value or
991 @code NULL@ for the identity
993 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
996 if (http
&& http
->accept_encoding
)
998 int i
; /* Looping var */
999 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
1000 *start
, /* Start of coding value */
1001 *end
; /* End of coding value */
1002 double qvalue
; /* "qvalue" for coding */
1003 struct lconv
*loc
= localeconv(); /* Locale data */
1004 static const char * const codings
[] =
1005 { /* Supported content codings */
1012 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
1014 for (start
= temp
; *start
; start
= end
)
1017 * Find the end of the coding name...
1022 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
1028 * Grab the qvalue as needed...
1031 if (!strncmp(end
, ";q=", 3))
1032 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1035 * Skip past all attributes...
1039 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1045 while (*end
&& isspace(*end
& 255))
1049 * Check value if it matches something we support...
1055 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1056 if (!strcmp(start
, codings
[i
]))
1057 return (codings
[i
]);
1060 #endif /* HAVE_LIBZ */
1067 * 'httpGetCookie()' - Get any cookie data from the response.
1069 * @since CUPS 1.1.19/OS X 10.3@
1072 const char * /* O - Cookie data or NULL */
1073 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1075 return (http
? http
->cookie
: NULL
);
1080 * 'httpGetEncryption()' - Get the current encryption mode of a connection.
1082 * This function returns the encryption mode for the connection. Use the
1083 * @link httpIsEncrypted@ function to determine whether a TLS session has
1089 http_encryption_t
/* O - Current encryption mode */
1090 httpGetEncryption(http_t
*http
) /* I - HTTP connection */
1092 return (http
? http
->encryption
: HTTP_ENCRYPTION_IF_REQUESTED
);
1097 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1099 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1100 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1102 * @since CUPS 1.7/OS X 10.9@
1105 http_status_t
/* O - Expect: status, if any */
1106 httpGetExpect(http_t
*http
) /* I - Connection to client */
1109 return (HTTP_STATUS_ERROR
);
1111 return (http
->expect
);
1116 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1118 * @since CUPS 1.2/OS X 10.5@
1121 int /* O - File descriptor or -1 if none */
1122 httpGetFd(http_t
*http
) /* I - HTTP connection */
1124 return (http
? http
->fd
: -1);
1129 * 'httpGetField()' - Get a field value from a request/response.
1132 const char * /* O - Field value */
1133 httpGetField(http_t
*http
, /* I - HTTP connection */
1134 http_field_t field
) /* I - Field to get */
1136 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1141 case HTTP_FIELD_ACCEPT_ENCODING
:
1142 return (http
->accept_encoding
);
1144 case HTTP_FIELD_ALLOW
:
1145 return (http
->allow
);
1147 case HTTP_FIELD_SERVER
:
1148 return (http
->server
);
1150 case HTTP_FIELD_AUTHORIZATION
:
1151 if (http
->field_authorization
)
1154 * Special case for WWW-Authenticate: as its contents can be
1155 * longer than HTTP_MAX_VALUE...
1158 return (http
->field_authorization
);
1162 return (http
->fields
[field
]);
1168 * 'httpGetKeepAlive()' - Get the current Keep-Alive state of the connection.
1173 http_keepalive_t
/* O - Keep-Alive state */
1174 httpGetKeepAlive(http_t
*http
) /* I - HTTP connection */
1176 return (http
? http
->keep_alive
: HTTP_KEEPALIVE_OFF
);
1181 * 'httpGetLength()' - Get the amount of data remaining from the
1182 * content-length or transfer-encoding fields.
1184 * This function is deprecated and will not return lengths larger than
1185 * 2^31 - 1; use httpGetLength2() instead.
1190 int /* O - Content length */
1191 httpGetLength(http_t
*http
) /* I - HTTP connection */
1194 * Get the read content length and return the 32-bit value.
1199 httpGetLength2(http
);
1201 return (http
->_data_remaining
);
1209 * 'httpGetLength2()' - Get the amount of data remaining from the
1210 * content-length or transfer-encoding fields.
1212 * This function returns the complete content length, even for
1213 * content larger than 2^31 - 1.
1215 * @since CUPS 1.2/OS X 10.5@
1218 off_t
/* O - Content length */
1219 httpGetLength2(http_t
*http
) /* I - HTTP connection */
1221 off_t remaining
; /* Remaining length */
1224 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1225 httpStateString(http
->state
)));
1230 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1232 DEBUG_puts("4httpGetLength2: chunked request!");
1238 * The following is a hack for HTTP servers that don't send a
1239 * Content-Length or Transfer-Encoding field...
1241 * If there is no Content-Length then the connection must close
1242 * after the transfer is complete...
1245 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1248 * Default content length is 0 for errors and certain types of operations,
1249 * and 2^31-1 for other successful requests...
1252 if (http
->status
>= HTTP_STATUS_MULTIPLE_CHOICES
||
1253 http
->state
== HTTP_STATE_OPTIONS
||
1254 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1255 http
->state
== HTTP_STATE_HEAD
||
1256 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1257 http
->state
== HTTP_STATE_DELETE
||
1258 http
->state
== HTTP_STATE_TRACE
||
1259 http
->state
== HTTP_STATE_CONNECT
)
1262 remaining
= 2147483647;
1264 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1268 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1269 CUPS_LLCAST remaining
));
1277 * 'httpGetReady()' - Get the number of bytes that can be read without blocking.
1282 size_t /* O - Number of bytes available */
1283 httpGetReady(http_t
*http
) /* I - HTTP connection */
1287 else if (http
->used
> 0)
1288 return (http
->used
);
1292 size_t ready
; /* Ready bytes */
1295 if ((ready
= SSL_pending((SSL
*)(http
->tls
))) > 0)
1297 # elif defined(HAVE_GNUTLS)
1298 if ((ready
= gnutls_record_check_pending(http
->tls
)) > 0)
1300 # elif defined(HAVE_CDSASSL)
1301 if (!SSLGetBufferedReadSize(http
->tls
, &ready
) && ready
> 0)
1303 # endif /* HAVE_LIBSSL */
1305 #endif /* HAVE_SSL */
1312 * 'httpGetRemaining()' - Get the number of remaining bytes in the message
1313 * body or current chunk.
1315 * The @link httpIsChunked@ function can be used to determine whether the
1316 * message body is chunked or fixed-length.
1321 size_t /* O - Remaining bytes */
1322 httpGetRemaining(http_t
*http
) /* I - HTTP connection */
1324 return (http
? http
->data_remaining
: 0);
1329 * 'httpGets()' - Get a line of text from a HTTP connection.
1332 char * /* O - Line or NULL */
1333 httpGets(char *line
, /* I - Line to read into */
1334 int length
, /* I - Max length of buffer */
1335 http_t
*http
) /* I - HTTP connection */
1337 char *lineptr
, /* Pointer into line */
1338 *lineend
, /* End of line */
1339 *bufptr
, /* Pointer into input buffer */
1340 *bufend
; /* Pointer to end of buffer */
1341 int bytes
, /* Number of bytes read */
1342 eol
; /* End-of-line? */
1345 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1347 if (!http
|| !line
|| length
<= 1)
1351 * Read a line from the buffer...
1356 lineend
= line
+ length
- 1;
1359 while (lineptr
< lineend
)
1362 * Pre-load the buffer as needed...
1371 while (http
->used
== 0)
1374 * No newline; see if there is more data to be read...
1377 while (!_httpWait(http
, http
->wait_value
, 1))
1379 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1382 DEBUG_puts("3httpGets: Timed out!");
1384 http
->error
= WSAETIMEDOUT
;
1386 http
->error
= ETIMEDOUT
;
1391 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1392 HTTP_MAX_BUFFER
- http
->used
);
1394 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1399 * Nope, can't get a line this time...
1403 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1405 if (WSAGetLastError() == WSAEINTR
)
1407 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1409 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1412 http
->error
= WSAGetLastError();
1414 else if (WSAGetLastError() != http
->error
)
1416 http
->error
= WSAGetLastError();
1421 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1425 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1427 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1429 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1432 http
->error
= errno
;
1434 else if (errno
!= http
->error
)
1436 http
->error
= errno
;
1443 else if (bytes
== 0)
1445 http
->error
= EPIPE
;
1451 * Yup, update the amount used...
1454 http
->used
+= bytes
;
1458 * Now copy as much of the current line as possible...
1461 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1462 lineptr
< lineend
&& bufptr
< bufend
;)
1464 if (*bufptr
== 0x0a)
1470 else if (*bufptr
== 0x0d)
1473 *lineptr
++ = *bufptr
++;
1476 http
->used
-= (int)(bufptr
- http
->buffer
);
1478 memmove(http
->buffer
, bufptr
, http
->used
);
1486 http
->activity
= time(NULL
);
1490 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1496 DEBUG_puts("3httpGets: No new line available!");
1503 * 'httpGetState()' - Get the current state of the HTTP request.
1506 http_state_t
/* O - HTTP state */
1507 httpGetState(http_t
*http
) /* I - HTTP connection */
1509 return (http
? http
->state
: HTTP_STATE_ERROR
);
1514 * 'httpGetStatus()' - Get the status of the last HTTP request.
1516 * @since CUPS 1.2/OS X 10.5@
1519 http_status_t
/* O - HTTP status */
1520 httpGetStatus(http_t
*http
) /* I - HTTP connection */
1522 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1527 * 'httpGetSubField()' - Get a sub-field value.
1532 char * /* O - Value or NULL */
1533 httpGetSubField(http_t
*http
, /* I - HTTP connection */
1534 http_field_t field
, /* I - Field index */
1535 const char *name
, /* I - Name of sub-field */
1536 char *value
) /* O - Value string */
1538 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1543 * 'httpGetSubField2()' - Get a sub-field value.
1545 * @since CUPS 1.2/OS X 10.5@
1548 char * /* O - Value or NULL */
1549 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
1550 http_field_t field
, /* I - Field index */
1551 const char *name
, /* I - Name of sub-field */
1552 char *value
, /* O - Value string */
1553 int valuelen
) /* I - Size of value buffer */
1555 const char *fptr
; /* Pointer into field */
1556 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1557 *ptr
, /* Pointer into string buffer */
1558 *end
; /* End of value buffer */
1560 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1561 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1563 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1564 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1567 end
= value
+ valuelen
- 1;
1569 for (fptr
= http
->fields
[field
]; *fptr
;)
1572 * Skip leading whitespace...
1575 while (_cups_isspace(*fptr
))
1585 * Get the sub-field name...
1589 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1590 ptr
< (temp
+ sizeof(temp
) - 1);
1595 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1598 * Skip trailing chars up to the '='...
1601 while (_cups_isspace(*fptr
))
1611 * Skip = and leading whitespace...
1616 while (_cups_isspace(*fptr
))
1622 * Read quoted string...
1625 for (ptr
= value
, fptr
++;
1626 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1631 while (*fptr
&& *fptr
!= '\"')
1640 * Read unquoted string...
1644 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1649 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1653 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1656 * See if this is the one...
1659 if (!strcmp(name
, temp
))
1661 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1668 DEBUG_puts("3httpGetSubField2: Returning NULL");
1675 * 'httpGetVersion()' - Get the HTTP version at the other end.
1678 http_version_t
/* O - Version number */
1679 httpGetVersion(http_t
*http
) /* I - HTTP connection */
1681 return (http
? http
->version
: HTTP_VERSION_1_0
);
1686 * 'httpHead()' - Send a HEAD request to the server.
1689 int /* O - Status of call (0 = success) */
1690 httpHead(http_t
*http
, /* I - HTTP connection */
1691 const char *uri
) /* I - URI for head */
1693 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1694 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1699 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1700 * default HTTP proxy (if any).
1704 httpInitialize(void)
1706 static int initialized
= 0; /* Have we been called before? */
1708 WSADATA winsockdata
; /* WinSock data */
1711 int i
; /* Looping var */
1712 unsigned char data
[1024]; /* Seed data */
1713 #endif /* HAVE_LIBSSL */
1719 _cupsGlobalUnlock();
1724 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1726 #elif !defined(SO_NOSIGPIPE)
1728 * Ignore SIGPIPE signals...
1732 sigset(SIGPIPE
, SIG_IGN
);
1734 # elif defined(HAVE_SIGACTION)
1735 struct sigaction action
; /* POSIX sigaction data */
1738 memset(&action
, 0, sizeof(action
));
1739 action
.sa_handler
= SIG_IGN
;
1740 sigaction(SIGPIPE
, &action
, NULL
);
1743 signal(SIGPIPE
, SIG_IGN
);
1744 # endif /* !SO_NOSIGPIPE */
1749 * Initialize GNU TLS...
1752 gnutls_global_init();
1754 #elif defined(HAVE_LIBSSL)
1756 * Initialize OpenSSL...
1759 SSL_load_error_strings();
1763 * Using the current time is a dubious random seed, but on some systems
1764 * it is the best we can do (on others, this seed isn't even used...)
1767 CUPS_SRAND(time(NULL
));
1769 for (i
= 0; i
< sizeof(data
); i
++)
1770 data
[i
] = CUPS_RAND();
1772 RAND_seed(data
, sizeof(data
));
1773 #endif /* HAVE_GNUTLS */
1776 _cupsGlobalUnlock();
1781 * 'httpIsChunked()' - Report whether a message body is chunked.
1783 * This function returns non-zero if the message body is composed of
1784 * variable-length chunks.
1789 int /* O - 1 if chunked, 0 if not */
1790 httpIsChunked(http_t
*http
) /* I - HTTP connection */
1792 return (http
? http
->data_encoding
== HTTP_ENCODING_CHUNKED
: 0);
1797 * 'httpIsEncrypted()' - Report whether a connection is encrypted.
1799 * This function returns non-zero if the connection is currently encrypted.
1804 int /* O - 1 if encrypted, 0 if not */
1805 httpIsEncrypted(http_t
*http
) /* I - HTTP connection */
1807 return (http
? http
->tls
!= NULL
: 0);
1812 * 'httpOptions()' - Send an OPTIONS request to the server.
1815 int /* O - Status of call (0 = success) */
1816 httpOptions(http_t
*http
, /* I - HTTP connection */
1817 const char *uri
) /* I - URI for options */
1819 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1824 * 'httpPeek()' - Peek at data from a HTTP connection.
1826 * This function copies available data from the given HTTP connection, reading
1827 * a buffer as needed. The data is still available for reading using
1828 * @link httpRead@ or @link httpRead2@.
1830 * For non-blocking connections the usual timeouts apply.
1832 * @since CUPS 1.7/OS X 10.9@
1835 ssize_t
/* O - Number of bytes copied */
1836 httpPeek(http_t
*http
, /* I - HTTP connection */
1837 char *buffer
, /* I - Buffer for data */
1838 size_t length
) /* I - Maximum number of bytes */
1840 ssize_t bytes
; /* Bytes read */
1841 char len
[32]; /* Length string */
1844 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1845 http
, buffer
, CUPS_LLCAST length
));
1847 if (http
== NULL
|| buffer
== NULL
)
1850 http
->activity
= time(NULL
);
1856 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1857 http
->data_remaining
<= 0)
1859 DEBUG_puts("2httpPeek: Getting chunk length...");
1861 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1863 DEBUG_puts("1httpPeek: Could not get length!");
1869 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1870 if (!httpGets(len
, sizeof(len
), http
))
1872 DEBUG_puts("1httpPeek: Could not get chunk length.");
1877 http
->data_remaining
= strtoll(len
, NULL
, 16);
1879 if (http
->data_remaining
< 0)
1881 DEBUG_puts("1httpPeek: Negative chunk length!");
1886 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1887 CUPS_LLCAST http
->data_remaining
));
1889 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1892 * A zero-length chunk ends a transfer; unless we are reading POST
1898 http_content_coding_finish(http
);
1899 #endif /* HAVE_LIBZ */
1901 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1902 httpGets(len
, sizeof(len
), http
);
1904 if (http
->state
== HTTP_STATE_POST_RECV
)
1907 http
->state
= HTTP_STATE_STATUS
;
1909 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1910 httpStateString(http
->state
)));
1913 * Prevent future reads for this request...
1916 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1920 else if (length
> (size_t)http
->data_remaining
)
1921 length
= (size_t)http
->data_remaining
;
1924 if (http
->used
== 0 &&
1925 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1927 if (http
->used
== 0)
1928 #endif /* HAVE_LIBZ */
1931 * Buffer small reads for better performance...
1934 ssize_t buflen
; /* Length of read for buffer */
1936 if (!http
->blocking
)
1938 while (!httpWait(http
, http
->wait_value
))
1940 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1947 if (http
->data_remaining
> sizeof(http
->buffer
))
1948 buflen
= sizeof(http
->buffer
);
1950 buflen
= http
->data_remaining
;
1952 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1953 bytes
= http_read(http
, http
->buffer
, buflen
);
1955 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1956 CUPS_LLCAST bytes
));
1960 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1970 # ifdef HAVE_INFLATECOPY
1971 int zerr
; /* Decompressor error */
1972 z_stream stream
; /* Copy of decompressor stream */
1974 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1976 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1977 /* Number of bytes to copy */
1979 if (http
->stream
.avail_in
> 0 &&
1980 http
->stream
.next_in
> http
->dbuffer
)
1981 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1983 http
->stream
.next_in
= http
->dbuffer
;
1985 if (buflen
> http
->data_remaining
)
1986 buflen
= http
->data_remaining
;
1988 if (buflen
> http
->used
)
1989 buflen
= http
->used
;
1991 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1992 "decompression buffer.", (int)buflen
));
1994 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
1995 http
->stream
.avail_in
+= buflen
;
1996 http
->used
-= buflen
;
1997 http
->data_remaining
-= buflen
;
2000 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
2003 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
2004 (int)http
->stream
.avail_in
));
2006 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
2008 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
2009 http
->error
= ENOMEM
;
2013 stream
.next_out
= (Bytef
*)buffer
;
2014 stream
.avail_out
= length
;
2016 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
2017 inflateEnd(&stream
);
2021 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
2023 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
2024 http
->stream
.avail_in
);
2031 bytes
= length
- http
->stream
.avail_out
;
2034 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
2035 "work with compressed streams.");
2037 # endif /* HAVE_INFLATECOPY */
2040 #endif /* HAVE_LIBZ */
2043 if (length
> (size_t)http
->used
)
2044 length
= (size_t)http
->used
;
2046 bytes
= (ssize_t
)length
;
2048 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
2051 memcpy(buffer
, http
->buffer
, length
);
2059 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2062 http
->error
= WSAGetLastError();
2064 if (errno
== EINTR
|| errno
== EAGAIN
)
2067 http
->error
= errno
;
2070 else if (bytes
== 0)
2072 http
->error
= EPIPE
;
2079 /* For OS X 10.8 and earlier */
2080 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
2081 { return (httpPeek(http
, buffer
, length
)); }
2085 * 'httpPost()' - Send a POST request to the server.
2088 int /* O - Status of call (0 = success) */
2089 httpPost(http_t
*http
, /* I - HTTP connection */
2090 const char *uri
) /* I - URI for post */
2092 return (http_send(http
, HTTP_STATE_POST
, uri
));
2097 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
2102 int /* O - Number of bytes written */
2103 httpPrintf(http_t
*http
, /* I - HTTP connection */
2104 const char *format
, /* I - printf-style format string */
2105 ...) /* I - Additional args as needed */
2107 int bytes
; /* Number of bytes to write */
2108 char buf
[16384]; /* Buffer for formatted string */
2109 va_list ap
; /* Variable argument pointer */
2112 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
2114 va_start(ap
, format
);
2115 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
2118 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
2120 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
2121 return (httpWrite2(http
, buf
, bytes
));
2126 DEBUG_puts("4httpPrintf: flushing existing data...");
2128 if (httpFlushWrite(http
) < 0)
2132 return (http_write(http
, buf
, bytes
));
2138 * 'httpPut()' - Send a PUT request to the server.
2141 int /* O - Status of call (0 = success) */
2142 httpPut(http_t
*http
, /* I - HTTP connection */
2143 const char *uri
) /* I - URI to put */
2145 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2146 return (http_send(http
, HTTP_STATE_PUT
, uri
));
2151 * 'httpRead()' - Read data from a HTTP connection.
2153 * This function is deprecated. Use the httpRead2() function which can
2154 * read more than 2GB of data.
2159 int /* O - Number of bytes read */
2160 httpRead(http_t
*http
, /* I - HTTP connection */
2161 char *buffer
, /* I - Buffer for data */
2162 int length
) /* I - Maximum number of bytes */
2164 return ((int)httpRead2(http
, buffer
, length
));
2169 * 'httpRead2()' - Read data from a HTTP connection.
2171 * @since CUPS 1.2/OS X 10.5@
2174 ssize_t
/* O - Number of bytes read */
2175 httpRead2(http_t
*http
, /* I - HTTP connection */
2176 char *buffer
, /* I - Buffer for data */
2177 size_t length
) /* I - Maximum number of bytes */
2179 ssize_t bytes
; /* Bytes read */
2183 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2184 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
2185 http
, buffer
, CUPS_LLCAST length
,
2187 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2189 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2190 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
2191 http
, buffer
, CUPS_LLCAST length
,
2192 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2193 #endif /* HAVE_LIBZ */
2195 if (http
== NULL
|| buffer
== NULL
)
2198 http
->activity
= time(NULL
);
2209 if (http
->stream
.avail_in
> 0)
2211 int zerr
; /* Decompressor error */
2213 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2214 (int)http
->stream
.avail_in
, (int)length
));
2216 http
->stream
.next_out
= (Bytef
*)buffer
;
2217 http
->stream
.avail_out
= length
;
2219 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2221 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2223 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2224 http
->stream
.avail_in
);
2231 bytes
= length
- http
->stream
.avail_out
;
2233 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2234 http
->stream
.avail_in
, http
->stream
.avail_out
,
2242 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2243 /* Additional bytes for buffer */
2247 if (http
->stream
.avail_in
> 0 &&
2248 http
->stream
.next_in
> http
->dbuffer
)
2249 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2251 http
->stream
.next_in
= http
->dbuffer
;
2253 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2254 "decompression buffer.", (int)buflen
));
2256 if (http
->data_remaining
> 0)
2258 if (buflen
> http
->data_remaining
)
2259 buflen
= http
->data_remaining
;
2261 bytes
= http_read_buffered(http
,
2262 (char *)http
->dbuffer
+
2263 http
->stream
.avail_in
, buflen
);
2265 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2266 bytes
= http_read_chunk(http
,
2267 (char *)http
->dbuffer
+
2268 http
->stream
.avail_in
, buflen
);
2274 else if (bytes
== 0)
2277 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2278 "decompression buffer.", CUPS_LLCAST bytes
));
2280 http
->data_remaining
-= bytes
;
2281 http
->stream
.avail_in
+= bytes
;
2283 if (http
->data_remaining
<= 0 &&
2284 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2287 * Read the trailing blank line now...
2290 char len
[32]; /* Length string */
2292 httpGets(len
, sizeof(len
), http
);
2304 #endif /* HAVE_LIBZ */
2305 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2307 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2309 http
->data_remaining
-= bytes
;
2311 if (http
->data_remaining
<= 0)
2314 * Read the trailing blank line now...
2317 char len
[32]; /* Length string */
2319 httpGets(len
, sizeof(len
), http
);
2323 else if (http
->data_remaining
<= 0)
2326 * No more data to read...
2333 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2336 if (length
> (size_t)http
->data_remaining
)
2337 length
= (size_t)http
->data_remaining
;
2339 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2341 http
->data_remaining
-= bytes
;
2343 if (http
->data_remaining
<= 0 &&
2344 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2347 * Read the trailing blank line now...
2350 char len
[32]; /* Length string */
2352 httpGets(len
, sizeof(len
), http
);
2359 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2360 #endif /* HAVE_LIBZ */
2361 ((http
->data_remaining
<= 0 &&
2362 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2363 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2367 http_content_coding_finish(http
);
2368 #endif /* HAVE_LIBZ */
2370 if (http
->state
== HTTP_STATE_POST_RECV
)
2372 else if (http
->state
== HTTP_STATE_GET_SEND
||
2373 http
->state
== HTTP_STATE_POST_SEND
)
2374 http
->state
= HTTP_STATE_WAITING
;
2376 http
->state
= HTTP_STATE_STATUS
;
2378 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2379 httpStateString(http
->state
)));
2386 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2388 * '_httpReadCDSA()' - Read function for the CDSA library.
2391 OSStatus
/* O - -1 on error, 0 on success */
2393 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2394 void *data
, /* I - Data buffer */
2395 size_t *dataLength
) /* IO - Number of bytes */
2397 OSStatus result
; /* Return value */
2398 ssize_t bytes
; /* Number of bytes read */
2399 http_t
*http
; /* HTTP connection */
2402 http
= (http_t
*)connection
;
2404 if (!http
->blocking
)
2407 * Make sure we have data before we read...
2410 while (!_httpWait(http
, http
->wait_value
, 0))
2412 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2415 http
->error
= ETIMEDOUT
;
2422 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2424 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2426 if (bytes
== *dataLength
)
2432 *dataLength
= bytes
;
2433 result
= errSSLWouldBlock
;
2440 result
= errSSLClosedGraceful
;
2441 else if (errno
== EAGAIN
)
2442 result
= errSSLWouldBlock
;
2444 result
= errSSLClosedAbort
;
2449 #endif /* HAVE_SSL && HAVE_CDSASSL */
2452 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2454 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2457 ssize_t
/* O - Number of bytes read or -1 on error */
2459 gnutls_transport_ptr ptr
, /* I - HTTP connection */
2460 void *data
, /* I - Buffer */
2461 size_t length
) /* I - Number of bytes to read */
2463 http_t
*http
; /* HTTP connection */
2464 ssize_t bytes
; /* Bytes read */
2467 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2469 http
= (http_t
*)ptr
;
2471 if (!http
->blocking
)
2474 * Make sure we have data before we read...
2477 while (!_httpWait(http
, http
->wait_value
, 0))
2479 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2482 http
->error
= ETIMEDOUT
;
2487 bytes
= recv(http
->fd
, data
, length
, 0);
2488 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2491 #endif /* HAVE_SSL && HAVE_GNUTLS */
2495 * 'httpReadRequest()' - Read a HTTP request from a connection.
2497 * @since CUPS 1.7/OS X 10.9@
2500 http_state_t
/* O - New state of connection */
2501 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2502 char *uri
, /* I - URI buffer */
2503 size_t urilen
) /* I - Size of URI buffer */
2505 char line
[4096], /* HTTP request line */
2506 *req_method
, /* HTTP request method */
2507 *req_uri
, /* HTTP request URI */
2508 *req_version
; /* HTTP request version number string */
2512 * Range check input...
2515 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2516 http
, uri
, CUPS_LLCAST urilen
));
2521 if (!http
|| !uri
|| urilen
< 1)
2523 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2524 return (HTTP_STATE_ERROR
);
2526 else if (http
->state
!= HTTP_STATE_WAITING
)
2528 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2529 httpStateString(http
->state
)));
2530 return (HTTP_STATE_ERROR
);
2537 httpClearFields(http
);
2539 http
->activity
= time(NULL
);
2540 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2541 http
->data_remaining
= 0;
2542 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2543 http
->status
= HTTP_STATUS_OK
;
2544 http
->version
= HTTP_VERSION_1_1
;
2547 * Read a line from the socket...
2550 if (!httpGets(line
, sizeof(line
), http
))
2552 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2553 return (HTTP_STATE_ERROR
);
2558 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2559 return (HTTP_STATE_WAITING
);
2562 DEBUG_printf(("1httpReadRequest: %s", line
));
2571 while (*req_uri
&& !isspace(*req_uri
& 255))
2576 DEBUG_puts("1httpReadRequest: No request URI.");
2577 return (HTTP_STATE_ERROR
);
2582 while (*req_uri
&& isspace(*req_uri
& 255))
2585 req_version
= req_uri
;
2587 while (*req_version
&& !isspace(*req_version
& 255))
2592 DEBUG_puts("1httpReadRequest: No request protocol version.");
2593 return (HTTP_STATE_ERROR
);
2596 *req_version
++ = '\0';
2598 while (*req_version
&& isspace(*req_version
& 255))
2605 if (!strcmp(req_method
, "OPTIONS"))
2606 http
->state
= HTTP_STATE_OPTIONS
;
2607 else if (!strcmp(req_method
, "GET"))
2608 http
->state
= HTTP_STATE_GET
;
2609 else if (!strcmp(req_method
, "HEAD"))
2610 http
->state
= HTTP_STATE_HEAD
;
2611 else if (!strcmp(req_method
, "POST"))
2612 http
->state
= HTTP_STATE_POST
;
2613 else if (!strcmp(req_method
, "PUT"))
2614 http
->state
= HTTP_STATE_PUT
;
2615 else if (!strcmp(req_method
, "DELETE"))
2616 http
->state
= HTTP_STATE_DELETE
;
2617 else if (!strcmp(req_method
, "TRACE"))
2618 http
->state
= HTTP_STATE_TRACE
;
2619 else if (!strcmp(req_method
, "CONNECT"))
2620 http
->state
= HTTP_STATE_CONNECT
;
2623 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2624 return (HTTP_STATE_UNKNOWN_METHOD
);
2627 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2628 httpStateString(http
->state
)));
2630 if (!strcmp(req_version
, "HTTP/1.0"))
2632 http
->version
= HTTP_VERSION_1_0
;
2633 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2635 else if (!strcmp(req_version
, "HTTP/1.1"))
2637 http
->version
= HTTP_VERSION_1_1
;
2638 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2642 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2643 return (HTTP_STATE_UNKNOWN_VERSION
);
2646 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2647 strlcpy(uri
, req_uri
, urilen
);
2649 return (http
->state
);
2654 * 'httpReconnect()' - Reconnect to a HTTP server.
2656 * This function is deprecated. Please use the @link httpReconnect2@ function
2662 int /* O - 0 on success, non-zero on failure */
2663 httpReconnect(http_t
*http
) /* I - HTTP connection */
2665 DEBUG_printf(("httpReconnect(http=%p)", http
));
2667 return (httpReconnect2(http
, 30000, NULL
));
2672 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2676 int /* O - 0 on success, non-zero on failure */
2677 httpReconnect2(http_t
*http
, /* I - HTTP connection */
2678 int msec
, /* I - Timeout in milliseconds */
2679 int *cancel
) /* I - Pointer to "cancel" variable */
2681 http_addrlist_t
*addr
; /* Connected address */
2683 http_addrlist_t
*current
; /* Current address */
2684 char temp
[256]; /* Temporary address string */
2688 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2693 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2700 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2701 http_shutdown_ssl(http
);
2703 #endif /* HAVE_SSL */
2706 * Close any previously open socket...
2711 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2714 closesocket(http
->fd
);
2723 * Reset all state (except fields, which may be reused)...
2726 http
->state
= HTTP_STATE_WAITING
;
2727 http
->version
= HTTP_VERSION_1_1
;
2728 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2729 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2730 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2731 http
->_data_remaining
= 0;
2733 http
->data_remaining
= 0;
2734 http
->hostaddr
= NULL
;
2738 * Connect to the server...
2742 for (current
= http
->addrlist
; current
; current
= current
->next
)
2743 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2744 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2745 httpAddrPort(&(current
->addr
))));
2748 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2752 * Unable to connect...
2756 http
->error
= WSAGetLastError();
2758 http
->error
= errno
;
2760 http
->status
= HTTP_STATUS_ERROR
;
2762 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2763 strerror(http
->error
)));
2768 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2770 if (http
->timeout_value
> 0)
2771 http_set_timeout(http
->fd
, http
->timeout_value
);
2773 http
->hostaddr
= &(addr
->addr
);
2777 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2780 * Always do encryption via SSL.
2783 if (http_setup_ssl(http
) != 0)
2786 closesocket(http
->fd
);
2794 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2795 return (http_upgrade(http
));
2796 #endif /* HAVE_SSL */
2798 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2799 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2800 httpAddrPort(http
->hostaddr
)));
2807 * 'httpSetAuthString()' - Set the current authorization string.
2809 * This function just stores a copy of the current authorization string in
2810 * the HTTP connection object. You must still call httpSetField() to set
2811 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2812 * httpHead(), httpOptions(), httpPost, or httpPut().
2814 * @since CUPS 1.3/OS X 10.5@
2818 httpSetAuthString(http_t
*http
, /* I - HTTP connection */
2819 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2820 const char *data
) /* I - Auth data (NULL for none) */
2823 * Range check input...
2829 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2830 free(http
->authstring
);
2832 http
->authstring
= http
->_authstring
;
2837 * Set the current authorization string...
2840 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2843 if (len
> (int)sizeof(http
->_authstring
))
2845 if ((temp
= malloc(len
)) == NULL
)
2846 len
= sizeof(http
->_authstring
);
2848 http
->authstring
= temp
;
2852 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2854 strlcpy(http
->authstring
, scheme
, len
);
2859 * Clear the current authorization string...
2862 http
->_authstring
[0] = '\0';
2868 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2871 * @since CUPS 1.5/OS X 10.7@
2874 int /* O - Status of call (0 = success) */
2875 httpSetCredentials(http_t
*http
, /* I - HTTP connection */
2876 cups_array_t
*credentials
) /* I - Array of credentials */
2878 if (!http
|| cupsArrayCount(credentials
) < 1)
2881 _httpFreeCredentials(http
->tls_credentials
);
2883 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2885 return (http
->tls_credentials
? 0 : -1);
2890 * 'httpSetCookie()' - Set the cookie value(s).
2892 * @since CUPS 1.1.19/OS X 10.3@
2896 httpSetCookie(http_t
*http
, /* I - Connection */
2897 const char *cookie
) /* I - Cookie string */
2906 http
->cookie
= strdup(cookie
);
2908 http
->cookie
= NULL
;
2913 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2915 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2916 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2918 * @since CUPS 1.7/OS X 10.9@
2922 httpSetDefaultField(http_t
*http
, /* I - HTTP connection */
2923 http_field_t field
, /* I - Field index */
2924 const char *value
)/* I - Value */
2926 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2927 http
, field
, http_fields
[field
], value
));
2934 case HTTP_FIELD_ACCEPT_ENCODING
:
2935 if (http
->default_accept_encoding
)
2936 _cupsStrFree(http
->default_accept_encoding
);
2938 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2941 case HTTP_FIELD_SERVER
:
2942 if (http
->default_server
)
2943 _cupsStrFree(http
->default_server
);
2945 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2948 case HTTP_FIELD_USER_AGENT
:
2949 if (http
->default_user_agent
)
2950 _cupsStrFree(http
->default_user_agent
);
2952 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2956 DEBUG_puts("1httpSetDefaultField: Ignored.");
2963 * 'httpSetExpect()' - Set the Expect: header in a request.
2965 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2968 * @since CUPS 1.2/OS X 10.5@
2972 httpSetExpect(http_t
*http
, /* I - HTTP connection */
2973 http_status_t expect
) /* I - HTTP status to expect
2974 (@code HTTP_STATUS_CONTINUE@) */
2976 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2979 http
->expect
= expect
;
2984 * 'httpSetField()' - Set the value of an HTTP header.
2988 httpSetField(http_t
*http
, /* I - HTTP connection */
2989 http_field_t field
, /* I - Field index */
2990 const char *value
) /* I - Value */
2992 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2993 field
, http_fields
[field
], value
));
2996 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2997 field
>= HTTP_FIELD_MAX
||
3003 case HTTP_FIELD_ACCEPT_ENCODING
:
3004 if (http
->accept_encoding
)
3005 _cupsStrFree(http
->accept_encoding
);
3007 http
->accept_encoding
= _cupsStrAlloc(value
);
3010 case HTTP_FIELD_ALLOW
:
3012 _cupsStrFree(http
->allow
);
3014 http
->allow
= _cupsStrAlloc(value
);
3017 case HTTP_FIELD_SERVER
:
3019 _cupsStrFree(http
->server
);
3021 http
->server
= _cupsStrAlloc(value
);
3025 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
3029 if (field
== HTTP_FIELD_AUTHORIZATION
)
3032 * Special case for Authorization: as its contents can be
3033 * longer than HTTP_MAX_VALUE
3036 if (http
->field_authorization
)
3037 free(http
->field_authorization
);
3039 http
->field_authorization
= strdup(value
);
3041 else if (field
== HTTP_FIELD_HOST
)
3044 * Special-case for Host: as we don't want a trailing "." on the hostname and
3045 * need to bracket IPv6 numeric addresses.
3048 char *ptr
= strchr(value
, ':');
3050 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
3053 * Bracket IPv6 numeric addresses...
3055 * This is slightly inefficient (basically copying twice), but is an edge
3056 * case and not worth optimizing...
3059 snprintf(http
->fields
[HTTP_FIELD_HOST
],
3060 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
3065 * Check for a trailing dot on the hostname...
3068 ptr
= http
->fields
[HTTP_FIELD_HOST
];
3072 ptr
+= strlen(ptr
) - 1;
3080 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
3081 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
3083 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
3084 http_content_coding_start(http
, value
);
3086 #endif /* HAVE_LIBZ */
3091 * 'httpSetKeepAlive()' - Set the current Keep-Alive state of a connection.
3098 http_t
*http
, /* I - HTTP connection */
3099 http_keepalive_t keep_alive
) /* I - New Keep-Alive value */
3102 http
->keep_alive
= keep_alive
;
3107 * 'httpSetLength()' - Set the content-length and content-encoding.
3109 * @since CUPS 1.2/OS X 10.5@
3113 httpSetLength(http_t
*http
, /* I - HTTP connection */
3114 size_t length
) /* I - Length (0 for chunked) */
3116 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
3117 CUPS_LLCAST length
));
3124 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
3126 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
3130 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
3131 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
3132 CUPS_LLFMT
, CUPS_LLCAST length
);
3138 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
3140 * The optional timeout callback receives both the HTTP connection and a user
3141 * data pointer and must return 1 to continue or 0 to error (time) out.
3143 * @since CUPS 1.5/OS X 10.7@
3148 http_t
*http
, /* I - HTTP connection */
3149 double timeout
, /* I - Number of seconds for timeout,
3150 must be greater than 0 */
3151 http_timeout_cb_t cb
, /* I - Callback function or NULL */
3152 void *user_data
) /* I - User data pointer */
3154 if (!http
|| timeout
<= 0.0)
3157 http
->timeout_cb
= cb
;
3158 http
->timeout_data
= user_data
;
3159 http
->timeout_value
= timeout
;
3162 http_set_timeout(http
->fd
, timeout
);
3164 http_set_wait(http
);
3169 * 'httpShutdown()' - Shutdown one side of an HTTP connection.
3175 httpShutdown(http_t
*http
) /* I - HTTP connection */
3177 if (!http
|| http
->fd
< 0)
3181 http_shutdown_ssl(http
);
3183 shutdown(http
->fd
, SHUT_RD
);
3188 * 'httpTrace()' - Send an TRACE request to the server.
3191 int /* O - Status of call (0 = success) */
3192 httpTrace(http_t
*http
, /* I - HTTP connection */
3193 const char *uri
) /* I - URI for trace */
3195 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
3200 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3202 * Note: Unlike httpUpdate(), this function does not flush pending write data
3203 * and only retrieves a single status line from the HTTP connection.
3206 int /* O - 1 to continue, 0 to stop */
3207 _httpUpdate(http_t
*http
, /* I - HTTP connection */
3208 http_status_t
*status
) /* O - Current HTTP status */
3210 char line
[32768], /* Line from connection... */
3211 *value
; /* Pointer to value on line */
3212 http_field_t field
; /* Field index */
3213 int major
, minor
; /* HTTP version numbers */
3216 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3217 httpStateString(http
->state
)));
3220 * Grab a single line from the connection...
3223 if (!httpGets(line
, sizeof(line
), http
))
3225 *status
= HTTP_STATUS_ERROR
;
3229 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3231 if (line
[0] == '\0')
3234 * Blank line means the start of the data section (if any). Return
3235 * the result code, too...
3237 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3238 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3242 if (http
->status
== HTTP_STATUS_CONTINUE
)
3244 *status
= http
->status
;
3248 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
3249 http
->digest_tries
= 0;
3252 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
3254 if (http_setup_ssl(http
) != 0)
3257 closesocket(http
->fd
);
3262 *status
= http
->status
= HTTP_STATUS_ERROR
;
3266 *status
= HTTP_STATUS_CONTINUE
;
3269 #endif /* HAVE_SSL */
3271 if (http_set_length(http
) < 0)
3273 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3274 http
->error
= EINVAL
;
3275 http
->status
= *status
= HTTP_STATUS_ERROR
;
3279 switch (http
->state
)
3281 case HTTP_STATE_GET
:
3282 case HTTP_STATE_POST
:
3283 case HTTP_STATE_POST_RECV
:
3284 case HTTP_STATE_PUT
:
3287 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3288 httpStateString(http
->state
)));
3290 case HTTP_STATE_POST_SEND
:
3291 case HTTP_STATE_HEAD
:
3295 http
->state
= HTTP_STATE_WAITING
;
3297 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
3302 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3303 http_content_coding_start(http
,
3304 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3305 #endif /* HAVE_LIBZ */
3307 *status
= http
->status
;
3310 else if (!strncmp(line
, "HTTP/", 5))
3313 * Got the beginning of a response...
3316 int intstatus
; /* Status value as an integer */
3318 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3320 *status
= http
->status
= HTTP_STATUS_ERROR
;
3324 httpClearFields(http
);
3326 http
->version
= (http_version_t
)(major
* 100 + minor
);
3327 *status
= http
->status
= (http_status_t
)intstatus
;
3329 else if ((value
= strchr(line
, ':')) != NULL
)
3336 while (_cups_isspace(*value
))
3339 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3342 * Be tolerants of servers that send unknown attribute fields...
3345 if (!_cups_strcasecmp(line
, "expect"))
3348 * "Expect: 100-continue" or similar...
3351 http
->expect
= (http_status_t
)atoi(value
);
3353 else if (!_cups_strcasecmp(line
, "cookie"))
3356 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3359 httpSetCookie(http
, value
);
3361 else if ((field
= httpFieldValue(line
)) != HTTP_FIELD_UNKNOWN
)
3362 httpSetField(http
, field
, value
);
3365 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3370 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3371 http
->error
= EINVAL
;
3372 http
->status
= *status
= HTTP_STATUS_ERROR
;
3381 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3384 http_status_t
/* O - HTTP status */
3385 httpUpdate(http_t
*http
) /* I - HTTP connection */
3387 http_status_t status
; /* Request status */
3390 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3391 httpStateString(http
->state
)));
3394 * Flush pending data, if any...
3399 DEBUG_puts("2httpUpdate: flushing buffer...");
3401 if (httpFlushWrite(http
) < 0)
3402 return (HTTP_STATUS_ERROR
);
3406 * If we haven't issued any commands, then there is nothing to "update"...
3409 if (http
->state
== HTTP_STATE_WAITING
)
3410 return (HTTP_STATUS_CONTINUE
);
3413 * Grab all of the lines we can from the connection...
3416 while (_httpUpdate(http
, &status
));
3419 * See if there was an error...
3422 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3424 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3425 return (http
->status
);
3430 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3431 strerror(http
->error
)));
3432 http
->status
= HTTP_STATUS_ERROR
;
3433 return (HTTP_STATUS_ERROR
);
3437 * Return the current status...
3445 * '_httpWait()' - Wait for data available on a connection (no flush).
3448 int /* O - 1 if data is available, 0 otherwise */
3449 _httpWait(http_t
*http
, /* I - HTTP connection */
3450 int msec
, /* I - Milliseconds to wait */
3451 int usessl
) /* I - Use SSL context? */
3454 struct pollfd pfd
; /* Polled file descriptor */
3456 fd_set input_set
; /* select() input set */
3457 struct timeval timeout
; /* Timeout */
3458 #endif /* HAVE_POLL */
3459 int nfds
; /* Result from select()/poll() */
3462 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3466 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3471 * Check the SSL/TLS buffers for data first...
3475 if (http
->tls
&& usessl
)
3478 if (SSL_pending(http
->tls
))
3480 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3484 # elif defined(HAVE_GNUTLS)
3485 if (gnutls_record_check_pending(http
->tls
))
3487 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3491 # elif defined(HAVE_CDSASSL)
3492 size_t bytes
; /* Bytes that are available */
3494 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3497 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3500 # endif /* HAVE_LIBSSL */
3502 #endif /* HAVE_SSL */
3505 * Then try doing a select() or poll() to poll the socket...
3510 pfd
.events
= POLLIN
;
3514 nfds
= poll(&pfd
, 1, msec
);
3516 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3521 FD_ZERO(&input_set
);
3522 FD_SET(http
->fd
, &input_set
);
3524 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3528 timeout
.tv_sec
= msec
/ 1000;
3529 timeout
.tv_usec
= (msec
% 1000) * 1000;
3531 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3534 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3536 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3539 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3540 WSAGetLastError() == WSAEWOULDBLOCK
));
3542 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3544 #endif /* HAVE_POLL */
3546 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3554 * 'httpWait()' - Wait for data available on a connection.
3556 * @since CUPS 1.1.19/OS X 10.3@
3559 int /* O - 1 if data is available, 0 otherwise */
3560 httpWait(http_t
*http
, /* I - HTTP connection */
3561 int msec
) /* I - Milliseconds to wait */
3564 * First see if there is data in the buffer...
3567 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3574 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3579 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3581 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3584 #endif /* HAVE_LIBZ */
3587 * Flush pending data, if any...
3592 DEBUG_puts("3httpWait: Flushing write buffer.");
3594 if (httpFlushWrite(http
) < 0)
3599 * If not, check the SSL/TLS buffers and do a select() on the connection...
3602 return (_httpWait(http
, msec
, 1));
3607 * 'httpWrite()' - Write data to a HTTP connection.
3609 * This function is deprecated. Use the httpWrite2() function which can
3610 * write more than 2GB of data.
3615 int /* O - Number of bytes written */
3616 httpWrite(http_t
*http
, /* I - HTTP connection */
3617 const char *buffer
, /* I - Buffer for data */
3618 int length
) /* I - Number of bytes to write */
3620 return ((int)httpWrite2(http
, buffer
, length
));
3625 * 'httpWrite2()' - Write data to a HTTP connection.
3627 * @since CUPS 1.2/OS X 10.5@
3630 ssize_t
/* O - Number of bytes written */
3631 httpWrite2(http_t
*http
, /* I - HTTP connection */
3632 const char *buffer
, /* I - Buffer for data */
3633 size_t length
) /* I - Number of bytes to write */
3635 ssize_t bytes
; /* Bytes written */
3638 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3639 buffer
, CUPS_LLCAST length
));
3642 * Range check input...
3645 if (!http
|| !buffer
)
3647 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3652 * Mark activity on the connection...
3655 http
->activity
= time(NULL
);
3658 * Buffer small writes for better performance...
3664 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3668 http_content_coding_finish(http
);
3673 http
->stream
.next_in
= (Bytef
*)buffer
;
3674 http
->stream
.avail_in
= length
;
3675 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3676 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3678 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3680 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3682 if (http
->stream
.avail_out
== 0)
3684 if (httpFlushWrite(http
) < 0)
3686 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3690 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3691 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3695 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3700 #endif /* HAVE_LIBZ */
3703 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3705 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3706 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3708 httpFlushWrite(http
);
3711 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3712 length
< sizeof(http
->wbuffer
))
3715 * Write to buffer...
3718 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3719 CUPS_LLCAST length
));
3721 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3722 http
->wused
+= (int)length
;
3723 bytes
= (ssize_t
)length
;
3728 * Otherwise write the data directly...
3731 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3732 CUPS_LLCAST length
));
3734 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3735 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3737 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3739 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3740 CUPS_LLCAST bytes
));
3743 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3744 http
->data_remaining
-= bytes
;
3750 * Handle end-of-request processing...
3753 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3754 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3757 * Finished with the transfer; unless we are sending POST or PUT
3763 http_content_coding_finish(http
);
3764 #endif /* HAVE_LIBZ */
3768 if (httpFlushWrite(http
) < 0)
3772 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3775 * Send a 0-length chunk at the end of the request...
3778 http_write(http
, "0\r\n\r\n", 5);
3781 * Reset the data state...
3784 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3785 http
->data_remaining
= 0;
3788 if (http
->state
== HTTP_STATE_POST_RECV
)
3790 else if (http
->state
== HTTP_STATE_POST_SEND
)
3791 http
->state
= HTTP_STATE_WAITING
;
3793 http
->state
= HTTP_STATE_STATUS
;
3795 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3796 httpStateString(http
->state
)));
3799 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3805 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3807 * '_httpWriteCDSA()' - Write function for the CDSA library.
3810 OSStatus
/* O - -1 on error, 0 on success */
3812 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3813 const void *data
, /* I - Data buffer */
3814 size_t *dataLength
) /* IO - Number of bytes */
3816 OSStatus result
; /* Return value */
3817 ssize_t bytes
; /* Number of bytes read */
3818 http_t
*http
; /* HTTP connection */
3821 http
= (http_t
*)connection
;
3825 bytes
= write(http
->fd
, data
, *dataLength
);
3827 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3829 if (bytes
== *dataLength
)
3833 else if (bytes
>= 0)
3835 *dataLength
= bytes
;
3836 result
= errSSLWouldBlock
;
3842 if (errno
== EAGAIN
)
3843 result
= errSSLWouldBlock
;
3845 result
= errSSLClosedAbort
;
3850 #endif /* HAVE_SSL && HAVE_CDSASSL */
3853 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3855 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3858 ssize_t
/* O - Number of bytes written or -1 on error */
3860 gnutls_transport_ptr ptr
, /* I - HTTP connection */
3861 const void *data
, /* I - Data buffer */
3862 size_t length
) /* I - Number of bytes to write */
3864 ssize_t bytes
; /* Bytes written */
3867 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3870 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3873 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3874 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3878 #endif /* HAVE_SSL && HAVE_GNUTLS */
3882 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3884 * @since CUPS 1.7/OS X 10.9@
3887 int /* O - 0 on success, -1 on error */
3888 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3889 http_status_t status
) /* I - Status code */
3891 http_encoding_t old_encoding
; /* Old data_encoding value */
3892 off_t old_remaining
; /* Old data_remaining value */
3896 * Range check input...
3899 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3901 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3903 DEBUG_puts("1httpWriteResponse: Bad input.");
3908 * Set the various standard fields if they aren't already...
3911 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3912 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3914 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3916 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
3917 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3920 if (http
->version
== HTTP_VERSION_1_1
)
3922 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3924 if (http
->keep_alive
)
3925 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3927 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3930 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3931 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3935 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
)
3937 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3938 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3940 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3941 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3943 #endif /* HAVE_SSL */
3946 httpSetField(http
, HTTP_FIELD_SERVER
,
3947 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3950 * Set the Accept-Encoding field if it isn't already...
3953 if (!http
->accept_encoding
)
3954 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3955 http
->default_accept_encoding
? http
->default_accept_encoding
:
3957 "gzip, deflate, identity");
3960 #endif /* HAVE_LIBZ */
3963 * Send the response header...
3966 old_encoding
= http
->data_encoding
;
3967 old_remaining
= http
->data_remaining
;
3968 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3970 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3971 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3973 http
->status
= HTTP_STATUS_ERROR
;
3977 if (status
!= HTTP_STATUS_CONTINUE
)
3980 * 100 Continue doesn't have the rest of the response headers...
3983 int i
; /* Looping var */
3984 const char *value
; /* Field value */
3986 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3988 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3990 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3992 http
->status
= HTTP_STATUS_ERROR
;
4000 if (httpPrintf(http
, "Set-Cookie: %s path=/%s\r\n", http
->cookie
,
4001 http
->tls
? " secure" : "") < 1)
4003 http
->status
= HTTP_STATUS_ERROR
;
4009 if (httpWrite2(http
, "\r\n", 2) < 2)
4011 http
->status
= HTTP_STATUS_ERROR
;
4015 if (httpFlushWrite(http
) < 0)
4017 http
->status
= HTTP_STATUS_ERROR
;
4021 if (status
== HTTP_STATUS_CONTINUE
)
4024 * Restore the old data_encoding and data_length values...
4027 http
->data_encoding
= old_encoding
;
4028 http
->data_remaining
= old_remaining
;
4030 if (old_remaining
<= INT_MAX
)
4031 http
->_data_remaining
= (int)old_remaining
;
4033 http
->_data_remaining
= INT_MAX
;
4035 else if (http
->state
== HTTP_STATE_OPTIONS
||
4036 http
->state
== HTTP_STATE_HEAD
||
4037 http
->state
== HTTP_STATE_PUT
||
4038 http
->state
== HTTP_STATE_TRACE
||
4039 http
->state
== HTTP_STATE_CONNECT
||
4040 http
->state
== HTTP_STATE_STATUS
)
4042 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
4043 "was %s.", httpStateString(http
->state
)));
4044 http
->state
= HTTP_STATE_WAITING
;
4049 * Force data_encoding and data_length to be set according to the response
4053 http_set_length(http
);
4057 * Then start any content encoding...
4060 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
4061 http_content_coding_start(http
,
4062 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
4063 #endif /* HAVE_LIBZ */
4070 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
4072 * 'http_bio_ctrl()' - Control the HTTP connection.
4075 static long /* O - Result/data */
4076 http_bio_ctrl(BIO
*h
, /* I - BIO data */
4077 int cmd
, /* I - Control command */
4078 long arg1
, /* I - First argument */
4079 void *arg2
) /* I - Second argument */
4086 case BIO_CTRL_RESET
:
4090 case BIO_C_SET_FILE_PTR
:
4095 case BIO_C_GET_FILE_PTR
:
4098 *((void **)arg2
) = h
->ptr
;
4105 case BIO_CTRL_FLUSH
:
4112 * 'http_bio_free()' - Free OpenSSL data.
4115 static int /* O - 1 on success, 0 on failure */
4116 http_bio_free(BIO
*h
) /* I - BIO data */
4132 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
4135 static int /* O - 1 on success, 0 on failure */
4136 http_bio_new(BIO
*h
) /* I - BIO data */
4151 * 'http_bio_puts()' - Send a string for OpenSSL.
4154 static int /* O - Bytes written */
4155 http_bio_puts(BIO
*h
, /* I - BIO data */
4156 const char *str
) /* I - String to write */
4159 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
4161 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
4167 * 'http_bio_read()' - Read data for OpenSSL.
4170 static int /* O - Bytes read */
4171 http_bio_read(BIO
*h
, /* I - BIO data */
4172 char *buf
, /* I - Buffer */
4173 int size
) /* I - Number of bytes to read */
4175 http_t
*http
; /* HTTP connection */
4178 http
= (http_t
*)h
->ptr
;
4180 if (!http
->blocking
)
4183 * Make sure we have data before we read...
4186 while (!_httpWait(http
, http
->wait_value
, 0))
4188 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4192 http
->error
= WSAETIMEDOUT
;
4194 http
->error
= ETIMEDOUT
;
4201 return (recv(http
->fd
, buf
, size
, 0));
4206 * 'http_bio_write()' - Write data for OpenSSL.
4209 static int /* O - Bytes written */
4210 http_bio_write(BIO
*h
, /* I - BIO data */
4211 const char *buf
, /* I - Buffer to write */
4212 int num
) /* I - Number of bytes to write */
4214 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4216 #endif /* HAVE_SSL && HAVE_LIBSSL */
4221 * 'http_content_coding_finish()' - Finish doing any content encoding.
4225 http_content_coding_finish(
4226 http_t
*http
) /* I - HTTP connection */
4228 int zerr
; /* Compression status */
4231 switch (http
->coding
)
4233 case _HTTP_CODING_DEFLATE
:
4234 case _HTTP_CODING_GZIP
:
4237 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4238 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4240 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4242 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4243 if (http
->wused
== sizeof(http
->wbuffer
))
4244 httpFlushWrite(http
);
4246 while (zerr
== Z_OK
);
4248 deflateEnd(&(http
->stream
));
4251 httpFlushWrite(http
);
4254 case _HTTP_CODING_INFLATE
:
4255 case _HTTP_CODING_GUNZIP
:
4256 inflateEnd(&(http
->stream
));
4257 free(http
->dbuffer
);
4258 http
->dbuffer
= NULL
;
4265 http
->coding
= _HTTP_CODING_IDENTITY
;
4270 * 'http_content_coding_start()' - Start doing content encoding.
4274 http_content_coding_start(
4275 http_t
*http
, /* I - HTTP connection */
4276 const char *value
) /* I - Value of Content-Encoding */
4278 int zerr
; /* Error/status */
4279 _http_coding_t coding
; /* Content coding value */
4282 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4285 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4287 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4291 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4293 if (http
->state
== HTTP_STATE_GET_SEND
||
4294 http
->state
== HTTP_STATE_POST_SEND
)
4295 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4296 _HTTP_CODING_GUNZIP
;
4297 else if (http
->state
== HTTP_STATE_POST_RECV
||
4298 http
->state
== HTTP_STATE_PUT_RECV
)
4299 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4300 _HTTP_CODING_GUNZIP
;
4303 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4307 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4309 if (http
->state
== HTTP_STATE_GET_SEND
||
4310 http
->state
== HTTP_STATE_POST_SEND
)
4311 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4312 _HTTP_CODING_INFLATE
;
4313 else if (http
->state
== HTTP_STATE_POST_RECV
||
4314 http
->state
== HTTP_STATE_PUT_RECV
)
4315 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4316 _HTTP_CODING_INFLATE
;
4319 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4325 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4329 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4333 case _HTTP_CODING_DEFLATE
:
4334 case _HTTP_CODING_GZIP
:
4336 httpFlushWrite(http
);
4339 * Window size for compression is 11 bits - optimal based on PWG Raster
4340 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
4344 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4346 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
4347 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4349 http
->status
= HTTP_STATUS_ERROR
;
4350 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4355 case _HTTP_CODING_INFLATE
:
4356 case _HTTP_CODING_GUNZIP
:
4357 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
4359 http
->status
= HTTP_STATUS_ERROR
;
4360 http
->error
= errno
;
4365 * Window size for decompression is up to 15 bits (maximum supported).
4366 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
4369 if ((zerr
= inflateInit2(&(http
->stream
),
4370 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
4373 free(http
->dbuffer
);
4374 http
->dbuffer
= NULL
;
4375 http
->status
= HTTP_STATUS_ERROR
;
4376 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4380 http
->stream
.avail_in
= 0;
4381 http
->stream
.next_in
= http
->dbuffer
;
4388 http
->coding
= coding
;
4390 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4393 #endif /* HAVE_LIBZ */
4397 * 'http_create()' - Create an unconnected HTTP connection.
4400 static http_t
* /* O - HTTP connection */
4402 const char *host
, /* I - Hostname */
4403 int port
, /* I - Port number */
4404 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
4405 int family
, /* I - Address family or AF_UNSPEC */
4406 http_encryption_t encryption
, /* I - Encryption to use */
4407 int blocking
, /* I - 1 for blocking mode */
4408 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
4410 http_t
*http
; /* New HTTP connection */
4411 char service
[255]; /* Service name */
4412 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
4415 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
4416 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
4417 family
, encryption
, blocking
, mode
));
4419 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
4425 * Lookup the host...
4430 myaddrlist
= httpAddrCopyList(addrlist
);
4434 snprintf(service
, sizeof(service
), "%d", port
);
4436 myaddrlist
= httpAddrGetList(host
, family
, service
);
4443 * Allocate memory for the structure...
4446 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
4448 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
4449 httpAddrFreeList(addrlist
);
4454 * Initialize the HTTP data...
4458 http
->activity
= time(NULL
);
4459 http
->addrlist
= myaddrlist
;
4460 http
->blocking
= blocking
;
4463 http
->gssctx
= GSS_C_NO_CONTEXT
;
4464 http
->gssname
= GSS_C_NO_NAME
;
4465 #endif /* HAVE_GSSAPI */
4466 http
->status
= HTTP_STATUS_CONTINUE
;
4467 http
->version
= HTTP_VERSION_1_1
;
4470 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
4472 if (port
== 443) /* Always use encryption for https */
4473 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
4475 http
->encryption
= encryption
;
4477 http_set_wait(http
);
4480 * Return the new structure...
4486 /* For OS X 10.8 and earlier */
4487 http_t
*_httpCreate(const char *host
, int port
, http_addrlist_t
*addrlist
,
4488 http_encryption_t encryption
, int family
)
4489 { return (http_create(host
, port
, addrlist
, family
, encryption
, 1,
4490 _HTTP_MODE_CLIENT
)); }
4495 * 'http_debug_hex()' - Do a hex dump of a buffer.
4499 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4500 const char *buffer
, /* I - Buffer to dump */
4501 int bytes
) /* I - Bytes to dump */
4503 int i
, j
, /* Looping vars */
4504 ch
; /* Current character */
4505 char line
[255], /* Line buffer */
4506 *start
, /* Start of line after prefix */
4507 *ptr
; /* Pointer into line */
4510 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4513 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4515 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4516 start
= line
+ strlen(line
);
4518 for (i
= 0; i
< bytes
; i
+= 16)
4520 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4521 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4525 memcpy(ptr
, " ", 3);
4530 memcpy(ptr
, " ", 3);
4533 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4535 ch
= buffer
[i
+ j
] & 255;
4537 if (ch
< ' ' || ch
>= 127)
4551 * 'http_read()' - Read a buffer from a HTTP connection.
4553 * This function does the low-level read from the socket, retrying and timing
4557 static ssize_t
/* O - Number of bytes read or -1 on error */
4558 http_read(http_t
*http
, /* I - HTTP connection */
4559 char *buffer
, /* I - Buffer */
4560 size_t length
) /* I - Maximum bytes to read */
4562 ssize_t bytes
; /* Bytes read */
4565 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4566 buffer
, CUPS_LLCAST length
));
4568 if (!http
->blocking
)
4570 while (!httpWait(http
, http
->wait_value
))
4572 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4575 DEBUG_puts("2http_read: Timeout.");
4580 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4586 bytes
= http_read_ssl(http
, buffer
, length
);
4588 #endif /* HAVE_SSL */
4589 bytes
= recv(http
->fd
, buffer
, length
, 0);
4594 if (WSAGetLastError() != WSAEINTR
)
4596 http
->error
= WSAGetLastError();
4599 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4601 if (!http
->timeout_cb
||
4602 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4604 http
->error
= WSAEWOULDBLOCK
;
4609 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4611 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4613 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4615 http
->error
= errno
;
4618 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4620 http
->error
= errno
;
4624 else if (errno
!= EINTR
)
4626 http
->error
= errno
;
4634 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4635 CUPS_LLCAST bytes
));
4638 http_debug_hex("http_read", buffer
, (int)bytes
);
4644 if (WSAGetLastError() == WSAEINTR
)
4647 http
->error
= WSAGetLastError();
4649 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4652 http
->error
= errno
;
4655 else if (bytes
== 0)
4657 http
->error
= EPIPE
;
4666 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4668 * This function reads data from the HTTP buffer or from the socket, as needed.
4671 static ssize_t
/* O - Number of bytes read or -1 on error */
4672 http_read_buffered(http_t
*http
, /* I - HTTP connection */
4673 char *buffer
, /* I - Buffer */
4674 size_t length
) /* I - Maximum bytes to read */
4676 ssize_t bytes
; /* Bytes read */
4679 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4681 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4685 if (length
> (size_t)http
->used
)
4686 bytes
= (size_t)http
->used
;
4690 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4693 memcpy(buffer
, http
->buffer
, bytes
);
4694 http
->used
-= (int)bytes
;
4697 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4700 bytes
= http_read(http
, buffer
, length
);
4707 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4709 * This function reads and validates the chunk length, then does a buffered read
4710 * returning the number of bytes placed in the buffer.
4713 static ssize_t
/* O - Number of bytes read or -1 on error */
4714 http_read_chunk(http_t
*http
, /* I - HTTP connection */
4715 char *buffer
, /* I - Buffer */
4716 size_t length
) /* I - Maximum bytes to read */
4718 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4719 http
, buffer
, CUPS_LLCAST length
));
4721 if (http
->data_remaining
<= 0)
4723 char len
[32]; /* Length string */
4725 if (!httpGets(len
, sizeof(len
), http
))
4727 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4733 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4734 if (!httpGets(len
, sizeof(len
), http
))
4736 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4741 http
->data_remaining
= strtoll(len
, NULL
, 16);
4743 if (http
->data_remaining
< 0)
4745 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4746 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4750 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4751 len
, CUPS_LLCAST http
->data_remaining
));
4753 if (http
->data_remaining
== 0)
4756 * 0-length chunk, grab trailing blank line...
4759 httpGets(len
, sizeof(len
), http
);
4763 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4764 CUPS_LLCAST http
->data_remaining
));
4766 if (http
->data_remaining
<= 0)
4768 else if (length
> (size_t)http
->data_remaining
)
4769 length
= (size_t)http
->data_remaining
;
4771 return (http_read_buffered(http
, buffer
, length
));
4777 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4780 static int /* O - Bytes read */
4781 http_read_ssl(http_t
*http
, /* I - HTTP connection */
4782 char *buf
, /* I - Buffer to store data */
4783 int len
) /* I - Length of buffer */
4785 # if defined(HAVE_LIBSSL)
4786 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4788 # elif defined(HAVE_GNUTLS)
4789 ssize_t result
; /* Return value */
4792 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4794 if (result
< 0 && !errno
)
4797 * Convert GNU TLS error to errno value...
4802 case GNUTLS_E_INTERRUPTED
:
4806 case GNUTLS_E_AGAIN
:
4818 return ((int)result
);
4820 # elif defined(HAVE_CDSASSL)
4821 int result
; /* Return value */
4822 OSStatus error
; /* Error info */
4823 size_t processed
; /* Number of bytes processed */
4826 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4827 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4832 result
= (int)processed
;
4835 case errSSLWouldBlock
:
4837 result
= (int)processed
;
4845 case errSSLClosedGraceful
:
4848 result
= (int)processed
;
4859 # elif defined(HAVE_SSPISSL)
4860 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4861 # endif /* HAVE_LIBSSL */
4863 #endif /* HAVE_SSL */
4867 * 'http_send()' - Send a request with all fields and the trailing blank line.
4870 static int /* O - 0 on success, non-zero on error */
4871 http_send(http_t
*http
, /* I - HTTP connection */
4872 http_state_t request
, /* I - Request code */
4873 const char *uri
) /* I - URI */
4875 int i
; /* Looping var */
4876 char buf
[1024]; /* Encoded URI buffer */
4877 const char *value
; /* Field value */
4878 static const char * const codes
[] = /* Request code strings */
4898 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4899 http
, codes
[request
], uri
));
4901 if (http
== NULL
|| uri
== NULL
)
4905 * Set the User-Agent field if it isn't already...
4908 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4910 if (http
->default_user_agent
)
4911 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4913 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4917 * Set the Accept-Encoding field if it isn't already...
4920 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4921 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4922 http
->default_accept_encoding
);
4925 * Encode the URI as needed...
4928 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4931 * See if we had an error the last time around; if so, reconnect...
4934 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4935 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4937 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4938 http
->fd
, http
->status
, http
->tls_upgrade
));
4940 if (httpReconnect2(http
, 30000, NULL
))
4945 * Flush any written data that is pending...
4950 if (httpFlushWrite(http
) < 0)
4951 if (httpReconnect2(http
, 30000, NULL
))
4956 * Send the request header...
4959 http
->state
= request
;
4960 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4962 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4965 http
->status
= HTTP_STATUS_CONTINUE
;
4968 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4970 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4971 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4973 #endif /* HAVE_SSL */
4975 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4977 http
->status
= HTTP_STATUS_ERROR
;
4981 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4982 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4984 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
4986 if (i
== HTTP_FIELD_HOST
)
4988 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4989 httpAddrPort(http
->hostaddr
)) < 1)
4991 http
->status
= HTTP_STATUS_ERROR
;
4995 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4997 http
->status
= HTTP_STATUS_ERROR
;
5003 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
5005 http
->status
= HTTP_STATUS_ERROR
;
5009 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
5010 http
->mode
, http
->state
));
5012 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
5013 (http
->state
== HTTP_STATE_POST_RECV
||
5014 http
->state
== HTTP_STATE_PUT_RECV
))
5015 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
5017 http
->status
= HTTP_STATUS_ERROR
;
5021 if (httpPrintf(http
, "\r\n") < 1)
5023 http
->status
= HTTP_STATUS_ERROR
;
5027 if (httpFlushWrite(http
) < 0)
5030 http_set_length(http
);
5031 httpClearFields(http
);
5034 * The Kerberos and AuthRef authentication strings can only be used once...
5037 if (http
->field_authorization
&& http
->authstring
&&
5038 (!strncmp(http
->authstring
, "Negotiate", 9) ||
5039 !strncmp(http
->authstring
, "AuthRef", 7)))
5041 http
->_authstring
[0] = '\0';
5043 if (http
->authstring
!= http
->_authstring
)
5044 free(http
->authstring
);
5046 http
->authstring
= http
->_authstring
;
5054 # if defined(HAVE_CDSASSL)
5056 * 'http_set_credentials()' - Set the SSL/TLS credentials.
5059 static int /* O - Status of connection */
5060 http_set_credentials(http_t
*http
) /* I - HTTP connection */
5062 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
5063 OSStatus error
= 0; /* Error code */
5064 http_tls_credentials_t credentials
= NULL
;
5065 /* TLS credentials */
5068 DEBUG_printf(("7http_set_credentials(%p)", http
));
5071 * Prefer connection specific credentials...
5074 if ((credentials
= http
->tls_credentials
) == NULL
)
5075 credentials
= cg
->tls_credentials
;
5079 error
= SSLSetCertificate(http
->tls
, credentials
);
5080 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
5084 DEBUG_puts("4http_set_credentials: No credentials to set.");
5088 # endif /* HAVE_CDSASSL */
5089 #endif /* HAVE_SSL */
5093 * 'http_set_length()' - Set the data_encoding and data_remaining values.
5096 static off_t
/* O - Remainder or -1 on error */
5097 http_set_length(http_t
*http
) /* I - Connection */
5099 off_t remaining
; /* Remainder */
5102 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
5103 httpStateString(http
->state
)));
5105 if ((remaining
= httpGetLength2(http
)) >= 0)
5107 if (http
->mode
== _HTTP_MODE_SERVER
&&
5108 http
->state
!= HTTP_STATE_GET_SEND
&&
5109 http
->state
!= HTTP_STATE_PUT
&&
5110 http
->state
!= HTTP_STATE_POST
&&
5111 http
->state
!= HTTP_STATE_POST_SEND
)
5113 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
5117 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
5120 DEBUG_puts("1http_set_length: Setting data_encoding to "
5121 "HTTP_ENCODING_CHUNKED.");
5122 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
5126 DEBUG_puts("1http_set_length: Setting data_encoding to "
5127 "HTTP_ENCODING_LENGTH.");
5128 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
5131 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
5132 CUPS_LLCAST remaining
));
5133 http
->data_remaining
= remaining
;
5135 if (remaining
<= INT_MAX
)
5136 http
->_data_remaining
= remaining
;
5138 http
->_data_remaining
= INT_MAX
;
5145 * 'http_set_timeout()' - Set the socket timeout values.
5149 http_set_timeout(int fd
, /* I - File descriptor */
5150 double timeout
) /* I - Timeout in seconds */
5153 DWORD tv
= (DWORD
)(timeout
* 1000);
5154 /* Timeout in milliseconds */
5156 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5157 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5160 struct timeval tv
; /* Timeout in secs and usecs */
5162 tv
.tv_sec
= (int)timeout
;
5163 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
5165 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5166 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5172 * 'http_set_wait()' - Set the default wait value for reads.
5176 http_set_wait(http_t
*http
) /* I - HTTP connection */
5180 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5182 if (http
->wait_value
<= 0)
5183 http
->wait_value
= 60000;
5186 http
->wait_value
= 10000;
5192 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5195 static int /* O - 0 on success, -1 on failure */
5196 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
5198 char hostname
[256], /* Hostname */
5199 *hostptr
; /* Pointer into hostname */
5202 SSL_CTX
*context
; /* Context for encryption */
5203 BIO
*bio
; /* BIO data */
5204 const char *message
= NULL
;/* Error message */
5205 # elif defined(HAVE_GNUTLS)
5206 int status
; /* Status of handshake */
5207 gnutls_certificate_client_credentials
*credentials
;
5208 /* TLS credentials */
5209 # elif defined(HAVE_CDSASSL)
5210 _cups_globals_t
*cg
= _cupsGlobals();
5211 /* Pointer to library globals */
5212 OSStatus error
; /* Error code */
5213 const char *message
= NULL
;/* Error message */
5214 cups_array_t
*credentials
; /* Credentials array */
5215 cups_array_t
*names
; /* CUPS distinguished names */
5216 CFArrayRef dn_array
; /* CF distinguished names array */
5217 CFIndex count
; /* Number of credentials */
5218 CFDataRef data
; /* Certificate data */
5219 int i
; /* Looping var */
5220 http_credential_t
*credential
; /* Credential data */
5221 # elif defined(HAVE_SSPISSL)
5222 TCHAR username
[256]; /* Username returned from GetUserName() */
5223 TCHAR commonName
[256];/* Common name for certificate */
5224 DWORD dwSize
; /* 32 bit size */
5225 # endif /* HAVE_LIBSSL */
5228 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5231 * Get the hostname to use for SSL...
5234 if (httpAddrLocalhost(http
->hostaddr
))
5236 strlcpy(hostname
, "localhost", sizeof(hostname
));
5241 * Otherwise make sure the hostname we have does not end in a trailing dot.
5244 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5245 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5251 context
= SSL_CTX_new(SSLv23_client_method());
5253 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5255 bio
= BIO_new(_httpBIOMethods());
5256 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5258 http
->tls
= SSL_new(context
);
5259 SSL_set_bio(http
->tls
, bio
, bio
);
5261 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5262 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5263 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5265 if (SSL_connect(http
->tls
) != 1)
5267 unsigned long error
; /* Error code */
5269 while ((error
= ERR_get_error()) != 0)
5271 message
= ERR_error_string(error
, NULL
);
5272 DEBUG_printf(("8http_setup_ssl: %s", message
));
5275 SSL_CTX_free(context
);
5276 SSL_free(http
->tls
);
5280 http
->error
= WSAGetLastError();
5282 http
->error
= errno
;
5284 http
->status
= HTTP_STATUS_ERROR
;
5287 message
= _("Unable to establish a secure connection to host.");
5289 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5294 # elif defined(HAVE_GNUTLS)
5295 credentials
= (gnutls_certificate_client_credentials
*)
5296 malloc(sizeof(gnutls_certificate_client_credentials
));
5297 if (credentials
== NULL
)
5299 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5301 http
->error
= errno
;
5302 http
->status
= HTTP_STATUS_ERROR
;
5303 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5308 gnutls_certificate_allocate_credentials(credentials
);
5310 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5311 gnutls_set_default_priority(http
->tls
);
5312 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5314 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5315 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5316 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5317 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5319 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5321 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5322 status
, gnutls_strerror(status
)));
5324 if (gnutls_error_is_fatal(status
))
5327 http
->status
= HTTP_STATUS_ERROR
;
5329 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
5331 gnutls_deinit(http
->tls
);
5332 gnutls_certificate_free_credentials(*credentials
);
5340 http
->tls_credentials
= credentials
;
5342 # elif defined(HAVE_CDSASSL)
5343 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, kSSLClientSide
,
5344 kSSLStreamType
)) == NULL
)
5346 DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
5347 http
->error
= errno
= ENOMEM
;
5348 http
->status
= HTTP_STATUS_ERROR
;
5349 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5354 error
= SSLSetConnection(http
->tls
, http
);
5355 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5359 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5360 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5365 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
5367 DEBUG_printf(("4http_setup_ssl: SSLSetSessionOption, error=%d",
5373 if (cg
->client_cert_cb
)
5375 error
= SSLSetSessionOption(http
->tls
,
5376 kSSLSessionOptionBreakOnCertRequested
, true);
5377 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5378 "error=%d", (int)error
));
5382 error
= http_set_credentials(http
);
5383 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5389 * Let the server know which hostname/domain we are trying to connect to
5390 * in case it wants to serve up a certificate with a matching common name.
5395 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5397 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5403 int done
= 0; /* Are we done yet? */
5405 while (!error
&& !done
)
5407 error
= SSLHandshake(http
->tls
);
5409 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5417 case errSSLWouldBlock
:
5418 error
= noErr
; /* Force a retry */
5419 usleep(1000); /* in 1 millisecond */
5422 case errSSLServerAuthCompleted
:
5424 if (cg
->server_cert_cb
)
5426 error
= httpCopyCredentials(http
, &credentials
);
5429 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5430 cg
->server_cert_data
);
5431 httpFreeCredentials(credentials
);
5434 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5435 "returned %d.", (int)error
));
5439 case errSSLClientCertRequested
:
5442 if (cg
->client_cert_cb
)
5445 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5448 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5450 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5452 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5454 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5456 credential
->datalen
= CFDataGetLength(data
);
5457 if ((credential
->data
= malloc(credential
->datalen
)))
5459 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5460 credential
->datalen
);
5461 cupsArrayAdd(names
, credential
);
5469 CFRelease(dn_array
);
5474 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5475 cg
->client_cert_data
);
5477 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5478 "returned %d.", (int)error
));
5481 httpFreeCredentials(names
);
5485 case errSSLUnknownRootCert
:
5486 message
= _("Unable to establish a secure connection to host "
5487 "(untrusted certificate).");
5490 case errSSLNoRootCert
:
5491 message
= _("Unable to establish a secure connection to host "
5492 "(self-signed certificate).");
5495 case errSSLCertExpired
:
5496 message
= _("Unable to establish a secure connection to host "
5497 "(expired certificate).");
5500 case errSSLCertNotYetValid
:
5501 message
= _("Unable to establish a secure connection to host "
5502 "(certificate not yet valid).");
5505 case errSSLHostNameMismatch
:
5506 message
= _("Unable to establish a secure connection to host "
5507 "(host name mismatch).");
5510 case errSSLXCertChainInvalid
:
5511 message
= _("Unable to establish a secure connection to host "
5512 "(certificate chain invalid).");
5515 case errSSLConnectionRefused
:
5516 message
= _("Unable to establish a secure connection to host "
5517 "(peer dropped connection before responding).");
5528 http
->error
= error
;
5529 http
->status
= HTTP_STATUS_ERROR
;
5530 errno
= ECONNREFUSED
;
5532 CFRelease(http
->tls
);
5536 * If an error string wasn't set by the callbacks use a generic one...
5540 #ifdef HAVE_CSSMERRORSTRING
5541 message
= cssmErrorString(error
);
5543 message
= _("Unable to establish a secure connection to host.");
5544 #endif /* HAVE_CSSMERRORSTRING */
5546 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5551 # elif defined(HAVE_SSPISSL)
5552 http
->tls
= _sspiAlloc();
5556 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5560 http
->tls
->sock
= http
->fd
;
5561 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5562 GetUserName(username
, &dwSize
);
5563 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5564 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5566 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5569 _sspiFree(http
->tls_credentials
);
5570 http
->tls_credentials
= NULL
;
5573 http
->status
= HTTP_STATUS_ERROR
;
5575 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
5576 _("Unable to establish a secure connection to host."), 1);
5581 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
5582 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5584 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5586 _sspiFree(http
->tls_credentials
);
5587 http
->tls_credentials
= NULL
;
5590 http
->status
= HTTP_STATUS_ERROR
;
5592 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
5593 _("Unable to establish a secure connection to host."), 1);
5597 # endif /* HAVE_CDSASSL */
5604 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5608 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
5611 SSL_CTX
*context
; /* Context for encryption */
5613 context
= SSL_get_SSL_CTX(http
->tls
);
5615 SSL_shutdown(http
->tls
);
5616 SSL_CTX_free(context
);
5617 SSL_free(http
->tls
);
5619 # elif defined(HAVE_GNUTLS)
5620 gnutls_certificate_client_credentials
*credentials
;
5621 /* TLS credentials */
5623 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5625 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5626 gnutls_deinit(http
->tls
);
5627 gnutls_certificate_free_credentials(*credentials
);
5630 # elif defined(HAVE_CDSASSL)
5631 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5634 CFRelease(http
->tls
);
5636 if (http
->tls_credentials
)
5637 CFRelease(http
->tls_credentials
);
5639 # elif defined(HAVE_SSPISSL)
5640 _sspiFree(http
->tls_credentials
);
5641 # endif /* HAVE_LIBSSL */
5644 http
->tls_credentials
= NULL
;
5646 #endif /* HAVE_SSL */
5651 * 'http_upgrade()' - Force upgrade to TLS encryption.
5654 static int /* O - Status of connection */
5655 http_upgrade(http_t
*http
) /* I - HTTP connection */
5657 int ret
; /* Return value */
5658 http_t myhttp
; /* Local copy of HTTP data */
5661 DEBUG_printf(("7http_upgrade(%p)", http
));
5664 * Flush the connection to make sure any previous "Upgrade" message
5671 * Copy the HTTP data to a local variable so we can do the OPTIONS
5672 * request without interfering with the existing request data...
5675 memcpy(&myhttp
, http
, sizeof(myhttp
));
5678 * Send an OPTIONS request to the server, requiring SSL or TLS
5679 * encryption on the link...
5682 http
->tls_upgrade
= 1;
5683 http
->field_authorization
= NULL
; /* Don't free the auth string */
5685 httpClearFields(http
);
5686 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5687 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5689 if ((ret
= httpOptions(http
, "*")) == 0)
5692 * Wait for the secure connection...
5695 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
5699 * Restore the HTTP request data...
5702 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5703 http
->data_encoding
= myhttp
.data_encoding
;
5704 http
->data_remaining
= myhttp
.data_remaining
;
5705 http
->_data_remaining
= myhttp
._data_remaining
;
5706 http
->expect
= myhttp
.expect
;
5707 http
->field_authorization
= myhttp
.field_authorization
;
5708 http
->digest_tries
= myhttp
.digest_tries
;
5709 http
->tls_upgrade
= 0;
5712 * See if we actually went secure...
5718 * Server does not support HTTP upgrade...
5721 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5724 closesocket(http
->fd
);
5736 #endif /* HAVE_SSL */
5740 * 'http_write()' - Write a buffer to a HTTP connection.
5743 static ssize_t
/* O - Number of bytes written */
5744 http_write(http_t
*http
, /* I - HTTP connection */
5745 const char *buffer
, /* I - Buffer for data */
5746 size_t length
) /* I - Number of bytes to write */
5748 ssize_t tbytes
, /* Total bytes sent */
5749 bytes
; /* Bytes sent */
5752 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
5753 buffer
, CUPS_LLCAST length
));
5759 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5761 if (http
->timeout_cb
)
5764 struct pollfd pfd
; /* Polled file descriptor */
5766 fd_set output_set
; /* Output ready for write? */
5767 struct timeval timeout
; /* Timeout value */
5768 #endif /* HAVE_POLL */
5769 int nfds
; /* Result from select()/poll() */
5775 pfd
.events
= POLLOUT
;
5777 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5778 (errno
== EINTR
|| errno
== EAGAIN
))
5784 FD_ZERO(&output_set
);
5785 FD_SET(http
->fd
, &output_set
);
5787 timeout
.tv_sec
= http
->wait_value
/ 1000;
5788 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5790 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5793 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5794 WSAGetLastError() == WSAEWOULDBLOCK
));
5796 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5798 #endif /* HAVE_POLL */
5802 http
->error
= errno
;
5805 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5808 http
->error
= WSAEWOULDBLOCK
;
5810 http
->error
= EWOULDBLOCK
;
5820 bytes
= http_write_ssl(http
, buffer
, length
);
5822 #endif /* HAVE_SSL */
5823 bytes
= send(http
->fd
, buffer
, length
, 0);
5825 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
5826 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
5831 if (WSAGetLastError() == WSAEINTR
)
5833 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5835 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5838 http
->error
= WSAGetLastError();
5840 else if (WSAGetLastError() != http
->error
&&
5841 WSAGetLastError() != WSAECONNRESET
)
5843 http
->error
= WSAGetLastError();
5850 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5852 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5854 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5857 http
->error
= errno
;
5859 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5861 http
->error
= errno
;
5866 DEBUG_printf(("3http_write: error writing data (%s).",
5867 strerror(http
->error
)));
5878 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5881 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
5888 * 'http_write_chunk()' - Write a chunked buffer.
5891 static ssize_t
/* O - Number bytes written */
5892 http_write_chunk(http_t
*http
, /* I - HTTP connection */
5893 const char *buffer
, /* I - Buffer to write */
5894 size_t length
) /* I - Length of buffer */
5896 char header
[16]; /* Chunk header */
5897 ssize_t bytes
; /* Bytes written */
5900 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
5901 http
, buffer
, CUPS_LLCAST length
));
5904 * Write the chunk header, data, and trailer.
5907 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
5908 if (http_write(http
, header
, strlen(header
)) < 0)
5910 DEBUG_puts("8http_write_chunk: http_write of length failed.");
5914 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5916 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
5920 if (http_write(http
, "\r\n", 2) < 0)
5922 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
5932 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5935 static int /* O - Bytes written */
5936 http_write_ssl(http_t
*http
, /* I - HTTP connection */
5937 const char *buf
, /* I - Buffer holding data */
5938 int len
) /* I - Length of buffer */
5940 ssize_t result
; /* Return value */
5943 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5945 # if defined(HAVE_LIBSSL)
5946 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5948 # elif defined(HAVE_GNUTLS)
5949 result
= gnutls_record_send(http
->tls
, buf
, len
);
5951 if (result
< 0 && !errno
)
5954 * Convert GNU TLS error to errno value...
5959 case GNUTLS_E_INTERRUPTED
:
5963 case GNUTLS_E_AGAIN
:
5975 # elif defined(HAVE_CDSASSL)
5976 OSStatus error
; /* Error info */
5977 size_t processed
; /* Number of bytes processed */
5980 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5985 result
= (int)processed
;
5988 case errSSLWouldBlock
:
5990 result
= (int)processed
;
5998 case errSSLClosedGraceful
:
6001 result
= (int)processed
;
6009 # elif defined(HAVE_SSPISSL)
6010 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
6011 # endif /* HAVE_LIBSSL */
6013 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
6015 return ((int)result
);
6017 #endif /* HAVE_SSL */