#include "http-private.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include "string.h"
#include <fcntl.h>
#include <errno.h>
#ifdef HAVE_INTTYPES_H
# include <inttypes.h>
#endif
#include "http.h"
#include "debug.h"
#ifdef HAVE_DOMAINSOCKETS
# include <sys/un.h>
#endif
#ifndef WIN32
# include <signal.h>
# include <sys/time.h>
# include <sys/resource.h>
#endif
#ifndef FNONBLK
# define FNONBLK O_NONBLOCK
#endif
#ifndef min
# define min(a,b) ((a) < (b) ? (a) : (b))
#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_wait(http_t *http, int msec);
#ifdef HAVE_SSL
static int http_upgrade(http_t *http);
static int http_setup_ssl(http_t *http);
static void http_shutdown_ssl(http_t *http);
static int http_read_ssl(http_t *http, char *buf, int len);
static int http_write_ssl(http_t *http, const char *buf, int len);
# ifdef HAVE_CDSASSL
static OSStatus CDSAReadFunc(SSLConnectionRef connection, void *data, size_t *dataLength);
static OSStatus CDSAWriteFunc(SSLConnectionRef connection, const void *data, size_t *dataLength);
# endif
#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"
};
static const char * const days[7] =
{
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
};
static const char * const months[12] =
{
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
};
void
httpInitialize(void)
{
#ifdef HAVE_LIBSSL
# ifndef WIN32
struct timeval curtime;
# endif
int i;
unsigned char data[1024];
#endif
#ifdef WIN32
WSADATA winsockdata;
static int initialized = 0;
if (!initialized)
WSAStartup(MAKEWORD(1,1), &winsockdata);
#elif defined(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
#ifdef HAVE_GNUTLS
gnutls_global_init();
#endif
#ifdef HAVE_LIBSSL
SSL_load_error_strings();
SSL_library_init();
#ifdef WIN32
#else
gettimeofday(&curtime, NULL);
srand(curtime.tv_sec + curtime.tv_usec);
#endif
for (i = 0; i < sizeof(data); i ++)
data[i] = rand();
RAND_seed(&data, sizeof(data));
#endif
}
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
httpClose(http_t *http)
{
if (!http)
return;
if (http->input_set)
free(http->input_set);
if (http->cookie)
free(http->cookie);
#ifdef HAVE_SSL
if (http->tls)
http_shutdown_ssl(http);
#endif
#ifdef WIN32
closesocket(http->fd);
#else
close(http->fd);
#endif
free(http);
}
http_t *
httpConnect(const char *host,
int port)
{
http_encryption_t encrypt;
if (port == 443)
encrypt = HTTP_ENCRYPT_ALWAYS;
else
encrypt = HTTP_ENCRYPT_IF_REQUESTED;
return (httpConnectEncrypt(host, port, encrypt));
}
http_t *
httpConnectEncrypt(const char *host,
int port,
http_encryption_t encrypt)
{
int i;
http_t *http;
struct hostent *hostaddr;
if (host == NULL)
return (NULL);
httpInitialize();
if ((hostaddr = httpGetHostByName(host)) == NULL)
{
if (strcasecmp(host, "localhost") != 0)
return (NULL);
else if ((hostaddr = httpGetHostByName("127.0.0.1")) == NULL)
return (NULL);
}
if (hostaddr->h_addrtype != AF_INET || hostaddr->h_length != 4)
return (NULL);
http = calloc(sizeof(http_t), 1);
if (http == NULL)
return (NULL);
http->version = HTTP_1_1;
http->blocking = 1;
http->activity = time(NULL);
http->fd = -1;
strlcpy(http->hostname, host, sizeof(http->hostname));
http->hostaddr.sin_family = hostaddr->h_addrtype;
#ifdef WIN32
http->hostaddr.sin_port = htons((u_short)port);
#else
http->hostaddr.sin_port = htons(port);
#endif
if (port == 443)
http->encryption = HTTP_ENCRYPT_ALWAYS;
else
http->encryption = encrypt;
strlcpy(http->hostname, host, sizeof(http->hostname));
for (i = 0; hostaddr->h_addr_list[i]; i ++)
{
memcpy((char *)&(http->hostaddr.sin_addr), hostaddr->h_addr_list[i],
hostaddr->h_length);
if (!httpReconnect(http))
return (http);
}
free(http);
return (NULL);
}
int
httpEncryption(http_t *http,
http_encryption_t e)
{
DEBUG_printf(("httpEncryption(http=%p, e=%d)\n", 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
httpReconnect(http_t *http)
{
int val;
DEBUG_printf(("httpReconnect(http=%p)\n", http));
if (!http)
return (-1);
#ifdef HAVE_SSL
if (http->tls)
http_shutdown_ssl(http);
#endif
if (http->fd >= 0)
#ifdef WIN32
closesocket(http->fd);
#else
close(http->fd);
#endif
http->fd = -1;
#ifdef HAVE_DOMAINSOCKETS
if (http->hostaddr.sin_family == AF_LOCAL ||
(http->hostaddr.sin_family == AF_INET &&
strcasecmp(http->hostname, "localhost") == 0 &&
cups_server_domainsocket[0] != '\0'))
{
struct sockaddr_un saddr;
if ((http->fd = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0)
{
#ifdef WIN32
http->error = WSAGetLastError();
#else
http->error = errno;
#endif
http->status = HTTP_ERROR;
return (-1);
}
#ifdef FD_CLOEXEC
fcntl(http->fd, F_SETFD, FD_CLOEXEC);
#endif
val = 1;
setsockopt(http->fd, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
#ifdef SO_REUSEPORT
val = 1;
setsockopt(http->fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val));
#endif
val = 1;
#ifdef WIN32
setsockopt(http->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
#else
setsockopt(http->fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
#endif // WIN32
saddr.sun_family = AF_LOCAL;
strlcpy(saddr.sun_path, cups_server_domainsocket, sizeof(saddr.sun_path));
if (connect(http->fd, (struct sockaddr *)&saddr, SUN_LEN(&saddr)) < 0)
{
#ifdef WIN32
http->error = WSAGetLastError();
#else
http->error = errno;
#endif
http->status = HTTP_ERROR;
#ifdef WIN32
closesocket(http->fd);
#else
close(http->fd);
#endif
http->fd = -1;
if (errno != ENOENT && errno != ECONNREFUSED)
return (-1);
}
}
#endif
if (http->fd == -1)
{
if ((http->fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
#ifdef WIN32
http->error = WSAGetLastError();
#else
http->error = errno;
#endif
http->status = HTTP_ERROR;
return (-1);
}
#ifdef FD_CLOEXEC
fcntl(http->fd, F_SETFD, FD_CLOEXEC);
#endif
val = 1;
setsockopt(http->fd, SOL_SOCKET, SO_REUSEADDR, (char *)&val, sizeof(val));
#ifdef SO_REUSEPORT
val = 1;
setsockopt(http->fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val));
#endif
val = 1;
#ifdef WIN32
setsockopt(http->fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
#else
setsockopt(http->fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
#endif // WIN32
if (connect(http->fd, (struct sockaddr *)&(http->hostaddr),
sizeof(http->hostaddr)) < 0)
{
#ifdef WIN32
http->error = WSAGetLastError();
#else
http->error = errno;
#endif
http->status = HTTP_ERROR;
#ifdef WIN32
closesocket(http->fd);
#else
close(http->fd);
#endif
http->fd = -1;
return (-1);
}
}
http->error = 0;
http->status = HTTP_CONTINUE;
#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
return (0);
}
char *
httpGetSubField(http_t *http,
http_field_t field,
const char *name,
char *value)
{
const char *fptr;
char temp[HTTP_MAX_VALUE],
*ptr;
DEBUG_printf(("httpGetSubField(http=%p, field=%d, name=\"%s\", value=%p)\n",
http, field, name, value));
if (http == NULL ||
field < HTTP_FIELD_ACCEPT_LANGUAGE ||
field > HTTP_FIELD_WWW_AUTHENTICATE ||
name == NULL || value == NULL)
return (NULL);
for (fptr = http->fields[field]; *fptr;)
{
while (isspace(*fptr & 255))
fptr ++;
if (*fptr == ',')
{
fptr ++;
continue;
}
for (ptr = temp;
*fptr && *fptr != '=' && !isspace(*fptr & 255) && ptr < (temp + sizeof(temp) - 1);
*ptr++ = *fptr++);
*ptr = '\0';
DEBUG_printf(("httpGetSubField: name=\"%s\"\n", temp));
while (isspace(*fptr & 255))
fptr ++;
if (!*fptr)
break;
if (*fptr != '=')
continue;
fptr ++;
while (isspace(*fptr & 255))
fptr ++;
if (*fptr == '\"')
{
for (ptr = value, fptr ++;
*fptr && *fptr != '\"' && ptr < (value + HTTP_MAX_VALUE - 1);
*ptr++ = *fptr++);
*ptr = '\0';
while (*fptr && *fptr != '\"')
fptr ++;
if (*fptr)
fptr ++;
}
else
{
for (ptr = value;
*fptr && !isspace(*fptr & 255) && *fptr != ',' && ptr < (value + HTTP_MAX_VALUE - 1);
*ptr++ = *fptr++);
*ptr = '\0';
while (*fptr && !isspace(*fptr & 255) && *fptr != ',')
fptr ++;
}
DEBUG_printf(("httpGetSubField: value=\"%s\"\n", value));
if (strcmp(name, temp) == 0)
return (value);
}
value[0] = '\0';
return (NULL);
}
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);
}
int
httpDelete(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_DELETE, uri));
}
int
httpGet(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_GET, uri));
}
int
httpHead(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_HEAD, uri));
}
int
httpOptions(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_OPTIONS, uri));
}
int
httpPost(http_t *http,
const char *uri)
{
httpGetLength(http);
return (http_send(http, HTTP_POST, uri));
}
int
httpPut(http_t *http,
const char *uri)
{
httpGetLength(http);
return (http_send(http, HTTP_PUT, uri));
}
int
httpTrace(http_t *http,
const char *uri)
{
return (http_send(http, HTTP_TRACE, uri));
}
void
httpFlush(http_t *http)
{
char buffer[8192];
DEBUG_printf(("httpFlush(http=%p), state=%d\n", http, http->state));
while (httpRead(http, buffer, sizeof(buffer)) > 0);
}
int
httpRead(http_t *http,
char *buffer,
int length)
{
int bytes;
char len[32];
DEBUG_printf(("httpRead(http=%p, buffer=%p, length=%d)\n",
http, buffer, length));
if (http == NULL || buffer == NULL)
return (-1);
http->activity = time(NULL);
if (length <= 0)
return (0);
if (http->data_encoding == HTTP_ENCODE_CHUNKED &&
http->data_remaining <= 0)
{
DEBUG_puts("httpRead: Getting chunk length...");
if (httpGets(len, sizeof(len), http) == NULL)
{
DEBUG_puts("httpRead: Could not get length!");
return (0);
}
http->data_remaining = strtoimax(len, NULL, 16);
http->deprecated_data_remaining = min(INT_MAX, http->data_remaining);
if (http->data_remaining < 0)
{
DEBUG_puts("httpRead: Negative chunk length!");
return (0);
}
}
DEBUG_printf(("httpRead: data_remaining = %" PRIdMAX "\n", (intmax_t)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 > http->data_remaining)
length = (int)http->data_remaining;
if (http->used == 0 && length <= 256)
{
if (!http->blocking && !httpWait(http, 1000))
return (0);
if (http->data_remaining > sizeof(http->buffer))
bytes = sizeof(http->buffer);
else
bytes = http->data_remaining;
#ifdef HAVE_SSL
if (http->tls)
bytes = http_read_ssl(http, http->buffer, bytes);
else
#endif
{
DEBUG_printf(("httpRead: reading %d bytes from socket into buffer...\n",
bytes));
bytes = recv(http->fd, http->buffer, bytes, 0);
DEBUG_printf(("httpRead: read %d bytes from socket into buffer...\n",
bytes));
}
if (bytes > 0)
http->used = bytes;
else if (bytes < 0)
{
#ifdef WIN32
http->error = WSAGetLastError();
return (-1);
#else
if (errno != EINTR)
{
http->error = errno;
return (-1);
}
#endif
}
else
{
http->error = EPIPE;
return (0);
}
}
if (http->used > 0)
{
if (length > http->used)
length = http->used;
bytes = length;
DEBUG_printf(("httpRead: grabbing %d bytes from input buffer...\n", bytes));
memcpy(buffer, http->buffer, length);
http->used -= length;
if (http->used > 0)
memmove(http->buffer, http->buffer + length, http->used);
}
#ifdef HAVE_SSL
else if (http->tls)
{
if (!http->blocking && !httpWait(http, 1000))
return (0);
bytes = http_read_ssl(http, buffer, length);
}
#endif
else
{
if (!http->blocking && !httpWait(http, 1000))
return (0);
DEBUG_printf(("httpRead: reading %d bytes from socket...\n", length));
bytes = recv(http->fd, buffer, length, 0);
DEBUG_printf(("httpRead: read %d bytes from socket...\n", bytes));
}
if (bytes > 0)
{
http->data_remaining -= bytes;
http->deprecated_data_remaining = min(INT_MAX, http->data_remaining);
}
else if (bytes < 0)
{
#ifdef WIN32
http->error = WSAGetLastError();
#else
if (errno == EINTR)
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);
if (http->data_encoding != HTTP_ENCODE_CHUNKED)
{
if (http->state == HTTP_POST_RECV)
http->state ++;
else
http->state = HTTP_WAITING;
}
}
#ifdef DEBUG
{
int i, j, ch;
printf("httpRead: Read %d bytes:\n", bytes);
for (i = 0; i < bytes; i += 16)
{
printf(" ");
for (j = 0; j < 16 && (i + j) < bytes; j ++)
printf(" %02X", buffer[i + j] & 255);
while (j < 16)
{
printf(" ");
j ++;
}
printf(" ");
for (j = 0; j < 16 && (i + j) < bytes; j ++)
{
ch = buffer[i + j] & 255;
if (ch < ' ' || ch == 127)
ch = '.';
putchar(ch);
}
putchar('\n');
}
}
#endif
return (bytes);
}
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;
}
int
httpWait(http_t *http,
int msec)
{
if (http == NULL)
return (0);
if (http->used)
return (1);
return (http_wait(http, msec));
}
int
httpWrite(http_t *http,
const char *buffer,
int length)
{
int tbytes,
bytes;
if (http == NULL || buffer == NULL)
return (-1);
http->activity = time(NULL);
if (http->data_encoding == HTTP_ENCODE_CHUNKED)
{
if (httpPrintf(http, "%x\r\n", length) < 0)
return (-1);
if (length == 0)
{
DEBUG_puts("httpWrite: changing states...");
if (http->state == HTTP_POST_RECV)
http->state ++;
else if (http->state == HTTP_PUT_RECV)
http->state = HTTP_STATUS;
else
http->state = HTTP_WAITING;
if (httpPrintf(http, "\r\n") < 0)
return (-1);
return (0);
}
}
tbytes = 0;
while (length > 0)
{
#ifdef HAVE_SSL
if (http->tls)
bytes = http_write_ssl(http, buffer, length);
else
#endif
bytes = send(http->fd, buffer, length, 0);
if (bytes < 0)
{
#ifdef WIN32
if (WSAGetLastError() != http->error)
{
http->error = WSAGetLastError();
continue;
}
#else
if (errno == EINTR)
continue;
else if (errno != http->error && errno != ECONNRESET)
{
http->error = errno;
continue;
}
#endif
DEBUG_puts("httpWrite: error writing data...\n");
return (-1);
}
buffer += bytes;
tbytes += bytes;
length -= bytes;
if (http->data_encoding == HTTP_ENCODE_LENGTH)
{
http->data_remaining -= bytes;
http->deprecated_data_remaining = min(INT_MAX, http->data_remaining);
}
}
if (http->data_encoding == HTTP_ENCODE_CHUNKED)
if (httpPrintf(http, "\r\n") < 0)
return (-1);
if (http->data_remaining == 0 && http->data_encoding == HTTP_ENCODE_LENGTH)
{
DEBUG_puts("httpWrite: changing states...");
if (http->state == HTTP_POST_RECV)
http->state ++;
else if (http->state == HTTP_PUT_RECV)
http->state = HTTP_STATUS;
else
http->state = HTTP_WAITING;
}
#ifdef DEBUG
{
int i, j, ch;
printf("httpWrite: wrote %d bytes: \n", tbytes);
for (i = 0, buffer -= tbytes; i < tbytes; i += 16)
{
printf(" ");
for (j = 0; j < 16 && (i + j) < tbytes; j ++)
printf(" %02X", buffer[i + j] & 255);
while (j < 16)
{
printf(" ");
j ++;
}
printf(" ");
for (j = 0; j < 16 && (i + j) < tbytes; j ++)
{
ch = buffer[i + j] & 255;
if (ch < ' ' || ch == 127)
ch = '.';
putchar(ch);
}
putchar('\n');
}
}
#endif
return (tbytes);
}
char *
httpGets(char *line,
int length,
http_t *http)
{
char *lineptr,
*bufptr,
*bufend;
int bytes;
DEBUG_printf(("httpGets(line=%p, length=%d, http=%p)\n", line, length, http));
if (http == NULL || line == NULL)
return (NULL);
#ifdef WIN32
WSASetLastError(0);
#else
errno = 0;
#endif
do
{
bufptr = http->buffer;
bufend = http->buffer + http->used;
while (bufptr < bufend)
if (*bufptr == 0x0a)
break;
else
bufptr ++;
if (bufptr >= bufend && http->used < HTTP_MAX_BUFFER)
{
if (!http->blocking && !http_wait(http, 1000))
return (NULL);
#ifdef HAVE_SSL
if (http->tls)
bytes = http_read_ssl(http, bufend, HTTP_MAX_BUFFER - http->used);
else
#endif
bytes = recv(http->fd, bufend, HTTP_MAX_BUFFER - http->used, 0);
DEBUG_printf(("httpGets: read %d bytes...\n", bytes));
if (bytes < 0)
{
#ifdef WIN32
if (WSAGetLastError() != http->error)
{
http->error = WSAGetLastError();
continue;
}
DEBUG_printf(("httpGets: recv() error %d!\n", WSAGetLastError()));
#else
DEBUG_printf(("httpGets: recv() error %d!\n", errno));
if (errno == EINTR)
continue;
else if (errno != http->error)
{
http->error = errno;
continue;
}
#endif
return (NULL);
}
else if (bytes == 0)
{
http->error = EPIPE;
return (NULL);
}
http->used += bytes;
bufend += bytes;
bufptr = bufend;
}
}
while (bufptr >= bufend && http->used < HTTP_MAX_BUFFER);
http->activity = time(NULL);
lineptr = line;
bufptr = http->buffer;
bytes = 0;
length --;
while (bufptr < bufend && bytes < length)
{
bytes ++;
if (*bufptr == 0x0a)
{
bufptr ++;
break;
}
else if (*bufptr == 0x0d)
bufptr ++;
else
*lineptr++ = *bufptr++;
}
if (bytes > 0)
{
*lineptr = '\0';
http->used -= bytes;
if (http->used > 0)
memmove(http->buffer, bufptr, http->used);
DEBUG_printf(("httpGets: Returning \"%s\"\n", line));
return (line);
}
DEBUG_puts("httpGets: No new line available!");
return (NULL);
}
int
httpPrintf(http_t *http,
const char *format,
...)
{
int bytes,
nbytes,
tbytes;
char buf[HTTP_MAX_BUFFER],
*bufptr;
va_list ap;
DEBUG_printf(("httpPrintf(http=%p, format=\"%s\", ...)\n", http, format));
va_start(ap, format);
bytes = vsnprintf(buf, sizeof(buf), format, ap);
va_end(ap);
DEBUG_printf(("httpPrintf: %s", buf));
for (tbytes = 0, bufptr = buf; tbytes < bytes; tbytes += nbytes, bufptr += nbytes)
{
#ifdef HAVE_SSL
if (http->tls)
nbytes = http_write_ssl(http, bufptr, bytes - tbytes);
else
#endif
nbytes = send(http->fd, bufptr, bytes - tbytes, 0);
if (nbytes < 0)
{
nbytes = 0;
#ifdef WIN32
if (WSAGetLastError() != http->error)
{
http->error = WSAGetLastError();
continue;
}
#else
if (errno == EINTR)
continue;
else if (errno != http->error)
{
http->error = errno;
continue;
}
#endif
return (-1);
}
}
return (bytes);
}
const char *
httpGetDateString(time_t t)
{
struct tm *tdate;
static char datetime[256];
tdate = gmtime(&t);
snprintf(datetime, sizeof(datetime), "%s, %02d %s %d %02d:%02d:%02d GMT",
days[tdate->tm_wday], tdate->tm_mday, months[tdate->tm_mon],
tdate->tm_year + 1900, tdate->tm_hour, tdate->tm_min, tdate->tm_sec);
return (datetime);
}
time_t
httpGetDateTime(const char *s)
{
int i;
struct tm tdate;
char mon[16];
int day, year;
int hour, min, sec;
if (sscanf(s, "%*s%d%15s%d%d:%d:%d", &day, mon, &year, &hour, &min, &sec) < 6)
return (0);
for (i = 0; i < 12; i ++)
if (strcasecmp(mon, months[i]) == 0)
break;
if (i >= 12)
return (0);
tdate.tm_mon = i;
tdate.tm_mday = day;
tdate.tm_year = year - 1900;
tdate.tm_hour = hour;
tdate.tm_min = min;
tdate.tm_sec = sec;
tdate.tm_isdst = 0;
return (mktime(&tdate));
}
http_status_t
httpUpdate(http_t *http)
{
char line[1024],
*value;
http_field_t field;
int major, minor,
status;
DEBUG_printf(("httpUpdate(http=%p), state=%d\n", http, http->state));
if (http->state == HTTP_WAITING)
return (HTTP_CONTINUE);
while (httpGets(line, sizeof(line), http) != NULL)
{
DEBUG_printf(("httpUpdate: Got \"%s\"\n", line));
if (line[0] == '\0')
{
if (http->status == HTTP_CONTINUE)
return (http->status);
#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
return (HTTP_ERROR);
}
return (HTTP_CONTINUE);
}
#endif
httpGetLength(http);
switch (http->state)
{
case HTTP_GET :
case HTTP_POST :
case HTTP_POST_RECV :
case HTTP_PUT :
http->state ++;
case HTTP_POST_SEND :
break;
default :
http->state = HTTP_WAITING;
break;
}
return (http->status);
}
else if (strncmp(line, "HTTP/", 5) == 0)
{
if (sscanf(line, "HTTP/%d.%d%d", &major, &minor, &status) != 3)
return (HTTP_ERROR);
http->version = (http_version_t)(major * 100 + minor);
http->status = (http_status_t)status;
}
else if ((value = strchr(line, ':')) != NULL)
{
*value++ = '\0';
while (isspace(*value & 255))
value ++;
if (!strcasecmp(line, "expect"))
{
http->expect = (http_status_t)atoi(value);
}
else if (!strcasecmp(line, "cookie"))
{
httpSetCookie(http, value);
}
else if ((field = http_field(line)) == HTTP_FIELD_UNKNOWN)
{
DEBUG_printf(("httpUpdate: unknown field %s seen!\n", line));
continue;
}
else
httpSetField(http, field, value);
}
else
{
http->status = HTTP_ERROR;
return (HTTP_ERROR);
}
}
if (http->error == EPIPE && http->status > HTTP_CONTINUE)
return (http->status);
if (http->error)
{
DEBUG_printf(("httpUpdate: socket error %d - %s\n", http->error,
strerror(http->error)));
http->status = HTTP_ERROR;
return (HTTP_ERROR);
}
return (HTTP_CONTINUE);
}
char *
httpDecode64(char *out,
const char *in)
{
int pos,
base64;
char *outptr;
for (outptr = out, pos = 0; *in != '\0'; in ++)
{
if (*in >= 'A' && *in <= 'Z')
base64 = *in - 'A';
else if (*in >= 'a' && *in <= 'z')
base64 = *in - 'a' + 26;
else if (*in >= '0' && *in <= '9')
base64 = *in - '0' + 52;
else if (*in == '+')
base64 = 62;
else if (*in == '/')
base64 = 63;
else if (*in == '=')
break;
else
continue;
switch (pos)
{
case 0 :
*outptr = base64 << 2;
pos ++;
break;
case 1 :
*outptr++ |= (base64 >> 4) & 3;
*outptr = (base64 << 4) & 255;
pos ++;
break;
case 2 :
*outptr++ |= (base64 >> 2) & 15;
*outptr = (base64 << 6) & 255;
pos ++;
break;
case 3 :
*outptr++ |= base64;
pos = 0;
break;
}
}
*outptr = '\0';
return (out);
}
char *
httpEncode64(char *out,
const char *in)
{
char *outptr;
static const char base64[] =
{
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789"
"+/"
};
for (outptr = out; *in != '\0'; in ++)
{
*outptr ++ = base64[in[0] >> 2];
*outptr ++ = base64[((in[0] << 4) | (in[1] >> 4)) & 63];
in ++;
if (*in == '\0')
{
*outptr ++ = '=';
*outptr ++ = '=';
break;
}
*outptr ++ = base64[((in[0] << 2) | (in[1] >> 6)) & 63];
in ++;
if (*in == '\0')
{
*outptr ++ = '=';
break;
}
*outptr ++ = base64[in[0] & 63];
}
*outptr = '\0';
return (out);
}
int
httpGetLength(http_t *http)
{
DEBUG_printf(("httpGetLength(http=%p), state=%d\n", http, http->state));
if (strcasecmp(http->fields[HTTP_FIELD_TRANSFER_ENCODING], "chunked") == 0)
{
DEBUG_puts("httpGetLength: chunked request!");
http->data_encoding = HTTP_ENCODE_CHUNKED;
http->data_remaining = 0;
http->deprecated_data_remaining = 0;
}
else
{
http->data_encoding = HTTP_ENCODE_LENGTH;
if (http->fields[HTTP_FIELD_CONTENT_LENGTH][0] == '\0')
http->data_remaining = 2147483647;
else
http->data_remaining = strtoimax(http->fields[HTTP_FIELD_CONTENT_LENGTH], (char **)NULL, 10);
http->deprecated_data_remaining = min(INT_MAX, http->data_remaining);
DEBUG_printf(("httpGetLength: content_length = %" PRIdMAX "\n", (intmax_t)http->data_remaining));
}
return (http->data_remaining);
}
static http_field_t
http_field(const char *name)
{
int i;
for (i = 0; i < HTTP_FIELD_MAX; i ++)
if (strcasecmp(name, http_fields[i]) == 0)
return ((http_field_t)i);
return (HTTP_FIELD_UNKNOWN);
}
static int
http_send(http_t *http,
http_state_t request,
const char *uri)
{
int i;
char *ptr,
buf[1024];
static const char * const codes[] =
{
NULL,
"OPTIONS",
"GET",
NULL,
"HEAD",
"POST",
NULL,
NULL,
"PUT",
NULL,
"DELETE",
"TRACE",
"CLOSE"
};
static const char hex[] = "0123456789ABCDEF";
DEBUG_printf(("http_send(http=%p, request=HTTP_%s, uri=\"%s\")\n",
http, codes[request], uri));
if (http == NULL || uri == NULL)
return (-1);
for (ptr = buf; *uri != '\0' && ptr < (buf + sizeof(buf) - 1); uri ++)
if (*uri <= ' ' || *uri >= 127)
{
if (ptr < (buf + sizeof(buf) - 1))
*ptr ++ = '%';
if (ptr < (buf + sizeof(buf) - 1))
*ptr ++ = hex[(*uri >> 4) & 15];
if (ptr < (buf + sizeof(buf) - 1))
*ptr ++ = hex[*uri & 15];
}
else
*ptr ++ = *uri;
*ptr = '\0';
if (http->status == HTTP_ERROR || http->status >= HTTP_BAD_REQUEST)
httpReconnect(http);
http->state = request;
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(("%s: %s\n", http_fields[i], http->fields[i]));
if (httpPrintf(http, "%s: %s\r\n", http_fields[i], http->fields[i]) < 1)
{
http->status = HTTP_ERROR;
return (-1);
}
}
if (httpPrintf(http, "\r\n") < 1)
{
http->status = HTTP_ERROR;
return (-1);
}
httpClearFields(http);
return (0);
}
static int
http_wait(http_t *http,
int msec)
{
#ifndef WIN32
struct rlimit limit;
#endif
struct timeval timeout;
int nfds;
int set_size;
DEBUG_printf(("http_wait(http=%p, msec=%d)\n", http, msec));
#ifdef HAVE_SSL
if (http->tls)
{
# ifdef HAVE_LIBSSL
if (SSL_pending((SSL *)(http->tls)))
return (1);
# elif defined(HAVE_GNUTLS)
if (gnutls_record_check_pending(((http_tls_t *)(http->tls))->session))
return (1);
# elif defined(HAVE_CDSASSL)
size_t bytes;
if (!SSLGetBufferedReadSize((SSLContextRef)http->tls, &bytes) && bytes > 0)
return;
# endif
}
#endif
if (!http->input_set)
{
#ifdef WIN32
http->input_set = calloc(1, sizeof(fd_set));
#else
getrlimit(RLIMIT_NOFILE, &limit);
set_size = (limit.rlim_cur + 31) / 8 + 4;
if (set_size < sizeof(fd_set))
set_size = sizeof(fd_set);
http->input_set = calloc(1, set_size);
#endif
if (!http->input_set)
return (0);
}
FD_SET(http->fd, http->input_set);
if (msec >= 0)
{
timeout.tv_sec = msec / 1000;
timeout.tv_usec = (msec % 1000) * 1000;
nfds = select(http->fd + 1, http->input_set, NULL, NULL, &timeout);
}
else
nfds = select(http->fd + 1, http->input_set, NULL, NULL, NULL);
FD_CLR(http->fd, http->input_set);
return (nfds > 0);
}
#ifdef HAVE_SSL
static int
http_upgrade(http_t *http)
{
int ret;
http_t myhttp;
DEBUG_printf(("http_upgrade(%p)\n", http));
memcpy(&myhttp, http, sizeof(myhttp));
httpClearFields(&myhttp);
httpSetField(&myhttp, HTTP_FIELD_CONNECTION, "upgrade");
httpSetField(&myhttp, HTTP_FIELD_UPGRADE, "TLS/1.0, SSL/2.0, SSL/3.0");
if ((ret = httpOptions(&myhttp, "*")) == 0)
{
while (httpUpdate(&myhttp) == HTTP_CONTINUE);
}
httpFlush(&myhttp);
http->fd = myhttp.fd;
http->error = myhttp.error;
http->activity = myhttp.activity;
http->status = myhttp.status;
http->version = myhttp.version;
http->keep_alive = myhttp.keep_alive;
http->used = myhttp.used;
if (http->used)
memcpy(http->buffer, myhttp.buffer, http->used);
http->auth_type = myhttp.auth_type;
http->nonce_count = myhttp.nonce_count;
memcpy(http->nonce, myhttp.nonce, sizeof(http->nonce));
http->tls = myhttp.tls;
http->encryption = myhttp.encryption;
if (!http->tls)
{
DEBUG_puts("Server does not support HTTP upgrade!");
# ifdef WIN32
closesocket(http->fd);
# else
close(http->fd);
# endif
http->fd = -1;
return (-1);
}
else
return (ret);
}
static int
http_setup_ssl(http_t *http)
{
# ifdef HAVE_LIBSSL
SSL_CTX *context;
SSL *conn;
# elif defined(HAVE_GNUTLS)
http_tls_t *conn;
gnutls_certificate_client_credentials *credentials;
# elif defined(HAVE_CDSASSL)
SSLContextRef conn;
OSStatus error;
# endif
DEBUG_printf(("http_setup_ssl(http=%p)\n", http));
# ifdef HAVE_LIBSSL
context = SSL_CTX_new(SSLv23_client_method());
conn = SSL_new(context);
SSL_set_fd(conn, http->fd);
if (SSL_connect(conn) != 1)
{
# ifdef DEBUG
unsigned long error;
while ((error = ERR_get_error()) != 0)
printf("http_setup_ssl: %s\n", ERR_error_string(error, NULL));
# endif
SSL_CTX_free(context);
SSL_free(conn);
# ifdef WIN32
http->error = WSAGetLastError();
# else
http->error = errno;
# endif
http->status = HTTP_ERROR;
return (HTTP_ERROR);
}
# elif defined(HAVE_GNUTLS)
conn = (http_tls_t *)malloc(sizeof(http_tls_t));
if (conn == NULL)
{
http->error = errno;
http->status = HTTP_ERROR;
return (-1);
}
credentials = (gnutls_certificate_client_credentials *)
malloc(sizeof(gnutls_certificate_client_credentials));
if (credentials == NULL)
{
free(conn);
http->error = errno;
http->status = HTTP_ERROR;
return (-1);
}
gnutls_certificate_allocate_credentials(credentials);
gnutls_init(&(conn->session), GNUTLS_CLIENT);
gnutls_set_default_priority(conn->session);
gnutls_credentials_set(conn->session, GNUTLS_CRD_CERTIFICATE, *credentials);
gnutls_transport_set_ptr(conn->session, http->fd);
if ((gnutls_handshake(conn->session)) != GNUTLS_E_SUCCESS)
{
http->error = errno;
http->status = HTTP_ERROR;
return (-1);
}
conn->credentials = credentials;
# elif defined(HAVE_CDSASSL)
error = SSLNewContext(false, &conn);
if (!error)
error = SSLSetIOFuncs(conn, CDSAReadFunc, CDSAWriteFunc);
if (!error)
error = SSLSetConnection(conn, (SSLConnectionRef)http->fd);
if (!error)
error = SSLSetAllowsExpiredCerts(conn, true);
if (!error)
error = SSLSetAllowsAnyRoot(conn, true);
if (!error)
error = SSLHandshake(conn);
if (error != 0)
{
http->error = error;
http->status = HTTP_ERROR;
SSLDisposeContext(conn);
close(http->fd);
return (-1);
}
# endif
http->tls = conn;
return (0);
}
static void
http_shutdown_ssl(http_t *http)
{
# ifdef HAVE_LIBSSL
SSL_CTX *context;
SSL *conn;
conn = (SSL *)(http->tls);
context = SSL_get_SSL_CTX(conn);
SSL_shutdown(conn);
SSL_CTX_free(context);
SSL_free(conn);
# elif defined(HAVE_GNUTLS)
http_tls_t *conn;
gnutls_certificate_client_credentials *credentials;
conn = (http_tls_t *)(http->tls);
credentials = (gnutls_certificate_client_credentials *)(conn->credentials);
gnutls_bye(conn->session, GNUTLS_SHUT_RDWR);
gnutls_deinit(conn->session);
gnutls_certificate_free_credentials(*credentials);
free(credentials);
free(conn);
# elif defined(HAVE_CDSASSL)
SSLClose((SSLContextRef)http->tls);
SSLDisposeContext((SSLContextRef)http->tls);
# endif
http->tls = NULL;
}
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)
return (gnutls_record_recv(((http_tls_t *)(http->tls))->session, buf, len));
# elif defined(HAVE_CDSASSL)
OSStatus error;
size_t processed;
error = SSLRead((SSLContextRef)http->tls, buf, len, &processed);
if (error == 0)
return (processed);
else
{
http->error = error;
return (-1);
}
# endif
}
static int
http_write_ssl(http_t *http,
const char *buf,
int len)
{
# if defined(HAVE_LIBSSL)
return (SSL_write((SSL *)(http->tls), buf, len));
# elif defined(HAVE_GNUTLS)
return (gnutls_record_send(((http_tls_t *)(http->tls))->session, buf, len));
# elif defined(HAVE_CDSASSL)
OSStatus error;
size_t processed;
error = SSLWrite((SSLContextRef)http->tls, buf, len, &processed);
if (error == 0)
return (processed);
else
{
http->error = error;
return (-1);
}
# endif
}
# if defined(HAVE_CDSASSL)
static OSStatus
CDSAReadFunc(SSLConnectionRef connection,
void *data,
size_t *dataLength)
{
ssize_t bytes;
bytes = recv((int)connection, data, *dataLength, 0);
if (bytes >= 0)
{
*dataLength = bytes;
return (0);
}
else
return (-1);
}
static OSStatus
CDSAWriteFunc(SSLConnectionRef connection,
const void *data,
size_t *dataLength)
{
ssize_t bytes;
bytes = write((int)connection, data, *dataLength);
if (bytes >= 0)
{
*dataLength = bytes;
return (0);
}
else
return (-1);
}
# endif
#endif