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 Jelmer Vernooij.
11 * These coded instructions, statements, and computer programs are the
12 * property of Apple Inc. and are protected by Federal copyright
13 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
14 * which should have been included with this file. If this file is
15 * file is missing or damaged, see the license at "http://www.cups.org/".
17 * This file is subject to the Apple OS-Developed Software exception.
21 * Include necessary headers...
24 #include "cups-private.h"
31 # include <sys/time.h>
32 # include <sys/resource.h>
36 #endif /* HAVE_POLL */
44 static void http_content_coding_finish(http_t
*http
);
45 static void http_content_coding_start(http_t
*http
,
47 #endif /* HAVE_LIBZ */
48 static http_t
*http_create(const char *host
, int port
,
49 http_addrlist_t
*addrlist
, int family
,
50 http_encryption_t encryption
,
51 int blocking
, _http_mode_t mode
);
53 static void http_debug_hex(const char *prefix
, const char *buffer
,
56 static http_field_t
http_field(const char *name
);
57 static ssize_t
http_read(http_t
*http
, char *buffer
, size_t length
);
58 static ssize_t
http_read_buffered(http_t
*http
, char *buffer
, size_t length
);
59 static ssize_t
http_read_chunk(http_t
*http
, char *buffer
, size_t length
);
60 static int http_send(http_t
*http
, http_state_t request
,
62 static ssize_t
http_write(http_t
*http
, const char *buffer
,
64 static ssize_t
http_write_chunk(http_t
*http
, const char *buffer
,
67 static int http_read_ssl(http_t
*http
, char *buf
, int len
);
69 static int http_set_credentials(http_t
*http
);
70 # endif /* HAVE_CDSASSL */
72 static off_t
http_set_length(http_t
*http
);
73 static void http_set_timeout(int fd
, double timeout
);
74 static void http_set_wait(http_t
*http
);
76 static const char *http_state_string(http_state_t state
);
79 static int http_setup_ssl(http_t
*http
);
80 static void http_shutdown_ssl(http_t
*http
);
81 static int http_upgrade(http_t
*http
);
82 static int http_write_ssl(http_t
*http
, const char *buf
, int len
);
90 static const char * const http_fields
[] =
107 "If-Unmodified-since",
125 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
127 * BIO methods for OpenSSL...
130 static int http_bio_write(BIO
*h
, const char *buf
, int num
);
131 static int http_bio_read(BIO
*h
, char *buf
, int size
);
132 static int http_bio_puts(BIO
*h
, const char *str
);
133 static long http_bio_ctrl(BIO
*h
, int cmd
, long arg1
, void *arg2
);
134 static int http_bio_new(BIO
*h
);
135 static int http_bio_free(BIO
*data
);
137 static BIO_METHOD http_bio_methods
=
144 NULL
, /* http_bio_gets, */
150 #endif /* HAVE_SSL && HAVE_LIBSSL */
154 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
155 * specified listening socket.
157 * @since CUPS 1.7/OS X 10.9@
160 http_t
* /* O - HTTP connection or @code NULL@ */
161 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
162 int blocking
) /* I - 1 if the connection should be
163 blocking, 0 otherwise */
165 http_t
*http
; /* HTTP connection */
166 http_addrlist_t addrlist
; /* Dummy address list */
167 socklen_t addrlen
; /* Length of address */
168 int val
; /* Socket option value */
172 * Range check input...
179 * Create the client connection...
182 memset(&addrlist
, 0, sizeof(addrlist
));
184 if ((http
= http_create(NULL
, 0, &addrlist
, AF_UNSPEC
,
185 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
186 _HTTP_MODE_SERVER
)) == NULL
)
190 * Accept the client and get the remote address...
193 addrlen
= sizeof(http_addr_t
);
195 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
198 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
204 httpAddrString(&(http
->addrlist
->addr
), http
->hostname
,
205 sizeof(http
->hostname
));
209 * Disable SIGPIPE for this socket.
213 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
214 #endif /* SO_NOSIGPIPE */
217 * Using TCP_NODELAY improves responsiveness, especially on systems
218 * with a slow loopback interface. Since we write large buffers
219 * when sending print files and requests, there shouldn't be any
220 * performance penalty for this...
224 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
228 * Close this socket when starting another process...
231 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
232 #endif /* FD_CLOEXEC */
239 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
241 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
243 * @since CUPS 1.5/OS X 10.7@
246 int /* O - 0 on success, -1 on error */
248 cups_array_t
*credentials
, /* I - Credentials array */
249 const void *data
, /* I - PEM-encoded X.509 data */
250 size_t datalen
) /* I - Length of data */
252 http_credential_t
*credential
; /* Credential data */
255 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
257 credential
->datalen
= datalen
;
259 if ((credential
->data
= malloc(datalen
)) != NULL
)
261 memcpy(credential
->data
, data
, datalen
);
262 cupsArrayAdd(credentials
, credential
);
273 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
275 * '_httpBIOMethods()' - Get the OpenSSL BIO methods for HTTP connections.
278 BIO_METHOD
* /* O - BIO methods for OpenSSL */
279 _httpBIOMethods(void)
281 return (&http_bio_methods
);
283 #endif /* HAVE_SSL && HAVE_LIBSSL */
287 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
291 httpBlocking(http_t
*http
, /* I - Connection to server */
292 int b
) /* I - 1 = blocking, 0 = non-blocking */
303 * 'httpCheck()' - Check to see if there is a pending response from the server.
306 int /* O - 0 = no data, 1 = data available */
307 httpCheck(http_t
*http
) /* I - Connection to server */
309 return (httpWait(http
, 0));
314 * 'httpClearCookie()' - Clear the cookie value(s).
316 * @since CUPS 1.1.19/OS X 10.3@
320 httpClearCookie(http_t
*http
) /* I - Connection to server */
334 * 'httpClearFields()' - Clear HTTP request fields.
338 httpClearFields(http_t
*http
) /* I - Connection to server */
340 DEBUG_printf(("httpClearFields(http=%p)", http
));
344 memset(http
->fields
, 0, sizeof(http
->fields
));
346 if (http
->mode
== _HTTP_MODE_CLIENT
)
348 if (http
->hostname
[0] == '/')
349 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
351 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
354 if (http
->field_authorization
)
356 free(http
->field_authorization
);
357 http
->field_authorization
= NULL
;
360 if (http
->accept_encoding
)
362 _cupsStrFree(http
->accept_encoding
);
363 http
->accept_encoding
= NULL
;
368 _cupsStrFree(http
->allow
);
374 _cupsStrFree(http
->server
);
378 http
->expect
= (http_status_t
)0;
384 * 'httpClose()' - Close an HTTP connection.
388 httpClose(http_t
*http
) /* I - Connection to server */
391 OM_uint32 minor_status
; /* Minor status code */
392 #endif /* HAVE_GSSAPI */
395 DEBUG_printf(("httpClose(http=%p)", http
));
398 * Range check input...
405 * Close any open connection...
408 _httpDisconnect(http
);
411 * Free memory used...
414 httpAddrFreeList(http
->addrlist
);
420 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
421 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
423 if (http
->gssname
!= GSS_C_NO_NAME
)
424 gss_release_name(&minor_status
, &http
->gssname
);
425 #endif /* HAVE_GSSAPI */
427 #ifdef HAVE_AUTHORIZATION_H
429 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
430 #endif /* HAVE_AUTHORIZATION_H */
432 httpClearFields(http
);
434 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
435 free(http
->authstring
);
442 * 'httpConnect()' - Connect to a HTTP server.
444 * This function is deprecated - use @link httpConnect2@ instead.
449 http_t
* /* O - New HTTP connection */
450 httpConnect(const char *host
, /* I - Host to connect to */
451 int port
) /* I - Port number */
453 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, HTTP_ENCRYPTION_IF_REQUESTED
,
459 * 'httpConnect2()' - Connect to a HTTP server.
461 * @since CUPS 1.7/OS X 10.9@
464 http_t
* /* O - New HTTP connection */
466 const char *host
, /* I - Host to connect to */
467 int port
, /* I - Port number */
468 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
469 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
470 http_encryption_t encryption
, /* I - Type of encryption to use */
471 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
472 int msec
, /* I - Connection timeout in milliseconds, 0 means don't connect */
473 int *cancel
) /* I - Pointer to "cancel" variable */
475 http_t
*http
; /* New HTTP connection */
478 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
479 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
480 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
483 * Create the HTTP structure...
486 if ((http
= http_create(host
, port
, addrlist
, family
, encryption
, blocking
,
487 _HTTP_MODE_CLIENT
)) == NULL
)
491 * Optionally connect to the remote system...
494 if (msec
== 0 || !httpReconnect2(http
, msec
, cancel
))
498 * Could not connect to any known address - bail out!
508 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
510 * This function is now deprecated. Please use the @link httpConnect2@ function
516 http_t
* /* O - New HTTP connection */
518 const char *host
, /* I - Host to connect to */
519 int port
, /* I - Port number */
520 http_encryption_t encryption
) /* I - Type of encryption to use */
522 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
523 host
, port
, encryption
));
525 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
531 * 'httpCopyCredentials()' - Copy the credentials associated with an encrypted
534 * @since CUPS 1.5/OS X 10.7@
537 int /* O - Status of call (0 = success) */
539 http_t
*http
, /* I - Connection to server */
540 cups_array_t
**credentials
) /* O - Array of credentials */
543 # elif defined(HAVE_GNUTLS)
544 # elif defined(HAVE_CDSASSL)
545 OSStatus error
; /* Error code */
546 SecTrustRef peerTrust
; /* Peer trust reference */
547 CFIndex count
; /* Number of credentials */
548 SecCertificateRef secCert
; /* Certificate reference */
549 CFDataRef data
; /* Certificate data */
550 int i
; /* Looping var */
551 # elif defined(HAVE_SSPISSL)
552 # endif /* HAVE_LIBSSL */
558 if (!http
|| !http
->tls
|| !credentials
)
564 # elif defined(HAVE_GNUTLS)
567 # elif defined(HAVE_CDSASSL)
568 if (!(error
= SSLCopyPeerTrust(http
->tls
, &peerTrust
)) && peerTrust
)
570 if ((*credentials
= cupsArrayNew(NULL
, NULL
)) != NULL
)
572 count
= SecTrustGetCertificateCount(peerTrust
);
574 for (i
= 0; i
< count
; i
++)
576 secCert
= SecTrustGetCertificateAtIndex(peerTrust
, i
);
577 if ((data
= SecCertificateCopyData(secCert
)))
579 httpAddCredential(*credentials
, CFDataGetBytePtr(data
),
580 CFDataGetLength(data
));
586 CFRelease(peerTrust
);
591 # elif defined(HAVE_SSPISSL)
596 # endif /* HAVE_LIBSSL */
601 * '_httpCreateCredentials()' - Create credentials in the internal format.
604 http_tls_credentials_t
/* O - Internal credentials */
605 _httpCreateCredentials(
606 cups_array_t
*credentials
) /* I - Array of credentials */
614 # elif defined(HAVE_GNUTLS)
617 # elif defined(HAVE_CDSASSL)
618 CFMutableArrayRef peerCerts
; /* Peer credentials reference */
619 SecCertificateRef secCert
; /* Certificate reference */
620 CFDataRef data
; /* Credential data reference */
621 http_credential_t
*credential
; /* Credential data */
624 if ((peerCerts
= CFArrayCreateMutable(kCFAllocatorDefault
,
625 cupsArrayCount(credentials
),
626 &kCFTypeArrayCallBacks
)) == NULL
)
629 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
631 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
633 if ((data
= CFDataCreate(kCFAllocatorDefault
, credential
->data
,
634 credential
->datalen
)))
636 if ((secCert
= SecCertificateCreateWithData(kCFAllocatorDefault
, data
))
639 CFArrayAppendValue(peerCerts
, secCert
);
649 # elif defined(HAVE_SSPISSL)
654 # endif /* HAVE_LIBSSL */
659 * 'httpDelete()' - Send a DELETE request to the server.
662 int /* O - Status of call (0 = success) */
663 httpDelete(http_t
*http
, /* I - Connection to server */
664 const char *uri
) /* I - URI to delete */
666 return (http_send(http
, HTTP_STATE_DELETE
, uri
));
671 * '_httpDisconnect()' - Disconnect a HTTP connection.
675 _httpDisconnect(http_t
*http
) /* I - Connection to server */
679 http_shutdown_ssl(http
);
680 #endif /* HAVE_SSL */
683 closesocket(http
->fd
);
693 * 'httpEncryption()' - Set the required encryption on the link.
696 int /* O - -1 on error, 0 on success */
697 httpEncryption(http_t
*http
, /* I - Connection to server */
698 http_encryption_t e
) /* I - New encryption preference */
700 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
706 http
->encryption
= e
;
708 if ((http
->encryption
== HTTP_ENCRYPTION_ALWAYS
&& !http
->tls
) ||
709 (http
->encryption
== HTTP_ENCRYPTION_NEVER
&& http
->tls
))
710 return (httpReconnect2(http
, 30000, NULL
));
711 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
712 return (http_upgrade(http
));
716 if (e
== HTTP_ENCRYPTION_ALWAYS
|| e
== HTTP_ENCRYPTION_REQUIRED
)
720 #endif /* HAVE_SSL */
725 * 'httpError()' - Get the last error on a connection.
728 int /* O - Error code (errno) value */
729 httpError(http_t
*http
) /* I - Connection to server */
732 return (http
->error
);
739 * 'httpFlush()' - Flush data from a HTTP connection.
743 httpFlush(http_t
*http
) /* I - Connection to server */
745 char buffer
[8192]; /* Junk buffer */
746 int blocking
; /* To block or not to block */
747 http_state_t oldstate
; /* Old state */
750 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
751 http_state_string(http
->state
)));
754 * Nothing to do if we are in the "waiting" state...
757 if (http
->state
== HTTP_STATE_WAITING
)
761 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
764 blocking
= http
->blocking
;
768 * Read any data we can...
771 oldstate
= http
->state
;
772 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
775 * Restore blocking and reset the connection if we didn't get all of
776 * the remaining data...
779 http
->blocking
= blocking
;
781 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
785 * Didn't get the data back, so close the current connection.
790 http_content_coding_finish(http
);
791 #endif /* HAVE_LIBZ */
793 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
795 http
->state
= HTTP_STATE_WAITING
;
799 http_shutdown_ssl(http
);
800 #endif /* HAVE_SSL */
803 closesocket(http
->fd
);
814 * 'httpFlushWrite()' - Flush data in write buffer.
816 * @since CUPS 1.2/OS X 10.5@
819 int /* O - Bytes written or -1 on error */
820 httpFlushWrite(http_t
*http
) /* I - Connection to server */
822 int bytes
; /* Bytes written */
825 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
826 http
? http
->data_encoding
: -1));
828 if (!http
|| !http
->wused
)
830 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
831 "1httpFlushWrite: No connection.");
835 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
836 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
838 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
842 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
849 * '_httpFreeCredentials()' - Free internal credentials.
853 _httpFreeCredentials(
854 http_tls_credentials_t credentials
) /* I - Internal credentials */
862 #elif defined(HAVE_GNUTLS)
865 #elif defined(HAVE_CDSASSL)
866 CFRelease(credentials
);
868 #elif defined(HAVE_SSPISSL)
871 #endif /* HAVE_LIBSSL */
876 * 'httpFreeCredentials()' - Free an array of credentials.
881 cups_array_t
*credentials
) /* I - Array of credentials */
883 http_credential_t
*credential
; /* Credential */
886 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
888 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
890 cupsArrayRemove(credentials
, credential
);
891 free((void *)credential
->data
);
895 cupsArrayDelete(credentials
);
900 * 'httpGet()' - Send a GET request to the server.
903 int /* O - Status of call (0 = success) */
904 httpGet(http_t
*http
, /* I - Connection to server */
905 const char *uri
) /* I - URI to get */
907 return (http_send(http
, HTTP_STATE_GET
, uri
));
912 * 'httpGetAuthString()' - Get the current authorization string.
914 * The authorization string is set by cupsDoAuthentication() and
915 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
916 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
919 * @since CUPS 1.3/OS X 10.5@
922 char * /* O - Authorization string */
923 httpGetAuthString(http_t
*http
) /* I - Connection to server */
926 return (http
->authstring
);
933 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
935 * @since CUPS 1.2/OS X 10.5@
938 int /* O - 1 if blocking, 0 if non-blocking */
939 httpGetBlocking(http_t
*http
) /* I - Connection to server */
941 return (http
? http
->blocking
: 0);
946 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
947 * the client and server.
949 * This function uses the value of the Accepts-Encoding HTTP header and must be
950 * called after receiving a response from the server or a request from the
951 * client. The value returned can be use in subsequent requests (for clients)
952 * or in the response (for servers) in order to compress the content stream.
954 * @since CUPS 1.7/OS X 10.9@
957 const char * /* O - Content-Coding value or
958 @code NULL@ for the identity
960 httpGetContentEncoding(http_t
*http
) /* I - Connection to client/server */
963 if (http
&& http
->accept_encoding
)
965 int i
; /* Looping var */
966 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
967 *start
, /* Start of coding value */
968 *end
; /* End of coding value */
969 double qvalue
; /* "qvalue" for coding */
970 struct lconv
*loc
= localeconv(); /* Locale data */
971 static const char * const codings
[] =
972 { /* Supported content codings */
979 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
981 for (start
= temp
; *start
; start
= end
)
984 * Find the end of the coding name...
989 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
995 * Grab the qvalue as needed...
998 if (!strncmp(end
, ";q=", 3))
999 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
1002 * Skip past all attributes...
1006 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
1012 while (*end
&& isspace(*end
& 255))
1016 * Check value if it matches something we support...
1022 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
1023 if (!strcmp(start
, codings
[i
]))
1024 return (codings
[i
]);
1027 #endif /* HAVE_LIBZ */
1034 * 'httpGetCookie()' - Get any cookie data from the response.
1036 * @since CUPS 1.1.19/OS X 10.3@
1039 const char * /* O - Cookie data or NULL */
1040 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
1042 return (http
? http
->cookie
: NULL
);
1047 * 'httpGetExpect()' - Get the value of the Expect header, if any.
1049 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
1050 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
1052 * @since CUPS 1.7/OS X 10.9@
1055 http_status_t
/* O - Expect: status, if any */
1056 httpGetExpect(http_t
*http
) /* I - Connection to client */
1059 return (HTTP_STATUS_ERROR
);
1061 return (http
->expect
);
1066 * 'httpGetFd()' - Get the file descriptor associated with a connection.
1068 * @since CUPS 1.2/OS X 10.5@
1071 int /* O - File descriptor or -1 if none */
1072 httpGetFd(http_t
*http
) /* I - Connection to server */
1074 return (http
? http
->fd
: -1);
1079 * 'httpGetField()' - Get a field value from a request/response.
1082 const char * /* O - Field value */
1083 httpGetField(http_t
*http
, /* I - Connection to server */
1084 http_field_t field
) /* I - Field to get */
1086 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1091 case HTTP_FIELD_ACCEPT_ENCODING
:
1092 return (http
->accept_encoding
);
1094 case HTTP_FIELD_ALLOW
:
1095 return (http
->allow
);
1097 case HTTP_FIELD_SERVER
:
1098 return (http
->server
);
1100 case HTTP_FIELD_AUTHORIZATION
:
1101 if (http
->field_authorization
)
1104 * Special case for WWW-Authenticate: as its contents can be
1105 * longer than HTTP_MAX_VALUE...
1108 return (http
->field_authorization
);
1112 return (http
->fields
[field
]);
1118 * 'httpGetLength()' - Get the amount of data remaining from the
1119 * content-length or transfer-encoding fields.
1121 * This function is deprecated and will not return lengths larger than
1122 * 2^31 - 1; use httpGetLength2() instead.
1127 int /* O - Content length */
1128 httpGetLength(http_t
*http
) /* I - Connection to server */
1131 * Get the read content length and return the 32-bit value.
1136 httpGetLength2(http
);
1138 return (http
->_data_remaining
);
1146 * 'httpGetLength2()' - Get the amount of data remaining from the
1147 * content-length or transfer-encoding fields.
1149 * This function returns the complete content length, even for
1150 * content larger than 2^31 - 1.
1152 * @since CUPS 1.2/OS X 10.5@
1155 off_t
/* O - Content length */
1156 httpGetLength2(http_t
*http
) /* I - Connection to server */
1158 off_t remaining
; /* Remaining length */
1161 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1162 http_state_string(http
->state
)));
1167 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1169 DEBUG_puts("4httpGetLength2: chunked request!");
1175 * The following is a hack for HTTP servers that don't send a
1176 * Content-Length or Transfer-Encoding field...
1178 * If there is no Content-Length then the connection must close
1179 * after the transfer is complete...
1182 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1185 * Default content length is 0 for errors and certain types of operations,
1186 * and 2^31-1 for other successful requests...
1189 if (http
->status
>= HTTP_STATUS_MULTIPLE_CHOICES
||
1190 http
->state
== HTTP_STATE_OPTIONS
||
1191 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1192 http
->state
== HTTP_STATE_HEAD
||
1193 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1194 http
->state
== HTTP_STATE_DELETE
||
1195 http
->state
== HTTP_STATE_TRACE
||
1196 http
->state
== HTTP_STATE_CONNECT
)
1199 remaining
= 2147483647;
1201 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1205 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1206 CUPS_LLCAST remaining
));
1214 * 'httpGets()' - Get a line of text from a HTTP connection.
1217 char * /* O - Line or NULL */
1218 httpGets(char *line
, /* I - Line to read into */
1219 int length
, /* I - Max length of buffer */
1220 http_t
*http
) /* I - Connection to server */
1222 char *lineptr
, /* Pointer into line */
1223 *lineend
, /* End of line */
1224 *bufptr
, /* Pointer into input buffer */
1225 *bufend
; /* Pointer to end of buffer */
1226 int bytes
, /* Number of bytes read */
1227 eol
; /* End-of-line? */
1230 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1232 if (!http
|| !line
|| length
<= 1)
1236 * Read a line from the buffer...
1241 lineend
= line
+ length
- 1;
1244 while (lineptr
< lineend
)
1247 * Pre-load the buffer as needed...
1256 while (http
->used
== 0)
1259 * No newline; see if there is more data to be read...
1262 while (!_httpWait(http
, http
->wait_value
, 1))
1264 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1267 DEBUG_puts("3httpGets: Timed out!");
1269 http
->error
= WSAETIMEDOUT
;
1271 http
->error
= ETIMEDOUT
;
1276 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1277 HTTP_MAX_BUFFER
- http
->used
);
1279 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1284 * Nope, can't get a line this time...
1288 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1290 if (WSAGetLastError() == WSAEINTR
)
1292 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1294 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1297 http
->error
= WSAGetLastError();
1299 else if (WSAGetLastError() != http
->error
)
1301 http
->error
= WSAGetLastError();
1306 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1310 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1312 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1314 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1317 http
->error
= errno
;
1319 else if (errno
!= http
->error
)
1321 http
->error
= errno
;
1328 else if (bytes
== 0)
1330 http
->error
= EPIPE
;
1336 * Yup, update the amount used...
1339 http
->used
+= bytes
;
1343 * Now copy as much of the current line as possible...
1346 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1347 lineptr
< lineend
&& bufptr
< bufend
;)
1349 if (*bufptr
== 0x0a)
1355 else if (*bufptr
== 0x0d)
1358 *lineptr
++ = *bufptr
++;
1361 http
->used
-= (int)(bufptr
- http
->buffer
);
1363 memmove(http
->buffer
, bufptr
, http
->used
);
1371 http
->activity
= time(NULL
);
1375 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1381 DEBUG_puts("3httpGets: No new line available!");
1388 * 'httpGetState()' - Get the current state of the HTTP request.
1391 http_state_t
/* O - HTTP state */
1392 httpGetState(http_t
*http
) /* I - Connection to server */
1394 return (http
? http
->state
: HTTP_STATE_ERROR
);
1399 * 'httpGetStatus()' - Get the status of the last HTTP request.
1401 * @since CUPS 1.2/OS X 10.5@
1404 http_status_t
/* O - HTTP status */
1405 httpGetStatus(http_t
*http
) /* I - Connection to server */
1407 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1412 * 'httpGetSubField()' - Get a sub-field value.
1417 char * /* O - Value or NULL */
1418 httpGetSubField(http_t
*http
, /* I - Connection to server */
1419 http_field_t field
, /* I - Field index */
1420 const char *name
, /* I - Name of sub-field */
1421 char *value
) /* O - Value string */
1423 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1428 * 'httpGetSubField2()' - Get a sub-field value.
1430 * @since CUPS 1.2/OS X 10.5@
1433 char * /* O - Value or NULL */
1434 httpGetSubField2(http_t
*http
, /* I - Connection to server */
1435 http_field_t field
, /* I - Field index */
1436 const char *name
, /* I - Name of sub-field */
1437 char *value
, /* O - Value string */
1438 int valuelen
) /* I - Size of value buffer */
1440 const char *fptr
; /* Pointer into field */
1441 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1442 *ptr
, /* Pointer into string buffer */
1443 *end
; /* End of value buffer */
1445 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1446 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1448 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1449 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1452 end
= value
+ valuelen
- 1;
1454 for (fptr
= http
->fields
[field
]; *fptr
;)
1457 * Skip leading whitespace...
1460 while (_cups_isspace(*fptr
))
1470 * Get the sub-field name...
1474 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1475 ptr
< (temp
+ sizeof(temp
) - 1);
1480 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1483 * Skip trailing chars up to the '='...
1486 while (_cups_isspace(*fptr
))
1496 * Skip = and leading whitespace...
1501 while (_cups_isspace(*fptr
))
1507 * Read quoted string...
1510 for (ptr
= value
, fptr
++;
1511 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1516 while (*fptr
&& *fptr
!= '\"')
1525 * Read unquoted string...
1529 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1534 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1538 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1541 * See if this is the one...
1544 if (!strcmp(name
, temp
))
1546 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1553 DEBUG_puts("3httpGetSubField2: Returning NULL");
1560 * 'httpGetVersion()' - Get the HTTP version at the other end.
1563 http_version_t
/* O - Version number */
1564 httpGetVersion(http_t
*http
) /* I - Connection to server */
1566 return (http
? http
->version
: HTTP_VERSION_1_0
);
1571 * 'httpHead()' - Send a HEAD request to the server.
1574 int /* O - Status of call (0 = success) */
1575 httpHead(http_t
*http
, /* I - Connection to server */
1576 const char *uri
) /* I - URI for head */
1578 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1579 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1584 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1585 * default HTTP proxy (if any).
1589 httpInitialize(void)
1591 static int initialized
= 0; /* Have we been called before? */
1593 WSADATA winsockdata
; /* WinSock data */
1596 int i
; /* Looping var */
1597 unsigned char data
[1024]; /* Seed data */
1598 #endif /* HAVE_LIBSSL */
1604 _cupsGlobalUnlock();
1609 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1611 #elif !defined(SO_NOSIGPIPE)
1613 * Ignore SIGPIPE signals...
1617 sigset(SIGPIPE
, SIG_IGN
);
1619 # elif defined(HAVE_SIGACTION)
1620 struct sigaction action
; /* POSIX sigaction data */
1623 memset(&action
, 0, sizeof(action
));
1624 action
.sa_handler
= SIG_IGN
;
1625 sigaction(SIGPIPE
, &action
, NULL
);
1628 signal(SIGPIPE
, SIG_IGN
);
1629 # endif /* !SO_NOSIGPIPE */
1634 * Initialize GNU TLS...
1637 gnutls_global_init();
1639 #elif defined(HAVE_LIBSSL)
1641 * Initialize OpenSSL...
1644 SSL_load_error_strings();
1648 * Using the current time is a dubious random seed, but on some systems
1649 * it is the best we can do (on others, this seed isn't even used...)
1652 CUPS_SRAND(time(NULL
));
1654 for (i
= 0; i
< sizeof(data
); i
++)
1655 data
[i
] = CUPS_RAND();
1657 RAND_seed(data
, sizeof(data
));
1658 #endif /* HAVE_GNUTLS */
1661 _cupsGlobalUnlock();
1666 * 'httpOptions()' - Send an OPTIONS request to the server.
1669 int /* O - Status of call (0 = success) */
1670 httpOptions(http_t
*http
, /* I - Connection to server */
1671 const char *uri
) /* I - URI for options */
1673 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1678 * 'httpPeek()' - Peek at data from a HTTP connection.
1680 * This function copies available data from the given HTTP connection, reading
1681 * a buffer as needed. The data is still available for reading using
1682 * @link httpRead@ or @link httpRead2@.
1684 * For non-blocking connections the usual timeouts apply.
1686 * @since CUPS 1.7/OS X 10.9@
1689 ssize_t
/* O - Number of bytes copied */
1690 httpPeek(http_t
*http
, /* I - Connection to server */
1691 char *buffer
, /* I - Buffer for data */
1692 size_t length
) /* I - Maximum number of bytes */
1694 ssize_t bytes
; /* Bytes read */
1695 char len
[32]; /* Length string */
1698 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1699 http
, buffer
, CUPS_LLCAST length
));
1701 if (http
== NULL
|| buffer
== NULL
)
1704 http
->activity
= time(NULL
);
1710 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1711 http
->data_remaining
<= 0)
1713 DEBUG_puts("2httpPeek: Getting chunk length...");
1715 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1717 DEBUG_puts("1httpPeek: Could not get length!");
1723 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1724 if (!httpGets(len
, sizeof(len
), http
))
1726 DEBUG_puts("1httpPeek: Could not get chunk length.");
1731 http
->data_remaining
= strtoll(len
, NULL
, 16);
1733 if (http
->data_remaining
< 0)
1735 DEBUG_puts("1httpPeek: Negative chunk length!");
1740 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1741 CUPS_LLCAST http
->data_remaining
));
1743 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1746 * A zero-length chunk ends a transfer; unless we are reading POST
1752 http_content_coding_finish(http
);
1753 #endif /* HAVE_LIBZ */
1755 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1756 httpGets(len
, sizeof(len
), http
);
1758 if (http
->state
== HTTP_STATE_POST_RECV
)
1761 http
->state
= HTTP_STATE_STATUS
;
1763 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1764 http_state_string(http
->state
)));
1767 * Prevent future reads for this request...
1770 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1774 else if (length
> (size_t)http
->data_remaining
)
1775 length
= (size_t)http
->data_remaining
;
1778 if (http
->used
== 0 &&
1779 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1781 if (http
->used
== 0)
1782 #endif /* HAVE_LIBZ */
1785 * Buffer small reads for better performance...
1788 ssize_t buflen
; /* Length of read for buffer */
1790 if (!http
->blocking
)
1792 while (!httpWait(http
, http
->wait_value
))
1794 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1801 if (http
->data_remaining
> sizeof(http
->buffer
))
1802 buflen
= sizeof(http
->buffer
);
1804 buflen
= http
->data_remaining
;
1806 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1807 bytes
= http_read(http
, http
->buffer
, buflen
);
1809 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1810 CUPS_LLCAST bytes
));
1814 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1824 # ifdef HAVE_INFLATECOPY
1825 int zerr
; /* Decompressor error */
1826 z_stream stream
; /* Copy of decompressor stream */
1828 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1830 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1831 /* Number of bytes to copy */
1833 if (http
->stream
.avail_in
> 0 &&
1834 http
->stream
.next_in
> http
->dbuffer
)
1835 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1837 http
->stream
.next_in
= http
->dbuffer
;
1839 if (buflen
> http
->data_remaining
)
1840 buflen
= http
->data_remaining
;
1842 if (buflen
> http
->used
)
1843 buflen
= http
->used
;
1845 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1846 "decompression buffer.", (int)buflen
));
1848 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
1849 http
->stream
.avail_in
+= buflen
;
1850 http
->used
-= buflen
;
1851 http
->data_remaining
-= buflen
;
1854 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
1857 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
1858 (int)http
->stream
.avail_in
));
1860 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
1862 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
1863 http
->error
= ENOMEM
;
1867 stream
.next_out
= (Bytef
*)buffer
;
1868 stream
.avail_out
= length
;
1870 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
1871 inflateEnd(&stream
);
1875 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
1877 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
1878 http
->stream
.avail_in
);
1885 bytes
= length
- http
->stream
.avail_out
;
1888 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
1889 "work with compressed streams.");
1891 # endif /* HAVE_INFLATECOPY */
1894 #endif /* HAVE_LIBZ */
1897 if (length
> (size_t)http
->used
)
1898 length
= (size_t)http
->used
;
1900 bytes
= (ssize_t
)length
;
1902 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
1905 memcpy(buffer
, http
->buffer
, length
);
1913 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1916 http
->error
= WSAGetLastError();
1918 if (errno
== EINTR
|| errno
== EAGAIN
)
1921 http
->error
= errno
;
1924 else if (bytes
== 0)
1926 http
->error
= EPIPE
;
1933 /* For OS X 10.8 and earlier */
1934 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
1935 { return (httpPeek(http
, buffer
, length
)); }
1939 * 'httpPost()' - Send a POST request to the server.
1942 int /* O - Status of call (0 = success) */
1943 httpPost(http_t
*http
, /* I - Connection to server */
1944 const char *uri
) /* I - URI for post */
1946 return (http_send(http
, HTTP_STATE_POST
, uri
));
1951 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1956 int /* O - Number of bytes written */
1957 httpPrintf(http_t
*http
, /* I - Connection to server */
1958 const char *format
, /* I - printf-style format string */
1959 ...) /* I - Additional args as needed */
1961 int bytes
; /* Number of bytes to write */
1962 char buf
[16384]; /* Buffer for formatted string */
1963 va_list ap
; /* Variable argument pointer */
1966 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1968 va_start(ap
, format
);
1969 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1972 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
1974 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
1975 return (httpWrite2(http
, buf
, bytes
));
1980 DEBUG_puts("4httpPrintf: flushing existing data...");
1982 if (httpFlushWrite(http
) < 0)
1986 return (http_write(http
, buf
, bytes
));
1992 * 'httpPut()' - Send a PUT request to the server.
1995 int /* O - Status of call (0 = success) */
1996 httpPut(http_t
*http
, /* I - Connection to server */
1997 const char *uri
) /* I - URI to put */
1999 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
2000 return (http_send(http
, HTTP_STATE_PUT
, uri
));
2005 * 'httpRead()' - Read data from a HTTP connection.
2007 * This function is deprecated. Use the httpRead2() function which can
2008 * read more than 2GB of data.
2013 int /* O - Number of bytes read */
2014 httpRead(http_t
*http
, /* I - Connection to server */
2015 char *buffer
, /* I - Buffer for data */
2016 int length
) /* I - Maximum number of bytes */
2018 return ((int)httpRead2(http
, buffer
, length
));
2023 * 'httpRead2()' - Read data from a HTTP connection.
2025 * @since CUPS 1.2/OS X 10.5@
2028 ssize_t
/* O - Number of bytes read */
2029 httpRead2(http_t
*http
, /* I - Connection to server */
2030 char *buffer
, /* I - Buffer for data */
2031 size_t length
) /* I - Maximum number of bytes */
2033 ssize_t bytes
; /* Bytes read */
2037 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2038 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
2039 http
, buffer
, CUPS_LLCAST length
,
2041 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2043 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
2044 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
2045 http
, buffer
, CUPS_LLCAST length
,
2046 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2047 #endif /* HAVE_LIBZ */
2049 if (http
== NULL
|| buffer
== NULL
)
2052 http
->activity
= time(NULL
);
2063 if (http
->stream
.avail_in
> 0)
2065 int zerr
; /* Decompressor error */
2067 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2068 (int)http
->stream
.avail_in
, (int)length
));
2070 http
->stream
.next_out
= (Bytef
*)buffer
;
2071 http
->stream
.avail_out
= length
;
2073 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2075 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2077 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2078 http
->stream
.avail_in
);
2085 bytes
= length
- http
->stream
.avail_out
;
2087 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2088 http
->stream
.avail_in
, http
->stream
.avail_out
,
2096 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2097 /* Additional bytes for buffer */
2101 if (http
->stream
.avail_in
> 0 &&
2102 http
->stream
.next_in
> http
->dbuffer
)
2103 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2105 http
->stream
.next_in
= http
->dbuffer
;
2107 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2108 "decompression buffer.", (int)buflen
));
2110 if (http
->data_remaining
> 0)
2112 if (buflen
> http
->data_remaining
)
2113 buflen
= http
->data_remaining
;
2115 bytes
= http_read_buffered(http
,
2116 (char *)http
->dbuffer
+
2117 http
->stream
.avail_in
, buflen
);
2119 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2120 bytes
= http_read_chunk(http
,
2121 (char *)http
->dbuffer
+
2122 http
->stream
.avail_in
, buflen
);
2128 else if (bytes
== 0)
2131 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2132 "decompression buffer.", CUPS_LLCAST bytes
));
2134 http
->data_remaining
-= bytes
;
2135 http
->stream
.avail_in
+= bytes
;
2137 if (http
->data_remaining
<= 0 &&
2138 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2141 * Read the trailing blank line now...
2144 char len
[32]; /* Length string */
2146 httpGets(len
, sizeof(len
), http
);
2158 #endif /* HAVE_LIBZ */
2159 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2161 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2163 http
->data_remaining
-= bytes
;
2165 if (http
->data_remaining
<= 0)
2168 * Read the trailing blank line now...
2171 char len
[32]; /* Length string */
2173 httpGets(len
, sizeof(len
), http
);
2177 else if (http
->data_remaining
<= 0)
2180 * No more data to read...
2187 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2190 if (length
> (size_t)http
->data_remaining
)
2191 length
= (size_t)http
->data_remaining
;
2193 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2195 http
->data_remaining
-= bytes
;
2197 if (http
->data_remaining
<= 0 &&
2198 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2201 * Read the trailing blank line now...
2204 char len
[32]; /* Length string */
2206 httpGets(len
, sizeof(len
), http
);
2213 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2214 #endif /* HAVE_LIBZ */
2215 ((http
->data_remaining
<= 0 &&
2216 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2217 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2221 http_content_coding_finish(http
);
2222 #endif /* HAVE_LIBZ */
2224 if (http
->state
== HTTP_STATE_POST_RECV
)
2226 else if (http
->state
== HTTP_STATE_GET_SEND
||
2227 http
->state
== HTTP_STATE_POST_SEND
)
2228 http
->state
= HTTP_STATE_WAITING
;
2230 http
->state
= HTTP_STATE_STATUS
;
2232 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2233 http_state_string(http
->state
)));
2240 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
2242 * '_httpReadCDSA()' - Read function for the CDSA library.
2245 OSStatus
/* O - -1 on error, 0 on success */
2247 SSLConnectionRef connection
, /* I - SSL/TLS connection */
2248 void *data
, /* I - Data buffer */
2249 size_t *dataLength
) /* IO - Number of bytes */
2251 OSStatus result
; /* Return value */
2252 ssize_t bytes
; /* Number of bytes read */
2253 http_t
*http
; /* HTTP connection */
2256 http
= (http_t
*)connection
;
2258 if (!http
->blocking
)
2261 * Make sure we have data before we read...
2264 while (!_httpWait(http
, http
->wait_value
, 0))
2266 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2269 http
->error
= ETIMEDOUT
;
2276 bytes
= recv(http
->fd
, data
, *dataLength
, 0);
2278 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
2280 if (bytes
== *dataLength
)
2286 *dataLength
= bytes
;
2287 result
= errSSLWouldBlock
;
2294 result
= errSSLClosedGraceful
;
2295 else if (errno
== EAGAIN
)
2296 result
= errSSLWouldBlock
;
2298 result
= errSSLClosedAbort
;
2303 #endif /* HAVE_SSL && HAVE_CDSASSL */
2306 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
2308 * '_httpReadGNUTLS()' - Read function for the GNU TLS library.
2311 ssize_t
/* O - Number of bytes read or -1 on error */
2313 gnutls_transport_ptr_t ptr
, /* I - Connection to server */
2314 void *data
, /* I - Buffer */
2315 size_t length
) /* I - Number of bytes to read */
2317 http_t
*http
; /* HTTP connection */
2318 ssize_t bytes
; /* Bytes read */
2321 DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
, (int)length
));
2323 http
= (http_t
*)ptr
;
2325 if (!http
->blocking
)
2328 * Make sure we have data before we read...
2331 while (!_httpWait(http
, http
->wait_value
, 0))
2333 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
2336 http
->error
= ETIMEDOUT
;
2341 bytes
= recv(http
->fd
, data
, length
, 0);
2342 DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes
));
2345 #endif /* HAVE_SSL && HAVE_GNUTLS */
2349 * 'httpReadRequest()' - Read a HTTP request from a connection.
2351 * @since CUPS 1.7/OS X 10.9@
2354 http_state_t
/* O - New state of connection */
2355 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2356 char *uri
, /* I - URI buffer */
2357 size_t urilen
) /* I - Size of URI buffer */
2359 char line
[4096], /* HTTP request line */
2360 *req_method
, /* HTTP request method */
2361 *req_uri
, /* HTTP request URI */
2362 *req_version
; /* HTTP request version number string */
2366 * Range check input...
2369 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2370 http
, uri
, CUPS_LLCAST urilen
));
2375 if (!http
|| !uri
|| urilen
< 1)
2377 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2378 return (HTTP_STATE_ERROR
);
2380 else if (http
->state
!= HTTP_STATE_WAITING
)
2382 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2383 http_state_string(http
->state
)));
2384 return (HTTP_STATE_ERROR
);
2391 httpClearFields(http
);
2393 http
->activity
= time(NULL
);
2394 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2395 http
->data_remaining
= 0;
2396 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2397 http
->status
= HTTP_STATUS_OK
;
2398 http
->version
= HTTP_VERSION_1_1
;
2401 * Read a line from the socket...
2404 if (!httpGets(line
, sizeof(line
), http
))
2406 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2407 return (HTTP_STATE_ERROR
);
2412 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2413 return (HTTP_STATE_WAITING
);
2416 DEBUG_printf(("1httpReadRequest: %s", line
));
2425 while (*req_uri
&& !isspace(*req_uri
& 255))
2430 DEBUG_puts("1httpReadRequest: No request URI.");
2431 return (HTTP_STATE_ERROR
);
2436 while (*req_uri
&& isspace(*req_uri
& 255))
2439 req_version
= req_uri
;
2441 while (*req_version
&& !isspace(*req_version
& 255))
2446 DEBUG_puts("1httpReadRequest: No request protocol version.");
2447 return (HTTP_STATE_ERROR
);
2450 *req_version
++ = '\0';
2452 while (*req_version
&& isspace(*req_version
& 255))
2459 if (!strcmp(req_method
, "OPTIONS"))
2460 http
->state
= HTTP_STATE_OPTIONS
;
2461 else if (!strcmp(req_method
, "GET"))
2462 http
->state
= HTTP_STATE_GET
;
2463 else if (!strcmp(req_method
, "HEAD"))
2464 http
->state
= HTTP_STATE_HEAD
;
2465 else if (!strcmp(req_method
, "POST"))
2466 http
->state
= HTTP_STATE_POST
;
2467 else if (!strcmp(req_method
, "PUT"))
2468 http
->state
= HTTP_STATE_PUT
;
2469 else if (!strcmp(req_method
, "DELETE"))
2470 http
->state
= HTTP_STATE_DELETE
;
2471 else if (!strcmp(req_method
, "TRACE"))
2472 http
->state
= HTTP_STATE_TRACE
;
2473 else if (!strcmp(req_method
, "CONNECT"))
2474 http
->state
= HTTP_STATE_CONNECT
;
2477 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2478 return (HTTP_STATE_UNKNOWN_METHOD
);
2481 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2482 http_state_string(http
->state
)));
2484 if (!strcmp(req_version
, "HTTP/1.0"))
2486 http
->version
= HTTP_VERSION_1_0
;
2487 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2489 else if (!strcmp(req_version
, "HTTP/1.1"))
2491 http
->version
= HTTP_VERSION_1_1
;
2492 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2496 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2497 return (HTTP_STATE_UNKNOWN_VERSION
);
2500 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2501 strlcpy(uri
, req_uri
, urilen
);
2503 return (http
->state
);
2508 * 'httpReconnect()' - Reconnect to a HTTP server.
2510 * This function is deprecated. Please use the @link httpReconnect2@ function
2516 int /* O - 0 on success, non-zero on failure */
2517 httpReconnect(http_t
*http
) /* I - Connection to server */
2519 DEBUG_printf(("httpReconnect(http=%p)", http
));
2521 return (httpReconnect2(http
, 30000, NULL
));
2526 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2530 int /* O - 0 on success, non-zero on failure */
2531 httpReconnect2(http_t
*http
, /* I - Connection to server */
2532 int msec
, /* I - Timeout in milliseconds */
2533 int *cancel
) /* I - Pointer to "cancel" variable */
2535 http_addrlist_t
*addr
; /* Connected address */
2537 http_addrlist_t
*current
; /* Current address */
2538 char temp
[256]; /* Temporary address string */
2542 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2547 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2554 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2555 http_shutdown_ssl(http
);
2557 #endif /* HAVE_SSL */
2560 * Close any previously open socket...
2565 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2568 closesocket(http
->fd
);
2577 * Reset all state (except fields, which may be reused)...
2580 http
->state
= HTTP_STATE_WAITING
;
2581 http
->version
= HTTP_VERSION_1_1
;
2582 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2583 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2584 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2585 http
->_data_remaining
= 0;
2587 http
->data_remaining
= 0;
2588 http
->hostaddr
= NULL
;
2592 * Connect to the server...
2596 for (current
= http
->addrlist
; current
; current
= current
->next
)
2597 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2598 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2599 httpAddrPort(&(current
->addr
))));
2602 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2606 * Unable to connect...
2610 http
->error
= WSAGetLastError();
2612 http
->error
= errno
;
2614 http
->status
= HTTP_STATUS_ERROR
;
2616 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2617 strerror(http
->error
)));
2622 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2624 if (http
->timeout_value
> 0)
2625 http_set_timeout(http
->fd
, http
->timeout_value
);
2627 http
->hostaddr
= &(addr
->addr
);
2631 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2634 * Always do encryption via SSL.
2637 if (http_setup_ssl(http
) != 0)
2640 closesocket(http
->fd
);
2648 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2649 return (http_upgrade(http
));
2650 #endif /* HAVE_SSL */
2652 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2653 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2654 httpAddrPort(http
->hostaddr
)));
2661 * 'httpSetAuthString()' - Set the current authorization string.
2663 * This function just stores a copy of the current authorization string in
2664 * the HTTP connection object. You must still call httpSetField() to set
2665 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2666 * httpHead(), httpOptions(), httpPost, or httpPut().
2668 * @since CUPS 1.3/OS X 10.5@
2672 httpSetAuthString(http_t
*http
, /* I - Connection to server */
2673 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2674 const char *data
) /* I - Auth data (NULL for none) */
2677 * Range check input...
2683 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2684 free(http
->authstring
);
2686 http
->authstring
= http
->_authstring
;
2691 * Set the current authorization string...
2694 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2697 if (len
> (int)sizeof(http
->_authstring
))
2699 if ((temp
= malloc(len
)) == NULL
)
2700 len
= sizeof(http
->_authstring
);
2702 http
->authstring
= temp
;
2706 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2708 strlcpy(http
->authstring
, scheme
, len
);
2713 * Clear the current authorization string...
2716 http
->_authstring
[0] = '\0';
2722 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2725 * @since CUPS 1.5/OS X 10.7@
2728 int /* O - Status of call (0 = success) */
2729 httpSetCredentials(http_t
*http
, /* I - Connection to server */
2730 cups_array_t
*credentials
) /* I - Array of credentials */
2732 if (!http
|| cupsArrayCount(credentials
) < 1)
2735 _httpFreeCredentials(http
->tls_credentials
);
2737 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2739 return (http
->tls_credentials
? 0 : -1);
2744 * 'httpSetCookie()' - Set the cookie value(s).
2746 * @since CUPS 1.1.19/OS X 10.3@
2750 httpSetCookie(http_t
*http
, /* I - Connection */
2751 const char *cookie
) /* I - Cookie string */
2760 http
->cookie
= strdup(cookie
);
2762 http
->cookie
= NULL
;
2767 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2769 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2770 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2772 * @since CUPS 1.7/OS X 10.9@
2776 httpSetDefaultField(http_t
*http
, /* I - Connection to server */
2777 http_field_t field
, /* I - Field index */
2778 const char *value
)/* I - Value */
2780 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2781 http
, field
, http_fields
[field
], value
));
2788 case HTTP_FIELD_ACCEPT_ENCODING
:
2789 if (http
->default_accept_encoding
)
2790 _cupsStrFree(http
->default_accept_encoding
);
2792 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2795 case HTTP_FIELD_SERVER
:
2796 if (http
->default_server
)
2797 _cupsStrFree(http
->default_server
);
2799 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2802 case HTTP_FIELD_USER_AGENT
:
2803 if (http
->default_user_agent
)
2804 _cupsStrFree(http
->default_user_agent
);
2806 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2810 DEBUG_puts("1httpSetDefaultField: Ignored.");
2817 * 'httpSetExpect()' - Set the Expect: header in a request.
2819 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2822 * @since CUPS 1.2/OS X 10.5@
2826 httpSetExpect(http_t
*http
, /* I - Connection to server */
2827 http_status_t expect
) /* I - HTTP status to expect
2828 (@code HTTP_STATUS_CONTINUE@) */
2830 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2833 http
->expect
= expect
;
2838 * 'httpSetField()' - Set the value of an HTTP header.
2842 httpSetField(http_t
*http
, /* I - Connection to server */
2843 http_field_t field
, /* I - Field index */
2844 const char *value
) /* I - Value */
2846 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2847 field
, http_fields
[field
], value
));
2850 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2851 field
>= HTTP_FIELD_MAX
||
2857 case HTTP_FIELD_ACCEPT_ENCODING
:
2858 if (http
->accept_encoding
)
2859 _cupsStrFree(http
->accept_encoding
);
2861 http
->accept_encoding
= _cupsStrAlloc(value
);
2864 case HTTP_FIELD_ALLOW
:
2866 _cupsStrFree(http
->allow
);
2868 http
->allow
= _cupsStrAlloc(value
);
2871 case HTTP_FIELD_SERVER
:
2873 _cupsStrFree(http
->server
);
2875 http
->server
= _cupsStrAlloc(value
);
2879 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2883 if (field
== HTTP_FIELD_AUTHORIZATION
)
2886 * Special case for Authorization: as its contents can be
2887 * longer than HTTP_MAX_VALUE
2890 if (http
->field_authorization
)
2891 free(http
->field_authorization
);
2893 http
->field_authorization
= strdup(value
);
2895 else if (field
== HTTP_FIELD_HOST
)
2898 * Special-case for Host: as we don't want a trailing "." on the hostname and
2899 * need to bracket IPv6 numeric addresses.
2902 char *ptr
= strchr(value
, ':');
2904 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2907 * Bracket IPv6 numeric addresses...
2909 * This is slightly inefficient (basically copying twice), but is an edge
2910 * case and not worth optimizing...
2913 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2914 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2919 * Check for a trailing dot on the hostname...
2922 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2926 ptr
+= strlen(ptr
) - 1;
2934 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
2935 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
2937 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
2938 http_content_coding_start(http
, value
);
2940 #endif /* HAVE_LIBZ */
2945 * 'httpSetLength()' - Set the content-length and content-encoding.
2947 * @since CUPS 1.2/OS X 10.5@
2951 httpSetLength(http_t
*http
, /* I - Connection to server */
2952 size_t length
) /* I - Length (0 for chunked) */
2954 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
2955 CUPS_LLCAST length
));
2962 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
2964 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2968 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2969 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2970 CUPS_LLFMT
, CUPS_LLCAST length
);
2976 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2978 * The optional timeout callback receives both the HTTP connection and a user
2979 * data pointer and must return 1 to continue or 0 to error (time) out.
2981 * @since CUPS 1.5/OS X 10.7@
2986 http_t
*http
, /* I - Connection to server */
2987 double timeout
, /* I - Number of seconds for timeout,
2988 must be greater than 0 */
2989 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2990 void *user_data
) /* I - User data pointer */
2992 if (!http
|| timeout
<= 0.0)
2995 http
->timeout_cb
= cb
;
2996 http
->timeout_data
= user_data
;
2997 http
->timeout_value
= timeout
;
3000 http_set_timeout(http
->fd
, timeout
);
3002 http_set_wait(http
);
3007 * 'httpTrace()' - Send an TRACE request to the server.
3010 int /* O - Status of call (0 = success) */
3011 httpTrace(http_t
*http
, /* I - Connection to server */
3012 const char *uri
) /* I - URI for trace */
3014 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
3019 * '_httpUpdate()' - Update the current HTTP status for incoming data.
3021 * Note: Unlike httpUpdate(), this function does not flush pending write data
3022 * and only retrieves a single status line from the HTTP connection.
3025 int /* O - 1 to continue, 0 to stop */
3026 _httpUpdate(http_t
*http
, /* I - Connection to server */
3027 http_status_t
*status
) /* O - Current HTTP status */
3029 char line
[32768], /* Line from connection... */
3030 *value
; /* Pointer to value on line */
3031 http_field_t field
; /* Field index */
3032 int major
, minor
; /* HTTP version numbers */
3035 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
3036 http_state_string(http
->state
)));
3039 * Grab a single line from the connection...
3042 if (!httpGets(line
, sizeof(line
), http
))
3044 *status
= HTTP_STATUS_ERROR
;
3048 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
3050 if (line
[0] == '\0')
3053 * Blank line means the start of the data section (if any). Return
3054 * the result code, too...
3056 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
3057 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
3061 if (http
->status
== HTTP_STATUS_CONTINUE
)
3063 *status
= http
->status
;
3067 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
3068 http
->digest_tries
= 0;
3071 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
3073 if (http_setup_ssl(http
) != 0)
3076 closesocket(http
->fd
);
3081 *status
= http
->status
= HTTP_STATUS_ERROR
;
3085 *status
= HTTP_STATUS_CONTINUE
;
3088 #endif /* HAVE_SSL */
3090 if (http_set_length(http
) < 0)
3092 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
3093 http
->error
= EINVAL
;
3094 http
->status
= *status
= HTTP_STATUS_ERROR
;
3098 switch (http
->state
)
3100 case HTTP_STATE_GET
:
3101 case HTTP_STATE_POST
:
3102 case HTTP_STATE_POST_RECV
:
3103 case HTTP_STATE_PUT
:
3106 DEBUG_printf(("1_httpUpdate: Set state to %s.",
3107 http_state_string(http
->state
)));
3109 case HTTP_STATE_POST_SEND
:
3110 case HTTP_STATE_HEAD
:
3114 http
->state
= HTTP_STATE_WAITING
;
3116 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
3121 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
3122 http_content_coding_start(http
,
3123 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3124 #endif /* HAVE_LIBZ */
3126 *status
= http
->status
;
3129 else if (!strncmp(line
, "HTTP/", 5))
3132 * Got the beginning of a response...
3135 int intstatus
; /* Status value as an integer */
3137 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3139 *status
= http
->status
= HTTP_STATUS_ERROR
;
3143 httpClearFields(http
);
3145 http
->version
= (http_version_t
)(major
* 100 + minor
);
3146 *status
= http
->status
= (http_status_t
)intstatus
;
3148 else if ((value
= strchr(line
, ':')) != NULL
)
3155 while (_cups_isspace(*value
))
3158 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3161 * Be tolerants of servers that send unknown attribute fields...
3164 if (!_cups_strcasecmp(line
, "expect"))
3167 * "Expect: 100-continue" or similar...
3170 http
->expect
= (http_status_t
)atoi(value
);
3172 else if (!_cups_strcasecmp(line
, "cookie"))
3175 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3178 httpSetCookie(http
, value
);
3180 else if ((field
= http_field(line
)) != HTTP_FIELD_UNKNOWN
)
3181 httpSetField(http
, field
, value
);
3184 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3189 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3190 http
->error
= EINVAL
;
3191 http
->status
= *status
= HTTP_STATUS_ERROR
;
3200 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3203 http_status_t
/* O - HTTP status */
3204 httpUpdate(http_t
*http
) /* I - Connection to server */
3206 http_status_t status
; /* Request status */
3209 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3210 http_state_string(http
->state
)));
3213 * Flush pending data, if any...
3218 DEBUG_puts("2httpUpdate: flushing buffer...");
3220 if (httpFlushWrite(http
) < 0)
3221 return (HTTP_STATUS_ERROR
);
3225 * If we haven't issued any commands, then there is nothing to "update"...
3228 if (http
->state
== HTTP_STATE_WAITING
)
3229 return (HTTP_STATUS_CONTINUE
);
3232 * Grab all of the lines we can from the connection...
3235 while (_httpUpdate(http
, &status
));
3238 * See if there was an error...
3241 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3243 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3244 return (http
->status
);
3249 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3250 strerror(http
->error
)));
3251 http
->status
= HTTP_STATUS_ERROR
;
3252 return (HTTP_STATUS_ERROR
);
3256 * Return the current status...
3264 * '_httpWait()' - Wait for data available on a connection (no flush).
3267 int /* O - 1 if data is available, 0 otherwise */
3268 _httpWait(http_t
*http
, /* I - Connection to server */
3269 int msec
, /* I - Milliseconds to wait */
3270 int usessl
) /* I - Use SSL context? */
3273 struct pollfd pfd
; /* Polled file descriptor */
3275 fd_set input_set
; /* select() input set */
3276 struct timeval timeout
; /* Timeout */
3277 #endif /* HAVE_POLL */
3278 int nfds
; /* Result from select()/poll() */
3281 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3285 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3290 * Check the SSL/TLS buffers for data first...
3294 if (http
->tls
&& usessl
)
3297 if (SSL_pending(http
->tls
))
3299 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3303 # elif defined(HAVE_GNUTLS)
3304 if (gnutls_record_check_pending(http
->tls
))
3306 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3310 # elif defined(HAVE_CDSASSL)
3311 size_t bytes
; /* Bytes that are available */
3313 if (!SSLGetBufferedReadSize(http
->tls
, &bytes
) &&
3316 DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
3319 # endif /* HAVE_LIBSSL */
3321 #endif /* HAVE_SSL */
3324 * Then try doing a select() or poll() to poll the socket...
3329 pfd
.events
= POLLIN
;
3333 nfds
= poll(&pfd
, 1, msec
);
3335 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3340 FD_ZERO(&input_set
);
3341 FD_SET(http
->fd
, &input_set
);
3343 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3347 timeout
.tv_sec
= msec
/ 1000;
3348 timeout
.tv_usec
= (msec
% 1000) * 1000;
3350 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3353 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3355 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3358 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3359 WSAGetLastError() == WSAEWOULDBLOCK
));
3361 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3363 #endif /* HAVE_POLL */
3365 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3373 * 'httpWait()' - Wait for data available on a connection.
3375 * @since CUPS 1.1.19/OS X 10.3@
3378 int /* O - 1 if data is available, 0 otherwise */
3379 httpWait(http_t
*http
, /* I - Connection to server */
3380 int msec
) /* I - Milliseconds to wait */
3383 * First see if there is data in the buffer...
3386 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3393 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3398 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3400 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3403 #endif /* HAVE_LIBZ */
3406 * Flush pending data, if any...
3411 DEBUG_puts("3httpWait: Flushing write buffer.");
3413 if (httpFlushWrite(http
) < 0)
3418 * If not, check the SSL/TLS buffers and do a select() on the connection...
3421 return (_httpWait(http
, msec
, 1));
3426 * 'httpWrite()' - Write data to a HTTP connection.
3428 * This function is deprecated. Use the httpWrite2() function which can
3429 * write more than 2GB of data.
3434 int /* O - Number of bytes written */
3435 httpWrite(http_t
*http
, /* I - Connection to server */
3436 const char *buffer
, /* I - Buffer for data */
3437 int length
) /* I - Number of bytes to write */
3439 return ((int)httpWrite2(http
, buffer
, length
));
3444 * 'httpWrite2()' - Write data to a HTTP connection.
3446 * @since CUPS 1.2/OS X 10.5@
3449 ssize_t
/* O - Number of bytes written */
3450 httpWrite2(http_t
*http
, /* I - Connection to server */
3451 const char *buffer
, /* I - Buffer for data */
3452 size_t length
) /* I - Number of bytes to write */
3454 ssize_t bytes
; /* Bytes written */
3457 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3458 buffer
, CUPS_LLCAST length
));
3461 * Range check input...
3464 if (!http
|| !buffer
)
3466 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3471 * Mark activity on the connection...
3474 http
->activity
= time(NULL
);
3477 * Buffer small writes for better performance...
3483 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3487 http_content_coding_finish(http
);
3492 http
->stream
.next_in
= (Bytef
*)buffer
;
3493 http
->stream
.avail_in
= length
;
3494 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3495 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3497 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3499 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3501 if (http
->stream
.avail_out
== 0)
3503 if (httpFlushWrite(http
) < 0)
3505 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3509 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3510 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3514 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3519 #endif /* HAVE_LIBZ */
3522 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3524 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3525 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3527 httpFlushWrite(http
);
3530 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3531 length
< sizeof(http
->wbuffer
))
3534 * Write to buffer...
3537 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3538 CUPS_LLCAST length
));
3540 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3541 http
->wused
+= (int)length
;
3542 bytes
= (ssize_t
)length
;
3547 * Otherwise write the data directly...
3550 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3551 CUPS_LLCAST length
));
3553 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3554 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3556 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3558 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3559 CUPS_LLCAST bytes
));
3562 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3563 http
->data_remaining
-= bytes
;
3569 * Handle end-of-request processing...
3572 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3573 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3576 * Finished with the transfer; unless we are sending POST or PUT
3582 http_content_coding_finish(http
);
3583 #endif /* HAVE_LIBZ */
3587 if (httpFlushWrite(http
) < 0)
3591 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3594 * Send a 0-length chunk at the end of the request...
3597 http_write(http
, "0\r\n\r\n", 5);
3600 * Reset the data state...
3603 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3604 http
->data_remaining
= 0;
3607 if (http
->state
== HTTP_STATE_POST_RECV
)
3609 else if (http
->state
== HTTP_STATE_POST_SEND
)
3610 http
->state
= HTTP_STATE_WAITING
;
3612 http
->state
= HTTP_STATE_STATUS
;
3614 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3615 http_state_string(http
->state
)));
3618 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3624 #if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
3626 * '_httpWriteCDSA()' - Write function for the CDSA library.
3629 OSStatus
/* O - -1 on error, 0 on success */
3631 SSLConnectionRef connection
, /* I - SSL/TLS connection */
3632 const void *data
, /* I - Data buffer */
3633 size_t *dataLength
) /* IO - Number of bytes */
3635 OSStatus result
; /* Return value */
3636 ssize_t bytes
; /* Number of bytes read */
3637 http_t
*http
; /* HTTP connection */
3640 http
= (http_t
*)connection
;
3644 bytes
= write(http
->fd
, data
, *dataLength
);
3646 while (bytes
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
3648 if (bytes
== *dataLength
)
3652 else if (bytes
>= 0)
3654 *dataLength
= bytes
;
3655 result
= errSSLWouldBlock
;
3661 if (errno
== EAGAIN
)
3662 result
= errSSLWouldBlock
;
3664 result
= errSSLClosedAbort
;
3669 #endif /* HAVE_SSL && HAVE_CDSASSL */
3672 #if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
3674 * '_httpWriteGNUTLS()' - Write function for the GNU TLS library.
3677 ssize_t
/* O - Number of bytes written or -1 on error */
3679 gnutls_transport_ptr_t ptr
, /* I - Connection to server */
3680 const void *data
, /* I - Data buffer */
3681 size_t length
) /* I - Number of bytes to write */
3683 ssize_t bytes
; /* Bytes written */
3686 DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr
, data
,
3689 http_debug_hex("_httpWriteGNUTLS", data
, (int)length
);
3692 bytes
= send(((http_t
*)ptr
)->fd
, data
, length
, 0);
3693 DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes
));
3697 #endif /* HAVE_SSL && HAVE_GNUTLS */
3701 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3703 * @since CUPS 1.7/OS X 10.9@
3706 int /* O - 0 on success, -1 on error */
3707 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3708 http_status_t status
) /* I - Status code */
3710 http_encoding_t old_encoding
; /* Old data_encoding value */
3711 off_t old_remaining
; /* Old data_remaining value */
3715 * Range check input...
3718 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3720 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3722 DEBUG_puts("1httpWriteResponse: Bad input.");
3727 * Set the various standard fields if they aren't already...
3730 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3731 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3733 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3735 http
->keep_alive
= 0;
3736 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3739 if (http
->version
== HTTP_VERSION_1_1
)
3741 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3743 if (http
->keep_alive
)
3744 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3746 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3749 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3750 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3754 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
)
3756 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3757 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3759 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3760 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3762 #endif /* HAVE_SSL */
3765 httpSetField(http
, HTTP_FIELD_SERVER
,
3766 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3769 * Set the Accept-Encoding field if it isn't already...
3772 if (!http
->accept_encoding
)
3773 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3774 http
->default_accept_encoding
? http
->default_accept_encoding
:
3776 "gzip, deflate, identity");
3779 #endif /* HAVE_LIBZ */
3782 * Send the response header...
3785 old_encoding
= http
->data_encoding
;
3786 old_remaining
= http
->data_remaining
;
3787 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3789 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3790 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3792 http
->status
= HTTP_STATUS_ERROR
;
3796 if (status
!= HTTP_STATUS_CONTINUE
)
3799 * 100 Continue doesn't have the rest of the response headers...
3802 int i
; /* Looping var */
3803 const char *value
; /* Field value */
3805 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3807 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3809 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3811 http
->status
= HTTP_STATUS_ERROR
;
3819 if (httpPrintf(http
, "Set-Cookie: %s path=/%s\r\n", http
->cookie
,
3820 http
->tls
? " secure" : "") < 1)
3822 http
->status
= HTTP_STATUS_ERROR
;
3828 if (httpWrite2(http
, "\r\n", 2) < 2)
3830 http
->status
= HTTP_STATUS_ERROR
;
3834 if (httpFlushWrite(http
) < 0)
3836 http
->status
= HTTP_STATUS_ERROR
;
3840 if (status
== HTTP_STATUS_CONTINUE
)
3843 * Restore the old data_encoding and data_length values...
3846 http
->data_encoding
= old_encoding
;
3847 http
->data_remaining
= old_remaining
;
3849 if (old_remaining
<= INT_MAX
)
3850 http
->_data_remaining
= (int)old_remaining
;
3852 http
->_data_remaining
= INT_MAX
;
3854 else if (http
->state
== HTTP_STATE_OPTIONS
||
3855 http
->state
== HTTP_STATE_HEAD
||
3856 http
->state
== HTTP_STATE_PUT
||
3857 http
->state
== HTTP_STATE_TRACE
||
3858 http
->state
== HTTP_STATE_CONNECT
||
3859 http
->state
== HTTP_STATE_STATUS
)
3861 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3862 "was %s.", http_state_string(http
->state
)));
3863 http
->state
= HTTP_STATE_WAITING
;
3868 * Force data_encoding and data_length to be set according to the response
3872 http_set_length(http
);
3876 * Then start any content encoding...
3879 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
3880 http_content_coding_start(http
,
3881 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3882 #endif /* HAVE_LIBZ */
3889 #if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
3891 * 'http_bio_ctrl()' - Control the HTTP connection.
3894 static long /* O - Result/data */
3895 http_bio_ctrl(BIO
*h
, /* I - BIO data */
3896 int cmd
, /* I - Control command */
3897 long arg1
, /* I - First argument */
3898 void *arg2
) /* I - Second argument */
3905 case BIO_CTRL_RESET
:
3909 case BIO_C_SET_FILE_PTR
:
3914 case BIO_C_GET_FILE_PTR
:
3917 *((void **)arg2
) = h
->ptr
;
3924 case BIO_CTRL_FLUSH
:
3931 * 'http_bio_free()' - Free OpenSSL data.
3934 static int /* O - 1 on success, 0 on failure */
3935 http_bio_free(BIO
*h
) /* I - BIO data */
3951 * 'http_bio_new()' - Initialize an OpenSSL BIO structure.
3954 static int /* O - 1 on success, 0 on failure */
3955 http_bio_new(BIO
*h
) /* I - BIO data */
3970 * 'http_bio_puts()' - Send a string for OpenSSL.
3973 static int /* O - Bytes written */
3974 http_bio_puts(BIO
*h
, /* I - BIO data */
3975 const char *str
) /* I - String to write */
3978 return (send(((http_t
*)h
->ptr
)->fd
, str
, (int)strlen(str
), 0));
3980 return (send(((http_t
*)h
->ptr
)->fd
, str
, strlen(str
), 0));
3986 * 'http_bio_read()' - Read data for OpenSSL.
3989 static int /* O - Bytes read */
3990 http_bio_read(BIO
*h
, /* I - BIO data */
3991 char *buf
, /* I - Buffer */
3992 int size
) /* I - Number of bytes to read */
3994 http_t
*http
; /* HTTP connection */
3997 http
= (http_t
*)h
->ptr
;
3999 if (!http
->blocking
)
4002 * Make sure we have data before we read...
4005 while (!_httpWait(http
, http
->wait_value
, 0))
4007 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4011 http
->error
= WSAETIMEDOUT
;
4013 http
->error
= ETIMEDOUT
;
4020 return (recv(http
->fd
, buf
, size
, 0));
4025 * 'http_bio_write()' - Write data for OpenSSL.
4028 static int /* O - Bytes written */
4029 http_bio_write(BIO
*h
, /* I - BIO data */
4030 const char *buf
, /* I - Buffer to write */
4031 int num
) /* I - Number of bytes to write */
4033 return (send(((http_t
*)h
->ptr
)->fd
, buf
, num
, 0));
4035 #endif /* HAVE_SSL && HAVE_LIBSSL */
4040 * 'http_content_coding_finish()' - Finish doing any content encoding.
4044 http_content_coding_finish(
4045 http_t
*http
) /* I - HTTP connection */
4047 int zerr
; /* Compression status */
4048 Byte dummy
[1]; /* Dummy read buffer */
4051 switch (http
->coding
)
4053 case _HTTP_CODING_DEFLATE
:
4054 case _HTTP_CODING_GZIP
:
4055 http
->stream
.next_in
= dummy
;
4056 http
->stream
.avail_in
= 0;
4060 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
4061 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
4063 zerr
= deflate(&(http
->stream
), Z_FINISH
);
4065 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
4066 if (http
->wused
== sizeof(http
->wbuffer
))
4067 httpFlushWrite(http
);
4069 while (zerr
== Z_OK
);
4071 deflateEnd(&(http
->stream
));
4074 httpFlushWrite(http
);
4077 case _HTTP_CODING_INFLATE
:
4078 case _HTTP_CODING_GUNZIP
:
4079 inflateEnd(&(http
->stream
));
4080 free(http
->dbuffer
);
4081 http
->dbuffer
= NULL
;
4088 http
->coding
= _HTTP_CODING_IDENTITY
;
4093 * 'http_content_coding_start()' - Start doing content encoding.
4097 http_content_coding_start(
4098 http_t
*http
, /* I - HTTP connection */
4099 const char *value
) /* I - Value of Content-Encoding */
4101 int zerr
; /* Error/status */
4102 _http_coding_t coding
; /* Content coding value */
4105 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
4108 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
4110 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
4114 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
4116 if (http
->state
== HTTP_STATE_GET_SEND
||
4117 http
->state
== HTTP_STATE_POST_SEND
)
4118 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
4119 _HTTP_CODING_GUNZIP
;
4120 else if (http
->state
== HTTP_STATE_POST_RECV
||
4121 http
->state
== HTTP_STATE_PUT_RECV
)
4122 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
4123 _HTTP_CODING_GUNZIP
;
4126 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4130 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
4132 if (http
->state
== HTTP_STATE_GET_SEND
||
4133 http
->state
== HTTP_STATE_POST_SEND
)
4134 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
4135 _HTTP_CODING_INFLATE
;
4136 else if (http
->state
== HTTP_STATE_POST_RECV
||
4137 http
->state
== HTTP_STATE_PUT_RECV
)
4138 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
4139 _HTTP_CODING_INFLATE
;
4142 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4148 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
4152 memset(&(http
->stream
), 0, sizeof(http
->stream
));
4156 case _HTTP_CODING_DEFLATE
:
4157 case _HTTP_CODING_GZIP
:
4159 httpFlushWrite(http
);
4162 * Window size for compression is 11 bits - optimal based on PWG Raster
4163 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
4167 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
4169 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
4170 Z_DEFAULT_STRATEGY
)) < Z_OK
)
4172 http
->status
= HTTP_STATUS_ERROR
;
4173 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4178 case _HTTP_CODING_INFLATE
:
4179 case _HTTP_CODING_GUNZIP
:
4180 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
4182 http
->status
= HTTP_STATUS_ERROR
;
4183 http
->error
= errno
;
4188 * Window size for decompression is up to 15 bits (maximum supported).
4189 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
4192 if ((zerr
= inflateInit2(&(http
->stream
),
4193 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
4196 free(http
->dbuffer
);
4197 http
->dbuffer
= NULL
;
4198 http
->status
= HTTP_STATUS_ERROR
;
4199 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
4203 http
->stream
.avail_in
= 0;
4204 http
->stream
.next_in
= http
->dbuffer
;
4211 http
->coding
= coding
;
4213 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
4216 #endif /* HAVE_LIBZ */
4220 * 'http_create()' - Create an unconnected HTTP connection.
4223 static http_t
* /* O - HTTP connection */
4225 const char *host
, /* I - Hostname */
4226 int port
, /* I - Port number */
4227 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
4228 int family
, /* I - Address family or AF_UNSPEC */
4229 http_encryption_t encryption
, /* I - Encryption to use */
4230 int blocking
, /* I - 1 for blocking mode */
4231 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
4233 http_t
*http
; /* New HTTP connection */
4234 char service
[255]; /* Service name */
4235 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
4238 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
4239 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
4240 family
, encryption
, blocking
, mode
));
4242 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
4248 * Lookup the host...
4253 myaddrlist
= httpAddrCopyList(addrlist
);
4257 snprintf(service
, sizeof(service
), "%d", port
);
4259 myaddrlist
= httpAddrGetList(host
, family
, service
);
4266 * Allocate memory for the structure...
4269 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
4271 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
4272 httpAddrFreeList(addrlist
);
4277 * Initialize the HTTP data...
4281 http
->activity
= time(NULL
);
4282 http
->addrlist
= myaddrlist
;
4283 http
->blocking
= blocking
;
4286 http
->gssctx
= GSS_C_NO_CONTEXT
;
4287 http
->gssname
= GSS_C_NO_NAME
;
4288 #endif /* HAVE_GSSAPI */
4289 http
->status
= HTTP_STATUS_CONTINUE
;
4290 http
->version
= HTTP_VERSION_1_1
;
4293 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
4295 if (port
== 443) /* Always use encryption for https */
4296 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
4298 http
->encryption
= encryption
;
4300 http_set_wait(http
);
4303 * Return the new structure...
4309 /* For OS X 10.8 and earlier */
4310 http_t
*_httpCreate(const char *host
, int port
, http_addrlist_t
*addrlist
,
4311 http_encryption_t encryption
, int family
)
4312 { return (http_create(host
, port
, addrlist
, family
, encryption
, 1,
4313 _HTTP_MODE_CLIENT
)); }
4318 * 'http_debug_hex()' - Do a hex dump of a buffer.
4322 http_debug_hex(const char *prefix
, /* I - Prefix for line */
4323 const char *buffer
, /* I - Buffer to dump */
4324 int bytes
) /* I - Bytes to dump */
4326 int i
, j
, /* Looping vars */
4327 ch
; /* Current character */
4328 char line
[255], /* Line buffer */
4329 *start
, /* Start of line after prefix */
4330 *ptr
; /* Pointer into line */
4333 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
4336 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
4338 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
4339 start
= line
+ strlen(line
);
4341 for (i
= 0; i
< bytes
; i
+= 16)
4343 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
4344 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
4348 memcpy(ptr
, " ", 3);
4353 memcpy(ptr
, " ", 3);
4356 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
4358 ch
= buffer
[i
+ j
] & 255;
4360 if (ch
< ' ' || ch
>= 127)
4374 * 'http_field()' - Return the field index for a field name.
4377 static http_field_t
/* O - Field index */
4378 http_field(const char *name
) /* I - String name */
4380 int i
; /* Looping var */
4383 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4384 if (_cups_strcasecmp(name
, http_fields
[i
]) == 0)
4385 return ((http_field_t
)i
);
4387 return (HTTP_FIELD_UNKNOWN
);
4392 * 'http_read()' - Read a buffer from a HTTP connection.
4394 * This function does the low-level read from the socket, retrying and timing
4398 static ssize_t
/* O - Number of bytes read or -1 on error */
4399 http_read(http_t
*http
, /* I - Connection to server */
4400 char *buffer
, /* I - Buffer */
4401 size_t length
) /* I - Maximum bytes to read */
4403 ssize_t bytes
; /* Bytes read */
4406 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4407 buffer
, CUPS_LLCAST length
));
4409 if (!http
->blocking
)
4411 while (!httpWait(http
, http
->wait_value
))
4413 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4416 DEBUG_puts("2http_read: Timeout.");
4421 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4427 bytes
= http_read_ssl(http
, buffer
, length
);
4429 #endif /* HAVE_SSL */
4430 bytes
= recv(http
->fd
, buffer
, length
, 0);
4435 if (WSAGetLastError() != WSAEINTR
)
4437 http
->error
= WSAGetLastError();
4440 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4442 if (!http
->timeout_cb
||
4443 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4445 http
->error
= WSAEWOULDBLOCK
;
4450 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4452 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4454 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4456 http
->error
= errno
;
4459 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4461 http
->error
= errno
;
4465 else if (errno
!= EINTR
)
4467 http
->error
= errno
;
4475 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4476 CUPS_LLCAST bytes
));
4479 http_debug_hex("http_read", buffer
, (int)bytes
);
4485 if (WSAGetLastError() == WSAEINTR
)
4488 http
->error
= WSAGetLastError();
4490 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4493 http
->error
= errno
;
4496 else if (bytes
== 0)
4498 http
->error
= EPIPE
;
4507 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4509 * This function reads data from the HTTP buffer or from the socket, as needed.
4512 static ssize_t
/* O - Number of bytes read or -1 on error */
4513 http_read_buffered(http_t
*http
, /* I - Connection to server */
4514 char *buffer
, /* I - Buffer */
4515 size_t length
) /* I - Maximum bytes to read */
4517 ssize_t bytes
; /* Bytes read */
4520 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4522 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4526 if (length
> (size_t)http
->used
)
4527 bytes
= (size_t)http
->used
;
4531 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4534 memcpy(buffer
, http
->buffer
, bytes
);
4535 http
->used
-= (int)bytes
;
4538 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4541 bytes
= http_read(http
, buffer
, length
);
4548 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4550 * This function reads and validates the chunk length, then does a buffered read
4551 * returning the number of bytes placed in the buffer.
4554 static ssize_t
/* O - Number of bytes read or -1 on error */
4555 http_read_chunk(http_t
*http
, /* I - Connection to server */
4556 char *buffer
, /* I - Buffer */
4557 size_t length
) /* I - Maximum bytes to read */
4559 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4560 http
, buffer
, CUPS_LLCAST length
));
4562 if (http
->data_remaining
<= 0)
4564 char len
[32]; /* Length string */
4566 if (!httpGets(len
, sizeof(len
), http
))
4568 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4574 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4575 if (!httpGets(len
, sizeof(len
), http
))
4577 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4582 http
->data_remaining
= strtoll(len
, NULL
, 16);
4584 if (http
->data_remaining
< 0)
4586 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4587 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4591 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4592 len
, CUPS_LLCAST http
->data_remaining
));
4594 if (http
->data_remaining
== 0)
4597 * 0-length chunk, grab trailing blank line...
4600 httpGets(len
, sizeof(len
), http
);
4604 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4605 CUPS_LLCAST http
->data_remaining
));
4607 if (http
->data_remaining
<= 0)
4609 else if (length
> (size_t)http
->data_remaining
)
4610 length
= (size_t)http
->data_remaining
;
4612 return (http_read_buffered(http
, buffer
, length
));
4618 * 'http_read_ssl()' - Read from a SSL/TLS connection.
4621 static int /* O - Bytes read */
4622 http_read_ssl(http_t
*http
, /* I - Connection to server */
4623 char *buf
, /* I - Buffer to store data */
4624 int len
) /* I - Length of buffer */
4626 # if defined(HAVE_LIBSSL)
4627 return (SSL_read((SSL
*)(http
->tls
), buf
, len
));
4629 # elif defined(HAVE_GNUTLS)
4630 ssize_t result
; /* Return value */
4633 result
= gnutls_record_recv(http
->tls
, buf
, len
);
4635 if (result
< 0 && !errno
)
4638 * Convert GNU TLS error to errno value...
4643 case GNUTLS_E_INTERRUPTED
:
4647 case GNUTLS_E_AGAIN
:
4659 return ((int)result
);
4661 # elif defined(HAVE_CDSASSL)
4662 int result
; /* Return value */
4663 OSStatus error
; /* Error info */
4664 size_t processed
; /* Number of bytes processed */
4667 error
= SSLRead(http
->tls
, buf
, len
, &processed
);
4668 DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error
,
4673 result
= (int)processed
;
4676 case errSSLWouldBlock
:
4678 result
= (int)processed
;
4686 case errSSLClosedGraceful
:
4689 result
= (int)processed
;
4700 # elif defined(HAVE_SSPISSL)
4701 return _sspiRead((_sspi_struct_t
*) http
->tls
, buf
, len
);
4702 # endif /* HAVE_LIBSSL */
4704 #endif /* HAVE_SSL */
4708 * 'http_send()' - Send a request with all fields and the trailing blank line.
4711 static int /* O - 0 on success, non-zero on error */
4712 http_send(http_t
*http
, /* I - Connection to server */
4713 http_state_t request
, /* I - Request code */
4714 const char *uri
) /* I - URI */
4716 int i
; /* Looping var */
4717 char buf
[1024]; /* Encoded URI buffer */
4718 const char *value
; /* Field value */
4719 static const char * const codes
[] = /* Request code strings */
4739 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4740 http
, codes
[request
], uri
));
4742 if (http
== NULL
|| uri
== NULL
)
4746 * Set the User-Agent field if it isn't already...
4749 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4751 if (http
->default_user_agent
)
4752 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4754 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4758 * Set the Accept-Encoding field if it isn't already...
4761 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4762 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4763 http
->default_accept_encoding
);
4766 * Encode the URI as needed...
4769 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4772 * See if we had an error the last time around; if so, reconnect...
4775 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4776 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4778 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4779 http
->fd
, http
->status
, http
->tls_upgrade
));
4781 if (httpReconnect2(http
, 30000, NULL
))
4786 * Flush any written data that is pending...
4791 if (httpFlushWrite(http
) < 0)
4792 if (httpReconnect2(http
, 30000, NULL
))
4797 * Send the request header...
4800 http
->state
= request
;
4801 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4803 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4806 http
->status
= HTTP_STATUS_CONTINUE
;
4809 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4811 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4812 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4814 #endif /* HAVE_SSL */
4816 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4818 http
->status
= HTTP_STATUS_ERROR
;
4822 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4823 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4825 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
4827 if (i
== HTTP_FIELD_HOST
)
4829 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4830 httpAddrPort(http
->hostaddr
)) < 1)
4832 http
->status
= HTTP_STATUS_ERROR
;
4836 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4838 http
->status
= HTTP_STATUS_ERROR
;
4844 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4846 http
->status
= HTTP_STATUS_ERROR
;
4850 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
4851 http
->mode
, http
->state
));
4853 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4854 (http
->state
== HTTP_STATE_POST_RECV
||
4855 http
->state
== HTTP_STATE_PUT_RECV
))
4856 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4858 http
->status
= HTTP_STATUS_ERROR
;
4862 if (httpPrintf(http
, "\r\n") < 1)
4864 http
->status
= HTTP_STATUS_ERROR
;
4868 if (httpFlushWrite(http
) < 0)
4871 http_set_length(http
);
4872 httpClearFields(http
);
4875 * The Kerberos and AuthRef authentication strings can only be used once...
4878 if (http
->field_authorization
&& http
->authstring
&&
4879 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4880 !strncmp(http
->authstring
, "AuthRef", 7)))
4882 http
->_authstring
[0] = '\0';
4884 if (http
->authstring
!= http
->_authstring
)
4885 free(http
->authstring
);
4887 http
->authstring
= http
->_authstring
;
4895 # if defined(HAVE_CDSASSL)
4897 * 'http_set_credentials()' - Set the SSL/TLS credentials.
4900 static int /* O - Status of connection */
4901 http_set_credentials(http_t
*http
) /* I - Connection to server */
4903 _cups_globals_t
*cg
= _cupsGlobals(); /* Pointer to library globals */
4904 OSStatus error
= 0; /* Error code */
4905 http_tls_credentials_t credentials
= NULL
;
4906 /* TLS credentials */
4909 DEBUG_printf(("7http_set_credentials(%p)", http
));
4912 * Prefer connection specific credentials...
4915 if ((credentials
= http
->tls_credentials
) == NULL
)
4916 credentials
= cg
->tls_credentials
;
4920 error
= SSLSetCertificate(http
->tls
, credentials
);
4921 DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
4925 DEBUG_puts("4http_set_credentials: No credentials to set.");
4929 # endif /* HAVE_CDSASSL */
4930 #endif /* HAVE_SSL */
4934 * 'http_set_length()' - Set the data_encoding and data_remaining values.
4937 static off_t
/* O - Remainder or -1 on error */
4938 http_set_length(http_t
*http
) /* I - Connection */
4940 off_t remaining
; /* Remainder */
4943 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
4944 http_state_string(http
->state
)));
4946 if ((remaining
= httpGetLength2(http
)) >= 0)
4948 if (http
->mode
== _HTTP_MODE_SERVER
&&
4949 http
->state
!= HTTP_STATE_GET_SEND
&&
4950 http
->state
!= HTTP_STATE_PUT
&&
4951 http
->state
!= HTTP_STATE_POST
&&
4952 http
->state
!= HTTP_STATE_POST_SEND
)
4954 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
4958 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
4961 DEBUG_puts("1http_set_length: Setting data_encoding to "
4962 "HTTP_ENCODING_CHUNKED.");
4963 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
4967 DEBUG_puts("1http_set_length: Setting data_encoding to "
4968 "HTTP_ENCODING_LENGTH.");
4969 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4972 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
4973 CUPS_LLCAST remaining
));
4974 http
->data_remaining
= remaining
;
4976 if (remaining
<= INT_MAX
)
4977 http
->_data_remaining
= remaining
;
4979 http
->_data_remaining
= INT_MAX
;
4986 * 'http_set_timeout()' - Set the socket timeout values.
4990 http_set_timeout(int fd
, /* I - File descriptor */
4991 double timeout
) /* I - Timeout in seconds */
4994 DWORD tv
= (DWORD
)(timeout
* 1000);
4995 /* Timeout in milliseconds */
4997 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4998 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5001 struct timeval tv
; /* Timeout in secs and usecs */
5003 tv
.tv_sec
= (int)timeout
;
5004 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
5006 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5007 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
5013 * 'http_set_wait()' - Set the default wait value for reads.
5017 http_set_wait(http_t
*http
) /* I - Connection to server */
5021 http
->wait_value
= (int)(http
->timeout_value
* 1000);
5023 if (http
->wait_value
<= 0)
5024 http
->wait_value
= 60000;
5027 http
->wait_value
= 10000;
5033 * 'http_setup_ssl()' - Set up SSL/TLS support on a connection.
5036 static int /* O - 0 on success, -1 on failure */
5037 http_setup_ssl(http_t
*http
) /* I - Connection to server */
5039 char hostname
[256], /* Hostname */
5040 *hostptr
; /* Pointer into hostname */
5043 SSL_CTX
*context
; /* Context for encryption */
5044 BIO
*bio
; /* BIO data */
5045 const char *message
= NULL
;/* Error message */
5046 # elif defined(HAVE_GNUTLS)
5047 int status
; /* Status of handshake */
5048 gnutls_certificate_client_credentials
*credentials
;
5049 /* TLS credentials */
5050 # elif defined(HAVE_CDSASSL)
5051 _cups_globals_t
*cg
= _cupsGlobals();
5052 /* Pointer to library globals */
5053 OSStatus error
; /* Error code */
5054 const char *message
= NULL
;/* Error message */
5055 cups_array_t
*credentials
; /* Credentials array */
5056 cups_array_t
*names
; /* CUPS distinguished names */
5057 CFArrayRef dn_array
; /* CF distinguished names array */
5058 CFIndex count
; /* Number of credentials */
5059 CFDataRef data
; /* Certificate data */
5060 int i
; /* Looping var */
5061 http_credential_t
*credential
; /* Credential data */
5062 # elif defined(HAVE_SSPISSL)
5063 TCHAR username
[256]; /* Username returned from GetUserName() */
5064 TCHAR commonName
[256];/* Common name for certificate */
5065 DWORD dwSize
; /* 32 bit size */
5066 # endif /* HAVE_LIBSSL */
5069 DEBUG_printf(("7http_setup_ssl(http=%p)", http
));
5072 * Get the hostname to use for SSL...
5075 if (httpAddrLocalhost(http
->hostaddr
))
5077 strlcpy(hostname
, "localhost", sizeof(hostname
));
5082 * Otherwise make sure the hostname we have does not end in a trailing dot.
5085 strlcpy(hostname
, http
->hostname
, sizeof(hostname
));
5086 if ((hostptr
= hostname
+ strlen(hostname
) - 1) >= hostname
&&
5092 context
= SSL_CTX_new(SSLv23_client_method());
5094 SSL_CTX_set_options(context
, SSL_OP_NO_SSLv2
); /* Only use SSLv3 or TLS */
5096 bio
= BIO_new(_httpBIOMethods());
5097 BIO_ctrl(bio
, BIO_C_SET_FILE_PTR
, 0, (char *)http
);
5099 http
->tls
= SSL_new(context
);
5100 SSL_set_bio(http
->tls
, bio
, bio
);
5102 # ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
5103 SSL_set_tlsext_host_name(http
->tls
, hostname
);
5104 # endif /* HAVE_SSL_SET_TLSEXT_HOST_NAME */
5106 if (SSL_connect(http
->tls
) != 1)
5108 unsigned long error
; /* Error code */
5110 while ((error
= ERR_get_error()) != 0)
5112 message
= ERR_error_string(error
, NULL
);
5113 DEBUG_printf(("8http_setup_ssl: %s", message
));
5116 SSL_CTX_free(context
);
5117 SSL_free(http
->tls
);
5121 http
->error
= WSAGetLastError();
5123 http
->error
= errno
;
5125 http
->status
= HTTP_STATUS_ERROR
;
5128 message
= _("Unable to establish a secure connection to host.");
5130 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5135 # elif defined(HAVE_GNUTLS)
5136 credentials
= (gnutls_certificate_client_credentials
*)
5137 malloc(sizeof(gnutls_certificate_client_credentials
));
5138 if (credentials
== NULL
)
5140 DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
5142 http
->error
= errno
;
5143 http
->status
= HTTP_STATUS_ERROR
;
5144 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5149 gnutls_certificate_allocate_credentials(credentials
);
5151 gnutls_init(&http
->tls
, GNUTLS_CLIENT
);
5152 gnutls_set_default_priority(http
->tls
);
5153 gnutls_server_name_set(http
->tls
, GNUTLS_NAME_DNS
, hostname
,
5155 gnutls_credentials_set(http
->tls
, GNUTLS_CRD_CERTIFICATE
, *credentials
);
5156 gnutls_transport_set_ptr(http
->tls
, (gnutls_transport_ptr_t
)http
);
5157 gnutls_transport_set_pull_function(http
->tls
, _httpReadGNUTLS
);
5158 gnutls_transport_set_push_function(http
->tls
, _httpWriteGNUTLS
);
5160 while ((status
= gnutls_handshake(http
->tls
)) != GNUTLS_E_SUCCESS
)
5162 DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
5163 status
, gnutls_strerror(status
)));
5165 if (gnutls_error_is_fatal(status
))
5168 http
->status
= HTTP_STATUS_ERROR
;
5170 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, gnutls_strerror(status
), 0);
5172 gnutls_deinit(http
->tls
);
5173 gnutls_certificate_free_credentials(*credentials
);
5181 http
->tls_credentials
= credentials
;
5183 # elif defined(HAVE_CDSASSL)
5184 if ((http
->tls
= SSLCreateContext(kCFAllocatorDefault
, kSSLClientSide
,
5185 kSSLStreamType
)) == NULL
)
5187 DEBUG_puts("4http_setup_ssl: SSLCreateContext failed.");
5188 http
->error
= errno
= ENOMEM
;
5189 http
->status
= HTTP_STATUS_ERROR
;
5190 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5195 error
= SSLSetConnection(http
->tls
, http
);
5196 DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error
));
5200 error
= SSLSetIOFuncs(http
->tls
, _httpReadCDSA
, _httpWriteCDSA
);
5201 DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error
));
5206 error
= SSLSetSessionOption(http
->tls
, kSSLSessionOptionBreakOnServerAuth
,
5208 DEBUG_printf(("4http_setup_ssl: SSLSetSessionOption, error=%d",
5214 if (cg
->client_cert_cb
)
5216 error
= SSLSetSessionOption(http
->tls
,
5217 kSSLSessionOptionBreakOnCertRequested
, true);
5218 DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
5219 "error=%d", (int)error
));
5223 error
= http_set_credentials(http
);
5224 DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
5230 * Let the server know which hostname/domain we are trying to connect to
5231 * in case it wants to serve up a certificate with a matching common name.
5236 error
= SSLSetPeerDomainName(http
->tls
, hostname
, strlen(hostname
));
5238 DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
5244 int done
= 0; /* Are we done yet? */
5246 while (!error
&& !done
)
5248 error
= SSLHandshake(http
->tls
);
5250 DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error
));
5258 case errSSLWouldBlock
:
5259 error
= noErr
; /* Force a retry */
5260 usleep(1000); /* in 1 millisecond */
5263 case errSSLServerAuthCompleted
:
5265 if (cg
->server_cert_cb
)
5267 error
= httpCopyCredentials(http
, &credentials
);
5270 error
= (cg
->server_cert_cb
)(http
, http
->tls
, credentials
,
5271 cg
->server_cert_data
);
5272 httpFreeCredentials(credentials
);
5275 DEBUG_printf(("4http_setup_ssl: Server certificate callback "
5276 "returned %d.", (int)error
));
5280 case errSSLClientCertRequested
:
5283 if (cg
->client_cert_cb
)
5286 if (!(error
= SSLCopyDistinguishedNames(http
->tls
, &dn_array
)) &&
5289 if ((names
= cupsArrayNew(NULL
, NULL
)) != NULL
)
5291 for (i
= 0, count
= CFArrayGetCount(dn_array
); i
< count
; i
++)
5293 data
= (CFDataRef
)CFArrayGetValueAtIndex(dn_array
, i
);
5295 if ((credential
= malloc(sizeof(*credential
))) != NULL
)
5297 credential
->datalen
= CFDataGetLength(data
);
5298 if ((credential
->data
= malloc(credential
->datalen
)))
5300 memcpy((void *)credential
->data
, CFDataGetBytePtr(data
),
5301 credential
->datalen
);
5302 cupsArrayAdd(names
, credential
);
5310 CFRelease(dn_array
);
5315 error
= (cg
->client_cert_cb
)(http
, http
->tls
, names
,
5316 cg
->client_cert_data
);
5318 DEBUG_printf(("4http_setup_ssl: Client certificate callback "
5319 "returned %d.", (int)error
));
5322 httpFreeCredentials(names
);
5326 case errSSLUnknownRootCert
:
5327 message
= _("Unable to establish a secure connection to host "
5328 "(untrusted certificate).");
5331 case errSSLNoRootCert
:
5332 message
= _("Unable to establish a secure connection to host "
5333 "(self-signed certificate).");
5336 case errSSLCertExpired
:
5337 message
= _("Unable to establish a secure connection to host "
5338 "(expired certificate).");
5341 case errSSLCertNotYetValid
:
5342 message
= _("Unable to establish a secure connection to host "
5343 "(certificate not yet valid).");
5346 case errSSLHostNameMismatch
:
5347 message
= _("Unable to establish a secure connection to host "
5348 "(host name mismatch).");
5351 case errSSLXCertChainInvalid
:
5352 message
= _("Unable to establish a secure connection to host "
5353 "(certificate chain invalid).");
5356 case errSSLConnectionRefused
:
5357 message
= _("Unable to establish a secure connection to host "
5358 "(peer dropped connection before responding).");
5369 http
->error
= error
;
5370 http
->status
= HTTP_STATUS_ERROR
;
5371 errno
= ECONNREFUSED
;
5373 CFRelease(http
->tls
);
5377 * If an error string wasn't set by the callbacks use a generic one...
5381 #ifdef HAVE_CSSMERRORSTRING
5382 message
= cssmErrorString(error
);
5384 message
= _("Unable to establish a secure connection to host.");
5385 #endif /* HAVE_CSSMERRORSTRING */
5387 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
, message
, 1);
5392 # elif defined(HAVE_SSPISSL)
5393 http
->tls
= _sspiAlloc();
5397 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
5401 http
->tls
->sock
= http
->fd
;
5402 dwSize
= sizeof(username
) / sizeof(TCHAR
);
5403 GetUserName(username
, &dwSize
);
5404 _sntprintf_s(commonName
, sizeof(commonName
) / sizeof(TCHAR
),
5405 sizeof(commonName
) / sizeof(TCHAR
), TEXT("CN=%s"), username
);
5407 if (!_sspiGetCredentials(http
->tls_credentials
, L
"ClientContainer",
5410 _sspiFree(http
->tls_credentials
);
5411 http
->tls_credentials
= NULL
;
5414 http
->status
= HTTP_STATUS_ERROR
;
5416 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
5417 _("Unable to establish a secure connection to host."), 1);
5422 _sspiSetAllowsAnyRoot(http
->tls_credentials
, TRUE
);
5423 _sspiSetAllowsExpiredCerts(http
->tls_credentials
, TRUE
);
5425 if (!_sspiConnect(http
->tls_credentials
, hostname
))
5427 _sspiFree(http
->tls_credentials
);
5428 http
->tls_credentials
= NULL
;
5431 http
->status
= HTTP_STATUS_ERROR
;
5433 _cupsSetError(IPP_STATUS_ERROR_CUPS_PKI
,
5434 _("Unable to establish a secure connection to host."), 1);
5438 # endif /* HAVE_CDSASSL */
5445 * 'http_shutdown_ssl()' - Shut down SSL/TLS on a connection.
5449 http_shutdown_ssl(http_t
*http
) /* I - Connection to server */
5452 SSL_CTX
*context
; /* Context for encryption */
5454 context
= SSL_get_SSL_CTX(http
->tls
);
5456 SSL_shutdown(http
->tls
);
5457 SSL_CTX_free(context
);
5458 SSL_free(http
->tls
);
5460 # elif defined(HAVE_GNUTLS)
5461 gnutls_certificate_client_credentials
*credentials
;
5462 /* TLS credentials */
5464 credentials
= (gnutls_certificate_client_credentials
*)(http
->tls_credentials
);
5466 gnutls_bye(http
->tls
, GNUTLS_SHUT_RDWR
);
5467 gnutls_deinit(http
->tls
);
5468 gnutls_certificate_free_credentials(*credentials
);
5471 # elif defined(HAVE_CDSASSL)
5472 while (SSLClose(http
->tls
) == errSSLWouldBlock
)
5475 CFRelease(http
->tls
);
5477 if (http
->tls_credentials
)
5478 CFRelease(http
->tls_credentials
);
5480 # elif defined(HAVE_SSPISSL)
5481 _sspiFree(http
->tls_credentials
);
5482 # endif /* HAVE_LIBSSL */
5485 http
->tls_credentials
= NULL
;
5487 #endif /* HAVE_SSL */
5492 * 'http_state_string()' - Return the string associated with a given HTTP state.
5495 static const char * /* O - State string */
5496 http_state_string(http_state_t state
) /* I - HTTP state */
5498 static char buffer
[255]; /* Unknown value buffer */
5499 static const char * const states
[] = /* State strings */
5502 "HTTP_STATE_WAITING",
5503 "HTTP_STATE_OPTIONS",
5505 "HTTP_STATE_GET_SEND",
5508 "HTTP_STATE_POST_RECV",
5509 "HTTP_STATE_POST_SEND",
5511 "HTTP_STATE_PUT_RECV",
5512 "HTTP_STATE_DELETE",
5514 "HTTP_STATE_CONNECT",
5515 "HTTP_STATE_STATUS",
5516 "HTTP_STATE_UNKNOWN_METHOD",
5517 "HTTP_STATE_UNKNOWN_VERSION"
5520 if (state
>= HTTP_STATE_ERROR
&& state
<= HTTP_STATE_UNKNOWN_VERSION
)
5521 return (states
[state
- HTTP_STATE_ERROR
]);
5523 snprintf(buffer
, sizeof(buffer
), "??? %d ???", (int)state
);
5531 * 'http_upgrade()' - Force upgrade to TLS encryption.
5534 static int /* O - Status of connection */
5535 http_upgrade(http_t
*http
) /* I - Connection to server */
5537 int ret
; /* Return value */
5538 http_t myhttp
; /* Local copy of HTTP data */
5541 DEBUG_printf(("7http_upgrade(%p)", http
));
5544 * Flush the connection to make sure any previous "Upgrade" message
5551 * Copy the HTTP data to a local variable so we can do the OPTIONS
5552 * request without interfering with the existing request data...
5555 memcpy(&myhttp
, http
, sizeof(myhttp
));
5558 * Send an OPTIONS request to the server, requiring SSL or TLS
5559 * encryption on the link...
5562 http
->tls_upgrade
= 1;
5563 http
->field_authorization
= NULL
; /* Don't free the auth string */
5565 httpClearFields(http
);
5566 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
5567 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
5569 if ((ret
= httpOptions(http
, "*")) == 0)
5572 * Wait for the secure connection...
5575 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
5579 * Restore the HTTP request data...
5582 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
5583 http
->data_encoding
= myhttp
.data_encoding
;
5584 http
->data_remaining
= myhttp
.data_remaining
;
5585 http
->_data_remaining
= myhttp
._data_remaining
;
5586 http
->expect
= myhttp
.expect
;
5587 http
->field_authorization
= myhttp
.field_authorization
;
5588 http
->digest_tries
= myhttp
.digest_tries
;
5589 http
->tls_upgrade
= 0;
5592 * See if we actually went secure...
5598 * Server does not support HTTP upgrade...
5601 DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
5604 closesocket(http
->fd
);
5616 #endif /* HAVE_SSL */
5620 * 'http_write()' - Write a buffer to a HTTP connection.
5623 static ssize_t
/* O - Number of bytes written */
5624 http_write(http_t
*http
, /* I - Connection to server */
5625 const char *buffer
, /* I - Buffer for data */
5626 size_t length
) /* I - Number of bytes to write */
5628 ssize_t tbytes
, /* Total bytes sent */
5629 bytes
; /* Bytes sent */
5632 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
5633 buffer
, CUPS_LLCAST length
));
5639 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
5641 if (http
->timeout_cb
)
5644 struct pollfd pfd
; /* Polled file descriptor */
5646 fd_set output_set
; /* Output ready for write? */
5647 struct timeval timeout
; /* Timeout value */
5648 #endif /* HAVE_POLL */
5649 int nfds
; /* Result from select()/poll() */
5655 pfd
.events
= POLLOUT
;
5657 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
5658 (errno
== EINTR
|| errno
== EAGAIN
))
5664 FD_ZERO(&output_set
);
5665 FD_SET(http
->fd
, &output_set
);
5667 timeout
.tv_sec
= http
->wait_value
/ 1000;
5668 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
5670 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
5673 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
5674 WSAGetLastError() == WSAEWOULDBLOCK
));
5676 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
5678 #endif /* HAVE_POLL */
5682 http
->error
= errno
;
5685 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
5688 http
->error
= WSAEWOULDBLOCK
;
5690 http
->error
= EWOULDBLOCK
;
5700 bytes
= http_write_ssl(http
, buffer
, length
);
5702 #endif /* HAVE_SSL */
5703 bytes
= send(http
->fd
, buffer
, length
, 0);
5705 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
5706 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
5711 if (WSAGetLastError() == WSAEINTR
)
5713 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
5715 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5718 http
->error
= WSAGetLastError();
5720 else if (WSAGetLastError() != http
->error
&&
5721 WSAGetLastError() != WSAECONNRESET
)
5723 http
->error
= WSAGetLastError();
5730 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
5732 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
5734 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
5737 http
->error
= errno
;
5739 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
5741 http
->error
= errno
;
5746 DEBUG_printf(("3http_write: error writing data (%s).",
5747 strerror(http
->error
)));
5758 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
5761 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
5768 * 'http_write_chunk()' - Write a chunked buffer.
5771 static ssize_t
/* O - Number bytes written */
5772 http_write_chunk(http_t
*http
, /* I - Connection to server */
5773 const char *buffer
, /* I - Buffer to write */
5774 size_t length
) /* I - Length of buffer */
5776 char header
[16]; /* Chunk header */
5777 ssize_t bytes
; /* Bytes written */
5780 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
5781 http
, buffer
, CUPS_LLCAST length
));
5784 * Write the chunk header, data, and trailer.
5787 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
5788 if (http_write(http
, header
, strlen(header
)) < 0)
5790 DEBUG_puts("8http_write_chunk: http_write of length failed.");
5794 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
5796 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
5800 if (http_write(http
, "\r\n", 2) < 0)
5802 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
5812 * 'http_write_ssl()' - Write to a SSL/TLS connection.
5815 static int /* O - Bytes written */
5816 http_write_ssl(http_t
*http
, /* I - Connection to server */
5817 const char *buf
, /* I - Buffer holding data */
5818 int len
) /* I - Length of buffer */
5820 ssize_t result
; /* Return value */
5823 DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http
, buf
, len
));
5825 # if defined(HAVE_LIBSSL)
5826 result
= SSL_write((SSL
*)(http
->tls
), buf
, len
);
5828 # elif defined(HAVE_GNUTLS)
5829 result
= gnutls_record_send(http
->tls
, buf
, len
);
5831 if (result
< 0 && !errno
)
5834 * Convert GNU TLS error to errno value...
5839 case GNUTLS_E_INTERRUPTED
:
5843 case GNUTLS_E_AGAIN
:
5855 # elif defined(HAVE_CDSASSL)
5856 OSStatus error
; /* Error info */
5857 size_t processed
; /* Number of bytes processed */
5860 error
= SSLWrite(http
->tls
, buf
, len
, &processed
);
5865 result
= (int)processed
;
5868 case errSSLWouldBlock
:
5870 result
= (int)processed
;
5878 case errSSLClosedGraceful
:
5881 result
= (int)processed
;
5889 # elif defined(HAVE_SSPISSL)
5890 return _sspiWrite((_sspi_struct_t
*)http
->tls
, (void *)buf
, len
);
5891 # endif /* HAVE_LIBSSL */
5893 DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result
));
5895 return ((int)result
);
5897 #endif /* HAVE_SSL */