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 * 'httpGetPending()' - Get the number of bytes that are buffered for writing.
1282 size_t /* O - Number of bytes buffered */
1283 httpGetPending(http_t
*http
) /* I - HTTP connection */
1285 return (http
? http
->wused
: 0);
1290 * 'httpGetReady()' - Get the number of bytes that can be read without blocking.
1295 size_t /* O - Number of bytes available */
1296 httpGetReady(http_t
*http
) /* I - HTTP connection */
1300 else if (http
->used
> 0)
1301 return (http
->used
);
1305 size_t ready
; /* Ready bytes */
1308 if ((ready
= SSL_pending((SSL
*)(http
->tls
))) > 0)
1310 # elif defined(HAVE_GNUTLS)
1311 if ((ready
= gnutls_record_check_pending(http
->tls
)) > 0)
1313 # elif defined(HAVE_CDSASSL)
1314 if (!SSLGetBufferedReadSize(http
->tls
, &ready
) && ready
> 0)
1316 # endif /* HAVE_LIBSSL */
1318 #endif /* HAVE_SSL */
1325 * 'httpGetRemaining()' - Get the number of remaining bytes in the message
1326 * body or current chunk.
1328 * The @link httpIsChunked@ function can be used to determine whether the
1329 * message body is chunked or fixed-length.
1334 size_t /* O - Remaining bytes */
1335 httpGetRemaining(http_t
*http
) /* I - HTTP connection */
1337 return (http
? http
->data_remaining
: 0);
1342 * 'httpGets()' - Get a line of text from a HTTP connection.
1345 char * /* O - Line or NULL */
1346 httpGets(char *line
, /* I - Line to read into */
1347 int length
, /* I - Max length of buffer */
1348 http_t
*http
) /* I - HTTP connection */
1350 char *lineptr
, /* Pointer into line */
1351 *lineend
, /* End of line */
1352 *bufptr
, /* Pointer into input buffer */
1353 *bufend
; /* Pointer to end of buffer */
1354 int bytes
, /* Number of bytes read */
1355 eol
; /* End-of-line? */
1358 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1360 if (!http
|| !line
|| length
<= 1)
1364 * Read a line from the buffer...
1369 lineend
= line
+ length
- 1;
1372 while (lineptr
< lineend
)
1375 * Pre-load the buffer as needed...
1384 while (http
->used
== 0)
1387 * No newline; see if there is more data to be read...
1390 while (!_httpWait(http
, http
->wait_value
, 1))
1392 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1395 DEBUG_puts("3httpGets: Timed out!");
1397 http
->error
= WSAETIMEDOUT
;
1399 http
->error
= ETIMEDOUT
;
1404 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1405 HTTP_MAX_BUFFER
- http
->used
);
1407 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1412 * Nope, can't get a line this time...
1416 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1418 if (WSAGetLastError() == WSAEINTR
)
1420 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1422 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1425 http
->error
= WSAGetLastError();
1427 else if (WSAGetLastError() != http
->error
)
1429 http
->error
= WSAGetLastError();
1434 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1438 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1440 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1442 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1445 http
->error
= errno
;
1447 else if (errno
!= http
->error
)
1449 http
->error
= errno
;
1456 else if (bytes
== 0)
1458 http
->error
= EPIPE
;
1464 * Yup, update the amount used...
1467 http
->used
+= bytes
;
1471 * Now copy as much of the current line as possible...
1474 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1475 lineptr
< lineend
&& bufptr
< bufend
;)
1477 if (*bufptr
== 0x0a)
1483 else if (*bufptr
== 0x0d)
1486 *lineptr
++ = *bufptr
++;
1489 http
->used
-= (int)(bufptr
- http
->buffer
);
1491 memmove(http
->buffer
, bufptr
, http
->used
);
1499 http
->activity
= time(NULL
);
1503 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1509 DEBUG_puts("3httpGets: No new line available!");
1516 * 'httpGetState()' - Get the current state of the HTTP request.
1519 http_state_t
/* O - HTTP state */
1520 httpGetState(http_t
*http
) /* I - HTTP connection */
1522 return (http
? http
->state
: HTTP_STATE_ERROR
);
1527 * 'httpGetStatus()' - Get the status of the last HTTP request.
1529 * @since CUPS 1.2/OS X 10.5@
1532 http_status_t
/* O - HTTP status */
1533 httpGetStatus(http_t
*http
) /* I - HTTP connection */
1535 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1540 * 'httpGetSubField()' - Get a sub-field value.
1545 char * /* O - Value or NULL */
1546 httpGetSubField(http_t
*http
, /* I - HTTP connection */
1547 http_field_t field
, /* I - Field index */
1548 const char *name
, /* I - Name of sub-field */
1549 char *value
) /* O - Value string */
1551 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1556 * 'httpGetSubField2()' - Get a sub-field value.
1558 * @since CUPS 1.2/OS X 10.5@
1561 char * /* O - Value or NULL */
1562 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
1563 http_field_t field
, /* I - Field index */
1564 const char *name
, /* I - Name of sub-field */
1565 char *value
, /* O - Value string */
1566 int valuelen
) /* I - Size of value buffer */
1568 const char *fptr
; /* Pointer into field */
1569 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1570 *ptr
, /* Pointer into string buffer */
1571 *end
; /* End of value buffer */
1573 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1574 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1576 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1577 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1580 end
= value
+ valuelen
- 1;
1582 for (fptr
= http
->fields
[field
]; *fptr
;)
1585 * Skip leading whitespace...
1588 while (_cups_isspace(*fptr
))
1598 * Get the sub-field name...
1602 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1603 ptr
< (temp
+ sizeof(temp
) - 1);
1608 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1611 * Skip trailing chars up to the '='...
1614 while (_cups_isspace(*fptr
))
1624 * Skip = and leading whitespace...
1629 while (_cups_isspace(*fptr
))
1635 * Read quoted string...
1638 for (ptr
= value
, fptr
++;
1639 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1644 while (*fptr
&& *fptr
!= '\"')
1653 * Read unquoted string...
1657 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1662 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1666 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1669 * See if this is the one...
1672 if (!strcmp(name
, temp
))
1674 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1681 DEBUG_puts("3httpGetSubField2: Returning NULL");
1688 * 'httpGetVersion()' - Get the HTTP version at the other end.
1691 http_version_t
/* O - Version number */
1692 httpGetVersion(http_t
*http
) /* I - HTTP connection */
1694 return (http
? http
->version
: HTTP_VERSION_1_0
);
1699 * 'httpHead()' - Send a HEAD request to the server.
1702 int /* O - Status of call (0 = success) */
1703 httpHead(http_t
*http
, /* I - HTTP connection */
1704 const char *uri
) /* I - URI for head */
1706 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1707 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1712 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1713 * default HTTP proxy (if any).
1717 httpInitialize(void)
1719 static int initialized
= 0; /* Have we been called before? */
1721 WSADATA winsockdata
; /* WinSock data */
1724 int i
; /* Looping var */
1725 unsigned char data
[1024]; /* Seed data */
1726 #endif /* HAVE_LIBSSL */
1732 _cupsGlobalUnlock();
1737 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1739 #elif !defined(SO_NOSIGPIPE)
1741 * Ignore SIGPIPE signals...
1745 sigset(SIGPIPE
, SIG_IGN
);
1747 # elif defined(HAVE_SIGACTION)
1748 struct sigaction action
; /* POSIX sigaction data */
1751 memset(&action
, 0, sizeof(action
));
1752 action
.sa_handler
= SIG_IGN
;
1753 sigaction(SIGPIPE
, &action
, NULL
);
1756 signal(SIGPIPE
, SIG_IGN
);
1757 # endif /* !SO_NOSIGPIPE */
1762 * Initialize GNU TLS...
1765 gnutls_global_init();
1767 #elif defined(HAVE_LIBSSL)
1769 * Initialize OpenSSL...
1772 SSL_load_error_strings();
1776 * Using the current time is a dubious random seed, but on some systems
1777 * it is the best we can do (on others, this seed isn't even used...)
1780 CUPS_SRAND(time(NULL
));
1782 for (i
= 0; i
< sizeof(data
); i
++)
1783 data
[i
] = CUPS_RAND();
1785 RAND_seed(data
, sizeof(data
));
1786 #endif /* HAVE_GNUTLS */
1789 _cupsGlobalUnlock();
1794 * 'httpIsChunked()' - Report whether a message body is chunked.
1796 * This function returns non-zero if the message body is composed of
1797 * variable-length chunks.
1802 int /* O - 1 if chunked, 0 if not */
1803 httpIsChunked(http_t
*http
) /* I - HTTP connection */
1805 return (http
? http
->data_encoding
== HTTP_ENCODING_CHUNKED
: 0);
1810 * 'httpIsEncrypted()' - Report whether a connection is encrypted.
1812 * This function returns non-zero if the connection is currently encrypted.
1817 int /* O - 1 if encrypted, 0 if not */
1818 httpIsEncrypted(http_t
*http
) /* I - HTTP connection */
1820 return (http
? http
->tls
!= NULL
: 0);
1825 * 'httpOptions()' - Send an OPTIONS request to the server.
1828 int /* O - Status of call (0 = success) */
1829 httpOptions(http_t
*http
, /* I - HTTP connection */
1830 const char *uri
) /* I - URI for options */
1832 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1837 * 'httpPeek()' - Peek at data from a HTTP connection.
1839 * This function copies available data from the given HTTP connection, reading
1840 * a buffer as needed. The data is still available for reading using
1841 * @link httpRead@ or @link httpRead2@.
1843 * For non-blocking connections the usual timeouts apply.
1845 * @since CUPS 1.7/OS X 10.9@
1848 ssize_t
/* O - Number of bytes copied */
1849 httpPeek(http_t
*http
, /* I - HTTP connection */
1850 char *buffer
, /* I - Buffer for data */
1851 size_t length
) /* I - Maximum number of bytes */
1853 ssize_t bytes
; /* Bytes read */
1854 char len
[32]; /* Length string */
1857 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1858 http
, buffer
, CUPS_LLCAST length
));
1860 if (http
== NULL
|| buffer
== NULL
)
1863 http
->activity
= time(NULL
);
1869 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1870 http
->data_remaining
<= 0)
1872 DEBUG_puts("2httpPeek: Getting chunk length...");
1874 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1876 DEBUG_puts("1httpPeek: Could not get length!");
1882 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1883 if (!httpGets(len
, sizeof(len
), http
))
1885 DEBUG_puts("1httpPeek: Could not get chunk length.");
1890 http
->data_remaining
= strtoll(len
, NULL
, 16);
1892 if (http
->data_remaining
< 0)
1894 DEBUG_puts("1httpPeek: Negative chunk length!");
1899 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1900 CUPS_LLCAST http
->data_remaining
));
1902 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1905 * A zero-length chunk ends a transfer; unless we are reading POST
1911 http_content_coding_finish(http
);
1912 #endif /* HAVE_LIBZ */
1914 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1915 httpGets(len
, sizeof(len
), http
);
1917 if (http
->state
== HTTP_STATE_POST_RECV
)
1920 http
->state
= HTTP_STATE_STATUS
;
1922 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1923 httpStateString(http
->state
)));
1926 * Prevent future reads for this request...
1929 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1933 else if (length
> (size_t)http
->data_remaining
)
1934 length
= (size_t)http
->data_remaining
;
1937 if (http
->used
== 0 &&
1938 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1940 if (http
->used
== 0)
1941 #endif /* HAVE_LIBZ */
1944 * Buffer small reads for better performance...
1947 ssize_t buflen
; /* Length of read for buffer */
1949 if (!http
->blocking
)
1951 while (!httpWait(http
, http
->wait_value
))
1953 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1960 if (http
->data_remaining
> sizeof(http
->buffer
))
1961 buflen
= sizeof(http
->buffer
);
1963 buflen
= http
->data_remaining
;
1965 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1966 bytes
= http_read(http
, http
->buffer
, buflen
);
1968 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1969 CUPS_LLCAST bytes
));
1973 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1983 # ifdef HAVE_INFLATECOPY
1984 int zerr
; /* Decompressor error */
1985 z_stream stream
; /* Copy of decompressor stream */
1987 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1989 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1990 /* Number of bytes to copy */
1992 if (http
->stream
.avail_in
> 0 &&
1993 http
->stream
.next_in
> http
->dbuffer
)
1994 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1996 http
->stream
.next_in
= http
->dbuffer
;
1998 if (buflen
> http
->data_remaining
)
1999 buflen
= http
->data_remaining
;
2001 if (buflen
> http
->used
)
2002 buflen
= http
->used
;
2004 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
2005 "decompression buffer.", (int)buflen
));
2007 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
2008 http
->stream
.avail_in
+= buflen
;
2009 http
->used
-= buflen
;
2010 http
->data_remaining
-= buflen
;
2013 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
2016 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
2017 (int)http
->stream
.avail_in
));
2019 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
2021 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
2022 http
->error
= ENOMEM
;
2026 stream
.next_out
= (Bytef
*)buffer
;
2027 stream
.avail_out
= length
;
2029 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
2030 inflateEnd(&stream
);
2034 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
2036 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
2037 http
->stream
.avail_in
);
2044 bytes
= length
- http
->stream
.avail_out
;
2047 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
2048 "work with compressed streams.");
2050 # endif /* HAVE_INFLATECOPY */
2053 #endif /* HAVE_LIBZ */
2056 if (length
> (size_t)http
->used
)
2057 length
= (size_t)http
->used
;
2059 bytes
= (ssize_t
)length
;
2061 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
2064 memcpy(buffer
, http
->buffer
, length
);
2072 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2075 http
->error
= WSAGetLastError();
2077 if (errno
== EINTR
|| errno
== EAGAIN
)
2080 http
->error
= errno
;
2083 else if (bytes
== 0)
2085 http
->error
= EPIPE
;
2092 /* For OS X 10.8 and earlier */
2093 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
2094 { return (httpPeek(http
, buffer
, length
)); }
2098 * 'httpPost()' - Send a POST request to the server.
2101 int /* O - Status of call (0 = success) */
2102 httpPost(http_t
*http
, /* I - HTTP connection */
2103 const char *uri
) /* I - URI for post */
2105 return (http_send(http
, HTTP_STATE_POST
, uri
));
2110 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
2115 int /* O - Number of bytes written */
2116 httpPrintf(http_t
*http
, /* I - HTTP connection */
2117 const char *format
, /* I - printf-style format string */
2118 ...) /* I - Additional args as needed */
2120 int bytes
; /* Number of bytes to write */
2121 char buf
[16384]; /* Buffer for formatted string */
2122 va_list ap
; /* Variable argument pointer */
2125 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
2127 va_start(ap
, format
);
2128 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
2131 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
2133 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
2134 return (httpWrite2(http
, buf
, bytes
));
2139 DEBUG_puts("4httpPrintf: flushing existing data...");
2141 if (httpFlushWrite(http
) < 0)
2145 return (http_write(http
, buf
, bytes
));
2151 * 'httpPut()' - Send a PUT request to the server.
2154 int /* O - Status of call (0 = success) */
2155 httpPut(http_t
*http
, /* I - HTTP connection */
2156 const char *uri
) /* I - URI to put */
2158 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2159 return (http_send(http
, HTTP_STATE_PUT
, uri
));
2164 * 'httpRead()' - Read data from a HTTP connection.
2166 * This function is deprecated. Use the httpRead2() function which can
2167 * read more than 2GB of data.
2172 int /* O - Number of bytes read */
2173 httpRead(http_t
*http
, /* I - HTTP connection */
2174 char *buffer
, /* I - Buffer for data */
2175 int length
) /* I - Maximum number of bytes */
2177 return ((int)httpRead2(http
, buffer
, length
));
2182 * 'httpRead2()' - Read data from a HTTP connection.
2184 * @since CUPS 1.2/OS X 10.5@
2187 ssize_t
/* O - Number of bytes read */
2188 httpRead2(http_t
*http
, /* I - HTTP connection */
2189 char *buffer
, /* I - Buffer for data */
2190 size_t length
) /* I - Maximum number of bytes */
2192 ssize_t bytes
; /* Bytes read */
2196 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2197 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
2198 http
, buffer
, CUPS_LLCAST length
,
2200 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2202 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2203 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
2204 http
, buffer
, CUPS_LLCAST length
,
2205 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2206 #endif /* HAVE_LIBZ */
2208 if (http
== NULL
|| buffer
== NULL
)
2211 http
->activity
= time(NULL
);
2222 if (http
->stream
.avail_in
> 0)
2224 int zerr
; /* Decompressor error */
2226 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2227 (int)http
->stream
.avail_in
, (int)length
));
2229 http
->stream
.next_out
= (Bytef
*)buffer
;
2230 http
->stream
.avail_out
= length
;
2232 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2234 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2236 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2237 http
->stream
.avail_in
);
2244 bytes
= length
- http
->stream
.avail_out
;
2246 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2247 http
->stream
.avail_in
, http
->stream
.avail_out
,
2255 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2256 /* Additional bytes for buffer */
2260 if (http
->stream
.avail_in
> 0 &&
2261 http
->stream
.next_in
> http
->dbuffer
)
2262 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2264 http
->stream
.next_in
= http
->dbuffer
;
2266 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2267 "decompression buffer.", (int)buflen
));
2269 if (http
->data_remaining
> 0)
2271 if (buflen
> http
->data_remaining
)
2272 buflen
= http
->data_remaining
;
2274 bytes
= http_read_buffered(http
,
2275 (char *)http
->dbuffer
+
2276 http
->stream
.avail_in
, buflen
);
2278 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2279 bytes
= http_read_chunk(http
,
2280 (char *)http
->dbuffer
+
2281 http
->stream
.avail_in
, buflen
);
2287 else if (bytes
== 0)
2290 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2291 "decompression buffer.", CUPS_LLCAST bytes
));
2293 http
->data_remaining
-= bytes
;
2294 http
->stream
.avail_in
+= bytes
;
2296 if (http
->data_remaining
<= 0 &&
2297 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2300 * Read the trailing blank line now...
2303 char len
[32]; /* Length string */
2305 httpGets(len
, sizeof(len
), http
);
2317 #endif /* HAVE_LIBZ */
2318 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2320 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2322 http
->data_remaining
-= bytes
;
2324 if (http
->data_remaining
<= 0)
2327 * Read the trailing blank line now...
2330 char len
[32]; /* Length string */
2332 httpGets(len
, sizeof(len
), http
);
2336 else if (http
->data_remaining
<= 0)
2339 * No more data to read...
2346 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2349 if (length
> (size_t)http
->data_remaining
)
2350 length
= (size_t)http
->data_remaining
;
2352 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2354 http
->data_remaining
-= bytes
;
2356 if (http
->data_remaining
<= 0 &&
2357 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2360 * Read the trailing blank line now...
2363 char len
[32]; /* Length string */
2365 httpGets(len
, sizeof(len
), http
);
2372 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2373 #endif /* HAVE_LIBZ */
2374 ((http
->data_remaining
<= 0 &&
2375 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2376 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2380 http_content_coding_finish(http
);
2381 #endif /* HAVE_LIBZ */
2383 if (http
->state
== HTTP_STATE_POST_RECV
)
2385 else if (http
->state
== HTTP_STATE_GET_SEND
||
2386 http
->state
== HTTP_STATE_POST_SEND
)
2387 http
->state
= HTTP_STATE_WAITING
;
2389 http
->state
= HTTP_STATE_STATUS
;
2391 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2392 httpStateString(http
->state
)));
2399 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2401 * '_httpReadCDSA()' - Read function for the CDSA library.
2404 OSStatus
/* O - -1 on error, 0 on success */
2406 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2407 void *data
, /* I - Data buffer */
2408 size_t *dataLength
) /* IO - Number of bytes */
2410 OSStatus result
; /* Return value */
2411 ssize_t bytes
; /* Number of bytes read */
2412 http_t
*http
; /* HTTP connection */
2415 http
= (http_t
*)connection
;
2417 if (!http
->blocking
)
2420 * Make sure we have data before we read...
2423 while (!_httpWait(http
, http
->wait_value
, 0))
2425 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2428 http
->error
= ETIMEDOUT
;
2435 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2437 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2439 if (bytes
== *dataLength
)
2445 *dataLength
= bytes
;
2446 result
= errSSLWouldBlock
;
2453 result
= errSSLClosedGraceful
;
2454 else if (errno
== EAGAIN
)
2455 result
= errSSLWouldBlock
;
2457 result
= errSSLClosedAbort
;
2462 #endif /* HAVE_SSL && HAVE_CDSASSL */
2465 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2467 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2470 ssize_t
/* O - Number of bytes read or -1 on error */
2472 gnutls_transport_ptr ptr
, /* I - HTTP connection */
2473 void *data
, /* I - Buffer */
2474 size_t length
) /* I - Number of bytes to read */
2476 http_t
*http
; /* HTTP connection */
2477 ssize_t bytes
; /* Bytes read */
2480 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2482 http
= (http_t
*)ptr
;
2484 if (!http
->blocking
)
2487 * Make sure we have data before we read...
2490 while (!_httpWait(http
, http
->wait_value
, 0))
2492 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2495 http
->error
= ETIMEDOUT
;
2500 bytes
= recv(http
->fd
, data
, length
, 0);
2501 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2504 #endif /* HAVE_SSL && HAVE_GNUTLS */
2508 * 'httpReadRequest()' - Read a HTTP request from a connection.
2510 * @since CUPS 1.7/OS X 10.9@
2513 http_state_t
/* O - New state of connection */
2514 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2515 char *uri
, /* I - URI buffer */
2516 size_t urilen
) /* I - Size of URI buffer */
2518 char line
[4096], /* HTTP request line */
2519 *req_method
, /* HTTP request method */
2520 *req_uri
, /* HTTP request URI */
2521 *req_version
; /* HTTP request version number string */
2525 * Range check input...
2528 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2529 http
, uri
, CUPS_LLCAST urilen
));
2534 if (!http
|| !uri
|| urilen
< 1)
2536 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2537 return (HTTP_STATE_ERROR
);
2539 else if (http
->state
!= HTTP_STATE_WAITING
)
2541 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2542 httpStateString(http
->state
)));
2543 return (HTTP_STATE_ERROR
);
2550 httpClearFields(http
);
2552 http
->activity
= time(NULL
);
2553 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2554 http
->data_remaining
= 0;
2555 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2556 http
->status
= HTTP_STATUS_OK
;
2557 http
->version
= HTTP_VERSION_1_1
;
2560 * Read a line from the socket...
2563 if (!httpGets(line
, sizeof(line
), http
))
2565 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2566 return (HTTP_STATE_ERROR
);
2571 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2572 return (HTTP_STATE_WAITING
);
2575 DEBUG_printf(("1httpReadRequest: %s", line
));
2584 while (*req_uri
&& !isspace(*req_uri
& 255))
2589 DEBUG_puts("1httpReadRequest: No request URI.");
2590 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request URI."), 1);
2591 return (HTTP_STATE_ERROR
);
2596 while (*req_uri
&& isspace(*req_uri
& 255))
2599 req_version
= req_uri
;
2601 while (*req_version
&& !isspace(*req_version
& 255))
2606 DEBUG_puts("1httpReadRequest: No request protocol version.");
2607 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request protocol version."), 1);
2608 return (HTTP_STATE_ERROR
);
2611 *req_version
++ = '\0';
2613 while (*req_version
&& isspace(*req_version
& 255))
2620 if (!strcmp(req_method
, "OPTIONS"))
2621 http
->state
= HTTP_STATE_OPTIONS
;
2622 else if (!strcmp(req_method
, "GET"))
2623 http
->state
= HTTP_STATE_GET
;
2624 else if (!strcmp(req_method
, "HEAD"))
2625 http
->state
= HTTP_STATE_HEAD
;
2626 else if (!strcmp(req_method
, "POST"))
2627 http
->state
= HTTP_STATE_POST
;
2628 else if (!strcmp(req_method
, "PUT"))
2629 http
->state
= HTTP_STATE_PUT
;
2630 else if (!strcmp(req_method
, "DELETE"))
2631 http
->state
= HTTP_STATE_DELETE
;
2632 else if (!strcmp(req_method
, "TRACE"))
2633 http
->state
= HTTP_STATE_TRACE
;
2634 else if (!strcmp(req_method
, "CONNECT"))
2635 http
->state
= HTTP_STATE_CONNECT
;
2638 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2639 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request method."), 1);
2640 return (HTTP_STATE_UNKNOWN_METHOD
);
2643 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2644 httpStateString(http
->state
)));
2646 if (!strcmp(req_version
, "HTTP/1.0"))
2648 http
->version
= HTTP_VERSION_1_0
;
2649 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2651 else if (!strcmp(req_version
, "HTTP/1.1"))
2653 http
->version
= HTTP_VERSION_1_1
;
2654 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2658 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2659 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request version."), 1);
2660 return (HTTP_STATE_UNKNOWN_VERSION
);
2663 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2664 strlcpy(uri
, req_uri
, urilen
);
2666 return (http
->state
);
2671 * 'httpReconnect()' - Reconnect to a HTTP server.
2673 * This function is deprecated. Please use the @link httpReconnect2@ function
2679 int /* O - 0 on success, non-zero on failure */
2680 httpReconnect(http_t
*http
) /* I - HTTP connection */
2682 DEBUG_printf(("httpReconnect(http=%p)", http
));
2684 return (httpReconnect2(http
, 30000, NULL
));
2689 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2693 int /* O - 0 on success, non-zero on failure */
2694 httpReconnect2(http_t
*http
, /* I - HTTP connection */
2695 int msec
, /* I - Timeout in milliseconds */
2696 int *cancel
) /* I - Pointer to "cancel" variable */
2698 http_addrlist_t
*addr
; /* Connected address */
2700 http_addrlist_t
*current
; /* Current address */
2701 char temp
[256]; /* Temporary address string */
2705 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2710 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2717 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2718 http_shutdown_ssl(http
);
2720 #endif /* HAVE_SSL */
2723 * Close any previously open socket...
2728 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2731 closesocket(http
->fd
);
2740 * Reset all state (except fields, which may be reused)...
2743 http
->state
= HTTP_STATE_WAITING
;
2744 http
->version
= HTTP_VERSION_1_1
;
2745 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2746 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2747 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2748 http
->_data_remaining
= 0;
2750 http
->data_remaining
= 0;
2751 http
->hostaddr
= NULL
;
2755 * Connect to the server...
2759 for (current
= http
->addrlist
; current
; current
= current
->next
)
2760 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2761 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2762 httpAddrPort(&(current
->addr
))));
2765 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2769 * Unable to connect...
2773 http
->error
= WSAGetLastError();
2775 http
->error
= errno
;
2777 http
->status
= HTTP_STATUS_ERROR
;
2779 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2780 strerror(http
->error
)));
2785 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2787 if (http
->timeout_value
> 0)
2788 http_set_timeout(http
->fd
, http
->timeout_value
);
2790 http
->hostaddr
= &(addr
->addr
);
2794 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2797 * Always do encryption via SSL.
2800 if (http_setup_ssl(http
) != 0)
2803 closesocket(http
->fd
);
2811 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2812 return (http_upgrade(http
));
2813 #endif /* HAVE_SSL */
2815 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2816 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2817 httpAddrPort(http
->hostaddr
)));
2824 * 'httpSetAuthString()' - Set the current authorization string.
2826 * This function just stores a copy of the current authorization string in
2827 * the HTTP connection object. You must still call httpSetField() to set
2828 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2829 * httpHead(), httpOptions(), httpPost, or httpPut().
2831 * @since CUPS 1.3/OS X 10.5@
2835 httpSetAuthString(http_t
*http
, /* I - HTTP connection */
2836 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2837 const char *data
) /* I - Auth data (NULL for none) */
2840 * Range check input...
2846 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2847 free(http
->authstring
);
2849 http
->authstring
= http
->_authstring
;
2854 * Set the current authorization string...
2857 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2860 if (len
> (int)sizeof(http
->_authstring
))
2862 if ((temp
= malloc(len
)) == NULL
)
2863 len
= sizeof(http
->_authstring
);
2865 http
->authstring
= temp
;
2869 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2871 strlcpy(http
->authstring
, scheme
, len
);
2876 * Clear the current authorization string...
2879 http
->_authstring
[0] = '\0';
2885 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2888 * @since CUPS 1.5/OS X 10.7@
2891 int /* O - Status of call (0 = success) */
2892 httpSetCredentials(http_t
*http
, /* I - HTTP connection */
2893 cups_array_t
*credentials
) /* I - Array of credentials */
2895 if (!http
|| cupsArrayCount(credentials
) < 1)
2898 _httpFreeCredentials(http
->tls_credentials
);
2900 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2902 return (http
->tls_credentials
? 0 : -1);
2907 * 'httpSetCookie()' - Set the cookie value(s).
2909 * @since CUPS 1.1.19/OS X 10.3@
2913 httpSetCookie(http_t
*http
, /* I - Connection */
2914 const char *cookie
) /* I - Cookie string */
2923 http
->cookie
= strdup(cookie
);
2925 http
->cookie
= NULL
;
2930 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2932 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2933 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2935 * @since CUPS 1.7/OS X 10.9@
2939 httpSetDefaultField(http_t
*http
, /* I - HTTP connection */
2940 http_field_t field
, /* I - Field index */
2941 const char *value
)/* I - Value */
2943 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2944 http
, field
, http_fields
[field
], value
));
2951 case HTTP_FIELD_ACCEPT_ENCODING
:
2952 if (http
->default_accept_encoding
)
2953 _cupsStrFree(http
->default_accept_encoding
);
2955 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2958 case HTTP_FIELD_SERVER
:
2959 if (http
->default_server
)
2960 _cupsStrFree(http
->default_server
);
2962 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2965 case HTTP_FIELD_USER_AGENT
:
2966 if (http
->default_user_agent
)
2967 _cupsStrFree(http
->default_user_agent
);
2969 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2973 DEBUG_puts("1httpSetDefaultField: Ignored.");
2980 * 'httpSetExpect()' - Set the Expect: header in a request.
2982 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2985 * @since CUPS 1.2/OS X 10.5@
2989 httpSetExpect(http_t
*http
, /* I - HTTP connection */
2990 http_status_t expect
) /* I - HTTP status to expect
2991 (@code HTTP_STATUS_CONTINUE@) */
2993 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2996 http
->expect
= expect
;
3001 * 'httpSetField()' - Set the value of an HTTP header.
3005 httpSetField(http_t
*http
, /* I - HTTP connection */
3006 http_field_t field
, /* I - Field index */
3007 const char *value
) /* I - Value */
3009 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
3010 field
, http_fields
[field
], value
));
3013 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
3014 field
>= HTTP_FIELD_MAX
||
3020 case HTTP_FIELD_ACCEPT_ENCODING
:
3021 if (http
->accept_encoding
)
3022 _cupsStrFree(http
->accept_encoding
);
3024 http
->accept_encoding
= _cupsStrAlloc(value
);
3027 case HTTP_FIELD_ALLOW
:
3029 _cupsStrFree(http
->allow
);
3031 http
->allow
= _cupsStrAlloc(value
);
3034 case HTTP_FIELD_SERVER
:
3036 _cupsStrFree(http
->server
);
3038 http
->server
= _cupsStrAlloc(value
);
3042 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
3046 if (field
== HTTP_FIELD_AUTHORIZATION
)
3049 * Special case for Authorization: as its contents can be
3050 * longer than HTTP_MAX_VALUE
3053 if (http
->field_authorization
)
3054 free(http
->field_authorization
);
3056 http
->field_authorization
= strdup(value
);
3058 else if (field
== HTTP_FIELD_HOST
)
3061 * Special-case for Host: as we don't want a trailing "." on the hostname and
3062 * need to bracket IPv6 numeric addresses.
3065 char *ptr
= strchr(value
, ':');
3067 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
3070 * Bracket IPv6 numeric addresses...
3072 * This is slightly inefficient (basically copying twice), but is an edge
3073 * case and not worth optimizing...
3076 snprintf(http
->fields
[HTTP_FIELD_HOST
],
3077 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
3082 * Check for a trailing dot on the hostname...
3085 ptr
= http
->fields
[HTTP_FIELD_HOST
];
3089 ptr
+= strlen(ptr
) - 1;
3097 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
3098 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
3100 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
3101 http_content_coding_start(http
, value
);
3103 #endif /* HAVE_LIBZ */
3108 * 'httpSetKeepAlive()' - Set the current Keep-Alive state of a connection.
3115 http_t
*http
, /* I - HTTP connection */
3116 http_keepalive_t keep_alive
) /* I - New Keep-Alive value */
3119 http
->keep_alive
= keep_alive
;
3124 * 'httpSetLength()' - Set the content-length and content-encoding.
3126 * @since CUPS 1.2/OS X 10.5@
3130 httpSetLength(http_t
*http
, /* I - HTTP connection */
3131 size_t length
) /* I - Length (0 for chunked) */
3133 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
3134 CUPS_LLCAST length
));
3141 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
3143 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
3147 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
3148 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
3149 CUPS_LLFMT
, CUPS_LLCAST length
);
3155 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
3157 * The optional timeout callback receives both the HTTP connection and a user
3158 * data pointer and must return 1 to continue or 0 to error (time) out.
3160 * @since CUPS 1.5/OS X 10.7@
3165 http_t
*http
, /* I - HTTP connection */
3166 double timeout
, /* I - Number of seconds for timeout,
3167 must be greater than 0 */
3168 http_timeout_cb_t cb
, /* I - Callback function or NULL */
3169 void *user_data
) /* I - User data pointer */
3171 if (!http
|| timeout
<= 0.0)
3174 http
->timeout_cb
= cb
;
3175 http
->timeout_data
= user_data
;
3176 http
->timeout_value
= timeout
;
3179 http_set_timeout(http
->fd
, timeout
);
3181 http_set_wait(http
);
3186 * 'httpShutdown()' - Shutdown one side of an HTTP connection.
3192 httpShutdown(http_t
*http
) /* I - HTTP connection */
3194 if (!http
|| http
->fd
< 0)
3198 http_shutdown_ssl(http
);
3200 shutdown(http
->fd
, SHUT_RD
);
3205 * 'httpTrace()' - Send an TRACE request to the server.
3208 int /* O - Status of call (0 = success) */
3209 httpTrace(http_t
*http
, /* I - HTTP connection */
3210 const char *uri
) /* I - URI for trace */
3212 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
3217 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3219 * Note: Unlike httpUpdate(), this function does not flush pending write data
3220 * and only retrieves a single status line from the HTTP connection.
3223 int /* O - 1 to continue, 0 to stop */
3224 _httpUpdate(http_t
*http
, /* I - HTTP connection */
3225 http_status_t
*status
) /* O - Current HTTP status */
3227 char line
[32768], /* Line from connection... */
3228 *value
; /* Pointer to value on line */
3229 http_field_t field
; /* Field index */
3230 int major
, minor
; /* HTTP version numbers */
3233 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3234 httpStateString(http
->state
)));
3237 * Grab a single line from the connection...
3240 if (!httpGets(line
, sizeof(line
), http
))
3242 *status
= HTTP_STATUS_ERROR
;
3246 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3248 if (line
[0] == '\0')
3251 * Blank line means the start of the data section (if any). Return
3252 * the result code, too...
3254 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3255 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3259 if (http
->status
== HTTP_STATUS_CONTINUE
)
3261 *status
= http
->status
;
3265 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
3266 http
->digest_tries
= 0;
3269 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
3271 if (http_setup_ssl(http
) != 0)
3274 closesocket(http
->fd
);
3279 *status
= http
->status
= HTTP_STATUS_ERROR
;
3283 *status
= HTTP_STATUS_CONTINUE
;
3286 #endif /* HAVE_SSL */
3288 if (http_set_length(http
) < 0)
3290 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3291 http
->error
= EINVAL
;
3292 http
->status
= *status
= HTTP_STATUS_ERROR
;
3296 switch (http
->state
)
3298 case HTTP_STATE_GET
:
3299 case HTTP_STATE_POST
:
3300 case HTTP_STATE_POST_RECV
:
3301 case HTTP_STATE_PUT
:
3304 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3305 httpStateString(http
->state
)));
3307 case HTTP_STATE_POST_SEND
:
3308 case HTTP_STATE_HEAD
:
3312 http
->state
= HTTP_STATE_WAITING
;
3314 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
3319 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3320 http_content_coding_start(http
,
3321 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3322 #endif /* HAVE_LIBZ */
3324 *status
= http
->status
;
3327 else if (!strncmp(line
, "HTTP/", 5))
3330 * Got the beginning of a response...
3333 int intstatus
; /* Status value as an integer */
3335 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3337 *status
= http
->status
= HTTP_STATUS_ERROR
;
3341 httpClearFields(http
);
3343 http
->version
= (http_version_t
)(major
* 100 + minor
);
3344 *status
= http
->status
= (http_status_t
)intstatus
;
3346 else if ((value
= strchr(line
, ':')) != NULL
)
3353 while (_cups_isspace(*value
))
3356 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3359 * Be tolerants of servers that send unknown attribute fields...
3362 if (!_cups_strcasecmp(line
, "expect"))
3365 * "Expect: 100-continue" or similar...
3368 http
->expect
= (http_status_t
)atoi(value
);
3370 else if (!_cups_strcasecmp(line
, "cookie"))
3373 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3376 httpSetCookie(http
, value
);
3378 else if ((field
= httpFieldValue(line
)) != HTTP_FIELD_UNKNOWN
)
3379 httpSetField(http
, field
, value
);
3382 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3387 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3388 http
->error
= EINVAL
;
3389 http
->status
= *status
= HTTP_STATUS_ERROR
;
3398 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3401 http_status_t
/* O - HTTP status */
3402 httpUpdate(http_t
*http
) /* I - HTTP connection */
3404 http_status_t status
; /* Request status */
3407 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3408 httpStateString(http
->state
)));
3411 * Flush pending data, if any...
3416 DEBUG_puts("2httpUpdate: flushing buffer...");
3418 if (httpFlushWrite(http
) < 0)
3419 return (HTTP_STATUS_ERROR
);
3423 * If we haven't issued any commands, then there is nothing to "update"...
3426 if (http
->state
== HTTP_STATE_WAITING
)
3427 return (HTTP_STATUS_CONTINUE
);
3430 * Grab all of the lines we can from the connection...
3433 while (_httpUpdate(http
, &status
));
3436 * See if there was an error...
3439 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3441 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3442 return (http
->status
);
3447 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3448 strerror(http
->error
)));
3449 http
->status
= HTTP_STATUS_ERROR
;
3450 return (HTTP_STATUS_ERROR
);
3454 * Return the current status...
3462 * '_httpWait()' - Wait for data available on a connection (no flush).
3465 int /* O - 1 if data is available, 0 otherwise */
3466 _httpWait(http_t
*http
, /* I - HTTP connection */
3467 int msec
, /* I - Milliseconds to wait */
3468 int usessl
) /* I - Use SSL context? */
3471 struct pollfd pfd
; /* Polled file descriptor */
3473 fd_set input_set
; /* select() input set */
3474 struct timeval timeout
; /* Timeout */
3475 #endif /* HAVE_POLL */
3476 int nfds
; /* Result from select()/poll() */
3479 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3483 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3488 * Check the SSL/TLS buffers for data first...
3492 if (http
->tls
&& usessl
)
3495 if (SSL_pending(http
->tls
))
3497 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3501 # elif defined(HAVE_GNUTLS)
3502 if (gnutls_record_check_pending(http
->tls
))
3504 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3508 # elif defined(HAVE_CDSASSL)
3509 size_t bytes
; /* Bytes that are available */
3511 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3514 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3517 # endif /* HAVE_LIBSSL */
3519 #endif /* HAVE_SSL */
3522 * Then try doing a select() or poll() to poll the socket...
3527 pfd
.events
= POLLIN
;
3531 nfds
= poll(&pfd
, 1, msec
);
3533 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3538 FD_ZERO(&input_set
);
3539 FD_SET(http
->fd
, &input_set
);
3541 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3545 timeout
.tv_sec
= msec
/ 1000;
3546 timeout
.tv_usec
= (msec
% 1000) * 1000;
3548 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3551 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3553 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3556 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3557 WSAGetLastError() == WSAEWOULDBLOCK
));
3559 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3561 #endif /* HAVE_POLL */
3563 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3571 * 'httpWait()' - Wait for data available on a connection.
3573 * @since CUPS 1.1.19/OS X 10.3@
3576 int /* O - 1 if data is available, 0 otherwise */
3577 httpWait(http_t
*http
, /* I - HTTP connection */
3578 int msec
) /* I - Milliseconds to wait */
3581 * First see if there is data in the buffer...
3584 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3591 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3596 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3598 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3601 #endif /* HAVE_LIBZ */
3604 * Flush pending data, if any...
3609 DEBUG_puts("3httpWait: Flushing write buffer.");
3611 if (httpFlushWrite(http
) < 0)
3616 * If not, check the SSL/TLS buffers and do a select() on the connection...
3619 return (_httpWait(http
, msec
, 1));
3624 * 'httpWrite()' - Write data to a HTTP connection.
3626 * This function is deprecated. Use the httpWrite2() function which can
3627 * write more than 2GB of data.
3632 int /* O - Number of bytes written */
3633 httpWrite(http_t
*http
, /* I - HTTP connection */
3634 const char *buffer
, /* I - Buffer for data */
3635 int length
) /* I - Number of bytes to write */
3637 return ((int)httpWrite2(http
, buffer
, length
));
3642 * 'httpWrite2()' - Write data to a HTTP connection.
3644 * @since CUPS 1.2/OS X 10.5@
3647 ssize_t
/* O - Number of bytes written */
3648 httpWrite2(http_t
*http
, /* I - HTTP connection */
3649 const char *buffer
, /* I - Buffer for data */
3650 size_t length
) /* I - Number of bytes to write */
3652 ssize_t bytes
; /* Bytes written */
3655 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3656 buffer
, CUPS_LLCAST length
));
3659 * Range check input...
3662 if (!http
|| !buffer
)
3664 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3669 * Mark activity on the connection...
3672 http
->activity
= time(NULL
);
3675 * Buffer small writes for better performance...
3681 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3685 http_content_coding_finish(http
);
3690 http
->stream
.next_in
= (Bytef
*)buffer
;
3691 http
->stream
.avail_in
= length
;
3692 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3693 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3695 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3697 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3699 if (http
->stream
.avail_out
== 0)
3701 if (httpFlushWrite(http
) < 0)
3703 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3707 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3708 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3712 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3717 #endif /* HAVE_LIBZ */
3720 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3722 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3723 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3725 httpFlushWrite(http
);
3728 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3729 length
< sizeof(http
->wbuffer
))
3732 * Write to buffer...
3735 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3736 CUPS_LLCAST length
));
3738 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3739 http
->wused
+= (int)length
;
3740 bytes
= (ssize_t
)length
;
3745 * Otherwise write the data directly...
3748 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3749 CUPS_LLCAST length
));
3751 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3752 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3754 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3756 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3757 CUPS_LLCAST bytes
));
3760 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3761 http
->data_remaining
-= bytes
;
3767 * Handle end-of-request processing...
3770 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3771 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3774 * Finished with the transfer; unless we are sending POST or PUT
3780 http_content_coding_finish(http
);
3781 #endif /* HAVE_LIBZ */
3785 if (httpFlushWrite(http
) < 0)
3789 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3792 * Send a 0-length chunk at the end of the request...
3795 http_write(http
, "0\r\n\r\n", 5);
3798 * Reset the data state...
3801 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3802 http
->data_remaining
= 0;
3805 if (http
->state
== HTTP_STATE_POST_RECV
)
3807 else if (http
->state
== HTTP_STATE_POST_SEND
)
3808 http
->state
= HTTP_STATE_WAITING
;
3810 http
->state
= HTTP_STATE_STATUS
;
3812 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3813 httpStateString(http
->state
)));
3816 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3822 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3824 * '_httpWriteCDSA()' - Write function for the CDSA library.
3827 OSStatus
/* O - -1 on error, 0 on success */
3829 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3830 const void *data
, /* I - Data buffer */
3831 size_t *dataLength
) /* IO - Number of bytes */
3833 OSStatus result
; /* Return value */
3834 ssize_t bytes
; /* Number of bytes read */
3835 http_t
*http
; /* HTTP connection */
3838 http
= (http_t
*)connection
;
3842 bytes
= write(http
->fd
, data
, *dataLength
);
3844 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3846 if (bytes
== *dataLength
)
3850 else if (bytes
>= 0)
3852 *dataLength
= bytes
;
3853 result
= errSSLWouldBlock
;
3859 if (errno
== EAGAIN
)
3860 result
= errSSLWouldBlock
;
3862 result
= errSSLClosedAbort
;
3867 #endif /* HAVE_SSL && HAVE_CDSASSL */
3870 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3872 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3875 ssize_t
/* O - Number of bytes written or -1 on error */
3877 gnutls_transport_ptr ptr
, /* I - HTTP connection */
3878 const void *data
, /* I - Data buffer */
3879 size_t length
) /* I - Number of bytes to write */
3881 ssize_t bytes
; /* Bytes written */
3884 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3887 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3890 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3891 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3895 #endif /* HAVE_SSL && HAVE_GNUTLS */
3899 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3901 * @since CUPS 1.7/OS X 10.9@
3904 int /* O - 0 on success, -1 on error */
3905 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3906 http_status_t status
) /* I - Status code */
3908 http_encoding_t old_encoding
; /* Old data_encoding value */
3909 off_t old_remaining
; /* Old data_remaining value */
3913 * Range check input...
3916 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3918 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3920 DEBUG_puts("1httpWriteResponse: Bad input.");
3925 * Set the various standard fields if they aren't already...
3928 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3929 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3931 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3933 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
3934 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3937 if (http
->version
== HTTP_VERSION_1_1
)
3939 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3941 if (http
->keep_alive
)
3942 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3944 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3947 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3948 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3952 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
||
3953 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
3955 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3956 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3958 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3959 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3961 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
3962 httpSetField(http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
3964 #endif /* HAVE_SSL */
3967 httpSetField(http
, HTTP_FIELD_SERVER
,
3968 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3971 * Set the Accept-Encoding field if it isn't already...
3974 if (!http
->accept_encoding
)
3975 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3976 http
->default_accept_encoding
? http
->default_accept_encoding
:
3978 "gzip, deflate, identity");
3981 #endif /* HAVE_LIBZ */
3984 * Send the response header...
3987 old_encoding
= http
->data_encoding
;
3988 old_remaining
= http
->data_remaining
;
3989 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3991 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3992 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3994 http
->status
= HTTP_STATUS_ERROR
;
3998 if (status
!= HTTP_STATUS_CONTINUE
)
4001 * 100 Continue doesn't have the rest of the response headers...
4004 int i
; /* Looping var */
4005 const char *value
; /* Field value */
4007 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4009 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4011 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4013 http
->status
= HTTP_STATUS_ERROR
;
4021 if (httpPrintf(http
, "Set-Cookie: %s path=/ httponly%s\r\n",
4022 http
->cookie
, http
->tls
? " secure" : "") < 1)
4024 http
->status
= HTTP_STATUS_ERROR
;
4030 if (httpWrite2(http
, "\r\n", 2) < 2)
4032 http
->status
= HTTP_STATUS_ERROR
;
4036 if (httpFlushWrite(http
) < 0)
4038 http
->status
= HTTP_STATUS_ERROR
;
4042 if (status
== HTTP_STATUS_CONTINUE
||
4043 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
4046 * Restore the old data_encoding and data_length values...
4049 http
->data_encoding
= old_encoding
;
4050 http
->data_remaining
= old_remaining
;
4052 if (old_remaining
<= INT_MAX
)
4053 http
->_data_remaining
= (int)old_remaining
;
4055 http
->_data_remaining
= INT_MAX
;
4057 else if (http
->state
== HTTP_STATE_OPTIONS
||
4058 http
->state
== HTTP_STATE_HEAD
||
4059 http
->state
== HTTP_STATE_PUT
||
4060 http
->state
== HTTP_STATE_TRACE
||
4061 http
->state
== HTTP_STATE_CONNECT
||
4062 http
->state
== HTTP_STATE_STATUS
)
4064 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
4065 "was %s.", httpStateString(http
->state
)));
4066 http
->state
= HTTP_STATE_WAITING
;
4071 * Force data_encoding and data_length to be set according to the response
4075 http_set_length(http
);
4079 * Then start any content encoding...
4082 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
4083 http_content_coding_start(http
,
4084 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
4085 #endif /* HAVE_LIBZ */
4092 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
4094 * 'http_bio_ctrl()' - Control the HTTP connection.
4097 static long /* O - Result/data */
4098 http_bio_ctrl(BIO
*h
, /* I - BIO data */
4099 int cmd
, /* I - Control command */
4100 long arg1
, /* I - First argument */
4101 void *arg2
) /* I - Second argument */
4108 case BIO_CTRL_RESET
:
4112 case BIO_C_SET_FILE_PTR
:
4117 case BIO_C_GET_FILE_PTR
:
4120 *((void **)arg2
) = h
->ptr
;
4127 case BIO_CTRL_FLUSH
:
4134 * 'http_bio_free()' - Free OpenSSL data.
4137 static int /* O - 1 on success, 0 on failure */
4138 http_bio_free(BIO
*h
) /* I - BIO data */
4154 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
4157 static int /* O - 1 on success, 0 on failure */
4158 http_bio_new(BIO
*h
) /* I - BIO data */
4173 * 'http_bio_puts()' - Send a string for OpenSSL.
4176 static int /* O - Bytes written */
4177 http_bio_puts(BIO
*h
, /* I - BIO data */
4178 const char *str
) /* I - String to write */
4181 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
4183 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
4189 * 'http_bio_read()' - Read data for OpenSSL.
4192 static int /* O - Bytes read */
4193 http_bio_read(BIO
*h
, /* I - BIO data */
4194 char *buf
, /* I - Buffer */
4195 int size
) /* I - Number of bytes to read */
4197 http_t
*http
; /* HTTP connection */
4200 http
= (http_t
*)h
->ptr
;
4202 if (!http
->blocking
)
4205 * Make sure we have data before we read...
4208 while (!_httpWait(http
, http
->wait_value
, 0))
4210 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4214 http
->error
= WSAETIMEDOUT
;
4216 http
->error
= ETIMEDOUT
;
4223 return (recv(http
->fd
, buf
, size
, 0));
4228 * 'http_bio_write()' - Write data for OpenSSL.
4231 static int /* O - Bytes written */
4232 http_bio_write(BIO
*h
, /* I - BIO data */
4233 const char *buf
, /* I - Buffer to write */
4234 int num
) /* I - Number of bytes to write */
4236 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4238 #endif /* HAVE_SSL && HAVE_LIBSSL */
4243 * 'http_content_coding_finish()' - Finish doing any content encoding.
4247 http_content_coding_finish(
4248 http_t
*http
) /* I - HTTP connection */
4250 int zerr
; /* Compression status */
4253 switch (http
->coding
)
4255 case _HTTP_CODING_DEFLATE
:
4256 case _HTTP_CODING_GZIP
:
4259 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4260 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4262 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4264 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4265 if (http
->wused
== sizeof(http
->wbuffer
))
4266 httpFlushWrite(http
);
4268 while (zerr
== Z_OK
);
4270 deflateEnd(&(http
->stream
));
4273 httpFlushWrite(http
);
4276 case _HTTP_CODING_INFLATE
:
4277 case _HTTP_CODING_GUNZIP
:
4278 inflateEnd(&(http
->stream
));
4279 free(http
->dbuffer
);
4280 http
->dbuffer
= NULL
;
4287 http
->coding
= _HTTP_CODING_IDENTITY
;
4292 * 'http_content_coding_start()' - Start doing content encoding.
4296 http_content_coding_start(
4297 http_t
*http
, /* I - HTTP connection */
4298 const char *value
) /* I - Value of Content-Encoding */
4300 int zerr
; /* Error/status */
4301 _http_coding_t coding
; /* Content coding value */
4304 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4307 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4309 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4313 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4315 if (http
->state
== HTTP_STATE_GET_SEND
||
4316 http
->state
== HTTP_STATE_POST_SEND
)
4317 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4318 _HTTP_CODING_GUNZIP
;
4319 else if (http
->state
== HTTP_STATE_POST_RECV
||
4320 http
->state
== HTTP_STATE_PUT_RECV
)
4321 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4322 _HTTP_CODING_GUNZIP
;
4325 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4329 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4331 if (http
->state
== HTTP_STATE_GET_SEND
||
4332 http
->state
== HTTP_STATE_POST_SEND
)
4333 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4334 _HTTP_CODING_INFLATE
;
4335 else if (http
->state
== HTTP_STATE_POST_RECV
||
4336 http
->state
== HTTP_STATE_PUT_RECV
)
4337 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4338 _HTTP_CODING_INFLATE
;
4341 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4347 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4351 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4355 case _HTTP_CODING_DEFLATE
:
4356 case _HTTP_CODING_GZIP
:
4358 httpFlushWrite(http
);
4361 * Window size for compression is 11 bits - optimal based on PWG Raster
4362 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
4366 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4368 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
4369 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4371 http
->status
= HTTP_STATUS_ERROR
;
4372 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4377 case _HTTP_CODING_INFLATE
:
4378 case _HTTP_CODING_GUNZIP
:
4379 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
4381 http
->status
= HTTP_STATUS_ERROR
;
4382 http
->error
= errno
;
4387 * Window size for decompression is up to 15 bits (maximum supported).
4388 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
4391 if ((zerr
= inflateInit2(&(http
->stream
),
4392 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
4395 free(http
->dbuffer
);
4396 http
->dbuffer
= NULL
;
4397 http
->status
= HTTP_STATUS_ERROR
;
4398 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4402 http
->stream
.avail_in
= 0;
4403 http
->stream
.next_in
= http
->dbuffer
;
4410 http
->coding
= coding
;
4412 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4415 #endif /* HAVE_LIBZ */
4419 * 'http_create()' - Create an unconnected HTTP connection.
4422 static http_t
* /* O - HTTP connection */
4424 const char *host
, /* I - Hostname */
4425 int port
, /* I - Port number */
4426 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
4427 int family
, /* I - Address family or AF_UNSPEC */
4428 http_encryption_t encryption
, /* I - Encryption to use */
4429 int blocking
, /* I - 1 for blocking mode */
4430 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
4432 http_t
*http
; /* New HTTP connection */
4433 char service
[255]; /* Service name */
4434 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
4437 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
4438 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
4439 family
, encryption
, blocking
, mode
));
4441 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
4447 * Lookup the host...
4452 myaddrlist
= httpAddrCopyList(addrlist
);
4456 snprintf(service
, sizeof(service
), "%d", port
);
4458 myaddrlist
= httpAddrGetList(host
, family
, service
);
4465 * Allocate memory for the structure...
4468 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
4470 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
4471 httpAddrFreeList(addrlist
);
4476 * Initialize the HTTP data...
4480 http
->activity
= time(NULL
);
4481 http
->addrlist
= myaddrlist
;
4482 http
->blocking
= blocking
;
4485 http
->gssctx
= GSS_C_NO_CONTEXT
;
4486 http
->gssname
= GSS_C_NO_NAME
;
4487 #endif /* HAVE_GSSAPI */
4488 http
->status
= HTTP_STATUS_CONTINUE
;
4489 http
->version
= HTTP_VERSION_1_1
;
4492 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
4494 if (port
== 443) /* Always use encryption for https */
4495 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
4497 http
->encryption
= encryption
;
4499 http_set_wait(http
);
4502 * Return the new structure...
4508 /* For OS X 10.8 and earlier */
4509 http_t
*_httpCreate(const char *host
, int port
, http_addrlist_t
*addrlist
,
4510 http_encryption_t encryption
, int family
)
4511 { return (http_create(host
, port
, addrlist
, family
, encryption
, 1,
4512 _HTTP_MODE_CLIENT
)); }
4517 * 'http_debug_hex()' - Do a hex dump of a buffer.
4521 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4522 const char *buffer
, /* I - Buffer to dump */
4523 int bytes
) /* I - Bytes to dump */
4525 int i
, j
, /* Looping vars */
4526 ch
; /* Current character */
4527 char line
[255], /* Line buffer */
4528 *start
, /* Start of line after prefix */
4529 *ptr
; /* Pointer into line */
4532 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4535 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4537 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4538 start
= line
+ strlen(line
);
4540 for (i
= 0; i
< bytes
; i
+= 16)
4542 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4543 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4547 memcpy(ptr
, " ", 3);
4552 memcpy(ptr
, " ", 3);
4555 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4557 ch
= buffer
[i
+ j
] & 255;
4559 if (ch
< ' ' || ch
>= 127)
4573 * 'http_read()' - Read a buffer from a HTTP connection.
4575 * This function does the low-level read from the socket, retrying and timing
4579 static ssize_t
/* O - Number of bytes read or -1 on error */
4580 http_read(http_t
*http
, /* I - HTTP connection */
4581 char *buffer
, /* I - Buffer */
4582 size_t length
) /* I - Maximum bytes to read */
4584 ssize_t bytes
; /* Bytes read */
4587 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4588 buffer
, CUPS_LLCAST length
));
4590 if (!http
->blocking
)
4592 while (!httpWait(http
, http
->wait_value
))
4594 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4597 DEBUG_puts("2http_read: Timeout.");
4602 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4608 bytes
= http_read_ssl(http
, buffer
, length
);
4610 #endif /* HAVE_SSL */
4611 bytes
= recv(http
->fd
, buffer
, length
, 0);
4616 if (WSAGetLastError() != WSAEINTR
)
4618 http
->error
= WSAGetLastError();
4621 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4623 if (!http
->timeout_cb
||
4624 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4626 http
->error
= WSAEWOULDBLOCK
;
4631 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4633 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4635 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4637 http
->error
= errno
;
4640 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4642 http
->error
= errno
;
4646 else if (errno
!= EINTR
)
4648 http
->error
= errno
;
4656 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4657 CUPS_LLCAST bytes
));
4660 http_debug_hex("http_read", buffer
, (int)bytes
);
4666 if (WSAGetLastError() == WSAEINTR
)
4669 http
->error
= WSAGetLastError();
4671 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4674 http
->error
= errno
;
4677 else if (bytes
== 0)
4679 http
->error
= EPIPE
;
4688 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4690 * This function reads data from the HTTP buffer or from the socket, as needed.
4693 static ssize_t
/* O - Number of bytes read or -1 on error */
4694 http_read_buffered(http_t
*http
, /* I - HTTP connection */
4695 char *buffer
, /* I - Buffer */
4696 size_t length
) /* I - Maximum bytes to read */
4698 ssize_t bytes
; /* Bytes read */
4701 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4703 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4707 if (length
> (size_t)http
->used
)
4708 bytes
= (size_t)http
->used
;
4712 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4715 memcpy(buffer
, http
->buffer
, bytes
);
4716 http
->used
-= (int)bytes
;
4719 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4722 bytes
= http_read(http
, buffer
, length
);
4729 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4731 * This function reads and validates the chunk length, then does a buffered read
4732 * returning the number of bytes placed in the buffer.
4735 static ssize_t
/* O - Number of bytes read or -1 on error */
4736 http_read_chunk(http_t
*http
, /* I - HTTP connection */
4737 char *buffer
, /* I - Buffer */
4738 size_t length
) /* I - Maximum bytes to read */
4740 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4741 http
, buffer
, CUPS_LLCAST length
));
4743 if (http
->data_remaining
<= 0)
4745 char len
[32]; /* Length string */
4747 if (!httpGets(len
, sizeof(len
), http
))
4749 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4755 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4756 if (!httpGets(len
, sizeof(len
), http
))
4758 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4763 http
->data_remaining
= strtoll(len
, NULL
, 16);
4765 if (http
->data_remaining
< 0)
4767 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4768 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4772 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4773 len
, CUPS_LLCAST http
->data_remaining
));
4775 if (http
->data_remaining
== 0)
4778 * 0-length chunk, grab trailing blank line...
4781 httpGets(len
, sizeof(len
), http
);
4785 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4786 CUPS_LLCAST http
->data_remaining
));
4788 if (http
->data_remaining
<= 0)
4790 else if (length
> (size_t)http
->data_remaining
)
4791 length
= (size_t)http
->data_remaining
;
4793 return (http_read_buffered(http
, buffer
, length
));
4799 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4802 static int /* O - Bytes read */
4803 http_read_ssl(http_t
*http
, /* I - HTTP connection */
4804 char *buf
, /* I - Buffer to store data */
4805 int len
) /* I - Length of buffer */
4807 # if defined(HAVE_LIBSSL)
4808 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4810 # elif defined(HAVE_GNUTLS)
4811 ssize_t result
; /* Return value */
4814 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4816 if (result
< 0 && !errno
)
4819 * Convert GNU TLS error to errno value...
4824 case GNUTLS_E_INTERRUPTED
:
4828 case GNUTLS_E_AGAIN
:
4840 return ((int)result
);
4842 # elif defined(HAVE_CDSASSL)
4843 int result
; /* Return value */
4844 OSStatus error
; /* Error info */
4845 size_t processed
; /* Number of bytes processed */
4848 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4849 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4854 result
= (int)processed
;
4857 case errSSLWouldBlock
:
4859 result
= (int)processed
;
4867 case errSSLClosedGraceful
:
4870 result
= (int)processed
;
4881 # elif defined(HAVE_SSPISSL)
4882 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4883 # endif /* HAVE_LIBSSL */
4885 #endif /* HAVE_SSL */
4889 * 'http_send()' - Send a request with all fields and the trailing blank line.
4892 static int /* O - 0 on success, non-zero on error */
4893 http_send(http_t
*http
, /* I - HTTP connection */
4894 http_state_t request
, /* I - Request code */
4895 const char *uri
) /* I - URI */
4897 int i
; /* Looping var */
4898 char buf
[1024]; /* Encoded URI buffer */
4899 const char *value
; /* Field value */
4900 static const char * const codes
[] = /* Request code strings */
4920 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4921 http
, codes
[request
], uri
));
4923 if (http
== NULL
|| uri
== NULL
)
4927 * Set the User-Agent field if it isn't already...
4930 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4932 if (http
->default_user_agent
)
4933 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4935 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4939 * Set the Accept-Encoding field if it isn't already...
4942 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4943 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4944 http
->default_accept_encoding
);
4947 * Encode the URI as needed...
4950 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4953 * See if we had an error the last time around; if so, reconnect...
4956 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4957 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4959 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4960 http
->fd
, http
->status
, http
->tls_upgrade
));
4962 if (httpReconnect2(http
, 30000, NULL
))
4967 * Flush any written data that is pending...
4972 if (httpFlushWrite(http
) < 0)
4973 if (httpReconnect2(http
, 30000, NULL
))
4978 * Send the request header...
4981 http
->state
= request
;
4982 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4984 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4987 http
->status
= HTTP_STATUS_CONTINUE
;
4990 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4992 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4993 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4995 #endif /* HAVE_SSL */
4997 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4999 http
->status
= HTTP_STATUS_ERROR
;
5003 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
5004 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
5006 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
5008 if (i
== HTTP_FIELD_HOST
)
5010 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
5011 httpAddrPort(http
->hostaddr
)) < 1)
5013 http
->status
= HTTP_STATUS_ERROR
;
5017 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
5019 http
->status
= HTTP_STATUS_ERROR
;
5025 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
5027 http
->status
= HTTP_STATUS_ERROR
;
5031 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
5032 http
->mode
, http
->state
));
5034 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
5035 (http
->state
== HTTP_STATE_POST_RECV
||
5036 http
->state
== HTTP_STATE_PUT_RECV
))
5037 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
5039 http
->status
= HTTP_STATUS_ERROR
;
5043 if (httpPrintf(http
, "\r\n") < 1)
5045 http
->status
= HTTP_STATUS_ERROR
;
5049 if (httpFlushWrite(http
) < 0)
5052 http_set_length(http
);
5053 httpClearFields(http
);
5056 * The Kerberos and AuthRef authentication strings can only be used once...
5059 if (http
->field_authorization
&& http
->authstring
&&
5060 (!strncmp(http
->authstring
, "Negotiate", 9) ||
5061 !strncmp(http
->authstring
, "AuthRef", 7)))
5063 http
->_authstring
[0] = '\0';
5065 if (http
->authstring
!= http
->_authstring
)
5066 free(http
->authstring
);
5068 http
->authstring
= http
->_authstring
;
5076 # if defined(HAVE_CDSASSL)
5078 * 'http_set_credentials()' - Set the SSL/TLS credentials.
5081 static int /* O - Status of connection */
5082 http_set_credentials(http_t
*http
) /* I - HTTP connection */
5084 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
5085 OSStatus error
= 0; /* Error code */
5086 http_tls_credentials_t credentials
= NULL
;
5087 /* TLS credentials */
5090 DEBUG_printf(("7http_set_credentials(%p)", http
));
5093 * Prefer connection specific credentials...
5096 if ((credentials
= http
->tls_credentials
) == NULL
)
5097 credentials
= cg
->tls_credentials
;
5101 error
= SSLSetCertificate(http
->tls
, credentials
);
5102 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
5106 DEBUG_puts("4http_set_credentials: No credentials to set.");
5110 # endif /* HAVE_CDSASSL */
5111 #endif /* HAVE_SSL */
5115 * 'http_set_length()' - Set the data_encoding and data_remaining values.
5118 static off_t
/* O - Remainder or -1 on error */
5119 http_set_length(http_t
*http
) /* I - Connection */
5121 off_t remaining
; /* Remainder */
5124 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
5125 httpStateString(http
->state
)));
5127 if ((remaining
= httpGetLength2(http
)) >= 0)
5129 if (http
->mode
== _HTTP_MODE_SERVER
&&
5130 http
->state
!= HTTP_STATE_GET_SEND
&&
5131 http
->state
!= HTTP_STATE_PUT
&&
5132 http
->state
!= HTTP_STATE_POST
&&
5133 http
->state
!= HTTP_STATE_POST_SEND
)
5135 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
5139 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
5142 DEBUG_puts("1http_set_length: Setting data_encoding to "
5143 "HTTP_ENCODING_CHUNKED.");
5144 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
5148 DEBUG_puts("1http_set_length: Setting data_encoding to "
5149 "HTTP_ENCODING_LENGTH.");
5150 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
5153 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
5154 CUPS_LLCAST remaining
));
5155 http
->data_remaining
= remaining
;
5157 if (remaining
<= INT_MAX
)
5158 http
->_data_remaining
= remaining
;
5160 http
->_data_remaining
= INT_MAX
;
5167 * 'http_set_timeout()' - Set the socket timeout values.
5171 http_set_timeout(int fd
, /* I - File descriptor */
5172 double timeout
) /* I - Timeout in seconds */
5175 DWORD tv
= (DWORD
)(timeout
* 1000);
5176 /* Timeout in milliseconds */
5178 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5179 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5182 struct timeval tv
; /* Timeout in secs and usecs */
5184 tv
.tv_sec
= (int)timeout
;
5185 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
5187 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5188 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5194 * 'http_set_wait()' - Set the default wait value for reads.
5198 http_set_wait(http_t
*http
) /* I - HTTP connection */
5202 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5204 if (http
->wait_value
<= 0)
5205 http
->wait_value
= 60000;
5208 http
->wait_value
= 10000;
5214 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5217 static int /* O - 0 on success, -1 on failure */
5218 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
5220 char hostname
[256], /* Hostname */
5221 *hostptr
; /* Pointer into hostname */
5224 SSL_CTX
*context
; /* Context for encryption */
5225 BIO
*bio
; /* BIO data */
5226 const char *message
= NULL
;/* Error message */
5227 # elif defined(HAVE_GNUTLS)
5228 int status
; /* Status of handshake */
5229 gnutls_certificate_client_credentials
*credentials
;
5230 /* TLS credentials */
5231 # elif defined(HAVE_CDSASSL)
5232 _cups_globals_t
*cg
= _cupsGlobals();
5233 /* Pointer to library globals */
5234 OSStatus error
; /* Error code */
5235 const char *message
= NULL
;/* Error message */
5236 cups_array_t
*credentials
; /* Credentials array */
5237 cups_array_t
*names
; /* CUPS distinguished names */
5238 CFArrayRef dn_array
; /* CF distinguished names array */
5239 CFIndex count
; /* Number of credentials */
5240 CFDataRef data
; /* Certificate data */
5241 int i
; /* Looping var */
5242 http_credential_t
*credential
; /* Credential data */
5243 # elif defined(HAVE_SSPISSL)
5244 TCHAR username
[256]; /* Username returned from GetUserName() */
5245 TCHAR commonName
[256];/* Common name for certificate */
5246 DWORD dwSize
; /* 32 bit size */
5247 # endif /* HAVE_LIBSSL */
5250 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5253 * Get the hostname to use for SSL...
5256 if (httpAddrLocalhost(http
->hostaddr
))
5258 strlcpy(hostname
, "localhost", sizeof(hostname
));
5263 * Otherwise make sure the hostname we have does not end in a trailing dot.
5266 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5267 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5273 context
= SSL_CTX_new(SSLv23_client_method());
5275 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5277 bio
= BIO_new(_httpBIOMethods());
5278 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5280 http
->tls
= SSL_new(context
);
5281 SSL_set_bio(http
->tls
, bio
, bio
);
5283 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5284 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5285 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5287 if (SSL_connect(http
->tls
) != 1)
5289 unsigned long error
; /* Error code */
5291 while ((error
= ERR_get_error()) != 0)
5293 message
= ERR_error_string(error
, NULL
);
5294 DEBUG_printf(("8http_setup_ssl: %s", message
));
5297 SSL_CTX_free(context
);
5298 SSL_free(http
->tls
);
5302 http
->error
= WSAGetLastError();
5304 http
->error
= errno
;
5306 http
->status
= HTTP_STATUS_ERROR
;
5309 message
= _("Unable to establish a secure connection to host.");
5311 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5316 # elif defined(HAVE_GNUTLS)
5317 credentials
= (gnutls_certificate_client_credentials
*)
5318 malloc(sizeof(gnutls_certificate_client_credentials
));
5319 if (credentials
== NULL
)
5321 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5323 http
->error
= errno
;
5324 http
->status
= HTTP_STATUS_ERROR
;
5325 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5330 gnutls_certificate_allocate_credentials(credentials
);
5332 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5333 gnutls_set_default_priority(http
->tls
);
5334 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5336 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5337 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5338 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5339 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5341 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5343 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5344 status
, gnutls_strerror(status
)));
5346 if (gnutls_error_is_fatal(status
))
5349 http
->status
= HTTP_STATUS_ERROR
;
5351 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
5353 gnutls_deinit(http
->tls
);
5354 gnutls_certificate_free_credentials(*credentials
);
5362 http
->tls_credentials
= credentials
;
5364 # elif defined(HAVE_CDSASSL)
5365 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, kSSLClientSide
,
5366 kSSLStreamType
)) == NULL
)
5368 DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
5369 http
->error
= errno
= ENOMEM
;
5370 http
->status
= HTTP_STATUS_ERROR
;
5371 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5376 error
= SSLSetConnection(http
->tls
, http
);
5377 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5381 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5382 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5387 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
5389 DEBUG_printf(("4http_setup_ssl: SSLSetSessionOption, error=%d",
5395 if (cg
->client_cert_cb
)
5397 error
= SSLSetSessionOption(http
->tls
,
5398 kSSLSessionOptionBreakOnCertRequested
, true);
5399 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5400 "error=%d", (int)error
));
5404 error
= http_set_credentials(http
);
5405 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5411 * Let the server know which hostname/domain we are trying to connect to
5412 * in case it wants to serve up a certificate with a matching common name.
5417 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5419 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5425 int done
= 0; /* Are we done yet? */
5427 while (!error
&& !done
)
5429 error
= SSLHandshake(http
->tls
);
5431 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5439 case errSSLWouldBlock
:
5440 error
= noErr
; /* Force a retry */
5441 usleep(1000); /* in 1 millisecond */
5444 case errSSLServerAuthCompleted
:
5446 if (cg
->server_cert_cb
)
5448 error
= httpCopyCredentials(http
, &credentials
);
5451 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5452 cg
->server_cert_data
);
5453 httpFreeCredentials(credentials
);
5456 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5457 "returned %d.", (int)error
));
5461 case errSSLClientCertRequested
:
5464 if (cg
->client_cert_cb
)
5467 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5470 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5472 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5474 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5476 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5478 credential
->datalen
= CFDataGetLength(data
);
5479 if ((credential
->data
= malloc(credential
->datalen
)))
5481 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5482 credential
->datalen
);
5483 cupsArrayAdd(names
, credential
);
5491 CFRelease(dn_array
);
5496 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5497 cg
->client_cert_data
);
5499 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5500 "returned %d.", (int)error
));
5503 httpFreeCredentials(names
);
5507 case errSSLUnknownRootCert
:
5508 message
= _("Unable to establish a secure connection to host "
5509 "(untrusted certificate).");
5512 case errSSLNoRootCert
:
5513 message
= _("Unable to establish a secure connection to host "
5514 "(self-signed certificate).");
5517 case errSSLCertExpired
:
5518 message
= _("Unable to establish a secure connection to host "
5519 "(expired certificate).");
5522 case errSSLCertNotYetValid
:
5523 message
= _("Unable to establish a secure connection to host "
5524 "(certificate not yet valid).");
5527 case errSSLHostNameMismatch
:
5528 message
= _("Unable to establish a secure connection to host "
5529 "(host name mismatch).");
5532 case errSSLXCertChainInvalid
:
5533 message
= _("Unable to establish a secure connection to host "
5534 "(certificate chain invalid).");
5537 case errSSLConnectionRefused
:
5538 message
= _("Unable to establish a secure connection to host "
5539 "(peer dropped connection before responding).");
5550 http
->error
= error
;
5551 http
->status
= HTTP_STATUS_ERROR
;
5552 errno
= ECONNREFUSED
;
5554 CFRelease(http
->tls
);
5558 * If an error string wasn't set by the callbacks use a generic one...
5562 #ifdef HAVE_CSSMERRORSTRING
5563 message
= cssmErrorString(error
);
5565 message
= _("Unable to establish a secure connection to host.");
5566 #endif /* HAVE_CSSMERRORSTRING */
5568 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5573 # elif defined(HAVE_SSPISSL)
5574 http
->tls
= _sspiAlloc();
5578 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5582 http
->tls
->sock
= http
->fd
;
5583 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5584 GetUserName(username
, &dwSize
);
5585 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5586 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5588 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5591 _sspiFree(http
->tls_credentials
);
5592 http
->tls_credentials
= NULL
;
5595 http
->status
= HTTP_STATUS_ERROR
;
5597 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
5598 _("Unable to establish a secure connection to host."), 1);
5603 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
5604 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5606 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5608 _sspiFree(http
->tls_credentials
);
5609 http
->tls_credentials
= NULL
;
5612 http
->status
= HTTP_STATUS_ERROR
;
5614 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
5615 _("Unable to establish a secure connection to host."), 1);
5619 # endif /* HAVE_CDSASSL */
5626 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5630 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
5633 SSL_CTX
*context
; /* Context for encryption */
5635 context
= SSL_get_SSL_CTX(http
->tls
);
5637 SSL_shutdown(http
->tls
);
5638 SSL_CTX_free(context
);
5639 SSL_free(http
->tls
);
5641 # elif defined(HAVE_GNUTLS)
5642 gnutls_certificate_client_credentials
*credentials
;
5643 /* TLS credentials */
5645 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5647 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5648 gnutls_deinit(http
->tls
);
5649 gnutls_certificate_free_credentials(*credentials
);
5652 # elif defined(HAVE_CDSASSL)
5653 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5656 CFRelease(http
->tls
);
5658 if (http
->tls_credentials
)
5659 CFRelease(http
->tls_credentials
);
5661 # elif defined(HAVE_SSPISSL)
5662 _sspiFree(http
->tls_credentials
);
5663 # endif /* HAVE_LIBSSL */
5666 http
->tls_credentials
= NULL
;
5668 #endif /* HAVE_SSL */
5673 * 'http_upgrade()' - Force upgrade to TLS encryption.
5676 static int /* O - Status of connection */
5677 http_upgrade(http_t
*http
) /* I - HTTP connection */
5679 int ret
; /* Return value */
5680 http_t myhttp
; /* Local copy of HTTP data */
5683 DEBUG_printf(("7http_upgrade(%p)", http
));
5686 * Flush the connection to make sure any previous "Upgrade" message
5693 * Copy the HTTP data to a local variable so we can do the OPTIONS
5694 * request without interfering with the existing request data...
5697 memcpy(&myhttp
, http
, sizeof(myhttp
));
5700 * Send an OPTIONS request to the server, requiring SSL or TLS
5701 * encryption on the link...
5704 http
->tls_upgrade
= 1;
5705 http
->field_authorization
= NULL
; /* Don't free the auth string */
5707 httpClearFields(http
);
5708 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5709 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5711 if ((ret
= httpOptions(http
, "*")) == 0)
5714 * Wait for the secure connection...
5717 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
5721 * Restore the HTTP request data...
5724 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5725 http
->data_encoding
= myhttp
.data_encoding
;
5726 http
->data_remaining
= myhttp
.data_remaining
;
5727 http
->_data_remaining
= myhttp
._data_remaining
;
5728 http
->expect
= myhttp
.expect
;
5729 http
->field_authorization
= myhttp
.field_authorization
;
5730 http
->digest_tries
= myhttp
.digest_tries
;
5731 http
->tls_upgrade
= 0;
5734 * See if we actually went secure...
5740 * Server does not support HTTP upgrade...
5743 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5746 closesocket(http
->fd
);
5758 #endif /* HAVE_SSL */
5762 * 'http_write()' - Write a buffer to a HTTP connection.
5765 static ssize_t
/* O - Number of bytes written */
5766 http_write(http_t
*http
, /* I - HTTP connection */
5767 const char *buffer
, /* I - Buffer for data */
5768 size_t length
) /* I - Number of bytes to write */
5770 ssize_t tbytes
, /* Total bytes sent */
5771 bytes
; /* Bytes sent */
5774 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
5775 buffer
, CUPS_LLCAST length
));
5781 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5783 if (http
->timeout_cb
)
5786 struct pollfd pfd
; /* Polled file descriptor */
5788 fd_set output_set
; /* Output ready for write? */
5789 struct timeval timeout
; /* Timeout value */
5790 #endif /* HAVE_POLL */
5791 int nfds
; /* Result from select()/poll() */
5797 pfd
.events
= POLLOUT
;
5799 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5800 (errno
== EINTR
|| errno
== EAGAIN
))
5806 FD_ZERO(&output_set
);
5807 FD_SET(http
->fd
, &output_set
);
5809 timeout
.tv_sec
= http
->wait_value
/ 1000;
5810 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5812 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5815 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5816 WSAGetLastError() == WSAEWOULDBLOCK
));
5818 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5820 #endif /* HAVE_POLL */
5824 http
->error
= errno
;
5827 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5830 http
->error
= WSAEWOULDBLOCK
;
5832 http
->error
= EWOULDBLOCK
;
5842 bytes
= http_write_ssl(http
, buffer
, length
);
5844 #endif /* HAVE_SSL */
5845 bytes
= send(http
->fd
, buffer
, length
, 0);
5847 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
5848 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
5853 if (WSAGetLastError() == WSAEINTR
)
5855 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5857 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5860 http
->error
= WSAGetLastError();
5862 else if (WSAGetLastError() != http
->error
&&
5863 WSAGetLastError() != WSAECONNRESET
)
5865 http
->error
= WSAGetLastError();
5872 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5874 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5876 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5879 http
->error
= errno
;
5881 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5883 http
->error
= errno
;
5888 DEBUG_printf(("3http_write: error writing data (%s).",
5889 strerror(http
->error
)));
5900 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5903 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
5910 * 'http_write_chunk()' - Write a chunked buffer.
5913 static ssize_t
/* O - Number bytes written */
5914 http_write_chunk(http_t
*http
, /* I - HTTP connection */
5915 const char *buffer
, /* I - Buffer to write */
5916 size_t length
) /* I - Length of buffer */
5918 char header
[16]; /* Chunk header */
5919 ssize_t bytes
; /* Bytes written */
5922 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
5923 http
, buffer
, CUPS_LLCAST length
));
5926 * Write the chunk header, data, and trailer.
5929 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
5930 if (http_write(http
, header
, strlen(header
)) < 0)
5932 DEBUG_puts("8http_write_chunk: http_write of length failed.");
5936 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5938 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
5942 if (http_write(http
, "\r\n", 2) < 0)
5944 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
5954 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5957 static int /* O - Bytes written */
5958 http_write_ssl(http_t
*http
, /* I - HTTP connection */
5959 const char *buf
, /* I - Buffer holding data */
5960 int len
) /* I - Length of buffer */
5962 ssize_t result
; /* Return value */
5965 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5967 # if defined(HAVE_LIBSSL)
5968 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5970 # elif defined(HAVE_GNUTLS)
5971 result
= gnutls_record_send(http
->tls
, buf
, len
);
5973 if (result
< 0 && !errno
)
5976 * Convert GNU TLS error to errno value...
5981 case GNUTLS_E_INTERRUPTED
:
5985 case GNUTLS_E_AGAIN
:
5997 # elif defined(HAVE_CDSASSL)
5998 OSStatus error
; /* Error info */
5999 size_t processed
; /* Number of bytes processed */
6002 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
6007 result
= (int)processed
;
6010 case errSSLWouldBlock
:
6012 result
= (int)processed
;
6020 case errSSLClosedGraceful
:
6023 result
= (int)processed
;
6031 # elif defined(HAVE_SSPISSL)
6032 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
6033 # endif /* HAVE_LIBSSL */
6035 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
6037 return ((int)result
);
6039 #endif /* HAVE_SSL */