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 */
681 httpAddrClose(NULL
, http
->fd
);
688 * 'httpEncryption()' - Set the required encryption on the link.
691 int /* O - -1 on error, 0 on success */
692 httpEncryption(http_t
*http
, /* I - HTTP connection */
693 http_encryption_t e
) /* I - New encryption preference */
695 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
701 http
->encryption
= e
;
703 if ((http
->encryption
== HTTP_ENCRYPTION_ALWAYS
&& !http
->tls
) ||
704 (http
->encryption
== HTTP_ENCRYPTION_NEVER
&& http
->tls
))
705 return (httpReconnect2(http
, 30000, NULL
));
706 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
707 return (http_upgrade(http
));
711 if (e
== HTTP_ENCRYPTION_ALWAYS
|| e
== HTTP_ENCRYPTION_REQUIRED
)
715 #endif /* HAVE_SSL */
720 * 'httpError()' - Get the last error on a connection.
723 int /* O - Error code (errno) value */
724 httpError(http_t
*http
) /* I - HTTP connection */
727 return (http
->error
);
734 * 'httpFieldValue()' - Return the HTTP field enumeration value for a field
738 http_field_t
/* O - Field index */
739 httpFieldValue(const char *name
) /* I - String name */
741 int i
; /* Looping var */
744 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
745 if (!_cups_strcasecmp(name
, http_fields
[i
]))
746 return ((http_field_t
)i
);
748 return (HTTP_FIELD_UNKNOWN
);
753 * 'httpFlush()' - Flush data from a HTTP connection.
757 httpFlush(http_t
*http
) /* I - HTTP connection */
759 char buffer
[8192]; /* Junk buffer */
760 int blocking
; /* To block or not to block */
761 http_state_t oldstate
; /* Old state */
764 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
765 httpStateString(http
->state
)));
768 * Nothing to do if we are in the "waiting" state...
771 if (http
->state
== HTTP_STATE_WAITING
)
775 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
778 blocking
= http
->blocking
;
782 * Read any data we can...
785 oldstate
= http
->state
;
786 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
789 * Restore blocking and reset the connection if we didn't get all of
790 * the remaining data...
793 http
->blocking
= blocking
;
795 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
799 * Didn't get the data back, so close the current connection.
804 http_content_coding_finish(http
);
805 #endif /* HAVE_LIBZ */
807 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
809 http
->state
= HTTP_STATE_WAITING
;
813 http_shutdown_ssl(http
);
814 #endif /* HAVE_SSL */
816 httpAddrClose(NULL
, http
->fd
);
824 * 'httpFlushWrite()' - Flush data in write buffer.
826 * @since CUPS 1.2/OS X 10.5@
829 int /* O - Bytes written or -1 on error */
830 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
832 int bytes
; /* Bytes written */
835 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
836 http
? http
->data_encoding
: -1));
838 if (!http
|| !http
->wused
)
840 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
841 "1httpFlushWrite: No connection.");
845 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
846 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
848 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
852 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
859 * '_httpFreeCredentials()' - Free internal credentials.
863 _httpFreeCredentials(
864 http_tls_credentials_t credentials
) /* I - Internal credentials */
872 #elif defined(HAVE_GNUTLS)
875 #elif defined(HAVE_CDSASSL)
876 CFRelease(credentials
);
878 #elif defined(HAVE_SSPISSL)
881 #endif /* HAVE_LIBSSL */
886 * 'httpFreeCredentials()' - Free an array of credentials.
891 cups_array_t
*credentials
) /* I - Array of credentials */
893 http_credential_t
*credential
; /* Credential */
896 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
898 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
900 cupsArrayRemove(credentials
, credential
);
901 free((void *)credential
->data
);
905 cupsArrayDelete(credentials
);
910 * 'httpGet()' - Send a GET request to the server.
913 int /* O - Status of call (0 = success) */
914 httpGet(http_t
*http
, /* I - HTTP connection */
915 const char *uri
) /* I - URI to get */
917 return (http_send(http
, HTTP_STATE_GET
, uri
));
922 * 'httpGetActivity()' - Get the most recent activity for a connection.
924 * The return value is the UNIX time of the last read or write.
929 time_t /* O - Time of last read or write */
930 httpGetActivity(http_t
*http
) /* I - HTTP connection */
932 return (http
? http
->activity
: 0);
937 * 'httpGetAuthString()' - Get the current authorization string.
939 * The authorization string is set by cupsDoAuthentication() and
940 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
941 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
944 * @since CUPS 1.3/OS X 10.5@
947 char * /* O - Authorization string */
948 httpGetAuthString(http_t
*http
) /* I - HTTP connection */
951 return (http
->authstring
);
958 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
960 * @since CUPS 1.2/OS X 10.5@
963 int /* O - 1 if blocking, 0 if non-blocking */
964 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
966 return (http
? http
->blocking
: 0);
971 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
972 * the client and server.
974 * This function uses the value of the Accepts-Encoding HTTP header and must be
975 * called after receiving a response from the server or a request from the
976 * client. The value returned can be use in subsequent requests (for clients)
977 * or in the response (for servers) in order to compress the content stream.
979 * @since CUPS 1.7/OS X 10.9@
982 const char * /* O - Content-Coding value or
983 @code NULL@ for the identity
985 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
988 if (http
&& http
->accept_encoding
)
990 int i
; /* Looping var */
991 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
992 *start
, /* Start of coding value */
993 *end
; /* End of coding value */
994 double qvalue
; /* "qvalue" for coding */
995 struct lconv
*loc
= localeconv(); /* Locale data */
996 static const char * const codings
[] =
997 { /* Supported content codings */
1004 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
1006 for (start
= temp
; *start
; start
= end
)
1009 * Find the end of the coding name...
1014 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
1020 * Grab the qvalue as needed...
1023 if (!strncmp(end
, ";q=", 3))
1024 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1027 * Skip past all attributes...
1031 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1037 while (*end
&& isspace(*end
& 255))
1041 * Check value if it matches something we support...
1047 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1048 if (!strcmp(start
, codings
[i
]))
1049 return (codings
[i
]);
1052 #endif /* HAVE_LIBZ */
1059 * 'httpGetCookie()' - Get any cookie data from the response.
1061 * @since CUPS 1.1.19/OS X 10.3@
1064 const char * /* O - Cookie data or NULL */
1065 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1067 return (http
? http
->cookie
: NULL
);
1072 * 'httpGetEncryption()' - Get the current encryption mode of a connection.
1074 * This function returns the encryption mode for the connection. Use the
1075 * @link httpIsEncrypted@ function to determine whether a TLS session has
1081 http_encryption_t
/* O - Current encryption mode */
1082 httpGetEncryption(http_t
*http
) /* I - HTTP connection */
1084 return (http
? http
->encryption
: HTTP_ENCRYPTION_IF_REQUESTED
);
1089 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1091 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1092 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1094 * @since CUPS 1.7/OS X 10.9@
1097 http_status_t
/* O - Expect: status, if any */
1098 httpGetExpect(http_t
*http
) /* I - Connection to client */
1101 return (HTTP_STATUS_ERROR
);
1103 return (http
->expect
);
1108 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1110 * @since CUPS 1.2/OS X 10.5@
1113 int /* O - File descriptor or -1 if none */
1114 httpGetFd(http_t
*http
) /* I - HTTP connection */
1116 return (http
? http
->fd
: -1);
1121 * 'httpGetField()' - Get a field value from a request/response.
1124 const char * /* O - Field value */
1125 httpGetField(http_t
*http
, /* I - HTTP connection */
1126 http_field_t field
) /* I - Field to get */
1128 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1133 case HTTP_FIELD_ACCEPT_ENCODING
:
1134 return (http
->accept_encoding
);
1136 case HTTP_FIELD_ALLOW
:
1137 return (http
->allow
);
1139 case HTTP_FIELD_SERVER
:
1140 return (http
->server
);
1142 case HTTP_FIELD_AUTHORIZATION
:
1143 if (http
->field_authorization
)
1146 * Special case for WWW-Authenticate: as its contents can be
1147 * longer than HTTP_MAX_VALUE...
1150 return (http
->field_authorization
);
1154 return (http
->fields
[field
]);
1160 * 'httpGetKeepAlive()' - Get the current Keep-Alive state of the connection.
1165 http_keepalive_t
/* O - Keep-Alive state */
1166 httpGetKeepAlive(http_t
*http
) /* I - HTTP connection */
1168 return (http
? http
->keep_alive
: HTTP_KEEPALIVE_OFF
);
1173 * 'httpGetLength()' - Get the amount of data remaining from the
1174 * content-length or transfer-encoding fields.
1176 * This function is deprecated and will not return lengths larger than
1177 * 2^31 - 1; use httpGetLength2() instead.
1182 int /* O - Content length */
1183 httpGetLength(http_t
*http
) /* I - HTTP connection */
1186 * Get the read content length and return the 32-bit value.
1191 httpGetLength2(http
);
1193 return (http
->_data_remaining
);
1201 * 'httpGetLength2()' - Get the amount of data remaining from the
1202 * content-length or transfer-encoding fields.
1204 * This function returns the complete content length, even for
1205 * content larger than 2^31 - 1.
1207 * @since CUPS 1.2/OS X 10.5@
1210 off_t
/* O - Content length */
1211 httpGetLength2(http_t
*http
) /* I - HTTP connection */
1213 off_t remaining
; /* Remaining length */
1216 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1217 httpStateString(http
->state
)));
1222 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1224 DEBUG_puts("4httpGetLength2: chunked request!");
1230 * The following is a hack for HTTP servers that don't send a
1231 * Content-Length or Transfer-Encoding field...
1233 * If there is no Content-Length then the connection must close
1234 * after the transfer is complete...
1237 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1240 * Default content length is 0 for errors and certain types of operations,
1241 * and 2^31-1 for other successful requests...
1244 if (http
->status
>= HTTP_STATUS_MULTIPLE_CHOICES
||
1245 http
->state
== HTTP_STATE_OPTIONS
||
1246 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1247 http
->state
== HTTP_STATE_HEAD
||
1248 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1249 http
->state
== HTTP_STATE_DELETE
||
1250 http
->state
== HTTP_STATE_TRACE
||
1251 http
->state
== HTTP_STATE_CONNECT
)
1254 remaining
= 2147483647;
1256 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1260 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1261 CUPS_LLCAST remaining
));
1269 * 'httpGetPending()' - Get the number of bytes that are buffered for writing.
1274 size_t /* O - Number of bytes buffered */
1275 httpGetPending(http_t
*http
) /* I - HTTP connection */
1277 return (http
? http
->wused
: 0);
1282 * 'httpGetReady()' - Get the number of bytes that can be read without blocking.
1287 size_t /* O - Number of bytes available */
1288 httpGetReady(http_t
*http
) /* I - HTTP connection */
1292 else if (http
->used
> 0)
1293 return (http
->used
);
1297 size_t ready
; /* Ready bytes */
1300 if ((ready
= SSL_pending((SSL
*)(http
->tls
))) > 0)
1302 # elif defined(HAVE_GNUTLS)
1303 if ((ready
= gnutls_record_check_pending(http
->tls
)) > 0)
1305 # elif defined(HAVE_CDSASSL)
1306 if (!SSLGetBufferedReadSize(http
->tls
, &ready
) && ready
> 0)
1308 # endif /* HAVE_LIBSSL */
1310 #endif /* HAVE_SSL */
1317 * 'httpGetRemaining()' - Get the number of remaining bytes in the message
1318 * body or current chunk.
1320 * The @link httpIsChunked@ function can be used to determine whether the
1321 * message body is chunked or fixed-length.
1326 size_t /* O - Remaining bytes */
1327 httpGetRemaining(http_t
*http
) /* I - HTTP connection */
1329 return (http
? http
->data_remaining
: 0);
1334 * 'httpGets()' - Get a line of text from a HTTP connection.
1337 char * /* O - Line or NULL */
1338 httpGets(char *line
, /* I - Line to read into */
1339 int length
, /* I - Max length of buffer */
1340 http_t
*http
) /* I - HTTP connection */
1342 char *lineptr
, /* Pointer into line */
1343 *lineend
, /* End of line */
1344 *bufptr
, /* Pointer into input buffer */
1345 *bufend
; /* Pointer to end of buffer */
1346 int bytes
, /* Number of bytes read */
1347 eol
; /* End-of-line? */
1350 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1352 if (!http
|| !line
|| length
<= 1)
1356 * Read a line from the buffer...
1361 lineend
= line
+ length
- 1;
1364 while (lineptr
< lineend
)
1367 * Pre-load the buffer as needed...
1376 while (http
->used
== 0)
1379 * No newline; see if there is more data to be read...
1382 while (!_httpWait(http
, http
->wait_value
, 1))
1384 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1387 DEBUG_puts("3httpGets: Timed out!");
1389 http
->error
= WSAETIMEDOUT
;
1391 http
->error
= ETIMEDOUT
;
1396 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1397 HTTP_MAX_BUFFER
- http
->used
);
1399 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1404 * Nope, can't get a line this time...
1408 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1410 if (WSAGetLastError() == WSAEINTR
)
1412 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1414 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1417 http
->error
= WSAGetLastError();
1419 else if (WSAGetLastError() != http
->error
)
1421 http
->error
= WSAGetLastError();
1426 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1430 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1432 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1434 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1437 http
->error
= errno
;
1439 else if (errno
!= http
->error
)
1441 http
->error
= errno
;
1448 else if (bytes
== 0)
1450 http
->error
= EPIPE
;
1456 * Yup, update the amount used...
1459 http
->used
+= bytes
;
1463 * Now copy as much of the current line as possible...
1466 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1467 lineptr
< lineend
&& bufptr
< bufend
;)
1469 if (*bufptr
== 0x0a)
1475 else if (*bufptr
== 0x0d)
1478 *lineptr
++ = *bufptr
++;
1481 http
->used
-= (int)(bufptr
- http
->buffer
);
1483 memmove(http
->buffer
, bufptr
, http
->used
);
1491 http
->activity
= time(NULL
);
1495 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1501 DEBUG_puts("3httpGets: No new line available!");
1508 * 'httpGetState()' - Get the current state of the HTTP request.
1511 http_state_t
/* O - HTTP state */
1512 httpGetState(http_t
*http
) /* I - HTTP connection */
1514 return (http
? http
->state
: HTTP_STATE_ERROR
);
1519 * 'httpGetStatus()' - Get the status of the last HTTP request.
1521 * @since CUPS 1.2/OS X 10.5@
1524 http_status_t
/* O - HTTP status */
1525 httpGetStatus(http_t
*http
) /* I - HTTP connection */
1527 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1532 * 'httpGetSubField()' - Get a sub-field value.
1537 char * /* O - Value or NULL */
1538 httpGetSubField(http_t
*http
, /* I - HTTP connection */
1539 http_field_t field
, /* I - Field index */
1540 const char *name
, /* I - Name of sub-field */
1541 char *value
) /* O - Value string */
1543 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1548 * 'httpGetSubField2()' - Get a sub-field value.
1550 * @since CUPS 1.2/OS X 10.5@
1553 char * /* O - Value or NULL */
1554 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
1555 http_field_t field
, /* I - Field index */
1556 const char *name
, /* I - Name of sub-field */
1557 char *value
, /* O - Value string */
1558 int valuelen
) /* I - Size of value buffer */
1560 const char *fptr
; /* Pointer into field */
1561 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1562 *ptr
, /* Pointer into string buffer */
1563 *end
; /* End of value buffer */
1565 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1566 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1568 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1569 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1572 end
= value
+ valuelen
- 1;
1574 for (fptr
= http
->fields
[field
]; *fptr
;)
1577 * Skip leading whitespace...
1580 while (_cups_isspace(*fptr
))
1590 * Get the sub-field name...
1594 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1595 ptr
< (temp
+ sizeof(temp
) - 1);
1600 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1603 * Skip trailing chars up to the '='...
1606 while (_cups_isspace(*fptr
))
1616 * Skip = and leading whitespace...
1621 while (_cups_isspace(*fptr
))
1627 * Read quoted string...
1630 for (ptr
= value
, fptr
++;
1631 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1636 while (*fptr
&& *fptr
!= '\"')
1645 * Read unquoted string...
1649 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1654 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1658 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1661 * See if this is the one...
1664 if (!strcmp(name
, temp
))
1666 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1673 DEBUG_puts("3httpGetSubField2: Returning NULL");
1680 * 'httpGetVersion()' - Get the HTTP version at the other end.
1683 http_version_t
/* O - Version number */
1684 httpGetVersion(http_t
*http
) /* I - HTTP connection */
1686 return (http
? http
->version
: HTTP_VERSION_1_0
);
1691 * 'httpHead()' - Send a HEAD request to the server.
1694 int /* O - Status of call (0 = success) */
1695 httpHead(http_t
*http
, /* I - HTTP connection */
1696 const char *uri
) /* I - URI for head */
1698 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1699 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1704 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1705 * default HTTP proxy (if any).
1709 httpInitialize(void)
1711 static int initialized
= 0; /* Have we been called before? */
1713 WSADATA winsockdata
; /* WinSock data */
1716 int i
; /* Looping var */
1717 unsigned char data
[1024]; /* Seed data */
1718 #endif /* HAVE_LIBSSL */
1724 _cupsGlobalUnlock();
1729 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1731 #elif !defined(SO_NOSIGPIPE)
1733 * Ignore SIGPIPE signals...
1737 sigset(SIGPIPE
, SIG_IGN
);
1739 # elif defined(HAVE_SIGACTION)
1740 struct sigaction action
; /* POSIX sigaction data */
1743 memset(&action
, 0, sizeof(action
));
1744 action
.sa_handler
= SIG_IGN
;
1745 sigaction(SIGPIPE
, &action
, NULL
);
1748 signal(SIGPIPE
, SIG_IGN
);
1749 # endif /* !SO_NOSIGPIPE */
1754 * Initialize GNU TLS...
1757 gnutls_global_init();
1759 #elif defined(HAVE_LIBSSL)
1761 * Initialize OpenSSL...
1764 SSL_load_error_strings();
1768 * Using the current time is a dubious random seed, but on some systems
1769 * it is the best we can do (on others, this seed isn't even used...)
1772 CUPS_SRAND(time(NULL
));
1774 for (i
= 0; i
< sizeof(data
); i
++)
1775 data
[i
] = CUPS_RAND();
1777 RAND_seed(data
, sizeof(data
));
1778 #endif /* HAVE_GNUTLS */
1781 _cupsGlobalUnlock();
1786 * 'httpIsChunked()' - Report whether a message body is chunked.
1788 * This function returns non-zero if the message body is composed of
1789 * variable-length chunks.
1794 int /* O - 1 if chunked, 0 if not */
1795 httpIsChunked(http_t
*http
) /* I - HTTP connection */
1797 return (http
? http
->data_encoding
== HTTP_ENCODING_CHUNKED
: 0);
1802 * 'httpIsEncrypted()' - Report whether a connection is encrypted.
1804 * This function returns non-zero if the connection is currently encrypted.
1809 int /* O - 1 if encrypted, 0 if not */
1810 httpIsEncrypted(http_t
*http
) /* I - HTTP connection */
1812 return (http
? http
->tls
!= NULL
: 0);
1817 * 'httpOptions()' - Send an OPTIONS request to the server.
1820 int /* O - Status of call (0 = success) */
1821 httpOptions(http_t
*http
, /* I - HTTP connection */
1822 const char *uri
) /* I - URI for options */
1824 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1829 * 'httpPeek()' - Peek at data from a HTTP connection.
1831 * This function copies available data from the given HTTP connection, reading
1832 * a buffer as needed. The data is still available for reading using
1833 * @link httpRead@ or @link httpRead2@.
1835 * For non-blocking connections the usual timeouts apply.
1837 * @since CUPS 1.7/OS X 10.9@
1840 ssize_t
/* O - Number of bytes copied */
1841 httpPeek(http_t
*http
, /* I - HTTP connection */
1842 char *buffer
, /* I - Buffer for data */
1843 size_t length
) /* I - Maximum number of bytes */
1845 ssize_t bytes
; /* Bytes read */
1846 char len
[32]; /* Length string */
1849 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1850 http
, buffer
, CUPS_LLCAST length
));
1852 if (http
== NULL
|| buffer
== NULL
)
1855 http
->activity
= time(NULL
);
1861 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1862 http
->data_remaining
<= 0)
1864 DEBUG_puts("2httpPeek: Getting chunk length...");
1866 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1868 DEBUG_puts("1httpPeek: Could not get length!");
1874 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1875 if (!httpGets(len
, sizeof(len
), http
))
1877 DEBUG_puts("1httpPeek: Could not get chunk length.");
1882 http
->data_remaining
= strtoll(len
, NULL
, 16);
1884 if (http
->data_remaining
< 0)
1886 DEBUG_puts("1httpPeek: Negative chunk length!");
1891 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1892 CUPS_LLCAST http
->data_remaining
));
1894 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1897 * A zero-length chunk ends a transfer; unless we are reading POST
1903 http_content_coding_finish(http
);
1904 #endif /* HAVE_LIBZ */
1906 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1907 httpGets(len
, sizeof(len
), http
);
1909 if (http
->state
== HTTP_STATE_POST_RECV
)
1912 http
->state
= HTTP_STATE_STATUS
;
1914 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1915 httpStateString(http
->state
)));
1918 * Prevent future reads for this request...
1921 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1925 else if (length
> (size_t)http
->data_remaining
)
1926 length
= (size_t)http
->data_remaining
;
1929 if (http
->used
== 0 &&
1930 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1932 if (http
->used
== 0)
1933 #endif /* HAVE_LIBZ */
1936 * Buffer small reads for better performance...
1939 ssize_t buflen
; /* Length of read for buffer */
1941 if (!http
->blocking
)
1943 while (!httpWait(http
, http
->wait_value
))
1945 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1952 if (http
->data_remaining
> sizeof(http
->buffer
))
1953 buflen
= sizeof(http
->buffer
);
1955 buflen
= http
->data_remaining
;
1957 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1958 bytes
= http_read(http
, http
->buffer
, buflen
);
1960 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1961 CUPS_LLCAST bytes
));
1965 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1975 # ifdef HAVE_INFLATECOPY
1976 int zerr
; /* Decompressor error */
1977 z_stream stream
; /* Copy of decompressor stream */
1979 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1981 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1982 /* Number of bytes to copy */
1984 if (http
->stream
.avail_in
> 0 &&
1985 http
->stream
.next_in
> http
->dbuffer
)
1986 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1988 http
->stream
.next_in
= http
->dbuffer
;
1990 if (buflen
> http
->data_remaining
)
1991 buflen
= http
->data_remaining
;
1993 if (buflen
> http
->used
)
1994 buflen
= http
->used
;
1996 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1997 "decompression buffer.", (int)buflen
));
1999 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
2000 http
->stream
.avail_in
+= buflen
;
2001 http
->used
-= buflen
;
2002 http
->data_remaining
-= buflen
;
2005 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
2008 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
2009 (int)http
->stream
.avail_in
));
2011 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
2013 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
2014 http
->error
= ENOMEM
;
2018 stream
.next_out
= (Bytef
*)buffer
;
2019 stream
.avail_out
= length
;
2021 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
2022 inflateEnd(&stream
);
2026 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
2028 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
2029 http
->stream
.avail_in
);
2036 bytes
= length
- http
->stream
.avail_out
;
2039 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
2040 "work with compressed streams.");
2042 # endif /* HAVE_INFLATECOPY */
2045 #endif /* HAVE_LIBZ */
2048 if (length
> (size_t)http
->used
)
2049 length
= (size_t)http
->used
;
2051 bytes
= (ssize_t
)length
;
2053 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
2056 memcpy(buffer
, http
->buffer
, length
);
2064 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
2067 http
->error
= WSAGetLastError();
2069 if (errno
== EINTR
|| errno
== EAGAIN
)
2072 http
->error
= errno
;
2075 else if (bytes
== 0)
2077 http
->error
= EPIPE
;
2084 /* For OS X 10.8 and earlier */
2085 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
2086 { return (httpPeek(http
, buffer
, length
)); }
2090 * 'httpPost()' - Send a POST request to the server.
2093 int /* O - Status of call (0 = success) */
2094 httpPost(http_t
*http
, /* I - HTTP connection */
2095 const char *uri
) /* I - URI for post */
2097 return (http_send(http
, HTTP_STATE_POST
, uri
));
2102 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
2107 int /* O - Number of bytes written */
2108 httpPrintf(http_t
*http
, /* I - HTTP connection */
2109 const char *format
, /* I - printf-style format string */
2110 ...) /* I - Additional args as needed */
2112 int bytes
; /* Number of bytes to write */
2113 char buf
[16384]; /* Buffer for formatted string */
2114 va_list ap
; /* Variable argument pointer */
2117 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
2119 va_start(ap
, format
);
2120 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
2123 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
2125 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
2126 return (httpWrite2(http
, buf
, bytes
));
2131 DEBUG_puts("4httpPrintf: flushing existing data...");
2133 if (httpFlushWrite(http
) < 0)
2137 return (http_write(http
, buf
, bytes
));
2143 * 'httpPut()' - Send a PUT request to the server.
2146 int /* O - Status of call (0 = success) */
2147 httpPut(http_t
*http
, /* I - HTTP connection */
2148 const char *uri
) /* I - URI to put */
2150 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2151 return (http_send(http
, HTTP_STATE_PUT
, uri
));
2156 * 'httpRead()' - Read data from a HTTP connection.
2158 * This function is deprecated. Use the httpRead2() function which can
2159 * read more than 2GB of data.
2164 int /* O - Number of bytes read */
2165 httpRead(http_t
*http
, /* I - HTTP connection */
2166 char *buffer
, /* I - Buffer for data */
2167 int length
) /* I - Maximum number of bytes */
2169 return ((int)httpRead2(http
, buffer
, length
));
2174 * 'httpRead2()' - Read data from a HTTP connection.
2176 * @since CUPS 1.2/OS X 10.5@
2179 ssize_t
/* O - Number of bytes read */
2180 httpRead2(http_t
*http
, /* I - HTTP connection */
2181 char *buffer
, /* I - Buffer for data */
2182 size_t length
) /* I - Maximum number of bytes */
2184 ssize_t bytes
; /* Bytes read */
2188 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2189 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
2190 http
, buffer
, CUPS_LLCAST length
,
2192 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2194 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2195 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
2196 http
, buffer
, CUPS_LLCAST length
,
2197 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2198 #endif /* HAVE_LIBZ */
2200 if (http
== NULL
|| buffer
== NULL
)
2203 http
->activity
= time(NULL
);
2214 if (http
->stream
.avail_in
> 0)
2216 int zerr
; /* Decompressor error */
2218 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2219 (int)http
->stream
.avail_in
, (int)length
));
2221 http
->stream
.next_out
= (Bytef
*)buffer
;
2222 http
->stream
.avail_out
= length
;
2224 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2226 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2228 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2229 http
->stream
.avail_in
);
2236 bytes
= length
- http
->stream
.avail_out
;
2238 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2239 http
->stream
.avail_in
, http
->stream
.avail_out
,
2247 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2248 /* Additional bytes for buffer */
2252 if (http
->stream
.avail_in
> 0 &&
2253 http
->stream
.next_in
> http
->dbuffer
)
2254 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2256 http
->stream
.next_in
= http
->dbuffer
;
2258 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2259 "decompression buffer.", (int)buflen
));
2261 if (http
->data_remaining
> 0)
2263 if (buflen
> http
->data_remaining
)
2264 buflen
= http
->data_remaining
;
2266 bytes
= http_read_buffered(http
,
2267 (char *)http
->dbuffer
+
2268 http
->stream
.avail_in
, buflen
);
2270 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2271 bytes
= http_read_chunk(http
,
2272 (char *)http
->dbuffer
+
2273 http
->stream
.avail_in
, buflen
);
2279 else if (bytes
== 0)
2282 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2283 "decompression buffer.", CUPS_LLCAST bytes
));
2285 http
->data_remaining
-= bytes
;
2286 http
->stream
.avail_in
+= bytes
;
2288 if (http
->data_remaining
<= 0 &&
2289 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2292 * Read the trailing blank line now...
2295 char len
[32]; /* Length string */
2297 httpGets(len
, sizeof(len
), http
);
2309 #endif /* HAVE_LIBZ */
2310 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2312 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2314 http
->data_remaining
-= bytes
;
2316 if (http
->data_remaining
<= 0)
2319 * Read the trailing blank line now...
2322 char len
[32]; /* Length string */
2324 httpGets(len
, sizeof(len
), http
);
2328 else if (http
->data_remaining
<= 0)
2331 * No more data to read...
2338 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2341 if (length
> (size_t)http
->data_remaining
)
2342 length
= (size_t)http
->data_remaining
;
2344 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2346 http
->data_remaining
-= bytes
;
2348 if (http
->data_remaining
<= 0 &&
2349 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2352 * Read the trailing blank line now...
2355 char len
[32]; /* Length string */
2357 httpGets(len
, sizeof(len
), http
);
2364 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2365 #endif /* HAVE_LIBZ */
2366 ((http
->data_remaining
<= 0 &&
2367 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2368 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2372 http_content_coding_finish(http
);
2373 #endif /* HAVE_LIBZ */
2375 if (http
->state
== HTTP_STATE_POST_RECV
)
2377 else if (http
->state
== HTTP_STATE_GET_SEND
||
2378 http
->state
== HTTP_STATE_POST_SEND
)
2379 http
->state
= HTTP_STATE_WAITING
;
2381 http
->state
= HTTP_STATE_STATUS
;
2383 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2384 httpStateString(http
->state
)));
2391 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2393 * '_httpReadCDSA()' - Read function for the CDSA library.
2396 OSStatus
/* O - -1 on error, 0 on success */
2398 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2399 void *data
, /* I - Data buffer */
2400 size_t *dataLength
) /* IO - Number of bytes */
2402 OSStatus result
; /* Return value */
2403 ssize_t bytes
; /* Number of bytes read */
2404 http_t
*http
; /* HTTP connection */
2407 http
= (http_t
*)connection
;
2409 if (!http
->blocking
)
2412 * Make sure we have data before we read...
2415 while (!_httpWait(http
, http
->wait_value
, 0))
2417 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2420 http
->error
= ETIMEDOUT
;
2427 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2429 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2431 if (bytes
== *dataLength
)
2437 *dataLength
= bytes
;
2438 result
= errSSLWouldBlock
;
2445 result
= errSSLClosedGraceful
;
2446 else if (errno
== EAGAIN
)
2447 result
= errSSLWouldBlock
;
2449 result
= errSSLClosedAbort
;
2454 #endif /* HAVE_SSL && HAVE_CDSASSL */
2457 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2459 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2462 ssize_t
/* O - Number of bytes read or -1 on error */
2464 gnutls_transport_ptr ptr
, /* I - HTTP connection */
2465 void *data
, /* I - Buffer */
2466 size_t length
) /* I - Number of bytes to read */
2468 http_t
*http
; /* HTTP connection */
2469 ssize_t bytes
; /* Bytes read */
2472 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2474 http
= (http_t
*)ptr
;
2476 if (!http
->blocking
)
2479 * Make sure we have data before we read...
2482 while (!_httpWait(http
, http
->wait_value
, 0))
2484 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2487 http
->error
= ETIMEDOUT
;
2492 bytes
= recv(http
->fd
, data
, length
, 0);
2493 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2496 #endif /* HAVE_SSL && HAVE_GNUTLS */
2500 * 'httpReadRequest()' - Read a HTTP request from a connection.
2502 * @since CUPS 1.7/OS X 10.9@
2505 http_state_t
/* O - New state of connection */
2506 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2507 char *uri
, /* I - URI buffer */
2508 size_t urilen
) /* I - Size of URI buffer */
2510 char line
[4096], /* HTTP request line */
2511 *req_method
, /* HTTP request method */
2512 *req_uri
, /* HTTP request URI */
2513 *req_version
; /* HTTP request version number string */
2517 * Range check input...
2520 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2521 http
, uri
, CUPS_LLCAST urilen
));
2526 if (!http
|| !uri
|| urilen
< 1)
2528 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2529 return (HTTP_STATE_ERROR
);
2531 else if (http
->state
!= HTTP_STATE_WAITING
)
2533 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2534 httpStateString(http
->state
)));
2535 return (HTTP_STATE_ERROR
);
2542 httpClearFields(http
);
2544 http
->activity
= time(NULL
);
2545 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2546 http
->data_remaining
= 0;
2547 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2548 http
->status
= HTTP_STATUS_OK
;
2549 http
->version
= HTTP_VERSION_1_1
;
2552 * Read a line from the socket...
2555 if (!httpGets(line
, sizeof(line
), http
))
2557 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2558 return (HTTP_STATE_ERROR
);
2563 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2564 return (HTTP_STATE_WAITING
);
2567 DEBUG_printf(("1httpReadRequest: %s", line
));
2576 while (*req_uri
&& !isspace(*req_uri
& 255))
2581 DEBUG_puts("1httpReadRequest: No request URI.");
2582 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request URI."), 1);
2583 return (HTTP_STATE_ERROR
);
2588 while (*req_uri
&& isspace(*req_uri
& 255))
2591 req_version
= req_uri
;
2593 while (*req_version
&& !isspace(*req_version
& 255))
2598 DEBUG_puts("1httpReadRequest: No request protocol version.");
2599 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request protocol version."), 1);
2600 return (HTTP_STATE_ERROR
);
2603 *req_version
++ = '\0';
2605 while (*req_version
&& isspace(*req_version
& 255))
2612 if (!strcmp(req_method
, "OPTIONS"))
2613 http
->state
= HTTP_STATE_OPTIONS
;
2614 else if (!strcmp(req_method
, "GET"))
2615 http
->state
= HTTP_STATE_GET
;
2616 else if (!strcmp(req_method
, "HEAD"))
2617 http
->state
= HTTP_STATE_HEAD
;
2618 else if (!strcmp(req_method
, "POST"))
2619 http
->state
= HTTP_STATE_POST
;
2620 else if (!strcmp(req_method
, "PUT"))
2621 http
->state
= HTTP_STATE_PUT
;
2622 else if (!strcmp(req_method
, "DELETE"))
2623 http
->state
= HTTP_STATE_DELETE
;
2624 else if (!strcmp(req_method
, "TRACE"))
2625 http
->state
= HTTP_STATE_TRACE
;
2626 else if (!strcmp(req_method
, "CONNECT"))
2627 http
->state
= HTTP_STATE_CONNECT
;
2630 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2631 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request method."), 1);
2632 return (HTTP_STATE_UNKNOWN_METHOD
);
2635 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2636 httpStateString(http
->state
)));
2638 if (!strcmp(req_version
, "HTTP/1.0"))
2640 http
->version
= HTTP_VERSION_1_0
;
2641 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2643 else if (!strcmp(req_version
, "HTTP/1.1"))
2645 http
->version
= HTTP_VERSION_1_1
;
2646 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2650 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2651 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request version."), 1);
2652 return (HTTP_STATE_UNKNOWN_VERSION
);
2655 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2656 strlcpy(uri
, req_uri
, urilen
);
2658 return (http
->state
);
2663 * 'httpReconnect()' - Reconnect to a HTTP server.
2665 * This function is deprecated. Please use the @link httpReconnect2@ function
2671 int /* O - 0 on success, non-zero on failure */
2672 httpReconnect(http_t
*http
) /* I - HTTP connection */
2674 DEBUG_printf(("httpReconnect(http=%p)", http
));
2676 return (httpReconnect2(http
, 30000, NULL
));
2681 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2685 int /* O - 0 on success, non-zero on failure */
2686 httpReconnect2(http_t
*http
, /* I - HTTP connection */
2687 int msec
, /* I - Timeout in milliseconds */
2688 int *cancel
) /* I - Pointer to "cancel" variable */
2690 http_addrlist_t
*addr
; /* Connected address */
2692 http_addrlist_t
*current
; /* Current address */
2693 char temp
[256]; /* Temporary address string */
2697 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2702 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2709 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2710 http_shutdown_ssl(http
);
2712 #endif /* HAVE_SSL */
2715 * Close any previously open socket...
2720 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2722 httpAddrClose(NULL
, http
->fd
);
2728 * Reset all state (except fields, which may be reused)...
2731 http
->state
= HTTP_STATE_WAITING
;
2732 http
->version
= HTTP_VERSION_1_1
;
2733 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2734 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2735 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2736 http
->_data_remaining
= 0;
2738 http
->data_remaining
= 0;
2739 http
->hostaddr
= NULL
;
2743 * Connect to the server...
2747 for (current
= http
->addrlist
; current
; current
= current
->next
)
2748 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2749 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2750 httpAddrPort(&(current
->addr
))));
2753 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2757 * Unable to connect...
2761 http
->error
= WSAGetLastError();
2763 http
->error
= errno
;
2765 http
->status
= HTTP_STATUS_ERROR
;
2767 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2768 strerror(http
->error
)));
2773 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2775 if (http
->timeout_value
> 0)
2776 http_set_timeout(http
->fd
, http
->timeout_value
);
2778 http
->hostaddr
= &(addr
->addr
);
2782 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2785 * Always do encryption via SSL.
2788 if (http_setup_ssl(http
) != 0)
2790 httpAddrClose(NULL
, http
->fd
);
2795 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2796 return (http_upgrade(http
));
2797 #endif /* HAVE_SSL */
2799 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2800 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2801 httpAddrPort(http
->hostaddr
)));
2808 * 'httpSetAuthString()' - Set the current authorization string.
2810 * This function just stores a copy of the current authorization string in
2811 * the HTTP connection object. You must still call httpSetField() to set
2812 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2813 * httpHead(), httpOptions(), httpPost, or httpPut().
2815 * @since CUPS 1.3/OS X 10.5@
2819 httpSetAuthString(http_t
*http
, /* I - HTTP connection */
2820 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2821 const char *data
) /* I - Auth data (NULL for none) */
2824 * Range check input...
2830 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2831 free(http
->authstring
);
2833 http
->authstring
= http
->_authstring
;
2838 * Set the current authorization string...
2841 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2844 if (len
> (int)sizeof(http
->_authstring
))
2846 if ((temp
= malloc(len
)) == NULL
)
2847 len
= sizeof(http
->_authstring
);
2849 http
->authstring
= temp
;
2853 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2855 strlcpy(http
->authstring
, scheme
, len
);
2860 * Clear the current authorization string...
2863 http
->_authstring
[0] = '\0';
2869 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2872 * @since CUPS 1.5/OS X 10.7@
2875 int /* O - Status of call (0 = success) */
2876 httpSetCredentials(http_t
*http
, /* I - HTTP connection */
2877 cups_array_t
*credentials
) /* I - Array of credentials */
2879 if (!http
|| cupsArrayCount(credentials
) < 1)
2882 _httpFreeCredentials(http
->tls_credentials
);
2884 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2886 return (http
->tls_credentials
? 0 : -1);
2891 * 'httpSetCookie()' - Set the cookie value(s).
2893 * @since CUPS 1.1.19/OS X 10.3@
2897 httpSetCookie(http_t
*http
, /* I - Connection */
2898 const char *cookie
) /* I - Cookie string */
2907 http
->cookie
= strdup(cookie
);
2909 http
->cookie
= NULL
;
2914 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2916 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2917 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2919 * @since CUPS 1.7/OS X 10.9@
2923 httpSetDefaultField(http_t
*http
, /* I - HTTP connection */
2924 http_field_t field
, /* I - Field index */
2925 const char *value
)/* I - Value */
2927 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2928 http
, field
, http_fields
[field
], value
));
2935 case HTTP_FIELD_ACCEPT_ENCODING
:
2936 if (http
->default_accept_encoding
)
2937 _cupsStrFree(http
->default_accept_encoding
);
2939 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2942 case HTTP_FIELD_SERVER
:
2943 if (http
->default_server
)
2944 _cupsStrFree(http
->default_server
);
2946 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2949 case HTTP_FIELD_USER_AGENT
:
2950 if (http
->default_user_agent
)
2951 _cupsStrFree(http
->default_user_agent
);
2953 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2957 DEBUG_puts("1httpSetDefaultField: Ignored.");
2964 * 'httpSetExpect()' - Set the Expect: header in a request.
2966 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2969 * @since CUPS 1.2/OS X 10.5@
2973 httpSetExpect(http_t
*http
, /* I - HTTP connection */
2974 http_status_t expect
) /* I - HTTP status to expect
2975 (@code HTTP_STATUS_CONTINUE@) */
2977 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2980 http
->expect
= expect
;
2985 * 'httpSetField()' - Set the value of an HTTP header.
2989 httpSetField(http_t
*http
, /* I - HTTP connection */
2990 http_field_t field
, /* I - Field index */
2991 const char *value
) /* I - Value */
2993 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2994 field
, http_fields
[field
], value
));
2997 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2998 field
>= HTTP_FIELD_MAX
||
3004 case HTTP_FIELD_ACCEPT_ENCODING
:
3005 if (http
->accept_encoding
)
3006 _cupsStrFree(http
->accept_encoding
);
3008 http
->accept_encoding
= _cupsStrAlloc(value
);
3011 case HTTP_FIELD_ALLOW
:
3013 _cupsStrFree(http
->allow
);
3015 http
->allow
= _cupsStrAlloc(value
);
3018 case HTTP_FIELD_SERVER
:
3020 _cupsStrFree(http
->server
);
3022 http
->server
= _cupsStrAlloc(value
);
3026 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
3030 if (field
== HTTP_FIELD_AUTHORIZATION
)
3033 * Special case for Authorization: as its contents can be
3034 * longer than HTTP_MAX_VALUE
3037 if (http
->field_authorization
)
3038 free(http
->field_authorization
);
3040 http
->field_authorization
= strdup(value
);
3042 else if (field
== HTTP_FIELD_HOST
)
3045 * Special-case for Host: as we don't want a trailing "." on the hostname and
3046 * need to bracket IPv6 numeric addresses.
3049 char *ptr
= strchr(value
, ':');
3051 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
3054 * Bracket IPv6 numeric addresses...
3056 * This is slightly inefficient (basically copying twice), but is an edge
3057 * case and not worth optimizing...
3060 snprintf(http
->fields
[HTTP_FIELD_HOST
],
3061 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
3066 * Check for a trailing dot on the hostname...
3069 ptr
= http
->fields
[HTTP_FIELD_HOST
];
3073 ptr
+= strlen(ptr
) - 1;
3081 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
3082 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
3084 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
3085 http_content_coding_start(http
, value
);
3087 #endif /* HAVE_LIBZ */
3092 * 'httpSetKeepAlive()' - Set the current Keep-Alive state of a connection.
3099 http_t
*http
, /* I - HTTP connection */
3100 http_keepalive_t keep_alive
) /* I - New Keep-Alive value */
3103 http
->keep_alive
= keep_alive
;
3108 * 'httpSetLength()' - Set the content-length and content-encoding.
3110 * @since CUPS 1.2/OS X 10.5@
3114 httpSetLength(http_t
*http
, /* I - HTTP connection */
3115 size_t length
) /* I - Length (0 for chunked) */
3117 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
3118 CUPS_LLCAST length
));
3125 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
3127 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
3131 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
3132 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
3133 CUPS_LLFMT
, CUPS_LLCAST length
);
3139 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
3141 * The optional timeout callback receives both the HTTP connection and a user
3142 * data pointer and must return 1 to continue or 0 to error (time) out.
3144 * @since CUPS 1.5/OS X 10.7@
3149 http_t
*http
, /* I - HTTP connection */
3150 double timeout
, /* I - Number of seconds for timeout,
3151 must be greater than 0 */
3152 http_timeout_cb_t cb
, /* I - Callback function or NULL */
3153 void *user_data
) /* I - User data pointer */
3155 if (!http
|| timeout
<= 0.0)
3158 http
->timeout_cb
= cb
;
3159 http
->timeout_data
= user_data
;
3160 http
->timeout_value
= timeout
;
3163 http_set_timeout(http
->fd
, timeout
);
3165 http_set_wait(http
);
3170 * 'httpShutdown()' - Shutdown one side of an HTTP connection.
3176 httpShutdown(http_t
*http
) /* I - HTTP connection */
3178 if (!http
|| http
->fd
< 0)
3182 http_shutdown_ssl(http
);
3184 shutdown(http
->fd
, SHUT_RD
);
3189 * 'httpTrace()' - Send an TRACE request to the server.
3192 int /* O - Status of call (0 = success) */
3193 httpTrace(http_t
*http
, /* I - HTTP connection */
3194 const char *uri
) /* I - URI for trace */
3196 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
3201 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3203 * Note: Unlike httpUpdate(), this function does not flush pending write data
3204 * and only retrieves a single status line from the HTTP connection.
3207 int /* O - 1 to continue, 0 to stop */
3208 _httpUpdate(http_t
*http
, /* I - HTTP connection */
3209 http_status_t
*status
) /* O - Current HTTP status */
3211 char line
[32768], /* Line from connection... */
3212 *value
; /* Pointer to value on line */
3213 http_field_t field
; /* Field index */
3214 int major
, minor
; /* HTTP version numbers */
3217 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3218 httpStateString(http
->state
)));
3221 * Grab a single line from the connection...
3224 if (!httpGets(line
, sizeof(line
), http
))
3226 *status
= HTTP_STATUS_ERROR
;
3230 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3232 if (line
[0] == '\0')
3235 * Blank line means the start of the data section (if any). Return
3236 * the result code, too...
3238 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3239 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3243 if (http
->status
== HTTP_STATUS_CONTINUE
)
3245 *status
= http
->status
;
3249 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
3250 http
->digest_tries
= 0;
3253 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
3255 if (http_setup_ssl(http
) != 0)
3257 httpAddrClose(NULL
, http
->fd
);
3259 *status
= http
->status
= HTTP_STATUS_ERROR
;
3263 *status
= HTTP_STATUS_CONTINUE
;
3266 #endif /* HAVE_SSL */
3268 if (http_set_length(http
) < 0)
3270 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3271 http
->error
= EINVAL
;
3272 http
->status
= *status
= HTTP_STATUS_ERROR
;
3276 switch (http
->state
)
3278 case HTTP_STATE_GET
:
3279 case HTTP_STATE_POST
:
3280 case HTTP_STATE_POST_RECV
:
3281 case HTTP_STATE_PUT
:
3284 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3285 httpStateString(http
->state
)));
3287 case HTTP_STATE_POST_SEND
:
3288 case HTTP_STATE_HEAD
:
3292 http
->state
= HTTP_STATE_WAITING
;
3294 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
3299 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3300 http_content_coding_start(http
,
3301 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3302 #endif /* HAVE_LIBZ */
3304 *status
= http
->status
;
3307 else if (!strncmp(line
, "HTTP/", 5))
3310 * Got the beginning of a response...
3313 int intstatus
; /* Status value as an integer */
3315 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3317 *status
= http
->status
= HTTP_STATUS_ERROR
;
3321 httpClearFields(http
);
3323 http
->version
= (http_version_t
)(major
* 100 + minor
);
3324 *status
= http
->status
= (http_status_t
)intstatus
;
3326 else if ((value
= strchr(line
, ':')) != NULL
)
3333 while (_cups_isspace(*value
))
3336 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3339 * Be tolerants of servers that send unknown attribute fields...
3342 if (!_cups_strcasecmp(line
, "expect"))
3345 * "Expect: 100-continue" or similar...
3348 http
->expect
= (http_status_t
)atoi(value
);
3350 else if (!_cups_strcasecmp(line
, "cookie"))
3353 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3356 httpSetCookie(http
, value
);
3358 else if ((field
= httpFieldValue(line
)) != HTTP_FIELD_UNKNOWN
)
3359 httpSetField(http
, field
, value
);
3362 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3367 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3368 http
->error
= EINVAL
;
3369 http
->status
= *status
= HTTP_STATUS_ERROR
;
3378 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3381 http_status_t
/* O - HTTP status */
3382 httpUpdate(http_t
*http
) /* I - HTTP connection */
3384 http_status_t status
; /* Request status */
3387 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3388 httpStateString(http
->state
)));
3391 * Flush pending data, if any...
3396 DEBUG_puts("2httpUpdate: flushing buffer...");
3398 if (httpFlushWrite(http
) < 0)
3399 return (HTTP_STATUS_ERROR
);
3403 * If we haven't issued any commands, then there is nothing to "update"...
3406 if (http
->state
== HTTP_STATE_WAITING
)
3407 return (HTTP_STATUS_CONTINUE
);
3410 * Grab all of the lines we can from the connection...
3413 while (_httpUpdate(http
, &status
));
3416 * See if there was an error...
3419 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3421 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3422 return (http
->status
);
3427 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3428 strerror(http
->error
)));
3429 http
->status
= HTTP_STATUS_ERROR
;
3430 return (HTTP_STATUS_ERROR
);
3434 * Return the current status...
3442 * '_httpWait()' - Wait for data available on a connection (no flush).
3445 int /* O - 1 if data is available, 0 otherwise */
3446 _httpWait(http_t
*http
, /* I - HTTP connection */
3447 int msec
, /* I - Milliseconds to wait */
3448 int usessl
) /* I - Use SSL context? */
3451 struct pollfd pfd
; /* Polled file descriptor */
3453 fd_set input_set
; /* select() input set */
3454 struct timeval timeout
; /* Timeout */
3455 #endif /* HAVE_POLL */
3456 int nfds
; /* Result from select()/poll() */
3459 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3463 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3468 * Check the SSL/TLS buffers for data first...
3472 if (http
->tls
&& usessl
)
3475 if (SSL_pending(http
->tls
))
3477 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3481 # elif defined(HAVE_GNUTLS)
3482 if (gnutls_record_check_pending(http
->tls
))
3484 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3488 # elif defined(HAVE_CDSASSL)
3489 size_t bytes
; /* Bytes that are available */
3491 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3494 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3497 # endif /* HAVE_LIBSSL */
3499 #endif /* HAVE_SSL */
3502 * Then try doing a select() or poll() to poll the socket...
3507 pfd
.events
= POLLIN
;
3511 nfds
= poll(&pfd
, 1, msec
);
3513 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3518 FD_ZERO(&input_set
);
3519 FD_SET(http
->fd
, &input_set
);
3521 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3525 timeout
.tv_sec
= msec
/ 1000;
3526 timeout
.tv_usec
= (msec
% 1000) * 1000;
3528 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3531 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3533 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3536 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3537 WSAGetLastError() == WSAEWOULDBLOCK
));
3539 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3541 #endif /* HAVE_POLL */
3543 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3551 * 'httpWait()' - Wait for data available on a connection.
3553 * @since CUPS 1.1.19/OS X 10.3@
3556 int /* O - 1 if data is available, 0 otherwise */
3557 httpWait(http_t
*http
, /* I - HTTP connection */
3558 int msec
) /* I - Milliseconds to wait */
3561 * First see if there is data in the buffer...
3564 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3571 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3576 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3578 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3581 #endif /* HAVE_LIBZ */
3584 * Flush pending data, if any...
3589 DEBUG_puts("3httpWait: Flushing write buffer.");
3591 if (httpFlushWrite(http
) < 0)
3596 * If not, check the SSL/TLS buffers and do a select() on the connection...
3599 return (_httpWait(http
, msec
, 1));
3604 * 'httpWrite()' - Write data to a HTTP connection.
3606 * This function is deprecated. Use the httpWrite2() function which can
3607 * write more than 2GB of data.
3612 int /* O - Number of bytes written */
3613 httpWrite(http_t
*http
, /* I - HTTP connection */
3614 const char *buffer
, /* I - Buffer for data */
3615 int length
) /* I - Number of bytes to write */
3617 return ((int)httpWrite2(http
, buffer
, length
));
3622 * 'httpWrite2()' - Write data to a HTTP connection.
3624 * @since CUPS 1.2/OS X 10.5@
3627 ssize_t
/* O - Number of bytes written */
3628 httpWrite2(http_t
*http
, /* I - HTTP connection */
3629 const char *buffer
, /* I - Buffer for data */
3630 size_t length
) /* I - Number of bytes to write */
3632 ssize_t bytes
; /* Bytes written */
3635 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3636 buffer
, CUPS_LLCAST length
));
3639 * Range check input...
3642 if (!http
|| !buffer
)
3644 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3649 * Mark activity on the connection...
3652 http
->activity
= time(NULL
);
3655 * Buffer small writes for better performance...
3661 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3665 http_content_coding_finish(http
);
3670 http
->stream
.next_in
= (Bytef
*)buffer
;
3671 http
->stream
.avail_in
= length
;
3672 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3673 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3675 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3677 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3679 if (http
->stream
.avail_out
== 0)
3681 if (httpFlushWrite(http
) < 0)
3683 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3687 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3688 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3692 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3697 #endif /* HAVE_LIBZ */
3700 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3702 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3703 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3705 httpFlushWrite(http
);
3708 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3709 length
< sizeof(http
->wbuffer
))
3712 * Write to buffer...
3715 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3716 CUPS_LLCAST length
));
3718 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3719 http
->wused
+= (int)length
;
3720 bytes
= (ssize_t
)length
;
3725 * Otherwise write the data directly...
3728 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3729 CUPS_LLCAST length
));
3731 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3732 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3734 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3736 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3737 CUPS_LLCAST bytes
));
3740 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3741 http
->data_remaining
-= bytes
;
3747 * Handle end-of-request processing...
3750 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3751 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3754 * Finished with the transfer; unless we are sending POST or PUT
3760 http_content_coding_finish(http
);
3761 #endif /* HAVE_LIBZ */
3765 if (httpFlushWrite(http
) < 0)
3769 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3772 * Send a 0-length chunk at the end of the request...
3775 http_write(http
, "0\r\n\r\n", 5);
3778 * Reset the data state...
3781 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3782 http
->data_remaining
= 0;
3785 if (http
->state
== HTTP_STATE_POST_RECV
)
3787 else if (http
->state
== HTTP_STATE_POST_SEND
)
3788 http
->state
= HTTP_STATE_WAITING
;
3790 http
->state
= HTTP_STATE_STATUS
;
3792 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3793 httpStateString(http
->state
)));
3796 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3802 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3804 * '_httpWriteCDSA()' - Write function for the CDSA library.
3807 OSStatus
/* O - -1 on error, 0 on success */
3809 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3810 const void *data
, /* I - Data buffer */
3811 size_t *dataLength
) /* IO - Number of bytes */
3813 OSStatus result
; /* Return value */
3814 ssize_t bytes
; /* Number of bytes read */
3815 http_t
*http
; /* HTTP connection */
3818 http
= (http_t
*)connection
;
3822 bytes
= write(http
->fd
, data
, *dataLength
);
3824 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3826 if (bytes
== *dataLength
)
3830 else if (bytes
>= 0)
3832 *dataLength
= bytes
;
3833 result
= errSSLWouldBlock
;
3839 if (errno
== EAGAIN
)
3840 result
= errSSLWouldBlock
;
3842 result
= errSSLClosedAbort
;
3847 #endif /* HAVE_SSL && HAVE_CDSASSL */
3850 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3852 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3855 ssize_t
/* O - Number of bytes written or -1 on error */
3857 gnutls_transport_ptr ptr
, /* I - HTTP connection */
3858 const void *data
, /* I - Data buffer */
3859 size_t length
) /* I - Number of bytes to write */
3861 ssize_t bytes
; /* Bytes written */
3864 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3867 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3870 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3871 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3875 #endif /* HAVE_SSL && HAVE_GNUTLS */
3879 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3881 * @since CUPS 1.7/OS X 10.9@
3884 int /* O - 0 on success, -1 on error */
3885 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3886 http_status_t status
) /* I - Status code */
3888 http_encoding_t old_encoding
; /* Old data_encoding value */
3889 off_t old_remaining
; /* Old data_remaining value */
3893 * Range check input...
3896 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3898 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3900 DEBUG_puts("1httpWriteResponse: Bad input.");
3905 * Set the various standard fields if they aren't already...
3908 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3909 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3911 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3913 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
3914 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3917 if (http
->version
== HTTP_VERSION_1_1
)
3919 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3921 if (http
->keep_alive
)
3922 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3924 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3927 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3928 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3932 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
||
3933 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
3935 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3936 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3938 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3939 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3941 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
3942 httpSetField(http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
3944 #endif /* HAVE_SSL */
3947 httpSetField(http
, HTTP_FIELD_SERVER
,
3948 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3951 * Set the Accept-Encoding field if it isn't already...
3954 if (!http
->accept_encoding
)
3955 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3956 http
->default_accept_encoding
? http
->default_accept_encoding
:
3958 "gzip, deflate, identity");
3961 #endif /* HAVE_LIBZ */
3964 * Send the response header...
3967 old_encoding
= http
->data_encoding
;
3968 old_remaining
= http
->data_remaining
;
3969 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3971 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3972 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3974 http
->status
= HTTP_STATUS_ERROR
;
3978 if (status
!= HTTP_STATUS_CONTINUE
)
3981 * 100 Continue doesn't have the rest of the response headers...
3984 int i
; /* Looping var */
3985 const char *value
; /* Field value */
3987 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3989 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3991 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3993 http
->status
= HTTP_STATUS_ERROR
;
4001 if (httpPrintf(http
, "Set-Cookie: %s path=/ httponly%s\r\n",
4002 http
->cookie
, http
->tls
? " secure" : "") < 1)
4004 http
->status
= HTTP_STATUS_ERROR
;
4010 if (httpWrite2(http
, "\r\n", 2) < 2)
4012 http
->status
= HTTP_STATUS_ERROR
;
4016 if (httpFlushWrite(http
) < 0)
4018 http
->status
= HTTP_STATUS_ERROR
;
4022 if (status
== HTTP_STATUS_CONTINUE
||
4023 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
4026 * Restore the old data_encoding and data_length values...
4029 http
->data_encoding
= old_encoding
;
4030 http
->data_remaining
= old_remaining
;
4032 if (old_remaining
<= INT_MAX
)
4033 http
->_data_remaining
= (int)old_remaining
;
4035 http
->_data_remaining
= INT_MAX
;
4037 else if (http
->state
== HTTP_STATE_OPTIONS
||
4038 http
->state
== HTTP_STATE_HEAD
||
4039 http
->state
== HTTP_STATE_PUT
||
4040 http
->state
== HTTP_STATE_TRACE
||
4041 http
->state
== HTTP_STATE_CONNECT
||
4042 http
->state
== HTTP_STATE_STATUS
)
4044 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
4045 "was %s.", httpStateString(http
->state
)));
4046 http
->state
= HTTP_STATE_WAITING
;
4051 * Force data_encoding and data_length to be set according to the response
4055 http_set_length(http
);
4059 * Then start any content encoding...
4062 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
4063 http_content_coding_start(http
,
4064 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
4065 #endif /* HAVE_LIBZ */
4072 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
4074 * 'http_bio_ctrl()' - Control the HTTP connection.
4077 static long /* O - Result/data */
4078 http_bio_ctrl(BIO
*h
, /* I - BIO data */
4079 int cmd
, /* I - Control command */
4080 long arg1
, /* I - First argument */
4081 void *arg2
) /* I - Second argument */
4088 case BIO_CTRL_RESET
:
4092 case BIO_C_SET_FILE_PTR
:
4097 case BIO_C_GET_FILE_PTR
:
4100 *((void **)arg2
) = h
->ptr
;
4107 case BIO_CTRL_FLUSH
:
4114 * 'http_bio_free()' - Free OpenSSL data.
4117 static int /* O - 1 on success, 0 on failure */
4118 http_bio_free(BIO
*h
) /* I - BIO data */
4134 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
4137 static int /* O - 1 on success, 0 on failure */
4138 http_bio_new(BIO
*h
) /* I - BIO data */
4153 * 'http_bio_puts()' - Send a string for OpenSSL.
4156 static int /* O - Bytes written */
4157 http_bio_puts(BIO
*h
, /* I - BIO data */
4158 const char *str
) /* I - String to write */
4161 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
4163 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
4169 * 'http_bio_read()' - Read data for OpenSSL.
4172 static int /* O - Bytes read */
4173 http_bio_read(BIO
*h
, /* I - BIO data */
4174 char *buf
, /* I - Buffer */
4175 int size
) /* I - Number of bytes to read */
4177 http_t
*http
; /* HTTP connection */
4180 http
= (http_t
*)h
->ptr
;
4182 if (!http
->blocking
)
4185 * Make sure we have data before we read...
4188 while (!_httpWait(http
, http
->wait_value
, 0))
4190 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4194 http
->error
= WSAETIMEDOUT
;
4196 http
->error
= ETIMEDOUT
;
4203 return (recv(http
->fd
, buf
, size
, 0));
4208 * 'http_bio_write()' - Write data for OpenSSL.
4211 static int /* O - Bytes written */
4212 http_bio_write(BIO
*h
, /* I - BIO data */
4213 const char *buf
, /* I - Buffer to write */
4214 int num
) /* I - Number of bytes to write */
4216 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4218 #endif /* HAVE_SSL && HAVE_LIBSSL */
4223 * 'http_content_coding_finish()' - Finish doing any content encoding.
4227 http_content_coding_finish(
4228 http_t
*http
) /* I - HTTP connection */
4230 int zerr
; /* Compression status */
4233 switch (http
->coding
)
4235 case _HTTP_CODING_DEFLATE
:
4236 case _HTTP_CODING_GZIP
:
4239 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4240 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4242 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4244 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4245 if (http
->wused
== sizeof(http
->wbuffer
))
4246 httpFlushWrite(http
);
4248 while (zerr
== Z_OK
);
4250 deflateEnd(&(http
->stream
));
4253 httpFlushWrite(http
);
4256 case _HTTP_CODING_INFLATE
:
4257 case _HTTP_CODING_GUNZIP
:
4258 inflateEnd(&(http
->stream
));
4259 free(http
->dbuffer
);
4260 http
->dbuffer
= NULL
;
4267 http
->coding
= _HTTP_CODING_IDENTITY
;
4272 * 'http_content_coding_start()' - Start doing content encoding.
4276 http_content_coding_start(
4277 http_t
*http
, /* I - HTTP connection */
4278 const char *value
) /* I - Value of Content-Encoding */
4280 int zerr
; /* Error/status */
4281 _http_coding_t coding
; /* Content coding value */
4284 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4287 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4289 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4293 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4295 if (http
->state
== HTTP_STATE_GET_SEND
||
4296 http
->state
== HTTP_STATE_POST_SEND
)
4297 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4298 _HTTP_CODING_GUNZIP
;
4299 else if (http
->state
== HTTP_STATE_POST_RECV
||
4300 http
->state
== HTTP_STATE_PUT_RECV
)
4301 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4302 _HTTP_CODING_GUNZIP
;
4305 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4309 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4311 if (http
->state
== HTTP_STATE_GET_SEND
||
4312 http
->state
== HTTP_STATE_POST_SEND
)
4313 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4314 _HTTP_CODING_INFLATE
;
4315 else if (http
->state
== HTTP_STATE_POST_RECV
||
4316 http
->state
== HTTP_STATE_PUT_RECV
)
4317 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4318 _HTTP_CODING_INFLATE
;
4321 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4327 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4331 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4335 case _HTTP_CODING_DEFLATE
:
4336 case _HTTP_CODING_GZIP
:
4338 httpFlushWrite(http
);
4341 * Window size for compression is 11 bits - optimal based on PWG Raster
4342 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
4346 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4348 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
4349 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4351 http
->status
= HTTP_STATUS_ERROR
;
4352 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4357 case _HTTP_CODING_INFLATE
:
4358 case _HTTP_CODING_GUNZIP
:
4359 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
4361 http
->status
= HTTP_STATUS_ERROR
;
4362 http
->error
= errno
;
4367 * Window size for decompression is up to 15 bits (maximum supported).
4368 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
4371 if ((zerr
= inflateInit2(&(http
->stream
),
4372 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
4375 free(http
->dbuffer
);
4376 http
->dbuffer
= NULL
;
4377 http
->status
= HTTP_STATUS_ERROR
;
4378 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4382 http
->stream
.avail_in
= 0;
4383 http
->stream
.next_in
= http
->dbuffer
;
4390 http
->coding
= coding
;
4392 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4395 #endif /* HAVE_LIBZ */
4399 * 'http_create()' - Create an unconnected HTTP connection.
4402 static http_t
* /* O - HTTP connection */
4404 const char *host
, /* I - Hostname */
4405 int port
, /* I - Port number */
4406 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
4407 int family
, /* I - Address family or AF_UNSPEC */
4408 http_encryption_t encryption
, /* I - Encryption to use */
4409 int blocking
, /* I - 1 for blocking mode */
4410 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
4412 http_t
*http
; /* New HTTP connection */
4413 char service
[255]; /* Service name */
4414 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
4417 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
4418 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
4419 family
, encryption
, blocking
, mode
));
4421 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
4427 * Lookup the host...
4432 myaddrlist
= httpAddrCopyList(addrlist
);
4436 snprintf(service
, sizeof(service
), "%d", port
);
4438 myaddrlist
= httpAddrGetList(host
, family
, service
);
4445 * Allocate memory for the structure...
4448 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
4450 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
4451 httpAddrFreeList(addrlist
);
4456 * Initialize the HTTP data...
4460 http
->activity
= time(NULL
);
4461 http
->addrlist
= myaddrlist
;
4462 http
->blocking
= blocking
;
4465 http
->gssctx
= GSS_C_NO_CONTEXT
;
4466 http
->gssname
= GSS_C_NO_NAME
;
4467 #endif /* HAVE_GSSAPI */
4468 http
->status
= HTTP_STATUS_CONTINUE
;
4469 http
->version
= HTTP_VERSION_1_1
;
4472 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
4474 if (port
== 443) /* Always use encryption for https */
4475 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
4477 http
->encryption
= encryption
;
4479 http_set_wait(http
);
4482 * Return the new structure...
4488 /* For OS X 10.8 and earlier */
4489 http_t
*_httpCreate(const char *host
, int port
, http_addrlist_t
*addrlist
,
4490 http_encryption_t encryption
, int family
)
4491 { return (http_create(host
, port
, addrlist
, family
, encryption
, 1,
4492 _HTTP_MODE_CLIENT
)); }
4497 * 'http_debug_hex()' - Do a hex dump of a buffer.
4501 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4502 const char *buffer
, /* I - Buffer to dump */
4503 int bytes
) /* I - Bytes to dump */
4505 int i
, j
, /* Looping vars */
4506 ch
; /* Current character */
4507 char line
[255], /* Line buffer */
4508 *start
, /* Start of line after prefix */
4509 *ptr
; /* Pointer into line */
4512 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4515 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4517 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4518 start
= line
+ strlen(line
);
4520 for (i
= 0; i
< bytes
; i
+= 16)
4522 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4523 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4527 memcpy(ptr
, " ", 3);
4532 memcpy(ptr
, " ", 3);
4535 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4537 ch
= buffer
[i
+ j
] & 255;
4539 if (ch
< ' ' || ch
>= 127)
4553 * 'http_read()' - Read a buffer from a HTTP connection.
4555 * This function does the low-level read from the socket, retrying and timing
4559 static ssize_t
/* O - Number of bytes read or -1 on error */
4560 http_read(http_t
*http
, /* I - HTTP connection */
4561 char *buffer
, /* I - Buffer */
4562 size_t length
) /* I - Maximum bytes to read */
4564 ssize_t bytes
; /* Bytes read */
4567 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4568 buffer
, CUPS_LLCAST length
));
4570 if (!http
->blocking
)
4572 while (!httpWait(http
, http
->wait_value
))
4574 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4577 DEBUG_puts("2http_read: Timeout.");
4582 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4588 bytes
= http_read_ssl(http
, buffer
, length
);
4590 #endif /* HAVE_SSL */
4591 bytes
= recv(http
->fd
, buffer
, length
, 0);
4596 if (WSAGetLastError() != WSAEINTR
)
4598 http
->error
= WSAGetLastError();
4601 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4603 if (!http
->timeout_cb
||
4604 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4606 http
->error
= WSAEWOULDBLOCK
;
4611 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4613 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4615 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4617 http
->error
= errno
;
4620 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4622 http
->error
= errno
;
4626 else if (errno
!= EINTR
)
4628 http
->error
= errno
;
4636 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4637 CUPS_LLCAST bytes
));
4640 http_debug_hex("http_read", buffer
, (int)bytes
);
4646 if (WSAGetLastError() == WSAEINTR
)
4649 http
->error
= WSAGetLastError();
4651 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4654 http
->error
= errno
;
4657 else if (bytes
== 0)
4659 http
->error
= EPIPE
;
4668 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4670 * This function reads data from the HTTP buffer or from the socket, as needed.
4673 static ssize_t
/* O - Number of bytes read or -1 on error */
4674 http_read_buffered(http_t
*http
, /* I - HTTP connection */
4675 char *buffer
, /* I - Buffer */
4676 size_t length
) /* I - Maximum bytes to read */
4678 ssize_t bytes
; /* Bytes read */
4681 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4683 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4687 if (length
> (size_t)http
->used
)
4688 bytes
= (size_t)http
->used
;
4692 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4695 memcpy(buffer
, http
->buffer
, bytes
);
4696 http
->used
-= (int)bytes
;
4699 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4702 bytes
= http_read(http
, buffer
, length
);
4709 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4711 * This function reads and validates the chunk length, then does a buffered read
4712 * returning the number of bytes placed in the buffer.
4715 static ssize_t
/* O - Number of bytes read or -1 on error */
4716 http_read_chunk(http_t
*http
, /* I - HTTP connection */
4717 char *buffer
, /* I - Buffer */
4718 size_t length
) /* I - Maximum bytes to read */
4720 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4721 http
, buffer
, CUPS_LLCAST length
));
4723 if (http
->data_remaining
<= 0)
4725 char len
[32]; /* Length string */
4727 if (!httpGets(len
, sizeof(len
), http
))
4729 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4735 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4736 if (!httpGets(len
, sizeof(len
), http
))
4738 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4743 http
->data_remaining
= strtoll(len
, NULL
, 16);
4745 if (http
->data_remaining
< 0)
4747 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4748 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4752 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4753 len
, CUPS_LLCAST http
->data_remaining
));
4755 if (http
->data_remaining
== 0)
4758 * 0-length chunk, grab trailing blank line...
4761 httpGets(len
, sizeof(len
), http
);
4765 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4766 CUPS_LLCAST http
->data_remaining
));
4768 if (http
->data_remaining
<= 0)
4770 else if (length
> (size_t)http
->data_remaining
)
4771 length
= (size_t)http
->data_remaining
;
4773 return (http_read_buffered(http
, buffer
, length
));
4779 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4782 static int /* O - Bytes read */
4783 http_read_ssl(http_t
*http
, /* I - HTTP connection */
4784 char *buf
, /* I - Buffer to store data */
4785 int len
) /* I - Length of buffer */
4787 # if defined(HAVE_LIBSSL)
4788 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4790 # elif defined(HAVE_GNUTLS)
4791 ssize_t result
; /* Return value */
4794 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4796 if (result
< 0 && !errno
)
4799 * Convert GNU TLS error to errno value...
4804 case GNUTLS_E_INTERRUPTED
:
4808 case GNUTLS_E_AGAIN
:
4820 return ((int)result
);
4822 # elif defined(HAVE_CDSASSL)
4823 int result
; /* Return value */
4824 OSStatus error
; /* Error info */
4825 size_t processed
; /* Number of bytes processed */
4828 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4829 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4834 result
= (int)processed
;
4837 case errSSLWouldBlock
:
4839 result
= (int)processed
;
4847 case errSSLClosedGraceful
:
4850 result
= (int)processed
;
4861 # elif defined(HAVE_SSPISSL)
4862 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4863 # endif /* HAVE_LIBSSL */
4865 #endif /* HAVE_SSL */
4869 * 'http_send()' - Send a request with all fields and the trailing blank line.
4872 static int /* O - 0 on success, non-zero on error */
4873 http_send(http_t
*http
, /* I - HTTP connection */
4874 http_state_t request
, /* I - Request code */
4875 const char *uri
) /* I - URI */
4877 int i
; /* Looping var */
4878 char buf
[1024]; /* Encoded URI buffer */
4879 const char *value
; /* Field value */
4880 static const char * const codes
[] = /* Request code strings */
4900 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4901 http
, codes
[request
], uri
));
4903 if (http
== NULL
|| uri
== NULL
)
4907 * Set the User-Agent field if it isn't already...
4910 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4912 if (http
->default_user_agent
)
4913 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4915 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4919 * Set the Accept-Encoding field if it isn't already...
4922 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4923 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4924 http
->default_accept_encoding
);
4927 * Encode the URI as needed...
4930 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4933 * See if we had an error the last time around; if so, reconnect...
4936 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4937 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4939 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4940 http
->fd
, http
->status
, http
->tls_upgrade
));
4942 if (httpReconnect2(http
, 30000, NULL
))
4947 * Flush any written data that is pending...
4952 if (httpFlushWrite(http
) < 0)
4953 if (httpReconnect2(http
, 30000, NULL
))
4958 * Send the request header...
4961 http
->state
= request
;
4962 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4964 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4967 http
->status
= HTTP_STATUS_CONTINUE
;
4970 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4972 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4973 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4975 #endif /* HAVE_SSL */
4977 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4979 http
->status
= HTTP_STATUS_ERROR
;
4983 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4984 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4986 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
4988 if (i
== HTTP_FIELD_HOST
)
4990 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4991 httpAddrPort(http
->hostaddr
)) < 1)
4993 http
->status
= HTTP_STATUS_ERROR
;
4997 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4999 http
->status
= HTTP_STATUS_ERROR
;
5005 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
5007 http
->status
= HTTP_STATUS_ERROR
;
5011 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
5012 http
->mode
, http
->state
));
5014 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
5015 (http
->state
== HTTP_STATE_POST_RECV
||
5016 http
->state
== HTTP_STATE_PUT_RECV
))
5017 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
5019 http
->status
= HTTP_STATUS_ERROR
;
5023 if (httpPrintf(http
, "\r\n") < 1)
5025 http
->status
= HTTP_STATUS_ERROR
;
5029 if (httpFlushWrite(http
) < 0)
5032 http_set_length(http
);
5033 httpClearFields(http
);
5036 * The Kerberos and AuthRef authentication strings can only be used once...
5039 if (http
->field_authorization
&& http
->authstring
&&
5040 (!strncmp(http
->authstring
, "Negotiate", 9) ||
5041 !strncmp(http
->authstring
, "AuthRef", 7)))
5043 http
->_authstring
[0] = '\0';
5045 if (http
->authstring
!= http
->_authstring
)
5046 free(http
->authstring
);
5048 http
->authstring
= http
->_authstring
;
5056 # if defined(HAVE_CDSASSL)
5058 * 'http_set_credentials()' - Set the SSL/TLS credentials.
5061 static int /* O - Status of connection */
5062 http_set_credentials(http_t
*http
) /* I - HTTP connection */
5064 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
5065 OSStatus error
= 0; /* Error code */
5066 http_tls_credentials_t credentials
= NULL
;
5067 /* TLS credentials */
5070 DEBUG_printf(("7http_set_credentials(%p)", http
));
5073 * Prefer connection specific credentials...
5076 if ((credentials
= http
->tls_credentials
) == NULL
)
5077 credentials
= cg
->tls_credentials
;
5081 error
= SSLSetCertificate(http
->tls
, credentials
);
5082 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
5086 DEBUG_puts("4http_set_credentials: No credentials to set.");
5090 # endif /* HAVE_CDSASSL */
5091 #endif /* HAVE_SSL */
5095 * 'http_set_length()' - Set the data_encoding and data_remaining values.
5098 static off_t
/* O - Remainder or -1 on error */
5099 http_set_length(http_t
*http
) /* I - Connection */
5101 off_t remaining
; /* Remainder */
5104 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
5105 httpStateString(http
->state
)));
5107 if ((remaining
= httpGetLength2(http
)) >= 0)
5109 if (http
->mode
== _HTTP_MODE_SERVER
&&
5110 http
->state
!= HTTP_STATE_GET_SEND
&&
5111 http
->state
!= HTTP_STATE_PUT
&&
5112 http
->state
!= HTTP_STATE_POST
&&
5113 http
->state
!= HTTP_STATE_POST_SEND
)
5115 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
5119 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
5122 DEBUG_puts("1http_set_length: Setting data_encoding to "
5123 "HTTP_ENCODING_CHUNKED.");
5124 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
5128 DEBUG_puts("1http_set_length: Setting data_encoding to "
5129 "HTTP_ENCODING_LENGTH.");
5130 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
5133 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
5134 CUPS_LLCAST remaining
));
5135 http
->data_remaining
= remaining
;
5137 if (remaining
<= INT_MAX
)
5138 http
->_data_remaining
= remaining
;
5140 http
->_data_remaining
= INT_MAX
;
5147 * 'http_set_timeout()' - Set the socket timeout values.
5151 http_set_timeout(int fd
, /* I - File descriptor */
5152 double timeout
) /* I - Timeout in seconds */
5155 DWORD tv
= (DWORD
)(timeout
* 1000);
5156 /* Timeout in milliseconds */
5158 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5159 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5162 struct timeval tv
; /* Timeout in secs and usecs */
5164 tv
.tv_sec
= (int)timeout
;
5165 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
5167 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5168 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5174 * 'http_set_wait()' - Set the default wait value for reads.
5178 http_set_wait(http_t
*http
) /* I - HTTP connection */
5182 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5184 if (http
->wait_value
<= 0)
5185 http
->wait_value
= 60000;
5188 http
->wait_value
= 10000;
5194 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5197 static int /* O - 0 on success, -1 on failure */
5198 http_setup_ssl(http_t
*http
) /* I - HTTP connection */
5200 char hostname
[256], /* Hostname */
5201 *hostptr
; /* Pointer into hostname */
5204 SSL_CTX
*context
; /* Context for encryption */
5205 BIO
*bio
; /* BIO data */
5206 const char *message
= NULL
;/* Error message */
5207 # elif defined(HAVE_GNUTLS)
5208 int status
; /* Status of handshake */
5209 gnutls_certificate_client_credentials
*credentials
;
5210 /* TLS credentials */
5211 # elif defined(HAVE_CDSASSL)
5212 _cups_globals_t
*cg
= _cupsGlobals();
5213 /* Pointer to library globals */
5214 OSStatus error
; /* Error code */
5215 const char *message
= NULL
;/* Error message */
5216 cups_array_t
*credentials
; /* Credentials array */
5217 cups_array_t
*names
; /* CUPS distinguished names */
5218 CFArrayRef dn_array
; /* CF distinguished names array */
5219 CFIndex count
; /* Number of credentials */
5220 CFDataRef data
; /* Certificate data */
5221 int i
; /* Looping var */
5222 http_credential_t
*credential
; /* Credential data */
5223 # elif defined(HAVE_SSPISSL)
5224 TCHAR username
[256]; /* Username returned from GetUserName() */
5225 TCHAR commonName
[256];/* Common name for certificate */
5226 DWORD dwSize
; /* 32 bit size */
5227 # endif /* HAVE_LIBSSL */
5230 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5233 * Get the hostname to use for SSL...
5236 if (httpAddrLocalhost(http
->hostaddr
))
5238 strlcpy(hostname
, "localhost", sizeof(hostname
));
5243 * Otherwise make sure the hostname we have does not end in a trailing dot.
5246 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5247 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5253 context
= SSL_CTX_new(SSLv23_client_method());
5255 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5257 bio
= BIO_new(_httpBIOMethods());
5258 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5260 http
->tls
= SSL_new(context
);
5261 SSL_set_bio(http
->tls
, bio
, bio
);
5263 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5264 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5265 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5267 if (SSL_connect(http
->tls
) != 1)
5269 unsigned long error
; /* Error code */
5271 while ((error
= ERR_get_error()) != 0)
5273 message
= ERR_error_string(error
, NULL
);
5274 DEBUG_printf(("8http_setup_ssl: %s", message
));
5277 SSL_CTX_free(context
);
5278 SSL_free(http
->tls
);
5282 http
->error
= WSAGetLastError();
5284 http
->error
= errno
;
5286 http
->status
= HTTP_STATUS_ERROR
;
5289 message
= _("Unable to establish a secure connection to host.");
5291 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5296 # elif defined(HAVE_GNUTLS)
5297 credentials
= (gnutls_certificate_client_credentials
*)
5298 malloc(sizeof(gnutls_certificate_client_credentials
));
5299 if (credentials
== NULL
)
5301 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5303 http
->error
= errno
;
5304 http
->status
= HTTP_STATUS_ERROR
;
5305 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5310 gnutls_certificate_allocate_credentials(credentials
);
5312 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5313 gnutls_set_default_priority(http
->tls
);
5314 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5316 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5317 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5318 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5319 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5321 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5323 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5324 status
, gnutls_strerror(status
)));
5326 if (gnutls_error_is_fatal(status
))
5329 http
->status
= HTTP_STATUS_ERROR
;
5331 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
5333 gnutls_deinit(http
->tls
);
5334 gnutls_certificate_free_credentials(*credentials
);
5342 http
->tls_credentials
= credentials
;
5344 # elif defined(HAVE_CDSASSL)
5345 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, kSSLClientSide
,
5346 kSSLStreamType
)) == NULL
)
5348 DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
5349 http
->error
= errno
= ENOMEM
;
5350 http
->status
= HTTP_STATUS_ERROR
;
5351 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5356 error
= SSLSetConnection(http
->tls
, http
);
5357 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5361 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5362 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5367 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
5369 DEBUG_printf(("4http_setup_ssl: SSLSetSessionOption, error=%d",
5375 if (cg
->client_cert_cb
)
5377 error
= SSLSetSessionOption(http
->tls
,
5378 kSSLSessionOptionBreakOnCertRequested
, true);
5379 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5380 "error=%d", (int)error
));
5384 error
= http_set_credentials(http
);
5385 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5391 * Let the server know which hostname/domain we are trying to connect to
5392 * in case it wants to serve up a certificate with a matching common name.
5397 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5399 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5405 int done
= 0; /* Are we done yet? */
5407 while (!error
&& !done
)
5409 error
= SSLHandshake(http
->tls
);
5411 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5419 case errSSLWouldBlock
:
5420 error
= noErr
; /* Force a retry */
5421 usleep(1000); /* in 1 millisecond */
5424 case errSSLServerAuthCompleted
:
5426 if (cg
->server_cert_cb
)
5428 error
= httpCopyCredentials(http
, &credentials
);
5431 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5432 cg
->server_cert_data
);
5433 httpFreeCredentials(credentials
);
5436 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5437 "returned %d.", (int)error
));
5441 case errSSLClientCertRequested
:
5444 if (cg
->client_cert_cb
)
5447 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5450 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5452 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5454 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5456 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5458 credential
->datalen
= CFDataGetLength(data
);
5459 if ((credential
->data
= malloc(credential
->datalen
)))
5461 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5462 credential
->datalen
);
5463 cupsArrayAdd(names
, credential
);
5471 CFRelease(dn_array
);
5476 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5477 cg
->client_cert_data
);
5479 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5480 "returned %d.", (int)error
));
5483 httpFreeCredentials(names
);
5487 case errSSLUnknownRootCert
:
5488 message
= _("Unable to establish a secure connection to host "
5489 "(untrusted certificate).");
5492 case errSSLNoRootCert
:
5493 message
= _("Unable to establish a secure connection to host "
5494 "(self-signed certificate).");
5497 case errSSLCertExpired
:
5498 message
= _("Unable to establish a secure connection to host "
5499 "(expired certificate).");
5502 case errSSLCertNotYetValid
:
5503 message
= _("Unable to establish a secure connection to host "
5504 "(certificate not yet valid).");
5507 case errSSLHostNameMismatch
:
5508 message
= _("Unable to establish a secure connection to host "
5509 "(host name mismatch).");
5512 case errSSLXCertChainInvalid
:
5513 message
= _("Unable to establish a secure connection to host "
5514 "(certificate chain invalid).");
5517 case errSSLConnectionRefused
:
5518 message
= _("Unable to establish a secure connection to host "
5519 "(peer dropped connection before responding).");
5530 http
->error
= error
;
5531 http
->status
= HTTP_STATUS_ERROR
;
5532 errno
= ECONNREFUSED
;
5534 CFRelease(http
->tls
);
5538 * If an error string wasn't set by the callbacks use a generic one...
5542 #ifdef HAVE_CSSMERRORSTRING
5543 message
= cssmErrorString(error
);
5545 message
= _("Unable to establish a secure connection to host.");
5546 #endif /* HAVE_CSSMERRORSTRING */
5548 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5553 # elif defined(HAVE_SSPISSL)
5554 http
->tls
= _sspiAlloc();
5558 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5562 http
->tls
->sock
= http
->fd
;
5563 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5564 GetUserName(username
, &dwSize
);
5565 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5566 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5568 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5571 _sspiFree(http
->tls_credentials
);
5572 http
->tls_credentials
= NULL
;
5575 http
->status
= HTTP_STATUS_ERROR
;
5577 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
5578 _("Unable to establish a secure connection to host."), 1);
5583 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
5584 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5586 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5588 _sspiFree(http
->tls_credentials
);
5589 http
->tls_credentials
= NULL
;
5592 http
->status
= HTTP_STATUS_ERROR
;
5594 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
5595 _("Unable to establish a secure connection to host."), 1);
5599 # endif /* HAVE_CDSASSL */
5606 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5610 http_shutdown_ssl(http_t
*http
) /* I - HTTP connection */
5613 SSL_CTX
*context
; /* Context for encryption */
5615 context
= SSL_get_SSL_CTX(http
->tls
);
5617 SSL_shutdown(http
->tls
);
5618 SSL_CTX_free(context
);
5619 SSL_free(http
->tls
);
5621 # elif defined(HAVE_GNUTLS)
5622 gnutls_certificate_client_credentials
*credentials
;
5623 /* TLS credentials */
5625 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5627 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5628 gnutls_deinit(http
->tls
);
5629 gnutls_certificate_free_credentials(*credentials
);
5632 # elif defined(HAVE_CDSASSL)
5633 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5636 CFRelease(http
->tls
);
5638 if (http
->tls_credentials
)
5639 CFRelease(http
->tls_credentials
);
5641 # elif defined(HAVE_SSPISSL)
5642 _sspiFree(http
->tls_credentials
);
5643 # endif /* HAVE_LIBSSL */
5646 http
->tls_credentials
= NULL
;
5648 #endif /* HAVE_SSL */
5653 * 'http_upgrade()' - Force upgrade to TLS encryption.
5656 static int /* O - Status of connection */
5657 http_upgrade(http_t
*http
) /* I - HTTP connection */
5659 int ret
; /* Return value */
5660 http_t myhttp
; /* Local copy of HTTP data */
5663 DEBUG_printf(("7http_upgrade(%p)", http
));
5666 * Flush the connection to make sure any previous "Upgrade" message
5673 * Copy the HTTP data to a local variable so we can do the OPTIONS
5674 * request without interfering with the existing request data...
5677 memcpy(&myhttp
, http
, sizeof(myhttp
));
5680 * Send an OPTIONS request to the server, requiring SSL or TLS
5681 * encryption on the link...
5684 http
->tls_upgrade
= 1;
5685 http
->field_authorization
= NULL
; /* Don't free the auth string */
5687 httpClearFields(http
);
5688 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5689 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5691 if ((ret
= httpOptions(http
, "*")) == 0)
5694 * Wait for the secure connection...
5697 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
5701 * Restore the HTTP request data...
5704 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5705 http
->data_encoding
= myhttp
.data_encoding
;
5706 http
->data_remaining
= myhttp
.data_remaining
;
5707 http
->_data_remaining
= myhttp
._data_remaining
;
5708 http
->expect
= myhttp
.expect
;
5709 http
->field_authorization
= myhttp
.field_authorization
;
5710 http
->digest_tries
= myhttp
.digest_tries
;
5711 http
->tls_upgrade
= 0;
5714 * See if we actually went secure...
5720 * Server does not support HTTP upgrade...
5723 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5725 httpAddrClose(NULL
, http
->fd
);
5734 #endif /* HAVE_SSL */
5738 * 'http_write()' - Write a buffer to a HTTP connection.
5741 static ssize_t
/* O - Number of bytes written */
5742 http_write(http_t
*http
, /* I - HTTP connection */
5743 const char *buffer
, /* I - Buffer for data */
5744 size_t length
) /* I - Number of bytes to write */
5746 ssize_t tbytes
, /* Total bytes sent */
5747 bytes
; /* Bytes sent */
5750 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
5751 buffer
, CUPS_LLCAST length
));
5757 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5759 if (http
->timeout_cb
)
5762 struct pollfd pfd
; /* Polled file descriptor */
5764 fd_set output_set
; /* Output ready for write? */
5765 struct timeval timeout
; /* Timeout value */
5766 #endif /* HAVE_POLL */
5767 int nfds
; /* Result from select()/poll() */
5773 pfd
.events
= POLLOUT
;
5775 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5776 (errno
== EINTR
|| errno
== EAGAIN
))
5782 FD_ZERO(&output_set
);
5783 FD_SET(http
->fd
, &output_set
);
5785 timeout
.tv_sec
= http
->wait_value
/ 1000;
5786 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5788 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5791 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5792 WSAGetLastError() == WSAEWOULDBLOCK
));
5794 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5796 #endif /* HAVE_POLL */
5800 http
->error
= errno
;
5803 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5806 http
->error
= WSAEWOULDBLOCK
;
5808 http
->error
= EWOULDBLOCK
;
5818 bytes
= http_write_ssl(http
, buffer
, length
);
5820 #endif /* HAVE_SSL */
5821 bytes
= send(http
->fd
, buffer
, length
, 0);
5823 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
5824 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
5829 if (WSAGetLastError() == WSAEINTR
)
5831 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5833 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5836 http
->error
= WSAGetLastError();
5838 else if (WSAGetLastError() != http
->error
&&
5839 WSAGetLastError() != WSAECONNRESET
)
5841 http
->error
= WSAGetLastError();
5848 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5850 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5852 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5855 http
->error
= errno
;
5857 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5859 http
->error
= errno
;
5864 DEBUG_printf(("3http_write: error writing data (%s).",
5865 strerror(http
->error
)));
5876 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5879 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
5886 * 'http_write_chunk()' - Write a chunked buffer.
5889 static ssize_t
/* O - Number bytes written */
5890 http_write_chunk(http_t
*http
, /* I - HTTP connection */
5891 const char *buffer
, /* I - Buffer to write */
5892 size_t length
) /* I - Length of buffer */
5894 char header
[16]; /* Chunk header */
5895 ssize_t bytes
; /* Bytes written */
5898 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
5899 http
, buffer
, CUPS_LLCAST length
));
5902 * Write the chunk header, data, and trailer.
5905 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
5906 if (http_write(http
, header
, strlen(header
)) < 0)
5908 DEBUG_puts("8http_write_chunk: http_write of length failed.");
5912 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5914 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
5918 if (http_write(http
, "\r\n", 2) < 0)
5920 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
5930 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5933 static int /* O - Bytes written */
5934 http_write_ssl(http_t
*http
, /* I - HTTP connection */
5935 const char *buf
, /* I - Buffer holding data */
5936 int len
) /* I - Length of buffer */
5938 ssize_t result
; /* Return value */
5941 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5943 # if defined(HAVE_LIBSSL)
5944 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5946 # elif defined(HAVE_GNUTLS)
5947 result
= gnutls_record_send(http
->tls
, buf
, len
);
5949 if (result
< 0 && !errno
)
5952 * Convert GNU TLS error to errno value...
5957 case GNUTLS_E_INTERRUPTED
:
5961 case GNUTLS_E_AGAIN
:
5973 # elif defined(HAVE_CDSASSL)
5974 OSStatus error
; /* Error info */
5975 size_t processed
; /* Number of bytes processed */
5978 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5983 result
= (int)processed
;
5986 case errSSLWouldBlock
:
5988 result
= (int)processed
;
5996 case errSSLClosedGraceful
:
5999 result
= (int)processed
;
6007 # elif defined(HAVE_SSPISSL)
6008 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
6009 # endif /* HAVE_LIBSSL */
6011 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
6013 return ((int)result
);
6015 #endif /* HAVE_SSL */