4 * HTTP routines for CUPS.
6 * Copyright 2007-2014 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * Include necessary headers...
25 #include "cups-private.h"
32 # include <sys/time.h>
33 # include <sys/resource.h>
37 #endif /* HAVE_POLL */
45 static void http_content_coding_finish(http_t
*http
);
46 static void http_content_coding_start(http_t
*http
,
48 #endif /* HAVE_LIBZ */
49 static http_t
*http_create(const char *host
, int port
,
50 http_addrlist_t
*addrlist
, int family
,
51 http_encryption_t encryption
,
52 int blocking
, _http_mode_t mode
);
54 static void http_debug_hex(const char *prefix
, const char *buffer
,
57 static ssize_t
http_read(http_t
*http
, char *buffer
, size_t length
);
58 static ssize_t
http_read_buffered(http_t
*http
, char *buffer
, size_t length
);
59 static ssize_t
http_read_chunk(http_t
*http
, char *buffer
, size_t length
);
60 static int http_send(http_t
*http
, http_state_t request
,
62 static ssize_t
http_write(http_t
*http
, const char *buffer
,
64 static ssize_t
http_write_chunk(http_t
*http
, const char *buffer
,
66 static off_t
http_set_length(http_t
*http
);
67 static void http_set_timeout(int fd
, double timeout
);
68 static void http_set_wait(http_t
*http
);
71 static size_t http_tls_pending(http_t
*http
);
72 static int http_tls_read(http_t
*http
, char *buf
, int len
);
73 static int http_tls_set_credentials(http_t
*http
);
74 static int http_tls_start(http_t
*http
);
75 static void http_tls_stop(http_t
*http
);
76 static int http_tls_upgrade(http_t
*http
);
77 static int http_tls_write(http_t
*http
, const char *buf
, int len
);
79 # include "tls-gnutls.c"
80 # elif defined(HAVE_CDSASSL)
81 # include "tls-darwin.c"
83 # include "tls-sspi.c"
84 # endif /* HAVE_GNUTLS */
92 static const char * const http_fields
[] =
109 "If-Unmodified-since",
128 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
129 * specified listening socket.
131 * @since CUPS 1.7/OS X 10.9@
134 http_t
* /* O - HTTP connection or @code NULL@ */
135 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
136 int blocking
) /* I - 1 if the connection should be
137 blocking, 0 otherwise */
139 http_t
*http
; /* HTTP connection */
140 http_addrlist_t addrlist
; /* Dummy address list */
141 socklen_t addrlen
; /* Length of address */
142 int val
; /* Socket option value */
146 * Range check input...
153 * Create the client connection...
156 memset(&addrlist
, 0, sizeof(addrlist
));
158 if ((http
= http_create(NULL
, 0, &addrlist
, AF_UNSPEC
,
159 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
160 _HTTP_MODE_SERVER
)) == NULL
)
164 * Accept the client and get the remote address...
167 addrlen
= sizeof(http_addr_t
);
169 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
172 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
178 http
->hostaddr
= &(http
->addrlist
->addr
);
180 if (httpAddrLocalhost(http
->hostaddr
))
181 strlcpy(http
->hostname
, "localhost", sizeof(http
->hostname
));
183 httpAddrString(http
->hostaddr
, http
->hostname
, sizeof(http
->hostname
));
187 * Disable SIGPIPE for this socket.
191 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
192 #endif /* SO_NOSIGPIPE */
195 * Using TCP_NODELAY improves responsiveness, especially on systems
196 * with a slow loopback interface. Since we write large buffers
197 * when sending print files and requests, there shouldn't be any
198 * performance penalty for this...
202 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
206 * Close this socket when starting another process...
209 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
210 #endif /* FD_CLOEXEC */
217 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
219 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
221 * @since CUPS 1.5/OS X 10.7@
224 int /* O - 0 on success, -1 on error */
226 cups_array_t
*credentials
, /* I - Credentials array */
227 const void *data
, /* I - PEM-encoded X.509 data */
228 size_t datalen
) /* I - Length of data */
230 http_credential_t
*credential
; /* Credential data */
233 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
235 credential
->datalen
= datalen
;
237 if ((credential
->data
= malloc(datalen
)) != NULL
)
239 memcpy(credential
->data
, data
, datalen
);
240 cupsArrayAdd(credentials
, credential
);
252 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
256 httpBlocking(http_t
*http
, /* I - HTTP connection */
257 int b
) /* I - 1 = blocking, 0 = non-blocking */
268 * 'httpCheck()' - Check to see if there is a pending response from the server.
271 int /* O - 0 = no data, 1 = data available */
272 httpCheck(http_t
*http
) /* I - HTTP connection */
274 return (httpWait(http
, 0));
279 * 'httpClearCookie()' - Clear the cookie value(s).
281 * @since CUPS 1.1.19/OS X 10.3@
285 httpClearCookie(http_t
*http
) /* I - HTTP connection */
299 * 'httpClearFields()' - Clear HTTP request fields.
303 httpClearFields(http_t
*http
) /* I - HTTP connection */
305 DEBUG_printf(("httpClearFields(http=%p)", http
));
309 memset(http
->fields
, 0, sizeof(http
->fields
));
311 if (http
->mode
== _HTTP_MODE_CLIENT
)
313 if (http
->hostname
[0] == '/')
314 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
316 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
319 if (http
->field_authorization
)
321 free(http
->field_authorization
);
322 http
->field_authorization
= NULL
;
325 if (http
->accept_encoding
)
327 _cupsStrFree(http
->accept_encoding
);
328 http
->accept_encoding
= NULL
;
333 _cupsStrFree(http
->allow
);
339 _cupsStrFree(http
->server
);
343 http
->expect
= (http_status_t
)0;
349 * 'httpClose()' - Close an HTTP connection.
353 httpClose(http_t
*http
) /* I - HTTP connection */
356 OM_uint32 minor_status
; /* Minor status code */
357 #endif /* HAVE_GSSAPI */
360 DEBUG_printf(("httpClose(http=%p)", http
));
363 * Range check input...
370 * Close any open connection...
373 _httpDisconnect(http
);
376 * Free memory used...
379 httpAddrFreeList(http
->addrlist
);
385 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
386 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
388 if (http
->gssname
!= GSS_C_NO_NAME
)
389 gss_release_name(&minor_status
, &http
->gssname
);
390 #endif /* HAVE_GSSAPI */
392 #ifdef HAVE_AUTHORIZATION_H
394 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
395 #endif /* HAVE_AUTHORIZATION_H */
397 httpClearFields(http
);
399 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
400 free(http
->authstring
);
407 * 'httpCompareCredentials()' - Compare two sets of X.509 credentials.
412 int /* O - 1 if they match, 0 if they do not */
413 httpCompareCredentials(
414 cups_array_t
*cred1
, /* I - First set of X.509 credentials */
415 cups_array_t
*cred2
) /* I - Second set of X.509 credentials */
417 http_credential_t
*temp1
, *temp2
; /* Temporary credentials */
420 for (temp1
= (http_credential_t
*)cupsArrayFirst(cred1
), temp2
= (http_credential_t
*)cupsArrayFirst(cred2
); temp1
&& temp2
; temp1
= (http_credential_t
*)cupsArrayNext(cred1
), temp2
= (http_credential_t
*)cupsArrayNext(cred2
))
421 if (temp1
->datalen
!= temp2
->datalen
)
423 else if (memcmp(temp1
->data
, temp2
->data
, temp1
->datalen
))
426 return (temp1
== temp2
);
431 * 'httpConnect()' - Connect to a HTTP server.
433 * This function is deprecated - use @link httpConnect2@ instead.
438 http_t
* /* O - New HTTP connection */
439 httpConnect(const char *host
, /* I - Host to connect to */
440 int port
) /* I - Port number */
442 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
,
443 HTTP_ENCRYPTION_IF_REQUESTED
, 1, 30000, NULL
));
448 * 'httpConnect2()' - Connect to a HTTP server.
450 * @since CUPS 1.7/OS X 10.9@
453 http_t
* /* O - New HTTP connection */
455 const char *host
, /* I - Host to connect to */
456 int port
, /* I - Port number */
457 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
458 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
459 http_encryption_t encryption
, /* I - Type of encryption to use */
460 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
461 int msec
, /* I - Connection timeout in milliseconds, 0 means don't connect */
462 int *cancel
) /* I - Pointer to "cancel" variable */
464 http_t
*http
; /* New HTTP connection */
467 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
468 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
469 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
472 * Create the HTTP structure...
475 if ((http
= http_create(host
, port
, addrlist
, family
, encryption
, blocking
,
476 _HTTP_MODE_CLIENT
)) == NULL
)
480 * Optionally connect to the remote system...
483 if (msec
== 0 || !httpReconnect2(http
, msec
, cancel
))
487 * Could not connect to any known address - bail out!
497 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
499 * This function is now deprecated. Please use the @link httpConnect2@ function
505 http_t
* /* O - New HTTP connection */
507 const char *host
, /* I - Host to connect to */
508 int port
, /* I - Port number */
509 http_encryption_t encryption
) /* I - Type of encryption to use */
511 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
512 host
, port
, encryption
));
514 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
520 * 'httpDelete()' - Send a DELETE request to the server.
523 int /* O - Status of call (0 = success) */
524 httpDelete(http_t
*http
, /* I - HTTP connection */
525 const char *uri
) /* I - URI to delete */
527 return (http_send(http
, HTTP_STATE_DELETE
, uri
));
532 * '_httpDisconnect()' - Disconnect a HTTP connection.
536 _httpDisconnect(http_t
*http
) /* I - HTTP connection */
541 #endif /* HAVE_SSL */
543 httpAddrClose(NULL
, http
->fd
);
550 * 'httpEncryption()' - Set the required encryption on the link.
553 int /* O - -1 on error, 0 on success */
554 httpEncryption(http_t
*http
, /* I - HTTP connection */
555 http_encryption_t e
) /* I - New encryption preference */
557 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
563 if (http
->mode
== _HTTP_MODE_CLIENT
)
565 http
->encryption
= e
;
567 if ((http
->encryption
== HTTP_ENCRYPTION_ALWAYS
&& !http
->tls
) ||
568 (http
->encryption
== HTTP_ENCRYPTION_NEVER
&& http
->tls
))
569 return (httpReconnect2(http
, 30000, NULL
));
570 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
571 return (http_tls_upgrade(http
));
577 if (e
== HTTP_ENCRYPTION_NEVER
&& http
->tls
)
580 http
->encryption
= e
;
581 if (e
!= HTTP_ENCRYPTION_IF_REQUESTED
&& !http
->tls
)
582 return (http_tls_start(http
));
587 if (e
== HTTP_ENCRYPTION_ALWAYS
|| e
== HTTP_ENCRYPTION_REQUIRED
)
591 #endif /* HAVE_SSL */
596 * 'httpError()' - Get the last error on a connection.
599 int /* O - Error code (errno) value */
600 httpError(http_t
*http
) /* I - HTTP connection */
603 return (http
->error
);
610 * 'httpFieldValue()' - Return the HTTP field enumeration value for a field
614 http_field_t
/* O - Field index */
615 httpFieldValue(const char *name
) /* I - String name */
617 int i
; /* Looping var */
620 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
621 if (!_cups_strcasecmp(name
, http_fields
[i
]))
622 return ((http_field_t
)i
);
624 return (HTTP_FIELD_UNKNOWN
);
629 * 'httpFlush()' - Flush data from a HTTP connection.
633 httpFlush(http_t
*http
) /* I - HTTP connection */
635 char buffer
[8192]; /* Junk buffer */
636 int blocking
; /* To block or not to block */
637 http_state_t oldstate
; /* Old state */
640 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
641 httpStateString(http
->state
)));
644 * Nothing to do if we are in the "waiting" state...
647 if (http
->state
== HTTP_STATE_WAITING
)
651 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
654 blocking
= http
->blocking
;
658 * Read any data we can...
661 oldstate
= http
->state
;
662 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
665 * Restore blocking and reset the connection if we didn't get all of
666 * the remaining data...
669 http
->blocking
= blocking
;
671 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
675 * Didn't get the data back, so close the current connection.
680 http_content_coding_finish(http
);
681 #endif /* HAVE_LIBZ */
683 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
685 http
->state
= HTTP_STATE_WAITING
;
690 #endif /* HAVE_SSL */
692 httpAddrClose(NULL
, http
->fd
);
700 * 'httpFlushWrite()' - Flush data in write buffer.
702 * @since CUPS 1.2/OS X 10.5@
705 int /* O - Bytes written or -1 on error */
706 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
708 ssize_t bytes
; /* Bytes written */
711 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
712 http
? http
->data_encoding
: 100));
714 if (!http
|| !http
->wused
)
716 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
717 "1httpFlushWrite: No connection.");
721 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
722 bytes
= http_write_chunk(http
, http
->wbuffer
, (size_t)http
->wused
);
724 bytes
= http_write(http
, http
->wbuffer
, (size_t)http
->wused
);
728 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", (int)bytes
, errno
));
735 * 'httpFreeCredentials()' - Free an array of credentials.
740 cups_array_t
*credentials
) /* I - Array of credentials */
742 http_credential_t
*credential
; /* Credential */
745 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
747 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
749 cupsArrayRemove(credentials
, credential
);
750 free((void *)credential
->data
);
754 cupsArrayDelete(credentials
);
759 * 'httpGet()' - Send a GET request to the server.
762 int /* O - Status of call (0 = success) */
763 httpGet(http_t
*http
, /* I - HTTP connection */
764 const char *uri
) /* I - URI to get */
766 return (http_send(http
, HTTP_STATE_GET
, uri
));
771 * 'httpGetActivity()' - Get the most recent activity for a connection.
773 * The return value is the UNIX time of the last read or write.
778 time_t /* O - Time of last read or write */
779 httpGetActivity(http_t
*http
) /* I - HTTP connection */
781 return (http
? http
->activity
: 0);
786 * 'httpGetAuthString()' - Get the current authorization string.
788 * The authorization string is set by cupsDoAuthentication() and
789 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
790 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
793 * @since CUPS 1.3/OS X 10.5@
796 char * /* O - Authorization string */
797 httpGetAuthString(http_t
*http
) /* I - HTTP connection */
800 return (http
->authstring
);
807 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
809 * @since CUPS 1.2/OS X 10.5@
812 int /* O - 1 if blocking, 0 if non-blocking */
813 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
815 return (http
? http
->blocking
: 0);
820 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
821 * the client and server.
823 * This function uses the value of the Accepts-Encoding HTTP header and must be
824 * called after receiving a response from the server or a request from the
825 * client. The value returned can be use in subsequent requests (for clients)
826 * or in the response (for servers) in order to compress the content stream.
828 * @since CUPS 1.7/OS X 10.9@
831 const char * /* O - Content-Coding value or
832 @code NULL@ for the identity
834 httpGetContentEncoding(http_t
*http
) /* I - HTTP connection */
837 if (http
&& http
->accept_encoding
)
839 int i
; /* Looping var */
840 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
841 *start
, /* Start of coding value */
842 *end
; /* End of coding value */
843 double qvalue
; /* "qvalue" for coding */
844 struct lconv
*loc
= localeconv(); /* Locale data */
845 static const char * const codings
[] =
846 { /* Supported content codings */
853 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
855 for (start
= temp
; *start
; start
= end
)
858 * Find the end of the coding name...
863 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
869 * Grab the qvalue as needed...
872 if (!strncmp(end
, ";q=", 3))
873 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
876 * Skip past all attributes...
880 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
886 while (*end
&& isspace(*end
& 255))
890 * Check value if it matches something we support...
896 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
897 if (!strcmp(start
, codings
[i
]))
901 #endif /* HAVE_LIBZ */
908 * 'httpGetCookie()' - Get any cookie data from the response.
910 * @since CUPS 1.1.19/OS X 10.3@
913 const char * /* O - Cookie data or NULL */
914 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
916 return (http
? http
->cookie
: NULL
);
921 * 'httpGetEncryption()' - Get the current encryption mode of a connection.
923 * This function returns the encryption mode for the connection. Use the
924 * @link httpIsEncrypted@ function to determine whether a TLS session has
930 http_encryption_t
/* O - Current encryption mode */
931 httpGetEncryption(http_t
*http
) /* I - HTTP connection */
933 return (http
? http
->encryption
: HTTP_ENCRYPTION_IF_REQUESTED
);
938 * 'httpGetExpect()' - Get the value of the Expect header, if any.
940 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
941 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
943 * @since CUPS 1.7/OS X 10.9@
946 http_status_t
/* O - Expect: status, if any */
947 httpGetExpect(http_t
*http
) /* I - HTTP connection */
950 return (HTTP_STATUS_ERROR
);
952 return (http
->expect
);
957 * 'httpGetFd()' - Get the file descriptor associated with a connection.
959 * @since CUPS 1.2/OS X 10.5@
962 int /* O - File descriptor or -1 if none */
963 httpGetFd(http_t
*http
) /* I - HTTP connection */
965 return (http
? http
->fd
: -1);
970 * 'httpGetField()' - Get a field value from a request/response.
973 const char * /* O - Field value */
974 httpGetField(http_t
*http
, /* I - HTTP connection */
975 http_field_t field
) /* I - Field to get */
977 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
982 case HTTP_FIELD_ACCEPT_ENCODING
:
983 return (http
->accept_encoding
);
985 case HTTP_FIELD_ALLOW
:
986 return (http
->allow
);
988 case HTTP_FIELD_SERVER
:
989 return (http
->server
);
991 case HTTP_FIELD_AUTHORIZATION
:
992 if (http
->field_authorization
)
995 * Special case for WWW-Authenticate: as its contents can be
996 * longer than HTTP_MAX_VALUE...
999 return (http
->field_authorization
);
1003 return (http
->fields
[field
]);
1009 * 'httpGetKeepAlive()' - Get the current Keep-Alive state of the connection.
1014 http_keepalive_t
/* O - Keep-Alive state */
1015 httpGetKeepAlive(http_t
*http
) /* I - HTTP connection */
1017 return (http
? http
->keep_alive
: HTTP_KEEPALIVE_OFF
);
1022 * 'httpGetLength()' - Get the amount of data remaining from the
1023 * content-length or transfer-encoding fields.
1025 * This function is deprecated and will not return lengths larger than
1026 * 2^31 - 1; use httpGetLength2() instead.
1031 int /* O - Content length */
1032 httpGetLength(http_t
*http
) /* I - HTTP connection */
1035 * Get the read content length and return the 32-bit value.
1040 httpGetLength2(http
);
1042 return (http
->_data_remaining
);
1050 * 'httpGetLength2()' - Get the amount of data remaining from the
1051 * content-length or transfer-encoding fields.
1053 * This function returns the complete content length, even for
1054 * content larger than 2^31 - 1.
1056 * @since CUPS 1.2/OS X 10.5@
1059 off_t
/* O - Content length */
1060 httpGetLength2(http_t
*http
) /* I - HTTP connection */
1062 off_t remaining
; /* Remaining length */
1065 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1066 httpStateString(http
->state
)));
1071 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1073 DEBUG_puts("4httpGetLength2: chunked request!");
1079 * The following is a hack for HTTP servers that don't send a
1080 * Content-Length or Transfer-Encoding field...
1082 * If there is no Content-Length then the connection must close
1083 * after the transfer is complete...
1086 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1089 * Default content length is 0 for errors and certain types of operations,
1090 * and 2^31-1 for other successful requests...
1093 if (http
->status
>= HTTP_STATUS_MULTIPLE_CHOICES
||
1094 http
->state
== HTTP_STATE_OPTIONS
||
1095 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1096 http
->state
== HTTP_STATE_HEAD
||
1097 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1098 http
->state
== HTTP_STATE_DELETE
||
1099 http
->state
== HTTP_STATE_TRACE
||
1100 http
->state
== HTTP_STATE_CONNECT
)
1103 remaining
= 2147483647;
1105 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1109 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1110 CUPS_LLCAST remaining
));
1118 * 'httpGetPending()' - Get the number of bytes that are buffered for writing.
1123 size_t /* O - Number of bytes buffered */
1124 httpGetPending(http_t
*http
) /* I - HTTP connection */
1126 return (http
? (size_t)http
->wused
: 0);
1131 * 'httpGetReady()' - Get the number of bytes that can be read without blocking.
1136 size_t /* O - Number of bytes available */
1137 httpGetReady(http_t
*http
) /* I - HTTP connection */
1141 else if (http
->used
> 0)
1142 return ((size_t)http
->used
);
1145 return (http_tls_pending(http
));
1146 #endif /* HAVE_SSL */
1153 * 'httpGetRemaining()' - Get the number of remaining bytes in the message
1154 * body or current chunk.
1156 * The @link httpIsChunked@ function can be used to determine whether the
1157 * message body is chunked or fixed-length.
1162 size_t /* O - Remaining bytes */
1163 httpGetRemaining(http_t
*http
) /* I - HTTP connection */
1165 return (http
? (size_t)http
->data_remaining
: 0);
1170 * 'httpGets()' - Get a line of text from a HTTP connection.
1173 char * /* O - Line or NULL */
1174 httpGets(char *line
, /* I - Line to read into */
1175 int length
, /* I - Max length of buffer */
1176 http_t
*http
) /* I - HTTP connection */
1178 char *lineptr
, /* Pointer into line */
1179 *lineend
, /* End of line */
1180 *bufptr
, /* Pointer into input buffer */
1181 *bufend
; /* Pointer to end of buffer */
1182 ssize_t bytes
; /* Number of bytes read */
1183 int eol
; /* End-of-line? */
1186 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1188 if (!http
|| !line
|| length
<= 1)
1192 * Read a line from the buffer...
1197 lineend
= line
+ length
- 1;
1200 while (lineptr
< lineend
)
1203 * Pre-load the buffer as needed...
1212 while (http
->used
== 0)
1215 * No newline; see if there is more data to be read...
1218 while (!_httpWait(http
, http
->wait_value
, 1))
1220 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1223 DEBUG_puts("3httpGets: Timed out!");
1225 http
->error
= WSAETIMEDOUT
;
1227 http
->error
= ETIMEDOUT
;
1232 bytes
= http_read(http
, http
->buffer
+ http
->used
, (size_t)(HTTP_MAX_BUFFER
- http
->used
));
1234 DEBUG_printf(("4httpGets: read " CUPS_LLFMT
" bytes.", CUPS_LLCAST bytes
));
1239 * Nope, can't get a line this time...
1243 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1245 if (WSAGetLastError() == WSAEINTR
)
1247 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1249 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1252 http
->error
= WSAGetLastError();
1254 else if (WSAGetLastError() != http
->error
)
1256 http
->error
= WSAGetLastError();
1261 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1265 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1267 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1269 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1272 http
->error
= errno
;
1274 else if (errno
!= http
->error
)
1276 http
->error
= errno
;
1283 else if (bytes
== 0)
1285 http
->error
= EPIPE
;
1291 * Yup, update the amount used...
1294 http
->used
+= (int)bytes
;
1298 * Now copy as much of the current line as possible...
1301 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1302 lineptr
< lineend
&& bufptr
< bufend
;)
1304 if (*bufptr
== 0x0a)
1310 else if (*bufptr
== 0x0d)
1313 *lineptr
++ = *bufptr
++;
1316 http
->used
-= (int)(bufptr
- http
->buffer
);
1318 memmove(http
->buffer
, bufptr
, (size_t)http
->used
);
1326 http
->activity
= time(NULL
);
1330 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1336 DEBUG_puts("3httpGets: No new line available!");
1343 * 'httpGetState()' - Get the current state of the HTTP request.
1346 http_state_t
/* O - HTTP state */
1347 httpGetState(http_t
*http
) /* I - HTTP connection */
1349 return (http
? http
->state
: HTTP_STATE_ERROR
);
1354 * 'httpGetStatus()' - Get the status of the last HTTP request.
1356 * @since CUPS 1.2/OS X 10.5@
1359 http_status_t
/* O - HTTP status */
1360 httpGetStatus(http_t
*http
) /* I - HTTP connection */
1362 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1367 * 'httpGetSubField()' - Get a sub-field value.
1372 char * /* O - Value or NULL */
1373 httpGetSubField(http_t
*http
, /* I - HTTP connection */
1374 http_field_t field
, /* I - Field index */
1375 const char *name
, /* I - Name of sub-field */
1376 char *value
) /* O - Value string */
1378 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1383 * 'httpGetSubField2()' - Get a sub-field value.
1385 * @since CUPS 1.2/OS X 10.5@
1388 char * /* O - Value or NULL */
1389 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
1390 http_field_t field
, /* I - Field index */
1391 const char *name
, /* I - Name of sub-field */
1392 char *value
, /* O - Value string */
1393 int valuelen
) /* I - Size of value buffer */
1395 const char *fptr
; /* Pointer into field */
1396 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1397 *ptr
, /* Pointer into string buffer */
1398 *end
; /* End of value buffer */
1400 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1401 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1403 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1404 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1407 end
= value
+ valuelen
- 1;
1409 for (fptr
= http
->fields
[field
]; *fptr
;)
1412 * Skip leading whitespace...
1415 while (_cups_isspace(*fptr
))
1425 * Get the sub-field name...
1429 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1430 ptr
< (temp
+ sizeof(temp
) - 1);
1435 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1438 * Skip trailing chars up to the '='...
1441 while (_cups_isspace(*fptr
))
1451 * Skip = and leading whitespace...
1456 while (_cups_isspace(*fptr
))
1462 * Read quoted string...
1465 for (ptr
= value
, fptr
++;
1466 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1471 while (*fptr
&& *fptr
!= '\"')
1480 * Read unquoted string...
1484 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1489 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1493 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1496 * See if this is the one...
1499 if (!strcmp(name
, temp
))
1501 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1508 DEBUG_puts("3httpGetSubField2: Returning NULL");
1515 * 'httpGetVersion()' - Get the HTTP version at the other end.
1518 http_version_t
/* O - Version number */
1519 httpGetVersion(http_t
*http
) /* I - HTTP connection */
1521 return (http
? http
->version
: HTTP_VERSION_1_0
);
1526 * 'httpHead()' - Send a HEAD request to the server.
1529 int /* O - Status of call (0 = success) */
1530 httpHead(http_t
*http
, /* I - HTTP connection */
1531 const char *uri
) /* I - URI for head */
1533 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1534 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1539 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1540 * default HTTP proxy (if any).
1544 httpInitialize(void)
1546 static int initialized
= 0; /* Have we been called before? */
1548 WSADATA winsockdata
; /* WinSock data */
1555 _cupsGlobalUnlock();
1560 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1562 #elif !defined(SO_NOSIGPIPE)
1564 * Ignore SIGPIPE signals...
1568 sigset(SIGPIPE
, SIG_IGN
);
1570 # elif defined(HAVE_SIGACTION)
1571 struct sigaction action
; /* POSIX sigaction data */
1574 memset(&action
, 0, sizeof(action
));
1575 action
.sa_handler
= SIG_IGN
;
1576 sigaction(SIGPIPE
, &action
, NULL
);
1579 signal(SIGPIPE
, SIG_IGN
);
1580 # endif /* !SO_NOSIGPIPE */
1584 http_tls_initialize();
1585 # endif /* HAVE_SSL */
1588 _cupsGlobalUnlock();
1593 * 'httpIsChunked()' - Report whether a message body is chunked.
1595 * This function returns non-zero if the message body is composed of
1596 * variable-length chunks.
1601 int /* O - 1 if chunked, 0 if not */
1602 httpIsChunked(http_t
*http
) /* I - HTTP connection */
1604 return (http
? http
->data_encoding
== HTTP_ENCODING_CHUNKED
: 0);
1609 * 'httpIsEncrypted()' - Report whether a connection is encrypted.
1611 * This function returns non-zero if the connection is currently encrypted.
1616 int /* O - 1 if encrypted, 0 if not */
1617 httpIsEncrypted(http_t
*http
) /* I - HTTP connection */
1619 return (http
? http
->tls
!= NULL
: 0);
1624 * 'httpOptions()' - Send an OPTIONS request to the server.
1627 int /* O - Status of call (0 = success) */
1628 httpOptions(http_t
*http
, /* I - HTTP connection */
1629 const char *uri
) /* I - URI for options */
1631 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1636 * 'httpPeek()' - Peek at data from a HTTP connection.
1638 * This function copies available data from the given HTTP connection, reading
1639 * a buffer as needed. The data is still available for reading using
1640 * @link httpRead@ or @link httpRead2@.
1642 * For non-blocking connections the usual timeouts apply.
1644 * @since CUPS 1.7/OS X 10.9@
1647 ssize_t
/* O - Number of bytes copied */
1648 httpPeek(http_t
*http
, /* I - HTTP connection */
1649 char *buffer
, /* I - Buffer for data */
1650 size_t length
) /* I - Maximum number of bytes */
1652 ssize_t bytes
; /* Bytes read */
1653 char len
[32]; /* Length string */
1656 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1657 http
, buffer
, CUPS_LLCAST length
));
1659 if (http
== NULL
|| buffer
== NULL
)
1662 http
->activity
= time(NULL
);
1668 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1669 http
->data_remaining
<= 0)
1671 DEBUG_puts("2httpPeek: Getting chunk length...");
1673 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1675 DEBUG_puts("1httpPeek: Could not get length!");
1681 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1682 if (!httpGets(len
, sizeof(len
), http
))
1684 DEBUG_puts("1httpPeek: Could not get chunk length.");
1689 http
->data_remaining
= strtoll(len
, NULL
, 16);
1691 if (http
->data_remaining
< 0)
1693 DEBUG_puts("1httpPeek: Negative chunk length!");
1698 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1699 CUPS_LLCAST http
->data_remaining
));
1701 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1704 * A zero-length chunk ends a transfer; unless we are reading POST
1710 http_content_coding_finish(http
);
1711 #endif /* HAVE_LIBZ */
1713 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1714 httpGets(len
, sizeof(len
), http
);
1716 if (http
->state
== HTTP_STATE_POST_RECV
)
1719 http
->state
= HTTP_STATE_STATUS
;
1721 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1722 httpStateString(http
->state
)));
1725 * Prevent future reads for this request...
1728 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1732 else if (length
> (size_t)http
->data_remaining
)
1733 length
= (size_t)http
->data_remaining
;
1736 if (http
->used
== 0 &&
1737 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1739 if (http
->used
== 0)
1740 #endif /* HAVE_LIBZ */
1743 * Buffer small reads for better performance...
1746 ssize_t buflen
; /* Length of read for buffer */
1748 if (!http
->blocking
)
1750 while (!httpWait(http
, http
->wait_value
))
1752 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1759 if ((size_t)http
->data_remaining
> sizeof(http
->buffer
))
1760 buflen
= sizeof(http
->buffer
);
1762 buflen
= (ssize_t
)http
->data_remaining
;
1764 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1765 bytes
= http_read(http
, http
->buffer
, (size_t)buflen
);
1767 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1768 CUPS_LLCAST bytes
));
1772 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1775 http
->used
= (int)bytes
;
1782 # ifdef HAVE_INFLATECOPY
1783 int zerr
; /* Decompressor error */
1784 z_stream stream
; /* Copy of decompressor stream */
1786 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1788 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1789 /* Number of bytes to copy */
1791 if (http
->stream
.avail_in
> 0 &&
1792 http
->stream
.next_in
> http
->dbuffer
)
1793 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1795 http
->stream
.next_in
= http
->dbuffer
;
1797 if (buflen
> (size_t)http
->data_remaining
)
1798 buflen
= (size_t)http
->data_remaining
;
1800 if (buflen
> (size_t)http
->used
)
1801 buflen
= (size_t)http
->used
;
1803 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1804 "decompression buffer.", (int)buflen
));
1806 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
1807 http
->stream
.avail_in
+= buflen
;
1808 http
->used
-= buflen
;
1809 http
->data_remaining
-= buflen
;
1812 memmove(http
->buffer
, http
->buffer
+ buflen
, (size_t)http
->used
);
1815 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
1816 (int)http
->stream
.avail_in
));
1818 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
1820 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
1821 http
->error
= ENOMEM
;
1825 stream
.next_out
= (Bytef
*)buffer
;
1826 stream
.avail_out
= (uInt
)length
;
1828 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
1829 inflateEnd(&stream
);
1833 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
1835 http_debug_hex("2httpPeek", (char *)http
->dbuffer
, (int)http
->stream
.avail_in
);
1842 bytes
= (ssize_t
)(length
- http
->stream
.avail_out
);
1845 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
1846 "work with compressed streams.");
1848 # endif /* HAVE_INFLATECOPY */
1851 #endif /* HAVE_LIBZ */
1854 if (length
> (size_t)http
->used
)
1855 length
= (size_t)http
->used
;
1857 bytes
= (ssize_t
)length
;
1859 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
1862 memcpy(buffer
, http
->buffer
, length
);
1870 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1873 http
->error
= WSAGetLastError();
1875 if (errno
== EINTR
|| errno
== EAGAIN
)
1878 http
->error
= errno
;
1881 else if (bytes
== 0)
1883 http
->error
= EPIPE
;
1892 * 'httpPost()' - Send a POST request to the server.
1895 int /* O - Status of call (0 = success) */
1896 httpPost(http_t
*http
, /* I - HTTP connection */
1897 const char *uri
) /* I - URI for post */
1899 return (http_send(http
, HTTP_STATE_POST
, uri
));
1904 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1909 int /* O - Number of bytes written */
1910 httpPrintf(http_t
*http
, /* I - HTTP connection */
1911 const char *format
, /* I - printf-style format string */
1912 ...) /* I - Additional args as needed */
1914 ssize_t bytes
; /* Number of bytes to write */
1915 char buf
[16384]; /* Buffer for formatted string */
1916 va_list ap
; /* Variable argument pointer */
1919 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1921 va_start(ap
, format
);
1922 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1925 DEBUG_printf(("3httpPrintf: (" CUPS_LLFMT
" bytes) %s", CUPS_LLCAST bytes
, buf
));
1927 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
1928 return ((int)httpWrite2(http
, buf
, (size_t)bytes
));
1933 DEBUG_puts("4httpPrintf: flushing existing data...");
1935 if (httpFlushWrite(http
) < 0)
1939 return ((int)http_write(http
, buf
, (size_t)bytes
));
1945 * 'httpPut()' - Send a PUT request to the server.
1948 int /* O - Status of call (0 = success) */
1949 httpPut(http_t
*http
, /* I - HTTP connection */
1950 const char *uri
) /* I - URI to put */
1952 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1953 return (http_send(http
, HTTP_STATE_PUT
, uri
));
1958 * 'httpRead()' - Read data from a HTTP connection.
1960 * This function is deprecated. Use the httpRead2() function which can
1961 * read more than 2GB of data.
1966 int /* O - Number of bytes read */
1967 httpRead(http_t
*http
, /* I - HTTP connection */
1968 char *buffer
, /* I - Buffer for data */
1969 int length
) /* I - Maximum number of bytes */
1971 return ((int)httpRead2(http
, buffer
, (size_t)length
));
1976 * 'httpRead2()' - Read data from a HTTP connection.
1978 * @since CUPS 1.2/OS X 10.5@
1981 ssize_t
/* O - Number of bytes read */
1982 httpRead2(http_t
*http
, /* I - HTTP connection */
1983 char *buffer
, /* I - Buffer for data */
1984 size_t length
) /* I - Maximum number of bytes */
1986 ssize_t bytes
; /* Bytes read */
1990 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
1991 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
1992 http
, buffer
, CUPS_LLCAST length
,
1994 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
1996 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
1997 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
1998 http
, buffer
, CUPS_LLCAST length
,
1999 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
2000 #endif /* HAVE_LIBZ */
2002 if (http
== NULL
|| buffer
== NULL
)
2005 http
->activity
= time(NULL
);
2016 if (http
->stream
.avail_in
> 0)
2018 int zerr
; /* Decompressor error */
2020 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2021 (int)http
->stream
.avail_in
, (int)length
));
2023 http
->stream
.next_out
= (Bytef
*)buffer
;
2024 http
->stream
.avail_out
= (uInt
)length
;
2026 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2028 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2030 http_debug_hex("2httpRead2", (char *)http
->dbuffer
, (int)http
->stream
.avail_in
);
2037 bytes
= (ssize_t
)(length
- http
->stream
.avail_out
);
2039 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2040 http
->stream
.avail_in
, http
->stream
.avail_out
,
2048 ssize_t buflen
= HTTP_MAX_BUFFER
- (ssize_t
)http
->stream
.avail_in
;
2049 /* Additional bytes for buffer */
2053 if (http
->stream
.avail_in
> 0 &&
2054 http
->stream
.next_in
> http
->dbuffer
)
2055 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2057 http
->stream
.next_in
= http
->dbuffer
;
2059 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2060 "decompression buffer.", (int)buflen
));
2062 if (http
->data_remaining
> 0)
2064 if (buflen
> http
->data_remaining
)
2065 buflen
= (ssize_t
)http
->data_remaining
;
2067 bytes
= http_read_buffered(http
, (char *)http
->dbuffer
+ http
->stream
.avail_in
, (size_t)buflen
);
2069 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2070 bytes
= http_read_chunk(http
, (char *)http
->dbuffer
+ http
->stream
.avail_in
, (size_t)buflen
);
2076 else if (bytes
== 0)
2079 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2080 "decompression buffer.", CUPS_LLCAST bytes
));
2082 http
->data_remaining
-= bytes
;
2083 http
->stream
.avail_in
+= (uInt
)bytes
;
2085 if (http
->data_remaining
<= 0 &&
2086 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2089 * Read the trailing blank line now...
2092 char len
[32]; /* Length string */
2094 httpGets(len
, sizeof(len
), http
);
2106 #endif /* HAVE_LIBZ */
2107 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2109 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2111 http
->data_remaining
-= bytes
;
2113 if (http
->data_remaining
<= 0)
2116 * Read the trailing blank line now...
2119 char len
[32]; /* Length string */
2121 httpGets(len
, sizeof(len
), http
);
2125 else if (http
->data_remaining
<= 0)
2128 * No more data to read...
2135 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2138 if (length
> (size_t)http
->data_remaining
)
2139 length
= (size_t)http
->data_remaining
;
2141 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2143 http
->data_remaining
-= bytes
;
2145 if (http
->data_remaining
<= 0 &&
2146 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2149 * Read the trailing blank line now...
2152 char len
[32]; /* Length string */
2154 httpGets(len
, sizeof(len
), http
);
2161 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2162 #endif /* HAVE_LIBZ */
2163 ((http
->data_remaining
<= 0 &&
2164 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2165 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2169 http_content_coding_finish(http
);
2170 #endif /* HAVE_LIBZ */
2172 if (http
->state
== HTTP_STATE_POST_RECV
)
2174 else if (http
->state
== HTTP_STATE_GET_SEND
||
2175 http
->state
== HTTP_STATE_POST_SEND
)
2176 http
->state
= HTTP_STATE_WAITING
;
2178 http
->state
= HTTP_STATE_STATUS
;
2180 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2181 httpStateString(http
->state
)));
2189 * 'httpReadRequest()' - Read a HTTP request from a connection.
2191 * @since CUPS 1.7/OS X 10.9@
2194 http_state_t
/* O - New state of connection */
2195 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2196 char *uri
, /* I - URI buffer */
2197 size_t urilen
) /* I - Size of URI buffer */
2199 char line
[4096], /* HTTP request line */
2200 *req_method
, /* HTTP request method */
2201 *req_uri
, /* HTTP request URI */
2202 *req_version
; /* HTTP request version number string */
2206 * Range check input...
2209 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2210 http
, uri
, CUPS_LLCAST urilen
));
2215 if (!http
|| !uri
|| urilen
< 1)
2217 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2218 return (HTTP_STATE_ERROR
);
2220 else if (http
->state
!= HTTP_STATE_WAITING
)
2222 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2223 httpStateString(http
->state
)));
2224 return (HTTP_STATE_ERROR
);
2231 httpClearFields(http
);
2233 http
->activity
= time(NULL
);
2234 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2235 http
->data_remaining
= 0;
2236 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2237 http
->status
= HTTP_STATUS_OK
;
2238 http
->version
= HTTP_VERSION_1_1
;
2241 * Read a line from the socket...
2244 if (!httpGets(line
, sizeof(line
), http
))
2246 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2247 return (HTTP_STATE_ERROR
);
2252 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2253 return (HTTP_STATE_WAITING
);
2256 DEBUG_printf(("1httpReadRequest: %s", line
));
2265 while (*req_uri
&& !isspace(*req_uri
& 255))
2270 DEBUG_puts("1httpReadRequest: No request URI.");
2271 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request URI."), 1);
2272 return (HTTP_STATE_ERROR
);
2277 while (*req_uri
&& isspace(*req_uri
& 255))
2280 req_version
= req_uri
;
2282 while (*req_version
&& !isspace(*req_version
& 255))
2287 DEBUG_puts("1httpReadRequest: No request protocol version.");
2288 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request protocol version."), 1);
2289 return (HTTP_STATE_ERROR
);
2292 *req_version
++ = '\0';
2294 while (*req_version
&& isspace(*req_version
& 255))
2301 if (!strcmp(req_method
, "OPTIONS"))
2302 http
->state
= HTTP_STATE_OPTIONS
;
2303 else if (!strcmp(req_method
, "GET"))
2304 http
->state
= HTTP_STATE_GET
;
2305 else if (!strcmp(req_method
, "HEAD"))
2306 http
->state
= HTTP_STATE_HEAD
;
2307 else if (!strcmp(req_method
, "POST"))
2308 http
->state
= HTTP_STATE_POST
;
2309 else if (!strcmp(req_method
, "PUT"))
2310 http
->state
= HTTP_STATE_PUT
;
2311 else if (!strcmp(req_method
, "DELETE"))
2312 http
->state
= HTTP_STATE_DELETE
;
2313 else if (!strcmp(req_method
, "TRACE"))
2314 http
->state
= HTTP_STATE_TRACE
;
2315 else if (!strcmp(req_method
, "CONNECT"))
2316 http
->state
= HTTP_STATE_CONNECT
;
2319 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2320 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request method."), 1);
2321 return (HTTP_STATE_UNKNOWN_METHOD
);
2324 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2325 httpStateString(http
->state
)));
2327 if (!strcmp(req_version
, "HTTP/1.0"))
2329 http
->version
= HTTP_VERSION_1_0
;
2330 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2332 else if (!strcmp(req_version
, "HTTP/1.1"))
2334 http
->version
= HTTP_VERSION_1_1
;
2335 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2339 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2340 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request version."), 1);
2341 return (HTTP_STATE_UNKNOWN_VERSION
);
2344 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2345 strlcpy(uri
, req_uri
, urilen
);
2347 return (http
->state
);
2352 * 'httpReconnect()' - Reconnect to a HTTP server.
2354 * This function is deprecated. Please use the @link httpReconnect2@ function
2360 int /* O - 0 on success, non-zero on failure */
2361 httpReconnect(http_t
*http
) /* I - HTTP connection */
2363 DEBUG_printf(("httpReconnect(http=%p)", http
));
2365 return (httpReconnect2(http
, 30000, NULL
));
2370 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2374 int /* O - 0 on success, non-zero on failure */
2375 httpReconnect2(http_t
*http
, /* I - HTTP connection */
2376 int msec
, /* I - Timeout in milliseconds */
2377 int *cancel
) /* I - Pointer to "cancel" variable */
2379 http_addrlist_t
*addr
; /* Connected address */
2381 http_addrlist_t
*current
; /* Current address */
2382 char temp
[256]; /* Temporary address string */
2386 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2391 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2398 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2399 http_tls_stop(http
);
2401 #endif /* HAVE_SSL */
2404 * Close any previously open socket...
2409 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2411 httpAddrClose(NULL
, http
->fd
);
2417 * Reset all state (except fields, which may be reused)...
2420 http
->state
= HTTP_STATE_WAITING
;
2421 http
->version
= HTTP_VERSION_1_1
;
2422 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2423 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2424 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2425 http
->_data_remaining
= 0;
2427 http
->data_remaining
= 0;
2428 http
->hostaddr
= NULL
;
2432 * Connect to the server...
2436 for (current
= http
->addrlist
; current
; current
= current
->next
)
2437 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2438 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2439 httpAddrPort(&(current
->addr
))));
2442 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2446 * Unable to connect...
2450 http
->error
= WSAGetLastError();
2452 http
->error
= errno
;
2454 http
->status
= HTTP_STATUS_ERROR
;
2456 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2457 strerror(http
->error
)));
2462 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2464 if (http
->timeout_value
> 0)
2465 http_set_timeout(http
->fd
, http
->timeout_value
);
2467 http
->hostaddr
= &(addr
->addr
);
2471 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2474 * Always do encryption via SSL.
2477 if (http_tls_start(http
) != 0)
2479 httpAddrClose(NULL
, http
->fd
);
2484 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2485 return (http_tls_upgrade(http
));
2486 #endif /* HAVE_SSL */
2488 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2489 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2490 httpAddrPort(http
->hostaddr
)));
2497 * 'httpSetAuthString()' - Set the current authorization string.
2499 * This function just stores a copy of the current authorization string in
2500 * the HTTP connection object. You must still call httpSetField() to set
2501 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2502 * httpHead(), httpOptions(), httpPost, or httpPut().
2504 * @since CUPS 1.3/OS X 10.5@
2508 httpSetAuthString(http_t
*http
, /* I - HTTP connection */
2509 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2510 const char *data
) /* I - Auth data (NULL for none) */
2513 * Range check input...
2519 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2520 free(http
->authstring
);
2522 http
->authstring
= http
->_authstring
;
2527 * Set the current authorization string...
2530 size_t len
= strlen(scheme
) + (data
? strlen(data
) + 1 : 0) + 1;
2533 if (len
> sizeof(http
->_authstring
))
2535 if ((temp
= malloc(len
)) == NULL
)
2536 len
= sizeof(http
->_authstring
);
2538 http
->authstring
= temp
;
2542 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2544 strlcpy(http
->authstring
, scheme
, len
);
2549 * Clear the current authorization string...
2552 http
->_authstring
[0] = '\0';
2558 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2561 * @since CUPS 1.5/OS X 10.7@
2564 int /* O - Status of call (0 = success) */
2565 httpSetCredentials(http_t
*http
, /* I - HTTP connection */
2566 cups_array_t
*credentials
) /* I - Array of credentials */
2568 if (!http
|| cupsArrayCount(credentials
) < 1)
2571 _httpFreeCredentials(http
->tls_credentials
);
2573 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2575 return (http
->tls_credentials
? 0 : -1);
2580 * 'httpSetCookie()' - Set the cookie value(s).
2582 * @since CUPS 1.1.19/OS X 10.3@
2586 httpSetCookie(http_t
*http
, /* I - Connection */
2587 const char *cookie
) /* I - Cookie string */
2596 http
->cookie
= strdup(cookie
);
2598 http
->cookie
= NULL
;
2603 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2605 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2606 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2608 * @since CUPS 1.7/OS X 10.9@
2612 httpSetDefaultField(http_t
*http
, /* I - HTTP connection */
2613 http_field_t field
, /* I - Field index */
2614 const char *value
)/* I - Value */
2616 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2617 http
, field
, http_fields
[field
], value
));
2624 case HTTP_FIELD_ACCEPT_ENCODING
:
2625 if (http
->default_accept_encoding
)
2626 _cupsStrFree(http
->default_accept_encoding
);
2628 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2631 case HTTP_FIELD_SERVER
:
2632 if (http
->default_server
)
2633 _cupsStrFree(http
->default_server
);
2635 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2638 case HTTP_FIELD_USER_AGENT
:
2639 if (http
->default_user_agent
)
2640 _cupsStrFree(http
->default_user_agent
);
2642 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2646 DEBUG_puts("1httpSetDefaultField: Ignored.");
2653 * 'httpSetExpect()' - Set the Expect: header in a request.
2655 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2658 * @since CUPS 1.2/OS X 10.5@
2662 httpSetExpect(http_t
*http
, /* I - HTTP connection */
2663 http_status_t expect
) /* I - HTTP status to expect
2664 (@code HTTP_STATUS_CONTINUE@) */
2666 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2669 http
->expect
= expect
;
2674 * 'httpSetField()' - Set the value of an HTTP header.
2678 httpSetField(http_t
*http
, /* I - HTTP connection */
2679 http_field_t field
, /* I - Field index */
2680 const char *value
) /* I - Value */
2682 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2683 field
, http_fields
[field
], value
));
2686 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2687 field
>= HTTP_FIELD_MAX
||
2693 case HTTP_FIELD_ACCEPT_ENCODING
:
2694 if (http
->accept_encoding
)
2695 _cupsStrFree(http
->accept_encoding
);
2697 http
->accept_encoding
= _cupsStrAlloc(value
);
2700 case HTTP_FIELD_ALLOW
:
2702 _cupsStrFree(http
->allow
);
2704 http
->allow
= _cupsStrAlloc(value
);
2707 case HTTP_FIELD_SERVER
:
2709 _cupsStrFree(http
->server
);
2711 http
->server
= _cupsStrAlloc(value
);
2715 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2719 if (field
== HTTP_FIELD_AUTHORIZATION
)
2722 * Special case for Authorization: as its contents can be
2723 * longer than HTTP_MAX_VALUE
2726 if (http
->field_authorization
)
2727 free(http
->field_authorization
);
2729 http
->field_authorization
= strdup(value
);
2731 else if (field
== HTTP_FIELD_HOST
)
2734 * Special-case for Host: as we don't want a trailing "." on the hostname and
2735 * need to bracket IPv6 numeric addresses.
2738 char *ptr
= strchr(value
, ':');
2740 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2743 * Bracket IPv6 numeric addresses...
2745 * This is slightly inefficient (basically copying twice), but is an edge
2746 * case and not worth optimizing...
2749 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2750 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2755 * Check for a trailing dot on the hostname...
2758 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2762 ptr
+= strlen(ptr
) - 1;
2770 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
2771 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
2773 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
2774 http_content_coding_start(http
, value
);
2776 #endif /* HAVE_LIBZ */
2781 * 'httpSetKeepAlive()' - Set the current Keep-Alive state of a connection.
2788 http_t
*http
, /* I - HTTP connection */
2789 http_keepalive_t keep_alive
) /* I - New Keep-Alive value */
2792 http
->keep_alive
= keep_alive
;
2797 * 'httpSetLength()' - Set the content-length and content-encoding.
2799 * @since CUPS 1.2/OS X 10.5@
2803 httpSetLength(http_t
*http
, /* I - HTTP connection */
2804 size_t length
) /* I - Length (0 for chunked) */
2806 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
2807 CUPS_LLCAST length
));
2814 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
2816 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2820 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2821 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2822 CUPS_LLFMT
, CUPS_LLCAST length
);
2828 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2830 * The optional timeout callback receives both the HTTP connection and a user
2831 * data pointer and must return 1 to continue or 0 to error (time) out.
2833 * @since CUPS 1.5/OS X 10.7@
2838 http_t
*http
, /* I - HTTP connection */
2839 double timeout
, /* I - Number of seconds for timeout,
2840 must be greater than 0 */
2841 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2842 void *user_data
) /* I - User data pointer */
2844 if (!http
|| timeout
<= 0.0)
2847 http
->timeout_cb
= cb
;
2848 http
->timeout_data
= user_data
;
2849 http
->timeout_value
= timeout
;
2852 http_set_timeout(http
->fd
, timeout
);
2854 http_set_wait(http
);
2859 * 'httpShutdown()' - Shutdown one side of an HTTP connection.
2865 httpShutdown(http_t
*http
) /* I - HTTP connection */
2867 if (!http
|| http
->fd
< 0)
2871 http_tls_stop(http
);
2873 shutdown(http
->fd
, SHUT_RD
);
2878 * 'httpTrace()' - Send an TRACE request to the server.
2881 int /* O - Status of call (0 = success) */
2882 httpTrace(http_t
*http
, /* I - HTTP connection */
2883 const char *uri
) /* I - URI for trace */
2885 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
2890 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2892 * Note: Unlike httpUpdate(), this function does not flush pending write data
2893 * and only retrieves a single status line from the HTTP connection.
2896 int /* O - 1 to continue, 0 to stop */
2897 _httpUpdate(http_t
*http
, /* I - HTTP connection */
2898 http_status_t
*status
) /* O - Current HTTP status */
2900 char line
[32768], /* Line from connection... */
2901 *value
; /* Pointer to value on line */
2902 http_field_t field
; /* Field index */
2903 int major
, minor
; /* HTTP version numbers */
2906 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2907 httpStateString(http
->state
)));
2910 * Grab a single line from the connection...
2913 if (!httpGets(line
, sizeof(line
), http
))
2915 *status
= HTTP_STATUS_ERROR
;
2919 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2921 if (line
[0] == '\0')
2924 * Blank line means the start of the data section (if any). Return
2925 * the result code, too...
2927 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
2928 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
2932 if (http
->status
== HTTP_STATUS_CONTINUE
)
2934 *status
= http
->status
;
2938 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
2939 http
->digest_tries
= 0;
2942 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
2944 if (http_tls_start(http
) != 0)
2946 httpAddrClose(NULL
, http
->fd
);
2948 *status
= http
->status
= HTTP_STATUS_ERROR
;
2952 *status
= HTTP_STATUS_CONTINUE
;
2955 #endif /* HAVE_SSL */
2957 if (http_set_length(http
) < 0)
2959 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
2960 http
->error
= EINVAL
;
2961 http
->status
= *status
= HTTP_STATUS_ERROR
;
2965 switch (http
->state
)
2967 case HTTP_STATE_GET
:
2968 case HTTP_STATE_POST
:
2969 case HTTP_STATE_POST_RECV
:
2970 case HTTP_STATE_PUT
:
2973 DEBUG_printf(("1_httpUpdate: Set state to %s.",
2974 httpStateString(http
->state
)));
2976 case HTTP_STATE_POST_SEND
:
2977 case HTTP_STATE_HEAD
:
2981 http
->state
= HTTP_STATE_WAITING
;
2983 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
2988 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
2989 http_content_coding_start(http
,
2990 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
2991 #endif /* HAVE_LIBZ */
2993 *status
= http
->status
;
2996 else if (!strncmp(line
, "HTTP/", 5))
2999 * Got the beginning of a response...
3002 int intstatus
; /* Status value as an integer */
3004 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3006 *status
= http
->status
= HTTP_STATUS_ERROR
;
3010 httpClearFields(http
);
3012 http
->version
= (http_version_t
)(major
* 100 + minor
);
3013 *status
= http
->status
= (http_status_t
)intstatus
;
3015 else if ((value
= strchr(line
, ':')) != NULL
)
3022 while (_cups_isspace(*value
))
3025 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3028 * Be tolerants of servers that send unknown attribute fields...
3031 if (!_cups_strcasecmp(line
, "expect"))
3034 * "Expect: 100-continue" or similar...
3037 http
->expect
= (http_status_t
)atoi(value
);
3039 else if (!_cups_strcasecmp(line
, "cookie"))
3042 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3045 httpSetCookie(http
, value
);
3047 else if ((field
= httpFieldValue(line
)) != HTTP_FIELD_UNKNOWN
)
3048 httpSetField(http
, field
, value
);
3051 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3056 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3057 http
->error
= EINVAL
;
3058 http
->status
= *status
= HTTP_STATUS_ERROR
;
3067 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3070 http_status_t
/* O - HTTP status */
3071 httpUpdate(http_t
*http
) /* I - HTTP connection */
3073 http_status_t status
; /* Request status */
3076 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3077 httpStateString(http
->state
)));
3080 * Flush pending data, if any...
3085 DEBUG_puts("2httpUpdate: flushing buffer...");
3087 if (httpFlushWrite(http
) < 0)
3088 return (HTTP_STATUS_ERROR
);
3092 * If we haven't issued any commands, then there is nothing to "update"...
3095 if (http
->state
== HTTP_STATE_WAITING
)
3096 return (HTTP_STATUS_CONTINUE
);
3099 * Grab all of the lines we can from the connection...
3102 while (_httpUpdate(http
, &status
));
3105 * See if there was an error...
3108 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3110 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3111 return (http
->status
);
3116 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3117 strerror(http
->error
)));
3118 http
->status
= HTTP_STATUS_ERROR
;
3119 return (HTTP_STATUS_ERROR
);
3123 * Return the current status...
3131 * '_httpWait()' - Wait for data available on a connection (no flush).
3134 int /* O - 1 if data is available, 0 otherwise */
3135 _httpWait(http_t
*http
, /* I - HTTP connection */
3136 int msec
, /* I - Milliseconds to wait */
3137 int usessl
) /* I - Use SSL context? */
3140 struct pollfd pfd
; /* Polled file descriptor */
3142 fd_set input_set
; /* select() input set */
3143 struct timeval timeout
; /* Timeout */
3144 #endif /* HAVE_POLL */
3145 int nfds
; /* Result from select()/poll() */
3148 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3152 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3157 * Check the SSL/TLS buffers for data first...
3161 if (http
->tls
&& http_tls_pending(http
))
3163 DEBUG_puts("5_httpWait: Return 1 since there is pending TLS data.");
3166 #endif /* HAVE_SSL */
3169 * Then try doing a select() or poll() to poll the socket...
3174 pfd
.events
= POLLIN
;
3178 nfds
= poll(&pfd
, 1, msec
);
3180 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3185 FD_ZERO(&input_set
);
3186 FD_SET(http
->fd
, &input_set
);
3188 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3192 timeout
.tv_sec
= msec
/ 1000;
3193 timeout
.tv_usec
= (msec
% 1000) * 1000;
3195 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3198 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3200 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3203 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3204 WSAGetLastError() == WSAEWOULDBLOCK
));
3206 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3208 #endif /* HAVE_POLL */
3210 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3218 * 'httpWait()' - Wait for data available on a connection.
3220 * @since CUPS 1.1.19/OS X 10.3@
3223 int /* O - 1 if data is available, 0 otherwise */
3224 httpWait(http_t
*http
, /* I - HTTP connection */
3225 int msec
) /* I - Milliseconds to wait */
3228 * First see if there is data in the buffer...
3231 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3238 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3243 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3245 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3248 #endif /* HAVE_LIBZ */
3251 * Flush pending data, if any...
3256 DEBUG_puts("3httpWait: Flushing write buffer.");
3258 if (httpFlushWrite(http
) < 0)
3263 * If not, check the SSL/TLS buffers and do a select() on the connection...
3266 return (_httpWait(http
, msec
, 1));
3271 * 'httpWrite()' - Write data to a HTTP connection.
3273 * This function is deprecated. Use the httpWrite2() function which can
3274 * write more than 2GB of data.
3279 int /* O - Number of bytes written */
3280 httpWrite(http_t
*http
, /* I - HTTP connection */
3281 const char *buffer
, /* I - Buffer for data */
3282 int length
) /* I - Number of bytes to write */
3284 return ((int)httpWrite2(http
, buffer
, (size_t)length
));
3289 * 'httpWrite2()' - Write data to a HTTP connection.
3291 * @since CUPS 1.2/OS X 10.5@
3294 ssize_t
/* O - Number of bytes written */
3295 httpWrite2(http_t
*http
, /* I - HTTP connection */
3296 const char *buffer
, /* I - Buffer for data */
3297 size_t length
) /* I - Number of bytes to write */
3299 ssize_t bytes
; /* Bytes written */
3302 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3303 buffer
, CUPS_LLCAST length
));
3306 * Range check input...
3309 if (!http
|| !buffer
)
3311 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3316 * Mark activity on the connection...
3319 http
->activity
= time(NULL
);
3322 * Buffer small writes for better performance...
3328 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3332 http_content_coding_finish(http
);
3337 http
->stream
.next_in
= (Bytef
*)buffer
;
3338 http
->stream
.avail_in
= (uInt
)length
;
3339 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3340 http
->stream
.avail_out
= (uInt
)(sizeof(http
->wbuffer
) - (size_t)http
->wused
);
3342 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3344 http
->wused
= (int)(sizeof(http
->wbuffer
) - (size_t)http
->stream
.avail_out
);
3346 if (http
->stream
.avail_out
== 0)
3348 if (httpFlushWrite(http
) < 0)
3350 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3354 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3355 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3359 http
->wused
= (int)(sizeof(http
->wbuffer
) - (size_t)http
->stream
.avail_out
);
3360 bytes
= (ssize_t
)length
;
3364 #endif /* HAVE_LIBZ */
3367 if (http
->wused
&& (length
+ (size_t)http
->wused
) > sizeof(http
->wbuffer
))
3369 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3370 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3372 httpFlushWrite(http
);
3375 if ((length
+ (size_t)http
->wused
) <= sizeof(http
->wbuffer
) && length
< sizeof(http
->wbuffer
))
3378 * Write to buffer...
3381 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3382 CUPS_LLCAST length
));
3384 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3385 http
->wused
+= (int)length
;
3386 bytes
= (ssize_t
)length
;
3391 * Otherwise write the data directly...
3394 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3395 CUPS_LLCAST length
));
3397 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3398 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, length
);
3400 bytes
= (ssize_t
)http_write(http
, buffer
, length
);
3402 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3403 CUPS_LLCAST bytes
));
3406 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3407 http
->data_remaining
-= bytes
;
3413 * Handle end-of-request processing...
3416 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3417 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3420 * Finished with the transfer; unless we are sending POST or PUT
3426 http_content_coding_finish(http
);
3427 #endif /* HAVE_LIBZ */
3431 if (httpFlushWrite(http
) < 0)
3435 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3438 * Send a 0-length chunk at the end of the request...
3441 http_write(http
, "0\r\n\r\n", 5);
3444 * Reset the data state...
3447 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3448 http
->data_remaining
= 0;
3451 if (http
->state
== HTTP_STATE_POST_RECV
)
3453 else if (http
->state
== HTTP_STATE_POST_SEND
||
3454 http
->state
== HTTP_STATE_GET_SEND
)
3455 http
->state
= HTTP_STATE_WAITING
;
3457 http
->state
= HTTP_STATE_STATUS
;
3459 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3460 httpStateString(http
->state
)));
3463 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3470 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3472 * @since CUPS 1.7/OS X 10.9@
3475 int /* O - 0 on success, -1 on error */
3476 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3477 http_status_t status
) /* I - Status code */
3479 http_encoding_t old_encoding
; /* Old data_encoding value */
3480 off_t old_remaining
; /* Old data_remaining value */
3484 * Range check input...
3487 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3489 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3491 DEBUG_puts("1httpWriteResponse: Bad input.");
3496 * Set the various standard fields if they aren't already...
3499 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3500 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3502 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3504 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
3505 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3508 if (http
->version
== HTTP_VERSION_1_1
)
3510 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3512 if (http
->keep_alive
)
3513 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3515 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3518 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3519 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3523 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
||
3524 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
3526 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3527 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3529 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3530 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3532 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
3533 httpSetField(http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
3535 #endif /* HAVE_SSL */
3538 httpSetField(http
, HTTP_FIELD_SERVER
,
3539 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3542 * Set the Accept-Encoding field if it isn't already...
3545 if (!http
->accept_encoding
)
3546 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3547 http
->default_accept_encoding
? http
->default_accept_encoding
:
3549 "gzip, deflate, identity");
3552 #endif /* HAVE_LIBZ */
3555 * Send the response header...
3558 old_encoding
= http
->data_encoding
;
3559 old_remaining
= http
->data_remaining
;
3560 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3562 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3563 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3565 http
->status
= HTTP_STATUS_ERROR
;
3569 if (status
!= HTTP_STATUS_CONTINUE
)
3572 * 100 Continue doesn't have the rest of the response headers...
3575 int i
; /* Looping var */
3576 const char *value
; /* Field value */
3578 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3580 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3582 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3584 http
->status
= HTTP_STATUS_ERROR
;
3592 if (httpPrintf(http
, "Set-Cookie: %s path=/ httponly%s\r\n",
3593 http
->cookie
, http
->tls
? " secure" : "") < 1)
3595 http
->status
= HTTP_STATUS_ERROR
;
3601 if (httpWrite2(http
, "\r\n", 2) < 2)
3603 http
->status
= HTTP_STATUS_ERROR
;
3607 if (httpFlushWrite(http
) < 0)
3609 http
->status
= HTTP_STATUS_ERROR
;
3613 if (status
== HTTP_STATUS_CONTINUE
||
3614 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
3617 * Restore the old data_encoding and data_length values...
3620 http
->data_encoding
= old_encoding
;
3621 http
->data_remaining
= old_remaining
;
3623 if (old_remaining
<= INT_MAX
)
3624 http
->_data_remaining
= (int)old_remaining
;
3626 http
->_data_remaining
= INT_MAX
;
3628 else if (http
->state
== HTTP_STATE_OPTIONS
||
3629 http
->state
== HTTP_STATE_HEAD
||
3630 http
->state
== HTTP_STATE_PUT
||
3631 http
->state
== HTTP_STATE_TRACE
||
3632 http
->state
== HTTP_STATE_CONNECT
||
3633 http
->state
== HTTP_STATE_STATUS
)
3635 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3636 "was %s.", httpStateString(http
->state
)));
3637 http
->state
= HTTP_STATE_WAITING
;
3642 * Force data_encoding and data_length to be set according to the response
3646 http_set_length(http
);
3648 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0)
3650 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3651 "was %s.", httpStateString(http
->state
)));
3652 http
->state
= HTTP_STATE_WAITING
;
3658 * Then start any content encoding...
3661 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
3662 http_content_coding_start(http
,
3663 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3664 #endif /* HAVE_LIBZ */
3674 * 'http_content_coding_finish()' - Finish doing any content encoding.
3678 http_content_coding_finish(
3679 http_t
*http
) /* I - HTTP connection */
3681 int zerr
; /* Compression status */
3682 Byte dummy
[1]; /* Dummy read buffer */
3685 switch (http
->coding
)
3687 case _HTTP_CODING_DEFLATE
:
3688 case _HTTP_CODING_GZIP
:
3689 http
->stream
.next_in
= dummy
;
3690 http
->stream
.avail_in
= 0;
3694 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3695 http
->stream
.avail_out
= (uInt
)(sizeof(http
->wbuffer
) - (size_t)http
->wused
);
3697 zerr
= deflate(&(http
->stream
), Z_FINISH
);
3699 http
->wused
= (int)(sizeof(http
->wbuffer
) - (size_t)http
->stream
.avail_out
);
3700 if (http
->wused
== sizeof(http
->wbuffer
))
3701 httpFlushWrite(http
);
3703 while (zerr
== Z_OK
);
3705 deflateEnd(&(http
->stream
));
3708 httpFlushWrite(http
);
3711 case _HTTP_CODING_INFLATE
:
3712 case _HTTP_CODING_GUNZIP
:
3713 inflateEnd(&(http
->stream
));
3714 free(http
->dbuffer
);
3715 http
->dbuffer
= NULL
;
3722 http
->coding
= _HTTP_CODING_IDENTITY
;
3727 * 'http_content_coding_start()' - Start doing content encoding.
3731 http_content_coding_start(
3732 http_t
*http
, /* I - HTTP connection */
3733 const char *value
) /* I - Value of Content-Encoding */
3735 int zerr
; /* Error/status */
3736 _http_coding_t coding
; /* Content coding value */
3739 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
3742 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
3744 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
3748 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
3750 if (http
->state
== HTTP_STATE_GET_SEND
||
3751 http
->state
== HTTP_STATE_POST_SEND
)
3752 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
3753 _HTTP_CODING_GUNZIP
;
3754 else if (http
->state
== HTTP_STATE_POST_RECV
||
3755 http
->state
== HTTP_STATE_PUT_RECV
)
3756 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
3757 _HTTP_CODING_GUNZIP
;
3760 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3764 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
3766 if (http
->state
== HTTP_STATE_GET_SEND
||
3767 http
->state
== HTTP_STATE_POST_SEND
)
3768 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
3769 _HTTP_CODING_INFLATE
;
3770 else if (http
->state
== HTTP_STATE_POST_RECV
||
3771 http
->state
== HTTP_STATE_PUT_RECV
)
3772 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
3773 _HTTP_CODING_INFLATE
;
3776 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3782 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3786 memset(&(http
->stream
), 0, sizeof(http
->stream
));
3790 case _HTTP_CODING_DEFLATE
:
3791 case _HTTP_CODING_GZIP
:
3793 httpFlushWrite(http
);
3796 * Window size for compression is 11 bits - optimal based on PWG Raster
3797 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
3801 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
3803 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
3804 Z_DEFAULT_STRATEGY
)) < Z_OK
)
3806 http
->status
= HTTP_STATUS_ERROR
;
3807 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
3812 case _HTTP_CODING_INFLATE
:
3813 case _HTTP_CODING_GUNZIP
:
3814 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
3816 http
->status
= HTTP_STATUS_ERROR
;
3817 http
->error
= errno
;
3822 * Window size for decompression is up to 15 bits (maximum supported).
3823 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
3826 if ((zerr
= inflateInit2(&(http
->stream
),
3827 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
3830 free(http
->dbuffer
);
3831 http
->dbuffer
= NULL
;
3832 http
->status
= HTTP_STATUS_ERROR
;
3833 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
3837 http
->stream
.avail_in
= 0;
3838 http
->stream
.next_in
= http
->dbuffer
;
3845 http
->coding
= coding
;
3847 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
3850 #endif /* HAVE_LIBZ */
3854 * 'http_create()' - Create an unconnected HTTP connection.
3857 static http_t
* /* O - HTTP connection */
3859 const char *host
, /* I - Hostname */
3860 int port
, /* I - Port number */
3861 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
3862 int family
, /* I - Address family or AF_UNSPEC */
3863 http_encryption_t encryption
, /* I - Encryption to use */
3864 int blocking
, /* I - 1 for blocking mode */
3865 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
3867 http_t
*http
; /* New HTTP connection */
3868 char service
[255]; /* Service name */
3869 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
3872 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
3873 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
3874 family
, encryption
, blocking
, mode
));
3876 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
3882 * Lookup the host...
3887 myaddrlist
= httpAddrCopyList(addrlist
);
3891 snprintf(service
, sizeof(service
), "%d", port
);
3893 myaddrlist
= httpAddrGetList(host
, family
, service
);
3900 * Allocate memory for the structure...
3903 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
3905 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
3906 httpAddrFreeList(addrlist
);
3911 * Initialize the HTTP data...
3915 http
->activity
= time(NULL
);
3916 http
->addrlist
= myaddrlist
;
3917 http
->blocking
= blocking
;
3920 http
->gssctx
= GSS_C_NO_CONTEXT
;
3921 http
->gssname
= GSS_C_NO_NAME
;
3922 #endif /* HAVE_GSSAPI */
3923 http
->status
= HTTP_STATUS_CONTINUE
;
3924 http
->version
= HTTP_VERSION_1_1
;
3927 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
3929 if (port
== 443) /* Always use encryption for https */
3930 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
3932 http
->encryption
= encryption
;
3934 http_set_wait(http
);
3937 * Return the new structure...
3946 * 'http_debug_hex()' - Do a hex dump of a buffer.
3950 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3951 const char *buffer
, /* I - Buffer to dump */
3952 int bytes
) /* I - Bytes to dump */
3954 int i
, j
, /* Looping vars */
3955 ch
; /* Current character */
3956 char line
[255], /* Line buffer */
3957 *start
, /* Start of line after prefix */
3958 *ptr
; /* Pointer into line */
3961 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3964 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
3966 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3967 start
= line
+ strlen(line
);
3969 for (i
= 0; i
< bytes
; i
+= 16)
3971 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3972 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3976 memcpy(ptr
, " ", 3);
3981 memcpy(ptr
, " ", 3);
3984 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3986 ch
= buffer
[i
+ j
] & 255;
3988 if (ch
< ' ' || ch
>= 127)
4002 * 'http_read()' - Read a buffer from a HTTP connection.
4004 * This function does the low-level read from the socket, retrying and timing
4008 static ssize_t
/* O - Number of bytes read or -1 on error */
4009 http_read(http_t
*http
, /* I - HTTP connection */
4010 char *buffer
, /* I - Buffer */
4011 size_t length
) /* I - Maximum bytes to read */
4013 ssize_t bytes
; /* Bytes read */
4016 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4017 buffer
, CUPS_LLCAST length
));
4019 if (!http
->blocking
)
4021 while (!httpWait(http
, http
->wait_value
))
4023 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4026 DEBUG_puts("2http_read: Timeout.");
4031 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4037 bytes
= http_tls_read(http
, buffer
, (int)length
);
4039 #endif /* HAVE_SSL */
4040 bytes
= recv(http
->fd
, buffer
, length
, 0);
4045 if (WSAGetLastError() != WSAEINTR
)
4047 http
->error
= WSAGetLastError();
4050 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4052 if (!http
->timeout_cb
||
4053 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4055 http
->error
= WSAEWOULDBLOCK
;
4060 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4062 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4064 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4066 http
->error
= errno
;
4069 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4071 http
->error
= errno
;
4075 else if (errno
!= EINTR
)
4077 http
->error
= errno
;
4085 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4086 CUPS_LLCAST bytes
));
4089 http_debug_hex("http_read", buffer
, (int)bytes
);
4095 if (WSAGetLastError() == WSAEINTR
)
4098 http
->error
= WSAGetLastError();
4100 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4103 http
->error
= errno
;
4106 else if (bytes
== 0)
4108 http
->error
= EPIPE
;
4117 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4119 * This function reads data from the HTTP buffer or from the socket, as needed.
4122 static ssize_t
/* O - Number of bytes read or -1 on error */
4123 http_read_buffered(http_t
*http
, /* I - HTTP connection */
4124 char *buffer
, /* I - Buffer */
4125 size_t length
) /* I - Maximum bytes to read */
4127 ssize_t bytes
; /* Bytes read */
4130 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4132 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4136 if (length
> (size_t)http
->used
)
4137 bytes
= (ssize_t
)http
->used
;
4139 bytes
= (ssize_t
)length
;
4141 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4144 memcpy(buffer
, http
->buffer
, (size_t)bytes
);
4145 http
->used
-= (int)bytes
;
4148 memmove(http
->buffer
, http
->buffer
+ bytes
, (size_t)http
->used
);
4151 bytes
= http_read(http
, buffer
, length
);
4158 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4160 * This function reads and validates the chunk length, then does a buffered read
4161 * returning the number of bytes placed in the buffer.
4164 static ssize_t
/* O - Number of bytes read or -1 on error */
4165 http_read_chunk(http_t
*http
, /* I - HTTP connection */
4166 char *buffer
, /* I - Buffer */
4167 size_t length
) /* I - Maximum bytes to read */
4169 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4170 http
, buffer
, CUPS_LLCAST length
));
4172 if (http
->data_remaining
<= 0)
4174 char len
[32]; /* Length string */
4176 if (!httpGets(len
, sizeof(len
), http
))
4178 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4184 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4185 if (!httpGets(len
, sizeof(len
), http
))
4187 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4192 http
->data_remaining
= strtoll(len
, NULL
, 16);
4194 if (http
->data_remaining
< 0)
4196 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4197 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4201 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4202 len
, CUPS_LLCAST http
->data_remaining
));
4204 if (http
->data_remaining
== 0)
4207 * 0-length chunk, grab trailing blank line...
4210 httpGets(len
, sizeof(len
), http
);
4214 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4215 CUPS_LLCAST http
->data_remaining
));
4217 if (http
->data_remaining
<= 0)
4219 else if (length
> (size_t)http
->data_remaining
)
4220 length
= (size_t)http
->data_remaining
;
4222 return (http_read_buffered(http
, buffer
, length
));
4227 * 'http_send()' - Send a request with all fields and the trailing blank line.
4230 static int /* O - 0 on success, non-zero on error */
4231 http_send(http_t
*http
, /* I - HTTP connection */
4232 http_state_t request
, /* I - Request code */
4233 const char *uri
) /* I - URI */
4235 int i
; /* Looping var */
4236 char buf
[1024]; /* Encoded URI buffer */
4237 const char *value
; /* Field value */
4238 static const char * const codes
[] = /* Request code strings */
4258 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4259 http
, codes
[request
], uri
));
4261 if (http
== NULL
|| uri
== NULL
)
4265 * Set the User-Agent field if it isn't already...
4268 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4270 if (http
->default_user_agent
)
4271 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4273 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4277 * Set the Accept-Encoding field if it isn't already...
4280 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4281 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4282 http
->default_accept_encoding
);
4285 * Encode the URI as needed...
4288 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4291 * See if we had an error the last time around; if so, reconnect...
4294 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4295 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4297 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4298 http
->fd
, http
->status
, http
->tls_upgrade
));
4300 if (httpReconnect2(http
, 30000, NULL
))
4305 * Flush any written data that is pending...
4310 if (httpFlushWrite(http
) < 0)
4311 if (httpReconnect2(http
, 30000, NULL
))
4316 * Send the request header...
4319 http
->state
= request
;
4320 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4322 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4325 http
->status
= HTTP_STATUS_CONTINUE
;
4328 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4330 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4331 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4333 #endif /* HAVE_SSL */
4335 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4337 http
->status
= HTTP_STATUS_ERROR
;
4341 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4342 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4344 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
4346 if (i
== HTTP_FIELD_HOST
)
4348 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4349 httpAddrPort(http
->hostaddr
)) < 1)
4351 http
->status
= HTTP_STATUS_ERROR
;
4355 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4357 http
->status
= HTTP_STATUS_ERROR
;
4363 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4365 http
->status
= HTTP_STATUS_ERROR
;
4369 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
4370 http
->mode
, http
->state
));
4372 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4373 (http
->state
== HTTP_STATE_POST_RECV
||
4374 http
->state
== HTTP_STATE_PUT_RECV
))
4375 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4377 http
->status
= HTTP_STATUS_ERROR
;
4381 if (httpPrintf(http
, "\r\n") < 1)
4383 http
->status
= HTTP_STATUS_ERROR
;
4387 if (httpFlushWrite(http
) < 0)
4390 http_set_length(http
);
4391 httpClearFields(http
);
4394 * The Kerberos and AuthRef authentication strings can only be used once...
4397 if (http
->field_authorization
&& http
->authstring
&&
4398 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4399 !strncmp(http
->authstring
, "AuthRef", 7)))
4401 http
->_authstring
[0] = '\0';
4403 if (http
->authstring
!= http
->_authstring
)
4404 free(http
->authstring
);
4406 http
->authstring
= http
->_authstring
;
4414 * 'http_set_length()' - Set the data_encoding and data_remaining values.
4417 static off_t
/* O - Remainder or -1 on error */
4418 http_set_length(http_t
*http
) /* I - Connection */
4420 off_t remaining
; /* Remainder */
4423 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
4424 httpStateString(http
->state
)));
4426 if ((remaining
= httpGetLength2(http
)) >= 0)
4428 if (http
->mode
== _HTTP_MODE_SERVER
&&
4429 http
->state
!= HTTP_STATE_GET_SEND
&&
4430 http
->state
!= HTTP_STATE_PUT
&&
4431 http
->state
!= HTTP_STATE_POST
&&
4432 http
->state
!= HTTP_STATE_POST_SEND
)
4434 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
4438 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
4441 DEBUG_puts("1http_set_length: Setting data_encoding to "
4442 "HTTP_ENCODING_CHUNKED.");
4443 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
4447 DEBUG_puts("1http_set_length: Setting data_encoding to "
4448 "HTTP_ENCODING_LENGTH.");
4449 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4452 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
4453 CUPS_LLCAST remaining
));
4454 http
->data_remaining
= remaining
;
4456 if (remaining
<= INT_MAX
)
4457 http
->_data_remaining
= (int)remaining
;
4459 http
->_data_remaining
= INT_MAX
;
4466 * 'http_set_timeout()' - Set the socket timeout values.
4470 http_set_timeout(int fd
, /* I - File descriptor */
4471 double timeout
) /* I - Timeout in seconds */
4474 DWORD tv
= (DWORD
)(timeout
* 1000);
4475 /* Timeout in milliseconds */
4477 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4478 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4481 struct timeval tv
; /* Timeout in secs and usecs */
4483 tv
.tv_sec
= (int)timeout
;
4484 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
4486 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4487 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4493 * 'http_set_wait()' - Set the default wait value for reads.
4497 http_set_wait(http_t
*http
) /* I - HTTP connection */
4501 http
->wait_value
= (int)(http
->timeout_value
* 1000);
4503 if (http
->wait_value
<= 0)
4504 http
->wait_value
= 60000;
4507 http
->wait_value
= 10000;
4513 * 'http_tls_upgrade()' - Force upgrade to TLS encryption.
4516 static int /* O - Status of connection */
4517 http_tls_upgrade(http_t
*http
) /* I - HTTP connection */
4519 int ret
; /* Return value */
4520 http_t myhttp
; /* Local copy of HTTP data */
4523 DEBUG_printf(("7http_tls_upgrade(%p)", http
));
4526 * Flush the connection to make sure any previous "Upgrade" message
4533 * Copy the HTTP data to a local variable so we can do the OPTIONS
4534 * request without interfering with the existing request data...
4537 memcpy(&myhttp
, http
, sizeof(myhttp
));
4540 * Send an OPTIONS request to the server, requiring SSL or TLS
4541 * encryption on the link...
4544 http
->tls_upgrade
= 1;
4545 http
->field_authorization
= NULL
; /* Don't free the auth string */
4547 httpClearFields(http
);
4548 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4549 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4551 if ((ret
= httpOptions(http
, "*")) == 0)
4554 * Wait for the secure connection...
4557 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
4561 * Restore the HTTP request data...
4564 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4565 http
->data_encoding
= myhttp
.data_encoding
;
4566 http
->data_remaining
= myhttp
.data_remaining
;
4567 http
->_data_remaining
= myhttp
._data_remaining
;
4568 http
->expect
= myhttp
.expect
;
4569 http
->field_authorization
= myhttp
.field_authorization
;
4570 http
->digest_tries
= myhttp
.digest_tries
;
4571 http
->tls_upgrade
= 0;
4574 * See if we actually went secure...
4580 * Server does not support HTTP upgrade...
4583 DEBUG_puts("8http_tls_upgrade: Server does not support HTTP upgrade!");
4585 httpAddrClose(NULL
, http
->fd
);
4594 #endif /* HAVE_SSL */
4598 * 'http_write()' - Write a buffer to a HTTP connection.
4601 static ssize_t
/* O - Number of bytes written */
4602 http_write(http_t
*http
, /* I - HTTP connection */
4603 const char *buffer
, /* I - Buffer for data */
4604 size_t length
) /* I - Number of bytes to write */
4606 ssize_t tbytes
, /* Total bytes sent */
4607 bytes
; /* Bytes sent */
4610 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4611 buffer
, CUPS_LLCAST length
));
4617 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
4619 if (http
->timeout_cb
)
4622 struct pollfd pfd
; /* Polled file descriptor */
4624 fd_set output_set
; /* Output ready for write? */
4625 struct timeval timeout
; /* Timeout value */
4626 #endif /* HAVE_POLL */
4627 int nfds
; /* Result from select()/poll() */
4633 pfd
.events
= POLLOUT
;
4635 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
4636 (errno
== EINTR
|| errno
== EAGAIN
))
4642 FD_ZERO(&output_set
);
4643 FD_SET(http
->fd
, &output_set
);
4645 timeout
.tv_sec
= http
->wait_value
/ 1000;
4646 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
4648 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
4651 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
4652 WSAGetLastError() == WSAEWOULDBLOCK
));
4654 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
4656 #endif /* HAVE_POLL */
4660 http
->error
= errno
;
4663 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4666 http
->error
= WSAEWOULDBLOCK
;
4668 http
->error
= EWOULDBLOCK
;
4678 bytes
= http_tls_write(http
, buffer
, (int)length
);
4680 #endif /* HAVE_SSL */
4681 bytes
= send(http
->fd
, buffer
, length
, 0);
4683 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
4684 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
4689 if (WSAGetLastError() == WSAEINTR
)
4691 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4693 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4696 http
->error
= WSAGetLastError();
4698 else if (WSAGetLastError() != http
->error
&&
4699 WSAGetLastError() != WSAECONNRESET
)
4701 http
->error
= WSAGetLastError();
4708 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4710 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4712 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4715 http
->error
= errno
;
4717 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4719 http
->error
= errno
;
4724 DEBUG_printf(("3http_write: error writing data (%s).",
4725 strerror(http
->error
)));
4732 length
-= (size_t)bytes
;
4736 http_debug_hex("http_write", buffer
- tbytes
, (int)tbytes
);
4739 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
4746 * 'http_write_chunk()' - Write a chunked buffer.
4749 static ssize_t
/* O - Number bytes written */
4750 http_write_chunk(http_t
*http
, /* I - HTTP connection */
4751 const char *buffer
, /* I - Buffer to write */
4752 size_t length
) /* I - Length of buffer */
4754 char header
[16]; /* Chunk header */
4755 ssize_t bytes
; /* Bytes written */
4758 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4759 http
, buffer
, CUPS_LLCAST length
));
4762 * Write the chunk header, data, and trailer.
4765 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
4766 if (http_write(http
, header
, strlen(header
)) < 0)
4768 DEBUG_puts("8http_write_chunk: http_write of length failed.");
4772 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4774 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
4778 if (http_write(http
, "\r\n", 2) < 0)
4780 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");