#include "cups-private.h"
#include <fcntl.h>
#include <math.h>
#ifdef WIN32
# include <tchar.h>
#else
# include <signal.h>
# include <sys/time.h>
# include <sys/resource.h>
# include <sys/utsname.h>
#endif
#ifdef HAVE_POLL
# include <poll.h>
#endif
#ifdef DEBUG
static void http_debug_hex(const char *prefix, const char *buffer,
int bytes);
#endif
static http_field_t http_field(const char *name);
static int http_send(http_t *http, http_state_t request,
const char *uri);
static int http_write(http_t *http, const char *buffer,
int length);
static int http_write_chunk(http_t *http, const char *buffer,
int length);
#ifdef HAVE_SSL
static int http_read_ssl(http_t *http, char *buf, int len);
# if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
static int http_set_credentials(http_t *http);
# endif
#endif
static void http_set_timeout(int fd, double timeout);
static void http_set_wait(http_t *http);
#ifdef HAVE_SSL
static int http_setup_ssl(http_t *http);
static void http_shutdown_ssl(http_t *http);
static int http_upgrade(http_t *http);
static int http_write_ssl(http_t *http, const char *buf, int len);
#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"
};
#ifdef DEBUG
static const char * const http_states[] =
{
"HTTP_WAITING",
"HTTP_OPTIONS",
"HTTP_GET",
"HTTP_GET_SEND",
"HTTP_HEAD",
"HTTP_POST",
"HTTP_POST_RECV",
"HTTP_POST_SEND",
"HTTP_PUT",
"HTTP_PUT_RECV",
"HTTP_DELETE",
"HTTP_TRACE",
"HTTP_CLOSE",
"HTTP_STATUS"
};
#endif
#if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
static int http_bio_write(BIO *h, const char *buf, int num);
static int http_bio_read(BIO *h, char *buf, int size);
static int http_bio_puts(BIO *h, const char *str);
static long http_bio_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int http_bio_new(BIO *h);
static int http_bio_free(BIO *data);
static BIO_METHOD http_bio_methods =
{
BIO_TYPE_SOCKET,
"http",
http_bio_write,
http_bio_read,
http_bio_puts,
NULL,
http_bio_ctrl,
http_bio_new,
http_bio_free,
NULL,
};
#endif
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);
}
#if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
BIO_METHOD *
_httpBIOMethods(void)
{
return (&http_bio_methods);
}
#endif
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)
{
if (http)
{
memset(http->fields, 0, sizeof(http->fields));
if (http->hostname[0] == '/')
httpSetField(http, HTTP_FIELD_HOST, "localhost");
else
httpSetField(http, HTTP_FIELD_HOST, http->hostname);
if (http->field_authorization)
{
free(http->field_authorization);
http->field_authorization = NULL;
}
http->expect = (http_status_t)0;
}
}
void
httpClose(http_t *http)
{
#ifdef HAVE_GSSAPI
OM_uint32 minor_status;
#endif
DEBUG_printf(("httpClose(http=%p)", 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);
}
http_t *
httpConnect(const char *host,
int port)
{
return (httpConnectEncrypt(host, port, HTTP_ENCRYPT_IF_REQUESTED));
}
http_t *
httpConnectEncrypt(
const char *host,
int port,
http_encryption_t encryption)
{
http_t *http;
DEBUG_printf(("httpConnectEncrypt(host=\"%s\", port=%d, encryption=%d)",
host, port, encryption));
if ((http = _httpCreate(host, port, NULL, encryption, AF_UNSPEC)) == NULL)
return (NULL);
if (!httpReconnect(http))
return (http);
httpAddrFreeList(http->addrlist);
free(http);
return (NULL);
}
int
httpCopyCredentials(
http_t *http,
cups_array_t **credentials)
{
# ifdef HAVE_LIBSSL
# elif defined(HAVE_GNUTLS)
# elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
OSStatus error;
CFIndex count;
CFArrayRef peerCerts;
SecCertificateRef secCert;
CFDataRef data;
int i;
# elif defined(HAVE_SSPISSL)
# endif
if (credentials)
*credentials = NULL;
if (!http || !http->tls || !credentials)
return (-1);
# ifdef HAVE_LIBSSL
return (-1);
# elif defined(HAVE_GNUTLS)
return (-1);
# elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
if (!(error = SSLCopyPeerCertificates(http->tls, &peerCerts)) && peerCerts)
{
if ((*credentials = cupsArrayNew(NULL, NULL)) != NULL)
{
for (i = 0, count = CFArrayGetCount(peerCerts); i < count; i++)
{
secCert = (SecCertificateRef)CFArrayGetValueAtIndex(peerCerts, i);
if ((data = SecCertificateCopyData(secCert)))
{
httpAddCredential(*credentials, CFDataGetBytePtr(data),
CFDataGetLength(data));
CFRelease(data);
}
}
}
CFRelease(peerCerts);
}
return (error);
# elif defined(HAVE_SSPISSL)
return (-1);
# else
return (-1);
# endif
}
http_t *
_httpCreate(
const char *host,
int port,
http_addrlist_t *addrlist,
http_encryption_t encryption,
int family)
{
http_t *http;
char service[255];
DEBUG_printf(("4_httpCreate(host=\"%s\", port=%d, encryption=%d)",
host, port, encryption));
if (!host)
return (NULL);
httpInitialize();
sprintf(service, "%d", port);
if (!addrlist)
if ((addrlist = httpAddrGetList(host, family, service)) == NULL)
return (NULL);
if ((http = calloc(sizeof(http_t), 1)) == NULL)
{
_cupsSetError(IPP_INTERNAL_ERROR, strerror(errno), 0);
httpAddrFreeList(addrlist);
return (NULL);
}
http->activity = time(NULL);
http->addrlist = addrlist;
http->blocking = 1;
http->fd = -1;
#ifdef HAVE_GSSAPI
http->gssctx = GSS_C_NO_CONTEXT;
http->gssname = GSS_C_NO_NAME;
#endif
http->version = HTTP_1_1;
strlcpy(http->hostname, host, sizeof(http->hostname));
if (port == 443)
http->encryption = HTTP_ENCRYPT_ALWAYS;
else
http->encryption = encryption;
http_set_wait(http);
return (http);
}
http_tls_credentials_t
_httpCreateCredentials(
cups_array_t *credentials)
{
if (!credentials)
return (NULL);
# ifdef HAVE_LIBSSL
return (NULL);
# elif defined(HAVE_GNUTLS)
return (NULL);
# elif defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
CFMutableArrayRef peerCerts;
SecCertificateRef secCert;
CFDataRef data;
http_credential_t *credential;
if ((peerCerts = CFArrayCreateMutable(kCFAllocatorDefault,
cupsArrayCount(credentials),
&kCFTypeArrayCallBacks)) == NULL)
return (NULL);
for (credential = (http_credential_t *)cupsArrayFirst(credentials);
credential;
credential = (http_credential_t *)cupsArrayNext(credentials))
{
if ((data = CFDataCreate(kCFAllocatorDefault, credential->data,
credential->datalen)))
{
if ((secCert = SecCertificateCreateWithData(kCFAllocatorDefault, data))
!= NULL)
{
CFArrayAppendValue(peerCerts, secCert);
CFRelease(secCert);
}
CFRelease(data);
}
}
return (peerCerts);
# elif defined(HAVE_SSPISSL)
return (NULL);
# else
return (NULL);
# endif
}
int
httpDelete(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_DELETE, uri));
}
void
_httpDisconnect(http_t *http)
{
#ifdef HAVE_SSL
if (http->tls)
http_shutdown_ssl(http);
#endif
#ifdef WIN32
closesocket(http->fd);
#else
close(http->fd);
#endif
http->fd = -1;
}
int
httpEncryption(http_t *http,
http_encryption_t e)
{
DEBUG_printf(("httpEncryption(http=%p, e=%d)", http, e));
#ifdef HAVE_SSL
if (!http)
return (0);
http->encryption = e;
if ((http->encryption == HTTP_ENCRYPT_ALWAYS && !http->tls) ||
(http->encryption == HTTP_ENCRYPT_NEVER && http->tls))
return (httpReconnect(http));
else if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
return (http_upgrade(http));
else
return (0);
#else
if (e == HTTP_ENCRYPT_ALWAYS || e == HTTP_ENCRYPT_REQUIRED)
return (-1);
else
return (0);
#endif
}
int
httpError(http_t *http)
{
if (http)
return (http->error);
else
return (EINVAL);
}
void
httpFlush(http_t *http)
{
char buffer[8192];
int blocking;
http_state_t oldstate;
DEBUG_printf(("httpFlush(http=%p), state=%s", http,
http_states[http->state]));
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_WAITING && http->fd >= 0)
{
http->state = HTTP_WAITING;
#ifdef HAVE_SSL
if (http->tls)
http_shutdown_ssl(http);
#endif
#ifdef WIN32
closesocket(http->fd);
#else
close(http->fd);
#endif
http->fd = -1;
}
}
int
httpFlushWrite(http_t *http)
{
int bytes;
DEBUG_printf(("httpFlushWrite(http=%p)", http));
if (!http || !http->wused)
{
DEBUG_puts(http ? "1httpFlushWrite: Write buffer is empty." :
"1httpFlushWrite: No connection.");
return (0);
}
if (http->data_encoding == HTTP_ENCODE_CHUNKED)
bytes = http_write_chunk(http, http->wbuffer, http->wused);
else
bytes = http_write(http, http->wbuffer, http->wused);
http->wused = 0;
DEBUG_printf(("1httpFlushWrite: Returning %d, errno=%d.", bytes, errno));
return (bytes);
}
void
_httpFreeCredentials(
http_tls_credentials_t credentials)
{
if (!credentials)
return;
#ifdef HAVE_LIBSSL
(void)credentials;
#elif defined(HAVE_GNUTLS)
(void)credentials;
#elif defined(HAVE_CDSASSL)
CFRelease(credentials);
#elif defined(HAVE_SSPISSL)
(void)credentials;
#endif
}
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_GET, uri));
}
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 *
httpGetCookie(http_t *http)
{
return (http ? http->cookie : NULL);
}
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 (field == HTTP_FIELD_AUTHORIZATION &&
http->field_authorization)
{
return (http->field_authorization);
}
else
return (http->fields[field]);
}
int
httpGetLength(http_t *http)
{
if (http)
{
httpGetLength2(http);
return (http->_data_remaining);
}
else
return (-1);
}
off_t
httpGetLength2(http_t *http)
{
DEBUG_printf(("2httpGetLength2(http=%p), state=%s", http,
http_states[http->state]));
if (!http)
return (-1);
if (!_cups_strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked"))
{
DEBUG_puts("4httpGetLength2: chunked request!");
http->data_encoding = HTTP_ENCODE_CHUNKED;
http->data_remaining = 0;
}
else
{
http->data_encoding = HTTP_ENCODE_LENGTH;
if (!http->fields[HTTP_FIELD_CONTENT_LENGTH][0])
{
if (http->status >= HTTP_MULTIPLE_CHOICES)
http->data_remaining = 0;
else
http->data_remaining = 2147483647;
}
else
http->data_remaining = strtoll(http->fields[HTTP_FIELD_CONTENT_LENGTH],
NULL, 10);
DEBUG_printf(("4httpGetLength2: content_length=" CUPS_LLFMT,
CUPS_LLCAST http->data_remaining));
}
if (http->data_remaining <= INT_MAX)
http->_data_remaining = (int)http->data_remaining;
else
http->_data_remaining = INT_MAX;
return (http->data_remaining);
}
char *
httpGets(char *line,
int length,
http_t *http)
{
char *lineptr,
*lineend,
*bufptr,
*bufend;
int bytes,
eol;
DEBUG_printf(("2httpGets(line=%p, length=%d, http=%p)", line, length, http));
if (http == NULL || line == NULL)
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);
}
#ifdef HAVE_SSL
if (http->tls)
bytes = http_read_ssl(http, http->buffer + http->used,
HTTP_MAX_BUFFER - http->used);
else
#endif
bytes = recv(http->fd, http->buffer + http->used,
HTTP_MAX_BUFFER - http->used, 0);
DEBUG_printf(("4httpGets: read %d bytes...", bytes));
#ifdef DEBUG
http_debug_hex("httpGets", http->buffer + http->used, bytes);
#endif
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 += 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, 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_ERROR);
}
http_status_t
httpGetStatus(http_t *http)
{
return (http ? http->status : HTTP_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)", http, field, name, value, valuelen));
if (!http || !name || !value || valuelen < 2 ||
field <= HTTP_FIELD_UNKNOWN || field >= HTTP_FIELD_MAX)
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_1_0);
}
int
httpHead(http_t *http,
const char *uri)
{
DEBUG_printf(("httpHead(http=%p, uri=\"%s\")", http, uri));
return (http_send(http, HTTP_HEAD, uri));
}
void
httpInitialize(void)
{
static int initialized = 0;
#ifdef WIN32
WSADATA winsockdata;
#endif
#ifdef HAVE_LIBSSL
int i;
unsigned char data[1024];
#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_GNUTLS
gnutls_global_init();
#elif defined(HAVE_LIBSSL)
SSL_load_error_strings();
SSL_library_init();
CUPS_SRAND(time(NULL));
for (i = 0; i < sizeof(data); i ++)
data[i] = CUPS_RAND();
RAND_seed(data, sizeof(data));
#endif
initialized = 1;
_cupsGlobalUnlock();
}
int
httpOptions(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_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 ")",
http, 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_ENCODE_CHUNKED &&
http->data_remaining <= 0)
{
DEBUG_puts("2_httpPeek: Getting chunk length...");
if (httpGets(len, sizeof(len), http) == NULL)
{
DEBUG_puts("1_httpPeek: Could not get length!");
return (0);
}
http->data_remaining = strtoll(len, NULL, 16);
if (http->data_remaining < 0)
{
DEBUG_puts("1_httpPeek: Negative chunk length!");
return (0);
}
}
DEBUG_printf(("2_httpPeek: data_remaining=" CUPS_LLFMT,
CUPS_LLCAST http->data_remaining));
if (http->data_remaining <= 0)
{
if (http->data_encoding == HTTP_ENCODE_CHUNKED)
httpGets(len, sizeof(len), http);
if (http->state == HTTP_POST_RECV)
http->state ++;
else
http->state = HTTP_WAITING;
http->data_encoding = HTTP_ENCODE_LENGTH;
return (0);
}
else if (length > (size_t)http->data_remaining)
length = (size_t)http->data_remaining;
if (http->used == 0)
{
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 (http->data_remaining > sizeof(http->buffer))
buflen = sizeof(http->buffer);
else
buflen = http->data_remaining;
DEBUG_printf(("2_httpPeek: Reading %d bytes into buffer.", (int)buflen));
do
{
#ifdef HAVE_SSL
if (http->tls)
bytes = http_read_ssl(http, http->buffer, buflen);
else
#endif
bytes = recv(http->fd, http->buffer, buflen, 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
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(("2_httpPeek: Read " CUPS_LLFMT " bytes into buffer.",
CUPS_LLCAST bytes));
#ifdef DEBUG
http_debug_hex("_httpPeek", http->buffer, (int)bytes);
#endif
http->used = bytes;
}
if (http->used > 0)
{
if (length > (size_t)http->used)
length = (size_t)http->used;
bytes = (ssize_t)length;
DEBUG_printf(("2_httpPeek: 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);
}
#ifdef DEBUG
http_debug_hex("_httpPeek", buffer, (int)bytes);
#endif
return (bytes);
}
int
httpPost(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_POST, uri));
}
int
httpPrintf(http_t *http,
const char *format,
...)
{
int bytes;
char buf[16384];
va_list ap;
DEBUG_printf(("2httpPrintf(http=%p, format=\"%s\", ...)", http, format));
va_start(ap, format);
bytes = vsnprintf(buf, sizeof(buf), format, ap);
va_end(ap);
DEBUG_printf(("3httpPrintf: %s", buf));
if (http->data_encoding == HTTP_ENCODE_FIELDS)
return (httpWrite2(http, buf, bytes));
else
{
if (http->wused)
{
DEBUG_puts("4httpPrintf: flushing existing data...");
if (httpFlushWrite(http) < 0)
return (-1);
}
return (http_write(http, buf, bytes));
}
}
int
httpPut(http_t *http,
const char *uri)
{
DEBUG_printf(("httpPut(http=%p, uri=\"%s\")", http, uri));
return (http_send(http, HTTP_PUT, uri));
}
int
httpRead(http_t *http,
char *buffer,
int length)
{
return ((int)httpRead2(http, buffer, length));
}
ssize_t
httpRead2(http_t *http,
char *buffer,
size_t length)
{
ssize_t bytes;
char len[32];
DEBUG_printf(("httpRead2(http=%p, buffer=%p, length=" CUPS_LLFMT ")",
http, 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_ENCODE_CHUNKED &&
http->data_remaining <= 0)
{
DEBUG_puts("2httpRead2: Getting chunk length...");
if (httpGets(len, sizeof(len), http) == NULL)
{
DEBUG_puts("1httpRead2: Could not get length!");
return (0);
}
http->data_remaining = strtoll(len, NULL, 16);
if (http->data_remaining < 0)
{
DEBUG_puts("1httpRead2: Negative chunk length!");
return (0);
}
}
DEBUG_printf(("2httpRead2: data_remaining=" CUPS_LLFMT,
CUPS_LLCAST http->data_remaining));
if (http->data_remaining <= 0)
{
if (http->data_encoding == HTTP_ENCODE_CHUNKED)
httpGets(len, sizeof(len), http);
if (http->state == HTTP_POST_RECV)
http->state ++;
else
http->state = HTTP_WAITING;
http->data_encoding = HTTP_ENCODE_LENGTH;
return (0);
}
else if (length > (size_t)http->data_remaining)
length = (size_t)http->data_remaining;
if (http->used == 0 && length <= 256)
{
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 (http->data_remaining > sizeof(http->buffer))
buflen = sizeof(http->buffer);
else
buflen = http->data_remaining;
DEBUG_printf(("2httpRead2: Reading %d bytes into buffer.", (int)buflen));
do
{
#ifdef HAVE_SSL
if (http->tls)
bytes = http_read_ssl(http, http->buffer, buflen);
else
#endif
bytes = recv(http->fd, http->buffer, buflen, 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
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(("2httpRead2: Read " CUPS_LLFMT " bytes into buffer.",
CUPS_LLCAST bytes));
#ifdef DEBUG
http_debug_hex("httpRead2", http->buffer, (int)bytes);
#endif
http->used = bytes;
}
if (http->used > 0)
{
if (length > (size_t)http->used)
length = (size_t)http->used;
bytes = (ssize_t)length;
DEBUG_printf(("2httpRead2: grabbing %d bytes from input buffer...",
(int)bytes));
memcpy(buffer, http->buffer, length);
http->used -= (int)length;
if (http->used > 0)
memmove(http->buffer, http->buffer + length, http->used);
}
#ifdef HAVE_SSL
else if (http->tls)
{
if (!http->blocking)
{
while (!httpWait(http, http->wait_value))
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
return (0);
}
}
while ((bytes = (ssize_t)http_read_ssl(http, buffer, (int)length)) < 0)
{
#ifdef WIN32
if (WSAGetLastError() == WSAEWOULDBLOCK)
{
if (!http->timeout_cb || !(*http->timeout_cb)(http, http->timeout_data))
break;
}
else if (WSAGetLastError() != WSAEINTR)
break;
#else
if (errno == EWOULDBLOCK || errno == EAGAIN)
{
if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
break;
else if (!http->timeout_cb && errno != EAGAIN)
break;
}
else if (errno != EINTR)
break;
#endif
}
}
#endif
else
{
if (!http->blocking)
{
while (!httpWait(http, http->wait_value))
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
return (0);
}
}
DEBUG_printf(("2httpRead2: reading " CUPS_LLFMT " bytes from socket...",
CUPS_LLCAST length));
#ifdef WIN32
while ((bytes = (ssize_t)recv(http->fd, buffer, (int)length, 0)) < 0)
{
if (WSAGetLastError() == WSAEWOULDBLOCK)
{
if (!http->timeout_cb || !(*http->timeout_cb)(http, http->timeout_data))
break;
}
else if (WSAGetLastError() != WSAEINTR)
break;
}
#else
while ((bytes = recv(http->fd, buffer, length, 0)) < 0)
{
if (errno == EWOULDBLOCK || errno == EAGAIN)
{
if (http->timeout_cb && !(*http->timeout_cb)(http, http->timeout_data))
break;
else if (!http->timeout_cb && errno != EAGAIN)
break;
}
else if (errno != EINTR)
break;
}
#endif
DEBUG_printf(("2httpRead2: read " CUPS_LLFMT " bytes from socket...",
CUPS_LLCAST bytes));
#ifdef DEBUG
http_debug_hex("httpRead2", buffer, (int)bytes);
#endif
}
if (bytes > 0)
{
http->data_remaining -= bytes;
if (http->data_remaining <= INT_MAX)
http->_data_remaining = (int)http->data_remaining;
else
http->_data_remaining = INT_MAX;
}
else 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
{
http->error = EPIPE;
return (0);
}
if (http->data_remaining == 0)
{
if (http->data_encoding == HTTP_ENCODE_CHUNKED)
httpGets(len, sizeof(len), http);
else if (http->state == HTTP_POST_RECV)
http->state ++;
else
http->state = HTTP_WAITING;
}
return (bytes);
}
#if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
OSStatus
_httpReadCDSA(
SSLConnectionRef connection,
void *data,
size_t *dataLength)
{
OSStatus result;
ssize_t bytes;
http_t *http;
http = (http_t *)connection;
if (!http->blocking)
{
while (!_httpWait(http, http->wait_value, 0))
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
http->error = ETIMEDOUT;
return (-1);
}
}
do
{
bytes = recv(http->fd, data, *dataLength, 0);
}
while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
if (bytes == *dataLength)
{
result = 0;
}
else if (bytes > 0)
{
*dataLength = bytes;
result = errSSLWouldBlock;
}
else
{
*dataLength = 0;
if (bytes == 0)
result = errSSLClosedGraceful;
else if (errno == EAGAIN)
result = errSSLWouldBlock;
else
result = errSSLClosedAbort;
}
return (result);
}
#endif
#if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
ssize_t
_httpReadGNUTLS(
gnutls_transport_ptr ptr,
void *data,
size_t length)
{
http_t *http;
ssize_t bytes;
DEBUG_printf(("6_httpReadGNUTLS(ptr=%p, data=%p, length=%d)", ptr, data, (int)length));
http = (http_t *)ptr;
if (!http->blocking)
{
while (!_httpWait(http, http->wait_value, 0))
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
http->error = ETIMEDOUT;
return (-1);
}
}
bytes = recv(http->fd, data, length, 0);
DEBUG_printf(("6_httpReadGNUTLS: bytes=%d", (int)bytes));
return (bytes);
}
#endif
int
httpReconnect(http_t *http)
{
DEBUG_printf(("httpReconnect(http=%p)", 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)", http, msec,
cancel));
if (!http)
{
_cupsSetError(IPP_INTERNAL_ERROR, strerror(EINVAL), 0);
return (-1);
}
#ifdef HAVE_SSL
if (http->tls)
{
DEBUG_puts("2httpReconnect2: Shutting down SSL/TLS...");
http_shutdown_ssl(http);
}
#endif
if (http->fd >= 0)
{
DEBUG_printf(("2httpReconnect2: Closing socket %d...", http->fd));
#ifdef WIN32
closesocket(http->fd);
#else
close(http->fd);
#endif
http->fd = -1;
}
http->state = HTTP_WAITING;
http->status = HTTP_CONTINUE;
http->version = HTTP_1_1;
http->keep_alive = HTTP_KEEPALIVE_OFF;
memset(&http->_hostaddr, 0, sizeof(http->_hostaddr));
http->data_encoding = HTTP_ENCODE_LENGTH;
http->_data_remaining = 0;
http->used = 0;
http->expect = 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_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_ENCRYPT_ALWAYS)
{
if (http_setup_ssl(http) != 0)
{
# ifdef WIN32
closesocket(http->fd);
# else
close(http->fd);
# endif
return (-1);
}
}
else if (http->encryption == HTTP_ENCRYPT_REQUIRED)
return (http_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)
{
int len = (int)strlen(scheme) + (data ? (int)strlen(data) + 1 : 0) + 1;
char *temp;
if (len > (int)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);
_httpFreeCredentials(http->tls_credentials);
http->tls_credentials = _httpCreateCredentials(credentials);
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
httpSetExpect(http_t *http,
http_status_t expect)
{
if (http)
http->expect = expect;
}
void
httpSetField(http_t *http,
http_field_t field,
const char *value)
{
if (http == NULL ||
field < HTTP_FIELD_ACCEPT_LANGUAGE ||
field > HTTP_FIELD_WWW_AUTHENTICATE ||
value == NULL)
return;
strlcpy(http->fields[field], value, HTTP_MAX_VALUE);
if (field == HTTP_FIELD_AUTHORIZATION)
{
if (http->field_authorization)
free(http->field_authorization);
http->field_authorization = strdup(value);
}
else if (field == HTTP_FIELD_HOST)
{
char *ptr = strchr(value, ':');
if (value[0] != '[' && ptr && strchr(ptr + 1, ':'))
{
snprintf(http->fields[HTTP_FIELD_HOST],
sizeof(http->fields[HTTP_FIELD_HOST]), "[%s]", value);
}
else
{
ptr = http->fields[HTTP_FIELD_HOST];
if (*ptr)
{
ptr += strlen(ptr) - 1;
if (*ptr == '.')
*ptr = '\0';
}
}
}
}
void
httpSetLength(http_t *http,
size_t length)
{
if (!http)
return;
if (!length)
{
strcpy(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked");
http->fields[HTTP_FIELD_CONTENT_LENGTH][0] = '\0';
}
else
{
http->fields[HTTP_FIELD_TRANSFER_ENCODING][0] = '\0';
snprintf(http->fields[HTTP_FIELD_CONTENT_LENGTH], HTTP_MAX_VALUE,
CUPS_LLFMT, CUPS_LLCAST length);
}
}
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);
}
int
httpTrace(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_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", http, status,
http_states[http->state]));
if (!httpGets(line, sizeof(line), http))
{
*status = HTTP_ERROR;
return (0);
}
DEBUG_printf(("2_httpUpdate: Got \"%s\"", line));
if (line[0] == '\0')
{
if (http->status == HTTP_CONTINUE)
{
*status = http->status;
return (0);
}
if (http->status < HTTP_BAD_REQUEST)
http->digest_tries = 0;
#ifdef HAVE_SSL
if (http->status == HTTP_SWITCHING_PROTOCOLS && !http->tls)
{
if (http_setup_ssl(http) != 0)
{
# ifdef WIN32
closesocket(http->fd);
# else
close(http->fd);
# endif
*status = http->status = HTTP_ERROR;
return (0);
}
*status = HTTP_CONTINUE;
return (0);
}
#endif
httpGetLength2(http);
switch (http->state)
{
case HTTP_GET :
case HTTP_POST :
case HTTP_POST_RECV :
case HTTP_PUT :
http->state ++;
case HTTP_POST_SEND :
case HTTP_HEAD :
break;
default :
http->state = HTTP_WAITING;
break;
}
*status = http->status;
return (0);
}
else if (!strncmp(line, "HTTP/", 5))
{
int intstatus;
if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, &intstatus) != 3)
{
*status = http->status = HTTP_ERROR;
return (0);
}
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 ++;
if (!_cups_strcasecmp(line, "expect"))
{
http->expect = (http_status_t)atoi(value);
}
else if (!_cups_strcasecmp(line, "cookie"))
{
httpSetCookie(http, value);
}
else if ((field = http_field(line)) != HTTP_FIELD_UNKNOWN)
httpSetField(http, field, value);
#ifdef DEBUG
else
DEBUG_printf(("1_httpUpdate: unknown field %s seen!", line));
#endif
}
else
{
DEBUG_printf(("1_httpUpdate: Bad response line \"%s\"!", line));
*status = http->status = HTTP_ERROR;
return (0);
}
return (1);
}
http_status_t
httpUpdate(http_t *http)
{
http_status_t status;
DEBUG_printf(("httpUpdate(http=%p), state=%s", http,
http_states[http->state]));
if (http->wused)
{
DEBUG_puts("2httpUpdate: flushing buffer...");
if (httpFlushWrite(http) < 0)
return (HTTP_ERROR);
}
if (http->state == HTTP_WAITING)
return (HTTP_CONTINUE);
while (_httpUpdate(http, &status));
if (http->error == EPIPE && http->status > HTTP_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_ERROR;
return (HTTP_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)", 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 && usessl)
{
# ifdef HAVE_LIBSSL
if (SSL_pending(http->tls))
{
DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
return (1);
}
# elif defined(HAVE_GNUTLS)
if (gnutls_record_check_pending(http->tls))
{
DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
return (1);
}
# elif defined(HAVE_CDSASSL)
size_t bytes;
if (!SSLGetBufferedReadSize(http->tls, &bytes) &&
bytes > 0)
{
DEBUG_puts("5_httpWait: Return 1 since there is pending SSL data.");
return (1);
}
# endif
}
#endif
#ifdef HAVE_POLL
pfd.fd = http->fd;
pfd.events = POLLIN;
while ((nfds = poll(&pfd, 1, msec)) < 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)", http, msec));
if (http == NULL)
return (0);
if (http->used)
{
DEBUG_puts("3httpWait: Returning 1 since there is buffered data ready.");
return (1);
}
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, 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 ")", http,
buffer, CUPS_LLCAST length));
if (http == NULL || buffer == NULL)
return (-1);
http->activity = time(NULL);
if (length > 0)
{
if (http->wused && (length + http->wused) > sizeof(http->wbuffer))
{
DEBUG_printf(("2httpWrite2: Flushing buffer (wused=%d, length="
CUPS_LLFMT ")", http->wused, CUPS_LLCAST length));
httpFlushWrite(http);
}
if ((length + 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_ENCODE_CHUNKED)
bytes = (ssize_t)http_write_chunk(http, buffer, (int)length);
else
bytes = (ssize_t)http_write(http, buffer, (int)length);
DEBUG_printf(("2httpWrite2: Wrote " CUPS_LLFMT " bytes...",
CUPS_LLCAST bytes));
}
if (http->data_encoding == HTTP_ENCODE_LENGTH)
http->data_remaining -= bytes;
}
else
bytes = 0;
if ((http->data_encoding == HTTP_ENCODE_CHUNKED && length == 0) ||
(http->data_encoding == HTTP_ENCODE_LENGTH && http->data_remaining == 0))
{
DEBUG_puts("2httpWrite: changing states...");
if (http->wused)
httpFlushWrite(http);
if (http->data_encoding == HTTP_ENCODE_CHUNKED)
{
http_write(http, "0\r\n\r\n", 5);
http->data_encoding = HTTP_ENCODE_LENGTH;
http->data_remaining = 0;
}
}
return (bytes);
}
#if defined(HAVE_SSL) && defined(HAVE_CDSASSL)
OSStatus
_httpWriteCDSA(
SSLConnectionRef connection,
const void *data,
size_t *dataLength)
{
OSStatus result;
ssize_t bytes;
http_t *http;
http = (http_t *)connection;
do
{
bytes = write(http->fd, data, *dataLength);
}
while (bytes == -1 && (errno == EINTR || errno == EAGAIN));
if (bytes == *dataLength)
{
result = 0;
}
else if (bytes >= 0)
{
*dataLength = bytes;
result = errSSLWouldBlock;
}
else
{
*dataLength = 0;
if (errno == EAGAIN)
result = errSSLWouldBlock;
else
result = errSSLClosedAbort;
}
return (result);
}
#endif
#if defined(HAVE_SSL) && defined(HAVE_GNUTLS)
ssize_t
_httpWriteGNUTLS(
gnutls_transport_ptr ptr,
const void *data,
size_t length)
{
ssize_t bytes;
DEBUG_printf(("6_httpWriteGNUTLS(ptr=%p, data=%p, length=%d)", ptr, data,
(int)length));
#ifdef DEBUG
http_debug_hex("_httpWriteGNUTLS", data, (int)length);
#endif
bytes = send(((http_t *)ptr)->fd, data, length, 0);
DEBUG_printf(("_httpWriteGNUTLS: bytes=%d", (int)bytes));
return (bytes);
}
#endif
#if defined(HAVE_SSL) && defined(HAVE_LIBSSL)
static long
http_bio_ctrl(BIO *h,
int cmd,
long arg1,
void *arg2)
{
switch (cmd)
{
default :
return (0);
case BIO_CTRL_RESET :
h->ptr = NULL;
return (0);
case BIO_C_SET_FILE_PTR :
h->ptr = arg2;
h->init = 1;
return (1);
case BIO_C_GET_FILE_PTR :
if (arg2)
{
*((void **)arg2) = h->ptr;
return (1);
}
else
return (0);
case BIO_CTRL_DUP :
case BIO_CTRL_FLUSH :
return (1);
}
}
static int
http_bio_free(BIO *h)
{
if (!h)
return (0);
if (h->shutdown)
{
h->init = 0;
h->flags = 0;
}
return (1);
}
static int
http_bio_new(BIO *h)
{
if (!h)
return (0);
h->init = 0;
h->num = 0;
h->ptr = NULL;
h->flags = 0;
return (1);
}
static int
http_bio_puts(BIO *h,
const char *str)
{
#ifdef WIN32
return (send(((http_t *)h->ptr)->fd, str, (int)strlen(str), 0));
#else
return (send(((http_t *)h->ptr)->fd, str, strlen(str), 0));
#endif
}
static int
http_bio_read(BIO *h,
char *buf,
int size)
{
http_t *http;
http = (http_t *)h->ptr;
if (!http->blocking)
{
while (!_httpWait(http, http->wait_value, 0))
{
if (http->timeout_cb && (*http->timeout_cb)(http, http->timeout_data))
continue;
#ifdef WIN32
http->error = WSAETIMEDOUT;
#else
http->error = ETIMEDOUT;
#endif
return (-1);
}
}
return (recv(http->fd, buf, size, 0));
}
static int
http_bio_write(BIO *h,
const char *buf,
int num)
{
return (send(((http_t *)h->ptr)->fd, buf, num, 0));
}
#endif
#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)
sprintf(ptr, "%02X", buffer[i + j] & 255);
while (j < 16)
{
strcpy(ptr, " ");
ptr += 2;
j ++;
}
strcpy(ptr, " ");
ptr += 2;
for (j = 0; j < 16 && (i + j) < bytes; j ++)
{
ch = buffer[i + j] & 255;
if (ch < ' ' || ch >= 127)
ch = '.';
*ptr++ = ch;
}
*ptr = '\0';
DEBUG_puts(line);
}
}
#endif
static http_field_t
http_field(const char *name)
{
int i;
for (i = 0; i < HTTP_FIELD_MAX; i ++)
if (_cups_strcasecmp(name, http_fields[i]) == 0)
return ((http_field_t)i);
return (HTTP_FIELD_UNKNOWN);
}
#ifdef HAVE_SSL
static int
http_read_ssl(http_t *http,
char *buf,
int len)
{
# if defined(HAVE_LIBSSL)
return (SSL_read((SSL *)(http->tls), buf, len));
# elif defined(HAVE_GNUTLS)
ssize_t result;
result = gnutls_record_recv(http->tls, buf, len);
if (result < 0 && !errno)
{
switch (result)
{
case GNUTLS_E_INTERRUPTED :
errno = EINTR;
break;
case GNUTLS_E_AGAIN :
errno = EAGAIN;
break;
default :
errno = EPIPE;
break;
}
result = -1;
}
return ((int)result);
# elif defined(HAVE_CDSASSL)
int result;
OSStatus error;
size_t processed;
error = SSLRead(http->tls, buf, len, &processed);
DEBUG_printf(("6http_read_ssl: error=%d, processed=%d", (int)error,
(int)processed));
switch (error)
{
case 0 :
result = (int)processed;
break;
case errSSLWouldBlock :
if (processed)
result = (int)processed;
else
{
result = -1;
errno = EINTR;
}
break;
case errSSLClosedGraceful :
default :
if (processed)
result = (int)processed;
else
{
result = -1;
errno = EPIPE;
}
break;
}
return (result);
# elif defined(HAVE_SSPISSL)
return _sspiRead((_sspi_struct_t*) http->tls, buf, len);
# endif
}
#endif
static int
http_send(http_t *http,
http_state_t request,
const char *uri)
{
int i;
char buf[1024];
static const char * const codes[] =
{
NULL,
"OPTIONS",
"GET",
NULL,
"HEAD",
"POST",
NULL,
NULL,
"PUT",
NULL,
"DELETE",
"TRACE",
"CLOSE"
};
DEBUG_printf(("7http_send(http=%p, request=HTTP_%s, uri=\"%s\")",
http, codes[request], uri));
if (http == NULL || uri == NULL)
return (-1);
if (!http->fields[HTTP_FIELD_USER_AGENT][0])
{
#ifdef WIN32
SYSTEM_INFO sysinfo;
OSVERSIONEX version;
version.dwOSVersionInfoSize = sizeof(OSVERSIONEX);
GetVersionInfoEx(&version);
GetNativeSystemInfo(&sysinfo);
snprintf(buf, sizeof(buf), CUPS_MINIMAL " (Windows %d.%d; %s) IPP/2.0",
version.major, version.minor,
sysinfo.wProcessorArchitecture
== PROCESSOR_ARCHITECTURE_AMD64 ? "amd64" :
sysinfo.wProcessorArchitecture
== PROCESSOR_ARCHITECTURE_ARM ? "arm" :
sysinfo.wProcessorArchitecture
== PROCESSOR_ARCHITECTURE_IA64 ? "ia64" :
sysinfo.wProcessorArchitecture
== PROCESSOR_ARCHITECTURE_INTEL ? "intel" :
"unknown");
#else
struct utsname name;
uname(&name);
snprintf(buf, sizeof(buf), CUPS_MINIMAL " (%s %s; %s) IPP/2.0",
name.sysname, name.release, name.machine);
#endif
DEBUG_printf(("8http_send: Default User-Agent: %s", buf));
httpSetField(http, HTTP_FIELD_USER_AGENT, buf);
}
_httpEncodeURI(buf, uri, sizeof(buf));
if (http->status == HTTP_ERROR || http->status >= HTTP_BAD_REQUEST)
if (httpReconnect(http))
return (-1);
if (http->wused)
{
if (httpFlushWrite(http) < 0)
if (httpReconnect(http))
return (-1);
}
http->state = request;
http->data_encoding = HTTP_ENCODE_FIELDS;
if (request == HTTP_POST || request == HTTP_PUT)
http->state ++;
http->status = HTTP_CONTINUE;
#ifdef HAVE_SSL
if (http->encryption == HTTP_ENCRYPT_REQUIRED && !http->tls)
{
httpSetField(http, HTTP_FIELD_CONNECTION, "Upgrade");
httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.0,SSL/2.0,SSL/3.0");
}
#endif
if (httpPrintf(http, "%s %s HTTP/1.1\r\n", codes[request], buf) < 1)
{
http->status = HTTP_ERROR;
return (-1);
}
for (i = 0; i < HTTP_FIELD_MAX; i ++)
if (http->fields[i][0] != '\0')
{
DEBUG_printf(("9http_send: %s: %s", http_fields[i],
httpGetField(http, i)));
if (i == HTTP_FIELD_HOST)
{
if (httpPrintf(http, "Host: %s:%d\r\n", httpGetField(http, i),
_httpAddrPort(http->hostaddr)) < 1)
{
http->status = HTTP_ERROR;
return (-1);
}
}
else if (httpPrintf(http, "%s: %s\r\n", http_fields[i],
httpGetField(http, i)) < 1)
{
http->status = HTTP_ERROR;
return (-1);
}
}
if (http->cookie)
if (httpPrintf(http, "Cookie: $Version=0; %s\r\n", http->cookie) < 1)
{
http->status = HTTP_ERROR;
return (-1);
}
if (http->expect == HTTP_CONTINUE &&
(http->state == HTTP_POST_RECV || http->state == HTTP_PUT_RECV))
if (httpPrintf(http, "Expect: 100-continue\r\n") < 1)
{
http->status = HTTP_ERROR;
return (-1);
}
if (httpPrintf(http, "\r\n") < 1)
{
http->status = HTTP_ERROR;
return (-1);
}
if (httpFlushWrite(http) < 0)
return (-1);
httpGetLength2(http);
httpClearFields(http);
if (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);
}
#ifdef HAVE_SSL
# if defined(HAVE_CDSASSL) && defined(HAVE_SECCERTIFICATECOPYDATA)
static int
http_set_credentials(http_t *http)
{
_cups_globals_t *cg = _cupsGlobals();
OSStatus error = 0;
http_tls_credentials_t credentials = NULL;
DEBUG_printf(("7http_set_credentials(%p)", http));
if ((credentials = http->tls_credentials) == NULL)
credentials = cg->tls_credentials;
if (credentials)
{
error = SSLSetCertificate(http->tls, credentials);
DEBUG_printf(("4http_set_credentials: SSLSetCertificate, error=%d",
(int)error));
}
else
DEBUG_puts("4http_set_credentials: No credentials to set.");
return (error);
}
# endif
#endif
static void
http_set_timeout(int fd,
double timeout)
{
#ifdef WIN32
DWORD tv = (DWORD)(timeout * 1000);
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *)&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, &tv, sizeof(tv));
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &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_setup_ssl(http_t *http)
{
int any_root;
char hostname[256],
*hostptr;
# ifdef HAVE_LIBSSL
SSL_CTX *context;
BIO *bio;
const char *message = NULL;
# elif defined(HAVE_GNUTLS)
int status;
gnutls_certificate_client_credentials *credentials;
# elif defined(HAVE_CDSASSL)
_cups_globals_t *cg = _cupsGlobals();
OSStatus error;
const char *message = NULL;
# ifdef HAVE_SECCERTIFICATECOPYDATA
cups_array_t *credentials;
cups_array_t *names;
CFArrayRef dn_array;
CFIndex count;
CFDataRef data;
int i;
http_credential_t *credential;
# endif
# elif defined(HAVE_SSPISSL)
TCHAR username[256];
TCHAR commonName[256];
DWORD dwSize;
# endif
DEBUG_printf(("7http_setup_ssl(http=%p)", http));
if (httpAddrLocalhost(http->hostaddr))
{
any_root = 1;
strlcpy(hostname, "localhost", sizeof(hostname));
}
else
{
any_root = cg->any_root;
strlcpy(hostname, http->hostname, sizeof(hostname));
if ((hostptr = hostname + strlen(hostname) - 1) >= hostname &&
*hostptr == '.')
*hostptr = '\0';
}
# ifdef HAVE_LIBSSL
(void)any_root;
context = SSL_CTX_new(SSLv23_client_method());
SSL_CTX_set_options(context, SSL_OP_NO_SSLv2);
bio = BIO_new(_httpBIOMethods());
BIO_ctrl(bio, BIO_C_SET_FILE_PTR, 0, (char *)http);
http->tls = SSL_new(context);
SSL_set_bio(http->tls, bio, bio);
# ifdef HAVE_SSL_SET_TLSEXT_HOST_NAME
SSL_set_tlsext_host_name(http->tls, hostname);
# endif
if (SSL_connect(http->tls) != 1)
{
unsigned long error;
while ((error = ERR_get_error()) != 0)
{
message = ERR_error_string(error, NULL);
DEBUG_printf(("8http_setup_ssl: %s", message));
}
SSL_CTX_free(context);
SSL_free(http->tls);
http->tls = NULL;
# ifdef WIN32
http->error = WSAGetLastError();
# else
http->error = errno;
# endif
http->status = HTTP_ERROR;
if (!message)
message = _("Unable to establish a secure connection to host.");
_cupsSetError(IPP_PKI_ERROR, message, 1);
return (-1);
}
# elif defined(HAVE_GNUTLS)
(void)any_root;
credentials = (gnutls_certificate_client_credentials *)
malloc(sizeof(gnutls_certificate_client_credentials));
if (credentials == NULL)
{
DEBUG_printf(("8http_setup_ssl: Unable to allocate credentials: %s",
strerror(errno)));
http->error = errno;
http->status = HTTP_ERROR;
_cupsSetHTTPError(HTTP_ERROR);
return (-1);
}
gnutls_certificate_allocate_credentials(credentials);
gnutls_init(&http->tls, GNUTLS_CLIENT);
gnutls_set_default_priority(http->tls);
gnutls_server_name_set(http->tls, GNUTLS_NAME_DNS, hostname,
strlen(hostname));
gnutls_credentials_set(http->tls, GNUTLS_CRD_CERTIFICATE, *credentials);
gnutls_transport_set_ptr(http->tls, (gnutls_transport_ptr)http);
gnutls_transport_set_pull_function(http->tls, _httpReadGNUTLS);
gnutls_transport_set_push_function(http->tls, _httpWriteGNUTLS);
while ((status = gnutls_handshake(http->tls)) != GNUTLS_E_SUCCESS)
{
DEBUG_printf(("8http_setup_ssl: gnutls_handshake returned %d (%s)",
status, gnutls_strerror(status)));
if (gnutls_error_is_fatal(status))
{
http->error = EIO;
http->status = HTTP_ERROR;
_cupsSetError(IPP_PKI_ERROR, gnutls_strerror(status), 0);
gnutls_deinit(http->tls);
gnutls_certificate_free_credentials(*credentials);
free(credentials);
http->tls = NULL;
return (-1);
}
}
http->tls_credentials = credentials;
# elif defined(HAVE_CDSASSL)
if ((error = SSLNewContext(false, &http->tls)))
{
http->error = errno;
http->status = HTTP_ERROR;
_cupsSetHTTPError(HTTP_ERROR);
return (-1);
}
error = SSLSetConnection(http->tls, http);
DEBUG_printf(("4http_setup_ssl: SSLSetConnection, error=%d", (int)error));
if (!error)
{
error = SSLSetIOFuncs(http->tls, _httpReadCDSA, _httpWriteCDSA);
DEBUG_printf(("4http_setup_ssl: SSLSetIOFuncs, error=%d", (int)error));
}
if (!error)
{
error = SSLSetAllowsAnyRoot(http->tls, any_root);
DEBUG_printf(("4http_setup_ssl: SSLSetAllowsAnyRoot(%d), error=%d",
any_root, (int)error));
}
if (!error)
{
error = SSLSetAllowsExpiredCerts(http->tls, cg->expired_certs);
DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredCerts(%d), error=%d",
cg->expired_certs, (int)error));
}
if (!error)
{
error = SSLSetAllowsExpiredRoots(http->tls, cg->expired_root);
DEBUG_printf(("4http_setup_ssl: SSLSetAllowsExpiredRoots(%d), error=%d",
cg->expired_root, (int)error));
}
if (!error)
{
error = SSLSetEnableCertVerify(http->tls, false);
DEBUG_printf(("4http_setup_ssl: SSLSetEnableCertVerify, error=%d",
(int)error));
}
# ifdef HAVE_SECCERTIFICATECOPYDATA
if (!error)
{
if (cg->client_cert_cb)
{
error = SSLSetSessionOption(http->tls,
kSSLSessionOptionBreakOnCertRequested, true);
DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnCertRequested, "
"error=%d", (int)error));
}
else
{
error = http_set_credentials(http);
DEBUG_printf(("4http_setup_ssl: http_set_credentials, error=%d",
(int)error));
}
}
if (!error && cg->server_cert_cb != NULL)
{
error = SSLSetSessionOption(http->tls,
kSSLSessionOptionBreakOnServerAuth, true);
DEBUG_printf(("4http_setup_ssl: kSSLSessionOptionBreakOnServerAuth, "
"error=%d", (int)error));
}
# endif
if (!error)
{
error = SSLSetPeerDomainName(http->tls, hostname, strlen(hostname));
DEBUG_printf(("4http_setup_ssl: SSLSetPeerDomainName, error=%d",
(int)error));
}
if (!error)
{
int done = 0;
while (!error && !done)
{
error = SSLHandshake(http->tls);
DEBUG_printf(("4http_setup_ssl: SSLHandshake returned %d.", (int)error));
switch (error)
{
case noErr :
done = 1;
break;
case errSSLWouldBlock :
error = noErr;
usleep(1000);
break;
# ifdef HAVE_SECCERTIFICATECOPYDATA
case errSSLServerAuthCompleted :
error = 0;
if (cg->server_cert_cb)
{
error = httpCopyCredentials(http, &credentials);
if (!error)
{
error = (cg->server_cert_cb)(http, http->tls, credentials,
cg->server_cert_data);
httpFreeCredentials(credentials);
}
DEBUG_printf(("4http_setup_ssl: Server certificate callback "
"returned %d.", (int)error));
}
break;
case errSSLClientCertRequested :
error = 0;
if (cg->client_cert_cb)
{
names = NULL;
if (!(error = SSLCopyDistinguishedNames(http->tls, &dn_array)) &&
dn_array)
{
if ((names = cupsArrayNew(NULL, NULL)) != NULL)
{
for (i = 0, count = CFArrayGetCount(dn_array); i < count; i++)
{
data = (CFDataRef)CFArrayGetValueAtIndex(dn_array, i);
if ((credential = malloc(sizeof(*credential))) != NULL)
{
credential->datalen = CFDataGetLength(data);
if ((credential->data = malloc(credential->datalen)))
{
memcpy((void *)credential->data, CFDataGetBytePtr(data),
credential->datalen);
cupsArrayAdd(names, credential);
}
else
free(credential);
}
}
}
CFRelease(dn_array);
}
if (!error)
{
error = (cg->client_cert_cb)(http, http->tls, names,
cg->client_cert_data);
DEBUG_printf(("4http_setup_ssl: Client certificate callback "
"returned %d.", (int)error));
}
httpFreeCredentials(names);
}
break;
# endif
case errSSLUnknownRootCert :
message = _("Unable to establish a secure connection to host "
"(untrusted certificate).");
break;
case errSSLNoRootCert :
message = _("Unable to establish a secure connection to host "
"(self-signed certificate).");
break;
case errSSLCertExpired :
message = _("Unable to establish a secure connection to host "
"(expired certificate).");
break;
case errSSLCertNotYetValid :
message = _("Unable to establish a secure connection to host "
"(certificate not yet valid).");
break;
case errSSLHostNameMismatch :
message = _("Unable to establish a secure connection to host "
"(host name mismatch).");
break;
case errSSLXCertChainInvalid :
message = _("Unable to establish a secure connection to host "
"(certificate chain invalid).");
break;
case errSSLConnectionRefused :
message = _("Unable to establish a secure connection to host "
"(peer dropped connection before responding).");
break;
default :
break;
}
}
}
if (error)
{
http->error = error;
http->status = HTTP_ERROR;
errno = ECONNREFUSED;
SSLDisposeContext(http->tls);
http->tls = NULL;
if (!message)
#ifdef HAVE_CSSMERRORSTRING
message = cssmErrorString(error);
#else
message = _("Unable to establish a secure connection to host.");
#endif
_cupsSetError(IPP_PKI_ERROR, message, 1);
return (-1);
}
# elif defined(HAVE_SSPISSL)
http->tls = _sspiAlloc();
if (!http->tls)
{
_cupsSetHTTPError(HTTP_ERROR);
return (-1);
}
http->tls->sock = http->fd;
dwSize = sizeof(username) / sizeof(TCHAR);
GetUserName(username, &dwSize);
_sntprintf_s(commonName, sizeof(commonName) / sizeof(TCHAR),
sizeof(commonName) / sizeof(TCHAR), TEXT("CN=%s"), username);
if (!_sspiGetCredentials(http->tls_credentials, L"ClientContainer",
commonName, FALSE))
{
_sspiFree(http->tls_credentials);
http->tls_credentials = NULL;
http->error = EIO;
http->status = HTTP_ERROR;
_cupsSetError(IPP_PKI_ERROR,
_("Unable to establish a secure connection to host."), 1);
return (-1);
}
_sspiSetAllowsAnyRoot(http->tls_credentials, any_root);
_sspiSetAllowsExpiredCerts(http->tls_credentials, TRUE);
if (!_sspiConnect(http->tls_credentials, hostname))
{
_sspiFree(http->tls_credentials);
http->tls_credentials = NULL;
http->error = EIO;
http->status = HTTP_ERROR;
_cupsSetError(IPP_PKI_ERROR,
_("Unable to establish a secure connection to host."), 1);
return (-1);
}
# endif
return (0);
}
static void
http_shutdown_ssl(http_t *http)
{
# ifdef HAVE_LIBSSL
SSL_CTX *context;
context = SSL_get_SSL_CTX(http->tls);
SSL_shutdown(http->tls);
SSL_CTX_free(context);
SSL_free(http->tls);
# elif defined(HAVE_GNUTLS)
gnutls_certificate_client_credentials *credentials;
credentials = (gnutls_certificate_client_credentials *)(http->tls_credentials);
gnutls_bye(http->tls, GNUTLS_SHUT_RDWR);
gnutls_deinit(http->tls);
gnutls_certificate_free_credentials(*credentials);
free(credentials);
# elif defined(HAVE_CDSASSL)
while (SSLClose(http->tls) == errSSLWouldBlock)
usleep(1000);
SSLDisposeContext(http->tls);
if (http->tls_credentials)
CFRelease(http->tls_credentials);
# elif defined(HAVE_SSPISSL)
_sspiFree(http->tls_credentials);
# endif
http->tls = NULL;
http->tls_credentials = NULL;
}
#endif
#ifdef HAVE_SSL
static int
http_upgrade(http_t *http)
{
int ret;
http_t myhttp;
DEBUG_printf(("7http_upgrade(%p)", http));
httpFlush(http);
memcpy(&myhttp, http, sizeof(myhttp));
http->field_authorization = NULL;
httpClearFields(http);
httpSetField(http, HTTP_FIELD_CONNECTION, "upgrade");
httpSetField(http, HTTP_FIELD_UPGRADE, "TLS/1.2, TLS/1.1, TLS/1.0, SSL/3.0");
if ((ret = httpOptions(http, "*")) == 0)
{
while (httpUpdate(http) == HTTP_CONTINUE);
}
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->field_authorization = myhttp.field_authorization;
http->digest_tries = myhttp.digest_tries;
if (!http->tls)
{
DEBUG_puts("8http_upgrade: Server does not support HTTP upgrade!");
# ifdef WIN32
closesocket(http->fd);
# else
close(http->fd);
# endif
http->fd = -1;
return (-1);
}
else
return (ret);
}
#endif
static int
http_write(http_t *http,
const char *buffer,
int length)
{
int tbytes,
bytes;
DEBUG_printf(("2http_write(http=%p, buffer=%p, length=%d)", http, buffer,
length));
http->error = 0;
tbytes = 0;
while (length > 0)
{
DEBUG_printf(("3http_write: About to write %d bytes.", (int)length));
if (http->timeout_cb)
{
#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, 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 = http_write_ssl(http, buffer, length);
else
#endif
bytes = send(http->fd, buffer, length, 0);
DEBUG_printf(("3http_write: Write of %d bytes returned %d.", (int)length,
(int)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 -= bytes;
}
#ifdef DEBUG
http_debug_hex("http_write", buffer - tbytes, tbytes);
#endif
DEBUG_printf(("3http_write: Returning %d.", tbytes));
return (tbytes);
}
static int
http_write_chunk(http_t *http,
const char *buffer,
int length)
{
char header[255];
int bytes;
DEBUG_printf(("7http_write_chunk(http=%p, buffer=%p, length=%d)",
http, buffer, length));
sprintf(header, "%x\r\n", length);
if (http_write(http, header, (int)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);
}
#ifdef HAVE_SSL
static int
http_write_ssl(http_t *http,
const char *buf,
int len)
{
ssize_t result;
DEBUG_printf(("2http_write_ssl(http=%p, buf=%p, len=%d)", http, buf, len));
# if defined(HAVE_LIBSSL)
result = SSL_write((SSL *)(http->tls), buf, len);
# elif defined(HAVE_GNUTLS)
result = gnutls_record_send(http->tls, buf, len);
if (result < 0 && !errno)
{
switch (result)
{
case GNUTLS_E_INTERRUPTED :
errno = EINTR;
break;
case GNUTLS_E_AGAIN :
errno = EAGAIN;
break;
default :
errno = EPIPE;
break;
}
result = -1;
}
# elif defined(HAVE_CDSASSL)
OSStatus error;
size_t processed;
error = SSLWrite(http->tls, buf, len, &processed);
switch (error)
{
case 0 :
result = (int)processed;
break;
case errSSLWouldBlock :
if (processed)
result = (int)processed;
else
{
result = -1;
errno = EINTR;
}
break;
case errSSLClosedGraceful :
default :
if (processed)
result = (int)processed;
else
{
result = -1;
errno = EPIPE;
}
break;
}
# elif defined(HAVE_SSPISSL)
return _sspiWrite((_sspi_struct_t *)http->tls, (void *)buf, len);
# endif
DEBUG_printf(("3http_write_ssl: Returning %d.", (int)result));
return ((int)result);
}
#endif