4 * HTTP routines for CUPS.
6 * Copyright 2007-2013 by Apple Inc.
7 * Copyright 1997-2007 by Easy Software Products, all rights reserved.
9 * This file contains Kerberos support code, copyright 2006 by
12 * These coded instructions, statements, and computer programs are the
13 * property of Apple Inc. and are protected by Federal copyright
14 * law. Distribution and use rights are outlined in the file "LICENSE.txt"
15 * which should have been included with this file. If this file is
16 * file is missing or damaged, see the license at "http://www.cups.org/".
18 * This file is subject to the Apple OS-Developed Software exception.
22 * Include necessary headers...
25 #include "cups-private.h"
32 # include <sys/time.h>
33 # include <sys/resource.h>
37 #endif /* HAVE_POLL */
45 static void http_content_coding_finish(http_t
*http
);
46 static void http_content_coding_start(http_t
*http
,
48 #endif /* HAVE_LIBZ */
49 static http_t
*http_create(const char *host
, int port
,
50 http_addrlist_t
*addrlist
, int family
,
51 http_encryption_t encryption
,
52 int blocking
, _http_mode_t mode
);
54 static void http_debug_hex(const char *prefix
, const char *buffer
,
57 static ssize_t
http_read(http_t
*http
, char *buffer
, size_t length
);
58 static ssize_t
http_read_buffered(http_t
*http
, char *buffer
, size_t length
);
59 static ssize_t
http_read_chunk(http_t
*http
, char *buffer
, size_t length
);
60 static int http_send(http_t
*http
, http_state_t request
,
62 static ssize_t
http_write(http_t
*http
, const char *buffer
,
64 static ssize_t
http_write_chunk(http_t
*http
, const char *buffer
,
66 static off_t
http_set_length(http_t
*http
);
67 static void http_set_timeout(int fd
, double timeout
);
68 static void http_set_wait(http_t
*http
);
71 static size_t http_tls_pending(http_t
*http
);
72 static int http_tls_read(http_t
*http
, char *buf
, int len
);
73 static int http_tls_set_credentials(http_t
*http
);
74 static int http_tls_start(http_t
*http
);
75 static void http_tls_stop(http_t
*http
);
76 static int http_tls_upgrade(http_t
*http
);
77 static int http_tls_write(http_t
*http
, const char *buf
, int len
);
79 # include "tls-openssl.c"
80 # elif defined(HAVE_GNUTLS)
81 # include "tls-gnutls.c"
82 # elif defined(HAVE_CDSASSL)
83 # include "tls-darwin.c"
85 # include "tls-sspi.c"
86 # endif /* HAVE_LIBSSL */
94 static const char * const http_fields
[] =
111 "If-Unmodified-since",
130 * 'httpAcceptConnection()' - Accept a new HTTP client connection from the
131 * specified listening socket.
133 * @since CUPS 1.7/OS X 10.9@
136 http_t
* /* O - HTTP connection or @code NULL@ */
137 httpAcceptConnection(int fd
, /* I - Listen socket file descriptor */
138 int blocking
) /* I - 1 if the connection should be
139 blocking, 0 otherwise */
141 http_t
*http
; /* HTTP connection */
142 http_addrlist_t addrlist
; /* Dummy address list */
143 socklen_t addrlen
; /* Length of address */
144 int val
; /* Socket option value */
148 * Range check input...
155 * Create the client connection...
158 memset(&addrlist
, 0, sizeof(addrlist
));
160 if ((http
= http_create(NULL
, 0, &addrlist
, AF_UNSPEC
,
161 HTTP_ENCRYPTION_IF_REQUESTED
, blocking
,
162 _HTTP_MODE_SERVER
)) == NULL
)
166 * Accept the client and get the remote address...
169 addrlen
= sizeof(http_addr_t
);
171 if ((http
->fd
= accept(fd
, (struct sockaddr
*)&(http
->addrlist
->addr
),
174 _cupsSetHTTPError(HTTP_STATUS_ERROR
);
180 http
->hostaddr
= &(http
->addrlist
->addr
);
182 if (httpAddrLocalhost(http
->hostaddr
))
183 strlcpy(http
->hostname
, "localhost", sizeof(http
->hostname
));
185 httpAddrString(http
->hostaddr
, http
->hostname
, sizeof(http
->hostname
));
189 * Disable SIGPIPE for this socket.
193 setsockopt(http
->fd
, SOL_SOCKET
, SO_NOSIGPIPE
, CUPS_SOCAST
&val
, sizeof(val
));
194 #endif /* SO_NOSIGPIPE */
197 * Using TCP_NODELAY improves responsiveness, especially on systems
198 * with a slow loopback interface. Since we write large buffers
199 * when sending print files and requests, there shouldn't be any
200 * performance penalty for this...
204 setsockopt(http
->fd
, IPPROTO_TCP
, TCP_NODELAY
, CUPS_SOCAST
&val
, sizeof(val
));
208 * Close this socket when starting another process...
211 fcntl(http
->fd
, F_SETFD
, FD_CLOEXEC
);
212 #endif /* FD_CLOEXEC */
219 * 'httpAddCredential()' - Allocates and adds a single credential to an array.
221 * Use @code cupsArrayNew(NULL, NULL)@ to create a credentials array.
223 * @since CUPS 1.5/OS X 10.7@
226 int /* O - 0 on success, -1 on error */
228 cups_array_t
*credentials
, /* I - Credentials array */
229 const void *data
, /* I - PEM-encoded X.509 data */
230 size_t datalen
) /* I - Length of data */
232 http_credential_t
*credential
; /* Credential data */
235 if ((credential
= malloc(sizeof(http_credential_t
))) != NULL
)
237 credential
->datalen
= datalen
;
239 if ((credential
->data
= malloc(datalen
)) != NULL
)
241 memcpy(credential
->data
, data
, datalen
);
242 cupsArrayAdd(credentials
, credential
);
254 * 'httpBlocking()' - Set blocking/non-blocking behavior on a connection.
258 httpBlocking(http_t
*http
, /* I - HTTP connection */
259 int b
) /* I - 1 = blocking, 0 = non-blocking */
270 * 'httpCheck()' - Check to see if there is a pending response from the server.
273 int /* O - 0 = no data, 1 = data available */
274 httpCheck(http_t
*http
) /* I - HTTP connection */
276 return (httpWait(http
, 0));
281 * 'httpClearCookie()' - Clear the cookie value(s).
283 * @since CUPS 1.1.19/OS X 10.3@
287 httpClearCookie(http_t
*http
) /* I - HTTP connection */
301 * 'httpClearFields()' - Clear HTTP request fields.
305 httpClearFields(http_t
*http
) /* I - HTTP connection */
307 DEBUG_printf(("httpClearFields(http=%p)", http
));
311 memset(http
->fields
, 0, sizeof(http
->fields
));
313 if (http
->mode
== _HTTP_MODE_CLIENT
)
315 if (http
->hostname
[0] == '/')
316 httpSetField(http
, HTTP_FIELD_HOST
, "localhost");
318 httpSetField(http
, HTTP_FIELD_HOST
, http
->hostname
);
321 if (http
->field_authorization
)
323 free(http
->field_authorization
);
324 http
->field_authorization
= NULL
;
327 if (http
->accept_encoding
)
329 _cupsStrFree(http
->accept_encoding
);
330 http
->accept_encoding
= NULL
;
335 _cupsStrFree(http
->allow
);
341 _cupsStrFree(http
->server
);
345 http
->expect
= (http_status_t
)0;
351 * 'httpClose()' - Close an HTTP connection.
355 httpClose(http_t
*http
) /* I - HTTP connection */
358 OM_uint32 minor_status
; /* Minor status code */
359 #endif /* HAVE_GSSAPI */
362 DEBUG_printf(("httpClose(http=%p)", http
));
365 * Range check input...
372 * Close any open connection...
375 _httpDisconnect(http
);
378 * Free memory used...
381 httpAddrFreeList(http
->addrlist
);
387 if (http
->gssctx
!= GSS_C_NO_CONTEXT
)
388 gss_delete_sec_context(&minor_status
, &http
->gssctx
, GSS_C_NO_BUFFER
);
390 if (http
->gssname
!= GSS_C_NO_NAME
)
391 gss_release_name(&minor_status
, &http
->gssname
);
392 #endif /* HAVE_GSSAPI */
394 #ifdef HAVE_AUTHORIZATION_H
396 AuthorizationFree(http
->auth_ref
, kAuthorizationFlagDefaults
);
397 #endif /* HAVE_AUTHORIZATION_H */
399 httpClearFields(http
);
401 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
402 free(http
->authstring
);
409 * 'httpConnect()' - Connect to a HTTP server.
411 * This function is deprecated - use @link httpConnect2@ instead.
416 http_t
* /* O - New HTTP connection */
417 httpConnect(const char *host
, /* I - Host to connect to */
418 int port
) /* I - Port number */
420 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
,
421 HTTP_ENCRYPTION_IF_REQUESTED
, 1, 30000, NULL
));
426 * 'httpConnect2()' - Connect to a HTTP server.
428 * @since CUPS 1.7/OS X 10.9@
431 http_t
* /* O - New HTTP connection */
433 const char *host
, /* I - Host to connect to */
434 int port
, /* I - Port number */
435 http_addrlist_t
*addrlist
, /* I - List of addresses or NULL to lookup */
436 int family
, /* I - Address family to use or @code AF_UNSPEC@ for any */
437 http_encryption_t encryption
, /* I - Type of encryption to use */
438 int blocking
, /* I - 1 for blocking connection, 0 for non-blocking */
439 int msec
, /* I - Connection timeout in milliseconds, 0 means don't connect */
440 int *cancel
) /* I - Pointer to "cancel" variable */
442 http_t
*http
; /* New HTTP connection */
445 DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, "
446 "encryption=%d, blocking=%d, msec=%d, cancel=%p)", host
, port
,
447 addrlist
, family
, encryption
, blocking
, msec
, cancel
));
450 * Create the HTTP structure...
453 if ((http
= http_create(host
, port
, addrlist
, family
, encryption
, blocking
,
454 _HTTP_MODE_CLIENT
)) == NULL
)
458 * Optionally connect to the remote system...
461 if (msec
== 0 || !httpReconnect2(http
, msec
, cancel
))
465 * Could not connect to any known address - bail out!
475 * 'httpConnectEncrypt()' - Connect to a HTTP server using encryption.
477 * This function is now deprecated. Please use the @link httpConnect2@ function
483 http_t
* /* O - New HTTP connection */
485 const char *host
, /* I - Host to connect to */
486 int port
, /* I - Port number */
487 http_encryption_t encryption
) /* I - Type of encryption to use */
489 DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
490 host
, port
, encryption
));
492 return (httpConnect2(host
, port
, NULL
, AF_UNSPEC
, encryption
, 1, 30000,
498 * 'httpDelete()' - Send a DELETE request to the server.
501 int /* O - Status of call (0 = success) */
502 httpDelete(http_t
*http
, /* I - HTTP connection */
503 const char *uri
) /* I - URI to delete */
505 return (http_send(http
, HTTP_STATE_DELETE
, uri
));
510 * '_httpDisconnect()' - Disconnect a HTTP connection.
514 _httpDisconnect(http_t
*http
) /* I - HTTP connection */
519 #endif /* HAVE_SSL */
521 httpAddrClose(NULL
, http
->fd
);
528 * 'httpEncryption()' - Set the required encryption on the link.
531 int /* O - -1 on error, 0 on success */
532 httpEncryption(http_t
*http
, /* I - HTTP connection */
533 http_encryption_t e
) /* I - New encryption preference */
535 DEBUG_printf(("httpEncryption(http=%p, e=%d)", http
, e
));
541 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
));
551 if (e
== HTTP_ENCRYPTION_ALWAYS
|| e
== HTTP_ENCRYPTION_REQUIRED
)
555 #endif /* HAVE_SSL */
560 * 'httpError()' - Get the last error on a connection.
563 int /* O - Error code (errno) value */
564 httpError(http_t
*http
) /* I - HTTP connection */
567 return (http
->error
);
574 * 'httpFieldValue()' - Return the HTTP field enumeration value for a field
578 http_field_t
/* O - Field index */
579 httpFieldValue(const char *name
) /* I - String name */
581 int i
; /* Looping var */
584 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
585 if (!_cups_strcasecmp(name
, http_fields
[i
]))
586 return ((http_field_t
)i
);
588 return (HTTP_FIELD_UNKNOWN
);
593 * 'httpFlush()' - Flush data from a HTTP connection.
597 httpFlush(http_t
*http
) /* I - HTTP connection */
599 char buffer
[8192]; /* Junk buffer */
600 int blocking
; /* To block or not to block */
601 http_state_t oldstate
; /* Old state */
604 DEBUG_printf(("httpFlush(http=%p), state=%s", http
,
605 httpStateString(http
->state
)));
608 * Nothing to do if we are in the "waiting" state...
611 if (http
->state
== HTTP_STATE_WAITING
)
615 * Temporarily set non-blocking mode so we don't get stuck in httpRead()...
618 blocking
= http
->blocking
;
622 * Read any data we can...
625 oldstate
= http
->state
;
626 while (httpRead2(http
, buffer
, sizeof(buffer
)) > 0);
629 * Restore blocking and reset the connection if we didn't get all of
630 * the remaining data...
633 http
->blocking
= blocking
;
635 if (http
->state
== oldstate
&& http
->state
!= HTTP_STATE_WAITING
&&
639 * Didn't get the data back, so close the current connection.
644 http_content_coding_finish(http
);
645 #endif /* HAVE_LIBZ */
647 DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
649 http
->state
= HTTP_STATE_WAITING
;
654 #endif /* HAVE_SSL */
656 httpAddrClose(NULL
, http
->fd
);
664 * 'httpFlushWrite()' - Flush data in write buffer.
666 * @since CUPS 1.2/OS X 10.5@
669 int /* O - Bytes written or -1 on error */
670 httpFlushWrite(http_t
*http
) /* I - HTTP connection */
672 int bytes
; /* Bytes written */
675 DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", http
,
676 http
? http
->data_encoding
: -1));
678 if (!http
|| !http
->wused
)
680 DEBUG_puts(http
? "1httpFlushWrite: Write buffer is empty." :
681 "1httpFlushWrite: No connection.");
685 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
686 bytes
= http_write_chunk(http
, http
->wbuffer
, http
->wused
);
688 bytes
= http_write(http
, http
->wbuffer
, http
->wused
);
692 DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes
, errno
));
699 * 'httpFreeCredentials()' - Free an array of credentials.
704 cups_array_t
*credentials
) /* I - Array of credentials */
706 http_credential_t
*credential
; /* Credential */
709 for (credential
= (http_credential_t
*)cupsArrayFirst(credentials
);
711 credential
= (http_credential_t
*)cupsArrayNext(credentials
))
713 cupsArrayRemove(credentials
, credential
);
714 free((void *)credential
->data
);
718 cupsArrayDelete(credentials
);
723 * 'httpGet()' - Send a GET request to the server.
726 int /* O - Status of call (0 = success) */
727 httpGet(http_t
*http
, /* I - HTTP connection */
728 const char *uri
) /* I - URI to get */
730 return (http_send(http
, HTTP_STATE_GET
, uri
));
735 * 'httpGetActivity()' - Get the most recent activity for a connection.
737 * The return value is the UNIX time of the last read or write.
742 time_t /* O - Time of last read or write */
743 httpGetActivity(http_t
*http
) /* I - HTTP connection */
745 return (http
? http
->activity
: 0);
750 * 'httpGetAuthString()' - Get the current authorization string.
752 * The authorization string is set by cupsDoAuthentication() and
753 * httpSetAuthString(). Use httpGetAuthString() to retrieve the
754 * string to use with httpSetField() for the HTTP_FIELD_AUTHORIZATION
757 * @since CUPS 1.3/OS X 10.5@
760 char * /* O - Authorization string */
761 httpGetAuthString(http_t
*http
) /* I - HTTP connection */
764 return (http
->authstring
);
771 * 'httpGetBlocking()' - Get the blocking/non-block state of a connection.
773 * @since CUPS 1.2/OS X 10.5@
776 int /* O - 1 if blocking, 0 if non-blocking */
777 httpGetBlocking(http_t
*http
) /* I - HTTP connection */
779 return (http
? http
->blocking
: 0);
784 * 'httpGetContentEncoding()' - Get a common content encoding, if any, between
785 * the client and server.
787 * This function uses the value of the Accepts-Encoding HTTP header and must be
788 * called after receiving a response from the server or a request from the
789 * client. The value returned can be use in subsequent requests (for clients)
790 * or in the response (for servers) in order to compress the content stream.
792 * @since CUPS 1.7/OS X 10.9@
795 const char * /* O - Content-Coding value or
796 @code NULL@ for the identity
798 httpGetContentEncoding(http_t
*http
) /* I - HTTP connection */
801 if (http
&& http
->accept_encoding
)
803 int i
; /* Looping var */
804 char temp
[HTTP_MAX_VALUE
], /* Copy of Accepts-Encoding value */
805 *start
, /* Start of coding value */
806 *end
; /* End of coding value */
807 double qvalue
; /* "qvalue" for coding */
808 struct lconv
*loc
= localeconv(); /* Locale data */
809 static const char * const codings
[] =
810 { /* Supported content codings */
817 strlcpy(temp
, http
->accept_encoding
, sizeof(temp
));
819 for (start
= temp
; *start
; start
= end
)
822 * Find the end of the coding name...
827 while (*end
&& *end
!= ';' && *end
!= ',' && !isspace(*end
& 255))
833 * Grab the qvalue as needed...
836 if (!strncmp(end
, ";q=", 3))
837 qvalue
= _cupsStrScand(end
+ 3, NULL
, loc
);
840 * Skip past all attributes...
844 while (*end
&& *end
!= ',' && !isspace(*end
& 255))
850 while (*end
&& isspace(*end
& 255))
854 * Check value if it matches something we support...
860 for (i
= 0; i
< (int)(sizeof(codings
) / sizeof(codings
[0])); i
++)
861 if (!strcmp(start
, codings
[i
]))
865 #endif /* HAVE_LIBZ */
872 * 'httpGetCookie()' - Get any cookie data from the response.
874 * @since CUPS 1.1.19/OS X 10.3@
877 const char * /* O - Cookie data or NULL */
878 httpGetCookie(http_t
*http
) /* I - HTTP connecion */
880 return (http
? http
->cookie
: NULL
);
885 * 'httpGetEncryption()' - Get the current encryption mode of a connection.
887 * This function returns the encryption mode for the connection. Use the
888 * @link httpIsEncrypted@ function to determine whether a TLS session has
894 http_encryption_t
/* O - Current encryption mode */
895 httpGetEncryption(http_t
*http
) /* I - HTTP connection */
897 return (http
? http
->encryption
: HTTP_ENCRYPTION_IF_REQUESTED
);
902 * 'httpGetExpect()' - Get the value of the Expect header, if any.
904 * Returns @code HTTP_STATUS_NONE@ if there is no Expect header, otherwise
905 * returns the expected HTTP status code, typically @code HTTP_STATUS_CONTINUE@.
907 * @since CUPS 1.7/OS X 10.9@
910 http_status_t
/* O - Expect: status, if any */
911 httpGetExpect(http_t
*http
) /* I - HTTP connection */
914 return (HTTP_STATUS_ERROR
);
916 return (http
->expect
);
921 * 'httpGetFd()' - Get the file descriptor associated with a connection.
923 * @since CUPS 1.2/OS X 10.5@
926 int /* O - File descriptor or -1 if none */
927 httpGetFd(http_t
*http
) /* I - HTTP connection */
929 return (http
? http
->fd
: -1);
934 * 'httpGetField()' - Get a field value from a request/response.
937 const char * /* O - Field value */
938 httpGetField(http_t
*http
, /* I - HTTP connection */
939 http_field_t field
) /* I - Field to get */
941 if (!http
|| field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
946 case HTTP_FIELD_ACCEPT_ENCODING
:
947 return (http
->accept_encoding
);
949 case HTTP_FIELD_ALLOW
:
950 return (http
->allow
);
952 case HTTP_FIELD_SERVER
:
953 return (http
->server
);
955 case HTTP_FIELD_AUTHORIZATION
:
956 if (http
->field_authorization
)
959 * Special case for WWW-Authenticate: as its contents can be
960 * longer than HTTP_MAX_VALUE...
963 return (http
->field_authorization
);
967 return (http
->fields
[field
]);
973 * 'httpGetKeepAlive()' - Get the current Keep-Alive state of the connection.
978 http_keepalive_t
/* O - Keep-Alive state */
979 httpGetKeepAlive(http_t
*http
) /* I - HTTP connection */
981 return (http
? http
->keep_alive
: HTTP_KEEPALIVE_OFF
);
986 * 'httpGetLength()' - Get the amount of data remaining from the
987 * content-length or transfer-encoding fields.
989 * This function is deprecated and will not return lengths larger than
990 * 2^31 - 1; use httpGetLength2() instead.
995 int /* O - Content length */
996 httpGetLength(http_t
*http
) /* I - HTTP connection */
999 * Get the read content length and return the 32-bit value.
1004 httpGetLength2(http
);
1006 return (http
->_data_remaining
);
1014 * 'httpGetLength2()' - Get the amount of data remaining from the
1015 * content-length or transfer-encoding fields.
1017 * This function returns the complete content length, even for
1018 * content larger than 2^31 - 1.
1020 * @since CUPS 1.2/OS X 10.5@
1023 off_t
/* O - Content length */
1024 httpGetLength2(http_t
*http
) /* I - HTTP connection */
1026 off_t remaining
; /* Remaining length */
1029 DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http
,
1030 httpStateString(http
->state
)));
1035 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked"))
1037 DEBUG_puts("4httpGetLength2: chunked request!");
1043 * The following is a hack for HTTP servers that don't send a
1044 * Content-Length or Transfer-Encoding field...
1046 * If there is no Content-Length then the connection must close
1047 * after the transfer is complete...
1050 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
1053 * Default content length is 0 for errors and certain types of operations,
1054 * and 2^31-1 for other successful requests...
1057 if (http
->status
>= HTTP_STATUS_MULTIPLE_CHOICES
||
1058 http
->state
== HTTP_STATE_OPTIONS
||
1059 (http
->state
== HTTP_STATE_GET
&& http
->mode
== _HTTP_MODE_SERVER
) ||
1060 http
->state
== HTTP_STATE_HEAD
||
1061 (http
->state
== HTTP_STATE_PUT
&& http
->mode
== _HTTP_MODE_CLIENT
) ||
1062 http
->state
== HTTP_STATE_DELETE
||
1063 http
->state
== HTTP_STATE_TRACE
||
1064 http
->state
== HTTP_STATE_CONNECT
)
1067 remaining
= 2147483647;
1069 else if ((remaining
= strtoll(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
],
1073 DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT
,
1074 CUPS_LLCAST remaining
));
1082 * 'httpGetPending()' - Get the number of bytes that are buffered for writing.
1087 size_t /* O - Number of bytes buffered */
1088 httpGetPending(http_t
*http
) /* I - HTTP connection */
1090 return (http
? http
->wused
: 0);
1095 * 'httpGetReady()' - Get the number of bytes that can be read without blocking.
1100 size_t /* O - Number of bytes available */
1101 httpGetReady(http_t
*http
) /* I - HTTP connection */
1105 else if (http
->used
> 0)
1106 return (http
->used
);
1110 size_t ready
; /* Ready bytes */
1113 if ((ready
= SSL_pending((SSL
*)(http
->tls
))) > 0)
1115 # elif defined(HAVE_GNUTLS)
1116 if ((ready
= gnutls_record_check_pending(http
->tls
)) > 0)
1118 # elif defined(HAVE_CDSASSL)
1119 if (!SSLGetBufferedReadSize(http
->tls
, &ready
) && ready
> 0)
1121 # endif /* HAVE_LIBSSL */
1123 #endif /* HAVE_SSL */
1130 * 'httpGetRemaining()' - Get the number of remaining bytes in the message
1131 * body or current chunk.
1133 * The @link httpIsChunked@ function can be used to determine whether the
1134 * message body is chunked or fixed-length.
1139 size_t /* O - Remaining bytes */
1140 httpGetRemaining(http_t
*http
) /* I - HTTP connection */
1142 return (http
? http
->data_remaining
: 0);
1147 * 'httpGets()' - Get a line of text from a HTTP connection.
1150 char * /* O - Line or NULL */
1151 httpGets(char *line
, /* I - Line to read into */
1152 int length
, /* I - Max length of buffer */
1153 http_t
*http
) /* I - HTTP connection */
1155 char *lineptr
, /* Pointer into line */
1156 *lineend
, /* End of line */
1157 *bufptr
, /* Pointer into input buffer */
1158 *bufend
; /* Pointer to end of buffer */
1159 int bytes
, /* Number of bytes read */
1160 eol
; /* End-of-line? */
1163 DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line
, length
, http
));
1165 if (!http
|| !line
|| length
<= 1)
1169 * Read a line from the buffer...
1174 lineend
= line
+ length
- 1;
1177 while (lineptr
< lineend
)
1180 * Pre-load the buffer as needed...
1189 while (http
->used
== 0)
1192 * No newline; see if there is more data to be read...
1195 while (!_httpWait(http
, http
->wait_value
, 1))
1197 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1200 DEBUG_puts("3httpGets: Timed out!");
1202 http
->error
= WSAETIMEDOUT
;
1204 http
->error
= ETIMEDOUT
;
1209 bytes
= http_read(http
, http
->buffer
+ http
->used
,
1210 HTTP_MAX_BUFFER
- http
->used
);
1212 DEBUG_printf(("4httpGets: read %d bytes.", bytes
));
1217 * Nope, can't get a line this time...
1221 DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
1223 if (WSAGetLastError() == WSAEINTR
)
1225 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
1227 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1230 http
->error
= WSAGetLastError();
1232 else if (WSAGetLastError() != http
->error
)
1234 http
->error
= WSAGetLastError();
1239 DEBUG_printf(("3httpGets: recv() error %d!", errno
));
1243 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
1245 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1247 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
1250 http
->error
= errno
;
1252 else if (errno
!= http
->error
)
1254 http
->error
= errno
;
1261 else if (bytes
== 0)
1263 http
->error
= EPIPE
;
1269 * Yup, update the amount used...
1272 http
->used
+= bytes
;
1276 * Now copy as much of the current line as possible...
1279 for (bufptr
= http
->buffer
, bufend
= http
->buffer
+ http
->used
;
1280 lineptr
< lineend
&& bufptr
< bufend
;)
1282 if (*bufptr
== 0x0a)
1288 else if (*bufptr
== 0x0d)
1291 *lineptr
++ = *bufptr
++;
1294 http
->used
-= (int)(bufptr
- http
->buffer
);
1296 memmove(http
->buffer
, bufptr
, http
->used
);
1304 http
->activity
= time(NULL
);
1308 DEBUG_printf(("3httpGets: Returning \"%s\"", line
));
1314 DEBUG_puts("3httpGets: No new line available!");
1321 * 'httpGetState()' - Get the current state of the HTTP request.
1324 http_state_t
/* O - HTTP state */
1325 httpGetState(http_t
*http
) /* I - HTTP connection */
1327 return (http
? http
->state
: HTTP_STATE_ERROR
);
1332 * 'httpGetStatus()' - Get the status of the last HTTP request.
1334 * @since CUPS 1.2/OS X 10.5@
1337 http_status_t
/* O - HTTP status */
1338 httpGetStatus(http_t
*http
) /* I - HTTP connection */
1340 return (http
? http
->status
: HTTP_STATUS_ERROR
);
1345 * 'httpGetSubField()' - Get a sub-field value.
1350 char * /* O - Value or NULL */
1351 httpGetSubField(http_t
*http
, /* I - HTTP connection */
1352 http_field_t field
, /* I - Field index */
1353 const char *name
, /* I - Name of sub-field */
1354 char *value
) /* O - Value string */
1356 return (httpGetSubField2(http
, field
, name
, value
, HTTP_MAX_VALUE
));
1361 * 'httpGetSubField2()' - Get a sub-field value.
1363 * @since CUPS 1.2/OS X 10.5@
1366 char * /* O - Value or NULL */
1367 httpGetSubField2(http_t
*http
, /* I - HTTP connection */
1368 http_field_t field
, /* I - Field index */
1369 const char *name
, /* I - Name of sub-field */
1370 char *value
, /* O - Value string */
1371 int valuelen
) /* I - Size of value buffer */
1373 const char *fptr
; /* Pointer into field */
1374 char temp
[HTTP_MAX_VALUE
], /* Temporary buffer for name */
1375 *ptr
, /* Pointer into string buffer */
1376 *end
; /* End of value buffer */
1378 DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, "
1379 "valuelen=%d)", http
, field
, name
, value
, valuelen
));
1381 if (!http
|| !name
|| !value
|| valuelen
< 2 ||
1382 field
<= HTTP_FIELD_UNKNOWN
|| field
>= HTTP_FIELD_MAX
)
1385 end
= value
+ valuelen
- 1;
1387 for (fptr
= http
->fields
[field
]; *fptr
;)
1390 * Skip leading whitespace...
1393 while (_cups_isspace(*fptr
))
1403 * Get the sub-field name...
1407 *fptr
&& *fptr
!= '=' && !_cups_isspace(*fptr
) &&
1408 ptr
< (temp
+ sizeof(temp
) - 1);
1413 DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp
));
1416 * Skip trailing chars up to the '='...
1419 while (_cups_isspace(*fptr
))
1429 * Skip = and leading whitespace...
1434 while (_cups_isspace(*fptr
))
1440 * Read quoted string...
1443 for (ptr
= value
, fptr
++;
1444 *fptr
&& *fptr
!= '\"' && ptr
< end
;
1449 while (*fptr
&& *fptr
!= '\"')
1458 * Read unquoted string...
1462 *fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',' && ptr
< end
;
1467 while (*fptr
&& !_cups_isspace(*fptr
) && *fptr
!= ',')
1471 DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value
));
1474 * See if this is the one...
1477 if (!strcmp(name
, temp
))
1479 DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value
));
1486 DEBUG_puts("3httpGetSubField2: Returning NULL");
1493 * 'httpGetVersion()' - Get the HTTP version at the other end.
1496 http_version_t
/* O - Version number */
1497 httpGetVersion(http_t
*http
) /* I - HTTP connection */
1499 return (http
? http
->version
: HTTP_VERSION_1_0
);
1504 * 'httpHead()' - Send a HEAD request to the server.
1507 int /* O - Status of call (0 = success) */
1508 httpHead(http_t
*http
, /* I - HTTP connection */
1509 const char *uri
) /* I - URI for head */
1511 DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http
, uri
));
1512 return (http_send(http
, HTTP_STATE_HEAD
, uri
));
1517 * 'httpInitialize()' - Initialize the HTTP interface library and set the
1518 * default HTTP proxy (if any).
1522 httpInitialize(void)
1524 static int initialized
= 0; /* Have we been called before? */
1526 WSADATA winsockdata
; /* WinSock data */
1529 int i
; /* Looping var */
1530 unsigned char data
[1024]; /* Seed data */
1531 #endif /* HAVE_LIBSSL */
1537 _cupsGlobalUnlock();
1542 WSAStartup(MAKEWORD(2,2), &winsockdata
);
1544 #elif !defined(SO_NOSIGPIPE)
1546 * Ignore SIGPIPE signals...
1550 sigset(SIGPIPE
, SIG_IGN
);
1552 # elif defined(HAVE_SIGACTION)
1553 struct sigaction action
; /* POSIX sigaction data */
1556 memset(&action
, 0, sizeof(action
));
1557 action
.sa_handler
= SIG_IGN
;
1558 sigaction(SIGPIPE
, &action
, NULL
);
1561 signal(SIGPIPE
, SIG_IGN
);
1562 # endif /* !SO_NOSIGPIPE */
1566 http_tls_initialize();
1567 # endif /* HAVE_SSL */
1570 _cupsGlobalUnlock();
1575 * 'httpIsChunked()' - Report whether a message body is chunked.
1577 * This function returns non-zero if the message body is composed of
1578 * variable-length chunks.
1583 int /* O - 1 if chunked, 0 if not */
1584 httpIsChunked(http_t
*http
) /* I - HTTP connection */
1586 return (http
? http
->data_encoding
== HTTP_ENCODING_CHUNKED
: 0);
1591 * 'httpIsEncrypted()' - Report whether a connection is encrypted.
1593 * This function returns non-zero if the connection is currently encrypted.
1598 int /* O - 1 if encrypted, 0 if not */
1599 httpIsEncrypted(http_t
*http
) /* I - HTTP connection */
1601 return (http
? http
->tls
!= NULL
: 0);
1606 * 'httpOptions()' - Send an OPTIONS request to the server.
1609 int /* O - Status of call (0 = success) */
1610 httpOptions(http_t
*http
, /* I - HTTP connection */
1611 const char *uri
) /* I - URI for options */
1613 return (http_send(http
, HTTP_STATE_OPTIONS
, uri
));
1618 * 'httpPeek()' - Peek at data from a HTTP connection.
1620 * This function copies available data from the given HTTP connection, reading
1621 * a buffer as needed. The data is still available for reading using
1622 * @link httpRead@ or @link httpRead2@.
1624 * For non-blocking connections the usual timeouts apply.
1626 * @since CUPS 1.7/OS X 10.9@
1629 ssize_t
/* O - Number of bytes copied */
1630 httpPeek(http_t
*http
, /* I - HTTP connection */
1631 char *buffer
, /* I - Buffer for data */
1632 size_t length
) /* I - Maximum number of bytes */
1634 ssize_t bytes
; /* Bytes read */
1635 char len
[32]; /* Length string */
1638 DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
1639 http
, buffer
, CUPS_LLCAST length
));
1641 if (http
== NULL
|| buffer
== NULL
)
1644 http
->activity
= time(NULL
);
1650 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&&
1651 http
->data_remaining
<= 0)
1653 DEBUG_puts("2httpPeek: Getting chunk length...");
1655 if (httpGets(len
, sizeof(len
), http
) == NULL
)
1657 DEBUG_puts("1httpPeek: Could not get length!");
1663 DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
1664 if (!httpGets(len
, sizeof(len
), http
))
1666 DEBUG_puts("1httpPeek: Could not get chunk length.");
1671 http
->data_remaining
= strtoll(len
, NULL
, 16);
1673 if (http
->data_remaining
< 0)
1675 DEBUG_puts("1httpPeek: Negative chunk length!");
1680 DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT
,
1681 CUPS_LLCAST http
->data_remaining
));
1683 if (http
->data_remaining
<= 0 && http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
1686 * A zero-length chunk ends a transfer; unless we are reading POST
1692 http_content_coding_finish(http
);
1693 #endif /* HAVE_LIBZ */
1695 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
1696 httpGets(len
, sizeof(len
), http
);
1698 if (http
->state
== HTTP_STATE_POST_RECV
)
1701 http
->state
= HTTP_STATE_STATUS
;
1703 DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
1704 httpStateString(http
->state
)));
1707 * Prevent future reads for this request...
1710 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
1714 else if (length
> (size_t)http
->data_remaining
)
1715 length
= (size_t)http
->data_remaining
;
1718 if (http
->used
== 0 &&
1719 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0))
1721 if (http
->used
== 0)
1722 #endif /* HAVE_LIBZ */
1725 * Buffer small reads for better performance...
1728 ssize_t buflen
; /* Length of read for buffer */
1730 if (!http
->blocking
)
1732 while (!httpWait(http
, http
->wait_value
))
1734 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
1741 if (http
->data_remaining
> sizeof(http
->buffer
))
1742 buflen
= sizeof(http
->buffer
);
1744 buflen
= http
->data_remaining
;
1746 DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen
));
1747 bytes
= http_read(http
, http
->buffer
, buflen
);
1749 DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT
" bytes into buffer.",
1750 CUPS_LLCAST bytes
));
1754 http_debug_hex("httpPeek", http
->buffer
, (int)bytes
);
1764 # ifdef HAVE_INFLATECOPY
1765 int zerr
; /* Decompressor error */
1766 z_stream stream
; /* Copy of decompressor stream */
1768 if (http
->used
> 0 && http
->stream
.avail_in
< HTTP_MAX_BUFFER
)
1770 size_t buflen
= buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
1771 /* Number of bytes to copy */
1773 if (http
->stream
.avail_in
> 0 &&
1774 http
->stream
.next_in
> http
->dbuffer
)
1775 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
1777 http
->stream
.next_in
= http
->dbuffer
;
1779 if (buflen
> http
->data_remaining
)
1780 buflen
= http
->data_remaining
;
1782 if (buflen
> http
->used
)
1783 buflen
= http
->used
;
1785 DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
1786 "decompression buffer.", (int)buflen
));
1788 memcpy(http
->dbuffer
+ http
->stream
.avail_in
, http
->buffer
, buflen
);
1789 http
->stream
.avail_in
+= buflen
;
1790 http
->used
-= buflen
;
1791 http
->data_remaining
-= buflen
;
1794 memmove(http
->buffer
, http
->buffer
+ buflen
, http
->used
);
1797 DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length
,
1798 (int)http
->stream
.avail_in
));
1800 if (inflateCopy(&stream
, &(http
->stream
)) != Z_OK
)
1802 DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
1803 http
->error
= ENOMEM
;
1807 stream
.next_out
= (Bytef
*)buffer
;
1808 stream
.avail_out
= length
;
1810 zerr
= inflate(&stream
, Z_SYNC_FLUSH
);
1811 inflateEnd(&stream
);
1815 DEBUG_printf(("2httpPeek: zerr=%d", zerr
));
1817 http_debug_hex("2httpPeek", (char *)http
->dbuffer
,
1818 http
->stream
.avail_in
);
1825 bytes
= length
- http
->stream
.avail_out
;
1828 DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
1829 "work with compressed streams.");
1831 # endif /* HAVE_INFLATECOPY */
1834 #endif /* HAVE_LIBZ */
1837 if (length
> (size_t)http
->used
)
1838 length
= (size_t)http
->used
;
1840 bytes
= (ssize_t
)length
;
1842 DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
1845 memcpy(buffer
, http
->buffer
, length
);
1853 if (WSAGetLastError() == WSAEINTR
|| WSAGetLastError() == WSAEWOULDBLOCK
)
1856 http
->error
= WSAGetLastError();
1858 if (errno
== EINTR
|| errno
== EAGAIN
)
1861 http
->error
= errno
;
1864 else if (bytes
== 0)
1866 http
->error
= EPIPE
;
1873 /* For OS X 10.8 and earlier */
1874 ssize_t
_httpPeek(http_t
*http
, char *buffer
, size_t length
)
1875 { return (httpPeek(http
, buffer
, length
)); }
1879 * 'httpPost()' - Send a POST request to the server.
1882 int /* O - Status of call (0 = success) */
1883 httpPost(http_t
*http
, /* I - HTTP connection */
1884 const char *uri
) /* I - URI for post */
1886 return (http_send(http
, HTTP_STATE_POST
, uri
));
1891 * 'httpPrintf()' - Print a formatted string to a HTTP connection.
1896 int /* O - Number of bytes written */
1897 httpPrintf(http_t
*http
, /* I - HTTP connection */
1898 const char *format
, /* I - printf-style format string */
1899 ...) /* I - Additional args as needed */
1901 int bytes
; /* Number of bytes to write */
1902 char buf
[16384]; /* Buffer for formatted string */
1903 va_list ap
; /* Variable argument pointer */
1906 DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http
, format
));
1908 va_start(ap
, format
);
1909 bytes
= vsnprintf(buf
, sizeof(buf
), format
, ap
);
1912 DEBUG_printf(("3httpPrintf: (%d bytes) %s", bytes
, buf
));
1914 if (http
->data_encoding
== HTTP_ENCODING_FIELDS
)
1915 return (httpWrite2(http
, buf
, bytes
));
1920 DEBUG_puts("4httpPrintf: flushing existing data...");
1922 if (httpFlushWrite(http
) < 0)
1926 return (http_write(http
, buf
, bytes
));
1932 * 'httpPut()' - Send a PUT request to the server.
1935 int /* O - Status of call (0 = success) */
1936 httpPut(http_t
*http
, /* I - HTTP connection */
1937 const char *uri
) /* I - URI to put */
1939 DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http
, uri
));
1940 return (http_send(http
, HTTP_STATE_PUT
, uri
));
1945 * 'httpRead()' - Read data from a HTTP connection.
1947 * This function is deprecated. Use the httpRead2() function which can
1948 * read more than 2GB of data.
1953 int /* O - Number of bytes read */
1954 httpRead(http_t
*http
, /* I - HTTP connection */
1955 char *buffer
, /* I - Buffer for data */
1956 int length
) /* I - Maximum number of bytes */
1958 return ((int)httpRead2(http
, buffer
, length
));
1963 * 'httpRead2()' - Read data from a HTTP connection.
1965 * @since CUPS 1.2/OS X 10.5@
1968 ssize_t
/* O - Number of bytes read */
1969 httpRead2(http_t
*http
, /* I - HTTP connection */
1970 char *buffer
, /* I - Buffer for data */
1971 size_t length
) /* I - Maximum number of bytes */
1973 ssize_t bytes
; /* Bytes read */
1977 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
1978 ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT
,
1979 http
, buffer
, CUPS_LLCAST length
,
1981 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
1983 DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT
1984 ") data_encoding=%d data_remaining=" CUPS_LLFMT
,
1985 http
, buffer
, CUPS_LLCAST length
,
1986 http
->data_encoding
, CUPS_LLCAST http
->data_remaining
));
1987 #endif /* HAVE_LIBZ */
1989 if (http
== NULL
|| buffer
== NULL
)
1992 http
->activity
= time(NULL
);
2003 if (http
->stream
.avail_in
> 0)
2005 int zerr
; /* Decompressor error */
2007 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
2008 (int)http
->stream
.avail_in
, (int)length
));
2010 http
->stream
.next_out
= (Bytef
*)buffer
;
2011 http
->stream
.avail_out
= length
;
2013 if ((zerr
= inflate(&(http
->stream
), Z_SYNC_FLUSH
)) < Z_OK
)
2015 DEBUG_printf(("2httpRead2: zerr=%d", zerr
));
2017 http_debug_hex("2httpRead2", (char *)http
->dbuffer
,
2018 http
->stream
.avail_in
);
2025 bytes
= length
- http
->stream
.avail_out
;
2027 DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
2028 http
->stream
.avail_in
, http
->stream
.avail_out
,
2036 ssize_t buflen
= HTTP_MAX_BUFFER
- http
->stream
.avail_in
;
2037 /* Additional bytes for buffer */
2041 if (http
->stream
.avail_in
> 0 &&
2042 http
->stream
.next_in
> http
->dbuffer
)
2043 memmove(http
->dbuffer
, http
->stream
.next_in
, http
->stream
.avail_in
);
2045 http
->stream
.next_in
= http
->dbuffer
;
2047 DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
2048 "decompression buffer.", (int)buflen
));
2050 if (http
->data_remaining
> 0)
2052 if (buflen
> http
->data_remaining
)
2053 buflen
= http
->data_remaining
;
2055 bytes
= http_read_buffered(http
,
2056 (char *)http
->dbuffer
+
2057 http
->stream
.avail_in
, buflen
);
2059 else if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2060 bytes
= http_read_chunk(http
,
2061 (char *)http
->dbuffer
+
2062 http
->stream
.avail_in
, buflen
);
2068 else if (bytes
== 0)
2071 DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT
" bytes to "
2072 "decompression buffer.", CUPS_LLCAST bytes
));
2074 http
->data_remaining
-= bytes
;
2075 http
->stream
.avail_in
+= bytes
;
2077 if (http
->data_remaining
<= 0 &&
2078 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2081 * Read the trailing blank line now...
2084 char len
[32]; /* Length string */
2086 httpGets(len
, sizeof(len
), http
);
2098 #endif /* HAVE_LIBZ */
2099 if (http
->data_remaining
== 0 && http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2101 if ((bytes
= http_read_chunk(http
, buffer
, length
)) > 0)
2103 http
->data_remaining
-= bytes
;
2105 if (http
->data_remaining
<= 0)
2108 * Read the trailing blank line now...
2111 char len
[32]; /* Length string */
2113 httpGets(len
, sizeof(len
), http
);
2117 else if (http
->data_remaining
<= 0)
2120 * No more data to read...
2127 DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
2130 if (length
> (size_t)http
->data_remaining
)
2131 length
= (size_t)http
->data_remaining
;
2133 if ((bytes
= http_read_buffered(http
, buffer
, length
)) > 0)
2135 http
->data_remaining
-= bytes
;
2137 if (http
->data_remaining
<= 0 &&
2138 http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
2141 * Read the trailing blank line now...
2144 char len
[32]; /* Length string */
2146 httpGets(len
, sizeof(len
), http
);
2153 (http
->coding
== _HTTP_CODING_IDENTITY
|| http
->stream
.avail_in
== 0) &&
2154 #endif /* HAVE_LIBZ */
2155 ((http
->data_remaining
<= 0 &&
2156 http
->data_encoding
== HTTP_ENCODING_LENGTH
) ||
2157 (http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& bytes
== 0)))
2161 http_content_coding_finish(http
);
2162 #endif /* HAVE_LIBZ */
2164 if (http
->state
== HTTP_STATE_POST_RECV
)
2166 else if (http
->state
== HTTP_STATE_GET_SEND
||
2167 http
->state
== HTTP_STATE_POST_SEND
)
2168 http
->state
= HTTP_STATE_WAITING
;
2170 http
->state
= HTTP_STATE_STATUS
;
2172 DEBUG_printf(("1httpRead2: End of content, set state to %s.",
2173 httpStateString(http
->state
)));
2181 * 'httpReadRequest()' - Read a HTTP request from a connection.
2183 * @since CUPS 1.7/OS X 10.9@
2186 http_state_t
/* O - New state of connection */
2187 httpReadRequest(http_t
*http
, /* I - HTTP connection */
2188 char *uri
, /* I - URI buffer */
2189 size_t urilen
) /* I - Size of URI buffer */
2191 char line
[4096], /* HTTP request line */
2192 *req_method
, /* HTTP request method */
2193 *req_uri
, /* HTTP request URI */
2194 *req_version
; /* HTTP request version number string */
2198 * Range check input...
2201 DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT
")",
2202 http
, uri
, CUPS_LLCAST urilen
));
2207 if (!http
|| !uri
|| urilen
< 1)
2209 DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
2210 return (HTTP_STATE_ERROR
);
2212 else if (http
->state
!= HTTP_STATE_WAITING
)
2214 DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
2215 httpStateString(http
->state
)));
2216 return (HTTP_STATE_ERROR
);
2223 httpClearFields(http
);
2225 http
->activity
= time(NULL
);
2226 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2227 http
->data_remaining
= 0;
2228 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2229 http
->status
= HTTP_STATUS_OK
;
2230 http
->version
= HTTP_VERSION_1_1
;
2233 * Read a line from the socket...
2236 if (!httpGets(line
, sizeof(line
), http
))
2238 DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
2239 return (HTTP_STATE_ERROR
);
2244 DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
2245 return (HTTP_STATE_WAITING
);
2248 DEBUG_printf(("1httpReadRequest: %s", line
));
2257 while (*req_uri
&& !isspace(*req_uri
& 255))
2262 DEBUG_puts("1httpReadRequest: No request URI.");
2263 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request URI."), 1);
2264 return (HTTP_STATE_ERROR
);
2269 while (*req_uri
&& isspace(*req_uri
& 255))
2272 req_version
= req_uri
;
2274 while (*req_version
&& !isspace(*req_version
& 255))
2279 DEBUG_puts("1httpReadRequest: No request protocol version.");
2280 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("No request protocol version."), 1);
2281 return (HTTP_STATE_ERROR
);
2284 *req_version
++ = '\0';
2286 while (*req_version
&& isspace(*req_version
& 255))
2293 if (!strcmp(req_method
, "OPTIONS"))
2294 http
->state
= HTTP_STATE_OPTIONS
;
2295 else if (!strcmp(req_method
, "GET"))
2296 http
->state
= HTTP_STATE_GET
;
2297 else if (!strcmp(req_method
, "HEAD"))
2298 http
->state
= HTTP_STATE_HEAD
;
2299 else if (!strcmp(req_method
, "POST"))
2300 http
->state
= HTTP_STATE_POST
;
2301 else if (!strcmp(req_method
, "PUT"))
2302 http
->state
= HTTP_STATE_PUT
;
2303 else if (!strcmp(req_method
, "DELETE"))
2304 http
->state
= HTTP_STATE_DELETE
;
2305 else if (!strcmp(req_method
, "TRACE"))
2306 http
->state
= HTTP_STATE_TRACE
;
2307 else if (!strcmp(req_method
, "CONNECT"))
2308 http
->state
= HTTP_STATE_CONNECT
;
2311 DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method
));
2312 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request method."), 1);
2313 return (HTTP_STATE_UNKNOWN_METHOD
);
2316 DEBUG_printf(("1httpReadRequest: Set state to %s.",
2317 httpStateString(http
->state
)));
2319 if (!strcmp(req_version
, "HTTP/1.0"))
2321 http
->version
= HTTP_VERSION_1_0
;
2322 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2324 else if (!strcmp(req_version
, "HTTP/1.1"))
2326 http
->version
= HTTP_VERSION_1_1
;
2327 http
->keep_alive
= HTTP_KEEPALIVE_ON
;
2331 DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version
));
2332 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, _("Unknown request version."), 1);
2333 return (HTTP_STATE_UNKNOWN_VERSION
);
2336 DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri
));
2337 strlcpy(uri
, req_uri
, urilen
);
2339 return (http
->state
);
2344 * 'httpReconnect()' - Reconnect to a HTTP server.
2346 * This function is deprecated. Please use the @link httpReconnect2@ function
2352 int /* O - 0 on success, non-zero on failure */
2353 httpReconnect(http_t
*http
) /* I - HTTP connection */
2355 DEBUG_printf(("httpReconnect(http=%p)", http
));
2357 return (httpReconnect2(http
, 30000, NULL
));
2362 * 'httpReconnect2()' - Reconnect to a HTTP server with timeout and optional
2366 int /* O - 0 on success, non-zero on failure */
2367 httpReconnect2(http_t
*http
, /* I - HTTP connection */
2368 int msec
, /* I - Timeout in milliseconds */
2369 int *cancel
) /* I - Pointer to "cancel" variable */
2371 http_addrlist_t
*addr
; /* Connected address */
2373 http_addrlist_t
*current
; /* Current address */
2374 char temp
[256]; /* Temporary address string */
2378 DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", http
, msec
,
2383 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(EINVAL
), 0);
2390 DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
2391 http_tls_stop(http
);
2393 #endif /* HAVE_SSL */
2396 * Close any previously open socket...
2401 DEBUG_printf(("2httpReconnect2: Closing socket %d...", http
->fd
));
2403 httpAddrClose(NULL
, http
->fd
);
2409 * Reset all state (except fields, which may be reused)...
2412 http
->state
= HTTP_STATE_WAITING
;
2413 http
->version
= HTTP_VERSION_1_1
;
2414 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
2415 memset(&http
->_hostaddr
, 0, sizeof(http
->_hostaddr
));
2416 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
2417 http
->_data_remaining
= 0;
2419 http
->data_remaining
= 0;
2420 http
->hostaddr
= NULL
;
2424 * Connect to the server...
2428 for (current
= http
->addrlist
; current
; current
= current
->next
)
2429 DEBUG_printf(("2httpReconnect2: Address %s:%d",
2430 httpAddrString(&(current
->addr
), temp
, sizeof(temp
)),
2431 httpAddrPort(&(current
->addr
))));
2434 if ((addr
= httpAddrConnect2(http
->addrlist
, &(http
->fd
), msec
,
2438 * Unable to connect...
2442 http
->error
= WSAGetLastError();
2444 http
->error
= errno
;
2446 http
->status
= HTTP_STATUS_ERROR
;
2448 DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
2449 strerror(http
->error
)));
2454 DEBUG_printf(("2httpReconnect2: New socket=%d", http
->fd
));
2456 if (http
->timeout_value
> 0)
2457 http_set_timeout(http
->fd
, http
->timeout_value
);
2459 http
->hostaddr
= &(addr
->addr
);
2463 if (http
->encryption
== HTTP_ENCRYPTION_ALWAYS
)
2466 * Always do encryption via SSL.
2469 if (http_tls_start(http
) != 0)
2471 httpAddrClose(NULL
, http
->fd
);
2476 else if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls_upgrade
)
2477 return (http_tls_upgrade(http
));
2478 #endif /* HAVE_SSL */
2480 DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
2481 httpAddrString(http
->hostaddr
, temp
, sizeof(temp
)),
2482 httpAddrPort(http
->hostaddr
)));
2489 * 'httpSetAuthString()' - Set the current authorization string.
2491 * This function just stores a copy of the current authorization string in
2492 * the HTTP connection object. You must still call httpSetField() to set
2493 * HTTP_FIELD_AUTHORIZATION prior to issuing a HTTP request using httpGet(),
2494 * httpHead(), httpOptions(), httpPost, or httpPut().
2496 * @since CUPS 1.3/OS X 10.5@
2500 httpSetAuthString(http_t
*http
, /* I - HTTP connection */
2501 const char *scheme
, /* I - Auth scheme (NULL to clear it) */
2502 const char *data
) /* I - Auth data (NULL for none) */
2505 * Range check input...
2511 if (http
->authstring
&& http
->authstring
!= http
->_authstring
)
2512 free(http
->authstring
);
2514 http
->authstring
= http
->_authstring
;
2519 * Set the current authorization string...
2522 int len
= (int)strlen(scheme
) + (data
? (int)strlen(data
) + 1 : 0) + 1;
2525 if (len
> (int)sizeof(http
->_authstring
))
2527 if ((temp
= malloc(len
)) == NULL
)
2528 len
= sizeof(http
->_authstring
);
2530 http
->authstring
= temp
;
2534 snprintf(http
->authstring
, len
, "%s %s", scheme
, data
);
2536 strlcpy(http
->authstring
, scheme
, len
);
2541 * Clear the current authorization string...
2544 http
->_authstring
[0] = '\0';
2550 * 'httpSetCredentials()' - Set the credentials associated with an encrypted
2553 * @since CUPS 1.5/OS X 10.7@
2556 int /* O - Status of call (0 = success) */
2557 httpSetCredentials(http_t
*http
, /* I - HTTP connection */
2558 cups_array_t
*credentials
) /* I - Array of credentials */
2560 if (!http
|| cupsArrayCount(credentials
) < 1)
2563 _httpFreeCredentials(http
->tls_credentials
);
2565 http
->tls_credentials
= _httpCreateCredentials(credentials
);
2567 return (http
->tls_credentials
? 0 : -1);
2572 * 'httpSetCookie()' - Set the cookie value(s).
2574 * @since CUPS 1.1.19/OS X 10.3@
2578 httpSetCookie(http_t
*http
, /* I - Connection */
2579 const char *cookie
) /* I - Cookie string */
2588 http
->cookie
= strdup(cookie
);
2590 http
->cookie
= NULL
;
2595 * 'httpSetDefaultField()' - Set the default value of an HTTP header.
2597 * Currently only @code HTTP_FIELD_ACCEPT_ENCODING@, @code HTTP_FIELD_SERVER@,
2598 * and @code HTTP_FIELD_USER_AGENT@ can be set.
2600 * @since CUPS 1.7/OS X 10.9@
2604 httpSetDefaultField(http_t
*http
, /* I - HTTP connection */
2605 http_field_t field
, /* I - Field index */
2606 const char *value
)/* I - Value */
2608 DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")",
2609 http
, field
, http_fields
[field
], value
));
2616 case HTTP_FIELD_ACCEPT_ENCODING
:
2617 if (http
->default_accept_encoding
)
2618 _cupsStrFree(http
->default_accept_encoding
);
2620 http
->default_accept_encoding
= value
? _cupsStrAlloc(value
) : NULL
;
2623 case HTTP_FIELD_SERVER
:
2624 if (http
->default_server
)
2625 _cupsStrFree(http
->default_server
);
2627 http
->default_server
= value
? _cupsStrAlloc(value
) : NULL
;
2630 case HTTP_FIELD_USER_AGENT
:
2631 if (http
->default_user_agent
)
2632 _cupsStrFree(http
->default_user_agent
);
2634 http
->default_user_agent
= value
? _cupsStrAlloc(value
) : NULL
;
2638 DEBUG_puts("1httpSetDefaultField: Ignored.");
2645 * 'httpSetExpect()' - Set the Expect: header in a request.
2647 * Currently only @code HTTP_STATUS_CONTINUE@ is supported for the "expect"
2650 * @since CUPS 1.2/OS X 10.5@
2654 httpSetExpect(http_t
*http
, /* I - HTTP connection */
2655 http_status_t expect
) /* I - HTTP status to expect
2656 (@code HTTP_STATUS_CONTINUE@) */
2658 DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", http
, expect
));
2661 http
->expect
= expect
;
2666 * 'httpSetField()' - Set the value of an HTTP header.
2670 httpSetField(http_t
*http
, /* I - HTTP connection */
2671 http_field_t field
, /* I - Field index */
2672 const char *value
) /* I - Value */
2674 DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", http
,
2675 field
, http_fields
[field
], value
));
2678 field
< HTTP_FIELD_ACCEPT_LANGUAGE
||
2679 field
>= HTTP_FIELD_MAX
||
2685 case HTTP_FIELD_ACCEPT_ENCODING
:
2686 if (http
->accept_encoding
)
2687 _cupsStrFree(http
->accept_encoding
);
2689 http
->accept_encoding
= _cupsStrAlloc(value
);
2692 case HTTP_FIELD_ALLOW
:
2694 _cupsStrFree(http
->allow
);
2696 http
->allow
= _cupsStrAlloc(value
);
2699 case HTTP_FIELD_SERVER
:
2701 _cupsStrFree(http
->server
);
2703 http
->server
= _cupsStrAlloc(value
);
2707 strlcpy(http
->fields
[field
], value
, HTTP_MAX_VALUE
);
2711 if (field
== HTTP_FIELD_AUTHORIZATION
)
2714 * Special case for Authorization: as its contents can be
2715 * longer than HTTP_MAX_VALUE
2718 if (http
->field_authorization
)
2719 free(http
->field_authorization
);
2721 http
->field_authorization
= strdup(value
);
2723 else if (field
== HTTP_FIELD_HOST
)
2726 * Special-case for Host: as we don't want a trailing "." on the hostname and
2727 * need to bracket IPv6 numeric addresses.
2730 char *ptr
= strchr(value
, ':');
2732 if (value
[0] != '[' && ptr
&& strchr(ptr
+ 1, ':'))
2735 * Bracket IPv6 numeric addresses...
2737 * This is slightly inefficient (basically copying twice), but is an edge
2738 * case and not worth optimizing...
2741 snprintf(http
->fields
[HTTP_FIELD_HOST
],
2742 sizeof(http
->fields
[HTTP_FIELD_HOST
]), "[%s]", value
);
2747 * Check for a trailing dot on the hostname...
2750 ptr
= http
->fields
[HTTP_FIELD_HOST
];
2754 ptr
+= strlen(ptr
) - 1;
2762 else if (field
== HTTP_FIELD_CONTENT_ENCODING
&&
2763 http
->data_encoding
!= HTTP_ENCODING_FIELDS
)
2765 DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
2766 http_content_coding_start(http
, value
);
2768 #endif /* HAVE_LIBZ */
2773 * 'httpSetKeepAlive()' - Set the current Keep-Alive state of a connection.
2780 http_t
*http
, /* I - HTTP connection */
2781 http_keepalive_t keep_alive
) /* I - New Keep-Alive value */
2784 http
->keep_alive
= keep_alive
;
2789 * 'httpSetLength()' - Set the content-length and content-encoding.
2791 * @since CUPS 1.2/OS X 10.5@
2795 httpSetLength(http_t
*http
, /* I - HTTP connection */
2796 size_t length
) /* I - Length (0 for chunked) */
2798 DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT
")", http
,
2799 CUPS_LLCAST length
));
2806 strlcpy(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
], "chunked",
2808 http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0] = '\0';
2812 http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
][0] = '\0';
2813 snprintf(http
->fields
[HTTP_FIELD_CONTENT_LENGTH
], HTTP_MAX_VALUE
,
2814 CUPS_LLFMT
, CUPS_LLCAST length
);
2820 * 'httpSetTimeout()' - Set read/write timeouts and an optional callback.
2822 * The optional timeout callback receives both the HTTP connection and a user
2823 * data pointer and must return 1 to continue or 0 to error (time) out.
2825 * @since CUPS 1.5/OS X 10.7@
2830 http_t
*http
, /* I - HTTP connection */
2831 double timeout
, /* I - Number of seconds for timeout,
2832 must be greater than 0 */
2833 http_timeout_cb_t cb
, /* I - Callback function or NULL */
2834 void *user_data
) /* I - User data pointer */
2836 if (!http
|| timeout
<= 0.0)
2839 http
->timeout_cb
= cb
;
2840 http
->timeout_data
= user_data
;
2841 http
->timeout_value
= timeout
;
2844 http_set_timeout(http
->fd
, timeout
);
2846 http_set_wait(http
);
2851 * 'httpShutdown()' - Shutdown one side of an HTTP connection.
2857 httpShutdown(http_t
*http
) /* I - HTTP connection */
2859 if (!http
|| http
->fd
< 0)
2863 http_shutdown_ssl(http
);
2865 shutdown(http
->fd
, SHUT_RD
);
2870 * 'httpTrace()' - Send an TRACE request to the server.
2873 int /* O - Status of call (0 = success) */
2874 httpTrace(http_t
*http
, /* I - HTTP connection */
2875 const char *uri
) /* I - URI for trace */
2877 return (http_send(http
, HTTP_STATE_TRACE
, uri
));
2882 * '_httpUpdate()' - Update the current HTTP status for incoming data.
2884 * Note: Unlike httpUpdate(), this function does not flush pending write data
2885 * and only retrieves a single status line from the HTTP connection.
2888 int /* O - 1 to continue, 0 to stop */
2889 _httpUpdate(http_t
*http
, /* I - HTTP connection */
2890 http_status_t
*status
) /* O - Current HTTP status */
2892 char line
[32768], /* Line from connection... */
2893 *value
; /* Pointer to value on line */
2894 http_field_t field
; /* Field index */
2895 int major
, minor
; /* HTTP version numbers */
2898 DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", http
, status
,
2899 httpStateString(http
->state
)));
2902 * Grab a single line from the connection...
2905 if (!httpGets(line
, sizeof(line
), http
))
2907 *status
= HTTP_STATUS_ERROR
;
2911 DEBUG_printf(("2_httpUpdate: Got \"%s\"", line
));
2913 if (line
[0] == '\0')
2916 * Blank line means the start of the data section (if any). Return
2917 * the result code, too...
2919 * If we get status 100 (HTTP_STATUS_CONTINUE), then we *don't* change
2920 * states. Instead, we just return HTTP_STATUS_CONTINUE to the caller and
2924 if (http
->status
== HTTP_STATUS_CONTINUE
)
2926 *status
= http
->status
;
2930 if (http
->status
< HTTP_STATUS_BAD_REQUEST
)
2931 http
->digest_tries
= 0;
2934 if (http
->status
== HTTP_STATUS_SWITCHING_PROTOCOLS
&& !http
->tls
)
2936 if (http_tls_start(http
) != 0)
2938 httpAddrClose(NULL
, http
->fd
);
2940 *status
= http
->status
= HTTP_STATUS_ERROR
;
2944 *status
= HTTP_STATUS_CONTINUE
;
2947 #endif /* HAVE_SSL */
2949 if (http_set_length(http
) < 0)
2951 DEBUG_puts("1_httpUpdate: Bad Content-Length.");
2952 http
->error
= EINVAL
;
2953 http
->status
= *status
= HTTP_STATUS_ERROR
;
2957 switch (http
->state
)
2959 case HTTP_STATE_GET
:
2960 case HTTP_STATE_POST
:
2961 case HTTP_STATE_POST_RECV
:
2962 case HTTP_STATE_PUT
:
2965 DEBUG_printf(("1_httpUpdate: Set state to %s.",
2966 httpStateString(http
->state
)));
2968 case HTTP_STATE_POST_SEND
:
2969 case HTTP_STATE_HEAD
:
2973 http
->state
= HTTP_STATE_WAITING
;
2975 DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
2980 DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
2981 http_content_coding_start(http
,
2982 httpGetField(http
, HTTP_FIELD_CONTENT_ENCODING
));
2983 #endif /* HAVE_LIBZ */
2985 *status
= http
->status
;
2988 else if (!strncmp(line
, "HTTP/", 5))
2991 * Got the beginning of a response...
2994 int intstatus
; /* Status value as an integer */
2996 if (sscanf(line
, "HTTP/%d.%d%d", &major
, &minor
, &intstatus
) != 3)
2998 *status
= http
->status
= HTTP_STATUS_ERROR
;
3002 httpClearFields(http
);
3004 http
->version
= (http_version_t
)(major
* 100 + minor
);
3005 *status
= http
->status
= (http_status_t
)intstatus
;
3007 else if ((value
= strchr(line
, ':')) != NULL
)
3014 while (_cups_isspace(*value
))
3017 DEBUG_printf(("1_httpUpdate: Header %s: %s", line
, value
));
3020 * Be tolerants of servers that send unknown attribute fields...
3023 if (!_cups_strcasecmp(line
, "expect"))
3026 * "Expect: 100-continue" or similar...
3029 http
->expect
= (http_status_t
)atoi(value
);
3031 else if (!_cups_strcasecmp(line
, "cookie"))
3034 * "Cookie: name=value[; name=value ...]" - replaces previous cookies...
3037 httpSetCookie(http
, value
);
3039 else if ((field
= httpFieldValue(line
)) != HTTP_FIELD_UNKNOWN
)
3040 httpSetField(http
, field
, value
);
3043 DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line
));
3048 DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line
));
3049 http
->error
= EINVAL
;
3050 http
->status
= *status
= HTTP_STATUS_ERROR
;
3059 * 'httpUpdate()' - Update the current HTTP state for incoming data.
3062 http_status_t
/* O - HTTP status */
3063 httpUpdate(http_t
*http
) /* I - HTTP connection */
3065 http_status_t status
; /* Request status */
3068 DEBUG_printf(("httpUpdate(http=%p), state=%s", http
,
3069 httpStateString(http
->state
)));
3072 * Flush pending data, if any...
3077 DEBUG_puts("2httpUpdate: flushing buffer...");
3079 if (httpFlushWrite(http
) < 0)
3080 return (HTTP_STATUS_ERROR
);
3084 * If we haven't issued any commands, then there is nothing to "update"...
3087 if (http
->state
== HTTP_STATE_WAITING
)
3088 return (HTTP_STATUS_CONTINUE
);
3091 * Grab all of the lines we can from the connection...
3094 while (_httpUpdate(http
, &status
));
3097 * See if there was an error...
3100 if (http
->error
== EPIPE
&& http
->status
> HTTP_STATUS_CONTINUE
)
3102 DEBUG_printf(("1httpUpdate: Returning status %d...", http
->status
));
3103 return (http
->status
);
3108 DEBUG_printf(("1httpUpdate: socket error %d - %s", http
->error
,
3109 strerror(http
->error
)));
3110 http
->status
= HTTP_STATUS_ERROR
;
3111 return (HTTP_STATUS_ERROR
);
3115 * Return the current status...
3123 * '_httpWait()' - Wait for data available on a connection (no flush).
3126 int /* O - 1 if data is available, 0 otherwise */
3127 _httpWait(http_t
*http
, /* I - HTTP connection */
3128 int msec
, /* I - Milliseconds to wait */
3129 int usessl
) /* I - Use SSL context? */
3132 struct pollfd pfd
; /* Polled file descriptor */
3134 fd_set input_set
; /* select() input set */
3135 struct timeval timeout
; /* Timeout */
3136 #endif /* HAVE_POLL */
3137 int nfds
; /* Result from select()/poll() */
3140 DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", http
, msec
, usessl
));
3144 DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http
->fd
));
3149 * Check the SSL/TLS buffers for data first...
3153 if (http_tls_pending(http
))
3155 DEBUG_puts("5_httpWait: Return 1 since there is pending TLS data.");
3158 #endif /* HAVE_SSL */
3161 * Then try doing a select() or poll() to poll the socket...
3166 pfd
.events
= POLLIN
;
3170 nfds
= poll(&pfd
, 1, msec
);
3172 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3177 FD_ZERO(&input_set
);
3178 FD_SET(http
->fd
, &input_set
);
3180 DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec
, http
->fd
));
3184 timeout
.tv_sec
= msec
/ 1000;
3185 timeout
.tv_usec
= (msec
% 1000) * 1000;
3187 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, &timeout
);
3190 nfds
= select(http
->fd
+ 1, &input_set
, NULL
, NULL
, NULL
);
3192 DEBUG_printf(("6_httpWait: select() returned %d...", nfds
));
3195 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
3196 WSAGetLastError() == WSAEWOULDBLOCK
));
3198 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
3200 #endif /* HAVE_POLL */
3202 DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds
,
3210 * 'httpWait()' - Wait for data available on a connection.
3212 * @since CUPS 1.1.19/OS X 10.3@
3215 int /* O - 1 if data is available, 0 otherwise */
3216 httpWait(http_t
*http
, /* I - HTTP connection */
3217 int msec
) /* I - Milliseconds to wait */
3220 * First see if there is data in the buffer...
3223 DEBUG_printf(("2httpWait(http=%p, msec=%d)", http
, msec
));
3230 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3235 if (http
->coding
>= _HTTP_CODING_GUNZIP
&& http
->stream
.avail_in
> 0)
3237 DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
3240 #endif /* HAVE_LIBZ */
3243 * Flush pending data, if any...
3248 DEBUG_puts("3httpWait: Flushing write buffer.");
3250 if (httpFlushWrite(http
) < 0)
3255 * If not, check the SSL/TLS buffers and do a select() on the connection...
3258 return (_httpWait(http
, msec
, 1));
3263 * 'httpWrite()' - Write data to a HTTP connection.
3265 * This function is deprecated. Use the httpWrite2() function which can
3266 * write more than 2GB of data.
3271 int /* O - Number of bytes written */
3272 httpWrite(http_t
*http
, /* I - HTTP connection */
3273 const char *buffer
, /* I - Buffer for data */
3274 int length
) /* I - Number of bytes to write */
3276 return ((int)httpWrite2(http
, buffer
, length
));
3281 * 'httpWrite2()' - Write data to a HTTP connection.
3283 * @since CUPS 1.2/OS X 10.5@
3286 ssize_t
/* O - Number of bytes written */
3287 httpWrite2(http_t
*http
, /* I - HTTP connection */
3288 const char *buffer
, /* I - Buffer for data */
3289 size_t length
) /* I - Number of bytes to write */
3291 ssize_t bytes
; /* Bytes written */
3294 DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
3295 buffer
, CUPS_LLCAST length
));
3298 * Range check input...
3301 if (!http
|| !buffer
)
3303 DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
3308 * Mark activity on the connection...
3311 http
->activity
= time(NULL
);
3314 * Buffer small writes for better performance...
3320 DEBUG_printf(("1httpWrite2: http->coding=%d", http
->coding
));
3324 http_content_coding_finish(http
);
3329 http
->stream
.next_in
= (Bytef
*)buffer
;
3330 http
->stream
.avail_in
= length
;
3331 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3332 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3334 while (deflate(&(http
->stream
), Z_NO_FLUSH
) == Z_OK
)
3336 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3338 if (http
->stream
.avail_out
== 0)
3340 if (httpFlushWrite(http
) < 0)
3342 DEBUG_puts("1httpWrite2: Unable to flush, returning -1.");
3346 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
;
3347 http
->stream
.avail_out
= sizeof(http
->wbuffer
);
3351 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3356 #endif /* HAVE_LIBZ */
3359 if (http
->wused
&& (length
+ http
->wused
) > sizeof(http
->wbuffer
))
3361 DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
3362 CUPS_LLFMT
")", http
->wused
, CUPS_LLCAST length
));
3364 httpFlushWrite(http
);
3367 if ((length
+ http
->wused
) <= sizeof(http
->wbuffer
) &&
3368 length
< sizeof(http
->wbuffer
))
3371 * Write to buffer...
3374 DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT
" bytes to wbuffer...",
3375 CUPS_LLCAST length
));
3377 memcpy(http
->wbuffer
+ http
->wused
, buffer
, length
);
3378 http
->wused
+= (int)length
;
3379 bytes
= (ssize_t
)length
;
3384 * Otherwise write the data directly...
3387 DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT
" bytes to socket...",
3388 CUPS_LLCAST length
));
3390 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3391 bytes
= (ssize_t
)http_write_chunk(http
, buffer
, (int)length
);
3393 bytes
= (ssize_t
)http_write(http
, buffer
, (int)length
);
3395 DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT
" bytes...",
3396 CUPS_LLCAST bytes
));
3399 if (http
->data_encoding
== HTTP_ENCODING_LENGTH
)
3400 http
->data_remaining
-= bytes
;
3406 * Handle end-of-request processing...
3409 if ((http
->data_encoding
== HTTP_ENCODING_CHUNKED
&& length
== 0) ||
3410 (http
->data_encoding
== HTTP_ENCODING_LENGTH
&& http
->data_remaining
== 0))
3413 * Finished with the transfer; unless we are sending POST or PUT
3419 http_content_coding_finish(http
);
3420 #endif /* HAVE_LIBZ */
3424 if (httpFlushWrite(http
) < 0)
3428 if (http
->data_encoding
== HTTP_ENCODING_CHUNKED
)
3431 * Send a 0-length chunk at the end of the request...
3434 http_write(http
, "0\r\n\r\n", 5);
3437 * Reset the data state...
3440 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3441 http
->data_remaining
= 0;
3444 if (http
->state
== HTTP_STATE_POST_RECV
)
3446 else if (http
->state
== HTTP_STATE_POST_SEND
)
3447 http
->state
= HTTP_STATE_WAITING
;
3449 http
->state
= HTTP_STATE_STATUS
;
3451 DEBUG_printf(("2httpWrite2: Changed state to %s.",
3452 httpStateString(http
->state
)));
3455 DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT
".", CUPS_LLCAST bytes
));
3462 * 'httpWriteResponse()' - Write a HTTP response to a client connection.
3464 * @since CUPS 1.7/OS X 10.9@
3467 int /* O - 0 on success, -1 on error */
3468 httpWriteResponse(http_t
*http
, /* I - HTTP connection */
3469 http_status_t status
) /* I - Status code */
3471 http_encoding_t old_encoding
; /* Old data_encoding value */
3472 off_t old_remaining
; /* Old data_remaining value */
3476 * Range check input...
3479 DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", http
, status
));
3481 if (!http
|| status
< HTTP_STATUS_CONTINUE
)
3483 DEBUG_puts("1httpWriteResponse: Bad input.");
3488 * Set the various standard fields if they aren't already...
3491 if (!http
->fields
[HTTP_FIELD_DATE
][0])
3492 httpSetField(http
, HTTP_FIELD_DATE
, httpGetDateString(time(NULL
)));
3494 if (status
>= HTTP_STATUS_BAD_REQUEST
&& http
->keep_alive
)
3496 http
->keep_alive
= HTTP_KEEPALIVE_OFF
;
3497 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "");
3500 if (http
->version
== HTTP_VERSION_1_1
)
3502 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3504 if (http
->keep_alive
)
3505 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Keep-Alive");
3507 httpSetField(http
, HTTP_FIELD_CONNECTION
, "close");
3510 if (http
->keep_alive
&& !http
->fields
[HTTP_FIELD_KEEP_ALIVE
][0])
3511 httpSetField(http
, HTTP_FIELD_KEEP_ALIVE
, "timeout=10");
3515 if (status
== HTTP_STATUS_UPGRADE_REQUIRED
||
3516 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
3518 if (!http
->fields
[HTTP_FIELD_CONNECTION
][0])
3519 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
3521 if (!http
->fields
[HTTP_FIELD_UPGRADE
][0])
3522 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
3524 if (!http
->fields
[HTTP_FIELD_CONTENT_LENGTH
][0])
3525 httpSetField(http
, HTTP_FIELD_CONTENT_LENGTH
, "0");
3527 #endif /* HAVE_SSL */
3530 httpSetField(http
, HTTP_FIELD_SERVER
,
3531 http
->default_server
? http
->default_server
: CUPS_MINIMAL
);
3534 * Set the Accept-Encoding field if it isn't already...
3537 if (!http
->accept_encoding
)
3538 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
3539 http
->default_accept_encoding
? http
->default_accept_encoding
:
3541 "gzip, deflate, identity");
3544 #endif /* HAVE_LIBZ */
3547 * Send the response header...
3550 old_encoding
= http
->data_encoding
;
3551 old_remaining
= http
->data_remaining
;
3552 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
3554 if (httpPrintf(http
, "HTTP/%d.%d %d %s\r\n", http
->version
/ 100,
3555 http
->version
% 100, (int)status
, httpStatus(status
)) < 0)
3557 http
->status
= HTTP_STATUS_ERROR
;
3561 if (status
!= HTTP_STATUS_CONTINUE
)
3564 * 100 Continue doesn't have the rest of the response headers...
3567 int i
; /* Looping var */
3568 const char *value
; /* Field value */
3570 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
3572 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
3574 if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
3576 http
->status
= HTTP_STATUS_ERROR
;
3584 if (httpPrintf(http
, "Set-Cookie: %s path=/ httponly%s\r\n",
3585 http
->cookie
, http
->tls
? " secure" : "") < 1)
3587 http
->status
= HTTP_STATUS_ERROR
;
3593 if (httpWrite2(http
, "\r\n", 2) < 2)
3595 http
->status
= HTTP_STATUS_ERROR
;
3599 if (httpFlushWrite(http
) < 0)
3601 http
->status
= HTTP_STATUS_ERROR
;
3605 if (status
== HTTP_STATUS_CONTINUE
||
3606 status
== HTTP_STATUS_SWITCHING_PROTOCOLS
)
3609 * Restore the old data_encoding and data_length values...
3612 http
->data_encoding
= old_encoding
;
3613 http
->data_remaining
= old_remaining
;
3615 if (old_remaining
<= INT_MAX
)
3616 http
->_data_remaining
= (int)old_remaining
;
3618 http
->_data_remaining
= INT_MAX
;
3620 else if (http
->state
== HTTP_STATE_OPTIONS
||
3621 http
->state
== HTTP_STATE_HEAD
||
3622 http
->state
== HTTP_STATE_PUT
||
3623 http
->state
== HTTP_STATE_TRACE
||
3624 http
->state
== HTTP_STATE_CONNECT
||
3625 http
->state
== HTTP_STATE_STATUS
)
3627 DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
3628 "was %s.", httpStateString(http
->state
)));
3629 http
->state
= HTTP_STATE_WAITING
;
3634 * Force data_encoding and data_length to be set according to the response
3638 http_set_length(http
);
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 */
3657 * 'http_content_coding_finish()' - Finish doing any content encoding.
3661 http_content_coding_finish(
3662 http_t
*http
) /* I - HTTP connection */
3664 int zerr
; /* Compression status */
3667 switch (http
->coding
)
3669 case _HTTP_CODING_DEFLATE
:
3670 case _HTTP_CODING_GZIP
:
3673 http
->stream
.next_out
= (Bytef
*)http
->wbuffer
+ http
->wused
;
3674 http
->stream
.avail_out
= sizeof(http
->wbuffer
) - http
->wused
;
3676 zerr
= deflate(&(http
->stream
), Z_FINISH
);
3678 http
->wused
= sizeof(http
->wbuffer
) - http
->stream
.avail_out
;
3679 if (http
->wused
== sizeof(http
->wbuffer
))
3680 httpFlushWrite(http
);
3682 while (zerr
== Z_OK
);
3684 deflateEnd(&(http
->stream
));
3687 httpFlushWrite(http
);
3690 case _HTTP_CODING_INFLATE
:
3691 case _HTTP_CODING_GUNZIP
:
3692 inflateEnd(&(http
->stream
));
3693 free(http
->dbuffer
);
3694 http
->dbuffer
= NULL
;
3701 http
->coding
= _HTTP_CODING_IDENTITY
;
3706 * 'http_content_coding_start()' - Start doing content encoding.
3710 http_content_coding_start(
3711 http_t
*http
, /* I - HTTP connection */
3712 const char *value
) /* I - Value of Content-Encoding */
3714 int zerr
; /* Error/status */
3715 _http_coding_t coding
; /* Content coding value */
3718 DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", http
,
3721 if (http
->coding
!= _HTTP_CODING_IDENTITY
)
3723 DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
3727 else if (!strcmp(value
, "x-gzip") || !strcmp(value
, "gzip"))
3729 if (http
->state
== HTTP_STATE_GET_SEND
||
3730 http
->state
== HTTP_STATE_POST_SEND
)
3731 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_GZIP
:
3732 _HTTP_CODING_GUNZIP
;
3733 else if (http
->state
== HTTP_STATE_POST_RECV
||
3734 http
->state
== HTTP_STATE_PUT_RECV
)
3735 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_GZIP
:
3736 _HTTP_CODING_GUNZIP
;
3739 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3743 else if (!strcmp(value
, "x-deflate") || !strcmp(value
, "deflate"))
3745 if (http
->state
== HTTP_STATE_GET_SEND
||
3746 http
->state
== HTTP_STATE_POST_SEND
)
3747 coding
= http
->mode
== _HTTP_MODE_SERVER
? _HTTP_CODING_DEFLATE
:
3748 _HTTP_CODING_INFLATE
;
3749 else if (http
->state
== HTTP_STATE_POST_RECV
||
3750 http
->state
== HTTP_STATE_PUT_RECV
)
3751 coding
= http
->mode
== _HTTP_MODE_CLIENT
? _HTTP_CODING_DEFLATE
:
3752 _HTTP_CODING_INFLATE
;
3755 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3761 DEBUG_puts("1http_content_coding_start: Not doing content coding.");
3765 memset(&(http
->stream
), 0, sizeof(http
->stream
));
3769 case _HTTP_CODING_DEFLATE
:
3770 case _HTTP_CODING_GZIP
:
3772 httpFlushWrite(http
);
3775 * Window size for compression is 11 bits - optimal based on PWG Raster
3776 * sample files on pwg.org. -11 is raw deflate, 27 is gzip, per ZLIB
3780 if ((zerr
= deflateInit2(&(http
->stream
), Z_DEFAULT_COMPRESSION
,
3782 coding
== _HTTP_CODING_DEFLATE
? -11 : 27, 7,
3783 Z_DEFAULT_STRATEGY
)) < Z_OK
)
3785 http
->status
= HTTP_STATUS_ERROR
;
3786 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
3791 case _HTTP_CODING_INFLATE
:
3792 case _HTTP_CODING_GUNZIP
:
3793 if ((http
->dbuffer
= malloc(HTTP_MAX_BUFFER
)) == NULL
)
3795 http
->status
= HTTP_STATUS_ERROR
;
3796 http
->error
= errno
;
3801 * Window size for decompression is up to 15 bits (maximum supported).
3802 * -15 is raw inflate, 31 is gunzip, per ZLIB documentation.
3805 if ((zerr
= inflateInit2(&(http
->stream
),
3806 coding
== _HTTP_CODING_INFLATE
? -15 : 31))
3809 free(http
->dbuffer
);
3810 http
->dbuffer
= NULL
;
3811 http
->status
= HTTP_STATUS_ERROR
;
3812 http
->error
= zerr
== Z_MEM_ERROR
? ENOMEM
: EINVAL
;
3816 http
->stream
.avail_in
= 0;
3817 http
->stream
.next_in
= http
->dbuffer
;
3824 http
->coding
= coding
;
3826 DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
3829 #endif /* HAVE_LIBZ */
3833 * 'http_create()' - Create an unconnected HTTP connection.
3836 static http_t
* /* O - HTTP connection */
3838 const char *host
, /* I - Hostname */
3839 int port
, /* I - Port number */
3840 http_addrlist_t
*addrlist
, /* I - Address list or NULL */
3841 int family
, /* I - Address family or AF_UNSPEC */
3842 http_encryption_t encryption
, /* I - Encryption to use */
3843 int blocking
, /* I - 1 for blocking mode */
3844 _http_mode_t mode
) /* I - _HTTP_MODE_CLIENT or _SERVER */
3846 http_t
*http
; /* New HTTP connection */
3847 char service
[255]; /* Service name */
3848 http_addrlist_t
*myaddrlist
= NULL
; /* My address list */
3851 DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, "
3852 "encryption=%d, blocking=%d, mode=%d)", host
, port
, addrlist
,
3853 family
, encryption
, blocking
, mode
));
3855 if (!host
&& mode
== _HTTP_MODE_CLIENT
)
3861 * Lookup the host...
3866 myaddrlist
= httpAddrCopyList(addrlist
);
3870 snprintf(service
, sizeof(service
), "%d", port
);
3872 myaddrlist
= httpAddrGetList(host
, family
, service
);
3879 * Allocate memory for the structure...
3882 if ((http
= calloc(sizeof(http_t
), 1)) == NULL
)
3884 _cupsSetError(IPP_STATUS_ERROR_INTERNAL
, strerror(errno
), 0);
3885 httpAddrFreeList(addrlist
);
3890 * Initialize the HTTP data...
3894 http
->activity
= time(NULL
);
3895 http
->addrlist
= myaddrlist
;
3896 http
->blocking
= blocking
;
3899 http
->gssctx
= GSS_C_NO_CONTEXT
;
3900 http
->gssname
= GSS_C_NO_NAME
;
3901 #endif /* HAVE_GSSAPI */
3902 http
->status
= HTTP_STATUS_CONTINUE
;
3903 http
->version
= HTTP_VERSION_1_1
;
3906 strlcpy(http
->hostname
, host
, sizeof(http
->hostname
));
3908 if (port
== 443) /* Always use encryption for https */
3909 http
->encryption
= HTTP_ENCRYPTION_ALWAYS
;
3911 http
->encryption
= encryption
;
3913 http_set_wait(http
);
3916 * Return the new structure...
3922 /* For OS X 10.8 and earlier */
3923 http_t
*_httpCreate(const char *host
, int port
, http_addrlist_t
*addrlist
,
3924 http_encryption_t encryption
, int family
)
3925 { return (http_create(host
, port
, addrlist
, family
, encryption
, 1,
3926 _HTTP_MODE_CLIENT
)); }
3931 * 'http_debug_hex()' - Do a hex dump of a buffer.
3935 http_debug_hex(const char *prefix
, /* I - Prefix for line */
3936 const char *buffer
, /* I - Buffer to dump */
3937 int bytes
) /* I - Bytes to dump */
3939 int i
, j
, /* Looping vars */
3940 ch
; /* Current character */
3941 char line
[255], /* Line buffer */
3942 *start
, /* Start of line after prefix */
3943 *ptr
; /* Pointer into line */
3946 if (_cups_debug_fd
< 0 || _cups_debug_level
< 6)
3949 DEBUG_printf(("6%s: %d bytes:", prefix
, bytes
));
3951 snprintf(line
, sizeof(line
), "6%s: ", prefix
);
3952 start
= line
+ strlen(line
);
3954 for (i
= 0; i
< bytes
; i
+= 16)
3956 for (j
= 0, ptr
= start
; j
< 16 && (i
+ j
) < bytes
; j
++, ptr
+= 2)
3957 sprintf(ptr
, "%02X", buffer
[i
+ j
] & 255);
3961 memcpy(ptr
, " ", 3);
3966 memcpy(ptr
, " ", 3);
3969 for (j
= 0; j
< 16 && (i
+ j
) < bytes
; j
++)
3971 ch
= buffer
[i
+ j
] & 255;
3973 if (ch
< ' ' || ch
>= 127)
3987 * 'http_read()' - Read a buffer from a HTTP connection.
3989 * This function does the low-level read from the socket, retrying and timing
3993 static ssize_t
/* O - Number of bytes read or -1 on error */
3994 http_read(http_t
*http
, /* I - HTTP connection */
3995 char *buffer
, /* I - Buffer */
3996 size_t length
) /* I - Maximum bytes to read */
3998 ssize_t bytes
; /* Bytes read */
4001 DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4002 buffer
, CUPS_LLCAST length
));
4004 if (!http
->blocking
)
4006 while (!httpWait(http
, http
->wait_value
))
4008 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4011 DEBUG_puts("2http_read: Timeout.");
4016 DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length
));
4022 bytes
= http_tls_read(http
, buffer
, length
);
4024 #endif /* HAVE_SSL */
4025 bytes
= recv(http
->fd
, buffer
, length
, 0);
4030 if (WSAGetLastError() != WSAEINTR
)
4032 http
->error
= WSAGetLastError();
4035 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4037 if (!http
->timeout_cb
||
4038 !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4040 http
->error
= WSAEWOULDBLOCK
;
4045 DEBUG_printf(("2http_read: %s", strerror(errno
)));
4047 if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4049 if (http
->timeout_cb
&& !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4051 http
->error
= errno
;
4054 else if (!http
->timeout_cb
&& errno
!= EAGAIN
)
4056 http
->error
= errno
;
4060 else if (errno
!= EINTR
)
4062 http
->error
= errno
;
4070 DEBUG_printf(("2http_read: Read " CUPS_LLFMT
" bytes into buffer.",
4071 CUPS_LLCAST bytes
));
4074 http_debug_hex("http_read", buffer
, (int)bytes
);
4080 if (WSAGetLastError() == WSAEINTR
)
4083 http
->error
= WSAGetLastError();
4085 if (errno
== EINTR
|| (errno
== EAGAIN
&& !http
->timeout_cb
))
4088 http
->error
= errno
;
4091 else if (bytes
== 0)
4093 http
->error
= EPIPE
;
4102 * 'http_read_buffered()' - Do a buffered read from a HTTP connection.
4104 * This function reads data from the HTTP buffer or from the socket, as needed.
4107 static ssize_t
/* O - Number of bytes read or -1 on error */
4108 http_read_buffered(http_t
*http
, /* I - HTTP connection */
4109 char *buffer
, /* I - Buffer */
4110 size_t length
) /* I - Maximum bytes to read */
4112 ssize_t bytes
; /* Bytes read */
4115 DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT
4117 http
, buffer
, CUPS_LLCAST length
, http
->used
));
4121 if (length
> (size_t)http
->used
)
4122 bytes
= (size_t)http
->used
;
4126 DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
4129 memcpy(buffer
, http
->buffer
, bytes
);
4130 http
->used
-= (int)bytes
;
4133 memmove(http
->buffer
, http
->buffer
+ bytes
, http
->used
);
4136 bytes
= http_read(http
, buffer
, length
);
4143 * 'http_read_chunk()' - Read a chunk from a HTTP connection.
4145 * This function reads and validates the chunk length, then does a buffered read
4146 * returning the number of bytes placed in the buffer.
4149 static ssize_t
/* O - Number of bytes read or -1 on error */
4150 http_read_chunk(http_t
*http
, /* I - HTTP connection */
4151 char *buffer
, /* I - Buffer */
4152 size_t length
) /* I - Maximum bytes to read */
4154 DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4155 http
, buffer
, CUPS_LLCAST length
));
4157 if (http
->data_remaining
<= 0)
4159 char len
[32]; /* Length string */
4161 if (!httpGets(len
, sizeof(len
), http
))
4163 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4169 DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
4170 if (!httpGets(len
, sizeof(len
), http
))
4172 DEBUG_puts("1http_read_chunk: Could not get chunk length.");
4177 http
->data_remaining
= strtoll(len
, NULL
, 16);
4179 if (http
->data_remaining
< 0)
4181 DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
4182 CUPS_LLFMT
")", len
, CUPS_LLCAST http
->data_remaining
));
4186 DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT
")",
4187 len
, CUPS_LLCAST http
->data_remaining
));
4189 if (http
->data_remaining
== 0)
4192 * 0-length chunk, grab trailing blank line...
4195 httpGets(len
, sizeof(len
), http
);
4199 DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT
,
4200 CUPS_LLCAST http
->data_remaining
));
4202 if (http
->data_remaining
<= 0)
4204 else if (length
> (size_t)http
->data_remaining
)
4205 length
= (size_t)http
->data_remaining
;
4207 return (http_read_buffered(http
, buffer
, length
));
4212 * 'http_send()' - Send a request with all fields and the trailing blank line.
4215 static int /* O - 0 on success, non-zero on error */
4216 http_send(http_t
*http
, /* I - HTTP connection */
4217 http_state_t request
, /* I - Request code */
4218 const char *uri
) /* I - URI */
4220 int i
; /* Looping var */
4221 char buf
[1024]; /* Encoded URI buffer */
4222 const char *value
; /* Field value */
4223 static const char * const codes
[] = /* Request code strings */
4243 DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
4244 http
, codes
[request
], uri
));
4246 if (http
== NULL
|| uri
== NULL
)
4250 * Set the User-Agent field if it isn't already...
4253 if (!http
->fields
[HTTP_FIELD_USER_AGENT
][0])
4255 if (http
->default_user_agent
)
4256 httpSetField(http
, HTTP_FIELD_USER_AGENT
, http
->default_user_agent
);
4258 httpSetField(http
, HTTP_FIELD_USER_AGENT
, cupsUserAgent());
4262 * Set the Accept-Encoding field if it isn't already...
4265 if (!http
->accept_encoding
&& http
->default_accept_encoding
)
4266 httpSetField(http
, HTTP_FIELD_ACCEPT_ENCODING
,
4267 http
->default_accept_encoding
);
4270 * Encode the URI as needed...
4273 _httpEncodeURI(buf
, uri
, sizeof(buf
));
4276 * See if we had an error the last time around; if so, reconnect...
4279 if (http
->fd
< 0 || http
->status
== HTTP_STATUS_ERROR
||
4280 http
->status
>= HTTP_STATUS_BAD_REQUEST
)
4282 DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
4283 http
->fd
, http
->status
, http
->tls_upgrade
));
4285 if (httpReconnect2(http
, 30000, NULL
))
4290 * Flush any written data that is pending...
4295 if (httpFlushWrite(http
) < 0)
4296 if (httpReconnect2(http
, 30000, NULL
))
4301 * Send the request header...
4304 http
->state
= request
;
4305 http
->data_encoding
= HTTP_ENCODING_FIELDS
;
4307 if (request
== HTTP_STATE_POST
|| request
== HTTP_STATE_PUT
)
4310 http
->status
= HTTP_STATUS_CONTINUE
;
4313 if (http
->encryption
== HTTP_ENCRYPTION_REQUIRED
&& !http
->tls
)
4315 httpSetField(http
, HTTP_FIELD_CONNECTION
, "Upgrade");
4316 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4318 #endif /* HAVE_SSL */
4320 if (httpPrintf(http
, "%s %s HTTP/1.1\r\n", codes
[request
], buf
) < 1)
4322 http
->status
= HTTP_STATUS_ERROR
;
4326 for (i
= 0; i
< HTTP_FIELD_MAX
; i
++)
4327 if ((value
= httpGetField(http
, i
)) != NULL
&& *value
)
4329 DEBUG_printf(("5http_send: %s: %s", http_fields
[i
], value
));
4331 if (i
== HTTP_FIELD_HOST
)
4333 if (httpPrintf(http
, "Host: %s:%d\r\n", value
,
4334 httpAddrPort(http
->hostaddr
)) < 1)
4336 http
->status
= HTTP_STATUS_ERROR
;
4340 else if (httpPrintf(http
, "%s: %s\r\n", http_fields
[i
], value
) < 1)
4342 http
->status
= HTTP_STATUS_ERROR
;
4348 if (httpPrintf(http
, "Cookie: $Version=0; %s\r\n", http
->cookie
) < 1)
4350 http
->status
= HTTP_STATUS_ERROR
;
4354 DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http
->expect
,
4355 http
->mode
, http
->state
));
4357 if (http
->expect
== HTTP_STATUS_CONTINUE
&& http
->mode
== _HTTP_MODE_CLIENT
&&
4358 (http
->state
== HTTP_STATE_POST_RECV
||
4359 http
->state
== HTTP_STATE_PUT_RECV
))
4360 if (httpPrintf(http
, "Expect: 100-continue\r\n") < 1)
4362 http
->status
= HTTP_STATUS_ERROR
;
4366 if (httpPrintf(http
, "\r\n") < 1)
4368 http
->status
= HTTP_STATUS_ERROR
;
4372 if (httpFlushWrite(http
) < 0)
4375 http_set_length(http
);
4376 httpClearFields(http
);
4379 * The Kerberos and AuthRef authentication strings can only be used once...
4382 if (http
->field_authorization
&& http
->authstring
&&
4383 (!strncmp(http
->authstring
, "Negotiate", 9) ||
4384 !strncmp(http
->authstring
, "AuthRef", 7)))
4386 http
->_authstring
[0] = '\0';
4388 if (http
->authstring
!= http
->_authstring
)
4389 free(http
->authstring
);
4391 http
->authstring
= http
->_authstring
;
4399 * 'http_set_length()' - Set the data_encoding and data_remaining values.
4402 static off_t
/* O - Remainder or -1 on error */
4403 http_set_length(http_t
*http
) /* I - Connection */
4405 off_t remaining
; /* Remainder */
4408 DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", http
, http
->mode
,
4409 httpStateString(http
->state
)));
4411 if ((remaining
= httpGetLength2(http
)) >= 0)
4413 if (http
->mode
== _HTTP_MODE_SERVER
&&
4414 http
->state
!= HTTP_STATE_GET_SEND
&&
4415 http
->state
!= HTTP_STATE_PUT
&&
4416 http
->state
!= HTTP_STATE_POST
&&
4417 http
->state
!= HTTP_STATE_POST_SEND
)
4419 DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
4423 if (!_cups_strcasecmp(http
->fields
[HTTP_FIELD_TRANSFER_ENCODING
],
4426 DEBUG_puts("1http_set_length: Setting data_encoding to "
4427 "HTTP_ENCODING_CHUNKED.");
4428 http
->data_encoding
= HTTP_ENCODING_CHUNKED
;
4432 DEBUG_puts("1http_set_length: Setting data_encoding to "
4433 "HTTP_ENCODING_LENGTH.");
4434 http
->data_encoding
= HTTP_ENCODING_LENGTH
;
4437 DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT
".",
4438 CUPS_LLCAST remaining
));
4439 http
->data_remaining
= remaining
;
4441 if (remaining
<= INT_MAX
)
4442 http
->_data_remaining
= remaining
;
4444 http
->_data_remaining
= INT_MAX
;
4451 * 'http_set_timeout()' - Set the socket timeout values.
4455 http_set_timeout(int fd
, /* I - File descriptor */
4456 double timeout
) /* I - Timeout in seconds */
4459 DWORD tv
= (DWORD
)(timeout
* 1000);
4460 /* Timeout in milliseconds */
4462 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4463 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4466 struct timeval tv
; /* Timeout in secs and usecs */
4468 tv
.tv_sec
= (int)timeout
;
4469 tv
.tv_usec
= (int)(1000000 * fmod(timeout
, 1.0));
4471 setsockopt(fd
, SOL_SOCKET
, SO_RCVTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4472 setsockopt(fd
, SOL_SOCKET
, SO_SNDTIMEO
, CUPS_SOCAST
&tv
, sizeof(tv
));
4478 * 'http_set_wait()' - Set the default wait value for reads.
4482 http_set_wait(http_t
*http
) /* I - HTTP connection */
4486 http
->wait_value
= (int)(http
->timeout_value
* 1000);
4488 if (http
->wait_value
<= 0)
4489 http
->wait_value
= 60000;
4492 http
->wait_value
= 10000;
4498 * 'http_tls_upgrade()' - Force upgrade to TLS encryption.
4501 static int /* O - Status of connection */
4502 http_tls_upgrade(http_t
*http
) /* I - HTTP connection */
4504 int ret
; /* Return value */
4505 http_t myhttp
; /* Local copy of HTTP data */
4508 DEBUG_printf(("7http_tls_upgrade(%p)", http
));
4511 * Flush the connection to make sure any previous "Upgrade" message
4518 * Copy the HTTP data to a local variable so we can do the OPTIONS
4519 * request without interfering with the existing request data...
4522 memcpy(&myhttp
, http
, sizeof(myhttp
));
4525 * Send an OPTIONS request to the server, requiring SSL or TLS
4526 * encryption on the link...
4529 http
->tls_upgrade
= 1;
4530 http
->field_authorization
= NULL
; /* Don't free the auth string */
4532 httpClearFields(http
);
4533 httpSetField(http
, HTTP_FIELD_CONNECTION
, "upgrade");
4534 httpSetField(http
, HTTP_FIELD_UPGRADE
, "TLS/1.2,TLS/1.1,TLS/1.0");
4536 if ((ret
= httpOptions(http
, "*")) == 0)
4539 * Wait for the secure connection...
4542 while (httpUpdate(http
) == HTTP_STATUS_CONTINUE
);
4546 * Restore the HTTP request data...
4549 memcpy(http
->fields
, myhttp
.fields
, sizeof(http
->fields
));
4550 http
->data_encoding
= myhttp
.data_encoding
;
4551 http
->data_remaining
= myhttp
.data_remaining
;
4552 http
->_data_remaining
= myhttp
._data_remaining
;
4553 http
->expect
= myhttp
.expect
;
4554 http
->field_authorization
= myhttp
.field_authorization
;
4555 http
->digest_tries
= myhttp
.digest_tries
;
4556 http
->tls_upgrade
= 0;
4559 * See if we actually went secure...
4565 * Server does not support HTTP upgrade...
4568 DEBUG_puts("8http_tls_upgrade: Server does not support HTTP upgrade!");
4570 httpAddrClose(NULL
, http
->fd
);
4579 #endif /* HAVE_SSL */
4583 * 'http_write()' - Write a buffer to a HTTP connection.
4586 static ssize_t
/* O - Number of bytes written */
4587 http_write(http_t
*http
, /* I - HTTP connection */
4588 const char *buffer
, /* I - Buffer for data */
4589 size_t length
) /* I - Number of bytes to write */
4591 ssize_t tbytes
, /* Total bytes sent */
4592 bytes
; /* Bytes sent */
4595 DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT
")", http
,
4596 buffer
, CUPS_LLCAST length
));
4602 DEBUG_printf(("3http_write: About to write %d bytes.", (int)length
));
4604 if (http
->timeout_cb
)
4607 struct pollfd pfd
; /* Polled file descriptor */
4609 fd_set output_set
; /* Output ready for write? */
4610 struct timeval timeout
; /* Timeout value */
4611 #endif /* HAVE_POLL */
4612 int nfds
; /* Result from select()/poll() */
4618 pfd
.events
= POLLOUT
;
4620 while ((nfds
= poll(&pfd
, 1, http
->wait_value
)) < 0 &&
4621 (errno
== EINTR
|| errno
== EAGAIN
))
4627 FD_ZERO(&output_set
);
4628 FD_SET(http
->fd
, &output_set
);
4630 timeout
.tv_sec
= http
->wait_value
/ 1000;
4631 timeout
.tv_usec
= 1000 * (http
->wait_value
% 1000);
4633 nfds
= select(http
->fd
+ 1, NULL
, &output_set
, NULL
, &timeout
);
4636 while (nfds
< 0 && (WSAGetLastError() == WSAEINTR
||
4637 WSAGetLastError() == WSAEWOULDBLOCK
));
4639 while (nfds
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
4641 #endif /* HAVE_POLL */
4645 http
->error
= errno
;
4648 else if (nfds
== 0 && !(*http
->timeout_cb
)(http
, http
->timeout_data
))
4651 http
->error
= WSAEWOULDBLOCK
;
4653 http
->error
= EWOULDBLOCK
;
4663 bytes
= http_tls_write(http
, buffer
, length
);
4665 #endif /* HAVE_SSL */
4666 bytes
= send(http
->fd
, buffer
, length
, 0);
4668 DEBUG_printf(("3http_write: Write of " CUPS_LLFMT
" bytes returned "
4669 CUPS_LLFMT
".", CUPS_LLCAST length
, CUPS_LLCAST bytes
));
4674 if (WSAGetLastError() == WSAEINTR
)
4676 else if (WSAGetLastError() == WSAEWOULDBLOCK
)
4678 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4681 http
->error
= WSAGetLastError();
4683 else if (WSAGetLastError() != http
->error
&&
4684 WSAGetLastError() != WSAECONNRESET
)
4686 http
->error
= WSAGetLastError();
4693 else if (errno
== EWOULDBLOCK
|| errno
== EAGAIN
)
4695 if (http
->timeout_cb
&& (*http
->timeout_cb
)(http
, http
->timeout_data
))
4697 else if (!http
->timeout_cb
&& errno
== EAGAIN
)
4700 http
->error
= errno
;
4702 else if (errno
!= http
->error
&& errno
!= ECONNRESET
)
4704 http
->error
= errno
;
4709 DEBUG_printf(("3http_write: error writing data (%s).",
4710 strerror(http
->error
)));
4721 http_debug_hex("http_write", buffer
- tbytes
, tbytes
);
4724 DEBUG_printf(("3http_write: Returning " CUPS_LLFMT
".", CUPS_LLCAST tbytes
));
4731 * 'http_write_chunk()' - Write a chunked buffer.
4734 static ssize_t
/* O - Number bytes written */
4735 http_write_chunk(http_t
*http
, /* I - HTTP connection */
4736 const char *buffer
, /* I - Buffer to write */
4737 size_t length
) /* I - Length of buffer */
4739 char header
[16]; /* Chunk header */
4740 ssize_t bytes
; /* Bytes written */
4743 DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT
")",
4744 http
, buffer
, CUPS_LLCAST length
));
4747 * Write the chunk header, data, and trailer.
4750 snprintf(header
, sizeof(header
), "%x\r\n", (unsigned)length
);
4751 if (http_write(http
, header
, strlen(header
)) < 0)
4753 DEBUG_puts("8http_write_chunk: http_write of length failed.");
4757 if ((bytes
= http_write(http
, buffer
, length
)) < 0)
4759 DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
4763 if (http_write(http
, "\r\n", 2) < 0)
4765 DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");