Skip to content
8857 lines (7750 sloc) 258 KB
#include "mongoose.h"
#ifdef NS_MODULE_LINES
#line 1 "./src/internal.h"
/**/
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#ifndef MG_INTERNAL_HEADER_INCLUDED
#define MG_INTERNAL_HEADER_INCLUDED
#ifndef MG_MALLOC
#define MG_MALLOC malloc
#endif
#ifndef MG_CALLOC
#define MG_CALLOC calloc
#endif
#ifndef MG_REALLOC
#define MG_REALLOC realloc
#endif
#ifndef MG_FREE
#define MG_FREE free
#endif
#ifndef MBUF_REALLOC
#define MBUF_REALLOC MG_REALLOC
#endif
#ifndef MBUF_FREE
#define MBUF_FREE MG_FREE
#endif
#define MG_SET_PTRPTR(_ptr, _v) \
do { \
if (_ptr) *(_ptr) = _v; \
} while (0)
#ifndef MG_INTERNAL
#define MG_INTERNAL static
#endif
#if !defined(MG_MGR_EV_MGR)
/*
* Switches between different methods of handling sockets. Supported values:
* 0 - select()
* 1 - epoll() (Linux only)
*/
#define MG_MGR_EV_MGR 0 /* select() */
#endif
#ifdef PICOTCP
#define NO_LIBC
#define MG_DISABLE_FILESYSTEM
#define MG_DISABLE_POPEN
#define MG_DISABLE_CGI
#define MG_DISABLE_DIRECTORY_LISTING
#define MG_DISABLE_SOCKETPAIR
#define MG_DISABLE_PFS
#endif
/* Amalgamated: #include "mongoose/src/net.h" */
/* Amalgamated: #include "mongoose/src/http.h" */
#define MG_CTL_MSG_MESSAGE_SIZE 8192
/* internals that need to be accessible in unit tests */
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
int proto,
union socket_address *sa);
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
int *proto, char *host, size_t host_len);
MG_INTERNAL void mg_call(struct mg_connection *nc,
mg_event_handler_t ev_handler, int ev, void *ev_data);
MG_INTERNAL void mg_forward(struct mg_connection *from,
struct mg_connection *to);
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max);
MG_INTERNAL struct mg_connection *mg_create_connection(
struct mg_mgr *mgr, mg_event_handler_t callback,
struct mg_add_sock_opts opts);
#ifndef MG_DISABLE_FILESYSTEM
MG_INTERNAL int find_index_file(char *path, size_t path_len, const char *list,
cs_stat_t *stp);
#endif
#ifdef _WIN32
void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
#endif
/*
* Reassemble the content of the buffer (buf, blen) which should be
* in the HTTP chunked encoding, by collapsing data chunks to the
* beginning of the buffer.
*
* If chunks get reassembled, modify hm->body to point to the reassembled
* body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
* in nc->flags, delete reassembled body from the mbuf.
*
* Return reassembled body size.
*/
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
struct http_message *hm, char *buf,
size_t blen);
#ifndef MG_DISABLE_FILESYSTEM
MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st);
#endif
struct ctl_msg {
mg_event_handler_t callback;
char message[MG_CTL_MSG_MESSAGE_SIZE];
};
/* Forward declarations for testing. */
extern void *(*test_malloc)(size_t size);
extern void *(*test_calloc)(size_t count, size_t size);
#endif /* MG_INTERNAL_HEADER_INCLUDED */
#ifdef NS_MODULE_LINES
#line 1 "./src/../../common/base64.c"
/**/
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#ifndef EXCLUDE_COMMON
/* Amalgamated: #include "common/base64.h" */
#include <string.h>
/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
#define NUM_UPPERCASES ('Z' - 'A' + 1)
#define NUM_LETTERS (NUM_UPPERCASES * 2)
#define NUM_DIGITS ('9' - '0' + 1)
/*
* Emit a base64 code char.
*
* Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
*/
static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
if (v < NUM_UPPERCASES) {
ctx->b64_putc(v + 'A', ctx->user_data);
} else if (v < (NUM_LETTERS)) {
ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
} else if (v < (NUM_LETTERS + NUM_DIGITS)) {
ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
} else {
ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
ctx->user_data);
}
}
static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
int a, b, c;
a = ctx->chunk[0];
b = ctx->chunk[1];
c = ctx->chunk[2];
cs_base64_emit_code(ctx, a >> 2);
cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
if (ctx->chunk_size > 1) {
cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
}
if (ctx->chunk_size > 2) {
cs_base64_emit_code(ctx, c & 63);
}
}
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
void *user_data) {
ctx->chunk_size = 0;
ctx->b64_putc = b64_putc;
ctx->user_data = user_data;
}
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
const unsigned char *src = (const unsigned char *) str;
size_t i;
for (i = 0; i < len; i++) {
ctx->chunk[ctx->chunk_size++] = src[i];
if (ctx->chunk_size == 3) {
cs_base64_emit_chunk(ctx);
ctx->chunk_size = 0;
}
}
}
void cs_base64_finish(struct cs_base64_ctx *ctx) {
if (ctx->chunk_size > 0) {
int i;
memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
cs_base64_emit_chunk(ctx);
for (i = 0; i < (3 - ctx->chunk_size); i++) {
ctx->b64_putc('=', ctx->user_data);
}
}
}
#define BASE64_ENCODE_BODY \
static const char *b64 = \
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
int i, j, a, b, c; \
\
for (i = j = 0; i < src_len; i += 3) { \
a = src[i]; \
b = i + 1 >= src_len ? 0 : src[i + 1]; \
c = i + 2 >= src_len ? 0 : src[i + 2]; \
\
BASE64_OUT(b64[a >> 2]); \
BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \
if (i + 1 < src_len) { \
BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \
} \
if (i + 2 < src_len) { \
BASE64_OUT(b64[c & 63]); \
} \
} \
\
while (j % 4 != 0) { \
BASE64_OUT('='); \
} \
BASE64_FLUSH()
#define BASE64_OUT(ch) \
do { \
dst[j++] = (ch); \
} while (0)
#define BASE64_FLUSH() \
do { \
dst[j++] = '\0'; \
} while (0)
void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
BASE64_ENCODE_BODY;
}
#undef BASE64_OUT
#undef BASE64_FLUSH
#define BASE64_OUT(ch) \
do { \
fprintf(f, "%c", (ch)); \
j++; \
} while (0)
#define BASE64_FLUSH()
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
BASE64_ENCODE_BODY;
}
#undef BASE64_OUT
#undef BASE64_FLUSH
/* Convert one byte of encoded base64 input stream to 6-bit chunk */
static unsigned char from_b64(unsigned char ch) {
/* Inverse lookup map */
static const unsigned char tab[128] = {
255, 255, 255, 255,
255, 255, 255, 255, /* 0 */
255, 255, 255, 255,
255, 255, 255, 255, /* 8 */
255, 255, 255, 255,
255, 255, 255, 255, /* 16 */
255, 255, 255, 255,
255, 255, 255, 255, /* 24 */
255, 255, 255, 255,
255, 255, 255, 255, /* 32 */
255, 255, 255, 62,
255, 255, 255, 63, /* 40 */
52, 53, 54, 55,
56, 57, 58, 59, /* 48 */
60, 61, 255, 255,
255, 200, 255, 255, /* 56 '=' is 200, on index 61 */
255, 0, 1, 2,
3, 4, 5, 6, /* 64 */
7, 8, 9, 10,
11, 12, 13, 14, /* 72 */
15, 16, 17, 18,
19, 20, 21, 22, /* 80 */
23, 24, 25, 255,
255, 255, 255, 255, /* 88 */
255, 26, 27, 28,
29, 30, 31, 32, /* 96 */
33, 34, 35, 36,
37, 38, 39, 40, /* 104 */
41, 42, 43, 44,
45, 46, 47, 48, /* 112 */
49, 50, 51, 255,
255, 255, 255, 255, /* 120 */
};
return tab[ch & 127];
}
int cs_base64_decode(const unsigned char *s, int len, char *dst) {
unsigned char a, b, c, d;
int orig_len = len;
while (len >= 4 && (a = from_b64(s[0])) != 255 &&
(b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
(d = from_b64(s[3])) != 255) {
s += 4;
len -= 4;
if (a == 200 || b == 200) break; /* '=' can't be there */
*dst++ = a << 2 | b >> 4;
if (c == 200) break;
*dst++ = b << 4 | c >> 2;
if (d == 200) break;
*dst++ = c << 6 | d;
}
*dst = 0;
return orig_len - len;
}
#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "./src/../../common/cs_dbg.c"
/**/
#endif
/* Amalgamated: #include "common/cs_dbg.h" */
#include <stdarg.h>
#include <stdio.h>
enum cs_log_level s_cs_log_level =
#ifdef CS_ENABLE_DEBUG
LL_VERBOSE_DEBUG;
#else
LL_ERROR;
#endif
void cs_log_printf(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
fflush(stderr);
}
void cs_log_set_level(enum cs_log_level level) {
s_cs_log_level = level;
}
#ifdef NS_MODULE_LINES
#line 1 "./src/../../common/cs_dirent.c"
/**/
#endif
/*
* Copyright (c) 2015 Cesanta Software Limited
* All rights reserved
*/
#ifndef EXCLUDE_COMMON
/* Amalgamated: #include "common/osdep.h" */
/* Amalgamated: #include "common/cs_dirent.h" */
/*
* This file contains POSIX opendir/closedir/readdir API implementation
* for systems which do not natively support it (e.g. Windows).
*/
#ifndef MG_FREE
#define MG_FREE free
#endif
#ifndef MG_MALLOC
#define MG_MALLOC malloc
#endif
#ifdef _WIN32
DIR *opendir(const char *name) {
DIR *dir = NULL;
wchar_t wpath[MAX_PATH];
DWORD attrs;
if (name == NULL) {
SetLastError(ERROR_BAD_ARGUMENTS);
} else if ((dir = (DIR *) MG_MALLOC(sizeof(*dir))) == NULL) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
} else {
to_wchar(name, wpath, ARRAY_SIZE(wpath));
attrs = GetFileAttributesW(wpath);
if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
(void) wcscat(wpath, L"\\*");
dir->handle = FindFirstFileW(wpath, &dir->info);
dir->result.d_name[0] = '\0';
} else {
MG_FREE(dir);
dir = NULL;
}
}
return dir;
}
int closedir(DIR *dir) {
int result = 0;
if (dir != NULL) {
if (dir->handle != INVALID_HANDLE_VALUE)
result = FindClose(dir->handle) ? 0 : -1;
MG_FREE(dir);
} else {
result = -1;
SetLastError(ERROR_BAD_ARGUMENTS);
}
return result;
}
struct dirent *readdir(DIR *dir) {
struct dirent *result = 0;
if (dir) {
if (dir->handle != INVALID_HANDLE_VALUE) {
result = &dir->result;
(void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
result->d_name, sizeof(result->d_name), NULL,
NULL);
if (!FindNextFileW(dir->handle, &dir->info)) {
(void) FindClose(dir->handle);
dir->handle = INVALID_HANDLE_VALUE;
}
} else {
SetLastError(ERROR_FILE_NOT_FOUND);
}
} else {
SetLastError(ERROR_BAD_ARGUMENTS);
}
return result;
}
#endif
#ifdef CS_ENABLE_SPIFFS
DIR *opendir(const char *dir_name) {
DIR *dir = NULL;
extern spiffs fs;
if (dir_name != NULL && (dir = (DIR *) malloc(sizeof(*dir))) != NULL &&
SPIFFS_opendir(&fs, (char *) dir_name, &dir->dh) == NULL) {
free(dir);
dir = NULL;
}
return dir;
}
int closedir(DIR *dir) {
if (dir != NULL) {
SPIFFS_closedir(&dir->dh);
free(dir);
}
return 0;
}
struct dirent *readdir(DIR *dir) {
return SPIFFS_readdir(&dir->dh, &dir->de);
}
/* SPIFFs doesn't support directory operations */
int rmdir(const char *path) {
(void) path;
return ENOTDIR;
}
int mkdir(const char *path, mode_t mode) {
(void) path;
(void) mode;
/* for spiffs supports only root dir, which comes from mongoose as '.' */
return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
}
#endif /* CS_ENABLE_SPIFFS */
#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "./src/../../common/cs_time.c"
/**/
#endif
#ifndef _WIN32
#include <stddef.h>
#ifndef MG_CC3200
#include <sys/time.h>
#endif
#else
#include <windows.h>
#endif
double cs_time() {
double now;
#ifndef _WIN32
struct timeval tv;
if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
#else
now = GetTickCount() / 1000.0;
#endif
return now;
}
#ifdef NS_MODULE_LINES
#line 1 "./src/../deps/frozen/frozen.c"
/**/
#endif
/*
* Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
* Copyright (c) 2013 Cesanta Software Limited
* All rights reserved
*
* This library is dual-licensed: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation. For the terms of this
* license, see <http: *www.gnu.org/licenses/>.
*
* You are free to use this library under the terms of the GNU General
* Public License, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* Alternatively, you can license this library under a commercial
* license, as set out in <https://www.cesanta.com/license>.
*/
#define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005+ */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
/* Amalgamated: #include "frozen.h" */
#ifdef _WIN32
#define snprintf _snprintf
#endif
#ifndef FROZEN_REALLOC
#define FROZEN_REALLOC realloc
#endif
#ifndef FROZEN_FREE
#define FROZEN_FREE free
#endif
struct frozen {
const char *end;
const char *cur;
struct json_token *tokens;
int max_tokens;
int num_tokens;
int do_realloc;
};
static int parse_object(struct frozen *f);
static int parse_value(struct frozen *f);
#define EXPECT(cond, err_code) do { if (!(cond)) return (err_code); } while (0)
#define TRY(expr) do { int _n = expr; if (_n < 0) return _n; } while (0)
#define END_OF_STRING (-1)
static int left(const struct frozen *f) {
return f->end - f->cur;
}
static int is_space(int ch) {
return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
}
static void skip_whitespaces(struct frozen *f) {
while (f->cur < f->end && is_space(*f->cur)) f->cur++;
}
static int cur(struct frozen *f) {
skip_whitespaces(f);
return f->cur >= f->end ? END_OF_STRING : * (unsigned char *) f->cur;
}
static int test_and_skip(struct frozen *f, int expected) {
int ch = cur(f);
if (ch == expected) { f->cur++; return 0; }
return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
}
static int is_alpha(int ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
static int is_digit(int ch) {
return ch >= '0' && ch <= '9';
}
static int is_hex_digit(int ch) {
return is_digit(ch) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
}
static int get_escape_len(const char *s, int len) {
switch (*s) {
case 'u':
return len < 6 ? JSON_STRING_INCOMPLETE :
is_hex_digit(s[1]) && is_hex_digit(s[2]) &&
is_hex_digit(s[3]) && is_hex_digit(s[4]) ? 5 : JSON_STRING_INVALID;
case '"': case '\\': case '/': case 'b':
case 'f': case 'n': case 'r': case 't':
return len < 2 ? JSON_STRING_INCOMPLETE : 1;
default:
return JSON_STRING_INVALID;
}
}
static int capture_ptr(struct frozen *f, const char *ptr, enum json_type type) {
if (f->do_realloc && f->num_tokens >= f->max_tokens) {
int new_size = f->max_tokens == 0 ? 100 : f->max_tokens * 2;
void *p = FROZEN_REALLOC(f->tokens, new_size * sizeof(f->tokens[0]));
if (p == NULL) return JSON_TOKEN_ARRAY_TOO_SMALL;
f->max_tokens = new_size;
f->tokens = (struct json_token *) p;
}
if (f->tokens == NULL || f->max_tokens == 0) return 0;
if (f->num_tokens >= f->max_tokens) return JSON_TOKEN_ARRAY_TOO_SMALL;
f->tokens[f->num_tokens].ptr = ptr;
f->tokens[f->num_tokens].type = type;
f->num_tokens++;
return 0;
}
static int capture_len(struct frozen *f, int token_index, const char *ptr) {
if (f->tokens == 0 || f->max_tokens == 0) return 0;
EXPECT(token_index >= 0 && token_index < f->max_tokens, JSON_STRING_INVALID);
f->tokens[token_index].len = ptr - f->tokens[token_index].ptr;
f->tokens[token_index].num_desc = (f->num_tokens - 1) - token_index;
return 0;
}
/* identifier = letter { letter | digit | '_' } */
static int parse_identifier(struct frozen *f) {
EXPECT(is_alpha(cur(f)), JSON_STRING_INVALID);
TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING));
while (f->cur < f->end &&
(*f->cur == '_' || is_alpha(*f->cur) || is_digit(*f->cur))) {
f->cur++;
}
capture_len(f, f->num_tokens - 1, f->cur);
return 0;
}
static int get_utf8_char_len(unsigned char ch) {
if ((ch & 0x80) == 0) return 1;
switch (ch & 0xf0) {
case 0xf0: return 4;
case 0xe0: return 3;
default: return 2;
}
}
/* string = '"' { quoted_printable_chars } '"' */
static int parse_string(struct frozen *f) {
int n, ch = 0, len = 0;
TRY(test_and_skip(f, '"'));
TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING));
for (; f->cur < f->end; f->cur += len) {
ch = * (unsigned char *) f->cur;
len = get_utf8_char_len((unsigned char) ch);
EXPECT(ch >= 32 && len > 0, JSON_STRING_INVALID); /* No control chars */
EXPECT(len < left(f), JSON_STRING_INCOMPLETE);
if (ch == '\\') {
EXPECT((n = get_escape_len(f->cur + 1, left(f))) > 0, n);
len += n;
} else if (ch == '"') {
capture_len(f, f->num_tokens - 1, f->cur);
f->cur++;
break;
};
}
return ch == '"' ? 0 : JSON_STRING_INCOMPLETE;
}
/* number = [ '-' ] digit+ [ '.' digit+ ] [ ['e'|'E'] ['+'|'-'] digit+ ] */
static int parse_number(struct frozen *f) {
int ch = cur(f);
TRY(capture_ptr(f, f->cur, JSON_TYPE_NUMBER));
if (ch == '-') f->cur++;
EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
if (f->cur < f->end && f->cur[0] == '.') {
f->cur++;
EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
}
if (f->cur < f->end && (f->cur[0] == 'e' || f->cur[0] == 'E')) {
f->cur++;
EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
if ((f->cur[0] == '+' || f->cur[0] == '-')) f->cur++;
EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
}
capture_len(f, f->num_tokens - 1, f->cur);
return 0;
}
/* array = '[' [ value { ',' value } ] ']' */
static int parse_array(struct frozen *f) {
int ind;
TRY(test_and_skip(f, '['));
TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_ARRAY));
ind = f->num_tokens - 1;
while (cur(f) != ']') {
TRY(parse_value(f));
if (cur(f) == ',') f->cur++;
}
TRY(test_and_skip(f, ']'));
capture_len(f, ind, f->cur);
return 0;
}
static int compare(const char *s, const char *str, int len) {
int i = 0;
while (i < len && s[i] == str[i]) i++;
return i == len ? 1 : 0;
}
static int expect(struct frozen *f, const char *s, int len, enum json_type t) {
int i, n = left(f);
TRY(capture_ptr(f, f->cur, t));
for (i = 0; i < len; i++) {
if (i >= n) return JSON_STRING_INCOMPLETE;
if (f->cur[i] != s[i]) return JSON_STRING_INVALID;
}
f->cur += len;
TRY(capture_len(f, f->num_tokens - 1, f->cur));
return 0;
}
/* value = 'null' | 'true' | 'false' | number | string | array | object */
static int parse_value(struct frozen *f) {
int ch = cur(f);
switch (ch) {
case '"': TRY(parse_string(f)); break;
case '{': TRY(parse_object(f)); break;
case '[': TRY(parse_array(f)); break;
case 'n': TRY(expect(f, "null", 4, JSON_TYPE_NULL)); break;
case 't': TRY(expect(f, "true", 4, JSON_TYPE_TRUE)); break;
case 'f': TRY(expect(f, "false", 5, JSON_TYPE_FALSE)); break;
case '-': case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
TRY(parse_number(f));
break;
default:
return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
}
return 0;
}
/* key = identifier | string */
static int parse_key(struct frozen *f) {
int ch = cur(f);
#if 0
printf("%s 1 [%.*s]\n", __func__, (int) (f->end - f->cur), f->cur);
#endif
if (is_alpha(ch)) {
TRY(parse_identifier(f));
} else if (ch == '"') {
TRY(parse_string(f));
} else {
return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
}
return 0;
}
/* pair = key ':' value */
static int parse_pair(struct frozen *f) {
TRY(parse_key(f));
TRY(test_and_skip(f, ':'));
TRY(parse_value(f));
return 0;
}
/* object = '{' pair { ',' pair } '}' */
static int parse_object(struct frozen *f) {
int ind;
TRY(test_and_skip(f, '{'));
TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_OBJECT));
ind = f->num_tokens - 1;
while (cur(f) != '}') {
TRY(parse_pair(f));
if (cur(f) == ',') f->cur++;
}
TRY(test_and_skip(f, '}'));
capture_len(f, ind, f->cur);
return 0;
}
static int doit(struct frozen *f) {
if (f->cur == 0 || f->end < f->cur) return JSON_STRING_INVALID;
if (f->end == f->cur) return JSON_STRING_INCOMPLETE;
TRY(parse_object(f));
TRY(capture_ptr(f, f->cur, JSON_TYPE_EOF));
capture_len(f, f->num_tokens, f->cur);
return 0;
}
/* json = object */
int parse_json(const char *s, int s_len, struct json_token *arr, int arr_len) {
struct frozen frozen;
memset(&frozen, 0, sizeof(frozen));
frozen.end = s + s_len;
frozen.cur = s;
frozen.tokens = arr;
frozen.max_tokens = arr_len;
TRY(doit(&frozen));
return frozen.cur - s;
}
struct json_token *parse_json2(const char *s, int s_len) {
struct frozen frozen;
memset(&frozen, 0, sizeof(frozen));
frozen.end = s + s_len;
frozen.cur = s;
frozen.do_realloc = 1;
if (doit(&frozen) < 0) {
FROZEN_FREE((void *) frozen.tokens);
frozen.tokens = NULL;
}
return frozen.tokens;
}
static int path_part_len(const char *p) {
int i = 0;
while (p[i] != '\0' && p[i] != '[' && p[i] != '.') i++;
return i;
}
struct json_token *find_json_token(struct json_token *toks, const char *path) {
while (path != 0 && path[0] != '\0') {
int i, ind2 = 0, ind = -1, skip = 2, n = path_part_len(path);
if (path[0] == '[') {
if (toks->type != JSON_TYPE_ARRAY || !is_digit(path[1])) return 0;
for (ind = 0, n = 1; path[n] != ']' && path[n] != '\0'; n++) {
if (!is_digit(path[n])) return 0;
ind *= 10;
ind += path[n] - '0';
}
if (path[n++] != ']') return 0;
skip = 1; /* In objects, we skip 2 elems while iterating, in arrays 1. */
} else if (toks->type != JSON_TYPE_OBJECT) return 0;
toks++;
for (i = 0; i < toks[-1].num_desc; i += skip, ind2++) {
/* ind == -1 indicated that we're iterating an array, not object */
if (ind == -1 && toks[i].type != JSON_TYPE_STRING) return 0;
if (ind2 == ind ||
(ind == -1 && toks[i].len == n && compare(path, toks[i].ptr, n))) {
i += skip - 1;
break;
};
if (toks[i - 1 + skip].type == JSON_TYPE_ARRAY ||
toks[i - 1 + skip].type == JSON_TYPE_OBJECT) {
i += toks[i - 1 + skip].num_desc;
}
}
if (i == toks[-1].num_desc) return 0;
path += n;
if (path[0] == '.') path++;
if (path[0] == '\0') return &toks[i];
toks += i;
}
return 0;
}
int json_emit_long(char *buf, int buf_len, long int value) {
char tmp[20];
int n = snprintf(tmp, sizeof(tmp), "%ld", value);
strncpy(buf, tmp, buf_len > 0 ? buf_len : 0);
return n;
}
int json_emit_double(char *buf, int buf_len, double value) {
char tmp[20];
int n = snprintf(tmp, sizeof(tmp), "%g", value);
strncpy(buf, tmp, buf_len > 0 ? buf_len : 0);
return n;
}
int json_emit_quoted_str(char *s, int s_len, const char *str, int len) {
const char *begin = s, *end = s + s_len, *str_end = str + len;
char ch;
#define EMIT(x) do { if (s < end) *s = x; s++; } while (0)
EMIT('"');
while (str < str_end) {
ch = *str++;
switch (ch) {
case '"': EMIT('\\'); EMIT('"'); break;
case '\\': EMIT('\\'); EMIT('\\'); break;
case '\b': EMIT('\\'); EMIT('b'); break;
case '\f': EMIT('\\'); EMIT('f'); break;
case '\n': EMIT('\\'); EMIT('n'); break;
case '\r': EMIT('\\'); EMIT('r'); break;
case '\t': EMIT('\\'); EMIT('t'); break;
default: EMIT(ch);
}
}
EMIT('"');
if (s < end) {
*s = '\0';
}
return s - begin;
}
int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len) {
if (buf_len > 0 && len > 0) {
int n = len < buf_len ? len : buf_len;
memcpy(buf, str, n);
if (n < buf_len) {
buf[n] = '\0';
}
}
return len;
}
int json_emit_va(char *s, int s_len, const char *fmt, va_list ap) {
const char *end = s + s_len, *str, *orig = s;
size_t len;
while (*fmt != '\0') {
switch (*fmt) {
case '[': case ']': case '{': case '}': case ',': case ':':
case ' ': case '\r': case '\n': case '\t':
if (s < end) {
*s = *fmt;
}
s++;
break;
case 'i':
s += json_emit_long(s, end - s, va_arg(ap, long));
break;
case 'f':
s += json_emit_double(s, end - s, va_arg(ap, double));
break;
case 'v':
str = va_arg(ap, char *);
len = va_arg(ap, size_t);
s += json_emit_quoted_str(s, end - s, str, len);
break;
case 'V':
str = va_arg(ap, char *);
len = va_arg(ap, size_t);
s += json_emit_unquoted_str(s, end - s, str, len);
break;
case 's':
str = va_arg(ap, char *);
s += json_emit_quoted_str(s, end - s, str, strlen(str));
break;
case 'S':
str = va_arg(ap, char *);
s += json_emit_unquoted_str(s, end - s, str, strlen(str));
break;
case 'T':
s += json_emit_unquoted_str(s, end - s, "true", 4);
break;
case 'F':
s += json_emit_unquoted_str(s, end - s, "false", 5);
break;
case 'N':
s += json_emit_unquoted_str(s, end - s, "null", 4);
break;
default:
return 0;
}
fmt++;
}
/* Best-effort to 0-terminate generated string */
if (s < end) {
*s = '\0';
}
return s - orig;
}
int json_emit(char *buf, int buf_len, const char *fmt, ...) {
int len;
va_list ap;
va_start(ap, fmt);
len = json_emit_va(buf, buf_len, fmt, ap);
va_end(ap);
return len;
}
#ifdef NS_MODULE_LINES
#line 1 "./src/../../common/md5.c"
/**/
#endif
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
#if !defined(DISABLE_MD5) && !defined(EXCLUDE_COMMON)
/* Amalgamated: #include "common/md5.h" */
#ifndef CS_ENABLE_NATIVE_MD5
static void byteReverse(unsigned char *buf, unsigned longs) {
/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
#if BYTE_ORDER == BIG_ENDIAN
do {
uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
((unsigned) buf[1] << 8 | buf[0]);
*(uint32_t *) buf = t;
buf += 4;
} while (--longs);
#else
(void) buf;
(void) longs;
#endif
}
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
#define MD5STEP(f, w, x, y, z, data, s) \
(w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
void MD5_Init(MD5_CTX *ctx) {
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bits[0] = 0;
ctx->bits[1] = 0;
}
static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
register uint32_t a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
void MD5_Update(MD5_CTX *ctx, const unsigned char *buf, size_t len) {
uint32_t t;
t = ctx->bits[0];
if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
ctx->bits[1] += (uint32_t) len >> 29;
t = (t >> 3) & 0x3f;
if (t) {
unsigned char *p = (unsigned char *) ctx->in + t;
t = 64 - t;
if (len < t) {
memcpy(p, buf, len);
return;
}
memcpy(p, buf, t);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
buf += t;
len -= t;
}
while (len >= 64) {
memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
buf += 64;
len -= 64;
}
memcpy(ctx->in, buf, len);
}
void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) {
unsigned count;
unsigned char *p;
uint32_t *a;
count = (ctx->bits[0] >> 3) & 0x3F;
p = ctx->in + count;
*p++ = 0x80;
count = 64 - 1 - count;
if (count < 8) {
memset(p, 0, count);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
memset(ctx->in, 0, 56);
} else {
memset(p, 0, count - 8);
}
byteReverse(ctx->in, 14);
a = (uint32_t *) ctx->in;
a[14] = ctx->bits[0];
a[15] = ctx->bits[1];
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
byteReverse((unsigned char *) ctx->buf, 4);
memcpy(digest, ctx->buf, 16);
memset((char *) ctx, 0, sizeof(*ctx));
}
#endif /* CS_ENABLE_NATIVE_MD5 */
/*
* Stringify binary data. Output buffer size must be 2 * size_of_input + 1
* because each byte of input takes 2 bytes in string representation
* plus 1 byte for the terminating \0 character.
*/
void cs_to_hex(char *to, const unsigned char *p, size_t len) {
static const char *hex = "0123456789abcdef";
for (; len--; p++) {
*to++ = hex[p[0] >> 4];
*to++ = hex[p[0] & 0x0f];
}
*to = '\0';
}
char *cs_md5(char buf[33], ...) {
unsigned char hash[16];
const unsigned char *p;
va_list ap;
MD5_CTX ctx;
MD5_Init(&ctx);
va_start(ap, buf);
while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
size_t len = va_arg(ap, size_t);
MD5_Update(&ctx, p, len);
}
va_end(ap);
MD5_Final(hash, &ctx);
cs_to_hex(buf, hash, sizeof(hash));
return buf;
}
#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "./src/../../common/mbuf.c"
/**/
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#ifndef EXCLUDE_COMMON
#include <assert.h>
#include <string.h>
/* Amalgamated: #include "common/mbuf.h" */
#ifndef MBUF_REALLOC
#define MBUF_REALLOC realloc
#endif
#ifndef MBUF_FREE
#define MBUF_FREE free
#endif
void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
mbuf->len = mbuf->size = 0;
mbuf->buf = NULL;
mbuf_resize(mbuf, initial_size);
}
void mbuf_free(struct mbuf *mbuf) {
if (mbuf->buf != NULL) {
MBUF_FREE(mbuf->buf);
mbuf_init(mbuf, 0);
}
}
void mbuf_resize(struct mbuf *a, size_t new_size) {
if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
/*
* In case realloc fails, there's not much we can do, except keep things as
* they are. Note that NULL is a valid return value from realloc when
* size == 0, but that is covered too.
*/
if (buf == NULL && new_size != 0) return;
a->buf = buf;
a->size = new_size;
}
}
void mbuf_trim(struct mbuf *mbuf) {
mbuf_resize(mbuf, mbuf->len);
}
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
char *p = NULL;
assert(a != NULL);
assert(a->len <= a->size);
assert(off <= a->len);
/* check overflow */
if (~(size_t) 0 - (size_t) a->buf < len) return 0;
if (a->len + len <= a->size) {
memmove(a->buf + off + len, a->buf + off, a->len - off);
if (buf != NULL) {
memcpy(a->buf + off, buf, len);
}
a->len += len;
} else if ((p = (char *) MBUF_REALLOC(
a->buf, (a->len + len) * MBUF_SIZE_MULTIPLIER)) != NULL) {
a->buf = p;
memmove(a->buf + off + len, a->buf + off, a->len - off);
if (buf != NULL) {
memcpy(a->buf + off, buf, len);
}
a->len += len;
a->size = a->len * MBUF_SIZE_MULTIPLIER;
} else {
len = 0;
}
return len;
}
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
return mbuf_insert(a, a->len, buf, len);
}
void mbuf_remove(struct mbuf *mb, size_t n) {
if (n > 0 && n <= mb->len) {
memmove(mb->buf, mb->buf + n, mb->len - n);
mb->len -= n;
}
}
#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "./src/../../common/sha1.c"
/**/
#endif
/* Copyright(c) By Steve Reid <steve@edmweb.com> */
/* 100% Public Domain */
#if !defined(DISABLE_SHA1) && !defined(EXCLUDE_COMMON)
/* Amalgamated: #include "common/sha1.h" */
#define SHA1HANDSOFF
#if defined(__sun)
/* Amalgamated: #include "common/solarisfixes.h" */
#endif
union char64long16 {
unsigned char c[64];
uint32_t l[16];
};
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
static uint32_t blk0(union char64long16 *block, int i) {
/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
#if BYTE_ORDER == LITTLE_ENDIAN
block->l[i] =
(rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
#endif
return block->l[i];
}
/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
#undef blk
#undef R0
#undef R1
#undef R2
#undef R3
#undef R4
#define blk(i) \
(block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
block->l[(i + 2) & 15] ^ block->l[i & 15], \
1))
#define R0(v, w, x, y, z, i) \
z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
w = rol(w, 30);
#define R1(v, w, x, y, z, i) \
z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
w = rol(w, 30);
#define R2(v, w, x, y, z, i) \
z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
w = rol(w, 30);
#define R3(v, w, x, y, z, i) \
z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
w = rol(w, 30);
#define R4(v, w, x, y, z, i) \
z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
w = rol(w, 30);
void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
uint32_t a, b, c, d, e;
union char64long16 block[1];
memcpy(block, buffer, 64);
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
R0(a, b, c, d, e, 0);
R0(e, a, b, c, d, 1);
R0(d, e, a, b, c, 2);
R0(c, d, e, a, b, 3);
R0(b, c, d, e, a, 4);
R0(a, b, c, d, e, 5);
R0(e, a, b, c, d, 6);
R0(d, e, a, b, c, 7);
R0(c, d, e, a, b, 8);
R0(b, c, d, e, a, 9);
R0(a, b, c, d, e, 10);
R0(e, a, b, c, d, 11);
R0(d, e, a, b, c, 12);
R0(c, d, e, a, b, 13);
R0(b, c, d, e, a, 14);
R0(a, b, c, d, e, 15);
R1(e, a, b, c, d, 16);
R1(d, e, a, b, c, 17);
R1(c, d, e, a, b, 18);
R1(b, c, d, e, a, 19);
R2(a, b, c, d, e, 20);
R2(e, a, b, c, d, 21);
R2(d, e, a, b, c, 22);
R2(c, d, e, a, b, 23);
R2(b, c, d, e, a, 24);
R2(a, b, c, d, e, 25);
R2(e, a, b, c, d, 26);
R2(d, e, a, b, c, 27);
R2(c, d, e, a, b, 28);
R2(b, c, d, e, a, 29);
R2(a, b, c, d, e, 30);
R2(e, a, b, c, d, 31);
R2(d, e, a, b, c, 32);
R2(c, d, e, a, b, 33);
R2(b, c, d, e, a, 34);
R2(a, b, c, d, e, 35);
R2(e, a, b, c, d, 36);
R2(d, e, a, b, c, 37);
R2(c, d, e, a, b, 38);
R2(b, c, d, e, a, 39);
R3(a, b, c, d, e, 40);
R3(e, a, b, c, d, 41);
R3(d, e, a, b, c, 42);
R3(c, d, e, a, b, 43);
R3(b, c, d, e, a, 44);
R3(a, b, c, d, e, 45);
R3(e, a, b, c, d, 46);
R3(d, e, a, b, c, 47);
R3(c, d, e, a, b, 48);
R3(b, c, d, e, a, 49);
R3(a, b, c, d, e, 50);
R3(e, a, b, c, d, 51);
R3(d, e, a, b, c, 52);
R3(c, d, e, a, b, 53);
R3(b, c, d, e, a, 54);
R3(a, b, c, d, e, 55);
R3(e, a, b, c, d, 56);
R3(d, e, a, b, c, 57);
R3(c, d, e, a, b, 58);
R3(b, c, d, e, a, 59);
R4(a, b, c, d, e, 60);
R4(e, a, b, c, d, 61);
R4(d, e, a, b, c, 62);
R4(c, d, e, a, b, 63);
R4(b, c, d, e, a, 64);
R4(a, b, c, d, e, 65);
R4(e, a, b, c, d, 66);
R4(d, e, a, b, c, 67);
R4(c, d, e, a, b, 68);
R4(b, c, d, e, a, 69);
R4(a, b, c, d, e, 70);
R4(e, a, b, c, d, 71);
R4(d, e, a, b, c, 72);
R4(c, d, e, a, b, 73);
R4(b, c, d, e, a, 74);
R4(a, b, c, d, e, 75);
R4(e, a, b, c, d, 76);
R4(d, e, a, b, c, 77);
R4(c, d, e, a, b, 78);
R4(b, c, d, e, a, 79);
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
/* Erase working structures. The order of operations is important,
* used to ensure that compiler doesn't optimize those out. */
memset(block, 0, sizeof(block));
a = b = c = d = e = 0;
(void) a;
(void) b;
(void) c;
(void) d;
(void) e;
}
void cs_sha1_init(cs_sha1_ctx *context) {
context->state[0] = 0x67452301;
context->state[1] = 0xEFCDAB89;
context->state[2] = 0x98BADCFE;
context->state[3] = 0x10325476;
context->state[4] = 0xC3D2E1F0;
context->count[0] = context->count[1] = 0;
}
void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
uint32_t len) {
uint32_t i, j;
j = context->count[0];
if ((context->count[0] += len << 3) < j) context->count[1]++;
context->count[1] += (len >> 29);
j = (j >> 3) & 63;
if ((j + len) > 63) {
memcpy(&context->buffer[j], data, (i = 64 - j));
cs_sha1_transform(context->state, context->buffer);
for (; i + 63 < len; i += 64) {
cs_sha1_transform(context->state, &data[i]);
}
j = 0;
} else
i = 0;
memcpy(&context->buffer[j], &data[i], len - i);
}
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
unsigned i;
unsigned char finalcount[8], c;
for (i = 0; i < 8; i++) {
finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
((3 - (i & 3)) * 8)) &
255);
}
c = 0200;
cs_sha1_update(context, &c, 1);
while ((context->count[0] & 504) != 448) {
c = 0000;
cs_sha1_update(context, &c, 1);
}
cs_sha1_update(context, finalcount, 8);
for (i = 0; i < 20; i++) {
digest[i] =
(unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
}
memset(context, '\0', sizeof(*context));
memset(&finalcount, '\0', sizeof(finalcount));
}
void cs_hmac_sha1(const unsigned char *key, size_t keylen,
const unsigned char *data, size_t datalen,
unsigned char out[20]) {
cs_sha1_ctx ctx;
unsigned char buf1[64], buf2[64], tmp_key[20], i;
if (keylen > sizeof(buf1)) {
cs_sha1_init(&ctx);
cs_sha1_update(&ctx, key, keylen);
cs_sha1_final(tmp_key, &ctx);
key = tmp_key;
keylen = sizeof(tmp_key);
}
memset(buf1, 0, sizeof(buf1));
memset(buf2, 0, sizeof(buf2));
memcpy(buf1, key, keylen);
memcpy(buf2, key, keylen);
for (i = 0; i < sizeof(buf1); i++) {
buf1[i] ^= 0x36;
buf2[i] ^= 0x5c;
}
cs_sha1_init(&ctx);
cs_sha1_update(&ctx, buf1, sizeof(buf1));
cs_sha1_update(&ctx, data, datalen);
cs_sha1_final(out, &ctx);
cs_sha1_init(&ctx);
cs_sha1_update(&ctx, buf2, sizeof(buf2));
cs_sha1_update(&ctx, out, 20);
cs_sha1_final(out, &ctx);
}
#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "./src/../../common/str_util.c"
/**/
#endif
/*
* Copyright (c) 2015 Cesanta Software Limited
* All rights reserved
*/
#ifndef EXCLUDE_COMMON
/* Amalgamated: #include "common/osdep.h" */
/* Amalgamated: #include "common/str_util.h" */
#ifdef _MG_PROVIDE_STRNLEN
size_t strnlen(const char *s, size_t maxlen) {
size_t l = 0;
for (; l < maxlen && s[l] != '\0'; l++) {
}
return l;
}
#endif
#define C_SNPRINTF_APPEND_CHAR(ch) \
do { \
if (i < (int) buf_size) buf[i] = ch; \
i++; \
} while (0)
#define C_SNPRINTF_FLAG_ZERO 1
#ifdef C_DISABLE_BUILTIN_SNPRINTF
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
return vsnprintf(buf, buf_size, fmt, ap);
}
#else
static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
int field_width) {
char tmp[40];
int i = 0, k = 0, neg = 0;
if (num < 0) {
neg++;
num = -num;
}
/* Print into temporary buffer - in reverse order */
do {
int rem = num % base;
if (rem < 10) {
tmp[k++] = '0' + rem;
} else {
tmp[k++] = 'a' + (rem - 10);
}
num /= base;
} while (num > 0);
/* Zero padding */
if (flags && C_SNPRINTF_FLAG_ZERO) {
while (k < field_width && k < (int) sizeof(tmp) - 1) {
tmp[k++] = '0';
}
}
/* And sign */
if (neg) {
tmp[k++] = '-';
}
/* Now output */
while (--k >= 0) {
C_SNPRINTF_APPEND_CHAR(tmp[k]);
}
return i;
}
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
int ch, i = 0, len_mod, flags, precision, field_width;
while ((ch = *fmt++) != '\0') {
if (ch != '%') {
C_SNPRINTF_APPEND_CHAR(ch);
} else {
/*
* Conversion specification:
* zero or more flags (one of: # 0 - <space> + ')
* an optional minimum field width (digits)
* an optional precision (. followed by digits, or *)
* an optional length modifier (one of: hh h l ll L q j z t)
* conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
*/
flags = field_width = precision = len_mod = 0;
/* Flags. only zero-pad flag is supported. */
if (*fmt == '0') {
flags |= C_SNPRINTF_FLAG_ZERO;
}
/* Field width */
while (*fmt >= '0' && *fmt <= '9') {
field_width *= 10;
field_width += *fmt++ - '0';
}
/* Dynamic field width */
if (*fmt == '*') {
field_width = va_arg(ap, int);
fmt++;
}
/* Precision */
if (*fmt == '.') {
fmt++;
if (*fmt == '*') {
precision = va_arg(ap, int);
fmt++;
} else {
while (*fmt >= '0' && *fmt <= '9') {
precision *= 10;
precision += *fmt++ - '0';
}
}
}
/* Length modifier */
switch (*fmt) {
case 'h':
case 'l':
case 'L':
case 'I':
case 'q':
case 'j':
case 'z':
case 't':
len_mod = *fmt++;
if (*fmt == 'h') {
len_mod = 'H';
fmt++;
}
if (*fmt == 'l') {
len_mod = 'q';
fmt++;
}
break;
}
ch = *fmt++;
if (ch == 's') {
const char *s = va_arg(ap, const char *); /* Always fetch parameter */
int j;
int pad = field_width - (precision >= 0 ? strnlen(s, precision) : 0);
for (j = 0; j < pad; j++) {
C_SNPRINTF_APPEND_CHAR(' ');
}
/* Ignore negative and 0 precisions */
for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
C_SNPRINTF_APPEND_CHAR(s[j]);
}
} else if (ch == 'c') {
ch = va_arg(ap, int); /* Always fetch parameter */
C_SNPRINTF_APPEND_CHAR(ch);
} else if (ch == 'd' && len_mod == 0) {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
field_width);
} else if (ch == 'd' && len_mod == 'l') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
field_width);
} else if (ch == 'd' && len_mod == 'q') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
ch == 'x' ? 16 : 10, flags, field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
ch == 'x' ? 16 : 10, flags, field_width);
} else if (ch == 'p') {
unsigned long num = (unsigned long) va_arg(ap, void *);
C_SNPRINTF_APPEND_CHAR('0');
C_SNPRINTF_APPEND_CHAR('x');
i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
} else {
#ifndef NO_LIBC
/*
* TODO(lsm): abort is not nice in a library, remove it
* Also, ESP8266 SDK doesn't have it
*/
abort();
#endif
}
}
}
/* Zero-terminate the result */
if (buf_size > 0) {
buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
}
return i;
}
#endif
int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
int result;
va_list ap;
va_start(ap, fmt);
result = c_vsnprintf(buf, buf_size, fmt, ap);
va_end(ap);
return result;
}
#ifdef _WIN32
void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
strncpy(buf, path, sizeof(buf));
buf[sizeof(buf) - 1] = '\0';
/* Trim trailing slashes. Leave backslash for paths like "X:\" */
p = buf + strlen(buf) - 1;
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';
}
}
#endif /* _WIN32 */
#endif /* EXCLUDE_COMMON */
#ifdef NS_MODULE_LINES
#line 1 "./src/net.c"
/**/
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*
* This software is dual-licensed: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation. For the terms of this
* license, see <http://www.gnu.org/licenses/>.
*
* You are free to use this software under the terms of the GNU General
* Public License, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* Alternatively, you can license this software under a commercial
* license, as set out in <https://www.cesanta.com/license>.
*/
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
/* Amalgamated: #include "mongoose/src/dns.h" */
/* Amalgamated: #include "mongoose/src/resolv.h" */
/* Amalgamated: #include "common/cs_time.h" */
#if MG_MGR_EV_MGR == 1 /* epoll() */
#include <sys/epoll.h>
#endif
#define MG_MAX_HOST_LEN 200
#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
memcpy(dst, src, sizeof(*dst));
/* Which flags can be pre-set by the user at connection creation time. */
#define _MG_ALLOWED_CONNECT_FLAGS_MASK \
(MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG)
/* Which flags should be modifiable by user's callbacks. */
#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \
(MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \
MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
#ifndef intptr_t
#define intptr_t long
#endif
int mg_is_error(int n);
void mg_set_non_blocking_mode(sock_t sock);
extern void mg_ev_mgr_init(struct mg_mgr *mgr);
extern void mg_ev_mgr_free(struct mg_mgr *mgr);
extern void mg_ev_mgr_add_conn(struct mg_connection *nc);
extern void mg_ev_mgr_remove_conn(struct mg_connection *nc);
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
DBG(("%p %p", mgr, c));
c->mgr = mgr;
c->next = mgr->active_connections;
mgr->active_connections = c;
c->prev = NULL;
if (c->next != NULL) c->next->prev = c;
mg_ev_mgr_add_conn(c);
}
MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
if (conn->prev) conn->prev->next = conn->next;
if (conn->next) conn->next->prev = conn->prev;
mg_ev_mgr_remove_conn(conn);
}
MG_INTERNAL void mg_call(struct mg_connection *nc,
mg_event_handler_t ev_handler, int ev, void *ev_data) {
unsigned long flags_before;
if (ev_handler == NULL) {
/*
* If protocol handler is specified, call it. Otherwise, call user-specified
* event handler.
*/
ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
}
DBG(("%p %s ev=%d ev_data=%p flags=%lu rmbl=%d smbl=%d", nc,
ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
#if !defined(NO_LIBC) && !defined(MG_DISABLE_HEXDUMP)
/* LCOV_EXCL_START */
if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL &&
ev != MG_EV_SEND /* handled separately */) {
if (ev == MG_EV_RECV) {
mg_hexdump_connection(nc, nc->mgr->hexdump_file, nc->recv_mbuf.buf,
*(int *) ev_data, ev);
} else {
mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev);
}
}
/* LCOV_EXCL_STOP */
#endif
if (ev_handler != NULL) {
flags_before = nc->flags;
ev_handler(nc, ev, ev_data);
/* Prevent user handler from fiddling with system flags. */
if (ev_handler == nc->handler && nc->flags != flags_before) {
nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
(nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
}
}
DBG(("%p after %s flags=%lu rmbl=%d smbl=%d", nc,
ev_handler == nc->handler ? "user" : "proto", nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
void mg_if_timer(struct mg_connection *c, double now) {
if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
double old_value = c->ev_timer_time;
mg_call(c, NULL, MG_EV_TIMER, &now);
/*
* To prevent timer firing all the time, reset the timer after delivery.
* However, in case user sets it to new value, do not reset.
*/
if (c->ev_timer_time == old_value) {
c->ev_timer_time = 0;
}
}
}
void mg_if_poll(struct mg_connection *nc, time_t now) {
mg_call(nc, NULL, MG_EV_POLL, &now);
}
static void mg_destroy_conn(struct mg_connection *conn) {
mg_if_destroy_conn(conn);
#ifdef MG_ENABLE_SSL
if (conn->ssl != NULL) SSL_free(conn->ssl);
if (conn->ssl_ctx != NULL) SSL_CTX_free(conn->ssl_ctx);
#endif
mbuf_free(&conn->recv_mbuf);
mbuf_free(&conn->send_mbuf);
memset(conn, 0, sizeof(*conn));
MG_FREE(conn);
}
void mg_close_conn(struct mg_connection *conn) {
DBG(("%p %lu", conn, conn->flags));
mg_call(conn, NULL, MG_EV_CLOSE, NULL);
mg_remove_conn(conn);
mg_destroy_conn(conn);
}
void mg_mgr_init(struct mg_mgr *m, void *user_data) {
memset(m, 0, sizeof(*m));
#ifndef MG_DISABLE_SOCKETPAIR
m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
#endif
m->user_data = user_data;
#ifdef _WIN32
{
WSADATA data;
WSAStartup(MAKEWORD(2, 2), &data);
}
#elif !defined(AVR_LIBC) && !defined(MG_ESP8266)
/* Ignore SIGPIPE signal, so if client cancels the request, it
* won't kill the whole process. */
signal(SIGPIPE, SIG_IGN);
#endif
#ifdef MG_ENABLE_SSL
{
static int init_done;
if (!init_done) {
SSL_library_init();
init_done++;
}
}
#endif
mg_ev_mgr_init(m);
DBG(("=================================="));
DBG(("init mgr=%p", m));
}
#ifdef MG_ENABLE_JAVASCRIPT
static enum v7_err mg_send_js(struct v7 *v7, v7_val_t *res) {
v7_val_t arg0 = v7_arg(v7, 0);
v7_val_t arg1 = v7_arg(v7, 1);
struct mg_connection *c = (struct mg_connection *) v7_to_foreign(arg0);
size_t len = 0;
if (v7_is_string(arg1)) {
const char *data = v7_get_string_data(v7, &arg1, &len);
mg_send(c, data, len);
}
*res = v7_create_number(len);
return V7_OK;
}
enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
const char *init_file_name) {
v7_val_t v;
m->v7 = v7;
v7_set_method(v7, v7_get_global(v7), "mg_send", mg_send_js);
return v7_exec_file(v7, init_file_name, &v);
}
#endif
void mg_mgr_free(struct mg_mgr *m) {
struct mg_connection *conn, *tmp_conn;
DBG(("%p", m));
if (m == NULL) return;
/* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
mg_mgr_poll(m, 0);
#ifndef MG_DISABLE_SOCKETPAIR
if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
#endif
for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
tmp_conn = conn->next;
mg_close_conn(conn);
}
mg_ev_mgr_free(m);
}
int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
int len;
if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
mg_send(nc, buf, len);
}
if (buf != mem && buf != NULL) {
MG_FREE(buf); /* LCOV_EXCL_LINE */
} /* LCOV_EXCL_LINE */
return len;
}
int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
int len;
va_list ap;
va_start(ap, fmt);
len = mg_vprintf(conn, fmt, ap);
va_end(ap);
return len;
}
#ifndef MG_DISABLE_SYNC_RESOLVER
/* TODO(lsm): use non-blocking resolver */
static int mg_resolve2(const char *host, struct in_addr *ina) {
#ifdef MG_ENABLE_GETADDRINFO
int rv = 0;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_in *h = NULL;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
DBG(("getaddrinfo(%s) failed: %s", host, strerror(errno)));
return 0;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
memcpy(ina, &h->sin_addr, sizeof(ina));
}
freeaddrinfo(servinfo);
return 1;
#else
struct hostent *he;
if ((he = gethostbyname(host)) == NULL) {
DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
} else {
memcpy(ina, he->h_addr_list[0], sizeof(*ina));
return 1;
}
return 0;
#endif /* MG_ENABLE_GETADDRINFO */
}
int mg_resolve(const char *host, char *buf, size_t n) {
struct in_addr ad;
return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
}
#endif /* MG_DISABLE_SYNC_RESOLVER */
MG_INTERNAL struct mg_connection *mg_create_connection(
struct mg_mgr *mgr, mg_event_handler_t callback,
struct mg_add_sock_opts opts) {
struct mg_connection *conn;
if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
conn->sock = INVALID_SOCKET;
conn->handler = callback;
conn->mgr = mgr;
conn->last_io_time = mg_time();
conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
conn->user_data = opts.user_data;
/*
* SIZE_MAX is defined as a long long constant in
* system headers on some platforms and so it
* doesn't compile with pedantic ansi flags.
*/
conn->recv_mbuf_limit = ~0;
if (!mg_if_create_conn(conn)) {
MG_FREE(conn);
conn = NULL;
MG_SET_PTRPTR(opts.error_string, "failed init connection");
}
} else {
MG_SET_PTRPTR(opts.error_string, "failed create connection");
}
return conn;
}
/*
* Address format: [PROTO://][HOST]:PORT
*
* HOST could be IPv4/IPv6 address or a host name.
* `host` is a destination buffer to hold parsed HOST part. Shoud be at least
* MG_MAX_HOST_LEN bytes long.
* `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
*
* Return:
* -1 on parse error
* 0 if HOST needs DNS lookup
* >0 length of the address string
*/
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
int *proto, char *host, size_t host_len) {
unsigned int a, b, c, d, port = 0;
int ch, len = 0;
#ifdef MG_ENABLE_IPV6
char buf[100];
#endif
/*
* MacOS needs that. If we do not zero it, subsequent bind() will fail.
* Also, all-zeroes in the socket address means binding to all addresses
* for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
*/
memset(sa, 0, sizeof(*sa));
sa->sin.sin_family = AF_INET;
*proto = SOCK_STREAM;
if (strncmp(str, "udp://", 6) == 0) {
str += 6;
*proto = SOCK_DGRAM;
} else if (strncmp(str, "tcp://", 6) == 0) {
str += 6;
}
if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
/* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
sa->sin.sin_addr.s_addr =
htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
sa->sin.sin_port = htons((uint16_t) port);
#ifdef MG_ENABLE_IPV6
} else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
/* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
sa->sin6.sin6_family = AF_INET6;
sa->sin.sin_port = htons((uint16_t) port);
#endif
#ifndef MG_DISABLE_RESOLVER
} else if (strlen(str) < host_len &&
sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
sa->sin.sin_port = htons((uint16_t) port);
if (mg_resolve_from_hosts_file(host, sa) != 0) {
return 0;
}
#endif
} else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
sscanf(str, "%u%n", &port, &len) == 1) {
/* If only port is specified, bind to IPv4, INADDR_ANY */
sa->sin.sin_port = htons((uint16_t) port);
} else {
return -1;
}
ch = str[len]; /* Character that follows the address */
return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
}
#ifdef MG_ENABLE_SSL
/*
* Certificate generation script is at
* https://github.com/cesanta/mongoose/blob/master/scripts/generate_ssl_certificates.sh
*/
#ifndef MG_DISABLE_PFS
/*
* Cipher suite options used for TLS negotiation.
* https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
*/
static const char mg_s_cipher_list[] =
#if defined(MG_SSL_CRYPTO_MODERN)
"ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
"ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
"DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
"ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
"!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
#elif defined(MG_SSL_CRYPTO_OLD)
"ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
"ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
"DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
"ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
"ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
"AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
"HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
"!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
#else /* Default - intermediate. */
"ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
"ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
"DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
"ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
"AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
"DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
"!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
#endif
;
/*
* Default DH params for PFS cipher negotiation. This is a 2048-bit group.
* Will be used if none are provided by the user in the certificate file.
*/
static const char mg_s_default_dh_params[] =
"\
-----BEGIN DH PARAMETERS-----\n\
MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
+E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
-----END DH PARAMETERS-----\n";
#endif
static int mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
if (ctx == NULL) {
return -1;
} else if (cert == NULL || cert[0] == '\0') {
return 0;
}
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2;
}
static int mg_use_cert(SSL_CTX *ctx, const char *pem_file) {
if (ctx == NULL) {
return -1;
} else if (pem_file == NULL || pem_file[0] == '\0') {
return 0;
} else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 ||
SSL_CTX_use_PrivateKey_file(ctx, pem_file, 1) == 0) {
return -2;
} else {
#ifndef MG_DISABLE_PFS
BIO *bio = NULL;
DH *dh = NULL;
/* Try to read DH parameters from the cert/key file. */
bio = BIO_new_file(pem_file, "r");
if (bio != NULL) {
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
BIO_free(bio);
}
/*
* If there are no DH params in the file, fall back to hard-coded ones.
* Not ideal, but better than nothing.
*/
if (dh == NULL) {
bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
BIO_free(bio);
}
if (dh != NULL) {
SSL_CTX_set_tmp_dh(ctx, dh);
SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
DH_free(dh);
}
#endif
SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
SSL_CTX_use_certificate_chain_file(ctx, pem_file);
return 0;
}
}
/*
* Turn the connection into SSL mode.
* `cert` is the certificate file in PEM format. For listening connections,
* certificate file must contain private key and server certificate,
* concatenated. It may also contain DH params - these will be used for more
* secure key exchange. `ca_cert` is a certificate authority (CA) PEM file, and
* it is optional (can be set to NULL). If `ca_cert` is non-NULL, then
* the connection is so-called two-way-SSL: other peer's certificate is
* checked against the `ca_cert`.
*
* Handy OpenSSL command to generate test self-signed certificate:
*
* openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 999
*
* Return NULL on success, or error message on failure.
*/
const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
const char *ca_cert) {
const char *result = NULL;
DBG(("%p %s %s", nc, (cert ? cert : ""), (ca_cert ? ca_cert : "")));
if (nc->ssl != NULL) {
SSL_free(nc->ssl);
nc->ssl = NULL;
}
if (nc->ssl_ctx != NULL) {
SSL_CTX_free(nc->ssl_ctx);
nc->ssl_ctx = NULL;
}
if ((nc->flags & MG_F_LISTENING) &&
(nc->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
result = "SSL_CTX_new() failed";
} else if (!(nc->flags & MG_F_LISTENING) &&
(nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
result = "SSL_CTX_new() failed";
} else if (mg_use_cert(nc->ssl_ctx, cert) != 0) {
result = "Invalid ssl cert";
} else if (mg_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) {
result = "Invalid CA cert";
} else if (!(nc->flags & MG_F_LISTENING) &&
(nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
result = "SSL_new() failed";
} else if (!(nc->flags & MG_F_LISTENING) && nc->sock != INVALID_SOCKET) {
/*
* Socket is open here only if we are connecting to IP address
* and does not open if we are connecting using async DNS resolver
*/
SSL_set_fd(nc->ssl, nc->sock);
}
/* TODO(rojer): remove when krypton exposes this function, even a dummy one */
#ifdef OPENSSL_VERSION_NUMBER
SSL_CTX_set_cipher_list(nc->ssl_ctx, mg_s_cipher_list);
#endif
return result;
}
#endif /* MG_ENABLE_SSL */
struct mg_connection *mg_if_accept_tcp_cb(struct mg_connection *lc,
union socket_address *sa,
size_t sa_len) {
struct mg_add_sock_opts opts;
struct mg_connection *nc;
(void) sa_len;
memset(&opts, 0, sizeof(opts));
nc = mg_create_connection(lc->mgr, lc->handler, opts);
if (nc == NULL) return NULL;
nc->listener = lc;
nc->proto_data = lc->proto_data;
nc->proto_handler = lc->proto_handler;
nc->user_data = lc->user_data;
nc->recv_mbuf_limit = lc->recv_mbuf_limit;
nc->sa = *sa;
mg_add_conn(nc->mgr, nc);
if (lc->ssl_ctx == NULL) {
/* For non-SSL connections deliver MG_EV_ACCEPT right away. */
mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
}
DBG(("%p %p %d %d, %p %p", lc, nc, nc->sock, (int) nc->flags, lc->ssl_ctx,
nc->ssl));
return nc;
}
MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
size_t avail;
if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
return avail > max ? max : avail;
}
void mg_send(struct mg_connection *nc, const void *buf, int len) {
nc->last_io_time = mg_time();
if (nc->flags & MG_F_UDP) {
mg_if_udp_send(nc, buf, len);
} else {
mg_if_tcp_send(nc, buf, len);
}
#if !defined(NO_LIBC) && !defined(MG_DISABLE_HEXDUMP)
if (nc->mgr && nc->mgr->hexdump_file != NULL) {
mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, len, MG_EV_SEND);
}
#endif
}
void mg_if_sent_cb(struct mg_connection *nc, int num_sent) {
if (num_sent < 0) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
mg_call(nc, NULL, MG_EV_SEND, &num_sent);
}
static void mg_recv_common(struct mg_connection *nc, void *buf, int len) {
DBG(("%p %d %u", nc, len, (unsigned int) nc->recv_mbuf.len));
if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
DBG(("%p discarded %d bytes", nc, len));
/*
* This connection will not survive next poll. Do not deliver events,
* send data to /dev/null without acking.
*/
MG_FREE(buf);
return;
}
nc->last_io_time = mg_time();
if (nc->recv_mbuf.len == 0) {
/* Adopt buf as recv_mbuf's backing store. */
mbuf_free(&nc->recv_mbuf);
nc->recv_mbuf.buf = (char *) buf;
nc->recv_mbuf.size = nc->recv_mbuf.len = len;
} else {
size_t avail = recv_avail_size(nc, len);
len = avail;
mbuf_append(&nc->recv_mbuf, buf, len);
MG_FREE(buf);
}
mg_call(nc, NULL, MG_EV_RECV, &len);
}
void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len) {
mg_recv_common(nc, buf, len);
mg_if_recved(nc, len);
}
void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
union socket_address *sa, size_t sa_len) {
assert(nc->flags & MG_F_UDP);
DBG(("%p %u", nc, (unsigned int) len));
if (nc->flags & MG_F_LISTENING) {
struct mg_connection *lc = nc;
/*
* Do we have an existing connection for this source?
* This is very inefficient for long connection lists.
*/
for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
if (memcmp(&nc->sa.sa, &sa->sa, sa_len) == 0) break;
}
if (nc == NULL) {
struct mg_add_sock_opts opts;
memset(&opts, 0, sizeof(opts));
nc = mg_create_connection(lc->mgr, lc->handler, opts);
}
if (nc != NULL) {
nc->sock = lc->sock;
nc->listener = lc;
nc->sa = *sa;
nc->proto_data = lc->proto_data;
nc->proto_handler = lc->proto_handler;
nc->user_data = lc->user_data;
nc->recv_mbuf_limit = lc->recv_mbuf_limit;
nc->flags = MG_F_UDP;
mg_add_conn(lc->mgr, nc);
mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
} else {
DBG(("OOM"));
}
}
if (nc != NULL) {
mg_recv_common(nc, buf, len);
} else {
/* Drop on the floor. */
MG_FREE(buf);
}
mg_if_recved(nc, len);
}
/*
* Schedules an async connect for a resolved address and proto.
* Called from two places: `mg_connect_opt()` and from async resolver.
* When called from the async resolver, it must trigger `MG_EV_CONNECT` event
* with a failure flag to indicate connection failure.
*/
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
int proto,
union socket_address *sa) {
DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
nc->flags |= MG_F_CONNECTING;
if (proto == SOCK_DGRAM) {
mg_if_connect_udp(nc);
} else {
mg_if_connect_tcp(nc, sa);
}
mg_add_conn(nc->mgr, nc);
return nc;
}
void mg_if_connect_cb(struct mg_connection *nc, int err) {
DBG(("%p connect, err=%d", nc, err));
nc->flags &= ~MG_F_CONNECTING;
if (err != 0) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
mg_call(nc, NULL, MG_EV_CONNECT, &err);
}
#ifndef MG_DISABLE_RESOLVER
/*
* Callback for the async resolver on mg_connect_opt() call.
* Main task of this function is to trigger MG_EV_CONNECT event with
* either failure (and dealloc the connection)
* or success (and proceed with connect()
*/
static void resolve_cb(struct mg_dns_message *msg, void *data,
enum mg_resolve_err e) {
struct mg_connection *nc = (struct mg_connection *) data;
int i;
int failure = -1;
nc->flags &= ~MG_F_RESOLVING;
if (msg != NULL) {
/*
* Take the first DNS A answer and run...
*/
for (i = 0; i < msg->num_answers; i++) {
if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
/*
* Async resolver guarantees that there is at least one answer.
* TODO(lsm): handle IPv6 answers too
*/
mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
4);
mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
&nc->sa);
return;
}
}
}
if (e == MG_RESOLVE_TIMEOUT) {
double now = mg_time();
mg_call(nc, NULL, MG_EV_TIMER, &now);
}
/*
* If we get there was no MG_DNS_A_RECORD in the answer
*/
mg_call(nc, NULL, MG_EV_CONNECT, &failure);
mg_call(nc, NULL, MG_EV_CLOSE, NULL);
mg_destroy_conn(nc);
}
#endif
struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
mg_event_handler_t callback) {
struct mg_connect_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_connect_opt(mgr, address, callback, opts);
}
struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
mg_event_handler_t callback,
struct mg_connect_opts opts) {
struct mg_connection *nc = NULL;
int proto, rc;
struct mg_add_sock_opts add_sock_opts;
char host[MG_MAX_HOST_LEN];
MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
return NULL;
} else if ((rc = mg_parse_address(address, &nc->sa, &proto, host,
sizeof(host))) < 0) {
/* Address is malformed */
MG_SET_PTRPTR(opts.error_string, "cannot parse address");
mg_destroy_conn(nc);
return NULL;
}
nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
nc->user_data = opts.user_data;
if (rc == 0) {
#ifndef MG_DISABLE_RESOLVER
/*
* DNS resolution is required for host.
* mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
*/
struct mg_connection *dns_conn = NULL;
struct mg_resolve_async_opts o;
memset(&o, 0, sizeof(o));
o.dns_conn = &dns_conn;
if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc,
o) != 0) {
MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
mg_destroy_conn(nc);
return NULL;
}
nc->priv_2 = dns_conn;
nc->flags |= MG_F_RESOLVING;
return nc;
#else
MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
mg_destroy_conn(nc);
return NULL;
#endif
} else {
/* Address is parsed and resolved to IP. proceed with connect() */
return mg_do_connect(nc, proto, &nc->sa);
}
}
struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
mg_event_handler_t event_handler) {
struct mg_bind_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_bind_opt(srv, address, event_handler, opts);
}
struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
mg_event_handler_t callback,
struct mg_bind_opts opts) {
union socket_address sa;
struct mg_connection *nc = NULL;
int proto, rc;
struct mg_add_sock_opts add_sock_opts;
char host[MG_MAX_HOST_LEN];
MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
MG_SET_PTRPTR(opts.error_string, "cannot parse address");
return NULL;
}
nc = mg_create_connection(mgr, callback, add_sock_opts);
if (nc == NULL) {
return NULL;
}
nc->sa = sa;
nc->flags |= MG_F_LISTENING;
if (proto == SOCK_DGRAM) {
nc->flags |= MG_F_UDP;
rc = mg_if_listen_udp(nc, &nc->sa);
} else {
rc = mg_if_listen_tcp(nc, &nc->sa);
}
if (rc != 0) {
DBG(("Failed to open listener: %d", rc));
MG_SET_PTRPTR(opts.error_string, "failed to open listener");
mg_destroy_conn(nc);
return NULL;
}
mg_add_conn(nc->mgr, nc);
return nc;
}
struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
return conn == NULL ? s->active_connections : conn->next;
}
#ifndef MG_DISABLE_SOCKETPAIR
void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
size_t len) {
struct ctl_msg ctl_msg;
/*
* Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
* where `mg_broadcast()` pushes the message.
* `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
* specified callback for each connection. Thus the callback function executes
* in event manager thread.
*/
if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
len < sizeof(ctl_msg.message)) {
size_t dummy;
ctl_msg.callback = cb;
memcpy(ctl_msg.message, data, len);
dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
offsetof(struct ctl_msg, message) + len, 0);
dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
(void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
}
}
#endif /* MG_DISABLE_SOCKETPAIR */
static int isbyte(int n) {
return n >= 0 && n <= 255;
}
static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
int n, a, b, c, d, slash = 32, len = 0;
if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
slash < 33) {
len = n;
*net =
((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
*mask = slash ? 0xffffffffU << (32 - slash) : 0;
}
return len;
}
int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
int allowed, flag;
uint32_t net, mask;
struct mg_str vec;
/* If any ACL is set, deny by default */
allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
flag = vec.p[0];
if ((flag != '+' && flag != '-') ||
parse_net(&vec.p[1], &net, &mask) == 0) {
return -1;
}
if (net == (remote_ip & mask)) {
allowed = flag;
}
}
return allowed == '+';
}
/* Move data from one connection to another */
void mg_forward(struct mg_connection *from, struct mg_connection *to) {
mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
}
double mg_set_timer(struct mg_connection *c, double timestamp) {
double result = c->ev_timer_time;
c->ev_timer_time = timestamp;
/*
* If this connection is resolving, it's not in the list of active
* connections, so not processed yet. It has a DNS resolver connection
* linked to it. Set up a timer for the DNS connection.
*/
DBG(("%p %p %d -> %lu", c, c->priv_2, c->flags & MG_F_RESOLVING,
(unsigned long) timestamp));
if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
((struct mg_connection *) c->priv_2)->ev_timer_time = timestamp;
}
return result;
}
double mg_time() {
return cs_time();
}
#ifdef NS_MODULE_LINES
#line 1 "./src/net_if_socket.c"
/**/
#endif
#ifndef MG_DISABLE_SOCKET_IF
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
#define MG_TCP_RECV_BUFFER_SIZE 1024
#define MG_UDP_RECV_BUFFER_SIZE 1500
static sock_t mg_open_listening_socket(union socket_address *sa, int proto);
static void mg_sock_set(struct mg_connection *nc, sock_t sock);
#ifdef MG_ENABLE_SSL
static void mg_ssl_begin(struct mg_connection *nc);
static int mg_ssl_err(struct mg_connection *conn, int res);
#endif
void mg_set_non_blocking_mode(sock_t sock) {
#ifdef _WIN32
unsigned long on = 1;
ioctlsocket(sock, FIONBIO, &on);
#elif defined(MG_CC3200)
cc3200_set_non_blocking_mode(sock);
#else
int flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
#endif
}
int mg_is_error(int n) {
#ifdef MG_CC3200
DBG(("n = %d, errno = %d", n, errno));
if (n < 0) errno = n;
#endif
return n == 0 || (n < 0 && errno != EINTR && errno != EINPROGRESS &&
errno != EAGAIN && errno != EWOULDBLOCK
#ifdef MG_CC3200
&& errno != SL_EALREADY
#endif
#ifdef _WIN32
&& WSAGetLastError() != WSAEINTR &&
WSAGetLastError() != WSAEWOULDBLOCK
#endif
);
}
void mg_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
int rc;
nc->sock = socket(AF_INET, SOCK_STREAM, 0);
if (nc->sock < 0) {
nc->sock = INVALID_SOCKET;
nc->err = errno ? errno : 1;
return;
}
#if !defined(MG_CC3200) && !defined(MG_ESP8266)
mg_set_non_blocking_mode(nc->sock);
#endif
rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
nc->err = mg_is_error(rc) ? errno : 0;
DBG(("%p sock %d err %d", nc, nc->sock, nc->err));
}
void mg_if_connect_udp(struct mg_connection *nc) {
nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
if (nc->sock < 0) {
nc->sock = INVALID_SOCKET;
nc->err = errno ? errno : 1;
return;
}
nc->err = 0;
}
int mg_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM);
if (sock < 0) return (errno ? errno : 1);
mg_sock_set(nc, sock);
return 0;
}
int mg_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM);
if (sock < 0) return (errno ? errno : 1);
mg_sock_set(nc, sock);
return 0;
}
void mg_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
void mg_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
DBG(("%p %d %d", nc, (int) len, (int) nc->send_mbuf.len));
mbuf_append(&nc->send_mbuf, buf, len);
}
void mg_if_recved(struct mg_connection *nc, size_t len) {
(void) nc;
(void) len;
}
int mg_if_create_conn(struct mg_connection *nc) {
(void) nc;
return 1;
}
void mg_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
if (!(nc->flags & MG_F_UDP)) {
closesocket(nc->sock);
} else {
/* Only close outgoing UDP sockets or listeners. */
if (nc->listener == NULL) closesocket(nc->sock);
}
/*
* avoid users accidentally double close a socket
* because it can lead to difficult to debug situations.
* It would happen only if reusing a destroyed mg_connection
* but it's not always possible to run the code through an
* address sanitizer.
*/
nc->sock = INVALID_SOCKET;
}
static void mg_accept_conn(struct mg_connection *lc) {
struct mg_connection *nc;
union socket_address sa;
socklen_t sa_len = sizeof(sa);
/* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
if (sock < 0) {
DBG(("%p: failed to accept: %d", lc, errno));
return;
}
nc = mg_if_accept_tcp_cb(lc, &sa, sa_len);
if (nc == NULL) {
closesocket(sock);
return;
}
mg_sock_set(nc, sock);
#ifdef MG_ENABLE_SSL
if (lc->ssl_ctx != NULL) {
nc->ssl = SSL_new(lc->ssl_ctx);
if (nc->ssl == NULL || SSL_set_fd(nc->ssl, sock) != 1) {
DBG(("SSL error"));
mg_close_conn(nc);
}
}
#endif
}
/* 'sa' must be an initialized address to bind to */
static sock_t mg_open_listening_socket(union socket_address *sa, int proto) {
socklen_t sa_len =
(sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
sock_t sock = INVALID_SOCKET;
#if !defined(MG_CC3200) && !defined(MG_LWIP)
int on = 1;
#endif
if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET &&
#if !defined(MG_CC3200) && \
!defined(MG_LWIP) /* CC3200 and LWIP don't support either */
#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE)
/* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
!setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
sizeof(on)) &&
#endif
#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
/*
* SO_RESUSEADDR is not enabled on Windows because the semantics of
* SO_REUSEADDR on UNIX and Windows is different. On Windows,
* SO_REUSEADDR allows to bind a socket to a port without error even if
* the port is already open by another program. This is not the behavior
* SO_REUSEADDR was designed for, and leads to hard-to-track failure
* scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
* SO_EXCLUSIVEADDRUSE is supported and set on a socket.
*/
!setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
#endif
#endif /* !MG_CC3200 && !MG_LWIP */
!bind(sock, &sa->sa, sa_len) &&
(proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
#if !defined(MG_CC3200) && !defined(MG_LWIP) /* TODO(rojer): Fix this. */
mg_set_non_blocking_mode(sock);
/* In case port was set to 0, get the real port number */
(void) getsockname(sock, &sa->sa, &sa_len);
#endif
} else if (sock != INVALID_SOCKET) {
closesocket(sock);
sock = INVALID_SOCKET;
}
return sock;
}
static void mg_write_to_socket(struct mg_connection *nc) {
struct mbuf *io = &nc->send_mbuf;
int n = 0;
#ifdef MG_LWIP
/* With LWIP we don't know if the socket is ready */
if (io->len == 0) return;
#endif
assert(io->len > 0);
if (nc->flags & MG_F_UDP) {
int n =
sendto(nc->sock, io->buf, io->len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
if (n > 0) {
mbuf_remove(io, n);
}
mg_if_sent_cb(nc, n);
return;
}
#ifdef MG_ENABLE_SSL
if (nc->ssl != NULL) {
if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
n = SSL_write(nc->ssl, io->buf, io->len);
if (n <= 0) {
int ssl_err = mg_ssl_err(nc, n);
if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
return; /* Call us again */
}
} else {
/* Successful SSL operation, clear off SSL wait flags */
nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
}
} else {
mg_ssl_begin(nc);
return;
}
} else
#endif
{
n = (int) MG_SEND_FUNC(nc->sock, io->buf, io->len, 0);
}
DBG(("%p %d bytes -> %d", nc, n, nc->sock));
if (n > 0) {
mbuf_remove(io, n);
}
mg_if_sent_cb(nc, n);
}
static void mg_read_from_socket(struct mg_connection *conn) {
int n = 0;
char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
if (buf == NULL) {
DBG(("OOM"));
return;
}
#ifdef MG_ENABLE_SSL
if (conn->ssl != NULL) {
if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
/* SSL library may have more bytes ready to read then we ask to read.
* Therefore, read in a loop until we read everything. Without the loop,
* we skip to the next select() cycle which can just timeout. */
while ((n = SSL_read(conn->ssl, buf, MG_TCP_RECV_BUFFER_SIZE)) > 0) {
DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock));
mg_if_recv_tcp_cb(conn, buf, n);
buf = NULL;
if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break;
/* buf has been freed, we need a new one. */
buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
if (buf == NULL) break;
}
MG_FREE(buf);
mg_ssl_err(conn, n);
} else {
MG_FREE(buf);
mg_ssl_begin(conn);
return;
}
} else
#endif
{
n = (int) MG_RECV_FUNC(conn->sock, buf,
recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
if (n > 0) {
DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock));
mg_if_recv_tcp_cb(conn, buf, n);
} else {
MG_FREE(buf);
}
if (mg_is_error(n)) {
conn->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
}
static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa,
socklen_t *sa_len, char **buf) {
int n;
*buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
if (*buf == NULL) {
DBG(("Out of memory"));
return -ENOMEM;
}
n = recvfrom(nc->sock, *buf, MG_UDP_RECV_BUFFER_SIZE, 0, &sa->sa, sa_len);
if (n <= 0) {
DBG(("%p recvfrom: %s", nc, strerror(errno)));
MG_FREE(*buf);
}
return n;
}
static void mg_handle_udp_read(struct mg_connection *nc) {
char *buf = NULL;
union socket_address sa;
socklen_t sa_len = sizeof(sa);
int n = mg_recvfrom(nc, &sa, &sa_len, &buf);
DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
ntohs(nc->sa.sin.sin_port)));
mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
}
#ifdef MG_ENABLE_SSL
static int mg_ssl_err(struct mg_connection *conn, int res) {
int ssl_err = SSL_get_error(conn->ssl, res);
DBG(("%p %d -> %d", conn, res, ssl_err));
if (ssl_err == SSL_ERROR_WANT_READ) {
conn->flags |= MG_F_WANT_READ;
} else if (ssl_err == SSL_ERROR_WANT_WRITE) {
conn->flags |= MG_F_WANT_WRITE;
} else {
/* There could be an alert to deliver. Try our best. */
SSL_write(conn->ssl, "", 0);
conn->flags |= MG_F_CLOSE_IMMEDIATELY;
}
return ssl_err;
}
static void mg_ssl_begin(struct mg_connection *nc) {
int server_side = nc->listener != NULL;
int res = server_side ? SSL_accept(nc->ssl) : SSL_connect(nc->ssl);
DBG(("%p %d res %d %d %d", nc, server_side, res, errno, mg_ssl_err(nc, res)));
if (res == 1) {
nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
if (server_side) {
union socket_address sa;
socklen_t sa_len = sizeof(sa);
/* In case port was set to 0, get the real port number */
(void) getsockname(nc->sock, &sa.sa, &sa_len);
mg_call(nc, NULL, MG_EV_ACCEPT, &sa);
} else {
mg_if_connect_cb(nc, 0);
}
} else {
int ssl_err = mg_ssl_err(nc, res);
if (ssl_err != SSL_ERROR_WANT_READ && ssl_err != SSL_ERROR_WANT_WRITE) {
if (!server_side) {
mg_if_connect_cb(nc, ssl_err);
}
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
}
#endif /* MG_ENABLE_SSL */
#define _MG_F_FD_CAN_READ 1
#define _MG_F_FD_CAN_WRITE 1 << 1
#define _MG_F_FD_ERROR 1 << 2
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
if (nc->flags & MG_F_CONNECTING) {
if (fd_flags != 0) {
int err = 0;
#if !defined(MG_CC3200) && !defined(MG_ESP8266)
if (!(nc->flags & MG_F_UDP)) {
socklen_t len = sizeof(err);
int ret =
getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
if (ret != 0) err = 1;
}
#else
/* On CC3200 and ESP8266 we use blocking connect. If we got as far as
* this, it means connect() was successful.
* TODO(rojer): Figure out why it fails where blocking succeeds.
*/
#endif
#ifdef MG_ENABLE_SSL
if (nc->ssl != NULL && err == 0) {
SSL_set_fd(nc->ssl, nc->sock);
mg_ssl_begin(nc);
} else {
mg_if_connect_cb(nc, err);
}
#else
mg_if_connect_cb(nc, err);
#endif
} else if (nc->err != 0) {
mg_if_connect_cb(nc, nc->err);
}
}
if (fd_flags & _MG_F_FD_CAN_READ) {
if (nc->flags & MG_F_UDP) {
mg_handle_udp_read(nc);
} else {
if (nc->flags & MG_F_LISTENING) {
/*
* 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.
*/
if (fd_flags & _MG_F_FD_CAN_READ) mg_accept_conn(nc);
return;
} else {
mg_read_from_socket(nc);
}
}
if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return;
}
if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
mg_write_to_socket(nc);
}
if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) {
mg_if_poll(nc, now);
}
mg_if_timer(nc, now);
DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
#ifndef MG_DISABLE_SOCKETPAIR
static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
struct ctl_msg ctl_msg;
int len =
(int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
DBG(("read %d from ctl socket", len));
(void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
struct mg_connection *nc;
for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
ctl_msg.callback(nc, MG_EV_POLL, ctl_msg.message);
}
}
}
#endif
struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
mg_event_handler_t callback) {
struct mg_add_sock_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_add_sock_opt(s, sock, callback, opts);
}
struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
mg_event_handler_t callback,
struct mg_add_sock_opts opts) {
struct mg_connection *nc = mg_create_connection(s, callback, opts);
if (nc != NULL) {
mg_sock_set(nc, sock);
mg_add_conn(nc->mgr, nc);
}
return nc;
}
/* Associate a socket to a connection. */
static void mg_sock_set(struct mg_connection *nc, sock_t sock) {
mg_set_non_blocking_mode(sock);
mg_set_close_on_exec(sock);
nc->sock = sock;
DBG(("%p %d", nc, sock));
}
#if MG_MGR_EV_MGR == 1 /* epoll() */
#ifndef MG_EPOLL_MAX_EVENTS
#define MG_EPOLL_MAX_EVENTS 100
#endif
#define _MG_EPF_EV_EPOLLIN (1 << 0)
#define _MG_EPF_EV_EPOLLOUT (1 << 1)
#define _MG_EPF_NO_POLL (1 << 2)
uint32_t mg_epf_to_evflags(unsigned int epf) {
uint32_t result = 0;
if (epf & _MG_EPF_EV_EPOLLIN) result |= EPOLLIN;
if (epf & _MG_EPF_EV_EPOLLOUT) result |= EPOLLOUT;
return result;
}
void mg_ev_mgr_epoll_set_flags(const struct mg_connection *nc,
struct epoll_event *ev) {
/* NOTE: EPOLLERR and EPOLLHUP are always enabled. */
ev->events = 0;
if ((nc->flags & MG_F_LISTENING) || nc->recv_mbuf.len < nc->recv_mbuf_limit) {
ev->events |= EPOLLIN;
}
if ((nc->flags & MG_F_CONNECTING) || (nc->send_mbuf.len > 0)) {
ev->events |= EPOLLOUT;
}
}
void mg_ev_mgr_epoll_ctl(struct mg_connection *nc, int op) {
int epoll_fd = (intptr_t) nc->mgr->mgr_data;
struct epoll_event ev;
assert(op == EPOLL_CTL_ADD || op == EPOLL_CTL_MOD || EPOLL_CTL_DEL);
DBG(("%p %d %d", nc, nc->sock, op));
if (nc->sock == INVALID_SOCKET) return;
if (op != EPOLL_CTL_DEL) {
mg_ev_mgr_epoll_set_flags(nc, &ev);
if (op == EPOLL_CTL_MOD) {
uint32_t old_ev_flags = mg_epf_to_evflags((intptr_t) nc->mgr_data);
if (ev.events == old_ev_flags) return;
}
ev.data.ptr = nc;
}
if (epoll_ctl(epoll_fd, op, nc->sock, &ev) != 0) {
perror("epoll_ctl");
abort();
}
}
void mg_ev_mgr_init(struct mg_mgr *mgr) {
int epoll_fd;
DBG(("%p using epoll()", mgr));
#ifndef MG_DISABLE_SOCKETPAIR
do {
mg_socketpair(mgr->ctl, SOCK_DGRAM);
} while (mgr->ctl[0] == INVALID_SOCKET);
#endif
epoll_fd = epoll_create(MG_EPOLL_MAX_EVENTS /* unused but required */);
if (epoll_fd < 0) {
perror("epoll_ctl");
abort();
}
mgr->mgr_data = (void *) ((intptr_t) epoll_fd);
if (mgr->ctl[1] != INVALID_SOCKET) {
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.ptr = NULL;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, mgr->ctl[1], &ev) != 0) {
perror("epoll_ctl");
abort();
}
}
}
void mg_ev_mgr_free(struct mg_mgr *mgr) {
int epoll_fd = (intptr_t) mgr->mgr_data;
close(epoll_fd);
}
void mg_ev_mgr_add_conn(struct mg_connection *nc) {
if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_ADD);
}
}
void mg_ev_mgr_remove_conn(struct mg_connection *nc) {
if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_DEL);
}
}
time_t mg_mgr_poll(struct mg_mgr *mgr, int timeout_ms) {
int epoll_fd = (intptr_t) mgr->mgr_data;
struct epoll_event events[MG_EPOLL_MAX_EVENTS];
struct mg_connection *nc, *next;
int num_ev, fd_flags;
double now;
num_ev = epoll_wait(epoll_fd, events, MG_EPOLL_MAX_EVENTS, timeout_ms);
now = mg_time();
DBG(("epoll_wait @ %ld num_ev=%d", (long) now, num_ev));
while (num_ev-- > 0) {
intptr_t epf;
struct epoll_event *ev = events + num_ev;
nc = (struct mg_connection *) ev->data.ptr;
if (nc == NULL) {
mg_mgr_handle_ctl_sock(mgr);
continue;
}
fd_flags = ((ev->events & (EPOLLIN | EPOLLHUP)) ? _MG_F_FD_CAN_READ : 0) |
((ev->events & (EPOLLOUT)) ? _MG_F_FD_CAN_WRITE : 0) |
((ev->events & (EPOLLERR)) ? _MG_F_FD_ERROR : 0);
mg_mgr_handle_conn(nc, fd_flags, now);
epf = (intptr_t) nc->mgr_data;
epf ^= _MG_EPF_NO_POLL;
nc->mgr_data = (void *) epf;
}
for (nc = mgr->active_connections; nc != NULL; nc = next) {
next = nc->next;
if (!(((intptr_t) nc->mgr_data) & _MG_EPF_NO_POLL)) {
mg_mgr_handle_conn(nc, 0, now);
} else {
intptr_t epf = (intptr_t) nc->mgr_data;
epf ^= _MG_EPF_NO_POLL;
nc->mgr_data = (void *) epf;
}
if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
(nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
mg_close_conn(nc);
} else {
if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
mg_ev_mgr_epoll_ctl(nc, EPOLL_CTL_MOD);
} else {
/* This is a kludge, but... */
if (nc->send_mbuf.len > 0) {
mg_mgr_handle_conn(nc, _MG_F_FD_CAN_WRITE, now);
}
}
}
}
return now;
}
#else /* select() */
void mg_ev_mgr_init(struct mg_mgr *mgr) {
(void) mgr;
DBG(("%p using select()", mgr));
#ifndef MG_DISABLE_SOCKETPAIR
do {
mg_socketpair(mgr->ctl, SOCK_DGRAM);
} while (mgr->ctl[0] == INVALID_SOCKET);
#endif
}
void mg_ev_mgr_free(struct mg_mgr *mgr) {
(void) mgr;
}
void mg_ev_mgr_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_ev_mgr_remove_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_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 mg_mgr_poll(struct mg_mgr *mgr, int milli) {
double now = mg_time();
struct mg_connection *nc, *tmp;
struct timeval tv;
fd_set read_set, write_set, err_set;
sock_t max_fd = INVALID_SOCKET;
int num_fds, num_selected;
FD_ZERO(&read_set);
FD_ZERO(&write_set);
FD_ZERO(&err_set);
#ifndef MG_DISABLE_SOCKETPAIR
mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
#endif
for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
tmp = nc->next;
if (nc->sock == INVALID_SOCKET) {
mg_mgr_handle_conn(nc, 0, now);
continue;
}
num_fds++;
if (!(nc->flags & MG_F_WANT_WRITE) &&
nc->recv_mbuf.len < nc->recv_mbuf_limit &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
mg_add_to_set(nc->sock, &read_set, &max_fd);
}
if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
(nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
mg_add_to_set(nc->sock, &write_set, &max_fd);
mg_add_to_set(nc->sock, &err_set, &max_fd);
}
}
tv.tv_sec = milli / 1000;
tv.tv_usec = (milli % 1000) * 1000;
num_selected = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
now = mg_time();
DBG(("select @ %ld num_ev=%d of %d", (long) now, num_selected, num_fds));
#ifndef MG_DISABLE_SOCKETPAIR
if (num_selected > 0 && mgr->ctl[1] != INVALID_SOCKET &&
FD_ISSET(mgr->ctl[1], &read_set)) {
mg_mgr_handle_ctl_sock(mgr);
}
#endif
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
int fd_flags = 0;
if (num_selected > 0) {
fd_flags = (FD_ISSET(nc->sock, &read_set) ? _MG_F_FD_CAN_READ : 0) |
(FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
(FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
}
#ifdef MG_CC3200
// CC3200 does not report UDP sockets as writeable.
if (nc->flags & MG_F_UDP &&
(nc->send_mbuf.len > 0 || nc->flags & MG_F_CONNECTING)) {
fd_flags |= _MG_F_FD_CAN_WRITE;
}
#endif
#ifdef MG_LWIP
/* With LWIP socket emulation layer, we don't get write events */
fd_flags |= _MG_F_FD_CAN_WRITE;
#endif
tmp = nc->next;
mg_mgr_handle_conn(nc, fd_flags, now);
}
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
(nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
mg_close_conn(nc);
}
}
return now;
}
#endif
#ifndef MG_DISABLE_SOCKETPAIR
int mg_socketpair(sock_t sp[2], int sock_type) {
union socket_address sa;
sock_t sock;
socklen_t len = sizeof(sa.sin);
int ret = 0;
sock = sp[0] = sp[1] = INVALID_SOCKET;
(void) memset(&sa, 0, sizeof(sa));
sa.sin.sin_family = AF_INET;
sa.sin.sin_port = htons(0);
sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
} else if (bind(sock, &sa.sa, len) != 0) {
} else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
} else if (getsockname(sock, &sa.sa, &len) != 0) {
} else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
} else if (connect(sp[0], &sa.sa, len) != 0) {
} else if (sock_type == SOCK_DGRAM &&
(getsockname(sp[0], &sa.sa, &len) != 0 ||
connect(sock, &sa.sa, len) != 0)) {
} else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock
: accept(sock, &sa.sa, &len))) ==
INVALID_SOCKET) {
} else {
mg_set_close_on_exec(sp[0]);
mg_set_close_on_exec(sp[1]);
if (sock_type == SOCK_STREAM) closesocket(sock);
ret = 1;
}
if (!ret) {
if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
if (sock != INVALID_SOCKET) closesocket(sock);
sock = sp[0] = sp[1] = INVALID_SOCKET;
}
return ret;
}
#endif /* MG_DISABLE_SOCKETPAIR */
static void mg_sock_get_addr(sock_t sock, int remote,
union socket_address *sa) {
#ifndef MG_CC3200
socklen_t slen = sizeof(sa);
memset(sa, 0, sizeof(*sa));
if (remote) {
getpeername(sock, &sa->sa, &slen);
} else {
getsockname(sock, &sa->sa, &slen);
}
#else
memset(sa, 0, sizeof(*sa));
#endif
}
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
union socket_address sa;
mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
mg_sock_addr_to_str(&sa, buf, len, flags);
}
void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
mg_sock_get_addr(nc->sock, remote, sa);
}
#endif /* !MG_DISABLE_SOCKET_IF */
#ifdef NS_MODULE_LINES
#line 1 "./src/multithreading.c"
/**/
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
#ifdef MG_ENABLE_THREADS
static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p);
/*
* This thread function executes user event handler.
* It runs an event manager that has only one connection, until that
* connection is alive.
*/
static void *per_connection_thread_function(void *param) {
struct mg_connection *c = (struct mg_connection *) param;
struct mg_mgr m;
mg_mgr_init(&m, NULL);
mg_add_conn(&m, c);
while (m.active_connections != NULL) {
mg_mgr_poll(&m, 1000);
}
mg_mgr_free(&m);
return param;
}
static void link_conns(struct mg_connection *c1, struct mg_connection *c2) {
c1->priv_2 = c2;
c2->priv_2 = c1;
}
static void unlink_conns(struct mg_connection *c) {
struct mg_connection *peer = (struct mg_connection *) c->priv_2;
if (peer != NULL) {
peer->flags |= MG_F_SEND_AND_CLOSE;
peer->priv_2 = NULL;
}
c->priv_2 = NULL;
}
static void forwarder_ev_handler(struct mg_connection *c, int ev, void *p) {
(void) p;
if (ev == MG_EV_RECV && c->priv_2) {
mg_forward(c, (struct mg_connection *) c->priv_2);
} else if (ev == MG_EV_CLOSE) {
unlink_conns(c);
}
}
static void spawn_handling_thread(struct mg_connection *nc) {
struct mg_mgr dummy;
sock_t sp[2];
struct mg_connection *c[2];
/*
* Create a socket pair, and wrap each socket into the connection with
* dummy event manager.
* c[0] stays in this thread, c[1] goes to another thread.
*/
mg_socketpair(sp, SOCK_STREAM);
memset(&dummy, 0, sizeof(dummy));
c[0] = mg_add_sock(&dummy, sp[0], forwarder_ev_handler);
c[1] = mg_add_sock(&dummy, sp[1], (mg_event_handler_t) nc->listener->priv_1);
/* Interlink client connection with c[0] */
link_conns(c[0], nc);
/*
* Switch c[0] manager from the dummy one to the real one. c[1] manager
* will be set in another thread, allocated on stack of that thread.
*/
mg_add_conn(nc->mgr, c[0]);
/*
* Dress c[1] as nc.
* TODO(lsm): code in accept_conn() looks similar. Refactor.
*/
c[1]->listener = nc->listener;
c[1]->proto_handler = nc->proto_handler;
c[1]->proto_data = nc->proto_data;
c[1]->user_data = nc->user_data;
mg_start_thread(per_connection_thread_function, c[1]);
}
static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p) {
(void) p;
if (ev == MG_EV_ACCEPT) {
spawn_handling_thread(c);
c->handler = forwarder_ev_handler;
}
}
void mg_enable_multithreading(struct mg_connection *nc) {
/* Wrap user event handler into our multithreaded_ev_handler */
nc->priv_1 = (void *) nc->handler;
nc->handler = multithreaded_ev_handler;
}
#endif
#ifdef NS_MODULE_LINES
#line 1 "./src/http.c"
/**/
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#ifndef MG_DISABLE_HTTP
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
/* Amalgamated: #include "common/sha1.h" */
/* Amalgamated: #include "common/md5.h" */
enum http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT, DATA_CGI };
struct proto_data_http {
FILE *fp; /* Opened file. */
int64_t cl; /* Content-Length. How many bytes to send. */
int64_t sent; /* How many bytes have been already sent. */
int64_t body_len; /* How many bytes of chunked body was reassembled. */
struct mg_connection *cgi_nc;
enum http_proto_data_type type;
};
/*
* This structure helps to create an environment for the spawned CGI program.
* Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
* last element must be NULL.