4 * HTTP routines for CUPS.
6 * Copyright 2007-2013 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * Include necessary headers...
25 #include "cups-private.h"
32 # include <sys/time.h>
33 # include <sys/resource.h>
37 #endif /* HAVE_POLL */
45 static void http_content_coding_finish(http_t
*http
);
46 static void http_content_coding_start(http_t
*http
,
48 #endif /* HAVE_LIBZ */
49 static http_t
*http_create(const char *host
, int port
,
50 http_addrlist_t
*addrlist
, int family
,
51 http_encryption_t encryption
,
52 int blocking
, _http_mode_t mode
);
54 static void http_debug_hex(const char *prefix
, const char *buffer
,
57 static ssize_t
http_read(http_t
*http
, char *buffer
, size_t length
);
58 static ssize_t
http_read_buffered(http_t
*http
, char *buffer
, size_t length
);
59 static ssize_t
http_read_chunk(http_t
*http
, char *buffer
, size_t length
);
60 static int http_send(http_t
*http
, http_state_t request
,
62 static ssize_t
http_write(http_t
*http
, const char *buffer
,
64 static ssize_t
http_write_chunk(http_t
*http
, const char *buffer
,
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-openssl.c"
80 # elif defined(HAVE_GNUTLS)
81 # include "tls-gnutls.c"
82 # elif defined(HAVE_CDSASSL)
83 # include "tls-darwin.c"
85 # include "tls-sspi.c"
86 # endif /* HAVE_LIBSSL */
94 static const char * const http_fields
[] =
111 "If-Unmodified-since",
130 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
131 * specified listening socket.
133 * @since CUPS 1.7/OS X 10.9@
136 http_t
* /* O - HTTP connection or @code NULL@ */
137 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
138 int blocking
) /* I - 1 if the connection should be
139 blocking, 0 otherwise */
141 http_t
*http
; /* HTTP connection */
142 http_addrlist_t addrlist
; /* Dummy address list */
143 socklen_t addrlen
; /* Length of address */
144 int val
; /* Socket option value */
148 * Range check input...
155 * Create the client connection...
158 memset(&addrlist
, 0, sizeof(addrlist
));
160 if ((http
= http_create(NULL
, 0, &addrlist
, AF_UNSPEC
,
161 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
162 _HTTP_MODE_SERVER
)) == NULL
)
166 * Accept the client and get the remote address...
169 addrlen
= sizeof(http_addr_t
);
171 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
174 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
180 http
->hostaddr
= &(http
->addrlist
->addr
);
182 if (httpAddrLocalhost(http
->hostaddr
))
183 strlcpy(http
->hostname
, "localhost", sizeof(http
->hostname
));
185 httpAddrString(http
->hostaddr
, http
->hostname
, sizeof(http
->hostname
));
189 * Disable SIGPIPE for this socket.
193 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
194 #endif /* SO_NOSIGPIPE */
197 * Using TCP_NODELAY improves responsiveness, especially on systems
198 * with a slow loopback interface. Since we write large buffers
199 * when sending print files and requests, there shouldn't be any
200 * performance penalty for this...
204 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
208 * Close this socket when starting another process...
211 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
212 #endif /* FD_CLOEXEC */
219 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
221 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
223 * @since CUPS 1.5/OS X 10.7@
226 int /* O - 0 on success, -1 on error */
228 cups_array_t
*credentials
, /* I - Credentials array */
229 const void *data
, /* I - PEM-encoded X.509 data */
230 size_t datalen
) /* I - Length of data */
232 http_credential_t
*credential
; /* Credential data */
235 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
237 credential
->datalen
= datalen
;
239 if ((credential
->data
= malloc(datalen
)) != NULL
)
241 memcpy(credential
->data
, data
, datalen
);
242 cupsArrayAdd(credentials
, credential
);
254 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
258 httpBlocking(http_t
*http
, /* I - HTTP connection */
259 int b
) /* I - 1 = blocking, 0 = non-blocking */
270 * 'httpCheck()' - Check to see if there is a pending response from the server.
273 int /* O - 0 = no data, 1 = data available */
274 httpCheck(http_t
*http
) /* I - HTTP connection */
276 return (httpWait(http
, 0));
281 * 'httpClearCookie()' - Clear the cookie value(s).
283 * @since CUPS 1.1.19/OS X 10.3@
287 httpClearCookie(http_t
*http
) /* I - HTTP connection */
301 * 'httpClearFields()' - Clear HTTP request fields.
305 httpClearFields(http_t
*http
) /* I - HTTP connection */
307 DEBUG_printf(("httpClearFields(http=%p)", http
));
311 memset(http
->fields
, 0, sizeof(http
->fields
));
313 if (http
->mode
== _HTTP_MODE_CLIENT
)
315 if (http
->hostname
[0] == '/')
316 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
318 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
321 if (http
->field_authorization
)
323 free(http
->field_authorization
);
324 http
->field_authorization
= NULL
;
327 if (http
->accept_encoding
)
329 _cupsStrFree(http
->accept_encoding
);
330 http
->accept_encoding
= NULL
;
335 _cupsStrFree(http
->allow
);
341 _cupsStrFree(http
->server
);
345 http
->expect
= (http_status_t
)0;
351 * 'httpClose()' - Close an HTTP connection.
355 httpClose(http_t
*http
) /* I - HTTP connection */
358 OM_uint32 minor_status
; /* Minor status code */
359 #endif /* HAVE_GSSAPI */
362 DEBUG_printf(("httpClose(http=%p)", http
));
365 * Range check input...
372 * Close any open connection...
375 _httpDisconnect(http
);
378 * Free memory used...
381 httpAddrFreeList(http
->addrlist
);
387 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
388 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
390 if (http
->gssname
!= GSS_C_NO_NAME
)
391 gss_release_name(&minor_status
, &http
->gssname
);
392 #endif /* HAVE_GSSAPI */
394 #ifdef HAVE_AUTHORIZATION_H
396 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
397 #endif /* HAVE_AUTHORIZATION_H */
399 httpClearFields(http
);
401 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
402 free(http
->authstring
);
409 * 'httpConnect()' - Connect to a HTTP server.
411 * This function is deprecated - use @link httpConnect2@ instead.
416 http_t
* /* O - New HTTP connection */
417 httpConnect(const char *host
, /* I - Host to connect to */
418 int port
) /* I - Port number */
420 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
,
421 HTTP_ENCRYPTION_IF_REQUESTED
, 1, 30000, NULL
));
426 * 'httpConnect2()' - Connect to a HTTP server.
428 * @since CUPS 1.7/OS X 10.9@
431 http_t
* /* O - New HTTP connection */
433 const char *host
, /* I - Host to connect to */
434 int port
, /* I - Port number */
435 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
436 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
437 http_encryption_t encryption
, /* I - Type of encryption to use */
438 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
439 int msec
, /* I - Connection timeout in milliseconds, 0 means don't connect */
440 int *cancel
) /* I - Pointer to "cancel" variable */
442 http_t
*http
; /* New HTTP connection */
445 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
446 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
447 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
450 * Create the HTTP structure...
453 if ((http
= http_create(host
, port
, addrlist
, family
, encryption
, blocking
,
454 _HTTP_MODE_CLIENT
)) == NULL
)
458 * Optionally connect to the remote system...
461 if (msec
== 0 || !httpReconnect2(http
, msec
, cancel
))
465 * Could not connect to any known address - bail out!
475 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
477 * This function is now deprecated. Please use the @link httpConnect2@ function
483 http_t
* /* O - New HTTP connection */
485 const char *host
, /* I - Host to connect to */
486 int port
, /* I - Port number */
487 http_encryption_t encryption
) /* I - Type of encryption to use */
489 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
490 host
, port
, encryption
));
492 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
498 * 'httpDelete()' - Send a DELETE request to the server.
501 int /* O - Status of call (0 = success) */
502 httpDelete(http_t
*http
, /* I - HTTP connection */
503 const char *uri
) /* I - URI to delete */
505 return (http_send(http
, HTTP_STATE_DELETE
, uri
));
510 * '_httpDisconnect()' - Disconnect a HTTP connection.
514 _httpDisconnect(http_t
*http
) /* I - HTTP connection */
519 #endif /* HAVE_SSL */
521 httpAddrClose(NULL
, http
->fd
);
528 * 'httpEncryption()' - Set the required encryption on the link.
531 int /* O - -1 on error, 0 on success */
532 httpEncryption(http_t
*http
, /* I - HTTP connection */
533 http_encryption_t e
) /* I - New encryption preference */
535 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
541 if (http
->mode
== _HTTP_MODE_CLIENT
)
543 http
->encryption
= e
;
545 if ((http
->encryption
== HTTP_ENCRYPTION_ALWAYS
&& !http
->tls
) ||
546 (http
->encryption
== HTTP_ENCRYPTION_NEVER
&& http
->tls
))
547 return (httpReconnect2(http
, 30000, NULL
));
548 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
549 return (http_tls_upgrade(http
));
555 if (e
== HTTP_ENCRYPTION_NEVER
&& http
->tls
)
558 http
->encryption
= e
;
559 if (e
!= HTTP_ENCRYPTION_IF_REQUESTED
&& !http
->tls
)
560 return (http_tls_start(http
));
565 if (e
== HTTP_ENCRYPTION_ALWAYS
|| e
== HTTP_ENCRYPTION_REQUIRED
)
569 #endif /* HAVE_SSL */
574 * 'httpError()' - Get the last error on a connection.
577 int /* O - Error code (errno) value */
578 httpError(http_t
*http
) /* I - HTTP connection */
581 return (http
->error
);
588 * 'httpFieldValue()' - Return the HTTP field enumeration value for a field
592 http_field_t
/* O - Field index */
593 httpFieldValue(const char *name
) /* I - String name */
595 int i
; /* Looping var */
598 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
599 if (!_cups_strcasecmp(name
, http_fields
[i
]))
600 return ((http_field_t
)i
);
602 return (HTTP_FIELD_UNKNOWN
);
607 * 'httpFlush()' - Flush data from a HTTP connection.
611 httpFlush(http_t
*http
) /* I - HTTP connection */
613 char buffer
[8192]; /* Junk buffer */
614 int blocking
; /* To block or not to block */
615 http_state_t oldstate
; /* Old state */
618 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
619 httpStateString(http
->state
)));
622 * Nothing to do if we are in the "waiting" state...
625 if (http
->state
== HTTP_STATE_WAITING
)
629 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
632 blocking
= http
->blocking
;
636 * Read any data we can...
639 oldstate
= http
->state
;
640 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
643 * Restore blocking and reset the connection if we didn't get all of
644 * the remaining data...
647 http
->blocking
= blocking
;
649 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
653 * Didn't get the data back, so close the current connection.
658 http_content_coding_finish(http
);
659 #endif /* HAVE_LIBZ */
661 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
663 http
->state
= HTTP_STATE_WAITING
;
668 #endif /* HAVE_SSL */
670 httpAddrClose(NULL
, http
->fd
);
678 * 'httpFlushWrite()' - Flush data in write buffer.
680 * @since CUPS 1.2/OS X 10.5@
683 int /* O - Bytes written or -1 on error */
684 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
686 int bytes
; /* Bytes written */
689 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
690 http
? http
->data_encoding
: -1));
692 if (!http
|| !http
->wused
)
694 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
695 "1httpFlushWrite: No connection.");
699 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
700 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
702 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
706 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
713 * 'httpFreeCredentials()' - Free an array of credentials.
718 cups_array_t
*credentials
) /* I - Array of credentials */
720 http_credential_t
*credential
; /* Credential */
723 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
725 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
727 cupsArrayRemove(credentials
, credential
);
728 free((void *)credential
->data
);
732 cupsArrayDelete(credentials
);
737 * 'httpGet()' - Send a GET request to the server.
740 int /* O - Status of call (0 = success) */
741 httpGet(http_t
*http
, /* I - HTTP connection */
742 const char *uri
) /* I - URI to get */
744 return (http_send(http
, HTTP_STATE_GET
, uri
));
749 * 'httpGetActivity()' - Get the most recent activity for a connection.
751 * The return value is the UNIX time of the last read or write.
756 time_t /* O - Time of last read or write */
757 httpGetActivity(http_t
*http
) /* I - HTTP connection */
759 return (http
? http
->activity
: 0);
764 * 'httpGetAuthString()' - Get the current authorization string.
766 * The authorization string is set by cupsDoAuthentication() and
767 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
768 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
771 * @since CUPS 1.3/OS X 10.5@
774 char * /* O - Authorization string */
775 httpGetAuthString(http_t
*http
) /* I - HTTP connection */
778 return (http
->authstring
);
785 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
787 * @since CUPS 1.2/OS X 10.5@
790 int /* O - 1 if blocking, 0 if non-blocking */
791 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
793 return (http
? http
->blocking
: 0);
798 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
799 * the client and server.
801 * This function uses the value of the Accepts-Encoding HTTP header and must be
802 * called after receiving a response from the server or a request from the
803 * client. The value returned can be use in subsequent requests (for clients)
804 * or in the response (for servers) in order to compress the content stream.
806 * @since CUPS 1.7/OS X 10.9@
809 const char * /* O - Content-Coding value or
810 @code NULL@ for the identity
812 httpGetContentEncoding(http_t
*http
) /* I - HTTP connection */
815 if (http
&& http
->accept_encoding
)
817 int i
; /* Looping var */
818 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
819 *start
, /* Start of coding value */
820 *end
; /* End of coding value */
821 double qvalue
; /* "qvalue" for coding */
822 struct lconv
*loc
= localeconv(); /* Locale data */
823 static const char * const codings
[] =
824 { /* Supported content codings */
831 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
833 for (start
= temp
; *start
; start
= end
)
836 * Find the end of the coding name...
841 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
847 * Grab the qvalue as needed...
850 if (!strncmp(end
, ";q=", 3))
851 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
854 * Skip past all attributes...
858 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
864 while (*end
&& isspace(*end
& 255))
868 * Check value if it matches something we support...
874 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
875 if (!strcmp(start
, codings
[i
]))
879 #endif /* HAVE_LIBZ */
886 * 'httpGetCookie()' - Get any cookie data from the response.
888 * @since CUPS 1.1.19/OS X 10.3@
891 const char * /* O - Cookie data or NULL */
892 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
894 return (http
? http
->cookie
: NULL
);
899 * 'httpGetEncryption()' - Get the current encryption mode of a connection.
901 * This function returns the encryption mode for the connection. Use the
902 * @link httpIsEncrypted@ function to determine whether a TLS session has
908 http_encryption_t
/* O - Current encryption mode */
909 httpGetEncryption(http_t
*http
) /* I - HTTP connection */
911 return (http
? http
->encryption
: HTTP_ENCRYPTION_IF_REQUESTED
);
916 * 'httpGetExpect()' - Get the value of the Expect header, if any.
918 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
919 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
921 * @since CUPS 1.7/OS X 10.9@
924 http_status_t
/* O - Expect: status, if any */
925 httpGetExpect(http_t
*http
) /* I - HTTP connection */
928 return (HTTP_STATUS_ERROR
);
930 return (http
->expect
);
935 * 'httpGetFd()' - Get the file descriptor associated with a connection.
937 * @since CUPS 1.2/OS X 10.5@
940 int /* O - File descriptor or -1 if none */
941 httpGetFd(http_t
*http
) /* I - HTTP connection */
943 return (http
? http
->fd
: -1);
948 * 'httpGetField()' - Get a field value from a request/response.
951 const char * /* O - Field value */
952 httpGetField(http_t
*http
, /* I - HTTP connection */
953 http_field_t field
) /* I - Field to get */
955 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
960 case HTTP_FIELD_ACCEPT_ENCODING
:
961 return (http
->accept_encoding
);
963 case HTTP_FIELD_ALLOW
:
964 return (http
->allow
);
966 case HTTP_FIELD_SERVER
:
967 return (http
->server
);
969 case HTTP_FIELD_AUTHORIZATION
:
970 if (http
->field_authorization
)
973 * Special case for WWW-Authenticate: as its contents can be
974 * longer than HTTP_MAX_VALUE...
977 return (http
->field_authorization
);
981 return (http
->fields
[field
]);
987 * 'httpGetKeepAlive()' - Get the current Keep-Alive state of the connection.
992 http_keepalive_t
/* O - Keep-Alive state */
993 httpGetKeepAlive(http_t
*http
) /* I - HTTP connection */
995 return (http
? http
->keep_alive
: HTTP_KEEPALIVE_OFF
);
1000 * 'httpGetLength()' - Get the amount of data remaining from the
1001 * content-length or transfer-encoding fields.
1003 * This function is deprecated and will not return lengths larger than
1004 * 2^31 - 1; use httpGetLength2() instead.
1009 int /* O - Content length */
1010 httpGetLength(http_t
*http
) /* I - HTTP connection */
1013 * Get the read content length and return the 32-bit value.
1018 httpGetLength2(http
);
1020 return (http
->_data_remaining
);
1028 * 'httpGetLength2()' - Get the amount of data remaining from the
1029 * content-length or transfer-encoding fields.
1031 * This function returns the complete content length, even for
1032 * content larger than 2^31 - 1.
1034 * @since CUPS 1.2/OS X 10.5@
1037 off_t
/* O - Content length */
1038 httpGetLength2(http_t
*http
) /* I - HTTP connection */
1040 off_t remaining
; /* Remaining length */
1043 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1044 httpStateString(http
->state
)));
1049 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1051 DEBUG_puts("4httpGetLength2: chunked request!");
1057 * The following is a hack for HTTP servers that don't send a
1058 * Content-Length or Transfer-Encoding field...
1060 * If there is no Content-Length then the connection must close
1061 * after the transfer is complete...
1064 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1067 * Default content length is 0 for errors and certain types of operations,
1068 * and 2^31-1 for other successful requests...
1071 if (http
->status
>= HTTP_STATUS_MULTIPLE_CHOICES
||
1072 http
->state
== HTTP_STATE_OPTIONS
||
1073 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1074 http
->state
== HTTP_STATE_HEAD
||
1075 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1076 http
->state
== HTTP_STATE_DELETE
||
1077 http
->state
== HTTP_STATE_TRACE
||
1078 http
->state
== HTTP_STATE_CONNECT
)
1081 remaining
= 2147483647;
1083 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1087 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1088 CUPS_LLCAST remaining
));
1096 * 'httpGetPending()' - Get the number of bytes that are buffered for writing.
1101 size_t /* O - Number of bytes buffered */
1102 httpGetPending(http_t
*http
) /* I - HTTP connection */
1104 return (http
? http
->wused
: 0);
1109 * 'httpGetReady()' - Get the number of bytes that can be read without blocking.
1114 size_t /* O - Number of bytes available */
1115 httpGetReady(http_t
*http
) /* I - HTTP connection */
1119 else if (http
->used
> 0)
1120 return (http
->used
);
1124 size_t ready
; /* Ready bytes */
1127 if ((ready
= SSL_pending((SSL
*)(http
->tls
))) > 0)
1129 # elif defined(HAVE_GNUTLS)
1130 if ((ready
= gnutls_record_check_pending(http
->tls
)) > 0)
1132 # elif defined(HAVE_CDSASSL)
1133 if (!SSLGetBufferedReadSize(http
->tls
, &ready
) && ready
> 0)
1135 # endif /* HAVE_LIBSSL */
1137 #endif /* HAVE_SSL */
1144 * 'httpGetRemaining()' - Get the number of remaining bytes in the message
1145 * body or current chunk.
1147 * The @link httpIsChunked@ function can be used to determine whether the
1148 * message body is chunked or fixed-length.
1153 size_t /* O - Remaining bytes */
1154 httpGetRemaining(http_t
*http
) /* I - HTTP connection */
1156 return (http
? http
->data_remaining
: 0);
1161 * 'httpGets()' - Get a line of text from a HTTP connection.
1164 char * /* O - Line or NULL */
1165 httpGets(char *line
, /* I - Line to read into */
1166 int length
, /* I - Max length of buffer */
1167 http_t
*http
) /* I - HTTP connection */
1169 char *lineptr
, /* Pointer into line */
1170 *lineend
, /* End of line */
1171 *bufptr
, /* Pointer into input buffer */
1172 *bufend
; /* Pointer to end of buffer */
1173 int bytes
, /* Number of bytes read */
1174 eol
; /* End-of-line? */
1177 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1179 if (!http
|| !line
|| length
<= 1)
1183 * Read a line from the buffer...
1188 lineend
= line
+ length
- 1;
1191 while (lineptr
< lineend
)
1194 * Pre-load the buffer as needed...
1203 while (http
->used
== 0)
1206 * No newline; see if there is more data to be read...
1209 while (!_httpWait(http
, http
->wait_value
, 1))
1211 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1214 DEBUG_puts("3httpGets: Timed out!");
1216 http
->error
= WSAETIMEDOUT
;
1218 http
->error
= ETIMEDOUT
;
1223 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1224 HTTP_MAX_BUFFER
- http
->used
);
1226 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1231 * Nope, can't get a line this time...
1235 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1237 if (WSAGetLastError() == WSAEINTR
)
1239 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1241 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1244 http
->error
= WSAGetLastError();
1246 else if (WSAGetLastError() != http
->error
)
1248 http
->error
= WSAGetLastError();
1253 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1257 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1259 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1261 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1264 http
->error
= errno
;
1266 else if (errno
!= http
->error
)
1268 http
->error
= errno
;
1275 else if (bytes
== 0)
1277 http
->error
= EPIPE
;
1283 * Yup, update the amount used...
1286 http
->used
+= bytes
;
1290 * Now copy as much of the current line as possible...
1293 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1294 lineptr
< lineend
&& bufptr
< bufend
;)
1296 if (*bufptr
== 0x0a)
1302 else if (*bufptr
== 0x0d)
1305 *lineptr
++ = *bufptr
++;
1308 http
->used
-= (int)(bufptr
- http
->buffer
);
1310 memmove(http
->buffer
, bufptr
, http
->used
);
1318 http
->activity
= time(NULL
);
1322 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1328 DEBUG_puts("3httpGets: No new line available!");
1335 * 'httpGetState()' - Get the current state of the HTTP request.
1338 http_state_t
/* O - HTTP state */
1339 httpGetState(http_t
*http
) /* I - HTTP connection */
1341 return (http
? http
->state
: HTTP_STATE_ERROR
);
1346 * 'httpGetStatus()' - Get the status of the last HTTP request.
1348 * @since CUPS 1.2/OS X 10.5@
1351 http_status_t
/* O - HTTP status */
1352 httpGetStatus(http_t
*http
) /* I - HTTP connection */
1354 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1359 * 'httpGetSubField()' - Get a sub-field value.
1364 char * /* O - Value or NULL */
1365 httpGetSubField(http_t
*http
, /* I - HTTP connection */
1366 http_field_t field
, /* I - Field index */
1367 const char *name
, /* I - Name of sub-field */
1368 char *value
) /* O - Value string */
1370 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1375 * 'httpGetSubField2()' - Get a sub-field value.
1377 * @since CUPS 1.2/OS X 10.5@
1380 char * /* O - Value or NULL */
1381 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
1382 http_field_t field
, /* I - Field index */
1383 const char *name
, /* I - Name of sub-field */
1384 char *value
, /* O - Value string */
1385 int valuelen
) /* I - Size of value buffer */
1387 const char *fptr
; /* Pointer into field */
1388 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1389 *ptr
, /* Pointer into string buffer */
1390 *end
; /* End of value buffer */
1392 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1393 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1395 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1396 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1399 end
= value
+ valuelen
- 1;
1401 for (fptr
= http
->fields
[field
]; *fptr
;)
1404 * Skip leading whitespace...
1407 while (_cups_isspace(*fptr
))
1417 * Get the sub-field name...
1421 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1422 ptr
< (temp
+ sizeof(temp
) - 1);
1427 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1430 * Skip trailing chars up to the '='...
1433 while (_cups_isspace(*fptr
))
1443 * Skip = and leading whitespace...
1448 while (_cups_isspace(*fptr
))
1454 * Read quoted string...
1457 for (ptr
= value
, fptr
++;
1458 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1463 while (*fptr
&& *fptr
!= '\"')
1472 * Read unquoted string...
1476 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1481 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1485 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1488 * See if this is the one...
1491 if (!strcmp(name
, temp
))
1493 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1500 DEBUG_puts("3httpGetSubField2: Returning NULL");
1507 * 'httpGetVersion()' - Get the HTTP version at the other end.
1510 http_version_t
/* O - Version number */
1511 httpGetVersion(http_t
*http
) /* I - HTTP connection */
1513 return (http
? http
->version
: HTTP_VERSION_1_0
);
1518 * 'httpHead()' - Send a HEAD request to the server.
1521 int /* O - Status of call (0 = success) */
1522 httpHead(http_t
*http
, /* I - HTTP connection */
1523 const char *uri
) /* I - URI for head */
1525 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1526 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1531 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1532 * default HTTP proxy (if any).
1536 httpInitialize(void)
1538 static int initialized
= 0; /* Have we been called before? */
1540 WSADATA winsockdata
; /* WinSock data */
1543 int i
; /* Looping var */
1544 unsigned char data
[1024]; /* Seed data */
1545 #endif /* HAVE_LIBSSL */
1551 _cupsGlobalUnlock();
1556 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1558 #elif !defined(SO_NOSIGPIPE)
1560 * Ignore SIGPIPE signals...
1564 sigset(SIGPIPE
, SIG_IGN
);
1566 # elif defined(HAVE_SIGACTION)
1567 struct sigaction action
; /* POSIX sigaction data */
1570 memset(&action
, 0, sizeof(action
));
1571 action
.sa_handler
= SIG_IGN
;
1572 sigaction(SIGPIPE
, &action
, NULL
);
1575 signal(SIGPIPE
, SIG_IGN
);
1576 # endif /* !SO_NOSIGPIPE */
1580 http_tls_initialize();
1581 # endif /* HAVE_SSL */
1584 _cupsGlobalUnlock();
1589 * 'httpIsChunked()' - Report whether a message body is chunked.
1591 * This function returns non-zero if the message body is composed of
1592 * variable-length chunks.
1597 int /* O - 1 if chunked, 0 if not */
1598 httpIsChunked(http_t
*http
) /* I - HTTP connection */
1600 return (http
? http
->data_encoding
== HTTP_ENCODING_CHUNKED
: 0);
1605 * 'httpIsEncrypted()' - Report whether a connection is encrypted.
1607 * This function returns non-zero if the connection is currently encrypted.
1612 int /* O - 1 if encrypted, 0 if not */
1613 httpIsEncrypted(http_t
*http
) /* I - HTTP connection */
1615 return (http
? http
->tls
!= NULL
: 0);
1620 * 'httpOptions()' - Send an OPTIONS request to the server.
1623 int /* O - Status of call (0 = success) */
1624 httpOptions(http_t
*http
, /* I - HTTP connection */
1625 const char *uri
) /* I - URI for options */
1627 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1632 * 'httpPeek()' - Peek at data from a HTTP connection.
1634 * This function copies available data from the given HTTP connection, reading
1635 * a buffer as needed. The data is still available for reading using
1636 * @link httpRead@ or @link httpRead2@.
1638 * For non-blocking connections the usual timeouts apply.
1640 * @since CUPS 1.7/OS X 10.9@
1643 ssize_t
/* O - Number of bytes copied */
1644 httpPeek(http_t
*http
, /* I - HTTP connection */
1645 char *buffer
, /* I - Buffer for data */
1646 size_t length
) /* I - Maximum number of bytes */
1648 ssize_t bytes
; /* Bytes read */
1649 char len
[32]; /* Length string */
1652 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1653 http
, buffer
, CUPS_LLCAST length
));
1655 if (http
== NULL
|| buffer
== NULL
)
1658 http
->activity
= time(NULL
);
1664 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1665 http
->data_remaining
<= 0)
1667 DEBUG_puts("2httpPeek: Getting chunk length...");
1669 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1671 DEBUG_puts("1httpPeek: Could not get length!");
1677 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1678 if (!httpGets(len
, sizeof(len
), http
))
1680 DEBUG_puts("1httpPeek: Could not get chunk length.");
1685 http
->data_remaining
= strtoll(len
, NULL
, 16);
1687 if (http
->data_remaining
< 0)
1689 DEBUG_puts("1httpPeek: Negative chunk length!");
1694 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1695 CUPS_LLCAST http
->data_remaining
));
1697 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1700 * A zero-length chunk ends a transfer; unless we are reading POST
1706 http_content_coding_finish(http
);
1707 #endif /* HAVE_LIBZ */
1709 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1710 httpGets(len
, sizeof(len
), http
);
1712 if (http
->state
== HTTP_STATE_POST_RECV
)
1715 http
->state
= HTTP_STATE_STATUS
;
1717 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1718 httpStateString(http
->state
)));
1721 * Prevent future reads for this request...
1724 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1728 else if (length
> (size_t)http
->data_remaining
)
1729 length
= (size_t)http
->data_remaining
;
1732 if (http
->used
== 0 &&
1733 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1735 if (http
->used
== 0)
1736 #endif /* HAVE_LIBZ */
1739 * Buffer small reads for better performance...
1742 ssize_t buflen
; /* Length of read for buffer */
1744 if (!http
->blocking
)
1746 while (!httpWait(http
, http
->wait_value
))
1748 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1755 if (http
->data_remaining
> sizeof(http
->buffer
))
1756 buflen
= sizeof(http
->buffer
);
1758 buflen
= http
->data_remaining
;
1760 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1761 bytes
= http_read(http
, http
->buffer
, buflen
);
1763 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1764 CUPS_LLCAST bytes
));
1768 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1778 # ifdef HAVE_INFLATECOPY
1779 int zerr
; /* Decompressor error */
1780 z_stream stream
; /* Copy of decompressor stream */
1782 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1784 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1785 /* Number of bytes to copy */
1787 if (http
->stream
.avail_in
> 0 &&
1788 http
->stream
.next_in
> http
->dbuffer
)
1789 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1791 http
->stream
.next_in
= http
->dbuffer
;
1793 if (buflen
> http
->data_remaining
)
1794 buflen
= http
->data_remaining
;
1796 if (buflen
> http
->used
)
1797 buflen
= http
->used
;
1799 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1800 "decompression buffer.", (int)buflen
));
1802 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
1803 http
->stream
.avail_in
+= buflen
;
1804 http
->used
-= buflen
;
1805 http
->data_remaining
-= buflen
;
1808 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
1811 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
1812 (int)http
->stream
.avail_in
));
1814 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
1816 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
1817 http
->error
= ENOMEM
;
1821 stream
.next_out
= (Bytef
*)buffer
;
1822 stream
.avail_out
= length
;
1824 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
1825 inflateEnd(&stream
);
1829 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
1831 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
1832 http
->stream
.avail_in
);
1839 bytes
= length
- http
->stream
.avail_out
;
1842 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
1843 "work with compressed streams.");
1845 # endif /* HAVE_INFLATECOPY */
1848 #endif /* HAVE_LIBZ */
1851 if (length
> (size_t)http
->used
)
1852 length
= (size_t)http
->used
;
1854 bytes
= (ssize_t
)length
;
1856 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
1859 memcpy(buffer
, http
->buffer
, length
);
1867 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1870 http
->error
= WSAGetLastError();
1872 if (errno
== EINTR
|| errno
== EAGAIN
)
1875 http
->error
= errno
;
1878 else if (bytes
== 0)
1880 http
->error
= EPIPE
;
1889 * 'httpPost()' - Send a POST request to the server.
1892 int /* O - Status of call (0 = success) */
1893 httpPost(http_t
*http
, /* I - HTTP connection */
1894 const char *uri
) /* I - URI for post */
1896 return (http_send(http
, HTTP_STATE_POST
, uri
));
1901 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1906 int /* O - Number of bytes written */
1907 httpPrintf(http_t
*http
, /* I - HTTP connection */
1908 const char *format
, /* I - printf-style format string */
1909 ...) /* I - Additional args as needed */
1911 int bytes
; /* Number of bytes to write */
1912 char buf
[16384]; /* Buffer for formatted string */
1913 va_list ap
; /* Variable argument pointer */
1916 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1918 va_start(ap
, format
);
1919 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1922 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
1924 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
1925 return (httpWrite2(http
, buf
, bytes
));
1930 DEBUG_puts("4httpPrintf: flushing existing data...");
1932 if (httpFlushWrite(http
) < 0)
1936 return (http_write(http
, buf
, bytes
));
1942 * 'httpPut()' - Send a PUT request to the server.
1945 int /* O - Status of call (0 = success) */
1946 httpPut(http_t
*http
, /* I - HTTP connection */
1947 const char *uri
) /* I - URI to put */
1949 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1950 return (http_send(http
, HTTP_STATE_PUT
, uri
));
1955 * 'httpRead()' - Read data from a HTTP connection.
1957 * This function is deprecated. Use the httpRead2() function which can
1958 * read more than 2GB of data.
1963 int /* O - Number of bytes read */
1964 httpRead(http_t
*http
, /* I - HTTP connection */
1965 char *buffer
, /* I - Buffer for data */
1966 int length
) /* I - Maximum number of bytes */
1968 return ((int)httpRead2(http
, buffer
, length
));
1973 * 'httpRead2()' - Read data from a HTTP connection.
1975 * @since CUPS 1.2/OS X 10.5@
1978 ssize_t
/* O - Number of bytes read */
1979 httpRead2(http_t
*http
, /* I - HTTP connection */
1980 char *buffer
, /* I - Buffer for data */
1981 size_t length
) /* I - Maximum number of bytes */
1983 ssize_t bytes
; /* Bytes read */
1987 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
1988 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
1989 http
, buffer
, CUPS_LLCAST length
,
1991 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
1993 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
1994 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
1995 http
, buffer
, CUPS_LLCAST length
,
1996 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
1997 #endif /* HAVE_LIBZ */
1999 if (http
== NULL
|| buffer
== NULL
)
2002 http
->activity
= time(NULL
);
2013 if (http
->stream
.avail_in
> 0)
2015 int zerr
; /* Decompressor error */
2017 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2018 (int)http
->stream
.avail_in
, (int)length
));
2020 http
->stream
.next_out
= (Bytef
*)buffer
;
2021 http
->stream
.avail_out
= length
;
2023 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2025 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2027 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2028 http
->stream
.avail_in
);
2035 bytes
= length
- http
->stream
.avail_out
;
2037 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2038 http
->stream
.avail_in
, http
->stream
.avail_out
,
2046 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2047 /* Additional bytes for buffer */
2051 if (http
->stream
.avail_in
> 0 &&
2052 http
->stream
.next_in
> http
->dbuffer
)
2053 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2055 http
->stream
.next_in
= http
->dbuffer
;
2057 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2058 "decompression buffer.", (int)buflen
));
2060 if (http
->data_remaining
> 0)
2062 if (buflen
> http
->data_remaining
)
2063 buflen
= http
->data_remaining
;
2065 bytes
= http_read_buffered(http
,
2066 (char *)http
->dbuffer
+
2067 http
->stream
.avail_in
, buflen
);
2069 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2070 bytes
= http_read_chunk(http
,
2071 (char *)http
->dbuffer
+
2072 http
->stream
.avail_in
, buflen
);
2078 else if (bytes
== 0)
2081 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2082 "decompression buffer.", CUPS_LLCAST bytes
));
2084 http
->data_remaining
-= bytes
;
2085 http
->stream
.avail_in
+= bytes
;
2087 if (http
->data_remaining
<= 0 &&
2088 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2091 * Read the trailing blank line now...
2094 char len
[32]; /* Length string */
2096 httpGets(len
, sizeof(len
), http
);
2108 #endif /* HAVE_LIBZ */
2109 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2111 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2113 http
->data_remaining
-= bytes
;
2115 if (http
->data_remaining
<= 0)
2118 * Read the trailing blank line now...
2121 char len
[32]; /* Length string */
2123 httpGets(len
, sizeof(len
), http
);
2127 else if (http
->data_remaining
<= 0)
2130 * No more data to read...
2137 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2140 if (length
> (size_t)http
->data_remaining
)
2141 length
= (size_t)http
->data_remaining
;
2143 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2145 http
->data_remaining
-= bytes
;
2147 if (http
->data_remaining
<= 0 &&
2148 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2151 * Read the trailing blank line now...
2154 char len
[32]; /* Length string */
2156 httpGets(len
, sizeof(len
), http
);
2163 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2164 #endif /* HAVE_LIBZ */
2165 ((http
->data_remaining
<= 0 &&
2166 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2167 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2171 http_content_coding_finish(http
);
2172 #endif /* HAVE_LIBZ */
2174 if (http
->state
== HTTP_STATE_POST_RECV
)
2176 else if (http
->state
== HTTP_STATE_GET_SEND
||
2177 http
->state
== HTTP_STATE_POST_SEND
)
2178 http
->state
= HTTP_STATE_WAITING
;
2180 http
->state
= HTTP_STATE_STATUS
;
2182 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2183 httpStateString(http
->state
)));
2191 * 'httpReadRequest()' - Read a HTTP request from a connection.
2193 * @since CUPS 1.7/OS X 10.9@
2196 http_state_t
/* O - New state of connection */
2197 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2198 char *uri
, /* I - URI buffer */
2199 size_t urilen
) /* I - Size of URI buffer */
2201 char line
[4096], /* HTTP request line */
2202 *req_method
, /* HTTP request method */
2203 *req_uri
, /* HTTP request URI */
2204 *req_version
; /* HTTP request version number string */
2208 * Range check input...
2211 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2212 http
, uri
, CUPS_LLCAST urilen
));
2217 if (!http
|| !uri
|| urilen
< 1)
2219 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2220 return (HTTP_STATE_ERROR
);
2222 else if (http
->state
!= HTTP_STATE_WAITING
)
2224 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2225 httpStateString(http
->state
)));
2226 return (HTTP_STATE_ERROR
);
2233 httpClearFields(http
);
2235 http
->activity
= time(NULL
);
2236 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2237 http
->data_remaining
= 0;
2238 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2239 http
->status
= HTTP_STATUS_OK
;
2240 http
->version
= HTTP_VERSION_1_1
;
2243 * Read a line from the socket...
2246 if (!httpGets(line
, sizeof(line
), http
))
2248 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2249 return (HTTP_STATE_ERROR
);
2254 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2255 return (HTTP_STATE_WAITING
);
2258 DEBUG_printf(("1httpReadRequest: %s", line
));
2267 while (*req_uri
&& !isspace(*req_uri
& 255))
2272 DEBUG_puts("1httpReadRequest: No request URI.");
2273 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request URI."), 1);
2274 return (HTTP_STATE_ERROR
);
2279 while (*req_uri
&& isspace(*req_uri
& 255))
2282 req_version
= req_uri
;
2284 while (*req_version
&& !isspace(*req_version
& 255))
2289 DEBUG_puts("1httpReadRequest: No request protocol version.");
2290 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request protocol version."), 1);
2291 return (HTTP_STATE_ERROR
);
2294 *req_version
++ = '\0';
2296 while (*req_version
&& isspace(*req_version
& 255))
2303 if (!strcmp(req_method
, "OPTIONS"))
2304 http
->state
= HTTP_STATE_OPTIONS
;
2305 else if (!strcmp(req_method
, "GET"))
2306 http
->state
= HTTP_STATE_GET
;
2307 else if (!strcmp(req_method
, "HEAD"))
2308 http
->state
= HTTP_STATE_HEAD
;
2309 else if (!strcmp(req_method
, "POST"))
2310 http
->state
= HTTP_STATE_POST
;
2311 else if (!strcmp(req_method
, "PUT"))
2312 http
->state
= HTTP_STATE_PUT
;
2313 else if (!strcmp(req_method
, "DELETE"))
2314 http
->state
= HTTP_STATE_DELETE
;
2315 else if (!strcmp(req_method
, "TRACE"))
2316 http
->state
= HTTP_STATE_TRACE
;
2317 else if (!strcmp(req_method
, "CONNECT"))
2318 http
->state
= HTTP_STATE_CONNECT
;
2321 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2322 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request method."), 1);
2323 return (HTTP_STATE_UNKNOWN_METHOD
);
2326 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2327 httpStateString(http
->state
)));
2329 if (!strcmp(req_version
, "HTTP/1.0"))
2331 http
->version
= HTTP_VERSION_1_0
;
2332 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2334 else if (!strcmp(req_version
, "HTTP/1.1"))
2336 http
->version
= HTTP_VERSION_1_1
;
2337 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2341 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2342 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request version."), 1);
2343 return (HTTP_STATE_UNKNOWN_VERSION
);
2346 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2347 strlcpy(uri
, req_uri
, urilen
);
2349 return (http
->state
);
2354 * 'httpReconnect()' - Reconnect to a HTTP server.
2356 * This function is deprecated. Please use the @link httpReconnect2@ function
2362 int /* O - 0 on success, non-zero on failure */
2363 httpReconnect(http_t
*http
) /* I - HTTP connection */
2365 DEBUG_printf(("httpReconnect(http=%p)", http
));
2367 return (httpReconnect2(http
, 30000, NULL
));
2372 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2376 int /* O - 0 on success, non-zero on failure */
2377 httpReconnect2(http_t
*http
, /* I - HTTP connection */
2378 int msec
, /* I - Timeout in milliseconds */
2379 int *cancel
) /* I - Pointer to "cancel" variable */
2381 http_addrlist_t
*addr
; /* Connected address */
2383 http_addrlist_t
*current
; /* Current address */
2384 char temp
[256]; /* Temporary address string */
2388 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2393 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2400 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2401 http_tls_stop(http
);
2403 #endif /* HAVE_SSL */
2406 * Close any previously open socket...
2411 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2413 httpAddrClose(NULL
, http
->fd
);
2419 * Reset all state (except fields, which may be reused)...
2422 http
->state
= HTTP_STATE_WAITING
;
2423 http
->version
= HTTP_VERSION_1_1
;
2424 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2425 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2426 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2427 http
->_data_remaining
= 0;
2429 http
->data_remaining
= 0;
2430 http
->hostaddr
= NULL
;
2434 * Connect to the server...
2438 for (current
= http
->addrlist
; current
; current
= current
->next
)
2439 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2440 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2441 httpAddrPort(&(current
->addr
))));
2444 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2448 * Unable to connect...
2452 http
->error
= WSAGetLastError();
2454 http
->error
= errno
;
2456 http
->status
= HTTP_STATUS_ERROR
;
2458 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2459 strerror(http
->error
)));
2464 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2466 if (http
->timeout_value
> 0)
2467 http_set_timeout(http
->fd
, http
->timeout_value
);
2469 http
->hostaddr
= &(addr
->addr
);
2473 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2476 * Always do encryption via SSL.
2479 if (http_tls_start(http
) != 0)
2481 httpAddrClose(NULL
, http
->fd
);
2486 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2487 return (http_tls_upgrade(http
));
2488 #endif /* HAVE_SSL */
2490 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2491 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2492 httpAddrPort(http
->hostaddr
)));
2499 * 'httpSetAuthString()' - Set the current authorization string.
2501 * This function just stores a copy of the current authorization string in
2502 * the HTTP connection object. You must still call httpSetField() to set
2503 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2504 * httpHead(), httpOptions(), httpPost, or httpPut().
2506 * @since CUPS 1.3/OS X 10.5@
2510 httpSetAuthString(http_t
*http
, /* I - HTTP connection */
2511 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2512 const char *data
) /* I - Auth data (NULL for none) */
2515 * Range check input...
2521 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2522 free(http
->authstring
);
2524 http
->authstring
= http
->_authstring
;
2529 * Set the current authorization string...
2532 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2535 if (len
> (int)sizeof(http
->_authstring
))
2537 if ((temp
= malloc(len
)) == NULL
)
2538 len
= sizeof(http
->_authstring
);
2540 http
->authstring
= temp
;
2544 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2546 strlcpy(http
->authstring
, scheme
, len
);
2551 * Clear the current authorization string...
2554 http
->_authstring
[0] = '\0';
2560 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2563 * @since CUPS 1.5/OS X 10.7@
2566 int /* O - Status of call (0 = success) */
2567 httpSetCredentials(http_t
*http
, /* I - HTTP connection */
2568 cups_array_t
*credentials
) /* I - Array of credentials */
2570 if (!http
|| cupsArrayCount(credentials
) < 1)
2573 _httpFreeCredentials(http
->tls_credentials
);
2575 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2577 return (http
->tls_credentials
? 0 : -1);
2582 * 'httpSetCookie()' - Set the cookie value(s).
2584 * @since CUPS 1.1.19/OS X 10.3@
2588 httpSetCookie(http_t
*http
, /* I - Connection */
2589 const char *cookie
) /* I - Cookie string */
2598 http
->cookie
= strdup(cookie
);
2600 http
->cookie
= NULL
;
2605 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2607 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2608 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2610 * @since CUPS 1.7/OS X 10.9@
2614 httpSetDefaultField(http_t
*http
, /* I - HTTP connection */
2615 http_field_t field
, /* I - Field index */
2616 const char *value
)/* I - Value */
2618 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2619 http
, field
, http_fields
[field
], value
));
2626 case HTTP_FIELD_ACCEPT_ENCODING
:
2627 if (http
->default_accept_encoding
)
2628 _cupsStrFree(http
->default_accept_encoding
);
2630 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2633 case HTTP_FIELD_SERVER
:
2634 if (http
->default_server
)
2635 _cupsStrFree(http
->default_server
);
2637 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2640 case HTTP_FIELD_USER_AGENT
:
2641 if (http
->default_user_agent
)
2642 _cupsStrFree(http
->default_user_agent
);
2644 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2648 DEBUG_puts("1httpSetDefaultField: Ignored.");
2655 * 'httpSetExpect()' - Set the Expect: header in a request.
2657 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2660 * @since CUPS 1.2/OS X 10.5@
2664 httpSetExpect(http_t
*http
, /* I - HTTP connection */
2665 http_status_t expect
) /* I - HTTP status to expect
2666 (@code HTTP_STATUS_CONTINUE@) */
2668 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2671 http
->expect
= expect
;
2676 * 'httpSetField()' - Set the value of an HTTP header.
2680 httpSetField(http_t
*http
, /* I - HTTP connection */
2681 http_field_t field
, /* I - Field index */
2682 const char *value
) /* I - Value */
2684 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2685 field
, http_fields
[field
], value
));
2688 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2689 field
>= HTTP_FIELD_MAX
||
2695 case HTTP_FIELD_ACCEPT_ENCODING
:
2696 if (http
->accept_encoding
)
2697 _cupsStrFree(http
->accept_encoding
);
2699 http
->accept_encoding
= _cupsStrAlloc(value
);
2702 case HTTP_FIELD_ALLOW
:
2704 _cupsStrFree(http
->allow
);
2706 http
->allow
= _cupsStrAlloc(value
);
2709 case HTTP_FIELD_SERVER
:
2711 _cupsStrFree(http
->server
);
2713 http
->server
= _cupsStrAlloc(value
);
2717 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2721 if (field
== HTTP_FIELD_AUTHORIZATION
)
2724 * Special case for Authorization: as its contents can be
2725 * longer than HTTP_MAX_VALUE
2728 if (http
->field_authorization
)
2729 free(http
->field_authorization
);
2731 http
->field_authorization
= strdup(value
);
2733 else if (field
== HTTP_FIELD_HOST
)
2736 * Special-case for Host: as we don't want a trailing "." on the hostname and
2737 * need to bracket IPv6 numeric addresses.
2740 char *ptr
= strchr(value
, ':');
2742 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2745 * Bracket IPv6 numeric addresses...
2747 * This is slightly inefficient (basically copying twice), but is an edge
2748 * case and not worth optimizing...
2751 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2752 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2757 * Check for a trailing dot on the hostname...
2760 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2764 ptr
+= strlen(ptr
) - 1;
2772 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
2773 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
2775 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
2776 http_content_coding_start(http
, value
);
2778 #endif /* HAVE_LIBZ */
2783 * 'httpSetKeepAlive()' - Set the current Keep-Alive state of a connection.
2790 http_t
*http
, /* I - HTTP connection */
2791 http_keepalive_t keep_alive
) /* I - New Keep-Alive value */
2794 http
->keep_alive
= keep_alive
;
2799 * 'httpSetLength()' - Set the content-length and content-encoding.
2801 * @since CUPS 1.2/OS X 10.5@
2805 httpSetLength(http_t
*http
, /* I - HTTP connection */
2806 size_t length
) /* I - Length (0 for chunked) */
2808 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
2809 CUPS_LLCAST length
));
2816 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
2818 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2822 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2823 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2824 CUPS_LLFMT
, CUPS_LLCAST length
);
2830 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2832 * The optional timeout callback receives both the HTTP connection and a user
2833 * data pointer and must return 1 to continue or 0 to error (time) out.
2835 * @since CUPS 1.5/OS X 10.7@
2840 http_t
*http
, /* I - HTTP connection */
2841 double timeout
, /* I - Number of seconds for timeout,
2842 must be greater than 0 */
2843 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2844 void *user_data
) /* I - User data pointer */
2846 if (!http
|| timeout
<= 0.0)
2849 http
->timeout_cb
= cb
;
2850 http
->timeout_data
= user_data
;
2851 http
->timeout_value
= timeout
;
2854 http_set_timeout(http
->fd
, timeout
);
2856 http_set_wait(http
);
2861 * 'httpShutdown()' - Shutdown one side of an HTTP connection.
2867 httpShutdown(http_t
*http
) /* I - HTTP connection */
2869 if (!http
|| http
->fd
< 0)
2873 http_tls_stop(http
);
2875 shutdown(http
->fd
, SHUT_RD
);
2880 * 'httpTrace()' - Send an TRACE request to the server.
2883 int /* O - Status of call (0 = success) */
2884 httpTrace(http_t
*http
, /* I - HTTP connection */
2885 const char *uri
) /* I - URI for trace */
2887 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
2892 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2894 * Note: Unlike httpUpdate(), this function does not flush pending write data
2895 * and only retrieves a single status line from the HTTP connection.
2898 int /* O - 1 to continue, 0 to stop */
2899 _httpUpdate(http_t
*http
, /* I - HTTP connection */
2900 http_status_t
*status
) /* O - Current HTTP status */
2902 char line
[32768], /* Line from connection... */
2903 *value
; /* Pointer to value on line */
2904 http_field_t field
; /* Field index */
2905 int major
, minor
; /* HTTP version numbers */
2908 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2909 httpStateString(http
->state
)));
2912 * Grab a single line from the connection...
2915 if (!httpGets(line
, sizeof(line
), http
))
2917 *status
= HTTP_STATUS_ERROR
;
2921 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2923 if (line
[0] == '\0')
2926 * Blank line means the start of the data section (if any). Return
2927 * the result code, too...
2929 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
2930 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
2934 if (http
->status
== HTTP_STATUS_CONTINUE
)
2936 *status
= http
->status
;
2940 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
2941 http
->digest_tries
= 0;
2944 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
2946 if (http_tls_start(http
) != 0)
2948 httpAddrClose(NULL
, http
->fd
);
2950 *status
= http
->status
= HTTP_STATUS_ERROR
;
2954 *status
= HTTP_STATUS_CONTINUE
;
2957 #endif /* HAVE_SSL */
2959 if (http_set_length(http
) < 0)
2961 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
2962 http
->error
= EINVAL
;
2963 http
->status
= *status
= HTTP_STATUS_ERROR
;
2967 switch (http
->state
)
2969 case HTTP_STATE_GET
:
2970 case HTTP_STATE_POST
:
2971 case HTTP_STATE_POST_RECV
:
2972 case HTTP_STATE_PUT
:
2975 DEBUG_printf(("1_httpUpdate: Set state to %s.",
2976 httpStateString(http
->state
)));
2978 case HTTP_STATE_POST_SEND
:
2979 case HTTP_STATE_HEAD
:
2983 http
->state
= HTTP_STATE_WAITING
;
2985 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
2990 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
2991 http_content_coding_start(http
,
2992 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
2993 #endif /* HAVE_LIBZ */
2995 *status
= http
->status
;
2998 else if (!strncmp(line
, "HTTP/", 5))
3001 * Got the beginning of a response...
3004 int intstatus
; /* Status value as an integer */
3006 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
3008 *status
= http
->status
= HTTP_STATUS_ERROR
;
3012 httpClearFields(http
);
3014 http
->version
= (http_version_t
)(major
* 100 + minor
);
3015 *status
= http
->status
= (http_status_t
)intstatus
;
3017 else if ((value
= strchr(line
, ':')) != NULL
)
3024 while (_cups_isspace(*value
))
3027 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3030 * Be tolerants of servers that send unknown attribute fields...
3033 if (!_cups_strcasecmp(line
, "expect"))
3036 * "Expect: 100-continue" or similar...
3039 http
->expect
= (http_status_t
)atoi(value
);
3041 else if (!_cups_strcasecmp(line
, "cookie"))
3044 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3047 httpSetCookie(http
, value
);
3049 else if ((field
= httpFieldValue(line
)) != HTTP_FIELD_UNKNOWN
)
3050 httpSetField(http
, field
, value
);
3053 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3058 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3059 http
->error
= EINVAL
;
3060 http
->status
= *status
= HTTP_STATUS_ERROR
;
3069 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3072 http_status_t
/* O - HTTP status */
3073 httpUpdate(http_t
*http
) /* I - HTTP connection */
3075 http_status_t status
; /* Request status */
3078 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3079 httpStateString(http
->state
)));
3082 * Flush pending data, if any...
3087 DEBUG_puts("2httpUpdate: flushing buffer...");
3089 if (httpFlushWrite(http
) < 0)
3090 return (HTTP_STATUS_ERROR
);
3094 * If we haven't issued any commands, then there is nothing to "update"...
3097 if (http
->state
== HTTP_STATE_WAITING
)
3098 return (HTTP_STATUS_CONTINUE
);
3101 * Grab all of the lines we can from the connection...
3104 while (_httpUpdate(http
, &status
));
3107 * See if there was an error...
3110 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3112 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3113 return (http
->status
);
3118 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3119 strerror(http
->error
)));
3120 http
->status
= HTTP_STATUS_ERROR
;
3121 return (HTTP_STATUS_ERROR
);
3125 * Return the current status...
3133 * '_httpWait()' - Wait for data available on a connection (no flush).
3136 int /* O - 1 if data is available, 0 otherwise */
3137 _httpWait(http_t
*http
, /* I - HTTP connection */
3138 int msec
, /* I - Milliseconds to wait */
3139 int usessl
) /* I - Use SSL context? */
3142 struct pollfd pfd
; /* Polled file descriptor */
3144 fd_set input_set
; /* select() input set */
3145 struct timeval timeout
; /* Timeout */
3146 #endif /* HAVE_POLL */
3147 int nfds
; /* Result from select()/poll() */
3150 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3154 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3159 * Check the SSL/TLS buffers for data first...
3163 if (http_tls_pending(http
))
3165 DEBUG_puts("5_httpWait: Return 1 since there is pending TLS data.");
3168 #endif /* HAVE_SSL */
3171 * Then try doing a select() or poll() to poll the socket...
3176 pfd
.events
= POLLIN
;
3180 nfds
= poll(&pfd
, 1, msec
);
3182 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3187 FD_ZERO(&input_set
);
3188 FD_SET(http
->fd
, &input_set
);
3190 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3194 timeout
.tv_sec
= msec
/ 1000;
3195 timeout
.tv_usec
= (msec
% 1000) * 1000;
3197 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3200 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3202 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3205 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3206 WSAGetLastError() == WSAEWOULDBLOCK
));
3208 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3210 #endif /* HAVE_POLL */
3212 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3220 * 'httpWait()' - Wait for data available on a connection.
3222 * @since CUPS 1.1.19/OS X 10.3@
3225 int /* O - 1 if data is available, 0 otherwise */
3226 httpWait(http_t
*http
, /* I - HTTP connection */
3227 int msec
) /* I - Milliseconds to wait */
3230 * First see if there is data in the buffer...
3233 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3240 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3245 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3247 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3250 #endif /* HAVE_LIBZ */
3253 * Flush pending data, if any...
3258 DEBUG_puts("3httpWait: Flushing write buffer.");
3260 if (httpFlushWrite(http
) < 0)
3265 * If not, check the SSL/TLS buffers and do a select() on the connection...
3268 return (_httpWait(http
, msec
, 1));
3273 * 'httpWrite()' - Write data to a HTTP connection.
3275 * This function is deprecated. Use the httpWrite2() function which can
3276 * write more than 2GB of data.
3281 int /* O - Number of bytes written */
3282 httpWrite(http_t
*http
, /* I - HTTP connection */
3283 const char *buffer
, /* I - Buffer for data */
3284 int length
) /* I - Number of bytes to write */
3286 return ((int)httpWrite2(http
, buffer
, length
));
3291 * 'httpWrite2()' - Write data to a HTTP connection.
3293 * @since CUPS 1.2/OS X 10.5@
3296 ssize_t
/* O - Number of bytes written */
3297 httpWrite2(http_t
*http
, /* I - HTTP connection */
3298 const char *buffer
, /* I - Buffer for data */
3299 size_t length
) /* I - Number of bytes to write */
3301 ssize_t bytes
; /* Bytes written */
3304 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3305 buffer
, CUPS_LLCAST length
));
3308 * Range check input...
3311 if (!http
|| !buffer
)
3313 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3318 * Mark activity on the connection...
3321 http
->activity
= time(NULL
);
3324 * Buffer small writes for better performance...
3330 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3334 http_content_coding_finish(http
);
3339 http
->stream
.next_in
= (Bytef
*)buffer
;
3340 http
->stream
.avail_in
= length
;
3341 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3342 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3344 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3346 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3348 if (http
->stream
.avail_out
== 0)
3350 if (httpFlushWrite(http
) < 0)
3352 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3356 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3357 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3361 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3366 #endif /* HAVE_LIBZ */
3369 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3371 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3372 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3374 httpFlushWrite(http
);
3377 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3378 length
< sizeof(http
->wbuffer
))
3381 * Write to buffer...
3384 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3385 CUPS_LLCAST length
));
3387 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3388 http
->wused
+= (int)length
;
3389 bytes
= (ssize_t
)length
;
3394 * Otherwise write the data directly...
3397 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3398 CUPS_LLCAST length
));
3400 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3401 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3403 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3405 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3406 CUPS_LLCAST bytes
));
3409 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3410 http
->data_remaining
-= bytes
;
3416 * Handle end-of-request processing...
3419 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3420 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3423 * Finished with the transfer; unless we are sending POST or PUT
3429 http_content_coding_finish(http
);
3430 #endif /* HAVE_LIBZ */
3434 if (httpFlushWrite(http
) < 0)
3438 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3441 * Send a 0-length chunk at the end of the request...
3444 http_write(http
, "0\r\n\r\n", 5);
3447 * Reset the data state...
3450 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3451 http
->data_remaining
= 0;
3454 if (http
->state
== HTTP_STATE_POST_RECV
)
3456 else if (http
->state
== HTTP_STATE_POST_SEND
)
3457 http
->state
= HTTP_STATE_WAITING
;
3459 http
->state
= HTTP_STATE_STATUS
;
3461 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3462 httpStateString(http
->state
)));
3465 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3472 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3474 * @since CUPS 1.7/OS X 10.9@
3477 int /* O - 0 on success, -1 on error */
3478 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3479 http_status_t status
) /* I - Status code */
3481 http_encoding_t old_encoding
; /* Old data_encoding value */
3482 off_t old_remaining
; /* Old data_remaining value */
3486 * Range check input...
3489 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3491 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3493 DEBUG_puts("1httpWriteResponse: Bad input.");
3498 * Set the various standard fields if they aren't already...
3501 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3502 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3504 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3506 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
3507 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3510 if (http
->version
== HTTP_VERSION_1_1
)
3512 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3514 if (http
->keep_alive
)
3515 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3517 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3520 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3521 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3525 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
||
3526 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
3528 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3529 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3531 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3532 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3534 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
3535 httpSetField(http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
3537 #endif /* HAVE_SSL */
3540 httpSetField(http
, HTTP_FIELD_SERVER
,
3541 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3544 * Set the Accept-Encoding field if it isn't already...
3547 if (!http
->accept_encoding
)
3548 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3549 http
->default_accept_encoding
? http
->default_accept_encoding
:
3551 "gzip, deflate, identity");
3554 #endif /* HAVE_LIBZ */
3557 * Send the response header...
3560 old_encoding
= http
->data_encoding
;
3561 old_remaining
= http
->data_remaining
;
3562 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3564 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3565 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3567 http
->status
= HTTP_STATUS_ERROR
;
3571 if (status
!= HTTP_STATUS_CONTINUE
)
3574 * 100 Continue doesn't have the rest of the response headers...
3577 int i
; /* Looping var */
3578 const char *value
; /* Field value */
3580 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3582 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3584 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3586 http
->status
= HTTP_STATUS_ERROR
;
3594 if (httpPrintf(http
, "Set-Cookie: %s path=/ httponly%s\r\n",
3595 http
->cookie
, http
->tls
? " secure" : "") < 1)
3597 http
->status
= HTTP_STATUS_ERROR
;
3603 if (httpWrite2(http
, "\r\n", 2) < 2)
3605 http
->status
= HTTP_STATUS_ERROR
;
3609 if (httpFlushWrite(http
) < 0)
3611 http
->status
= HTTP_STATUS_ERROR
;
3615 if (status
== HTTP_STATUS_CONTINUE
||
3616 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
3619 * Restore the old data_encoding and data_length values...
3622 http
->data_encoding
= old_encoding
;
3623 http
->data_remaining
= old_remaining
;
3625 if (old_remaining
<= INT_MAX
)
3626 http
->_data_remaining
= (int)old_remaining
;
3628 http
->_data_remaining
= INT_MAX
;
3630 else if (http
->state
== HTTP_STATE_OPTIONS
||
3631 http
->state
== HTTP_STATE_HEAD
||
3632 http
->state
== HTTP_STATE_PUT
||
3633 http
->state
== HTTP_STATE_TRACE
||
3634 http
->state
== HTTP_STATE_CONNECT
||
3635 http
->state
== HTTP_STATE_STATUS
)
3637 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3638 "was %s.", httpStateString(http
->state
)));
3639 http
->state
= HTTP_STATE_WAITING
;
3644 * Force data_encoding and data_length to be set according to the response
3648 http_set_length(http
);
3652 * Then start any content encoding...
3655 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
3656 http_content_coding_start(http
,
3657 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3658 #endif /* HAVE_LIBZ */
3667 * 'http_content_coding_finish()' - Finish doing any content encoding.
3671 http_content_coding_finish(
3672 http_t
*http
) /* I - HTTP connection */
3674 int zerr
; /* Compression status */
3677 switch (http
->coding
)
3679 case _HTTP_CODING_DEFLATE
:
3680 case _HTTP_CODING_GZIP
:
3683 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3684 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3686 zerr
= deflate(&(http
->stream
), Z_FINISH
);
3688 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3689 if (http
->wused
== sizeof(http
->wbuffer
))
3690 httpFlushWrite(http
);
3692 while (zerr
== Z_OK
);
3694 deflateEnd(&(http
->stream
));
3697 httpFlushWrite(http
);
3700 case _HTTP_CODING_INFLATE
:
3701 case _HTTP_CODING_GUNZIP
:
3702 inflateEnd(&(http
->stream
));
3703 free(http
->dbuffer
);
3704 http
->dbuffer
= NULL
;
3711 http
->coding
= _HTTP_CODING_IDENTITY
;
3716 * 'http_content_coding_start()' - Start doing content encoding.
3720 http_content_coding_start(
3721 http_t
*http
, /* I - HTTP connection */
3722 const char *value
) /* I - Value of Content-Encoding */
3724 int zerr
; /* Error/status */
3725 _http_coding_t coding
; /* Content coding value */
3728 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
3731 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
3733 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
3737 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
3739 if (http
->state
== HTTP_STATE_GET_SEND
||
3740 http
->state
== HTTP_STATE_POST_SEND
)
3741 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
3742 _HTTP_CODING_GUNZIP
;
3743 else if (http
->state
== HTTP_STATE_POST_RECV
||
3744 http
->state
== HTTP_STATE_PUT_RECV
)
3745 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
3746 _HTTP_CODING_GUNZIP
;
3749 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3753 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
3755 if (http
->state
== HTTP_STATE_GET_SEND
||
3756 http
->state
== HTTP_STATE_POST_SEND
)
3757 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
3758 _HTTP_CODING_INFLATE
;
3759 else if (http
->state
== HTTP_STATE_POST_RECV
||
3760 http
->state
== HTTP_STATE_PUT_RECV
)
3761 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
3762 _HTTP_CODING_INFLATE
;
3765 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3771 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3775 memset(&(http
->stream
), 0, sizeof(http
->stream
));
3779 case _HTTP_CODING_DEFLATE
:
3780 case _HTTP_CODING_GZIP
:
3782 httpFlushWrite(http
);
3785 * Window size for compression is 11 bits - optimal based on PWG Raster
3786 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
3790 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
3792 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
3793 Z_DEFAULT_STRATEGY
)) < Z_OK
)
3795 http
->status
= HTTP_STATUS_ERROR
;
3796 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
3801 case _HTTP_CODING_INFLATE
:
3802 case _HTTP_CODING_GUNZIP
:
3803 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
3805 http
->status
= HTTP_STATUS_ERROR
;
3806 http
->error
= errno
;
3811 * Window size for decompression is up to 15 bits (maximum supported).
3812 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
3815 if ((zerr
= inflateInit2(&(http
->stream
),
3816 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
3819 free(http
->dbuffer
);
3820 http
->dbuffer
= NULL
;
3821 http
->status
= HTTP_STATUS_ERROR
;
3822 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
3826 http
->stream
.avail_in
= 0;
3827 http
->stream
.next_in
= http
->dbuffer
;
3834 http
->coding
= coding
;
3836 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
3839 #endif /* HAVE_LIBZ */
3843 * 'http_create()' - Create an unconnected HTTP connection.
3846 static http_t
* /* O - HTTP connection */
3848 const char *host
, /* I - Hostname */
3849 int port
, /* I - Port number */
3850 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
3851 int family
, /* I - Address family or AF_UNSPEC */
3852 http_encryption_t encryption
, /* I - Encryption to use */
3853 int blocking
, /* I - 1 for blocking mode */
3854 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
3856 http_t
*http
; /* New HTTP connection */
3857 char service
[255]; /* Service name */
3858 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
3861 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
3862 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
3863 family
, encryption
, blocking
, mode
));
3865 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
3871 * Lookup the host...
3876 myaddrlist
= httpAddrCopyList(addrlist
);
3880 snprintf(service
, sizeof(service
), "%d", port
);
3882 myaddrlist
= httpAddrGetList(host
, family
, service
);
3889 * Allocate memory for the structure...
3892 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
3894 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
3895 httpAddrFreeList(addrlist
);
3900 * Initialize the HTTP data...
3904 http
->activity
= time(NULL
);
3905 http
->addrlist
= myaddrlist
;
3906 http
->blocking
= blocking
;
3909 http
->gssctx
= GSS_C_NO_CONTEXT
;
3910 http
->gssname
= GSS_C_NO_NAME
;
3911 #endif /* HAVE_GSSAPI */
3912 http
->status
= HTTP_STATUS_CONTINUE
;
3913 http
->version
= HTTP_VERSION_1_1
;
3916 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
3918 if (port
== 443) /* Always use encryption for https */
3919 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
3921 http
->encryption
= encryption
;
3923 http_set_wait(http
);
3926 * Return the new structure...
3935 * 'http_debug_hex()' - Do a hex dump of a buffer.
3939 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3940 const char *buffer
, /* I - Buffer to dump */
3941 int bytes
) /* I - Bytes to dump */
3943 int i
, j
, /* Looping vars */
3944 ch
; /* Current character */
3945 char line
[255], /* Line buffer */
3946 *start
, /* Start of line after prefix */
3947 *ptr
; /* Pointer into line */
3950 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3953 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
3955 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3956 start
= line
+ strlen(line
);
3958 for (i
= 0; i
< bytes
; i
+= 16)
3960 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3961 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3965 memcpy(ptr
, " ", 3);
3970 memcpy(ptr
, " ", 3);
3973 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3975 ch
= buffer
[i
+ j
] & 255;
3977 if (ch
< ' ' || ch
>= 127)
3991 * 'http_read()' - Read a buffer from a HTTP connection.
3993 * This function does the low-level read from the socket, retrying and timing
3997 static ssize_t
/* O - Number of bytes read or -1 on error */
3998 http_read(http_t
*http
, /* I - HTTP connection */
3999 char *buffer
, /* I - Buffer */
4000 size_t length
) /* I - Maximum bytes to read */
4002 ssize_t bytes
; /* Bytes read */
4005 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4006 buffer
, CUPS_LLCAST length
));
4008 if (!http
->blocking
)
4010 while (!httpWait(http
, http
->wait_value
))
4012 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4015 DEBUG_puts("2http_read: Timeout.");
4020 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4026 bytes
= http_tls_read(http
, buffer
, length
);
4028 #endif /* HAVE_SSL */
4029 bytes
= recv(http
->fd
, buffer
, length
, 0);
4034 if (WSAGetLastError() != WSAEINTR
)
4036 http
->error
= WSAGetLastError();
4039 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4041 if (!http
->timeout_cb
||
4042 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4044 http
->error
= WSAEWOULDBLOCK
;
4049 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4051 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4053 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4055 http
->error
= errno
;
4058 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4060 http
->error
= errno
;
4064 else if (errno
!= EINTR
)
4066 http
->error
= errno
;
4074 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4075 CUPS_LLCAST bytes
));
4078 http_debug_hex("http_read", buffer
, (int)bytes
);
4084 if (WSAGetLastError() == WSAEINTR
)
4087 http
->error
= WSAGetLastError();
4089 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4092 http
->error
= errno
;
4095 else if (bytes
== 0)
4097 http
->error
= EPIPE
;
4106 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4108 * This function reads data from the HTTP buffer or from the socket, as needed.
4111 static ssize_t
/* O - Number of bytes read or -1 on error */
4112 http_read_buffered(http_t
*http
, /* I - HTTP connection */
4113 char *buffer
, /* I - Buffer */
4114 size_t length
) /* I - Maximum bytes to read */
4116 ssize_t bytes
; /* Bytes read */
4119 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4121 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4125 if (length
> (size_t)http
->used
)
4126 bytes
= (size_t)http
->used
;
4130 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4133 memcpy(buffer
, http
->buffer
, bytes
);
4134 http
->used
-= (int)bytes
;
4137 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4140 bytes
= http_read(http
, buffer
, length
);
4147 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4149 * This function reads and validates the chunk length, then does a buffered read
4150 * returning the number of bytes placed in the buffer.
4153 static ssize_t
/* O - Number of bytes read or -1 on error */
4154 http_read_chunk(http_t
*http
, /* I - HTTP connection */
4155 char *buffer
, /* I - Buffer */
4156 size_t length
) /* I - Maximum bytes to read */
4158 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4159 http
, buffer
, CUPS_LLCAST length
));
4161 if (http
->data_remaining
<= 0)
4163 char len
[32]; /* Length string */
4165 if (!httpGets(len
, sizeof(len
), http
))
4167 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4173 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4174 if (!httpGets(len
, sizeof(len
), http
))
4176 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4181 http
->data_remaining
= strtoll(len
, NULL
, 16);
4183 if (http
->data_remaining
< 0)
4185 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4186 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4190 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4191 len
, CUPS_LLCAST http
->data_remaining
));
4193 if (http
->data_remaining
== 0)
4196 * 0-length chunk, grab trailing blank line...
4199 httpGets(len
, sizeof(len
), http
);
4203 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4204 CUPS_LLCAST http
->data_remaining
));
4206 if (http
->data_remaining
<= 0)
4208 else if (length
> (size_t)http
->data_remaining
)
4209 length
= (size_t)http
->data_remaining
;
4211 return (http_read_buffered(http
, buffer
, length
));
4216 * 'http_send()' - Send a request with all fields and the trailing blank line.
4219 static int /* O - 0 on success, non-zero on error */
4220 http_send(http_t
*http
, /* I - HTTP connection */
4221 http_state_t request
, /* I - Request code */
4222 const char *uri
) /* I - URI */
4224 int i
; /* Looping var */
4225 char buf
[1024]; /* Encoded URI buffer */
4226 const char *value
; /* Field value */
4227 static const char * const codes
[] = /* Request code strings */
4247 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4248 http
, codes
[request
], uri
));
4250 if (http
== NULL
|| uri
== NULL
)
4254 * Set the User-Agent field if it isn't already...
4257 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4259 if (http
->default_user_agent
)
4260 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4262 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4266 * Set the Accept-Encoding field if it isn't already...
4269 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4270 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4271 http
->default_accept_encoding
);
4274 * Encode the URI as needed...
4277 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4280 * See if we had an error the last time around; if so, reconnect...
4283 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4284 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4286 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4287 http
->fd
, http
->status
, http
->tls_upgrade
));
4289 if (httpReconnect2(http
, 30000, NULL
))
4294 * Flush any written data that is pending...
4299 if (httpFlushWrite(http
) < 0)
4300 if (httpReconnect2(http
, 30000, NULL
))
4305 * Send the request header...
4308 http
->state
= request
;
4309 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4311 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4314 http
->status
= HTTP_STATUS_CONTINUE
;
4317 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4319 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4320 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4322 #endif /* HAVE_SSL */
4324 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4326 http
->status
= HTTP_STATUS_ERROR
;
4330 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4331 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4333 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
4335 if (i
== HTTP_FIELD_HOST
)
4337 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4338 httpAddrPort(http
->hostaddr
)) < 1)
4340 http
->status
= HTTP_STATUS_ERROR
;
4344 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4346 http
->status
= HTTP_STATUS_ERROR
;
4352 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4354 http
->status
= HTTP_STATUS_ERROR
;
4358 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
4359 http
->mode
, http
->state
));
4361 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4362 (http
->state
== HTTP_STATE_POST_RECV
||
4363 http
->state
== HTTP_STATE_PUT_RECV
))
4364 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4366 http
->status
= HTTP_STATUS_ERROR
;
4370 if (httpPrintf(http
, "\r\n") < 1)
4372 http
->status
= HTTP_STATUS_ERROR
;
4376 if (httpFlushWrite(http
) < 0)
4379 http_set_length(http
);
4380 httpClearFields(http
);
4383 * The Kerberos and AuthRef authentication strings can only be used once...
4386 if (http
->field_authorization
&& http
->authstring
&&
4387 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4388 !strncmp(http
->authstring
, "AuthRef", 7)))
4390 http
->_authstring
[0] = '\0';
4392 if (http
->authstring
!= http
->_authstring
)
4393 free(http
->authstring
);
4395 http
->authstring
= http
->_authstring
;
4403 * 'http_set_length()' - Set the data_encoding and data_remaining values.
4406 static off_t
/* O - Remainder or -1 on error */
4407 http_set_length(http_t
*http
) /* I - Connection */
4409 off_t remaining
; /* Remainder */
4412 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
4413 httpStateString(http
->state
)));
4415 if ((remaining
= httpGetLength2(http
)) >= 0)
4417 if (http
->mode
== _HTTP_MODE_SERVER
&&
4418 http
->state
!= HTTP_STATE_GET_SEND
&&
4419 http
->state
!= HTTP_STATE_PUT
&&
4420 http
->state
!= HTTP_STATE_POST
&&
4421 http
->state
!= HTTP_STATE_POST_SEND
)
4423 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
4427 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
4430 DEBUG_puts("1http_set_length: Setting data_encoding to "
4431 "HTTP_ENCODING_CHUNKED.");
4432 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
4436 DEBUG_puts("1http_set_length: Setting data_encoding to "
4437 "HTTP_ENCODING_LENGTH.");
4438 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4441 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
4442 CUPS_LLCAST remaining
));
4443 http
->data_remaining
= remaining
;
4445 if (remaining
<= INT_MAX
)
4446 http
->_data_remaining
= remaining
;
4448 http
->_data_remaining
= INT_MAX
;
4455 * 'http_set_timeout()' - Set the socket timeout values.
4459 http_set_timeout(int fd
, /* I - File descriptor */
4460 double timeout
) /* I - Timeout in seconds */
4463 DWORD tv
= (DWORD
)(timeout
* 1000);
4464 /* Timeout in milliseconds */
4466 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4467 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4470 struct timeval tv
; /* Timeout in secs and usecs */
4472 tv
.tv_sec
= (int)timeout
;
4473 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
4475 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4476 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4482 * 'http_set_wait()' - Set the default wait value for reads.
4486 http_set_wait(http_t
*http
) /* I - HTTP connection */
4490 http
->wait_value
= (int)(http
->timeout_value
* 1000);
4492 if (http
->wait_value
<= 0)
4493 http
->wait_value
= 60000;
4496 http
->wait_value
= 10000;
4502 * 'http_tls_upgrade()' - Force upgrade to TLS encryption.
4505 static int /* O - Status of connection */
4506 http_tls_upgrade(http_t
*http
) /* I - HTTP connection */
4508 int ret
; /* Return value */
4509 http_t myhttp
; /* Local copy of HTTP data */
4512 DEBUG_printf(("7http_tls_upgrade(%p)", http
));
4515 * Flush the connection to make sure any previous "Upgrade" message
4522 * Copy the HTTP data to a local variable so we can do the OPTIONS
4523 * request without interfering with the existing request data...
4526 memcpy(&myhttp
, http
, sizeof(myhttp
));
4529 * Send an OPTIONS request to the server, requiring SSL or TLS
4530 * encryption on the link...
4533 http
->tls_upgrade
= 1;
4534 http
->field_authorization
= NULL
; /* Don't free the auth string */
4536 httpClearFields(http
);
4537 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4538 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4540 if ((ret
= httpOptions(http
, "*")) == 0)
4543 * Wait for the secure connection...
4546 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
4550 * Restore the HTTP request data...
4553 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4554 http
->data_encoding
= myhttp
.data_encoding
;
4555 http
->data_remaining
= myhttp
.data_remaining
;
4556 http
->_data_remaining
= myhttp
._data_remaining
;
4557 http
->expect
= myhttp
.expect
;
4558 http
->field_authorization
= myhttp
.field_authorization
;
4559 http
->digest_tries
= myhttp
.digest_tries
;
4560 http
->tls_upgrade
= 0;
4563 * See if we actually went secure...
4569 * Server does not support HTTP upgrade...
4572 DEBUG_puts("8http_tls_upgrade: Server does not support HTTP upgrade!");
4574 httpAddrClose(NULL
, http
->fd
);
4583 #endif /* HAVE_SSL */
4587 * 'http_write()' - Write a buffer to a HTTP connection.
4590 static ssize_t
/* O - Number of bytes written */
4591 http_write(http_t
*http
, /* I - HTTP connection */
4592 const char *buffer
, /* I - Buffer for data */
4593 size_t length
) /* I - Number of bytes to write */
4595 ssize_t tbytes
, /* Total bytes sent */
4596 bytes
; /* Bytes sent */
4599 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4600 buffer
, CUPS_LLCAST length
));
4606 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
4608 if (http
->timeout_cb
)
4611 struct pollfd pfd
; /* Polled file descriptor */
4613 fd_set output_set
; /* Output ready for write? */
4614 struct timeval timeout
; /* Timeout value */
4615 #endif /* HAVE_POLL */
4616 int nfds
; /* Result from select()/poll() */
4622 pfd
.events
= POLLOUT
;
4624 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
4625 (errno
== EINTR
|| errno
== EAGAIN
))
4631 FD_ZERO(&output_set
);
4632 FD_SET(http
->fd
, &output_set
);
4634 timeout
.tv_sec
= http
->wait_value
/ 1000;
4635 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
4637 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
4640 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
4641 WSAGetLastError() == WSAEWOULDBLOCK
));
4643 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
4645 #endif /* HAVE_POLL */
4649 http
->error
= errno
;
4652 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4655 http
->error
= WSAEWOULDBLOCK
;
4657 http
->error
= EWOULDBLOCK
;
4667 bytes
= http_tls_write(http
, buffer
, length
);
4669 #endif /* HAVE_SSL */
4670 bytes
= send(http
->fd
, buffer
, length
, 0);
4672 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
4673 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
4678 if (WSAGetLastError() == WSAEINTR
)
4680 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4682 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4685 http
->error
= WSAGetLastError();
4687 else if (WSAGetLastError() != http
->error
&&
4688 WSAGetLastError() != WSAECONNRESET
)
4690 http
->error
= WSAGetLastError();
4697 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4699 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4701 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4704 http
->error
= errno
;
4706 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4708 http
->error
= errno
;
4713 DEBUG_printf(("3http_write: error writing data (%s).",
4714 strerror(http
->error
)));
4725 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4728 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
4735 * 'http_write_chunk()' - Write a chunked buffer.
4738 static ssize_t
/* O - Number bytes written */
4739 http_write_chunk(http_t
*http
, /* I - HTTP connection */
4740 const char *buffer
, /* I - Buffer to write */
4741 size_t length
) /* I - Length of buffer */
4743 char header
[16]; /* Chunk header */
4744 ssize_t bytes
; /* Bytes written */
4747 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4748 http
, buffer
, CUPS_LLCAST length
));
4751 * Write the chunk header, data, and trailer.
4754 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
4755 if (http_write(http
, header
, strlen(header
)) < 0)
4757 DEBUG_puts("8http_write_chunk: http_write of length failed.");
4761 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4763 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
4767 if (http_write(http
, "\r\n", 2) < 0)
4769 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");