5#line 1 "mongoose/src/mg_internal.h"
12#ifndef CS_MONGOOSE_SRC_INTERNAL_H_
13#define CS_MONGOOSE_SRC_INTERNAL_H_
18#define MBUF_REALLOC MG_REALLOC
22#define MBUF_FREE MG_FREE
25#define MG_SET_PTRPTR(_ptr, _v) \
27 if (_ptr) *(_ptr) = _v; \
31#define MG_INTERNAL static
43#ifndef MG_CTL_MSG_MESSAGE_SIZE
44#define MG_CTL_MSG_MESSAGE_SIZE 8192
53 int *proto,
char *host,
size_t host_len);
65int to_wchar(
const char *path,
wchar_t *wbuf,
size_t wbuf_len);
76#define MG_MQTT_ERROR_INCOMPLETE_MSG -1
77#define MG_MQTT_ERROR_MALFORMED_MSG -2
83extern void *(*test_malloc)(
size_t size);
84extern void *(*test_calloc)(
size_t count,
size_t size);
87#define MIN(a, b) ((a) < (b) ? (a) : (b))
111#if MG_ENABLE_FILESYSTEM
115 struct mg_str *remainder);
119#if MG_ENABLE_HTTP_CGI
121 const struct mg_str *path_info,
127#if MG_ENABLE_HTTP_SSI
133#if MG_ENABLE_HTTP_WEBDAV
150#if MG_ENABLE_HTTP_WEBSOCKET
152 void *ev_data
MG_UD_ARG(
void *user_data));
164MG_INTERNAL int mg_sntp_parse_reply(
const char *buf,
int len,
165 struct mg_sntp_message *msg);
169#ifdef MG_MODULE_LINES
170#line 1 "common/mg_mem.h"
189#ifndef CS_COMMON_MG_MEM_H_
190#define CS_COMMON_MG_MEM_H_
197#define MG_MALLOC malloc
201#define MG_CALLOC calloc
205#define MG_REALLOC realloc
217#ifdef MG_MODULE_LINES
218#line 1 "common/cs_base64.c"
237#ifndef EXCLUDE_COMMON
247#define NUM_UPPERCASES ('Z' - 'A' + 1)
248#define NUM_LETTERS (NUM_UPPERCASES * 2)
249#define NUM_DIGITS ('9' - '0' + 1)
294 const unsigned char *src = (
const unsigned char *)
str;
296 for (
i = 0;
i < len;
i++) {
316#define BASE64_ENCODE_BODY \
317 static const char *b64 = \
318 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
321 for (i = j = 0; i < src_len; i += 3) { \
323 b = i + 1 >= src_len ? 0 : src[i + 1]; \
324 c = i + 2 >= src_len ? 0 : src[i + 2]; \
326 BASE64_OUT(b64[a >> 2]); \
327 BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \
328 if (i + 1 < src_len) { \
329 BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \
331 if (i + 2 < src_len) { \
332 BASE64_OUT(b64[c & 63]); \
336 while (j % 4 != 0) { \
341#define BASE64_OUT(ch) \
346#define BASE64_FLUSH() \
359#define BASE64_OUT(ch) \
361 fprintf(f, "%c", (ch)); \
365#define BASE64_FLUSH()
378 static const unsigned char tab[128] = {
412 return tab[ch & 127];
416 unsigned char a, b,
c,
d;
418 char *orig_dst = dst;
419 while (len >= 4 && (a =
from_b64(s[0])) != 255 &&
424 if (a == 200 || b == 200)
break;
425 *dst++ = a << 2 | b >> 4;
427 *dst++ = b << 4 | c >> 2;
432 if (dec_len != NULL) *dec_len = (dst - orig_dst);
433 return orig_len - len;
437#ifdef MG_MODULE_LINES
438#line 1 "common/cs_dbg.h"
457#ifndef CS_COMMON_CS_DBG_H_
458#define CS_COMMON_CS_DBG_H_
466#ifndef CS_ENABLE_DEBUG
467#define CS_ENABLE_DEBUG 0
470#ifndef CS_LOG_PREFIX_LEN
471#define CS_LOG_PREFIX_LEN 24
474#ifndef CS_LOG_ENABLE_TS_DIFF
475#define CS_LOG_ENABLE_TS_DIFF 0
552 if (cs_log_print_prefix(l, __FILE__, __LINE__)) { \
559#define LOG(l, x) ((void) l)
568#define DBG(x) LOG(LL_VERBOSE_DEBUG, x)
588#ifdef MG_MODULE_LINES
589#line 1 "common/cs_dbg.c"
625static char *s_file_level = NULL;
631#if CS_LOG_ENABLE_TS_DIFF
632double cs_log_ts
WEAK;
638 char *fl = s_file_level;
639 if (file_level != NULL) {
640 s_file_level = strdup(file_level);
651 size_t fl = 0, ll = 0, pl = 0;
653 if (level >
cs_log_level && s_file_level == NULL)
return 0;
658 const char c = *(p - 1);
659 if (
c ==
'/' ||
c ==
'\\')
break;
664 ll = (ln < 10000 ? (ln < 1000 ? (ln < 100 ? (ln < 10 ? 1 : 2) : 3) : 4) : 5);
665 if (fl > (
sizeof(prefix) - ll - 2)) fl = (
sizeof(prefix) - ll - 2);
668 memcpy(prefix, p, fl);
670 memset(
q,
' ',
sizeof(prefix) - pl);
672 *(--
q) =
'0' + (ln % 10);
677 if (s_file_level != NULL) {
687 if (level > pll)
return 0;
691 cs_log_cur_msg_level = level;
693#if CS_LOG_ENABLE_TS_DIFF
696 fprintf(
cs_log_file,
"%7u ", (
unsigned int) ((now - cs_log_ts) * 1000000));
711 cs_log_cur_msg_level =
LL_NONE;
730#if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO
734#ifdef MG_MODULE_LINES
735#line 1 "common/cs_dirent.h"
754#ifndef CS_COMMON_CS_DIRENT_H_
755#define CS_COMMON_CS_DIRENT_H_
765#ifdef CS_DEFINE_DIRENT
766typedef struct {
int dummy; }
DIR;
771 char d_name[MAX_PATH];
778DIR *opendir(
const char *dir_name);
779int closedir(
DIR *dir);
780struct dirent *readdir(
DIR *dir);
788#ifdef MG_MODULE_LINES
789#line 1 "common/cs_dirent.c"
808#ifndef EXCLUDE_COMMON
822 WIN32_FIND_DATAW
info;
823 struct dirent result;
826DIR *opendir(
const char *
name) {
827 struct win32_dir *dir = NULL;
828 wchar_t wpath[MAX_PATH];
832 SetLastError(ERROR_BAD_ARGUMENTS);
833 }
else if ((dir = (
struct win32_dir *)
MG_MALLOC(
sizeof(*dir))) == NULL) {
834 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
837 attrs = GetFileAttributesW(wpath);
838 if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
839 (void) wcscat(wpath, L
"\\*");
840 dir->handle = FindFirstFileW(wpath, &dir->info);
841 dir->result.d_name[0] =
'\0';
851int closedir(
DIR *
d) {
852 struct win32_dir *dir = (
struct win32_dir *)
d;
856 if (dir->handle != INVALID_HANDLE_VALUE)
857 result = FindClose(dir->handle) ? 0 : -1;
861 SetLastError(ERROR_BAD_ARGUMENTS);
867struct dirent *readdir(
DIR *
d) {
868 struct win32_dir *dir = (
struct win32_dir *)
d;
869 struct dirent *result = NULL;
872 memset(&dir->result, 0,
sizeof(dir->result));
873 if (dir->handle != INVALID_HANDLE_VALUE) {
874 result = &dir->result;
875 (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
876 result->d_name,
sizeof(result->d_name), NULL,
879 if (!FindNextFileW(dir->handle, &dir->info)) {
880 (void) FindClose(dir->handle);
881 dir->handle = INVALID_HANDLE_VALUE;
885 SetLastError(ERROR_FILE_NOT_FOUND);
888 SetLastError(ERROR_BAD_ARGUMENTS);
899#ifdef MG_MODULE_LINES
900#line 1 "common/cs_time.c"
926#if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \
927 !defined(__TI_COMPILER_VERSION__) && \
928 (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC)
941 now = (double)
tv.tv_sec + (((
double)
tv.tv_usec) / 1000000.0);
945 GetLocalTime(&sysnow);
946 SystemTimeToFileTime(&sysnow, &ftime);
955 now = (double) (((int64_t) ftime.dwLowDateTime +
956 ((int64_t) ftime.dwHighDateTime << 32)) /
965 static const int month_day[12] = {0, 31, 59, 90, 120, 151,
966 181, 212, 243, 273, 304, 334};
969 int month =
tm->tm_mon % 12;
970 int year =
tm->tm_year +
tm->tm_mon / 12;
980 year_for_leap = (month > 1) ? year + 1 : year;
990 24 * (month_day[month] +
tm->tm_mday - 1
992 + (year_for_leap - 69) / 4
993 - (year_for_leap - 1) / 100
994 + (year_for_leap + 299) / 400)));
995 return rt < 0 ? -1 : (double) rt;
997#ifdef MG_MODULE_LINES
998#line 1 "common/cs_endian.h"
1017#ifndef CS_COMMON_CS_ENDIAN_H_
1018#define CS_COMMON_CS_ENDIAN_H_
1029#if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
1030#define BYTE_ORDER __BYTE_ORDER
1031#ifndef LITTLE_ENDIAN
1032#define LITTLE_ENDIAN __LITTLE_ENDIAN
1035#define BIG_ENDIAN __LITTLE_ENDIAN
1044#ifdef MG_MODULE_LINES
1045#line 1 "common/cs_md5.c"
1067#if !defined(EXCLUDE_COMMON)
1074#if BYTE_ORDER == BIG_ENDIAN
1076 uint32_t t = (uint32_t)((
unsigned) buf[3] << 8 | buf[2]) << 16 |
1077 ((
unsigned) buf[1] << 8 | buf[0]);
1078 *(uint32_t *) buf = t;
1087#define F1(x, y, z) (z ^ (x & (y ^ z)))
1088#define F2(x, y, z) F1(z, x, y)
1089#define F3(x, y, z) (x ^ y ^ z)
1090#define F4(x, y, z) (y ^ (x | ~z))
1092#define MD5STEP(f, w, x, y, z, data, s) \
1093 (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
1100 ctx->
buf[0] = 0x67452301;
1101 ctx->
buf[1] = 0xefcdab89;
1102 ctx->
buf[2] = 0x98badcfe;
1103 ctx->
buf[3] = 0x10325476;
1110 uint32_t a, b,
c,
d;
1195 if ((ctx->
bits[0] = t + ((uint32_t) len << 3)) < t) ctx->
bits[1]++;
1196 ctx->
bits[1] += (uint32_t) len >> 29;
1198 t = (t >> 3) & 0x3f;
1201 unsigned char *p = (
unsigned char *) ctx->
in + t;
1205 memcpy(p, buf, len);
1216 memcpy(ctx->
in, buf, 64);
1223 memcpy(ctx->
in, buf, len);
1237 memset(p, 0,
count);
1240 memset(ctx->
in, 0, 56);
1242 memset(p, 0,
count - 8);
1246 a = (uint32_t *) ctx->
in;
1247 a[14] = ctx->
bits[0];
1248 a[15] = ctx->
bits[1];
1252 memcpy(digest, ctx->
buf, 16);
1253 memset((
char *) ctx, 0,
sizeof(*ctx));
1258#ifdef MG_MODULE_LINES
1259#line 1 "common/cs_sha1.c"
1266#if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON)
1276 unsigned char c[64];
1280#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
1284#if BYTE_ORDER == LITTLE_ENDIAN
1286 (
rol(block->
l[
i], 24) & 0xFF00FF00) | (
rol(block->
l[
i], 8) & 0x00FF00FF);
1300 (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
1301 block->l[(i + 2) & 15] ^ block->l[i & 15], \
1303#define R0(v, w, x, y, z, i) \
1304 z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
1306#define R1(v, w, x, y, z, i) \
1307 z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
1309#define R2(v, w, x, y, z, i) \
1310 z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
1312#define R3(v, w, x, y, z, i) \
1313 z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
1315#define R4(v, w, x, y, z, i) \
1316 z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
1320 uint32_t a, b,
c,
d,
e;
1323 memcpy(block, buffer, 64);
1329 R0(a, b,
c,
d,
e, 0);
1330 R0(
e, a, b,
c,
d, 1);
1331 R0(
d,
e, a, b,
c, 2);
1332 R0(
c,
d,
e, a, b, 3);
1333 R0(b,
c,
d,
e, a, 4);
1334 R0(a, b,
c,
d,
e, 5);
1335 R0(
e, a, b,
c,
d, 6);
1336 R0(
d,
e, a, b,
c, 7);
1337 R0(
c,
d,
e, a, b, 8);
1338 R0(b,
c,
d,
e, a, 9);
1339 R0(a, b,
c,
d,
e, 10);
1340 R0(
e, a, b,
c,
d, 11);
1341 R0(
d,
e, a, b,
c, 12);
1342 R0(
c,
d,
e, a, b, 13);
1343 R0(b,
c,
d,
e, a, 14);
1344 R0(a, b,
c,
d,
e, 15);
1345 R1(
e, a, b,
c,
d, 16);
1346 R1(
d,
e, a, b,
c, 17);
1347 R1(
c,
d,
e, a, b, 18);
1348 R1(b,
c,
d,
e, a, 19);
1349 R2(a, b,
c,
d,
e, 20);
1350 R2(
e, a, b,
c,
d, 21);
1351 R2(
d,
e, a, b,
c, 22);
1352 R2(
c,
d,
e, a, b, 23);
1353 R2(b,
c,
d,
e, a, 24);
1354 R2(a, b,
c,
d,
e, 25);
1355 R2(
e, a, b,
c,
d, 26);
1356 R2(
d,
e, a, b,
c, 27);
1357 R2(
c,
d,
e, a, b, 28);
1358 R2(b,
c,
d,
e, a, 29);
1359 R2(a, b,
c,
d,
e, 30);
1360 R2(
e, a, b,
c,
d, 31);
1361 R2(
d,
e, a, b,
c, 32);
1362 R2(
c,
d,
e, a, b, 33);
1363 R2(b,
c,
d,
e, a, 34);
1364 R2(a, b,
c,
d,
e, 35);
1365 R2(
e, a, b,
c,
d, 36);
1366 R2(
d,
e, a, b,
c, 37);
1367 R2(
c,
d,
e, a, b, 38);
1368 R2(b,
c,
d,
e, a, 39);
1369 R3(a, b,
c,
d,
e, 40);
1370 R3(
e, a, b,
c,
d, 41);
1371 R3(
d,
e, a, b,
c, 42);
1372 R3(
c,
d,
e, a, b, 43);
1373 R3(b,
c,
d,
e, a, 44);
1374 R3(a, b,
c,
d,
e, 45);
1375 R3(
e, a, b,
c,
d, 46);
1376 R3(
d,
e, a, b,
c, 47);
1377 R3(
c,
d,
e, a, b, 48);
1378 R3(b,
c,
d,
e, a, 49);
1379 R3(a, b,
c,
d,
e, 50);
1380 R3(
e, a, b,
c,
d, 51);
1381 R3(
d,
e, a, b,
c, 52);
1382 R3(
c,
d,
e, a, b, 53);
1383 R3(b,
c,
d,
e, a, 54);
1384 R3(a, b,
c,
d,
e, 55);
1385 R3(
e, a, b,
c,
d, 56);
1386 R3(
d,
e, a, b,
c, 57);
1387 R3(
c,
d,
e, a, b, 58);
1388 R3(b,
c,
d,
e, a, 59);
1389 R4(a, b,
c,
d,
e, 60);
1390 R4(
e, a, b,
c,
d, 61);
1391 R4(
d,
e, a, b,
c, 62);
1392 R4(
c,
d,
e, a, b, 63);
1393 R4(b,
c,
d,
e, a, 64);
1394 R4(a, b,
c,
d,
e, 65);
1395 R4(
e, a, b,
c,
d, 66);
1396 R4(
d,
e, a, b,
c, 67);
1397 R4(
c,
d,
e, a, b, 68);
1398 R4(b,
c,
d,
e, a, 69);
1399 R4(a, b,
c,
d,
e, 70);
1400 R4(
e, a, b,
c,
d, 71);
1401 R4(
d,
e, a, b,
c, 72);
1402 R4(
c,
d,
e, a, b, 73);
1403 R4(b,
c,
d,
e, a, 74);
1404 R4(a, b,
c,
d,
e, 75);
1405 R4(
e, a, b,
c,
d, 76);
1406 R4(
d,
e, a, b,
c, 77);
1407 R4(
c,
d,
e, a, b, 78);
1408 R4(b,
c,
d,
e, a, 79);
1416 memset(block, 0,
sizeof(block));
1417 a = b =
c =
d =
e = 0;
1426 context->
state[0] = 0x67452301;
1427 context->
state[1] = 0xEFCDAB89;
1428 context->
state[2] = 0x98BADCFE;
1429 context->
state[3] = 0x10325476;
1430 context->
state[4] = 0xC3D2E1F0;
1439 if ((context->
count[0] += len << 3) <
j) context->
count[1]++;
1440 context->
count[1] += (len >> 29);
1442 if ((
j + len) > 63) {
1445 for (;
i + 63 < len;
i += 64) {
1456 unsigned char finalcount[8],
c;
1458 for (
i = 0;
i < 8;
i++) {
1459 finalcount[
i] = (
unsigned char) ((context->
count[(
i >= 4 ? 0 : 1)] >>
1460 ((3 - (
i & 3)) * 8)) &
1465 while ((context->
count[0] & 504) != 448) {
1470 for (
i = 0;
i < 20;
i++) {
1472 (
unsigned char) ((context->
state[
i >> 2] >> ((3 - (
i & 3)) * 8)) & 255);
1474 memset(context,
'\0',
sizeof(*context));
1475 memset(&finalcount,
'\0',
sizeof(finalcount));
1479 const unsigned char *
data,
size_t datalen,
1480 unsigned char out[20]) {
1482 unsigned char buf1[64], buf2[64], tmp_key[20],
i;
1484 if (keylen >
sizeof(buf1)) {
1489 keylen =
sizeof(tmp_key);
1492 memset(buf1, 0,
sizeof(buf1));
1493 memset(buf2, 0,
sizeof(buf2));
1494 memcpy(buf1,
key, keylen);
1495 memcpy(buf2,
key, keylen);
1497 for (
i = 0;
i <
sizeof(buf1);
i++) {
1514#ifdef MG_MODULE_LINES
1515#line 1 "common/mbuf.c"
1534#ifndef EXCLUDE_COMMON
1541#define MBUF_REALLOC realloc
1545#define MBUF_FREE free
1565 if (new_size > a->
size || (new_size < a->size && new_size >= a->
len)) {
1572 if (buf == NULL && new_size != 0)
return;
1589 assert(off <= a->len);
1592 if (~(
size_t) 0 - (
size_t) a->
buf < len)
return 0;
1594 if (a->
len + len <= a->size) {
1595 memmove(a->
buf + off + len, a->
buf + off, a->
len - off);
1597 memcpy(a->
buf + off, buf, len);
1601 size_t min_size = (a->
len + len);
1607 if (p == NULL && new_size != min_size) {
1608 new_size = min_size;
1613 if (off != a->
len) {
1614 memmove(a->
buf + off + len, a->
buf + off, a->
len - off);
1616 if (buf != NULL) memcpy(a->
buf + off, buf, len);
1638 if (a->
buf != NULL) free(a->
buf);
1650 if (
n > 0 && n <= mb->len) {
1663 memcpy(to, from,
sizeof(*to));
1664 memset(from, 0,
sizeof(*from));
1668#ifdef MG_MODULE_LINES
1669#line 1 "common/mg_str.c"
1700 struct mg_str ret = {s, 0};
1701 if (s != NULL) ret.
len = strlen(s);
1713 size_t n2 = strlen(str2), n1 = str1->
len;
1714 int r = strncmp(str1->
p, str2, (n1 < n2) ? n1 : n2);
1723 size_t n2 = strlen(str2), n1 = str1->
len;
1724 int r =
mg_ncasecmp(str1->
p, str2, (n1 < n2) ? n1 : n2);
1732 int nul_terminate) {
1733 struct mg_str r = {NULL, 0};
1734 if (s.
len > 0 && s.
p != NULL) {
1735 char *sc = (
char *)
MG_MALLOC(s.
len + (nul_terminate ? 1 : 0));
1737 memcpy(sc, s.
p, s.
len);
1738 if (nul_terminate) sc[s.
len] =
'\0';
1759 for (
i = 0;
i < s.
len;
i++) {
1760 if (s.
p[
i] ==
c)
return &s.
p[
i];
1768 while (
i < str1.
len &&
i < str2.
len) {
1769 if (str1.
p[
i] < str2.
p[
i])
return -1;
1770 if (str1.
p[
i] > str2.
p[
i])
return 1;
1773 if (
i < str1.
len)
return 1;
1774 if (
i < str2.
len)
return -1;
1794 char *sp = (
char *) s->
p;
1797 if (sp != NULL) free(sp);
1803 const struct mg_str needle) {
1805 if (needle.
len > haystack.
len)
return NULL;
1806 for (
i = 0;
i <= haystack.
len - needle.
len;
i++) {
1807 if (memcmp(haystack.
p +
i, needle.
p, needle.
len) == 0) {
1808 return haystack.
p +
i;
1816 while (s.
len > 0 && isspace((
int) *s.
p)) {
1820 while (s.
len > 0 && isspace((
int) *(s.
p + s.
len - 1))) {
1829 if (s.
len < prefix.
len)
return 0;
1832#ifdef MG_MODULE_LINES
1833#line 1 "common/str_util.c"
1852#ifndef EXCLUDE_COMMON
1858#ifndef C_DISABLE_BUILTIN_SNPRINTF
1859#define C_DISABLE_BUILTIN_SNPRINTF 0
1867 for (; l < maxlen && s[l] !=
'\0'; l++) {
1872#define C_SNPRINTF_APPEND_CHAR(ch) \
1874 if (i < (int) buf_size) buf[i] = ch; \
1878#define C_SNPRINTF_FLAG_ZERO 1
1880#if C_DISABLE_BUILTIN_SNPRINTF
1881int c_vsnprintf(
char *buf,
size_t buf_size,
const char *fmt, va_list ap)
WEAK;
1882int c_vsnprintf(
char *buf,
size_t buf_size,
const char *fmt, va_list ap) {
1883 return vsnprintf(buf, buf_size, fmt, ap);
1886static int c_itoa(
char *buf,
size_t buf_size, int64_t num,
int base,
int flags,
1889 int i = 0,
k = 0, neg = 0;
1898 int rem = num %
base;
1900 tmp[
k++] =
'0' + rem;
1902 tmp[
k++] =
'a' + (rem - 10);
1909 while (
k < field_width &&
k < (
int)
sizeof(tmp) - 1) {
1927int c_vsnprintf(
char *buf,
size_t buf_size,
const char *fmt, va_list ap)
WEAK;
1928int c_vsnprintf(
char *buf,
size_t buf_size,
const char *fmt, va_list ap) {
1929 int ch,
i = 0, len_mod, flags, precision, field_width;
1931 while ((ch = *fmt++) !=
'\0') {
1943 flags = field_width = precision = len_mod = 0;
1951 while (*fmt >=
'0' && *fmt <=
'9') {
1953 field_width += *fmt++ -
'0';
1957 field_width = va_arg(ap,
int);
1965 precision = va_arg(ap,
int);
1968 while (*fmt >=
'0' && *fmt <=
'9') {
1970 precision += *fmt++ -
'0';
1999 const char *s = va_arg(ap,
const char *);
2001 int pad = field_width - (precision >= 0 ?
c_strnlen(s, precision) : 0);
2002 for (
j = 0;
j < pad;
j++) {
2009 for (
j = 0; (precision <= 0 ||
j < precision) && s[
j] !=
'\0';
j++) {
2013 }
else if (ch ==
'c') {
2014 ch = va_arg(ap,
int);
2016 }
else if (ch ==
'd' && len_mod == 0) {
2017 i +=
c_itoa(buf +
i, buf_size -
i, va_arg(ap,
int), 10, flags,
2019 }
else if (ch ==
'd' && len_mod ==
'l') {
2020 i +=
c_itoa(buf +
i, buf_size -
i, va_arg(ap,
long), 10, flags,
2023 }
else if (ch ==
'd' && len_mod ==
'z') {
2024 i +=
c_itoa(buf +
i, buf_size -
i, va_arg(ap, ssize_t), 10, flags,
2027 }
else if (ch ==
'd' && len_mod ==
'q') {
2028 i +=
c_itoa(buf +
i, buf_size -
i, va_arg(ap, int64_t), 10, flags,
2030 }
else if ((ch ==
'x' || ch ==
'u') && len_mod == 0) {
2031 i +=
c_itoa(buf +
i, buf_size -
i, va_arg(ap,
unsigned),
2032 ch ==
'x' ? 16 : 10, flags, field_width);
2033 }
else if ((ch ==
'x' || ch ==
'u') && len_mod ==
'l') {
2034 i +=
c_itoa(buf +
i, buf_size -
i, va_arg(ap,
unsigned long),
2035 ch ==
'x' ? 16 : 10, flags, field_width);
2036 }
else if ((ch ==
'x' || ch ==
'u') && len_mod ==
'z') {
2037 i +=
c_itoa(buf +
i, buf_size -
i, va_arg(ap,
size_t),
2038 ch ==
'x' ? 16 : 10, flags, field_width);
2039 }
else if (ch ==
'p') {
2040 unsigned long num = (
unsigned long) (uintptr_t) va_arg(ap,
void *);
2043 i +=
c_itoa(buf +
i, buf_size -
i, num, 16, flags, 0);
2058 buf[
i < (int) buf_size ?
i : (int) buf_size - 1] =
'\0';
2065int c_snprintf(
char *buf,
size_t buf_size,
const char *fmt, ...)
WEAK;
2066int c_snprintf(
char *buf,
size_t buf_size, const
char *fmt, ...) {
2076int to_wchar(
const char *path,
wchar_t *wbuf,
size_t wbuf_len) {
2078 char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *
p;
2080 strncpy(buf, path,
sizeof(buf));
2081 buf[
sizeof(buf) - 1] =
'\0';
2084 p = buf + strlen(buf) - 1;
2085 while (
p > buf &&
p[-1] !=
':' && (
p[0] ==
'\\' ||
p[0] ==
'/')) *
p-- =
'\0';
2087 memset(wbuf, 0, wbuf_len *
sizeof(
wchar_t));
2088 ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (
int) wbuf_len);
2094 WideCharToMultiByte(CP_UTF8, 0, wbuf, (
int) wbuf_len, buf2,
sizeof(buf2),
2096 if (strcmp(buf, buf2) != 0) {
2106const char *
c_strnstr(
const char *s,
const char *find,
size_t slen)
WEAK;
2107const char *
c_strnstr(
const char *s,
const char *find,
size_t slen) {
2108 size_t find_length = strlen(find);
2111 for (
i = 0;
i < slen;
i++) {
2112 if (
i + find_length > slen) {
2116 if (strncmp(&s[
i], find, find_length) == 0) {
2125char *strdup(
const char *src)
WEAK;
2126char *strdup(
const char *src) {
2127 size_t len = strlen(src) + 1;
2138 static const char *hex =
"0123456789abcdef";
2140 for (;
len--;
p++) {
2141 *to++ = hex[
p[0] >> 4];
2142 *to++ = hex[
p[0] & 0x0f];
2148 if (ch >=
'0' && ch <=
'9') {
2150 }
else if (ch >=
'a' && ch <=
'f') {
2151 return ch -
'a' + 10;
2152 }
else if (ch >=
'A' && ch <=
'F') {
2153 return ch -
'A' + 10;
2162 for (
i = 0;
i <
len;
i += 2) {
2169int64_t cs_to64(
const char *s)
WEAK;
2170int64_t cs_to64(
const char *s) {
2173 while (*s && isspace((
unsigned char) *s)) s++;
2178 while (isdigit((
unsigned char) *s)) {
2180 result += (*s -
'0');
2183 return result * neg;
2188 return tolower(*(
const unsigned char *) s);
2197 }
while (diff == 0 && s1[-1] !=
'\0' && --
len > 0);
2217int mg_avprintf(
char **buf,
size_t size,
const char *fmt, va_list ap)
WEAK;
2218int mg_avprintf(
char **buf,
size_t size,
const char *fmt, va_list ap) {
2222 va_copy(ap_copy, ap);
2223 len = vsnprintf(*buf, size, fmt, ap_copy);
2237 if ((*buf = (
char *)
MG_MALLOC(size)) == NULL) {
2241 va_copy(ap_copy, ap);
2242 len = vsnprintf(*buf, size - 1, fmt, ap_copy);
2252 }
else if (
len >= (
int) size) {
2257 va_copy(ap_copy, ap);
2258 len = vsnprintf(*buf,
len + 1, fmt, ap_copy);
2278 if (
list.len == 0) {
2282 const char *chr = NULL;
2285 if ((chr =
mg_strchr(*val,
',')) != NULL) {
2287 val->
len = chr - val->
p;
2296 if (eq_val != NULL) {
2300 eq_val->p = (
const char *) memchr(val->
p,
'=', val->
len);
2301 if (eq_val->p != NULL) {
2303 eq_val->len = val->
p + val->
len - eq_val->p;
2304 val->
len = (eq_val->p - val->
p) - 1;
2315 size_t res = 0,
len = 0,
i = 0,
j = 0;
2317 if ((or_str = (
const char *) memchr(pattern.
p,
'|', pattern.
len)) != NULL ||
2318 (or_str = (
const char *) memchr(pattern.
p,
',', pattern.
len)) != NULL) {
2319 struct mg_str pstr = {pattern.
p, (size_t)(or_str - pattern.
p)};
2321 if (res > 0)
return res;
2322 pstr.
p = or_str + 1;
2323 pstr.
len = (pattern.
p + pattern.
len) - (or_str + 1);
2327 for (;
i < pattern.
len &&
j <
str.len;
i++,
j++) {
2328 if (pattern.
p[
i] ==
'?') {
2330 }
else if (pattern.
p[
i] ==
'*') {
2332 if (
i < pattern.
len && pattern.
p[
i] ==
'*') {
2339 if (
i == pattern.
len || (pattern.
p[
i] ==
'$' &&
i == pattern.
len - 1))
2342 const struct mg_str pstr = {pattern.
p +
i, pattern.
len -
i};
2345 }
while (res == 0 &&
len != 0 &&
len-- > 0);
2346 return res == 0 ? 0 :
j + res +
len;
2352 if (
i < pattern.
len && pattern.
p[
i] ==
'$') {
2353 return j ==
str.len ?
str.len : 0;
2355 return i == pattern.
len ?
j : 0;
2360 const struct mg_str pstr = {pattern, (size_t) pattern_len};
2367#ifdef MG_MODULE_LINES
2368#line 1 "mongoose/src/mg_net.c"
2394#define MG_MAX_HOST_LEN 200
2396#ifndef MG_TCP_IO_SIZE
2398#define MG_TCP_IO_SIZE 1460000
2400#ifndef MG_UDP_IO_SIZE
2401#define MG_UDP_IO_SIZE 1460
2404#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
2405 memcpy(dst, src, sizeof(*dst));
2408#define _MG_ALLOWED_CONNECT_FLAGS_MASK \
2409 (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
2410 MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST)
2412#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \
2413 (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
2414 MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \
2415 MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
2418#define intptr_t long
2422 DBG((
"%p %p", mgr,
c));
2444 if (ev_handler == NULL) {
2452 DBG((
"%p %s ev=%d ev_data=%p flags=0x%lx rmbl=%d smbl=%d", nc,
2453 ev_handler == nc->
handler ?
"user" :
"proto", ev, ev_data, nc->
flags,
2457#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
2463 if (ev_handler != NULL) {
2464 unsigned long flags_before = nc->
flags;
2465 ev_handler(nc, ev, ev_data
MG_UD_ARG(user_data));
2467 if (ev_handler == nc->
handler && nc->
flags != flags_before) {
2468 nc->
flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
2474 DBG((
"%p after %s flags=0x%lx rmbl=%d smbl=%d", nc,
2475 ev_handler == nc->
handler ?
"user" :
"proto", nc->
flags,
2478#if !MG_ENABLE_CALLBACK_USERDATA
2484 if (
c->ev_timer_time > 0 && now >=
c->ev_timer_time) {
2485 double old_value =
c->ev_timer_time;
2486 c->ev_timer_time = 0;
2495 return avail > max ? max : avail;
2523 }
while (recved > 0);
2528 time_t now_t = (time_t) now;
2543 mg_ssl_if_conn_free(conn);
2548 memset(conn, 0,
sizeof(*conn));
2562 mg_ssl_if_conn_close_notify(conn);
2578 memset(&opts, 0,
sizeof(opts));
2584 memset(m, 0,
sizeof(*m));
2585#if MG_ENABLE_BROADCAST
2593 WSAStartup(MAKEWORD(2, 2), &
data);
2595#elif defined(__unix__)
2598 signal(SIGPIPE, SIG_IGN);
2621 DBG((
"=================================="));
2622 DBG((
"init mgr=%p", m));
2625 static int init_done;
2638 if (m == NULL)
return;
2642#if MG_ENABLE_BROADCAST
2649 tmp_conn = conn->
next;
2673 return (m->
num_calls - num_calls_before);
2683 if (
buf != mem &&
buf != NULL) {
2699#if MG_ENABLE_SYNC_RESOLVER
2701static int mg_resolve2(
const char *host,
struct in_addr *ina) {
2702#if MG_ENABLE_GETADDRINFO
2704 struct addrinfo hints, *servinfo, *p;
2705 struct sockaddr_in *h = NULL;
2706 memset(&hints, 0,
sizeof hints);
2707 hints.ai_family = AF_INET;
2708 hints.ai_socktype = SOCK_STREAM;
2709 if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
2713 for (p = servinfo; p != NULL; p = p->ai_next) {
2714 memcpy(&h, &p->ai_addr,
sizeof(h));
2715 memcpy(ina, &h->sin_addr,
sizeof(*ina));
2717 freeaddrinfo(servinfo);
2721 if ((he = gethostbyname(host)) == NULL) {
2722 DBG((
"gethostbyname(%s) failed: %s", host, strerror(
mg_get_errno())));
2724 memcpy(ina, he->h_addr_list[0],
sizeof(*ina));
2731int mg_resolve(
const char *host,
char *buf,
size_t n) {
2794 int *proto,
char *host,
size_t host_len) {
2795 unsigned int a, b,
c,
d, port = 0;
2806 memset(
sa, 0,
sizeof(*
sa));
2807 sa->
sin.sin_family = AF_INET;
2809 *proto = SOCK_STREAM;
2811 if (strncmp(
str,
"udp://", 6) == 0) {
2813 *proto = SOCK_DGRAM;
2814 }
else if (strncmp(
str,
"tcp://", 6) == 0) {
2818 if (sscanf(
str,
"%u.%u.%u.%u:%u%n", &a, &b, &
c, &
d, &port, &len) == 5) {
2820 sa->
sin.sin_addr.s_addr =
2821 htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) |
c << 8 |
d);
2822 sa->
sin.sin_port = htons((uint16_t) port);
2824 }
else if (sscanf(
str,
"[%99[^]]]:%u%n",
buf, &port, &len) == 2 &&
2827 sa->
sin6.sin6_family = AF_INET6;
2828 sa->
sin.sin_port = htons((uint16_t) port);
2830#if MG_ENABLE_ASYNC_RESOLVER
2831 }
else if (strlen(
str) < host_len &&
2832 sscanf(
str,
"%[^ :]:%u%n", host, &port, &len) == 2) {
2833 sa->
sin.sin_port = htons((uint16_t) port);
2845#if MG_ENABLE_SYNC_RESOLVER
2854 }
else if (sscanf(
str,
":%u%n", &port, &len) == 1 ||
2855 sscanf(
str,
"%u%n", &port, &len) == 1) {
2857 sa->
sin.sin_port = htons((uint16_t) port);
2867 return port < 0xffffUL && (ch ==
'\0' || ch ==
',' || isspace(ch)) ? len : -1;
2873 int server_side = (nc->
listener != NULL);
2874 enum mg_ssl_if_result res;
2876 res = mg_ssl_if_handshake(nc);
2878 if (res == MG_SSL_OK) {
2886 }
else if (res == MG_SSL_WANT_READ) {
2888 }
else if (res == MG_SSL_WANT_WRITE) {
2903 memset(&opts, 0,
sizeof(opts));
2905 if (nc == NULL)
return NULL;
2925 if (mg_ssl_if_conn_accept(nc, nc->
listener) == MG_SSL_OK) {
2926 mg_ssl_handshake(nc);
2983 n = mg_ssl_if_read(nc,
buf, len);
2984 DBG((
"%p <- %d bytes (SSL)", nc,
n));
2986 if (
n == MG_SSL_WANT_READ) {
2993 nc->
flags &= ~MG_F_WANT_READ;
2996 mg_ssl_handshake(nc);
3002 DBG((
"%p <- %d bytes", nc,
n));
3007#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
3025 size_t sa_len =
sizeof(
sa);
3038 if (memcmp(&nc->
sa.
sa, &
sa.sa, sa_len) == 0 && nc->
listener == lc) {
3044 memset(&opts, 0,
sizeof(opts));
3074 ntohs(nc->
sa.
sin.sin_port)));
3082#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
3113 n = mg_ssl_if_write(nc, buf, len);
3114 DBG((
"%p -> %d bytes (SSL)", nc,
n));
3117 if (
n == MG_SSL_WANT_WRITE) {
3124 nc->
flags &= ~MG_F_WANT_WRITE;
3127 mg_ssl_handshake(nc);
3137 DBG((
"%p -> %d bytes", nc,
n));
3140#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
3164 LOG(
LL_DEBUG, (
"%p %s://%s:%hu", nc, proto == SOCK_DGRAM ?
"udp" :
"tcp",
3168 if (proto == SOCK_DGRAM) {
3179 (
"%p %s://%s:%hu -> %d", nc, (nc->
flags &
MG_F_UDP ?
"udp" :
"tcp"),
3181 nc->
flags &= ~MG_F_CONNECTING;
3187 mg_ssl_handshake(nc);
3195#if MG_ENABLE_ASYNC_RESOLVER
3208 nc->
flags &= ~MG_F_RESOLVING;
3246 memset(&opts, 0,
sizeof(opts));
3255#if MG_ENABLE_CALLBACK_USERDATA
3287#if MG_ENABLE_CALLBACK_USERDATA
3295 (
"%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert :
"-"),
3296 (opts.ssl_key ? opts.ssl_key :
"-"),
3297 (opts.ssl_ca_cert ? opts.ssl_ca_cert :
"-")));
3299 if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL ||
3300 opts.ssl_psk_identity != NULL) {
3301 const char *err_msg = NULL;
3302 struct mg_ssl_if_conn_params params;
3308 memset(¶ms, 0,
sizeof(params));
3309 params.cert = opts.ssl_cert;
3310 params.key = opts.ssl_key;
3311 params.ca_cert = opts.ssl_ca_cert;
3312 params.cipher_suites = opts.ssl_cipher_suites;
3313 params.psk_identity = opts.ssl_psk_identity;
3314 params.psk_key = opts.ssl_psk_key;
3315 if (opts.ssl_ca_cert != NULL) {
3316 if (opts.ssl_server_name != NULL) {
3317 if (strcmp(opts.ssl_server_name,
"*") != 0) {
3318 params.server_name = opts.ssl_server_name;
3320 }
else if (rc == 0) {
3321 params.server_name = host;
3324 if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
3334#if MG_ENABLE_ASYNC_RESOLVER
3341 memset(&o, 0,
sizeof(o));
3368 memset(&opts, 0,
sizeof(opts));
3382#if MG_ENABLE_CALLBACK_USERDATA
3405 DBG((
"%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert :
"-"),
3406 (opts.ssl_key ? opts.ssl_key :
"-"),
3407 (opts.ssl_ca_cert ? opts.ssl_ca_cert :
"-")));
3409 if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
3410 const char *err_msg = NULL;
3411 struct mg_ssl_if_conn_params params;
3417 memset(¶ms, 0,
sizeof(params));
3418 params.cert = opts.ssl_cert;
3419 params.key = opts.ssl_key;
3420 params.ca_cert = opts.ssl_ca_cert;
3421 params.cipher_suites = opts.ssl_cipher_suites;
3422 if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
3437 DBG((
"Failed to open listener: %d", rc));
3451#if MG_ENABLE_BROADCAST
3478 return n >= 0 &&
n <= 255;
3482 int n, a, b,
c,
d, slash = 32, len = 0;
3484 if ((sscanf(spec,
"%d.%d.%d.%d/%d%n", &a, &b, &
c, &
d, &slash, &
n) == 5 ||
3485 sscanf(spec,
"%d.%d.%d.%d%n", &a, &b, &
c, &
d, &
n) == 4) &&
3490 ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t)
c << 8) |
d;
3491 *
mask = slash ? 0xffffffffU << (32 - slash) : 0;
3503 allowed = (acl == NULL || *acl ==
'\0') ?
'+' :
'-';
3507 if ((flag !=
'+' && flag !=
'-') ||
3512 if (net == (remote_ip &
mask)) {
3517 DBG((
"%08x %c", (
unsigned int) remote_ip, allowed));
3518 return allowed ==
'+';
3528 double result =
c->ev_timer_time;
3529 c->ev_timer_time = timestamp;
3536 (
unsigned long) timestamp));
3558#if MG_ENABLE_CALLBACK_USERDATA
3574 memset(&opts, 0,
sizeof(opts));
3581#ifdef MG_MODULE_LINES
3582#line 1 "mongoose/src/mg_net_if_socket.h"
3589#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
3590#define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
3598#ifndef MG_ENABLE_NET_IF_SOCKET
3599#define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET
3609#ifdef MG_MODULE_LINES
3610#line 1 "mongoose/src/mg_net_if_socks.h"
3617#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
3618#define CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
3634#ifdef MG_MODULE_LINES
3635#line 1 "mongoose/src/mg_net_if.c"
3680 double min_timer = 0;
3690#ifdef MG_MODULE_LINES
3691#line 1 "mongoose/src/mg_net_if_null.c"
3809 return (time_t) now;
3819#define MG_NULL_IFACE_VTABLE \
3821 mg_null_if_init, mg_null_if_free, mg_null_if_add_conn, \
3822 mg_null_if_remove_conn, mg_null_if_poll, mg_null_if_listen_tcp, \
3823 mg_null_if_listen_udp, mg_null_if_connect_tcp, mg_null_if_connect_udp, \
3824 mg_null_if_tcp_send, mg_null_if_udp_send, mg_null_if_tcp_recv, \
3825 mg_null_if_udp_recv, mg_null_if_create_conn, mg_null_if_destroy_conn, \
3826 mg_null_if_sock_set, mg_null_if_get_conn_addr, \
3831#if MG_NET_IF == MG_NET_IF_NULL
3834#ifdef MG_MODULE_LINES
3835#line 1 "mongoose/src/mg_net_if_socket.c"
3842#if MG_ENABLE_NET_IF_SOCKET
3853 unsigned long on = 1;
3854 ioctlsocket(sock, FIONBIO, &on);
3856 int flags = fcntl(sock, F_GETFL, 0);
3857 fcntl(sock, F_SETFL, flags | O_NONBLOCK);
3863 return err != EINPROGRESS && err != EWOULDBLOCK
3865 && err != EAGAIN && err != EINTR
3868 && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
3876 nc->
sock =
socket(AF_INET, SOCK_STREAM, proto);
3881#if !defined(MG_ESP8266)
3884 rc = connect(nc->
sock, &sa->
sa,
sizeof(sa->
sin));
3898 if (setsockopt(nc->
sock, SOL_SOCKET, SO_BROADCAST, (
const char *) &optval,
3899 sizeof(optval)) < 0) {
3935 int n = sendto(nc->
sock, buf, len, 0, &nc->
sa.
sa,
sizeof(nc->
sa.
sin));
3955 socklen_t sa_len_st = *sa_len;
3956 int n = recvfrom(nc->
sock, buf, len, 0, &sa->
sa, &sa_len_st);
3957 *sa_len = sa_len_st;
3981 socklen_t sa_len =
sizeof(
sa);
3983 sock_t sock = accept(lc->
sock, &
sa.sa, &sa_len);
3996 ntohs(
sa.sin.sin_port)));
4006 (
sa->sa.sa_family == AF_INET) ?
sizeof(
sa->sin) :
sizeof(
sa->sin6);
4014#
if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE)
4016 !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (
void *) &on,
4020#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
4030 !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (
void *) &on,
sizeof(on)) &&
4034 !bind(sock, &
sa->sa, sa_len) &&
4039 (void) getsockname(sock, &
sa->sa, &sa_len);
4049#define _MG_F_FD_CAN_READ 1
4050#define _MG_F_FD_CAN_WRITE 1 << 1
4051#define _MG_F_FD_ERROR 1 << 2
4056 if (worth_logging) {
4057 DBG((
"%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->
sock,
4065 if (fd_flags != 0) {
4067#if !defined(MG_ESP8266)
4069 socklen_t len =
sizeof(err);
4071 getsockopt(nc->
sock, SOL_SOCKET, SO_ERROR, (
char *) &err, &len);
4074 }
else if (err == EAGAIN || err == EWOULDBLOCK) {
4085 }
else if (nc->
err != 0) {
4109 if (worth_logging) {
4110 DBG((
"%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->
sock,
4115#if MG_ENABLE_BROADCAST
4120 DBG((
"read %d from ctl socket", len));
4146#if MG_ENABLE_BROADCAST
4182 fd_set read_set, write_set, err_set;
4184 int num_fds, num_ev, num_timers = 0;
4190 FD_ZERO(&write_set);
4192#if MG_ENABLE_BROADCAST
4210 int new_sock = dup(nc->
sock);
4211 if (new_sock >= 0) {
4214 DBG((
"new sock %d -> %d", nc->
sock, new_sock));
4215 nc->
sock = new_sock;
4218 DBG((
"new sock is still larger than FD_SETSIZE, disregard"));
4251 if (num_timers > 0) {
4252 double timer_timeout_ms = (min_timer -
mg_time()) * 1000 + 1 ;
4253 if (timer_timeout_ms < timeout_ms) {
4254 timeout_ms = (int) timer_timeout_ms;
4257 if (timeout_ms < 0) timeout_ms = 0;
4259 tv.tv_sec = timeout_ms / 1000;
4260 tv.tv_usec = (timeout_ms % 1000) * 1000;
4262 num_ev = select((
int) max_fd + 1, &read_set, &write_set, &err_set, &
tv);
4265 DBG((
"select @ %ld num_ev=%d of %d, timeout=%d", (
long) now, num_ev, num_fds,
4269#if MG_ENABLE_BROADCAST
4271 FD_ISSET(mgr->
ctl[1], &read_set)) {
4280 fd_flags = (FD_ISSET(nc->
sock, &read_set) &&
4298 return (time_t) now;
4301#if MG_ENABLE_BROADCAST
4302MG_INTERNAL void mg_socketpair_close(sock_t *sock) {
4304 if (
closesocket(*sock) == -1 && errno == EINTR)
continue;
4311mg_socketpair_accept(sock_t sock,
union socket_address *sa, socklen_t sa_len) {
4325 socklen_t len =
sizeof(
sa.sin);
4330 (void) memset(&
sa, 0,
sizeof(
sa));
4331 sa.
sin.sin_family = AF_INET;
4332 sa.sin.sin_addr.s_addr = htonl(0x7f000001);
4336 }
else if (bind(sock, &
sa.sa, len) != 0) {
4337 }
else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
4338 }
else if (getsockname(sock, &
sa.sa, &len) != 0) {
4340 }
else if (sock_type == SOCK_STREAM && connect(sp[0], &
sa.sa, len) != 0) {
4341 }
else if (sock_type == SOCK_DGRAM &&
4342 (bind(sp[0], &sa2.sa, len) != 0 ||
4343 getsockname(sp[0], &sa2.sa, &len) != 0 ||
4344 connect(sp[0], &
sa.sa, len) != 0 ||
4345 connect(sock, &sa2.sa, len) != 0)) {
4346 }
else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : mg_socketpair_accept(
4347 sock, &
sa, len))) ==
4352 if (sock_type == SOCK_STREAM) mg_socketpair_close(&sock);
4368 socklen_t slen =
sizeof(*sa);
4369 memset(
sa, 0, slen);
4371 getpeername(sock, &
sa->sa, &slen);
4373 getsockname(sock, &
sa->sa, &slen);
4386 memcpy(
sa, &nc->
sa,
sizeof(*
sa));
4393#define MG_SOCKET_IFACE_VTABLE \
4395 mg_socket_if_init, \
4396 mg_socket_if_free, \
4397 mg_socket_if_add_conn, \
4398 mg_socket_if_remove_conn, \
4399 mg_socket_if_poll, \
4400 mg_socket_if_listen_tcp, \
4401 mg_socket_if_listen_udp, \
4402 mg_socket_if_connect_tcp, \
4403 mg_socket_if_connect_udp, \
4404 mg_socket_if_tcp_send, \
4405 mg_socket_if_udp_send, \
4406 mg_socket_if_tcp_recv, \
4407 mg_socket_if_udp_recv, \
4408 mg_socket_if_create_conn, \
4409 mg_socket_if_destroy_conn, \
4410 mg_socket_if_sock_set, \
4411 mg_socket_if_get_conn_addr, \
4416#if MG_NET_IF == MG_NET_IF_SOCKET
4421#ifdef MG_MODULE_LINES
4422#line 1 "mongoose/src/mg_net_if_socks.c"
4437static void socks_if_disband(
struct socksdata *
d) {
4441 d->c->user_data = NULL;
4446 d->s->user_data = NULL;
4452 struct socksdata *
d = (
struct socksdata *) s->
user_data;
4453 if (
d == NULL ||
d->c == NULL || !(s->flags & MG_SOCKS_CONNECT_DONE) ||
4461static void socks_if_handler(
struct mg_connection *
c,
int ev,
void *ev_data) {
4462 struct socksdata *
d = (
struct socksdata *)
c->user_data;
4463 if (
d == NULL)
return;
4465 int res = *(
int *) ev_data;
4468 unsigned char buf[] = {MG_SOCKS_VERSION, 1, MG_SOCKS_HANDSHAKE_NOAUTH};
4470 LOG(
LL_DEBUG, (
"Sent handshake to %s",
d->proxy_addr));
4472 LOG(
LL_ERROR, (
"Cannot connect to %s: %d",
d->proxy_addr, res));
4476 socks_if_disband(
d);
4479 if (!(
c->flags & MG_SOCKS_HANDSHAKE_DONE)) {
4481 unsigned char buf[10] = {MG_SOCKS_VERSION, MG_SOCKS_CMD_CONNECT, 0,
4482 MG_SOCKS_ADDR_IPV4};
4483 if (
c->recv_mbuf.len < 2)
return;
4484 if ((
unsigned char)
c->recv_mbuf.buf[1] == MG_SOCKS_HANDSHAKE_FAILURE) {
4486 socks_if_disband(
d);
4490 c->flags |= MG_SOCKS_HANDSHAKE_DONE;
4493 memcpy(buf + 4, &
d->c->sa.sin.sin_addr, 4);
4494 memcpy(buf + 8, &
d->c->sa.sin.sin_port, 2);
4499 if ((
c->flags & MG_SOCKS_HANDSHAKE_DONE) &&
4500 !(
c->flags & MG_SOCKS_CONNECT_DONE)) {
4501 if (
c->recv_mbuf.len < 10)
return;
4502 if (
c->recv_mbuf.buf[1] != MG_SOCKS_SUCCESS) {
4503 LOG(
LL_ERROR, (
"Socks connection error: %d",
c->recv_mbuf.buf[1]));
4504 socks_if_disband(
d);
4508 c->flags |= MG_SOCKS_CONNECT_DONE;
4520 struct socksdata *
d = (
struct socksdata *)
c->iface->data;
4523 d->s->user_data =
d;
4546static int mg_socks_if_tcp_send(
struct mg_connection *
c,
const void *buf,
4549 struct socksdata *
d = (
struct socksdata *)
c->iface->data;
4550 if (
d->s == NULL)
return -1;
4552 DBG((
"%p -> %d -> %p",
c, res,
d->s));
4556static int mg_socks_if_udp_send(
struct mg_connection *
c,
const void *buf,
4564int mg_socks_if_tcp_recv(
struct mg_connection *
c,
void *buf,
size_t len) {
4565 struct socksdata *
d = (
struct socksdata *)
c->iface->data;
4566 if (
d->s == NULL)
return -1;
4567 if (len >
d->s->recv_mbuf.len) len =
d->s->recv_mbuf.len;
4569 memcpy(buf,
d->s->recv_mbuf.buf, len);
4572 DBG((
"%p <- %d <- %p",
c, (
int) len,
d->s));
4576int mg_socks_if_udp_recv(
struct mg_connection *
c,
void *buf,
size_t len,
4592 c->iface->vtable->free(
c->iface);
4598static void mg_socks_if_sock_set(
struct mg_connection *
c, sock_t sock) {
4603static void mg_socks_if_init(
struct mg_iface *iface) {
4607static void mg_socks_if_free(
struct mg_iface *iface) {
4608 struct socksdata *
d = (
struct socksdata *) iface->
data;
4611 socks_if_disband(
d);
4626static time_t mg_socks_if_poll(
struct mg_iface *iface,
int timeout_ms) {
4633static void mg_socks_if_get_conn_addr(
struct mg_connection *
c,
int remote,
4642 mg_socks_if_init, mg_socks_if_free,
4643 mg_socks_if_add_conn, mg_socks_if_remove_conn,
4644 mg_socks_if_poll, mg_socks_if_listen_tcp,
4645 mg_socks_if_listen_udp, mg_socks_if_connect_tcp,
4646 mg_socks_if_connect_udp, mg_socks_if_tcp_send,
4647 mg_socks_if_udp_send, mg_socks_if_tcp_recv,
4648 mg_socks_if_udp_recv, mg_socks_if_create_conn,
4649 mg_socks_if_destroy_conn, mg_socks_if_sock_set,
4650 mg_socks_if_get_conn_addr,
4656 ((
struct socksdata *) iface->
data)->proxy_addr = strdup(proxy_addr);
4661#ifdef MG_MODULE_LINES
4662#line 1 "mongoose/src/mg_ssl_if_openssl.c"
4669#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL
4672#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
4675#include <openssl/ssl.h>
4677#include <openssl/tls1.h>
4680struct mg_ssl_if_ctx {
4684 size_t identity_len;
4687void mg_ssl_if_init() {
4691enum mg_ssl_if_result mg_ssl_if_conn_accept(
struct mg_connection *nc,
4693 struct mg_ssl_if_ctx *ctx =
4694 (
struct mg_ssl_if_ctx *)
MG_CALLOC(1,
sizeof(*ctx));
4695 struct mg_ssl_if_ctx *lc_ctx = (
struct mg_ssl_if_ctx *) lc->ssl_if_data;
4696 nc->ssl_if_data = ctx;
4697 if (ctx == NULL || lc_ctx == NULL)
return MG_SSL_ERROR;
4698 ctx->ssl_ctx = lc_ctx->ssl_ctx;
4699 if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
4700 return MG_SSL_ERROR;
4705static enum mg_ssl_if_result mg_use_cert(
SSL_CTX *ctx,
const char *cert,
4706 const char *
key,
const char **err_msg);
4707static enum mg_ssl_if_result mg_use_ca_cert(
SSL_CTX *ctx,
const char *cert);
4708static enum mg_ssl_if_result mg_set_cipher_list(
SSL_CTX *ctx,
const char *cl);
4709static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(
struct mg_ssl_if_ctx *ctx,
4710 const char *identity,
4711 const char *key_str);
4713enum mg_ssl_if_result mg_ssl_if_conn_init(
4714 struct mg_connection *nc,
const struct mg_ssl_if_conn_params *params,
4715 const char **err_msg) {
4716 struct mg_ssl_if_ctx *ctx =
4717 (
struct mg_ssl_if_ctx *)
MG_CALLOC(1,
sizeof(*ctx));
4718 DBG((
"%p %s,%s,%s", nc, (params->cert ? params->cert :
""),
4719 (params->
key ? params->
key :
""),
4720 (params->ca_cert ? params->ca_cert :
"")));
4723 return MG_SSL_ERROR;
4725 nc->ssl_if_data = ctx;
4727 ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
4729 ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
4731 if (ctx->ssl_ctx == NULL) {
4733 return MG_SSL_ERROR;
4738 SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2);
4739 SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3);
4740 SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1);
4741#ifdef MG_SSL_OPENSSL_NO_COMPRESSION
4742 SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
4744#ifdef MG_SSL_OPENSSL_CIPHER_SERVER_PREFERENCE
4745 SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
4751 if (params->cert != NULL &&
4752 mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) !=
4754 return MG_SSL_ERROR;
4757 if (params->ca_cert != NULL &&
4758 mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) {
4760 return MG_SSL_ERROR;
4763 if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) {
4765 return MG_SSL_ERROR;
4769 if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) !=
4772 return MG_SSL_ERROR;
4776 (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
4778 return MG_SSL_ERROR;
4781 if (params->server_name != NULL) {
4783 SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name);
4785 SSL_set_tlsext_host_name(ctx->ssl, params->server_name);
4794static enum mg_ssl_if_result mg_ssl_if_ssl_err(
struct mg_connection *nc,
4796 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
4797 int err = SSL_get_error(ctx->ssl, res);
4798 if (err == SSL_ERROR_WANT_READ)
return MG_SSL_WANT_READ;
4799 if (err == SSL_ERROR_WANT_WRITE)
return MG_SSL_WANT_WRITE;
4800 DBG((
"%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err));
4802 return MG_SSL_ERROR;
4805enum mg_ssl_if_result mg_ssl_if_handshake(
struct mg_connection *nc) {
4806 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
4807 int server_side = (nc->
listener != NULL);
4810 if (SSL_get_fd(ctx->ssl) < 0) {
4811 if (SSL_set_fd(ctx->ssl, nc->
sock) != 1)
return MG_SSL_ERROR;
4813 res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl);
4814 if (res != 1)
return mg_ssl_if_ssl_err(nc, res);
4818int mg_ssl_if_read(
struct mg_connection *nc,
void *buf,
size_t buf_size) {
4819 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
4820 int n = SSL_read(ctx->ssl, buf, buf_size);
4821 DBG((
"%p %d -> %d", nc, (
int) buf_size,
n));
4822 if (
n < 0)
return mg_ssl_if_ssl_err(nc,
n);
4828 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
4829 int n = SSL_write(ctx->ssl,
data, len);
4830 DBG((
"%p %d -> %d", nc, (
int) len,
n));
4831 if (
n <= 0)
return mg_ssl_if_ssl_err(nc,
n);
4836 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
4837 if (ctx == NULL)
return;
4838 SSL_shutdown(ctx->ssl);
4842 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
4843 if (ctx == NULL)
return;
4844 nc->ssl_if_data = NULL;
4845 if (ctx->ssl != NULL) SSL_free(ctx->ssl);
4846 if (ctx->ssl_ctx != NULL && nc->
listener == NULL) SSL_CTX_free(ctx->ssl_ctx);
4848 memset(ctx, 0,
sizeof(*ctx));
4856static const char mg_s_cipher_list[] =
4857#if defined(MG_SSL_CRYPTO_MODERN)
4858 "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
4859 "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
4860 "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
4861 "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
4862 "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
4863 "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
4864 "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
4865 "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
4866 "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
4867#elif defined(MG_SSL_CRYPTO_OLD)
4868 "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
4869 "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
4870 "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
4871 "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
4872 "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
4873 "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
4874 "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
4875 "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
4876 "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
4877 "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
4878 "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
4879 "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
4881 "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
4882 "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
4883 "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
4884 "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
4885 "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
4886 "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
4887 "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
4888 "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
4889 "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
4890 "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
4891 "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:"
4904#if !MG_DISABLE_PFS && !defined(KR_VERSION)
4905static const char mg_s_default_dh_params[] =
4907-----BEGIN DH PARAMETERS-----\n\
4908MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
4909Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
4910+E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
4911ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
4912wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
49139VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
4914-----END DH PARAMETERS-----\n";
4917static enum mg_ssl_if_result mg_use_ca_cert(
SSL_CTX *ctx,
const char *cert) {
4918 if (cert == NULL || strcmp(cert,
"*") == 0) {
4921 SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
4922 return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK
4926static enum mg_ssl_if_result mg_use_cert(
SSL_CTX *ctx,
const char *cert,
4928 const char **err_msg) {
4929 if (
key == NULL)
key = cert;
4930 if (cert == NULL || cert[0] ==
'\0' ||
key == NULL ||
key[0] ==
'\0') {
4932 }
else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) {
4934 return MG_SSL_ERROR;
4935 }
else if (SSL_CTX_use_PrivateKey_file(ctx,
key, 1) == 0) {
4937 return MG_SSL_ERROR;
4938 }
else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) {
4940 return MG_SSL_ERROR;
4942 SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
4943#if !MG_DISABLE_PFS && !defined(KR_VERSION)
4948 bio = BIO_new_file(cert,
"r");
4950 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
4958 bio = BIO_new_mem_buf((
void *) mg_s_default_dh_params, -1);
4959 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
4963 SSL_CTX_set_tmp_dh(ctx, dh);
4964 SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
4967#if OPENSSL_VERSION_NUMBER > 0x10002000L
4968 SSL_CTX_set_ecdh_auto(ctx, 1);
4975static enum mg_ssl_if_result mg_set_cipher_list(
SSL_CTX *ctx,
const char *cl) {
4976 return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1
4981#if !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER)
4982static unsigned int mg_ssl_if_ossl_psk_cb(
SSL *ssl,
const char *hint,
4984 unsigned int max_identity_len,
4986 unsigned int max_psk_len) {
4987 struct mg_ssl_if_ctx *ctx =
4988 (
struct mg_ssl_if_ctx *) SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl));
4989 size_t key_len = ctx->psk.len - ctx->identity_len - 1;
4990 DBG((
"hint: '%s'", (hint ? hint :
"")));
4991 if (ctx->identity_len + 1 > max_identity_len) {
4992 DBG((
"identity too long"));
4995 if (key_len > max_psk_len) {
4996 DBG((
"key too long"));
4999 memcpy(identity, ctx->psk.buf, ctx->identity_len + 1);
5000 memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len);
5005static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(
struct mg_ssl_if_ctx *ctx,
5006 const char *identity,
5007 const char *key_str) {
5008 unsigned char key[32];
5011 if (identity == NULL && key_str == NULL)
return MG_SSL_OK;
5012 if (identity == NULL || key_str == NULL)
return MG_SSL_ERROR;
5013 key_len = strlen(key_str);
5014 if (key_len != 32 && key_len != 64)
return MG_SSL_ERROR;
5015 memset(
key, 0,
sizeof(
key));
5017 for (
i = 0; key_str[
i] !=
'\0';
i++) {
5019 char hc = tolower((
int) key_str[
i]);
5020 if (hc >=
'0' && hc <=
'9') {
5022 }
else if (hc >=
'a' && hc <=
'f') {
5025 return MG_SSL_ERROR;
5032 DBG((
"identity = '%s', key = (%u)", identity, (
unsigned int) key_len));
5033 ctx->identity_len = strlen(identity);
5034 mbuf_append(&ctx->psk, identity, ctx->identity_len + 1);
5036 SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb);
5037 SSL_CTX_set_app_data(ctx->ssl_ctx, ctx);
5041static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(
struct mg_ssl_if_ctx *ctx,
5042 const char *identity,
5043 const char *key_str) {
5048 return MG_SSL_ERROR;
5053 const char *ca_cert) {
5054 const char *err_msg = NULL;
5055 struct mg_ssl_if_conn_params params;
5056 memset(¶ms, 0,
sizeof(params));
5058 params.ca_cert = ca_cert;
5059 if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
5066#ifdef MG_MODULE_LINES
5067#line 1 "mongoose/src/mg_ssl_if_mbedtls.c"
5074#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS
5076#include <mbedtls/debug.h>
5077#include <mbedtls/ecp.h>
5078#include <mbedtls/net.h>
5079#include <mbedtls/platform.h>
5080#include <mbedtls/ssl.h>
5081#include <mbedtls/ssl_internal.h>
5082#include <mbedtls/x509_crt.h>
5083#include <mbedtls/version.h>
5085static void mg_ssl_mbed_log(
void *ctx,
int level,
const char *
file,
int line,
5102 LOG(cs_level, (
"%p %.*s", ctx, (
int) (strlen(
str) - 1),
str));
5110struct mg_ssl_if_ctx {
5111 mbedtls_ssl_config *conf;
5112 mbedtls_ssl_context *ssl;
5113 mbedtls_x509_crt *cert;
5114 mbedtls_pk_context *
key;
5115 mbedtls_x509_crt *ca_cert;
5116 struct mbuf cipher_suites;
5121extern int mg_ssl_if_mbed_random(
void *ctx,
unsigned char *
buf,
size_t len);
5123void mg_ssl_if_init() {
5124 LOG(
LL_INFO, (
"%s", MBEDTLS_VERSION_STRING_FULL));
5127enum mg_ssl_if_result mg_ssl_if_conn_accept(
struct mg_connection *nc,
5129 struct mg_ssl_if_ctx *ctx =
5130 (
struct mg_ssl_if_ctx *)
MG_CALLOC(1,
sizeof(*ctx));
5131 struct mg_ssl_if_ctx *lc_ctx = (
struct mg_ssl_if_ctx *) lc->ssl_if_data;
5132 nc->ssl_if_data = ctx;
5133 if (ctx == NULL || lc_ctx == NULL)
return MG_SSL_ERROR;
5134 ctx->ssl = (mbedtls_ssl_context *)
MG_CALLOC(1,
sizeof(*ctx->ssl));
5135 if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) {
5136 return MG_SSL_ERROR;
5141static enum mg_ssl_if_result mg_use_cert(
struct mg_ssl_if_ctx *ctx,
5142 const char *cert,
const char *
key,
5143 const char **err_msg);
5144static enum mg_ssl_if_result mg_use_ca_cert(
struct mg_ssl_if_ctx *ctx,
5146static enum mg_ssl_if_result mg_set_cipher_list(
struct mg_ssl_if_ctx *ctx,
5147 const char *ciphers);
5148#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
5149static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(
struct mg_ssl_if_ctx *ctx,
5150 const char *identity,
5154enum mg_ssl_if_result mg_ssl_if_conn_init(
5155 struct mg_connection *nc,
const struct mg_ssl_if_conn_params *params,
5156 const char **err_msg) {
5157 struct mg_ssl_if_ctx *ctx =
5158 (
struct mg_ssl_if_ctx *)
MG_CALLOC(1,
sizeof(*ctx));
5159 DBG((
"%p %s,%s,%s", nc, (params->cert ? params->cert :
""),
5160 (params->
key ? params->
key :
""),
5161 (params->ca_cert ? params->ca_cert :
"")));
5165 return MG_SSL_ERROR;
5167 nc->ssl_if_data = ctx;
5168 ctx->conf = (mbedtls_ssl_config *)
MG_CALLOC(1,
sizeof(*ctx->conf));
5170 mbedtls_ssl_config_init(ctx->conf);
5171 mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc);
5172 if (mbedtls_ssl_config_defaults(
5174 : MBEDTLS_SSL_IS_CLIENT),
5175 MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) {
5177 return MG_SSL_ERROR;
5181 mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
5182 MBEDTLS_SSL_MINOR_VERSION_3);
5183 mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc);
5185 if (params->cert != NULL &&
5186 mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) {
5187 return MG_SSL_ERROR;
5190 if (params->ca_cert != NULL &&
5191 mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) {
5193 return MG_SSL_ERROR;
5196 if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) {
5198 return MG_SSL_ERROR;
5201#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
5202 if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) !=
5205 return MG_SSL_ERROR;
5210 ctx->ssl = (mbedtls_ssl_context *)
MG_CALLOC(1,
sizeof(*ctx->ssl));
5211 mbedtls_ssl_init(ctx->ssl);
5212 if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) {
5214 return MG_SSL_ERROR;
5216 if (params->server_name != NULL &&
5217 mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) {
5218 return MG_SSL_ERROR;
5222#ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
5223 if (mbedtls_ssl_conf_max_frag_len(ctx->conf,
5224#
if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512
5225 MBEDTLS_SSL_MAX_FRAG_LEN_512
5226#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024
5227 MBEDTLS_SSL_MAX_FRAG_LEN_1024
5228#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048
5229 MBEDTLS_SSL_MAX_FRAG_LEN_2048
5230#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096
5231 MBEDTLS_SSL_MAX_FRAG_LEN_4096
5233#error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
5236 return MG_SSL_ERROR;
5245static int mg_ssl_if_mbed_send(
void *ctx,
const unsigned char *buf,
5249 if (
n > 0)
return n;
5250 if (
n == 0)
return MBEDTLS_ERR_SSL_WANT_WRITE;
5251 return MBEDTLS_ERR_NET_SEND_FAILED;
5254static int mg_ssl_if_mbed_recv(
void *
ctx,
unsigned char *
buf,
size_t len) {
5257 if (
n > 0)
return n;
5258 if (
n == 0)
return MBEDTLS_ERR_SSL_WANT_READ;
5259 return MBEDTLS_ERR_NET_RECV_FAILED;
5262static enum mg_ssl_if_result mg_ssl_if_mbed_err(
struct mg_connection *nc,
5264 enum mg_ssl_if_result res = MG_SSL_OK;
5265 if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
5266 res = MG_SSL_WANT_READ;
5267 }
else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
5268 res = MG_SSL_WANT_WRITE;
5269 }
else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
5270 LOG(
LL_DEBUG, (
"%p TLS connection closed by peer", nc));
5273 }
else if (ret == MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) {
5276 }
else if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
5279 }
else if (ret == MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION) {
5282 }
else if (ret == MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) {
5285 }
else if (ret == MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN) {
5288 }
else if (ret == MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) {
5291 }
else if (ret == MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO) {
5294 }
else if (ret == MBEDTLS_ERR_NET_RECV_FAILED) {
5298 LOG(
LL_ERROR, (
"%p mbedTLS error: -0x%04x", nc, -ret));
5306static void mg_ssl_if_mbed_free_certs_and_keys(
struct mg_ssl_if_ctx *
ctx) {
5307 if (
ctx->cert != NULL) {
5308 mbedtls_x509_crt_free(
ctx->cert);
5311 mbedtls_pk_free(
ctx->key);
5315 if (
ctx->ca_cert != NULL) {
5316 mbedtls_ssl_conf_ca_chain(
ctx->conf, NULL, NULL);
5317#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
5318 if (
ctx->conf->ca_chain_file != NULL) {
5320 ctx->conf->ca_chain_file = NULL;
5323 mbedtls_x509_crt_free(
ctx->ca_cert);
5325 ctx->ca_cert = NULL;
5329enum mg_ssl_if_result mg_ssl_if_handshake(
struct mg_connection *nc) {
5330 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
5333 if (ctx->ssl->p_bio == NULL) {
5334 mbedtls_ssl_set_bio(ctx->ssl, nc, mg_ssl_if_mbed_send, mg_ssl_if_mbed_recv,
5337 err = mbedtls_ssl_handshake(ctx->ssl);
5338 if (err != 0)
return mg_ssl_if_mbed_err(nc, err);
5339#ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS
5344 mbedtls_x509_crt_free(ctx->ssl->session->peer_cert);
5345 mbedtls_free(ctx->ssl->session->peer_cert);
5346 ctx->ssl->session->peer_cert = NULL;
5349 if (ctx->conf->key_cert != NULL) {
5352 ctx->conf->key_cert = NULL;
5354 mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
5355 mg_ssl_if_mbed_free_certs_and_keys(ctx);
5361int mg_ssl_if_read(
struct mg_connection *nc,
void *buf,
size_t len) {
5362 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
5363 int n = mbedtls_ssl_read(ctx->ssl, (
unsigned char *) buf, len);
5364 DBG((
"%p %d -> %d", nc, (
int) len,
n));
5365 if (
n < 0)
return mg_ssl_if_mbed_err(nc,
n);
5370int mg_ssl_if_write(
struct mg_connection *nc,
const void *buf,
size_t len) {
5371 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
5379 if (ctx->saved_len > 0 && ctx->saved_len < l) l = ctx->saved_len;
5380 int n = mbedtls_ssl_write(ctx->ssl, (
const unsigned char *) buf, l);
5381 DBG((
"%p %d,%d,%d -> %d", nc, (
int) len, (
int) ctx->saved_len, (
int) l,
n));
5383 if (
n == MBEDTLS_ERR_SSL_WANT_READ ||
n == MBEDTLS_ERR_SSL_WANT_WRITE) {
5384 ctx->saved_len = len;
5386 return mg_ssl_if_mbed_err(nc,
n);
5394 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
5395 if (ctx == NULL)
return;
5396 mbedtls_ssl_close_notify(ctx->ssl);
5400 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
5401 if (ctx == NULL)
return;
5402 nc->ssl_if_data = NULL;
5403 if (ctx->ssl != NULL) {
5404 mbedtls_ssl_free(ctx->ssl);
5407 mg_ssl_if_mbed_free_certs_and_keys(ctx);
5408 if (ctx->conf != NULL) {
5409 mbedtls_ssl_config_free(ctx->conf);
5413 memset(ctx, 0,
sizeof(*ctx));
5417static enum mg_ssl_if_result mg_use_ca_cert(
struct mg_ssl_if_ctx *ctx,
5418 const char *ca_cert) {
5419 if (ca_cert == NULL || strcmp(ca_cert,
"*") == 0) {
5420 mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
5423 ctx->ca_cert = (mbedtls_x509_crt *)
MG_CALLOC(1,
sizeof(*ctx->ca_cert));
5424 mbedtls_x509_crt_init(ctx->ca_cert);
5425#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
5426 ca_cert = strdup(ca_cert);
5427 mbedtls_ssl_conf_ca_chain_file(ctx->conf, ca_cert, NULL);
5429 if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) {
5430 return MG_SSL_ERROR;
5432 mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL);
5434 mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
5438static enum mg_ssl_if_result mg_use_cert(
struct mg_ssl_if_ctx *ctx,
5439 const char *cert,
const char *
key,
5440 const char **err_msg) {
5441 if (
key == NULL)
key = cert;
5442 if (cert == NULL || cert[0] ==
'\0' ||
key == NULL ||
key[0] ==
'\0') {
5445 ctx->cert = (mbedtls_x509_crt *)
MG_CALLOC(1,
sizeof(*ctx->cert));
5446 mbedtls_x509_crt_init(ctx->cert);
5447 ctx->key = (mbedtls_pk_context *)
MG_CALLOC(1,
sizeof(*ctx->key));
5448 mbedtls_pk_init(ctx->key);
5449 if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) {
5451 return MG_SSL_ERROR;
5453 if (mbedtls_pk_parse_keyfile(ctx->key,
key, NULL) != 0) {
5455 return MG_SSL_ERROR;
5457 if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) {
5459 return MG_SSL_ERROR;
5464static const int mg_s_cipher_list[] = {
5465#if CS_PLATFORM != CS_P_ESP8266
5466 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
5467 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
5468 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
5469 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
5470 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
5471 MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
5472 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
5473 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
5474 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
5475 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
5476 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
5477 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
5478 MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
5479 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
5480 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
5487 MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
5488 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
5489 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
5490 MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
5491 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
5492 MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
5493 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
5494 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
5495 MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
5496 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
5497 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
5498 MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
5499 MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
5510static enum mg_ssl_if_result mg_set_cipher_list(
struct mg_ssl_if_ctx *ctx,
5511 const char *ciphers) {
5512 if (ciphers != NULL) {
5514 const char *s = ciphers, *
e;
5518 l = (
e != NULL ? (
e - s) : (int) strlen(s));
5521 id = mbedtls_ssl_get_ciphersuite_id(tmp);
5522 DBG((
"%s -> %04x", tmp,
id));
5524 mbuf_append(&ctx->cipher_suites, &
id,
sizeof(
id));
5526 s = (
e != NULL ?
e + 1 : NULL);
5528 if (ctx->cipher_suites.len == 0)
return MG_SSL_ERROR;
5530 mbuf_append(&ctx->cipher_suites, &
id,
sizeof(
id));
5532 mbedtls_ssl_conf_ciphersuites(ctx->conf,
5533 (
const int *) ctx->cipher_suites.buf);
5535 mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list);
5540#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
5541static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(
struct mg_ssl_if_ctx *ctx,
5542 const char *identity,
5543 const char *key_str) {
5544 unsigned char key[32];
5546 if (identity == NULL && key_str == NULL)
return MG_SSL_OK;
5547 if (identity == NULL || key_str == NULL)
return MG_SSL_ERROR;
5548 key_len = strlen(key_str);
5549 if (key_len != 32 && key_len != 64)
return MG_SSL_ERROR;
5551 memset(
key, 0,
sizeof(
key));
5553 for (
i = 0; key_str[
i] !=
'\0';
i++) {
5555 char hc = tolower((
int) key_str[
i]);
5556 if (hc >=
'0' && hc <=
'9') {
5558 }
else if (hc >=
'a' && hc <=
'f') {
5561 return MG_SSL_ERROR;
5568 DBG((
"identity = '%s', key = (%u)", identity, (
unsigned int) key_len));
5570 if (mbedtls_ssl_conf_psk(ctx->conf, (
const unsigned char *)
key, key_len,
5571 (
const unsigned char *) identity,
5572 strlen(identity)) != 0) {
5573 return MG_SSL_ERROR;
5580 const char *ca_cert) {
5581 const char *err_msg = NULL;
5582 struct mg_ssl_if_conn_params params;
5583 memset(¶ms, 0,
sizeof(params));
5585 params.ca_cert = ca_cert;
5586 if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
5593#ifdef MG_SSL_MBED_DUMMY_RANDOM
5594int mg_ssl_if_mbed_random(
void *ctx,
unsigned char *buf,
size_t len) {
5596 while (len--) *buf++ = rand();
5602#ifdef MG_MODULE_LINES
5603#line 1 "mongoose/src/mg_uri.c"
5620 const char *seps,
struct mg_str *res) {
5623 for (; *p <
end; (*p)++) {
5624 for (
q = seps; *
q !=
'\0';
q++) {
5625 if (**p == *
q)
break;
5627 if (*
q !=
'\0')
break;
5629 res->
len = (*p) - res->
p;
5630 if (*p <
end) (*p)++;
5635 unsigned int *port,
struct mg_str *path,
struct mg_str *query,
5636 struct mg_str *fragment) {
5637 struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
5638 rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
5639 unsigned int rport = 0;
5649 const char *
p = uri.
p, *
end =
p + uri.
len;
5664 for (;
p <
end;
p++) {
5666 state = P_SCHEME_OR_PORT;
5668 }
else if (*
p ==
'/') {
5675 rhost.len =
p - uri.
p;
5678 case P_SCHEME_OR_PORT:
5679 if (
end -
p >= 3 && strncmp(
p,
"://", 3) == 0) {
5681 rscheme.
len =
p - uri.
p;
5682 state = P_USER_INFO;
5686 rhost.len =
p - uri.
p;
5692 for (;
p <
end;
p++) {
5693 if (*
p ==
'@' || *
p ==
'[' || *
p ==
'/') {
5697 if (
p ==
end || *
p ==
'/' || *
p ==
'[') {
5701 ruser_info.len =
p - ruser_info.p;
5709 for (; !found &&
p <
end;
p++) {
5710 found = (*
p ==
']');
5712 if (!found)
return -1;
5714 for (;
p <
end;
p++) {
5715 if (*
p ==
':' || *
p ==
'/')
break;
5718 rhost.len =
p - rhost.p;
5723 }
else if (*
p ==
'/') {
5731 for (;
p <
end;
p++) {
5743 if (
p <
end && *(
p - 1) ==
'?') {
5751 if (scheme != 0) *scheme = rscheme;
5752 if (user_info != 0) *user_info = ruser_info;
5753 if (host != 0) *host = rhost;
5754 if (port != 0) *port = rport;
5755 if (path != 0) *path = rpath;
5756 if (query != 0) *query = rquery;
5757 if (fragment != 0) *fragment = rfragment;
5764 const char *s = in->
p, *se = s + in->
len;
5765 char *cp = (
char *) out->
p, *
d;
5767 if (in->
len == 0 || *s !=
'/') {
5775 const char *next = s;
5778 if (
mg_vcmp(&component,
".") == 0) {
5780 }
else if (
mg_vcmp(&component,
"..") == 0) {
5782 if (
d > cp + 1 && *(
d - 1) ==
'/')
d--;
5783 while (
d > cp && *(
d - 1) !=
'/')
d--;
5785 memmove(
d, s, next - s);
5790 if (
d == cp) *
d++ =
'/';
5798 const struct mg_str *host,
unsigned int port,
5800 const struct mg_str *fragment,
int normalize_path,
5806 if (scheme != NULL && scheme->
len > 0) {
5811 if (user_info != NULL && user_info->
len > 0) {
5816 if (host != NULL && host->
len > 0) {
5822 int port_str_len = sprintf(port_str,
":%u", port);
5826 if (path != NULL && path->
len > 0) {
5827 if (normalize_path) {
5829 if (npath.
len != path->
len)
goto out;
5831 free((
void *) npath.
p);
5835 free((
void *) npath.
p);
5839 }
else if (normalize_path) {
5843 if (query != NULL && query->
len > 0) {
5848 if (fragment != NULL && fragment->
len > 0) {
5866#ifdef MG_MODULE_LINES
5867#line 1 "mongoose/src/mg_http.c"
5890 size_t user_buf_size;
5896MG_INTERNAL void altbuf_init(
struct altbuf *ab,
char *
buf,
size_t buf_size) {
5899 ab->user_buf_size = buf_size;
5906MG_INTERNAL void altbuf_append(
struct altbuf *ab,
char c) {
5907 if (ab->len < ab->user_buf_size) {
5909 ab->user_buf[ab->len++] =
c;
5918 if (ab->len > 0 && ab->m.len == 0) {
5923 ab->len = ab->m.len;
5939MG_INTERNAL int altbuf_reallocated(
struct altbuf *ab) {
5940 return ab->len > ab->user_buf_size;
5947MG_INTERNAL char *altbuf_get_buf(
struct altbuf *ab,
int trim) {
5948 if (altbuf_reallocated(ab)) {
5954 return ab->user_buf;
5960static const char *mg_version_header =
"Mongoose/" MG_VERSION;
5972#if MG_ENABLE_HTTP_CGI
5984 struct mg_str uri_pattern;
5989#if MG_ENABLE_CALLBACK_USERDATA
6014struct mg_reverse_proxy_data {
6018struct mg_ws_proto_data {
6029#if MG_ENABLE_FILESYSTEM
6032#if MG_ENABLE_HTTP_CGI
6035#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6038#if MG_ENABLE_HTTP_WEBSOCKET
6039 struct mg_ws_proto_data ws_data;
6044 struct mg_reverse_proxy_data reverse_proxy_data;
6048static void mg_http_proto_data_destructor(
void *proto_data);
6052 struct mg_connect_opts opts,
const char *scheme1,
const char *scheme2,
6053 const char *scheme_ssl1,
const char *scheme_ssl2,
const char *url,
6059 if (
c->proto_data != NULL) {
6060 void *pd =
c->proto_data;
6061 c->proto_data = NULL;
6062 mg_http_proto_data_destructor(pd);
6065 c->proto_data_destructor = mg_http_proto_data_destructor;
6074#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6075static void mg_http_free_proto_data_mp_stream(
6080 memset(mp, 0,
sizeof(*mp));
6084#if MG_ENABLE_FILESYSTEM
6087 if (
d->fp != NULL) {
6098 while (current != NULL) {
6100 MG_FREE((
void *) current->uri_pattern.p);
6101 MG_FREE((
void *) current->auth_domain);
6102 MG_FREE((
void *) current->auth_file);
6110static void mg_http_free_reverse_proxy_data(
struct mg_reverse_proxy_data *rpd) {
6111 if (rpd->linked_conn != NULL) {
6118 if (pd->reverse_proxy_data.linked_conn != NULL) {
6120 pd->reverse_proxy_data.linked_conn = NULL;
6122 rpd->linked_conn = NULL;
6126static void mg_http_proto_data_destructor(
void *proto_data) {
6128#if MG_ENABLE_FILESYSTEM
6131#if MG_ENABLE_HTTP_CGI
6134#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6135 mg_http_free_proto_data_mp_stream(&pd->mp_stream);
6138 mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data);
6142#if MG_ENABLE_FILESYSTEM
6144#define MIME_ENTRY(_ext, _type) \
6145 { _ext, sizeof(_ext) - 1, _type }
6146static const struct {
6157 MIME_ENTRY(
"js",
"application/x-javascript"),
6165 MIME_ENTRY(
"torrent",
"application/x-bittorrent"),
6179 MIME_ENTRY(
"exe",
"application/octet-stream"),
6180 MIME_ENTRY(
"zip",
"application/x-zip-compressed"),
6185 MIME_ENTRY(
"arj",
"application/x-arj-compressed"),
6186 MIME_ENTRY(
"rar",
"application/x-rar-compressed"),
6189 MIME_ENTRY(
"swf",
"application/x-shockwave-flash"),
6203 const char *ext, *overrides;
6207 path_len = strlen(path);
6209 overrides = opts->custom_mime_types;
6211 ext = path + (path_len -
k.len);
6222 r.len = strlen(r.p);
6228 r.len = strlen(r.p);
6240 const unsigned char *buf = (
unsigned char *) s;
6243 for (
i = 0;
i < buf_len;
i++) {
6244 if (!isprint(buf[
i]) && buf[
i] !=
'\r' && buf[
i] !=
'\n' && buf[
i] < 128) {
6246 }
else if (buf[
i] ==
'\n' &&
i + 1 < buf_len && buf[
i + 1] ==
'\n') {
6248 }
else if (buf[
i] ==
'\n' &&
i + 2 < buf_len && buf[
i + 1] ==
'\r' &&
6249 buf[
i + 2] ==
'\n') {
6266 while (v->len > 0 && v->p[v->len - 1] ==
' ') {
6275 if (
k->len != 0 && v->len == 0) {
6279 if (
k->len == 0 || v->len == 0) {
6281 k->len = v->len = 0;
6286 req->
body.
len = (size_t) to64(v->p);
6297 const char *
end, *qs;
6300 if (
len <= 0)
return len;
6302 memset(hm, 0,
sizeof(*hm));
6309 while (s <
end && isspace(*(
unsigned char *) s)) s++;
6319 if ((qs = (
char *) memchr(hm->
uri.
p,
'?', hm->
uri.
len)) != NULL) {
6326 if (
end - s < 4 || s[0] <
'0' || s[0] >
'9' || s[3] !=
' ')
return -1;
6350 if (hm->
body.
len == (
size_t) ~0 && is_req &&
6372#if MG_ENABLE_FILESYSTEM
6385 if (to_read >
left) {
6393 DBG((
"%p sent %d (total %d)", nc, (
int)
n, (
int) pd->
file.
sent));
6400 pd->
file.keepalive));
6407 size_t n = mg_fwrite(io->
buf, 1, to_write, pd->
file.
fp);
6417#if MG_ENABLE_HTTP_CGI
6436 size_t *chunk_len) {
6437 unsigned char *s = (
unsigned char *)
buf;
6442 while (
i <
len && isxdigit(s[
i])) {
6444 n += (s[
i] >=
'0' && s[
i] <=
'9') ? s[
i] -
'0' : tolower(s[
i]) -
'a' + 10;
6453 if (
i == 0 ||
i + 2 >
len || s[
i] !=
'\r' || s[
i + 1] !=
'\n') {
6459 *chunk_data = (
char *) s +
i;
6466 if (
i == 0 ||
i + 2 >
len || s[
i] !=
'\r' || s[
i + 1] !=
'\n') {
6477 size_t i,
n, data_len, body_len, zero_chunk_received = 0;
6480 assert(blen >= body_len);
6487 memmove(buf + body_len,
data, data_len);
6488 body_len += data_len;
6491 if (data_len == 0) {
6492 zero_chunk_received = 1;
6501 memmove(buf + body_len, buf +
i, blen -
i);
6502 memset(buf + body_len + blen -
i, 0,
i - body_len);
6507 nc->
flags &= ~MG_F_DELETE_CHUNK;
6512 memset(buf, 0, body_len);
6513 memmove(buf, buf + body_len, blen -
i);
6519 if (zero_chunk_received) {
6530 struct mg_str *uri_path) {
6533 int matched, matched_max = 0;
6536 if (nc == NULL)
return NULL;
6540 if (pd == NULL)
return NULL;
6543 while (ep != NULL) {
6545 if (matched > matched_max) {
6548 matched_max = matched;
6558#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6559static void mg_http_multipart_continue(
struct mg_connection *nc);
6561static void mg_http_multipart_begin(
struct mg_connection *nc,
6572 hm->
body.
len =
c->recv_mbuf.len - req_len;
6573 c->flags &= ~MG_F_DELETE_CHUNK;
6585static void mg_http_handler2(
struct mg_connection *nc,
int ev,
6586 void *ev_data
MG_UD_ARG(
void *user_data),
6590 void *ev_data
MG_UD_ARG(
void *user_data)) {
6592 mg_http_handler2(nc, ev, ev_data
MG_UD_ARG(user_data), &hm);
6595static void mg_http_handler2(
struct mg_connection *nc,
int ev,
6596 void *ev_data
MG_UD_ARG(
void *user_data),
6600 void *ev_data
MG_UD_ARG(
void *user_data)) {
6606 const int is_req = (nc->
listener != NULL);
6607#if MG_ENABLE_HTTP_WEBSOCKET
6611#if MG_ENABLE_HTTP_CGI
6613 if (pd != NULL && pd->
cgi.
cgi_nc != NULL) {
6618#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6619 if (pd != NULL && pd->mp_stream.boundary != NULL) {
6625 memset(&mp, 0,
sizeof(mp));
6628 mp.
var_name = pd->mp_stream.var_name;
6631 nc->
user_data, MG_EV_HTTP_PART_END, &mp);
6635 nc->
user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp);
6647 deliver_chunk(nc, hm, req_len);
6656#if MG_ENABLE_FILESYSTEM
6657 if (pd != NULL && pd->
file.
fp != NULL) {
6664#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6665 if (pd != NULL && pd->mp_stream.boundary != NULL &&
6668 pd->rcvd += *(
int *) ev_data;
6669 mg_http_multipart_continue(nc);
6670 }
else if (pd->mp_stream.data_avail) {
6672 mg_http_multipart_continue(nc);
6687 pd = mg_http_create_proto_data(nc);
6698#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6700 s->
len >= 9 && strncmp(s->
p,
"multipart", 9) == 0) {
6701 mg_http_multipart_begin(nc, hm, req_len);
6702 mg_http_multipart_continue(nc);
6710 DBG((
"invalid request"));
6712 }
else if (req_len == 0) {
6715#if MG_ENABLE_HTTP_WEBSOCKET
6718 DBG((
"%p WebSocket upgrade code %d", nc, hm->
resp_code));
6750#if MG_ENABLE_CALLBACK_USERDATA
6770 deliver_chunk(nc, hm, req_len);
6772 LOG(
LL_ERROR, (
"%p recv buffer (%lu bytes) exceeds the limit "
6773 "%lu bytes, and not drained, closing",
6780 int request_done = 1;
6787 deliver_chunk(nc, hm, req_len);
6792#if MG_ENABLE_FILESYSTEM
6797 if (pd->
file.
fp != NULL) request_done = 0;
6799#if MG_ENABLE_HTTP_CGI
6801 if (pd->
cgi.
cgi_nc != NULL) request_done = 0;
6803 if (request_done && io->
len > 0)
goto again;
6810 while (len < buf_len && buf[len] !=
'\n') len++;
6811 return len == buf_len ? 0 : len + 1;
6814#if MG_ENABLE_HTTP_STREAMING_MULTIPART
6815static void mg_http_multipart_begin(
struct mg_connection *nc,
6821 char boundary_buf[100];
6822 char *boundary = boundary_buf;
6832 if (ct->
len < 9 || strncmp(ct->
p,
"multipart", 9) != 0) {
6838 if (boundary_len == 0) {
6844 DBG((
"invalid request"));
6850 if (pd->mp_stream.boundary != NULL) {
6859 pd->mp_stream.boundary = strdup(boundary);
6860 pd->mp_stream.boundary_len = strlen(boundary);
6861 pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
6874 if (boundary != boundary_buf)
MG_FREE(boundary);
6877#define CONTENT_DISPOSITION "Content-Disposition: "
6879static size_t mg_http_multipart_call_handler(
struct mg_connection *
c,
int ev,
6884 memset(&mp, 0,
sizeof(mp));
6886 mp.
var_name = pd->mp_stream.var_name;
6890 mp.data.len = data_len;
6891 mp.num_data_consumed = data_len;
6894 pd->mp_stream.data_avail = (mp.num_data_consumed != data_len);
6895 return mp.num_data_consumed;
6901 mg_http_multipart_call_handler(
c, MG_EV_HTTP_PART_END, NULL, 0);
6902 MG_FREE((
void *) pd->mp_stream.file_name);
6903 pd->mp_stream.file_name = NULL;
6904 MG_FREE((
void *) pd->mp_stream.var_name);
6905 pd->mp_stream.var_name = NULL;
6906 mg_http_multipart_call_handler(
c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0);
6907 mg_http_free_proto_data_mp_stream(&pd->mp_stream);
6913static int mg_http_multipart_wait_for_boundary(
struct mg_connection *
c) {
6914 const char *boundary;
6915 struct mbuf *io = &
c->recv_mbuf;
6918 if (pd->mp_stream.boundary == NULL) {
6920 DBG((
"Invalid request: boundary not initialized"));
6924 if ((
int) io->
len < pd->mp_stream.boundary_len + 2) {
6929 if (boundary != NULL) {
6930 const char *boundary_end = (boundary + pd->mp_stream.boundary_len);
6931 if (io->
len - (boundary_end - io->
buf) < 4) {
6934 if (strncmp(boundary_end,
"--\r\n", 4) == 0) {
6947static void mg_http_parse_header_internal(
struct mg_str *hdr,
6951static int mg_http_multipart_process_boundary(
struct mg_connection *
c) {
6953 const char *boundary, *block_begin;
6954 struct mbuf *io = &
c->recv_mbuf;
6956 struct altbuf ab_file_name, ab_var_name;
6959 block_begin = boundary + pd->mp_stream.boundary_len + 2;
6960 data_size = io->
len - (block_begin - io->
buf);
6962 altbuf_init(&ab_file_name, NULL, 0);
6963 altbuf_init(&ab_var_name, NULL, 0);
6965 while (data_size > 0 &&
6967 if (line_len > (
int)
sizeof(CONTENT_DISPOSITION) &&
6969 sizeof(CONTENT_DISPOSITION) - 1) == 0) {
6972 header.
p = block_begin +
sizeof(CONTENT_DISPOSITION) - 1;
6973 header.len = line_len -
sizeof(CONTENT_DISPOSITION) - 1;
6975 altbuf_reset(&ab_var_name);
6976 mg_http_parse_header_internal(&header,
"name", &ab_var_name);
6978 altbuf_reset(&ab_file_name);
6979 mg_http_parse_header_internal(&header,
"filename", &ab_file_name);
6981 block_begin += line_len;
6982 data_size -= line_len;
6987 if (line_len == 2 &&
mg_ncasecmp(block_begin,
"\r\n", 2) == 0) {
6990 if (pd->mp_stream.processing_part != 0) {
6991 mg_http_multipart_call_handler(
c, MG_EV_HTTP_PART_END, NULL, 0);
6995 altbuf_append(&ab_file_name,
'\0');
6996 altbuf_append(&ab_file_name,
'\0');
6997 altbuf_append(&ab_var_name,
'\0');
6998 altbuf_append(&ab_var_name,
'\0');
7000 MG_FREE((
void *) pd->mp_stream.file_name);
7001 pd->mp_stream.file_name = altbuf_get_buf(&ab_file_name, 1 );
7002 MG_FREE((
void *) pd->mp_stream.var_name);
7003 pd->mp_stream.var_name = altbuf_get_buf(&ab_var_name, 1 );
7005 mg_http_multipart_call_handler(
c, MG_EV_HTTP_PART_BEGIN, NULL, 0);
7007 pd->mp_stream.processing_part++;
7011 block_begin += line_len;
7016 altbuf_reset(&ab_var_name);
7017 altbuf_reset(&ab_file_name);
7022static int mg_http_multipart_continue_wait_for_chunk(
struct mg_connection *
c) {
7024 struct mbuf *io = &
c->recv_mbuf;
7026 const char *boundary;
7027 if ((
int) io->
len < pd->mp_stream.boundary_len + 6 ) {
7032 if (boundary == NULL) {
7033 int data_len = (io->
len - (pd->mp_stream.boundary_len + 6));
7035 size_t consumed = mg_http_multipart_call_handler(
7036 c, MG_EV_HTTP_PART_DATA, io->
buf, (
size_t) data_len);
7040 }
else if (boundary != NULL) {
7041 size_t data_len = ((size_t)(boundary - io->
buf) - 4);
7042 size_t consumed = mg_http_multipart_call_handler(
c, MG_EV_HTTP_PART_DATA,
7045 if (consumed == data_len) {
7060 switch (pd->mp_stream.state) {
7066 if (mg_http_multipart_wait_for_boundary(
c) == 0) {
7072 if (mg_http_multipart_process_boundary(
c) == 0) {
7078 if (mg_http_multipart_continue_wait_for_chunk(
c) == 0) {
7084 if (mg_http_multipart_finalize(
c) == 0) {
7096struct file_upload_state {
7108const char *mg_status_message(
int status_code) {
7109 switch (status_code) {
7111 return "Partial Content";
7117 return "Bad Request";
7119 return "Unauthorized";
7125 return "Requested Range Not Satisfiable";
7127 return "I'm a teapot";
7129 return "Internal Server Error";
7131 return "Bad Gateway";
7133 return "Service Unavailable";
7135#if MG_ENABLE_EXTRA_ERRORS_DESC
7139 return "Switching Protocols";
7141 return "Processing";
7149 return "Non-Authoritative Information";
7151 return "No Content";
7153 return "Reset Content";
7155 return "Multi-Status";
7157 return "Already Reported";
7161 return "Multiple Choices";
7165 return "Not Modified";
7169 return "Switch Proxy";
7171 return "Temporary Redirect";
7173 return "Permanent Redirect";
7175 return "Payment Required";
7177 return "Method Not Allowed";
7179 return "Not Acceptable";
7181 return "Proxy Authentication Required";
7183 return "Request Timeout";
7189 return "Length Required";
7191 return "Precondition Failed";
7193 return "Payload Too Large";
7195 return "URI Too Long";
7197 return "Unsupported Media Type";
7199 return "Expectation Failed";
7201 return "Unprocessable Entity";
7205 return "Failed Dependency";
7207 return "Upgrade Required";
7209 return "Precondition Required";
7211 return "Too Many Requests";
7213 return "Request Header Fields Too Large";
7215 return "Unavailable For Legal Reasons";
7217 return "Not Implemented";
7219 return "Gateway Timeout";
7221 return "HTTP Version Not Supported";
7223 return "Variant Also Negotiates";
7225 return "Insufficient Storage";
7227 return "Loop Detected";
7229 return "Not Extended";
7231 return "Network Authentication Required";
7239void mg_send_response_line_s(
struct mg_connection *nc,
int status_code,
7240 const struct mg_str extra_headers) {
7241 mg_printf(nc,
"HTTP/1.1 %d %s\r\n", status_code,
7242 mg_status_message(status_code));
7243#ifndef MG_HIDE_SERVER_INFO
7244 mg_printf(nc,
"Server: %s\r\n", mg_version_header);
7246 if (extra_headers.
len > 0) {
7247 mg_printf(nc,
"%.*s\r\n", (
int) extra_headers.
len, extra_headers.
p);
7252 const char *extra_headers) {
7253 mg_send_response_line_s(nc, status_code,
mg_mk_str(extra_headers));
7257 const struct mg_str location,
7258 const struct mg_str extra_headers) {
7259 char bbody[100], *pbody = bbody;
7261 "<p>Moved <a href='%.*s'>here</a>.\r\n",
7262 (
int) location.
len, location.
p);
7263 char bhead[150], *phead = bhead;
7265 "Location: %.*s\r\n"
7266 "Content-Type: text/html\r\n"
7267 "Content-Length: %d\r\n"
7268 "Cache-Control: no-cache\r\n"
7270 (
int) location.
len, location.
p,
bl, (
int) extra_headers.
len,
7271 extra_headers.
p, (extra_headers.
len > 0 ?
"\r\n" :
""));
7273 if (phead != bhead)
MG_FREE(phead);
7275 if (pbody != bbody)
MG_FREE(pbody);
7279 int64_t content_length,
const char *extra_headers) {
7281 if (content_length < 0) {
7282 mg_printf(
c,
"%s",
"Transfer-Encoding: chunked\r\n");
7290 const char *reason) {
7291 if (!reason) reason = mg_status_message(code);
7294 "Content-Type: text/plain\r\nConnection: close");
7295 mg_send(nc, reason, strlen(reason));
7299#if MG_ENABLE_FILESYSTEM
7301 const cs_stat_t *st) {
7302 snprintf(buf, buf_len,
"\"%lx.%" INT64_FMT "\"", (
unsigned long) st->st_mtime,
7303 (int64_t) st->st_size);
7308 strftime(buf, buf_len,
"%a, %d %b %Y %H:%M:%S GMT",
gmtime(t));
7323 if (p == NULL)
return 0;
7324 memcpy(p, header->
p, header->
len);
7325 p[header->
len] =
'\0';
7333 const struct mg_str extra_headers) {
7351 char etag[50], current_time[50], last_modified[50], range[70];
7352 time_t t = (time_t)
mg_time();
7353 int64_t r1 = 0, r2 = 0, cl = st.st_size;
7355 int n, status_code = 200;
7359 if (range_hdr != NULL &&
7366 if (r1 > r2 || r2 >= cl) {
7369 snprintf(range,
sizeof(range),
7370 "Content-Range: bytes */%" INT64_FMT "\r\n",
7371 (int64_t) st.st_size);
7375 snprintf(range,
sizeof(range),
"Content-Range: bytes %" INT64_FMT
7377 r1, r1 + cl - 1, (int64_t) st.st_size);
7378#if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
7379 _XOPEN_SOURCE >= 600
7380 fseeko(pd->
file.
fp, r1, SEEK_SET);
7382 fseek(pd->
file.
fp, (
long) r1, SEEK_SET);
7387#if !MG_DISABLE_HTTP_KEEP_ALIVE
7390 if (conn_hdr != NULL) {
7408 mg_send_response_line_s(nc, status_code, extra_headers);
7411 "Last-Modified: %s\r\n"
7412 "Accept-Ranges: bytes\r\n"
7413 "Content-Type: %.*s\r\n"
7414 "Connection: %s\r\n"
7415 "Content-Length: %" SIZE_T_FMT
7417 "%sEtag: %s\r\n\r\n",
7419 (pd->
file.keepalive ?
"keep-alive" :
"close"), (size_t) cl, range,
7428static void mg_http_serve_file2(
struct mg_connection *nc,
const char *path,
7431#if MG_ENABLE_HTTP_SSI
7437 mg_http_serve_file(nc, hm, path,
mg_get_mime_type(path,
"text/plain", opts),
7443int mg_url_decode(
const char *src,
int src_len,
char *dst,
int dst_len,
7444 int is_form_url_encoded) {
7446#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
7448 for (
i =
j = 0;
i < src_len &&
j < dst_len - 1;
i++,
j++) {
7449 if (src[
i] ==
'%') {
7450 if (
i < src_len - 2 && isxdigit(*(
const unsigned char *) (src +
i + 1)) &&
7451 isxdigit(*(
const unsigned char *) (src +
i + 2))) {
7452 a = tolower(*(
const unsigned char *) (src +
i + 1));
7453 b = tolower(*(
const unsigned char *) (src +
i + 2));
7459 }
else if (is_form_url_encoded && src[
i] ==
'+') {
7468 return i >= src_len ?
j : -1;
7473 const char *
p, *
e, *s;
7485 if (dst == NULL || dst_len == 0) {
7487 }
else if (buf->
p == NULL ||
name == NULL || buf->
len == 0) {
7491 name_len = strlen(
name);
7492 e = buf->
p + buf->
len;
7496 for (
p = buf->
p;
p + name_len <
e;
p++) {
7497 if ((
p == buf->
p ||
p[-1] ==
'&') &&
p[name_len] ==
'=' &&
7500 s = (
const char *) memchr(
p,
'&', (
size_t)(
e -
p));
7518 char chunk_size[50];
7521 n = snprintf(chunk_size,
sizeof(chunk_size),
"%lX\r\n", (
unsigned long)
len);
7541 if (buf != mem && buf != NULL) {
7557 for (
i =
j = 0;
i <
len;
i++) {
7558 if (buf[
i] ==
'<' || buf[
i] ==
'>') {
7560 mg_send(nc, buf[
i] ==
'<' ?
"<" :
">", 4);
7568 if (buf != mem && buf != NULL) {
7574static void mg_http_parse_header_internal(
struct mg_str *hdr,
7576 struct altbuf *ab) {
7577 int ch =
' ', ch1 =
',', ch2 =
';',
n = strlen(
var_name);
7578 const char *
p, *
end = hdr ? hdr->
p + hdr->
len : NULL, *s = NULL;
7581 for (s = hdr->
p; s != NULL && s +
n <
end; s++) {
7582 if ((s == hdr->
p || s[-1] == ch || s[-1] == ch1 || s[-1] ==
';') &&
7587 if (s != NULL && &s[
n + 1] <
end) {
7589 if (*s ==
'"' || *s ==
'\'') {
7590 ch = ch1 = ch2 = *s++;
7593 while (
p <
end &&
p[0] != ch &&
p[0] != ch1 &&
p[0] != ch2) {
7594 if (ch !=
' ' &&
p[0] ==
'\\' &&
p[1] == ch)
p++;
7595 altbuf_append(ab, *
p++);
7598 if (ch !=
' ' && *
p != ch) {
7605 altbuf_append(ab,
'\0');
7612 altbuf_init(&ab, *buf, buf_size);
7613 if (hdr == NULL)
return 0;
7614 if (*buf != NULL && buf_size > 0) *buf[0] =
'\0';
7616 mg_http_parse_header_internal(hdr,
var_name, &ab);
7622 *buf = altbuf_get_buf(&ab, 1 );
7623 return ab.len > 0 ? ab.len - 1 : 0;
7642 char *pass,
size_t pass_len) {
7644 if (hdr == NULL)
return -1;
7649 char *pass,
size_t pass_len) {
7660 snprintf(fmt,
sizeof(fmt),
"%%%" SIZE_T_FMT
"[^:]:%%%" SIZE_T_FMT
"[^\n]",
7661 user_len - 1, pass_len - 1);
7662 if (sscanf(buf, fmt, user, pass) == 0) {
7670#if MG_ENABLE_FILESYSTEM
7673 int exclude_specials) {
7678 const char *pdir = strrchr(path, DIRSEP);
7683 return (exclude_specials && (!strcmp(path,
".") || !strcmp(path,
".."))) ||
7684 (p1 != NULL &&
mg_match_prefix(p1, strlen(p1), path) == strlen(p1)) ||
7688#if !MG_DISABLE_HTTP_DIGEST_AUTH
7692 const size_t *msg_lens, uint8_t *digest) {
7696 for (
i = 0;
i < num_msgs;
i++) {
7702extern void mg_hash_md5_v(
size_t num_msgs,
const uint8_t *msgs[],
7703 const size_t *msg_lens, uint8_t *digest);
7706void cs_md5(
char buf[33], ...) {
7707 unsigned char hash[16];
7708 const uint8_t *msgs[20], *
p;
7709 size_t msg_lens[20];
7710 size_t num_msgs = 0;
7714 while ((
p = va_arg(ap,
const unsigned char *) ) != NULL) {
7716 msg_lens[num_msgs] = va_arg(ap,
size_t);
7725static void mg_mkmd5resp(
const char *method,
size_t method_len,
const char *uri,
7726 size_t uri_len,
const char *ha1,
size_t ha1_len,
7727 const char *nonce,
size_t nonce_len,
const char *nc,
7728 size_t nc_len,
const char *cnonce,
size_t cnonce_len,
7729 const char *qop,
size_t qop_len,
char *resp) {
7730 static const char colon[] =
":";
7731 static const size_t one = 1;
7733 cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
7734 cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
7735 nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
7736 colon, one, ha2,
sizeof(ha2) - 1, NULL);
7740 const char *method,
const char *uri,
7741 const char *auth_domain,
const char *user,
7742 const char *passwd,
const char *nonce) {
7743 static const char colon[] =
":", qop[] =
"auth";
7744 static const size_t one = 1;
7745 char ha1[33], resp[33], cnonce[40];
7747 snprintf(cnonce,
sizeof(cnonce),
"%lx", (
unsigned long)
mg_time());
7748 cs_md5(ha1, user, (
size_t) strlen(user), colon, one, auth_domain,
7749 (
size_t) strlen(auth_domain), colon, one, passwd,
7750 (
size_t) strlen(passwd), NULL);
7751 mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1,
sizeof(ha1) - 1,
7752 nonce, strlen(nonce),
"1", one, cnonce, strlen(cnonce), qop,
7753 sizeof(qop) - 1, resp);
7754 return snprintf(buf, buf_len,
7755 "Authorization: Digest username=\"%s\","
7756 "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
7757 "nonce=%s,response=%s\r\n",
7758 user, auth_domain, uri, qop, cnonce, nonce, resp);
7768 unsigned long now = (
unsigned long)
mg_time();
7769 unsigned long val = (
unsigned long) strtoul(nonce, NULL, 16);
7770 return (now >= val) && (now - val < 60 * 60);
7777 char username_buf[50], cnonce_buf[64], response_buf[40], uri_buf[200],
7778 qop_buf[20], nc_buf[20], nonce_buf[16];
7780 char *username = username_buf, *cnonce = cnonce_buf, *
response = response_buf,
7781 *uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf;
7784 if (hm == NULL ||
fp == NULL ||
7812 if (username != username_buf)
MG_FREE(username);
7813 if (cnonce != cnonce_buf)
MG_FREE(cnonce);
7815 if (uri != uri_buf)
MG_FREE(uri);
7816 if (qop != qop_buf)
MG_FREE(qop);
7817 if (nc != nc_buf)
MG_FREE(nc);
7818 if (nonce != nonce_buf)
MG_FREE(nonce);
7827 struct mg_str auth_domain, FILE *
fp) {
7828 char buf[128], f_user[
sizeof(buf)], f_ha1[
sizeof(buf)], f_domain[
sizeof(buf)];
7836 while (fgets(buf,
sizeof(buf),
fp) != NULL) {
7837 if (sscanf(buf,
"%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
7838 mg_vcmp(&username, f_user) == 0 &&
7839 mg_vcmp(&auth_domain, f_domain) == 0) {
7842 nonce.
p, nonce.
len, nc.
p, nc.
len, cnonce.
p, cnonce.
len,
7843 qop.
p, qop.
len, exp_resp);
7855 const char *domain,
const char *passwords_file,
7862 if (domain != NULL && passwords_file != NULL) {
7866 snprintf(buf,
sizeof(buf),
"%.*s%c%s", (
int) path.
len, path.
p, DIRSEP,
7870 p = strrchr(path.
p, DIRSEP);
7871 if (
p == NULL)
p = path.
p;
7872 snprintf(buf,
sizeof(buf),
"%.*s%c%s", (
int) (
p - path.
p), path.
p, DIRSEP,
7886 passwords_file ? passwords_file :
"", flags, authorized));
7891 const char *domain,
const char *passwords_file,
7896 (void) passwords_file;
7902#if MG_ENABLE_DIRECTORY_LISTING
7903static void mg_escape(
const char *src,
char *dst,
size_t dst_len) {
7905 while (*src !=
'\0' &&
n + 5 < dst_len) {
7906 unsigned char ch = *(
unsigned char *) src++;
7908 n += snprintf(dst +
n, dst_len -
n,
"%s",
"<");
7919 int64_t fsize = stp->st_size;
7920 int is_dir = S_ISDIR(stp->st_mode);
7921 const char *slash = is_dir ?
"/" :
"";
7925 snprintf(size,
sizeof(size),
"%s",
"[DIRECTORY]");
7932 snprintf(size,
sizeof(size),
"%d", (
int) fsize);
7933 }
else if (fsize < 0x100000) {
7934 snprintf(size,
sizeof(size),
"%.1fk", (
double) fsize / 1024.0);
7935 }
else if (fsize < 0x40000000) {
7936 snprintf(size,
sizeof(size),
"%.1fM", (
double) fsize / 1048576);
7938 snprintf(size,
sizeof(size),
"%.1fG", (
double) fsize / 1073741824);
7941 strftime(mod,
sizeof(mod),
"%d-%b-%Y %H:%M",
localtime(&stp->st_mtime));
7945 "<tr><td><a href=\"%s%s\">%s%s</a></td>"
7946 "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
7947 href.p, slash, path, slash, mod, is_dir ? -1 : fsize,
7949 free((
void *) href.p);
7962 if ((dirp = (opendir(dir))) != NULL) {
7963 while ((dp = readdir(dirp)) != NULL) {
7968 snprintf(path,
sizeof(path),
"%s/%s", dir, dp->d_name);
7969 if (
mg_stat(path, &st) == 0) {
7970 func(nc, (
const char *) dp->d_name, &st);
7982 static const char *sort_js_code =
7983 "<script>function srt(tb, sc, so, d) {"
7984 "var tr = Array.prototype.slice.call(tb.rows, 0),"
7985 "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
7986 "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
7987 "t1 = a.cells[2].getAttribute('name'), "
7988 "t2 = b.cells[2].getAttribute('name'); "
7989 "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
7990 "n1 ? parseInt(n2) - parseInt(n1) : "
7991 "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
7992 static const char *sort_js_code2 =
7993 "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
7994 "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
7996 "window.onload = function() {"
7997 "var tb = document.getElementById('tb');"
7998 "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
7999 "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
8000 "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
8001 "sc = c; ev.preventDefault();}};"
8002 "srt(tb, sc, so, true);"
8007 mg_printf(nc,
"%s: %s\r\n%s: %s\r\n\r\n",
"Transfer-Encoding",
"chunked",
8008 "Content-Type",
"text/html; charset=utf-8");
8012 "<html><head><title>Index of %.*s</title>%s%s"
8013 "<style>th,td {text-align: left; padding-right: 1em; "
8014 "font-family: monospace; }</style></head>\n"
8015 "<body><h1>Index of %.*s</h1>\n<table cellpadding=0><thead>"
8016 "<tr><th><a href=# rel=0>Name</a></th><th>"
8017 "<a href=# rel=1>Modified</a</th>"
8018 "<th><a href=# rel=2>Size</a></th></tr>"
8019 "<tr><td colspan=3><hr></td></tr>\n"
8022 (
int) hm->
uri.
len, hm->
uri.
p, sort_js_code, sort_js_code2,
8026 "</tbody><tr><td colspan=3><hr></td></tr>\n"
8028 "<address>%s</address>\n"
8045 char **index_file, cs_stat_t *stp) {
8047 size_t path_len = strlen(path);
8055 size_t len = path_len + 1 +
vec.
len + 1;
8057 if (*index_file == NULL)
break;
8058 snprintf(*index_file,
len,
"%s%c%.*s", path, DIRSEP, (
int)
vec.
len,
vec.p);
8061 if (
mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
8072 LOG(
LL_DEBUG, (
"[%s] [%s]", path, (*index_file ? *index_file :
"")));
8075#if MG_ENABLE_HTTP_URL_REWRITES
8081 char local_port[20] = {
'%'};
8087 if (
mg_vcmp(&a, local_port) == 0) {
8089 mg_printf(
c,
"Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
8090 (
int) b.len, b.p, (
int) (hm->
proto.
p - hm->
uri.
p - 1),
8099static uint64_t ContentLength(
const std::string& msg)
8101 const char* CRLFCRLF =
"\r\n\r\n";
8102 size_t pos = msg.find(CRLFCRLF);
8103 if (pos == std::string::npos) {
8107 return msg.length() - pos - 4;
8110static void SetContentLength(std::string& msg, uint64_t
len)
8112 const char* CRLF =
"\r\n";
8113 const char* CL =
"Content-Length: ";
8114 size_t pos = msg.find(CL);
8115 if (pos == std::string::npos) {
8119 size_t pos2 = msg.find(CRLF, pos);
8120 if (pos2 == std::string::npos) {
8124 sprintf(buf,
"%llu", (
long long unsigned)
len);
8125 msg.replace(pos, pos2-pos, buf);
8129bool Rewrite(std::string&
message,
const char* re,
const char* rs)
8131 bool changed =
false;
8133 size_t len = strlen(re);
8136 if (pos == std::string::npos) {
8145static void mg_reverse_proxy_handler(
struct mg_connection *nc,
int ev,
8146 void *ev_data
MG_UD_ARG(
void *user_data)) {
8150 if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) {
8151 DBG((
"%p: upstream closed", nc));
8161 if (*(
int *) ev_data != 0) {
8178 xstr.
p =
"Transfer-Encoding: chunked";
8179 xstr.
len = strlen(xstr.
p);
8195 bool changed =
false;
8196 std::string
message = message_in;
8197 changed |= Rewrite(
message,
"href=\"/",
"href=\"");
8198 changed |= Rewrite(
message,
"src=\"/",
"src=\"");
8200 changed |= Rewrite(
message,
"post(\"/api/",
"post(\"api/");
8220 mg_send(pd->reverse_proxy_data.linked_conn, io->
buf, io->
len);
8227#if MG_ENABLE_CALLBACK_USERDATA
8234 struct mg_str upstream) {
8236 char burl[256], *purl = burl;
8241 memset(&opts, 0,
sizeof(opts));
8242 opts.error_string = &error;
8244 mg_asprintf(&purl,
sizeof(burl),
"%.*s%.*s%s%.*s", (
int) upstream.
len, upstream.
p,
8250 opts,
"http", NULL,
"https", NULL, purl, &path,
8253 hm->
uri.
p, purl, (
int) mount.
len, mount.
p));
8256 LOG(
LL_ERROR, (
"Error connecting to %s: %s", purl, error));
8261 mg_http_create_proto_data(be);
8269 (
int) path.
len, path.
p);
8271 mg_printf(be,
"Host: %.*s\r\n", (
int) host.len, host.p);
8300 if (purl != burl)
MG_FREE(purl);
8303static int mg_http_handle_forwarding(
struct mg_connection *nc,
8313 mg_http_reverse_proxy(nc, hm, a, b);
8327 struct mg_str *remainder) {
8330 struct mg_str root = {NULL, 0};
8331 const char *file_uri_start = cp;
8333 remainder->
p = NULL;
8338#if MG_ENABLE_HTTP_URL_REWRITES
8341 const char *rewrites =
"";
8347 if (a.len > 1 && a.p[0] ==
'@') {
8349 if (hh != NULL && hh->
len == a.len - 1 &&
8357 if (match_len > 0) {
8358 file_uri_start = hm->
uri.
p + match_len;
8359 if (*file_uri_start ==
'/' || file_uri_start == cp_end) {
8361 }
else if (*(file_uri_start - 1) ==
'/') {
8374 if (root.
p == NULL) {
8375#if MG_ENABLE_HTTP_WEBDAV
8386 assert(root.
p != NULL && root.
len > 0);
8390 const char *u = file_uri_start + 1;
8392 char *lp_end = lp + root.
len + hm->
uri.
len + 1;
8399 memcpy(
p, root.
p, root.
len);
8401 if (*(
p - 1) == DIRSEP)
p--;
8406 while (u <= cp_end) {
8407 const char *next = u;
8411 exists = (
mg_stat(lp, &st) == 0);
8412 if (exists && S_ISREG(st.st_mode)) {
8415 if (*(u - 1) ==
'/') u--;
8419 if (u >= cp_end)
break;
8421 if (component.len > 0) {
8423 memmove(
p + 1, component.p, component.len);
8429 component.p =
p + 1;
8430 component.len =
len;
8431 if (
mg_vcmp(&component,
".") == 0) {
8433 }
else if (
mg_vcmp(&component,
"..") == 0) {
8434 while (
p > ps && *
p != DIRSEP)
p--;
8441 if (to_wchar(component.p, buf,
MG_MAX_PATH) == 0) {
8442 DBG((
"[%.*s] smells funny", (
int) component.len, component.p));
8449 for (
i = 0;
i < component.len;
i++,
p++) {
8450 if (*
p ==
'\0' || *
p == DIRSEP
8467 if (u > cp_end) u = cp_end;
8469 remainder->
len = cp_end - u;
8477 (
"'%.*s' -> '%s' + '%.*s'", (
int) hm->
uri.
len, hm->
uri.
p,
8478 *local_path ? *local_path :
"", (int) remainder->
len, remainder->
p));
8484 static const char *
month_names[] = {
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
8485 "Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"};
8495 return year / 4 - year / 100 + year / 400;
8500 static const unsigned short days_before_month[] = {
8501 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
8503 int second, minute, hour, day, month, year, leap_days, days;
8504 time_t result = (time_t) 0;
8506 if (((sscanf(datetime,
"%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
8507 &minute, &second) == 6) ||
8508 (sscanf(datetime,
"%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
8509 &minute, &second) == 6) ||
8510 (sscanf(datetime,
"%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
8511 &hour, &minute, &second) == 6) ||
8512 (sscanf(datetime,
"%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
8513 &minute, &second) == 6)) &&
8517 days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
8518 result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
8538 const char *domain) {
8540 "HTTP/1.1 401 Unauthorized\r\n"
8541 "WWW-Authenticate: Digest qop=\"auth\", "
8542 "realm=\"%s\", nonce=\"%lx\"\r\n"
8543 "Content-Length: 0\r\n\r\n",
8544 domain, (
unsigned long)
mg_time());
8551 "Allow: GET, POST, HEAD, CONNECT, OPTIONS"
8553 ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
8564 const struct mg_str *path_info,
8567 int exists, is_directory, is_cgi;
8568#if MG_ENABLE_HTTP_WEBDAV
8573 char *index_file = NULL;
8576 exists = (
mg_stat(path, &st) == 0);
8577 is_directory = exists && S_ISDIR(st.st_mode);
8584 index_file ? index_file : path) > 0);
8587 (
"%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc,
8589 is_cgi, index_file ? index_file :
""));
8591 if (is_directory && hm->
uri.
p[hm->
uri.
len - 1] !=
'/' && !is_dav) {
8593 "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
8594 "Content-Length: 0\r\n\r\n",
8601 if (path_info->
len > 0 && !is_cgi) {
8616 opts->per_directory_auth_file,
8620 }
else if (is_cgi) {
8621#if MG_ENABLE_HTTP_CGI
8622 mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
8626 }
else if ((!exists ||
8630#if MG_ENABLE_HTTP_WEBDAV
8633#if !MG_DISABLE_DAV_AUTH
8634 }
else if (is_dav &&
8652#if MG_ENABLE_FAKE_DAVLOCK
8654 mg_handle_lock(nc, path);
8659 }
else if (is_directory && index_file == NULL) {
8660#if MG_ENABLE_DIRECTORY_LISTING
8672 mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts);
8681 struct mg_str *hdr, path_info;
8682 uint32_t remote_ip = ntohl(*(uint32_t *) &nc->
sa.
sin.sin_addr);
8691#if MG_ENABLE_HTTP_URL_REWRITES
8692 if (mg_http_handle_forwarding(nc, hm, &opts)) {
8717 opts.
index_files =
"index.html,index.htm,index.shtml,index.cgi,index.php";
8736 mg_vcmp(hdr,
"keep-alive") != 0)) {
8744#if MG_ENABLE_HTTP_STREAMING_MULTIPART
8745void mg_file_upload_handler(
struct mg_connection *nc,
int ev,
void *ev_data,
8746 mg_fu_fname_fn local_name_fn
8749 case MG_EV_HTTP_PART_BEGIN: {
8752 struct file_upload_state *fus;
8755 if (lfn.
p == NULL || lfn.
len == 0) {
8758 "HTTP/1.1 403 Not Allowed\r\n"
8759 "Content-Type: text/plain\r\n"
8760 "Connection: close\r\n\r\n"
8761 "Not allowed to upload %s\r\n",
8766 fus = (
struct file_upload_state *)
MG_CALLOC(1,
sizeof(*fus));
8772 memcpy(fus->lfn, lfn.
p, lfn.
len);
8773 fus->lfn[lfn.
len] =
'\0';
8776 (
"%p Receiving file %s -> %s", nc, mp->
file_name, fus->lfn));
8777 fus->fp =
mg_fopen(fus->lfn,
"wb");
8778 if (fus->fp == NULL) {
8780 "HTTP/1.1 500 Internal Server Error\r\n"
8781 "Content-Type: text/plain\r\n"
8782 "Connection: close\r\n\r\n");
8792 case MG_EV_HTTP_PART_DATA: {
8795 struct file_upload_state *fus =
8796 (
struct file_upload_state *) mp->
user_data;
8797 if (fus == NULL || fus->fp == NULL)
break;
8799 LOG(
LL_ERROR, (
"Failed to write to %s: %d, wrote %d", fus->lfn,
8802#ifdef SPIFFS_ERR_FULL
8807 "HTTP/1.1 413 Payload Too Large\r\n"
8808 "Content-Type: text/plain\r\n"
8809 "Connection: close\r\n\r\n");
8810 mg_printf(nc,
"Failed to write to %s: no space left; wrote %d\r\n",
8811 fus->lfn, (
int) fus->num_recd);
8814 "HTTP/1.1 500 Internal Server Error\r\n"
8815 "Content-Type: text/plain\r\n"
8816 "Connection: close\r\n\r\n");
8828 fus->num_recd += mp->
data.
len;
8830 (
int) fus->num_recd));
8833 case MG_EV_HTTP_PART_END: {
8836 struct file_upload_state *fus =
8837 (
struct file_upload_state *) mp->
user_data;
8838 if (fus == NULL)
break;
8839 if (mp->
status >= 0 && fus->fp != NULL) {
8841 fus->lfn, (
int) fus->num_recd));
8849 if (fus->fp != NULL) fclose(fus->fp);
8856 case MG_EV_HTTP_MULTIPART_REQUEST_END: {
8858 "HTTP/1.1 200 OK\r\n"
8859 "Content-Type: text/plain\r\n"
8860 "Connection: close\r\n\r\n"
8867#if MG_ENABLE_CALLBACK_USERDATA
8877 struct mg_connect_opts opts,
const char *scheme1,
const char *scheme2,
8878 const char *scheme_ssl1,
const char *scheme_ssl2,
const char *url,
8881 unsigned int port_i = 0;
8883 struct mg_str scheme, query, fragment;
8884 char conn_addr_buf[2];
8885 char *conn_addr = conn_addr_buf;
8888 &query, &fragment) != 0) {
8894 if (query.len > 0) path->
len += query.len + 1;
8896 if (scheme.len == 0 ||
mg_vcmp(&scheme, scheme1) == 0 ||
8897 (scheme2 != NULL &&
mg_vcmp(&scheme, scheme2) == 0)) {
8899 if (port_i == 0) port_i = 80;
8900 }
else if (
mg_vcmp(&scheme, scheme_ssl1) == 0 ||
8901 (scheme2 != NULL &&
mg_vcmp(&scheme, scheme_ssl2) == 0)) {
8903 if (port_i == 0) port_i = 443;
8908 mg_asprintf(&conn_addr,
sizeof(conn_addr_buf),
"tcp://%.*s:%u",
8909 (
int) host->
len, host->
p, port_i);
8910 if (conn_addr == NULL)
goto out;
8912 LOG(
LL_DEBUG, (
"%s use_ssl? %d %s", url, use_ssl, conn_addr));
8920 if (opts.ssl_ca_cert == NULL) {
8921 opts.ssl_ca_cert =
"*";
8935 if (conn_addr != NULL && conn_addr != conn_addr_buf)
MG_FREE(conn_addr);
8941 struct mg_connect_opts opts,
const char *url,
const char *extra_headers,
8942 const char *post_data) {
8948 NULL,
"https", NULL, url, &path, &user, &host);
8959 if (post_data == NULL) post_data =
"";
8960 if (extra_headers == NULL) extra_headers =
"";
8961 if (path.len == 0) path =
mg_mk_str(
"/");
8964 mg_printf(nc,
"%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
8966 (post_data[0] ==
'\0' ?
"GET" :
"POST"), (int) path.len, path.p,
8967 (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len,
8968 (auth.
buf == NULL ?
"" : auth.
buf), extra_headers, post_data);
8976 const char *url,
const char *extra_headers,
const char *post_data) {
8978 memset(&opts, 0,
sizeof(opts));
8980 extra_headers, post_data);
8985 size_t file_name_len,
const char **
data,
8987 static const char cd[] =
"Content-Disposition: ";
8988 size_t hl,
bl,
n, ll, pos, cdl =
sizeof(cd) - 1;
8991 if (buf == NULL || buf_len <= 0)
return 0;
8994 if (buf[0] !=
'-' || buf[1] !=
'-' || buf[2] ==
'\n')
return 0;
9004 header.
p = buf +
n + cdl;
9005 header.
len = ll - (cdl + 2);
9028 for (pos = hl; pos + (
bl - 2) < buf_len; pos++) {
9029 if (buf[pos] ==
'-' && !strncmp(buf, &buf[pos],
bl - 2)) {
9030 if (data_len != NULL) *data_len = (pos - 2) - hl;
9031 if (
data != NULL) *
data = buf + hl;
9040 const char *uri_path,
9046 if (nc == NULL)
return;
9048 if (new_ep == NULL)
return;
9051 if (pd == NULL) pd = mg_http_create_proto_data(nc);
9055 new_ep->auth_file = strdup(opts.
auth_file);
9058#if MG_ENABLE_CALLBACK_USERDATA
9072 || ev == MG_EV_HTTP_MULTIPART_REQUEST
9078#if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH
9086#if MG_ENABLE_CALLBACK_USERDATA
9087 user_data = ep->user_data;
9099 memset(&opts, 0,
sizeof(opts));
9100#if MG_ENABLE_CALLBACK_USERDATA
9107#ifdef MG_MODULE_LINES
9108#line 1 "mongoose/src/mg_http_cgi.c"
9119#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
9121#ifndef MG_MAX_CGI_ENVIR_VARS
9122#define MG_MAX_CGI_ENVIR_VARS 64
9125#ifndef MG_ENV_EXPORT_TO_CGI
9126#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
9129#define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1
9150struct mg_threadparam {
9155static int mg_wait_until_ready(sock_t sock,
int for_read) {
9159 return select(sock + 1, for_read ? &
set : 0, for_read ? 0 : &
set, 0, 0) == 1;
9162static void *mg_push_to_stdin(
void *arg) {
9163 struct mg_threadparam *tp = (
struct mg_threadparam *) arg;
9164 int n, sent, stop = 0;
9168 while (!stop && mg_wait_until_ready(tp->s, 1) &&
9169 (
n = recv(tp->s, buf,
sizeof(buf), 0)) > 0) {
9170 if (
n == -1 && GetLastError() == WSAEWOULDBLOCK)
continue;
9171 for (sent = 0; !stop && sent <
n; sent +=
k) {
9172 if (!WriteFile(tp->hPipe, buf + sent,
n - sent, &
k, 0)) stop = 1;
9175 DBG((
"%s",
"FORWARED EVERYTHING TO CGI"));
9176 CloseHandle(tp->hPipe);
9181static void *mg_pull_from_stdout(
void *arg) {
9182 struct mg_threadparam *tp = (
struct mg_threadparam *) arg;
9183 int k = 0, stop = 0;
9187 while (!stop && ReadFile(tp->hPipe, buf,
sizeof(buf), &
n, NULL)) {
9188 for (sent = 0; !stop && sent <
n; sent +=
k) {
9189 if (mg_wait_until_ready(tp->s, 0) &&
9190 (
k = send(tp->s, buf + sent,
n - sent, 0)) <= 0)
9194 DBG((
"%s",
"EOF FROM CGI"));
9195 CloseHandle(tp->hPipe);
9202static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
9203 void *(*func)(
void *)) {
9204 struct mg_threadparam *tp = (
struct mg_threadparam *)
MG_MALLOC(
sizeof(*tp));
9212static void mg_abs_path(
const char *utf8_path,
char *abs_path,
size_t len) {
9215 GetFullPathNameW(buf,
ARRAY_SIZE(buf2), buf2, NULL);
9216 WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
9220 const char *env,
const char *envp[],
9221 const char *dir, sock_t sock) {
9223 PROCESS_INFORMATION
pi;
9224 HANDLE a[2], b[2], me = GetCurrentProcess();
9228 DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
9231 memset(&si, 0,
sizeof(si));
9232 memset(&
pi, 0,
sizeof(
pi));
9235 si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
9236 si.wShowWindow = SW_HIDE;
9237 si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
9239 CreatePipe(&a[0], &a[1], NULL, 0);
9240 CreatePipe(&b[0], &b[1], NULL, 0);
9241 DuplicateHandle(me, a[0], me, &si.hStdInput, 0,
TRUE, flags);
9242 DuplicateHandle(me, b[1], me, &si.hStdOutput, 0,
TRUE, flags);
9244 if (interp == NULL && (
fp =
mg_fopen(cmd,
"r")) != NULL) {
9245 buf[0] = buf[1] =
'\0';
9246 fgets(buf,
sizeof(buf),
fp);
9247 buf[
sizeof(buf) - 1] =
'\0';
9248 if (buf[0] ==
'#' && buf[1] ==
'!') {
9251 while (*interp !=
'\0' && isspace(*(
unsigned char *) interp)) {
9258 snprintf(buf,
sizeof(buf),
"%s/%s", dir, cmd);
9262 to_wchar(dir, full_dir,
ARRAY_SIZE(full_dir));
9264 if (interp != NULL) {
9266 snprintf(cmdline,
sizeof(cmdline),
"%s \"%s\"", buf4, buf2);
9268 snprintf(cmdline,
sizeof(cmdline),
"\"%s\"", buf2);
9272 if (CreateProcessW(NULL, wcmd, NULL, NULL,
TRUE, CREATE_NEW_PROCESS_GROUP,
9273 (
void *) env, full_dir, &si, &
pi) != 0) {
9274 mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
9275 mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
9277 CloseHandle(si.hStdOutput);
9278 CloseHandle(si.hStdInput);
9280 CloseHandle(
pi.hThread);
9281 CloseHandle(
pi.hProcess);
9287 DBG((
"CGI command: [%ls] -> %p", wcmd,
pi.hProcess));
9291 return (
pi.hProcess != NULL);
9295 const char *env,
const char *envp[],
9296 const char *dir, sock_t sock) {
9306 int tmp = chdir(dir);
9308 (void) dup2(sock, 0);
9309 (void) dup2(sock, 1);
9318 signal(SIGCHLD, SIG_DFL);
9320 if (interp == NULL) {
9321 execle(cmd, cmd, (
char *) 0, envp);
9323 execle(interp, interp, cmd, (
char *) 0, envp);
9325 snprintf(buf,
sizeof(buf),
9326 "Status: 500\r\n\r\n"
9327 "500 Server Error: %s%s%s: %s",
9328 interp == NULL ?
"" : interp, interp == NULL ?
"" :
" ", cmd,
9330 send(1, buf, strlen(buf), 0);
9331 _exit(EXIT_FAILURE);
9344 char *added = block->
buf + block->
len;
9348 space =
sizeof(block->
buf) - (block->
len + 2);
9352 n = vsnprintf(added, (
size_t) space, fmt, ap);
9356 if (
n > 0 &&
n + 1 < space &&
9361 block->
len +=
n + 1;
9375 const struct mg_str *path_info,
9384 size_t path_info_len = path_info != NULL ? path_info->
len : 0;
9386 blk->len =
blk->nvars = 0;
9389 if ((s = getenv(
"SERVER_NAME")) != NULL) {
9408 hm->query_string.
p);
9416 s = hm->
uri.
p + hm->
uri.
len - path_info_len - 1;
9418 const char *base_name = strrchr(prog, DIRSEP);
9420 (base_name != NULL ? base_name + 1 : prog));
9426 if (path_info != NULL && path_info->
len > 0) {
9429 mg_addenv(
blk,
"PATH_TRANSLATED=%.*s", (
int) path_info->
len, path_info->
p);
9478 for (; *
p !=
'=' && *
p !=
'\0';
p++) {
9479 if (*
p ==
'-') *
p =
'_';
9480 *
p = (char) toupper(*(
unsigned char *)
p);
9484 blk->vars[
blk->nvars++] = NULL;
9485 blk->buf[
blk->len++] =
'\0';
9489 void *ev_data
MG_UD_ARG(
void *user_data)) {
9490#if !MG_ENABLE_CALLBACK_USERDATA
9517 if (nc->
flags & MG_F_HTTP_CGI_PARSE_HEADERS) {
9521 if (
len == 0)
break;
9530 mg_printf(nc,
"%s",
"HTTP/1.1 302 Moved\r\n");
9534 mg_printf(nc,
"%s",
"HTTP/1.1 200 OK\r\n");
9537 nc->
flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS;
9539 if (!(nc->
flags & MG_F_HTTP_CGI_PARSE_HEADERS)) {
9544 DBG((
"%p CLOSE", cgi_nc));
9552 const struct mg_str *path_info,
9560 DBG((
"%p [%s]",
nc, prog));
9567 if ((p = strrchr(prog, DIRSEP)) == NULL) {
9568 snprintf(dir,
sizeof(dir),
"%s",
".");
9570 snprintf(dir,
sizeof(dir),
"%.*s", (
int) (p - prog), prog);
9580 struct sigaction sa;
9582 sigemptyset(&sa.sa_mask);
9583 sa.sa_handler = SIG_IGN;
9585 sigaction(SIGCHLD, &sa, NULL);
9594#if !MG_ENABLE_CALLBACK_USERDATA
9597 nc->
flags |= MG_F_HTTP_CGI_PARSE_HEADERS;
9614 if (
d == NULL)
return;
9615 if (
d->cgi_nc != NULL) {
9617 d->cgi_nc->user_data = NULL;
9619 memset(
d, 0,
sizeof(*
d));
9623#ifdef MG_MODULE_LINES
9624#line 1 "mongoose/src/mg_http_ssi.c"
9631#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
9634 const char *path, FILE *
fp,
int include_level,
9640 while ((
n = mg_fread(buf, 1,
sizeof(buf),
fp)) > 0) {
9647 const char *ssi,
char *tag,
int include_level,
9656 if (sscanf(tag,
" virtual=\"%[^\"]\"",
file_name) == 1) {
9659 }
else if (sscanf(tag,
" abspath=\"%[^\"]\"",
file_name) == 1) {
9664 snprintf(path,
sizeof(path),
"%s",
file_name);
9665 }
else if (sscanf(tag,
" file=\"%[^\"]\"",
file_name) == 1 ||
9666 sscanf(tag,
" \"%[^\"]\"",
file_name) == 1) {
9668 snprintf(path,
sizeof(path),
"%s", ssi);
9669 if ((p = strrchr(path, DIRSEP)) != NULL) {
9672 snprintf(path + strlen(path),
sizeof(path) - strlen(path),
"%s",
file_name);
9674 mg_printf(nc,
"Bad SSI #include: [%s]", tag);
9679 mg_printf(nc,
"SSI include error: mg_fopen(%s): %s", path,
9694#if MG_ENABLE_HTTP_SSI_EXEC
9699 if (sscanf(tag,
" \"%[^\"]\"", cmd) != 1) {
9700 mg_printf(nc,
"Bad SSI #exec: [%s]", tag);
9701 }
else if ((
fp = popen(cmd,
"r")) == NULL) {
9716 const char *path, FILE *
fp,
int include_level,
9721#if MG_ENABLE_HTTP_SSI_EXEC
9724 char buf[BUFSIZ], *
p = buf + btag.
len;
9725 int ch,
len, in_ssi_tag;
9727 if (include_level > 10) {
9728 mg_printf(nc,
"SSI #include level is too deep (%s)", path);
9732 in_ssi_tag =
len = 0;
9733 while ((ch = fgetc(
fp)) != EOF) {
9734 if (in_ssi_tag && ch ==
'>' && buf[
len - 1] ==
'-' && buf[
len - 2] ==
'-') {
9740 while (
i > 0 && buf[
i] ==
' ') {
9745 if (strncmp(
p, d_include.
p, d_include.
len) == 0) {
9746 mg_do_ssi_include(nc, hm, path,
p + d_include.
len + 1, include_level,
9748 }
else if (strncmp(
p, d_call.
p, d_call.
len) == 0) {
9750 memset(&cctx, 0,
sizeof(cctx));
9755 (
void *) cctx.arg.p);
9757#if MG_ENABLE_HTTP_SSI_EXEC
9758 }
else if (strncmp(p, d_exec.
p, d_exec.
len) == 0) {
9765 }
else if (ch ==
'<') {
9768 mg_send(nc, buf, (
size_t) len);
9771 buf[len++] = ch & 0xff;
9772 }
else if (in_ssi_tag) {
9773 if (len == (
int) btag.
len && strncmp(buf, btag.
p, btag.
len) != 0) {
9776 }
else if (len == (
int)
sizeof(buf) - 2) {
9777 mg_printf(nc,
"%s: SSI tag is too large", path);
9780 buf[len++] = ch & 0xff;
9782 buf[len++] = ch & 0xff;
9783 if (len == (
int)
sizeof(buf)) {
9784 mg_send(nc, buf, (
size_t) len);
9792 mg_send(nc, buf, (
size_t) len);
9802 DBG((
"%p %s", nc, path));
9812 "Content-Type: %.*s\r\n"
9813 "Connection: close\r\n\r\n",
9823#ifdef MG_MODULE_LINES
9824#line 1 "mongoose/src/mg_http_webdav.c"
9831#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
9834 static const char *methods[] = {
9840#if MG_ENABLE_FAKE_DAVLOCK
9857static int mg_mkdir(
const char *path, uint32_t mode) {
9859 return mkdir(path, mode);
9862 return _mkdir(path);
9869 time_t t = stp->st_mtime;
9874 "<d:href>%s</d:href>"
9877 "<d:resourcetype>%s</d:resourcetype>"
9879 "</d:getcontentlength>"
9880 "<d:getlastmodified>%s</d:getlastmodified>"
9882 "<d:status>HTTP/1.1 200 OK</d:status>"
9885 name_esc.
p, S_ISDIR(stp->st_mode) ?
"<d:collection/>" :
"",
9886 (int64_t) stp->st_size, mtime);
9887 free((
void *) name_esc.
p);
9893 static const char header[] =
9894 "HTTP/1.1 207 Multi-Status\r\n"
9895 "Connection: close\r\n"
9896 "Content-Type: text/xml; charset=utf-8\r\n\r\n"
9897 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
9898 "<d:multistatus xmlns:d='DAV:'>\n";
9899 static const char footer[] =
"</d:multistatus>\n";
9903 if (S_ISDIR(stp->st_mode) &&
9905 mg_printf(nc,
"%s",
"HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
9908 mg_send(nc, header,
sizeof(header) - 1);
9909 snprintf(uri,
sizeof(uri),
"%.*s", (
int) hm->
uri.
len, hm->
uri.
p);
9911 if (S_ISDIR(stp->st_mode) && (depth == NULL ||
mg_vcmp(depth,
"0") != 0)) {
9914 mg_send(nc, footer,
sizeof(footer) - 1);
9919#if MG_ENABLE_FAKE_DAVLOCK
9932 static const char *reply =
9933 "HTTP/1.1 207 Multi-Status\r\n"
9934 "Connection: close\r\n"
9935 "Content-Type: text/xml; charset=utf-8\r\n\r\n"
9936 "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
9937 "<d:multistatus xmlns:d='DAV:'>\n"
9938 "<D:lockdiscovery>\n"
9942 "opaquelocktoken:%s%u"
9946 "</D:lockdiscovery>"
9947 "</d:multistatus>\n";
9955 int status_code = 500;
9958 }
else if (!
mg_mkdir(path, 0755)) {
9960 }
else if (errno == EEXIST) {
9962 }
else if (errno == EACCES) {
9964 }
else if (errno == ENOENT) {
9979 if ((dirp = opendir(dir)) == NULL)
return 0;
9981 while ((dp = readdir(dirp)) != NULL) {
9985 snprintf(path,
sizeof(path),
"%s%c%s", dir,
'/', dp->d_name);
9987 if (S_ISDIR(st.st_mode)) {
10003 if (dest == NULL) {
10006 const char *
p = (
char *) memchr(dest->
p,
'/', dest->
len);
10007 if (
p != NULL &&
p[1] ==
'/' &&
10008 (
p = (
char *) memchr(
p + 2,
'/', dest->
p + dest->
len -
p)) != NULL) {
10011 (
int) (dest->
p + dest->
len -
p),
p);
10012 if (rename(path, buf) == 0) {
10025 const char *path) {
10027 if (
mg_stat(path, &st) != 0) {
10029 }
else if (S_ISDIR(st.st_mode)) {
10032 }
else if (
remove(path) == 0) {
10044 for (s = path + 1; *s !=
'\0'; s++) {
10048 snprintf(buf,
sizeof(buf),
"%.*s", (
int) (s - path), path);
10049 buf[
sizeof(buf) - 1] =
'\0';
10064 int rc, status_code =
mg_stat(path, &st) == 0 ? 200 : 201;
10068 mg_printf(nc,
"HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
10069 }
else if (rc == -1) {
10071 }
else if (cl_hdr == NULL) {
10077 int64_t r1 = 0, r2 = 0;
10080 pd->
file.
cl = to64(cl_hdr->
p);
10081 if (range_hdr != NULL &&
10084 fseeko(pd->
file.
fp, r1, SEEK_SET);
10085 pd->
file.
cl = r2 > r1 ? r2 - r1 + 1 : pd->
file.
cl - r1;
10087 mg_printf(nc,
"HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
10095#ifdef MG_MODULE_LINES
10096#line 1 "mongoose/src/mg_http_websocket.c"
10103#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
10107#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
10108#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
10111#define FLAGS_MASK_FIN (1 << 7)
10112#define FLAGS_MASK_OP 0x0f
10115 return (flags & FLAGS_MASK_FIN) == 0 ||
10120 return (flags & FLAGS_MASK_FIN) == 0 &&
10124static int mg_is_ws_control_frame(
unsigned char flags) {
10125 unsigned char op = (flags & FLAGS_MASK_OP);
10132 if (wsm->
flags & 0x8) {
10139static struct mg_ws_proto_data *mg_ws_get_proto_data(
struct mg_connection *nc) {
10141 return (htd != NULL ? &htd->ws_data : NULL);
10150 if ((
int) len == ~0) {
10151 len = strlen((
const char *)
data);
10159 uint64_t
i, data_len = 0, frame_len = 0, new_data_len = nc->
recv_mbuf.
len,
10160 len, mask_len = 0, header_len = 0;
10161 struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc);
10162 unsigned char *new_data = (
unsigned char *) nc->
recv_mbuf.
buf,
10167 if (wsd->reass_len > 0) {
10178 size_t existing_len = wsd->reass_len;
10179 assert(new_data_len >= existing_len);
10181 new_data += existing_len;
10182 new_data_len -= existing_len;
10185 flags = new_data[0];
10190 if (reass && mg_is_ws_control_frame(flags)) {
10195 mg_ws_close(nc,
"fragmented control frames are illegal", ~0);
10197 }
else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) &&
10198 wsd->reass_len > 0) {
10203 mg_ws_close(nc,
"non-continuation in the middle of a fragmented message",
10208 if (new_data_len >= 2) {
10209 len = new_data[1] & 0x7f;
10210 mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0;
10211 if (len < 126 && new_data_len >= mask_len) {
10213 header_len = 2 + mask_len;
10214 }
else if (len == 126 && new_data_len >= 4 + mask_len) {
10215 header_len = 4 + mask_len;
10216 data_len = ntohs(*(uint16_t *) &new_data[2]);
10217 }
else if (new_data_len >= 10 + mask_len) {
10218 header_len = 10 + mask_len;
10219 data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) +
10220 ntohl(*(uint32_t *) &new_data[6]);
10224 frame_len = header_len + data_len;
10225 ok = (frame_len > 0 && frame_len <= new_data_len);
10228 if (frame_len < header_len || frame_len < data_len) {
10230 mg_ws_close(nc,
"overflowed message", ~0);
10234 size_t cleanup_len = 0;
10237 wsm.
size = (size_t) data_len;
10238 wsm.
data = new_data + header_len;
10242 if (mask_len > 0) {
10243 for (
i = 0;
i < data_len;
i++) {
10244 new_data[
i + header_len] ^= (new_data + header_len - mask_len)[
i % 4];
10257 wsd->reass_len = 1 ;
10261 memmove(new_data, wsm.
data,
e - wsm.
data);
10262 wsd->reass_len += wsm.
size;
10265 if (
flags & FLAGS_MASK_FIN) {
10269 wsm.
size = wsd->reass_len - 1 ;
10270 cleanup_len = wsd->reass_len;
10271 wsd->reass_len = 0;
10283 cleanup_len = (size_t) frame_len;
10286 switch (
flags & FLAGS_MASK_OP) {
10292 mg_ws_close(nc, wsm.
data, wsm.
size);
10331#if MG_DISABLE_WS_RANDOM_MASK
10334 if (
sizeof(
long) >= 4) {
10335 mask = (uint32_t) rand();
10336 }
else if (
sizeof(
long) == 2) {
10337 mask = (uint32_t) rand() << 16 | (uint32_t) rand();
10346 unsigned char header[10];
10351 header[1] = (
unsigned char) len;
10353 }
else if (len < 65535) {
10354 uint16_t tmp = htons((uint16_t) len);
10356 memcpy(&header[2], &tmp,
sizeof(tmp));
10361 tmp = htonl((uint32_t)((uint64_t) len >> 32));
10362 memcpy(&header[2], &tmp,
sizeof(tmp));
10363 tmp = htonl((uint32_t)(len & 0xffffffff));
10364 memcpy(&header[6], &tmp,
sizeof(tmp));
10370 header[1] |= 1 << 7;
10371 mg_send(nc, header, header_len);
10376 mg_send(nc, header, header_len);
10383 if (ctx->
pos == 0)
return;
10392 DBG((
"%p %d %d", nc, op, (
int) len));
10404 const struct mg_str *strv,
int strvcnt) {
10408 for (
i = 0;
i < strvcnt;
i++) {
10409 len += strv[
i].
len;
10414 for (
i = 0;
i < strvcnt;
i++) {
10426 const char *fmt, ...) {
10432 if ((len =
mg_avprintf(&buf,
sizeof(mem), fmt, ap)) > 0) {
10437 if (buf != mem && buf != NULL) {
10443 void *ev_data
MG_UD_ARG(
void *user_data)) {
10454 time_t now = *(time_t *) ev_data;
10464#if MG_ENABLE_CALLBACK_USERDATA
10471 const size_t *msg_lens, uint8_t *digest) {
10475 for (
i = 0;
i < num_msgs;
i++) {
10481extern void mg_hash_sha1_v(
size_t num_msgs,
const uint8_t *msgs[],
10482 const size_t *msg_lens, uint8_t *digest);
10488 static const char *magic =
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
10489 const uint8_t *msgs[2] = {(
const uint8_t *)
key->p, (
const uint8_t *) magic};
10490 const size_t msg_lens[2] = {
key->len, 36};
10491 unsigned char sha[20];
10498 "HTTP/1.1 101 Switching Protocols\r\n"
10499 "Upgrade: websocket\r\n"
10500 "Connection: Upgrade\r\n");
10504 mg_printf(nc,
"Sec-WebSocket-Protocol: %.*s\r\n", (
int) s->
len, s->
p);
10506 mg_printf(nc,
"Sec-WebSocket-Accept: %s%s", b64_sha,
"\r\n\r\n");
10508 DBG((
"%p %.*s %s", nc, (
int)
key->len,
key->p, b64_sha));
10512 const char *host,
const char *protocol,
10513 const char *extra_headers) {
10519 const char *host,
const char *protocol,
10520 const char *extra_headers,
const char *user,
10521 const char *pass) {
10528 const struct mg_str path,
10529 const struct mg_str host,
10530 const struct mg_str protocol,
10531 const struct mg_str extra_headers,
10532 const struct mg_str user,
10533 const struct mg_str pass) {
10544 if (user.
len > 0) {
10555 "GET %.*s HTTP/1.1\r\n"
10556 "Upgrade: websocket\r\n"
10557 "Connection: Upgrade\r\n"
10559 "Sec-WebSocket-Version: 13\r\n"
10560 "Sec-WebSocket-Key: %s\r\n",
10561 (
int) path.
len, path.
p, (
int) auth.len,
10562 (auth.buf == NULL ?
"" : auth.
buf),
key);
10565 if (host.
len > 0) {
10566 int host_len = (int) (path.
p - host.
p);
10567 mg_printf(nc,
"Host: %.*s\r\n", host_len, host.
p);
10569 if (protocol.
len > 0) {
10570 mg_printf(nc,
"Sec-WebSocket-Protocol: %.*s\r\n", (
int) protocol.
len,
10573 if (extra_headers.
len > 0) {
10574 mg_printf(nc,
"%.*s", (
int) extra_headers.
len, extra_headers.
p);
10584 const char *extra_headers) {
10587 nc,
mg_mk_str(path), null_str , null_str ,
10588 mg_mk_str(extra_headers), null_str , null_str );
10594 const char *extra_headers) {
10599 "ws",
"https",
"wss", url, &path, &user_info, &host);
10610 const char *url,
const char *protocol,
const char *extra_headers) {
10612 memset(&opts, 0,
sizeof(opts));
10614 protocol, extra_headers);
10617#ifdef MG_MODULE_LINES
10618#line 1 "mongoose/src/mg_util.c"
10631#define MAX(a, b) ((a) > (b) ? (a) : (b))
10634const char *
mg_skip(
const char *s,
const char *
end,
const char *delims,
10637 while (s <
end && strchr(delims, *(
unsigned char *) s) == NULL) s++;
10639 while (s <
end && strchr(delims, *(
unsigned char *) s) != NULL) s++;
10643#if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS)
10644int mg_stat(
const char *path, cs_stat_t *st) {
10648 DBG((
"[%ls] -> %d", wpath, _wstati64(wpath, st)));
10649 return _wstati64(wpath, st);
10651 return stat(path, st);
10655FILE *
mg_fopen(
const char *path,
const char *mode) {
10660 return _wfopen(wpath, wmode);
10662 return fopen(path, mode);
10666int mg_open(
const char *path,
int flag,
int mode) {
10667#if defined(_WIN32) && !defined(WINCE)
10670 return _wopen(wpath, flag, mode);
10672 return open(path, flag, mode);
10676size_t mg_fread(
void *ptr,
size_t size,
size_t count, FILE *f) {
10677 return fread(ptr, size,
count, f);
10680size_t mg_fwrite(
const void *ptr,
size_t size,
size_t count, FILE *f) {
10681 return fwrite(ptr, size,
count, f);
10693#if MG_ENABLE_THREADS
10696 return (
void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL);
10697#elif defined(_WIN32)
10698 return (
void *) _beginthread((
void(__cdecl *) (
void *) ) f, 0, p);
10700 pthread_t thread_id = (pthread_t) 0;
10701 pthread_attr_t attr;
10703 (void) pthread_attr_init(&attr);
10704 (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
10706#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
10707 (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
10710 pthread_create(&thread_id, &attr, f, p);
10711 pthread_attr_destroy(&attr);
10713 return (
void *) thread_id;
10720#if defined(_WIN32) && !defined(WINCE)
10721 (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
10722#elif defined(__unix__)
10723 fcntl(sock, F_SETFD, FD_CLOEXEC);
10732 if (buf == NULL || len <= 0)
return 0;
10733 memset(buf, 0, len);
10735 is_v6 = sa->
sa.sa_family == AF_INET6;
10741 const void *
addr = NULL;
10743 socklen_t capacity = len;
10747 addr = (
void *) &sa->
sin6.sin6_addr;
10757#elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
10760 if (addr_str != NULL) {
10766 if (
inet_ntop(AF_INET, (
void *) &sa->
sin.sin_addr, buf, len) == NULL) {
10772 int port = ntohs(sa->
sin.sin_port);
10774 int buf_len = strlen(buf);
10775 snprintf(buf + buf_len, len - (buf_len + 1),
"%s:%d", (is_v6 ?
"]" :
""),
10778 snprintf(buf, len,
"%d", port);
10782 return strlen(buf);
10792 memset(&
sa, 0,
sizeof(
sa));
10797#if MG_ENABLE_HEXDUMP
10798static int mg_hexdump_n(
const void *buf,
int len,
char *dst,
int dst_len,
10800 const unsigned char *p = (
const unsigned char *) buf;
10801 char ascii[17] =
"";
10804 for (
i = 0;
i < len;
i++) {
10807 if (
i > 0)
n += snprintf(dst +
n,
MAX(dst_len -
n, 0),
" %s\n", ascii);
10808 n += snprintf(dst +
n,
MAX(dst_len -
n, 0),
"%04x ",
i +
offset);
10810 if (dst_len -
n < 0) {
10813 n += snprintf(dst +
n,
MAX(dst_len -
n, 0),
" %02x", p[
i]);
10814 ascii[idx] = p[
i] < 0x20 || p[
i] > 0x7e ?
'.' : p[
i];
10815 ascii[idx + 1] =
'\0';
10818 while (
i++ % 16)
n += snprintf(dst +
n,
MAX(dst_len -
n, 0),
"%s",
" ");
10819 n += snprintf(dst +
n,
MAX(dst_len -
n, 0),
" %s\n", ascii);
10824int mg_hexdump(
const void *buf,
int len,
char *dst,
int dst_len) {
10825 return mg_hexdump_n(buf, len, dst, dst_len, 0);
10828void mg_hexdumpf(FILE *
fp,
const void *buf,
int len) {
10832 n = (len < 16 ? len : 16);
10833 mg_hexdump_n(((
const char *) buf) +
offset,
n, tmp,
sizeof(tmp),
offset);
10841 const void *buf,
int num_bytes,
int ev) {
10843 char src[60], dst[60];
10844 const char *tag = NULL;
10862 if (tag == NULL)
return;
10864 if (strcmp(path,
"-") == 0) {
10866 }
else if (strcmp(path,
"--") == 0) {
10868#if MG_ENABLE_FILESYSTEM
10873 if (
fp == NULL)
return;
10880 fprintf(
fp,
"%lu %p %s %s %s %d\n", (
unsigned long)
mg_time(), (
void *) nc,
10881 src, tag, dst, (
int) num_bytes);
10882 if (num_bytes > 0) {
10883 mg_hexdumpf(
fp, buf, num_bytes);
10885 if (
fp != stdout &&
fp != stderr) fclose(
fp);
10890 static const int n = 1;
10892 return ((
char *) &
n)[0] == 0;
10900 return GetLastError();
10917 struct mbuf *buf) {
10918 const char *header_prefix =
"Authorization: Basic ";
10919 const char *header_suffix =
"\r\n";
10924 mbuf_append(buf, header_prefix, strlen(header_prefix));
10927 if (pass.
len > 0) {
10932 mbuf_append(buf, header_suffix, strlen(header_suffix));
10936 const struct
mg_str safe, unsigned int flags) {
10939 :
"0123456789abcdef");
10944 for (
i = 0;
i < src.len;
i++) {
10945 const unsigned char c = *((
const unsigned char *) src.p +
i);
10964#ifdef MG_MODULE_LINES
10965#line 1 "mongoose/src/mg_mqtt.c"
10979static uint16_t getu16(
const char *p) {
10980 const uint8_t *up = (
const uint8_t *) p;
10981 return (up[0] << 8) + up[1];
10984static const char *scanto(
const char *p,
struct mg_str *s) {
10985 s->
len = getu16(p);
10987 return s->
p + s->
len;
10992 size_t len = 0, len_len = 0;
10993 const char *p, *
end, *eop = &io->
buf[io->
len];
10994 unsigned char lc = 0;
10997 if (io->
len < 2)
return MG_MQTT_ERROR_INCOMPLETE_MSG;
10998 header = io->
buf[0];
11005 lc = *((
const unsigned char *) p++);
11006 len += (lc & 0x7f) << 7 * len_len;
11008 if (!(lc & 0x80))
break;
11009 if (len_len > 4)
return MG_MQTT_ERROR_MALFORMED_MSG;
11013 if (lc & 0x80 ||
end > eop)
return MG_MQTT_ERROR_INCOMPLETE_MSG;
11021 if (p >
end - 4)
return MG_MQTT_ERROR_MALFORMED_MSG;
11026 if (p >=
end)
return MG_MQTT_ERROR_MALFORMED_MSG;
11028 if (p >
end)
return MG_MQTT_ERROR_MALFORMED_MSG;
11030 if (p >=
end)
return MG_MQTT_ERROR_MALFORMED_MSG;
11034 if (p >=
end)
return MG_MQTT_ERROR_MALFORMED_MSG;
11038 if (p >=
end)
return MG_MQTT_ERROR_MALFORMED_MSG;
11042 if (p >=
end)
return MG_MQTT_ERROR_MALFORMED_MSG;
11045 if (p !=
end)
return MG_MQTT_ERROR_MALFORMED_MSG;
11048 (
"%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
11049 "will_msg [%.*s] user_name [%.*s] password [%.*s]",
11059 if (
end - p < 2)
return MG_MQTT_ERROR_MALFORMED_MSG;
11067 if (
end - p < 2)
return MG_MQTT_ERROR_MALFORMED_MSG;
11072 p = scanto(p, &mm->
topic);
11073 if (p >
end)
return MG_MQTT_ERROR_MALFORMED_MSG;
11075 if (
end - p < 2)
return MG_MQTT_ERROR_MALFORMED_MSG;
11084 if (
end - p < 2)
return MG_MQTT_ERROR_MALFORMED_MSG;
11104 void *ev_data
MG_UD_ARG(
void *user_data)) {
11107 memset(&mm, 0,
sizeof(mm));
11120 if (
len == MG_MQTT_ERROR_MALFORMED_MSG) {
11123 }
else if (
len == MG_MQTT_ERROR_INCOMPLETE_MSG) {
11128 LOG(
LL_ERROR, (
"%p recv buffer (%lu bytes) exceeds the limit "
11129 "%lu bytes, and not drained, closing",
11151 if (pd->keep_alive > 0 && pd->last_control_time > 0 &&
11152 (now - pd->last_control_time) > pd->keep_alive) {
11161static void mg_mqtt_proto_data_destructor(
void *proto_data) {
11165static struct mg_str mg_mqtt_next_topic_component(struct
mg_str *topic) {
11166 struct mg_str res = *topic;
11169 res.
len = (
c - topic->p);
11170 topic->len -= (res.
len + 1);
11171 topic->p += (res.
len + 1);
11181 if (exp.
len == 0)
return 0;
11183 ec = mg_mqtt_next_topic_component(&exp);
11184 tc = mg_mqtt_next_topic_component(&topic);
11186 if (tc.len != 0)
return 0;
11187 if (exp.
len == 0)
break;
11190 if (
mg_vcmp(&ec,
"+") == 0) {
11191 if (tc.len == 0 && topic.
len == 0)
return 0;
11194 if (
mg_vcmp(&ec,
"#") == 0) {
11196 return (exp.
len == 0);
11202 return (tc.len == 0 && topic.
len == 0);
11215static void mg_send_mqtt_header(
struct mg_connection *nc, uint8_t cmd,
11216 uint8_t flags,
size_t len) {
11218 uint8_t buf[1 +
sizeof(size_t)];
11219 uint8_t *vlen = &buf[1];
11221 buf[0] = (cmd << 4) | flags;
11225 *vlen = len % 0x80;
11227 if (len > 0) *vlen |= 0x80;
11231 mg_send(nc, buf, vlen - buf);
11232 pd->last_control_time =
mg_time();
11243 uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0;
11247 if (client_id != NULL) {
11248 id_len = strlen(client_id);
11251 total_len = 7 + 1 + 2 + 2 + id_len;
11253 if (opts.user_name != NULL) {
11256 if (opts.password != NULL) {
11259 if (opts.will_topic != NULL && opts.will_message != NULL) {
11260 wt_len = strlen(opts.will_topic);
11261 wm_len = strlen(opts.will_message);
11264 if (opts.keep_alive == 0) {
11265 opts.keep_alive = 60;
11269 total_len += 2 + wt_len + 2 + wm_len;
11272 user_len = strlen(opts.user_name);
11273 total_len += 2 + user_len;
11276 pw_len = strlen(opts.password);
11277 total_len += 2 + pw_len;
11281 mg_send(nc,
"\00\04MQTT\04", 7);
11284 netbytes = htons(opts.keep_alive);
11287 netbytes = htons(id_len);
11289 mg_send(nc, client_id, id_len);
11292 netbytes = htons(wt_len);
11294 mg_send(nc, opts.will_topic, wt_len);
11296 netbytes = htons(wm_len);
11298 mg_send(nc, opts.will_message, wm_len);
11302 netbytes = htons(user_len);
11304 mg_send(nc, opts.user_name, user_len);
11307 netbytes = htons(pw_len);
11309 mg_send(nc, opts.password, pw_len);
11313 pd->keep_alive = opts.keep_alive;
11318 uint16_t message_id,
int flags,
const void *
data,
11321 uint16_t topic_len = strlen(topic);
11323 size_t total_len = 2 + topic_len + len;
11330 netbytes = htons(topic_len);
11332 mg_send(nc, topic, topic_len);
11335 netbytes = htons(message_id);
11344 size_t topics_len, uint16_t message_id) {
11347 uint16_t topic_len;
11348 size_t total_len = 2;
11350 for (
i = 0;
i < topics_len;
i++) {
11351 total_len += 2 + strlen(topics[
i].topic) + 1;
11356 netbytes = htons(message_id);
11357 mg_send(nc, (
char *) &netbytes, 2);
11359 for (
i = 0;
i < topics_len;
i++) {
11360 topic_len = strlen(topics[
i].topic);
11361 netbytes = htons(topic_len);
11363 mg_send(nc, topics[
i].topic, topic_len);
11369 struct mg_str *topic, uint8_t *qos,
int pos) {
11370 unsigned char *buf = (
unsigned char *) msg->
payload.
p + pos;
11373 if ((
size_t) pos >= msg->payload.len)
return -1;
11375 topic->len = buf[0] << 8 | buf[1];
11376 topic->p = (
char *) buf + 2;
11377 new_pos = pos + 2 + topic->len + 1;
11378 if ((
size_t) new_pos > msg->payload.len)
return -1;
11379 *qos = buf[2 + topic->len];
11384 size_t topics_len, uint16_t message_id) {
11387 uint16_t topic_len;
11388 size_t total_len = 2;
11390 for (
i = 0;
i < topics_len;
i++) {
11391 total_len += 2 + strlen(topics[
i]);
11396 netbytes = htons(message_id);
11397 mg_send(nc, (
char *) &netbytes, 2);
11399 for (
i = 0;
i < topics_len;
i++) {
11400 topic_len = strlen(topics[
i]);
11401 netbytes = htons(topic_len);
11403 mg_send(nc, topics[
i], topic_len);
11408 uint8_t unused = 0;
11411 mg_send(nc, &return_code, 1);
11420 uint16_t message_id) {
11424 mg_send_mqtt_header(nc, cmd, flags, 2 );
11426 netbytes = htons(message_id);
11447 uint16_t message_id) {
11453 netbytes = htons(message_id);
11456 for (
i = 0;
i < qoss_len;
i++) {
11478#ifdef MG_MODULE_LINES
11479#line 1 "mongoose/src/mg_mqtt_server.c"
11489#if MG_ENABLE_MQTT_BROKER
11491static void mg_mqtt_session_init(
struct mg_mqtt_broker *brk,
11492 struct mg_mqtt_session *s,
11495 s->subscriptions = NULL;
11496 s->num_subscriptions = 0;
11500static void mg_mqtt_add_session(
struct mg_mqtt_session *s) {
11504static void mg_mqtt_remove_session(
struct mg_mqtt_session *s) {
11508static void mg_mqtt_destroy_session(
struct mg_mqtt_session *s) {
11510 for (
i = 0;
i < s->num_subscriptions;
i++) {
11511 MG_FREE((
void *) s->subscriptions[
i].topic);
11517static void mg_mqtt_close_session(
struct mg_mqtt_session *s) {
11518 mg_mqtt_remove_session(s);
11519 mg_mqtt_destroy_session(s);
11522void mg_mqtt_broker_init(
struct mg_mqtt_broker *brk,
void *user_data) {
11524 brk->user_data = user_data;
11527static void mg_mqtt_broker_handle_connect(
struct mg_mqtt_broker *brk,
11529 struct mg_mqtt_session *s =
11530 (
struct mg_mqtt_session *)
MG_CALLOC(1,
sizeof *s);
11540 mg_mqtt_session_init(brk, s, nc);
11542 mg_mqtt_add_session(s);
11547static void mg_mqtt_broker_handle_subscribe(
struct mg_connection *nc,
11549 struct mg_mqtt_session *ss = (
struct mg_mqtt_session *) nc->
priv_2;
11550 uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS];
11551 size_t num_subs = 0;
11559 if (num_subs >=
sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) ||
11560 (ss->num_subscriptions + num_subs >=
11561 MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) {
11565 qoss[num_subs++] =
qos;
11568 if (num_subs > 0) {
11571 sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs));
11576 ss->subscriptions = te;
11578 pos < (int) msg->payload.len &&
11580 ss->num_subscriptions++) {
11581 te = &ss->subscriptions[ss->num_subscriptions];
11589 if (pos == (
int) msg->payload.len) {
11597static void mg_mqtt_broker_handle_publish(
struct mg_mqtt_broker *brk,
11599 struct mg_mqtt_session *s;
11602 for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
11603 for (
i = 0;
i < s->num_subscriptions;
i++) {
11606 char buf[100], *p = buf;
11624 struct mg_mqtt_broker *brk;
11629 brk = (
struct mg_mqtt_broker *) nc->
priv_2;
11638 if (nc->
priv_2 == NULL) {
11639 mg_mqtt_broker_handle_connect(brk, nc);
11646 if (nc->
priv_2 != NULL) {
11647 mg_mqtt_broker_handle_subscribe(nc, msg);
11654 if (nc->
priv_2 != NULL) {
11655 mg_mqtt_broker_handle_publish(brk, msg);
11663 mg_mqtt_close_session((
struct mg_mqtt_session *) nc->
priv_2);
11669struct mg_mqtt_session *mg_mqtt_next(
struct mg_mqtt_broker *brk,
11670 struct mg_mqtt_session *s) {
11675#ifdef MG_MODULE_LINES
11676#line 1 "mongoose/src/mg_dns.c"
11704 for (rr = (prev == NULL ? msg->
answers : prev + 1);
11706 if (rr->
rtype == query) {
11716 switch (rr->
rtype) {
11718 if (data_len <
sizeof(
struct in_addr)) {
11728 if (data_len <
sizeof(
struct in6_addr)) {
11746 memset(&header, 0,
sizeof(header));
11748 header.flags = htons(msg->
flags);
11752 return mbuf_insert(io, pos, &header,
sizeof(header));
11768 size_t pos = io->
len;
11771 if ((s = strchr(
name,
'.')) == NULL) {
11775 if (s -
name > 127) {
11788 }
while (*s !=
'\0');
11791 return io->
len - pos;
11795 const char *
name,
size_t nlen,
const void *
rdata,
11797 size_t pos = io->
len;
11809 u16 = htons(rr->
rtype);
11811 u16 = htons(rr->
rclass);
11815 u32 = htonl(rr->
ttl);
11821 size_t off = io->
len;
11827 io->
buf[off] = u16 >> 8;
11828 io->
buf[off + 1] = u16 & 0xff;
11830 u16 = htons((uint16_t) rlen);
11836 return io->
len - pos;
11846 DBG((
"%s %d",
name, query_type));
11851 msg->
flags = 0x100;
11856 rr->
rtype = query_type;
11867 uint16_t len = htons((uint16_t) pkt.len);
11871 mg_send(nc, pkt.buf, pkt.len);
11882 int chunk_len, data_len;
11885 if (((
unsigned char *)
data)[0] & 0xc0) {
11889 data += chunk_len + 1;
11912 rr->
ttl = (uint32_t)
data[0] << 24 | (uint32_t)
data[1] << 16 |
11916 data_len = *
data << 8 | *(
data + 1);
11928 unsigned char *
data = (
unsigned char *) buf +
sizeof(*header);
11929 unsigned char *
end = (
unsigned char *) buf + len;
11932 memset(msg, 0,
sizeof(*msg));
11936 if (len < (
int)
sizeof(*header))
return -1;
11951 if (
data == NULL)
return -1;
11956 if (
data == NULL)
return -1;
11963 char *dst,
int dst_len) {
11964 int chunk_len, num_ptrs = 0;
11965 char *old_dst = dst;
11966 const unsigned char *
data = (
unsigned char *)
name->p;
11967 const unsigned char *
end = (
unsigned char *) msg->
pkt.
p + msg->
pkt.
len;
11973 while ((chunk_len = *
data++)) {
11974 int leeway = dst_len - (dst - old_dst);
11979 if ((chunk_len & 0xc0) == 0xc0) {
11980 uint16_t off = (
data[-1] & (~0xc0)) << 8 |
data[0];
11981 if (off >= msg->
pkt.
len) {
11985 if (++num_ptrs > 15) {
11988 data = (
unsigned char *) msg->
pkt.
p + off;
11991 if (chunk_len > 63) {
11994 if (chunk_len > leeway) {
11995 chunk_len = leeway;
11998 if (
data + chunk_len >=
end) {
12002 memcpy(dst,
data, chunk_len);
12005 leeway -= chunk_len;
12007 return dst - old_dst;
12012 if (dst != old_dst) {
12015 return dst - old_dst;
12019 void *ev_data
MG_UD_ARG(
void *user_data)) {
12033 memset(&msg, 0,
sizeof(msg));
12034 msg.
flags = 0x8081;
12037 uint16_t len = htons((uint16_t) io->
len);
12055#ifdef MG_MODULE_LINES
12056#line 1 "mongoose/src/mg_dns_server.c"
12063#if MG_ENABLE_DNS_SERVER
12068struct mg_dns_reply mg_dns_create_reply(struct
mbuf *io,
12070 struct mg_dns_reply rep;
12073 rep.start = io->len;
12076 msg->
flags |= 0x8080;
12083void mg_dns_send_reply(
struct mg_connection *nc,
struct mg_dns_reply *r) {
12084 size_t sent = r->io->len - r->start;
12087 uint16_t len = htons((uint16_t) sent);
12092 mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
12093 r->io->len = r->start;
12097int mg_dns_reply_record(
struct mg_dns_reply *reply,
12099 const char *
name,
int rtype,
int ttl,
const void *rdata,
12100 size_t rdata_len) {
12108 if (
name == NULL) {
12120 rdata_len) == -1) {
12129#ifdef MG_MODULE_LINES
12130#line 1 "mongoose/src/mg_resolv.c"
12137#if MG_ENABLE_ASYNC_RESOLVER
12142#ifndef MG_DEFAULT_NAMESERVER
12143#define MG_DEFAULT_NAMESERVER "8.8.8.8"
12172 wchar_t subkey[512],
value[128],
12173 *
key = L
"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
12175 if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE,
key, 0, KEY_READ, &
hKey)) !=
12177 fprintf(stderr,
"cannot open reg key %S: %ld\n",
key, err);
12180 for (ret = -1,
i = 0; 1;
i++) {
12182 if (RegEnumKeyExW(
hKey,
i, subkey, &subkey_size, NULL, NULL, NULL,
12183 NULL) != ERROR_SUCCESS) {
12186 if (RegOpenKeyExW(
hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS &&
12187 ((RegQueryValueExW(hSub, L
"NameServer", 0, &
type, (
void *)
value,
12188 &len) == ERROR_SUCCESS &&
12189 value[0] !=
'\0') ||
12190 (RegQueryValueExW(hSub, L
"DhcpNameServer", 0, &
type, (
void *)
value,
12191 &len) == ERROR_SUCCESS &&
12192 value[0] !=
'\0'))) {
12201 if (
comma != NULL) {
12213#elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME)
12217 if ((
fp =
mg_fopen(MG_RESOLV_CONF_FILE_NAME,
"r")) == NULL) {
12221 for (ret = -1; fgets(line,
sizeof(line),
fp) != NULL;) {
12222 unsigned int a, b,
c,
d;
12223 if (sscanf(line,
"nameserver %u.%u.%u.%u", &a, &b, &
c, &
d) == 4) {
12224 snprintf(
name, name_len,
"%u.%u.%u.%u", a, b,
c,
d);
12239#if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME)
12245 unsigned int a, b,
c,
d;
12248 if ((
fp =
mg_fopen(MG_HOSTS_FILE_NAME,
"r")) == NULL) {
12252 for (; fgets(line,
sizeof(line),
fp) != NULL;) {
12253 if (line[0] ==
'#')
continue;
12255 if (sscanf(line,
"%u.%u.%u.%u%n", &a, &b, &
c, &
d, &len) == 0) {
12259 for (p = line + len; sscanf(p,
"%s%n", alias, &len) == 1; p += len) {
12260 if (strcmp(alias,
name) == 0) {
12261 usa->
sin.sin_addr.s_addr = htonl(a << 24 | b << 16 |
c << 8 |
d);
12279 time_t now = (time_t)
mg_time();
12282#if !MG_ENABLE_CALLBACK_USERDATA
12287 DBG((
"ev=%d user_data=%p", ev, user_data));
12330 nc->
flags &= ~MG_F_CLOSE_IMMEDIATELY;
12342#ifdef MG_LOG_DNS_FAILURES
12356 memset(&opts, 0,
sizeof(opts));
12366 char dns_server_buff[17], nameserver_url[26];
12368 if (nameserver == NULL) {
12381 req->
name[
sizeof(req->
name) - 1] =
'\0';
12391 if (nameserver == NULL) {
12393 sizeof(dns_server_buff)) != -1) {
12394 nameserver = dns_server_buff;
12400 snprintf(nameserver_url,
sizeof(nameserver_url),
"udp://%s:53", nameserver);
12403 if (dns_nc == NULL) {
12418 if (nameserver != NULL) {
12424#ifdef MG_MODULE_LINES
12425#line 1 "mongoose/src/mg_coap.c"
12449void mg_coap_free_options(
struct mg_coap_message *cm) {
12450 while (cm->options != NULL) {
12451 struct mg_coap_option *next = cm->options->next;
12453 cm->options = next;
12457struct mg_coap_option *mg_coap_add_option(
struct mg_coap_message *cm,
12458 uint32_t number,
char *
value,
12460 struct mg_coap_option *new_option =
12461 (
struct mg_coap_option *)
MG_CALLOC(1,
sizeof(*new_option));
12463 new_option->number = number;
12464 new_option->value.p =
value;
12465 new_option->value.len = len;
12467 if (cm->options == NULL) {
12468 cm->options = cm->optiomg_tail = new_option;
12475 if (cm->optiomg_tail->number <= new_option->number) {
12477 cm->optiomg_tail = cm->optiomg_tail->next = new_option;
12480 struct mg_coap_option *current_opt = cm->options;
12481 struct mg_coap_option *prev_opt = 0;
12483 while (current_opt != NULL) {
12484 if (current_opt->number > new_option->number) {
12487 prev_opt = current_opt;
12488 current_opt = current_opt->next;
12491 if (prev_opt != NULL) {
12492 prev_opt->next = new_option;
12493 new_option->next = current_opt;
12496 new_option->next = cm->options;
12497 cm->options = new_option;
12510static char *coap_parse_header(
char *ptr,
struct mbuf *io,
12511 struct mg_coap_message *cm) {
12512 if (io->
len <
sizeof(uint32_t)) {
12513 cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
12523 if (((uint8_t) *ptr >> 6) != 1) {
12524 cm->flags |= MG_COAP_IGNORE;
12533 cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
12534 cm->flags |= MG_COAP_MSG_TYPE_FIELD;
12542 cm->token.len = *ptr & 0x0F;
12543 if (cm->token.len > 8) {
12544 cm->flags |= MG_COAP_FORMAT_ERROR;
12554 cm->code_class = (uint8_t) *ptr >> 5;
12555 cm->code_detail = *ptr & 0x1F;
12556 cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
12561 cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
12562 cm->flags |= MG_COAP_MSG_ID_FIELD;
12574static char *coap_get_token(
char *ptr,
struct mbuf *io,
12575 struct mg_coap_message *cm) {
12576 if (cm->token.len != 0) {
12577 if (ptr + cm->token.len > io->
buf + io->
len) {
12578 cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
12582 ptr += cm->token.len;
12583 cm->flags |= MG_COAP_TOKEN_FIELD;
12595static int coap_get_ext_opt(
char *ptr,
struct mbuf *io, uint16_t *opt_info) {
12598 if (*opt_info == 13) {
12603 if (ptr < io->buf + io->
len) {
12604 *opt_info = (uint8_t) *ptr + 13;
12605 ret =
sizeof(uint8_t);
12609 }
else if (*opt_info == 14) {
12614 if (ptr +
sizeof(uint8_t) < io->
buf + io->
len) {
12615 *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
12616 ret =
sizeof(uint16_t);
12641static char *coap_get_options(
char *ptr,
struct mbuf *io,
12642 struct mg_coap_message *cm) {
12643 uint16_t prev_opt = 0;
12645 if (ptr == io->
buf + io->
len) {
12651 while (ptr < io->buf + io->
len && (uint8_t) *ptr != 0xFF) {
12652 uint16_t option_delta, option_lenght;
12656 option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
12658 option_lenght = *ptr & 0x0F;
12660 if (option_delta == 15 || option_lenght == 15) {
12665 cm->flags |= MG_COAP_FORMAT_ERROR;
12672 optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
12673 if (optinfo_len == -1) {
12674 cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
12678 ptr += optinfo_len;
12681 optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
12682 if (optinfo_len == -1) {
12683 cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
12687 ptr += optinfo_len;
12694 option_delta += prev_opt;
12696 mg_coap_add_option(cm, option_delta, ptr, option_lenght);
12698 prev_opt = option_delta;
12700 if (ptr + option_lenght > io->
buf + io->
len) {
12701 cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
12705 ptr += option_lenght;
12708 if ((cm->flags & MG_COAP_ERROR) != 0) {
12709 mg_coap_free_options(cm);
12713 cm->flags |= MG_COAP_OPTIOMG_FIELD;
12715 if (ptr == io->
buf + io->
len) {
12725uint32_t mg_coap_parse(
struct mbuf *io,
struct mg_coap_message *cm) {
12728 memset(cm, 0,
sizeof(*cm));
12730 if ((ptr = coap_parse_header(io->
buf, io, cm)) == NULL) {
12734 if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
12738 if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
12743 cm->payload.len = io->
len - (ptr - io->
buf);
12744 if (cm->payload.len != 0) {
12745 cm->payload.p = ptr;
12746 cm->flags |= MG_COAP_PAYLOAD_FIELD;
12757static size_t coap_get_ext_opt_size(uint32_t
value) {
12761 ret =
sizeof(uint8_t);
12762 }
else if (
value > 0xFF + 13 &&
value <= 0xFFFF + 269) {
12763 ret =
sizeof(uint16_t);
12774static int coap_split_opt(uint32_t
value, uint8_t *
base, uint16_t *ext) {
12779 }
else if (
value >= 13 &&
value <= 0xFF + 13) {
12782 ret =
sizeof(uint8_t);
12783 }
else if (
value > 0xFF + 13 &&
value <= 0xFFFF + 269) {
12785 *ext =
value - 269;
12786 ret =
sizeof(uint16_t);
12797static char *coap_add_uint16(
char *ptr, uint16_t val) {
12800 *ptr = val & 0x00FF;
12810static char *coap_add_opt_info(
char *ptr, uint16_t val,
size_t len) {
12811 if (len ==
sizeof(uint8_t)) {
12814 }
else if (len ==
sizeof(uint16_t)) {
12815 ptr = coap_add_uint16(ptr, val);
12826static uint32_t coap_calculate_packet_size(
struct mg_coap_message *cm,
12828 struct mg_coap_option *opt;
12829 uint32_t prev_opt_number;
12832 if (cm->msg_type > MG_COAP_MSG_MAX) {
12833 return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
12835 if (cm->token.len > 8) {
12836 return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
12838 if (cm->code_class > 7) {
12839 return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
12841 if (cm->code_detail > 31) {
12842 return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
12845 *len += cm->token.len;
12846 if (cm->payload.len != 0) {
12847 *len += cm->payload.len + 1;
12851 prev_opt_number = 0;
12852 while (opt != NULL) {
12854 *len += coap_get_ext_opt_size(opt->number - prev_opt_number);
12855 *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
12862 if ((opt->next != NULL && opt->number > opt->next->number) ||
12863 opt->value.len > 0xFFFF + 269 ||
12864 opt->number - prev_opt_number > 0xFFFF + 269) {
12865 return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
12867 *len += opt->value.len;
12868 prev_opt_number = opt->number;
12875uint32_t mg_coap_compose(
struct mg_coap_message *cm,
struct mbuf *io) {
12876 struct mg_coap_option *opt;
12877 uint32_t res, prev_opt_number;
12878 size_t prev_io_len, packet_size;
12881 res = coap_calculate_packet_size(cm, &packet_size);
12887 prev_io_len = io->
len;
12888 if (
mbuf_append(io, NULL, packet_size) == 0)
return MG_COAP_ERROR;
12889 ptr = io->
buf + prev_io_len;
12897 *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
12901 *ptr = (cm->code_class << 5) | (cm->code_detail);
12904 ptr = coap_add_uint16(ptr, cm->msg_id);
12906 if (cm->token.len != 0) {
12907 memcpy(ptr, cm->token.p, cm->token.len);
12908 ptr += cm->token.len;
12912 prev_opt_number = 0;
12913 while (opt != NULL) {
12914 uint8_t delta_base = 0, length_base = 0;
12915 uint16_t delta_ext = 0, length_ext = 0;
12917 size_t opt_delta_len =
12918 coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
12919 size_t opt_lenght_len =
12920 coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
12922 *ptr = (delta_base << 4) | length_base;
12925 ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
12926 ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
12928 if (opt->value.len != 0) {
12929 memcpy(ptr, opt->value.p, opt->value.len);
12930 ptr += opt->value.len;
12933 prev_opt_number = opt->number;
12937 if (cm->payload.len != 0) {
12940 memcpy(ptr, cm->payload.p, cm->payload.len);
12947 struct mg_coap_message *cm) {
12948 struct mbuf packet_out;
12949 uint32_t compose_res;
12952 compose_res = mg_coap_compose(cm, &packet_out);
12953 if (compose_res != 0) {
12954 return compose_res;
12957 mg_send(nc, packet_out.buf, (
int) packet_out.len);
12963uint32_t mg_coap_send_ack(
struct mg_connection *nc, uint16_t msg_id) {
12964 struct mg_coap_message cm;
12965 memset(&cm, 0,
sizeof(cm));
12966 cm.msg_type = MG_COAP_MSG_ACK;
12967 cm.msg_id = msg_id;
12969 return mg_coap_send_message(nc, &cm);
12973 void *ev_data
MG_UD_ARG(
void *user_data)) {
12975 struct mg_coap_message cm;
12976 uint32_t parse_res;
12978 memset(&cm, 0,
sizeof(cm));
12984 parse_res = mg_coap_parse(io, &cm);
12985 if ((parse_res & MG_COAP_IGNORE) == 0) {
12986 if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
12991 cm.flags |= MG_COAP_FORMAT_ERROR;
12993 nc->
handler(nc, MG_COAP_EVENT_BASE + cm.msg_type,
12997 mg_coap_free_options(&cm);
13024#ifdef MG_MODULE_LINES
13025#line 1 "mongoose/src/mg_sntp.c"
13038#define SNTP_TIME_OFFSET 2208988800
13040#ifndef SNTP_TIMEOUT
13041#define SNTP_TIMEOUT 10
13044#ifndef SNTP_ATTEMPTS
13045#define SNTP_ATTEMPTS 3
13048static uint64_t mg_get_sec(uint64_t val) {
13049 return (val & 0xFFFFFFFF00000000) >> 32;
13052static uint64_t mg_get_usec(uint64_t val) {
13053 uint64_t tmp = (val & 0x00000000FFFFFFFF);
13059static void mg_ntp_to_tv(uint64_t val,
struct timeval *
tv) {
13061 tmp = mg_get_sec(val);
13062 tmp -= SNTP_TIME_OFFSET;
13064 tv->tv_usec = mg_get_usec(val);
13067static void mg_get_ntp_ts(
const char *ntp, uint64_t *val) {
13069 memcpy(&tmp, ntp,
sizeof(tmp));
13071 *val = (uint64_t) tmp << 32;
13072 memcpy(&tmp, ntp + 4,
sizeof(tmp));
13078 uint8_t buf[48] = {0};
13084 buf[0] = (3 << 6) | (4 << 3) | 3;
13106#ifndef MG_SNTP_NO_DELAY_CORRECTION
13108 sec = htonl((uint32_t)(
mg_time() + SNTP_TIME_OFFSET));
13109 memcpy(&buf[40], &sec,
sizeof(sec));
13115#ifndef MG_SNTP_NO_DELAY_CORRECTION
13116static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) {
13118 uint64_t d1 = ((
mg_time() + SNTP_TIME_OFFSET) * 1000000) -
13119 (mg_get_sec(t1) * 1000000 + mg_get_usec(t1));
13120 uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) -
13121 (mg_get_sec(t2) * 1000000 + mg_get_usec(t2));
13123 return (d1 > d2) ? d1 - d2 : 0;
13127MG_INTERNAL int mg_sntp_parse_reply(
const char *buf,
int len,
13128 struct mg_sntp_message *msg) {
13130 uint64_t trsm_ts_T3, delay = 0;
13140 if ((hdr & 0x38) >> 3 != 4) {
13146 if (mode != 4 && mode != 5) {
13151 memset(msg, 0,
sizeof(*msg));
13153 msg->kiss_of_death = (buf[1] == 0);
13155 mg_get_ntp_ts(&buf[40], &trsm_ts_T3);
13157#ifndef MG_SNTP_NO_DELAY_CORRECTION
13159 uint64_t orig_ts_T1, recv_ts_T2;
13160 mg_get_ntp_ts(&buf[24], &orig_ts_T1);
13161 mg_get_ntp_ts(&buf[32], &recv_ts_T2);
13162 delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3);
13166 mg_ntp_to_tv(trsm_ts_T3, &
tv);
13168 msg->time = (double)
tv.tv_sec + (((
double)
tv.tv_usec + delay) / 1000000.0);
13174 void *ev_data
MG_UD_ARG(
void *user_data)) {
13175 struct mbuf *io = &
c->recv_mbuf;
13176 struct mg_sntp_message msg;
13182 if (mg_sntp_parse_reply(io->
buf, io->
len, &msg) < 0) {
13183 DBG((
"Invalid SNTP packet received (%d)", (
int) io->
len));
13184 c->handler(
c, MG_SNTP_MALFORMED_REPLY, NULL
MG_UD_ARG(user_data));
13186 c->handler(
c, MG_SNTP_REPLY, (
void *) &msg
MG_UD_ARG(user_data));
13200 c->proto_handler = mg_sntp_handler;
13208 const char *sntp_server_name) {
13210 char url[100], *p_url = url;
13211 const char *proto =
"", *port =
"", *tmp;
13214 tmp = strchr(sntp_server_name,
':');
13215 if (tmp != NULL && *(tmp + 1) ==
'/') {
13216 tmp = strchr(tmp + 1,
':');
13224 if (strncmp(sntp_server_name,
"udp://", 6) != 0) {
13228 mg_asprintf(&p_url,
sizeof(url),
"%s%s%s", proto, sntp_server_name, port);
13236 mg_set_protocol_sntp(
c);
13239 if (p_url != url) {
13251static void mg_sntp_util_ev_handler(
struct mg_connection *
c,
int ev,
13252 void *ev_data
MG_UD_ARG(
void *user_data)) {
13253#if !MG_ENABLE_CALLBACK_USERDATA
13254 void *user_data =
c->user_data;
13256 struct sntp_data *sd = (
struct sntp_data *) user_data;
13260 if (*(
int *) ev_data != 0) {
13261 mg_call(
c, sd->hander,
c->user_data, MG_SNTP_FAILED, NULL);
13266 if (sd->count <= SNTP_ATTEMPTS) {
13267 mg_sntp_send_request(
c);
13271 mg_call(
c, sd->hander,
c->user_data, MG_SNTP_FAILED, NULL);
13275 case MG_SNTP_MALFORMED_REPLY:
13276 mg_call(
c, sd->hander,
c->user_data, MG_SNTP_FAILED, NULL);
13279 case MG_SNTP_REPLY:
13280 mg_call(
c, sd->hander,
c->user_data, MG_SNTP_REPLY, ev_data);
13285 c->user_data = NULL;
13292 const char *sntp_server_name) {
13294 struct sntp_data *sd = (
struct sntp_data *)
MG_CALLOC(1,
sizeof(*sd));
13299 c = mg_sntp_connect(mgr,
MG_CB(mg_sntp_util_ev_handler, sd),
13306 sd->hander = event_handler;
13307#if !MG_ENABLE_CALLBACK_USERDATA
13315#ifdef MG_MODULE_LINES
13316#line 1 "mongoose/src/mg_socks.c"
13338 struct mbuf *r = &
c->recv_mbuf;
13339 if (r->
buf[0] != MG_SOCKS_VERSION) {
13341 }
else if (r->
len > 2 && (
size_t) r->
buf[1] + 2 <= r->
len) {
13343 unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE};
13345 for (
i = 2;
i < r->
buf[1] + 2;
i++) {
13347 if (r->
buf[
i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->
buf[
i];
13351 c->flags |= MG_SOCKS_HANDSHAKE_DONE;
13359 c2->user_data = NULL;
13362 c->user_data = NULL;
13368 mg_send(c2,
c->recv_mbuf.buf,
c->recv_mbuf.len);
13375static void serv_ev_handler(
struct mg_connection *
c,
int ev,
void *ev_data) {
13381 int res = *(
int *) ev_data;
13382 if (res != 0)
LOG(
LL_ERROR, (
"connect error: %d", res));
13389 c->user_data = serv;
13402 struct mbuf *r = &
c->recv_mbuf;
13403 unsigned char *p = (
unsigned char *) r->
buf;
13404 unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS;
13405 int ver, cmd, atyp;
13408 if (r->
len < 8)
return;
13414 if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) {
13415 reply = MG_SOCKS_CMD_NOT_SUPPORTED;
13416 }
else if (atyp == MG_SOCKS_ADDR_IPV4) {
13418 if (r->
len < (
size_t) addr_len + 6)
return;
13419 snprintf(
addr,
sizeof(
addr),
"%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7],
13421 mg_socks5_connect(
c,
addr);
13422 }
else if (atyp == MG_SOCKS_ADDR_IPV6) {
13424 if (r->
len < (
size_t) addr_len + 6)
return;
13425 snprintf(
addr,
sizeof(
addr),
"[%x:%x:%x:%x:%x:%x:%x:%x]:%d",
13426 p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9],
13427 p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15],
13428 p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]);
13429 mg_socks5_connect(
c,
addr);
13430 }
else if (atyp == MG_SOCKS_ADDR_DOMAIN) {
13431 addr_len = p[4] + 1;
13432 if (r->
len < (
size_t) addr_len + 6)
return;
13433 snprintf(
addr,
sizeof(
addr),
"%.*s:%d", p[4], p + 5,
13434 p[4 + addr_len] << 8 | p[4 + addr_len + 1]);
13435 mg_socks5_connect(
c,
addr);
13437 reply = MG_SOCKS_ADDR_NOT_SUPPORTED;
13450 unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0};
13456 c->flags |= MG_SOCKS_CONNECT_DONE;
13459static void socks_handler(
struct mg_connection *
c,
int ev,
void *ev_data) {
13461 if (!(
c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(
c);
13462 if (
c->flags & MG_SOCKS_HANDSHAKE_DONE &&
13463 !(
c->flags & MG_SOCKS_CONNECT_DONE)) {
13464 mg_socks5_handle_request(
c);
13466 if (
c->flags & MG_SOCKS_CONNECT_DONE) relay_data(
c);
13474 c->proto_handler = socks_handler;
13477#ifdef MG_MODULE_LINES
13478#line 1 "common/platforms/cc3200/cc3200_libc.c"
13497#if CS_PLATFORM == CS_P_CC3200
13503#ifndef __TI_COMPILER_VERSION__
13505#include <sys/stat.h>
13506#include <sys/time.h>
13510#include <inc/hw_types.h>
13511#include <inc/hw_memmap.h>
13512#include <driverlib/prcm.h>
13513#include <driverlib/rom.h>
13514#include <driverlib/rom_map.h>
13515#include <driverlib/uart.h>
13516#include <driverlib/utils.h>
13518#define CONSOLE_UART UARTA0_BASE
13520#ifdef __TI_COMPILER_VERSION__
13521int asprintf(
char **strp,
const char *fmt, ...) {
13526 if (*strp == NULL)
return -1;
13529 len = vsnprintf(*strp, BUFSIZ, fmt, ap);
13534 if (*strp == NULL)
return -1;
13537 if (
len >= BUFSIZ) {
13539 len = vsnprintf(*strp,
len + 1, fmt, ap);
13546#if MG_TI_NO_HOST_INTERFACE
13557 while (*
str !=
'\0') {
13573 fprint_str(stderr,
" is not implemented\n");
13585 fprint_str(stderr,
"_getpid is not implemented\n");
13595#ifdef MG_MODULE_LINES
13596#line 1 "common/platforms/msp432/msp432_libc.c"
13615#if CS_PLATFORM == CS_P_MSP432
13617#include <ti/sysbios/BIOS.h>
13618#include <ti/sysbios/knl/Clock.h>
13621 uint32_t ticks = Clock_getTicks();
13622 tp->tv_sec = ticks / 1000;
13623 tp->tv_usec = (ticks % 1000) * 1000;
13628#ifdef MG_MODULE_LINES
13629#line 1 "common/platforms/nrf5/nrf5_libc.c"
13648#if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
13649 defined(__ARMCC_VERSION)
13657#ifdef MG_MODULE_LINES
13658#line 1 "common/platforms/simplelink/sl_fs_slfs.h"
13677#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
13678#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
13680#if defined(MG_FS_SLFS)
13683#ifndef __TI_COMPILER_VERSION__
13685#include <sys/stat.h>
13688#define MAX_OPEN_SLFS_FILES 8
13691int fs_slfs_open(
const char *pathname,
int flags, mode_t mode);
13692int fs_slfs_close(
int fd);
13693ssize_t fs_slfs_read(
int fd,
void *buf,
size_t count);
13694ssize_t fs_slfs_write(
int fd,
const void *buf,
size_t count);
13695int fs_slfs_stat(
const char *pathname,
struct stat *s);
13696int fs_slfs_fstat(
int fd,
struct stat *s);
13697off_t fs_slfs_lseek(
int fd, off_t
offset,
int whence);
13698int fs_slfs_unlink(
const char *filename);
13699int fs_slfs_rename(
const char *from,
const char *to);
13701void fs_slfs_set_file_size(
const char *
name,
size_t size);
13702void fs_slfs_set_file_flags(
const char *
name, uint32_t flags, uint32_t *token);
13703void fs_slfs_unset_file_flags(
const char *
name);
13708#ifdef MG_MODULE_LINES
13709#line 1 "common/platforms/simplelink/sl_fs_slfs.c"
13730#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
13736#if CS_PLATFORM == CS_P_CC3200
13737#include <inc/hw_types.h>
13743#if SL_MAJOR_VERSION_NUM < 2
13744int slfs_open(
const unsigned char *fname, uint32_t flags, uint32_t *token) {
13746 _i32 r = sl_FsOpen(fname, flags, (
unsigned long *) token, &fh);
13747 return (r < 0 ? r : fh);
13750int slfs_open(
const unsigned char *fname, uint32_t flags, uint32_t *token) {
13751 return sl_FsOpen(fname, flags, (
unsigned long *) token);
13756int set_errno(
int e);
13757const char *drop_dir(
const char *fname,
bool *is_slfs);
13763#ifndef FS_SLFS_MAX_FILE_SIZE
13764#define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
13767struct sl_file_open_info {
13780static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
13781static struct sl_file_open_info s_sl_file_open_infos[MAX_OPEN_SLFS_FILES];
13783static struct sl_file_open_info *fs_slfs_find_foi(
const char *
name,
13786static int sl_fs_to_errno(_i32 r) {
13787 DBG((
"SL error: %d", (
int) r));
13791 case SL_ERROR_FS_FILE_NAME_EXIST:
13793 case SL_ERROR_FS_WRONG_FILE_NAME:
13795 case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX:
13796 case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE:
13798 case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM:
13800 case SL_ERROR_FS_FILE_NOT_EXISTS:
13802 case SL_ERROR_FS_NOT_SUPPORTED:
13808int fs_slfs_open(
const char *pathname,
int flags, mode_t mode) {
13810 for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
13811 if (s_sl_fds[fd].fh <= 0)
break;
13813 if (fd >= MAX_OPEN_SLFS_FILES)
return set_errno(ENOMEM);
13814 struct sl_fd_info *fi = &s_sl_fds[fd];
13820 pathname = drop_dir(pathname, NULL);
13823 fi->size = (size_t) -1;
13824 int rw = (flags & 3);
13825 size_t new_size = 0;
13826 struct sl_file_open_info *foi =
13827 fs_slfs_find_foi(pathname,
false );
13829 LOG(
LL_DEBUG, (
"FOI for %s: %d 0x%x %p", pathname, (
int) foi->size,
13830 (
unsigned int) foi->flags, foi->token));
13832 if (rw == O_RDONLY) {
13833 SlFsFileInfo_t sl_fi;
13834 _i32 r = sl_FsGetInfo((
const _u8 *) pathname, 0, &sl_fi);
13835 if (r == SL_FS_OK) {
13836 fi->size = SL_FI_FILE_SIZE(sl_fi);
13840 if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
13843 return set_errno(ENOTSUP);
13845 if (flags & O_CREAT) {
13846 if (foi->size > 0) {
13847 new_size = foi->size;
13849 new_size = FS_SLFS_MAX_FILE_SIZE;
13851 am = FS_MODE_OPEN_CREATE(new_size, 0);
13855#if SL_MAJOR_VERSION_NUM >= 2
13856 am |= SL_FS_OVERWRITE;
13859 uint32_t *token = NULL;
13862 token = foi->token;
13864 fi->fh = slfs_open((_u8 *) pathname, am, token);
13865 LOG(
LL_DEBUG, (
"sl_FsOpen(%s, 0x%x, %p) sz %u = %d", pathname, (
int) am,
13866 token, (
unsigned int) new_size, (
int) fi->fh));
13872 r = set_errno(sl_fs_to_errno(fi->fh));
13877int fs_slfs_close(
int fd) {
13878 struct sl_fd_info *fi = &s_sl_fds[fd];
13879 if (fi->fh <= 0)
return set_errno(EBADF);
13880 _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
13881 LOG(
LL_DEBUG, (
"sl_FsClose(%d) = %d", (
int) fi->fh, (
int) r));
13882 s_sl_fds[fd].fh = -1;
13883 return set_errno(sl_fs_to_errno(r));
13886ssize_t fs_slfs_read(
int fd,
void *buf,
size_t count) {
13887 struct sl_fd_info *fi = &s_sl_fds[fd];
13888 if (fi->fh <= 0)
return set_errno(EBADF);
13891 if (fi->pos == fi->size)
return 0;
13892 _i32 r = sl_FsRead(fi->fh, fi->pos, buf,
count);
13893 DBG((
"sl_FsRead(%d, %d, %d) = %d", (
int) fi->fh, (
int) fi->pos, (
int)
count,
13899 return set_errno(sl_fs_to_errno(r));
13902ssize_t fs_slfs_write(
int fd,
const void *buf,
size_t count) {
13903 struct sl_fd_info *fi = &s_sl_fds[fd];
13904 if (fi->fh <= 0)
return set_errno(EBADF);
13905 _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf,
count);
13906 DBG((
"sl_FsWrite(%d, %d, %d) = %d", (
int) fi->fh, (
int) fi->pos, (
int)
count,
13912 return set_errno(sl_fs_to_errno(r));
13915int fs_slfs_stat(
const char *pathname,
struct stat *s) {
13916 SlFsFileInfo_t sl_fi;
13921 pathname = drop_dir(pathname, NULL);
13922 _i32 r = sl_FsGetInfo((
const _u8 *) pathname, 0, &sl_fi);
13923 if (r == SL_FS_OK) {
13924 s->st_mode = S_IFREG | 0666;
13926 s->st_size = SL_FI_FILE_SIZE(sl_fi);
13929 return set_errno(sl_fs_to_errno(r));
13932int fs_slfs_fstat(
int fd,
struct stat *s) {
13933 struct sl_fd_info *fi = &s_sl_fds[fd];
13934 if (fi->fh <= 0)
return set_errno(EBADF);
13936 s->st_mode = S_IFREG | 0666;
13938 s->st_size = fi->size;
13942off_t fs_slfs_lseek(
int fd, off_t
offset,
int whence) {
13943 if (s_sl_fds[fd].fh <= 0)
return set_errno(EBADF);
13946 s_sl_fds[fd].pos =
offset;
13949 s_sl_fds[fd].pos +=
offset;
13952 return set_errno(ENOTSUP);
13957int fs_slfs_unlink(
const char *pathname) {
13962 pathname = drop_dir(pathname, NULL);
13963 return set_errno(sl_fs_to_errno(sl_FsDel((
const _u8 *) pathname, 0)));
13966int fs_slfs_rename(
const char *from,
const char *to) {
13967 return set_errno(ENOTSUP);
13970static struct sl_file_open_info *fs_slfs_find_foi(
const char *
name,
13973 for (
i = 0;
i < MAX_OPEN_SLFS_FILES;
i++) {
13974 if (s_sl_file_open_infos[
i].
name != NULL &&
13975 strcmp(drop_dir(s_sl_file_open_infos[
i].
name, NULL),
name) == 0) {
13979 if (
i != MAX_OPEN_SLFS_FILES)
return &s_sl_file_open_infos[
i];
13980 if (!
create)
return NULL;
13981 for (
i = 0;
i < MAX_OPEN_SLFS_FILES;
i++) {
13982 if (s_sl_file_open_infos[
i].
name == NULL)
break;
13984 if (
i == MAX_OPEN_SLFS_FILES) {
13987 if (s_sl_file_open_infos[
i].
name != NULL) {
13988 free(s_sl_file_open_infos[
i].
name);
13990 s_sl_file_open_infos[
i].name = strdup(
name);
13991 return &s_sl_file_open_infos[
i];
13994void fs_slfs_set_file_size(
const char *
name,
size_t size) {
13995 struct sl_file_open_info *foi = fs_slfs_find_foi(
name,
true );
13999void fs_slfs_set_file_flags(
const char *
name, uint32_t flags, uint32_t *token) {
14000 struct sl_file_open_info *foi = fs_slfs_find_foi(
name,
true );
14001 foi->flags = flags;
14002 foi->token = token;
14005void fs_slfs_unset_file_flags(
const char *
name) {
14006 struct sl_file_open_info *foi = fs_slfs_find_foi(
name,
false );
14007 if (foi == NULL)
return;
14009 memset(foi, 0,
sizeof(*foi));
14013#ifdef MG_MODULE_LINES
14014#line 1 "common/platforms/simplelink/sl_fs.c"
14033#if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
14034 (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
14036int set_errno(
int e) {
14038 return (
e == 0 ? 0 : -1);
14041const char *drop_dir(
const char *fname,
bool *is_slfs) {
14042 if (is_slfs != NULL) {
14043 *is_slfs = (strncmp(fname,
"SL:", 3) == 0);
14044 if (*is_slfs) fname += 3;
14047 if (fname[0] ==
'.' && fname[1] ==
'/') {
14054 if (fname[0] ==
'/' && strchr(fname + 1,
'/') == NULL) {
14060#if !defined(MG_FS_NO_VFS)
14063#include <stdbool.h>
14067#ifdef __TI_COMPILER_VERSION__
14074#ifdef CC3200_FS_SPIFFS
14082#define NUM_SYS_FDS 3
14083#define SPIFFS_FD_BASE 10
14084#define SLFS_FD_BASE 100
14086#if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE)
14087#if CS_PLATFORM == CS_P_CC3200
14088#include <inc/hw_types.h>
14089#include <inc/hw_memmap.h>
14090#include <driverlib/rom.h>
14091#include <driverlib/rom_map.h>
14092#include <driverlib/uart.h>
14093#define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
14095#define MG_UART_WRITE(fd, buf, len)
14102#ifdef CC3200_FS_SPIFFS
14109static int fd_type(
int fd) {
14110 if (fd >= 0 && fd < NUM_SYS_FDS)
return FD_SYS;
14111#ifdef CC3200_FS_SPIFFS
14112 if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
14117 if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
14124#if MG_TI_NO_HOST_INTERFACE
14125int open(
const char *pathname,
unsigned flags,
int mode) {
14127int _open(
const char *pathname,
int flags, mode_t mode) {
14131 const char *fname = drop_dir(pathname, &is_sl);
14134 fd = fs_slfs_open(fname, flags, mode);
14135 if (fd >= 0) fd += SLFS_FD_BASE;
14138#ifdef CC3200_FS_SPIFFS
14139 fd = fs_spiffs_open(fname, flags, mode);
14140 if (fd >= 0) fd += SPIFFS_FD_BASE;
14144 (
"open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
14148int _stat(
const char *pathname,
struct stat *st) {
14151 const char *fname = drop_dir(pathname, &is_sl);
14152 memset(st, 0,
sizeof(*st));
14154 if (fname[0] ==
'\0' || strcmp(fname,
".") == 0) {
14156 st->st_mode = S_IFDIR | 0777;
14163 res = fs_slfs_stat(fname, st);
14166#ifdef CC3200_FS_SPIFFS
14167 res = fs_spiffs_stat(fname, st);
14170 LOG(
LL_DEBUG, (
"stat(%s) = %d; fname = %s", pathname, res, fname));
14174#if MG_TI_NO_HOST_INTERFACE
14177int _close(
int fd) {
14180 switch (fd_type(fd)) {
14182 r = set_errno(EBADF);
14185 r = set_errno(EACCES);
14187#ifdef CC3200_FS_SPIFFS
14189 r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
14194 r = fs_slfs_close(fd - SLFS_FD_BASE);
14198 DBG((
"close(%d) = %d", fd, r));
14202#if MG_TI_NO_HOST_INTERFACE
14203off_t lseek(
int fd, off_t
offset,
int whence) {
14205off_t _lseek(
int fd, off_t
offset,
int whence) {
14208 switch (fd_type(fd)) {
14210 r = set_errno(EBADF);
14213 r = set_errno(ESPIPE);
14215#ifdef CC3200_FS_SPIFFS
14217 r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE,
offset, whence);
14222 r = fs_slfs_lseek(fd - SLFS_FD_BASE,
offset, whence);
14226 DBG((
"lseek(%d, %d, %d) = %d", fd, (
int)
offset, whence, r));
14230int _fstat(
int fd,
struct stat *s) {
14232 memset(s, 0,
sizeof(*s));
14233 switch (fd_type(fd)) {
14235 r = set_errno(EBADF);
14239 memset(s, 0,
sizeof(*s));
14241 s->st_mode = S_IFCHR | 0666;
14245#ifdef CC3200_FS_SPIFFS
14247 r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
14252 r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
14256 DBG((
"fstat(%d) = %d", fd, r));
14260#if MG_TI_NO_HOST_INTERFACE
14261int read(
int fd,
char *buf,
unsigned count) {
14263ssize_t _read(
int fd,
void *buf,
size_t count) {
14266 switch (fd_type(fd)) {
14268 r = set_errno(EBADF);
14272 r = set_errno(EACCES);
14276 r = set_errno(ENOTSUP);
14279#ifdef CC3200_FS_SPIFFS
14281 r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf,
count);
14286 r = fs_slfs_read(fd - SLFS_FD_BASE, buf,
count);
14290 DBG((
"read(%d, %u) = %d", fd,
count, r));
14294#if MG_TI_NO_HOST_INTERFACE
14295int write(
int fd,
const char *buf,
unsigned count) {
14297ssize_t _write(
int fd,
const void *buf,
size_t count) {
14300 switch (fd_type(fd)) {
14302 r = set_errno(EBADF);
14306 r = set_errno(EACCES);
14309#ifdef MG_UART_WRITE
14310 MG_UART_WRITE(fd, buf,
count);
14311#elif defined(MG_UART_CHAR_PUT)
14315 const char c = ((
const char *) buf)[
i];
14316 if (
c ==
'\n') MG_UART_CHAR_PUT(fd,
'\r');
14317 MG_UART_CHAR_PUT(fd,
c);
14324#ifdef CC3200_FS_SPIFFS
14326 r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf,
count);
14331 r = fs_slfs_write(fd - SLFS_FD_BASE, buf,
count);
14342#if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
14343int rename(
const char *frompath,
const char *topath) {
14345 bool is_sl_from, is_sl_to;
14346 const char *from = drop_dir(frompath, &is_sl_from);
14347 const char *to = drop_dir(topath, &is_sl_to);
14348 if (is_sl_from || is_sl_to) {
14349 set_errno(ENOTSUP);
14351#ifdef CC3200_FS_SPIFFS
14352 r = fs_spiffs_rename(from, to);
14355 DBG((
"rename(%s, %s) = %d", from, to, r));
14360#if MG_TI_NO_HOST_INTERFACE
14361int unlink(
const char *pathname) {
14363int _unlink(
const char *pathname) {
14367 const char *fname = drop_dir(pathname, &is_sl);
14370 r = fs_slfs_unlink(fname);
14373#ifdef CC3200_FS_SPIFFS
14374 r = fs_spiffs_unlink(fname);
14377 DBG((
"unlink(%s) = %d, fname = %s", pathname, r, fname));
14381#ifdef CC3200_FS_SPIFFS
14382DIR *opendir(
const char *dir_name) {
14385 drop_dir(dir_name, &is_sl);
14388 set_errno(ENOTSUP);
14390 r = fs_spiffs_opendir(dir_name);
14392 DBG((
"opendir(%s) = %p", dir_name, r));
14396struct dirent *readdir(
DIR *dir) {
14397 struct dirent *res = fs_spiffs_readdir(dir);
14398 DBG((
"readdir(%p) = %p", dir, res));
14402int closedir(
DIR *dir) {
14403 int res = fs_spiffs_closedir(dir);
14404 DBG((
"closedir(%p) = %d", dir, res));
14408int rmdir(
const char *path) {
14409 return fs_spiffs_rmdir(path);
14412int mkdir(
const char *path, mode_t mode) {
14416 return (strlen(path) == 1 && *path ==
'.') ? 0 : ENOTDIR;
14420int sl_fs_init(
void) {
14422#ifdef __TI_COMPILER_VERSION__
14425#pragma diag_suppress 169
14427 ret = (add_device(
"SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
14428 fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
14429 fs_slfs_rename) == 0);
14439#ifdef MG_MODULE_LINES
14440#line 1 "common/platforms/simplelink/sl_socket.c"
14459#if MG_NET_IF == MG_NET_IF_SIMPLELINK
14466const char *
inet_ntop(
int af,
const void *src,
char *dst, socklen_t size) {
14468 struct in_addr *in = (
struct in_addr *) src;
14469 if (af != AF_INET) {
14473 res = snprintf(dst, size,
"%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
14474 SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
14475 SL_IPV4_BYTE(in->s_addr, 3));
14476 return res > 0 ? dst : NULL;
14481 return (
char *)
inet_ntop(AF_INET, &
n, a,
sizeof(a));
14485 uint32_t a0, a1, a2, a3;
14486 uint8_t *db = (uint8_t *) dst;
14487 if (af != AF_INET) {
14491 if (sscanf(src,
"%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
14502#ifdef MG_MODULE_LINES
14503#line 1 "common/platforms/simplelink/sl_mg_task.c"
14505#if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
14509#include <oslib/osi.h>
14520static void mg_task(
void *arg);
14523 if (osi_MsgQCreate(&
s_mg_q,
"MG",
sizeof(
struct mg_q_msg), 16) != OSI_OK) {
14526 if (osi_TaskCreate(
mg_task, (
const signed char *)
"MG", stack_size,
14527 (
void *) mg_init, priority, NULL) != OSI_OK) {
14535 mg_init_cb mg_init = (mg_init_cb) arg;
14541 if (osi_MsgQRead(&
s_mg_q, &msg, 1) != OSI_OK)
continue;
14542 switch (msg.
type) {
14544 msg.
cb(&mgr, msg.
arg);
14552 osi_MsgQWrite(&
s_mg_q, &msg, OSI_NO_WAIT);
14557#ifdef MG_MODULE_LINES
14558#line 1 "common/platforms/simplelink/sl_net_if.h"
14577#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
14578#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
14586#ifndef MG_ENABLE_NET_IF_SIMPLELINK
14587#define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
14597#ifdef MG_MODULE_LINES
14598#line 1 "common/platforms/simplelink/sl_net_if.c"
14619#if MG_ENABLE_NET_IF_SIMPLELINK
14624#define MG_TCP_RECV_BUFFER_SIZE 1024
14625#define MG_UDP_RECV_BUFFER_SIZE 1500
14632 SlSockNonblocking_t opt;
14633#if SL_MAJOR_VERSION_NUM < 2
14634 opt.NonblockingEnabled = 1;
14636 opt.NonBlockingEnabled = 1;
14638 sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt,
sizeof(opt));
14642 return (
n < 0 &&
n != SL_ERROR_BSD_EALREADY &&
n != SL_ERROR_BSD_EAGAIN);
14648#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
14651 sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
14657#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
14658 nc->
err = sl_set_ssl_opts(sock, nc);
14659 if (nc->
err != 0)
goto out;
14661 nc->
err = sl_Connect(sock, &sa->
sa,
sizeof(sa->
sin));
14663 DBG((
"%p to %s:%d sock %d %d err %d", nc,
inet_ntoa(sa->
sin.sin_addr),
14664 ntohs(sa->
sin.sin_port), nc->
sock, proto, nc->
err));
14668 sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
14682 if (sock < 0)
return sock;
14697 int n = (int) sl_Send(nc->
sock, buf, len, 0);
14704 int n = sl_SendTo(nc->
sock, buf, len, 0, &nc->
sa.
sa,
sizeof(nc->
sa.
sin));
14710 int n = sl_Recv(nc->
sock, buf, len, 0);
14722 SlSocklen_t sa_len_t = *sa_len;
14724 (SlSockAddr_t *) sa, &sa_len_t);
14725 *sa_len = sa_len_t;
14739 sl_Close(nc->
sock);
14747 socklen_t sa_len =
sizeof(
sa);
14748 sock_t sock = sl_Accept(lc->
sock, &
sa.sa, &sa_len);
14750 DBG((
"%p: failed to accept: %d", lc, sock));
14759 ntohs(
sa.sin.sin_port)));
14771 (
sa->sa.sa_family == AF_INET) ?
sizeof(
sa->sin) :
sizeof(
sa->sin6);
14772 sock_t sock = sl_Socket(
sa->sa.sa_family,
type, proto);
14773 if (sock < 0)
return sock;
14774#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
14775 if ((r = sl_set_ssl_opts(sock, nc)) < 0)
goto clean;
14777 if ((r = sl_Bind(sock, &
sa->sa, sa_len)) < 0)
goto clean;
14778 if (
type != SOCK_DGRAM) {
14779 if ((r = sl_Listen(sock,
SOMAXCONN)) < 0)
goto clean;
14790#define _MG_F_FD_CAN_READ 1
14791#define _MG_F_FD_CAN_WRITE 1 << 1
14792#define _MG_F_FD_ERROR 1 << 2
14795 DBG((
"%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->
sock,
14809 DBG((
"%p conn res=%d", nc, nc->
err));
14810 if (nc->
err == SL_ERROR_BSD_ESECSNOVERIFY ||
14812 nc->
err == SL_ERROR_BSD_ESECDATEERROR
14813#
if SL_MAJOR_VERSION_NUM >= 2
14818 nc->
err == SL_ERROR_BSD_ESECUNKNOWNROOTCA
14846 DBG((
"%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->
sock, nc->
flags,
14854 DBG((
"%p %d", nc, sock));
14859 DBG((
"%p using sl_Select()", iface->
mgr));
14879 struct SlTimeval_t
tv;
14880 SlFdSet_t read_set, write_set, err_set;
14882 int num_fds, num_ev = 0, num_timers = 0;
14884 SL_SOCKET_FD_ZERO(&read_set);
14885 SL_SOCKET_FD_ZERO(&write_set);
14886 SL_SOCKET_FD_ZERO(&err_set);
14902 SL_SOCKET_FD_SET(nc->
sock, &read_set);
14908 SL_SOCKET_FD_SET(nc->
sock, &write_set);
14909 SL_SOCKET_FD_SET(nc->
sock, &err_set);
14926 if (num_timers > 0) {
14927 double timer_timeout_ms = (min_timer -
mg_time()) * 1000 + 1 ;
14928 if (timer_timeout_ms < timeout_ms) {
14929 timeout_ms = timer_timeout_ms;
14932 if (timeout_ms < 0) timeout_ms = 0;
14934 tv.tv_sec = timeout_ms / 1000;
14935 tv.tv_usec = (timeout_ms % 1000) * 1000;
14938 num_ev = sl_Select((
int) max_fd + 1, &read_set, &write_set, &err_set, &
tv);
14942 DBG((
"sl_Select @ %ld num_ev=%d of %d, timeout=%d", (
long) now, num_ev,
14943 num_fds, timeout_ms));
14950 (SL_SOCKET_FD_ISSET(nc->
sock, &read_set) &&
14975 if (remote) memcpy(sa, &nc->
sa,
sizeof(*sa));
14989 ntohs(nc->
sa.
sin.sin_port)));
14992 if (res == 0)
continue;
14997 ntohs(nc->
sa.
sin.sin_port)));
15004#define MG_SL_IFACE_VTABLE \
15008 mg_sl_if_add_conn, \
15009 mg_sl_if_remove_conn, \
15011 mg_sl_if_listen_tcp, \
15012 mg_sl_if_listen_udp, \
15013 mg_sl_if_connect_tcp, \
15014 mg_sl_if_connect_udp, \
15015 mg_sl_if_tcp_send, \
15016 mg_sl_if_udp_send, \
15017 mg_sl_if_tcp_recv, \
15018 mg_sl_if_udp_recv, \
15019 mg_sl_if_create_conn, \
15020 mg_sl_if_destroy_conn, \
15021 mg_sl_if_sock_set, \
15022 mg_sl_if_get_conn_addr, \
15027#if MG_NET_IF == MG_NET_IF_SIMPLELINK
15032#ifdef MG_MODULE_LINES
15033#line 1 "common/platforms/simplelink/sl_ssl_if.c"
15052#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
15056#ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX
15057#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:"
15060#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \
15061 (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1)
15063struct mg_ssl_if_ctx {
15067 char *ssl_server_name;
15070void mg_ssl_if_init() {
15073enum mg_ssl_if_result mg_ssl_if_conn_init(
15074 struct mg_connection *nc,
const struct mg_ssl_if_conn_params *params,
15075 const char **err_msg) {
15076 struct mg_ssl_if_ctx *ctx =
15077 (
struct mg_ssl_if_ctx *)
MG_CALLOC(1,
sizeof(*ctx));
15080 return MG_SSL_ERROR;
15082 nc->ssl_if_data = ctx;
15084 if (params->cert != NULL || params->key != NULL) {
15085 if (params->cert != NULL && params->key != NULL) {
15086 ctx->ssl_cert = strdup(params->cert);
15087 ctx->ssl_key = strdup(params->key);
15090 return MG_SSL_ERROR;
15093 if (params->ca_cert != NULL && strcmp(params->ca_cert,
"*") != 0) {
15094 ctx->ssl_ca_cert = strdup(params->ca_cert);
15097 if (params->server_name != NULL) {
15098 ctx->ssl_server_name = strdup(params->server_name);
15103enum mg_ssl_if_result mg_ssl_if_conn_accept(
struct mg_connection *nc,
15111enum mg_ssl_if_result mg_ssl_if_handshake(
struct mg_connection *nc) {
15116int mg_ssl_if_read(
struct mg_connection *nc,
void *buf,
size_t len) {
15123int mg_ssl_if_write(
struct mg_connection *nc,
const void *buf,
size_t len) {
15128void mg_ssl_if_conn_close_notify(
struct mg_connection *nc) {
15134 struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
15135 if (ctx == NULL)
return;
15136 nc->ssl_if_data = NULL;
15140 MG_FREE(ctx->ssl_server_name);
15141 memset(ctx, 0,
sizeof(*ctx));
15145bool pem_to_der(
const char *pem_file,
const char *der_file) {
15147 FILE *pf = NULL, *df = NULL;
15148 bool writing =
false;
15149 pf = fopen(pem_file,
"r");
15150 if (pf == NULL)
goto clean;
15152 fs_slfs_set_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, 2048);
15153 df = fopen(der_file,
"w");
15154 fs_slfs_unset_file_flags(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN);
15155 if (df == NULL)
goto clean;
15159 if (!fgets(pem_buf,
sizeof(pem_buf), pf))
break;
15161 if (strstr(pem_buf,
"-----END ") != NULL) {
15166 while (!isspace((
unsigned int) pem_buf[l])) l++;
15169 der_buf, &der_len);
15170 if (der_len <= 0)
break;
15171 if (fwrite(der_buf, 1, der_len, df) != der_len)
break;
15172 }
else if (strstr(pem_buf,
"-----BEGIN ") != NULL) {
15178 if (pf != NULL) fclose(pf);
15181 if (!ret)
remove(der_file);
15186#if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
15188static char *sl_pem2der(
const char *pem_file) {
15189 const char *pem_ext = strstr(pem_file,
".pem");
15190 if (pem_ext == NULL || *(pem_ext + 4) !=
'\0') {
15191 return strdup(pem_file);
15193 char *der_file = NULL;
15195 int l =
mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX
"%.*s.der",
15196 (
int) (pem_ext - pem_file), pem_file);
15197 if (der_file == NULL)
return NULL;
15198 bool result =
false;
15200 if (
mg_stat(der_file, &st) != 0) {
15201 result = pem_to_der(pem_file, der_file);
15202 LOG(
LL_DEBUG, (
"%s -> %s = %d", pem_file, der_file, result));
15209 memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN,
15218static char *sl_pem2der(
const char *pem_file) {
15219 return strdup(pem_file);
15225 const struct mg_ssl_if_ctx *ctx = (
struct mg_ssl_if_ctx *) nc->ssl_if_data;
15226 DBG((
"%p ssl ctx: %p", nc, ctx));
15228 if (ctx == NULL)
return 0;
15229 DBG((
"%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert :
"-"),
15230 (ctx->ssl_key ? ctx->ssl_cert :
"-"),
15231 (ctx->ssl_ca_cert ? ctx->ssl_ca_cert :
"-"),
15232 (ctx->ssl_server_name ? ctx->ssl_server_name :
"-")));
15233 if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
15234 char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL;
15235 if (ssl_cert != NULL) {
15236 err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
15237 SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
15240 LOG(
LL_DEBUG, (
"CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
15241 ssl_key = sl_pem2der(ctx->ssl_key);
15242 if (ssl_key != NULL) {
15243 err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
15244 SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
15247 LOG(
LL_DEBUG, (
"PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
15254 if (err != 0)
return err;
15256 if (ctx->ssl_ca_cert != NULL) {
15257 if (ctx->ssl_ca_cert[0] !=
'\0') {
15258 char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
15259 if (ssl_ca_cert != NULL) {
15261 sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME,
15262 ssl_ca_cert, strlen(ssl_ca_cert));
15263 LOG(
LL_DEBUG, (
"CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
15268 if (err != 0)
return err;
15271 if (ctx->ssl_server_name != NULL) {
15272 err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
15273 SL_SO_SECURE_DOMAIN_NAME_VERIFICATION,
15274 ctx->ssl_server_name, strlen(ctx->ssl_server_name));
15275 DBG((
"DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
15280 if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT)
return err;
15286#ifdef MG_MODULE_LINES
15287#line 1 "common/platforms/lwip/mg_lwip_net_if.h"
15306#ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
15307#define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
15309#ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
15310#define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
15313#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
15323 struct tcp_pcb *tcp;
15324 struct udp_pcb *udp;
15354#ifdef MG_MODULE_LINES
15355#line 1 "common/platforms/lwip/mg_lwip_net_if.c"
15374#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
15378#include <lwip/init.h>
15379#include <lwip/pbuf.h>
15380#include <lwip/tcp.h>
15381#include <lwip/tcpip.h>
15382#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
15383#include <lwip/priv/tcp_priv.h>
15384#include <lwip/priv/tcpip_priv.h>
15386#include <lwip/tcp_impl.h>
15388#include <lwip/udp.h>
15398#define ip_2_ip4(addr) ipX_2_ip(addr)
15400#define ip_2_ip4(addr) (addr)
15409#define TCP_NEW tcp_new_ip6
15410#define TCP_BIND tcp_bind_ip6
15411#define UDP_BIND udp_bind_ip6
15412#define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
15413#define SET_ADDR(dst, src) \
15414 memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
15415 sizeof((dst)->sin6.sin6_addr.s6_addr))
15417#define TCP_NEW tcp_new
15418#define TCP_BIND tcp_bind
15419#define UDP_BIND udp_bind
15420#define IPADDR_NTOA ipaddr_ntoa
15421#define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr
15425#if LWIP_TCPIP_CORE_LOCKING
15429 tcpip_api_call((tcpip_api_call_fn) fn, (
struct tcpip_api_call_data *) arg);
15452#define mg_lwip_netif_run_on_tcpip(fn, arg) (fn)(arg)
15467#define mgos_unlock()
15472#if LWIP_TCP_KEEPALIVE
15473void mg_lwip_set_keepalive_params(
struct mg_connection *nc,
int idle,
15474 int interval,
int count) {
15479 struct tcp_pcb *tpcb = cs->pcb.tcp;
15480 if (idle > 0 && interval > 0 &&
count > 0) {
15481 tpcb->keep_idle = idle * 1000;
15482 tpcb->keep_intvl = interval * 1000;
15483 tpcb->keep_cnt =
count;
15484 tpcb->so_options |= SOF_KEEPALIVE;
15486 tpcb->so_options &= ~SOF_KEEPALIVE;
15489#elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
15490#warning LWIP TCP keepalive is disabled. Please consider enabling it.
15495 DBG((
"%p connect to %s:%u = %d", nc,
IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
15496 tpcb->remote_port,
err));
15503#if LWIP_TCP_KEEPALIVE
15504 if (
err == 0) mg_lwip_set_keepalive_params(
nc, 60, 10, 6);
15512 DBG((
"%p conn error %d", nc,
err));
15525 struct pbuf *p, err_t
err) {
15529 DBG((
"%p %p %p %p %u %d",
nc, cs, tpcb, p, (p != NULL ? p->tot_len : 0),
15546 }
else if (
nc == NULL) {
15554 if (p->next != NULL) {
15555 struct pbuf *
q = p->next;
15556 for (;
q != NULL;
q =
q->next) pbuf_ref(
q);
15561 }
else if (pbuf_clen(cs->
rx_chain) >= 4) {
15565 struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
15581 DBG((
"%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked));
15582 if (nc == NULL)
return ERR_OK;
15584 nc->
send_mbuf.
len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) {
15606 struct tcp_pcb *tpcb =
TCP_NEW();
15608 ip_addr_t *ip = (ip_addr_t *) &sa->
sin.sin_addr.s_addr;
15609 u16_t port = ntohs(sa->
sin.sin_port);
15615 DBG((
"%p tcp_bind = %d", nc, cs->
err));
15616 if (cs->
err != ERR_OK) {
15621 DBG((
"%p tcp_connect %p = %d", nc, tpcb, cs->
err));
15622 if (cs->
err != ERR_OK) {
15638#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
15640 const ip_addr_t *
addr, u16_t port)
15643 ip_addr_t *
addr, u16_t port)
15656#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
15659 sa->sin.sin_addr.s_addr =
addr->addr;
15661 sa->sin.sin_port = htons(port);
15663 p = pbuf_coalesce(p, PBUF_RAW);
15664 pbuf_chain(sap, p);
15696 struct pbuf *dp = ap->next;
15698 res =
MIN(dp->len, len);
15699 pbuf_copy_partial(dp, buf, res, 0);
15701 pbuf_copy_partial(ap, sa,
MIN(*sa_len, ap->len), 0);
15711 struct udp_pcb *upcb = udp_new();
15713 DBG((
"%p udp_bind %p = %d", nc, upcb, cs->
err));
15714 if (cs->
err == ERR_OK) {
15728 tcp_close((
struct tcp_pcb *) arg);
15733 if (cs->
pcb.
tcp == NULL)
return;
15735 struct tcp_pcb *tpcb = cs->
pcb.
tcp;
15737 sa.
sin.sin_port = htons(tpcb->remote_port);
15744 struct tcp_pcb_listen *lpcb;
15746 (
"%p conn %p from %s:%u", lc, newtpcb,
15747 IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
15749 tcp_abort(newtpcb);
15753 lpcb = (
struct tcp_pcb_listen *) lcs->
pcb.
tcp;
15754#if TCP_LISTEN_BACKLOG
15755 tcp_accepted(lpcb);
15759 tcp_abort(newtpcb);
15767 tcp_arg(newtpcb,
nc);
15771#if LWIP_TCP_KEEPALIVE
15772 mg_lwip_set_keepalive_params(
nc, 60, 10, 6);
15791 struct tcp_pcb *tpcb =
TCP_NEW();
15792 ip_addr_t *ip = (ip_addr_t *) &sa->
sin.sin_addr.s_addr;
15793 u16_t port = ntohs(sa->
sin.sin_port);
15796 if (cs->
err != ERR_OK) {
15802 tpcb = tcp_listen(tpcb);
15819 struct udp_pcb *upcb = udp_new();
15820 ip_addr_t *ip = (ip_addr_t *) &sa->
sin.sin_addr.s_addr;
15821 u16_t port = ntohs(sa->
sin.sin_port);
15824 if (cs->
err != ERR_OK) {
15848 tcp_output((
struct tcp_pcb *) arg);
15855 struct tcp_pcb *tpcb = cs->
pcb.
tcp;
15856 size_t len =
MIN(tpcb->mss,
MIN(ctx->
len, tpcb->snd_buf));
15857 size_t unsent, unacked;
15859 DBG((
"%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen,
15860 tpcb->unsent, tpcb->unacked));
15865 unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
15866 unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
15873#if CS_PLATFORM == CS_P_ESP8266
15878 len =
MIN(len, (TCP_MSS - unsent));
15880 cs->
err = tcp_write(tpcb, ctx->
data, len, TCP_WRITE_FLAG_COPY);
15881 unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
15882 unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
15883 DBG((
"%p tcp_write %u = %d, %u %u", tpcb, len, cs->
err, unsent, unacked));
15884 if (cs->
err != ERR_OK) {
15889 ctx->
ret = (cs->
err == ERR_MEM ? 0 : -1);
15901 struct tcp_pcb *tpcb = cs->
pcb.
tcp;
15902 if (tpcb == NULL)
return -1;
15903 if (tpcb->snd_buf <= 0)
return 0;
15909 struct udp_pcb *
upcb;
15925 struct udp_pcb *upcb = cs->
pcb.
udp;
15926 struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
15927#if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6
15928 ip_addr_t ip = {.u_addr.ip4.addr = nc->
sa.
sin.sin_addr.s_addr, .type = 0};
15930 ip_addr_t ip = {.addr = nc->
sa.
sin.sin_addr.s_addr};
15932 u16_t port = ntohs(nc->
sa.
sin.sin_port);
15933 if (p == NULL)
return 0;
15934 memcpy(p->payload,
data, len);
15939 return (cs->
err == ERR_OK ? (
int) len : -2);
15949 can_send = (cs->
pcb.
udp != NULL);
15951 can_send = (cs->
pcb.
tcp != NULL && cs->
pcb.
tcp->snd_buf > 0);
15953#if CS_PLATFORM == CS_P_ESP8266
15954 if (cs->
pcb.
tcp->unacked != NULL) can_send = 0;
15962 struct tcp_pcb *
tpcb;
15968 if (ctx->
tpcb != NULL) tcp_recved(ctx->
tpcb, ctx->
len);
15978 while (cs->
rx_chain != NULL && len > 0) {
15980 size_t seg_len = (seg->len - cs->
rx_offset);
15981 size_t copy_len =
MIN(len, seg_len);
15983 pbuf_copy_partial(seg, bufp, copy_len, cs->
rx_offset);
16005 if (cs == NULL)
return 0;
16012 udp_remove((
struct udp_pcb *) arg);
16019 struct tcp_pcb *tpcb = cs->
pcb.
tcp;
16020 if (tpcb != NULL) {
16021 tcp_arg(tpcb, NULL);
16022 DBG((
"%p tcp_close %p", nc, tpcb));
16023 tcp_arg(tpcb, NULL);
16031 memset(cs, 0,
sizeof(*cs));
16033 }
else if (nc->
listener == NULL) {
16035 struct udp_pcb *upcb = cs->
pcb.
udp;
16036 if (upcb != NULL) {
16037 DBG((
"%p udp_remove %p", nc, upcb));
16040 memset(cs, 0,
sizeof(*cs));
16048 memset(sa, 0,
sizeof(*sa));
16052 struct udp_pcb *upcb = cs->
pcb.
udp;
16054 memcpy(sa, &nc->
sa,
sizeof(*sa));
16055 }
else if (upcb != NULL) {
16056 sa->
sin.sin_port = htons(upcb->local_port);
16060 struct tcp_pcb *tpcb = cs->
pcb.
tcp;
16062 memcpy(sa, &nc->
sa,
sizeof(*sa));
16063 }
else if (tpcb != NULL) {
16064 sa->
sin.sin_port = htons(tpcb->local_port);
16075#define MG_LWIP_IFACE_VTABLE \
16079 mg_lwip_if_add_conn, \
16080 mg_lwip_if_remove_conn, \
16082 mg_lwip_if_listen_tcp, \
16083 mg_lwip_if_listen_udp, \
16084 mg_lwip_if_connect_tcp, \
16085 mg_lwip_if_connect_udp, \
16086 mg_lwip_if_tcp_send, \
16087 mg_lwip_if_udp_send, \
16088 mg_lwip_if_tcp_recv, \
16089 mg_lwip_if_udp_recv, \
16090 mg_lwip_if_create_conn, \
16091 mg_lwip_if_destroy_conn, \
16092 mg_lwip_if_sock_set, \
16093 mg_lwip_if_get_conn_addr, \
16098#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
16103#ifdef MG_MODULE_LINES
16104#line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c"
16123#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
16125#ifndef MG_SIG_QUEUE_LEN
16126#define MG_SIG_QUEUE_LEN 32
16197 LWIP_VERSION_MINOR, LWIP_VERSION_REVISION));
16199#if !NO_SYS && !LWIP_TCPIP_CORE_LOCKING
16207 iface->
data = NULL;
16230 double min_timer = 0;
16231 int num_timers = 0;
16233 DBG((
"begin poll @%u", (
unsigned int) (now * 1000)));
16243 cs->
pcb.
tcp->unsent != NULL) {
16270 DBG((
"end poll @%u, %d conns, %d timers (min %u), next in %d ms",
16271 (
unsigned int) (now * 1000),
n, num_timers,
16272 (
unsigned int) (min_timer * 1000), timeout_ms));
16279#ifdef MG_MODULE_LINES
16280#line 1 "common/platforms/wince/wince_libc.c"
16301const char *strerror(
int err) {
16306 static char buf[10];
16307 snprintf(buf,
sizeof(buf),
"%d",
err);
16311int open(
const char *filename,
int oflag,
int pmode) {
16321int _wstati64(
const wchar_t *path, cs_stat_t *st) {
16322 DWORD fa = GetFileAttributesW(path);
16323 if (fa == INVALID_FILE_ATTRIBUTES) {
16326 memset(st, 0,
sizeof(*st));
16327 if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
16330 st->st_mode |= _S_IFREG;
16331 h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
16332 FILE_ATTRIBUTE_NORMAL, NULL);
16333 if (h == INVALID_HANDLE_VALUE) {
16336 st->st_size = GetFileSize(h, NULL);
16337 GetFileTime(h, NULL, NULL, &ftime);
16338 st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
16339 ((uint64_t) ftime.dwHighDateTime << 32)) /
16344 st->st_mode |= _S_IFDIR;
16352 SYSTEMTIME systime;
16354 uint64_t filetime = (*t + 11644473600) * 10000000;
16355 ft.dwLowDateTime = filetime & 0xFFFFFFFF;
16356 ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
16357 FileTimeToSystemTime(&ft, &systime);
16359 GetSystemTime(&systime);
16362 snprintf(buf, buf_len,
"%d.%d.%d %d:%d:%d GMT", (
int) systime.wYear,
16363 (
int) systime.wMonth, (
int) systime.wDay, (
int) systime.wHour,
16364 (
int) systime.wMinute, (
int) systime.wSecond);
16368#ifdef MG_MODULE_LINES
16369#line 1 "common/platforms/pic32/pic32_net_if.h"
16388#ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
16389#define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
16397#ifndef MG_ENABLE_NET_IF_PIC32
16398#define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
16408#ifdef MG_MODULE_LINES
16409#line 1 "common/platforms/pic32/pic32_net_if.c"
16428#if MG_ENABLE_NET_IF_PIC32
16462 TCPIP_TCP_Close((TCP_SOCKET) nc->
sock);
16463 }
else if (nc->
listener == NULL) {
16465 TCPIP_UDP_Close((UDP_SOCKET) nc->
sock);
16472 nc->
sock = TCPIP_UDP_ServerOpen(
16473 sa->
sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16474 : IP_ADDRESS_TYPE_IPV6,
16475 ntohs(sa->
sin.sin_port),
16476 sa->
sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->
sin);
16494 nc->
sock = TCPIP_TCP_ServerOpen(
16495 sa->
sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16496 : IP_ADDRESS_TYPE_IPV6,
16497 ntohs(sa->
sin.sin_port),
16498 sa->
sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->
sin);
16499 memcpy(&nc->
sa, sa,
sizeof(*sa));
16508 TCP_SOCKET_INFO si;
16518 nc->
flags &= ~MG_F_LISTENING;
16520 if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->
sock, &si)) {
16524 if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
16525 sa.sin.sin_family = AF_INET;
16526 sa.sin.sin_port = htons(si.remotePort);
16527 sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
16530 memset(&
sa, 0,
sizeof(
sa));
16539 static char addr[17];
16540 snprintf(
addr,
sizeof(
addr),
"%d.%d.%d.%d", (
int) in.S_un.S_un_b.s_b1,
16541 (
int) in.S_un.S_un_b.s_b2, (
int) in.S_un.S_un_b.s_b3,
16542 (
int) in.S_un.S_un_b.s_b4);
16547 uint16_t bytes_written = 0;
16549 if (!TCPIP_UDP_RemoteBind(
16550 (UDP_SOCKET) nc->
sock,
16551 nc->
sa.
sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16552 : IP_ADDRESS_TYPE_IPV6,
16553 ntohs(nc->
sa.
sin.sin_port), (IP_MULTI_ADDRESS *) &nc->
sa.
sin)) {
16557 bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->
sock, 0);
16559 if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->
sock,
16567 bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->
sock);
16568 if (bytes_written != 0) {
16572 if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->
sock,
16574 bytes_written) != bytes_written) {
16585 uint16_t bytes_read = 0;
16586 uint8_t *buf = NULL;
16588 bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->
sock);
16589 if (bytes_read != 0 &&
16591 nc->
recv_mbuf.
len + bytes_read < nc->recv_mbuf_limit)) {
16592 buf = (uint8_t *)
MG_MALLOC(bytes_read);
16593 if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->
sock, buf, bytes_read) !=
16601 bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->
sock);
16602 if (bytes_read != 0) {
16607 buf = (uint8_t *)
MG_MALLOC(bytes_read);
16608 if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->
sock, buf, bytes_read) !=
16617 if (bytes_read != 0) {
16633 TCPIP_TCP_IsConnected((TCP_SOCKET) nc->
sock)) {
16637 if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->
sock)) {
16675 nc->
sock = TCPIP_TCP_ClientOpen(
16676 sa->
sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
16677 : IP_ADDRESS_TYPE_IPV6,
16678 ntohs(
sa->
sin.sin_port), (IP_MULTI_ADDRESS *) &
sa->
sin);
16683 nc->
sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
16688#define MG_PIC32_IFACE_VTABLE \
16690 mg_pic32_if_init, \
16691 mg_pic32_if_free, \
16692 mg_pic32_if_add_conn, \
16693 mg_pic32_if_remove_conn, \
16694 mg_pic32_if_poll, \
16695 mg_pic32_if_listen_tcp, \
16696 mg_pic32_if_listen_udp, \
16697 mg_pic32_if_connect_tcp, \
16698 mg_pic32_if_connect_udp, \
16699 mg_pic32_if_tcp_send, \
16700 mg_pic32_if_udp_send, \
16701 mg_pic32_if_recved, \
16702 mg_pic32_if_create_conn, \
16703 mg_pic32_if_destroy_conn, \
16704 mg_pic32_if_sock_set, \
16705 mg_pic32_if_get_conn_addr, \
16710#if MG_NET_IF == MG_NET_IF_PIC32
16715#ifdef MG_MODULE_LINES
16716#line 1 "common/platforms/windows/windows_direct.c"
16737int rmdir(
const char *dirname) {
16738 return _rmdir(dirname);
16741unsigned int sleep(
unsigned int seconds) {
16742 Sleep(seconds * 1000);
int mg_start_thread(mg_thread_func_t f, void *p)
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded)
int(* mg_event_handler_t)(struct mg_event *event)
int mg_mgr_poll(struct mg_mgr *m, int timeout_ms)
void mg_mqtt_ping(struct mg_connection *nc)
void mg_set_protocol_mqtt(struct mg_connection *nc)
void mg_mgr_free(struct mg_mgr *m)
const char * hexdump_file
int mg_resolve_from_hosts_file(const char *host, union socket_address *usa)
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len)
void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK
#define WEBSOCKET_DONT_FIN
#define MG_MK_STR(str_literal)
void mg_send_dns_query(struct mg_connection *nc, const char *name, int query_type)
#define WEBSOCKET_OP_PING
char * cs_md5(char buf[33],...)
void mg_mqtt_disconnect(struct mg_connection *nc)
#define MG_MQTT_HAS_USER_NAME
#define MG_MQTT_CMD_PUBREC
void mg_mqtt_publish(struct mg_connection *nc, const char *topic, uint16_t message_id, int flags, const void *data, size_t len)
void mg_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa)
#define MG_MQTT_CMD_UNSUBACK
struct mg_str header_names[MG_MAX_HTTP_HEADERS]
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK
#define MG_MAX_HTTP_HEADERS
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK
#define MG_MAX_HTTP_SEND_MBUF
#define MG_MAX_DNS_ANSWERS
#define MG_EV_WEBSOCKET_FRAME
int mg_stat(const char *path, cs_stat_t *st)
struct mg_connection * mg_connect_http(struct mg_mgr *mgr, mg_event_handler_t event_handler, const char *url, const char *extra_headers, const char *post_data)
const char * global_auth_file
#define MG_EV_WEBSOCKET_HANDSHAKE_DONE
int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query, mg_resolve_callback_t cb, void *data, struct mg_resolve_async_opts opts)
mg_event_handler_t handler
struct mg_connection * active_connections
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code)
#define MG_MQTT_CMD_PUBACK
int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr, const char *name, size_t nlen, const void *rdata, size_t rlen)
void mg_mqtt_pong(struct mg_connection *nc)
struct mg_connection ** dns_conn
int mg_is_big_endian(void)
#define MG_F_CLOSE_IMMEDIATELY
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK
size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name, size_t var_name_len, char *file_name, size_t file_name_len, const char **chunk, size_t *chunk_len)
#define MG_SOCK_STRINGIFY_PORT
void mbuf_remove(struct mbuf *mb, size_t n) WEAK
void mg_mgr_init(struct mg_mgr *m, void *user_data)
int mg_dns_insert_header(struct mbuf *io, size_t pos, struct mg_dns_message *msg)
const char * extra_headers
void mg_send_head(struct mg_connection *n, int status_code, int64_t content_length, const char *extra_headers)
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id)
void(* proto_data_destructor)(void *proto_data)
struct mg_connection * mg_next(struct mg_mgr *s, struct mg_connection *conn)
int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query, mg_resolve_callback_t cb, void *data)
void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa, size_t sa_len)
int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out)
#define WEBSOCKET_OP_CLOSE
const char * c_strnstr(const char *s, const char *find, size_t slen) WEAK
int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap)
const char * mg_set_ssl(struct mg_connection *nc, const char *cert, const char *ca_cert)
void mg_broadcast(struct mg_mgr *, mg_event_handler_t func, void *, size_t)
#define MG_DNS_AAAA_RECORD
void mg_send_response_line(struct mg_connection *c, int status_code, const char *extra_headers)
#define MG_MQTT_CMD_CONNACK
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id)
#define MG_VPRINTF_BUFFER_SIZE
struct mg_str header_values[MG_MAX_HTTP_HEADERS]
void mbuf_free(struct mbuf *mbuf) WEAK
const char * url_rewrites
#define MG_EV_WEBSOCKET_CONTROL_FRAME
void mg_serve_http(struct mg_connection *nc, struct http_message *hm, struct mg_serve_http_opts opts)
const char ** error_string
#define MG_MAX_CGI_ENVIR_VARS
#define MG_SOCK_STRINGIFY_REMOTE
int mg_open(const char *path, int flag, int mode)
double mg_set_timer(struct mg_connection *c, double timestamp)
int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len, int flags)
#define MG_MQTT_GET_QOS(flags)
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req)
size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK
#define MG_SEND_FUNC(s, b, l, f)
void mbuf_resize(struct mbuf *a, size_t new_size) WEAK
void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len)
void mg_printf_html_escape(struct mg_connection *nc, const char *fmt,...)
cs_base64_putc_t b64_putc
void mg_if_sent_cb(struct mg_connection *nc, int num_sent)
#define MG_DNS_CNAME_RECORD
struct mg_connection * mg_if_accept_new_conn(struct mg_connection *lc)
#define MG_CGI_ENVIRONMENT_SIZE
const char * cgi_file_pattern
int mg_casecmp(const char *s1, const char *s2) WEAK
void mg_send(struct mg_connection *nc, const void *buf, int len)
int mg_socketpair(sock_t[2], int sock_type)
#define WEBSOCKET_OP_PONG
#define MG_MQTT_CMD_PUBREL
struct mg_connection * next
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len)
#define MG_MQTT_CMD_PINGREQ
const char * cgi_interpreter
#define MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE
#define MG_ENV_EXPORT_TO_CGI
void mg_hexdump_connection(struct mg_connection *nc, const char *path, const void *buf, int num_bytes, int ev)
enum mg_dns_resource_record_kind kind
#define MG_F_WEBSOCKET_NO_DEFRAG
#define ARRAY_SIZE(array)
void mg_if_connect_cb(struct mg_connection *nc, int err)
int mg_http_create_digest_auth_header(char *buf, size_t buf_len, const char *method, const char *uri, const char *auth_domain, const char *user, const char *passwd)
#define MG_EV_MQTT_CONNECT
void mg_sock_set(struct mg_connection *nc, sock_t sock)
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path, const char *host, const char *protocol, const char *extra_headers)
void cs_base64_finish(struct cs_base64_ctx *ctx)
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path, mg_event_handler_t handler)
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags)
#define MG_MQTT_CMD_PUBCOMP
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id)
struct mg_str query_string
void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags, const char *fmt,...)
#define MG_MQTT_EVENT_BASE
#define MG_MQTT_CMD_PUBLISH
#define MBUF_SIZE_MULTIPLIER
struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS]
void cs_log_set_level(enum cs_log_level level)
#define MG_SOCK_STRINGIFY_IP
const char * enable_directory_listing
size_t c_strnlen(const char *s, size_t maxlen) WEAK
size_t mg_match_prefix(const char *, int, const char *) WEAK
#define MG_MQTT_CMD_PINGRESP
#define MG_MQTT_CMD_CONNECT
void cs_hmac_sha1(const unsigned char *key, size_t keylen, const unsigned char *data, size_t datalen, unsigned char out[20])
const char * dav_auth_file
void mg_set_protocol_http_websocket(struct mg_connection *nc)
void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags, const struct mg_str *strings, int num_strings)
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len)
int mg_hexdump(const void *buf, int len, char *dst, int dst_len)
int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK
#define MG_WEBSOCKET_PING_INTERVAL_SECONDS
int mg_base64_decode(const unsigned char *s, int len, char *dst)
struct mg_connection * mg_connect_ws(struct mg_mgr *mgr, mg_event_handler_t event_handler, const char *url, const char *protocol, const char *extra_headers)
struct mg_connection * listener
struct mg_connection * prev
#define MG_MQTT_HAS_PASSWORD
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id)
void mg_set_close_on_exec(sock_t sock)
double cs_time(void) WEAK
void(* cs_base64_putc_t)(char, void *)
struct mg_connection * mg_connect_ws_opt(struct mg_mgr *mgr, mg_event_handler_t ev_handler, struct mg_connect_opts opts, const char *url, const char *protocol, const char *extra_headers)
#define MG_F_DELETE_CHUNK
int mg_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len)
void mg_set_protocol_dns(struct mg_connection *nc)
const char * mg_skip(const char *s, const char *end, const char *delims, struct mg_str *v)
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len, uint16_t message_id)
#define MG_MAX_HTTP_REQUEST_SIZE
#define MG_MQTT_CMD_UNSUBSCRIBE
int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg)
const char * hidden_file_pattern
int c_snprintf(char *buf, size_t buf_size, const char *fmt,...) WEAK
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id)
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc, void *user_data)
struct mg_dns_resource_record * mg_dns_next_record(struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev)
const char * document_root
void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK
void cs_log_printf(const char *fmt,...)
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id, struct mg_send_mqtt_handshake_opts)
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK
#define MG_F_SSL_HANDSHAKE_DONE
int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len, int flags)
const char * per_directory_auth_file
void mg_base64_encode(const unsigned char *src, int src_len, char *dst)
void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags, const void *data, size_t data_len)
#define MG_EV_MQTT_PUBLISH
void(* mg_resolve_callback_t)(struct mg_dns_message *dns_message, void *user_data, enum mg_resolve_err)
#define MG_F_IS_WEBSOCKET
#define MG_RECV_FUNC(s, b, l, f)
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context)
const char ** error_string
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf, size_t buf_size)
struct mg_str mg_mk_str(const char *s) WEAK
const char ** error_string
void cs_base64_encode(const unsigned char *src, int src_len, char *dst)
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst, size_t dst_len)
void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri, const char *extra_headers)
void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt,...)
#define MG_EV_MQTT_SUBSCRIBE
const char * mg_next_comma_list_entry(const char *, struct mg_str *, struct mg_str *) WEAK
size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name, char *dst, int dst_len)
struct mg_connection * mg_connect_http_opt(struct mg_mgr *mgr, mg_event_handler_t ev_handler, struct mg_connect_opts opts, const char *url, const char *extra_headers, const char *post_data)
void mbuf_trim(struct mbuf *mbuf) WEAK
#define MG_MQTT_CMD_DISCONNECT
FILE * mg_fopen(const char *path, const char *mode)
struct mg_str * mg_get_http_header(struct http_message *hm, const char *name)
void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data, uint32_t len)
#define MG_MQTT_CMD_SUBSCRIBE
#define MG_MQTT_CMD_SUBACK
int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK
int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme, struct mg_str *user_info, struct mg_str *host, unsigned int *port, struct mg_str *path, struct mg_str *query, struct mg_str *fragment)
int mg_check_ip_acl(const char *acl, uint32_t remote_ip)
struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS]
mg_event_handler_t proto_handler
const char * dav_document_root
MG_INTERNAL void mg_close_conn(struct mg_connection *conn)
struct mg_str resp_status_msg
void cs_sha1_init(cs_sha1_ctx *context)
int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK
int mg_dns_parse_record_data(struct mg_dns_message *msg, struct mg_dns_resource_record *rr, void *data, size_t data_len)
#define MG_EV_MQTT_CONNACK_ACCEPTED
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics, size_t topics_len, uint16_t message_id)
#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST
int mg_printf(struct mg_connection *conn, const char *fmt,...)
void mg_mqtt_subscribe(struct mg_connection *nc, const struct mg_mqtt_topic_expression *topics, size_t topics_len, uint16_t message_id)
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id)
void cs_log_set_file(FILE *file)
#define WEBSOCKET_OP_CONTINUE
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg, struct mg_str *topic, uint8_t *qos, int pos)
#define MG_F_SEND_AND_CLOSE
#define MG_EV_HTTP_REQUEST
@ MG_RESOLVE_EXCEEDED_RETRY_COUNT
static std::string q(const char *s)
#define message(type, str)
#define write(n, a, f, d)
static std::string remove(const std::string s, char c)
static void do_ssi_exec(struct mg_connection *conn, char *tag)
static const char * month_names[]
static struct mg_str mg_strdup_common(const struct mg_str s, int nul_terminate)
void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver)
#define MBUF_SIZE_MAX_HEADROOM
#define MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE
#define DO_NOT_WARN_UNUSED
void mg_http_send_error(struct mg_connection *nc, int code, const char *reason)
int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len, char *pass, size_t pass_len)
int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len, char *pass, size_t pass_len)
#define MG_AUTH_FLAG_IS_DIRECTORY
void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[], const size_t *msg_lens, uint8_t *digest)
void mg_send_websocket_handshake3v(struct mg_connection *nc, const struct mg_str path, const struct mg_str host, const struct mg_str protocol, const struct mg_str extra_headers, const struct mg_str user, const struct mg_str pass)
#define MG_ENABLE_HTTP_WEBDAV
#define MG_MK_STR_N(str_literal, len)
#define LIST_REMOVE(elm, field)
#define MG_EV_SSI_CALL_CTX
void mg_http_send_digest_auth_request(struct mg_connection *c, const char *domain)
#define PRINTF_LIKE(f, a)
#define MG_AUTH_FLAG_ALLOW_MISSING_FILE
#define MG_F_RECV_AND_CLOSE
void mg_http_send_redirect(struct mg_connection *nc, int status_code, const struct mg_str location, const struct mg_str extra_headers)
int mg_check_digest_auth(struct mg_str method, struct mg_str uri, struct mg_str username, struct mg_str cnonce, struct mg_str response, struct mg_str qop, struct mg_str nc, struct mg_str nonce, struct mg_str auth_domain, FILE *fp)
int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic)
int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain, FILE *fp)
int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf, size_t buf_size)
void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[], const size_t *msg_lens, uint8_t *digest)
int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len)
#define MG_ENABLE_HTTP_STREAMING_MULTIPART
int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic)
#define LIST_NEXT(elm, field)
void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path, const char *host, const char *protocol, const char *extra_headers, const char *user, const char *pass)
#define LIST_INSERT_HEAD(head, elm, field)
int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg)
#define MG_F_ENABLE_BROADCAST
int mg_http_is_authorized(struct http_message *hm, struct mg_str path, const char *domain, const char *passwords_file, int flags)
void mg_register_http_endpoint_opt(struct mg_connection *nc, const char *uri_path, mg_event_handler_t handler, struct mg_http_endpoint_opts opts)
#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src)
int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa)
void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf, size_t len)
void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock)
#define MD5STEP(f, w, x, y, z, data, s)
int _kill(int pid, int sig)
void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx)
void mg_lwip_if_connect_udp(struct mg_connection *nc)
struct mg_connection * mg_bind(struct mg_mgr *srv, const char *address, MG_CB(mg_event_handler_t event_handler, void *user_data))
int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa)
static int mg_accept_conn(struct mg_connection *lc)
static int mg_sl_if_listen_tcp(struct mg_connection *nc, union socket_address *sa)
void mg_socket_if_connect_udp(struct mg_connection *nc)
void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock)
static sock_t mg_open_listening_socket(union socket_address *sa, int type, int proto)
struct mg_str mg_strdup_nul(const struct mg_str s) WEAK
void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64])
int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK
MG_INTERNAL void mg_remove_conn(struct mg_connection *c)
void sl_restart_cb(struct mg_mgr *mgr)
void cs_md5_init(cs_md5_ctx *ctx)
struct mg_connection * mg_add_sock_opt(struct mg_mgr *s, sock_t sock, MG_CB(mg_event_handler_t callback, void *user_data), struct mg_add_sock_opts opts)
static int mg_sl_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, union socket_address *sa, size_t *sa_len)
const struct mg_iface_vtable * mg_ifaces[]
double cs_timegm(const struct tm *tm)
static void mg_lwip_if_connect_tcp_tcpip(void *arg)
MG_INTERNAL struct mg_connection * mg_create_connection_base(struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts)
static int mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len)
#define MG_LWIP_IFACE_VTABLE
#define R1(v, w, x, y, z, i)
static int mg_do_recv(struct mg_connection *nc)
MG_INTERNAL struct mg_connection * mg_create_connection(struct mg_mgr *mgr, mg_event_handler_t callback, struct mg_add_sock_opts opts)
void mg_lwip_if_destroy_conn(struct mg_connection *nc)
static int mg_socket_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, union socket_address *sa, size_t *sa_len)
void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len)
time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms)
static void mg_null_if_add_conn(struct mg_connection *c)
int mg_null_if_tcp_recv(struct mg_connection *c, void *buf, size_t len)
void mg_lwip_if_add_conn(struct mg_connection *nc)
static void mg_lwip_tcp_error_cb(void *arg, err_t err)
void mg_mbuf_append_base64_putc(char ch, void *user_data)
#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK
void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass, struct mbuf *buf)
static unsigned char from_b64(unsigned char ch)
static void tcp_output_tcpip(void *arg)
bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init)
double mg_mgr_min_timer(const struct mg_mgr *mgr)
static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags, int field_width)
static void mg_lwip_if_connect_udp_tcpip(void *arg)
static void mg_null_if_get_conn_addr(struct mg_connection *c, int remote, union socket_address *sa)
int mg_str_starts_with(struct mg_str s, struct mg_str prefix) WEAK
#define MG_UDP_RECV_BUFFER_SIZE
static int parse_net(const char *spec, uint32_t *net, uint32_t *mask)
struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val, struct mg_str *eq_val) WEAK
int mg_lwip_if_create_conn(struct mg_connection *nc)
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms)
void mg_pic32_if_recved(struct mg_connection *nc, size_t len)
static void mg_null_if_free(struct mg_iface *iface)
void mg_pic32_if_add_conn(struct mg_connection *nc)
void mg_lwip_handle_accept(struct mg_connection *nc)
struct mg_str mg_url_encode(const struct mg_str src)
static int mg_sl_if_create_conn(struct mg_connection *nc)
int mg_asprintf(char **buf, size_t size, const char *fmt,...) WEAK
MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max)
static void mg_sl_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa)
void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa)
void _not_implemented(const char *what)
size_t mbuf_append_and_free(struct mbuf *a, void *buf, size_t len) WEAK
static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb, u16_t num_sent)
void mg_lwip_if_free(struct mg_iface *iface)
struct mg_str mg_url_encode_opt(const struct mg_str src, const struct mg_str safe, unsigned int flags)
int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK
#define MG_CTL_MSG_MESSAGE_SIZE
int mg_if_poll(struct mg_connection *nc, double now)
static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err)
static int mg_lwip_if_can_send(struct mg_connection *nc, struct mg_lwip_conn_state *cs)
void mg_socket_if_add_conn(struct mg_connection *nc)
void mg_sl_if_add_conn(struct mg_connection *nc)
void mg_sl_if_remove_conn(struct mg_connection *nc)
static void mg_handle_recv(struct mg_connection *nc)
static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err)
static int mg_lwip_if_udp_send(struct mg_connection *nc, const void *data, size_t len)
void mg_lwip_if_remove_conn(struct mg_connection *nc)
void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa)
static time_t mg_null_if_poll(struct mg_iface *iface, int timeout_ms)
void mg_mgr_init_opt(struct mg_mgr *m, void *user_data, struct mg_mgr_init_opts opts)
static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16])
static void udp_sendto_tcpip(void *arg)
void mg_socket_if_init(struct mg_iface *iface)
struct mg_connection * mg_connect(struct mg_mgr *mgr, const char *address, MG_CB(mg_event_handler_t callback, void *user_data))
static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx)
#define MG_PIC32_IFACE_VTABLE
#define _MG_ALLOWED_CONNECT_FLAGS_MASK
static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len)
enum cs_log_level cs_log_level WEAK
void mg_pic32_if_init(struct mg_iface *iface)
static void mg_null_if_init(struct mg_iface *iface)
static void mg_null_if_destroy_conn(struct mg_connection *c)
struct mg_str mg_strdup(const struct mg_str s) WEAK
static int mg_null_if_create_conn(struct mg_connection *c)
void mg_set_non_blocking_mode(sock_t sock)
void mbuf_clear(struct mbuf *mb) WEAK
static void mg_null_if_sock_set(struct mg_connection *c, sock_t sock)
void mg_socket_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa)
void mg_socket_if_remove_conn(struct mg_connection *nc)
#define R2(v, w, x, y, z, i)
void mg_pic32_if_connect_udp(struct mg_connection *nc)
void mg_lwip_if_init(struct mg_iface *iface)
const struct mg_iface_vtable mg_default_iface_vtable
void mg_pic32_if_free(struct mg_iface *iface)
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p)
void mg_if_can_recv_cb(struct mg_connection *nc)
#define CS_LOG_PREFIX_LEN
static int mg_lwip_if_udp_recv(struct mg_connection *nc, void *buf, size_t len, union socket_address *sa, size_t *sa_len)
static int mg_socket_if_udp_send(struct mg_connection *nc, const void *buf, size_t len)
static void mg_sock_get_addr(sock_t sock, int remote, 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)
static int mg_sl_if_listen_udp(struct mg_connection *nc, union socket_address *sa)
void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr)
void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len)
void mg_lwip_netif_run_on_tcpip(void(*fn)(void *), void *arg)
#define _MG_F_FD_CAN_READ
static void byteReverse(unsigned char *buf, unsigned longs)
#define MG_SL_IFACE_VTABLE
static void mg_null_if_connect_udp(struct mg_connection *c)
#define R0(v, w, x, y, z, i)
static void mg_sl_if_connect_udp(struct mg_connection *nc)
static int mg_sl_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len)
static void parse_uri_component(const char **p, const char *end, const char *seps, struct mg_str *res)
#define MG_SET_PTRPTR(_ptr, _v)
int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len)
static void tcp_close_tcpip(void *arg)
const struct mg_iface_vtable mg_simplelink_iface_vtable
static int mg_null_if_listen_tcp(struct mg_connection *c, union socket_address *sa)
int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info, const struct mg_str *host, unsigned int port, const struct mg_str *path, const struct mg_str *query, const struct mg_str *fragment, int normalize_path, struct mg_str *uri)
void mg_pic32_if_destroy_conn(struct mg_connection *nc)
void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock)
struct mg_iface * mg_if_create_iface(const struct mg_iface_vtable *vtable, struct mg_mgr *mgr)
static sys_sem_t s_tcpip_call_lock_sem
static int mg_socket_if_listen_udp(struct mg_connection *nc, union socket_address *sa)
static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb, struct pbuf *p, err_t err)
struct mg_connection * mg_bind_opt(struct mg_mgr *mgr, const char *address, MG_CB(mg_event_handler_t callback, void *user_data), struct mg_bind_opts opts)
const char * mg_strstr(const struct mg_str haystack, const struct mg_str needle) WEAK
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc)
static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v)
const struct mg_iface_vtable mg_pic32_iface_vtable
static int mg_socket_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len)
static sys_sem_t s_tcpip_call_sync_sem
static void mg_lwip_tcp_write_tcpip(void *arg)
char * inet_ntoa(struct in_addr n)
void mg_forward(struct mg_connection *from, struct mg_connection *to)
void cs_from_hex(char *to, const char *p, size_t len) WEAK
struct mg_str mg_strstrip(struct mg_str s) WEAK
static int mg_null_if_tcp_send(struct mg_connection *c, const void *buf, size_t len)
static int str_util_lowercase(const char *s)
static int mg_lwip_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len)
static int mg_null_if_udp_send(struct mg_connection *c, const void *buf, size_t len)
static void mg_task(void *arg)
void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa)
void mg_sl_if_destroy_conn(struct mg_connection *nc)
const char * mg_strchr(const struct mg_str s, int c) WEAK
static void mg_lwip_if_listen_tcp_tcpip(void *arg)
void mbuf_move(struct mbuf *from, struct mbuf *to) WEAK
int mg_null_if_udp_recv(struct mg_connection *c, void *buf, size_t len, union socket_address *sa, size_t *sa_len)
int mg_pic32_if_create_conn(struct mg_connection *nc)
void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote, union socket_address *sa)
static int fourbit(int ch)
#define C_SNPRINTF_FLAG_ZERO
struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK
#define BASE64_ENCODE_BODY
void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock)
#define R3(v, w, x, y, z, i)
int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa)
#define MG_SOCKET_IFACE_VTABLE
int mg_socket_if_listen_tcp(struct mg_connection *nc, union socket_address *sa)
void mg_sl_if_init(struct mg_iface *iface)
static void mg_null_if_remove_conn(struct mg_connection *c)
const struct mg_iface_vtable mg_socket_iface_vtable
const char * inet_ntop(int af, const void *src, char *dst, socklen_t size)
int gettimeofday(struct timeval *tp, void *tzp)
void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len)
struct mg_iface * mg_find_iface(struct mg_mgr *mgr, const struct mg_iface_vtable *vtable, struct mg_iface *from)
static void mg_handle_send(struct mg_connection *nc)
void cs_log_set_file_level(const char *file_level)
#define SET_ADDR(dst, src)
static void udp_remove_tcpip(void *arg)
static void mg_lwip_if_listen_udp_tcpip(void *arg)
void mg_sl_if_free(struct mg_iface *iface)
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c)
int inet_pton(int af, const char *src, void *dst)
int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa)
#define _MG_F_FD_CAN_WRITE
static int mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len)
MG_INTERNAL struct mg_connection * mg_do_connect(struct mg_connection *nc, int proto, union socket_address *sa)
void mg_ev_handler_empty(struct mg_connection *c, int ev, void *ev_data MG_UD_ARG(void *user_data))
void mg_socket_if_free(struct mg_iface *iface)
void mg_if_can_send_cb(struct mg_connection *nc)
static int mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, size_t len)
static void mg_null_if_connect_tcp(struct mg_connection *c, const union socket_address *sa)
static void xxx_tcpip(void *arg)
void mg_pic32_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa)
static struct mg_str mg_strdup_common(const struct mg_str s, int nul_terminate)
void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr)
void mg_strfree(struct mg_str *s) WEAK
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p, ip_addr_t *addr, u16_t port)
void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd)
const struct mg_iface_vtable mg_lwip_iface_vtable
void fprint_str(FILE *fp, const char *str)
struct mg_connection * mg_connect_opt(struct mg_mgr *mgr, const char *address, MG_CB(mg_event_handler_t callback, void *user_data), struct mg_connect_opts opts)
int mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len)
void mg_destroy_conn(struct mg_connection *conn, int destroy_if)
void mg_lwip_if_connect_tcp(struct mg_connection *nc, const union socket_address *sa)
time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms)
MG_INTERNAL int mg_get_errno(void)
int mg_socket_if_create_conn(struct mg_connection *nc)
int cs_log_print_prefix(enum cs_log_level level, const char *fname, int line)
static int mg_is_error(void)
static uint32_t blk0(union char64long16 *block, int i)
MG_INTERNAL void mg_call(struct mg_connection *nc, mg_event_handler_t ev_handler, void *user_data, int ev, void *ev_data)
static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len)
#define C_SNPRINTF_APPEND_CHAR(ch)
void mg_socket_if_destroy_conn(struct mg_connection *nc)
void mg_run_in_task(void(*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg)
static int mg_null_if_listen_udp(struct mg_connection *c, union socket_address *sa)
void mg_pic32_if_remove_conn(struct mg_connection *nc)
#define R4(v, w, x, y, z, i)
#define MG_NULL_IFACE_VTABLE
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now)
time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms)
struct mg_connection * mg_add_sock(struct mg_mgr *s, sock_t sock, MG_CB(mg_event_handler_t callback, void *user_data))
MG_INTERNAL void mg_timer(struct mg_connection *c, double now)
void tcp_recved_tcpip(void *arg)
struct mg_str mg_url_encode_opt(const struct mg_str src, const struct mg_str safe, unsigned int flags)
const char * mg_strchr(const struct mg_str s, int c)
struct mg_str mg_mk_str_n(const char *s, size_t len)
#define MG_URL_ENCODE_F_UPPERCASE_HEX
#define MG_URL_ENCODE_F_SPACE_AS_PLUS
static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data, size_t *chunk_len)
mg_http_multipart_stream_state
@ MPS_WAITING_FOR_BOUNDARY
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm)
static void mg_send_directory_listing(struct mg_connection *nc, const char *dir, struct http_message *hm, struct mg_serve_http_opts *opts)
MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm, const struct mg_serve_http_opts *opts, char **local_path, struct mg_str *remainder)
static void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d)
static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data)
static int mg_resolve2(const char *host, struct in_addr *ina)
static void mg_handle_cgi(struct mg_connection *nc, const char *prog, const struct mg_str *path_info, const struct http_message *hm, const struct mg_serve_http_opts *opts)
static struct mg_http_proto_data * mg_http_get_proto_data(struct mg_connection *c)
static void mg_send_file_data(struct mg_connection *nc, FILE *fp)
static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data)
static const struct @23 mg_static_builtin_mime_types[]
#define MIME_ENTRY(_ext, _type)
static int mg_create_itermediate_directories(const char *path)
MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path, const struct mg_str *path_info, struct http_message *hm, struct mg_serve_http_opts *opts)
static void dns_handler(struct mg_connection *nc, int ev, void *ev_data)
static void mg_http_construct_etag(char *buf, size_t buf_len, const cs_stat_t *st)
MG_INTERNAL time_t mg_parse_date_string(const char *datetime)
static void resolve_cb(struct mg_dns_message *msg, void *data, enum mg_resolve_err e)
static mg_event_handler_t mg_http_get_endpoint_handler(struct mg_connection *nc, struct mg_str *uri_path)
static int mg_is_ws_first_fragment(unsigned char flags)
static int mg_remove_directory(const struct mg_serve_http_opts *opts, const char *dir)
static int mg_check_nonce(const char *nonce)
static void mg_scan_directory(struct mg_connection *nc, const char *dir, const struct mg_serve_http_opts *opts, void(*func)(struct mg_connection *, const char *, cs_stat_t *))
static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name, cs_stat_t *stp)
struct mg_connection * mg_connect_http_base(struct mg_mgr *mgr, mg_event_handler_t ev_handler, struct mg_connect_opts opts, const char *schema, const char *schema_ssl, const char *url, const char **path, char **addr)
static int left(const struct frozen *f)
static void mg_handle_put(struct mg_connection *nc, const char *path, struct http_message *hm)
static const char * mg_http_parse_headers(const char *s, const char *end, int len, struct http_message *req)
static void mg_escape(const char *src, char *dst, size_t dst_len)
static void mg_send_ssi_file(struct mg_connection *, const char *, FILE *, int, const struct mg_serve_http_opts *)
MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st)
static int mg_get_month_index(const char *s)
static uint32_t mg_ws_random_mask(void)
static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d)
static int mg_get_ip_address_of_nameserver(char *name, size_t name_len)
static int mg_is_dav_request(const struct mg_str *s)
static unsigned char * mg_parse_dns_resource_record(unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr, int reply)
static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr)
static char * mg_addenv(struct mg_cgi_env_block *block, const char *fmt,...)
static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx)
static void mg_prepare_cgi_environment(struct mg_connection *nc, const char *prog, const struct mg_str *path_info, const struct http_message *hm, const struct mg_serve_http_opts *opts, struct mg_cgi_env_block *blk)
static void mg_handle_incoming_websocket_frame(struct mg_connection *nc, struct websocket_message *wsm)
static int mg_is_file_hidden(const char *path, const struct mg_serve_http_opts *opts, int exclude_specials)
static void mg_handle_ssi_request(struct mg_connection *nc, const char *path, const struct mg_serve_http_opts *opts)
static int mg_http_get_request_len(const char *s, int buf_len)
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc, struct http_message *hm, char *buf, size_t blen)
static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name)
static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len, struct ws_mask_ctx *ctx)
static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a, int64_t *b)
static void mg_print_props(struct mg_connection *nc, const char *name, cs_stat_t *stp)
static pid_t mg_start_process(const char *interp, const char *cmd, const char *env, const char *envp[], const char *dir, sock_t sock)
static int mg_is_ws_fragment(unsigned char flags)
MG_INTERNAL void mg_find_index_file(const char *path, const char *list, char **index_file, cs_stat_t *stp)
static int mg_deliver_websocket_data(struct mg_connection *nc)
static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep)
static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev, void *ev_data)
static size_t mg_get_line_len(const char *buf, size_t buf_len)
static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev, struct http_message *hm)
static void mg_handle_mkcol(struct mg_connection *nc, const char *path, struct http_message *hm)
static void mg_http_transfer_file_data(struct mg_connection *nc)
static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri, size_t uri_len, const char *ha1, size_t ha1_len, const char *nonce, size_t nonce_len, const char *nc, size_t nc_len, const char *cnonce, size_t cnonce_len, const char *qop, size_t qop_len, char *resp)
void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data)
static int mg_http_send_port_based_redirect(struct mg_connection *c, struct http_message *hm, const struct mg_serve_http_opts *opts)
static void mg_handle_delete(struct mg_connection *nc, const struct mg_serve_http_opts *opts, const char *path)
static void mg_handle_move(struct mg_connection *c, const struct mg_serve_http_opts *opts, const char *path, struct http_message *hm)
static void mg_handle_propfind(struct mg_connection *nc, const char *path, cs_stat_t *stp, struct http_message *hm, struct mg_serve_http_opts *opts)
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t)
static void mg_http_send_options(struct mg_connection *nc)
#define MG_DEFAULT_NAMESERVER
static void mg_ws_handshake(struct mg_connection *nc, const struct mg_str *key)
static int mg_is_creation_request(const struct http_message *hm)
static int mg_num_leap_years(int year)
static struct mg_str mg_get_mime_type(const char *path, const char *dflt, const struct mg_serve_http_opts *opts)
static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd, uint16_t message_id)
struct callback_addr callback
char message[MG_CTL_MSG_MESSAGE_SIZE]
mg_event_handler_t callback
const char * vars[MG_MAX_CGI_ENVIR_VARS]
struct mg_connection * nc
char buf[MG_CGI_ENVIRONMENT_SIZE]
struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN]
struct mg_connection * nc
mg_event_handler_t handler
struct mg_http_endpoint * next
enum mg_http_multipart_stream_state state
struct mg_connection * cgi_nc
enum mg_http_proto_data_type type
struct mg_http_proto_data_chuncked chunk
struct mg_http_endpoint * endpoints
struct mg_http_proto_data_cgi cgi
mg_event_handler_t endpoint_handler
struct mg_http_proto_data_file file
time_t(* poll)(struct mg_iface *iface, int timeout_ms)
void(* destroy_conn)(struct mg_connection *nc)
int(* listen_tcp)(struct mg_connection *nc, union socket_address *sa)
void(* remove_conn)(struct mg_connection *nc)
void(* connect_tcp)(struct mg_connection *nc, const union socket_address *sa)
void(* free)(struct mg_iface *iface)
void(* init)(struct mg_iface *iface)
void(* get_conn_addr)(struct mg_connection *nc, int remote, union socket_address *sa)
void(* connect_udp)(struct mg_connection *nc)
int(* udp_send)(struct mg_connection *nc, const void *buf, size_t len)
int(* create_conn)(struct mg_connection *nc)
int(* listen_udp)(struct mg_connection *nc, union socket_address *sa)
void(* sock_set)(struct mg_connection *nc, sock_t sock)
int(* udp_recv)(struct mg_connection *nc, void *buf, size_t len, union socket_address *sa, size_t *sa_len)
int(* tcp_send)(struct mg_connection *nc, const void *buf, size_t len)
int(* tcp_recv)(struct mg_connection *nc, void *buf, size_t len)
void(* add_conn)(struct mg_connection *nc)
const struct mg_iface_vtable * vtable
struct mg_connection * lc
union mg_lwip_conn_state::@24 pcb
struct mg_connection * nc
const union socket_address * sa
struct mg_connection * nc
struct mg_connection * nc
union socket_address * sa
struct mg_connection * nc
const struct mg_iface_vtable ** ifaces
const struct mg_iface_vtable * main_iface
struct mg_iface ** ifaces
uint16_t keep_alive_timer
struct mg_str will_message
struct mg_str protocol_name
void(* cb)(struct mg_mgr *mgr, void *arg)
mg_resolve_callback_t callback
bool rmdir(HNDLE hDB, HNDLE hROOT, const char *path)
static double comma(double a, double b)
static te_expr * base(state *s)
static te_expr * list(state *s)