Newer
Older
nc.sock = ls->sock;
nc.callback = ls->callback;
nc.user_data = ls->user_data;
nc.proto_data = ls->proto_data;
nc.mgr = ls->mgr;
DBG(("%p %d bytes received", ls, n));
ns_call(&nc, NS_RECV, &n);
}
static void ns_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
if (sock != INVALID_SOCKET) {
FD_SET(sock, set);
if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
*max_fd = sock;
}
time_t ns_mgr_poll(struct ns_mgr *mgr, int milli) {
struct ns_connection *conn, *tmp_conn;
struct timeval tv;
fd_set read_set, write_set;
sock_t max_fd = INVALID_SOCKET;
time_t current_time = time(NULL);
FD_ZERO(&read_set);
FD_ZERO(&write_set);
ns_add_to_set(mgr->ctl[1], &read_set, &max_fd);
for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
if (!(conn->flags & (NSF_LISTENING | NSF_CONNECTING))) {
ns_call(conn, NS_POLL, ¤t_time);
}
if (conn->flags & NSF_CLOSE_IMMEDIATELY) {
ns_close_conn(conn);
} else {
if (!(conn->flags & NSF_WANT_WRITE)) {
//DBG(("%p read_set", conn));
ns_add_to_set(conn->sock, &read_set, &max_fd);
}
if (((conn->flags & NSF_CONNECTING) && !(conn->flags & NSF_WANT_READ)) ||
(conn->send_iobuf.len > 0 && !(conn->flags & NSF_CONNECTING) &&
!(conn->flags & NSF_BUFFER_BUT_DONT_SEND))) {
//DBG(("%p write_set", conn));
ns_add_to_set(conn->sock, &write_set, &max_fd);
}
}
}
tv.tv_sec = milli / 1000;
tv.tv_usec = (milli % 1000) * 1000;
if (select((int) max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) {
// select() might have been waiting for a long time, reset current_time
// now to prevent last_io_time being set to the past.
current_time = time(NULL);
if (mgr->ctl[1] != INVALID_SOCKET &&
FD_ISSET(mgr->ctl[1], &read_set)) {
int len = (int) recv(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
send(mgr->ctl[1], ctl_msg.message, 1, 0);
if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
struct ns_connection *c;
for (c = ns_next(mgr, NULL); c != NULL; c = ns_next(mgr, c)) {
ctl_msg.callback(c, NS_POLL, ctl_msg.message);
}
for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
tmp_conn = conn->next;
if (FD_ISSET(conn->sock, &read_set)) {
if (conn->flags & NSF_LISTENING) {
if (conn->flags & NSF_UDP) {
ns_handle_udp(conn);
} else {
// We're not looping here, and accepting just one connection at
// a time. The reason is that eCos does not respect non-blocking
// flag on a listening socket and hangs in a loop.
accept_conn(conn);
}
} else {
conn->last_io_time = current_time;
ns_read_from_socket(conn);
}
if (FD_ISSET(conn->sock, &write_set)) {
if (conn->flags & NSF_CONNECTING) {
ns_read_from_socket(conn);
} else if (!(conn->flags & NSF_BUFFER_BUT_DONT_SEND)) {
conn->last_io_time = current_time;
ns_write_to_socket(conn);
for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
if ((conn->flags & NSF_CLOSE_IMMEDIATELY) ||
(conn->send_iobuf.len == 0 &&
(conn->flags & NSF_FINISHED_SENDING_DATA))) {
ns_close_conn(conn);
return current_time;
struct ns_connection *ns_connect(struct ns_mgr *mgr, const char *address,
ns_callback_t callback, void *user_data) {
struct ns_connection *nc = NULL;
union socket_address sa;
char cert[100], ca_cert[100];
int rc, use_ssl, proto;
ns_parse_address(address, &sa, &proto, &use_ssl, cert, ca_cert);
if ((sock = socket(AF_INET, proto, 0)) == INVALID_SOCKET) {
ns_set_non_blocking_mode(sock);
rc = (proto == SOCK_DGRAM) ? 0 : connect(sock, &sa.sa, sizeof(sa.sin));
if (rc != 0 && ns_is_error(rc)) {
} else if ((nc = ns_add_sock(mgr, sock, callback, user_data)) == NULL) {
nc->sa = sa; // Important, cause UDP conns will use sendto()
nc->flags = (proto == SOCK_DGRAM) ? NSF_UDP : NSF_CONNECTING;
if (use_ssl) {
if ((nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL ||
ns_use_cert(nc->ssl_ctx, cert) != 0 ||
ns_use_ca_cert(nc->ssl_ctx, ca_cert) != 0 ||
(nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
ns_close_conn(nc);
return NULL;
} else {
SSL_set_fd(nc->ssl, sock);
}
struct ns_connection *ns_add_sock(struct ns_mgr *s, sock_t sock,
ns_callback_t callback, void *user_data) {
struct ns_connection *conn;
if ((conn = (struct ns_connection *) NS_MALLOC(sizeof(*conn))) != NULL) {
memset(conn, 0, sizeof(*conn));
ns_set_non_blocking_mode(sock);
ns_set_close_on_exec(sock);
conn->user_data = user_data;
conn->callback = callback;
conn->mgr = s;
ns_add_conn(s, conn);
DBG(("%p %d", conn, sock));
}
return conn;
}
struct ns_connection *ns_next(struct ns_mgr *s, struct ns_connection *conn) {
return conn == NULL ? s->active_connections : conn->next;
}
void ns_broadcast(struct ns_mgr *mgr, ns_callback_t cb,void *data, size_t len) {
if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
len < sizeof(ctl_msg.message)) {
ctl_msg.callback = cb;
memcpy(ctl_msg.message, data, len);
send(mgr->ctl[0], (char *) &ctl_msg,
recv(mgr->ctl[0], (char *) &len, 1, 0);
void ns_mgr_init(struct ns_mgr *s, void *user_data) {
s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
s->user_data = user_data;
#ifdef _WIN32
{ WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
#else
// Ignore SIGPIPE signal, so if client cancels the request, it
// won't kill the whole process.
signal(SIGPIPE, SIG_IGN);
#endif
ns_socketpair2(s->ctl, SOCK_DGRAM);
} while (s->ctl[0] == INVALID_SOCKET);
#endif
{static int init_done; if (!init_done) { SSL_library_init(); init_done++; }}
void ns_mgr_free(struct ns_mgr *s) {
struct ns_connection *conn, *tmp_conn;
DBG(("%p", s));
if (s == NULL) return;
// Do one last poll, see https://github.com/cesanta/mongoose/issues/286
ns_mgr_poll(s, 0);
if (s->ctl[0] != INVALID_SOCKET) closesocket(s->ctl[0]);
if (s->ctl[1] != INVALID_SOCKET) closesocket(s->ctl[1]);
s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
for (conn = s->active_connections; conn != NULL; conn = tmp_conn) {
tmp_conn = conn->next;
ns_close_conn(conn);
#endif // NOEMBED_NET_SKELETON
#ifdef _WIN32 //////////////// Windows specific defines and includes
#include <io.h> // For _lseeki64
#include <direct.h> // For _mkdir
#ifndef S_ISDIR
#define S_ISDIR(x) ((x) & _S_IFDIR)
#endif
#ifdef stat
#undef stat
#endif
#ifdef lseek
#undef lseek
#endif
#ifdef popen
#undef popen
#endif
#ifdef pclose
#undef pclose
#endif
#define stat(x, y) mg_stat((x), (y))
#define fopen(x, y) mg_fopen((x), (y))
#define open(x, y, z) mg_open((x), (y), (z))
Sergey Lyubka
committed
#define close(x) _close(x)
#define fileno(x) _fileno(x)
#define lseek(x, y, z) _lseeki64((x), (y), (z))
#define read(x, y, z) _read((x), (y), (z))
#define write(x, y, z) _write((x), (y), (z))
#define popen(x, y) _popen((x), (y))
#define pclose(x) _pclose(x)
#define rmdir(x) _rmdir(x)
#define strdup(x) _strdup(x)
#ifndef __func__
#define STRX(x) #x
#define STR(x) STRX(x)
#define __func__ __FILE__ ":" STR(__LINE__)
m.milanovic@levi9.com
committed
/* MINGW has adopted the MSVC formatting for 64-bit ints as of gcc 4.4 till 4.8*/
#if (defined(__MINGW32__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4 && __GNUC_MINOR__ < 8))) || defined(_MSC_VER)
#define INT64_FMT "I64d"
#else
#define INT64_FMT "lld"
#endif
#define flockfile(x) ((void) (x))
#define funlockfile(x) ((void) (x))
typedef HANDLE process_id_t;
#else ////////////// UNIX specific defines and includes
#if !defined(MONGOOSE_NO_FILESYSTEM) &&\
(!defined(MONGOOSE_NO_DAV) || !defined(MONGOOSE_NO_DIRECTORY_LISTING))
#endif
#if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_DL)
#define INT64_FMT PRId64
typedef struct stat file_stat_t;
typedef pid_t process_id_t;
#endif //////// End of platform-specific defines and includes
#define MAX_REQUEST_SIZE 16384
#define IOBUF_SIZE 8192
#define MAX_PATH_SIZE 8192
#define DEFAULT_CGI_PATTERN "**.cgi$|**.pl$|**.php$"
#define CGI_ENVIRONMENT_SIZE 8192
#define ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
#define PASSWORDS_FILE_NAME ".htpasswd"
#ifndef MONGOOSE_USE_WEBSOCKET_PING_INTERVAL
#define MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 5
#endif
// Extra HTTP headers to send in every static file reply
#if !defined(MONGOOSE_USE_EXTRA_HTTP_HEADERS)
#define MONGOOSE_USE_EXTRA_HTTP_HEADERS ""
#ifndef MONGOOSE_POST_SIZE_LIMIT
#define MONGOOSE_POST_SIZE_LIMIT 0
#define MONGOOSE_IDLE_TIMEOUT_SECONDS 300
#if defined(NS_DISABLE_SOCKETPAIR) && !defined(MONGOOSE_NO_CGI)
#ifdef MONGOOSE_NO_FILESYSTEM
#define MONGOOSE_NO_AUTH
#define MONGOOSE_NO_DAV
#define MONGOOSE_NO_DIRECTORY_LISTING
#define MONGOOSE_NO_LOGGING
#define MONGOOSE_NO_SSI
#define MONGOOSE_NO_DL
// For directory listing and WevDAV support
struct dir_entry {
struct connection *conn;
char *file_name;
file_stat_t st;
};
// NOTE(lsm): this enum shoulds be in sync with the config_options.
enum {
#ifndef MONGOOSE_NO_FILESYSTEM
ACCESS_LOG_FILE,
#ifndef MONGOOSE_NO_AUTH
AUTH_DOMAIN,
#endif
#ifndef MONGOOSE_NO_CGI
CGI_INTERPRETER,
CGI_PATTERN,
#endif
DAV_AUTH_FILE,
DOCUMENT_ROOT,
#ifndef MONGOOSE_NO_DIRECTORY_LISTING
ENABLE_DIRECTORY_LISTING,
#endif
#if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
#ifndef MONGOOSE_NO_FILESYSTEM
#ifndef _WIN32
RUN_AS_USER,
#endif
#endif
URL_REWRITES,
NUM_OPTIONS
static const char *static_config_options[] = {
"access_control_list", NULL,
#ifndef MONGOOSE_NO_FILESYSTEM
#ifndef MONGOOSE_NO_AUTH
#endif
#ifndef MONGOOSE_NO_CGI
"cgi_pattern", DEFAULT_CGI_PATTERN,
#endif
"dav_auth_file", NULL,
"document_root", NULL,
#ifndef MONGOOSE_NO_DIRECTORY_LISTING
"enable_proxy", NULL,
#if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
#ifndef MONGOOSE_NO_FILESYSTEM
"index_files","index.html,index.htm,index.shtml,index.cgi,index.php",
#endif
"listening_port", NULL,
#ifndef _WIN32
"run_as_user", NULL,
#endif
#ifndef MONGOOSE_NO_SSI
"ssi_pattern", "**.shtml$|**.shtm$",
#endif
"url_rewrites", NULL,
NULL
};
struct ns_mgr ns_mgr;
union socket_address lsa; // Listening socket address
mg_handler_t event_handler;
char *config_options[NUM_OPTIONS];
// Local endpoint representation
union endpoint {
int fd; // Opened regular local file
struct ns_connection *nc; // CGI or proxy->target connection
enum endpoint_type {
EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT, EP_PROXY
};
#define MG_HEADERS_SENT NSF_USER_1
#define MG_LONG_RUNNING NSF_USER_2
#define MG_CGI_CONN NSF_USER_3
struct ns_connection *ns_conn; // NOTE(lsm): main.c depends on this order
struct mg_server *server;
union endpoint endpoint;
enum endpoint_type endpoint_type;
char *path_info;
char *request;
int64_t num_bytes_recv; // Total number of bytes received
int64_t cl; // Reply content length, for Range support
int request_len; // Request length, including last \r\n after last header
};
#define MG_CONN_2_CONN(c) ((struct connection *) ((char *) (c) - \
offsetof(struct connection, mg_conn)))
static void open_local_endpoint(struct connection *conn, int skip_user);
static void close_local_endpoint(struct connection *conn);
static void mg_ev_handler(struct ns_connection *nc, int ev, void *p);
static const struct {
const char *extension;
size_t ext_len;
const char *mime_type;
} static_builtin_mime_types[] = {
{".html", 5, "text/html"},
{".htm", 4, "text/html"},
{".shtm", 5, "text/html"},
{".shtml", 6, "text/html"},
{".css", 4, "text/css"},
{".js", 3, "application/javascript"},
{".ico", 4, "image/x-icon"},
{".gif", 4, "image/gif"},
{".jpg", 4, "image/jpeg"},
{".jpeg", 5, "image/jpeg"},
{".png", 4, "image/png"},
{".svg", 4, "image/svg+xml"},
{".txt", 4, "text/plain"},
{".torrent", 8, "application/x-bittorrent"},
{".wav", 4, "audio/x-wav"},
{".mp3", 4, "audio/x-mp3"},
{".mid", 4, "audio/mid"},
{".m3u", 4, "audio/x-mpegurl"},
{".ogg", 4, "application/ogg"},
{".ram", 4, "audio/x-pn-realaudio"},
{".xml", 4, "text/xml"},
{".xslt", 5, "application/xml"},
{".xsl", 4, "application/xml"},
{".ra", 3, "audio/x-pn-realaudio"},
{".doc", 4, "application/msword"},
{".exe", 4, "application/octet-stream"},
{".zip", 4, "application/x-zip-compressed"},
{".xls", 4, "application/excel"},
{".tgz", 4, "application/x-tar-gz"},
{".tar", 4, "application/x-tar"},
{".gz", 3, "application/x-gunzip"},
{".arj", 4, "application/x-arj-compressed"},
{".rar", 4, "application/x-rar-compressed"},
{".rtf", 4, "application/rtf"},
{".pdf", 4, "application/pdf"},
{".swf", 4, "application/x-shockwave-flash"},
{".mpg", 4, "video/mpeg"},
{".webm", 5, "video/webm"},
{".mpeg", 5, "video/mpeg"},
{".mov", 4, "video/quicktime"},
{".mp4", 4, "video/mp4"},
{".m4v", 4, "video/x-m4v"},
{".asf", 4, "video/x-ms-asf"},
{".avi", 4, "video/x-msvideo"},
{".bmp", 4, "image/bmp"},
{".ttf", 4, "application/x-font-ttf"},
{NULL, 0, NULL}
};
#ifndef MONGOOSE_NO_THREADS
void *mg_start_thread(void *(*f)(void *), void *p) {
#endif // MONGOOSE_NO_THREADS
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
#ifdef _WIN32
static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
int offset) {
HANDLE fh = (HANDLE) _get_osfhandle(fd);
HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
CloseHandle(mh);
return p;
}
#define munmap(x, y) UnmapViewOfFile(x)
#define MAP_FAILED NULL
#define MAP_PRIVATE 0
#define PROT_READ 0
#else
#include <sys/mman.h>
#endif
void *mg_mmap(FILE *fp, size_t size) {
void *p = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fileno(fp), 0);
return p == MAP_FAILED ? NULL : p;
}
void mg_munmap(void *p, size_t size) {
munmap(p, size);
}
#if defined(_WIN32) && !defined(MONGOOSE_NO_FILESYSTEM)
// Encode 'path' which is assumed UTF-8 string, into UNICODE string.
// wbuf and wbuf_len is a target buffer and its length.
static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
strncpy(buf, path, sizeof(buf));
buf[sizeof(buf) - 1] = '\0';
// Trim trailing slashes. Leave backslash for paths like "X:\"
while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
// Convert to Unicode and back. If doubly-converted string does not
// match the original, something is fishy, reject.
memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
NULL, NULL);
if (strcmp(buf, buf2) != 0) {
wbuf[0] = L'\0';
}
}
static int mg_stat(const char *path, file_stat_t *st) {
wchar_t wpath[MAX_PATH_SIZE];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
return _wstati64(wpath, st);
}
static FILE *mg_fopen(const char *path, const char *mode) {
wchar_t wpath[MAX_PATH_SIZE], wmode[10];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
to_wchar(mode, wmode, ARRAY_SIZE(wmode));
return _wfopen(wpath, wmode);
}
static int mg_open(const char *path, int flag, int mode) {
wchar_t wpath[MAX_PATH_SIZE];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
// A helper function for traversing a comma separated list of values.
// It returns a list pointer shifted to the next value, or NULL if the end
// of the list found.
// Value is stored in val vector. If value has form "x=y", then eq_val
// vector is initialized to point to the "y" part, and val vector length
// is adjusted to point only to "x".
static const char *next_option(const char *list, struct vec *val,
struct vec *eq_val) {
if (list == NULL || *list == '\0') {
// End of the list
list = NULL;
} else {
val->ptr = list;
if ((list = strchr(val->ptr, ',')) != NULL) {
// Comma found. Store length and shift the list ptr
val->len = list - val->ptr;
list++;
} else {
// This value is the last one
list = val->ptr + strlen(val->ptr);
val->len = list - val->ptr;
}
if (eq_val != NULL) {
// Value has form "x=y", adjust pointers and lengths
// so that val points to "x", and eq_val points to "y".
eq_val->len = 0;
eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
if (eq_val->ptr != NULL) {
eq_val->ptr++; // Skip over '=' character
eq_val->len = val->ptr + val->len - eq_val->ptr;
val->len = (eq_val->ptr - val->ptr) - 1;
}
}
}
return list;
}
// Like snprintf(), but never returns negative value, or a value
// that is larger than a supplied buffer.
static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) {
int n;
n = vsnprintf(buf, buflen, fmt, ap);
if (n < 0) {
n = 0;
} else if (n >= (int) buflen) {
n = (int) buflen - 1;
}
buf[n] = '\0';
return n;
}
static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) {
va_list ap;
int n;
va_start(ap, fmt);
n = mg_vsnprintf(buf, buflen, fmt, ap);
va_end(ap);
return n;
}
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
// Check whether full request is buffered. Return:
// -1 if request is malformed
// 0 if request is not yet fully buffered
// >0 actual request length, including last \r\n\r\n
static int get_request_len(const char *s, int buf_len) {
const unsigned char *buf = (unsigned char *) s;
int i;
for (i = 0; i < buf_len; i++) {
// Control characters are not allowed but >=128 are.
// Abort scan as soon as one malformed character is found.
if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
return -1;
} else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
return i + 2;
} else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
buf[i + 2] == '\n') {
return i + 3;
}
}
return 0;
}
// Skip the characters until one of the delimiters characters found.
// 0-terminate resulting word. Skip the rest of the delimiters if any.
// Advance pointer to buffer to the next word. Return found 0-terminated word.
static char *skip(char **buf, const char *delimiters) {
char *p, *begin_word, *end_word, *end_delimiters;
begin_word = *buf;
end_word = begin_word + strcspn(begin_word, delimiters);
end_delimiters = end_word + strspn(end_word, delimiters);
for (p = end_word; p < end_delimiters; p++) {
*p = '\0';
}
*buf = end_delimiters;
return begin_word;
}
// Parse HTTP headers from the given buffer, advance buffer to the point
// where parsing stopped.
static void parse_http_headers(char **buf, struct mg_connection *ri) {
size_t i;
for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) {
ri->http_headers[i].name = skip(buf, ": ");
ri->http_headers[i].value = skip(buf, "\r\n");
if (ri->http_headers[i].name[0] == '\0')
break;
ri->num_headers = i + 1;
}
}
static const char *status_code_to_str(int status_code) {
switch (status_code) {
case 100: return "Continue";
case 101: return "Switching Protocols";
case 102: return "Processing";
case 200: return "OK";
case 201: return "Created";
case 202: return "Accepted";
case 203: return "Non-Authoritative Information";
case 205: return "Reset Content";
case 206: return "Partial Content";
case 207: return "Multi-Status";
case 208: return "Already Reported";
case 226: return "IM Used";
case 301: return "Moved Permanently";
case 302: return "Found";
case 305: return "Use Proxy";
case 306: return "Switch Proxy";
case 307: return "Temporary Redirect";
case 308: return "Permanent Redirect";
case 401: return "Unauthorized";
case 402: return "Payment Required";
case 403: return "Forbidden";
case 404: return "Not Found";
case 405: return "Method Not Allowed";
case 406: return "Not Acceptable";
case 407: return "Proxy Authentication Required";
case 408: return "Request Timeout";
case 411: return "Length Required";
case 412: return "Precondition Failed";
case 413: return "Payload Too Large";
case 414: return "URI Too Long";
case 415: return "Unsupported Media Type";
case 416: return "Requested Range Not Satisfiable";
case 417: return "Expectation Failed";
case 418: return "I\'m a teapot";
case 422: return "Unprocessable Entity";
case 424: return "Failed Dependency";
case 426: return "Upgrade Required";
case 428: return "Precondition Required";
case 429: return "Too Many Requests";
case 431: return "Request Header Fields Too Large";
case 451: return "Unavailable For Legal Reasons";
case 501: return "Not Implemented";
case 502: return "Bad Gateway";
case 503: return "Service Unavailable";
case 504: return "Gateway Timeout";
case 505: return "HTTP Version Not Supported";
case 506: return "Variant Also Negotiates";
case 507: return "Insufficient Storage";
case 508: return "Loop Detected";
case 510: return "Not Extended";
case 511: return "Network Authentication Required";
default: return "Server Error";
}
}
static int call_user(struct connection *conn, enum mg_event ev) {
return conn != NULL && conn->server != NULL &&
conn->server->event_handler != NULL ?
conn->server->event_handler(&conn->mg_conn, ev) : MG_FALSE;
}
static void send_http_error(struct connection *conn, int code,
const char *fmt, ...) {
const char *message = status_code_to_str(code);
const char *rewrites = conn->server->config_options[URL_REWRITES];
struct vec a, b;
int body_len, headers_len, match_code;
conn->mg_conn.status_code = code;
// Invoke error handler if it is set
if (call_user(conn, MG_HTTP_ERROR) == MG_TRUE) {
close_local_endpoint(conn);
return;
}
// Handle error code rewrites
while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
if ((match_code = atoi(a.ptr)) > 0 && match_code == code) {
struct mg_connection *c = &conn->mg_conn;
c->status_code = 302;
mg_printf(c, "HTTP/1.1 %d Moved\r\n"
"Location: %.*s?code=%d&orig_uri=%s&query_string=%s\r\n\r\n",
c->status_code, b.len, b.ptr, code, c->uri,
c->query_string == NULL ? "" : c->query_string);
close_local_endpoint(conn);
return;
}
}
body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message);
if (fmt != NULL) {
va_start(ap, fmt);
body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap);
if ((code >= 300 && code <= 399) || code == 204) {
// 3xx errors do not have body
body_len = 0;
}
headers_len = mg_snprintf(headers, sizeof(headers),
"HTTP/1.1 %d %s\r\nContent-Length: %d\r\n"
"Content-Type: text/plain\r\n\r\n",
code, message, body_len);
ns_send(conn->ns_conn, headers, headers_len);
ns_send(conn->ns_conn, body, body_len);
close_local_endpoint(conn); // This will write to the log file
}
static void write_chunk(struct connection *conn, const char *buf, int len) {
char chunk_size[50];
int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len);
ns_send(conn->ns_conn, chunk_size, n);
ns_send(conn->ns_conn, buf, len);
ns_send(conn->ns_conn, "\r\n", 2);
size_t mg_printf(struct mg_connection *conn, const char *fmt, ...) {
ns_vprintf(c->ns_conn, fmt, ap);
return c->ns_conn->send_iobuf.len;
static void ns_forward(struct ns_connection *from, struct ns_connection *to) {
DBG(("%p -> %p %lu bytes", from, to, (unsigned long)from->recv_iobuf.len));
ns_send(to, from->recv_iobuf.buf, from->recv_iobuf.len);
iobuf_remove(&from->recv_iobuf, from->recv_iobuf.len);
struct threadparam {
sock_t s;
HANDLE hPipe;
};
static int wait_until_ready(sock_t sock, int for_read) {
fd_set set;
FD_ZERO(&set);
FD_SET(sock, &set);
select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0);
return 1;
}
static void *push_to_stdin(void *arg) {
struct threadparam *tp = (struct threadparam *)arg;
int n, sent, stop = 0;
DWORD k;
char buf[IOBUF_SIZE];
while (!stop && wait_until_ready(tp->s, 1) &&
(n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
for (sent = 0; !stop && sent < n; sent += k) {
if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
}
}
DBG(("%s", "FORWARED EVERYTHING TO CGI"));
CloseHandle(tp->hPipe);
_endthread();
return NULL;
}
static void *pull_from_stdout(void *arg) {
struct threadparam *tp = (struct threadparam *)arg;
DWORD n, sent;
char buf[IOBUF_SIZE];
while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
for (sent = 0; !stop && sent < n; sent += k) {
if (wait_until_ready(tp->s, 0) &&
(k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
}
}
DBG(("%s", "EOF FROM CGI"));
CloseHandle(tp->hPipe);
shutdown(tp->s, 2); // Without this, IO thread may get truncated data
closesocket(tp->s);
static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
void *(*func)(void *)) {
struct threadparam *tp = (struct threadparam *)NS_MALLOC(sizeof(*tp));
if (tp != NULL) {
tp->s = sock;
tp->hPipe = hPipe;
mg_start_thread(func, tp);
}
}
static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
}
static process_id_t start_process(char *interp, const char *cmd,
const char *env, const char *envp[],
const char *dir, sock_t sock) {
STARTUPINFOW si;
PROCESS_INFORMATION pi;
wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
cmdline[MAX_PATH_SIZE], *p;
DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
CreatePipe(&a[0], &a[1], NULL, 0);
CreatePipe(&b[0], &b[1], NULL, 0);
DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
buf[0] = buf[1] = '\0';
fgets(buf, sizeof(buf), fp);
buf[sizeof(buf) - 1] = '\0';
if (buf[0] == '#' && buf[1] == '!') {
interp = buf + 2;
for (p = interp + strlen(interp) - 1;
isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
abs_path(interp, buf4, ARRAY_SIZE(buf4));