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-gnutls.c"
80 # elif defined(HAVE_CDSASSL)
81 # include "tls-darwin.c"
83 # include "tls-sspi.c"
84 # endif /* HAVE_GNUTLS */
92 static const char * const http_fields
[] =
109 "If-Unmodified-since",
128 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
129 * specified listening socket.
131 * @since CUPS 1.7/OS X 10.9@
134 http_t
* /* O - HTTP connection or @code NULL@ */
135 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
136 int blocking
) /* I - 1 if the connection should be
137 blocking, 0 otherwise */
139 http_t
*http
; /* HTTP connection */
140 http_addrlist_t addrlist
; /* Dummy address list */
141 socklen_t addrlen
; /* Length of address */
142 int val
; /* Socket option value */
146 * Range check input...
153 * Create the client connection...
156 memset(&addrlist
, 0, sizeof(addrlist
));
158 if ((http
= http_create(NULL
, 0, &addrlist
, AF_UNSPEC
,
159 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
160 _HTTP_MODE_SERVER
)) == NULL
)
164 * Accept the client and get the remote address...
167 addrlen
= sizeof(http_addr_t
);
169 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
172 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
178 http
->hostaddr
= &(http
->addrlist
->addr
);
180 if (httpAddrLocalhost(http
->hostaddr
))
181 strlcpy(http
->hostname
, "localhost", sizeof(http
->hostname
));
183 httpAddrString(http
->hostaddr
, http
->hostname
, sizeof(http
->hostname
));
187 * Disable SIGPIPE for this socket.
191 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
192 #endif /* SO_NOSIGPIPE */
195 * Using TCP_NODELAY improves responsiveness, especially on systems
196 * with a slow loopback interface. Since we write large buffers
197 * when sending print files and requests, there shouldn't be any
198 * performance penalty for this...
202 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
206 * Close this socket when starting another process...
209 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
210 #endif /* FD_CLOEXEC */
217 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
219 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
221 * @since CUPS 1.5/OS X 10.7@
224 int /* O - 0 on success, -1 on error */
226 cups_array_t
*credentials
, /* I - Credentials array */
227 const void *data
, /* I - PEM-encoded X.509 data */
228 size_t datalen
) /* I - Length of data */
230 http_credential_t
*credential
; /* Credential data */
233 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
235 credential
->datalen
= datalen
;
237 if ((credential
->data
= malloc(datalen
)) != NULL
)
239 memcpy(credential
->data
, data
, datalen
);
240 cupsArrayAdd(credentials
, credential
);
252 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
256 httpBlocking(http_t
*http
, /* I - HTTP connection */
257 int b
) /* I - 1 = blocking, 0 = non-blocking */
268 * 'httpCheck()' - Check to see if there is a pending response from the server.
271 int /* O - 0 = no data, 1 = data available */
272 httpCheck(http_t
*http
) /* I - HTTP connection */
274 return (httpWait(http
, 0));
279 * 'httpClearCookie()' - Clear the cookie value(s).
281 * @since CUPS 1.1.19/OS X 10.3@
285 httpClearCookie(http_t
*http
) /* I - HTTP connection */
299 * 'httpClearFields()' - Clear HTTP request fields.
303 httpClearFields(http_t
*http
) /* I - HTTP connection */
305 DEBUG_printf(("httpClearFields(http=%p)", http
));
309 memset(http
->fields
, 0, sizeof(http
->fields
));
311 if (http
->mode
== _HTTP_MODE_CLIENT
)
313 if (http
->hostname
[0] == '/')
314 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
316 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
319 if (http
->field_authorization
)
321 free(http
->field_authorization
);
322 http
->field_authorization
= NULL
;
325 if (http
->accept_encoding
)
327 _cupsStrFree(http
->accept_encoding
);
328 http
->accept_encoding
= NULL
;
333 _cupsStrFree(http
->allow
);
339 _cupsStrFree(http
->server
);
343 http
->expect
= (http_status_t
)0;
349 * 'httpClose()' - Close an HTTP connection.
353 httpClose(http_t
*http
) /* I - HTTP connection */
356 OM_uint32 minor_status
; /* Minor status code */
357 #endif /* HAVE_GSSAPI */
360 DEBUG_printf(("httpClose(http=%p)", http
));
363 * Range check input...
370 * Close any open connection...
373 _httpDisconnect(http
);
376 * Free memory used...
379 httpAddrFreeList(http
->addrlist
);
385 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
386 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
388 if (http
->gssname
!= GSS_C_NO_NAME
)
389 gss_release_name(&minor_status
, &http
->gssname
);
390 #endif /* HAVE_GSSAPI */
392 #ifdef HAVE_AUTHORIZATION_H
394 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
395 #endif /* HAVE_AUTHORIZATION_H */
397 httpClearFields(http
);
399 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
400 free(http
->authstring
);
407 * 'httpConnect()' - Connect to a HTTP server.
409 * This function is deprecated - use @link httpConnect2@ instead.
414 http_t
* /* O - New HTTP connection */
415 httpConnect(const char *host
, /* I - Host to connect to */
416 int port
) /* I - Port number */
418 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
,
419 HTTP_ENCRYPTION_IF_REQUESTED
, 1, 30000, NULL
));
424 * 'httpConnect2()' - Connect to a HTTP server.
426 * @since CUPS 1.7/OS X 10.9@
429 http_t
* /* O - New HTTP connection */
431 const char *host
, /* I - Host to connect to */
432 int port
, /* I - Port number */
433 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
434 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
435 http_encryption_t encryption
, /* I - Type of encryption to use */
436 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
437 int msec
, /* I - Connection timeout in milliseconds, 0 means don't connect */
438 int *cancel
) /* I - Pointer to "cancel" variable */
440 http_t
*http
; /* New HTTP connection */
443 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
444 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
445 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
448 * Create the HTTP structure...
451 if ((http
= http_create(host
, port
, addrlist
, family
, encryption
, blocking
,
452 _HTTP_MODE_CLIENT
)) == NULL
)
456 * Optionally connect to the remote system...
459 if (msec
== 0 || !httpReconnect2(http
, msec
, cancel
))
463 * Could not connect to any known address - bail out!
473 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
475 * This function is now deprecated. Please use the @link httpConnect2@ function
481 http_t
* /* O - New HTTP connection */
483 const char *host
, /* I - Host to connect to */
484 int port
, /* I - Port number */
485 http_encryption_t encryption
) /* I - Type of encryption to use */
487 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
488 host
, port
, encryption
));
490 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
496 * 'httpDelete()' - Send a DELETE request to the server.
499 int /* O - Status of call (0 = success) */
500 httpDelete(http_t
*http
, /* I - HTTP connection */
501 const char *uri
) /* I - URI to delete */
503 return (http_send(http
, HTTP_STATE_DELETE
, uri
));
508 * '_httpDisconnect()' - Disconnect a HTTP connection.
512 _httpDisconnect(http_t
*http
) /* I - HTTP connection */
517 #endif /* HAVE_SSL */
519 httpAddrClose(NULL
, http
->fd
);
526 * 'httpEncryption()' - Set the required encryption on the link.
529 int /* O - -1 on error, 0 on success */
530 httpEncryption(http_t
*http
, /* I - HTTP connection */
531 http_encryption_t e
) /* I - New encryption preference */
533 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
539 if (http
->mode
== _HTTP_MODE_CLIENT
)
541 http
->encryption
= e
;
543 if ((http
->encryption
== HTTP_ENCRYPTION_ALWAYS
&& !http
->tls
) ||
544 (http
->encryption
== HTTP_ENCRYPTION_NEVER
&& http
->tls
))
545 return (httpReconnect2(http
, 30000, NULL
));
546 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
547 return (http_tls_upgrade(http
));
553 if (e
== HTTP_ENCRYPTION_NEVER
&& http
->tls
)
556 http
->encryption
= e
;
557 if (e
!= HTTP_ENCRYPTION_IF_REQUESTED
&& !http
->tls
)
558 return (http_tls_start(http
));
563 if (e
== HTTP_ENCRYPTION_ALWAYS
|| e
== HTTP_ENCRYPTION_REQUIRED
)
567 #endif /* HAVE_SSL */
572 * 'httpError()' - Get the last error on a connection.
575 int /* O - Error code (errno) value */
576 httpError(http_t
*http
) /* I - HTTP connection */
579 return (http
->error
);
586 * 'httpFieldValue()' - Return the HTTP field enumeration value for a field
590 http_field_t
/* O - Field index */
591 httpFieldValue(const char *name
) /* I - String name */
593 int i
; /* Looping var */
596 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
597 if (!_cups_strcasecmp(name
, http_fields
[i
]))
598 return ((http_field_t
)i
);
600 return (HTTP_FIELD_UNKNOWN
);
605 * 'httpFlush()' - Flush data from a HTTP connection.
609 httpFlush(http_t
*http
) /* I - HTTP connection */
611 char buffer
[8192]; /* Junk buffer */
612 int blocking
; /* To block or not to block */
613 http_state_t oldstate
; /* Old state */
616 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
617 httpStateString(http
->state
)));
620 * Nothing to do if we are in the "waiting" state...
623 if (http
->state
== HTTP_STATE_WAITING
)
627 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
630 blocking
= http
->blocking
;
634 * Read any data we can...
637 oldstate
= http
->state
;
638 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
641 * Restore blocking and reset the connection if we didn't get all of
642 * the remaining data...
645 http
->blocking
= blocking
;
647 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
651 * Didn't get the data back, so close the current connection.
656 http_content_coding_finish(http
);
657 #endif /* HAVE_LIBZ */
659 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
661 http
->state
= HTTP_STATE_WAITING
;
666 #endif /* HAVE_SSL */
668 httpAddrClose(NULL
, http
->fd
);
676 * 'httpFlushWrite()' - Flush data in write buffer.
678 * @since CUPS 1.2/OS X 10.5@
681 int /* O - Bytes written or -1 on error */
682 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
684 int bytes
; /* Bytes written */
687 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
688 http
? http
->data_encoding
: -1));
690 if (!http
|| !http
->wused
)
692 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
693 "1httpFlushWrite: No connection.");
697 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
698 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
700 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
704 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
711 * 'httpFreeCredentials()' - Free an array of credentials.
716 cups_array_t
*credentials
) /* I - Array of credentials */
718 http_credential_t
*credential
; /* Credential */
721 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
723 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
725 cupsArrayRemove(credentials
, credential
);
726 free((void *)credential
->data
);
730 cupsArrayDelete(credentials
);
735 * 'httpGet()' - Send a GET request to the server.
738 int /* O - Status of call (0 = success) */
739 httpGet(http_t
*http
, /* I - HTTP connection */
740 const char *uri
) /* I - URI to get */
742 return (http_send(http
, HTTP_STATE_GET
, uri
));
747 * 'httpGetActivity()' - Get the most recent activity for a connection.
749 * The return value is the UNIX time of the last read or write.
754 time_t /* O - Time of last read or write */
755 httpGetActivity(http_t
*http
) /* I - HTTP connection */
757 return (http
? http
->activity
: 0);
762 * 'httpGetAuthString()' - Get the current authorization string.
764 * The authorization string is set by cupsDoAuthentication() and
765 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
766 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
769 * @since CUPS 1.3/OS X 10.5@
772 char * /* O - Authorization string */
773 httpGetAuthString(http_t
*http
) /* I - HTTP connection */
776 return (http
->authstring
);
783 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
785 * @since CUPS 1.2/OS X 10.5@
788 int /* O - 1 if blocking, 0 if non-blocking */
789 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
791 return (http
? http
->blocking
: 0);
796 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
797 * the client and server.
799 * This function uses the value of the Accepts-Encoding HTTP header and must be
800 * called after receiving a response from the server or a request from the
801 * client. The value returned can be use in subsequent requests (for clients)
802 * or in the response (for servers) in order to compress the content stream.
804 * @since CUPS 1.7/OS X 10.9@
807 const char * /* O - Content-Coding value or
808 @code NULL@ for the identity
810 httpGetContentEncoding(http_t
*http
) /* I - HTTP connection */
813 if (http
&& http
->accept_encoding
)
815 int i
; /* Looping var */
816 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
817 *start
, /* Start of coding value */
818 *end
; /* End of coding value */
819 double qvalue
; /* "qvalue" for coding */
820 struct lconv
*loc
= localeconv(); /* Locale data */
821 static const char * const codings
[] =
822 { /* Supported content codings */
829 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
831 for (start
= temp
; *start
; start
= end
)
834 * Find the end of the coding name...
839 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
845 * Grab the qvalue as needed...
848 if (!strncmp(end
, ";q=", 3))
849 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
852 * Skip past all attributes...
856 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
862 while (*end
&& isspace(*end
& 255))
866 * Check value if it matches something we support...
872 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
873 if (!strcmp(start
, codings
[i
]))
877 #endif /* HAVE_LIBZ */
884 * 'httpGetCookie()' - Get any cookie data from the response.
886 * @since CUPS 1.1.19/OS X 10.3@
889 const char * /* O - Cookie data or NULL */
890 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
892 return (http
? http
->cookie
: NULL
);
897 * 'httpGetEncryption()' - Get the current encryption mode of a connection.
899 * This function returns the encryption mode for the connection. Use the
900 * @link httpIsEncrypted@ function to determine whether a TLS session has
906 http_encryption_t
/* O - Current encryption mode */
907 httpGetEncryption(http_t
*http
) /* I - HTTP connection */
909 return (http
? http
->encryption
: HTTP_ENCRYPTION_IF_REQUESTED
);
914 * 'httpGetExpect()' - Get the value of the Expect header, if any.
916 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
917 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
919 * @since CUPS 1.7/OS X 10.9@
922 http_status_t
/* O - Expect: status, if any */
923 httpGetExpect(http_t
*http
) /* I - HTTP connection */
926 return (HTTP_STATUS_ERROR
);
928 return (http
->expect
);
933 * 'httpGetFd()' - Get the file descriptor associated with a connection.
935 * @since CUPS 1.2/OS X 10.5@
938 int /* O - File descriptor or -1 if none */
939 httpGetFd(http_t
*http
) /* I - HTTP connection */
941 return (http
? http
->fd
: -1);
946 * 'httpGetField()' - Get a field value from a request/response.
949 const char * /* O - Field value */
950 httpGetField(http_t
*http
, /* I - HTTP connection */
951 http_field_t field
) /* I - Field to get */
953 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
958 case HTTP_FIELD_ACCEPT_ENCODING
:
959 return (http
->accept_encoding
);
961 case HTTP_FIELD_ALLOW
:
962 return (http
->allow
);
964 case HTTP_FIELD_SERVER
:
965 return (http
->server
);
967 case HTTP_FIELD_AUTHORIZATION
:
968 if (http
->field_authorization
)
971 * Special case for WWW-Authenticate: as its contents can be
972 * longer than HTTP_MAX_VALUE...
975 return (http
->field_authorization
);
979 return (http
->fields
[field
]);
985 * 'httpGetKeepAlive()' - Get the current Keep-Alive state of the connection.
990 http_keepalive_t
/* O - Keep-Alive state */
991 httpGetKeepAlive(http_t
*http
) /* I - HTTP connection */
993 return (http
? http
->keep_alive
: HTTP_KEEPALIVE_OFF
);
998 * 'httpGetLength()' - Get the amount of data remaining from the
999 * content-length or transfer-encoding fields.
1001 * This function is deprecated and will not return lengths larger than
1002 * 2^31 - 1; use httpGetLength2() instead.
1007 int /* O - Content length */
1008 httpGetLength(http_t
*http
) /* I - HTTP connection */
1011 * Get the read content length and return the 32-bit value.
1016 httpGetLength2(http
);
1018 return (http
->_data_remaining
);
1026 * 'httpGetLength2()' - Get the amount of data remaining from the
1027 * content-length or transfer-encoding fields.
1029 * This function returns the complete content length, even for
1030 * content larger than 2^31 - 1.
1032 * @since CUPS 1.2/OS X 10.5@
1035 off_t
/* O - Content length */
1036 httpGetLength2(http_t
*http
) /* I - HTTP connection */
1038 off_t remaining
; /* Remaining length */
1041 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1042 httpStateString(http
->state
)));
1047 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1049 DEBUG_puts("4httpGetLength2: chunked request!");
1055 * The following is a hack for HTTP servers that don't send a
1056 * Content-Length or Transfer-Encoding field...
1058 * If there is no Content-Length then the connection must close
1059 * after the transfer is complete...
1062 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1065 * Default content length is 0 for errors and certain types of operations,
1066 * and 2^31-1 for other successful requests...
1069 if (http
->status
>= HTTP_STATUS_MULTIPLE_CHOICES
||
1070 http
->state
== HTTP_STATE_OPTIONS
||
1071 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1072 http
->state
== HTTP_STATE_HEAD
||
1073 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1074 http
->state
== HTTP_STATE_DELETE
||
1075 http
->state
== HTTP_STATE_TRACE
||
1076 http
->state
== HTTP_STATE_CONNECT
)
1079 remaining
= 2147483647;
1081 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1085 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1086 CUPS_LLCAST remaining
));
1094 * 'httpGetPending()' - Get the number of bytes that are buffered for writing.
1099 size_t /* O - Number of bytes buffered */
1100 httpGetPending(http_t
*http
) /* I - HTTP connection */
1102 return (http
? http
->wused
: 0);
1107 * 'httpGetReady()' - Get the number of bytes that can be read without blocking.
1112 size_t /* O - Number of bytes available */
1113 httpGetReady(http_t
*http
) /* I - HTTP connection */
1117 else if (http
->used
> 0)
1118 return (http
->used
);
1121 return (http_tls_pending(http
));
1122 #endif /* HAVE_SSL */
1129 * 'httpGetRemaining()' - Get the number of remaining bytes in the message
1130 * body or current chunk.
1132 * The @link httpIsChunked@ function can be used to determine whether the
1133 * message body is chunked or fixed-length.
1138 size_t /* O - Remaining bytes */
1139 httpGetRemaining(http_t
*http
) /* I - HTTP connection */
1141 return (http
? http
->data_remaining
: 0);
1146 * 'httpGets()' - Get a line of text from a HTTP connection.
1149 char * /* O - Line or NULL */
1150 httpGets(char *line
, /* I - Line to read into */
1151 int length
, /* I - Max length of buffer */
1152 http_t
*http
) /* I - HTTP connection */
1154 char *lineptr
, /* Pointer into line */
1155 *lineend
, /* End of line */
1156 *bufptr
, /* Pointer into input buffer */
1157 *bufend
; /* Pointer to end of buffer */
1158 int bytes
, /* Number of bytes read */
1159 eol
; /* End-of-line? */
1162 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1164 if (!http
|| !line
|| length
<= 1)
1168 * Read a line from the buffer...
1173 lineend
= line
+ length
- 1;
1176 while (lineptr
< lineend
)
1179 * Pre-load the buffer as needed...
1188 while (http
->used
== 0)
1191 * No newline; see if there is more data to be read...
1194 while (!_httpWait(http
, http
->wait_value
, 1))
1196 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1199 DEBUG_puts("3httpGets: Timed out!");
1201 http
->error
= WSAETIMEDOUT
;
1203 http
->error
= ETIMEDOUT
;
1208 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1209 HTTP_MAX_BUFFER
- http
->used
);
1211 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1216 * Nope, can't get a line this time...
1220 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1222 if (WSAGetLastError() == WSAEINTR
)
1224 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1226 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1229 http
->error
= WSAGetLastError();
1231 else if (WSAGetLastError() != http
->error
)
1233 http
->error
= WSAGetLastError();
1238 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1242 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1244 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1246 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1249 http
->error
= errno
;
1251 else if (errno
!= http
->error
)
1253 http
->error
= errno
;
1260 else if (bytes
== 0)
1262 http
->error
= EPIPE
;
1268 * Yup, update the amount used...
1271 http
->used
+= bytes
;
1275 * Now copy as much of the current line as possible...
1278 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1279 lineptr
< lineend
&& bufptr
< bufend
;)
1281 if (*bufptr
== 0x0a)
1287 else if (*bufptr
== 0x0d)
1290 *lineptr
++ = *bufptr
++;
1293 http
->used
-= (int)(bufptr
- http
->buffer
);
1295 memmove(http
->buffer
, bufptr
, http
->used
);
1303 http
->activity
= time(NULL
);
1307 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1313 DEBUG_puts("3httpGets: No new line available!");
1320 * 'httpGetState()' - Get the current state of the HTTP request.
1323 http_state_t
/* O - HTTP state */
1324 httpGetState(http_t
*http
) /* I - HTTP connection */
1326 return (http
? http
->state
: HTTP_STATE_ERROR
);
1331 * 'httpGetStatus()' - Get the status of the last HTTP request.
1333 * @since CUPS 1.2/OS X 10.5@
1336 http_status_t
/* O - HTTP status */
1337 httpGetStatus(http_t
*http
) /* I - HTTP connection */
1339 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1344 * 'httpGetSubField()' - Get a sub-field value.
1349 char * /* O - Value or NULL */
1350 httpGetSubField(http_t
*http
, /* I - HTTP connection */
1351 http_field_t field
, /* I - Field index */
1352 const char *name
, /* I - Name of sub-field */
1353 char *value
) /* O - Value string */
1355 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1360 * 'httpGetSubField2()' - Get a sub-field value.
1362 * @since CUPS 1.2/OS X 10.5@
1365 char * /* O - Value or NULL */
1366 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
1367 http_field_t field
, /* I - Field index */
1368 const char *name
, /* I - Name of sub-field */
1369 char *value
, /* O - Value string */
1370 int valuelen
) /* I - Size of value buffer */
1372 const char *fptr
; /* Pointer into field */
1373 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1374 *ptr
, /* Pointer into string buffer */
1375 *end
; /* End of value buffer */
1377 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1378 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1380 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1381 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1384 end
= value
+ valuelen
- 1;
1386 for (fptr
= http
->fields
[field
]; *fptr
;)
1389 * Skip leading whitespace...
1392 while (_cups_isspace(*fptr
))
1402 * Get the sub-field name...
1406 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1407 ptr
< (temp
+ sizeof(temp
) - 1);
1412 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1415 * Skip trailing chars up to the '='...
1418 while (_cups_isspace(*fptr
))
1428 * Skip = and leading whitespace...
1433 while (_cups_isspace(*fptr
))
1439 * Read quoted string...
1442 for (ptr
= value
, fptr
++;
1443 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1448 while (*fptr
&& *fptr
!= '\"')
1457 * Read unquoted string...
1461 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1466 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1470 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1473 * See if this is the one...
1476 if (!strcmp(name
, temp
))
1478 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1485 DEBUG_puts("3httpGetSubField2: Returning NULL");
1492 * 'httpGetVersion()' - Get the HTTP version at the other end.
1495 http_version_t
/* O - Version number */
1496 httpGetVersion(http_t
*http
) /* I - HTTP connection */
1498 return (http
? http
->version
: HTTP_VERSION_1_0
);
1503 * 'httpHead()' - Send a HEAD request to the server.
1506 int /* O - Status of call (0 = success) */
1507 httpHead(http_t
*http
, /* I - HTTP connection */
1508 const char *uri
) /* I - URI for head */
1510 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1511 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1516 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1517 * default HTTP proxy (if any).
1521 httpInitialize(void)
1523 static int initialized
= 0; /* Have we been called before? */
1525 WSADATA winsockdata
; /* WinSock data */
1532 _cupsGlobalUnlock();
1537 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1539 #elif !defined(SO_NOSIGPIPE)
1541 * Ignore SIGPIPE signals...
1545 sigset(SIGPIPE
, SIG_IGN
);
1547 # elif defined(HAVE_SIGACTION)
1548 struct sigaction action
; /* POSIX sigaction data */
1551 memset(&action
, 0, sizeof(action
));
1552 action
.sa_handler
= SIG_IGN
;
1553 sigaction(SIGPIPE
, &action
, NULL
);
1556 signal(SIGPIPE
, SIG_IGN
);
1557 # endif /* !SO_NOSIGPIPE */
1561 http_tls_initialize();
1562 # endif /* HAVE_SSL */
1565 _cupsGlobalUnlock();
1570 * 'httpIsChunked()' - Report whether a message body is chunked.
1572 * This function returns non-zero if the message body is composed of
1573 * variable-length chunks.
1578 int /* O - 1 if chunked, 0 if not */
1579 httpIsChunked(http_t
*http
) /* I - HTTP connection */
1581 return (http
? http
->data_encoding
== HTTP_ENCODING_CHUNKED
: 0);
1586 * 'httpIsEncrypted()' - Report whether a connection is encrypted.
1588 * This function returns non-zero if the connection is currently encrypted.
1593 int /* O - 1 if encrypted, 0 if not */
1594 httpIsEncrypted(http_t
*http
) /* I - HTTP connection */
1596 return (http
? http
->tls
!= NULL
: 0);
1601 * 'httpOptions()' - Send an OPTIONS request to the server.
1604 int /* O - Status of call (0 = success) */
1605 httpOptions(http_t
*http
, /* I - HTTP connection */
1606 const char *uri
) /* I - URI for options */
1608 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1613 * 'httpPeek()' - Peek at data from a HTTP connection.
1615 * This function copies available data from the given HTTP connection, reading
1616 * a buffer as needed. The data is still available for reading using
1617 * @link httpRead@ or @link httpRead2@.
1619 * For non-blocking connections the usual timeouts apply.
1621 * @since CUPS 1.7/OS X 10.9@
1624 ssize_t
/* O - Number of bytes copied */
1625 httpPeek(http_t
*http
, /* I - HTTP connection */
1626 char *buffer
, /* I - Buffer for data */
1627 size_t length
) /* I - Maximum number of bytes */
1629 ssize_t bytes
; /* Bytes read */
1630 char len
[32]; /* Length string */
1633 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1634 http
, buffer
, CUPS_LLCAST length
));
1636 if (http
== NULL
|| buffer
== NULL
)
1639 http
->activity
= time(NULL
);
1645 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1646 http
->data_remaining
<= 0)
1648 DEBUG_puts("2httpPeek: Getting chunk length...");
1650 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1652 DEBUG_puts("1httpPeek: Could not get length!");
1658 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1659 if (!httpGets(len
, sizeof(len
), http
))
1661 DEBUG_puts("1httpPeek: Could not get chunk length.");
1666 http
->data_remaining
= strtoll(len
, NULL
, 16);
1668 if (http
->data_remaining
< 0)
1670 DEBUG_puts("1httpPeek: Negative chunk length!");
1675 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1676 CUPS_LLCAST http
->data_remaining
));
1678 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1681 * A zero-length chunk ends a transfer; unless we are reading POST
1687 http_content_coding_finish(http
);
1688 #endif /* HAVE_LIBZ */
1690 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1691 httpGets(len
, sizeof(len
), http
);
1693 if (http
->state
== HTTP_STATE_POST_RECV
)
1696 http
->state
= HTTP_STATE_STATUS
;
1698 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1699 httpStateString(http
->state
)));
1702 * Prevent future reads for this request...
1705 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1709 else if (length
> (size_t)http
->data_remaining
)
1710 length
= (size_t)http
->data_remaining
;
1713 if (http
->used
== 0 &&
1714 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1716 if (http
->used
== 0)
1717 #endif /* HAVE_LIBZ */
1720 * Buffer small reads for better performance...
1723 ssize_t buflen
; /* Length of read for buffer */
1725 if (!http
->blocking
)
1727 while (!httpWait(http
, http
->wait_value
))
1729 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1736 if (http
->data_remaining
> sizeof(http
->buffer
))
1737 buflen
= sizeof(http
->buffer
);
1739 buflen
= http
->data_remaining
;
1741 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1742 bytes
= http_read(http
, http
->buffer
, buflen
);
1744 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1745 CUPS_LLCAST bytes
));
1749 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1759 # ifdef HAVE_INFLATECOPY
1760 int zerr
; /* Decompressor error */
1761 z_stream stream
; /* Copy of decompressor stream */
1763 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1765 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1766 /* Number of bytes to copy */
1768 if (http
->stream
.avail_in
> 0 &&
1769 http
->stream
.next_in
> http
->dbuffer
)
1770 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1772 http
->stream
.next_in
= http
->dbuffer
;
1774 if (buflen
> http
->data_remaining
)
1775 buflen
= http
->data_remaining
;
1777 if (buflen
> http
->used
)
1778 buflen
= http
->used
;
1780 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1781 "decompression buffer.", (int)buflen
));
1783 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
1784 http
->stream
.avail_in
+= buflen
;
1785 http
->used
-= buflen
;
1786 http
->data_remaining
-= buflen
;
1789 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
1792 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
1793 (int)http
->stream
.avail_in
));
1795 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
1797 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
1798 http
->error
= ENOMEM
;
1802 stream
.next_out
= (Bytef
*)buffer
;
1803 stream
.avail_out
= length
;
1805 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
1806 inflateEnd(&stream
);
1810 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
1812 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
1813 http
->stream
.avail_in
);
1820 bytes
= length
- http
->stream
.avail_out
;
1823 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
1824 "work with compressed streams.");
1826 # endif /* HAVE_INFLATECOPY */
1829 #endif /* HAVE_LIBZ */
1832 if (length
> (size_t)http
->used
)
1833 length
= (size_t)http
->used
;
1835 bytes
= (ssize_t
)length
;
1837 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
1840 memcpy(buffer
, http
->buffer
, length
);
1848 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1851 http
->error
= WSAGetLastError();
1853 if (errno
== EINTR
|| errno
== EAGAIN
)
1856 http
->error
= errno
;
1859 else if (bytes
== 0)
1861 http
->error
= EPIPE
;
1870 * 'httpPost()' - Send a POST request to the server.
1873 int /* O - Status of call (0 = success) */
1874 httpPost(http_t
*http
, /* I - HTTP connection */
1875 const char *uri
) /* I - URI for post */
1877 return (http_send(http
, HTTP_STATE_POST
, uri
));
1882 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1887 int /* O - Number of bytes written */
1888 httpPrintf(http_t
*http
, /* I - HTTP connection */
1889 const char *format
, /* I - printf-style format string */
1890 ...) /* I - Additional args as needed */
1892 int bytes
; /* Number of bytes to write */
1893 char buf
[16384]; /* Buffer for formatted string */
1894 va_list ap
; /* Variable argument pointer */
1897 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1899 va_start(ap
, format
);
1900 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1903 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
1905 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
1906 return (httpWrite2(http
, buf
, bytes
));
1911 DEBUG_puts("4httpPrintf: flushing existing data...");
1913 if (httpFlushWrite(http
) < 0)
1917 return (http_write(http
, buf
, bytes
));
1923 * 'httpPut()' - Send a PUT request to the server.
1926 int /* O - Status of call (0 = success) */
1927 httpPut(http_t
*http
, /* I - HTTP connection */
1928 const char *uri
) /* I - URI to put */
1930 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1931 return (http_send(http
, HTTP_STATE_PUT
, uri
));
1936 * 'httpRead()' - Read data from a HTTP connection.
1938 * This function is deprecated. Use the httpRead2() function which can
1939 * read more than 2GB of data.
1944 int /* O - Number of bytes read */
1945 httpRead(http_t
*http
, /* I - HTTP connection */
1946 char *buffer
, /* I - Buffer for data */
1947 int length
) /* I - Maximum number of bytes */
1949 return ((int)httpRead2(http
, buffer
, length
));
1954 * 'httpRead2()' - Read data from a HTTP connection.
1956 * @since CUPS 1.2/OS X 10.5@
1959 ssize_t
/* O - Number of bytes read */
1960 httpRead2(http_t
*http
, /* I - HTTP connection */
1961 char *buffer
, /* I - Buffer for data */
1962 size_t length
) /* I - Maximum number of bytes */
1964 ssize_t bytes
; /* Bytes read */
1968 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
1969 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
1970 http
, buffer
, CUPS_LLCAST length
,
1972 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
1974 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
1975 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
1976 http
, buffer
, CUPS_LLCAST length
,
1977 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
1978 #endif /* HAVE_LIBZ */
1980 if (http
== NULL
|| buffer
== NULL
)
1983 http
->activity
= time(NULL
);
1994 if (http
->stream
.avail_in
> 0)
1996 int zerr
; /* Decompressor error */
1998 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
1999 (int)http
->stream
.avail_in
, (int)length
));
2001 http
->stream
.next_out
= (Bytef
*)buffer
;
2002 http
->stream
.avail_out
= length
;
2004 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2006 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2008 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2009 http
->stream
.avail_in
);
2016 bytes
= length
- http
->stream
.avail_out
;
2018 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2019 http
->stream
.avail_in
, http
->stream
.avail_out
,
2027 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2028 /* Additional bytes for buffer */
2032 if (http
->stream
.avail_in
> 0 &&
2033 http
->stream
.next_in
> http
->dbuffer
)
2034 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2036 http
->stream
.next_in
= http
->dbuffer
;
2038 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2039 "decompression buffer.", (int)buflen
));
2041 if (http
->data_remaining
> 0)
2043 if (buflen
> http
->data_remaining
)
2044 buflen
= http
->data_remaining
;
2046 bytes
= http_read_buffered(http
,
2047 (char *)http
->dbuffer
+
2048 http
->stream
.avail_in
, buflen
);
2050 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2051 bytes
= http_read_chunk(http
,
2052 (char *)http
->dbuffer
+
2053 http
->stream
.avail_in
, buflen
);
2059 else if (bytes
== 0)
2062 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2063 "decompression buffer.", CUPS_LLCAST bytes
));
2065 http
->data_remaining
-= bytes
;
2066 http
->stream
.avail_in
+= bytes
;
2068 if (http
->data_remaining
<= 0 &&
2069 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2072 * Read the trailing blank line now...
2075 char len
[32]; /* Length string */
2077 httpGets(len
, sizeof(len
), http
);
2089 #endif /* HAVE_LIBZ */
2090 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2092 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2094 http
->data_remaining
-= bytes
;
2096 if (http
->data_remaining
<= 0)
2099 * Read the trailing blank line now...
2102 char len
[32]; /* Length string */
2104 httpGets(len
, sizeof(len
), http
);
2108 else if (http
->data_remaining
<= 0)
2111 * No more data to read...
2118 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2121 if (length
> (size_t)http
->data_remaining
)
2122 length
= (size_t)http
->data_remaining
;
2124 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2126 http
->data_remaining
-= bytes
;
2128 if (http
->data_remaining
<= 0 &&
2129 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2132 * Read the trailing blank line now...
2135 char len
[32]; /* Length string */
2137 httpGets(len
, sizeof(len
), http
);
2144 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2145 #endif /* HAVE_LIBZ */
2146 ((http
->data_remaining
<= 0 &&
2147 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2148 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2152 http_content_coding_finish(http
);
2153 #endif /* HAVE_LIBZ */
2155 if (http
->state
== HTTP_STATE_POST_RECV
)
2157 else if (http
->state
== HTTP_STATE_GET_SEND
||
2158 http
->state
== HTTP_STATE_POST_SEND
)
2159 http
->state
= HTTP_STATE_WAITING
;
2161 http
->state
= HTTP_STATE_STATUS
;
2163 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2164 httpStateString(http
->state
)));
2172 * 'httpReadRequest()' - Read a HTTP request from a connection.
2174 * @since CUPS 1.7/OS X 10.9@
2177 http_state_t
/* O - New state of connection */
2178 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2179 char *uri
, /* I - URI buffer */
2180 size_t urilen
) /* I - Size of URI buffer */
2182 char line
[4096], /* HTTP request line */
2183 *req_method
, /* HTTP request method */
2184 *req_uri
, /* HTTP request URI */
2185 *req_version
; /* HTTP request version number string */
2189 * Range check input...
2192 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2193 http
, uri
, CUPS_LLCAST urilen
));
2198 if (!http
|| !uri
|| urilen
< 1)
2200 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2201 return (HTTP_STATE_ERROR
);
2203 else if (http
->state
!= HTTP_STATE_WAITING
)
2205 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2206 httpStateString(http
->state
)));
2207 return (HTTP_STATE_ERROR
);
2214 httpClearFields(http
);
2216 http
->activity
= time(NULL
);
2217 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2218 http
->data_remaining
= 0;
2219 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2220 http
->status
= HTTP_STATUS_OK
;
2221 http
->version
= HTTP_VERSION_1_1
;
2224 * Read a line from the socket...
2227 if (!httpGets(line
, sizeof(line
), http
))
2229 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2230 return (HTTP_STATE_ERROR
);
2235 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2236 return (HTTP_STATE_WAITING
);
2239 DEBUG_printf(("1httpReadRequest: %s", line
));
2248 while (*req_uri
&& !isspace(*req_uri
& 255))
2253 DEBUG_puts("1httpReadRequest: No request URI.");
2254 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request URI."), 1);
2255 return (HTTP_STATE_ERROR
);
2260 while (*req_uri
&& isspace(*req_uri
& 255))
2263 req_version
= req_uri
;
2265 while (*req_version
&& !isspace(*req_version
& 255))
2270 DEBUG_puts("1httpReadRequest: No request protocol version.");
2271 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request protocol version."), 1);
2272 return (HTTP_STATE_ERROR
);
2275 *req_version
++ = '\0';
2277 while (*req_version
&& isspace(*req_version
& 255))
2284 if (!strcmp(req_method
, "OPTIONS"))
2285 http
->state
= HTTP_STATE_OPTIONS
;
2286 else if (!strcmp(req_method
, "GET"))
2287 http
->state
= HTTP_STATE_GET
;
2288 else if (!strcmp(req_method
, "HEAD"))
2289 http
->state
= HTTP_STATE_HEAD
;
2290 else if (!strcmp(req_method
, "POST"))
2291 http
->state
= HTTP_STATE_POST
;
2292 else if (!strcmp(req_method
, "PUT"))
2293 http
->state
= HTTP_STATE_PUT
;
2294 else if (!strcmp(req_method
, "DELETE"))
2295 http
->state
= HTTP_STATE_DELETE
;
2296 else if (!strcmp(req_method
, "TRACE"))
2297 http
->state
= HTTP_STATE_TRACE
;
2298 else if (!strcmp(req_method
, "CONNECT"))
2299 http
->state
= HTTP_STATE_CONNECT
;
2302 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2303 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request method."), 1);
2304 return (HTTP_STATE_UNKNOWN_METHOD
);
2307 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2308 httpStateString(http
->state
)));
2310 if (!strcmp(req_version
, "HTTP/1.0"))
2312 http
->version
= HTTP_VERSION_1_0
;
2313 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2315 else if (!strcmp(req_version
, "HTTP/1.1"))
2317 http
->version
= HTTP_VERSION_1_1
;
2318 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2322 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2323 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request version."), 1);
2324 return (HTTP_STATE_UNKNOWN_VERSION
);
2327 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2328 strlcpy(uri
, req_uri
, urilen
);
2330 return (http
->state
);
2335 * 'httpReconnect()' - Reconnect to a HTTP server.
2337 * This function is deprecated. Please use the @link httpReconnect2@ function
2343 int /* O - 0 on success, non-zero on failure */
2344 httpReconnect(http_t
*http
) /* I - HTTP connection */
2346 DEBUG_printf(("httpReconnect(http=%p)", http
));
2348 return (httpReconnect2(http
, 30000, NULL
));
2353 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2357 int /* O - 0 on success, non-zero on failure */
2358 httpReconnect2(http_t
*http
, /* I - HTTP connection */
2359 int msec
, /* I - Timeout in milliseconds */
2360 int *cancel
) /* I - Pointer to "cancel" variable */
2362 http_addrlist_t
*addr
; /* Connected address */
2364 http_addrlist_t
*current
; /* Current address */
2365 char temp
[256]; /* Temporary address string */
2369 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2374 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2381 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2382 http_tls_stop(http
);
2384 #endif /* HAVE_SSL */
2387 * Close any previously open socket...
2392 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2394 httpAddrClose(NULL
, http
->fd
);
2400 * Reset all state (except fields, which may be reused)...
2403 http
->state
= HTTP_STATE_WAITING
;
2404 http
->version
= HTTP_VERSION_1_1
;
2405 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2406 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2407 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2408 http
->_data_remaining
= 0;
2410 http
->data_remaining
= 0;
2411 http
->hostaddr
= NULL
;
2415 * Connect to the server...
2419 for (current
= http
->addrlist
; current
; current
= current
->next
)
2420 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2421 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2422 httpAddrPort(&(current
->addr
))));
2425 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2429 * Unable to connect...
2433 http
->error
= WSAGetLastError();
2435 http
->error
= errno
;
2437 http
->status
= HTTP_STATUS_ERROR
;
2439 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2440 strerror(http
->error
)));
2445 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2447 if (http
->timeout_value
> 0)
2448 http_set_timeout(http
->fd
, http
->timeout_value
);
2450 http
->hostaddr
= &(addr
->addr
);
2454 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2457 * Always do encryption via SSL.
2460 if (http_tls_start(http
) != 0)
2462 httpAddrClose(NULL
, http
->fd
);
2467 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2468 return (http_tls_upgrade(http
));
2469 #endif /* HAVE_SSL */
2471 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2472 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2473 httpAddrPort(http
->hostaddr
)));
2480 * 'httpSetAuthString()' - Set the current authorization string.
2482 * This function just stores a copy of the current authorization string in
2483 * the HTTP connection object. You must still call httpSetField() to set
2484 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2485 * httpHead(), httpOptions(), httpPost, or httpPut().
2487 * @since CUPS 1.3/OS X 10.5@
2491 httpSetAuthString(http_t
*http
, /* I - HTTP connection */
2492 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2493 const char *data
) /* I - Auth data (NULL for none) */
2496 * Range check input...
2502 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2503 free(http
->authstring
);
2505 http
->authstring
= http
->_authstring
;
2510 * Set the current authorization string...
2513 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2516 if (len
> (int)sizeof(http
->_authstring
))
2518 if ((temp
= malloc(len
)) == NULL
)
2519 len
= sizeof(http
->_authstring
);
2521 http
->authstring
= temp
;
2525 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2527 strlcpy(http
->authstring
, scheme
, len
);
2532 * Clear the current authorization string...
2535 http
->_authstring
[0] = '\0';
2541 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2544 * @since CUPS 1.5/OS X 10.7@
2547 int /* O - Status of call (0 = success) */
2548 httpSetCredentials(http_t
*http
, /* I - HTTP connection */
2549 cups_array_t
*credentials
) /* I - Array of credentials */
2551 if (!http
|| cupsArrayCount(credentials
) < 1)
2554 _httpFreeCredentials(http
->tls_credentials
);
2556 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2558 return (http
->tls_credentials
? 0 : -1);
2563 * 'httpSetCookie()' - Set the cookie value(s).
2565 * @since CUPS 1.1.19/OS X 10.3@
2569 httpSetCookie(http_t
*http
, /* I - Connection */
2570 const char *cookie
) /* I - Cookie string */
2579 http
->cookie
= strdup(cookie
);
2581 http
->cookie
= NULL
;
2586 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2588 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2589 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2591 * @since CUPS 1.7/OS X 10.9@
2595 httpSetDefaultField(http_t
*http
, /* I - HTTP connection */
2596 http_field_t field
, /* I - Field index */
2597 const char *value
)/* I - Value */
2599 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2600 http
, field
, http_fields
[field
], value
));
2607 case HTTP_FIELD_ACCEPT_ENCODING
:
2608 if (http
->default_accept_encoding
)
2609 _cupsStrFree(http
->default_accept_encoding
);
2611 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2614 case HTTP_FIELD_SERVER
:
2615 if (http
->default_server
)
2616 _cupsStrFree(http
->default_server
);
2618 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2621 case HTTP_FIELD_USER_AGENT
:
2622 if (http
->default_user_agent
)
2623 _cupsStrFree(http
->default_user_agent
);
2625 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2629 DEBUG_puts("1httpSetDefaultField: Ignored.");
2636 * 'httpSetExpect()' - Set the Expect: header in a request.
2638 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2641 * @since CUPS 1.2/OS X 10.5@
2645 httpSetExpect(http_t
*http
, /* I - HTTP connection */
2646 http_status_t expect
) /* I - HTTP status to expect
2647 (@code HTTP_STATUS_CONTINUE@) */
2649 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2652 http
->expect
= expect
;
2657 * 'httpSetField()' - Set the value of an HTTP header.
2661 httpSetField(http_t
*http
, /* I - HTTP connection */
2662 http_field_t field
, /* I - Field index */
2663 const char *value
) /* I - Value */
2665 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2666 field
, http_fields
[field
], value
));
2669 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2670 field
>= HTTP_FIELD_MAX
||
2676 case HTTP_FIELD_ACCEPT_ENCODING
:
2677 if (http
->accept_encoding
)
2678 _cupsStrFree(http
->accept_encoding
);
2680 http
->accept_encoding
= _cupsStrAlloc(value
);
2683 case HTTP_FIELD_ALLOW
:
2685 _cupsStrFree(http
->allow
);
2687 http
->allow
= _cupsStrAlloc(value
);
2690 case HTTP_FIELD_SERVER
:
2692 _cupsStrFree(http
->server
);
2694 http
->server
= _cupsStrAlloc(value
);
2698 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2702 if (field
== HTTP_FIELD_AUTHORIZATION
)
2705 * Special case for Authorization: as its contents can be
2706 * longer than HTTP_MAX_VALUE
2709 if (http
->field_authorization
)
2710 free(http
->field_authorization
);
2712 http
->field_authorization
= strdup(value
);
2714 else if (field
== HTTP_FIELD_HOST
)
2717 * Special-case for Host: as we don't want a trailing "." on the hostname and
2718 * need to bracket IPv6 numeric addresses.
2721 char *ptr
= strchr(value
, ':');
2723 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2726 * Bracket IPv6 numeric addresses...
2728 * This is slightly inefficient (basically copying twice), but is an edge
2729 * case and not worth optimizing...
2732 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2733 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2738 * Check for a trailing dot on the hostname...
2741 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2745 ptr
+= strlen(ptr
) - 1;
2753 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
2754 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
2756 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
2757 http_content_coding_start(http
, value
);
2759 #endif /* HAVE_LIBZ */
2764 * 'httpSetKeepAlive()' - Set the current Keep-Alive state of a connection.
2771 http_t
*http
, /* I - HTTP connection */
2772 http_keepalive_t keep_alive
) /* I - New Keep-Alive value */
2775 http
->keep_alive
= keep_alive
;
2780 * 'httpSetLength()' - Set the content-length and content-encoding.
2782 * @since CUPS 1.2/OS X 10.5@
2786 httpSetLength(http_t
*http
, /* I - HTTP connection */
2787 size_t length
) /* I - Length (0 for chunked) */
2789 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
2790 CUPS_LLCAST length
));
2797 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
2799 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2803 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2804 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2805 CUPS_LLFMT
, CUPS_LLCAST length
);
2811 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2813 * The optional timeout callback receives both the HTTP connection and a user
2814 * data pointer and must return 1 to continue or 0 to error (time) out.
2816 * @since CUPS 1.5/OS X 10.7@
2821 http_t
*http
, /* I - HTTP connection */
2822 double timeout
, /* I - Number of seconds for timeout,
2823 must be greater than 0 */
2824 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2825 void *user_data
) /* I - User data pointer */
2827 if (!http
|| timeout
<= 0.0)
2830 http
->timeout_cb
= cb
;
2831 http
->timeout_data
= user_data
;
2832 http
->timeout_value
= timeout
;
2835 http_set_timeout(http
->fd
, timeout
);
2837 http_set_wait(http
);
2842 * 'httpShutdown()' - Shutdown one side of an HTTP connection.
2848 httpShutdown(http_t
*http
) /* I - HTTP connection */
2850 if (!http
|| http
->fd
< 0)
2854 http_tls_stop(http
);
2856 shutdown(http
->fd
, SHUT_RD
);
2861 * 'httpTrace()' - Send an TRACE request to the server.
2864 int /* O - Status of call (0 = success) */
2865 httpTrace(http_t
*http
, /* I - HTTP connection */
2866 const char *uri
) /* I - URI for trace */
2868 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
2873 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2875 * Note: Unlike httpUpdate(), this function does not flush pending write data
2876 * and only retrieves a single status line from the HTTP connection.
2879 int /* O - 1 to continue, 0 to stop */
2880 _httpUpdate(http_t
*http
, /* I - HTTP connection */
2881 http_status_t
*status
) /* O - Current HTTP status */
2883 char line
[32768], /* Line from connection... */
2884 *value
; /* Pointer to value on line */
2885 http_field_t field
; /* Field index */
2886 int major
, minor
; /* HTTP version numbers */
2889 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2890 httpStateString(http
->state
)));
2893 * Grab a single line from the connection...
2896 if (!httpGets(line
, sizeof(line
), http
))
2898 *status
= HTTP_STATUS_ERROR
;
2902 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2904 if (line
[0] == '\0')
2907 * Blank line means the start of the data section (if any). Return
2908 * the result code, too...
2910 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
2911 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
2915 if (http
->status
== HTTP_STATUS_CONTINUE
)
2917 *status
= http
->status
;
2921 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
2922 http
->digest_tries
= 0;
2925 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
2927 if (http_tls_start(http
) != 0)
2929 httpAddrClose(NULL
, http
->fd
);
2931 *status
= http
->status
= HTTP_STATUS_ERROR
;
2935 *status
= HTTP_STATUS_CONTINUE
;
2938 #endif /* HAVE_SSL */
2940 if (http_set_length(http
) < 0)
2942 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
2943 http
->error
= EINVAL
;
2944 http
->status
= *status
= HTTP_STATUS_ERROR
;
2948 switch (http
->state
)
2950 case HTTP_STATE_GET
:
2951 case HTTP_STATE_POST
:
2952 case HTTP_STATE_POST_RECV
:
2953 case HTTP_STATE_PUT
:
2956 DEBUG_printf(("1_httpUpdate: Set state to %s.",
2957 httpStateString(http
->state
)));
2959 case HTTP_STATE_POST_SEND
:
2960 case HTTP_STATE_HEAD
:
2964 http
->state
= HTTP_STATE_WAITING
;
2966 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
2971 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
2972 http_content_coding_start(http
,
2973 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
2974 #endif /* HAVE_LIBZ */
2976 *status
= http
->status
;
2979 else if (!strncmp(line
, "HTTP/", 5))
2982 * Got the beginning of a response...
2985 int intstatus
; /* Status value as an integer */
2987 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2989 *status
= http
->status
= HTTP_STATUS_ERROR
;
2993 httpClearFields(http
);
2995 http
->version
= (http_version_t
)(major
* 100 + minor
);
2996 *status
= http
->status
= (http_status_t
)intstatus
;
2998 else if ((value
= strchr(line
, ':')) != NULL
)
3005 while (_cups_isspace(*value
))
3008 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3011 * Be tolerants of servers that send unknown attribute fields...
3014 if (!_cups_strcasecmp(line
, "expect"))
3017 * "Expect: 100-continue" or similar...
3020 http
->expect
= (http_status_t
)atoi(value
);
3022 else if (!_cups_strcasecmp(line
, "cookie"))
3025 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3028 httpSetCookie(http
, value
);
3030 else if ((field
= httpFieldValue(line
)) != HTTP_FIELD_UNKNOWN
)
3031 httpSetField(http
, field
, value
);
3034 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3039 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3040 http
->error
= EINVAL
;
3041 http
->status
= *status
= HTTP_STATUS_ERROR
;
3050 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3053 http_status_t
/* O - HTTP status */
3054 httpUpdate(http_t
*http
) /* I - HTTP connection */
3056 http_status_t status
; /* Request status */
3059 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3060 httpStateString(http
->state
)));
3063 * Flush pending data, if any...
3068 DEBUG_puts("2httpUpdate: flushing buffer...");
3070 if (httpFlushWrite(http
) < 0)
3071 return (HTTP_STATUS_ERROR
);
3075 * If we haven't issued any commands, then there is nothing to "update"...
3078 if (http
->state
== HTTP_STATE_WAITING
)
3079 return (HTTP_STATUS_CONTINUE
);
3082 * Grab all of the lines we can from the connection...
3085 while (_httpUpdate(http
, &status
));
3088 * See if there was an error...
3091 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3093 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3094 return (http
->status
);
3099 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3100 strerror(http
->error
)));
3101 http
->status
= HTTP_STATUS_ERROR
;
3102 return (HTTP_STATUS_ERROR
);
3106 * Return the current status...
3114 * '_httpWait()' - Wait for data available on a connection (no flush).
3117 int /* O - 1 if data is available, 0 otherwise */
3118 _httpWait(http_t
*http
, /* I - HTTP connection */
3119 int msec
, /* I - Milliseconds to wait */
3120 int usessl
) /* I - Use SSL context? */
3123 struct pollfd pfd
; /* Polled file descriptor */
3125 fd_set input_set
; /* select() input set */
3126 struct timeval timeout
; /* Timeout */
3127 #endif /* HAVE_POLL */
3128 int nfds
; /* Result from select()/poll() */
3131 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3135 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3140 * Check the SSL/TLS buffers for data first...
3144 if (http_tls_pending(http
))
3146 DEBUG_puts("5_httpWait: Return 1 since there is pending TLS data.");
3149 #endif /* HAVE_SSL */
3152 * Then try doing a select() or poll() to poll the socket...
3157 pfd
.events
= POLLIN
;
3161 nfds
= poll(&pfd
, 1, msec
);
3163 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3168 FD_ZERO(&input_set
);
3169 FD_SET(http
->fd
, &input_set
);
3171 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3175 timeout
.tv_sec
= msec
/ 1000;
3176 timeout
.tv_usec
= (msec
% 1000) * 1000;
3178 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3181 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3183 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3186 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3187 WSAGetLastError() == WSAEWOULDBLOCK
));
3189 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3191 #endif /* HAVE_POLL */
3193 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3201 * 'httpWait()' - Wait for data available on a connection.
3203 * @since CUPS 1.1.19/OS X 10.3@
3206 int /* O - 1 if data is available, 0 otherwise */
3207 httpWait(http_t
*http
, /* I - HTTP connection */
3208 int msec
) /* I - Milliseconds to wait */
3211 * First see if there is data in the buffer...
3214 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3221 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3226 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3228 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3231 #endif /* HAVE_LIBZ */
3234 * Flush pending data, if any...
3239 DEBUG_puts("3httpWait: Flushing write buffer.");
3241 if (httpFlushWrite(http
) < 0)
3246 * If not, check the SSL/TLS buffers and do a select() on the connection...
3249 return (_httpWait(http
, msec
, 1));
3254 * 'httpWrite()' - Write data to a HTTP connection.
3256 * This function is deprecated. Use the httpWrite2() function which can
3257 * write more than 2GB of data.
3262 int /* O - Number of bytes written */
3263 httpWrite(http_t
*http
, /* I - HTTP connection */
3264 const char *buffer
, /* I - Buffer for data */
3265 int length
) /* I - Number of bytes to write */
3267 return ((int)httpWrite2(http
, buffer
, length
));
3272 * 'httpWrite2()' - Write data to a HTTP connection.
3274 * @since CUPS 1.2/OS X 10.5@
3277 ssize_t
/* O - Number of bytes written */
3278 httpWrite2(http_t
*http
, /* I - HTTP connection */
3279 const char *buffer
, /* I - Buffer for data */
3280 size_t length
) /* I - Number of bytes to write */
3282 ssize_t bytes
; /* Bytes written */
3285 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3286 buffer
, CUPS_LLCAST length
));
3289 * Range check input...
3292 if (!http
|| !buffer
)
3294 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3299 * Mark activity on the connection...
3302 http
->activity
= time(NULL
);
3305 * Buffer small writes for better performance...
3311 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3315 http_content_coding_finish(http
);
3320 http
->stream
.next_in
= (Bytef
*)buffer
;
3321 http
->stream
.avail_in
= length
;
3322 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3323 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3325 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3327 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3329 if (http
->stream
.avail_out
== 0)
3331 if (httpFlushWrite(http
) < 0)
3333 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3337 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3338 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3342 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3347 #endif /* HAVE_LIBZ */
3350 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3352 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3353 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3355 httpFlushWrite(http
);
3358 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3359 length
< sizeof(http
->wbuffer
))
3362 * Write to buffer...
3365 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3366 CUPS_LLCAST length
));
3368 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3369 http
->wused
+= (int)length
;
3370 bytes
= (ssize_t
)length
;
3375 * Otherwise write the data directly...
3378 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3379 CUPS_LLCAST length
));
3381 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3382 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3384 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3386 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3387 CUPS_LLCAST bytes
));
3390 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3391 http
->data_remaining
-= bytes
;
3397 * Handle end-of-request processing...
3400 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3401 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3404 * Finished with the transfer; unless we are sending POST or PUT
3410 http_content_coding_finish(http
);
3411 #endif /* HAVE_LIBZ */
3415 if (httpFlushWrite(http
) < 0)
3419 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3422 * Send a 0-length chunk at the end of the request...
3425 http_write(http
, "0\r\n\r\n", 5);
3428 * Reset the data state...
3431 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3432 http
->data_remaining
= 0;
3435 if (http
->state
== HTTP_STATE_POST_RECV
)
3437 else if (http
->state
== HTTP_STATE_POST_SEND
||
3438 http
->state
== HTTP_STATE_GET_SEND
)
3439 http
->state
= HTTP_STATE_WAITING
;
3441 http
->state
= HTTP_STATE_STATUS
;
3443 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3444 httpStateString(http
->state
)));
3447 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3454 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3456 * @since CUPS 1.7/OS X 10.9@
3459 int /* O - 0 on success, -1 on error */
3460 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3461 http_status_t status
) /* I - Status code */
3463 http_encoding_t old_encoding
; /* Old data_encoding value */
3464 off_t old_remaining
; /* Old data_remaining value */
3468 * Range check input...
3471 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3473 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3475 DEBUG_puts("1httpWriteResponse: Bad input.");
3480 * Set the various standard fields if they aren't already...
3483 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3484 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3486 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3488 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
3489 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3492 if (http
->version
== HTTP_VERSION_1_1
)
3494 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3496 if (http
->keep_alive
)
3497 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3499 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3502 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3503 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3507 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
||
3508 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
3510 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3511 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3513 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3514 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3516 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
3517 httpSetField(http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
3519 #endif /* HAVE_SSL */
3522 httpSetField(http
, HTTP_FIELD_SERVER
,
3523 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3526 * Set the Accept-Encoding field if it isn't already...
3529 if (!http
->accept_encoding
)
3530 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3531 http
->default_accept_encoding
? http
->default_accept_encoding
:
3533 "gzip, deflate, identity");
3536 #endif /* HAVE_LIBZ */
3539 * Send the response header...
3542 old_encoding
= http
->data_encoding
;
3543 old_remaining
= http
->data_remaining
;
3544 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3546 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3547 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3549 http
->status
= HTTP_STATUS_ERROR
;
3553 if (status
!= HTTP_STATUS_CONTINUE
)
3556 * 100 Continue doesn't have the rest of the response headers...
3559 int i
; /* Looping var */
3560 const char *value
; /* Field value */
3562 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3564 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3566 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3568 http
->status
= HTTP_STATUS_ERROR
;
3576 if (httpPrintf(http
, "Set-Cookie: %s path=/ httponly%s\r\n",
3577 http
->cookie
, http
->tls
? " secure" : "") < 1)
3579 http
->status
= HTTP_STATUS_ERROR
;
3585 if (httpWrite2(http
, "\r\n", 2) < 2)
3587 http
->status
= HTTP_STATUS_ERROR
;
3591 if (httpFlushWrite(http
) < 0)
3593 http
->status
= HTTP_STATUS_ERROR
;
3597 if (status
== HTTP_STATUS_CONTINUE
||
3598 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
3601 * Restore the old data_encoding and data_length values...
3604 http
->data_encoding
= old_encoding
;
3605 http
->data_remaining
= old_remaining
;
3607 if (old_remaining
<= INT_MAX
)
3608 http
->_data_remaining
= (int)old_remaining
;
3610 http
->_data_remaining
= INT_MAX
;
3612 else if (http
->state
== HTTP_STATE_OPTIONS
||
3613 http
->state
== HTTP_STATE_HEAD
||
3614 http
->state
== HTTP_STATE_PUT
||
3615 http
->state
== HTTP_STATE_TRACE
||
3616 http
->state
== HTTP_STATE_CONNECT
||
3617 http
->state
== HTTP_STATE_STATUS
)
3619 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3620 "was %s.", httpStateString(http
->state
)));
3621 http
->state
= HTTP_STATE_WAITING
;
3626 * Force data_encoding and data_length to be set according to the response
3630 http_set_length(http
);
3632 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0)
3634 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3635 "was %s.", httpStateString(http
->state
)));
3636 http
->state
= HTTP_STATE_WAITING
;
3642 * Then start any content encoding...
3645 DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
3646 http_content_coding_start(http
,
3647 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
3648 #endif /* HAVE_LIBZ */
3658 * 'http_content_coding_finish()' - Finish doing any content encoding.
3662 http_content_coding_finish(
3663 http_t
*http
) /* I - HTTP connection */
3665 int zerr
; /* Compression status */
3666 Byte dummy
[1]; /* Dummy read buffer */
3669 switch (http
->coding
)
3671 case _HTTP_CODING_DEFLATE
:
3672 case _HTTP_CODING_GZIP
:
3673 http
->stream
.next_in
= dummy
;
3674 http
->stream
.avail_in
= 0;
3678 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3679 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3681 zerr
= deflate(&(http
->stream
), Z_FINISH
);
3683 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3684 if (http
->wused
== sizeof(http
->wbuffer
))
3685 httpFlushWrite(http
);
3687 while (zerr
== Z_OK
);
3689 deflateEnd(&(http
->stream
));
3692 httpFlushWrite(http
);
3695 case _HTTP_CODING_INFLATE
:
3696 case _HTTP_CODING_GUNZIP
:
3697 inflateEnd(&(http
->stream
));
3698 free(http
->dbuffer
);
3699 http
->dbuffer
= NULL
;
3706 http
->coding
= _HTTP_CODING_IDENTITY
;
3711 * 'http_content_coding_start()' - Start doing content encoding.
3715 http_content_coding_start(
3716 http_t
*http
, /* I - HTTP connection */
3717 const char *value
) /* I - Value of Content-Encoding */
3719 int zerr
; /* Error/status */
3720 _http_coding_t coding
; /* Content coding value */
3723 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
3726 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
3728 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
3732 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
3734 if (http
->state
== HTTP_STATE_GET_SEND
||
3735 http
->state
== HTTP_STATE_POST_SEND
)
3736 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
3737 _HTTP_CODING_GUNZIP
;
3738 else if (http
->state
== HTTP_STATE_POST_RECV
||
3739 http
->state
== HTTP_STATE_PUT_RECV
)
3740 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
3741 _HTTP_CODING_GUNZIP
;
3744 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3748 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
3750 if (http
->state
== HTTP_STATE_GET_SEND
||
3751 http
->state
== HTTP_STATE_POST_SEND
)
3752 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
3753 _HTTP_CODING_INFLATE
;
3754 else if (http
->state
== HTTP_STATE_POST_RECV
||
3755 http
->state
== HTTP_STATE_PUT_RECV
)
3756 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
3757 _HTTP_CODING_INFLATE
;
3760 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3766 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3770 memset(&(http
->stream
), 0, sizeof(http
->stream
));
3774 case _HTTP_CODING_DEFLATE
:
3775 case _HTTP_CODING_GZIP
:
3777 httpFlushWrite(http
);
3780 * Window size for compression is 11 bits - optimal based on PWG Raster
3781 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
3785 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
3787 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
3788 Z_DEFAULT_STRATEGY
)) < Z_OK
)
3790 http
->status
= HTTP_STATUS_ERROR
;
3791 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
3796 case _HTTP_CODING_INFLATE
:
3797 case _HTTP_CODING_GUNZIP
:
3798 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
3800 http
->status
= HTTP_STATUS_ERROR
;
3801 http
->error
= errno
;
3806 * Window size for decompression is up to 15 bits (maximum supported).
3807 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
3810 if ((zerr
= inflateInit2(&(http
->stream
),
3811 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
3814 free(http
->dbuffer
);
3815 http
->dbuffer
= NULL
;
3816 http
->status
= HTTP_STATUS_ERROR
;
3817 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
3821 http
->stream
.avail_in
= 0;
3822 http
->stream
.next_in
= http
->dbuffer
;
3829 http
->coding
= coding
;
3831 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
3834 #endif /* HAVE_LIBZ */
3838 * 'http_create()' - Create an unconnected HTTP connection.
3841 static http_t
* /* O - HTTP connection */
3843 const char *host
, /* I - Hostname */
3844 int port
, /* I - Port number */
3845 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
3846 int family
, /* I - Address family or AF_UNSPEC */
3847 http_encryption_t encryption
, /* I - Encryption to use */
3848 int blocking
, /* I - 1 for blocking mode */
3849 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
3851 http_t
*http
; /* New HTTP connection */
3852 char service
[255]; /* Service name */
3853 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
3856 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
3857 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
3858 family
, encryption
, blocking
, mode
));
3860 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
3866 * Lookup the host...
3871 myaddrlist
= httpAddrCopyList(addrlist
);
3875 snprintf(service
, sizeof(service
), "%d", port
);
3877 myaddrlist
= httpAddrGetList(host
, family
, service
);
3884 * Allocate memory for the structure...
3887 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
3889 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
3890 httpAddrFreeList(addrlist
);
3895 * Initialize the HTTP data...
3899 http
->activity
= time(NULL
);
3900 http
->addrlist
= myaddrlist
;
3901 http
->blocking
= blocking
;
3904 http
->gssctx
= GSS_C_NO_CONTEXT
;
3905 http
->gssname
= GSS_C_NO_NAME
;
3906 #endif /* HAVE_GSSAPI */
3907 http
->status
= HTTP_STATUS_CONTINUE
;
3908 http
->version
= HTTP_VERSION_1_1
;
3911 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
3913 if (port
== 443) /* Always use encryption for https */
3914 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
3916 http
->encryption
= encryption
;
3918 http_set_wait(http
);
3921 * Return the new structure...
3930 * 'http_debug_hex()' - Do a hex dump of a buffer.
3934 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3935 const char *buffer
, /* I - Buffer to dump */
3936 int bytes
) /* I - Bytes to dump */
3938 int i
, j
, /* Looping vars */
3939 ch
; /* Current character */
3940 char line
[255], /* Line buffer */
3941 *start
, /* Start of line after prefix */
3942 *ptr
; /* Pointer into line */
3945 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3948 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
3950 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3951 start
= line
+ strlen(line
);
3953 for (i
= 0; i
< bytes
; i
+= 16)
3955 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3956 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3960 memcpy(ptr
, " ", 3);
3965 memcpy(ptr
, " ", 3);
3968 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3970 ch
= buffer
[i
+ j
] & 255;
3972 if (ch
< ' ' || ch
>= 127)
3986 * 'http_read()' - Read a buffer from a HTTP connection.
3988 * This function does the low-level read from the socket, retrying and timing
3992 static ssize_t
/* O - Number of bytes read or -1 on error */
3993 http_read(http_t
*http
, /* I - HTTP connection */
3994 char *buffer
, /* I - Buffer */
3995 size_t length
) /* I - Maximum bytes to read */
3997 ssize_t bytes
; /* Bytes read */
4000 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4001 buffer
, CUPS_LLCAST length
));
4003 if (!http
->blocking
)
4005 while (!httpWait(http
, http
->wait_value
))
4007 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4010 DEBUG_puts("2http_read: Timeout.");
4015 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4021 bytes
= http_tls_read(http
, buffer
, length
);
4023 #endif /* HAVE_SSL */
4024 bytes
= recv(http
->fd
, buffer
, length
, 0);
4029 if (WSAGetLastError() != WSAEINTR
)
4031 http
->error
= WSAGetLastError();
4034 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4036 if (!http
->timeout_cb
||
4037 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4039 http
->error
= WSAEWOULDBLOCK
;
4044 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4046 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4048 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4050 http
->error
= errno
;
4053 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4055 http
->error
= errno
;
4059 else if (errno
!= EINTR
)
4061 http
->error
= errno
;
4069 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4070 CUPS_LLCAST bytes
));
4073 http_debug_hex("http_read", buffer
, (int)bytes
);
4079 if (WSAGetLastError() == WSAEINTR
)
4082 http
->error
= WSAGetLastError();
4084 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4087 http
->error
= errno
;
4090 else if (bytes
== 0)
4092 http
->error
= EPIPE
;
4101 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4103 * This function reads data from the HTTP buffer or from the socket, as needed.
4106 static ssize_t
/* O - Number of bytes read or -1 on error */
4107 http_read_buffered(http_t
*http
, /* I - HTTP connection */
4108 char *buffer
, /* I - Buffer */
4109 size_t length
) /* I - Maximum bytes to read */
4111 ssize_t bytes
; /* Bytes read */
4114 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4116 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4120 if (length
> (size_t)http
->used
)
4121 bytes
= (size_t)http
->used
;
4125 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4128 memcpy(buffer
, http
->buffer
, bytes
);
4129 http
->used
-= (int)bytes
;
4132 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4135 bytes
= http_read(http
, buffer
, length
);
4142 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4144 * This function reads and validates the chunk length, then does a buffered read
4145 * returning the number of bytes placed in the buffer.
4148 static ssize_t
/* O - Number of bytes read or -1 on error */
4149 http_read_chunk(http_t
*http
, /* I - HTTP connection */
4150 char *buffer
, /* I - Buffer */
4151 size_t length
) /* I - Maximum bytes to read */
4153 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4154 http
, buffer
, CUPS_LLCAST length
));
4156 if (http
->data_remaining
<= 0)
4158 char len
[32]; /* Length string */
4160 if (!httpGets(len
, sizeof(len
), http
))
4162 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4168 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4169 if (!httpGets(len
, sizeof(len
), http
))
4171 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4176 http
->data_remaining
= strtoll(len
, NULL
, 16);
4178 if (http
->data_remaining
< 0)
4180 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4181 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4185 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4186 len
, CUPS_LLCAST http
->data_remaining
));
4188 if (http
->data_remaining
== 0)
4191 * 0-length chunk, grab trailing blank line...
4194 httpGets(len
, sizeof(len
), http
);
4198 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4199 CUPS_LLCAST http
->data_remaining
));
4201 if (http
->data_remaining
<= 0)
4203 else if (length
> (size_t)http
->data_remaining
)
4204 length
= (size_t)http
->data_remaining
;
4206 return (http_read_buffered(http
, buffer
, length
));
4211 * 'http_send()' - Send a request with all fields and the trailing blank line.
4214 static int /* O - 0 on success, non-zero on error */
4215 http_send(http_t
*http
, /* I - HTTP connection */
4216 http_state_t request
, /* I - Request code */
4217 const char *uri
) /* I - URI */
4219 int i
; /* Looping var */
4220 char buf
[1024]; /* Encoded URI buffer */
4221 const char *value
; /* Field value */
4222 static const char * const codes
[] = /* Request code strings */
4242 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4243 http
, codes
[request
], uri
));
4245 if (http
== NULL
|| uri
== NULL
)
4249 * Set the User-Agent field if it isn't already...
4252 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4254 if (http
->default_user_agent
)
4255 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4257 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4261 * Set the Accept-Encoding field if it isn't already...
4264 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4265 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4266 http
->default_accept_encoding
);
4269 * Encode the URI as needed...
4272 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4275 * See if we had an error the last time around; if so, reconnect...
4278 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4279 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4281 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4282 http
->fd
, http
->status
, http
->tls_upgrade
));
4284 if (httpReconnect2(http
, 30000, NULL
))
4289 * Flush any written data that is pending...
4294 if (httpFlushWrite(http
) < 0)
4295 if (httpReconnect2(http
, 30000, NULL
))
4300 * Send the request header...
4303 http
->state
= request
;
4304 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4306 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4309 http
->status
= HTTP_STATUS_CONTINUE
;
4312 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4314 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4315 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4317 #endif /* HAVE_SSL */
4319 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4321 http
->status
= HTTP_STATUS_ERROR
;
4325 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4326 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4328 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
4330 if (i
== HTTP_FIELD_HOST
)
4332 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4333 httpAddrPort(http
->hostaddr
)) < 1)
4335 http
->status
= HTTP_STATUS_ERROR
;
4339 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4341 http
->status
= HTTP_STATUS_ERROR
;
4347 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4349 http
->status
= HTTP_STATUS_ERROR
;
4353 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
4354 http
->mode
, http
->state
));
4356 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4357 (http
->state
== HTTP_STATE_POST_RECV
||
4358 http
->state
== HTTP_STATE_PUT_RECV
))
4359 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4361 http
->status
= HTTP_STATUS_ERROR
;
4365 if (httpPrintf(http
, "\r\n") < 1)
4367 http
->status
= HTTP_STATUS_ERROR
;
4371 if (httpFlushWrite(http
) < 0)
4374 http_set_length(http
);
4375 httpClearFields(http
);
4378 * The Kerberos and AuthRef authentication strings can only be used once...
4381 if (http
->field_authorization
&& http
->authstring
&&
4382 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4383 !strncmp(http
->authstring
, "AuthRef", 7)))
4385 http
->_authstring
[0] = '\0';
4387 if (http
->authstring
!= http
->_authstring
)
4388 free(http
->authstring
);
4390 http
->authstring
= http
->_authstring
;
4398 * 'http_set_length()' - Set the data_encoding and data_remaining values.
4401 static off_t
/* O - Remainder or -1 on error */
4402 http_set_length(http_t
*http
) /* I - Connection */
4404 off_t remaining
; /* Remainder */
4407 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
4408 httpStateString(http
->state
)));
4410 if ((remaining
= httpGetLength2(http
)) >= 0)
4412 if (http
->mode
== _HTTP_MODE_SERVER
&&
4413 http
->state
!= HTTP_STATE_GET_SEND
&&
4414 http
->state
!= HTTP_STATE_PUT
&&
4415 http
->state
!= HTTP_STATE_POST
&&
4416 http
->state
!= HTTP_STATE_POST_SEND
)
4418 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
4422 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
4425 DEBUG_puts("1http_set_length: Setting data_encoding to "
4426 "HTTP_ENCODING_CHUNKED.");
4427 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
4431 DEBUG_puts("1http_set_length: Setting data_encoding to "
4432 "HTTP_ENCODING_LENGTH.");
4433 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4436 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
4437 CUPS_LLCAST remaining
));
4438 http
->data_remaining
= remaining
;
4440 if (remaining
<= INT_MAX
)
4441 http
->_data_remaining
= remaining
;
4443 http
->_data_remaining
= INT_MAX
;
4450 * 'http_set_timeout()' - Set the socket timeout values.
4454 http_set_timeout(int fd
, /* I - File descriptor */
4455 double timeout
) /* I - Timeout in seconds */
4458 DWORD tv
= (DWORD
)(timeout
* 1000);
4459 /* Timeout in milliseconds */
4461 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4462 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4465 struct timeval tv
; /* Timeout in secs and usecs */
4467 tv
.tv_sec
= (int)timeout
;
4468 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
4470 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4471 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4477 * 'http_set_wait()' - Set the default wait value for reads.
4481 http_set_wait(http_t
*http
) /* I - HTTP connection */
4485 http
->wait_value
= (int)(http
->timeout_value
* 1000);
4487 if (http
->wait_value
<= 0)
4488 http
->wait_value
= 60000;
4491 http
->wait_value
= 10000;
4497 * 'http_tls_upgrade()' - Force upgrade to TLS encryption.
4500 static int /* O - Status of connection */
4501 http_tls_upgrade(http_t
*http
) /* I - HTTP connection */
4503 int ret
; /* Return value */
4504 http_t myhttp
; /* Local copy of HTTP data */
4507 DEBUG_printf(("7http_tls_upgrade(%p)", http
));
4510 * Flush the connection to make sure any previous "Upgrade" message
4517 * Copy the HTTP data to a local variable so we can do the OPTIONS
4518 * request without interfering with the existing request data...
4521 memcpy(&myhttp
, http
, sizeof(myhttp
));
4524 * Send an OPTIONS request to the server, requiring SSL or TLS
4525 * encryption on the link...
4528 http
->tls_upgrade
= 1;
4529 http
->field_authorization
= NULL
; /* Don't free the auth string */
4531 httpClearFields(http
);
4532 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4533 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4535 if ((ret
= httpOptions(http
, "*")) == 0)
4538 * Wait for the secure connection...
4541 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
4545 * Restore the HTTP request data...
4548 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4549 http
->data_encoding
= myhttp
.data_encoding
;
4550 http
->data_remaining
= myhttp
.data_remaining
;
4551 http
->_data_remaining
= myhttp
._data_remaining
;
4552 http
->expect
= myhttp
.expect
;
4553 http
->field_authorization
= myhttp
.field_authorization
;
4554 http
->digest_tries
= myhttp
.digest_tries
;
4555 http
->tls_upgrade
= 0;
4558 * See if we actually went secure...
4564 * Server does not support HTTP upgrade...
4567 DEBUG_puts("8http_tls_upgrade: Server does not support HTTP upgrade!");
4569 httpAddrClose(NULL
, http
->fd
);
4578 #endif /* HAVE_SSL */
4582 * 'http_write()' - Write a buffer to a HTTP connection.
4585 static ssize_t
/* O - Number of bytes written */
4586 http_write(http_t
*http
, /* I - HTTP connection */
4587 const char *buffer
, /* I - Buffer for data */
4588 size_t length
) /* I - Number of bytes to write */
4590 ssize_t tbytes
, /* Total bytes sent */
4591 bytes
; /* Bytes sent */
4594 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4595 buffer
, CUPS_LLCAST length
));
4601 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
4603 if (http
->timeout_cb
)
4606 struct pollfd pfd
; /* Polled file descriptor */
4608 fd_set output_set
; /* Output ready for write? */
4609 struct timeval timeout
; /* Timeout value */
4610 #endif /* HAVE_POLL */
4611 int nfds
; /* Result from select()/poll() */
4617 pfd
.events
= POLLOUT
;
4619 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
4620 (errno
== EINTR
|| errno
== EAGAIN
))
4626 FD_ZERO(&output_set
);
4627 FD_SET(http
->fd
, &output_set
);
4629 timeout
.tv_sec
= http
->wait_value
/ 1000;
4630 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
4632 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
4635 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
4636 WSAGetLastError() == WSAEWOULDBLOCK
));
4638 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
4640 #endif /* HAVE_POLL */
4644 http
->error
= errno
;
4647 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4650 http
->error
= WSAEWOULDBLOCK
;
4652 http
->error
= EWOULDBLOCK
;
4662 bytes
= http_tls_write(http
, buffer
, length
);
4664 #endif /* HAVE_SSL */
4665 bytes
= send(http
->fd
, buffer
, length
, 0);
4667 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
4668 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
4673 if (WSAGetLastError() == WSAEINTR
)
4675 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4677 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4680 http
->error
= WSAGetLastError();
4682 else if (WSAGetLastError() != http
->error
&&
4683 WSAGetLastError() != WSAECONNRESET
)
4685 http
->error
= WSAGetLastError();
4692 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4694 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4696 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4699 http
->error
= errno
;
4701 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4703 http
->error
= errno
;
4708 DEBUG_printf(("3http_write: error writing data (%s).",
4709 strerror(http
->error
)));
4720 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4723 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
4730 * 'http_write_chunk()' - Write a chunked buffer.
4733 static ssize_t
/* O - Number bytes written */
4734 http_write_chunk(http_t
*http
, /* I - HTTP connection */
4735 const char *buffer
, /* I - Buffer to write */
4736 size_t length
) /* I - Length of buffer */
4738 char header
[16]; /* Chunk header */
4739 ssize_t bytes
; /* Bytes written */
4742 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4743 http
, buffer
, CUPS_LLCAST length
));
4746 * Write the chunk header, data, and trailer.
4749 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
4750 if (http_write(http
, header
, strlen(header
)) < 0)
4752 DEBUG_puts("8http_write_chunk: http_write of length failed.");
4756 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4758 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
4762 if (http_write(http
, "\r\n", 2) < 0)
4764 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");