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 http_field_t
http_field(const char *name
);
58 static ssize_t
http_read(http_t
*http
, char *buffer
, size_t length
);
59 static ssize_t
http_read_buffered(http_t
*http
, char *buffer
, size_t length
);
60 static ssize_t
http_read_chunk(http_t
*http
, char *buffer
, size_t length
);
61 static int http_send(http_t
*http
, http_state_t request
,
63 static ssize_t
http_write(http_t
*http
, const char *buffer
,
65 static ssize_t
http_write_chunk(http_t
*http
, const char *buffer
,
68 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
70 static int http_set_credentials(http_t
*http
);
71 # endif /* HAVE_CDSASSL */
73 static off_t
http_set_length(http_t
*http
);
74 static void http_set_timeout(int fd
, double timeout
);
75 static void http_set_wait(http_t
*http
);
77 static const char *http_state_string(http_state_t state
);
80 static int http_setup_ssl(http_t
*http
);
81 static void http_shutdown_ssl(http_t
*http
);
82 static int http_upgrade(http_t
*http
);
83 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
91 static const char * const http_fields
[] =
108 "If-Unmodified-since",
126 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
128 * BIO methods for OpenSSL...
131 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
132 static int http_bio_read(BIO
*h
, char *buf
, int size
);
133 static int http_bio_puts(BIO
*h
, const char *str
);
134 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
135 static int http_bio_new(BIO
*h
);
136 static int http_bio_free(BIO
*data
);
138 static BIO_METHOD http_bio_methods
=
145 NULL
, /* http_bio_gets, */
151 #endif /* HAVE_SSL && HAVE_LIBSSL */
155 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
156 * specified listening socket.
158 * @since CUPS 1.7/OS X 10.9@
161 http_t
* /* O - HTTP connection or @code NULL@ */
162 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
163 int blocking
) /* I - 1 if the connection should be
164 blocking, 0 otherwise */
166 http_t
*http
; /* HTTP connection */
167 http_addrlist_t addrlist
; /* Dummy address list */
168 socklen_t addrlen
; /* Length of address */
169 int val
; /* Socket option value */
173 * Range check input...
180 * Create the client connection...
183 memset(&addrlist
, 0, sizeof(addrlist
));
185 if ((http
= http_create(NULL
, 0, &addrlist
, AF_UNSPEC
,
186 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
187 _HTTP_MODE_SERVER
)) == NULL
)
191 * Accept the client and get the remote address...
194 addrlen
= sizeof(http_addr_t
);
196 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
199 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
205 httpAddrString(&(http
->addrlist
->addr
), http
->hostname
,
206 sizeof(http
->hostname
));
210 * Disable SIGPIPE for this socket.
214 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
215 #endif /* SO_NOSIGPIPE */
218 * Using TCP_NODELAY improves responsiveness, especially on systems
219 * with a slow loopback interface. Since we write large buffers
220 * when sending print files and requests, there shouldn't be any
221 * performance penalty for this...
225 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
229 * Close this socket when starting another process...
232 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
233 #endif /* FD_CLOEXEC */
240 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
242 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
244 * @since CUPS 1.5/OS X 10.7@
247 int /* O - 0 on success, -1 on error */
249 cups_array_t
*credentials
, /* I - Credentials array */
250 const void *data
, /* I - PEM-encoded X.509 data */
251 size_t datalen
) /* I - Length of data */
253 http_credential_t
*credential
; /* Credential data */
256 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
258 credential
->datalen
= datalen
;
260 if ((credential
->data
= malloc(datalen
)) != NULL
)
262 memcpy(credential
->data
, data
, datalen
);
263 cupsArrayAdd(credentials
, credential
);
274 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
276 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
279 BIO_METHOD
* /* O - BIO methods for OpenSSL */
280 _httpBIOMethods(void)
282 return (&http_bio_methods
);
284 #endif /* HAVE_SSL && HAVE_LIBSSL */
288 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
292 httpBlocking(http_t
*http
, /* I - Connection to server */
293 int b
) /* I - 1 = blocking, 0 = non-blocking */
304 * 'httpCheck()' - Check to see if there is a pending response from the server.
307 int /* O - 0 = no data, 1 = data available */
308 httpCheck(http_t
*http
) /* I - Connection to server */
310 return (httpWait(http
, 0));
315 * 'httpClearCookie()' - Clear the cookie value(s).
317 * @since CUPS 1.1.19/OS X 10.3@
321 httpClearCookie(http_t
*http
) /* I - Connection to server */
335 * 'httpClearFields()' - Clear HTTP request fields.
339 httpClearFields(http_t
*http
) /* I - Connection to server */
341 DEBUG_printf(("httpClearFields(http=%p)", http
));
345 memset(http
->fields
, 0, sizeof(http
->fields
));
347 if (http
->mode
== _HTTP_MODE_CLIENT
)
349 if (http
->hostname
[0] == '/')
350 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
352 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
355 if (http
->field_authorization
)
357 free(http
->field_authorization
);
358 http
->field_authorization
= NULL
;
361 if (http
->accept_encoding
)
363 _cupsStrFree(http
->accept_encoding
);
364 http
->accept_encoding
= NULL
;
369 _cupsStrFree(http
->allow
);
375 _cupsStrFree(http
->server
);
379 http
->expect
= (http_status_t
)0;
385 * 'httpClose()' - Close an HTTP connection.
389 httpClose(http_t
*http
) /* I - Connection to server */
392 OM_uint32 minor_status
; /* Minor status code */
393 #endif /* HAVE_GSSAPI */
396 DEBUG_printf(("httpClose(http=%p)", http
));
399 * Range check input...
406 * Close any open connection...
409 _httpDisconnect(http
);
412 * Free memory used...
415 httpAddrFreeList(http
->addrlist
);
421 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
422 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
424 if (http
->gssname
!= GSS_C_NO_NAME
)
425 gss_release_name(&minor_status
, &http
->gssname
);
426 #endif /* HAVE_GSSAPI */
428 #ifdef HAVE_AUTHORIZATION_H
430 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
431 #endif /* HAVE_AUTHORIZATION_H */
433 httpClearFields(http
);
435 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
436 free(http
->authstring
);
443 * 'httpConnect()' - Connect to a HTTP server.
445 * This function is deprecated - use @link httpConnect2@ instead.
450 http_t
* /* O - New HTTP connection */
451 httpConnect(const char *host
, /* I - Host to connect to */
452 int port
) /* I - Port number */
454 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, HTTP_ENCRYPTION_IF_REQUESTED
,
460 * 'httpConnect2()' - Connect to a HTTP server.
462 * @since CUPS 1.7/OS X 10.9@
465 http_t
* /* O - New HTTP connection */
467 const char *host
, /* I - Host to connect to */
468 int port
, /* I - Port number */
469 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
470 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
471 http_encryption_t encryption
, /* I - Type of encryption to use */
472 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
473 int msec
, /* I - Connection timeout in milliseconds, 0 means don't connect */
474 int *cancel
) /* I - Pointer to "cancel" variable */
476 http_t
*http
; /* New HTTP connection */
479 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
480 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
481 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
484 * Create the HTTP structure...
487 if ((http
= http_create(host
, port
, addrlist
, family
, encryption
, blocking
,
488 _HTTP_MODE_CLIENT
)) == NULL
)
492 * Optionally connect to the remote system...
495 if (msec
== 0 || !httpReconnect2(http
, msec
, cancel
))
499 * Could not connect to any known address - bail out!
509 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
511 * This function is now deprecated. Please use the @link httpConnect2@ function
517 http_t
* /* O - New HTTP connection */
519 const char *host
, /* I - Host to connect to */
520 int port
, /* I - Port number */
521 http_encryption_t encryption
) /* I - Type of encryption to use */
523 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
524 host
, port
, encryption
));
526 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
532 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
535 * @since CUPS 1.5/OS X 10.7@
538 int /* O - Status of call (0 = success) */
540 http_t
*http
, /* I - Connection to server */
541 cups_array_t
**credentials
) /* O - Array of credentials */
544 # elif defined(HAVE_GNUTLS)
545 # elif defined(HAVE_CDSASSL)
546 OSStatus error
; /* Error code */
547 SecTrustRef peerTrust
; /* Peer trust reference */
548 CFIndex count
; /* Number of credentials */
549 SecCertificateRef secCert
; /* Certificate reference */
550 CFDataRef data
; /* Certificate data */
551 int i
; /* Looping var */
552 # elif defined(HAVE_SSPISSL)
553 # endif /* HAVE_LIBSSL */
559 if (!http
|| !http
->tls
|| !credentials
)
565 # elif defined(HAVE_GNUTLS)
568 # elif defined(HAVE_CDSASSL)
569 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
571 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
573 count
= SecTrustGetCertificateCount(peerTrust
);
575 for (i
= 0; i
< count
; i
++)
577 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
578 if ((data
= SecCertificateCopyData(secCert
)))
580 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
581 CFDataGetLength(data
));
587 CFRelease(peerTrust
);
592 # elif defined(HAVE_SSPISSL)
597 # endif /* HAVE_LIBSSL */
602 * '_httpCreateCredentials()' - Create credentials in the internal format.
605 http_tls_credentials_t
/* O - Internal credentials */
606 _httpCreateCredentials(
607 cups_array_t
*credentials
) /* I - Array of credentials */
615 # elif defined(HAVE_GNUTLS)
618 # elif defined(HAVE_CDSASSL)
619 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
620 SecCertificateRef secCert
; /* Certificate reference */
621 CFDataRef data
; /* Credential data reference */
622 http_credential_t
*credential
; /* Credential data */
625 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
626 cupsArrayCount(credentials
),
627 &kCFTypeArrayCallBacks
)) == NULL
)
630 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
632 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
634 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
635 credential
->datalen
)))
637 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
640 CFArrayAppendValue(peerCerts
, secCert
);
650 # elif defined(HAVE_SSPISSL)
655 # endif /* HAVE_LIBSSL */
660 * 'httpDelete()' - Send a DELETE request to the server.
663 int /* O - Status of call (0 = success) */
664 httpDelete(http_t
*http
, /* I - Connection to server */
665 const char *uri
) /* I - URI to delete */
667 return (http_send(http
, HTTP_STATE_DELETE
, uri
));
672 * '_httpDisconnect()' - Disconnect a HTTP connection.
676 _httpDisconnect(http_t
*http
) /* I - Connection to server */
680 http_shutdown_ssl(http
);
681 #endif /* HAVE_SSL */
684 closesocket(http
->fd
);
694 * 'httpEncryption()' - Set the required encryption on the link.
697 int /* O - -1 on error, 0 on success */
698 httpEncryption(http_t
*http
, /* I - Connection to server */
699 http_encryption_t e
) /* I - New encryption preference */
701 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
707 http
->encryption
= e
;
709 if ((http
->encryption
== HTTP_ENCRYPTION_ALWAYS
&& !http
->tls
) ||
710 (http
->encryption
== HTTP_ENCRYPTION_NEVER
&& http
->tls
))
711 return (httpReconnect2(http
, 30000, NULL
));
712 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
713 return (http_upgrade(http
));
717 if (e
== HTTP_ENCRYPTION_ALWAYS
|| e
== HTTP_ENCRYPTION_REQUIRED
)
721 #endif /* HAVE_SSL */
726 * 'httpError()' - Get the last error on a connection.
729 int /* O - Error code (errno) value */
730 httpError(http_t
*http
) /* I - Connection to server */
733 return (http
->error
);
740 * 'httpFlush()' - Flush data from a HTTP connection.
744 httpFlush(http_t
*http
) /* I - Connection to server */
746 char buffer
[8192]; /* Junk buffer */
747 int blocking
; /* To block or not to block */
748 http_state_t oldstate
; /* Old state */
751 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
752 http_state_string(http
->state
)));
755 * Nothing to do if we are in the "waiting" state...
758 if (http
->state
== HTTP_STATE_WAITING
)
762 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
765 blocking
= http
->blocking
;
769 * Read any data we can...
772 oldstate
= http
->state
;
773 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
776 * Restore blocking and reset the connection if we didn't get all of
777 * the remaining data...
780 http
->blocking
= blocking
;
782 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
786 * Didn't get the data back, so close the current connection.
791 http_content_coding_finish(http
);
792 #endif /* HAVE_LIBZ */
794 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
796 http
->state
= HTTP_STATE_WAITING
;
800 http_shutdown_ssl(http
);
801 #endif /* HAVE_SSL */
804 closesocket(http
->fd
);
815 * 'httpFlushWrite()' - Flush data in write buffer.
817 * @since CUPS 1.2/OS X 10.5@
820 int /* O - Bytes written or -1 on error */
821 httpFlushWrite(http_t
*http
) /* I - Connection to server */
823 int bytes
; /* Bytes written */
826 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
827 http
? http
->data_encoding
: -1));
829 if (!http
|| !http
->wused
)
831 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
832 "1httpFlushWrite: No connection.");
836 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
837 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
839 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
843 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
850 * '_httpFreeCredentials()' - Free internal credentials.
854 _httpFreeCredentials(
855 http_tls_credentials_t credentials
) /* I - Internal credentials */
863 #elif defined(HAVE_GNUTLS)
866 #elif defined(HAVE_CDSASSL)
867 CFRelease(credentials
);
869 #elif defined(HAVE_SSPISSL)
872 #endif /* HAVE_LIBSSL */
877 * 'httpFreeCredentials()' - Free an array of credentials.
882 cups_array_t
*credentials
) /* I - Array of credentials */
884 http_credential_t
*credential
; /* Credential */
887 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
889 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
891 cupsArrayRemove(credentials
, credential
);
892 free((void *)credential
->data
);
896 cupsArrayDelete(credentials
);
901 * 'httpGet()' - Send a GET request to the server.
904 int /* O - Status of call (0 = success) */
905 httpGet(http_t
*http
, /* I - Connection to server */
906 const char *uri
) /* I - URI to get */
908 return (http_send(http
, HTTP_STATE_GET
, uri
));
913 * 'httpGetAuthString()' - Get the current authorization string.
915 * The authorization string is set by cupsDoAuthentication() and
916 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
917 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
920 * @since CUPS 1.3/OS X 10.5@
923 char * /* O - Authorization string */
924 httpGetAuthString(http_t
*http
) /* I - Connection to server */
927 return (http
->authstring
);
934 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
936 * @since CUPS 1.2/OS X 10.5@
939 int /* O - 1 if blocking, 0 if non-blocking */
940 httpGetBlocking(http_t
*http
) /* I - Connection to server */
942 return (http
? http
->blocking
: 0);
947 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
948 * the client and server.
950 * This function uses the value of the Accepts-Encoding HTTP header and must be
951 * called after receiving a response from the server or a request from the
952 * client. The value returned can be use in subsequent requests (for clients)
953 * or in the response (for servers) in order to compress the content stream.
955 * @since CUPS 1.7/OS X 10.9@
958 const char * /* O - Content-Coding value or
959 @code NULL@ for the identity
961 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
964 if (http
&& http
->accept_encoding
)
966 int i
; /* Looping var */
967 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
968 *start
, /* Start of coding value */
969 *end
; /* End of coding value */
970 double qvalue
; /* "qvalue" for coding */
971 struct lconv
*loc
= localeconv(); /* Locale data */
972 static const char * const codings
[] =
973 { /* Supported content codings */
980 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
982 for (start
= temp
; *start
; start
= end
)
985 * Find the end of the coding name...
990 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
996 * Grab the qvalue as needed...
999 if (!strncmp(end
, ";q=", 3))
1000 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1003 * Skip past all attributes...
1007 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1013 while (*end
&& isspace(*end
& 255))
1017 * Check value if it matches something we support...
1023 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1024 if (!strcmp(start
, codings
[i
]))
1025 return (codings
[i
]);
1028 #endif /* HAVE_LIBZ */
1035 * 'httpGetCookie()' - Get any cookie data from the response.
1037 * @since CUPS 1.1.19/OS X 10.3@
1040 const char * /* O - Cookie data or NULL */
1041 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1043 return (http
? http
->cookie
: NULL
);
1048 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1050 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1051 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1053 * @since CUPS 1.7/OS X 10.9@
1056 http_status_t
/* O - Expect: status, if any */
1057 httpGetExpect(http_t
*http
) /* I - Connection to client */
1060 return (HTTP_STATUS_ERROR
);
1062 return (http
->expect
);
1067 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1069 * @since CUPS 1.2/OS X 10.5@
1072 int /* O - File descriptor or -1 if none */
1073 httpGetFd(http_t
*http
) /* I - Connection to server */
1075 return (http
? http
->fd
: -1);
1080 * 'httpGetField()' - Get a field value from a request/response.
1083 const char * /* O - Field value */
1084 httpGetField(http_t
*http
, /* I - Connection to server */
1085 http_field_t field
) /* I - Field to get */
1087 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1092 case HTTP_FIELD_ACCEPT_ENCODING
:
1093 return (http
->accept_encoding
);
1095 case HTTP_FIELD_ALLOW
:
1096 return (http
->allow
);
1098 case HTTP_FIELD_SERVER
:
1099 return (http
->server
);
1101 case HTTP_FIELD_AUTHORIZATION
:
1102 if (http
->field_authorization
)
1105 * Special case for WWW-Authenticate: as its contents can be
1106 * longer than HTTP_MAX_VALUE...
1109 return (http
->field_authorization
);
1113 return (http
->fields
[field
]);
1119 * 'httpGetLength()' - Get the amount of data remaining from the
1120 * content-length or transfer-encoding fields.
1122 * This function is deprecated and will not return lengths larger than
1123 * 2^31 - 1; use httpGetLength2() instead.
1128 int /* O - Content length */
1129 httpGetLength(http_t
*http
) /* I - Connection to server */
1132 * Get the read content length and return the 32-bit value.
1137 httpGetLength2(http
);
1139 return (http
->_data_remaining
);
1147 * 'httpGetLength2()' - Get the amount of data remaining from the
1148 * content-length or transfer-encoding fields.
1150 * This function returns the complete content length, even for
1151 * content larger than 2^31 - 1.
1153 * @since CUPS 1.2/OS X 10.5@
1156 off_t
/* O - Content length */
1157 httpGetLength2(http_t
*http
) /* I - Connection to server */
1159 off_t remaining
; /* Remaining length */
1162 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1163 http_state_string(http
->state
)));
1168 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1170 DEBUG_puts("4httpGetLength2: chunked request!");
1176 * The following is a hack for HTTP servers that don't send a
1177 * Content-Length or Transfer-Encoding field...
1179 * If there is no Content-Length then the connection must close
1180 * after the transfer is complete...
1183 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1186 * Default content length is 0 for errors and certain types of operations,
1187 * and 2^31-1 for other successful requests...
1190 if (http
->status
>= HTTP_STATUS_MULTIPLE_CHOICES
||
1191 http
->state
== HTTP_STATE_OPTIONS
||
1192 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1193 http
->state
== HTTP_STATE_HEAD
||
1194 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1195 http
->state
== HTTP_STATE_DELETE
||
1196 http
->state
== HTTP_STATE_TRACE
||
1197 http
->state
== HTTP_STATE_CONNECT
)
1200 remaining
= 2147483647;
1202 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1206 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1207 CUPS_LLCAST remaining
));
1215 * 'httpGets()' - Get a line of text from a HTTP connection.
1218 char * /* O - Line or NULL */
1219 httpGets(char *line
, /* I - Line to read into */
1220 int length
, /* I - Max length of buffer */
1221 http_t
*http
) /* I - Connection to server */
1223 char *lineptr
, /* Pointer into line */
1224 *lineend
, /* End of line */
1225 *bufptr
, /* Pointer into input buffer */
1226 *bufend
; /* Pointer to end of buffer */
1227 int bytes
, /* Number of bytes read */
1228 eol
; /* End-of-line? */
1231 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1233 if (!http
|| !line
|| length
<= 1)
1237 * Read a line from the buffer...
1242 lineend
= line
+ length
- 1;
1245 while (lineptr
< lineend
)
1248 * Pre-load the buffer as needed...
1257 while (http
->used
== 0)
1260 * No newline; see if there is more data to be read...
1263 while (!_httpWait(http
, http
->wait_value
, 1))
1265 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1268 DEBUG_puts("3httpGets: Timed out!");
1270 http
->error
= WSAETIMEDOUT
;
1272 http
->error
= ETIMEDOUT
;
1277 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1278 HTTP_MAX_BUFFER
- http
->used
);
1280 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1285 * Nope, can't get a line this time...
1289 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1291 if (WSAGetLastError() == WSAEINTR
)
1293 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1295 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1298 http
->error
= WSAGetLastError();
1300 else if (WSAGetLastError() != http
->error
)
1302 http
->error
= WSAGetLastError();
1307 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1311 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1313 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1315 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1318 http
->error
= errno
;
1320 else if (errno
!= http
->error
)
1322 http
->error
= errno
;
1329 else if (bytes
== 0)
1331 http
->error
= EPIPE
;
1337 * Yup, update the amount used...
1340 http
->used
+= bytes
;
1344 * Now copy as much of the current line as possible...
1347 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1348 lineptr
< lineend
&& bufptr
< bufend
;)
1350 if (*bufptr
== 0x0a)
1356 else if (*bufptr
== 0x0d)
1359 *lineptr
++ = *bufptr
++;
1362 http
->used
-= (int)(bufptr
- http
->buffer
);
1364 memmove(http
->buffer
, bufptr
, http
->used
);
1372 http
->activity
= time(NULL
);
1376 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1382 DEBUG_puts("3httpGets: No new line available!");
1389 * 'httpGetState()' - Get the current state of the HTTP request.
1392 http_state_t
/* O - HTTP state */
1393 httpGetState(http_t
*http
) /* I - Connection to server */
1395 return (http
? http
->state
: HTTP_STATE_ERROR
);
1400 * 'httpGetStatus()' - Get the status of the last HTTP request.
1402 * @since CUPS 1.2/OS X 10.5@
1405 http_status_t
/* O - HTTP status */
1406 httpGetStatus(http_t
*http
) /* I - Connection to server */
1408 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1413 * 'httpGetSubField()' - Get a sub-field value.
1418 char * /* O - Value or NULL */
1419 httpGetSubField(http_t
*http
, /* I - Connection to server */
1420 http_field_t field
, /* I - Field index */
1421 const char *name
, /* I - Name of sub-field */
1422 char *value
) /* O - Value string */
1424 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1429 * 'httpGetSubField2()' - Get a sub-field value.
1431 * @since CUPS 1.2/OS X 10.5@
1434 char * /* O - Value or NULL */
1435 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1436 http_field_t field
, /* I - Field index */
1437 const char *name
, /* I - Name of sub-field */
1438 char *value
, /* O - Value string */
1439 int valuelen
) /* I - Size of value buffer */
1441 const char *fptr
; /* Pointer into field */
1442 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1443 *ptr
, /* Pointer into string buffer */
1444 *end
; /* End of value buffer */
1446 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1447 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1449 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1450 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1453 end
= value
+ valuelen
- 1;
1455 for (fptr
= http
->fields
[field
]; *fptr
;)
1458 * Skip leading whitespace...
1461 while (_cups_isspace(*fptr
))
1471 * Get the sub-field name...
1475 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1476 ptr
< (temp
+ sizeof(temp
) - 1);
1481 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1484 * Skip trailing chars up to the '='...
1487 while (_cups_isspace(*fptr
))
1497 * Skip = and leading whitespace...
1502 while (_cups_isspace(*fptr
))
1508 * Read quoted string...
1511 for (ptr
= value
, fptr
++;
1512 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1517 while (*fptr
&& *fptr
!= '\"')
1526 * Read unquoted string...
1530 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1535 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1539 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1542 * See if this is the one...
1545 if (!strcmp(name
, temp
))
1547 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1554 DEBUG_puts("3httpGetSubField2: Returning NULL");
1561 * 'httpGetVersion()' - Get the HTTP version at the other end.
1564 http_version_t
/* O - Version number */
1565 httpGetVersion(http_t
*http
) /* I - Connection to server */
1567 return (http
? http
->version
: HTTP_VERSION_1_0
);
1572 * 'httpHead()' - Send a HEAD request to the server.
1575 int /* O - Status of call (0 = success) */
1576 httpHead(http_t
*http
, /* I - Connection to server */
1577 const char *uri
) /* I - URI for head */
1579 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1580 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1585 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1586 * default HTTP proxy (if any).
1590 httpInitialize(void)
1592 static int initialized
= 0; /* Have we been called before? */
1594 WSADATA winsockdata
; /* WinSock data */
1597 int i
; /* Looping var */
1598 unsigned char data
[1024]; /* Seed data */
1599 #endif /* HAVE_LIBSSL */
1605 _cupsGlobalUnlock();
1610 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1612 #elif !defined(SO_NOSIGPIPE)
1614 * Ignore SIGPIPE signals...
1618 sigset(SIGPIPE
, SIG_IGN
);
1620 # elif defined(HAVE_SIGACTION)
1621 struct sigaction action
; /* POSIX sigaction data */
1624 memset(&action
, 0, sizeof(action
));
1625 action
.sa_handler
= SIG_IGN
;
1626 sigaction(SIGPIPE
, &action
, NULL
);
1629 signal(SIGPIPE
, SIG_IGN
);
1630 # endif /* !SO_NOSIGPIPE */
1635 * Initialize GNU TLS...
1638 gnutls_global_init();
1640 #elif defined(HAVE_LIBSSL)
1642 * Initialize OpenSSL...
1645 SSL_load_error_strings();
1649 * Using the current time is a dubious random seed, but on some systems
1650 * it is the best we can do (on others, this seed isn't even used...)
1653 CUPS_SRAND(time(NULL
));
1655 for (i
= 0; i
< sizeof(data
); i
++)
1656 data
[i
] = CUPS_RAND();
1658 RAND_seed(data
, sizeof(data
));
1659 #endif /* HAVE_GNUTLS */
1662 _cupsGlobalUnlock();
1667 * 'httpOptions()' - Send an OPTIONS request to the server.
1670 int /* O - Status of call (0 = success) */
1671 httpOptions(http_t
*http
, /* I - Connection to server */
1672 const char *uri
) /* I - URI for options */
1674 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1679 * 'httpPeek()' - Peek at data from a HTTP connection.
1681 * This function copies available data from the given HTTP connection, reading
1682 * a buffer as needed. The data is still available for reading using
1683 * @link httpRead@ or @link httpRead2@.
1685 * For non-blocking connections the usual timeouts apply.
1687 * @since CUPS 1.7/OS X 10.9@
1690 ssize_t
/* O - Number of bytes copied */
1691 httpPeek(http_t
*http
, /* I - Connection to server */
1692 char *buffer
, /* I - Buffer for data */
1693 size_t length
) /* I - Maximum number of bytes */
1695 ssize_t bytes
; /* Bytes read */
1696 char len
[32]; /* Length string */
1699 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1700 http
, buffer
, CUPS_LLCAST length
));
1702 if (http
== NULL
|| buffer
== NULL
)
1705 http
->activity
= time(NULL
);
1711 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1712 http
->data_remaining
<= 0)
1714 DEBUG_puts("2httpPeek: Getting chunk length...");
1716 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1718 DEBUG_puts("1httpPeek: Could not get length!");
1724 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1725 if (!httpGets(len
, sizeof(len
), http
))
1727 DEBUG_puts("1httpPeek: Could not get chunk length.");
1732 http
->data_remaining
= strtoll(len
, NULL
, 16);
1734 if (http
->data_remaining
< 0)
1736 DEBUG_puts("1httpPeek: Negative chunk length!");
1741 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1742 CUPS_LLCAST http
->data_remaining
));
1744 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1747 * A zero-length chunk ends a transfer; unless we are reading POST
1753 http_content_coding_finish(http
);
1754 #endif /* HAVE_LIBZ */
1756 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1757 httpGets(len
, sizeof(len
), http
);
1759 if (http
->state
== HTTP_STATE_POST_RECV
)
1762 http
->state
= HTTP_STATE_STATUS
;
1764 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1765 http_state_string(http
->state
)));
1768 * Prevent future reads for this request...
1771 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1775 else if (length
> (size_t)http
->data_remaining
)
1776 length
= (size_t)http
->data_remaining
;
1779 if (http
->used
== 0 &&
1780 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1782 if (http
->used
== 0)
1783 #endif /* HAVE_LIBZ */
1786 * Buffer small reads for better performance...
1789 ssize_t buflen
; /* Length of read for buffer */
1791 if (!http
->blocking
)
1793 while (!httpWait(http
, http
->wait_value
))
1795 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1802 if (http
->data_remaining
> sizeof(http
->buffer
))
1803 buflen
= sizeof(http
->buffer
);
1805 buflen
= http
->data_remaining
;
1807 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1808 bytes
= http_read(http
, http
->buffer
, buflen
);
1810 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1811 CUPS_LLCAST bytes
));
1815 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1825 # ifdef HAVE_INFLATECOPY
1826 int zerr
; /* Decompressor error */
1827 z_stream stream
; /* Copy of decompressor stream */
1829 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1831 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1832 /* Number of bytes to copy */
1834 if (http
->stream
.avail_in
> 0 &&
1835 http
->stream
.next_in
> http
->dbuffer
)
1836 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1838 http
->stream
.next_in
= http
->dbuffer
;
1840 if (buflen
> http
->data_remaining
)
1841 buflen
= http
->data_remaining
;
1843 if (buflen
> http
->used
)
1844 buflen
= http
->used
;
1846 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1847 "decompression buffer.", (int)buflen
));
1849 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
1850 http
->stream
.avail_in
+= buflen
;
1851 http
->used
-= buflen
;
1852 http
->data_remaining
-= buflen
;
1855 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
1858 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
1859 (int)http
->stream
.avail_in
));
1861 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
1863 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
1864 http
->error
= ENOMEM
;
1868 stream
.next_out
= (Bytef
*)buffer
;
1869 stream
.avail_out
= length
;
1871 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
1872 inflateEnd(&stream
);
1876 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
1878 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
1879 http
->stream
.avail_in
);
1886 bytes
= length
- http
->stream
.avail_out
;
1889 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
1890 "work with compressed streams.");
1892 # endif /* HAVE_INFLATECOPY */
1895 #endif /* HAVE_LIBZ */
1898 if (length
> (size_t)http
->used
)
1899 length
= (size_t)http
->used
;
1901 bytes
= (ssize_t
)length
;
1903 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
1906 memcpy(buffer
, http
->buffer
, length
);
1914 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1917 http
->error
= WSAGetLastError();
1919 if (errno
== EINTR
|| errno
== EAGAIN
)
1922 http
->error
= errno
;
1925 else if (bytes
== 0)
1927 http
->error
= EPIPE
;
1934 /* For OS X 10.8 and earlier */
1935 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
1936 { return (httpPeek(http
, buffer
, length
)); }
1940 * 'httpPost()' - Send a POST request to the server.
1943 int /* O - Status of call (0 = success) */
1944 httpPost(http_t
*http
, /* I - Connection to server */
1945 const char *uri
) /* I - URI for post */
1947 return (http_send(http
, HTTP_STATE_POST
, uri
));
1952 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1957 int /* O - Number of bytes written */
1958 httpPrintf(http_t
*http
, /* I - Connection to server */
1959 const char *format
, /* I - printf-style format string */
1960 ...) /* I - Additional args as needed */
1962 int bytes
; /* Number of bytes to write */
1963 char buf
[16384]; /* Buffer for formatted string */
1964 va_list ap
; /* Variable argument pointer */
1967 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1969 va_start(ap
, format
);
1970 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1973 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
1975 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
1976 return (httpWrite2(http
, buf
, bytes
));
1981 DEBUG_puts("4httpPrintf: flushing existing data...");
1983 if (httpFlushWrite(http
) < 0)
1987 return (http_write(http
, buf
, bytes
));
1993 * 'httpPut()' - Send a PUT request to the server.
1996 int /* O - Status of call (0 = success) */
1997 httpPut(http_t
*http
, /* I - Connection to server */
1998 const char *uri
) /* I - URI to put */
2000 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2001 return (http_send(http
, HTTP_STATE_PUT
, uri
));
2006 * 'httpRead()' - Read data from a HTTP connection.
2008 * This function is deprecated. Use the httpRead2() function which can
2009 * read more than 2GB of data.
2014 int /* O - Number of bytes read */
2015 httpRead(http_t
*http
, /* I - Connection to server */
2016 char *buffer
, /* I - Buffer for data */
2017 int length
) /* I - Maximum number of bytes */
2019 return ((int)httpRead2(http
, buffer
, length
));
2024 * 'httpRead2()' - Read data from a HTTP connection.
2026 * @since CUPS 1.2/OS X 10.5@
2029 ssize_t
/* O - Number of bytes read */
2030 httpRead2(http_t
*http
, /* I - Connection to server */
2031 char *buffer
, /* I - Buffer for data */
2032 size_t length
) /* I - Maximum number of bytes */
2034 ssize_t bytes
; /* Bytes read */
2038 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2039 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
2040 http
, buffer
, CUPS_LLCAST length
,
2042 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2044 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2045 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
2046 http
, buffer
, CUPS_LLCAST length
,
2047 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2048 #endif /* HAVE_LIBZ */
2050 if (http
== NULL
|| buffer
== NULL
)
2053 http
->activity
= time(NULL
);
2064 if (http
->stream
.avail_in
> 0)
2066 int zerr
; /* Decompressor error */
2068 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2069 (int)http
->stream
.avail_in
, (int)length
));
2071 http
->stream
.next_out
= (Bytef
*)buffer
;
2072 http
->stream
.avail_out
= length
;
2074 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2076 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2078 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2079 http
->stream
.avail_in
);
2086 bytes
= length
- http
->stream
.avail_out
;
2088 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2089 http
->stream
.avail_in
, http
->stream
.avail_out
,
2097 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2098 /* Additional bytes for buffer */
2102 if (http
->stream
.avail_in
> 0 &&
2103 http
->stream
.next_in
> http
->dbuffer
)
2104 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2106 http
->stream
.next_in
= http
->dbuffer
;
2108 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2109 "decompression buffer.", (int)buflen
));
2111 if (http
->data_remaining
> 0)
2113 if (buflen
> http
->data_remaining
)
2114 buflen
= http
->data_remaining
;
2116 bytes
= http_read_buffered(http
,
2117 (char *)http
->dbuffer
+
2118 http
->stream
.avail_in
, buflen
);
2120 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2121 bytes
= http_read_chunk(http
,
2122 (char *)http
->dbuffer
+
2123 http
->stream
.avail_in
, buflen
);
2129 else if (bytes
== 0)
2132 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2133 "decompression buffer.", CUPS_LLCAST bytes
));
2135 http
->data_remaining
-= bytes
;
2136 http
->stream
.avail_in
+= bytes
;
2138 if (http
->data_remaining
<= 0 &&
2139 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2142 * Read the trailing blank line now...
2145 char len
[32]; /* Length string */
2147 httpGets(len
, sizeof(len
), http
);
2159 #endif /* HAVE_LIBZ */
2160 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2162 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2164 http
->data_remaining
-= bytes
;
2166 if (http
->data_remaining
<= 0)
2169 * Read the trailing blank line now...
2172 char len
[32]; /* Length string */
2174 httpGets(len
, sizeof(len
), http
);
2178 else if (http
->data_remaining
<= 0)
2181 * No more data to read...
2188 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2191 if (length
> (size_t)http
->data_remaining
)
2192 length
= (size_t)http
->data_remaining
;
2194 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2196 http
->data_remaining
-= bytes
;
2198 if (http
->data_remaining
<= 0 &&
2199 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2202 * Read the trailing blank line now...
2205 char len
[32]; /* Length string */
2207 httpGets(len
, sizeof(len
), http
);
2214 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2215 #endif /* HAVE_LIBZ */
2216 ((http
->data_remaining
<= 0 &&
2217 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2218 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2222 http_content_coding_finish(http
);
2223 #endif /* HAVE_LIBZ */
2225 if (http
->state
== HTTP_STATE_POST_RECV
)
2227 else if (http
->state
== HTTP_STATE_GET_SEND
||
2228 http
->state
== HTTP_STATE_POST_SEND
)
2229 http
->state
= HTTP_STATE_WAITING
;
2231 http
->state
= HTTP_STATE_STATUS
;
2233 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2234 http_state_string(http
->state
)));
2241 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2243 * '_httpReadCDSA()' - Read function for the CDSA library.
2246 OSStatus
/* O - -1 on error, 0 on success */
2248 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2249 void *data
, /* I - Data buffer */
2250 size_t *dataLength
) /* IO - Number of bytes */
2252 OSStatus result
; /* Return value */
2253 ssize_t bytes
; /* Number of bytes read */
2254 http_t
*http
; /* HTTP connection */
2257 http
= (http_t
*)connection
;
2259 if (!http
->blocking
)
2262 * Make sure we have data before we read...
2265 while (!_httpWait(http
, http
->wait_value
, 0))
2267 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2270 http
->error
= ETIMEDOUT
;
2277 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2279 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2281 if (bytes
== *dataLength
)
2287 *dataLength
= bytes
;
2288 result
= errSSLWouldBlock
;
2295 result
= errSSLClosedGraceful
;
2296 else if (errno
== EAGAIN
)
2297 result
= errSSLWouldBlock
;
2299 result
= errSSLClosedAbort
;
2304 #endif /* HAVE_SSL && HAVE_CDSASSL */
2307 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2309 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2312 ssize_t
/* O - Number of bytes read or -1 on error */
2314 gnutls_transport_ptr ptr
, /* I - Connection to server */
2315 void *data
, /* I - Buffer */
2316 size_t length
) /* I - Number of bytes to read */
2318 http_t
*http
; /* HTTP connection */
2319 ssize_t bytes
; /* Bytes read */
2322 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2324 http
= (http_t
*)ptr
;
2326 if (!http
->blocking
)
2329 * Make sure we have data before we read...
2332 while (!_httpWait(http
, http
->wait_value
, 0))
2334 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2337 http
->error
= ETIMEDOUT
;
2342 bytes
= recv(http
->fd
, data
, length
, 0);
2343 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2346 #endif /* HAVE_SSL && HAVE_GNUTLS */
2350 * 'httpReadRequest()' - Read a HTTP request from a connection.
2352 * @since CUPS 1.7/OS X 10.9@
2355 http_state_t
/* O - New state of connection */
2356 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2357 char *uri
, /* I - URI buffer */
2358 size_t urilen
) /* I - Size of URI buffer */
2360 char line
[4096], /* HTTP request line */
2361 *req_method
, /* HTTP request method */
2362 *req_uri
, /* HTTP request URI */
2363 *req_version
; /* HTTP request version number string */
2367 * Range check input...
2370 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2371 http
, uri
, CUPS_LLCAST urilen
));
2376 if (!http
|| !uri
|| urilen
< 1)
2378 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2379 return (HTTP_STATE_ERROR
);
2381 else if (http
->state
!= HTTP_STATE_WAITING
)
2383 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2384 http_state_string(http
->state
)));
2385 return (HTTP_STATE_ERROR
);
2392 httpClearFields(http
);
2394 http
->activity
= time(NULL
);
2395 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2396 http
->data_remaining
= 0;
2397 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2398 http
->status
= HTTP_STATUS_OK
;
2399 http
->version
= HTTP_VERSION_1_1
;
2402 * Read a line from the socket...
2405 if (!httpGets(line
, sizeof(line
), http
))
2407 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2408 return (HTTP_STATE_ERROR
);
2413 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2414 return (HTTP_STATE_WAITING
);
2417 DEBUG_printf(("1httpReadRequest: %s", line
));
2426 while (*req_uri
&& !isspace(*req_uri
& 255))
2431 DEBUG_puts("1httpReadRequest: No request URI.");
2432 return (HTTP_STATE_ERROR
);
2437 while (*req_uri
&& isspace(*req_uri
& 255))
2440 req_version
= req_uri
;
2442 while (*req_version
&& !isspace(*req_version
& 255))
2447 DEBUG_puts("1httpReadRequest: No request protocol version.");
2448 return (HTTP_STATE_ERROR
);
2451 *req_version
++ = '\0';
2453 while (*req_version
&& isspace(*req_version
& 255))
2460 if (!strcmp(req_method
, "OPTIONS"))
2461 http
->state
= HTTP_STATE_OPTIONS
;
2462 else if (!strcmp(req_method
, "GET"))
2463 http
->state
= HTTP_STATE_GET
;
2464 else if (!strcmp(req_method
, "HEAD"))
2465 http
->state
= HTTP_STATE_HEAD
;
2466 else if (!strcmp(req_method
, "POST"))
2467 http
->state
= HTTP_STATE_POST
;
2468 else if (!strcmp(req_method
, "PUT"))
2469 http
->state
= HTTP_STATE_PUT
;
2470 else if (!strcmp(req_method
, "DELETE"))
2471 http
->state
= HTTP_STATE_DELETE
;
2472 else if (!strcmp(req_method
, "TRACE"))
2473 http
->state
= HTTP_STATE_TRACE
;
2474 else if (!strcmp(req_method
, "CONNECT"))
2475 http
->state
= HTTP_STATE_CONNECT
;
2478 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2479 return (HTTP_STATE_UNKNOWN_METHOD
);
2482 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2483 http_state_string(http
->state
)));
2485 if (!strcmp(req_version
, "HTTP/1.0"))
2487 http
->version
= HTTP_VERSION_1_0
;
2488 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2490 else if (!strcmp(req_version
, "HTTP/1.1"))
2492 http
->version
= HTTP_VERSION_1_1
;
2493 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2497 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2498 return (HTTP_STATE_UNKNOWN_VERSION
);
2501 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2502 strlcpy(uri
, req_uri
, urilen
);
2504 return (http
->state
);
2509 * 'httpReconnect()' - Reconnect to a HTTP server.
2511 * This function is deprecated. Please use the @link httpReconnect2@ function
2517 int /* O - 0 on success, non-zero on failure */
2518 httpReconnect(http_t
*http
) /* I - Connection to server */
2520 DEBUG_printf(("httpReconnect(http=%p)", http
));
2522 return (httpReconnect2(http
, 30000, NULL
));
2527 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2531 int /* O - 0 on success, non-zero on failure */
2532 httpReconnect2(http_t
*http
, /* I - Connection to server */
2533 int msec
, /* I - Timeout in milliseconds */
2534 int *cancel
) /* I - Pointer to "cancel" variable */
2536 http_addrlist_t
*addr
; /* Connected address */
2538 http_addrlist_t
*current
; /* Current address */
2539 char temp
[256]; /* Temporary address string */
2543 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2548 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2555 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2556 http_shutdown_ssl(http
);
2558 #endif /* HAVE_SSL */
2561 * Close any previously open socket...
2566 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2569 closesocket(http
->fd
);
2578 * Reset all state (except fields, which may be reused)...
2581 http
->state
= HTTP_STATE_WAITING
;
2582 http
->version
= HTTP_VERSION_1_1
;
2583 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2584 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2585 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2586 http
->_data_remaining
= 0;
2588 http
->data_remaining
= 0;
2589 http
->hostaddr
= NULL
;
2593 * Connect to the server...
2597 for (current
= http
->addrlist
; current
; current
= current
->next
)
2598 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2599 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2600 httpAddrPort(&(current
->addr
))));
2603 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2607 * Unable to connect...
2611 http
->error
= WSAGetLastError();
2613 http
->error
= errno
;
2615 http
->status
= HTTP_STATUS_ERROR
;
2617 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2618 strerror(http
->error
)));
2623 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2625 if (http
->timeout_value
> 0)
2626 http_set_timeout(http
->fd
, http
->timeout_value
);
2628 http
->hostaddr
= &(addr
->addr
);
2632 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2635 * Always do encryption via SSL.
2638 if (http_setup_ssl(http
) != 0)
2641 closesocket(http
->fd
);
2649 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2650 return (http_upgrade(http
));
2651 #endif /* HAVE_SSL */
2653 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2654 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2655 httpAddrPort(http
->hostaddr
)));
2662 * 'httpSetAuthString()' - Set the current authorization string.
2664 * This function just stores a copy of the current authorization string in
2665 * the HTTP connection object. You must still call httpSetField() to set
2666 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2667 * httpHead(), httpOptions(), httpPost, or httpPut().
2669 * @since CUPS 1.3/OS X 10.5@
2673 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2674 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2675 const char *data
) /* I - Auth data (NULL for none) */
2678 * Range check input...
2684 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2685 free(http
->authstring
);
2687 http
->authstring
= http
->_authstring
;
2692 * Set the current authorization string...
2695 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2698 if (len
> (int)sizeof(http
->_authstring
))
2700 if ((temp
= malloc(len
)) == NULL
)
2701 len
= sizeof(http
->_authstring
);
2703 http
->authstring
= temp
;
2707 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2709 strlcpy(http
->authstring
, scheme
, len
);
2714 * Clear the current authorization string...
2717 http
->_authstring
[0] = '\0';
2723 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2726 * @since CUPS 1.5/OS X 10.7@
2729 int /* O - Status of call (0 = success) */
2730 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2731 cups_array_t
*credentials
) /* I - Array of credentials */
2733 if (!http
|| cupsArrayCount(credentials
) < 1)
2736 _httpFreeCredentials(http
->tls_credentials
);
2738 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2740 return (http
->tls_credentials
? 0 : -1);
2745 * 'httpSetCookie()' - Set the cookie value(s).
2747 * @since CUPS 1.1.19/OS X 10.3@
2751 httpSetCookie(http_t
*http
, /* I - Connection */
2752 const char *cookie
) /* I - Cookie string */
2761 http
->cookie
= strdup(cookie
);
2763 http
->cookie
= NULL
;
2768 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2770 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2771 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2773 * @since CUPS 1.7/OS X 10.9@
2777 httpSetDefaultField(http_t
*http
, /* I - Connection to server */
2778 http_field_t field
, /* I - Field index */
2779 const char *value
)/* I - Value */
2781 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2782 http
, field
, http_fields
[field
], value
));
2789 case HTTP_FIELD_ACCEPT_ENCODING
:
2790 if (http
->default_accept_encoding
)
2791 _cupsStrFree(http
->default_accept_encoding
);
2793 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2796 case HTTP_FIELD_SERVER
:
2797 if (http
->default_server
)
2798 _cupsStrFree(http
->default_server
);
2800 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2803 case HTTP_FIELD_USER_AGENT
:
2804 if (http
->default_user_agent
)
2805 _cupsStrFree(http
->default_user_agent
);
2807 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2811 DEBUG_puts("1httpSetDefaultField: Ignored.");
2818 * 'httpSetExpect()' - Set the Expect: header in a request.
2820 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2823 * @since CUPS 1.2/OS X 10.5@
2827 httpSetExpect(http_t
*http
, /* I - Connection to server */
2828 http_status_t expect
) /* I - HTTP status to expect
2829 (@code HTTP_STATUS_CONTINUE@) */
2831 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2834 http
->expect
= expect
;
2839 * 'httpSetField()' - Set the value of an HTTP header.
2843 httpSetField(http_t
*http
, /* I - Connection to server */
2844 http_field_t field
, /* I - Field index */
2845 const char *value
) /* I - Value */
2847 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2848 field
, http_fields
[field
], value
));
2851 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2852 field
>= HTTP_FIELD_MAX
||
2858 case HTTP_FIELD_ACCEPT_ENCODING
:
2859 if (http
->accept_encoding
)
2860 _cupsStrFree(http
->accept_encoding
);
2862 http
->accept_encoding
= _cupsStrAlloc(value
);
2865 case HTTP_FIELD_ALLOW
:
2867 _cupsStrFree(http
->allow
);
2869 http
->allow
= _cupsStrAlloc(value
);
2872 case HTTP_FIELD_SERVER
:
2874 _cupsStrFree(http
->server
);
2876 http
->server
= _cupsStrAlloc(value
);
2880 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2884 if (field
== HTTP_FIELD_AUTHORIZATION
)
2887 * Special case for Authorization: as its contents can be
2888 * longer than HTTP_MAX_VALUE
2891 if (http
->field_authorization
)
2892 free(http
->field_authorization
);
2894 http
->field_authorization
= strdup(value
);
2896 else if (field
== HTTP_FIELD_HOST
)
2899 * Special-case for Host: as we don't want a trailing "." on the hostname and
2900 * need to bracket IPv6 numeric addresses.
2903 char *ptr
= strchr(value
, ':');
2905 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2908 * Bracket IPv6 numeric addresses...
2910 * This is slightly inefficient (basically copying twice), but is an edge
2911 * case and not worth optimizing...
2914 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2915 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2920 * Check for a trailing dot on the hostname...
2923 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2927 ptr
+= strlen(ptr
) - 1;
2935 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
2936 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
2938 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
2939 http_content_coding_start(http
, value
);
2941 #endif /* HAVE_LIBZ */
2946 * 'httpSetLength()' - Set the content-length and content-encoding.
2948 * @since CUPS 1.2/OS X 10.5@
2952 httpSetLength(http_t
*http
, /* I - Connection to server */
2953 size_t length
) /* I - Length (0 for chunked) */
2955 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
2956 CUPS_LLCAST length
));
2963 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
2965 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2969 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2970 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2971 CUPS_LLFMT
, CUPS_LLCAST length
);
2977 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2979 * The optional timeout callback receives both the HTTP connection and a user
2980 * data pointer and must return 1 to continue or 0 to error (time) out.
2982 * @since CUPS 1.5/OS X 10.7@
2987 http_t
*http
, /* I - Connection to server */
2988 double timeout
, /* I - Number of seconds for timeout,
2989 must be greater than 0 */
2990 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2991 void *user_data
) /* I - User data pointer */
2993 if (!http
|| timeout
<= 0.0)
2996 http
->timeout_cb
= cb
;
2997 http
->timeout_data
= user_data
;
2998 http
->timeout_value
= timeout
;
3001 http_set_timeout(http
->fd
, timeout
);
3003 http_set_wait(http
);
3008 * 'httpTrace()' - Send an TRACE request to the server.
3011 int /* O - Status of call (0 = success) */
3012 httpTrace(http_t
*http
, /* I - Connection to server */
3013 const char *uri
) /* I - URI for trace */
3015 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
3020 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3022 * Note: Unlike httpUpdate(), this function does not flush pending write data
3023 * and only retrieves a single status line from the HTTP connection.
3026 int /* O - 1 to continue, 0 to stop */
3027 _httpUpdate(http_t
*http
, /* I - Connection to server */
3028 http_status_t
*status
) /* O - Current HTTP status */
3030 char line
[32768], /* Line from connection... */
3031 *value
; /* Pointer to value on line */
3032 http_field_t field
; /* Field index */
3033 int major
, minor
; /* HTTP version numbers */
3036 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3037 http_state_string(http
->state
)));
3040 * Grab a single line from the connection...
3043 if (!httpGets(line
, sizeof(line
), http
))
3045 *status
= HTTP_STATUS_ERROR
;
3049 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3051 if (line
[0] == '\0')
3054 * Blank line means the start of the data section (if any). Return
3055 * the result code, too...
3057 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3058 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3062 if (http
->status
== HTTP_STATUS_CONTINUE
)
3064 *status
= http
->status
;
3068 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
3069 http
->digest_tries
= 0;
3072 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
3074 if (http_setup_ssl(http
) != 0)
3077 closesocket(http
->fd
);
3082 *status
= http
->status
= HTTP_STATUS_ERROR
;
3086 *status
= HTTP_STATUS_CONTINUE
;
3089 #endif /* HAVE_SSL */
3091 if (http_set_length(http
) < 0)
3093 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3094 http
->error
= EINVAL
;
3095 http
->status
= *status
= HTTP_STATUS_ERROR
;
3099 switch (http
->state
)
3101 case HTTP_STATE_GET
:
3102 case HTTP_STATE_POST
:
3103 case HTTP_STATE_POST_RECV
:
3104 case HTTP_STATE_PUT
:
3107 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3108 http_state_string(http
->state
)));
3110 case HTTP_STATE_POST_SEND
:
3111 case HTTP_STATE_HEAD
:
3115 http
->state
= HTTP_STATE_WAITING
;
3117 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
3122 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3123 http_content_coding_start(http
,
3124 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3125 #endif /* HAVE_LIBZ */
3127 *status
= http
->status
;
3130 else if (!strncmp(line
, "HTTP/", 5))
3133 * Got the beginning of a response...
3136 int intstatus
; /* Status value as an integer */
3138 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3140 *status
= http
->status
= HTTP_STATUS_ERROR
;
3144 httpClearFields(http
);
3146 http
->version
= (http_version_t
)(major
* 100 + minor
);
3147 *status
= http
->status
= (http_status_t
)intstatus
;
3149 else if ((value
= strchr(line
, ':')) != NULL
)
3156 while (_cups_isspace(*value
))
3159 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3162 * Be tolerants of servers that send unknown attribute fields...
3165 if (!_cups_strcasecmp(line
, "expect"))
3168 * "Expect: 100-continue" or similar...
3171 http
->expect
= (http_status_t
)atoi(value
);
3173 else if (!_cups_strcasecmp(line
, "cookie"))
3176 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3179 httpSetCookie(http
, value
);
3181 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
3182 httpSetField(http
, field
, value
);
3185 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3190 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3191 http
->error
= EINVAL
;
3192 http
->status
= *status
= HTTP_STATUS_ERROR
;
3201 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3204 http_status_t
/* O - HTTP status */
3205 httpUpdate(http_t
*http
) /* I - Connection to server */
3207 http_status_t status
; /* Request status */
3210 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3211 http_state_string(http
->state
)));
3214 * Flush pending data, if any...
3219 DEBUG_puts("2httpUpdate: flushing buffer...");
3221 if (httpFlushWrite(http
) < 0)
3222 return (HTTP_STATUS_ERROR
);
3226 * If we haven't issued any commands, then there is nothing to "update"...
3229 if (http
->state
== HTTP_STATE_WAITING
)
3230 return (HTTP_STATUS_CONTINUE
);
3233 * Grab all of the lines we can from the connection...
3236 while (_httpUpdate(http
, &status
));
3239 * See if there was an error...
3242 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3244 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3245 return (http
->status
);
3250 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3251 strerror(http
->error
)));
3252 http
->status
= HTTP_STATUS_ERROR
;
3253 return (HTTP_STATUS_ERROR
);
3257 * Return the current status...
3265 * '_httpWait()' - Wait for data available on a connection (no flush).
3268 int /* O - 1 if data is available, 0 otherwise */
3269 _httpWait(http_t
*http
, /* I - Connection to server */
3270 int msec
, /* I - Milliseconds to wait */
3271 int usessl
) /* I - Use SSL context? */
3274 struct pollfd pfd
; /* Polled file descriptor */
3276 fd_set input_set
; /* select() input set */
3277 struct timeval timeout
; /* Timeout */
3278 #endif /* HAVE_POLL */
3279 int nfds
; /* Result from select()/poll() */
3282 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3286 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3291 * Check the SSL/TLS buffers for data first...
3295 if (http
->tls
&& usessl
)
3298 if (SSL_pending(http
->tls
))
3300 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3304 # elif defined(HAVE_GNUTLS)
3305 if (gnutls_record_check_pending(http
->tls
))
3307 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3311 # elif defined(HAVE_CDSASSL)
3312 size_t bytes
; /* Bytes that are available */
3314 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3317 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3320 # endif /* HAVE_LIBSSL */
3322 #endif /* HAVE_SSL */
3325 * Then try doing a select() or poll() to poll the socket...
3330 pfd
.events
= POLLIN
;
3334 nfds
= poll(&pfd
, 1, msec
);
3336 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3341 FD_ZERO(&input_set
);
3342 FD_SET(http
->fd
, &input_set
);
3344 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3348 timeout
.tv_sec
= msec
/ 1000;
3349 timeout
.tv_usec
= (msec
% 1000) * 1000;
3351 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3354 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3356 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3359 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3360 WSAGetLastError() == WSAEWOULDBLOCK
));
3362 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3364 #endif /* HAVE_POLL */
3366 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3374 * 'httpWait()' - Wait for data available on a connection.
3376 * @since CUPS 1.1.19/OS X 10.3@
3379 int /* O - 1 if data is available, 0 otherwise */
3380 httpWait(http_t
*http
, /* I - Connection to server */
3381 int msec
) /* I - Milliseconds to wait */
3384 * First see if there is data in the buffer...
3387 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3394 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3399 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3401 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3404 #endif /* HAVE_LIBZ */
3407 * Flush pending data, if any...
3412 DEBUG_puts("3httpWait: Flushing write buffer.");
3414 if (httpFlushWrite(http
) < 0)
3419 * If not, check the SSL/TLS buffers and do a select() on the connection...
3422 return (_httpWait(http
, msec
, 1));
3427 * 'httpWrite()' - Write data to a HTTP connection.
3429 * This function is deprecated. Use the httpWrite2() function which can
3430 * write more than 2GB of data.
3435 int /* O - Number of bytes written */
3436 httpWrite(http_t
*http
, /* I - Connection to server */
3437 const char *buffer
, /* I - Buffer for data */
3438 int length
) /* I - Number of bytes to write */
3440 return ((int)httpWrite2(http
, buffer
, length
));
3445 * 'httpWrite2()' - Write data to a HTTP connection.
3447 * @since CUPS 1.2/OS X 10.5@
3450 ssize_t
/* O - Number of bytes written */
3451 httpWrite2(http_t
*http
, /* I - Connection to server */
3452 const char *buffer
, /* I - Buffer for data */
3453 size_t length
) /* I - Number of bytes to write */
3455 ssize_t bytes
; /* Bytes written */
3458 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3459 buffer
, CUPS_LLCAST length
));
3462 * Range check input...
3465 if (!http
|| !buffer
)
3467 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3472 * Mark activity on the connection...
3475 http
->activity
= time(NULL
);
3478 * Buffer small writes for better performance...
3484 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3488 http_content_coding_finish(http
);
3493 http
->stream
.next_in
= (Bytef
*)buffer
;
3494 http
->stream
.avail_in
= length
;
3495 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3496 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3498 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3500 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3502 if (http
->stream
.avail_out
== 0)
3504 if (httpFlushWrite(http
) < 0)
3506 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3510 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3511 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3515 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3520 #endif /* HAVE_LIBZ */
3523 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3525 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3526 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3528 httpFlushWrite(http
);
3531 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3532 length
< sizeof(http
->wbuffer
))
3535 * Write to buffer...
3538 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3539 CUPS_LLCAST length
));
3541 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3542 http
->wused
+= (int)length
;
3543 bytes
= (ssize_t
)length
;
3548 * Otherwise write the data directly...
3551 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3552 CUPS_LLCAST length
));
3554 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3555 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3557 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3559 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3560 CUPS_LLCAST bytes
));
3563 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3564 http
->data_remaining
-= bytes
;
3570 * Handle end-of-request processing...
3573 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3574 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3577 * Finished with the transfer; unless we are sending POST or PUT
3583 http_content_coding_finish(http
);
3584 #endif /* HAVE_LIBZ */
3588 if (httpFlushWrite(http
) < 0)
3592 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3595 * Send a 0-length chunk at the end of the request...
3598 http_write(http
, "0\r\n\r\n", 5);
3601 * Reset the data state...
3604 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3605 http
->data_remaining
= 0;
3608 if (http
->state
== HTTP_STATE_POST_RECV
)
3610 else if (http
->state
== HTTP_STATE_POST_SEND
)
3611 http
->state
= HTTP_STATE_WAITING
;
3613 http
->state
= HTTP_STATE_STATUS
;
3615 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3616 http_state_string(http
->state
)));
3619 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3625 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3627 * '_httpWriteCDSA()' - Write function for the CDSA library.
3630 OSStatus
/* O - -1 on error, 0 on success */
3632 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3633 const void *data
, /* I - Data buffer */
3634 size_t *dataLength
) /* IO - Number of bytes */
3636 OSStatus result
; /* Return value */
3637 ssize_t bytes
; /* Number of bytes read */
3638 http_t
*http
; /* HTTP connection */
3641 http
= (http_t
*)connection
;
3645 bytes
= write(http
->fd
, data
, *dataLength
);
3647 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3649 if (bytes
== *dataLength
)
3653 else if (bytes
>= 0)
3655 *dataLength
= bytes
;
3656 result
= errSSLWouldBlock
;
3662 if (errno
== EAGAIN
)
3663 result
= errSSLWouldBlock
;
3665 result
= errSSLClosedAbort
;
3670 #endif /* HAVE_SSL && HAVE_CDSASSL */
3673 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3675 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3678 ssize_t
/* O - Number of bytes written or -1 on error */
3680 gnutls_transport_ptr ptr
, /* I - Connection to server */
3681 const void *data
, /* I - Data buffer */
3682 size_t length
) /* I - Number of bytes to write */
3684 ssize_t bytes
; /* Bytes written */
3687 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3690 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3693 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3694 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3698 #endif /* HAVE_SSL && HAVE_GNUTLS */
3702 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3704 * @since CUPS 1.7/OS X 10.9@
3707 int /* O - 0 on success, -1 on error */
3708 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3709 http_status_t status
) /* I - Status code */
3711 http_encoding_t old_encoding
; /* Old data_encoding value */
3712 off_t old_remaining
; /* Old data_remaining value */
3716 * Range check input...
3719 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3721 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3723 DEBUG_puts("1httpWriteResponse: Bad input.");
3728 * Set the various standard fields if they aren't already...
3731 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3732 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3734 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3736 http
->keep_alive
= 0;
3737 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3740 if (http
->version
== HTTP_VERSION_1_1
)
3742 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3744 if (http
->keep_alive
)
3745 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3747 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3750 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3751 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3755 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
)
3757 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3758 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3760 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3761 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3763 #endif /* HAVE_SSL */
3766 httpSetField(http
, HTTP_FIELD_SERVER
,
3767 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3770 * Set the Accept-Encoding field if it isn't already...
3773 if (!http
->accept_encoding
)
3774 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3775 http
->default_accept_encoding
? http
->default_accept_encoding
:
3777 "gzip, deflate, identity");
3780 #endif /* HAVE_LIBZ */
3783 * Send the response header...
3786 old_encoding
= http
->data_encoding
;
3787 old_remaining
= http
->data_remaining
;
3788 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3790 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3791 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3793 http
->status
= HTTP_STATUS_ERROR
;
3797 if (status
!= HTTP_STATUS_CONTINUE
)
3800 * 100 Continue doesn't have the rest of the response headers...
3803 int i
; /* Looping var */
3804 const char *value
; /* Field value */
3806 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3808 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3810 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3812 http
->status
= HTTP_STATUS_ERROR
;
3820 if (httpPrintf(http
, "Set-Cookie: %s path=/%s\r\n", http
->cookie
,
3821 http
->tls
? " secure" : "") < 1)
3823 http
->status
= HTTP_STATUS_ERROR
;
3829 if (httpWrite2(http
, "\r\n", 2) < 2)
3831 http
->status
= HTTP_STATUS_ERROR
;
3835 if (httpFlushWrite(http
) < 0)
3837 http
->status
= HTTP_STATUS_ERROR
;
3841 if (status
== HTTP_STATUS_CONTINUE
)
3844 * Restore the old data_encoding and data_length values...
3847 http
->data_encoding
= old_encoding
;
3848 http
->data_remaining
= old_remaining
;
3850 if (old_remaining
<= INT_MAX
)
3851 http
->_data_remaining
= (int)old_remaining
;
3853 http
->_data_remaining
= INT_MAX
;
3855 else if (http
->state
== HTTP_STATE_OPTIONS
||
3856 http
->state
== HTTP_STATE_HEAD
||
3857 http
->state
== HTTP_STATE_PUT
||
3858 http
->state
== HTTP_STATE_TRACE
||
3859 http
->state
== HTTP_STATE_CONNECT
||
3860 http
->state
== HTTP_STATE_STATUS
)
3862 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3863 "was %s.", http_state_string(http
->state
)));
3864 http
->state
= HTTP_STATE_WAITING
;
3869 * Force data_encoding and data_length to be set according to the response
3873 http_set_length(http
);
3877 * Then start any content encoding...
3880 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
3881 http_content_coding_start(http
,
3882 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3883 #endif /* HAVE_LIBZ */
3890 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3892 * 'http_bio_ctrl()' - Control the HTTP connection.
3895 static long /* O - Result/data */
3896 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3897 int cmd
, /* I - Control command */
3898 long arg1
, /* I - First argument */
3899 void *arg2
) /* I - Second argument */
3906 case BIO_CTRL_RESET
:
3910 case BIO_C_SET_FILE_PTR
:
3915 case BIO_C_GET_FILE_PTR
:
3918 *((void **)arg2
) = h
->ptr
;
3925 case BIO_CTRL_FLUSH
:
3932 * 'http_bio_free()' - Free OpenSSL data.
3935 static int /* O - 1 on success, 0 on failure */
3936 http_bio_free(BIO
*h
) /* I - BIO data */
3952 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3955 static int /* O - 1 on success, 0 on failure */
3956 http_bio_new(BIO
*h
) /* I - BIO data */
3971 * 'http_bio_puts()' - Send a string for OpenSSL.
3974 static int /* O - Bytes written */
3975 http_bio_puts(BIO
*h
, /* I - BIO data */
3976 const char *str
) /* I - String to write */
3979 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3981 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3987 * 'http_bio_read()' - Read data for OpenSSL.
3990 static int /* O - Bytes read */
3991 http_bio_read(BIO
*h
, /* I - BIO data */
3992 char *buf
, /* I - Buffer */
3993 int size
) /* I - Number of bytes to read */
3995 http_t
*http
; /* HTTP connection */
3998 http
= (http_t
*)h
->ptr
;
4000 if (!http
->blocking
)
4003 * Make sure we have data before we read...
4006 while (!_httpWait(http
, http
->wait_value
, 0))
4008 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4012 http
->error
= WSAETIMEDOUT
;
4014 http
->error
= ETIMEDOUT
;
4021 return (recv(http
->fd
, buf
, size
, 0));
4026 * 'http_bio_write()' - Write data for OpenSSL.
4029 static int /* O - Bytes written */
4030 http_bio_write(BIO
*h
, /* I - BIO data */
4031 const char *buf
, /* I - Buffer to write */
4032 int num
) /* I - Number of bytes to write */
4034 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4036 #endif /* HAVE_SSL && HAVE_LIBSSL */
4041 * 'http_content_coding_finish()' - Finish doing any content encoding.
4045 http_content_coding_finish(
4046 http_t
*http
) /* I - HTTP connection */
4048 int zerr
; /* Compression status */
4051 switch (http
->coding
)
4053 case _HTTP_CODING_DEFLATE
:
4054 case _HTTP_CODING_GZIP
:
4057 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4058 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4060 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4062 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4063 if (http
->wused
== sizeof(http
->wbuffer
))
4064 httpFlushWrite(http
);
4066 while (zerr
== Z_OK
);
4068 deflateEnd(&(http
->stream
));
4071 httpFlushWrite(http
);
4074 case _HTTP_CODING_INFLATE
:
4075 case _HTTP_CODING_GUNZIP
:
4076 inflateEnd(&(http
->stream
));
4077 free(http
->dbuffer
);
4078 http
->dbuffer
= NULL
;
4085 http
->coding
= _HTTP_CODING_IDENTITY
;
4090 * 'http_content_coding_start()' - Start doing content encoding.
4094 http_content_coding_start(
4095 http_t
*http
, /* I - HTTP connection */
4096 const char *value
) /* I - Value of Content-Encoding */
4098 int zerr
; /* Error/status */
4099 _http_coding_t coding
; /* Content coding value */
4102 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4105 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4107 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4111 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4113 if (http
->state
== HTTP_STATE_GET_SEND
||
4114 http
->state
== HTTP_STATE_POST_SEND
)
4115 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4116 _HTTP_CODING_GUNZIP
;
4117 else if (http
->state
== HTTP_STATE_POST_RECV
||
4118 http
->state
== HTTP_STATE_PUT_RECV
)
4119 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4120 _HTTP_CODING_GUNZIP
;
4123 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4127 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4129 if (http
->state
== HTTP_STATE_GET_SEND
||
4130 http
->state
== HTTP_STATE_POST_SEND
)
4131 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4132 _HTTP_CODING_INFLATE
;
4133 else if (http
->state
== HTTP_STATE_POST_RECV
||
4134 http
->state
== HTTP_STATE_PUT_RECV
)
4135 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4136 _HTTP_CODING_INFLATE
;
4139 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4145 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4149 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4153 case _HTTP_CODING_DEFLATE
:
4154 case _HTTP_CODING_GZIP
:
4156 httpFlushWrite(http
);
4159 * Window size for compression is 11 bits - optimal based on PWG Raster
4160 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
4164 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4166 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
4167 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4169 http
->status
= HTTP_STATUS_ERROR
;
4170 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4175 case _HTTP_CODING_INFLATE
:
4176 case _HTTP_CODING_GUNZIP
:
4177 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
4179 http
->status
= HTTP_STATUS_ERROR
;
4180 http
->error
= errno
;
4185 * Window size for decompression is up to 15 bits (maximum supported).
4186 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
4189 if ((zerr
= inflateInit2(&(http
->stream
),
4190 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
4193 free(http
->dbuffer
);
4194 http
->dbuffer
= NULL
;
4195 http
->status
= HTTP_STATUS_ERROR
;
4196 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4200 http
->stream
.avail_in
= 0;
4201 http
->stream
.next_in
= http
->dbuffer
;
4208 http
->coding
= coding
;
4210 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4213 #endif /* HAVE_LIBZ */
4217 * 'http_create()' - Create an unconnected HTTP connection.
4220 static http_t
* /* O - HTTP connection */
4222 const char *host
, /* I - Hostname */
4223 int port
, /* I - Port number */
4224 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
4225 int family
, /* I - Address family or AF_UNSPEC */
4226 http_encryption_t encryption
, /* I - Encryption to use */
4227 int blocking
, /* I - 1 for blocking mode */
4228 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
4230 http_t
*http
; /* New HTTP connection */
4231 char service
[255]; /* Service name */
4232 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
4235 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
4236 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
4237 family
, encryption
, blocking
, mode
));
4239 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
4245 * Lookup the host...
4250 myaddrlist
= httpAddrCopyList(addrlist
);
4254 snprintf(service
, sizeof(service
), "%d", port
);
4256 myaddrlist
= httpAddrGetList(host
, family
, service
);
4263 * Allocate memory for the structure...
4266 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
4268 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
4269 httpAddrFreeList(addrlist
);
4274 * Initialize the HTTP data...
4278 http
->activity
= time(NULL
);
4279 http
->addrlist
= myaddrlist
;
4280 http
->blocking
= blocking
;
4283 http
->gssctx
= GSS_C_NO_CONTEXT
;
4284 http
->gssname
= GSS_C_NO_NAME
;
4285 #endif /* HAVE_GSSAPI */
4286 http
->status
= HTTP_STATUS_CONTINUE
;
4287 http
->version
= HTTP_VERSION_1_1
;
4290 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
4292 if (port
== 443) /* Always use encryption for https */
4293 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
4295 http
->encryption
= encryption
;
4297 http_set_wait(http
);
4300 * Return the new structure...
4306 /* For OS X 10.8 and earlier */
4307 http_t
*_httpCreate(const char *host
, int port
, http_addrlist_t
*addrlist
,
4308 http_encryption_t encryption
, int family
)
4309 { return (http_create(host
, port
, addrlist
, family
, encryption
, 1,
4310 _HTTP_MODE_CLIENT
)); }
4315 * 'http_debug_hex()' - Do a hex dump of a buffer.
4319 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4320 const char *buffer
, /* I - Buffer to dump */
4321 int bytes
) /* I - Bytes to dump */
4323 int i
, j
, /* Looping vars */
4324 ch
; /* Current character */
4325 char line
[255], /* Line buffer */
4326 *start
, /* Start of line after prefix */
4327 *ptr
; /* Pointer into line */
4330 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4333 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4335 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4336 start
= line
+ strlen(line
);
4338 for (i
= 0; i
< bytes
; i
+= 16)
4340 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4341 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4345 memcpy(ptr
, " ", 3);
4350 memcpy(ptr
, " ", 3);
4353 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4355 ch
= buffer
[i
+ j
] & 255;
4357 if (ch
< ' ' || ch
>= 127)
4371 * 'http_field()' - Return the field index for a field name.
4374 static http_field_t
/* O - Field index */
4375 http_field(const char *name
) /* I - String name */
4377 int i
; /* Looping var */
4380 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4381 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
4382 return ((http_field_t
)i
);
4384 return (HTTP_FIELD_UNKNOWN
);
4389 * 'http_read()' - Read a buffer from a HTTP connection.
4391 * This function does the low-level read from the socket, retrying and timing
4395 static ssize_t
/* O - Number of bytes read or -1 on error */
4396 http_read(http_t
*http
, /* I - Connection to server */
4397 char *buffer
, /* I - Buffer */
4398 size_t length
) /* I - Maximum bytes to read */
4400 ssize_t bytes
; /* Bytes read */
4403 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4404 buffer
, CUPS_LLCAST length
));
4406 if (!http
->blocking
)
4408 while (!httpWait(http
, http
->wait_value
))
4410 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4413 DEBUG_puts("2http_read: Timeout.");
4418 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4424 bytes
= http_read_ssl(http
, buffer
, length
);
4426 #endif /* HAVE_SSL */
4427 bytes
= recv(http
->fd
, buffer
, length
, 0);
4432 if (WSAGetLastError() != WSAEINTR
)
4434 http
->error
= WSAGetLastError();
4437 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4439 if (!http
->timeout_cb
||
4440 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4442 http
->error
= WSAEWOULDBLOCK
;
4447 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4449 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4451 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4453 http
->error
= errno
;
4456 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4458 http
->error
= errno
;
4462 else if (errno
!= EINTR
)
4464 http
->error
= errno
;
4472 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4473 CUPS_LLCAST bytes
));
4476 http_debug_hex("http_read", buffer
, (int)bytes
);
4482 if (WSAGetLastError() == WSAEINTR
)
4485 http
->error
= WSAGetLastError();
4487 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4490 http
->error
= errno
;
4493 else if (bytes
== 0)
4495 http
->error
= EPIPE
;
4504 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4506 * This function reads data from the HTTP buffer or from the socket, as needed.
4509 static ssize_t
/* O - Number of bytes read or -1 on error */
4510 http_read_buffered(http_t
*http
, /* I - Connection to server */
4511 char *buffer
, /* I - Buffer */
4512 size_t length
) /* I - Maximum bytes to read */
4514 ssize_t bytes
; /* Bytes read */
4517 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4519 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4523 if (length
> (size_t)http
->used
)
4524 bytes
= (size_t)http
->used
;
4528 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4531 memcpy(buffer
, http
->buffer
, bytes
);
4532 http
->used
-= (int)bytes
;
4535 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4538 bytes
= http_read(http
, buffer
, length
);
4545 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4547 * This function reads and validates the chunk length, then does a buffered read
4548 * returning the number of bytes placed in the buffer.
4551 static ssize_t
/* O - Number of bytes read or -1 on error */
4552 http_read_chunk(http_t
*http
, /* I - Connection to server */
4553 char *buffer
, /* I - Buffer */
4554 size_t length
) /* I - Maximum bytes to read */
4556 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4557 http
, buffer
, CUPS_LLCAST length
));
4559 if (http
->data_remaining
<= 0)
4561 char len
[32]; /* Length string */
4563 if (!httpGets(len
, sizeof(len
), http
))
4565 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4571 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4572 if (!httpGets(len
, sizeof(len
), http
))
4574 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4579 http
->data_remaining
= strtoll(len
, NULL
, 16);
4581 if (http
->data_remaining
< 0)
4583 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4584 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4588 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4589 len
, CUPS_LLCAST http
->data_remaining
));
4591 if (http
->data_remaining
== 0)
4594 * 0-length chunk, grab trailing blank line...
4597 httpGets(len
, sizeof(len
), http
);
4601 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4602 CUPS_LLCAST http
->data_remaining
));
4604 if (http
->data_remaining
<= 0)
4606 else if (length
> (size_t)http
->data_remaining
)
4607 length
= (size_t)http
->data_remaining
;
4609 return (http_read_buffered(http
, buffer
, length
));
4615 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4618 static int /* O - Bytes read */
4619 http_read_ssl(http_t
*http
, /* I - Connection to server */
4620 char *buf
, /* I - Buffer to store data */
4621 int len
) /* I - Length of buffer */
4623 # if defined(HAVE_LIBSSL)
4624 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4626 # elif defined(HAVE_GNUTLS)
4627 ssize_t result
; /* Return value */
4630 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4632 if (result
< 0 && !errno
)
4635 * Convert GNU TLS error to errno value...
4640 case GNUTLS_E_INTERRUPTED
:
4644 case GNUTLS_E_AGAIN
:
4656 return ((int)result
);
4658 # elif defined(HAVE_CDSASSL)
4659 int result
; /* Return value */
4660 OSStatus error
; /* Error info */
4661 size_t processed
; /* Number of bytes processed */
4664 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4665 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4670 result
= (int)processed
;
4673 case errSSLWouldBlock
:
4675 result
= (int)processed
;
4683 case errSSLClosedGraceful
:
4686 result
= (int)processed
;
4697 # elif defined(HAVE_SSPISSL)
4698 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4699 # endif /* HAVE_LIBSSL */
4701 #endif /* HAVE_SSL */
4705 * 'http_send()' - Send a request with all fields and the trailing blank line.
4708 static int /* O - 0 on success, non-zero on error */
4709 http_send(http_t
*http
, /* I - Connection to server */
4710 http_state_t request
, /* I - Request code */
4711 const char *uri
) /* I - URI */
4713 int i
; /* Looping var */
4714 char buf
[1024]; /* Encoded URI buffer */
4715 const char *value
; /* Field value */
4716 static const char * const codes
[] = /* Request code strings */
4736 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4737 http
, codes
[request
], uri
));
4739 if (http
== NULL
|| uri
== NULL
)
4743 * Set the User-Agent field if it isn't already...
4746 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4748 if (http
->default_user_agent
)
4749 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4751 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4755 * Set the Accept-Encoding field if it isn't already...
4758 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4759 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4760 http
->default_accept_encoding
);
4763 * Encode the URI as needed...
4766 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4769 * See if we had an error the last time around; if so, reconnect...
4772 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4773 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4775 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4776 http
->fd
, http
->status
, http
->tls_upgrade
));
4778 if (httpReconnect2(http
, 30000, NULL
))
4783 * Flush any written data that is pending...
4788 if (httpFlushWrite(http
) < 0)
4789 if (httpReconnect2(http
, 30000, NULL
))
4794 * Send the request header...
4797 http
->state
= request
;
4798 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4800 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4803 http
->status
= HTTP_STATUS_CONTINUE
;
4806 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4808 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4809 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4811 #endif /* HAVE_SSL */
4813 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4815 http
->status
= HTTP_STATUS_ERROR
;
4819 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4820 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4822 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
4824 if (i
== HTTP_FIELD_HOST
)
4826 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4827 httpAddrPort(http
->hostaddr
)) < 1)
4829 http
->status
= HTTP_STATUS_ERROR
;
4833 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4835 http
->status
= HTTP_STATUS_ERROR
;
4841 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4843 http
->status
= HTTP_STATUS_ERROR
;
4847 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
4848 http
->mode
, http
->state
));
4850 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4851 (http
->state
== HTTP_STATE_POST_RECV
||
4852 http
->state
== HTTP_STATE_PUT_RECV
))
4853 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4855 http
->status
= HTTP_STATUS_ERROR
;
4859 if (httpPrintf(http
, "\r\n") < 1)
4861 http
->status
= HTTP_STATUS_ERROR
;
4865 if (httpFlushWrite(http
) < 0)
4868 http_set_length(http
);
4869 httpClearFields(http
);
4872 * The Kerberos and AuthRef authentication strings can only be used once...
4875 if (http
->field_authorization
&& http
->authstring
&&
4876 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4877 !strncmp(http
->authstring
, "AuthRef", 7)))
4879 http
->_authstring
[0] = '\0';
4881 if (http
->authstring
!= http
->_authstring
)
4882 free(http
->authstring
);
4884 http
->authstring
= http
->_authstring
;
4892 # if defined(HAVE_CDSASSL)
4894 * 'http_set_credentials()' - Set the SSL/TLS credentials.
4897 static int /* O - Status of connection */
4898 http_set_credentials(http_t
*http
) /* I - Connection to server */
4900 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
4901 OSStatus error
= 0; /* Error code */
4902 http_tls_credentials_t credentials
= NULL
;
4903 /* TLS credentials */
4906 DEBUG_printf(("7http_set_credentials(%p)", http
));
4909 * Prefer connection specific credentials...
4912 if ((credentials
= http
->tls_credentials
) == NULL
)
4913 credentials
= cg
->tls_credentials
;
4917 error
= SSLSetCertificate(http
->tls
, credentials
);
4918 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
4922 DEBUG_puts("4http_set_credentials: No credentials to set.");
4926 # endif /* HAVE_CDSASSL */
4927 #endif /* HAVE_SSL */
4931 * 'http_set_length()' - Set the data_encoding and data_remaining values.
4934 static off_t
/* O - Remainder or -1 on error */
4935 http_set_length(http_t
*http
) /* I - Connection */
4937 off_t remaining
; /* Remainder */
4940 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
4941 http_state_string(http
->state
)));
4943 if ((remaining
= httpGetLength2(http
)) >= 0)
4945 if (http
->mode
== _HTTP_MODE_SERVER
&&
4946 http
->state
!= HTTP_STATE_GET_SEND
&&
4947 http
->state
!= HTTP_STATE_PUT
&&
4948 http
->state
!= HTTP_STATE_POST
&&
4949 http
->state
!= HTTP_STATE_POST_SEND
)
4951 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
4955 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
4958 DEBUG_puts("1http_set_length: Setting data_encoding to "
4959 "HTTP_ENCODING_CHUNKED.");
4960 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
4964 DEBUG_puts("1http_set_length: Setting data_encoding to "
4965 "HTTP_ENCODING_LENGTH.");
4966 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4969 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
4970 CUPS_LLCAST remaining
));
4971 http
->data_remaining
= remaining
;
4973 if (remaining
<= INT_MAX
)
4974 http
->_data_remaining
= remaining
;
4976 http
->_data_remaining
= INT_MAX
;
4983 * 'http_set_timeout()' - Set the socket timeout values.
4987 http_set_timeout(int fd
, /* I - File descriptor */
4988 double timeout
) /* I - Timeout in seconds */
4991 DWORD tv
= (DWORD
)(timeout
* 1000);
4992 /* Timeout in milliseconds */
4994 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4995 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4998 struct timeval tv
; /* Timeout in secs and usecs */
5000 tv
.tv_sec
= (int)timeout
;
5001 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
5003 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5004 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5010 * 'http_set_wait()' - Set the default wait value for reads.
5014 http_set_wait(http_t
*http
) /* I - Connection to server */
5018 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5020 if (http
->wait_value
<= 0)
5021 http
->wait_value
= 60000;
5024 http
->wait_value
= 10000;
5030 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5033 static int /* O - 0 on success, -1 on failure */
5034 http_setup_ssl(http_t
*http
) /* I - Connection to server */
5036 char hostname
[256], /* Hostname */
5037 *hostptr
; /* Pointer into hostname */
5040 SSL_CTX
*context
; /* Context for encryption */
5041 BIO
*bio
; /* BIO data */
5042 const char *message
= NULL
;/* Error message */
5043 # elif defined(HAVE_GNUTLS)
5044 int status
; /* Status of handshake */
5045 gnutls_certificate_client_credentials
*credentials
;
5046 /* TLS credentials */
5047 # elif defined(HAVE_CDSASSL)
5048 _cups_globals_t
*cg
= _cupsGlobals();
5049 /* Pointer to library globals */
5050 OSStatus error
; /* Error code */
5051 const char *message
= NULL
;/* Error message */
5052 cups_array_t
*credentials
; /* Credentials array */
5053 cups_array_t
*names
; /* CUPS distinguished names */
5054 CFArrayRef dn_array
; /* CF distinguished names array */
5055 CFIndex count
; /* Number of credentials */
5056 CFDataRef data
; /* Certificate data */
5057 int i
; /* Looping var */
5058 http_credential_t
*credential
; /* Credential data */
5059 # elif defined(HAVE_SSPISSL)
5060 TCHAR username
[256]; /* Username returned from GetUserName() */
5061 TCHAR commonName
[256];/* Common name for certificate */
5062 DWORD dwSize
; /* 32 bit size */
5063 # endif /* HAVE_LIBSSL */
5066 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5069 * Get the hostname to use for SSL...
5072 if (httpAddrLocalhost(http
->hostaddr
))
5074 strlcpy(hostname
, "localhost", sizeof(hostname
));
5079 * Otherwise make sure the hostname we have does not end in a trailing dot.
5082 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5083 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5089 context
= SSL_CTX_new(SSLv23_client_method());
5091 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5093 bio
= BIO_new(_httpBIOMethods());
5094 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5096 http
->tls
= SSL_new(context
);
5097 SSL_set_bio(http
->tls
, bio
, bio
);
5099 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5100 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5101 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5103 if (SSL_connect(http
->tls
) != 1)
5105 unsigned long error
; /* Error code */
5107 while ((error
= ERR_get_error()) != 0)
5109 message
= ERR_error_string(error
, NULL
);
5110 DEBUG_printf(("8http_setup_ssl: %s", message
));
5113 SSL_CTX_free(context
);
5114 SSL_free(http
->tls
);
5118 http
->error
= WSAGetLastError();
5120 http
->error
= errno
;
5122 http
->status
= HTTP_STATUS_ERROR
;
5125 message
= _("Unable to establish a secure connection to host.");
5127 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5132 # elif defined(HAVE_GNUTLS)
5133 credentials
= (gnutls_certificate_client_credentials
*)
5134 malloc(sizeof(gnutls_certificate_client_credentials
));
5135 if (credentials
== NULL
)
5137 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5139 http
->error
= errno
;
5140 http
->status
= HTTP_STATUS_ERROR
;
5141 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5146 gnutls_certificate_allocate_credentials(credentials
);
5148 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5149 gnutls_set_default_priority(http
->tls
);
5150 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5152 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5153 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr
)http
);
5154 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5155 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5157 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5159 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5160 status
, gnutls_strerror(status
)));
5162 if (gnutls_error_is_fatal(status
))
5165 http
->status
= HTTP_STATUS_ERROR
;
5167 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
5169 gnutls_deinit(http
->tls
);
5170 gnutls_certificate_free_credentials(*credentials
);
5178 http
->tls_credentials
= credentials
;
5180 # elif defined(HAVE_CDSASSL)
5181 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, kSSLClientSide
,
5182 kSSLStreamType
)) == NULL
)
5184 DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
5185 http
->error
= errno
= ENOMEM
;
5186 http
->status
= HTTP_STATUS_ERROR
;
5187 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5192 error
= SSLSetConnection(http
->tls
, http
);
5193 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5197 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5198 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5203 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
5205 DEBUG_printf(("4http_setup_ssl: SSLSetSessionOption, error=%d",
5211 if (cg
->client_cert_cb
)
5213 error
= SSLSetSessionOption(http
->tls
,
5214 kSSLSessionOptionBreakOnCertRequested
, true);
5215 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5216 "error=%d", (int)error
));
5220 error
= http_set_credentials(http
);
5221 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5227 * Let the server know which hostname/domain we are trying to connect to
5228 * in case it wants to serve up a certificate with a matching common name.
5233 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5235 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5241 int done
= 0; /* Are we done yet? */
5243 while (!error
&& !done
)
5245 error
= SSLHandshake(http
->tls
);
5247 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5255 case errSSLWouldBlock
:
5256 error
= noErr
; /* Force a retry */
5257 usleep(1000); /* in 1 millisecond */
5260 case errSSLServerAuthCompleted
:
5262 if (cg
->server_cert_cb
)
5264 error
= httpCopyCredentials(http
, &credentials
);
5267 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5268 cg
->server_cert_data
);
5269 httpFreeCredentials(credentials
);
5272 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5273 "returned %d.", (int)error
));
5277 case errSSLClientCertRequested
:
5280 if (cg
->client_cert_cb
)
5283 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5286 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5288 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5290 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5292 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5294 credential
->datalen
= CFDataGetLength(data
);
5295 if ((credential
->data
= malloc(credential
->datalen
)))
5297 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5298 credential
->datalen
);
5299 cupsArrayAdd(names
, credential
);
5307 CFRelease(dn_array
);
5312 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5313 cg
->client_cert_data
);
5315 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5316 "returned %d.", (int)error
));
5319 httpFreeCredentials(names
);
5323 case errSSLUnknownRootCert
:
5324 message
= _("Unable to establish a secure connection to host "
5325 "(untrusted certificate).");
5328 case errSSLNoRootCert
:
5329 message
= _("Unable to establish a secure connection to host "
5330 "(self-signed certificate).");
5333 case errSSLCertExpired
:
5334 message
= _("Unable to establish a secure connection to host "
5335 "(expired certificate).");
5338 case errSSLCertNotYetValid
:
5339 message
= _("Unable to establish a secure connection to host "
5340 "(certificate not yet valid).");
5343 case errSSLHostNameMismatch
:
5344 message
= _("Unable to establish a secure connection to host "
5345 "(host name mismatch).");
5348 case errSSLXCertChainInvalid
:
5349 message
= _("Unable to establish a secure connection to host "
5350 "(certificate chain invalid).");
5353 case errSSLConnectionRefused
:
5354 message
= _("Unable to establish a secure connection to host "
5355 "(peer dropped connection before responding).");
5366 http
->error
= error
;
5367 http
->status
= HTTP_STATUS_ERROR
;
5368 errno
= ECONNREFUSED
;
5370 CFRelease(http
->tls
);
5374 * If an error string wasn't set by the callbacks use a generic one...
5378 #ifdef HAVE_CSSMERRORSTRING
5379 message
= cssmErrorString(error
);
5381 message
= _("Unable to establish a secure connection to host.");
5382 #endif /* HAVE_CSSMERRORSTRING */
5384 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5389 # elif defined(HAVE_SSPISSL)
5390 http
->tls
= _sspiAlloc();
5394 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5398 http
->tls
->sock
= http
->fd
;
5399 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5400 GetUserName(username
, &dwSize
);
5401 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5402 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5404 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5407 _sspiFree(http
->tls_credentials
);
5408 http
->tls_credentials
= NULL
;
5411 http
->status
= HTTP_STATUS_ERROR
;
5413 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
5414 _("Unable to establish a secure connection to host."), 1);
5419 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
5420 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5422 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5424 _sspiFree(http
->tls_credentials
);
5425 http
->tls_credentials
= NULL
;
5428 http
->status
= HTTP_STATUS_ERROR
;
5430 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
5431 _("Unable to establish a secure connection to host."), 1);
5435 # endif /* HAVE_CDSASSL */
5442 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5446 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
5449 SSL_CTX
*context
; /* Context for encryption */
5451 context
= SSL_get_SSL_CTX(http
->tls
);
5453 SSL_shutdown(http
->tls
);
5454 SSL_CTX_free(context
);
5455 SSL_free(http
->tls
);
5457 # elif defined(HAVE_GNUTLS)
5458 gnutls_certificate_client_credentials
*credentials
;
5459 /* TLS credentials */
5461 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5463 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5464 gnutls_deinit(http
->tls
);
5465 gnutls_certificate_free_credentials(*credentials
);
5468 # elif defined(HAVE_CDSASSL)
5469 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5472 CFRelease(http
->tls
);
5474 if (http
->tls_credentials
)
5475 CFRelease(http
->tls_credentials
);
5477 # elif defined(HAVE_SSPISSL)
5478 _sspiFree(http
->tls_credentials
);
5479 # endif /* HAVE_LIBSSL */
5482 http
->tls_credentials
= NULL
;
5484 #endif /* HAVE_SSL */
5489 * 'http_state_string()' - Return the string associated with a given HTTP state.
5492 static const char * /* O - State string */
5493 http_state_string(http_state_t state
) /* I - HTTP state */
5495 static char buffer
[255]; /* Unknown value buffer */
5496 static const char * const states
[] = /* State strings */
5499 "HTTP_STATE_WAITING",
5500 "HTTP_STATE_OPTIONS",
5502 "HTTP_STATE_GET_SEND",
5505 "HTTP_STATE_POST_RECV",
5506 "HTTP_STATE_POST_SEND",
5508 "HTTP_STATE_PUT_RECV",
5509 "HTTP_STATE_DELETE",
5511 "HTTP_STATE_CONNECT",
5512 "HTTP_STATE_STATUS",
5513 "HTTP_STATE_UNKNOWN_METHOD",
5514 "HTTP_STATE_UNKNOWN_VERSION"
5517 if (state
>= HTTP_STATE_ERROR
&& state
<= HTTP_STATE_UNKNOWN_VERSION
)
5518 return (states
[state
- HTTP_STATE_ERROR
]);
5520 snprintf(buffer
, sizeof(buffer
), "??? %d ???", (int)state
);
5528 * 'http_upgrade()' - Force upgrade to TLS encryption.
5531 static int /* O - Status of connection */
5532 http_upgrade(http_t
*http
) /* I - Connection to server */
5534 int ret
; /* Return value */
5535 http_t myhttp
; /* Local copy of HTTP data */
5538 DEBUG_printf(("7http_upgrade(%p)", http
));
5541 * Flush the connection to make sure any previous "Upgrade" message
5548 * Copy the HTTP data to a local variable so we can do the OPTIONS
5549 * request without interfering with the existing request data...
5552 memcpy(&myhttp
, http
, sizeof(myhttp
));
5555 * Send an OPTIONS request to the server, requiring SSL or TLS
5556 * encryption on the link...
5559 http
->tls_upgrade
= 1;
5560 http
->field_authorization
= NULL
; /* Don't free the auth string */
5562 httpClearFields(http
);
5563 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5564 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5566 if ((ret
= httpOptions(http
, "*")) == 0)
5569 * Wait for the secure connection...
5572 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
5576 * Restore the HTTP request data...
5579 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5580 http
->data_encoding
= myhttp
.data_encoding
;
5581 http
->data_remaining
= myhttp
.data_remaining
;
5582 http
->_data_remaining
= myhttp
._data_remaining
;
5583 http
->expect
= myhttp
.expect
;
5584 http
->field_authorization
= myhttp
.field_authorization
;
5585 http
->digest_tries
= myhttp
.digest_tries
;
5586 http
->tls_upgrade
= 0;
5589 * See if we actually went secure...
5595 * Server does not support HTTP upgrade...
5598 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5601 closesocket(http
->fd
);
5613 #endif /* HAVE_SSL */
5617 * 'http_write()' - Write a buffer to a HTTP connection.
5620 static ssize_t
/* O - Number of bytes written */
5621 http_write(http_t
*http
, /* I - Connection to server */
5622 const char *buffer
, /* I - Buffer for data */
5623 size_t length
) /* I - Number of bytes to write */
5625 ssize_t tbytes
, /* Total bytes sent */
5626 bytes
; /* Bytes sent */
5629 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
5630 buffer
, CUPS_LLCAST length
));
5636 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5638 if (http
->timeout_cb
)
5641 struct pollfd pfd
; /* Polled file descriptor */
5643 fd_set output_set
; /* Output ready for write? */
5644 struct timeval timeout
; /* Timeout value */
5645 #endif /* HAVE_POLL */
5646 int nfds
; /* Result from select()/poll() */
5652 pfd
.events
= POLLOUT
;
5654 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5655 (errno
== EINTR
|| errno
== EAGAIN
))
5661 FD_ZERO(&output_set
);
5662 FD_SET(http
->fd
, &output_set
);
5664 timeout
.tv_sec
= http
->wait_value
/ 1000;
5665 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5667 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5670 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5671 WSAGetLastError() == WSAEWOULDBLOCK
));
5673 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5675 #endif /* HAVE_POLL */
5679 http
->error
= errno
;
5682 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5685 http
->error
= WSAEWOULDBLOCK
;
5687 http
->error
= EWOULDBLOCK
;
5697 bytes
= http_write_ssl(http
, buffer
, length
);
5699 #endif /* HAVE_SSL */
5700 bytes
= send(http
->fd
, buffer
, length
, 0);
5702 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
5703 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
5708 if (WSAGetLastError() == WSAEINTR
)
5710 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5712 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5715 http
->error
= WSAGetLastError();
5717 else if (WSAGetLastError() != http
->error
&&
5718 WSAGetLastError() != WSAECONNRESET
)
5720 http
->error
= WSAGetLastError();
5727 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5729 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5731 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5734 http
->error
= errno
;
5736 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5738 http
->error
= errno
;
5743 DEBUG_printf(("3http_write: error writing data (%s).",
5744 strerror(http
->error
)));
5755 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5758 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
5765 * 'http_write_chunk()' - Write a chunked buffer.
5768 static ssize_t
/* O - Number bytes written */
5769 http_write_chunk(http_t
*http
, /* I - Connection to server */
5770 const char *buffer
, /* I - Buffer to write */
5771 size_t length
) /* I - Length of buffer */
5773 char header
[16]; /* Chunk header */
5774 ssize_t bytes
; /* Bytes written */
5777 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
5778 http
, buffer
, CUPS_LLCAST length
));
5781 * Write the chunk header, data, and trailer.
5784 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
5785 if (http_write(http
, header
, strlen(header
)) < 0)
5787 DEBUG_puts("8http_write_chunk: http_write of length failed.");
5791 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5793 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
5797 if (http_write(http
, "\r\n", 2) < 0)
5799 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
5809 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5812 static int /* O - Bytes written */
5813 http_write_ssl(http_t
*http
, /* I - Connection to server */
5814 const char *buf
, /* I - Buffer holding data */
5815 int len
) /* I - Length of buffer */
5817 ssize_t result
; /* Return value */
5820 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5822 # if defined(HAVE_LIBSSL)
5823 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5825 # elif defined(HAVE_GNUTLS)
5826 result
= gnutls_record_send(http
->tls
, buf
, len
);
5828 if (result
< 0 && !errno
)
5831 * Convert GNU TLS error to errno value...
5836 case GNUTLS_E_INTERRUPTED
:
5840 case GNUTLS_E_AGAIN
:
5852 # elif defined(HAVE_CDSASSL)
5853 OSStatus error
; /* Error info */
5854 size_t processed
; /* Number of bytes processed */
5857 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5862 result
= (int)processed
;
5865 case errSSLWouldBlock
:
5867 result
= (int)processed
;
5875 case errSSLClosedGraceful
:
5878 result
= (int)processed
;
5886 # elif defined(HAVE_SSPISSL)
5887 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
5888 # endif /* HAVE_LIBSSL */
5890 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
5892 return ((int)result
);
5894 #endif /* HAVE_SSL */