#include "cups-private.h"
#include "debug-internal.h"
#include <fcntl.h>
#include <math.h>
#ifdef _WIN32
# include <tchar.h>
#else
# include <signal.h>
# include <sys/time.h>
# include <sys/resource.h>
#endif
#ifdef HAVE_POLL
# include <poll.h>
#endif
# ifdef HAVE_LIBZ
# include <zlib.h>
# endif
static void http_add_field(http_t *http, http_field_t field, const char *value, int append);
#ifdef HAVE_LIBZ
static void http_content_coding_finish(http_t *http);
static void http_content_coding_start(http_t *http,
const char *value);
#endif
static http_t *http_create(const char *host, int port,
http_addrlist_t *addrlist, int family,
http_encryption_t encryption,
int blocking, _http_mode_t mode);
#ifdef DEBUG
static void http_debug_hex(const char *prefix, const char *buffer,
int bytes);
#endif
static ssize_t http_read(http_t *http, char *buffer, size_t length);
static ssize_t http_read_buffered(http_t *http, char *buffer, size_t length);
static ssize_t http_read_chunk(http_t *http, char *buffer, size_t length);
static int http_send(http_t *http, http_state_t request,
const char *uri);
static ssize_t http_write(http_t *http, const char *buffer,
size_t length);
static ssize_t http_write_chunk(http_t *http, const char *buffer,
size_t length);
static off_t http_set_length(http_t *http);
static void http_set_timeout(int fd, double timeout);
static void http_set_wait(http_t *http);
#ifdef HAVE_SSL
static int http_tls_upgrade(http_t *http);
#endif
static const char * const http_fields[] =
{
"Accept-Language",
"Accept-Ranges",
"Authorization",
"Connection",
"Content-Encoding",
"Content-Language",
"Content-Length",
"Content-Location",
"Content-MD5",
"Content-Range",
"Content-Type",
"Content-Version",
"Date",
"Host",
"If-Modified-Since",
"If-Unmodified-since",
"Keep-Alive",
"Last-Modified",
"Link",
"Location",
"Range",
"Referer",
"Retry-After",
"Transfer-Encoding",
"Upgrade",
"User-Agent",
"WWW-Authenticate",
"Accept-Encoding",
"Allow",
"Server",
"Authentication-Info"
};
http_t *
httpAcceptConnection(int fd,
int blocking)
{
http_t *http;
http_addrlist_t addrlist;
socklen_t addrlen;
int val;
if (fd < 0)
return (NULL);
memset(&addrlist, 0, sizeof(addrlist));
if ((http = http_create(NULL, 0, &addrlist, AF_UNSPEC,
HTTP_ENCRYPTION_IF_REQUESTED, blocking,
_HTTP_MODE_SERVER)) == NULL)
return (NULL);
addrlen = sizeof(http_addr_t);
if ((http->fd = accept(fd, (struct sockaddr *)&(http->addrlist->addr),
&addrlen)) < 0)
{
_cupsSetHTTPError(HTTP_STATUS_ERROR);
httpClose(http);
return (NULL);
}
http->hostaddr = &(http->addrlist->addr);
if (httpAddrLocalhost(http->hostaddr))
strlcpy(http->hostname, "localhost", sizeof(http->hostname));
else
httpAddrString(http->hostaddr, http->hostname, sizeof(http->hostname));
#ifdef SO_NOSIGPIPE
val = 1;
setsockopt(http->fd, SOL_SOCKET, SO_NOSIGPIPE, CUPS_SOCAST &val, sizeof(val));
#endif
val = 1;
setsockopt(http->fd, IPPROTO_TCP, TCP_NODELAY, CUPS_SOCAST &val, sizeof(val));
#ifdef FD_CLOEXEC
fcntl(http->fd, F_SETFD, FD_CLOEXEC);
#endif
return (http);
}
int
httpAddCredential(
cups_array_t *credentials,
const void *data,
size_t datalen)
{
http_credential_t *credential;
if ((credential = malloc(sizeof(http_credential_t))) != NULL)
{
credential->datalen = datalen;
if ((credential->data = malloc(datalen)) != NULL)
{
memcpy(credential->data, data, datalen);
cupsArrayAdd(credentials, credential);
return (0);
}
free(credential);
}
return (-1);
}
void
httpBlocking(http_t *http,
int b)
{
if (http)
{
http->blocking = b;
http_set_wait(http);
}
}
int
httpCheck(http_t *http)
{
return (httpWait(http, 0));
}
void
httpClearCookie(http_t *http)
{
if (!http)
return;
if (http->cookie)
{
free(http->cookie);
http->cookie = NULL;
}
}
void
httpClearFields(http_t *http)
{
http_field_t field;
DEBUG_printf(("httpClearFields(http=%p)", (void *)http));
if (http)
{
memset(http->_fields, 0, sizeof(http->fields));
for (field = HTTP_FIELD_ACCEPT_LANGUAGE; field < HTTP_FIELD_MAX; field ++)
{
if (http->fields[field] && http->fields[field] != http->_fields[field])
free(http->fields[field]);
http->fields[field] = NULL;
}
if (http->mode == _HTTP_MODE_CLIENT)
{
if (http->hostname[0] == '/')
httpSetField(http, HTTP_FIELD_HOST, "localhost");
else
httpSetField(http, HTTP_FIELD_HOST, http->hostname);
}
http->expect = (http_status_t)0;
}
}
void
httpClose(http_t *http)
{
#ifdef HAVE_GSSAPI
OM_uint32 minor_status;
#endif
DEBUG_printf(("httpClose(http=%p)", (void *)http));
if (!http)
return;
_httpDisconnect(http);
httpAddrFreeList(http->addrlist);
if (http->cookie)
free(http->cookie);
#ifdef HAVE_GSSAPI
if (http->gssctx != GSS_C_NO_CONTEXT)
gss_delete_sec_context(&minor_status, &http->gssctx, GSS_C_NO_BUFFER);
if (http->gssname != GSS_C_NO_NAME)
gss_release_name(&minor_status, &http->gssname);
#endif
#ifdef HAVE_AUTHORIZATION_H
if (http->auth_ref)
AuthorizationFree(http->auth_ref, kAuthorizationFlagDefaults);
#endif
httpClearFields(http);
if (http->authstring && http->authstring != http->_authstring)
free(http->authstring);
free(http);
}
int
httpCompareCredentials(
cups_array_t *cred1,
cups_array_t *cred2)
{
http_credential_t *temp1, *temp2;
for (temp1 = (http_credential_t *)cupsArrayFirst(cred1), temp2 = (http_credential_t *)cupsArrayFirst(cred2); temp1 && temp2; temp1 = (http_credential_t *)cupsArrayNext(cred1), temp2 = (http_credential_t *)cupsArrayNext(cred2))
if (temp1->datalen != temp2->datalen)
return (0);
else if (memcmp(temp1->data, temp2->data, temp1->datalen))
return (0);
return (temp1 == temp2);
}
http_t *
httpConnect(const char *host,
int port)
{
return (httpConnect2(host, port, NULL, AF_UNSPEC,
HTTP_ENCRYPTION_IF_REQUESTED, 1, 30000, NULL));
}
http_t *
httpConnect2(
const char *host,
int port,
http_addrlist_t *addrlist,
int family,
http_encryption_t encryption,
int blocking,
int msec,
int *cancel)
{
http_t *http;
DEBUG_printf(("httpConnect2(host=\"%s\", port=%d, addrlist=%p, family=%d, encryption=%d, blocking=%d, msec=%d, cancel=%p)", host, port, (void *)addrlist, family, encryption, blocking, msec, (void *)cancel));
if ((http = http_create(host, port, addrlist, family, encryption, blocking,
_HTTP_MODE_CLIENT)) == NULL)
return (NULL);
if (msec == 0 || !httpReconnect2(http, msec, cancel))
return (http);
httpClose(http);
return (NULL);
}
http_t *
httpConnectEncrypt(
const char *host,
int port,
http_encryption_t encryption)
{
DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
host, port, encryption));
return (httpConnect2(host, port, NULL, AF_UNSPEC, encryption, 1, 30000,
NULL));
}
int
httpDelete(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_STATE_DELETE, uri));
}
void
_httpDisconnect(http_t *http)
{
#ifdef HAVE_SSL
if (http->tls)
_httpTLSStop(http);
#endif
httpAddrClose(NULL, http->fd);
http->fd = -1;
}
int
httpEncryption(http_t *http,
http_encryption_t e)
{
DEBUG_printf(("httpEncryption(http=%p, e=%d)", (void *)http, e));
#ifdef HAVE_SSL
if (!http)
return (0);
if (http->mode == _HTTP_MODE_CLIENT)
{
http->encryption = e;
if ((http->encryption == HTTP_ENCRYPTION_ALWAYS && !http->tls) ||
(http->encryption == HTTP_ENCRYPTION_NEVER && http->tls))
return (httpReconnect2(http, 30000, NULL));
else if (http->encryption == HTTP_ENCRYPTION_REQUIRED && !http->tls)
return (http_tls_upgrade(http));
else
return (0);
}
else
{
if (e == HTTP_ENCRYPTION_NEVER && http->tls)
return (-1);
http->encryption = e;
if (e != HTTP_ENCRYPTION_IF_REQUESTED && !http->tls)
return (_httpTLSStart(http));
else
return (0);
}
#else
if (e == HTTP_ENCRYPTION_ALWAYS || e == HTTP_ENCRYPTION_REQUIRED)
return (-1);
else
return (0);
#endif
}
int
httpError(http_t *http)
{
if (http)
return (http->error);
else
return (EINVAL);
}
http_field_t
httpFieldValue(const char *name)
{
int i;
for (i = 0; i < HTTP_FIELD_MAX; i ++)
if (!_cups_strcasecmp(name, http_fields[i]))
return ((http_field_t)i);
return (HTTP_FIELD_UNKNOWN);
}
void
httpFlush(http_t *http)
{
char buffer[8192];
int blocking;
http_state_t oldstate;
DEBUG_printf(("httpFlush(http=%p), state=%s", (void *)http, httpStateString(http->state)));
if (http->state == HTTP_STATE_WAITING)
return;
blocking = http->blocking;
http->blocking = 0;
oldstate = http->state;
while (httpRead2(http, buffer, sizeof(buffer)) > 0);
http->blocking = blocking;
if (http->state == oldstate && http->state != HTTP_STATE_WAITING &&
http->fd >= 0)
{
#ifdef HAVE_LIBZ
if (http->coding)
http_content_coding_finish(http);
#endif
DEBUG_puts("1httpFlush: Setting state to HTTP_STATE_WAITING and closing.");
http->state = HTTP_STATE_WAITING;
#ifdef HAVE_SSL
if (http->tls)
_httpTLSStop(http);
#endif
httpAddrClose(NULL, http->fd);
http->fd = -1;
}
}
int
httpFlushWrite(http_t *http)
{
ssize_t bytes;
DEBUG_printf(("httpFlushWrite(http=%p) data_encoding=%d", (void *)http, http ? http->data_encoding : 100));
if (!http || !http->wused)
{
DEBUG_puts(http ? "1httpFlushWrite: Write buffer is empty." :
"1httpFlushWrite: No connection.");
return (0);
}
if (http->data_encoding == HTTP_ENCODING_CHUNKED)
bytes = http_write_chunk(http, http->wbuffer, (size_t)http->wused);
else
bytes = http_write(http, http->wbuffer, (size_t)http->wused);
http->wused = 0;
DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", (int)bytes, errno));
return ((int)bytes);
}
void
httpFreeCredentials(
cups_array_t *credentials)
{
http_credential_t *credential;
for (credential = (http_credential_t *)cupsArrayFirst(credentials);
credential;
credential = (http_credential_t *)cupsArrayNext(credentials))
{
cupsArrayRemove(credentials, credential);
free((void *)credential->data);
free(credential);
}
cupsArrayDelete(credentials);
}
int
httpGet(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_STATE_GET, uri));
}
time_t
httpGetActivity(http_t *http)
{
return (http ? http->activity : 0);
}
char *
httpGetAuthString(http_t *http)
{
if (http)
return (http->authstring);
else
return (NULL);
}
int
httpGetBlocking(http_t *http)
{
return (http ? http->blocking : 0);
}
const char *
httpGetContentEncoding(http_t *http)
{
#ifdef HAVE_LIBZ
if (http && http->fields[HTTP_FIELD_ACCEPT_ENCODING])
{
int i;
char temp[HTTP_MAX_VALUE],
*start,
*end;
double qvalue;
struct lconv *loc = localeconv();
static const char * const codings[] =
{
"deflate",
"gzip",
"x-deflate",
"x-gzip"
};
strlcpy(temp, http->fields[HTTP_FIELD_ACCEPT_ENCODING], sizeof(temp));
for (start = temp; *start; start = end)
{
qvalue = 1.0;
end = start;
while (*end && *end != ';' && *end != ',' && !isspace(*end & 255))
end ++;
if (*end == ';')
{
if (!strncmp(end, ";q=", 3))
qvalue = _cupsStrScand(end + 3, NULL, loc);
*end++ = '\0';
while (*end && *end != ',' && !isspace(*end & 255))
end ++;
}
else if (*end)
*end++ = '\0';
while (*end && isspace(*end & 255))
end ++;
if (qvalue <= 0.0)
continue;
for (i = 0; i < (int)(sizeof(codings) / sizeof(codings[0])); i ++)
if (!strcmp(start, codings[i]))
return (codings[i]);
}
}
#endif
return (NULL);
}
const char *
httpGetCookie(http_t *http)
{
return (http ? http->cookie : NULL);
}
http_encryption_t
httpGetEncryption(http_t *http)
{
return (http ? http->encryption : HTTP_ENCRYPTION_IF_REQUESTED);
}
http_status_t
httpGetExpect(http_t *http)
{
if (!http)
return (HTTP_STATUS_ERROR);
else
return (http->expect);
}
int
httpGetFd(http_t *http)
{
return (http ? http->fd : -1);
}
const char *
httpGetField(http_t *http,
http_field_t field)
{
if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
return (NULL);
else if (http->fields[field])
return (http->fields[field]);
else
return ("");
}
http_keepalive_t
httpGetKeepAlive(http_t *http)
{
return (http ? http->keep_alive : HTTP_KEEPALIVE_OFF);
}
int
httpGetLength(http_t *http)
{
if (http)
{
httpGetLength2(http);
return (http->_data_remaining);
}
else
return (-1);
}
off_t
httpGetLength2(http_t *http)
{
off_t remaining;
DEBUG_printf(("2httpGetLength2(http=%p), state=%s", (void *)http, httpStateString(http->state)));
if (!http)
return (-1);
if (http->fields[HTTP_FIELD_TRANSFER_ENCODING] && !_cups_strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked"))
{
DEBUG_puts("4httpGetLength2: chunked request!");
remaining = 0;
}
else
{
if (!http->fields[HTTP_FIELD_CONTENT_LENGTH] || !http->fields[HTTP_FIELD_CONTENT_LENGTH][0])
{
if (http->status >= HTTP_STATUS_MULTIPLE_CHOICES ||
http->state == HTTP_STATE_OPTIONS ||
(http->state == HTTP_STATE_GET && http->mode == _HTTP_MODE_SERVER) ||
http->state == HTTP_STATE_HEAD ||
(http->state == HTTP_STATE_PUT && http->mode == _HTTP_MODE_CLIENT) ||
http->state == HTTP_STATE_DELETE ||
http->state == HTTP_STATE_TRACE ||
http->state == HTTP_STATE_CONNECT)
remaining = 0;
else
remaining = 2147483647;
}
else if ((remaining = strtoll(http->fields[HTTP_FIELD_CONTENT_LENGTH],
NULL, 10)) < 0)
remaining = -1;
DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT,
CUPS_LLCAST remaining));
}
return (remaining);
}
size_t
httpGetPending(http_t *http)
{
return (http ? (size_t)http->wused : 0);
}
size_t
httpGetReady(http_t *http)
{
if (!http)
return (0);
else if (http->used > 0)
return ((size_t)http->used);
#ifdef HAVE_SSL
else if (http->tls)
return (_httpTLSPending(http));
#endif
return (0);
}
size_t
httpGetRemaining(http_t *http)
{
return (http ? (size_t)http->data_remaining : 0);
}
char *
httpGets(char *line,
int length,
http_t *http)
{
char *lineptr,
*lineend,
*bufptr,
*bufend;
ssize_t bytes;
int eol;
DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", (void *)line, length, (void *)http));
if (!http || !line || length <= 1)
return (NULL);
http->error = 0;
lineptr = line;
lineend = line + length - 1;
eol = 0;
while (lineptr < lineend)
{
#ifdef _WIN32
WSASetLastError(0);
#else
errno = 0;
#endif
while (http->used == 0)
{
while (!_httpWait(http, http->wait_value, 1))
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
DEBUG_puts("3httpGets: Timed out!");
#ifdef _WIN32
http->error = WSAETIMEDOUT;
#else
http->error = ETIMEDOUT;
#endif
return (NULL);
}
bytes = http_read(http, http->buffer + http->used, (size_t)(HTTP_MAX_BUFFER - http->used));
DEBUG_printf(("4httpGets: read " CUPS_LLFMT " bytes.", CUPS_LLCAST bytes));
if (bytes < 0)
{
#ifdef _WIN32
DEBUG_printf(("3httpGets: recv() error %d!", WSAGetLastError()));
if (WSAGetLastError() == WSAEINTR)
continue;
else if (WSAGetLastError() == WSAEWOULDBLOCK)
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
http->error = WSAGetLastError();
}
else if (WSAGetLastError() != http->error)
{
http->error = WSAGetLastError();
continue;
}
#else
DEBUG_printf(("3httpGets: recv() error %d!", errno));
if (errno == EINTR)
continue;
else if (errno == EWOULDBLOCK || errno == EAGAIN)
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
else if (!http->timeout_cb && errno == EAGAIN)
continue;
http->error = errno;
}
else if (errno != http->error)
{
http->error = errno;
continue;
}
#endif
return (NULL);
}
else if (bytes == 0)
{
http->error = EPIPE;
return (NULL);
}
http->used += (int)bytes;
}
for (bufptr = http->buffer, bufend = http->buffer + http->used;
lineptr < lineend && bufptr < bufend;)
{
if (*bufptr == 0x0a)
{
eol = 1;
bufptr ++;
break;
}
else if (*bufptr == 0x0d)
bufptr ++;
else
*lineptr++ = *bufptr++;
}
http->used -= (int)(bufptr - http->buffer);
if (http->used > 0)
memmove(http->buffer, bufptr, (size_t)http->used);
if (eol)
{
http->activity = time(NULL);
*lineptr = '\0';
DEBUG_printf(("3httpGets: Returning \"%s\"", line));
return (line);
}
}
DEBUG_puts("3httpGets: No new line available!");
return (NULL);
}
http_state_t
httpGetState(http_t *http)
{
return (http ? http->state : HTTP_STATE_ERROR);
}
http_status_t
httpGetStatus(http_t *http)
{
return (http ? http->status : HTTP_STATUS_ERROR);
}
char *
httpGetSubField(http_t *http,
http_field_t field,
const char *name,
char *value)
{
return (httpGetSubField2(http, field, name, value, HTTP_MAX_VALUE));
}
char *
httpGetSubField2(http_t *http,
http_field_t field,
const char *name,
char *value,
int valuelen)
{
const char *fptr;
char temp[HTTP_MAX_VALUE],
*ptr,
*end;
DEBUG_printf(("2httpGetSubField2(http=%p, field=%d, name=\"%s\", value=%p, valuelen=%d)", (void *)http, field, name, (void *)value, valuelen));
if (value)
*value = '\0';
if (!http || !name || !value || valuelen < 2 ||
field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX || !http->fields[field])
return (NULL);
end = value + valuelen - 1;
for (fptr = http->fields[field]; *fptr;)
{
while (_cups_isspace(*fptr))
fptr ++;
if (*fptr == ',')
{
fptr ++;
continue;
}
for (ptr = temp;
*fptr && *fptr != '=' && !_cups_isspace(*fptr) &&
ptr < (temp + sizeof(temp) - 1);
*ptr++ = *fptr++);
*ptr = '\0';
DEBUG_printf(("4httpGetSubField2: name=\"%s\"", temp));
while (_cups_isspace(*fptr))
fptr ++;
if (!*fptr)
break;
if (*fptr != '=')
continue;
fptr ++;
while (_cups_isspace(*fptr))
fptr ++;
if (*fptr == '\"')
{
for (ptr = value, fptr ++;
*fptr && *fptr != '\"' && ptr < end;
*ptr++ = *fptr++);
*ptr = '\0';
while (*fptr && *fptr != '\"')
fptr ++;
if (*fptr)
fptr ++;
}
else
{
for (ptr = value;
*fptr && !_cups_isspace(*fptr) && *fptr != ',' && ptr < end;
*ptr++ = *fptr++);
*ptr = '\0';
while (*fptr && !_cups_isspace(*fptr) && *fptr != ',')
fptr ++;
}
DEBUG_printf(("4httpGetSubField2: value=\"%s\"", value));
if (!strcmp(name, temp))
{
DEBUG_printf(("3httpGetSubField2: Returning \"%s\"", value));
return (value);
}
}
value[0] = '\0';
DEBUG_puts("3httpGetSubField2: Returning NULL");
return (NULL);
}
http_version_t
httpGetVersion(http_t *http)
{
return (http ? http->version : HTTP_VERSION_1_0);
}
int
httpHead(http_t *http,
const char *uri)
{
DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", (void *)http, uri));
return (http_send(http, HTTP_STATE_HEAD, uri));
}
void
httpInitialize(void)
{
static int initialized = 0;
#ifdef _WIN32
WSADATA winsockdata;
#endif
_cupsGlobalLock();
if (initialized)
{
_cupsGlobalUnlock();
return;
}
#ifdef _WIN32
WSAStartup(MAKEWORD(2,2), &winsockdata);
#elif !defined(SO_NOSIGPIPE)
# ifdef HAVE_SIGSET
sigset(SIGPIPE, SIG_IGN);
# elif defined(HAVE_SIGACTION)
struct sigaction action;
memset(&action, 0, sizeof(action));
action.sa_handler = SIG_IGN;
sigaction(SIGPIPE, &action, NULL);
# else
signal(SIGPIPE, SIG_IGN);
# endif
#endif
# ifdef HAVE_SSL
_httpTLSInitialize();
# endif
initialized = 1;
_cupsGlobalUnlock();
}
int
httpIsChunked(http_t *http)
{
return (http ? http->data_encoding == HTTP_ENCODING_CHUNKED : 0);
}
int
httpIsEncrypted(http_t *http)
{
return (http ? http->tls != NULL : 0);
}
int
httpOptions(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_STATE_OPTIONS, uri));
}
ssize_t
httpPeek(http_t *http,
char *buffer,
size_t length)
{
ssize_t bytes;
char len[32];
DEBUG_printf(("httpPeek(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length));
if (http == NULL || buffer == NULL)
return (-1);
http->activity = time(NULL);
http->error = 0;
if (length <= 0)
return (0);
if (http->data_encoding == HTTP_ENCODING_CHUNKED &&
http->data_remaining <= 0)
{
DEBUG_puts("2httpPeek: Getting chunk length...");
if (httpGets(len, sizeof(len), http) == NULL)
{
DEBUG_puts("1httpPeek: Could not get length!");
return (0);
}
if (!len[0])
{
DEBUG_puts("1httpPeek: Blank chunk length, trying again...");
if (!httpGets(len, sizeof(len), http))
{
DEBUG_puts("1httpPeek: Could not get chunk length.");
return (0);
}
}
http->data_remaining = strtoll(len, NULL, 16);
if (http->data_remaining < 0)
{
DEBUG_puts("1httpPeek: Negative chunk length!");
return (0);
}
}
DEBUG_printf(("2httpPeek: data_remaining=" CUPS_LLFMT,
CUPS_LLCAST http->data_remaining));
if (http->data_remaining <= 0 && http->data_encoding != HTTP_ENCODING_FIELDS)
{
#ifdef HAVE_LIBZ
if (http->coding >= _HTTP_CODING_GUNZIP)
http_content_coding_finish(http);
#endif
if (http->data_encoding == HTTP_ENCODING_CHUNKED)
httpGets(len, sizeof(len), http);
if (http->state == HTTP_STATE_POST_RECV)
http->state ++;
else
http->state = HTTP_STATE_STATUS;
DEBUG_printf(("1httpPeek: 0-length chunk, set state to %s.",
httpStateString(http->state)));
http->data_encoding = HTTP_ENCODING_FIELDS;
return (0);
}
else if (length > (size_t)http->data_remaining)
length = (size_t)http->data_remaining;
#ifdef HAVE_LIBZ
if (http->used == 0 &&
(http->coding == _HTTP_CODING_IDENTITY ||
(http->coding >= _HTTP_CODING_GUNZIP && ((z_stream *)http->stream)->avail_in == 0)))
#else
if (http->used == 0)
#endif
{
ssize_t buflen;
if (!http->blocking)
{
while (!httpWait(http, http->wait_value))
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
return (0);
}
}
if ((size_t)http->data_remaining > sizeof(http->buffer))
buflen = sizeof(http->buffer);
else
buflen = (ssize_t)http->data_remaining;
DEBUG_printf(("2httpPeek: Reading %d bytes into buffer.", (int)buflen));
bytes = http_read(http, http->buffer, (size_t)buflen);
DEBUG_printf(("2httpPeek: Read " CUPS_LLFMT " bytes into buffer.",
CUPS_LLCAST bytes));
if (bytes > 0)
{
#ifdef DEBUG
http_debug_hex("httpPeek", http->buffer, (int)bytes);
#endif
http->used = (int)bytes;
}
}
#ifdef HAVE_LIBZ
if (http->coding >= _HTTP_CODING_GUNZIP)
{
# ifdef HAVE_INFLATECOPY
int zerr;
z_stream stream;
if (http->used > 0 && ((z_stream *)http->stream)->avail_in < HTTP_MAX_BUFFER)
{
size_t buflen = HTTP_MAX_BUFFER - ((z_stream *)http->stream)->avail_in;
if (((z_stream *)http->stream)->avail_in > 0 &&
((z_stream *)http->stream)->next_in > http->sbuffer)
memmove(http->sbuffer, ((z_stream *)http->stream)->next_in, ((z_stream *)http->stream)->avail_in);
((z_stream *)http->stream)->next_in = http->sbuffer;
if (buflen > (size_t)http->data_remaining)
buflen = (size_t)http->data_remaining;
if (buflen > (size_t)http->used)
buflen = (size_t)http->used;
DEBUG_printf(("1httpPeek: Copying %d more bytes of data into "
"decompression buffer.", (int)buflen));
memcpy(http->sbuffer + ((z_stream *)http->stream)->avail_in, http->buffer, buflen);
((z_stream *)http->stream)->avail_in += buflen;
http->used -= (int)buflen;
http->data_remaining -= (off_t)buflen;
if (http->used > 0)
memmove(http->buffer, http->buffer + buflen, (size_t)http->used);
}
DEBUG_printf(("2httpPeek: length=%d, avail_in=%d", (int)length,
(int)((z_stream *)http->stream)->avail_in));
if (inflateCopy(&stream, (z_stream *)http->stream) != Z_OK)
{
DEBUG_puts("2httpPeek: Unable to copy decompressor stream.");
http->error = ENOMEM;
return (-1);
}
stream.next_out = (Bytef *)buffer;
stream.avail_out = (uInt)length;
zerr = inflate(&stream, Z_SYNC_FLUSH);
inflateEnd(&stream);
if (zerr < Z_OK)
{
DEBUG_printf(("2httpPeek: zerr=%d", zerr));
#ifdef DEBUG
http_debug_hex("2httpPeek", (char *)http->sbuffer, (int)((z_stream *)http->stream)->avail_in);
#endif
http->error = EIO;
return (-1);
}
bytes = (ssize_t)(length - ((z_stream *)http->stream)->avail_out);
# else
DEBUG_puts("2httpPeek: No inflateCopy on this platform, httpPeek does not "
"work with compressed streams.");
return (-1);
# endif
}
else
#endif
if (http->used > 0)
{
if (length > (size_t)http->used)
length = (size_t)http->used;
bytes = (ssize_t)length;
DEBUG_printf(("2httpPeek: grabbing %d bytes from input buffer...",
(int)bytes));
memcpy(buffer, http->buffer, length);
}
else
bytes = 0;
if (bytes < 0)
{
#ifdef _WIN32
if (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK)
bytes = 0;
else
http->error = WSAGetLastError();
#else
if (errno == EINTR || errno == EAGAIN)
bytes = 0;
else
http->error = errno;
#endif
}
else if (bytes == 0)
{
http->error = EPIPE;
return (0);
}
return (bytes);
}
int
httpPost(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_STATE_POST, uri));
}
int
httpPrintf(http_t *http,
const char *format,
...)
{
ssize_t bytes;
char buf[65536];
va_list ap;
DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", (void *)http, format));
va_start(ap, format);
bytes = vsnprintf(buf, sizeof(buf), format, ap);
va_end(ap);
DEBUG_printf(("3httpPrintf: (" CUPS_LLFMT " bytes) %s", CUPS_LLCAST bytes, buf));
if (bytes > (ssize_t)(sizeof(buf) - 1))
{
http->error = ENOMEM;
return (-1);
}
else if (http->data_encoding == HTTP_ENCODING_FIELDS)
return ((int)httpWrite2(http, buf, (size_t)bytes));
else
{
if (http->wused)
{
DEBUG_puts("4httpPrintf: flushing existing data...");
if (httpFlushWrite(http) < 0)
return (-1);
}
return ((int)http_write(http, buf, (size_t)bytes));
}
}
int
httpPut(http_t *http,
const char *uri)
{
DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", (void *)http, uri));
return (http_send(http, HTTP_STATE_PUT, uri));
}
int
httpRead(http_t *http,
char *buffer,
int length)
{
return ((int)httpRead2(http, buffer, (size_t)length));
}
ssize_t
httpRead2(http_t *http,
char *buffer,
size_t length)
{
ssize_t bytes;
#ifdef HAVE_LIBZ
DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT ") coding=%d data_encoding=%d data_remaining=" CUPS_LLFMT, (void *)http, (void *)buffer, CUPS_LLCAST length, http->coding, http->data_encoding, CUPS_LLCAST http->data_remaining));
#else
DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT ") data_encoding=%d data_remaining=" CUPS_LLFMT, (void *)http, (void *)buffer, CUPS_LLCAST length, http->data_encoding, CUPS_LLCAST http->data_remaining));
#endif
if (http == NULL || buffer == NULL)
return (-1);
http->activity = time(NULL);
http->error = 0;
if (length <= 0)
return (0);
#ifdef HAVE_LIBZ
if (http->coding >= _HTTP_CODING_GUNZIP)
{
do
{
if (((z_stream *)http->stream)->avail_in > 0)
{
int zerr;
DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d",
(int)((z_stream *)http->stream)->avail_in, (int)length));
((z_stream *)http->stream)->next_out = (Bytef *)buffer;
((z_stream *)http->stream)->avail_out = (uInt)length;
if ((zerr = inflate((z_stream *)http->stream, Z_SYNC_FLUSH)) < Z_OK)
{
DEBUG_printf(("2httpRead2: zerr=%d", zerr));
#ifdef DEBUG
http_debug_hex("2httpRead2", (char *)http->sbuffer, (int)((z_stream *)http->stream)->avail_in);
#endif
http->error = EIO;
return (-1);
}
bytes = (ssize_t)(length - ((z_stream *)http->stream)->avail_out);
DEBUG_printf(("2httpRead2: avail_in=%d, avail_out=%d, bytes=%d",
((z_stream *)http->stream)->avail_in, ((z_stream *)http->stream)->avail_out,
(int)bytes));
}
else
bytes = 0;
if (bytes == 0)
{
ssize_t buflen = HTTP_MAX_BUFFER - (ssize_t)((z_stream *)http->stream)->avail_in;
if (buflen > 0)
{
if (((z_stream *)http->stream)->avail_in > 0 &&
((z_stream *)http->stream)->next_in > http->sbuffer)
memmove(http->sbuffer, ((z_stream *)http->stream)->next_in, ((z_stream *)http->stream)->avail_in);
((z_stream *)http->stream)->next_in = http->sbuffer;
DEBUG_printf(("1httpRead2: Reading up to %d more bytes of data into "
"decompression buffer.", (int)buflen));
if (http->data_remaining > 0)
{
if (buflen > http->data_remaining)
buflen = (ssize_t)http->data_remaining;
bytes = http_read_buffered(http, (char *)http->sbuffer + ((z_stream *)http->stream)->avail_in, (size_t)buflen);
}
else if (http->data_encoding == HTTP_ENCODING_CHUNKED)
bytes = http_read_chunk(http, (char *)http->sbuffer + ((z_stream *)http->stream)->avail_in, (size_t)buflen);
else
bytes = 0;
if (bytes < 0)
return (bytes);
else if (bytes == 0)
break;
DEBUG_printf(("1httpRead2: Adding " CUPS_LLFMT " bytes to "
"decompression buffer.", CUPS_LLCAST bytes));
http->data_remaining -= bytes;
((z_stream *)http->stream)->avail_in += (uInt)bytes;
if (http->data_remaining <= 0 &&
http->data_encoding == HTTP_ENCODING_CHUNKED)
{
char len[32];
httpGets(len, sizeof(len), http);
}
bytes = 0;
}
else
return (0);
}
}
while (bytes == 0);
}
else
#endif
if (http->data_remaining == 0 && http->data_encoding == HTTP_ENCODING_CHUNKED)
{
if ((bytes = http_read_chunk(http, buffer, length)) > 0)
{
http->data_remaining -= bytes;
if (http->data_remaining <= 0)
{
char len[32];
httpGets(len, sizeof(len), http);
}
}
}
else if (http->data_remaining <= 0)
{
return (0);
}
else
{
DEBUG_printf(("1httpRead2: Reading up to %d bytes into buffer.",
(int)length));
if (length > (size_t)http->data_remaining)
length = (size_t)http->data_remaining;
if ((bytes = http_read_buffered(http, buffer, length)) > 0)
{
http->data_remaining -= bytes;
if (http->data_remaining <= 0 &&
http->data_encoding == HTTP_ENCODING_CHUNKED)
{
char len[32];
httpGets(len, sizeof(len), http);
}
}
}
if (
#ifdef HAVE_LIBZ
(http->coding == _HTTP_CODING_IDENTITY ||
(http->coding >= _HTTP_CODING_GUNZIP && ((z_stream *)http->stream)->avail_in == 0)) &&
#endif
((http->data_remaining <= 0 &&
http->data_encoding == HTTP_ENCODING_LENGTH) ||
(http->data_encoding == HTTP_ENCODING_CHUNKED && bytes == 0)))
{
#ifdef HAVE_LIBZ
if (http->coding >= _HTTP_CODING_GUNZIP)
http_content_coding_finish(http);
#endif
if (http->state == HTTP_STATE_POST_RECV)
http->state ++;
else if (http->state == HTTP_STATE_GET_SEND ||
http->state == HTTP_STATE_POST_SEND)
http->state = HTTP_STATE_WAITING;
else
http->state = HTTP_STATE_STATUS;
DEBUG_printf(("1httpRead2: End of content, set state to %s.",
httpStateString(http->state)));
}
return (bytes);
}
http_state_t
httpReadRequest(http_t *http,
char *uri,
size_t urilen)
{
char line[4096],
*req_method,
*req_uri,
*req_version;
DEBUG_printf(("httpReadRequest(http=%p, uri=%p, urilen=" CUPS_LLFMT ")", (void *)http, (void *)uri, CUPS_LLCAST urilen));
if (uri)
*uri = '\0';
if (!http || !uri || urilen < 1)
{
DEBUG_puts("1httpReadRequest: Bad arguments, returning HTTP_STATE_ERROR.");
return (HTTP_STATE_ERROR);
}
else if (http->state != HTTP_STATE_WAITING)
{
DEBUG_printf(("1httpReadRequest: Bad state %s, returning HTTP_STATE_ERROR.",
httpStateString(http->state)));
return (HTTP_STATE_ERROR);
}
httpClearFields(http);
http->activity = time(NULL);
http->data_encoding = HTTP_ENCODING_FIELDS;
http->data_remaining = 0;
http->keep_alive = HTTP_KEEPALIVE_OFF;
http->status = HTTP_STATUS_OK;
http->version = HTTP_VERSION_1_1;
if (!httpGets(line, sizeof(line), http))
{
DEBUG_puts("1httpReadRequest: Unable to read, returning HTTP_STATE_ERROR");
return (HTTP_STATE_ERROR);
}
if (!line[0])
{
DEBUG_puts("1httpReadRequest: Blank line, returning HTTP_STATE_WAITING");
return (HTTP_STATE_WAITING);
}
DEBUG_printf(("1httpReadRequest: %s", line));
req_method = line;
req_uri = line;
while (*req_uri && !isspace(*req_uri & 255))
req_uri ++;
if (!*req_uri)
{
DEBUG_puts("1httpReadRequest: No request URI.");
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No request URI."), 1);
return (HTTP_STATE_ERROR);
}
*req_uri++ = '\0';
while (*req_uri && isspace(*req_uri & 255))
req_uri ++;
req_version = req_uri;
while (*req_version && !isspace(*req_version & 255))
req_version ++;
if (!*req_version)
{
DEBUG_puts("1httpReadRequest: No request protocol version.");
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("No request protocol version."), 1);
return (HTTP_STATE_ERROR);
}
*req_version++ = '\0';
while (*req_version && isspace(*req_version & 255))
req_version ++;
if (!strcmp(req_method, "OPTIONS"))
http->state = HTTP_STATE_OPTIONS;
else if (!strcmp(req_method, "GET"))
http->state = HTTP_STATE_GET;
else if (!strcmp(req_method, "HEAD"))
http->state = HTTP_STATE_HEAD;
else if (!strcmp(req_method, "POST"))
http->state = HTTP_STATE_POST;
else if (!strcmp(req_method, "PUT"))
http->state = HTTP_STATE_PUT;
else if (!strcmp(req_method, "DELETE"))
http->state = HTTP_STATE_DELETE;
else if (!strcmp(req_method, "TRACE"))
http->state = HTTP_STATE_TRACE;
else if (!strcmp(req_method, "CONNECT"))
http->state = HTTP_STATE_CONNECT;
else
{
DEBUG_printf(("1httpReadRequest: Unknown method \"%s\".", req_method));
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unknown request method."), 1);
return (HTTP_STATE_UNKNOWN_METHOD);
}
DEBUG_printf(("1httpReadRequest: Set state to %s.",
httpStateString(http->state)));
if (!strcmp(req_version, "HTTP/1.0"))
{
http->version = HTTP_VERSION_1_0;
http->keep_alive = HTTP_KEEPALIVE_OFF;
}
else if (!strcmp(req_version, "HTTP/1.1"))
{
http->version = HTTP_VERSION_1_1;
http->keep_alive = HTTP_KEEPALIVE_ON;
}
else
{
DEBUG_printf(("1httpReadRequest: Unknown version \"%s\".", req_version));
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, _("Unknown request version."), 1);
return (HTTP_STATE_UNKNOWN_VERSION);
}
DEBUG_printf(("1httpReadRequest: URI is \"%s\".", req_uri));
strlcpy(uri, req_uri, urilen);
return (http->state);
}
int
httpReconnect(http_t *http)
{
DEBUG_printf(("httpReconnect(http=%p)", (void *)http));
return (httpReconnect2(http, 30000, NULL));
}
int
httpReconnect2(http_t *http,
int msec,
int *cancel)
{
http_addrlist_t *addr;
#ifdef DEBUG
http_addrlist_t *current;
char temp[256];
#endif
DEBUG_printf(("httpReconnect2(http=%p, msec=%d, cancel=%p)", (void *)http, msec, (void *)cancel));
if (!http)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(EINVAL), 0);
return (-1);
}
#ifdef HAVE_SSL
if (http->tls)
{
DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
_httpTLSStop(http);
}
#endif
if (http->fd >= 0)
{
DEBUG_printf(("2httpReconnect2: Closing socket %d...", http->fd));
httpAddrClose(NULL, http->fd);
http->fd = -1;
}
http->state = HTTP_STATE_WAITING;
http->version = HTTP_VERSION_1_1;
http->keep_alive = HTTP_KEEPALIVE_OFF;
memset(&http->_hostaddr, 0, sizeof(http->_hostaddr));
http->data_encoding = HTTP_ENCODING_FIELDS;
http->_data_remaining = 0;
http->used = 0;
http->data_remaining = 0;
http->hostaddr = NULL;
http->wused = 0;
#ifdef DEBUG
for (current = http->addrlist; current; current = current->next)
DEBUG_printf(("2httpReconnect2: Address %s:%d",
httpAddrString(&(current->addr), temp, sizeof(temp)),
httpAddrPort(&(current->addr))));
#endif
if ((addr = httpAddrConnect2(http->addrlist, &(http->fd), msec, cancel)) == NULL)
{
#ifdef _WIN32
http->error = WSAGetLastError();
#else
http->error = errno;
#endif
http->status = HTTP_STATUS_ERROR;
DEBUG_printf(("1httpReconnect2: httpAddrConnect failed: %s",
strerror(http->error)));
return (-1);
}
DEBUG_printf(("2httpReconnect2: New socket=%d", http->fd));
if (http->timeout_value > 0)
http_set_timeout(http->fd, http->timeout_value);
http->hostaddr = &(addr->addr);
http->error = 0;
#ifdef HAVE_SSL
if (http->encryption == HTTP_ENCRYPTION_ALWAYS)
{
if (_httpTLSStart(http) != 0)
{
httpAddrClose(NULL, http->fd);
return (-1);
}
}
else if (http->encryption == HTTP_ENCRYPTION_REQUIRED && !http->tls_upgrade)
return (http_tls_upgrade(http));
#endif
DEBUG_printf(("1httpReconnect2: Connected to %s:%d...",
httpAddrString(http->hostaddr, temp, sizeof(temp)),
httpAddrPort(http->hostaddr)));
return (0);
}
void
httpSetAuthString(http_t *http,
const char *scheme,
const char *data)
{
if (!http)
return;
if (http->authstring && http->authstring != http->_authstring)
free(http->authstring);
http->authstring = http->_authstring;
if (scheme)
{
size_t len = strlen(scheme) + (data ? strlen(data) + 1 : 0) + 1;
char *temp;
if (len > sizeof(http->_authstring))
{
if ((temp = malloc(len)) == NULL)
len = sizeof(http->_authstring);
else
http->authstring = temp;
}
if (data)
snprintf(http->authstring, len, "%s %s", scheme, data);
else
strlcpy(http->authstring, scheme, len);
}
else
{
http->_authstring[0] = '\0';
}
}
int
httpSetCredentials(http_t *http,
cups_array_t *credentials)
{
if (!http || cupsArrayCount(credentials) < 1)
return (-1);
#ifdef HAVE_SSL
_httpFreeCredentials(http->tls_credentials);
http->tls_credentials = _httpCreateCredentials(credentials);
#endif
return (http->tls_credentials ? 0 : -1);
}
void
httpSetCookie(http_t *http,
const char *cookie)
{
if (!http)
return;
if (http->cookie)
free(http->cookie);
if (cookie)
http->cookie = strdup(cookie);
else
http->cookie = NULL;
}
void
httpSetDefaultField(http_t *http,
http_field_t field,
const char *value)
{
DEBUG_printf(("httpSetDefaultField(http=%p, field=%d(%s), value=\"%s\")", (void *)http, field, http_fields[field], value));
if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
return;
if (http->default_fields[field])
free(http->default_fields[field]);
http->default_fields[field] = value ? strdup(value) : NULL;
}
void
httpSetExpect(http_t *http,
http_status_t expect)
{
DEBUG_printf(("httpSetExpect(http=%p, expect=%d)", (void *)http, expect));
if (http)
http->expect = expect;
}
void
httpSetField(http_t *http,
http_field_t field,
const char *value)
{
DEBUG_printf(("httpSetField(http=%p, field=%d(%s), value=\"%s\")", (void *)http, field, http_fields[field], value));
if (!http || field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX || !value)
return;
http_add_field(http, field, value, 0);
}
void
httpSetKeepAlive(
http_t *http,
http_keepalive_t keep_alive)
{
if (http)
http->keep_alive = keep_alive;
}
void
httpSetLength(http_t *http,
size_t length)
{
DEBUG_printf(("httpSetLength(http=%p, length=" CUPS_LLFMT ")", (void *)http, CUPS_LLCAST length));
if (!http)
return;
if (!length)
{
httpSetField(http, HTTP_FIELD_TRANSFER_ENCODING, "chunked");
httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, "");
}
else
{
char len[32];
snprintf(len, sizeof(len), CUPS_LLFMT, CUPS_LLCAST length);
httpSetField(http, HTTP_FIELD_TRANSFER_ENCODING, "");
httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, len);
}
}
void
httpSetTimeout(
http_t *http,
double timeout,
http_timeout_cb_t cb,
void *user_data)
{
if (!http || timeout <= 0.0)
return;
http->timeout_cb = cb;
http->timeout_data = user_data;
http->timeout_value = timeout;
if (http->fd >= 0)
http_set_timeout(http->fd, timeout);
http_set_wait(http);
}
void
httpShutdown(http_t *http)
{
if (!http || http->fd < 0)
return;
#ifdef HAVE_SSL
if (http->tls)
_httpTLSStop(http);
#endif
#ifdef _WIN32
shutdown(http->fd, SD_RECEIVE);
#else
shutdown(http->fd, SHUT_RD);
#endif
}
int
httpTrace(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_STATE_TRACE, uri));
}
int
_httpUpdate(http_t *http,
http_status_t *status)
{
char line[32768],
*value;
http_field_t field;
int major, minor;
DEBUG_printf(("_httpUpdate(http=%p, status=%p), state=%s", (void *)http, (void *)status, httpStateString(http->state)));
if (!httpGets(line, sizeof(line), http))
{
*status = HTTP_STATUS_ERROR;
return (0);
}
DEBUG_printf(("2_httpUpdate: Got \"%s\"", line));
if (line[0] == '\0')
{
if (http->status == HTTP_STATUS_CONTINUE)
{
*status = http->status;
return (0);
}
if (http->status < HTTP_STATUS_BAD_REQUEST)
http->digest_tries = 0;
#ifdef HAVE_SSL
if (http->status == HTTP_STATUS_SWITCHING_PROTOCOLS && !http->tls)
{
if (_httpTLSStart(http) != 0)
{
httpAddrClose(NULL, http->fd);
*status = http->status = HTTP_STATUS_ERROR;
return (0);
}
*status = HTTP_STATUS_CONTINUE;
return (0);
}
#endif
if (http_set_length(http) < 0)
{
DEBUG_puts("1_httpUpdate: Bad Content-Length.");
http->error = EINVAL;
http->status = *status = HTTP_STATUS_ERROR;
return (0);
}
switch (http->state)
{
case HTTP_STATE_GET :
case HTTP_STATE_POST :
case HTTP_STATE_POST_RECV :
case HTTP_STATE_PUT :
http->state ++;
DEBUG_printf(("1_httpUpdate: Set state to %s.",
httpStateString(http->state)));
case HTTP_STATE_POST_SEND :
case HTTP_STATE_HEAD :
break;
default :
http->state = HTTP_STATE_WAITING;
DEBUG_puts("1_httpUpdate: Reset state to HTTP_STATE_WAITING.");
break;
}
#ifdef HAVE_LIBZ
DEBUG_puts("1_httpUpdate: Calling http_content_coding_start.");
http_content_coding_start(http,
httpGetField(http, HTTP_FIELD_CONTENT_ENCODING));
#endif
*status = http->status;
return (0);
}
else if (!strncmp(line, "HTTP/", 5) && http->mode == _HTTP_MODE_CLIENT)
{
int intstatus;
if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, &intstatus) != 3)
{
*status = http->status = HTTP_STATUS_ERROR;
return (0);
}
httpClearFields(http);
http->version = (http_version_t)(major * 100 + minor);
*status = http->status = (http_status_t)intstatus;
}
else if ((value = strchr(line, ':')) != NULL)
{
*value++ = '\0';
while (_cups_isspace(*value))
value ++;
DEBUG_printf(("1_httpUpdate: Header %s: %s", line, value));
if (!_cups_strcasecmp(line, "expect"))
{
http->expect = (http_status_t)atoi(value);
}
else if (!_cups_strcasecmp(line, "cookie"))
{
httpSetCookie(http, value);
}
else if ((field = httpFieldValue(line)) != HTTP_FIELD_UNKNOWN)
{
http_add_field(http, field, value, 1);
if (field == HTTP_FIELD_AUTHENTICATION_INFO)
httpGetSubField2(http, HTTP_FIELD_AUTHENTICATION_INFO, "nextnonce", http->nextnonce, (int)sizeof(http->nextnonce));
}
#ifdef DEBUG
else
DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line));
#endif
}
else
{
DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line));
http->error = EINVAL;
http->status = *status = HTTP_STATUS_ERROR;
return (0);
}
return (1);
}
http_status_t
httpUpdate(http_t *http)
{
http_status_t status;
DEBUG_printf(("httpUpdate(http=%p), state=%s", (void *)http, httpStateString(http->state)));
if (http->wused)
{
DEBUG_puts("2httpUpdate: flushing buffer...");
if (httpFlushWrite(http) < 0)
return (HTTP_STATUS_ERROR);
}
if (http->state == HTTP_STATE_WAITING)
return (HTTP_STATUS_CONTINUE);
while (_httpUpdate(http, &status));
if (http->error == EPIPE && http->status > HTTP_STATUS_CONTINUE)
{
DEBUG_printf(("1httpUpdate: Returning status %d...", http->status));
return (http->status);
}
if (http->error)
{
DEBUG_printf(("1httpUpdate: socket error %d - %s", http->error,
strerror(http->error)));
http->status = HTTP_STATUS_ERROR;
return (HTTP_STATUS_ERROR);
}
return (status);
}
int
_httpWait(http_t *http,
int msec,
int usessl)
{
#ifdef HAVE_POLL
struct pollfd pfd;
#else
fd_set input_set;
struct timeval timeout;
#endif
int nfds;
DEBUG_printf(("4_httpWait(http=%p, msec=%d, usessl=%d)", (void *)http, msec, usessl));
if (http->fd < 0)
{
DEBUG_printf(("5_httpWait: Returning 0 since fd=%d", http->fd));
return (0);
}
#ifdef HAVE_SSL
if (http->tls && _httpTLSPending(http))
{
DEBUG_puts("5_httpWait: Return 1 since there is pending TLS data.");
return (1);
}
#endif
#ifdef HAVE_POLL
pfd.fd = http->fd;
pfd.events = POLLIN;
do
{
nfds = poll(&pfd, 1, msec);
}
while (nfds < 0 && (errno == EINTR || errno == EAGAIN));
#else
do
{
FD_ZERO(&input_set);
FD_SET(http->fd, &input_set);
DEBUG_printf(("6_httpWait: msec=%d, http->fd=%d", msec, http->fd));
if (msec >= 0)
{
timeout.tv_sec = msec / 1000;
timeout.tv_usec = (msec % 1000) * 1000;
nfds = select(http->fd + 1, &input_set, NULL, NULL, &timeout);
}
else
nfds = select(http->fd + 1, &input_set, NULL, NULL, NULL);
DEBUG_printf(("6_httpWait: select() returned %d...", nfds));
}
# ifdef _WIN32
while (nfds < 0 && (WSAGetLastError() == WSAEINTR ||
WSAGetLastError() == WSAEWOULDBLOCK));
# else
while (nfds < 0 && (errno == EINTR || errno == EAGAIN));
# endif
#endif
DEBUG_printf(("5_httpWait: returning with nfds=%d, errno=%d...", nfds,
errno));
return (nfds > 0);
}
int
httpWait(http_t *http,
int msec)
{
DEBUG_printf(("2httpWait(http=%p, msec=%d)", (void *)http, msec));
if (http == NULL)
return (0);
if (http->used)
{
DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
return (1);
}
#ifdef HAVE_LIBZ
if (http->coding >= _HTTP_CODING_GUNZIP && ((z_stream *)http->stream)->avail_in > 0)
{
DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
return (1);
}
#endif
if (http->wused)
{
DEBUG_puts("3httpWait: Flushing write buffer.");
if (httpFlushWrite(http) < 0)
return (0);
}
return (_httpWait(http, msec, 1));
}
int
httpWrite(http_t *http,
const char *buffer,
int length)
{
return ((int)httpWrite2(http, buffer, (size_t)length));
}
ssize_t
httpWrite2(http_t *http,
const char *buffer,
size_t length)
{
ssize_t bytes;
DEBUG_printf(("httpWrite2(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length));
if (!http || !buffer)
{
DEBUG_puts("1httpWrite2: Returning -1 due to bad input.");
return (-1);
}
http->activity = time(NULL);
#ifdef HAVE_LIBZ
if (http->coding == _HTTP_CODING_GZIP || http->coding == _HTTP_CODING_DEFLATE)
{
DEBUG_printf(("1httpWrite2: http->coding=%d", http->coding));
if (length == 0)
{
http_content_coding_finish(http);
bytes = 0;
}
else
{
size_t slen;
ssize_t sret;
((z_stream *)http->stream)->next_in = (Bytef *)buffer;
((z_stream *)http->stream)->avail_in = (uInt)length;
while (deflate((z_stream *)http->stream, Z_NO_FLUSH) == Z_OK)
{
DEBUG_printf(("1httpWrite2: avail_out=%d", ((z_stream *)http->stream)->avail_out));
if (((z_stream *)http->stream)->avail_out > 0)
continue;
slen = _HTTP_MAX_SBUFFER - ((z_stream *)http->stream)->avail_out;
DEBUG_printf(("1httpWrite2: Writing intermediate chunk, len=%d", (int)slen));
if (slen > 0 && http->data_encoding == HTTP_ENCODING_CHUNKED)
sret = http_write_chunk(http, (char *)http->sbuffer, slen);
else if (slen > 0)
sret = http_write(http, (char *)http->sbuffer, slen);
else
sret = 0;
if (sret < 0)
{
DEBUG_puts("1httpWrite2: Unable to write, returning -1.");
return (-1);
}
((z_stream *)http->stream)->next_out = (Bytef *)http->sbuffer;
((z_stream *)http->stream)->avail_out = (uInt)_HTTP_MAX_SBUFFER;
}
bytes = (ssize_t)length;
}
}
else
#endif
if (length > 0)
{
if (http->wused && (length + (size_t)http->wused) > sizeof(http->wbuffer))
{
DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
CUPS_LLFMT ")", http->wused, CUPS_LLCAST length));
httpFlushWrite(http);
}
if ((length + (size_t)http->wused) <= sizeof(http->wbuffer) && length < sizeof(http->wbuffer))
{
DEBUG_printf(("2httpWrite2: Copying " CUPS_LLFMT " bytes to wbuffer...",
CUPS_LLCAST length));
memcpy(http->wbuffer + http->wused, buffer, length);
http->wused += (int)length;
bytes = (ssize_t)length;
}
else
{
DEBUG_printf(("2httpWrite2: Writing " CUPS_LLFMT " bytes to socket...",
CUPS_LLCAST length));
if (http->data_encoding == HTTP_ENCODING_CHUNKED)
bytes = (ssize_t)http_write_chunk(http, buffer, length);
else
bytes = (ssize_t)http_write(http, buffer, length);
DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT " bytes...",
CUPS_LLCAST bytes));
}
if (http->data_encoding == HTTP_ENCODING_LENGTH)
http->data_remaining -= bytes;
}
else
bytes = 0;
if ((http->data_encoding == HTTP_ENCODING_CHUNKED && length == 0) ||
(http->data_encoding == HTTP_ENCODING_LENGTH && http->data_remaining == 0))
{
#ifdef HAVE_LIBZ
if (http->coding == _HTTP_CODING_GZIP || http->coding == _HTTP_CODING_DEFLATE)
http_content_coding_finish(http);
#endif
if (http->wused)
{
if (httpFlushWrite(http) < 0)
return (-1);
}
if (http->data_encoding == HTTP_ENCODING_CHUNKED)
{
http_write(http, "0\r\n\r\n", 5);
http->data_encoding = HTTP_ENCODING_FIELDS;
http->data_remaining = 0;
}
if (http->state == HTTP_STATE_POST_RECV)
http->state ++;
else if (http->state == HTTP_STATE_POST_SEND ||
http->state == HTTP_STATE_GET_SEND)
http->state = HTTP_STATE_WAITING;
else
http->state = HTTP_STATE_STATUS;
DEBUG_printf(("2httpWrite2: Changed state to %s.",
httpStateString(http->state)));
}
DEBUG_printf(("1httpWrite2: Returning " CUPS_LLFMT ".", CUPS_LLCAST bytes));
return (bytes);
}
int
httpWriteResponse(http_t *http,
http_status_t status)
{
http_encoding_t old_encoding;
off_t old_remaining;
DEBUG_printf(("httpWriteResponse(http=%p, status=%d)", (void *)http, status));
if (!http || status < HTTP_STATUS_CONTINUE)
{
DEBUG_puts("1httpWriteResponse: Bad input.");
return (-1);
}
if (!http->fields[HTTP_FIELD_DATE])
httpSetField(http, HTTP_FIELD_DATE, httpGetDateString(time(NULL)));
if (status >= HTTP_STATUS_BAD_REQUEST && http->keep_alive)
{
http->keep_alive = HTTP_KEEPALIVE_OFF;
httpSetField(http, HTTP_FIELD_KEEP_ALIVE, "");
}
if (http->version == HTTP_VERSION_1_1)
{
if (!http->fields[HTTP_FIELD_CONNECTION])
{
if (http->keep_alive)
httpSetField(http, HTTP_FIELD_CONNECTION, "Keep-Alive");
else
httpSetField(http, HTTP_FIELD_CONNECTION, "close");
}
if (http->keep_alive && !http->fields[HTTP_FIELD_KEEP_ALIVE])
httpSetField(http, HTTP_FIELD_KEEP_ALIVE, "timeout=10");
}
#ifdef HAVE_SSL
if (status == HTTP_STATUS_UPGRADE_REQUIRED ||
status == HTTP_STATUS_SWITCHING_PROTOCOLS)
{
if (!http->fields[HTTP_FIELD_CONNECTION])
httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
if (!http->fields[HTTP_FIELD_UPGRADE])
httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.2,TLS/1.1,TLS/1.0");
if (!http->fields[HTTP_FIELD_CONTENT_LENGTH])
httpSetField(http, HTTP_FIELD_CONTENT_LENGTH, "0");
}
#endif
if (!http->fields[HTTP_FIELD_SERVER])
httpSetField(http, HTTP_FIELD_SERVER, http->default_fields[HTTP_FIELD_SERVER] ? http->default_fields[HTTP_FIELD_SERVER] : CUPS_MINIMAL);
if (!http->fields[HTTP_FIELD_ACCEPT_ENCODING])
httpSetField(http, HTTP_FIELD_ACCEPT_ENCODING, http->default_fields[HTTP_FIELD_ACCEPT_ENCODING] ? http->default_fields[HTTP_FIELD_ACCEPT_ENCODING] :
#ifdef HAVE_LIBZ
"gzip, deflate, identity");
#else
"identity");
#endif
old_encoding = http->data_encoding;
old_remaining = http->data_remaining;
http->data_encoding = HTTP_ENCODING_FIELDS;
if (httpPrintf(http, "HTTP/%d.%d %d %s\r\n", http->version / 100, http->version % 100, (int)status, httpStatus(status)) < 0)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
if (status != HTTP_STATUS_CONTINUE)
{
int i;
const char *value;
for (i = 0; i < HTTP_FIELD_MAX; i ++)
{
if ((value = httpGetField(http, i)) != NULL && *value)
{
if (httpPrintf(http, "%s: %s\r\n", http_fields[i], value) < 1)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
}
}
if (http->cookie)
{
if (strchr(http->cookie, ';'))
{
if (httpPrintf(http, "Set-Cookie: %s\r\n", http->cookie) < 1)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
}
else if (httpPrintf(http, "Set-Cookie: %s; path=/; httponly;%s\r\n", http->cookie, http->tls ? " secure;" : "") < 1)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
}
if (httpPrintf(http, "X-Frame-Options: DENY\r\n"
"Content-Security-Policy: frame-ancestors 'none'\r\n") < 1)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
}
if (httpWrite2(http, "\r\n", 2) < 2)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
if (httpFlushWrite(http) < 0)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
if (status == HTTP_STATUS_CONTINUE ||
status == HTTP_STATUS_SWITCHING_PROTOCOLS)
{
http->data_encoding = old_encoding;
http->data_remaining = old_remaining;
if (old_remaining <= INT_MAX)
http->_data_remaining = (int)old_remaining;
else
http->_data_remaining = INT_MAX;
}
else if (http->state == HTTP_STATE_OPTIONS ||
http->state == HTTP_STATE_HEAD ||
http->state == HTTP_STATE_PUT ||
http->state == HTTP_STATE_TRACE ||
http->state == HTTP_STATE_CONNECT ||
http->state == HTTP_STATE_STATUS)
{
DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
"was %s.", httpStateString(http->state)));
http->state = HTTP_STATE_WAITING;
}
else
{
http_set_length(http);
if (http->data_encoding == HTTP_ENCODING_LENGTH && http->data_remaining == 0)
{
DEBUG_printf(("1httpWriteResponse: Resetting state to HTTP_STATE_WAITING, "
"was %s.", httpStateString(http->state)));
http->state = HTTP_STATE_WAITING;
return (0);
}
if (http->state == HTTP_STATE_POST_RECV || http->state == HTTP_STATE_GET)
http->state ++;
#ifdef HAVE_LIBZ
DEBUG_puts("1httpWriteResponse: Calling http_content_coding_start.");
http_content_coding_start(http,
httpGetField(http, HTTP_FIELD_CONTENT_ENCODING));
#endif
}
return (0);
}
static void
http_add_field(http_t *http,
http_field_t field,
const char *value,
int append)
{
char temp[1024];
size_t fieldlen,
valuelen,
total;
if (field == HTTP_FIELD_HOST)
{
char *ptr = strchr(value, ':');
if (value[0] != '[' && ptr && strchr(ptr + 1, ':'))
{
snprintf(temp, sizeof(temp), "[%s]", value);
value = temp;
}
else if (*value)
{
strlcpy(temp, value, sizeof(temp));
value = temp;
ptr = temp + strlen(temp) - 1;
if (*ptr == '.')
*ptr = '\0';
}
}
if (append && field != HTTP_FIELD_ACCEPT_ENCODING && field != HTTP_FIELD_ACCEPT_LANGUAGE && field != HTTP_FIELD_ACCEPT_RANGES && field != HTTP_FIELD_ALLOW && field != HTTP_FIELD_LINK && field != HTTP_FIELD_TRANSFER_ENCODING && field != HTTP_FIELD_UPGRADE && field != HTTP_FIELD_WWW_AUTHENTICATE)
append = 0;
if (!append && http->fields[field])
{
if (http->fields[field] != http->_fields[field])
free(http->fields[field]);
http->fields[field] = NULL;
}
valuelen = strlen(value);
if (!valuelen)
{
http->_fields[field][0] = '\0';
return;
}
if (http->fields[field])
{
fieldlen = strlen(http->fields[field]);
total = fieldlen + 2 + valuelen;
}
else
{
fieldlen = 0;
total = valuelen;
}
if (total < HTTP_MAX_VALUE && field < HTTP_FIELD_ACCEPT_ENCODING)
{
if (fieldlen)
{
char combined[HTTP_MAX_VALUE];
snprintf(combined, sizeof(combined), "%s, %s", http->_fields[field], value);
value = combined;
}
strlcpy(http->_fields[field], value, sizeof(http->_fields[field]));
http->fields[field] = http->_fields[field];
}
else if (fieldlen)
{
char *combined;
if (http->fields[field] == http->_fields[field])
{
if ((combined = malloc(total + 1)) != NULL)
{
http->fields[field] = combined;
snprintf(combined, total + 1, "%s, %s", http->_fields[field], value);
}
}
else if ((combined = realloc(http->fields[field], total + 1)) != NULL)
{
http->fields[field] = combined;
strlcat(combined, ", ", total + 1);
strlcat(combined, value, total + 1);
}
}
else
{
http->fields[field] = strdup(value);
}
#ifdef HAVE_LIBZ
if (field == HTTP_FIELD_CONTENT_ENCODING && http->data_encoding != HTTP_ENCODING_FIELDS)
{
DEBUG_puts("1httpSetField: Calling http_content_coding_start.");
http_content_coding_start(http, value);
}
#endif
}
#ifdef HAVE_LIBZ
static void
http_content_coding_finish(
http_t *http)
{
int zerr;
Byte dummy[1];
size_t bytes;
DEBUG_printf(("http_content_coding_finish(http=%p)", (void *)http));
DEBUG_printf(("1http_content_coding_finishing: http->coding=%d", http->coding));
switch (http->coding)
{
case _HTTP_CODING_DEFLATE :
case _HTTP_CODING_GZIP :
((z_stream *)http->stream)->next_in = dummy;
((z_stream *)http->stream)->avail_in = 0;
do
{
zerr = deflate((z_stream *)http->stream, Z_FINISH);
bytes = _HTTP_MAX_SBUFFER - ((z_stream *)http->stream)->avail_out;
if (bytes > 0)
{
DEBUG_printf(("1http_content_coding_finish: Writing trailing chunk, len=%d", (int)bytes));
if (http->data_encoding == HTTP_ENCODING_CHUNKED)
http_write_chunk(http, (char *)http->sbuffer, bytes);
else
http_write(http, (char *)http->sbuffer, bytes);
}
((z_stream *)http->stream)->next_out = (Bytef *)http->sbuffer;
((z_stream *)http->stream)->avail_out = (uInt)_HTTP_MAX_SBUFFER;
}
while (zerr == Z_OK);
deflateEnd((z_stream *)http->stream);
free(http->sbuffer);
free(http->stream);
http->sbuffer = NULL;
http->stream = NULL;
if (http->wused)
httpFlushWrite(http);
break;
case _HTTP_CODING_INFLATE :
case _HTTP_CODING_GUNZIP :
inflateEnd((z_stream *)http->stream);
free(http->sbuffer);
free(http->stream);
http->sbuffer = NULL;
http->stream = NULL;
break;
default :
break;
}
http->coding = _HTTP_CODING_IDENTITY;
}
static void
http_content_coding_start(
http_t *http,
const char *value)
{
int zerr;
_http_coding_t coding;
DEBUG_printf(("http_content_coding_start(http=%p, value=\"%s\")", (void *)http, value));
if (http->coding != _HTTP_CODING_IDENTITY)
{
DEBUG_printf(("1http_content_coding_start: http->coding already %d.",
http->coding));
return;
}
else if (!strcmp(value, "x-gzip") || !strcmp(value, "gzip"))
{
if (http->state == HTTP_STATE_GET_SEND ||
http->state == HTTP_STATE_POST_SEND)
coding = http->mode == _HTTP_MODE_SERVER ? _HTTP_CODING_GZIP :
_HTTP_CODING_GUNZIP;
else if (http->state == HTTP_STATE_POST_RECV ||
http->state == HTTP_STATE_PUT_RECV)
coding = http->mode == _HTTP_MODE_CLIENT ? _HTTP_CODING_GZIP :
_HTTP_CODING_GUNZIP;
else
{
DEBUG_puts("1http_content_coding_start: Not doing content coding.");
return;
}
}
else if (!strcmp(value, "x-deflate") || !strcmp(value, "deflate"))
{
if (http->state == HTTP_STATE_GET_SEND ||
http->state == HTTP_STATE_POST_SEND)
coding = http->mode == _HTTP_MODE_SERVER ? _HTTP_CODING_DEFLATE :
_HTTP_CODING_INFLATE;
else if (http->state == HTTP_STATE_POST_RECV ||
http->state == HTTP_STATE_PUT_RECV)
coding = http->mode == _HTTP_MODE_CLIENT ? _HTTP_CODING_DEFLATE :
_HTTP_CODING_INFLATE;
else
{
DEBUG_puts("1http_content_coding_start: Not doing content coding.");
return;
}
}
else
{
DEBUG_puts("1http_content_coding_start: Not doing content coding.");
return;
}
switch (coding)
{
case _HTTP_CODING_DEFLATE :
case _HTTP_CODING_GZIP :
if (http->wused)
httpFlushWrite(http);
if ((http->sbuffer = malloc(_HTTP_MAX_SBUFFER)) == NULL)
{
http->status = HTTP_STATUS_ERROR;
http->error = errno;
return;
}
if ((http->stream = calloc(1, sizeof(z_stream))) == NULL)
{
free(http->sbuffer);
http->sbuffer = NULL;
http->status = HTTP_STATUS_ERROR;
http->error = errno;
return;
}
if ((zerr = deflateInit2((z_stream *)http->stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, coding == _HTTP_CODING_DEFLATE ? -11 : 27, 7, Z_DEFAULT_STRATEGY)) < Z_OK)
{
free(http->sbuffer);
free(http->stream);
http->sbuffer = NULL;
http->stream = NULL;
http->status = HTTP_STATUS_ERROR;
http->error = zerr == Z_MEM_ERROR ? ENOMEM : EINVAL;
return;
}
((z_stream *)http->stream)->next_out = (Bytef *)http->sbuffer;
((z_stream *)http->stream)->avail_out = (uInt)_HTTP_MAX_SBUFFER;
break;
case _HTTP_CODING_INFLATE :
case _HTTP_CODING_GUNZIP :
if ((http->sbuffer = malloc(_HTTP_MAX_SBUFFER)) == NULL)
{
http->status = HTTP_STATUS_ERROR;
http->error = errno;
return;
}
if ((http->stream = calloc(1, sizeof(z_stream))) == NULL)
{
free(http->sbuffer);
http->sbuffer = NULL;
http->status = HTTP_STATUS_ERROR;
http->error = errno;
return;
}
if ((zerr = inflateInit2((z_stream *)http->stream, coding == _HTTP_CODING_INFLATE ? -15 : 31)) < Z_OK)
{
free(http->sbuffer);
free(http->stream);
http->sbuffer = NULL;
http->stream = NULL;
http->status = HTTP_STATUS_ERROR;
http->error = zerr == Z_MEM_ERROR ? ENOMEM : EINVAL;
return;
}
((z_stream *)http->stream)->avail_in = 0;
((z_stream *)http->stream)->next_in = http->sbuffer;
break;
default :
break;
}
http->coding = coding;
DEBUG_printf(("1http_content_coding_start: http->coding now %d.",
http->coding));
}
#endif
static http_t *
http_create(
const char *host,
int port,
http_addrlist_t *addrlist,
int family,
http_encryption_t encryption,
int blocking,
_http_mode_t mode)
{
http_t *http;
char service[255];
http_addrlist_t *myaddrlist = NULL;
DEBUG_printf(("4http_create(host=\"%s\", port=%d, addrlist=%p, family=%d, encryption=%d, blocking=%d, mode=%d)", host, port, (void *)addrlist, family, encryption, blocking, mode));
if (!host && mode == _HTTP_MODE_CLIENT)
return (NULL);
httpInitialize();
if (addrlist)
{
myaddrlist = httpAddrCopyList(addrlist);
}
else
{
snprintf(service, sizeof(service), "%d", port);
myaddrlist = httpAddrGetList(host, family, service);
}
if (!myaddrlist)
return (NULL);
if ((http = calloc(sizeof(http_t), 1)) == NULL)
{
_cupsSetError(IPP_STATUS_ERROR_INTERNAL, strerror(errno), 0);
httpAddrFreeList(myaddrlist);
return (NULL);
}
http->mode = mode;
http->activity = time(NULL);
http->addrlist = myaddrlist;
http->blocking = blocking;
http->fd = -1;
#ifdef HAVE_GSSAPI
http->gssctx = GSS_C_NO_CONTEXT;
http->gssname = GSS_C_NO_NAME;
#endif
http->status = HTTP_STATUS_CONTINUE;
http->version = HTTP_VERSION_1_1;
if (host)
strlcpy(http->hostname, host, sizeof(http->hostname));
if (port == 443)
http->encryption = HTTP_ENCRYPTION_ALWAYS;
else
http->encryption = encryption;
http_set_wait(http);
return (http);
}
#ifdef DEBUG
static void
http_debug_hex(const char *prefix,
const char *buffer,
int bytes)
{
int i, j,
ch;
char line[255],
*start,
*ptr;
if (_cups_debug_fd < 0 || _cups_debug_level < 6)
return;
DEBUG_printf(("6%s: %d bytes:", prefix, bytes));
snprintf(line, sizeof(line), "6%s: ", prefix);
start = line + strlen(line);
for (i = 0; i < bytes; i += 16)
{
for (j = 0, ptr = start; j < 16 && (i + j) < bytes; j ++, ptr += 2)
snprintf(ptr, 3, "%02X", buffer[i + j] & 255);
while (j < 16)
{
memcpy(ptr, " ", 3);
ptr += 2;
j ++;
}
memcpy(ptr, " ", 3);
ptr += 2;
for (j = 0; j < 16 && (i + j) < bytes; j ++)
{
ch = buffer[i + j] & 255;
if (ch < ' ' || ch >= 127)
ch = '.';
*ptr++ = (char)ch;
}
*ptr = '\0';
DEBUG_puts(line);
}
}
#endif
static ssize_t
http_read(http_t *http,
char *buffer,
size_t length)
{
ssize_t bytes;
DEBUG_printf(("http_read(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length));
if (!http->blocking || http->timeout_value > 0.0)
{
while (!httpWait(http, http->wait_value))
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
DEBUG_puts("2http_read: Timeout.");
return (0);
}
}
DEBUG_printf(("2http_read: Reading %d bytes into buffer.", (int)length));
do
{
#ifdef HAVE_SSL
if (http->tls)
bytes = _httpTLSRead(http, buffer, (int)length);
else
#endif
bytes = recv(http->fd, buffer, length, 0);
if (bytes < 0)
{
#ifdef _WIN32
if (WSAGetLastError() != WSAEINTR)
{
http->error = WSAGetLastError();
return (-1);
}
else if (WSAGetLastError() == WSAEWOULDBLOCK)
{
if (!http->timeout_cb ||
!(*http->timeout_cb)(http, http->timeout_data))
{
http->error = WSAEWOULDBLOCK;
return (-1);
}
}
#else
DEBUG_printf(("2http_read: %s", strerror(errno)));
if (errno == EWOULDBLOCK || errno == EAGAIN)
{
if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
{
http->error = errno;
return (-1);
}
else if (!http->timeout_cb && errno != EAGAIN)
{
http->error = errno;
return (-1);
}
}
else if (errno != EINTR)
{
http->error = errno;
return (-1);
}
#endif
}
}
while (bytes < 0);
DEBUG_printf(("2http_read: Read " CUPS_LLFMT " bytes into buffer.",
CUPS_LLCAST bytes));
#ifdef DEBUG
if (bytes > 0)
http_debug_hex("http_read", buffer, (int)bytes);
#endif
if (bytes < 0)
{
#ifdef _WIN32
if (WSAGetLastError() == WSAEINTR)
bytes = 0;
else
http->error = WSAGetLastError();
#else
if (errno == EINTR || (errno == EAGAIN && !http->timeout_cb))
bytes = 0;
else
http->error = errno;
#endif
}
else if (bytes == 0)
{
http->error = EPIPE;
return (0);
}
return (bytes);
}
static ssize_t
http_read_buffered(http_t *http,
char *buffer,
size_t length)
{
ssize_t bytes;
DEBUG_printf(("http_read_buffered(http=%p, buffer=%p, length=" CUPS_LLFMT ") used=%d", (void *)http, (void *)buffer, CUPS_LLCAST length, http->used));
if (http->used > 0)
{
if (length > (size_t)http->used)
bytes = (ssize_t)http->used;
else
bytes = (ssize_t)length;
DEBUG_printf(("2http_read: Grabbing %d bytes from input buffer.",
(int)bytes));
memcpy(buffer, http->buffer, (size_t)bytes);
http->used -= (int)bytes;
if (http->used > 0)
memmove(http->buffer, http->buffer + bytes, (size_t)http->used);
}
else
bytes = http_read(http, buffer, length);
return (bytes);
}
static ssize_t
http_read_chunk(http_t *http,
char *buffer,
size_t length)
{
DEBUG_printf(("http_read_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length));
if (http->data_remaining <= 0)
{
char len[32];
if (!httpGets(len, sizeof(len), http))
{
DEBUG_puts("1http_read_chunk: Could not get chunk length.");
return (0);
}
if (!len[0])
{
DEBUG_puts("1http_read_chunk: Blank chunk length, trying again...");
if (!httpGets(len, sizeof(len), http))
{
DEBUG_puts("1http_read_chunk: Could not get chunk length.");
return (0);
}
}
http->data_remaining = strtoll(len, NULL, 16);
if (http->data_remaining < 0)
{
DEBUG_printf(("1http_read_chunk: Negative chunk length \"%s\" ("
CUPS_LLFMT ")", len, CUPS_LLCAST http->data_remaining));
return (0);
}
DEBUG_printf(("2http_read_chunk: Got chunk length \"%s\" (" CUPS_LLFMT ")",
len, CUPS_LLCAST http->data_remaining));
if (http->data_remaining == 0)
{
httpGets(len, sizeof(len), http);
}
}
DEBUG_printf(("2http_read_chunk: data_remaining=" CUPS_LLFMT,
CUPS_LLCAST http->data_remaining));
if (http->data_remaining <= 0)
return (0);
else if (length > (size_t)http->data_remaining)
length = (size_t)http->data_remaining;
return (http_read_buffered(http, buffer, length));
}
static int
http_send(http_t *http,
http_state_t request,
const char *uri)
{
int i;
char buf[1024];
const char *value;
static const char * const codes[] =
{
NULL,
"OPTIONS",
"GET",
NULL,
"HEAD",
"POST",
NULL,
NULL,
"PUT",
NULL,
"DELETE",
"TRACE",
"CLOSE",
NULL,
NULL
};
DEBUG_printf(("4http_send(http=%p, request=HTTP_%s, uri=\"%s\")", (void *)http, codes[request], uri));
if (http == NULL || uri == NULL)
return (-1);
if (!http->fields[HTTP_FIELD_USER_AGENT])
{
if (http->default_fields[HTTP_FIELD_USER_AGENT])
httpSetField(http, HTTP_FIELD_USER_AGENT, http->default_fields[HTTP_FIELD_USER_AGENT]);
else
httpSetField(http, HTTP_FIELD_USER_AGENT, cupsUserAgent());
}
if (!http->fields[HTTP_FIELD_ACCEPT_ENCODING] && http->default_fields[HTTP_FIELD_ACCEPT_ENCODING])
httpSetField(http, HTTP_FIELD_ACCEPT_ENCODING, http->default_fields[HTTP_FIELD_ACCEPT_ENCODING]);
_httpEncodeURI(buf, uri, sizeof(buf));
if (http->fd < 0 || http->status == HTTP_STATUS_ERROR ||
http->status >= HTTP_STATUS_BAD_REQUEST)
{
DEBUG_printf(("5http_send: Reconnecting, fd=%d, status=%d, tls_upgrade=%d",
http->fd, http->status, http->tls_upgrade));
if (httpReconnect2(http, 30000, NULL))
return (-1);
}
if (http->wused)
{
if (httpFlushWrite(http) < 0)
if (httpReconnect2(http, 30000, NULL))
return (-1);
}
http->state = request;
http->data_encoding = HTTP_ENCODING_FIELDS;
if (request == HTTP_STATE_POST || request == HTTP_STATE_PUT)
http->state ++;
http->status = HTTP_STATUS_CONTINUE;
#ifdef HAVE_SSL
if (http->encryption == HTTP_ENCRYPTION_REQUIRED && !http->tls)
{
httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.2,TLS/1.1,TLS/1.0");
}
#endif
if (httpPrintf(http, "%s %s HTTP/1.1\r\n", codes[request], buf) < 1)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
for (i = 0; i < HTTP_FIELD_MAX; i ++)
if ((value = httpGetField(http, i)) != NULL && *value)
{
DEBUG_printf(("5http_send: %s: %s", http_fields[i], value));
if (i == HTTP_FIELD_HOST)
{
if (httpPrintf(http, "Host: %s:%d\r\n", value,
httpAddrPort(http->hostaddr)) < 1)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
}
else if (httpPrintf(http, "%s: %s\r\n", http_fields[i], value) < 1)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
}
if (http->cookie)
if (httpPrintf(http, "Cookie: $Version=0; %s\r\n", http->cookie) < 1)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
DEBUG_printf(("5http_send: expect=%d, mode=%d, state=%d", http->expect,
http->mode, http->state));
if (http->expect == HTTP_STATUS_CONTINUE && http->mode == _HTTP_MODE_CLIENT &&
(http->state == HTTP_STATE_POST_RECV ||
http->state == HTTP_STATE_PUT_RECV))
if (httpPrintf(http, "Expect: 100-continue\r\n") < 1)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
if (httpPrintf(http, "\r\n") < 1)
{
http->status = HTTP_STATUS_ERROR;
return (-1);
}
if (httpFlushWrite(http) < 0)
return (-1);
http_set_length(http);
httpClearFields(http);
if (http->fields[HTTP_FIELD_AUTHORIZATION] && http->authstring &&
(!strncmp(http->authstring, "Negotiate", 9) ||
!strncmp(http->authstring, "AuthRef", 7)))
{
http->_authstring[0] = '\0';
if (http->authstring != http->_authstring)
free(http->authstring);
http->authstring = http->_authstring;
}
return (0);
}
static off_t
http_set_length(http_t *http)
{
off_t remaining;
DEBUG_printf(("http_set_length(http=%p) mode=%d state=%s", (void *)http, http->mode, httpStateString(http->state)));
if ((remaining = httpGetLength2(http)) >= 0)
{
if (http->mode == _HTTP_MODE_SERVER &&
http->state != HTTP_STATE_GET_SEND &&
http->state != HTTP_STATE_PUT &&
http->state != HTTP_STATE_POST &&
http->state != HTTP_STATE_POST_SEND)
{
DEBUG_puts("1http_set_length: Not setting data_encoding/remaining.");
return (remaining);
}
if (!_cups_strcasecmp(httpGetField(http, HTTP_FIELD_TRANSFER_ENCODING), "chunked"))
{
DEBUG_puts("1http_set_length: Setting data_encoding to "
"HTTP_ENCODING_CHUNKED.");
http->data_encoding = HTTP_ENCODING_CHUNKED;
}
else
{
DEBUG_puts("1http_set_length: Setting data_encoding to "
"HTTP_ENCODING_LENGTH.");
http->data_encoding = HTTP_ENCODING_LENGTH;
}
DEBUG_printf(("1http_set_length: Setting data_remaining to " CUPS_LLFMT ".",
CUPS_LLCAST remaining));
http->data_remaining = remaining;
if (remaining <= INT_MAX)
http->_data_remaining = (int)remaining;
else
http->_data_remaining = INT_MAX;
}
return (remaining);
}
static void
http_set_timeout(int fd,
double timeout)
{
#ifdef _WIN32
DWORD tv = (DWORD)(timeout * 1000);
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CUPS_SOCAST &tv, sizeof(tv));
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, CUPS_SOCAST &tv, sizeof(tv));
#else
struct timeval tv;
tv.tv_sec = (int)timeout;
tv.tv_usec = (int)(1000000 * fmod(timeout, 1.0));
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, CUPS_SOCAST &tv, sizeof(tv));
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, CUPS_SOCAST &tv, sizeof(tv));
#endif
}
static void
http_set_wait(http_t *http)
{
if (http->blocking)
{
http->wait_value = (int)(http->timeout_value * 1000);
if (http->wait_value <= 0)
http->wait_value = 60000;
}
else
http->wait_value = 10000;
}
#ifdef HAVE_SSL
static int
http_tls_upgrade(http_t *http)
{
int ret;
http_t myhttp;
DEBUG_printf(("7http_tls_upgrade(%p)", (void *)http));
httpFlush(http);
memcpy(&myhttp, http, sizeof(myhttp));
http->tls_upgrade = 1;
memset(http->fields, 0, sizeof(http->fields));
http->expect = (http_status_t)0;
if (http->hostname[0] == '/')
httpSetField(http, HTTP_FIELD_HOST, "localhost");
else
httpSetField(http, HTTP_FIELD_HOST, http->hostname);
httpSetField(http, HTTP_FIELD_CONNECTION, "upgrade");
httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.2,TLS/1.1,TLS/1.0");
if ((ret = httpOptions(http, "*")) == 0)
{
while (httpUpdate(http) == HTTP_STATUS_CONTINUE);
}
memcpy(http->_fields, myhttp._fields, sizeof(http->_fields));
memcpy(http->fields, myhttp.fields, sizeof(http->fields));
http->data_encoding = myhttp.data_encoding;
http->data_remaining = myhttp.data_remaining;
http->_data_remaining = myhttp._data_remaining;
http->expect = myhttp.expect;
http->digest_tries = myhttp.digest_tries;
http->tls_upgrade = 0;
if (!http->tls)
{
DEBUG_puts("8http_tls_upgrade: Server does not support HTTP upgrade!");
_cupsSetError(IPP_STATUS_ERROR_CUPS_PKI, _("Encryption is not supported."), 1);
httpAddrClose(NULL, http->fd);
http->fd = -1;
return (-1);
}
else
return (ret);
}
#endif
static ssize_t
http_write(http_t *http,
const char *buffer,
size_t length)
{
ssize_t tbytes,
bytes;
DEBUG_printf(("2http_write(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length));
http->error = 0;
tbytes = 0;
while (length > 0)
{
DEBUG_printf(("3http_write: About to write %d bytes.", (int)length));
if (http->timeout_value > 0.0)
{
#ifdef HAVE_POLL
struct pollfd pfd;
#else
fd_set output_set;
struct timeval timeout;
#endif
int nfds;
do
{
#ifdef HAVE_POLL
pfd.fd = http->fd;
pfd.events = POLLOUT;
while ((nfds = poll(&pfd, 1, http->wait_value)) < 0 &&
(errno == EINTR || errno == EAGAIN))
;
#else
do
{
FD_ZERO(&output_set);
FD_SET(http->fd, &output_set);
timeout.tv_sec = http->wait_value / 1000;
timeout.tv_usec = 1000 * (http->wait_value % 1000);
nfds = select(http->fd + 1, NULL, &output_set, NULL, &timeout);
}
# ifdef _WIN32
while (nfds < 0 && (WSAGetLastError() == WSAEINTR ||
WSAGetLastError() == WSAEWOULDBLOCK));
# else
while (nfds < 0 && (errno == EINTR || errno == EAGAIN));
# endif
#endif
if (nfds < 0)
{
http->error = errno;
return (-1);
}
else if (nfds == 0 && (!http->timeout_cb || !(*http->timeout_cb)(http, http->timeout_data)))
{
#ifdef _WIN32
http->error = WSAEWOULDBLOCK;
#else
http->error = EWOULDBLOCK;
#endif
return (-1);
}
}
while (nfds <= 0);
}
#ifdef HAVE_SSL
if (http->tls)
bytes = _httpTLSWrite(http, buffer, (int)length);
else
#endif
bytes = send(http->fd, buffer, length, 0);
DEBUG_printf(("3http_write: Write of " CUPS_LLFMT " bytes returned "
CUPS_LLFMT ".", CUPS_LLCAST length, CUPS_LLCAST bytes));
if (bytes < 0)
{
#ifdef _WIN32
if (WSAGetLastError() == WSAEINTR)
continue;
else if (WSAGetLastError() == WSAEWOULDBLOCK)
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
http->error = WSAGetLastError();
}
else if (WSAGetLastError() != http->error &&
WSAGetLastError() != WSAECONNRESET)
{
http->error = WSAGetLastError();
continue;
}
#else
if (errno == EINTR)
continue;
else if (errno == EWOULDBLOCK || errno == EAGAIN)
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
else if (!http->timeout_cb && errno == EAGAIN)
continue;
http->error = errno;
}
else if (errno != http->error && errno != ECONNRESET)
{
http->error = errno;
continue;
}
#endif
DEBUG_printf(("3http_write: error writing data (%s).",
strerror(http->error)));
return (-1);
}
buffer += bytes;
tbytes += bytes;
length -= (size_t)bytes;
}
#ifdef DEBUG
http_debug_hex("http_write", buffer - tbytes, (int)tbytes);
#endif
DEBUG_printf(("3http_write: Returning " CUPS_LLFMT ".", CUPS_LLCAST tbytes));
return (tbytes);
}
static ssize_t
http_write_chunk(http_t *http,
const char *buffer,
size_t length)
{
char header[16];
ssize_t bytes;
DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=" CUPS_LLFMT ")", (void *)http, (void *)buffer, CUPS_LLCAST length));
snprintf(header, sizeof(header), "%x\r\n", (unsigned)length);
if (http_write(http, header, strlen(header)) < 0)
{
DEBUG_puts("8http_write_chunk: http_write of length failed.");
return (-1);
}
if ((bytes = http_write(http, buffer, length)) < 0)
{
DEBUG_puts("8http_write_chunk: http_write of buffer failed.");
return (-1);
}
if (http_write(http, "\r\n", 2) < 0)
{
DEBUG_puts("8http_write_chunk: http_write of CR LF failed.");
return (-1);
}
return (bytes);
}