7.0 refactor

This commit is contained in:
cpq
2020-12-05 11:26:32 +00:00
parent 34d4fb8cf0
commit f2fba1d200
838 changed files with 14236 additions and 255316 deletions
+97
View File
@@ -0,0 +1,97 @@
#pragma once
#define MG_ARCH_CUSTOM 0
#define MG_ARCH_UNIX 1
#define MG_ARCH_WIN32 2
#define MG_ARCH_ESP32 3
#define MG_ARCH_ESP8266 4
#define MG_ARCH_CC3100 5
#define MG_ARCH_CC3200 6
#define MG_ARCH_CC3220 7
#define MG_ARCH_MSP432 8
#define MG_ARCH_TM4C129 9
#define MG_ARCH_MBED 10
#define MG_ARCH_WINCE 11
#define MG_ARCH_NXP_LPC 12
#define MG_ARCH_NXP_KINETIS 13
#define MG_ARCH_NRF51 14
#define MG_ARCH_NRF52 15
#define MG_ARCH_PIC32 16
#define MG_ARCH_RS14100 17
#define MG_ARCH_STM32 18
#define MG_ARCH_FREERTOS 19
#if !defined(MG_ARCH)
#if defined(TARGET_IS_MSP432P4XX) || defined(__MSP432P401R__)
#define MG_ARCH MG_ARCH_MSP432
#elif defined(cc3200) || defined(TARGET_IS_CC3200)
#define MG_ARCH MG_ARCH_CC3200
#elif defined(cc3220) || defined(TARGET_IS_CC3220)
#define MG_ARCH MG_ARCH_CC3220
#elif defined(__unix__) || defined(__APPLE__)
#define MG_ARCH MG_ARCH_UNIX
#elif defined(WINCE)
#define MG_ARCH MG_ARCH_WINCE
#elif defined(_WIN32)
#define MG_ARCH MG_ARCH_WIN32
#elif defined(__MBED__)
#define MG_ARCH MG_ARCH_MBED
#elif defined(__USE_LPCOPEN)
#define MG_ARCH MG_ARCH_NXP_LPC
#elif defined(FRDM_K64F) || defined(FREEDOM)
#define MG_ARCH MG_ARCH_NXP_KINETIS
#elif defined(PIC32)
#define MG_ARCH MG_ARCH_PIC32
#elif defined(ESP_PLATFORM)
#define MG_ARCH MG_ARCH_ESP32
#elif defined(ICACHE_FLASH) || defined(ICACHE_RAM_ATTR)
#define MG_ARCH MG_ARCH_ESP8266
#elif defined(TARGET_IS_TM4C129_RA0) || defined(TARGET_IS_TM4C129_RA1) || \
defined(TARGET_IS_TM4C129_RA2)
#define MG_ARCH MG_ARCH_TM4C129
#elif defined(RS14100)
#define MG_ARCH MG_ARCH_RS14100
#elif defined(STM32)
#define MG_ARCH MG_ARCH_STM32
#endif
#if !defined(MG_ARCH)
#error "MG_ARCH is not specified and we couldn't guess it."
#endif
#endif // !defined(MG_ARCH)
#define WIN32_LEAN_AND_MEAN
#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS
// Standard C headers
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#if MG_ARCH == MG_ARCH_CUSTOM
#include <mongoose_custom.h>
#endif
#include "arch_esp32.h"
#include "arch_esp8266.h"
#include "arch_freertos.h"
#include "arch_unix.h"
#include "arch_win32.h"
#if !defined(PRINTF_LIKE)
#if defined(__GNUC__) || defined(__clang__) || defined(__TI_COMPILER_VERSION__)
#define PRINTF_LIKE(f, a) __attribute__((format(printf, f, a)))
#else
#define PRINTF_LIKE(f, a)
#endif
#endif
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#if MG_ARCH == MG_ARCH_ESP32
#include <dirent.h>
#include <netdb.h>
#define MG_DIRSEP '/'
#endif
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#if MG_ARCH == MG_ARCH_ESP8266
#include <dirent.h>
#include <stdbool.h>
#include <sys/time.h>
#include <user_interface.h>
#define MG_DIRSEP '/'
#ifndef PATH_MAX
#define PATH_MAX 128
#endif
#define MG_ENABLE_LWIP 1
#define LWIP_TIMEVAL_PRIVATE 0 // struct timeval is defined in sys/time.h
#if LWIP_SOCKET
#include <lwip/sockets.h>
#else
#undef LWIP_SOCKET
#define LWIP_SOCKET 1
#include <lwip/sockets.h> // Source sockaddr_in anyway
#undef LWIP_SOCKET
#define LWIP_SOCKET 0
#endif
#endif
+63
View File
@@ -0,0 +1,63 @@
#pragma once
#if MG_ARCH == MG_ARCH_FREERTOS
#include <FreeRTOS.h>
#include <task.h>
#include <FreeRTOS_IP.h>
#include <FreeRTOS_Sockets.h>
#include <stdbool.h>
#define MG_DIRSEP '/'
#define IPPROTO_TCP FREERTOS_IPPROTO_TCP
#define IPPROTO_UDP FREERTOS_IPPROTO_UDP
#define AF_INET FREERTOS_AF_INET
#define SOCK_STREAM FREERTOS_SOCK_STREAM
#define SOCK_DGRAM FREERTOS_SOCK_DGRAM
#define SO_BROADCAST 0
#define SO_ERROR 0
#define SOL_SOCKET 0
#define SO_REUSEADDR 0
#define sockaddr_in freertos_sockaddr
struct sockaddr {
uint8_t sa_len, sa_family;
};
#define accept(a, b, c) FreeRTOS_accept((a), (b), (c))
#define connect(a, b, c) FreeRTOS_connect((a), (b), (c))
#define bind(a, b, c) FreeRTOS_bind((a), (b), (c))
#define listen(a, b) FreeRTOS_listen((a), (b))
#define socket(a, b, c) FreeRTOS_socket((a), (b), (c))
#define send(a, b, c, d) FreeRTOS_send((a), (b), (c), (d))
#define recv(a, b, c, d) FreeRTOS_recv((a), (b), (c), (d))
#define setsockopt(a, b, c, d, e) FreeRTOS_setsockopt((a), (b), (c), (d), (e))
#define sendto(a, b, c, d, e, f) FreeRTOS_sendto((a), (b), (c), (d), (e), (f))
#define recvfrom(a, b, c, d, e, f) \
FreeRTOS_recvfrom((a), (b), (c), (d), (e), (f))
#define closesocket(x) FreeRTOS_closesocket(x)
#define gethostbyname(x) FreeRTOS_gethostbyname(x)
#include <ff_stdio.h>
#undef FILE
#define FILE FF_FILE
//#define SEEK_SET FF_SEEK_SET
//#define SEEK_END FF_SEEK_END
#define stat(a, b) ff_stat((a), (b))
#define fopen(a, b) ff_fopen((a), (b))
#define fclose(a) ff_fclose(a)
#define fread(a, b, c, d) ff_fread((a), (b), (c), (d))
#define fwrite(a, b, c, d) ff_fwrite((a), (b), (c), (d))
#define vfprintf ff_vfprintf
#define fprintf ff_fprintf
#define remove(a) ff_remove(a)
#define rename(a, b) ff_rename((a), (b), 1)
static inline int ff_vfprintf(FF_FILE *fp, const char *fmt, va_list ap) {
char *buf = NULL;
int n = mg_vasprintf(&buf, 0, fmt, ap);
if (buf != NULL) ff_fwrite(buf, 1, n, fp), free(buf);
return n;
}
#endif
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#if MG_ARCH == MG_ARCH_UNIX
#define _DARWIN_UNLIMITED_SELECT 1
#include <arpa/inet.h>
#include <dirent.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#define MG_DIRSEP '/'
#define MG_ENABLE_POSIX 1
#endif
+47
View File
@@ -0,0 +1,47 @@
#pragma once
#if MG_ARCH == MG_ARCH_WIN32
#if defined(_MSC_VER) && _MSC_VER < 1700
#define __func__ ""
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
typedef int bool;
enum { false = 0, true = 1 };
#else
#include <stdbool.h>
#include <stdint.h>
#endif
#include <winsock2.h>
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define strdup(x) _strdup(x)
#define sleep(x) Sleep((x) *1000)
typedef int socklen_t;
#define PATH_MAX MAX_PATH
#define MG_DIRSEP '\\'
#define inline __inline
#ifndef EINPROGRESS
#define EINPROGRESS WSAEINPROGRESS
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK WSAEWOULDBLOCK
#endif
#define realpath(a, b) _fullpath((b), (a), 512)
#ifndef va_copy
#ifdef __va_copy
#define va_copy __va_copy
#else
#define va_copy(x, y) (x) = (y)
#endif
#endif
#ifndef S_ISDIR
#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR)
#endif
#endif
+104
View File
@@ -0,0 +1,104 @@
#include <string.h>
static int mg_b64idx(int c) {
if (c < 26) {
return c + 'A';
} else if (c < 52) {
return c - 26 + 'a';
} else if (c < 62) {
return c - 52 + '0';
} else {
return c == 62 ? '+' : '/';
}
}
static int mg_b64rev(int c) {
if (c >= 'A' && c <= 'Z') {
return c - 'A';
} else if (c >= 'a' && c <= 'z') {
return c + 26 - 'a';
} else if (c >= '0' && c <= '9') {
return c + 52 - '0';
} else if (c == '+') {
return 62;
} else if (c == '/') {
return 63;
} else if (c == '=') {
return 64;
} else {
return -1;
}
}
int mg_base64_update(unsigned char ch, char *to, int n) {
unsigned char rem = (n & 3) % 3;
if (rem == 0) {
to[n] = mg_b64idx(ch >> 2);
to[++n] = (ch & 3) << 4;
} else if (rem == 1) {
to[n] = mg_b64idx(to[n] | (ch >> 4));
to[++n] = (ch & 15) << 2;
} else {
to[n] = mg_b64idx(to[n] | (ch >> 6));
to[++n] = mg_b64idx(ch & 63);
n++;
}
return n;
}
int mg_base64_final(char *to, int n) {
int saved = n;
// printf("---[%.*s]\n", n, to);
if (n & 3) n = mg_base64_update(0, to, n);
if ((saved & 3) == 2) n--;
// printf(" %d[%.*s]\n", n, n, to);
while (n & 3) to[n++] = '=';
to[n] = '\0';
return n;
}
int mg_base64_encode(const unsigned char *p, int n, char *to) {
#if 0
char buf[4];
int i, j, len = 0;
for (i = 0; i < n; i += 3) {
int a = p[i], b = i + 1 < n ? p[i + 1] : 0, c = i + 2 < n ? p[i + 2] : 0;
buf[0] = mg_b64idx(a >> 2);
buf[1] = mg_b64idx((a & 3) << 4 | (b >> 4));
buf[2] = mg_b64idx((b & 15) << 2 | (c >> 6));
buf[3] = mg_b64idx(c & 63);
j = 0;
if (i + 1 >= n) buf[2] = '=', j++;
if (i + 2 >= n) buf[3] = '=', j++;
memcpy(to + len, buf, sizeof(buf));
len += sizeof(buf);
}
to[len] = '\0';
printf("%d[%.*s] -> %d[%.*s]\n", n, n, p, len, len, to);
return len;
#else
int i, len = 0;
for (i = 0; i < n; i++) len = mg_base64_update(p[i], to, len);
len = mg_base64_final(to, len);
// printf("%d[%.*s] -> %d[%.*s]\n", n, n, p, len, len, to);
return len;
#endif
}
int mg_base64_decode(const char *src, int n, char *dst) {
const char *end = src + n;
int len = 0;
while (src + 3 < end) {
int a = mg_b64rev(src[0]), b = mg_b64rev(src[1]), c = mg_b64rev(src[2]),
d = mg_b64rev(src[3]);
if (a == 64 || a < 0 || b == 64 || b < 0 || c < 0 || d < 0) return 0;
dst[len++] = (a << 2) | (b >> 4);
if (src[2] != '=') {
dst[len++] = (b << 4) | (c >> 2);
if (src[3] != '=') dst[len++] = (c << 6) | d;
}
src += 4;
}
dst[len] = '\0';
return len;
}
+5
View File
@@ -0,0 +1,5 @@
#pragma once
int mg_base64_update(unsigned char p, char *to, int len);
int mg_base64_final(char *to, int len);
int mg_base64_encode(const unsigned char *p, int n, char *to);
int mg_base64_decode(const char *src, int n, char *dst);
-201
View File
@@ -1,201 +0,0 @@
#ifndef EXCLUDE_COMMON
#include "common/cs_base64.h"
#include <string.h>
#include "common/cs_dbg.h"
/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
#define NUM_UPPERCASES ('Z' - 'A' + 1)
#define NUM_LETTERS (NUM_UPPERCASES * 2)
#define NUM_DIGITS ('9' - '0' + 1)
/*
* Emit a base64 code char.
*
* Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
*/
static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
if (v < NUM_UPPERCASES) {
ctx->b64_putc(v + 'A', ctx->user_data);
} else if (v < (NUM_LETTERS)) {
ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
} else if (v < (NUM_LETTERS + NUM_DIGITS)) {
ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
} else {
ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
ctx->user_data);
}
}
static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
int a, b, c;
a = ctx->chunk[0];
b = ctx->chunk[1];
c = ctx->chunk[2];
cs_base64_emit_code(ctx, a >> 2);
cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
if (ctx->chunk_size > 1) {
cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
}
if (ctx->chunk_size > 2) {
cs_base64_emit_code(ctx, c & 63);
}
}
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
void *user_data) {
ctx->chunk_size = 0;
ctx->b64_putc = b64_putc;
ctx->user_data = user_data;
}
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
const unsigned char *src = (const unsigned char *) str;
size_t i;
for (i = 0; i < len; i++) {
ctx->chunk[ctx->chunk_size++] = src[i];
if (ctx->chunk_size == 3) {
cs_base64_emit_chunk(ctx);
ctx->chunk_size = 0;
}
}
}
void cs_base64_finish(struct cs_base64_ctx *ctx) {
if (ctx->chunk_size > 0) {
int i;
memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
cs_base64_emit_chunk(ctx);
for (i = 0; i < (3 - ctx->chunk_size); i++) {
ctx->b64_putc('=', ctx->user_data);
}
}
}
#define BASE64_ENCODE_BODY \
static const char *b64 = \
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
int i, j, a, b, c; \
\
for (i = j = 0; i < src_len; i += 3) { \
a = src[i]; \
b = i + 1 >= src_len ? 0 : src[i + 1]; \
c = i + 2 >= src_len ? 0 : src[i + 2]; \
\
BASE64_OUT(b64[a >> 2]); \
BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \
if (i + 1 < src_len) { \
BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \
} \
if (i + 2 < src_len) { \
BASE64_OUT(b64[c & 63]); \
} \
} \
\
while (j % 4 != 0) { \
BASE64_OUT('='); \
} \
BASE64_FLUSH()
#define BASE64_OUT(ch) \
do { \
dst[j++] = (ch); \
} while (0)
#define BASE64_FLUSH() \
do { \
dst[j++] = '\0'; \
} while (0)
void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
BASE64_ENCODE_BODY;
}
#undef BASE64_OUT
#undef BASE64_FLUSH
#if CS_ENABLE_STDIO
#define BASE64_OUT(ch) \
do { \
fprintf(f, "%c", (ch)); \
j++; \
} while (0)
#define BASE64_FLUSH()
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
BASE64_ENCODE_BODY;
}
#undef BASE64_OUT
#undef BASE64_FLUSH
#endif /* CS_ENABLE_STDIO */
/* Convert one byte of encoded base64 input stream to 6-bit chunk */
static unsigned char from_b64(unsigned char ch) {
/* Inverse lookup map */
static const unsigned char tab[128] = {
255, 255, 255, 255,
255, 255, 255, 255, /* 0 */
255, 255, 255, 255,
255, 255, 255, 255, /* 8 */
255, 255, 255, 255,
255, 255, 255, 255, /* 16 */
255, 255, 255, 255,
255, 255, 255, 255, /* 24 */
255, 255, 255, 255,
255, 255, 255, 255, /* 32 */
255, 255, 255, 62,
255, 255, 255, 63, /* 40 */
52, 53, 54, 55,
56, 57, 58, 59, /* 48 */
60, 61, 255, 255,
255, 200, 255, 255, /* 56 '=' is 200, on index 61 */
255, 0, 1, 2,
3, 4, 5, 6, /* 64 */
7, 8, 9, 10,
11, 12, 13, 14, /* 72 */
15, 16, 17, 18,
19, 20, 21, 22, /* 80 */
23, 24, 25, 255,
255, 255, 255, 255, /* 88 */
255, 26, 27, 28,
29, 30, 31, 32, /* 96 */
33, 34, 35, 36,
37, 38, 39, 40, /* 104 */
41, 42, 43, 44,
45, 46, 47, 48, /* 112 */
49, 50, 51, 255,
255, 255, 255, 255, /* 120 */
};
return tab[ch & 127];
}
int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) {
unsigned char a, b, c, d;
int orig_len = len;
char *orig_dst = dst;
while (len >= 4 && (a = from_b64(s[0])) != 255 &&
(b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
(d = from_b64(s[3])) != 255) {
s += 4;
len -= 4;
if (a == 200 || b == 200) break; /* '=' can't be there */
*dst++ = a << 2 | b >> 4;
if (c == 200) break;
*dst++ = b << 4 | c >> 2;
if (d == 200) break;
*dst++ = c << 6 | d;
}
*dst = 0;
if (dec_len != NULL) *dec_len = (dst - orig_dst);
return orig_len - len;
}
#endif /* EXCLUDE_COMMON */
-50
View File
@@ -1,50 +0,0 @@
#ifndef CS_COMMON_CS_BASE64_H_
#define CS_COMMON_CS_BASE64_H_
#ifndef DISABLE_BASE64
#define DISABLE_BASE64 0
#endif
#if !DISABLE_BASE64
#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef void (*cs_base64_putc_t)(char, void *);
struct cs_base64_ctx {
/* cannot call it putc because it's a macro on some environments */
cs_base64_putc_t b64_putc;
unsigned char chunk[3];
int chunk_size;
void *user_data;
};
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t putc,
void *user_data);
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len);
void cs_base64_finish(struct cs_base64_ctx *ctx);
void cs_base64_encode(const unsigned char *src, int src_len, char *dst);
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len);
/*
* Decodes a base64 string `s` length `len` into `dst`.
* `dst` must have enough space to hold the result.
* `*dec_len` will contain the resulting length of the string in `dst`
* while return value will return number of processed bytes in `src`.
* Return value == len indicates successful processing of all the data.
*/
int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len);
#ifdef __cplusplus
}
#endif
#endif /* DISABLE_BASE64 */
#endif /* CS_COMMON_CS_BASE64_H_ */
-138
View File
@@ -1,138 +0,0 @@
#include "common/cs_dbg.h"
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "common/cs_time.h"
#include "common/str_util.h"
enum cs_log_level cs_log_level WEAK =
#if CS_ENABLE_DEBUG
LL_VERBOSE_DEBUG;
#else
LL_ERROR;
#endif
#if CS_ENABLE_STDIO
static char *s_file_level = NULL;
void cs_log_set_file_level(const char *file_level) WEAK;
FILE *cs_log_file WEAK = NULL;
#if CS_LOG_ENABLE_TS_DIFF
double cs_log_ts WEAK;
#endif
enum cs_log_level cs_log_cur_msg_level WEAK = LL_NONE;
/* In implementations that require locking, these can be overridden. */
void cs_log_lock(void) WEAK;
void cs_log_lock(void) {
}
void cs_log_unlock(void) WEAK;
void cs_log_unlock(void) {
}
void cs_log_set_file_level(const char *file_level) {
char *fl = s_file_level;
if (file_level != NULL) {
s_file_level = strdup(file_level);
} else {
s_file_level = NULL;
}
free(fl);
}
int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) WEAK;
int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) {
char prefix[CS_LOG_PREFIX_LEN], *q;
const char *p;
size_t fl = 0, ll = 0, pl = 0;
if (level > cs_log_level && s_file_level == NULL) return 0;
p = file + strlen(file);
while (p != file) {
const char c = *(p - 1);
if (c == '/' || c == '\\') break;
p--;
fl++;
}
ll = (ln < 10000 ? (ln < 1000 ? (ln < 100 ? (ln < 10 ? 1 : 2) : 3) : 4) : 5);
if (fl > (sizeof(prefix) - ll - 2)) fl = (sizeof(prefix) - ll - 2);
pl = fl + 1 + ll;
memcpy(prefix, p, fl);
q = prefix + pl;
memset(q, ' ', sizeof(prefix) - pl);
do {
*(--q) = '0' + (ln % 10);
ln /= 10;
} while (ln > 0);
*(--q) = ':';
if (s_file_level != NULL) {
enum cs_log_level pll = cs_log_level;
struct mg_str fl = mg_mk_str(s_file_level), ps = MG_MK_STR_N(prefix, pl);
struct mg_str k, v;
while ((fl = mg_next_comma_list_entry_n(fl, &k, &v)).p != NULL) {
bool yes = !(!mg_str_starts_with(ps, k) || v.len == 0);
if (!yes) continue;
pll = (enum cs_log_level)(*v.p - '0');
break;
}
if (level > pll) return 0;
}
cs_log_lock();
if (cs_log_file == NULL) cs_log_file = stderr;
cs_log_cur_msg_level = level;
fwrite(prefix, 1, sizeof(prefix), cs_log_file);
#if CS_LOG_ENABLE_TS_DIFF
{
double now = cs_time();
fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000));
cs_log_ts = now;
}
#endif
return 1;
}
void cs_log_printf(const char *fmt, ...) WEAK;
void cs_log_printf(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(cs_log_file, fmt, ap);
va_end(ap);
fputc('\n', cs_log_file);
fflush(cs_log_file);
cs_log_cur_msg_level = LL_NONE;
cs_log_unlock();
}
void cs_log_set_file(FILE *file) WEAK;
void cs_log_set_file(FILE *file) {
cs_log_file = file;
}
#else
void cs_log_set_file_level(const char *file_level) {
(void) file_level;
}
#endif /* CS_ENABLE_STDIO */
void cs_log_set_level(enum cs_log_level level) WEAK;
void cs_log_set_level(enum cs_log_level level) {
cs_log_level = level;
#if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO
cs_log_ts = cs_time();
#endif
}
-132
View File
@@ -1,132 +0,0 @@
#ifndef CS_COMMON_CS_DBG_H_
#define CS_COMMON_CS_DBG_H_
#include "common/platform.h"
#if CS_ENABLE_STDIO
#include <stdio.h>
#endif
#ifndef CS_ENABLE_DEBUG
#define CS_ENABLE_DEBUG 0
#endif
#ifndef CS_LOG_PREFIX_LEN
#define CS_LOG_PREFIX_LEN 24
#endif
#ifndef CS_LOG_ENABLE_TS_DIFF
#define CS_LOG_ENABLE_TS_DIFF 0
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* Log level; `LL_INFO` is the default. Use `cs_log_set_level()` to change it.
*/
enum cs_log_level {
LL_NONE = -1,
LL_ERROR = 0,
LL_WARN = 1,
LL_INFO = 2,
LL_DEBUG = 3,
LL_VERBOSE_DEBUG = 4,
_LL_MIN = -2,
_LL_MAX = 5,
};
/*
* Set max log level to print; messages with the level above the given one will
* not be printed.
*/
void cs_log_set_level(enum cs_log_level level);
/*
* A comma-separated set of prefix=level.
* prefix is matched against the log prefix exactly as printed, including line
* number, but partial match is ok. Check stops on first matching entry.
* If nothing matches, default level is used.
*
* Examples:
* main.c:=4 - everything from main C at verbose debug level.
* mongoose.c=1,mjs.c=1,=4 - everything at verbose debug except mg_* and mjs_*
*
*/
void cs_log_set_file_level(const char *file_level);
/*
* Helper function which prints message prefix with the given `level`.
* If message should be printed (according to the current log level
* and filter), prints the prefix and returns 1, otherwise returns 0.
*
* Clients should typically just use `LOG()` macro.
*/
int cs_log_print_prefix(enum cs_log_level level, const char *fname, int line);
extern enum cs_log_level cs_log_level;
#if CS_ENABLE_STDIO
/*
* Set file to write logs into. If `NULL`, logs go to `stderr`.
*/
void cs_log_set_file(FILE *file);
/*
* Prints log to the current log file, appends "\n" in the end and flushes the
* stream.
*/
void cs_log_printf(const char *fmt, ...) PRINTF_LIKE(1, 2);
#if CS_ENABLE_STDIO
/*
* Format and print message `x` with the given level `l`. Example:
*
* ```c
* LOG(LL_INFO, ("my info message: %d", 123));
* LOG(LL_DEBUG, ("my debug message: %d", 123));
* ```
*/
#define LOG(l, x) \
do { \
if (cs_log_print_prefix(l, __FILE__, __LINE__)) { \
cs_log_printf x; \
} \
} while (0)
#else
#define LOG(l, x) ((void) l)
#endif
#ifndef CS_NDEBUG
/*
* Shortcut for `LOG(LL_VERBOSE_DEBUG, (...))`
*/
#define DBG(x) LOG(LL_VERBOSE_DEBUG, x)
#else /* NDEBUG */
#define DBG(x)
#endif
#else /* CS_ENABLE_STDIO */
#define LOG(l, x)
#define DBG(x)
#endif
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_CS_DBG_H_ */
-92
View File
@@ -1,92 +0,0 @@
#ifndef EXCLUDE_COMMON
#include "common/mg_mem.h"
#include "common/cs_dirent.h"
/*
* This file contains POSIX opendir/closedir/readdir API implementation
* for systems which do not natively support it (e.g. Windows).
*/
#ifdef _WIN32
struct win32_dir {
DIR d;
HANDLE handle;
WIN32_FIND_DATAW info;
struct dirent result;
};
DIR *opendir(const char *name) {
struct win32_dir *dir = NULL;
wchar_t wpath[MAX_PATH];
DWORD attrs;
if (name == NULL) {
SetLastError(ERROR_BAD_ARGUMENTS);
} else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
} else {
to_wchar(name, wpath, ARRAY_SIZE(wpath));
attrs = GetFileAttributesW(wpath);
if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
(void) wcscat(wpath, L"\\*");
dir->handle = FindFirstFileW(wpath, &dir->info);
dir->result.d_name[0] = '\0';
} else {
MG_FREE(dir);
dir = NULL;
}
}
return (DIR *) dir;
}
int closedir(DIR *d) {
struct win32_dir *dir = (struct win32_dir *) d;
int result = 0;
if (dir != NULL) {
if (dir->handle != INVALID_HANDLE_VALUE)
result = FindClose(dir->handle) ? 0 : -1;
MG_FREE(dir);
} else {
result = -1;
SetLastError(ERROR_BAD_ARGUMENTS);
}
return result;
}
struct dirent *readdir(DIR *d) {
struct win32_dir *dir = (struct win32_dir *) d;
struct dirent *result = NULL;
if (dir) {
memset(&dir->result, 0, sizeof(dir->result));
if (dir->handle != INVALID_HANDLE_VALUE) {
result = &dir->result;
(void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
result->d_name, sizeof(result->d_name), NULL,
NULL);
if (!FindNextFileW(dir->handle, &dir->info)) {
(void) FindClose(dir->handle);
dir->handle = INVALID_HANDLE_VALUE;
}
} else {
SetLastError(ERROR_FILE_NOT_FOUND);
}
} else {
SetLastError(ERROR_BAD_ARGUMENTS);
}
return result;
}
#endif
#endif /* EXCLUDE_COMMON */
/* ISO C requires a translation unit to contain at least one declaration */
typedef int cs_dirent_dummy;
-35
View File
@@ -1,35 +0,0 @@
#ifndef CS_COMMON_CS_DIRENT_H_
#define CS_COMMON_CS_DIRENT_H_
#include <limits.h>
#include "common/platform.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifdef CS_DEFINE_DIRENT
typedef struct { int dummy; } DIR;
struct dirent {
int d_ino;
#ifdef _WIN32
char d_name[MAX_PATH];
#else
/* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */
char d_name[256];
#endif
};
DIR *opendir(const char *dir_name);
int closedir(DIR *dir);
struct dirent *readdir(DIR *dir);
#endif /* CS_DEFINE_DIRENT */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_CS_DIRENT_H_ */
-28
View File
@@ -1,28 +0,0 @@
#ifndef CS_COMMON_CS_ENDIAN_H_
#define CS_COMMON_CS_ENDIAN_H_
#ifdef __cplusplus
extern "C" {
#endif
/*
* clang with std=-c99 uses __LITTLE_ENDIAN, by default
* while for ex, RTOS gcc - LITTLE_ENDIAN, by default
* it depends on __USE_BSD, but let's have everything
*/
#if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
#define BYTE_ORDER __BYTE_ORDER
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN __LITTLE_ENDIAN
#endif /* LITTLE_ENDIAN */
#ifndef BIG_ENDIAN
#define BIG_ENDIAN __LITTLE_ENDIAN
#endif /* BIG_ENDIAN */
#endif /* BYTE_ORDER */
#ifdef __cplusplus
}
#endif
#endif /* CS_COMMON_CS_ENDIAN_H_ */
-29
View File
@@ -1,29 +0,0 @@
#ifndef CS_COMMON_MD5_H_
#define CS_COMMON_MD5_H_
#include "common/platform.h"
#ifndef CS_DISABLE_MD5
#define CS_DISABLE_MD5 0
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct {
uint32_t buf[4];
uint32_t bits[2];
unsigned char in[64];
} cs_md5_ctx;
void cs_md5_init(cs_md5_ctx *c);
void cs_md5_update(cs_md5_ctx *c, const unsigned char *data, size_t len);
void cs_md5_final(unsigned char *md, cs_md5_ctx *c);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_MD5_H_ */
-35
View File
@@ -1,35 +0,0 @@
#ifndef CS_COMMON_SHA1_H_
#define CS_COMMON_SHA1_H_
#ifndef CS_DISABLE_SHA1
#define CS_DISABLE_SHA1 0
#endif
#if !CS_DISABLE_SHA1
#include "common/platform.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
typedef struct {
uint32_t state[5];
uint32_t count[2];
unsigned char buffer[64];
} cs_sha1_ctx;
void cs_sha1_init(cs_sha1_ctx *);
void cs_sha1_update(cs_sha1_ctx *, const unsigned char *data, uint32_t len);
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *);
void cs_hmac_sha1(const unsigned char *key, size_t key_len,
const unsigned char *text, size_t text_len,
unsigned char out[20]);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_DISABLE_SHA1 */
#endif /* CS_COMMON_SHA1_H_ */
-79
View File
@@ -1,79 +0,0 @@
#include "common/cs_time.h"
#ifndef _WIN32
#include <stddef.h>
/*
* There is no sys/time.h on ARMCC.
*/
#if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \
!defined(__TI_COMPILER_VERSION__) && \
(!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC)
#include <sys/time.h>
#endif
#else
#include <windows.h>
#endif
double cs_time(void) WEAK;
double cs_time(void) {
double now;
#ifndef _WIN32
struct timeval tv;
if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
#else
SYSTEMTIME sysnow;
FILETIME ftime;
GetLocalTime(&sysnow);
SystemTimeToFileTime(&sysnow, &ftime);
/*
* 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64
* This should not cause a problems in this (21th) century
* 2. Windows FILETIME is a number of 100-nanosecond intervals since January
* 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC,
* thus, we need to convert to seconds and adjust amount (subtract 11644473600
* seconds)
*/
now = (double) (((int64_t) ftime.dwLowDateTime +
((int64_t) ftime.dwHighDateTime << 32)) /
10000000.0) -
11644473600;
#endif /* _WIN32 */
return now;
}
double cs_timegm(const struct tm *tm) {
/* Month-to-day offset for non-leap-years. */
static const int month_day[12] = {0, 31, 59, 90, 120, 151,
181, 212, 243, 273, 304, 334};
/* Most of the calculation is easy; leap years are the main difficulty. */
int month = tm->tm_mon % 12;
int year = tm->tm_year + tm->tm_mon / 12;
int year_for_leap;
int64_t rt;
if (month < 0) { /* Negative values % 12 are still negative. */
month += 12;
--year;
}
/* This is the number of Februaries since 1900. */
year_for_leap = (month > 1) ? year + 1 : year;
rt =
tm->tm_sec /* Seconds */
+
60 *
(tm->tm_min /* Minute = 60 seconds */
+
60 * (tm->tm_hour /* Hour = 60 minutes */
+
24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */
+ 365 * (year - 70) /* Year = 365 days */
+ (year_for_leap - 69) / 4 /* Every 4 years is leap... */
- (year_for_leap - 1) / 100 /* Except centuries... */
+ (year_for_leap + 299) / 400))); /* Except 400s. */
return rt < 0 ? -1 : (double) rt;
}
-26
View File
@@ -1,26 +0,0 @@
#ifndef CS_COMMON_CS_TIME_H_
#define CS_COMMON_CS_TIME_H_
#include <time.h>
#include "common/platform.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Sub-second granularity time(). */
double cs_time(void);
/*
* Similar to (non-standard) timegm, converts broken-down time into the number
* of seconds since Unix Epoch.
*/
double cs_timegm(const struct tm *tm);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_CS_TIME_H_ */
-135
View File
@@ -1,135 +0,0 @@
#ifndef EXCLUDE_COMMON
#include <assert.h>
#include <string.h>
#include "common/mbuf.h"
#ifndef MBUF_REALLOC
#define MBUF_REALLOC realloc
#endif
#ifndef MBUF_FREE
#define MBUF_FREE free
#endif
void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK;
void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
mbuf->len = mbuf->size = 0;
mbuf->buf = NULL;
mbuf_resize(mbuf, initial_size);
}
void mbuf_free(struct mbuf *mbuf) WEAK;
void mbuf_free(struct mbuf *mbuf) {
if (mbuf->buf != NULL) {
MBUF_FREE(mbuf->buf);
mbuf_init(mbuf, 0);
}
}
void mbuf_resize(struct mbuf *a, size_t new_size) WEAK;
void mbuf_resize(struct mbuf *a, size_t new_size) {
if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
/*
* In case realloc fails, there's not much we can do, except keep things as
* they are. Note that NULL is a valid return value from realloc when
* size == 0, but that is covered too.
*/
if (buf == NULL && new_size != 0) return;
a->buf = buf;
a->size = new_size;
}
}
void mbuf_trim(struct mbuf *mbuf) WEAK;
void mbuf_trim(struct mbuf *mbuf) {
mbuf_resize(mbuf, mbuf->len);
}
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK;
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
char *p = NULL;
assert(a != NULL);
assert(a->len <= a->size);
assert(off <= a->len);
/* check overflow */
if (~(size_t) 0 - (size_t) a->buf < len) return 0;
if (a->len + len <= a->size) {
memmove(a->buf + off + len, a->buf + off, a->len - off);
if (buf != NULL) {
memcpy(a->buf + off, buf, len);
}
a->len += len;
} else {
size_t min_size = (a->len + len);
size_t new_size = (size_t)(min_size * MBUF_SIZE_MULTIPLIER);
if (new_size - min_size > MBUF_SIZE_MAX_HEADROOM) {
new_size = min_size + MBUF_SIZE_MAX_HEADROOM;
}
p = (char *) MBUF_REALLOC(a->buf, new_size);
if (p == NULL && new_size != min_size) {
new_size = min_size;
p = (char *) MBUF_REALLOC(a->buf, new_size);
}
if (p != NULL) {
a->buf = p;
if (off != a->len) {
memmove(a->buf + off + len, a->buf + off, a->len - off);
}
if (buf != NULL) memcpy(a->buf + off, buf, len);
a->len += len;
a->size = new_size;
} else {
len = 0;
}
}
return len;
}
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK;
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
return mbuf_insert(a, a->len, buf, len);
}
size_t mbuf_append_and_free(struct mbuf *a, void *buf, size_t len) WEAK;
size_t mbuf_append_and_free(struct mbuf *a, void *data, size_t len) {
size_t ret;
/* Optimization: if the buffer is currently empty,
* take over the user-provided buffer. */
if (a->len == 0) {
if (a->buf != NULL) free(a->buf);
a->buf = (char *) data;
a->len = a->size = len;
return len;
}
ret = mbuf_insert(a, a->len, data, len);
free(data);
return ret;
}
void mbuf_remove(struct mbuf *mb, size_t n) WEAK;
void mbuf_remove(struct mbuf *mb, size_t n) {
if (n > 0 && n <= mb->len) {
memmove(mb->buf, mb->buf + n, mb->len - n);
mb->len -= n;
}
}
void mbuf_clear(struct mbuf *mb) WEAK;
void mbuf_clear(struct mbuf *mb) {
mb->len = 0;
}
void mbuf_move(struct mbuf *from, struct mbuf *to) WEAK;
void mbuf_move(struct mbuf *from, struct mbuf *to) {
memcpy(to, from, sizeof(*to));
memset(from, 0, sizeof(*from));
}
#endif /* EXCLUDE_COMMON */
-95
View File
@@ -1,95 +0,0 @@
/*
* Mbufs are mutable/growing memory buffers, like C++ strings.
* Mbuf can append data to the end of a buffer or insert data into arbitrary
* position in the middle of a buffer. The buffer grows automatically when
* needed.
*/
#ifndef CS_COMMON_MBUF_H_
#define CS_COMMON_MBUF_H_
#include <stdlib.h>
#include "common/platform.h"
#if defined(__cplusplus)
extern "C" {
#endif
#ifndef MBUF_SIZE_MULTIPLIER
#define MBUF_SIZE_MULTIPLIER 1.5
#endif
#ifndef MBUF_SIZE_MAX_HEADROOM
#ifdef BUFSIZ
#define MBUF_SIZE_MAX_HEADROOM BUFSIZ
#else
#define MBUF_SIZE_MAX_HEADROOM 1024
#endif
#endif
/* Memory buffer descriptor */
struct mbuf {
char *buf; /* Buffer pointer */
size_t len; /* Data length. Data is located between offset 0 and len. */
size_t size; /* Buffer size allocated by realloc(1). Must be >= len */
};
/*
* Initialises an Mbuf.
* `initial_capacity` specifies the initial capacity of the mbuf.
*/
void mbuf_init(struct mbuf *, size_t initial_capacity);
/* Frees the space allocated for the mbuffer and resets the mbuf structure. */
void mbuf_free(struct mbuf *);
/*
* Appends data to the Mbuf.
*
* Returns the number of bytes appended or 0 if out of memory.
*/
size_t mbuf_append(struct mbuf *, const void *data, size_t data_size);
/*
* Appends data to the Mbuf and frees it (data must be heap-allocated).
*
* Returns the number of bytes appended or 0 if out of memory.
* data is freed irrespective of return value.
*/
size_t mbuf_append_and_free(struct mbuf *, void *data, size_t data_size);
/*
* Inserts data at a specified offset in the Mbuf.
*
* Existing data will be shifted forwards and the buffer will
* be grown if necessary.
* Returns the number of bytes inserted.
*/
size_t mbuf_insert(struct mbuf *, size_t, const void *, size_t);
/* Removes `data_size` bytes from the beginning of the buffer. */
void mbuf_remove(struct mbuf *, size_t data_size);
/*
* Resizes an Mbuf.
*
* If `new_size` is smaller than buffer's `len`, the
* resize is not performed.
*/
void mbuf_resize(struct mbuf *, size_t new_size);
/* Moves the state from one mbuf to the other. */
void mbuf_move(struct mbuf *from, struct mbuf *to);
/* Removes all the data from mbuf (if any). */
void mbuf_clear(struct mbuf *);
/* Shrinks an Mbuf by resizing its `size` to `len`. */
void mbuf_trim(struct mbuf *);
#if defined(__cplusplus)
}
#endif /* __cplusplus */
#endif /* CS_COMMON_MBUF_H_ */
-29
View File
@@ -1,29 +0,0 @@
#ifndef CS_COMMON_MG_MEM_H_
#define CS_COMMON_MG_MEM_H_
#ifdef __cplusplus
extern "C" {
#endif
#ifndef MG_MALLOC
#define MG_MALLOC malloc
#endif
#ifndef MG_CALLOC
#define MG_CALLOC calloc
#endif
#ifndef MG_REALLOC
#define MG_REALLOC realloc
#endif
#ifndef MG_FREE
#define MG_FREE free
#endif
#ifdef __cplusplus
}
#endif
#endif /* CS_COMMON_MG_MEM_H_ */
-162
View File
@@ -1,162 +0,0 @@
#include "common/mg_mem.h"
#include "common/mg_str.h"
#include "common/platform.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
struct mg_str mg_mk_str(const char *s) WEAK;
struct mg_str mg_mk_str(const char *s) {
struct mg_str ret = {s, 0};
if (s != NULL) ret.len = strlen(s);
return ret;
}
struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK;
struct mg_str mg_mk_str_n(const char *s, size_t len) {
struct mg_str ret = {s, len};
return ret;
}
int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK;
int mg_vcmp(const struct mg_str *str1, const char *str2) {
size_t n2 = strlen(str2), n1 = str1->len;
int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2);
if (r == 0) {
return n1 - n2;
}
return r;
}
int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK;
int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
size_t n2 = strlen(str2), n1 = str1->len;
int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
if (r == 0) {
return n1 - n2;
}
return r;
}
static struct mg_str mg_strdup_common(const struct mg_str s,
int nul_terminate) {
struct mg_str r = {NULL, 0};
if (s.len > 0 && s.p != NULL) {
char *sc = (char *) MG_MALLOC(s.len + (nul_terminate ? 1 : 0));
if (sc != NULL) {
memcpy(sc, s.p, s.len);
if (nul_terminate) sc[s.len] = '\0';
r.p = sc;
r.len = s.len;
}
}
return r;
}
struct mg_str mg_strdup(const struct mg_str s) WEAK;
struct mg_str mg_strdup(const struct mg_str s) {
return mg_strdup_common(s, 0 /* NUL-terminate */);
}
struct mg_str mg_strdup_nul(const struct mg_str s) WEAK;
struct mg_str mg_strdup_nul(const struct mg_str s) {
return mg_strdup_common(s, 1 /* NUL-terminate */);
}
const char *mg_strchr(const struct mg_str s, int c) WEAK;
const char *mg_strchr(const struct mg_str s, int c) {
size_t i;
for (i = 0; i < s.len; i++) {
if (s.p[i] == c) return &s.p[i];
}
return NULL;
}
int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK;
int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
size_t i = 0;
while (i < str1.len && i < str2.len) {
int c1 = str1.p[i];
int c2 = str2.p[i];
if (c1 < c2) return -1;
if (c1 > c2) return 1;
i++;
}
if (i < str1.len) return 1;
if (i < str2.len) return -1;
return 0;
}
int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK;
int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) {
struct mg_str s1 = str1;
struct mg_str s2 = str2;
if (s1.len > n) {
s1.len = n;
}
if (s2.len > n) {
s2.len = n;
}
return mg_strcmp(s1, s2);
}
int mg_strcasecmp(const struct mg_str str1, const struct mg_str str2) WEAK;
int mg_strcasecmp(const struct mg_str str1, const struct mg_str str2) {
size_t i = 0;
while (i < str1.len && i < str2.len) {
int c1 = tolower((int) str1.p[i]);
int c2 = tolower((int) str2.p[i]);
if (c1 < c2) return -1;
if (c1 > c2) return 1;
i++;
}
if (i < str1.len) return 1;
if (i < str2.len) return -1;
return 0;
}
void mg_strfree(struct mg_str *s) WEAK;
void mg_strfree(struct mg_str *s) {
char *sp = (char *) s->p;
s->p = NULL;
s->len = 0;
if (sp != NULL) free(sp);
}
const char *mg_strstr(const struct mg_str haystack,
const struct mg_str needle) WEAK;
const char *mg_strstr(const struct mg_str haystack,
const struct mg_str needle) {
size_t i;
if (needle.len > haystack.len) return NULL;
for (i = 0; i <= haystack.len - needle.len; i++) {
if (memcmp(haystack.p + i, needle.p, needle.len) == 0) {
return haystack.p + i;
}
}
return NULL;
}
struct mg_str mg_strstrip(struct mg_str s) WEAK;
struct mg_str mg_strstrip(struct mg_str s) {
while (s.len > 0 && isspace((int) *s.p)) {
s.p++;
s.len--;
}
while (s.len > 0 && isspace((int) *(s.p + s.len - 1))) {
s.len--;
}
return s;
}
int mg_str_starts_with(struct mg_str s, struct mg_str prefix) WEAK;
int mg_str_starts_with(struct mg_str s, struct mg_str prefix) {
const struct mg_str sp = MG_MK_STR_N(s.p, prefix.len);
if (s.len < prefix.len) return 0;
return (mg_strcmp(sp, prefix) == 0);
}
-97
View File
@@ -1,97 +0,0 @@
#ifndef CS_COMMON_MG_STR_H_
#define CS_COMMON_MG_STR_H_
#include <stddef.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Describes chunk of memory */
struct mg_str {
const char *p; /* Memory chunk pointer */
size_t len; /* Memory chunk length */
};
/*
* Helper function for creating mg_str struct from plain C string.
* `NULL` is allowed and becomes `{NULL, 0}`.
*/
struct mg_str mg_mk_str(const char *s);
/*
* Like `mg_mk_str`, but takes string length explicitly.
*/
struct mg_str mg_mk_str_n(const char *s, size_t len);
/* Macro for initializing mg_str. */
#define MG_MK_STR(str_literal) \
{ str_literal, sizeof(str_literal) - 1 }
#define MG_MK_STR_N(str_literal, len) \
{ str_literal, len }
#define MG_NULL_STR \
{ NULL, 0 }
/*
* Cross-platform version of `strcmp()` where where first string is
* specified by `struct mg_str`.
*/
int mg_vcmp(const struct mg_str *str2, const char *str1);
/*
* Cross-platform version of `strncasecmp()` where first string is
* specified by `struct mg_str`.
*/
int mg_vcasecmp(const struct mg_str *str2, const char *str1);
/* Creates a copy of s (heap-allocated). */
struct mg_str mg_strdup(const struct mg_str s);
/*
* Creates a copy of s (heap-allocated).
* Resulting string is NUL-terminated (but NUL is not included in len).
*/
struct mg_str mg_strdup_nul(const struct mg_str s);
/*
* Locates character in a string.
*/
const char *mg_strchr(const struct mg_str s, int c);
/*
* Compare two `mg_str`s; return value is the same as `strcmp`.
*/
int mg_strcmp(const struct mg_str str1, const struct mg_str str2);
/*
* Like `mg_strcmp`, but compares at most `n` characters.
*/
int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n);
/*
* Compare two `mg_str`s ignoreing case; return value is the same as `strcmp`.
*/
int mg_strcasecmp(const struct mg_str str1, const struct mg_str str2);
/*
* Free the string (assuming it was heap allocated).
*/
void mg_strfree(struct mg_str *s);
/*
* Finds the first occurrence of a substring `needle` in the `haystack`.
*/
const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle);
/* Strip whitespace at the start and the end of s */
struct mg_str mg_strstrip(struct mg_str s);
/* Returns 1 if s starts with the given prefix. */
int mg_str_starts_with(struct mg_str s, struct mg_str prefix);
#ifdef __cplusplus
}
#endif
#endif /* CS_COMMON_MG_STR_H_ */
-139
View File
@@ -1,139 +0,0 @@
#ifndef CS_COMMON_PLATFORM_H_
#define CS_COMMON_PLATFORM_H_
/*
* For the "custom" platform, includes and dependencies can be
* provided through mg_locals.h.
*/
#define CS_P_CUSTOM 0
#define CS_P_UNIX 1
#define CS_P_WINDOWS 2
#define CS_P_ESP32 15
#define CS_P_ESP8266 3
#define CS_P_CC3100 6
#define CS_P_CC3200 4
#define CS_P_CC3220 17
#define CS_P_MSP432 5
#define CS_P_TM4C129 14
#define CS_P_MBED 7
#define CS_P_WINCE 8
#define CS_P_NXP_LPC 13
#define CS_P_NXP_KINETIS 9
#define CS_P_NRF51 12
#define CS_P_NRF52 10
#define CS_P_PIC32 11
#define CS_P_RS14100 18
#define CS_P_STM32 16
/* Next id: 19 */
/* If not specified explicitly, we guess platform by defines. */
#ifndef CS_PLATFORM
#if defined(TARGET_IS_MSP432P4XX) || defined(__MSP432P401R__)
#define CS_PLATFORM CS_P_MSP432
#elif defined(cc3200) || defined(TARGET_IS_CC3200)
#define CS_PLATFORM CS_P_CC3200
#elif defined(cc3220) || defined(TARGET_IS_CC3220)
#define CS_PLATFORM CS_P_CC3220
#elif defined(__unix__) || defined(__APPLE__)
#define CS_PLATFORM CS_P_UNIX
#elif defined(WINCE)
#define CS_PLATFORM CS_P_WINCE
#elif defined(_WIN32)
#define CS_PLATFORM CS_P_WINDOWS
#elif defined(__MBED__)
#define CS_PLATFORM CS_P_MBED
#elif defined(__USE_LPCOPEN)
#define CS_PLATFORM CS_P_NXP_LPC
#elif defined(FRDM_K64F) || defined(FREEDOM)
#define CS_PLATFORM CS_P_NXP_KINETIS
#elif defined(PIC32)
#define CS_PLATFORM CS_P_PIC32
#elif defined(ESP_PLATFORM)
#define CS_PLATFORM CS_P_ESP32
#elif defined(ICACHE_FLASH)
#define CS_PLATFORM CS_P_ESP8266
#elif defined(TARGET_IS_TM4C129_RA0) || defined(TARGET_IS_TM4C129_RA1) || \
defined(TARGET_IS_TM4C129_RA2)
#define CS_PLATFORM CS_P_TM4C129
#elif defined(RS14100)
#define CS_PLATFORM CS_P_RS14100
#elif defined(STM32)
#define CS_PLATFORM CS_P_STM32
#endif
#ifndef CS_PLATFORM
#error "CS_PLATFORM is not specified and we couldn't guess it."
#endif
#endif /* !defined(CS_PLATFORM) */
#define MG_NET_IF_SOCKET 1
#define MG_NET_IF_SIMPLELINK 2
#define MG_NET_IF_LWIP_LOW_LEVEL 3
#define MG_NET_IF_PIC32 4
#define MG_NET_IF_NULL 5
#define MG_SSL_IF_OPENSSL 1
#define MG_SSL_IF_MBEDTLS 2
#define MG_SSL_IF_SIMPLELINK 3
#include "common/platforms/platform_unix.h"
#include "common/platforms/platform_windows.h"
#include "common/platforms/platform_esp32.h"
#include "common/platforms/platform_esp8266.h"
#include "common/platforms/platform_cc3100.h"
#include "common/platforms/platform_cc3200.h"
#include "common/platforms/platform_cc3220.h"
#include "common/platforms/platform_mbed.h"
#include "common/platforms/platform_nrf51.h"
#include "common/platforms/platform_nrf52.h"
#include "common/platforms/platform_wince.h"
#include "common/platforms/platform_nxp_lpc.h"
#include "common/platforms/platform_nxp_kinetis.h"
#include "common/platforms/platform_pic32.h"
#include "common/platforms/platform_rs14100.h"
#include "common/platforms/platform_stm32.h"
#if CS_PLATFORM == CS_P_CUSTOM
#include <platform_custom.h>
#endif
/* Common stuff */
#if !defined(PRINTF_LIKE)
#if defined(__GNUC__) || defined(__clang__) || defined(__TI_COMPILER_VERSION__)
#define PRINTF_LIKE(f, a) __attribute__((format(printf, f, a)))
#else
#define PRINTF_LIKE(f, a)
#endif
#endif
#if !defined(WEAK)
#if (defined(__GNUC__) || defined(__clang__) || \
defined(__TI_COMPILER_VERSION__)) && \
!defined(_WIN32)
#define WEAK __attribute__((weak))
#else
#define WEAK
#endif
#endif
#ifdef __GNUC__
#define NORETURN __attribute__((noreturn))
#define NOINLINE __attribute__((noinline))
#define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#define NOINSTR __attribute__((no_instrument_function))
#define DO_NOT_WARN_UNUSED __attribute__((unused))
#else
#define NORETURN
#define NOINLINE
#define WARN_UNUSED_RESULT
#define NOINSTR
#define DO_NOT_WARN_UNUSED
#endif /* __GNUC__ */
#ifndef ARRAY_SIZE
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
#endif
#endif /* CS_COMMON_PLATFORM_H_ */
-99
View File
@@ -1,99 +0,0 @@
#if CS_PLATFORM == CS_P_CC3200
#include "common/mg_mem.h"
#include <stdio.h>
#include <string.h>
#ifndef __TI_COMPILER_VERSION__
#include <reent.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#endif
#include <inc/hw_types.h>
#include <inc/hw_memmap.h>
#include <driverlib/prcm.h>
#include <driverlib/rom.h>
#include <driverlib/rom_map.h>
#include <driverlib/uart.h>
#include <driverlib/utils.h>
#define CONSOLE_UART UARTA0_BASE
#ifdef __TI_COMPILER_VERSION__
int asprintf(char **strp, const char *fmt, ...) {
va_list ap;
int len;
*strp = MG_MALLOC(BUFSIZ);
if (*strp == NULL) return -1;
va_start(ap, fmt);
len = vsnprintf(*strp, BUFSIZ, fmt, ap);
va_end(ap);
if (len > 0) {
*strp = MG_REALLOC(*strp, len + 1);
if (*strp == NULL) return -1;
}
if (len >= BUFSIZ) {
va_start(ap, fmt);
len = vsnprintf(*strp, len + 1, fmt, ap);
va_end(ap);
}
return len;
}
#if MG_TI_NO_HOST_INTERFACE
time_t HOSTtime() {
struct timeval tp;
gettimeofday(&tp, NULL);
return tp.tv_sec;
}
#endif
#endif /* __TI_COMPILER_VERSION__ */
void fprint_str(FILE *fp, const char *str) {
while (*str != '\0') {
if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
MAP_UARTCharPut(CONSOLE_UART, *str++);
}
}
void _exit(int status) {
fprint_str(stderr, "_exit\n");
/* cause an unaligned access exception, that will drop you into gdb */
*(int *) 1 = status;
while (1)
; /* avoid gcc warning because stdlib abort() has noreturn attribute */
}
void _not_implemented(const char *what) {
fprint_str(stderr, what);
fprint_str(stderr, " is not implemented\n");
_exit(42);
}
int _kill(int pid, int sig) {
(void) pid;
(void) sig;
_not_implemented("_kill");
return -1;
}
int _getpid() {
fprint_str(stderr, "_getpid is not implemented\n");
return 42;
}
int _isatty(int fd) {
/* 0, 1 and 2 are TTYs. */
return fd < 2;
}
#endif /* CS_PLATFORM == CS_P_CC3200 */
-64
View File
@@ -1,64 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_
#define CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_
#ifndef MG_LWIP
#define MG_LWIP 0
#endif
#if MG_LWIP
/*
* When compiling for nRF5x chips with arm-none-eabi-gcc, it has BYTE_ORDER
* already defined, so in order to avoid warnings in lwip, we have to undefine
* it.
*
* TODO: Check if in the future versions of nRF5 SDK that changes.
* Current version of nRF51 SDK: 0.8.0
* nRF5 SDK: 0.9.0
*/
#if CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52
#undef BYTE_ORDER
#endif
#include <lwip/opt.h>
#include <lwip/err.h>
#include <lwip/ip_addr.h>
#include <lwip/inet.h>
#include <lwip/netdb.h>
#include <lwip/dns.h>
#ifndef LWIP_PROVIDE_ERRNO
#include <errno.h>
#endif
#if LWIP_SOCKET
#include <lwip/sockets.h>
#else
/* We really need the definitions from sockets.h. */
#undef LWIP_SOCKET
#define LWIP_SOCKET 1
#include <lwip/sockets.h>
#undef LWIP_SOCKET
#define LWIP_SOCKET 0
#endif
#define INVALID_SOCKET (-1)
#define SOMAXCONN 10
typedef int sock_t;
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
struct mg_mgr;
struct mg_connection;
void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
int interval, int count);
#endif
/* For older version of LWIP */
#ifndef ipX_2_ip
#define ipX_2_ip(x) (x)
#endif
#endif /* MG_LWIP */
#endif /* CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ */
-157
View File
@@ -1,157 +0,0 @@
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
#ifndef MG_SIG_QUEUE_LEN
#define MG_SIG_QUEUE_LEN 32
#endif
struct mg_ev_mgr_lwip_signal {
int sig;
struct mg_connection *nc;
};
struct mg_ev_mgr_lwip_data {
struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN];
int sig_queue_len;
int start_index;
};
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) {
struct mg_ev_mgr_lwip_data *md =
(struct mg_ev_mgr_lwip_data *) nc->iface->data;
mgos_lock();
if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) {
mgos_unlock();
return;
}
int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN;
md->sig_queue[end_index].sig = sig;
md->sig_queue[end_index].nc = nc;
md->sig_queue_len++;
mg_lwip_mgr_schedule_poll(nc->mgr);
mgos_unlock();
}
void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) {
struct mg_ev_mgr_lwip_data *md =
(struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data;
while (md->sig_queue_len > 0) {
mgos_lock();
int i = md->start_index;
int sig = md->sig_queue[i].sig;
struct mg_connection *nc = md->sig_queue[i].nc;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
md->start_index = (i + 1) % MG_SIG_QUEUE_LEN;
md->sig_queue_len--;
mgos_unlock();
if (nc->iface == NULL || nc->mgr == NULL) continue;
switch (sig) {
case MG_SIG_CONNECT_RESULT: {
mg_if_connect_cb(nc, cs->err);
break;
}
case MG_SIG_CLOSE_CONN: {
mg_close_conn(nc);
break;
}
case MG_SIG_RECV: {
cs->recv_pending = 0;
mg_if_can_recv_cb(nc);
mbuf_trim(&nc->recv_mbuf);
break;
}
case MG_SIG_TOMBSTONE: {
break;
}
case MG_SIG_ACCEPT: {
mg_lwip_handle_accept(nc);
break;
}
}
}
}
void mg_lwip_if_init(struct mg_iface *iface) {
LOG(LL_INFO, ("Mongoose %s, LwIP %u.%u.%u", MG_VERSION, LWIP_VERSION_MAJOR,
LWIP_VERSION_MINOR, LWIP_VERSION_REVISION));
iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data));
#if !NO_SYS && !LWIP_TCPIP_CORE_LOCKING
sys_sem_new(&s_tcpip_call_lock_sem, 1);
sys_sem_new(&s_tcpip_call_sync_sem, 0);
#endif
}
void mg_lwip_if_free(struct mg_iface *iface) {
MG_FREE(iface->data);
iface->data = NULL;
}
void mg_lwip_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_lwip_if_remove_conn(struct mg_connection *nc) {
struct mg_ev_mgr_lwip_data *md =
(struct mg_ev_mgr_lwip_data *) nc->iface->data;
/* Walk the queue and null-out further signals for this conn. */
for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) {
if (md->sig_queue[i].nc == nc) {
md->sig_queue[i].sig = MG_SIG_TOMBSTONE;
}
}
}
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
int n = 0;
double now = mg_time();
struct mg_connection *nc, *tmp;
double min_timer = 0;
int num_timers = 0;
#if 0
DBG(("begin poll @%u", (unsigned int) (now * 1000)));
#endif
mg_ev_mgr_lwip_process_signals(mgr);
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
tmp = nc->next;
n++;
if (!mg_if_poll(nc, now)) continue;
if (nc->sock != INVALID_SOCKET &&
!(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL &&
cs->pcb.tcp->unsent != NULL) {
mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, cs->pcb.tcp);
}
if (nc->ev_timer_time > 0) {
if (num_timers == 0 || nc->ev_timer_time < min_timer) {
min_timer = nc->ev_timer_time;
}
num_timers++;
}
if (nc->sock != INVALID_SOCKET) {
if (mg_lwip_if_can_send(nc, cs)) {
mg_if_can_send_cb(nc);
mbuf_trim(&nc->send_mbuf);
}
if (cs->rx_chain != NULL) {
mg_if_can_recv_cb(nc);
} else if (cs->draining_rx_chain) {
/*
* If the connection is about to close, and rx_chain is finally empty,
* send the MG_SIG_CLOSE_CONN signal
*/
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
}
}
#if 0
DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms",
(unsigned int) (now * 1000), n, num_timers,
(unsigned int) (min_timer * 1000), timeout_ms));
#endif
(void) timeout_ms;
return now;
}
#endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
-731
View File
@@ -1,731 +0,0 @@
#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
#include "common/mg_mem.h"
#include <lwip/init.h>
#include <lwip/pbuf.h>
#include <lwip/tcp.h>
#include <lwip/tcpip.h>
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
#include <lwip/priv/tcp_priv.h> /* For tcp_seg */
#include <lwip/priv/tcpip_priv.h> /* For tcpip_api_call */
#else
#include <lwip/tcp_impl.h>
#endif
#include <lwip/udp.h>
#include "common/cs_dbg.h"
/*
* Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip,
* even older have nothing.
*/
#ifndef ip_2_ip4
#ifdef ipX_2_ip
#define ip_2_ip4(addr) ipX_2_ip(addr)
#else
#define ip_2_ip4(addr) (addr)
#endif
#endif
/*
* Depending on whether Mongoose is compiled with ipv6 support, use right
* lwip functions
*/
#if MG_ENABLE_IPV6
#define TCP_NEW tcp_new_ip6
#define TCP_BIND tcp_bind_ip6
#define UDP_BIND udp_bind_ip6
#define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
#define SET_ADDR(dst, src) \
memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
sizeof((dst)->sin6.sin6_addr.s6_addr))
#else
#define TCP_NEW tcp_new
#define TCP_BIND tcp_bind
#define UDP_BIND udp_bind
#define IPADDR_NTOA ipaddr_ntoa
#define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr
#endif
#if !NO_SYS
#if LWIP_TCPIP_CORE_LOCKING
/* With locking tcpip_api_call is just a function call wrapped in lock/unlock,
* so we can get away with just casting. */
void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) {
tcpip_api_call((tcpip_api_call_fn) fn, (struct tcpip_api_call_data *) arg);
}
#else
static sys_sem_t s_tcpip_call_lock_sem = NULL;
static sys_sem_t s_tcpip_call_sync_sem = NULL;
struct mg_lwip_netif_tcpip_call_ctx {
void (*fn)(void *);
void *arg;
};
static void xxx_tcpip(void *arg) {
struct mg_lwip_netif_tcpip_call_ctx *ctx =
(struct mg_lwip_netif_tcpip_call_ctx *) arg;
ctx->fn(ctx->arg);
sys_sem_signal(&s_tcpip_call_sync_sem);
}
void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) {
struct mg_lwip_netif_tcpip_call_ctx ctx = {.fn = fn, .arg = arg};
sys_arch_sem_wait(&s_tcpip_call_lock_sem, 0);
tcpip_send_msg_wait_sem(xxx_tcpip, &ctx, &s_tcpip_call_sync_sem);
sys_sem_signal(&s_tcpip_call_lock_sem);
}
#endif
#else
#define mg_lwip_netif_run_on_tcpip(fn, arg) (fn)(arg)
#endif
void mg_lwip_if_init(struct mg_iface *iface);
void mg_lwip_if_free(struct mg_iface *iface);
void mg_lwip_if_add_conn(struct mg_connection *nc);
void mg_lwip_if_remove_conn(struct mg_connection *nc);
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms);
// If compiling for Mongoose OS.
#ifdef MGOS
extern void mgos_lock();
extern void mgos_unlock();
#else
#define mgos_lock()
#define mgos_unlock()
#endif
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p);
#if LWIP_TCP_KEEPALIVE
void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
int interval, int count) {
if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) {
return;
}
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (idle > 0 && interval > 0 && count > 0) {
tpcb->keep_idle = idle * 1000;
tpcb->keep_intvl = interval * 1000;
tpcb->keep_cnt = count;
tpcb->so_options |= SOF_KEEPALIVE;
} else {
tpcb->so_options &= ~SOF_KEEPALIVE;
}
}
#elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
#warning LWIP TCP keepalive is disabled. Please consider enabling it.
#endif /* LWIP_TCP_KEEPALIVE */
static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
tpcb->remote_port, (int) err));
if (nc == NULL) {
tcp_abort(tpcb);
return ERR_ARG;
}
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
cs->err = err;
#if LWIP_TCP_KEEPALIVE
if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6);
#endif
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
return ERR_OK;
}
static void mg_lwip_tcp_error_cb(void *arg, err_t err) {
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p conn error %d", nc, (int) err));
if (nc == NULL || (nc->flags & MG_F_CLOSE_IMMEDIATELY)) return;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
cs->pcb.tcp = NULL; /* Has already been deallocated */
if (nc->flags & MG_F_CONNECTING) {
cs->err = err;
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
} else {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
}
static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb,
struct pbuf *p, err_t err) {
struct mg_connection *nc = (struct mg_connection *) arg;
struct mg_lwip_conn_state *cs =
(nc ? (struct mg_lwip_conn_state *) nc->sock : NULL);
DBG(("%p %p %p %p %u %d", nc, cs, tpcb, p, (p != NULL ? p->tot_len : 0),
(int) err));
if (p == NULL) {
if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
if (cs->rx_chain != NULL) {
/*
* rx_chain still contains non-consumed data, don't close the
* connection
*/
cs->draining_rx_chain = 1;
} else {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
} else {
/* Tombstoned connection, do nothing. */
}
return ERR_OK;
} else if (nc == NULL) {
tcp_abort(tpcb);
return ERR_ARG;
}
/*
* If we get a chain of more than one segment at once, we need to bump
* refcount on the subsequent bufs to make them independent.
*/
if (p->next != NULL) {
struct pbuf *q = p->next;
for (; q != NULL; q = q->next) pbuf_ref(q);
}
mgos_lock();
if (cs->rx_chain == NULL) {
cs->rx_offset = 0;
} else if (pbuf_clen(cs->rx_chain) >= 4) {
/* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX
* will be completely blocked. We already have at least 4 in the chain,
* this one is the last, so we have to make a copy and release this one. */
struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
if (np != NULL) {
pbuf_copy(np, p);
pbuf_free(p);
p = np;
}
}
mg_lwip_recv_common(nc, p);
mgos_unlock();
(void) err;
return ERR_OK;
}
static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb,
u16_t num_sent) {
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p %p %u %p %p", nc, tpcb, num_sent, tpcb->unsent, tpcb->unacked));
if (nc == NULL) return ERR_OK;
if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) &&
nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) {
mg_lwip_mgr_schedule_poll(nc->mgr);
}
(void) num_sent;
return ERR_OK;
}
struct mg_lwip_if_connect_tcp_ctx {
struct mg_connection *nc;
const union socket_address *sa;
};
static void mg_lwip_if_connect_tcp_tcpip(void *arg) {
struct mg_lwip_if_connect_tcp_ctx *ctx =
(struct mg_lwip_if_connect_tcp_ctx *) arg;
struct mg_connection *nc = ctx->nc;
const union socket_address *sa = ctx->sa;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = TCP_NEW();
cs->pcb.tcp = tpcb;
ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
u16_t port = ntohs(sa->sin.sin_port);
tcp_arg(tpcb, nc);
tcp_err(tpcb, mg_lwip_tcp_error_cb);
tcp_sent(tpcb, mg_lwip_tcp_sent_cb);
tcp_recv(tpcb, mg_lwip_tcp_recv_cb);
cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */);
DBG(("%p tcp_bind = %d", nc, (int) cs->err));
if (cs->err != ERR_OK) {
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
return;
}
cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb);
DBG(("%p tcp_connect %p = %d", nc, tpcb, (int) cs->err));
if (cs->err != ERR_OK) {
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
return;
}
}
void mg_lwip_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa};
mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_tcp_tcpip, &ctx);
}
/*
* Lwip included in the SDKs for nRF5x chips has different type for the
* callback of `udp_recv()`
*/
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
const ip_addr_t *addr, u16_t port)
#else
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
ip_addr_t *addr, u16_t port)
#endif
{
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len));
/* Put address in a separate pbuf and tack it onto the packet. */
struct pbuf *sap =
pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM);
if (sap == NULL) {
pbuf_free(p);
return;
}
union socket_address *sa = (union socket_address *) sap->payload;
#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr;
#else
sa->sin.sin_addr.s_addr = addr->addr;
#endif
sa->sin.sin_port = htons(port);
/* Logic in the recv handler requires that there be exactly one data pbuf. */
p = pbuf_coalesce(p, PBUF_RAW);
pbuf_chain(sap, p);
mgos_lock();
mg_lwip_recv_common(nc, sap);
mgos_unlock();
(void) pcb;
}
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (cs->rx_chain == NULL) {
cs->rx_chain = p;
} else {
pbuf_chain(cs->rx_chain, p);
}
if (!cs->recv_pending) {
cs->recv_pending = 1;
mg_lwip_post_signal(MG_SIG_RECV, nc);
}
}
static int mg_lwip_if_udp_recv(struct mg_connection *nc, void *buf, size_t len,
union socket_address *sa, size_t *sa_len) {
/*
* For UDP, RX chain consists of interleaved address and packet bufs:
* Address pbuf followed by exactly one data pbuf (recv_cb took care of that).
*/
int res = 0;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET) return -1;
mgos_lock();
if (cs->rx_chain != NULL) {
struct pbuf *ap = cs->rx_chain;
struct pbuf *dp = ap->next;
cs->rx_chain = pbuf_dechain(dp);
res = MIN(dp->len, len);
pbuf_copy_partial(dp, buf, res, 0);
pbuf_free(dp);
pbuf_copy_partial(ap, sa, MIN(*sa_len, ap->len), 0);
pbuf_free(ap);
}
mgos_unlock();
return res;
}
static void mg_lwip_if_connect_udp_tcpip(void *arg) {
struct mg_connection *nc = (struct mg_connection *) arg;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct udp_pcb *upcb = udp_new();
cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */);
DBG(("%p udp_bind %p = %d", nc, upcb, (int) cs->err));
if (cs->err == ERR_OK) {
udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
cs->pcb.udp = upcb;
} else {
udp_remove(upcb);
}
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
}
void mg_lwip_if_connect_udp(struct mg_connection *nc) {
mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_udp_tcpip, nc);
}
static void tcp_close_tcpip(void *arg) {
tcp_close((struct tcp_pcb *) arg);
}
void mg_lwip_handle_accept(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (cs->pcb.tcp == NULL) return;
union socket_address sa;
struct tcp_pcb *tpcb = cs->pcb.tcp;
SET_ADDR(&sa, &tpcb->remote_ip);
sa.sin.sin_port = htons(tpcb->remote_port);
mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin));
}
static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) {
struct mg_connection *lc = (struct mg_connection *) arg, *nc;
struct mg_lwip_conn_state *lcs, *cs;
struct tcp_pcb_listen *lpcb;
LOG(LL_DEBUG,
("%p conn %p from %s:%u", lc, newtpcb,
IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
if (lc == NULL) {
tcp_abort(newtpcb);
return ERR_ABRT;
}
lcs = (struct mg_lwip_conn_state *) lc->sock;
lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp;
#if TCP_LISTEN_BACKLOG
tcp_accepted(lpcb);
#endif
nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
tcp_abort(newtpcb);
return ERR_ABRT;
}
cs = (struct mg_lwip_conn_state *) nc->sock;
cs->lc = lc;
cs->pcb.tcp = newtpcb;
/* We need to set up callbacks before returning because data may start
* arriving immediately. */
tcp_arg(newtpcb, nc);
tcp_err(newtpcb, mg_lwip_tcp_error_cb);
tcp_sent(newtpcb, mg_lwip_tcp_sent_cb);
tcp_recv(newtpcb, mg_lwip_tcp_recv_cb);
#if LWIP_TCP_KEEPALIVE
mg_lwip_set_keepalive_params(nc, 60, 10, 6);
#endif
mg_lwip_post_signal(MG_SIG_ACCEPT, nc);
(void) err;
(void) lpcb;
return ERR_OK;
}
struct mg_lwip_if_listen_ctx {
struct mg_connection *nc;
union socket_address *sa;
int ret;
};
static void mg_lwip_if_listen_tcp_tcpip(void *arg) {
struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
struct mg_connection *nc = ctx->nc;
union socket_address *sa = ctx->sa;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = TCP_NEW();
ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
u16_t port = ntohs(sa->sin.sin_port);
cs->err = TCP_BIND(tpcb, ip, port);
DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, (int) cs->err));
if (cs->err != ERR_OK) {
tcp_close(tpcb);
ctx->ret = -1;
return;
}
tcp_arg(tpcb, nc);
tpcb = tcp_listen(tpcb);
cs->pcb.tcp = tpcb;
tcp_accept(tpcb, mg_lwip_accept_cb);
ctx->ret = 0;
}
int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_tcp_tcpip, &ctx);
return ctx.ret;
}
static void mg_lwip_if_listen_udp_tcpip(void *arg) {
struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
struct mg_connection *nc = ctx->nc;
union socket_address *sa = ctx->sa;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct udp_pcb *upcb = udp_new();
ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
u16_t port = ntohs(sa->sin.sin_port);
cs->err = UDP_BIND(upcb, ip, port);
DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, (int) cs->err));
if (cs->err != ERR_OK) {
udp_remove(upcb);
ctx->ret = -1;
} else {
udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
cs->pcb.udp = upcb;
ctx->ret = 0;
}
}
int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_udp_tcpip, &ctx);
return ctx.ret;
}
struct mg_lwip_tcp_write_ctx {
struct mg_connection *nc;
const void *data;
uint16_t len;
int ret;
};
static void tcp_output_tcpip(void *arg) {
tcp_output((struct tcp_pcb *) arg);
}
static void mg_lwip_tcp_write_tcpip(void *arg) {
struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg;
struct mg_connection *nc = ctx->nc;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = cs->pcb.tcp;
size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf));
size_t unsent, unacked;
if (len == 0) {
DBG(("%p no buf avail %u %u %p %p", tpcb, tpcb->snd_buf, tpcb->snd_queuelen,
tpcb->unsent, tpcb->unacked));
mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, tpcb);
ctx->ret = 0;
return;
}
unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
/*
* On ESP8266 we only allow one TCP segment in flight at any given time.
* This may increase latency and reduce efficiency of tcp windowing,
* but memory is scarce and precious on that platform so we do this to
* reduce footprint.
*/
#if CS_PLATFORM == CS_P_ESP8266
if (unacked > 0) {
ctx->ret = 0;
return;
}
len = MIN(len, (TCP_MSS - unsent));
#endif
cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY);
unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
DBG(("%p tcp_write %u = %d, %u %u",
tpcb, len, (int) cs->err, unsent, unacked));
if (cs->err != ERR_OK) {
/*
* We ignore ERR_MEM because memory will be freed up when the data is sent
* and we'll retry.
*/
ctx->ret = (cs->err == ERR_MEM ? 0 : -1);
return;
}
ctx->ret = len;
(void) unsent;
(void) unacked;
}
int mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = buf, .len = len};
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET) return -1;
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (tpcb == NULL) return -1;
if (tpcb->snd_buf <= 0) return 0;
mg_lwip_netif_run_on_tcpip(mg_lwip_tcp_write_tcpip, &ctx);
return ctx.ret;
}
struct udp_sendto_ctx {
struct udp_pcb *upcb;
struct pbuf *p;
ip_addr_t *ip;
uint16_t port;
int ret;
};
static void udp_sendto_tcpip(void *arg) {
struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg;
ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port);
}
static int mg_lwip_if_udp_send(struct mg_connection *nc, const void *data,
size_t len) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) return -1;
struct udp_pcb *upcb = cs->pcb.udp;
struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
#if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6
ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0};
#else
ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr};
#endif
u16_t port = ntohs(nc->sa.sin.sin_port);
if (p == NULL) return 0;
memcpy(p->payload, data, len);
struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port};
mg_lwip_netif_run_on_tcpip(udp_sendto_tcpip, &ctx);
cs->err = ctx.ret;
pbuf_free(p);
return (cs->err == ERR_OK ? (int) len : -2);
}
static int mg_lwip_if_can_send(struct mg_connection *nc,
struct mg_lwip_conn_state *cs) {
int can_send = 0;
if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) {
/* We have stuff to send, but can we? */
if (nc->flags & MG_F_UDP) {
/* UDP is always ready for sending. */
can_send = (cs->pcb.udp != NULL);
} else {
can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0);
/* See comment above. */
#if CS_PLATFORM == CS_P_ESP8266
if (cs->pcb.tcp->unacked != NULL) can_send = 0;
#endif
}
}
return can_send;
}
struct tcp_recved_ctx {
struct tcp_pcb *tpcb;
size_t len;
};
void tcp_recved_tcpip(void *arg) {
struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg;
if (ctx->tpcb != NULL) tcp_recved(ctx->tpcb, ctx->len);
}
static int mg_lwip_if_tcp_recv(struct mg_connection *nc, void *buf,
size_t len) {
int res = 0;
char *bufp = buf;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET) return -1;
mgos_lock();
while (cs->rx_chain != NULL && len > 0) {
struct pbuf *seg = cs->rx_chain;
size_t seg_len = (seg->len - cs->rx_offset);
size_t copy_len = MIN(len, seg_len);
pbuf_copy_partial(seg, bufp, copy_len, cs->rx_offset);
len -= copy_len;
res += copy_len;
bufp += copy_len;
cs->rx_offset += copy_len;
if (cs->rx_offset == cs->rx_chain->len) {
cs->rx_chain = pbuf_dechain(cs->rx_chain);
pbuf_free(seg);
cs->rx_offset = 0;
}
}
mgos_unlock();
if (res > 0) {
struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = res};
mg_lwip_netif_run_on_tcpip(tcp_recved_tcpip, &ctx);
}
return res;
}
int mg_lwip_if_create_conn(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs =
(struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs));
if (cs == NULL) return 0;
cs->nc = nc;
nc->sock = (intptr_t) cs;
return 1;
}
static void udp_remove_tcpip(void *arg) {
udp_remove((struct udp_pcb *) arg);
}
void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (!(nc->flags & MG_F_UDP)) {
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (tpcb != NULL) {
tcp_arg(tpcb, NULL);
DBG(("%p tcp_close %p", nc, tpcb));
tcp_arg(tpcb, NULL);
mg_lwip_netif_run_on_tcpip(tcp_close_tcpip, tpcb);
}
while (cs->rx_chain != NULL) {
struct pbuf *seg = cs->rx_chain;
cs->rx_chain = pbuf_dechain(cs->rx_chain);
pbuf_free(seg);
}
memset(cs, 0, sizeof(*cs));
MG_FREE(cs);
} else if (nc->listener == NULL) {
/* Only close outgoing UDP pcb or listeners. */
struct udp_pcb *upcb = cs->pcb.udp;
if (upcb != NULL) {
DBG(("%p udp_remove %p", nc, upcb));
mg_lwip_netif_run_on_tcpip(udp_remove_tcpip, upcb);
}
memset(cs, 0, sizeof(*cs));
MG_FREE(cs);
}
nc->sock = INVALID_SOCKET;
}
void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
memset(sa, 0, sizeof(*sa));
if (nc == NULL || nc->sock == INVALID_SOCKET) return;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->flags & MG_F_UDP) {
struct udp_pcb *upcb = cs->pcb.udp;
if (remote) {
memcpy(sa, &nc->sa, sizeof(*sa));
} else if (upcb != NULL) {
sa->sin.sin_port = htons(upcb->local_port);
SET_ADDR(sa, &upcb->local_ip);
}
} else {
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (remote) {
memcpy(sa, &nc->sa, sizeof(*sa));
} else if (tpcb != NULL) {
sa->sin.sin_port = htons(tpcb->local_port);
SET_ADDR(sa, &tpcb->local_ip);
}
}
}
void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) {
nc->sock = sock;
}
/* clang-format off */
#define MG_LWIP_IFACE_VTABLE \
{ \
mg_lwip_if_init, \
mg_lwip_if_free, \
mg_lwip_if_add_conn, \
mg_lwip_if_remove_conn, \
mg_lwip_if_poll, \
mg_lwip_if_listen_tcp, \
mg_lwip_if_listen_udp, \
mg_lwip_if_connect_tcp, \
mg_lwip_if_connect_udp, \
mg_lwip_if_tcp_send, \
mg_lwip_if_udp_send, \
mg_lwip_if_tcp_recv, \
mg_lwip_if_udp_recv, \
mg_lwip_if_create_conn, \
mg_lwip_if_destroy_conn, \
mg_lwip_if_sock_set, \
mg_lwip_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
@@ -1,49 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
#define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
#ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
#define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
#endif
#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
#include <stdint.h>
extern const struct mg_iface_vtable mg_lwip_iface_vtable;
struct mg_lwip_conn_state {
struct mg_connection *nc;
struct mg_connection *lc;
union {
struct tcp_pcb *tcp;
struct udp_pcb *udp;
} pcb;
err_t err;
size_t num_sent; /* Number of acknowledged bytes to be reported to the core */
struct pbuf *rx_chain; /* Chain of incoming data segments. */
size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */
/* Last SSL write size, for retries. */
int last_ssl_write_size;
/* Whether MG_SIG_RECV is already pending for this connection */
int recv_pending;
/* Whether the connection is about to close, just `rx_chain` needs to drain */
int draining_rx_chain;
};
enum mg_sig_type {
MG_SIG_CONNECT_RESULT = 1,
MG_SIG_RECV = 2,
MG_SIG_CLOSE_CONN = 3,
MG_SIG_TOMBSTONE = 4,
MG_SIG_ACCEPT = 5,
};
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc);
/* To be implemented by the platform. */
void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr);
#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
#endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */
-14
View File
@@ -1,14 +0,0 @@
#if CS_PLATFORM == CS_P_MSP432
#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Clock.h>
int gettimeofday(struct timeval *tp, void *tzp) {
uint32_t ticks = Clock_getTicks();
tp->tv_sec = ticks / 1000;
tp->tv_usec = (ticks % 1000) * 1000;
return 0;
}
#endif /* CS_PLATFORM == CS_P_MSP432 */
-10
View File
@@ -1,10 +0,0 @@
#if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
defined(__ARMCC_VERSION)
int gettimeofday(struct timeval *tp, void *tzp) {
/* TODO */
tp->tv_sec = 0;
tp->tv_usec = 0;
return 0;
}
#endif
-288
View File
@@ -1,288 +0,0 @@
#if MG_ENABLE_NET_IF_PIC32
int mg_pic32_if_create_conn(struct mg_connection *nc) {
(void) nc;
return 1;
}
void mg_pic32_if_recved(struct mg_connection *nc, size_t len) {
(void) nc;
(void) len;
}
void mg_pic32_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_pic32_if_init(struct mg_iface *iface) {
(void) iface;
(void) mg_get_errno(); /* Shutup compiler */
}
void mg_pic32_if_free(struct mg_iface *iface) {
(void) iface;
}
void mg_pic32_if_remove_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_pic32_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
/* For UDP, only close outgoing sockets or listeners. */
if (!(nc->flags & MG_F_UDP)) {
/* Close TCP */
TCPIP_TCP_Close((TCP_SOCKET) nc->sock);
} else if (nc->listener == NULL) {
/* Only close outgoing UDP or listeners. */
TCPIP_UDP_Close((UDP_SOCKET) nc->sock);
}
nc->sock = INVALID_SOCKET;
}
int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
nc->sock = TCPIP_UDP_ServerOpen(
sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(sa->sin.sin_port),
sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
if (nc->sock == INVALID_SOCKET) {
return -1;
}
return 0;
}
void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf,
size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf,
size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
nc->sock = TCPIP_TCP_ServerOpen(
sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(sa->sin.sin_port),
sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
memcpy(&nc->sa, sa, sizeof(*sa));
if (nc->sock == INVALID_SOCKET) {
return -1;
}
return 0;
}
static int mg_accept_conn(struct mg_connection *lc) {
struct mg_connection *nc;
TCP_SOCKET_INFO si;
union socket_address sa;
nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
return 0;
}
nc->sock = lc->sock;
nc->flags &= ~MG_F_LISTENING;
if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) {
return 0;
}
if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
sa.sin.sin_family = AF_INET;
sa.sin.sin_port = htons(si.remotePort);
sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
} else {
/* TODO(alashkin): do something with _potential_ IPv6 */
memset(&sa, 0, sizeof(sa));
}
mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa));
return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0;
}
char *inet_ntoa(struct in_addr in) {
static char addr[17];
snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1,
(int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3,
(int) in.S_un.S_un_b.s_b4);
return addr;
}
static void mg_handle_send(struct mg_connection *nc) {
uint16_t bytes_written = 0;
if (nc->flags & MG_F_UDP) {
if (!TCPIP_UDP_RemoteBind(
(UDP_SOCKET) nc->sock,
nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0);
if (bytes_written >= nc->send_mbuf.len) {
if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock,
(uint8_t *) nc->send_mbuf.buf,
nc->send_mbuf.len) != nc->send_mbuf.len) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
bytes_written = 0;
}
}
} else {
bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock);
if (bytes_written != 0) {
if (bytes_written > nc->send_mbuf.len) {
bytes_written = nc->send_mbuf.len;
}
if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock,
(uint8_t *) nc->send_mbuf.buf,
bytes_written) != bytes_written) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
bytes_written = 0;
}
}
}
mg_if_sent_cb(nc, bytes_written);
}
static void mg_handle_recv(struct mg_connection *nc) {
uint16_t bytes_read = 0;
uint8_t *buf = NULL;
if (nc->flags & MG_F_UDP) {
bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock);
if (bytes_read != 0 &&
(nc->recv_mbuf_limit == -1 ||
nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) {
buf = (uint8_t *) MG_MALLOC(bytes_read);
if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) !=
bytes_read) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
bytes_read = 0;
MG_FREE(buf);
}
}
} else {
bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock);
if (bytes_read != 0) {
if (nc->recv_mbuf_limit != -1 &&
nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) {
bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len;
}
buf = (uint8_t *) MG_MALLOC(bytes_read);
if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) !=
bytes_read) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
MG_FREE(buf);
bytes_read = 0;
}
}
}
if (bytes_read != 0) {
mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */);
}
}
time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
double now = mg_time();
struct mg_connection *nc, *tmp;
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
if (nc->flags & MG_F_CONNECTING) {
/* processing connections */
if (nc->flags & MG_F_UDP ||
TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
mg_if_connect_cb(nc, 0);
}
} else if (nc->flags & MG_F_LISTENING) {
if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
/* accept new connections */
mg_accept_conn(nc);
}
} else {
if (nc->send_mbuf.len != 0) {
mg_handle_send(nc);
}
if (nc->recv_mbuf_limit == -1 ||
nc->recv_mbuf.len < nc->recv_mbuf_limit) {
mg_handle_recv(nc);
}
}
}
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
(nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
mg_close_conn(nc);
}
}
return now;
}
void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) {
nc->sock = sock;
}
void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
/* TODO(alaskin): not implemented yet */
}
void mg_pic32_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
nc->sock = TCPIP_TCP_ClientOpen(
sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin);
nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
}
void mg_pic32_if_connect_udp(struct mg_connection *nc) {
nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
}
/* clang-format off */
#define MG_PIC32_IFACE_VTABLE \
{ \
mg_pic32_if_init, \
mg_pic32_if_free, \
mg_pic32_if_add_conn, \
mg_pic32_if_remove_conn, \
mg_pic32_if_poll, \
mg_pic32_if_listen_tcp, \
mg_pic32_if_listen_udp, \
mg_pic32_if_connect_tcp, \
mg_pic32_if_connect_udp, \
mg_pic32_if_tcp_send, \
mg_pic32_if_udp_send, \
mg_pic32_if_recved, \
mg_pic32_if_create_conn, \
mg_pic32_if_destroy_conn, \
mg_pic32_if_sock_set, \
mg_pic32_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_PIC32
const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_PIC32 */
-21
View File
@@ -1,21 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
#define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
#include "mongoose/src/net_if.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef MG_ENABLE_NET_IF_PIC32
#define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
#endif
extern const struct mg_iface_vtable mg_pic32_iface_vtable;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */
-42
View File
@@ -1,42 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_
#define CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_
#if CS_PLATFORM == CS_P_CC3100
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#define MG_NET_IF MG_NET_IF_SIMPLELINK
#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
/*
* CC3100 SDK and STM32 SDK include headers w/out path, just like
* #include "simplelink.h". As result, we have to add all required directories
* into Makefile IPATH and do the same thing (include w/out path)
*/
#include <simplelink.h>
#include <netapp.h>
#undef timeval
typedef int sock_t;
#define INVALID_SOCKET (-1)
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT PRId64
#define INT64_X_FMT PRIx64
#define SIZE_T_FMT "u"
#define SOMAXCONN 8
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
char *inet_ntoa(struct in_addr in);
int inet_pton(int af, const char *src, void *dst);
#endif /* CS_PLATFORM == CS_P_CC3100 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ */
-118
View File
@@ -1,118 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_
#define CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_
#if CS_PLATFORM == CS_P_CC3200
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#ifndef __TI_COMPILER_VERSION__
#include <fcntl.h>
#include <sys/time.h>
#endif
#define MG_NET_IF MG_NET_IF_SIMPLELINK
#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
/* Only SPIFFS supports directories, SLFS does not. */
#if defined(CC3200_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING)
#define MG_ENABLE_DIRECTORY_LISTING 1
#endif
#include "common/platforms/simplelink/cs_simplelink.h"
typedef int sock_t;
#define INVALID_SOCKET (-1)
#define SIZE_T_FMT "u"
typedef struct stat cs_stat_t;
#define DIRSEP '/'
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT PRId64
#define INT64_X_FMT PRIx64
#define __cdecl
#define fileno(x) -1
/* Some functions we implement for Mongoose. */
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __TI_COMPILER_VERSION__
struct SlTimeval_t;
#define timeval SlTimeval_t
int gettimeofday(struct timeval *t, void *tz);
int settimeofday(const struct timeval *tv, const void *tz);
int asprintf(char **strp, const char *fmt, ...);
#endif
/* TI's libc does not have stat & friends, add them. */
#ifdef __TI_COMPILER_VERSION__
#include <file.h>
typedef unsigned int mode_t;
typedef size_t _off_t;
typedef long ssize_t;
struct stat {
int st_ino;
mode_t st_mode;
int st_nlink;
time_t st_mtime;
off_t st_size;
};
int _stat(const char *pathname, struct stat *st);
int stat(const char *pathname, struct stat *st);
#define __S_IFMT 0170000
#define __S_IFDIR 0040000
#define __S_IFCHR 0020000
#define __S_IFREG 0100000
#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask))
#define S_IFDIR __S_IFDIR
#define S_IFCHR __S_IFCHR
#define S_IFREG __S_IFREG
#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR)
#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
/* 5.x series compilers don't have va_copy, 16.x do. */
#if __TI_COMPILER_VERSION__ < 16000000
#define va_copy(apc, ap) ((apc) = (ap))
#endif
#endif /* __TI_COMPILER_VERSION__ */
#ifdef CC3200_FS_SLFS
#define MG_FS_SLFS
#endif
#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \
!defined(MG_ENABLE_FILESYSTEM)
#define MG_ENABLE_FILESYSTEM 1
#define CS_DEFINE_DIRENT
#endif
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#ifdef __cplusplus
}
#endif
#endif /* CS_PLATFORM == CS_P_CC3200 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */
-105
View File
@@ -1,105 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3220_H_
#define CS_COMMON_PLATFORMS_PLATFORM_CC3220_H_
#if CS_PLATFORM == CS_P_CC3220
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#ifndef __TI_COMPILER_VERSION__
#include <fcntl.h>
#include <sys/time.h>
#endif
#define MG_NET_IF MG_NET_IF_SIMPLELINK
#ifndef MG_SSL_IF
#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
#endif
/* Only SPIFFS supports directories, SLFS does not. */
#if defined(CC3220_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING)
#define MG_ENABLE_DIRECTORY_LISTING 1
#endif
#include "common/platforms/simplelink/cs_simplelink.h"
typedef int sock_t;
#define INVALID_SOCKET (-1)
#define SIZE_T_FMT "u"
typedef struct stat cs_stat_t;
#define DIRSEP '/'
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT PRId64
#define INT64_X_FMT PRIx64
#define __cdecl
#define fileno(x) -1
/* Some functions we implement for Mongoose. */
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __TI_COMPILER_VERSION__
struct SlTimeval_t;
#define timeval SlTimeval_t
int gettimeofday(struct timeval *t, void *tz);
int settimeofday(const struct timeval *tv, const void *tz);
int asprintf(char **strp, const char *fmt, ...);
#endif
/* TI's libc does not have stat & friends, add them. */
#ifdef __TI_COMPILER_VERSION__
#include <file.h>
typedef unsigned int mode_t;
typedef size_t _off_t;
typedef long ssize_t;
struct stat {
int st_ino;
mode_t st_mode;
int st_nlink;
time_t st_mtime;
off_t st_size;
};
int _stat(const char *pathname, struct stat *st);
int stat(const char *pathname, struct stat *st);
#define __S_IFMT 0170000
#define __S_IFDIR 0040000
#define __S_IFCHR 0020000
#define __S_IFREG 0100000
#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask))
#define S_IFDIR __S_IFDIR
#define S_IFCHR __S_IFCHR
#define S_IFREG __S_IFREG
#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR)
#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
#endif /* __TI_COMPILER_VERSION__ */
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#ifdef __cplusplus
}
#endif
#endif /* CS_PLATFORM == CS_P_CC3220 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */
-38
View File
@@ -1,38 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_
#define CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_
#if CS_PLATFORM == CS_P_ESP32
#include <assert.h>
#include <ctype.h>
#include <dirent.h>
#include <fcntl.h>
#include <inttypes.h>
#include <machine/endian.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#define SIZE_T_FMT "u"
typedef struct stat cs_stat_t;
#define DIRSEP '/'
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT PRId64
#define INT64_X_FMT PRIx64
#define __cdecl
#define _FILE_OFFSET_BITS 32
#define MG_LWIP 1
#ifndef MG_NET_IF
#define MG_NET_IF MG_NET_IF_SOCKET
#endif
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#endif /* CS_PLATFORM == CS_P_ESP32 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ */
-54
View File
@@ -1,54 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_
#define CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_
#if CS_PLATFORM == CS_P_ESP8266
#include <assert.h>
#include <ctype.h>
#include <fcntl.h>
#include <inttypes.h>
#include <machine/endian.h>
#include <stdbool.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#define SIZE_T_FMT "u"
typedef struct stat cs_stat_t;
#define DIRSEP '/'
#if !defined(MGOS_VFS_DEFINE_DIRENT)
#define CS_DEFINE_DIRENT
#endif
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT PRId64
#define INT64_X_FMT PRIx64
#define __cdecl
#define _FILE_OFFSET_BITS 32
#define MG_LWIP 1
/* struct timeval is defined in sys/time.h. */
#define LWIP_TIMEVAL_PRIVATE 0
#ifndef MG_NET_IF
#include <lwip/opt.h>
#if LWIP_SOCKET /* RTOS SDK has LWIP sockets */
#define MG_NET_IF MG_NET_IF_SOCKET
#else
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
#endif
#endif
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#define inet_ntop(af, src, dst, size) \
(((af) == AF_INET) ? ipaddr_ntoa_r((const ip_addr_t *) (src), (dst), (size)) \
: NULL)
#define inet_pton(af, src, dst) \
(((af) == AF_INET) ? ipaddr_aton((src), (ip_addr_t *) (dst)) : 0)
#endif /* CS_PLATFORM == CS_P_ESP8266 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ */
-77
View File
@@ -1,77 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_MBED_H_
#define CS_COMMON_PLATFORMS_PLATFORM_MBED_H_
#if CS_PLATFORM == CS_P_MBED
/*
* mbed.h contains C++ code (e.g. templates), thus, it should be processed
* only if included directly to startup file (ex: main.cpp)
*/
#ifdef __cplusplus
#include "mbed.h"
#endif /* __cplusplus */
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
typedef struct stat cs_stat_t;
#define DIRSEP '/'
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
/*
* mbed can be compiled with the ARM compiler which
* just doesn't come with a gettimeofday shim
* because it's a BSD API and ARM targets embedded
* non-unix platforms.
*/
#if defined(__ARMCC_VERSION) || defined(__ICCARM__)
#define _TIMEVAL_DEFINED
#define gettimeofday _gettimeofday
/* copied from GCC on ARM; for some reason useconds are signed */
typedef long suseconds_t; /* microseconds (signed) */
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* and microseconds */
};
#endif
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
#define MG_SIMPLELINK_NO_OSI 1
#include <simplelink.h>
typedef int sock_t;
#define INVALID_SOCKET (-1)
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT PRId64
#define INT64_X_FMT PRIx64
#define SIZE_T_FMT "u"
#define SOMAXCONN 8
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
char *inet_ntoa(struct in_addr in);
int inet_pton(int af, const char *src, void *dst);
int inet_aton(const char *cp, struct in_addr *inp);
in_addr_t inet_addr(const char *cp);
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
#endif /* CS_PLATFORM == CS_P_MBED */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ */
-101
View File
@@ -1,101 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_
#define CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_
#if CS_PLATFORM == CS_P_MSP432
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#ifndef __TI_COMPILER_VERSION__
#include <fcntl.h>
#include <sys/time.h>
#endif
#define MG_NET_IF MG_NET_IF_SIMPLELINK
#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
#include "common/platforms/simplelink/cs_simplelink.h"
typedef int sock_t;
#define INVALID_SOCKET (-1)
#define SIZE_T_FMT "u"
typedef struct stat cs_stat_t;
#define DIRSEP '/'
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT PRId64
#define INT64_X_FMT PRIx64
#define __cdecl
#define fileno(x) -1
/* Some functions we implement for Mongoose. */
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __TI_COMPILER_VERSION__
struct SlTimeval_t;
#define timeval SlTimeval_t
int gettimeofday(struct timeval *t, void *tz);
#endif
/* TI's libc does not have stat & friends, add them. */
#ifdef __TI_COMPILER_VERSION__
#include <file.h>
typedef unsigned int mode_t;
typedef size_t _off_t;
typedef long ssize_t;
struct stat {
int st_ino;
mode_t st_mode;
int st_nlink;
time_t st_mtime;
off_t st_size;
};
int _stat(const char *pathname, struct stat *st);
#define stat(a, b) _stat(a, b)
#define __S_IFMT 0170000
#define __S_IFDIR 0040000
#define __S_IFCHR 0020000
#define __S_IFREG 0100000
#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask))
#define S_IFDIR __S_IFDIR
#define S_IFCHR __S_IFCHR
#define S_IFREG __S_IFREG
#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR)
#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
/* As of 5.2.7, TI compiler does not support va_copy() yet. */
#define va_copy(apc, ap) ((apc) = (ap))
#endif /* __TI_COMPILER_VERSION__ */
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \
!defined(MG_ENABLE_FILESYSTEM)
#define MG_ENABLE_FILESYSTEM 1
#endif
#ifdef __cplusplus
}
#endif
#endif /* CS_PLATFORM == CS_P_MSP432 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ */
-38
View File
@@ -1,38 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_
#define CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_
#if CS_PLATFORM == CS_P_NRF51
#include <assert.h>
#include <ctype.h>
#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#define to64(x) strtoll(x, NULL, 10)
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
#define MG_LWIP 1
#define MG_ENABLE_IPV6 1
/*
* For ARM C Compiler, make lwip to export `struct timeval`; for other
* compilers, suppress it.
*/
#if !defined(__ARMCC_VERSION)
#define LWIP_TIMEVAL_PRIVATE 0
#else
struct timeval;
int gettimeofday(struct timeval *tp, void *tzp);
#endif
#define INT64_FMT PRId64
#define SIZE_T_FMT "u"
/*
* ARM C Compiler doesn't have strdup, so we provide it
*/
#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION)
#endif /* CS_PLATFORM == CS_P_NRF51 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ */
-41
View File
@@ -1,41 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_
#define CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_
#if CS_PLATFORM == CS_P_NRF52
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#define to64(x) strtoll(x, NULL, 10)
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
#define MG_LWIP 1
#define MG_ENABLE_IPV6 1
#if !defined(ENOSPC)
#define ENOSPC 28 /* No space left on device */
#endif
/*
* For ARM C Compiler, make lwip to export `struct timeval`; for other
* compilers, suppress it.
*/
#if !defined(__ARMCC_VERSION)
#define LWIP_TIMEVAL_PRIVATE 0
#endif
#define INT64_FMT PRId64
#define SIZE_T_FMT "u"
/*
* ARM C Compiler doesn't have strdup, so we provide it
*/
#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION)
#endif /* CS_PLATFORM == CS_P_NRF52 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ */
@@ -1,27 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_
#define CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_
#if CS_PLATFORM == CS_P_NXP_KINETIS
#include <ctype.h>
#include <inttypes.h>
#include <string.h>
#include <sys/time.h>
#define SIZE_T_FMT "u"
typedef struct stat cs_stat_t;
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT "lld"
#define INT64_X_FMT "llx"
#define __cdecl
#define MG_LWIP 1
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
/* struct timeval is defined in sys/time.h. */
#define LWIP_TIMEVAL_PRIVATE 0
#endif /* CS_PLATFORM == CS_P_NXP_KINETIS */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ */
-49
View File
@@ -1,49 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_
#define CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_
#if CS_PLATFORM == CS_P_NXP_LPC
#include <ctype.h>
#include <stdint.h>
#include <string.h>
#define SIZE_T_FMT "u"
typedef struct stat cs_stat_t;
#define INT64_FMT "lld"
#define INT64_X_FMT "llx"
#define __cdecl
#define MG_LWIP 1
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
/*
* LPCXpress comes with 3 C library implementations: Newlib, NewlibNano and
*Redlib.
* See https://community.nxp.com/message/630860 for more details.
*
* Redlib is the default and lacks certain things, so we provide them.
*/
#ifdef __REDLIB_INTERFACE_VERSION__
/* Let LWIP define timeval for us. */
#define LWIP_TIMEVAL_PRIVATE 1
#define va_copy(d, s) __builtin_va_copy(d, s)
#define CS_ENABLE_TO64 1
#define to64(x) cs_to64(x)
#define CS_ENABLE_STRDUP 1
#else
#include <sys/time.h>
#define LWIP_TIMEVAL_PRIVATE 0
#define to64(x) strtoll(x, NULL, 10)
#endif
#endif /* CS_PLATFORM == CS_P_NXP_LPC */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ */
-33
View File
@@ -1,33 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_
#define CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_
#if CS_PLATFORM == CS_P_PIC32
#define MG_NET_IF MG_NET_IF_PIC32
#include <stdint.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
#include <system_config.h>
#include <system_definitions.h>
#include <sys/types.h>
typedef TCP_SOCKET sock_t;
#define to64(x) strtoll(x, NULL, 10)
#define SIZE_T_FMT "lu"
#define INT64_FMT "lld"
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
char *inet_ntoa(struct in_addr in);
#endif /* CS_PLATFORM == CS_P_PIC32 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ */
-45
View File
@@ -1,45 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_RS14100_H_
#define CS_COMMON_PLATFORMS_PLATFORM_RS14100_H_
#if CS_PLATFORM == CS_P_RS14100
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#ifdef MGOS_HAVE_VFS_COMMON
#include <mgos_vfs.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT "lld"
#define SIZE_T_FMT "u"
typedef struct stat cs_stat_t;
#define DIRSEP '/'
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#ifndef MG_ENABLE_FILESYSTEM
#define MG_ENABLE_FILESYSTEM 1
#endif
#ifdef __cplusplus
}
#endif
#endif /* CS_PLATFORM == CS_P_RS14100 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_RS14100_H_ */
-35
View File
@@ -1,35 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_STM32_H_
#define CS_COMMON_PLATFORMS_PLATFORM_STM32_H_
#if CS_PLATFORM == CS_P_STM32
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <dirent.h>
#include <stm32_sdk_hal.h>
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT "lld"
#define SIZE_T_FMT "u"
typedef struct stat cs_stat_t;
#define DIRSEP '/'
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#ifndef MG_ENABLE_FILESYSTEM
#define MG_ENABLE_FILESYSTEM 1
#endif
#endif /* CS_PLATFORM == CS_P_STM32 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ */
-53
View File
@@ -1,53 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_
#define CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_
#if CS_PLATFORM == CS_P_TM4C129
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#ifndef __TI_COMPILER_VERSION__
#include <fcntl.h>
#include <sys/time.h>
#endif
#define SIZE_T_FMT "u"
typedef struct stat cs_stat_t;
#define DIRSEP '/'
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT PRId64
#define INT64_X_FMT PRIx64
#define __cdecl
#ifndef MG_NET_IF
#include <lwip/opt.h>
#if LWIP_SOCKET
#define MG_NET_IF MG_NET_IF_SOCKET
#else
#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
#endif
#define MG_LWIP 1
#elif MG_NET_IF == MG_NET_IF_SIMPLELINK
#include "common/platforms/simplelink/cs_simplelink.h"
#endif
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#ifdef __TI_COMPILER_VERSION__
/* As of 5.2.8, TI compiler does not support va_copy() yet. */
#define va_copy(apc, ap) ((apc) = (ap))
#endif /* __TI_COMPILER_VERSION__ */
#ifdef __cplusplus
}
#endif
#endif /* CS_PLATFORM == CS_P_TM4C129 */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ */
-145
View File
@@ -1,145 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_
#define CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_
#if CS_PLATFORM == CS_P_UNIX
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 600
#endif
/* <inttypes.h> wants this for C++ */
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
/* C++ wants that for INT64_MAX */
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#endif
/* Enable fseeko() and ftello() functions */
#ifndef _LARGEFILE_SOURCE
#define _LARGEFILE_SOURCE
#endif
/* Enable 64-bit file offsets */
#ifndef _FILE_OFFSET_BITS
#define _FILE_OFFSET_BITS 64
#endif
#include <arpa/inet.h>
#include <assert.h>
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdint.h>
#include <limits.h>
#include <math.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#ifdef __APPLE__
#include <machine/endian.h>
#ifndef BYTE_ORDER
#define LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN
#define BIG_ENDIAN __DARWIN_BIG_ENDIAN
#define PDP_ENDIAN __DARWIN_PDP_ENDIAN
#define BYTE_ORDER __DARWIN_BYTE_ORDER
#endif
#endif
/*
* osx correctly avoids defining strtoll when compiling in strict ansi mode.
* c++ 11 standard defines strtoll as well.
* We require strtoll, and if your embedded pre-c99 compiler lacks one, please
* implement a shim.
*/
#if !(defined(__cplusplus) && __cplusplus >= 201103L) && \
!(defined(__DARWIN_C_LEVEL) && __DARWIN_C_LEVEL >= 200809L)
long long strtoll(const char *, char **, int);
#endif
typedef int sock_t;
#define INVALID_SOCKET (-1)
#define SIZE_T_FMT "zu"
typedef struct stat cs_stat_t;
#define DIRSEP '/'
#define to64(x) strtoll(x, NULL, 10)
#define INT64_FMT PRId64
#define INT64_X_FMT PRIx64
#ifndef __cdecl
#define __cdecl
#endif
#ifndef va_copy
#ifdef __va_copy
#define va_copy __va_copy
#else
#define va_copy(x, y) (x) = (y)
#endif
#endif
#define closesocket(x) close(x)
#ifndef MG_MAX_HTTP_REQUEST_SIZE
#define MG_MAX_HTTP_REQUEST_SIZE 8192
#endif
#ifndef MG_MAX_HTTP_SEND_MBUF
#define MG_MAX_HTTP_SEND_MBUF 4096
#endif
#ifndef MG_MAX_HTTP_HEADERS
#define MG_MAX_HTTP_HEADERS 40
#endif
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#ifndef MG_ENABLE_BROADCAST
#define MG_ENABLE_BROADCAST 1
#endif
#ifndef MG_ENABLE_DIRECTORY_LISTING
#define MG_ENABLE_DIRECTORY_LISTING 1
#endif
#ifndef MG_ENABLE_FILESYSTEM
#define MG_ENABLE_FILESYSTEM 1
#endif
#ifndef MG_ENABLE_HTTP_CGI
#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM
#endif
#ifndef MG_NET_IF
#define MG_NET_IF MG_NET_IF_SOCKET
#endif
#ifndef MG_HOSTS_FILE_NAME
#define MG_HOSTS_FILE_NAME "/etc/hosts"
#endif
#ifndef MG_RESOLV_CONF_FILE_NAME
#define MG_RESOLV_CONF_FILE_NAME "/etc/resolv.conf"
#endif
#endif /* CS_PLATFORM == CS_P_UNIX */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ */
-201
View File
@@ -1,201 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_
#define CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_
#if CS_PLATFORM == CS_P_WINCE
/*
* MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)
* MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)
* MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012)
* MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010)
* MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008)
* MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005)
* MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio 2003)
* MSVC++ 7.0 _MSC_VER == 1300
* MSVC++ 6.0 _MSC_VER == 1200
* MSVC++ 5.0 _MSC_VER == 1100
*/
#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */
#pragma warning(disable : 4204) /* missing c99 support */
#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
#endif
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <assert.h>
#include <limits.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#pragma comment(lib, "ws2.lib") /* Linking with WinCE winsock library */
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#define strdup _strdup
#ifndef EINPROGRESS
#define EINPROGRESS WSAEINPROGRESS
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK WSAEWOULDBLOCK
#endif
#ifndef EAGAIN
#define EAGAIN EWOULDBLOCK
#endif
#ifndef __func__
#define STRX(x) #x
#define STR(x) STRX(x)
#define __func__ __FILE__ ":" STR(__LINE__)
#endif
#define snprintf _snprintf
#define fileno _fileno
#define vsnprintf _vsnprintf
#define sleep(x) Sleep((x) *1000)
#define to64(x) _atoi64(x)
#define rmdir _rmdir
#if defined(_MSC_VER) && _MSC_VER >= 1400
#define fseeko(x, y, z) _fseeki64((x), (y), (z))
#else
#define fseeko(x, y, z) fseek((x), (y), (z))
#endif
typedef int socklen_t;
#if _MSC_VER >= 1700
#include <stdint.h>
#else
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#endif
typedef SOCKET sock_t;
typedef uint32_t in_addr_t;
#ifndef UINT16_MAX
#define UINT16_MAX 65535
#endif
#ifndef UINT32_MAX
#define UINT32_MAX 4294967295
#endif
#ifndef pid_t
#define pid_t HANDLE
#endif
#define INT64_FMT "I64d"
#define INT64_X_FMT "I64x"
/* TODO(alashkin): check if this is correct */
#define SIZE_T_FMT "u"
#define DIRSEP '\\'
#define CS_DEFINE_DIRENT
#ifndef va_copy
#ifdef __va_copy
#define va_copy __va_copy
#else
#define va_copy(x, y) (x) = (y)
#endif
#endif
#ifndef MG_MAX_HTTP_REQUEST_SIZE
#define MG_MAX_HTTP_REQUEST_SIZE 8192
#endif
#ifndef MG_MAX_HTTP_SEND_MBUF
#define MG_MAX_HTTP_SEND_MBUF 4096
#endif
#ifndef MG_MAX_HTTP_HEADERS
#define MG_MAX_HTTP_HEADERS 40
#endif
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#define abort() DebugBreak();
#ifndef BUFSIZ
#define BUFSIZ 4096
#endif
/*
* Explicitly disabling MG_ENABLE_THREADS for WinCE
* because they are enabled for _WIN32 by default
*/
#ifndef MG_ENABLE_THREADS
#define MG_ENABLE_THREADS 0
#endif
#ifndef MG_ENABLE_FILESYSTEM
#define MG_ENABLE_FILESYSTEM 1
#endif
#ifndef MG_NET_IF
#define MG_NET_IF MG_NET_IF_SOCKET
#endif
typedef struct _stati64 {
uint32_t st_mtime;
uint32_t st_size;
uint32_t st_mode;
} cs_stat_t;
/*
* WinCE 6.0 has a lot of useful definitions in ATL (not windows.h) headers
* use #ifdefs to avoid conflicts
*/
#ifndef ENOENT
#define ENOENT ERROR_PATH_NOT_FOUND
#endif
#ifndef EACCES
#define EACCES ERROR_ACCESS_DENIED
#endif
#ifndef ENOMEM
#define ENOMEM ERROR_NOT_ENOUGH_MEMORY
#endif
#ifndef _UINTPTR_T_DEFINED
typedef unsigned int *uintptr_t;
#endif
#define _S_IFREG 2
#define _S_IFDIR 4
#ifndef S_ISDIR
#define S_ISDIR(x) (((x) &_S_IFDIR) != 0)
#endif
#ifndef S_ISREG
#define S_ISREG(x) (((x) &_S_IFREG) != 0)
#endif
int open(const char *filename, int oflag, int pmode);
int _wstati64(const wchar_t *path, cs_stat_t *st);
const char *strerror();
#endif /* CS_PLATFORM == CS_P_WINCE */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ */
-183
View File
@@ -1,183 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_
#define CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_
#if CS_PLATFORM == CS_P_WINDOWS
/*
* MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)
* MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)
* MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012)
* MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010)
* MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008)
* MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005)
* MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio 2003)
* MSVC++ 7.0 _MSC_VER == 1300
* MSVC++ 6.0 _MSC_VER == 1200
* MSVC++ 5.0 _MSC_VER == 1100
*/
#ifdef _MSC_VER
#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */
#pragma warning(disable : 4204) /* missing c99 support */
#endif
#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
#endif
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <assert.h>
#include <direct.h>
#include <errno.h>
#include <fcntl.h>
#include <io.h>
#include <limits.h>
#include <signal.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <ctype.h>
#ifdef _MSC_VER
#pragma comment(lib, "ws2_32.lib") /* Linking with winsock library */
#endif
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <process.h>
#if defined(_MSC_VER) && (_MSC_VER < 1700)
typedef int bool;
#else
#include <stdbool.h>
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1800
#define strdup _strdup
#endif
#ifndef EINPROGRESS
#define EINPROGRESS WSAEINPROGRESS
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK WSAEWOULDBLOCK
#endif
#ifndef __func__
#define STRX(x) #x
#define STR(x) STRX(x)
#define __func__ __FILE__ ":" STR(__LINE__)
#endif
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define to64(x) _atoi64(x)
#if !defined(__MINGW32__) && !defined(__MINGW64__)
#define popen(x, y) _popen((x), (y))
#define pclose(x) _pclose(x)
#define fileno _fileno
#endif
#if defined(_MSC_VER) && _MSC_VER >= 1400
#define fseeko(x, y, z) _fseeki64((x), (y), (z))
#else
#define fseeko(x, y, z) fseek((x), (y), (z))
#endif
#if defined(_MSC_VER) && _MSC_VER <= 1200
typedef unsigned long uintptr_t;
typedef long intptr_t;
#endif
typedef int socklen_t;
#if _MSC_VER >= 1700
#include <stdint.h>
#else
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#endif
typedef SOCKET sock_t;
typedef uint32_t in_addr_t;
#ifndef UINT16_MAX
#define UINT16_MAX 65535
#endif
#ifndef UINT32_MAX
#define UINT32_MAX 4294967295
#endif
#ifndef pid_t
#define pid_t HANDLE
#endif
#define INT64_FMT "I64d"
#define INT64_X_FMT "I64x"
#define SIZE_T_FMT "Iu"
typedef struct _stati64 cs_stat_t;
#ifndef S_ISDIR
#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR)
#endif
#ifndef S_ISREG
#define S_ISREG(x) (((x) &_S_IFMT) == _S_IFREG)
#endif
#define DIRSEP '\\'
#define CS_DEFINE_DIRENT
#ifndef va_copy
#ifdef __va_copy
#define va_copy __va_copy
#else
#define va_copy(x, y) (x) = (y)
#endif
#endif
#ifndef MG_MAX_HTTP_REQUEST_SIZE
#define MG_MAX_HTTP_REQUEST_SIZE 8192
#endif
#ifndef MG_MAX_HTTP_SEND_MBUF
#define MG_MAX_HTTP_SEND_MBUF 4096
#endif
#ifndef MG_MAX_HTTP_HEADERS
#define MG_MAX_HTTP_HEADERS 40
#endif
#ifndef CS_ENABLE_STDIO
#define CS_ENABLE_STDIO 1
#endif
#ifndef MG_ENABLE_BROADCAST
#define MG_ENABLE_BROADCAST 1
#endif
#ifndef MG_ENABLE_DIRECTORY_LISTING
#define MG_ENABLE_DIRECTORY_LISTING 1
#endif
#ifndef MG_ENABLE_FILESYSTEM
#define MG_ENABLE_FILESYSTEM 1
#endif
#ifndef MG_ENABLE_HTTP_CGI
#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM
#endif
#ifndef MG_NET_IF
#define MG_NET_IF MG_NET_IF_SOCKET
#endif
unsigned int sleep(unsigned int seconds);
/* https://stackoverflow.com/questions/16647819/timegm-cross-platform */
#define timegm _mkgmtime
#define gmtime_r(a, b) \
do { \
*(b) = *gmtime(a); \
} while (0)
#endif /* CS_PLATFORM == CS_P_WINDOWS */
#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ */
@@ -1,160 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_
#define CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_
#if defined(MG_NET_IF) && MG_NET_IF == MG_NET_IF_SIMPLELINK
/* If simplelink.h is already included, all bets are off. */
#if !defined(__SIMPLELINK_H__)
#include <stdbool.h>
#ifndef __TI_COMPILER_VERSION__
#undef __CONCAT
#undef FD_CLR
#undef FD_ISSET
#undef FD_SET
#undef FD_SETSIZE
#undef FD_ZERO
#undef fd_set
#endif
#if CS_PLATFORM == CS_P_CC3220
#include <ti/drivers/net/wifi/porting/user.h>
#include <ti/drivers/net/wifi/simplelink.h>
#include <ti/drivers/net/wifi/sl_socket.h>
#include <ti/drivers/net/wifi/netapp.h>
#else
/* We want to disable SL_INC_STD_BSD_API_NAMING, so we include user.h ourselves
* and undef it. */
#define PROVISIONING_API_H_
#include <simplelink/user.h>
#undef PROVISIONING_API_H_
#undef SL_INC_STD_BSD_API_NAMING
#include <simplelink/include/simplelink.h>
#include <simplelink/include/netapp.h>
#endif /* CS_PLATFORM == CS_P_CC3220 */
/* Now define only the subset of the BSD API that we use.
* Notably, close(), read() and write() are not defined. */
#define AF_INET SL_AF_INET
#define socklen_t SlSocklen_t
#define sockaddr SlSockAddr_t
#define sockaddr_in SlSockAddrIn_t
#define in_addr SlInAddr_t
#define SOCK_STREAM SL_SOCK_STREAM
#define SOCK_DGRAM SL_SOCK_DGRAM
#define htonl sl_Htonl
#define ntohl sl_Ntohl
#define htons sl_Htons
#define ntohs sl_Ntohs
#ifndef EACCES
#define EACCES SL_EACCES
#endif
#ifndef EAFNOSUPPORT
#define EAFNOSUPPORT SL_EAFNOSUPPORT
#endif
#ifndef EAGAIN
#define EAGAIN SL_EAGAIN
#endif
#ifndef EBADF
#define EBADF SL_EBADF
#endif
#ifndef EINVAL
#define EINVAL SL_EINVAL
#endif
#ifndef ENOMEM
#define ENOMEM SL_ENOMEM
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK SL_EWOULDBLOCK
#endif
#define SOMAXCONN 8
#ifdef __cplusplus
extern "C" {
#endif
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
char *inet_ntoa(struct in_addr in);
int inet_pton(int af, const char *src, void *dst);
struct mg_mgr;
struct mg_connection;
typedef void (*mg_init_cb)(struct mg_mgr *mgr);
bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init);
void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg);
int sl_fs_init(void);
void sl_restart_cb(struct mg_mgr *mgr);
int sl_set_ssl_opts(int sock, struct mg_connection *nc);
#ifdef __cplusplus
}
#endif
#endif /* !defined(__SIMPLELINK_H__) */
/* Compatibility with older versions of SimpleLink */
#if SL_MAJOR_VERSION_NUM < 2
#define SL_ERROR_BSD_EAGAIN SL_EAGAIN
#define SL_ERROR_BSD_EALREADY SL_EALREADY
#define SL_ERROR_BSD_ENOPROTOOPT SL_ENOPROTOOPT
#define SL_ERROR_BSD_ESECDATEERROR SL_ESECDATEERROR
#define SL_ERROR_BSD_ESECSNOVERIFY SL_ESECSNOVERIFY
#define SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM SL_FS_ERR_FAILED_TO_ALLOCATE_MEM
#define SL_ERROR_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY \
SL_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY
#define SL_ERROR_FS_FILE_NAME_EXIST SL_FS_FILE_NAME_EXIST
#define SL_ERROR_FS_FILE_NOT_EXISTS SL_FS_ERR_FILE_NOT_EXISTS
#define SL_ERROR_FS_NO_AVAILABLE_NV_INDEX SL_FS_ERR_NO_AVAILABLE_NV_INDEX
#define SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE SL_FS_ERR_NO_AVAILABLE_BLOCKS
#define SL_ERROR_FS_NOT_SUPPORTED SL_FS_ERR_NOT_SUPPORTED
#define SL_ERROR_FS_WRONG_FILE_NAME SL_FS_WRONG_FILE_NAME
#define SL_ERROR_FS_INVALID_HANDLE SL_FS_ERR_INVALID_HANDLE
#define SL_NETCFG_MAC_ADDRESS_GET SL_MAC_ADDRESS_GET
#define SL_SOCKET_FD_ZERO SL_FD_ZERO
#define SL_SOCKET_FD_SET SL_FD_SET
#define SL_SOCKET_FD_ISSET SL_FD_ISSET
#define SL_SO_SECURE_DOMAIN_NAME_VERIFICATION SO_SECURE_DOMAIN_NAME_VERIFICATION
#define SL_FS_READ FS_MODE_OPEN_READ
#define SL_FS_WRITE FS_MODE_OPEN_WRITE
#define SL_FI_FILE_SIZE(fi) ((fi).FileLen)
#define SL_FI_FILE_MAX_SIZE(fi) ((fi).AllocatedLen)
#define SlDeviceVersion_t SlVersionFull
#define sl_DeviceGet sl_DevGet
#define SL_DEVICE_GENERAL SL_DEVICE_GENERAL_CONFIGURATION
#define SL_LEN_TYPE _u8
#define SL_OPT_TYPE _u8
#else /* SL_MAJOR_VERSION_NUM >= 2 */
#define FS_MODE_OPEN_CREATE(max_size, flag) \
(SL_FS_CREATE | SL_FS_CREATE_MAX_SIZE(max_size))
#define SL_FI_FILE_SIZE(fi) ((fi).Len)
#define SL_FI_FILE_MAX_SIZE(fi) ((fi).MaxSize)
#define SL_LEN_TYPE _u16
#define SL_OPT_TYPE _u16
#endif /* SL_MAJOR_VERSION_NUM < 2 */
int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token);
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ */
-407
View File
@@ -1,407 +0,0 @@
#if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
(defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
int set_errno(int e) {
errno = e;
return (e == 0 ? 0 : -1);
}
const char *drop_dir(const char *fname, bool *is_slfs) {
if (is_slfs != NULL) {
*is_slfs = (strncmp(fname, "SL:", 3) == 0);
if (*is_slfs) fname += 3;
}
/* Drop "./", if any */
if (fname[0] == '.' && fname[1] == '/') {
fname += 2;
}
/*
* Drop / if it is the only one in the path.
* This allows use of /pretend/directories but serves /file.txt as normal.
*/
if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) {
fname++;
}
return fname;
}
#if !defined(MG_FS_NO_VFS)
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __TI_COMPILER_VERSION__
#include <file.h>
#endif
#include "common/cs_dbg.h"
#include "common/platform.h"
#ifdef CC3200_FS_SPIFFS
#include "cc3200_fs_spiffs.h"
#endif
#ifdef MG_FS_SLFS
#include "sl_fs_slfs.h"
#endif
#define NUM_SYS_FDS 3
#define SPIFFS_FD_BASE 10
#define SLFS_FD_BASE 100
#if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE)
#if CS_PLATFORM == CS_P_CC3200
#include <inc/hw_types.h>
#include <inc/hw_memmap.h>
#include <driverlib/rom.h>
#include <driverlib/rom_map.h>
#include <driverlib/uart.h>
#define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
#else
#define MG_UART_WRITE(fd, buf, len)
#endif /* CS_PLATFORM == CS_P_CC3200 */
#endif /* !MG_UART_CHAR_PUT */
enum fd_type {
FD_INVALID,
FD_SYS,
#ifdef CC3200_FS_SPIFFS
FD_SPIFFS,
#endif
#ifdef MG_FS_SLFS
FD_SLFS
#endif
};
static int fd_type(int fd) {
if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
#ifdef CC3200_FS_SPIFFS
if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
return FD_SPIFFS;
}
#endif
#ifdef MG_FS_SLFS
if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
return FD_SLFS;
}
#endif
return FD_INVALID;
}
#if MG_TI_NO_HOST_INTERFACE
int open(const char *pathname, unsigned flags, int mode) {
#else
int _open(const char *pathname, int flags, mode_t mode) {
#endif
int fd = -1;
bool is_sl;
const char *fname = drop_dir(pathname, &is_sl);
if (is_sl) {
#ifdef MG_FS_SLFS
fd = fs_slfs_open(fname, flags, mode);
if (fd >= 0) fd += SLFS_FD_BASE;
#endif
} else {
#ifdef CC3200_FS_SPIFFS
fd = fs_spiffs_open(fname, flags, mode);
if (fd >= 0) fd += SPIFFS_FD_BASE;
#endif
}
LOG(LL_DEBUG,
("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
return fd;
}
int _stat(const char *pathname, struct stat *st) {
int res = -1;
bool is_sl;
const char *fname = drop_dir(pathname, &is_sl);
memset(st, 0, sizeof(*st));
/* Simulate statting the root directory. */
if (fname[0] == '\0' || strcmp(fname, ".") == 0) {
st->st_ino = 0;
st->st_mode = S_IFDIR | 0777;
st->st_nlink = 1;
st->st_size = 0;
return 0;
}
if (is_sl) {
#ifdef MG_FS_SLFS
res = fs_slfs_stat(fname, st);
#endif
} else {
#ifdef CC3200_FS_SPIFFS
res = fs_spiffs_stat(fname, st);
#endif
}
LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname));
return res;
}
#if MG_TI_NO_HOST_INTERFACE
int close(int fd) {
#else
int _close(int fd) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS:
r = set_errno(EACCES);
break;
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_close(fd - SLFS_FD_BASE);
break;
#endif
}
DBG(("close(%d) = %d", fd, r));
return r;
}
#if MG_TI_NO_HOST_INTERFACE
off_t lseek(int fd, off_t offset, int whence) {
#else
off_t _lseek(int fd, off_t offset, int whence) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS:
r = set_errno(ESPIPE);
break;
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
break;
#endif
}
DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
return r;
}
int _fstat(int fd, struct stat *s) {
int r = -1;
memset(s, 0, sizeof(*s));
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS: {
/* Create barely passable stats for STD{IN,OUT,ERR}. */
memset(s, 0, sizeof(*s));
s->st_ino = fd;
s->st_mode = S_IFCHR | 0666;
r = 0;
break;
}
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
break;
#endif
}
DBG(("fstat(%d) = %d", fd, r));
return r;
}
#if MG_TI_NO_HOST_INTERFACE
int read(int fd, char *buf, unsigned count) {
#else
ssize_t _read(int fd, void *buf, size_t count) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS: {
if (fd != 0) {
r = set_errno(EACCES);
break;
}
/* Should we allow reading from stdin = uart? */
r = set_errno(ENOTSUP);
break;
}
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
break;
#endif
}
DBG(("read(%d, %u) = %d", fd, count, r));
return r;
}
#if MG_TI_NO_HOST_INTERFACE
int write(int fd, const char *buf, unsigned count) {
#else
ssize_t _write(int fd, const void *buf, size_t count) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS: {
if (fd == 0) {
r = set_errno(EACCES);
break;
}
#ifdef MG_UART_WRITE
MG_UART_WRITE(fd, buf, count);
#elif defined(MG_UART_CHAR_PUT)
{
size_t i;
for (i = 0; i < count; i++) {
const char c = ((const char *) buf)[i];
if (c == '\n') MG_UART_CHAR_PUT(fd, '\r');
MG_UART_CHAR_PUT(fd, c);
}
}
#endif
r = count;
break;
}
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
break;
#endif
}
return r;
}
/*
* On Newlib we override rename directly too, because the default
* implementation using _link and _unlink doesn't work for us.
*/
#if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
int rename(const char *frompath, const char *topath) {
int r = -1;
bool is_sl_from, is_sl_to;
const char *from = drop_dir(frompath, &is_sl_from);
const char *to = drop_dir(topath, &is_sl_to);
if (is_sl_from || is_sl_to) {
set_errno(ENOTSUP);
} else {
#ifdef CC3200_FS_SPIFFS
r = fs_spiffs_rename(from, to);
#endif
}
DBG(("rename(%s, %s) = %d", from, to, r));
return r;
}
#endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */
#if MG_TI_NO_HOST_INTERFACE
int unlink(const char *pathname) {
#else
int _unlink(const char *pathname) {
#endif
int r = -1;
bool is_sl;
const char *fname = drop_dir(pathname, &is_sl);
if (is_sl) {
#ifdef MG_FS_SLFS
r = fs_slfs_unlink(fname);
#endif
} else {
#ifdef CC3200_FS_SPIFFS
r = fs_spiffs_unlink(fname);
#endif
}
DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname));
return r;
}
#ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
DIR *opendir(const char *dir_name) {
DIR *r = NULL;
bool is_sl;
drop_dir(dir_name, &is_sl);
if (is_sl) {
r = NULL;
set_errno(ENOTSUP);
} else {
r = fs_spiffs_opendir(dir_name);
}
DBG(("opendir(%s) = %p", dir_name, r));
return r;
}
struct dirent *readdir(DIR *dir) {
struct dirent *res = fs_spiffs_readdir(dir);
DBG(("readdir(%p) = %p", dir, res));
return res;
}
int closedir(DIR *dir) {
int res = fs_spiffs_closedir(dir);
DBG(("closedir(%p) = %d", dir, res));
return res;
}
int rmdir(const char *path) {
return fs_spiffs_rmdir(path);
}
int mkdir(const char *path, mode_t mode) {
(void) path;
(void) mode;
/* for spiffs supports only root dir, which comes from mongoose as '.' */
return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
}
#endif
int sl_fs_init(void) {
int ret = 1;
#ifdef __TI_COMPILER_VERSION__
#ifdef MG_FS_SLFS
#pragma diag_push
#pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \
*/
ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
fs_slfs_rename) == 0);
#pragma diag_pop
#endif
#endif
return ret;
}
#endif /* !defined(MG_FS_NO_VFS) */
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \
defined(MG_FS_SPIFFS)) */
@@ -1,286 +0,0 @@
/* Standard libc interface to TI SimpleLink FS. */
#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
#include "common/platforms/simplelink/sl_fs_slfs.h"
#include <errno.h>
#if CS_PLATFORM == CS_P_CC3200
#include <inc/hw_types.h>
#endif
#include "common/cs_dbg.h"
#include "common/mg_mem.h"
#if SL_MAJOR_VERSION_NUM < 2
int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) {
_i32 fh;
_i32 r = sl_FsOpen(fname, flags, (unsigned long *) token, &fh);
return (r < 0 ? r : fh);
}
#else /* SL_MAJOR_VERSION_NUM >= 2 */
int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) {
return sl_FsOpen(fname, flags, (unsigned long *) token);
}
#endif
/* From sl_fs.c */
int set_errno(int e);
const char *drop_dir(const char *fname, bool *is_slfs);
/*
* With SLFS, you have to pre-declare max file size. Yes. Really.
* 64K should be enough for everyone. Right?
*/
#ifndef FS_SLFS_MAX_FILE_SIZE
#define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
#endif
struct sl_file_open_info {
char *name;
size_t size;
uint32_t flags;
uint32_t *token;
};
struct sl_fd_info {
_i32 fh;
_off_t pos;
size_t size;
};
static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
static struct sl_file_open_info s_sl_file_open_infos[MAX_OPEN_SLFS_FILES];
static struct sl_file_open_info *fs_slfs_find_foi(const char *name,
bool create);
static int sl_fs_to_errno(_i32 r) {
DBG(("SL error: %d", (int) r));
switch (r) {
case SL_FS_OK:
return 0;
case SL_ERROR_FS_FILE_NAME_EXIST:
return EEXIST;
case SL_ERROR_FS_WRONG_FILE_NAME:
return EINVAL;
case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX:
case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE:
return ENOSPC;
case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM:
return ENOMEM;
case SL_ERROR_FS_FILE_NOT_EXISTS:
return ENOENT;
case SL_ERROR_FS_NOT_SUPPORTED:
return ENOTSUP;
}
return ENXIO;
}
int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
int fd;
for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
if (s_sl_fds[fd].fh <= 0) break;
}
if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
struct sl_fd_info *fi = &s_sl_fds[fd];
/*
* Apply path manipulations again, in case we got here directly
* (via TI libc's "add_device").
*/
pathname = drop_dir(pathname, NULL);
_u32 am = 0;
fi->size = (size_t) -1;
int rw = (flags & 3);
size_t new_size = 0;
struct sl_file_open_info *foi =
fs_slfs_find_foi(pathname, false /* create */);
if (foi != NULL) {
LOG(LL_DEBUG, ("FOI for %s: %d 0x%x %p", pathname, (int) foi->size,
(unsigned int) foi->flags, foi->token));
}
if (rw == O_RDONLY) {
SlFsFileInfo_t sl_fi;
_i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
if (r == SL_FS_OK) {
fi->size = SL_FI_FILE_SIZE(sl_fi);
}
am = SL_FS_READ;
} else {
if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
// FailFS files cannot be opened for append and will be truncated
// when opened for write.
return set_errno(ENOTSUP);
}
if (flags & O_CREAT) {
if (foi->size > 0) {
new_size = foi->size;
} else {
new_size = FS_SLFS_MAX_FILE_SIZE;
}
am = FS_MODE_OPEN_CREATE(new_size, 0);
} else {
am = SL_FS_WRITE;
}
#if SL_MAJOR_VERSION_NUM >= 2
am |= SL_FS_OVERWRITE;
#endif
}
uint32_t *token = NULL;
if (foi != NULL) {
am |= foi->flags;
token = foi->token;
}
fi->fh = slfs_open((_u8 *) pathname, am, token);
LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x, %p) sz %u = %d", pathname, (int) am,
token, (unsigned int) new_size, (int) fi->fh));
int r;
if (fi->fh >= 0) {
fi->pos = 0;
r = fd;
} else {
r = set_errno(sl_fs_to_errno(fi->fh));
}
return r;
}
int fs_slfs_close(int fd) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
_i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
s_sl_fds[fd].fh = -1;
return set_errno(sl_fs_to_errno(r));
}
ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
/* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
*/
if (fi->pos == fi->size) return 0;
_i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
(int) r));
if (r >= 0) {
fi->pos += r;
return r;
}
return set_errno(sl_fs_to_errno(r));
}
ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
_i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
(int) r));
if (r >= 0) {
fi->pos += r;
return r;
}
return set_errno(sl_fs_to_errno(r));
}
int fs_slfs_stat(const char *pathname, struct stat *s) {
SlFsFileInfo_t sl_fi;
/*
* Apply path manipulations again, in case we got here directly
* (via TI libc's "add_device").
*/
pathname = drop_dir(pathname, NULL);
_i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
if (r == SL_FS_OK) {
s->st_mode = S_IFREG | 0666;
s->st_nlink = 1;
s->st_size = SL_FI_FILE_SIZE(sl_fi);
return 0;
}
return set_errno(sl_fs_to_errno(r));
}
int fs_slfs_fstat(int fd, struct stat *s) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
s->st_mode = 0666;
s->st_mode = S_IFREG | 0666;
s->st_nlink = 1;
s->st_size = fi->size;
return 0;
}
off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
switch (whence) {
case SEEK_SET:
s_sl_fds[fd].pos = offset;
break;
case SEEK_CUR:
s_sl_fds[fd].pos += offset;
break;
case SEEK_END:
return set_errno(ENOTSUP);
}
return 0;
}
int fs_slfs_unlink(const char *pathname) {
/*
* Apply path manipulations again, in case we got here directly
* (via TI libc's "add_device").
*/
pathname = drop_dir(pathname, NULL);
return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0)));
}
int fs_slfs_rename(const char *from, const char *to) {
return set_errno(ENOTSUP);
}
static struct sl_file_open_info *fs_slfs_find_foi(const char *name,
bool create) {
int i = 0;
for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
if (s_sl_file_open_infos[i].name != NULL &&
strcmp(drop_dir(s_sl_file_open_infos[i].name, NULL), name) == 0) {
break;
}
}
if (i != MAX_OPEN_SLFS_FILES) return &s_sl_file_open_infos[i];
if (!create) return NULL;
for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
if (s_sl_file_open_infos[i].name == NULL) break;
}
if (i == MAX_OPEN_SLFS_FILES) {
i = 0; /* Evict a random slot. */
}
if (s_sl_file_open_infos[i].name != NULL) {
free(s_sl_file_open_infos[i].name);
}
s_sl_file_open_infos[i].name = strdup(name);
return &s_sl_file_open_infos[i];
}
void fs_slfs_set_file_size(const char *name, size_t size) {
struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */);
foi->size = size;
}
void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token) {
struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */);
foi->flags = flags;
foi->token = token;
}
void fs_slfs_unset_file_flags(const char *name) {
struct sl_file_open_info *foi = fs_slfs_find_foi(name, false /* create */);
if (foi == NULL) return;
free(foi->name);
memset(foi, 0, sizeof(*foi));
}
#endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
@@ -1,32 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
#if defined(MG_FS_SLFS)
#include <stdio.h>
#ifndef __TI_COMPILER_VERSION__
#include <unistd.h>
#include <sys/stat.h>
#endif
#define MAX_OPEN_SLFS_FILES 8
/* Indirect libc interface - same functions, different names. */
int fs_slfs_open(const char *pathname, int flags, mode_t mode);
int fs_slfs_close(int fd);
ssize_t fs_slfs_read(int fd, void *buf, size_t count);
ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
int fs_slfs_stat(const char *pathname, struct stat *s);
int fs_slfs_fstat(int fd, struct stat *s);
off_t fs_slfs_lseek(int fd, off_t offset, int whence);
int fs_slfs_unlink(const char *filename);
int fs_slfs_rename(const char *from, const char *to);
void fs_slfs_set_file_size(const char *name, size_t size);
void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token);
void fs_slfs_unset_file_flags(const char *name);
#endif /* defined(MG_FS_SLFS) */
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
@@ -1,52 +0,0 @@
#if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
#include "mg_task.h"
#include <oslib/osi.h>
enum mg_q_msg_type {
MG_Q_MSG_CB,
};
struct mg_q_msg {
enum mg_q_msg_type type;
void (*cb)(struct mg_mgr *mgr, void *arg);
void *arg;
};
static OsiMsgQ_t s_mg_q;
static void mg_task(void *arg);
bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
return false;
}
if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
(void *) mg_init, priority, NULL) != OSI_OK) {
return false;
}
return true;
}
static void mg_task(void *arg) {
struct mg_mgr mgr;
mg_init_cb mg_init = (mg_init_cb) arg;
mg_mgr_init(&mgr, NULL);
mg_init(&mgr);
while (1) {
struct mg_q_msg msg;
mg_mgr_poll(&mgr, 1);
if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
switch (msg.type) {
case MG_Q_MSG_CB: {
msg.cb(&mgr, msg.arg);
}
}
}
}
void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
}
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \
*/
-416
View File
@@ -1,416 +0,0 @@
#include "common/platforms/simplelink/sl_net_if.h"
#if MG_ENABLE_NET_IF_SIMPLELINK
#include "mongoose/src/internal.h"
#include "mongoose/src/util.h"
#define MG_TCP_RECV_BUFFER_SIZE 1024
#define MG_UDP_RECV_BUFFER_SIZE 1500
static sock_t mg_open_listening_socket(struct mg_connection *nc,
union socket_address *sa, int type,
int proto);
static void mg_set_non_blocking_mode(sock_t sock) {
SlSockNonblocking_t opt;
#if SL_MAJOR_VERSION_NUM < 2
opt.NonblockingEnabled = 1;
#else
opt.NonBlockingEnabled = 1;
#endif
sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
}
static int mg_is_error(int n) {
return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN);
}
static void mg_sl_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
int proto = 0;
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
#endif
sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
if (sock < 0) {
nc->err = sock;
goto out;
}
mg_sock_set(nc, sock);
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
nc->err = sl_set_ssl_opts(sock, nc);
if (nc->err != 0) goto out;
#endif
nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin));
out:
DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr),
ntohs(sa->sin.sin_port), nc->sock, proto, nc->err));
}
static void mg_sl_if_connect_udp(struct mg_connection *nc) {
sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
nc->err = sock;
return;
}
mg_sock_set(nc, sock);
nc->err = 0;
}
static int mg_sl_if_listen_tcp(struct mg_connection *nc,
union socket_address *sa) {
int proto = 0;
if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto);
if (sock < 0) return sock;
mg_sock_set(nc, sock);
return 0;
}
static int mg_sl_if_listen_udp(struct mg_connection *nc,
union socket_address *sa) {
sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) return (errno ? errno : 1);
mg_sock_set(nc, sock);
return 0;
}
static int mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf,
size_t len) {
int n = (int) sl_Send(nc->sock, buf, len, 0);
if (n < 0 && !mg_is_error(n)) n = 0;
return n;
}
static int mg_sl_if_udp_send(struct mg_connection *nc, const void *buf,
size_t len) {
int n = sl_SendTo(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
if (n < 0 && !mg_is_error(n)) n = 0;
return n;
}
static int mg_sl_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) {
int n = sl_Recv(nc->sock, buf, len, 0);
if (n == 0) {
/* Orderly shutdown of the socket, try flushing output. */
nc->flags |= MG_F_SEND_AND_CLOSE;
} else if (n < 0 && !mg_is_error(n)) {
n = 0;
}
return n;
}
static int mg_sl_if_udp_recv(struct mg_connection *nc, void *buf, size_t len,
union socket_address *sa, size_t *sa_len) {
SlSocklen_t sa_len_t = *sa_len;
int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0,
(SlSockAddr_t *) sa, &sa_len_t);
*sa_len = sa_len_t;
if (n < 0 && !mg_is_error(n)) n = 0;
return n;
}
static int mg_sl_if_create_conn(struct mg_connection *nc) {
(void) nc;
return 1;
}
void mg_sl_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
/* For UDP, only close outgoing sockets or listeners. */
if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
sl_Close(nc->sock);
}
nc->sock = INVALID_SOCKET;
}
static int mg_accept_conn(struct mg_connection *lc) {
struct mg_connection *nc;
union socket_address sa;
socklen_t sa_len = sizeof(sa);
sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len);
if (sock < 0) {
DBG(("%p: failed to accept: %d", lc, sock));
return 0;
}
nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
sl_Close(sock);
return 0;
}
DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
ntohs(sa.sin.sin_port)));
mg_sock_set(nc, sock);
mg_if_accept_tcp_cb(nc, &sa, sa_len);
return 1;
}
/* 'sa' must be an initialized address to bind to */
static sock_t mg_open_listening_socket(struct mg_connection *nc,
union socket_address *sa, int type,
int proto) {
int r;
socklen_t sa_len =
(sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
sock_t sock = sl_Socket(sa->sa.sa_family, type, proto);
if (sock < 0) return sock;
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean;
#endif
if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean;
if (type != SOCK_DGRAM) {
if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean;
}
mg_set_non_blocking_mode(sock);
clean:
if (r < 0) {
sl_Close(sock);
sock = r;
}
return sock;
}
#define _MG_F_FD_CAN_READ 1
#define _MG_F_FD_CAN_WRITE 1 << 1
#define _MG_F_FD_ERROR 1 << 2
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock,
fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
if (!mg_if_poll(nc, now)) return;
if (nc->flags & MG_F_CONNECTING) {
if ((nc->flags & MG_F_UDP) || nc->err != SL_ERROR_BSD_EALREADY) {
mg_if_connect_cb(nc, nc->err);
} else {
/* In SimpleLink, to get status of non-blocking connect() we need to wait
* until socket is writable and repeat the call to sl_Connect again,
* which will now return the real status. */
if (fd_flags & _MG_F_FD_CAN_WRITE) {
nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin));
DBG(("%p conn res=%d", nc, nc->err));
if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY ||
/* TODO(rojer): Provide API to set the date for verification. */
nc->err == SL_ERROR_BSD_ESECDATEERROR
#if SL_MAJOR_VERSION_NUM >= 2
/* Per SWRU455, this error does not mean verification failed,
* it only means that the cert used is not present in the trusted
* root CA catalog. Which is perfectly fine. */
||
nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA
#endif
) {
nc->err = 0;
}
mg_if_connect_cb(nc, nc->err);
}
}
/* Ignore read/write in further processing, we've handled it. */
fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE);
}
if (fd_flags & _MG_F_FD_CAN_READ) {
if (nc->flags & MG_F_UDP) {
mg_if_can_recv_cb(nc);
} else {
if (nc->flags & MG_F_LISTENING) {
mg_accept_conn(nc);
} else {
mg_if_can_recv_cb(nc);
}
}
}
if (fd_flags & _MG_F_FD_CAN_WRITE) {
mg_if_can_send_cb(nc);
}
DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
/* Associate a socket to a connection. */
void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) {
mg_set_non_blocking_mode(sock);
nc->sock = sock;
DBG(("%p %d", nc, sock));
}
void mg_sl_if_init(struct mg_iface *iface) {
(void) iface;
DBG(("%p using sl_Select()", iface->mgr));
}
void mg_sl_if_free(struct mg_iface *iface) {
(void) iface;
}
void mg_sl_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_sl_if_remove_conn(struct mg_connection *nc) {
(void) nc;
}
time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
double now = mg_time();
double min_timer;
struct mg_connection *nc, *tmp;
struct SlTimeval_t tv;
SlFdSet_t read_set, write_set, err_set;
sock_t max_fd = INVALID_SOCKET;
int num_fds, num_ev = 0, num_timers = 0;
SL_SOCKET_FD_ZERO(&read_set);
SL_SOCKET_FD_ZERO(&write_set);
SL_SOCKET_FD_ZERO(&err_set);
/*
* Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
* e.g. timer-only "connections".
*/
min_timer = 0;
for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
tmp = nc->next;
if (nc->sock != INVALID_SOCKET) {
num_fds++;
if (!(nc->flags & MG_F_WANT_WRITE) &&
nc->recv_mbuf.len < nc->recv_mbuf_limit &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
SL_SOCKET_FD_SET(nc->sock, &read_set);
if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
}
if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
(nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
SL_SOCKET_FD_SET(nc->sock, &write_set);
SL_SOCKET_FD_SET(nc->sock, &err_set);
if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
}
}
if (nc->ev_timer_time > 0) {
if (num_timers == 0 || nc->ev_timer_time < min_timer) {
min_timer = nc->ev_timer_time;
}
num_timers++;
}
}
/*
* If there is a timer to be fired earlier than the requested timeout,
* adjust the timeout.
*/
if (num_timers > 0) {
double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
if (timer_timeout_ms < timeout_ms) {
timeout_ms = timer_timeout_ms;
}
}
if (timeout_ms < 0) timeout_ms = 0;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
if (num_fds > 0) {
num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
}
now = mg_time();
DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev,
num_fds, timeout_ms));
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
int fd_flags = 0;
if (nc->sock != INVALID_SOCKET) {
if (num_ev > 0) {
fd_flags =
(SL_SOCKET_FD_ISSET(nc->sock, &read_set) &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)
? _MG_F_FD_CAN_READ
: 0) |
(SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE
: 0) |
(SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
}
/* SimpleLink does not report UDP sockets as writable. */
if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) {
fd_flags |= _MG_F_FD_CAN_WRITE;
}
}
tmp = nc->next;
mg_mgr_handle_conn(nc, fd_flags, now);
}
return now;
}
void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
/* SimpleLink does not provide a way to get socket's peer address after
* accept or connect. Address should have been preserved in the connection,
* so we do our best here by using it. */
if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
}
void sl_restart_cb(struct mg_mgr *mgr) {
/*
* SimpleLink has been restarted, meaning all sockets have been invalidated.
* We try our best - we'll restart the listeners, but for outgoing
* connections we have no option but to terminate.
*/
struct mg_connection *nc;
for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */
if (nc->flags & MG_F_LISTENING) {
DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
ntohs(nc->sa.sin.sin_port)));
int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa)
: mg_sl_if_listen_tcp(nc, &nc->sa));
if (res == 0) continue;
/* Well, we tried and failed. Fall through to closing. */
}
nc->sock = INVALID_SOCKET;
DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
ntohs(nc->sa.sin.sin_port)));
/* TODO(rojer): Outgoing UDP? */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
/* clang-format off */
#define MG_SL_IFACE_VTABLE \
{ \
mg_sl_if_init, \
mg_sl_if_free, \
mg_sl_if_add_conn, \
mg_sl_if_remove_conn, \
mg_sl_if_poll, \
mg_sl_if_listen_tcp, \
mg_sl_if_listen_udp, \
mg_sl_if_connect_tcp, \
mg_sl_if_connect_udp, \
mg_sl_if_tcp_send, \
mg_sl_if_udp_send, \
mg_sl_if_tcp_recv, \
mg_sl_if_udp_recv, \
mg_sl_if_create_conn, \
mg_sl_if_destroy_conn, \
mg_sl_if_sock_set, \
mg_sl_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_SIMPLELINK */
@@ -1,21 +0,0 @@
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
#include "mongoose/src/net_if.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef MG_ENABLE_NET_IF_SIMPLELINK
#define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
#endif
extern const struct mg_iface_vtable mg_simplelink_iface_vtable;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */
@@ -1,44 +0,0 @@
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
#include <errno.h>
#include <stdio.h>
#include "common/platform.h"
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
int res;
struct in_addr *in = (struct in_addr *) src;
if (af != AF_INET) {
errno = ENOTSUP;
return NULL;
}
res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
SL_IPV4_BYTE(in->s_addr, 3));
return res > 0 ? dst : NULL;
}
char *inet_ntoa(struct in_addr n) {
static char a[16];
return (char *) inet_ntop(AF_INET, &n, a, sizeof(a));
}
int inet_pton(int af, const char *src, void *dst) {
uint32_t a0, a1, a2, a3;
uint8_t *db = (uint8_t *) dst;
if (af != AF_INET) {
errno = ENOTSUP;
return 0;
}
if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
return 0;
}
*db = a3;
*(db + 1) = a2;
*(db + 2) = a1;
*(db + 3) = a0;
return 1;
}
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
-235
View File
@@ -1,235 +0,0 @@
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
#include "common/mg_mem.h"
#ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX
#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:"
#endif
#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \
(sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1)
struct mg_ssl_if_ctx {
char *ssl_cert;
char *ssl_key;
char *ssl_ca_cert;
char *ssl_server_name;
};
void mg_ssl_if_init() {
}
enum mg_ssl_if_result mg_ssl_if_conn_init(
struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
const char **err_msg) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
if (ctx == NULL) {
MG_SET_PTRPTR(err_msg, "Out of memory");
return MG_SSL_ERROR;
}
nc->ssl_if_data = ctx;
if (params->cert != NULL || params->key != NULL) {
if (params->cert != NULL && params->key != NULL) {
ctx->ssl_cert = strdup(params->cert);
ctx->ssl_key = strdup(params->key);
} else {
MG_SET_PTRPTR(err_msg, "Both cert and key are required.");
return MG_SSL_ERROR;
}
}
if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) {
ctx->ssl_ca_cert = strdup(params->ca_cert);
}
/* TODO(rojer): cipher_suites. */
if (params->server_name != NULL) {
ctx->ssl_server_name = strdup(params->server_name);
}
return MG_SSL_OK;
}
enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
struct mg_connection *lc) {
/* SimpleLink does everything for us, nothing for us to do. */
(void) nc;
(void) lc;
return MG_SSL_OK;
}
enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
/* SimpleLink has already performed the handshake, nothing to do. */
return MG_SSL_OK;
}
int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) {
/* SimpelLink handles TLS, so this is just a pass-through. */
int n = nc->iface->vtable->tcp_recv(nc, buf, len);
if (n == 0) nc->flags |= MG_F_WANT_READ;
return n;
}
int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) {
/* SimpelLink handles TLS, so this is just a pass-through. */
return nc->iface->vtable->tcp_send(nc, buf, len);
}
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
/* Nothing to do */
(void) nc;
}
void mg_ssl_if_conn_free(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
nc->ssl_if_data = NULL;
MG_FREE(ctx->ssl_cert);
MG_FREE(ctx->ssl_key);
MG_FREE(ctx->ssl_ca_cert);
MG_FREE(ctx->ssl_server_name);
memset(ctx, 0, sizeof(*ctx));
MG_FREE(ctx);
}
bool pem_to_der(const char *pem_file, const char *der_file) {
bool ret = false;
FILE *pf = NULL, *df = NULL;
bool writing = false;
pf = fopen(pem_file, "r");
if (pf == NULL) goto clean;
remove(der_file);
fs_slfs_set_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, 2048);
df = fopen(der_file, "w");
fs_slfs_unset_file_flags(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN);
if (df == NULL) goto clean;
while (1) {
char pem_buf[70];
char der_buf[48];
if (!fgets(pem_buf, sizeof(pem_buf), pf)) break;
if (writing) {
if (strstr(pem_buf, "-----END ") != NULL) {
ret = true;
break;
}
int l = 0;
while (!isspace((unsigned int) pem_buf[l])) l++;
int der_len = 0;
cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf),
der_buf, &der_len);
if (der_len <= 0) break;
if (fwrite(der_buf, 1, der_len, df) != der_len) break;
} else if (strstr(pem_buf, "-----BEGIN ") != NULL) {
writing = true;
}
}
clean:
if (pf != NULL) fclose(pf);
if (df != NULL) {
fclose(df);
if (!ret) remove(der_file);
}
return ret;
}
#if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
/* If the file's extension is .pem, convert it to DER format and put on SLFS. */
static char *sl_pem2der(const char *pem_file) {
const char *pem_ext = strstr(pem_file, ".pem");
if (pem_ext == NULL || *(pem_ext + 4) != '\0') {
return strdup(pem_file);
}
char *der_file = NULL;
/* DER file must be located on SLFS, add prefix. */
int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der",
(int) (pem_ext - pem_file), pem_file);
if (der_file == NULL) return NULL;
bool result = false;
cs_stat_t st;
if (mg_stat(der_file, &st) != 0) {
result = pem_to_der(pem_file, der_file);
LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result));
} else {
/* File exists, assume it's already been converted. */
result = true;
}
if (result) {
/* Strip the SL: prefix we added since NWP does not expect it. */
memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN,
l - 2 /* including \0 */);
} else {
MG_FREE(der_file);
der_file = NULL;
}
return der_file;
}
#else
static char *sl_pem2der(const char *pem_file) {
return strdup(pem_file);
}
#endif
int sl_set_ssl_opts(int sock, struct mg_connection *nc) {
int err;
const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
DBG(("%p ssl ctx: %p", nc, ctx));
if (ctx == NULL) return 0;
DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
(ctx->ssl_key ? ctx->ssl_cert : "-"),
(ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
(ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL;
if (ssl_cert != NULL) {
err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
strlen(ssl_cert));
MG_FREE(ssl_cert);
LOG(LL_DEBUG, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
ssl_key = sl_pem2der(ctx->ssl_key);
if (ssl_key != NULL) {
err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
strlen(ssl_key));
MG_FREE(ssl_key);
LOG(LL_DEBUG, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
} else {
err = -1;
}
} else {
err = -1;
}
if (err != 0) return err;
}
if (ctx->ssl_ca_cert != NULL) {
if (ctx->ssl_ca_cert[0] != '\0') {
char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
if (ssl_ca_cert != NULL) {
err =
sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME,
ssl_ca_cert, strlen(ssl_ca_cert));
LOG(LL_DEBUG, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
} else {
err = -1;
}
MG_FREE(ssl_ca_cert);
if (err != 0) return err;
}
}
if (ctx->ssl_server_name != NULL) {
err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
SL_SO_SECURE_DOMAIN_NAME_VERIFICATION,
ctx->ssl_server_name, strlen(ctx->ssl_server_name));
DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
/* Domain name verificationw as added in a NWP service pack, older
* versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do
* about it,
* so we ignore the error. */
if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err;
}
return 0;
}
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */
-70
View File
@@ -1,70 +0,0 @@
#ifdef WINCE
const char *strerror(int err) {
/*
* TODO(alashkin): there is no strerror on WinCE;
* look for similar wce_xxxx function
*/
static char buf[10];
snprintf(buf, sizeof(buf), "%d", err);
return buf;
}
int open(const char *filename, int oflag, int pmode) {
/*
* TODO(alashkin): mg_open function is not used in mongoose
* but exists in documentation as utility function
* Shall we delete it at all or implement for WinCE as well?
*/
DebugBreak();
return 0; /* for compiler */
}
int _wstati64(const wchar_t *path, cs_stat_t *st) {
DWORD fa = GetFileAttributesW(path);
if (fa == INVALID_FILE_ATTRIBUTES) {
return -1;
}
memset(st, 0, sizeof(*st));
if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
HANDLE h;
FILETIME ftime;
st->st_mode |= _S_IFREG;
h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) {
return -1;
}
st->st_size = GetFileSize(h, NULL);
GetFileTime(h, NULL, NULL, &ftime);
st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
((uint64_t) ftime.dwHighDateTime << 32)) /
10000000.0) -
11644473600);
CloseHandle(h);
} else {
st->st_mode |= _S_IFDIR;
}
return 0;
}
/* Windows CE doesn't have neither gmtime nor strftime */
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
FILETIME ft;
SYSTEMTIME systime;
if (t != NULL) {
uint64_t filetime = (*t + 11644473600) * 10000000;
ft.dwLowDateTime = filetime & 0xFFFFFFFF;
ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
FileTimeToSystemTime(&ft, &systime);
} else {
GetSystemTime(&systime);
}
/* There is no PRIu16 in WinCE SDK */
snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear,
(int) systime.wMonth, (int) systime.wDay, (int) systime.wHour,
(int) systime.wMinute, (int) systime.wSecond);
}
#endif
@@ -1,13 +0,0 @@
#ifdef _WIN32
int rmdir(const char *dirname) {
return _rmdir(dirname);
}
unsigned int sleep(unsigned int seconds) {
Sleep(seconds * 1000);
return 0;
}
#endif /* _WIN32 */
-752
View File
@@ -1,752 +0,0 @@
/* clang-format off */
/*-
* Copyright (c) 1991, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)queue.h 8.5 (Berkeley) 8/20/94
* $FreeBSD$
*/
#ifndef _SYS_QUEUE_H_
#define _SYS_QUEUE_H_
/*
* This file defines four types of data structures: singly-linked lists,
* singly-linked tail queues, lists and tail queues.
*
* A singly-linked list is headed by a single forward pointer. The elements
* are singly linked for minimum space and pointer manipulation overhead at
* the expense of O(n) removal for arbitrary elements. New elements can be
* added to the list after an existing element or at the head of the list.
* Elements being removed from the head of the list should use the explicit
* macro for this purpose for optimum efficiency. A singly-linked list may
* only be traversed in the forward direction. Singly-linked lists are ideal
* for applications with large datasets and few or no removals or for
* implementing a LIFO queue.
*
* A singly-linked tail queue is headed by a pair of pointers, one to the
* head of the list and the other to the tail of the list. The elements are
* singly linked for minimum space and pointer manipulation overhead at the
* expense of O(n) removal for arbitrary elements. New elements can be added
* to the list after an existing element, at the head of the list, or at the
* end of the list. Elements being removed from the head of the tail queue
* should use the explicit macro for this purpose for optimum efficiency.
* A singly-linked tail queue may only be traversed in the forward direction.
* Singly-linked tail queues are ideal for applications with large datasets
* and few or no removals or for implementing a FIFO queue.
*
* A list is headed by a single forward pointer (or an array of forward
* pointers for a hash table header). The elements are doubly linked
* so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before
* or after an existing element or at the head of the list. A list
* may be traversed in either direction.
*
* A tail queue is headed by a pair of pointers, one to the head of the
* list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or
* after an existing element, at the head of the list, or at the end of
* the list. A tail queue may be traversed in either direction.
*
* For details on the use of these macros, see the queue(3) manual page.
*
*
* SLIST LIST STAILQ TAILQ
* _HEAD + + + +
* _CLASS_HEAD + + + +
* _HEAD_INITIALIZER + + + +
* _ENTRY + + + +
* _CLASS_ENTRY + + + +
* _INIT + + + +
* _EMPTY + + + +
* _FIRST + + + +
* _NEXT + + + +
* _PREV - + - +
* _LAST - - + +
* _FOREACH + + + +
* _FOREACH_FROM + + + +
* _FOREACH_SAFE + + + +
* _FOREACH_FROM_SAFE + + + +
* _FOREACH_REVERSE - - - +
* _FOREACH_REVERSE_FROM - - - +
* _FOREACH_REVERSE_SAFE - - - +
* _FOREACH_REVERSE_FROM_SAFE - - - +
* _INSERT_HEAD + + + +
* _INSERT_BEFORE - + - +
* _INSERT_AFTER + + + +
* _INSERT_TAIL - - + +
* _CONCAT - - + +
* _REMOVE_AFTER + - + -
* _REMOVE_HEAD + - + -
* _REMOVE + + + +
* _SWAP + + + +
*
*/
#ifdef QUEUE_MACRO_DEBUG
/* Store the last 2 places the queue element or head was altered */
struct qm_trace {
unsigned long lastline;
unsigned long prevline;
const char *lastfile;
const char *prevfile;
};
#define TRACEBUF struct qm_trace trace;
#define TRACEBUF_INITIALIZER { __LINE__, 0, __FILE__, NULL } ,
#define TRASHIT(x) do {(x) = (void *)-1;} while (0)
#define QMD_SAVELINK(name, link) void **name = (void *)&(link)
#define QMD_TRACE_HEAD(head) do { \
(head)->trace.prevline = (head)->trace.lastline; \
(head)->trace.prevfile = (head)->trace.lastfile; \
(head)->trace.lastline = __LINE__; \
(head)->trace.lastfile = __FILE__; \
} while (0)
#define QMD_TRACE_ELEM(elem) do { \
(elem)->trace.prevline = (elem)->trace.lastline; \
(elem)->trace.prevfile = (elem)->trace.lastfile; \
(elem)->trace.lastline = __LINE__; \
(elem)->trace.lastfile = __FILE__; \
} while (0)
#else
#define QMD_TRACE_ELEM(elem)
#define QMD_TRACE_HEAD(head)
#define QMD_SAVELINK(name, link)
#define TRACEBUF
#define TRACEBUF_INITIALIZER
#define TRASHIT(x)
#endif /* QUEUE_MACRO_DEBUG */
#ifdef __cplusplus
/*
* In C++ there can be structure lists and class lists:
*/
#define QUEUE_TYPEOF(type) type
#else
#define QUEUE_TYPEOF(type) struct type
#endif
/*
* Singly-linked List declarations.
*/
#define SLIST_HEAD(name, type) \
struct name { \
struct type *slh_first; /* first element */ \
}
#define SLIST_CLASS_HEAD(name, type) \
struct name { \
class type *slh_first; /* first element */ \
}
#define SLIST_HEAD_INITIALIZER(head) \
{ NULL }
#define SLIST_ENTRY(type) \
struct { \
struct type *sle_next; /* next element */ \
}
#define SLIST_CLASS_ENTRY(type) \
struct { \
class type *sle_next; /* next element */ \
}
/*
* Singly-linked List functions.
*/
#define SLIST_EMPTY(head) ((head)->slh_first == NULL)
#define SLIST_FIRST(head) ((head)->slh_first)
#define SLIST_FOREACH(var, head, field) \
for ((var) = SLIST_FIRST((head)); \
(var); \
(var) = SLIST_NEXT((var), field))
#define SLIST_FOREACH_FROM(var, head, field) \
for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \
(var); \
(var) = SLIST_NEXT((var), field))
#define SLIST_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = SLIST_FIRST((head)); \
(var) && ((tvar) = SLIST_NEXT((var), field), 1); \
(var) = (tvar))
#define SLIST_FOREACH_FROM_SAFE(var, head, field, tvar) \
for ((var) = ((var) ? (var) : SLIST_FIRST((head))); \
(var) && ((tvar) = SLIST_NEXT((var), field), 1); \
(var) = (tvar))
#define SLIST_FOREACH_PREVPTR(var, varp, head, field) \
for ((varp) = &SLIST_FIRST((head)); \
((var) = *(varp)) != NULL; \
(varp) = &SLIST_NEXT((var), field))
#define SLIST_INIT(head) do { \
SLIST_FIRST((head)) = NULL; \
} while (0)
#define SLIST_INSERT_AFTER(slistelm, elm, field) do { \
SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field); \
SLIST_NEXT((slistelm), field) = (elm); \
} while (0)
#define SLIST_INSERT_HEAD(head, elm, field) do { \
SLIST_NEXT((elm), field) = SLIST_FIRST((head)); \
SLIST_FIRST((head)) = (elm); \
} while (0)
#define SLIST_NEXT(elm, field) ((elm)->field.sle_next)
#define SLIST_REMOVE(head, elm, type, field) do { \
QMD_SAVELINK(oldnext, (elm)->field.sle_next); \
if (SLIST_FIRST((head)) == (elm)) { \
SLIST_REMOVE_HEAD((head), field); \
} \
else { \
QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head); \
while (SLIST_NEXT(curelm, field) != (elm)) \
curelm = SLIST_NEXT(curelm, field); \
SLIST_REMOVE_AFTER(curelm, field); \
} \
TRASHIT(*oldnext); \
} while (0)
#define SLIST_REMOVE_AFTER(elm, field) do { \
SLIST_NEXT(elm, field) = \
SLIST_NEXT(SLIST_NEXT(elm, field), field); \
} while (0)
#define SLIST_REMOVE_HEAD(head, field) do { \
SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field); \
} while (0)
#define SLIST_SWAP(head1, head2, type) do { \
QUEUE_TYPEOF(type) *swap_first = SLIST_FIRST(head1); \
SLIST_FIRST(head1) = SLIST_FIRST(head2); \
SLIST_FIRST(head2) = swap_first; \
} while (0)
/*
* Singly-linked Tail queue declarations.
*/
#define STAILQ_HEAD(name, type) \
struct name { \
struct type *stqh_first;/* first element */ \
struct type **stqh_last;/* addr of last next element */ \
}
#define STAILQ_CLASS_HEAD(name, type) \
struct name { \
class type *stqh_first; /* first element */ \
class type **stqh_last; /* addr of last next element */ \
}
#define STAILQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).stqh_first }
#define STAILQ_ENTRY(type) \
struct { \
struct type *stqe_next; /* next element */ \
}
#define STAILQ_CLASS_ENTRY(type) \
struct { \
class type *stqe_next; /* next element */ \
}
/*
* Singly-linked Tail queue functions.
*/
#define STAILQ_CONCAT(head1, head2) do { \
if (!STAILQ_EMPTY((head2))) { \
*(head1)->stqh_last = (head2)->stqh_first; \
(head1)->stqh_last = (head2)->stqh_last; \
STAILQ_INIT((head2)); \
} \
} while (0)
#define STAILQ_EMPTY(head) ((head)->stqh_first == NULL)
#define STAILQ_FIRST(head) ((head)->stqh_first)
#define STAILQ_FOREACH(var, head, field) \
for((var) = STAILQ_FIRST((head)); \
(var); \
(var) = STAILQ_NEXT((var), field))
#define STAILQ_FOREACH_FROM(var, head, field) \
for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \
(var); \
(var) = STAILQ_NEXT((var), field))
#define STAILQ_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = STAILQ_FIRST((head)); \
(var) && ((tvar) = STAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#define STAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \
for ((var) = ((var) ? (var) : STAILQ_FIRST((head))); \
(var) && ((tvar) = STAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#define STAILQ_INIT(head) do { \
STAILQ_FIRST((head)) = NULL; \
(head)->stqh_last = &STAILQ_FIRST((head)); \
} while (0)
#define STAILQ_INSERT_AFTER(head, tqelm, elm, field) do { \
if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\
(head)->stqh_last = &STAILQ_NEXT((elm), field); \
STAILQ_NEXT((tqelm), field) = (elm); \
} while (0)
#define STAILQ_INSERT_HEAD(head, elm, field) do { \
if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL) \
(head)->stqh_last = &STAILQ_NEXT((elm), field); \
STAILQ_FIRST((head)) = (elm); \
} while (0)
#define STAILQ_INSERT_TAIL(head, elm, field) do { \
STAILQ_NEXT((elm), field) = NULL; \
*(head)->stqh_last = (elm); \
(head)->stqh_last = &STAILQ_NEXT((elm), field); \
} while (0)
#define STAILQ_LAST(head, type, field) \
(STAILQ_EMPTY((head)) ? NULL : \
__containerof((head)->stqh_last, \
QUEUE_TYPEOF(type), field.stqe_next))
#define STAILQ_NEXT(elm, field) ((elm)->field.stqe_next)
#define STAILQ_REMOVE(head, elm, type, field) do { \
QMD_SAVELINK(oldnext, (elm)->field.stqe_next); \
if (STAILQ_FIRST((head)) == (elm)) { \
STAILQ_REMOVE_HEAD((head), field); \
} \
else { \
QUEUE_TYPEOF(type) *curelm = STAILQ_FIRST(head); \
while (STAILQ_NEXT(curelm, field) != (elm)) \
curelm = STAILQ_NEXT(curelm, field); \
STAILQ_REMOVE_AFTER(head, curelm, field); \
} \
TRASHIT(*oldnext); \
} while (0)
#define STAILQ_REMOVE_AFTER(head, elm, field) do { \
if ((STAILQ_NEXT(elm, field) = \
STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL) \
(head)->stqh_last = &STAILQ_NEXT((elm), field); \
} while (0)
#define STAILQ_REMOVE_HEAD(head, field) do { \
if ((STAILQ_FIRST((head)) = \
STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL) \
(head)->stqh_last = &STAILQ_FIRST((head)); \
} while (0)
#define STAILQ_SWAP(head1, head2, type) do { \
QUEUE_TYPEOF(type) *swap_first = STAILQ_FIRST(head1); \
QUEUE_TYPEOF(type) **swap_last = (head1)->stqh_last; \
STAILQ_FIRST(head1) = STAILQ_FIRST(head2); \
(head1)->stqh_last = (head2)->stqh_last; \
STAILQ_FIRST(head2) = swap_first; \
(head2)->stqh_last = swap_last; \
if (STAILQ_EMPTY(head1)) \
(head1)->stqh_last = &STAILQ_FIRST(head1); \
if (STAILQ_EMPTY(head2)) \
(head2)->stqh_last = &STAILQ_FIRST(head2); \
} while (0)
/*
* List declarations.
*/
#define LIST_HEAD(name, type) \
struct name { \
struct type *lh_first; /* first element */ \
}
#define LIST_CLASS_HEAD(name, type) \
struct name { \
class type *lh_first; /* first element */ \
}
#define LIST_HEAD_INITIALIZER(head) \
{ NULL }
#define LIST_ENTRY(type) \
struct { \
struct type *le_next; /* next element */ \
struct type **le_prev; /* address of previous next element */ \
}
#define LIST_CLASS_ENTRY(type) \
struct { \
class type *le_next; /* next element */ \
class type **le_prev; /* address of previous next element */ \
}
/*
* List functions.
*/
#if (defined(_KERNEL) && defined(INVARIANTS))
#define QMD_LIST_CHECK_HEAD(head, field) do { \
if (LIST_FIRST((head)) != NULL && \
LIST_FIRST((head))->field.le_prev != \
&LIST_FIRST((head))) \
panic("Bad list head %p first->prev != head", (head)); \
} while (0)
#define QMD_LIST_CHECK_NEXT(elm, field) do { \
if (LIST_NEXT((elm), field) != NULL && \
LIST_NEXT((elm), field)->field.le_prev != \
&((elm)->field.le_next)) \
panic("Bad link elm %p next->prev != elm", (elm)); \
} while (0)
#define QMD_LIST_CHECK_PREV(elm, field) do { \
if (*(elm)->field.le_prev != (elm)) \
panic("Bad link elm %p prev->next != elm", (elm)); \
} while (0)
#else
#define QMD_LIST_CHECK_HEAD(head, field)
#define QMD_LIST_CHECK_NEXT(elm, field)
#define QMD_LIST_CHECK_PREV(elm, field)
#endif /* (_KERNEL && INVARIANTS) */
#define LIST_EMPTY(head) ((head)->lh_first == NULL)
#define LIST_FIRST(head) ((head)->lh_first)
#define LIST_FOREACH(var, head, field) \
for ((var) = LIST_FIRST((head)); \
(var); \
(var) = LIST_NEXT((var), field))
#define LIST_FOREACH_FROM(var, head, field) \
for ((var) = ((var) ? (var) : LIST_FIRST((head))); \
(var); \
(var) = LIST_NEXT((var), field))
#define LIST_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = LIST_FIRST((head)); \
(var) && ((tvar) = LIST_NEXT((var), field), 1); \
(var) = (tvar))
#define LIST_FOREACH_FROM_SAFE(var, head, field, tvar) \
for ((var) = ((var) ? (var) : LIST_FIRST((head))); \
(var) && ((tvar) = LIST_NEXT((var), field), 1); \
(var) = (tvar))
#define LIST_INIT(head) do { \
LIST_FIRST((head)) = NULL; \
} while (0)
#define LIST_INSERT_AFTER(listelm, elm, field) do { \
QMD_LIST_CHECK_NEXT(listelm, field); \
if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\
LIST_NEXT((listelm), field)->field.le_prev = \
&LIST_NEXT((elm), field); \
LIST_NEXT((listelm), field) = (elm); \
(elm)->field.le_prev = &LIST_NEXT((listelm), field); \
} while (0)
#define LIST_INSERT_BEFORE(listelm, elm, field) do { \
QMD_LIST_CHECK_PREV(listelm, field); \
(elm)->field.le_prev = (listelm)->field.le_prev; \
LIST_NEXT((elm), field) = (listelm); \
*(listelm)->field.le_prev = (elm); \
(listelm)->field.le_prev = &LIST_NEXT((elm), field); \
} while (0)
#define LIST_INSERT_HEAD(head, elm, field) do { \
QMD_LIST_CHECK_HEAD((head), field); \
if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL) \
LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\
LIST_FIRST((head)) = (elm); \
(elm)->field.le_prev = &LIST_FIRST((head)); \
} while (0)
#define LIST_NEXT(elm, field) ((elm)->field.le_next)
#define LIST_PREV(elm, head, type, field) \
((elm)->field.le_prev == &LIST_FIRST((head)) ? NULL : \
__containerof((elm)->field.le_prev, \
QUEUE_TYPEOF(type), field.le_next))
#define LIST_REMOVE(elm, field) do { \
QMD_SAVELINK(oldnext, (elm)->field.le_next); \
QMD_SAVELINK(oldprev, (elm)->field.le_prev); \
QMD_LIST_CHECK_NEXT(elm, field); \
QMD_LIST_CHECK_PREV(elm, field); \
if (LIST_NEXT((elm), field) != NULL) \
LIST_NEXT((elm), field)->field.le_prev = \
(elm)->field.le_prev; \
*(elm)->field.le_prev = LIST_NEXT((elm), field); \
TRASHIT(*oldnext); \
TRASHIT(*oldprev); \
} while (0)
#define LIST_SWAP(head1, head2, type, field) do { \
QUEUE_TYPEOF(type) *swap_tmp = LIST_FIRST(head1); \
LIST_FIRST((head1)) = LIST_FIRST((head2)); \
LIST_FIRST((head2)) = swap_tmp; \
if ((swap_tmp = LIST_FIRST((head1))) != NULL) \
swap_tmp->field.le_prev = &LIST_FIRST((head1)); \
if ((swap_tmp = LIST_FIRST((head2))) != NULL) \
swap_tmp->field.le_prev = &LIST_FIRST((head2)); \
} while (0)
/*
* Tail queue declarations.
*/
#define TAILQ_HEAD(name, type) \
struct name { \
struct type *tqh_first; /* first element */ \
struct type **tqh_last; /* addr of last next element */ \
TRACEBUF \
}
#define TAILQ_CLASS_HEAD(name, type) \
struct name { \
class type *tqh_first; /* first element */ \
class type **tqh_last; /* addr of last next element */ \
TRACEBUF \
}
#define TAILQ_HEAD_INITIALIZER(head) \
{ NULL, &(head).tqh_first, TRACEBUF_INITIALIZER }
#define TAILQ_ENTRY(type) \
struct { \
struct type *tqe_next; /* next element */ \
struct type **tqe_prev; /* address of previous next element */ \
TRACEBUF \
}
#define TAILQ_CLASS_ENTRY(type) \
struct { \
class type *tqe_next; /* next element */ \
class type **tqe_prev; /* address of previous next element */ \
TRACEBUF \
}
/*
* Tail queue functions.
*/
#if (defined(_KERNEL) && defined(INVARIANTS))
#define QMD_TAILQ_CHECK_HEAD(head, field) do { \
if (!TAILQ_EMPTY(head) && \
TAILQ_FIRST((head))->field.tqe_prev != \
&TAILQ_FIRST((head))) \
panic("Bad tailq head %p first->prev != head", (head)); \
} while (0)
#define QMD_TAILQ_CHECK_TAIL(head, field) do { \
if (*(head)->tqh_last != NULL) \
panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head)); \
} while (0)
#define QMD_TAILQ_CHECK_NEXT(elm, field) do { \
if (TAILQ_NEXT((elm), field) != NULL && \
TAILQ_NEXT((elm), field)->field.tqe_prev != \
&((elm)->field.tqe_next)) \
panic("Bad link elm %p next->prev != elm", (elm)); \
} while (0)
#define QMD_TAILQ_CHECK_PREV(elm, field) do { \
if (*(elm)->field.tqe_prev != (elm)) \
panic("Bad link elm %p prev->next != elm", (elm)); \
} while (0)
#else
#define QMD_TAILQ_CHECK_HEAD(head, field)
#define QMD_TAILQ_CHECK_TAIL(head, headname)
#define QMD_TAILQ_CHECK_NEXT(elm, field)
#define QMD_TAILQ_CHECK_PREV(elm, field)
#endif /* (_KERNEL && INVARIANTS) */
#define TAILQ_CONCAT(head1, head2, field) do { \
if (!TAILQ_EMPTY(head2)) { \
*(head1)->tqh_last = (head2)->tqh_first; \
(head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \
(head1)->tqh_last = (head2)->tqh_last; \
TAILQ_INIT((head2)); \
QMD_TRACE_HEAD(head1); \
QMD_TRACE_HEAD(head2); \
} \
} while (0)
#define TAILQ_EMPTY(head) ((head)->tqh_first == NULL)
#define TAILQ_FIRST(head) ((head)->tqh_first)
#define TAILQ_FOREACH(var, head, field) \
for ((var) = TAILQ_FIRST((head)); \
(var); \
(var) = TAILQ_NEXT((var), field))
#define TAILQ_FOREACH_FROM(var, head, field) \
for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \
(var); \
(var) = TAILQ_NEXT((var), field))
#define TAILQ_FOREACH_SAFE(var, head, field, tvar) \
for ((var) = TAILQ_FIRST((head)); \
(var) && ((tvar) = TAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#define TAILQ_FOREACH_FROM_SAFE(var, head, field, tvar) \
for ((var) = ((var) ? (var) : TAILQ_FIRST((head))); \
(var) && ((tvar) = TAILQ_NEXT((var), field), 1); \
(var) = (tvar))
#define TAILQ_FOREACH_REVERSE(var, head, headname, field) \
for ((var) = TAILQ_LAST((head), headname); \
(var); \
(var) = TAILQ_PREV((var), headname, field))
#define TAILQ_FOREACH_REVERSE_FROM(var, head, headname, field) \
for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \
(var); \
(var) = TAILQ_PREV((var), headname, field))
#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \
for ((var) = TAILQ_LAST((head), headname); \
(var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \
(var) = (tvar))
#define TAILQ_FOREACH_REVERSE_FROM_SAFE(var, head, headname, field, tvar) \
for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname)); \
(var) && ((tvar) = TAILQ_PREV((var), headname, field), 1); \
(var) = (tvar))
#define TAILQ_INIT(head) do { \
TAILQ_FIRST((head)) = NULL; \
(head)->tqh_last = &TAILQ_FIRST((head)); \
QMD_TRACE_HEAD(head); \
} while (0)
#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \
QMD_TAILQ_CHECK_NEXT(listelm, field); \
if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\
TAILQ_NEXT((elm), field)->field.tqe_prev = \
&TAILQ_NEXT((elm), field); \
else { \
(head)->tqh_last = &TAILQ_NEXT((elm), field); \
QMD_TRACE_HEAD(head); \
} \
TAILQ_NEXT((listelm), field) = (elm); \
(elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field); \
QMD_TRACE_ELEM(&(elm)->field); \
QMD_TRACE_ELEM(&(listelm)->field); \
} while (0)
#define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \
QMD_TAILQ_CHECK_PREV(listelm, field); \
(elm)->field.tqe_prev = (listelm)->field.tqe_prev; \
TAILQ_NEXT((elm), field) = (listelm); \
*(listelm)->field.tqe_prev = (elm); \
(listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field); \
QMD_TRACE_ELEM(&(elm)->field); \
QMD_TRACE_ELEM(&(listelm)->field); \
} while (0)
#define TAILQ_INSERT_HEAD(head, elm, field) do { \
QMD_TAILQ_CHECK_HEAD(head, field); \
if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL) \
TAILQ_FIRST((head))->field.tqe_prev = \
&TAILQ_NEXT((elm), field); \
else \
(head)->tqh_last = &TAILQ_NEXT((elm), field); \
TAILQ_FIRST((head)) = (elm); \
(elm)->field.tqe_prev = &TAILQ_FIRST((head)); \
QMD_TRACE_HEAD(head); \
QMD_TRACE_ELEM(&(elm)->field); \
} while (0)
#define TAILQ_INSERT_TAIL(head, elm, field) do { \
QMD_TAILQ_CHECK_TAIL(head, field); \
TAILQ_NEXT((elm), field) = NULL; \
(elm)->field.tqe_prev = (head)->tqh_last; \
*(head)->tqh_last = (elm); \
(head)->tqh_last = &TAILQ_NEXT((elm), field); \
QMD_TRACE_HEAD(head); \
QMD_TRACE_ELEM(&(elm)->field); \
} while (0)
#define TAILQ_LAST(head, headname) \
(*(((struct headname *)((head)->tqh_last))->tqh_last))
#define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
#define TAILQ_PREV(elm, headname, field) \
(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
#define TAILQ_REMOVE(head, elm, field) do { \
QMD_SAVELINK(oldnext, (elm)->field.tqe_next); \
QMD_SAVELINK(oldprev, (elm)->field.tqe_prev); \
QMD_TAILQ_CHECK_NEXT(elm, field); \
QMD_TAILQ_CHECK_PREV(elm, field); \
if ((TAILQ_NEXT((elm), field)) != NULL) \
TAILQ_NEXT((elm), field)->field.tqe_prev = \
(elm)->field.tqe_prev; \
else { \
(head)->tqh_last = (elm)->field.tqe_prev; \
QMD_TRACE_HEAD(head); \
} \
*(elm)->field.tqe_prev = TAILQ_NEXT((elm), field); \
TRASHIT(*oldnext); \
TRASHIT(*oldprev); \
QMD_TRACE_ELEM(&(elm)->field); \
} while (0)
#define TAILQ_SWAP(head1, head2, type, field) do { \
QUEUE_TYPEOF(type) *swap_first = (head1)->tqh_first; \
QUEUE_TYPEOF(type) **swap_last = (head1)->tqh_last; \
(head1)->tqh_first = (head2)->tqh_first; \
(head1)->tqh_last = (head2)->tqh_last; \
(head2)->tqh_first = swap_first; \
(head2)->tqh_last = swap_last; \
if ((swap_first = (head1)->tqh_first) != NULL) \
swap_first->field.tqe_prev = &(head1)->tqh_first; \
else \
(head1)->tqh_last = &(head1)->tqh_first; \
if ((swap_first = (head2)->tqh_first) != NULL) \
swap_first->field.tqe_prev = &(head2)->tqh_first; \
else \
(head2)->tqh_last = &(head2)->tqh_first; \
} while (0)
#endif /* !_SYS_QUEUE_H_ */
-531
View File
@@ -1,531 +0,0 @@
#ifndef EXCLUDE_COMMON
#include "common/str_util.h"
#include "common/mg_mem.h"
#include "common/platform.h"
#ifndef C_DISABLE_BUILTIN_SNPRINTF
#define C_DISABLE_BUILTIN_SNPRINTF 0
#endif
#include "common/mg_mem.h"
size_t c_strnlen(const char *s, size_t maxlen) WEAK;
size_t c_strnlen(const char *s, size_t maxlen) {
size_t l = 0;
for (; l < maxlen && s[l] != '\0'; l++) {
}
return l;
}
#define C_SNPRINTF_APPEND_CHAR(ch) \
do { \
if (i < (int) buf_size) buf[i] = ch; \
i++; \
} while (0)
#define C_SNPRINTF_FLAG_ZERO 1
#if C_DISABLE_BUILTIN_SNPRINTF
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
return vsnprintf(buf, buf_size, fmt, ap);
}
#else
static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
int field_width) {
char tmp[40];
int i = 0, k = 0, neg = 0;
if (num < 0) {
neg++;
num = -num;
}
/* Print into temporary buffer - in reverse order */
do {
int rem = num % base;
if (rem < 10) {
tmp[k++] = '0' + rem;
} else {
tmp[k++] = 'a' + (rem - 10);
}
num /= base;
} while (num > 0);
/* Zero padding */
if (flags && C_SNPRINTF_FLAG_ZERO) {
while (k < field_width && k < (int) sizeof(tmp) - 1) {
tmp[k++] = '0';
}
}
/* And sign */
if (neg) {
tmp[k++] = '-';
}
/* Now output */
while (--k >= 0) {
C_SNPRINTF_APPEND_CHAR(tmp[k]);
}
return i;
}
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
int ch, i = 0, len_mod, flags, precision, field_width;
while ((ch = *fmt++) != '\0') {
if (ch != '%') {
C_SNPRINTF_APPEND_CHAR(ch);
} else {
/*
* Conversion specification:
* zero or more flags (one of: # 0 - <space> + ')
* an optional minimum field width (digits)
* an optional precision (. followed by digits, or *)
* an optional length modifier (one of: hh h l ll L q j z t)
* conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
*/
flags = field_width = precision = len_mod = 0;
/* Flags. only zero-pad flag is supported. */
if (*fmt == '0') {
flags |= C_SNPRINTF_FLAG_ZERO;
}
/* Field width */
while (*fmt >= '0' && *fmt <= '9') {
field_width *= 10;
field_width += *fmt++ - '0';
}
/* Dynamic field width */
if (*fmt == '*') {
field_width = va_arg(ap, int);
fmt++;
}
/* Precision */
if (*fmt == '.') {
fmt++;
if (*fmt == '*') {
precision = va_arg(ap, int);
fmt++;
} else {
while (*fmt >= '0' && *fmt <= '9') {
precision *= 10;
precision += *fmt++ - '0';
}
}
}
/* Length modifier */
switch (*fmt) {
case 'h':
case 'l':
case 'L':
case 'I':
case 'q':
case 'j':
case 'z':
case 't':
len_mod = *fmt++;
if (*fmt == 'h') {
len_mod = 'H';
fmt++;
}
if (*fmt == 'l') {
len_mod = 'q';
fmt++;
}
break;
}
ch = *fmt++;
if (ch == 's') {
const char *s = va_arg(ap, const char *); /* Always fetch parameter */
int j;
int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
for (j = 0; j < pad; j++) {
C_SNPRINTF_APPEND_CHAR(' ');
}
/* `s` may be NULL in case of %.*s */
if (s != NULL) {
/* Ignore negative and 0 precisions */
for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
C_SNPRINTF_APPEND_CHAR(s[j]);
}
}
} else if (ch == 'c') {
ch = va_arg(ap, int); /* Always fetch parameter */
C_SNPRINTF_APPEND_CHAR(ch);
} else if (ch == 'd' && len_mod == 0) {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
field_width);
} else if (ch == 'd' && len_mod == 'l') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
field_width);
#ifdef SSIZE_MAX
} else if (ch == 'd' && len_mod == 'z') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
field_width);
#endif
} else if (ch == 'd' && len_mod == 'q') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
ch == 'x' ? 16 : 10, flags, field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
ch == 'x' ? 16 : 10, flags, field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
ch == 'x' ? 16 : 10, flags, field_width);
} else if (ch == 'p') {
unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *);
C_SNPRINTF_APPEND_CHAR('0');
C_SNPRINTF_APPEND_CHAR('x');
i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
} else {
#ifndef NO_LIBC
/*
* TODO(lsm): abort is not nice in a library, remove it
* Also, ESP8266 SDK doesn't have it
*/
abort();
#endif
}
}
}
/* Zero-terminate the result */
if (buf_size > 0) {
buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
}
return i;
}
#endif
int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK;
int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
int result;
va_list ap;
va_start(ap, fmt);
result = c_vsnprintf(buf, buf_size, fmt, ap);
va_end(ap);
return result;
}
#ifdef _WIN32
int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
int ret;
char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
strncpy(buf, path, sizeof(buf));
buf[sizeof(buf) - 1] = '\0';
/* Trim trailing slashes. Leave backslash for paths like "X:\" */
p = buf + strlen(buf) - 1;
while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
/*
* Convert back to Unicode. If doubly-converted string does not match the
* original, something is fishy, reject.
*/
WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
NULL, NULL);
if (strcmp(buf, buf2) != 0) {
wbuf[0] = L'\0';
ret = 0;
}
return ret;
}
#endif /* _WIN32 */
/* The simplest O(mn) algorithm. Better implementation are GPLed */
const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK;
const char *c_strnstr(const char *s, const char *find, size_t slen) {
size_t find_length = strlen(find);
size_t i;
for (i = 0; i < slen; i++) {
if (i + find_length > slen) {
return NULL;
}
if (strncmp(&s[i], find, find_length) == 0) {
return &s[i];
}
}
return NULL;
}
#if CS_ENABLE_STRDUP
char *strdup(const char *src) WEAK;
char *strdup(const char *src) {
size_t len = strlen(src) + 1;
char *ret = MG_MALLOC(len);
if (ret != NULL) {
strcpy(ret, src);
}
return ret;
}
#endif
void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK;
void cs_to_hex(char *to, const unsigned char *p, size_t len) {
static const char *hex = "0123456789abcdef";
for (; len--; p++) {
*to++ = hex[p[0] >> 4];
*to++ = hex[p[0] & 0x0f];
}
*to = '\0';
}
static int fourbit(int ch) {
if (ch >= '0' && ch <= '9') {
return ch - '0';
} else if (ch >= 'a' && ch <= 'f') {
return ch - 'a' + 10;
} else if (ch >= 'A' && ch <= 'F') {
return ch - 'A' + 10;
}
return 0;
}
void cs_from_hex(char *to, const char *p, size_t len) WEAK;
void cs_from_hex(char *to, const char *p, size_t len) {
size_t i;
for (i = 0; i < len; i += 2) {
*to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]);
}
*to = '\0';
}
#if CS_ENABLE_TO64
int64_t cs_to64(const char *s) WEAK;
int64_t cs_to64(const char *s) {
int64_t result = 0;
int64_t neg = 1;
while (*s && isspace((unsigned char) *s)) s++;
if (*s == '-') {
neg = -1;
s++;
}
while (isdigit((unsigned char) *s)) {
result *= 10;
result += (*s - '0');
s++;
}
return result * neg;
}
#endif
static int str_util_lowercase(const char *s) {
return tolower(*(const unsigned char *) s);
}
int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
int diff = 0;
if (len > 0) do {
diff = str_util_lowercase(s1++) - str_util_lowercase(s2++);
} while (diff == 0 && s1[-1] != '\0' && --len > 0);
return diff;
}
int mg_casecmp(const char *s1, const char *s2) WEAK;
int mg_casecmp(const char *s1, const char *s2) {
return mg_ncasecmp(s1, s2, (size_t) ~0);
}
int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK;
int mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
int ret;
va_list ap;
va_start(ap, fmt);
ret = mg_avprintf(buf, size, fmt, ap);
va_end(ap);
return ret;
}
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK;
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
va_list ap_copy;
int len;
va_copy(ap_copy, ap);
len = vsnprintf(*buf, size, fmt, ap_copy);
va_end(ap_copy);
if (len < 0) {
/* eCos and Windows are not standard-compliant and return -1 when
* the buffer is too small. Keep allocating larger buffers until we
* succeed or out of memory. */
*buf = NULL; /* LCOV_EXCL_START */
while (len < 0) {
MG_FREE(*buf);
if (size == 0) {
size = 5;
}
size *= 2;
if ((*buf = (char *) MG_MALLOC(size)) == NULL) {
len = -1;
break;
}
va_copy(ap_copy, ap);
len = vsnprintf(*buf, size - 1, fmt, ap_copy);
va_end(ap_copy);
}
/*
* Microsoft version of vsnprintf() is not always null-terminated, so put
* the terminator manually
*/
(*buf)[len] = 0;
/* LCOV_EXCL_STOP */
} else if (len >= (int) size) {
/* Standard-compliant code path. Allocate a buffer that is large enough. */
if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
len = -1; /* LCOV_EXCL_LINE */
} else { /* LCOV_EXCL_LINE */
va_copy(ap_copy, ap);
len = vsnprintf(*buf, len + 1, fmt, ap_copy);
va_end(ap_copy);
}
}
return len;
}
static struct mg_str mg_next_list_entry_n(struct mg_str list, char sep1,
struct mg_str *val1, char sep2,
struct mg_str *val2) {
if (list.len == 0) {
/* End of the list */
list = mg_mk_str(NULL);
} else {
const char *chr = NULL;
*val1 = list;
if ((chr = mg_strchr(*val1, sep1)) != NULL) {
/* Comma found. Store length and shift the list ptr */
val1->len = chr - val1->p;
chr++;
list.len -= (chr - list.p);
list.p = chr;
} else {
/* This value is the last one */
list = mg_mk_str_n(list.p + list.len, 0);
}
if (val2 != NULL) {
/* Value has form "x=y", adjust pointers and lengths */
/* so that val points to "x", and eq_val points to "y". */
val2->len = 0;
val2->p = (const char *) memchr(val1->p, sep2, val1->len);
if (val2->p != NULL) {
val2->p++; /* Skip over sep2 character */
val2->len = val1->p + val1->len - val2->p;
val1->len = (val2->p - val1->p) - 1;
}
}
}
return list;
}
const char *mg_next_comma_list_entry(const char *, struct mg_str *,
struct mg_str *) WEAK;
const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
struct mg_str *eq_val) {
struct mg_str ret = mg_next_comma_list_entry_n(mg_mk_str(list), val, eq_val);
return ret.p;
}
struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
struct mg_str *eq_val) WEAK;
struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
struct mg_str *eq_val) {
return mg_next_list_entry_n(list, ',', val, '=', eq_val);
}
struct mg_str mg_next_query_string_entry_n(struct mg_str list,
struct mg_str *val,
struct mg_str *eq_val) WEAK;
struct mg_str mg_next_query_string_entry_n(struct mg_str list,
struct mg_str *val,
struct mg_str *eq_val) {
return mg_next_list_entry_n(list, '&', val, '=', eq_val);
}
size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK;
size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
const char *or_str;
size_t res = 0, len = 0, i = 0, j = 0;
if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL ||
(or_str = (const char *) memchr(pattern.p, ',', pattern.len)) != NULL) {
struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
res = mg_match_prefix_n(pstr, str);
if (res > 0) return res;
pstr.p = or_str + 1;
pstr.len = (pattern.p + pattern.len) - (or_str + 1);
return mg_match_prefix_n(pstr, str);
}
for (; i < pattern.len && j < str.len; i++, j++) {
if (pattern.p[i] == '?') {
continue;
} else if (pattern.p[i] == '*') {
i++;
if (i < pattern.len && pattern.p[i] == '*') {
i++;
len = str.len - j;
} else {
len = 0;
while (j + len < str.len && str.p[j + len] != '/') len++;
}
if (i == pattern.len || (pattern.p[i] == '$' && i == pattern.len - 1))
return j + len;
do {
const struct mg_str pstr = {pattern.p + i, pattern.len - i};
const struct mg_str sstr = {str.p + j + len, str.len - j - len};
res = mg_match_prefix_n(pstr, sstr);
} while (res == 0 && len != 0 && len-- > 0);
return res == 0 ? 0 : j + res + len;
} else if (str_util_lowercase(&pattern.p[i]) !=
str_util_lowercase(&str.p[j])) {
break;
}
}
if (i < pattern.len && pattern.p[i] == '$') {
return j == str.len ? str.len : 0;
}
return i == pattern.len ? j : 0;
}
size_t mg_match_prefix(const char *, int, const char *) WEAK;
size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
const struct mg_str pstr = {pattern, (size_t) pattern_len};
struct mg_str s = {str, 0};
if (str != NULL) s.len = strlen(str);
return mg_match_prefix_n(pstr, s);
}
#endif /* EXCLUDE_COMMON */
-190
View File
@@ -1,190 +0,0 @@
#ifndef CS_COMMON_STR_UTIL_H_
#define CS_COMMON_STR_UTIL_H_
#include <stdarg.h>
#include <stdlib.h>
#include "common/mg_str.h"
#include "common/platform.h"
#ifndef CS_ENABLE_STRDUP
#define CS_ENABLE_STRDUP 0
#endif
#ifndef CS_ENABLE_TO64
#define CS_ENABLE_TO64 0
#endif
/*
* Expands to a string representation of its argument: e.g.
* `CS_STRINGIFY_LIT(5) expands to "5"`
*/
#if !defined(_MSC_VER) || _MSC_VER >= 1900
#define CS_STRINGIFY_LIT(...) #__VA_ARGS__
#else
#define CS_STRINGIFY_LIT(x) #x
#endif
/*
* Expands to a string representation of its argument, which is allowed
* to be a macro: e.g.
*
* #define FOO 123
* CS_STRINGIFY_MACRO(FOO)
*
* expands to 123.
*/
#define CS_STRINGIFY_MACRO(x) CS_STRINGIFY_LIT(x)
#ifdef __cplusplus
extern "C" {
#endif
/*
* Equivalent of standard `strnlen()`.
*/
size_t c_strnlen(const char *s, size_t maxlen);
/*
* Equivalent of standard `snprintf()`.
*/
int c_snprintf(char *buf, size_t buf_size, const char *format, ...)
PRINTF_LIKE(3, 4);
/*
* Equivalent of standard `vsnprintf()`.
*/
int c_vsnprintf(char *buf, size_t buf_size, const char *format, va_list ap);
/*
* Find the first occurrence of find in s, where the search is limited to the
* first slen characters of s.
*/
const char *c_strnstr(const char *s, const char *find, size_t slen);
/*
* Stringify binary data. Output buffer size must be 2 * size_of_input + 1
* because each byte of input takes 2 bytes in string representation
* plus 1 byte for the terminating \0 character.
*/
void cs_to_hex(char *to, const unsigned char *p, size_t len);
/*
* Convert stringified binary data back to binary.
* Does the reverse of `cs_to_hex()`.
*/
void cs_from_hex(char *to, const char *p, size_t len);
#if CS_ENABLE_STRDUP
/*
* Equivalent of standard `strdup()`, defined if only `CS_ENABLE_STRDUP` is 1.
*/
char *strdup(const char *src);
#endif
#if CS_ENABLE_TO64
#include <stdint.h>
/*
* Simple string -> int64 conversion routine.
*/
int64_t cs_to64(const char *s);
#endif
/*
* Cross-platform version of `strncasecmp()`.
*/
int mg_ncasecmp(const char *s1, const char *s2, size_t len);
/*
* Cross-platform version of `strcasecmp()`.
*/
int mg_casecmp(const char *s1, const char *s2);
/*
* Prints message to the buffer. If the buffer is large enough to hold the
* message, it returns buffer. If buffer is to small, it allocates a large
* enough buffer on heap and returns allocated buffer.
* This is a supposed use case:
*
* ```c
* char buf[5], *p = buf;
* mg_avprintf(&p, sizeof(buf), "%s", "hi there");
* use_p_somehow(p);
* if (p != buf) {
* free(p);
* }
* ```
*
* The purpose of this is to avoid malloc-ing if generated strings are small.
*/
int mg_asprintf(char **buf, size_t size, const char *fmt, ...)
PRINTF_LIKE(3, 4);
/* Same as mg_asprintf, but takes varargs list. */
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap);
/*
* A helper function for traversing a comma separated list of values.
* It returns a list pointer shifted to the next value or NULL if the end
* of the list found.
* The value is stored in a val vector. If the value has a form "x=y", then
* eq_val vector is initialised to point to the "y" part, and val vector length
* is adjusted to point only to "x".
* If the list is just a comma separated list of entries, like "aa,bb,cc" then
* `eq_val` will contain zero-length string.
*
* The purpose of this function is to parse comma separated string without
* any copying/memory allocation.
*/
const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
struct mg_str *eq_val);
/*
* Like `mg_next_comma_list_entry()`, but takes `list` as `struct mg_str`.
* NB: Test return value's .p, not .len. On last itreation that yields result
* .len will be 0 but .p will not. When finished, .p will be NULL.
*/
struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
struct mg_str *eq_val);
/*
* Helper for parsing query strings.
* Parses '&' and '=' entries. Does not perform unescaping.
*/
struct mg_str mg_next_query_string_entry_n(struct mg_str list,
struct mg_str *val,
struct mg_str *eq_val);
/*
* Matches 0-terminated string (mg_match_prefix) or string with given length
* mg_match_prefix_n against a glob pattern. Glob syntax:
* ```
* - * matches zero or more characters until a slash character /
* - ** matches zero or more characters
* - ? Matches exactly one character which is not a slash /
* - | or , divides alternative patterns
* - any other character matches itself
* ```
* Match is case-insensitive. Return number of bytes matched.
* Examples:
* ```
* mg_match_prefix("a*f", len, "abcdefgh") == 6
* mg_match_prefix("a*f", len, "abcdexgh") == 0
* mg_match_prefix("a*f|de*,xy", len, "defgh") == 5
* mg_match_prefix("?*", len, "abc") == 3
* mg_match_prefix("?*", len, "") == 0
* ```
*/
size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str);
/*
* Like `mg_match_prefix()`, but takes `pattern` and `str` as `struct mg_str`.
*/
size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str);
#ifdef __cplusplus
}
#endif
#endif /* CS_COMMON_STR_UTIL_H_ */
+65
View File
@@ -0,0 +1,65 @@
#pragma once
#ifndef MG_ENABLE_LWIP
#define MG_ENABLE_LWIP 0
#endif
#if MG_ENABLE_LWIP
#define MG_ENABLE_SOCKET 0
#else
#define MG_ENABLE_SOCKET 1
#endif
#ifndef MG_ENABLE_MBEDTLS
#define MG_ENABLE_MBEDTLS 0
#endif
#ifndef MG_ENABLE_OPENSSL
#define MG_ENABLE_OPENSSL 0
#endif
#ifndef MG_ENABLE_FS
#define MG_ENABLE_FS 1
#endif
#ifndef MG_ENABLE_IPV6
#define MG_ENABLE_IPV6 0
#endif
#ifndef MG_ENABLE_LOG
#define MG_ENABLE_LOG 1
#endif
#ifndef MG_ENABLE_MGOS
#define MG_ENABLE_MGOS 0
#endif
#ifndef MG_ENABLE_MD5
#define MG_ENABLE_MD5 0
#endif
#ifndef MG_ENABLE_DIRECTORY_LISTING
#define MG_ENABLE_DIRECTORY_LISTING 0
#endif
#ifndef MG_ENABLE_HTTP_DEBUG_ENDPOINT
#define MG_ENABLE_HTTP_DEBUG_ENDPOINT 0
#endif
#ifndef MG_ENABLE_SOCKETPAIR
#define MG_ENABLE_SOCKETPAIR 0
#endif
// Granularity of the send/recv IO buffer growth
#ifndef MG_IO_SIZE
#define MG_IO_SIZE 512
#endif
// Maximum size of the recv IO buffer
#ifndef MG_MAX_RECV_BUF_SIZE
#define MG_MAX_RECV_BUF_SIZE (3 * 1024 * 1024)
#endif
#ifndef MG_MAX_HTTP_HEADERS
#define MG_MAX_HTTP_HEADERS 40
#endif
+205
View File
@@ -0,0 +1,205 @@
#include "dns.h"
#include "log.h"
#include "private.h"
#include "str.h"
#include "timer.h"
#include "util.h"
struct mg_dns_header {
uint16_t transaction_id;
uint16_t flags;
uint16_t num_questions;
uint16_t num_answers;
uint16_t num_authority_prs;
uint16_t num_other_prs;
};
struct dns_data {
struct dns_data *next;
struct mg_connection *c;
unsigned long expire;
uint16_t txnid;
};
static void mg_dns_free(struct dns_data **head, struct dns_data *d) {
LIST_DELETE(struct dns_data, head, d);
// LOG(LL_INFO, ("--> %p %p %d", d, d->c, d->c->fd));
free(d);
}
void mg_resolve_cancel(struct mg_mgr *mgr, struct mg_connection *c) {
struct dns_data *tmp, *d, **head;
head = mgr->dnsc == NULL ? NULL : (struct dns_data **) &mgr->dnsc->pfn_data;
for (d = head == NULL ? NULL : *head; d != NULL; d = tmp) {
tmp = d->next;
if (d->c == c) mg_dns_free(head, d);
}
}
static size_t mg_dns_parse_name(const uint8_t *s, const uint8_t *e, size_t off,
char *to, size_t tolen, int depth) {
size_t i = 0, j = 0;
while (&s[off + i + 1] < e && s[off + i] > 0) {
size_t n = s[off + i];
if (n & 0xc0) {
size_t ptr = (((n & 0x3f) << 8) | s[off + i + 1]) - 12; // 12 is hdr len
if (&s[ptr + 1] < e && (s[ptr] & 0xc0) == 0 && depth < 5) {
j = mg_dns_parse_name(s, e, ptr, to, tolen, depth + 1);
}
i++;
break;
}
if (&s[off + i + n + 1] >= e) break;
if (j > 0 && j < tolen) to[j++] = '.';
if (j + n < tolen) memcpy(&to[j], &s[off + i + 1], n);
j += n;
i += n + 1;
}
if (j < tolen) to[j] = '\0'; // Zero-terminate the name
to[tolen - 1] = '\0'; // Just in case
return i;
}
// txid flags numQ numA numAP numOP
// 0000 00 01 81 80 00 01 00 01 00 00 00 00 07 63 65 73 .............ces
// 0010 61 6e 74 61 03 63 6f 6d 00 00 01 00 01 c0 0c 00 anta.com........
// 0020 01 00 01 00 00 02 57 00 04 94 fb 36 ec ......W....6.
int mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) {
struct mg_dns_header *h = (struct mg_dns_header *) buf;
const uint8_t *s = buf + sizeof(*h), *e = &buf[len];
size_t i, j, n, ok = 0;
if (len < sizeof(*h)) return ok;
for (i = j = 0; i < mg_ntohs(h->num_questions); i++) {
j += mg_dns_parse_name(s, e, j, dm->name, sizeof(dm->name), 0) + 5;
// LOG(LL_INFO, ("QUE [%s]", name));
}
for (i = 0; i < mg_ntohs(h->num_answers); i++) {
j += mg_dns_parse_name(s, e, j, dm->name, sizeof(dm->name), 0) + 9;
// LOG(LL_DEBUG, ("NAME %s", name));
if (&s[j] + 2 > e) break;
n = ((int) s[j] << 8) | s[j + 1];
if (&s[j] + 2 + n > e) break;
if (n == 4) {
dm->txnid = mg_ntohs(h->transaction_id);
memcpy(&dm->ipaddr, &s[j + 2], 4);
ok = 1;
break;
}
j += 2 + n;
}
return ok;
}
static void dns_cb(struct mg_connection *c, int ev, void *ev_data,
void *fn_data) {
struct dns_data *d, *tmp, **head = (struct dns_data **) &c->pfn_data;
if (ev == MG_EV_POLL) {
unsigned long now = *(unsigned long *) ev_data;
for (d = (struct dns_data *) fn_data; d != NULL; d = tmp) {
tmp = d->next;
// LOG(LL_DEBUG, ("%lu %lu dns poll", d->expire, now));
if (now > d->expire) mg_error(d->c, "DNS timeout");
}
} else if (ev == MG_EV_READ) {
struct mg_dns_message dm;
int resolved = 0;
if (mg_dns_parse(c->recv.buf, c->recv.len, &dm)) {
for (d = (struct dns_data *) c->pfn_data; d != NULL; d = tmp) {
tmp = d->next;
// LOG(LL_INFO, ("d %p %p", d, tmp));
if (dm.txnid != d->txnid) continue;
if (d->c->is_resolving) {
d->c->is_resolving = 0;
d->c->peer.ip = dm.ipaddr;
mg_connect_resolved(d->c);
mg_dns_free(head, d);
} else {
LOG(LL_ERROR, ("%p already resolved", d->c->fd));
}
resolved = 1;
}
}
if (!resolved) LOG(LL_ERROR, ("stray DNS reply"));
c->recv.len = 0;
} else if (ev == MG_EV_CLOSE) {
for (d = *head; d != NULL; d = tmp) {
tmp = d->next;
mg_dns_free(head, d);
}
}
}
void mg_dns_send(struct mg_connection *c, const struct mg_str *name,
uint16_t txnid) {
struct {
struct mg_dns_header header;
uint8_t data[256];
} pkt;
size_t i, n;
memset(&pkt, 0, sizeof(pkt));
pkt.header.transaction_id = mg_htons(txnid);
pkt.header.flags = mg_htons(0x100);
pkt.header.num_questions = mg_htons(1);
for (i = n = 0; i < sizeof(pkt.data) - 5; i++) {
if (name->ptr[i] == '.' || i >= name->len) {
pkt.data[n] = (uint8_t)(i - n);
memcpy(&pkt.data[n + 1], name->ptr + n, i - n);
n = i + 1;
}
if (i >= name->len) break;
}
memcpy(&pkt.data[n], "\x00\x00\x01\x00\x01", 5); // A query
n += 5;
mg_send(c, &pkt, sizeof(pkt.header) + n);
#if 0
// Immediately after A query, send AAAA query. Whatever reply comes first,
// we'll use it. Note: we cannot send two queries in a single packet.
// https://stackoverflow.com/questions/4082081/requesting-a-and-aaaa-records-in-single-dns-query
pkt.data[n - 3] = 0x1c; // AAAA query
mg_send(c, &pkt, sizeof(pkt.header) + n);
#endif
}
void mg_resolve(struct mg_mgr *mgr, struct mg_connection *c,
struct mg_str *name, int ms) {
struct dns_data *d = NULL;
int resolved = mg_aton(name->ptr, &c->peer.ip);
// Try to parse name as IP address
if (mg_vcmp(name, "localhost") == 0) {
resolved = 1;
c->peer.ip = mg_htonl(0x7f000001);
}
if (resolved) {
// name is an IP address, do not fire name resolution
mg_connect_resolved(c);
} else {
// name is not an IP, send DNS resolution request
if (mgr->dnsc == NULL) {
const char *srv = mgr->dnsserver ? mgr->dnsserver : "udp://8.8.8.8:53";
mgr->dnsc = mg_connect(mgr, srv, NULL, NULL);
if (mgr->dnsc != NULL) {
mgr->dnsc->pfn = dns_cb;
// mgr->dnsc->is_hexdumping = 1;
snprintf(mgr->dnsc->label, sizeof(mgr->dnsc->label), "%s", "RESOLVER");
}
}
if (mgr->dnsc == NULL) {
mg_error(c, "resolver");
} else if ((d = (struct dns_data *) calloc(1, sizeof(*d))) == NULL) {
mg_error(c, "resolve OOM");
} else {
struct dns_data **head = (struct dns_data **) &mgr->dnsc->pfn_data;
d->txnid = *head ? (*head)->txnid + 1 : 1;
d->next = *head;
*head = d;
d->expire = mg_millis() + ms;
d->c = c;
c->is_resolving = 1;
LOG(LL_DEBUG, ("%p resolving %.*s, txnid %hu", c->fd, (int) name->len,
name->ptr, d->txnid));
mg_dns_send(mgr->dnsc, name, d->txnid);
}
}
}
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include "net.h"
#include "str.h"
struct mg_dns_message {
uint16_t txnid; // Transaction ID
uint32_t ipaddr; // Resolved IPv4 address
char name[256]; // Host name
};
void mg_resolve(struct mg_mgr *, struct mg_connection *, struct mg_str *, int);
void mg_resolve_cancel(struct mg_mgr *, struct mg_connection *);
int mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *);
+21
View File
@@ -0,0 +1,21 @@
#include "event.h"
#include "log.h"
#include "net.h"
#include "util.h"
void mg_call(struct mg_connection *c, int ev, void *ev_data) {
if (c->pfn != NULL) c->pfn(c, ev, ev_data, c->pfn_data);
if (c->fn != NULL) c->fn(c, ev, ev_data, c->fn_data);
}
void mg_error(struct mg_connection *c, const char *fmt, ...) {
char mem[256], *buf = mem;
va_list ap;
va_start(ap, fmt);
mg_vasprintf(&buf, sizeof(mem), fmt, ap);
va_end(ap);
LOG(LL_ERROR, ("%p %s", c->fd, buf));
mg_call(c, MG_EV_ERROR, buf);
if (buf != mem) free(buf);
c->is_closing = 1;
}
+37
View File
@@ -0,0 +1,37 @@
#pragma once
struct mg_connection;
typedef void (*mg_event_handler_t)(struct mg_connection *, int ev,
void *ev_data, void *fn_data);
#if 0
struct mg_fn {
struct mg_fn *next;
mg_event_handler_t fn;
void *fn_data;
};
void mg_fn_add(struct mg_connection *c, mg_event_handler_t fn, void *fn_data);
void mg_fn_del(struct mg_connection *c, mg_event_handler_t fn);
#endif
void mg_call(struct mg_connection *c, int ev, void *ev_data);
void mg_error(struct mg_connection *c, const char *fmt, ...);
enum {
MG_EV_ERROR, // Error char *error_message
MG_EV_POLL, // mg_mgr_poll iteration unsigned long *millis
MG_EV_RESOLVE, // Host name is resolved NULL
MG_EV_CONNECT, // Connection established NULL
MG_EV_ACCEPT, // Connection accepted NULL
MG_EV_READ, // Data received from socket struct mg_str *
MG_EV_WRITE, // Data written to socket int *num_bytes_written
MG_EV_CLOSE, // Connection closed NULL
MG_EV_HTTP_MSG, // HTTP request/response struct mg_http_message *
MG_EV_WS_OPEN, // Websocket handshake done NULL
MG_EV_WS_MSG, // Websocket message received struct mg_ws_message *
MG_EV_MQTT_MSG, // MQTT message struct mg_mqtt_message *
MG_EV_MQTT_OPEN, // MQTT CONNACK received int *connack_status_code
MG_EV_SNTP_TIME, // SNTP time received struct timeval *
MG_EV_USER, // Starting ID for user events
};
+682
View File
@@ -0,0 +1,682 @@
#include "http.h"
#include "arch.h"
#include "base64.h"
#include "log.h"
#include "net.h"
#include "private.h"
#include "util.h"
#include "ws.h"
struct http_data {
void *old_pfn_data; // Previous pfn_data
FILE *fp; // For static file serving
};
// Multipart POST example:
// https://gist.github.com/cpq/b8dd247571e6ee9c54ef7e8dfcfecf48
void mg_http_bauth(struct mg_connection *c, const char *user,
const char *pass) {
struct mg_str u = mg_str(user), p = mg_str(pass);
size_t need = c->send.len + 36 + (u.len + p.len) * 2;
if (c->send.size < need) mg_iobuf_resize(&c->send, need);
if (c->send.size >= need) {
size_t i, n = 0;
char *buf = (char *) &c->send.buf[c->send.len + 21];
memcpy(&buf[-21], "Authorization: Basic ", 21); // DON'T use mg_send!
for (i = 0; i < u.len; i++) n = mg_base64_update(u.ptr[i], buf, n);
if (p.len > 0) {
n = mg_base64_update(':', buf, n);
for (i = 0; i < p.len; i++) n = mg_base64_update(p.ptr[i], buf, n);
}
n = mg_base64_final(buf, n);
c->send.len += 21 + n + 2;
memcpy(&c->send.buf[c->send.len - 2], "\r\n", 2);
} else {
LOG(LL_ERROR, ("%p %s cannot resize iobuf %d->%d ", c->fd, c->label,
(int) c->send.size, (int) need));
}
}
int mg_http_get_var(const struct mg_str *buf, const char *name, char *dst,
int dst_len) {
const char *p, *e, *s;
size_t name_len;
int len;
if (dst == NULL || dst_len == 0) {
len = -2; // Bad destination
} else if (buf->ptr == NULL || name == NULL || buf->len == 0) {
len = -1; // Bad source
dst[0] = '\0';
} else {
name_len = strlen(name);
e = buf->ptr + buf->len;
len = -4; // Name does not exist
dst[0] = '\0';
for (p = buf->ptr; p + name_len < e; p++) {
if ((p == buf->ptr || p[-1] == '&') && p[name_len] == '=' &&
!mg_ncasecmp(name, p, name_len)) {
p += name_len + 1;
s = (const char *) memchr(p, '&', (size_t)(e - p));
if (s == NULL) s = e;
len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
if (len == -1) len = -3; // Failed to decode
break;
}
}
}
return len;
}
int mg_url_decode(const char *src, size_t src_len, char *dst, size_t dst_len,
int is_form_url_encoded) {
size_t i, j;
for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
if (src[i] == '%') {
if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
isxdigit(*(const unsigned char *) (src + i + 2))) {
mg_unhex(src + i + 1, 2, (uint8_t *) &dst[j]);
i += 2;
} else {
return -1;
}
} else if (is_form_url_encoded && src[i] == '+') {
dst[j] = ' ';
} else {
dst[j] = src[i];
}
}
dst[j] = '\0'; // Null-terminate the destination
return i >= src_len ? (int) j : -1;
}
int mg_http_get_request_len(const unsigned char *buf, size_t buf_len) {
size_t i;
for (i = 0; i < buf_len; i++) {
if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128)
return -1;
if ((i > 0 && buf[i] == '\n' && buf[i - 1] == '\n') ||
(i > 3 && buf[i] == '\n' && buf[i - 1] == '\r' && buf[i - 2] == '\n'))
return (int) i + 1;
}
return 0;
}
static const char *skip(const char *s, const char *end, const char *delims,
struct mg_str *v) {
v->ptr = s;
while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
v->len = s - v->ptr;
while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
return s;
}
struct mg_str *mg_http_get_header(struct mg_http_message *h, const char *name) {
size_t i, n = strlen(name), max = sizeof(h->headers) / sizeof(h->headers[0]);
for (i = 0; i < max && h->headers[i].name.len > 0; i++) {
struct mg_str *k = &h->headers[i].name, *v = &h->headers[i].value;
if (n == k->len && mg_ncasecmp(k->ptr, name, n) == 0) return v;
}
return NULL;
}
void mg_http_parse_headers(const char *s, const char *end,
struct mg_http_header *h, int max_headers) {
int i;
for (i = 0; i < max_headers; i++) {
struct mg_str k, v, tmp;
const char *he = skip(s, end, "\n", &tmp);
s = skip(s, he, ": \r\n", &k);
s = skip(s, he, "\r\n", &v);
if (k.len == tmp.len) continue;
while (v.len > 0 && v.ptr[v.len - 1] == ' ') v.len--; // Trim spaces
if (k.len == 0) break;
// LOG(LL_INFO, ("--HH [%.*s] [%.*s] [%.*s]", (int) tmp.len - 1, tmp.ptr,
//(int) k.len, k.ptr, (int) v.len, v.ptr));
h[i].name = k;
h[i].value = v;
}
}
int mg_http_parse(const char *s, size_t len, struct mg_http_message *hm) {
int is_response, req_len = mg_http_get_request_len((unsigned char *) s, len);
const char *end = s + req_len, *qs;
struct mg_str *cl;
memset(hm, 0, sizeof(*hm));
if (req_len <= 0) return req_len;
hm->message.ptr = s;
hm->body.ptr = s + req_len;
hm->message.len = hm->body.len = (size_t) ~0; // Set body length to infinite
// Parse request line
s = skip(s, end, " ", &hm->method);
s = skip(s, end, " ", &hm->uri);
s = skip(s, end, "\r\n", &hm->proto);
if (hm->uri.ptr <= hm->method.ptr || hm->proto.ptr <= hm->uri.ptr) return -1;
// If URI contains '?' character, setup query string
if ((qs = (const char *) memchr(hm->uri.ptr, '?', hm->uri.len)) != NULL) {
hm->query.ptr = qs + 1;
hm->query.len = &hm->uri.ptr[hm->uri.len] - (qs + 1);
hm->uri.len = qs - hm->uri.ptr;
}
mg_http_parse_headers(s, end, hm->headers,
sizeof(hm->headers) / sizeof(hm->headers[0]));
if ((cl = mg_http_get_header(hm, "Content-Length")) != NULL) {
hm->body.len = (size_t) mg_to64(cl->ptr);
hm->message.len = req_len + hm->body.len;
}
// mg_http_parse() is used to parse both HTTP requests and HTTP
// responses. If HTTP response does not have Content-Length set, then
// body is read until socket is closed, i.e. body.len is infinite (~0).
//
// For HTTP requests though, according to
// http://tools.ietf.org/html/rfc7231#section-8.1.3,
// only POST and PUT methods have defined body semantics.
// Therefore, if Content-Length is not specified and methods are
// not one of PUT or POST, set body length to 0.
//
// So, if it is HTTP request, and Content-Length is not set,
// and method is not (PUT or POST) then reset body length to zero.
is_response = mg_ncasecmp(hm->method.ptr, "HTTP/", 5) == 0;
if (hm->body.len == (size_t) ~0 && !is_response &&
mg_vcasecmp(&hm->method, "PUT") != 0 &&
mg_vcasecmp(&hm->method, "POST") != 0) {
hm->body.len = 0;
hm->message.len = req_len;
}
return req_len;
}
static void mg_http_vprintf_chunk(struct mg_connection *c, const char *fmt,
va_list ap) {
char mem[256], *buf = mem;
int len = mg_vasprintf(&buf, sizeof(mem), fmt, ap);
mg_printf(c, "%X\r\n", len);
mg_send(c, buf, len);
mg_send(c, "\r\n", 2);
if (buf != mem) free(buf);
}
void mg_http_printf_chunk(struct mg_connection *c, const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
mg_http_vprintf_chunk(c, fmt, ap);
va_end(ap);
}
void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) {
mg_printf(c, "%X\r\n", len);
mg_send(c, buf, len);
mg_send(c, "\r\n", 2);
}
void mg_http_reply(struct mg_connection *c, int code, const char *fmt, ...) {
char mem[100], *buf = mem;
va_list ap;
int len;
va_start(ap, fmt);
len = mg_vasprintf(&buf, sizeof(mem), fmt, ap);
va_end(ap);
mg_printf(c,
"HTTP/1.1 %d OK\r\nContent-Type: text/plain\r\n"
"Content-Length: %d\r\n\r\n",
code, len);
mg_send(c, buf, len);
if (buf != mem) free(buf);
}
static void http_cb(struct mg_connection *, int, void *, void *);
static void restore_http_cb(struct mg_connection *c) {
struct http_data *d = (struct http_data *) c->pfn_data;
if (d->fp != NULL) fclose(d->fp);
c->pfn_data = d->old_pfn_data;
c->pfn = http_cb;
free(d);
}
#if MG_ENABLE_FS
char *mg_http_etag(char *buf, size_t len, struct stat *st) {
snprintf(buf, len, "\"%lx.%lu\"", (unsigned long) st->st_mtime,
(unsigned long) st->st_size);
return buf;
}
int mg_http_upload(struct mg_connection *c, struct mg_http_message *hm,
const char *dir) {
char offset[40] = "", name[200] = "", path[256];
mg_http_get_var(&hm->query, "offset", offset, sizeof(offset));
mg_http_get_var(&hm->query, "name", name, sizeof(name));
if (name[0] == '\0') {
mg_http_reply(c, 400, "%s", "name required");
return -1;
} else {
FILE *fp;
size_t oft = strtoul(offset, NULL, 0);
snprintf(path, sizeof(path), "%s%c%s", dir, MG_DIRSEP, name);
LOG(LL_DEBUG,
("%p %d bytes @ %d [%s]", c->fd, (int) hm->body.len, (int) oft, name));
if ((fp = fopen(path, oft == 0 ? "wb" : "a")) == NULL) {
mg_http_reply(c, 400, "fopen(%s): %d", name, errno);
return -2;
} else {
fwrite(hm->body.ptr, 1, hm->body.len, fp);
fclose(fp);
mg_http_reply(c, 200, "");
return hm->body.len;
}
}
}
static void static_cb(struct mg_connection *c, int ev, void *ev_data,
void *fn_data) {
if (ev == MG_EV_WRITE || ev == MG_EV_POLL) {
struct http_data *d = (struct http_data *) fn_data;
// Read to send IO buffer directly, avoid extra on-stack buffer
size_t n, max = 2 * MG_IO_SIZE;
if (c->send.size < max) mg_iobuf_resize(&c->send, max);
if (c->send.len >= c->send.size) return; // Rate limit
n = fread(c->send.buf + c->send.len, 1, c->send.size - c->send.len, d->fp);
if (n > 0) c->send.len += n;
if (c->send.len < c->send.size) restore_http_cb(c);
} else if (ev == MG_EV_CLOSE) {
restore_http_cb(c);
}
(void) ev_data;
}
static const char *guess_content_type(const char *filename) {
int n = (int) strlen(filename);
if (mg_globmatch("#.html", 6, filename, n)) return "text/html";
if (mg_globmatch("#.css", 5, filename, n)) return "text/css";
if (mg_globmatch("#.js", 4, filename, n)) return "text/javascript";
return "text/plain";
}
void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm,
const char *path, const char *mime) {
struct mg_str *inm = mg_http_get_header(hm, "If-None-Match");
struct stat st;
FILE *fp = fopen(path, "rb");
char etag[64];
if (fp == NULL || stat(path, &st) != 0 ||
mg_http_etag(etag, sizeof(etag), &st) != etag) {
mg_http_reply(c, 404, "%s", "Not found\n");
} else if (inm != NULL && mg_vcasecmp(inm, etag) == 0) {
mg_printf(c, "HTTP/1.1 304 Not Modified\r\nContent-Length: 0\r\n\r\n");
} else {
mg_printf(c,
"HTTP/1.1 200 OK\r\nContent-Type: %s\r\n"
"Etag: %s\r\nContent-Length: %lu\r\n\r\n",
mime, etag, (unsigned long) st.st_size);
if (mg_vcasecmp(&hm->method, "HEAD") == 0) {
fclose(fp);
} else {
struct http_data *d = (struct http_data *) calloc(1, sizeof(*d));
d->fp = fp;
d->old_pfn_data = c->pfn_data;
c->pfn = static_cb;
c->pfn_data = d;
}
}
}
#if MG_ARCH == MG_ARCH_ESP32 || MG_ARCH == MG_ARCH_ESP8266 || \
MG_ARCH == MG_ARCH_FREERTOS
char *realpath(const char *src, char *dst) {
int len = strlen(src);
if (len > PATH_MAX - 1) len = PATH_MAX - 1;
strncpy(dst, src, len);
dst[len] = '\0';
return dst;
}
#endif
// Try to avoid dirent API
static int mg_is_dir(const char *path) {
#if MG_ARCH == MG_ARCH_FREERTOS
struct FF_STAT st;
return (ff_stat(path, &st) == 0) && (st.st_mode & FF_IFDIR);
#else
struct stat st;
return (stat(path, &st) == 0) && (st.st_mode & S_IFDIR);
#endif
}
#if MG_ENABLE_DIRECTORY_LISTING
#ifdef _WIN32
struct dirent {
char d_name[MAX_PATH];
};
typedef struct win32_dir {
HANDLE handle;
WIN32_FIND_DATAW info;
struct dirent result;
} DIR;
int gettimeofday(struct timeval *tv, void *tz) {
FILETIME ft;
unsigned __int64 tmpres = 0;
static int tzflag = 0;
if (tv != NULL) {
GetSystemTimeAsFileTime(&ft);
tmpres |= ft.dwHighDateTime;
tmpres <<= 32;
tmpres |= ft.dwLowDateTime;
tmpres /= 10; // convert into microseconds
tmpres -= 11644473600000000ULL;
tv->tv_sec = (long) (tmpres / 1000000UL);
tv->tv_usec = (long) (tmpres % 1000000UL);
}
return 0;
}
static int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
int ret;
char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
strncpy(buf, path, sizeof(buf));
buf[sizeof(buf) - 1] = '\0';
// Trim trailing slashes. Leave backslash for paths like "X:\"
p = buf + strlen(buf) - 1;
while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
// Convert back to Unicode. If doubly-converted string does not match the
// original, something is fishy, reject.
WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
NULL, NULL);
if (strcmp(buf, buf2) != 0) {
wbuf[0] = L'\0';
ret = 0;
}
return ret;
}
DIR *opendir(const char *name) {
DIR *d = NULL;
wchar_t wpath[MAX_PATH];
DWORD attrs;
if (name == NULL) {
SetLastError(ERROR_BAD_ARGUMENTS);
} else if ((d = malloc(sizeof(*d))) == NULL) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
} else {
to_wchar(name, wpath, sizeof(wpath) / sizeof(wpath[0]));
attrs = GetFileAttributesW(wpath);
if (attrs != 0Xffffffff && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
(void) wcscat(wpath, L"\\*");
d->handle = FindFirstFileW(wpath, &d->info);
d->result.d_name[0] = '\0';
} else {
free(d);
d = NULL;
}
}
return d;
}
int closedir(DIR *d) {
int result = 0;
if (d != NULL) {
if (d->handle != INVALID_HANDLE_VALUE)
result = FindClose(d->handle) ? 0 : -1;
free(d);
} else {
result = -1;
SetLastError(ERROR_BAD_ARGUMENTS);
}
return result;
}
struct dirent *readdir(DIR *d) {
struct dirent *result = NULL;
if (d != NULL) {
memset(&d->result, 0, sizeof(d->result));
if (d->handle != INVALID_HANDLE_VALUE) {
result = &d->result;
WideCharToMultiByte(CP_UTF8, 0, d->info.cFileName, -1, result->d_name,
sizeof(result->d_name), NULL, NULL);
if (!FindNextFileW(d->handle, &d->info)) {
FindClose(d->handle);
d->handle = INVALID_HANDLE_VALUE;
}
} else {
SetLastError(ERROR_FILE_NOT_FOUND);
}
} else {
SetLastError(ERROR_BAD_ARGUMENTS);
}
return result;
}
#endif
static void printdirentry(struct mg_connection *c, struct mg_http_message *hm,
const char *name, struct stat *stp) {
char size[64], mod[64]; //, path[PATH_MAX];
int is_dir = S_ISDIR(stp->st_mode);
const char *slash = is_dir ? "/" : "";
if (is_dir) {
snprintf(size, sizeof(size), "%s", "[DIR]");
} else {
if (stp->st_size < 1024) {
snprintf(size, sizeof(size), "%d", (int) stp->st_size);
} else if (stp->st_size < 0x100000) {
snprintf(size, sizeof(size), "%.1fk", (double) stp->st_size / 1024.0);
} else if (stp->st_size < 0x40000000) {
snprintf(size, sizeof(size), "%.1fM", (double) stp->st_size / 1048576);
} else {
snprintf(size, sizeof(size), "%.1fG", (double) stp->st_size / 1073741824);
}
}
strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
// mg_escape(file_name, path, sizeof(path));
// href = mg_url_encode(mg_mk_str(file_name));
mg_http_printf_chunk(
c,
"<tr><td><a href=\"%.*s%s%s\">%s%s</a></td><td>%s</td><td>%s</td></tr>",
(int) hm->uri.len, hm->uri.ptr, name, slash, name, slash, mod, size);
// free((void *) href.p);
}
static void listdir(struct mg_connection *c, struct mg_http_message *hm,
char *dir) {
char path[PATH_MAX + 1], *p = &dir[strlen(dir) - 1];
struct dirent *dp;
DIR *dirp;
while (p > dir && *p != '/') *p-- = '\0';
// LOG(LL_DEBUG, ("%p [%s]", c->fd, dir));
if ((dirp = (opendir(dir))) != NULL) {
mg_printf(c, "%s\r\n", "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n");
mg_http_printf_chunk(
c,
"<!DOCTYPE html><html><head><title>Index of %.*s</title>"
"<style>th,td {text-align: left; padding-right: 1em; "
"font-family: monospace; }</style></head>"
"<body><h1>Index of %.*s</h1><table cellpadding=\"0\"><thead>"
"<tr><th>Name</th><th>Modified</th><th>Size</th></tr>"
"<tr><td colspan=\"3\"><hr></td></tr></thead><tbody>",
(int) hm->uri.len, hm->uri.ptr, (int) hm->uri.len, hm->uri.ptr);
while ((dp = readdir(dirp)) != NULL) {
struct stat st;
// Do not show current dir and hidden files
if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
if (stat(path, &st) != 0) {
LOG(LL_ERROR, ("%p stat(%s): %d", c->fd, path, errno));
continue;
}
printdirentry(c, hm, dp->d_name, &st);
}
closedir(dirp);
mg_http_printf_chunk(
c,
"</tbody><tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>"
"</table><address>Mongoose v.%s</address></body></html>",
MG_VERSION);
mg_http_write_chunk(c, "", 0);
} else {
mg_http_reply(c, 400, "Cannot open dir");
LOG(LL_DEBUG, ("%p opendir(%s) -> %d", c->fd, dir, errno));
}
}
#endif
void mg_http_serve_dir(struct mg_connection *c, struct mg_http_message *hm,
const char *dir) {
char path[PATH_MAX + 2], root[sizeof(path) - 2], real[sizeof(path) - 2];
path[0] = root[0] = real[0] = '\0';
if (realpath(dir, root) == NULL)
LOG(LL_DEBUG, ("realpath(%s): %d", dir, errno));
if (!mg_is_dir(root)) {
mg_http_reply(c, 400, "Bad web root [%s]\n", root);
} else {
// NOTE(lsm): Xilinx snprintf does not 0-terminate the detination for
// the %.*s specifier, if the length is zero. Make sure hm->uri.len > 0
bool is_index = false;
size_t n = snprintf(path, sizeof(path), "%s%.*s", root, (int) hm->uri.len,
hm->uri.ptr);
while (n > 0 && n < sizeof(path) && path[n - 1] == MG_DIRSEP) path[--n] = 0;
if (realpath(path, real) == NULL)
LOG(LL_DEBUG, ("realpath(%s): %d", dir, errno));
// LOG(LL_INFO, ("PATH: [%s] REAL: [%s]", path, real));
if (mg_is_dir(real)) {
strncat(real, "/index.html", sizeof(real) - strlen(real) - 1);
is_index = true;
}
if (strlen(real) < strlen(root) || memcmp(real, root, strlen(root)) != 0) {
mg_http_reply(c, 404, "Not found %.*s\n", hm->uri.len, hm->uri.ptr);
} else {
FILE *fp = fopen(real, "r");
#if MG_ENABLE_HTTP_DEBUG_ENDPOINT
snprintf(c->label, sizeof(c->label) - 1, "<-F %s", real);
#endif
if (is_index && fp == NULL) {
#if MG_ENABLE_DIRECTORY_LISTING
listdir(c, hm, real);
#else
mg_http_reply(c, 403, "%s", "Directory listing not supported");
#endif
} else {
mg_http_serve_file(c, hm, real, guess_content_type(real));
}
if (fp != NULL) fclose(fp);
}
}
}
#endif
void mg_http_creds(struct mg_http_message *hm, char *user, int userlen,
char *pass, int passlen) {
struct mg_str *v = mg_http_get_header(hm, "Authorization");
user[0] = pass[0] = '\0';
if (v != NULL && v->len > 6 && memcmp(v->ptr, "Basic ", 6) == 0) {
char buf[256];
int n = mg_base64_decode(v->ptr + 6, (int) v->len - 6, buf);
const char *p = (const char *) memchr(buf, ':', n);
if (p != NULL) {
snprintf(user, userlen, "%.*s", (int) (p - buf), buf);
snprintf(pass, passlen, "%.*s", n - (int) (p - buf) - 1, p + 1);
}
} else if (v != NULL && v->len > 7 && memcmp(v->ptr, "Bearer ", 7) == 0) {
snprintf(pass, passlen, "%.*s", (int) v->len - 7, v->ptr + 7);
} else if ((v = mg_http_get_header(hm, "Cookie")) != NULL) {
size_t i;
for (i = 0; i < v->len - 13; i++) {
if (memcmp(&v->ptr[i], "access_token=", 13) == 0) {
const char *p2 = v->ptr + i + 13, *p3 = p2;
while (p2 < &v->ptr[v->len] && p2[0] != ';' && p2[0] != ' ') p2++;
snprintf(pass, passlen, "%.*s", (int) (p2 - p3), p3);
break;
}
}
} else {
mg_http_get_var(&hm->query, "access_token", pass, passlen);
}
}
bool mg_http_match_uri(const struct mg_http_message *hm, const char *glob) {
return mg_globmatch(glob, strlen(glob), hm->uri.ptr, hm->uri.len);
}
static void http_cb(struct mg_connection *c, int ev, void *ev_data,
void *fn_data) {
if (ev == MG_EV_READ || ev == MG_EV_CLOSE) {
struct mg_http_message hm;
for (;;) {
int n = mg_http_parse((char *) c->recv.buf, c->recv.len, &hm);
if (ev == MG_EV_CLOSE) {
hm.message.len = c->recv.len;
hm.body.len = hm.message.len - (hm.body.ptr - hm.message.ptr);
}
if (n < 0 && ev == MG_EV_READ) {
LOG(LL_ERROR, ("%p HTTP parse error", c->fd));
c->is_closing = 1;
break;
} else if (n > 0 && (size_t) c->recv.len >= hm.message.len) {
#if MG_ENABLE_HTTP_DEBUG_ENDPOINT
snprintf(c->label, sizeof(c->label) - 1, "<-[%.*s]", (int) hm.uri.len,
hm.uri.ptr);
if (mg_http_match_uri(&hm, "/debug/info")) {
struct mg_mgr *mgr = (struct mg_mgr *) fn_data;
struct mg_connection *x;
mg_printf(c, "%s\r\n",
"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n");
for (x = mgr->conns; x != NULL; x = x->next) {
// LOG(LL_INFO, ("%p %s", x->fd, x->label));
mg_http_printf_chunk(
c,
"%-4p %-12s %04d.%04d/%04d.%04d"
" %d%d%d%d%d%d%d%d%d%d%d%d%d%d\n",
x->fd, x->label, x->recv.len, x->recv.size, x->send.len,
x->send.size, c->is_listening, c->is_client, c->is_accepted,
c->is_resolving, c->is_connecting, c->is_tls, c->is_tls_hs,
c->is_udp, c->is_websocket, c->is_hexdumping, c->is_draining,
c->is_closing, c->is_readable, c->is_writable);
}
mg_http_write_chunk(c, "", 0);
mg_iobuf_delete(&c->recv, hm.message.len);
continue;
}
#endif
mg_call(c, MG_EV_HTTP_MSG, &hm);
mg_iobuf_delete(&c->recv, hm.message.len);
} else {
break;
}
}
}
(void) fn_data;
(void) ev_data;
}
struct mg_connection *mg_http_connect(struct mg_mgr *mgr, const char *url,
mg_event_handler_t fn, void *fn_data) {
struct mg_connection *c = mg_connect(mgr, url, fn, fn_data);
if (c != NULL) c->pfn = http_cb, c->pfn_data = mgr;
#if MG_ENABLE_HTTP_DEBUG_ENDPOINT
snprintf(c->label, sizeof(c->label) - 1, "->%s", url);
#endif
return c;
}
struct mg_connection *mg_http_listen(struct mg_mgr *mgr, const char *url,
mg_event_handler_t fn, void *fn_data) {
struct mg_connection *c = mg_listen(mgr, url, fn, fn_data);
if (c != NULL) c->pfn = http_cb, c->pfn_data = mgr;
#if MG_ENABLE_HTTP_DEBUG_ENDPOINT
snprintf(c->label, sizeof(c->label) - 1, "<-LSN");
#endif
return c;
}
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include "config.h"
#include "net.h"
#include "str.h"
struct mg_http_header {
struct mg_str name;
struct mg_str value;
};
struct mg_http_message {
// GET /foo/bar/baz?aa=b&cc=ddd HTTP/1.1
// method |-| |----uri---| |--query--| |proto-|
struct mg_str method, uri, query, proto; // Request/response line
struct mg_http_header headers[MG_MAX_HTTP_HEADERS]; // Headers
struct mg_str body; // Body
struct mg_str message; // Request line + headers + body
};
int mg_http_parse(const char *s, size_t len, struct mg_http_message *);
int mg_http_get_request_len(const unsigned char *buf, size_t buf_len);
void mg_http_write_head(struct mg_connection *, int code, const char *fmt, ...);
void mg_http_printf_chunk(struct mg_connection *cnn, const char *fmt, ...);
void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len);
struct mg_connection *mg_http_listen(struct mg_mgr *, const char *url,
mg_event_handler_t fn, void *fn_data);
struct mg_connection *mg_http_connect(struct mg_mgr *, const char *url,
mg_event_handler_t fn, void *fn_data);
void mg_http_serve_dir(struct mg_connection *, struct mg_http_message *hm,
const char *path);
void mg_http_serve_file(struct mg_connection *, struct mg_http_message *,
const char *, const char *mime);
void mg_http_reply(struct mg_connection *c, int code, const char *fmt, ...);
struct mg_str *mg_http_get_header(struct mg_http_message *, const char *name);
void mg_http_event_handler(struct mg_connection *c, int ev);
int mg_http_get_var(const struct mg_str *, const char *name, char *, int);
int mg_http_unescape(const char *s, int n, char *buf, size_t len);
int mg_url_decode(const char *s, size_t n, char *to, size_t to_len, int form);
void mg_http_creds(struct mg_http_message *, char *user, int, char *pass, int);
bool mg_http_match_uri(const struct mg_http_message *, const char *glob);
int mg_http_upload(struct mg_connection *, struct mg_http_message *hm,
const char *dir);
void mg_http_bauth(struct mg_connection *, const char *user, const char *pass);
+54
View File
@@ -0,0 +1,54 @@
#include "iobuf.h"
#include "log.h"
#include <string.h>
void mg_iobuf_resize(struct mg_iobuf *io, size_t new_size) {
if (new_size == 0) {
free(io->buf);
io->buf = NULL;
io->len = io->size = 0;
} else if (new_size != io->size) {
// NOTE(lsm): do not use realloc here. Use malloc/free only, to ease the
// porting to some obscure platforms like FreeRTOS
void *p = malloc(new_size);
if (p != NULL) {
memcpy(p, io->buf, io->size < new_size ? io->size : new_size);
free(io->buf);
io->buf = (unsigned char *) p;
io->size = new_size;
} else {
LOG(LL_ERROR,
("%lu->%lu", (unsigned long) io->size, (unsigned long) new_size));
}
}
}
void mg_iobuf_init(struct mg_iobuf *io, size_t size) {
io->buf = NULL;
io->len = io->size = 0;
if (size > 0) mg_iobuf_resize(io, size);
}
size_t mg_iobuf_append(struct mg_iobuf *io, const void *buf, size_t len,
size_t chunk_size) {
size_t new_size = io->len + len + chunk_size;
new_size -= new_size % chunk_size;
if (new_size != io->size) mg_iobuf_resize(io, new_size);
if (new_size != io->size) len = 0; // Realloc failure, append nothing
if (buf != NULL) memmove(io->buf + io->len, buf, len);
io->len += len;
return len;
}
size_t mg_iobuf_delete(struct mg_iobuf *io, size_t len) {
if (len > io->len) len = 0;
memmove(io->buf, io->buf + len, io->len - len);
io->len -= len;
return len;
}
void mg_iobuf_free(struct mg_iobuf *io) {
free(io->buf);
mg_iobuf_init(io, 0);
}
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include <stddef.h>
struct mg_iobuf {
unsigned char *buf;
size_t size, len;
};
void mg_iobuf_init(struct mg_iobuf *, size_t);
void mg_iobuf_resize(struct mg_iobuf *, size_t);
void mg_iobuf_free(struct mg_iobuf *);
size_t mg_iobuf_append(struct mg_iobuf *, const void *, size_t, size_t);
size_t mg_iobuf_delete(struct mg_iobuf *, size_t);
+17
View File
@@ -0,0 +1,17 @@
// Copyright (c) 2004-2013 Sergey Lyubka
// Copyright (c) 2013-2020 Cesanta Software Limited
// All rights reserved
//
// This software is dual-licensed: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation. For the terms of this
// license, see <http://www.gnu.org/licenses/>.
//
// You are free to use this software under the terms of the GNU General
// Public License, but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// Alternatively, you can license this software under a commercial
// license, as set out in <https://www.cesanta.com/license>.
+69
View File
@@ -0,0 +1,69 @@
#include "log.h"
#include "util.h"
#if MG_ENABLE_MGOS
#else
#if MG_ENABLE_LOG
static void mg_log_stdout(const void *buf, int len, void *userdata) {
(void) userdata;
fwrite(buf, 1, len, stdout);
}
static const char *s_spec = "2";
static void (*s_fn)(const void *, int, void *) = mg_log_stdout;
static void *s_fn_param = NULL;
void mg_log_set(const char *spec) {
LOG(LL_INFO, ("Setting log level to %s", spec));
s_spec = spec;
}
bool mg_log_prefix(int level, const char *file, int line, const char *fname) {
// static unsigned long seq;
int max = LL_INFO;
struct mg_str k, v, s = mg_str(s_spec);
const char *p = strrchr(file, '/');
p = p == NULL ? file : p + 1;
if (s_fn == NULL) return false;
while (mg_next_comma_entry(&s, &k, &v)) {
if (v.len == 0) max = atoi(k.ptr);
if (v.len > 0 && strncmp(p, k.ptr, k.len) == 0) max = atoi(v.ptr);
}
if (level <= max) {
char timebuf[21], buf[50] = "";
time_t t = time(NULL);
struct tm *tm = gmtime(&t);
int n, tag;
strftime(timebuf, sizeof(timebuf), "%Y-%m-%d %H:%M:%S", tm);
tag = level == LL_ERROR ? 'E' : level == LL_INFO ? 'I' : ' ';
n = snprintf(buf, sizeof(buf), "%s %c %s:%d:%s", timebuf, tag, p, line,
fname);
if (n < 0 || n > (int) sizeof(buf) - 2) n = sizeof(buf) - 2;
while (n < (int) sizeof(buf) - 1) buf[n++] = ' ';
s_fn(buf, sizeof(buf) - 1, s_fn_param);
return true;
} else {
return false;
}
}
void mg_log(const char *fmt, ...) {
char mem[256], *buf = mem;
va_list ap;
int len = 0;
va_start(ap, fmt);
len = mg_vasprintf(&buf, sizeof(mem), fmt, ap);
va_end(ap);
s_fn(buf, len, s_fn_param);
s_fn("\n", 1, s_fn_param);
if (buf != mem) free(buf);
}
void mg_log_set_callback(void (*fn)(const void *, int, void *), void *param) {
s_fn = fn;
s_fn_param = param;
}
#endif
#endif
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include "arch.h"
#include "config.h"
#if MG_ENABLE_MGOS
#include <common/cs_dbg.h>
#else
#if MG_ENABLE_LOG
#define LOG(level, args) \
do { \
if (mg_log_prefix((level), __FILE__, __LINE__, __func__)) mg_log args; \
} while (0)
enum { LL_NONE, LL_ERROR, LL_INFO, LL_DEBUG, LL_VERBOSE_DEBUG };
bool mg_log_prefix(int ll, const char *file, int line, const char *fname);
void mg_log(const char *fmt, ...) PRINTF_LIKE(1, 2);
void mg_log_set(const char *spec);
void mg_log_set_callback(void (*fn)(const void *, int, void *), void *param);
#else
#define LOG(level, args)
#endif
#endif
+201
View File
@@ -0,0 +1,201 @@
#include "dns.h"
#include "log.h"
#include "net.h"
#include "private.h"
#include "tls.h"
#include "url.h"
#if MG_ENABLE_LWIP
#include <lwip/tcp.h>
#include <lwip/udp.h>
static void tcp_error_cb(void *arg, err_t err) {
struct mg_connection *c = (struct mg_connection *) arg;
mg_error(c, "%p err %ld", c->fd, err);
}
static err_t connect_cb(void *arg, struct tcp_pcb *pcb, err_t err) {
struct mg_connection *c = (struct mg_connection *) arg;
LOG(LL_DEBUG, ("err %ld, arg %p, pcb %p", err, arg, pcb));
c->is_connecting = 0;
if (err != ERR_OK) mg_error(c, "%p err %d", c->fd, err);
return err;
}
static err_t tcp_recv_cb(void *arg, struct tcp_pcb *pcb, struct pbuf *p,
err_t err) {
struct mg_connection *c = (struct mg_connection *) arg;
LOG(LL_DEBUG,
("err %ld, pbuf %p/%d, io.len %d, io.size %d", err, p,
p == NULL ? 0 : (int) p->len, (int) c->recv.len, (int) c->recv.size));
if (err == ERR_OK && p != NULL) {
#if 0
if (s->io.size < s->io.len + p->len) {
char *buf = realloc(s->io.buf, s->io.len + p->len);
if (buf != NULL) {
s->io.buf = buf;
s->io.size = s->io.len + p->len;
} else {
return ERR_MEM;
}
}
// MLOG(LL_DEBUG, " --> cpy, %p %p", s->io.buf, p->payload);
memcpy(s->io.buf + s->io.len, p->payload, p->len);
s->io.len += p->len;
#endif
tcp_recved(pcb, p->len);
pbuf_free(p);
return err;
} else {
// rmsock(s);
return ERR_ABRT;
}
}
static void udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
const ip_addr_t *addr, uint16_t port) {
LOG(LL_DEBUG,
("%p %p pbuf %p/%d port %hu", arg, pcb, p, p == NULL ? 0 : p->len, port));
}
static err_t tcp_sent_cb(void *arg, struct tcp_pcb *pcb, uint16_t len) {
LOG(LL_DEBUG, ("%p %d", pcb, (int) len));
return ERR_OK;
}
#if 0
static int ll_write(struct mg_connection *c, const void *buf, int len,
int *fail) {
int n = c->is_tls ? mg_tls_send(c, buf, len, fail)
: mg_sock_send(c, buf, len, fail);
LOG(*fail ? LL_ERROR : LL_VERBOSE_DEBUG,
("%p %c%c%c %d/%d %d", c->fd, c->is_tls ? 'T' : 't',
c->is_udp ? 'U' : 'u', c->is_connecting ? 'C' : 'c', n, len,
MG_SOCK_ERRNO));
if (n > 0 && c->is_hexdumping) mg_hexdump(c, "->", buf, n);
return n;
}
#endif
int mg_send(struct mg_connection *c, const void *buf, size_t len) {
if (c->is_udp) {
struct udp_pcb *pcb = (struct udp_pcb *) c->fd;
struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
if (p != NULL) {
// p->payload = (void *) buf;
memcpy(p->payload, buf, len);
err_t err = udp_send(pcb, p);
pbuf_free(p);
LOG(LL_DEBUG,
("%p UDP %d bytes -> %x:%hu, err %ld", c->fd, (int) len,
(unsigned) *(uint32_t *) &pcb->remote_ip, pcb->remote_port, err));
if (err != ERR_OK) mg_error(c, "%p err %d", c->fd, err);
} else {
mg_error(c, "%p pbuf OOM", c->fd);
}
} else if (c->is_connecting) {
mg_iobuf_append(&c->send, buf, len, MG_IO_SIZE);
} else {
}
#if 0
int fail, n = c->is_udp
? ll_write(c, buf, (SOCKET) len, &fail)
: mg_iobuf_append(&c->send, buf, len, MG_IO_SIZE);
return n;
#endif
return 0;
}
static struct mg_connection *mg_mkconn(const char *url) {
struct mg_connection *c = (struct mg_connection *) calloc(1, sizeof(*c));
typedef void *(*new_t)(void);
int is_udp = strncmp(url, "udp:", 4) == 0;
if (c == NULL) {
LOG(LL_ERROR, ("%s %s", url, "OOM"));
} else if ((c->fd = (is_udp ? (new_t) udp_new : (new_t) tcp_new)()) == NULL) {
LOG(LL_ERROR, ("%s new", url));
free(c);
c = NULL;
} else {
c->is_udp = is_udp;
}
return c;
}
struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *url,
mg_event_handler_t fn, void *fn_data) {
struct mg_connection *c = mg_mkconn(url);
struct mg_str host = mg_url_host(url);
if (c == NULL) return c;
c->next = mgr->conns;
mgr->conns = c;
// mg_set_non_blocking_mode((SOCKET) c->fd);
c->is_client = 1;
c->peer.port = mg_htons(mg_url_port(url));
c->fn = fn;
c->fn_data = fn_data;
c->is_hexdumping = 1;
if (c->is_udp) {
udp_bind(c->fd, IP_ADDR_ANY, 0);
udp_recv(c->fd, udp_recv_cb, c);
} else {
tcp_arg(c->fd, c);
tcp_err(c->fd, tcp_error_cb);
tcp_sent(c->fd, tcp_sent_cb);
tcp_recv(c->fd, tcp_recv_cb);
tcp_bind(c->fd, IP_ADDR_ANY, 0);
tcp_nagle_disable((struct tcp_pcb *) c->fd);
}
LOG(LL_DEBUG, ("%p -> %s %s", c->fd, url, c->is_udp ? "UDP" : "TCP"));
mg_resolve(mgr, c, &host, mgr->dnstimeout);
return c;
}
void mg_connect_resolved(struct mg_connection *c) {
char buf[40];
ip_addr_t ipaddr;
memcpy(&ipaddr, &c->peer.ip, sizeof(ipaddr));
mg_call(c, MG_EV_RESOLVE, NULL);
LOG(LL_DEBUG, ("%p resolved to %s", c->fd, mg_straddr(c, buf, sizeof(buf))));
err_t err = c->is_udp ? udp_connect((struct udp_pcb *) c->fd, &ipaddr,
mg_ntohs(c->peer.port))
: tcp_connect((struct tcp_pcb *) c->fd, &ipaddr,
mg_ntohs(c->peer.port), connect_cb);
if (c->is_udp) c->is_connecting = 0;
if (err != ERR_OK) mg_error(c, "%p failed, err %d", c->fd, err);
}
static err_t accept_cb(void *arg, struct tcp_pcb *pcb, err_t e) {
LOG(LL_DEBUG, ("%p err %ld, pcb %p", arg, e, pcb));
return ERR_OK;
}
struct mg_connection *mg_listen(struct mg_mgr *mgr, const char *url,
mg_event_handler_t fn, void *fn_data) {
struct mg_connection *c = mg_mkconn(url);
struct mg_str host = mg_url_host(url);
uint16_t port = mg_url_port(url);
uint32_t ipaddr;
err_t err;
if (c == NULL) return c;
mg_aton(host.ptr, &ipaddr);
if (!mg_vcasecmp(&host, "localhost")) ipaddr = mg_htonl(0x7f000001);
if ((err = tcp_bind(c->fd, (ip_addr_t *) &ipaddr, port)) != ERR_OK) {
mg_error(c, "%p tcp_bind(%x:%hu) -> %ld", c->fd, ipaddr, port, err);
} else {
tcp_listen(c->fd);
tcp_accept(c->fd, accept_cb);
}
return c;
}
void mg_mgr_poll(struct mg_mgr *mgr, int ms) {
LOG(LL_DEBUG, ("%p %d", mgr, ms));
mg_usleep(200 * 1000);
mg_timer_poll(mg_millis());
}
void mg_mgr_init(struct mg_mgr *mgr) {
(void) mgr;
}
#endif
+27 -40
View File
@@ -1,29 +1,18 @@
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
#include "md5.h"
#include <string.h>
#include "common/cs_md5.h"
#include "common/str_util.h"
#if MG_ENABLE_MD5
#if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
#define BYTE_ORDER __BYTE_ORDER
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN __LITTLE_ENDIAN
#endif /* LITTLE_ENDIAN */
#ifndef BIG_ENDIAN
#define BIG_ENDIAN __LITTLE_ENDIAN
#endif /* BIG_ENDIAN */
#endif /* BYTE_ORDER */
#if !defined(EXCLUDE_COMMON)
#if !CS_DISABLE_MD5
#include "common/cs_endian.h"
static void byteReverse(unsigned char *buf, unsigned longs) {
static void mg_byte_reverse(unsigned char *buf, unsigned longs) {
/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
#if BYTE_ORDER == BIG_ENDIAN
do {
@@ -50,7 +39,7 @@ static void byteReverse(unsigned char *buf, unsigned longs) {
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
void cs_md5_init(cs_md5_ctx *ctx) {
void mg_md5_init(mg_md5_ctx *ctx) {
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
@@ -60,7 +49,7 @@ void cs_md5_init(cs_md5_ctx *ctx) {
ctx->bits[1] = 0;
}
static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
static void mg_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
register uint32_t a, b, c, d;
a = buf[0];
@@ -142,7 +131,7 @@ static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
buf[3] += d;
}
void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) {
void mg_md5_update(mg_md5_ctx *ctx, const unsigned char *buf, size_t len) {
uint32_t t;
t = ctx->bits[0];
@@ -160,16 +149,16 @@ void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) {
return;
}
memcpy(p, buf, t);
byteReverse(ctx->in, 16);
cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
mg_byte_reverse(ctx->in, 16);
mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
buf += t;
len -= t;
}
while (len >= 64) {
memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
mg_byte_reverse(ctx->in, 16);
mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
buf += 64;
len -= 64;
}
@@ -177,7 +166,7 @@ void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) {
memcpy(ctx->in, buf, len);
}
void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx) {
void mg_md5_final(mg_md5_ctx *ctx, unsigned char digest[16]) {
unsigned count;
unsigned char *p;
uint32_t *a;
@@ -189,23 +178,21 @@ void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx) {
count = 64 - 1 - count;
if (count < 8) {
memset(p, 0, count);
byteReverse(ctx->in, 16);
cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
mg_byte_reverse(ctx->in, 16);
mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
memset(ctx->in, 0, 56);
} else {
memset(p, 0, count - 8);
}
byteReverse(ctx->in, 14);
mg_byte_reverse(ctx->in, 14);
a = (uint32_t *) ctx->in;
a[14] = ctx->bits[0];
a[15] = ctx->bits[1];
cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
byteReverse((unsigned char *) ctx->buf, 4);
mg_md5_transform(ctx->buf, (uint32_t *) ctx->in);
mg_byte_reverse((unsigned char *) ctx->buf, 4);
memcpy(digest, ctx->buf, 16);
memset((char *) ctx, 0, sizeof(*ctx));
}
#endif /* CS_DISABLE_MD5 */
#endif /* EXCLUDE_COMMON */
#endif
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include "arch.h"
typedef struct {
uint32_t buf[4];
uint32_t bits[2];
unsigned char in[64];
} mg_md5_ctx;
void mg_md5_init(mg_md5_ctx *c);
void mg_md5_update(mg_md5_ctx *c, const unsigned char *data, size_t len);
void mg_md5_final(mg_md5_ctx *c, unsigned char[16]);
-581
View File
@@ -1,581 +0,0 @@
#include "mg_internal.h"
#include "mg_coap.h"
#if MG_ENABLE_COAP
void mg_coap_free_options(struct mg_coap_message *cm) {
while (cm->options != NULL) {
struct mg_coap_option *next = cm->options->next;
MG_FREE(cm->options);
cm->options = next;
}
}
struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
uint32_t number, char *value,
size_t len) {
struct mg_coap_option *new_option =
(struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
new_option->number = number;
new_option->value.p = value;
new_option->value.len = len;
if (cm->options == NULL) {
cm->options = cm->optiomg_tail = new_option;
} else {
/*
* A very simple attention to help clients to compose options:
* CoAP wants to see options ASC ordered.
* Could be change by using sort in coap_compose
*/
if (cm->optiomg_tail->number <= new_option->number) {
/* if option is already ordered just add it */
cm->optiomg_tail = cm->optiomg_tail->next = new_option;
} else {
/* looking for appropriate position */
struct mg_coap_option *current_opt = cm->options;
struct mg_coap_option *prev_opt = 0;
while (current_opt != NULL) {
if (current_opt->number > new_option->number) {
break;
}
prev_opt = current_opt;
current_opt = current_opt->next;
}
if (prev_opt != NULL) {
prev_opt->next = new_option;
new_option->next = current_opt;
} else {
/* insert new_option to the beginning */
new_option->next = cm->options;
cm->options = new_option;
}
}
}
return new_option;
}
/*
* Fills CoAP header in mg_coap_message.
*
* Helper function.
*/
static char *coap_parse_header(char *ptr, struct mbuf *io,
struct mg_coap_message *cm) {
if (io->len < sizeof(uint32_t)) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
return NULL;
}
/*
* Version (Ver): 2-bit unsigned integer. Indicates the CoAP version
* number. Implementations of this specification MUST set this field
* to 1 (01 binary). Other values are reserved for future versions.
* Messages with unknown version numbers MUST be silently ignored.
*/
if (((uint8_t) *ptr >> 6) != 1) {
cm->flags |= MG_COAP_IGNORE;
return NULL;
}
/*
* Type (T): 2-bit unsigned integer. Indicates if this message is of
* type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
* Reset (3).
*/
cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
cm->flags |= MG_COAP_MSG_TYPE_FIELD;
/*
* Token Length (TKL): 4-bit unsigned integer. Indicates the length of
* the variable-length Token field (0-8 bytes). Lengths 9-15 are
* reserved, MUST NOT be sent, and MUST be processed as a message
* format error.
*/
cm->token.len = *ptr & 0x0F;
if (cm->token.len > 8) {
cm->flags |= MG_COAP_FORMAT_ERROR;
return NULL;
}
ptr++;
/*
* Code: 8-bit unsigned integer, split into a 3-bit class (most
* significant bits) and a 5-bit detail (least significant bits)
*/
cm->code_class = (uint8_t) *ptr >> 5;
cm->code_detail = *ptr & 0x1F;
cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
ptr++;
/* Message ID: 16-bit unsigned integer in network byte order. */
cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
cm->flags |= MG_COAP_MSG_ID_FIELD;
ptr += 2;
return ptr;
}
/*
* Fills token information in mg_coap_message.
*
* Helper function.
*/
static char *coap_get_token(char *ptr, struct mbuf *io,
struct mg_coap_message *cm) {
if (cm->token.len != 0) {
if (ptr + cm->token.len > io->buf + io->len) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
return NULL;
} else {
cm->token.p = ptr;
ptr += cm->token.len;
cm->flags |= MG_COAP_TOKEN_FIELD;
}
}
return ptr;
}
/*
* Returns Option Delta or Length.
*
* Helper function.
*/
static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
int ret = 0;
if (*opt_info == 13) {
/*
* 13: An 8-bit unsigned integer follows the initial byte and
* indicates the Option Delta/Length minus 13.
*/
if (ptr < io->buf + io->len) {
*opt_info = (uint8_t) *ptr + 13;
ret = sizeof(uint8_t);
} else {
ret = -1; /* LCOV_EXCL_LINE */
}
} else if (*opt_info == 14) {
/*
* 14: A 16-bit unsigned integer in network byte order follows the
* initial byte and indicates the Option Delta/Length minus 269.
*/
if (ptr + sizeof(uint8_t) < io->buf + io->len) {
*opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
ret = sizeof(uint16_t);
} else {
ret = -1; /* LCOV_EXCL_LINE */
}
}
return ret;
}
/*
* Fills options in mg_coap_message.
*
* Helper function.
*
* General options format:
* +---------------+---------------+
* | Option Delta | Option Length | 1 byte
* +---------------+---------------+
* \ Option Delta (extended) \ 0-2 bytes
* +-------------------------------+
* / Option Length (extended) \ 0-2 bytes
* +-------------------------------+
* \ Option Value \ 0 or more bytes
* +-------------------------------+
*/
static char *coap_get_options(char *ptr, struct mbuf *io,
struct mg_coap_message *cm) {
uint16_t prev_opt = 0;
if (ptr == io->buf + io->len) {
/* end of packet, ok */
return NULL;
}
/* 0xFF is payload marker */
while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
uint16_t option_delta, option_lenght;
int optinfo_len;
/* Option Delta: 4-bit unsigned integer */
option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
/* Option Length: 4-bit unsigned integer */
option_lenght = *ptr & 0x0F;
if (option_delta == 15 || option_lenght == 15) {
/*
* 15: Reserved for future use. If the field is set to this value,
* it MUST be processed as a message format error
*/
cm->flags |= MG_COAP_FORMAT_ERROR;
break;
}
ptr++;
/* check for extended option delta */
optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
if (optinfo_len == -1) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
break; /* LCOV_EXCL_LINE */
}
ptr += optinfo_len;
/* check or extended option lenght */
optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
if (optinfo_len == -1) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
break; /* LCOV_EXCL_LINE */
}
ptr += optinfo_len;
/*
* Instead of specifying the Option Number directly, the instances MUST
* appear in order of their Option Numbers and a delta encoding is used
* between them.
*/
option_delta += prev_opt;
mg_coap_add_option(cm, option_delta, ptr, option_lenght);
prev_opt = option_delta;
if (ptr + option_lenght > io->buf + io->len) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
break; /* LCOV_EXCL_LINE */
}
ptr += option_lenght;
}
if ((cm->flags & MG_COAP_ERROR) != 0) {
mg_coap_free_options(cm);
return NULL;
}
cm->flags |= MG_COAP_OPTIOMG_FIELD;
if (ptr == io->buf + io->len) {
/* end of packet, ok */
return NULL;
}
ptr++;
return ptr;
}
uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
char *ptr;
memset(cm, 0, sizeof(*cm));
if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
return cm->flags;
}
if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
return cm->flags;
}
if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
return cm->flags;
}
/* the rest is payload */
cm->payload.len = io->len - (ptr - io->buf);
if (cm->payload.len != 0) {
cm->payload.p = ptr;
cm->flags |= MG_COAP_PAYLOAD_FIELD;
}
return cm->flags;
}
/*
* Calculates extended size of given Opt Number/Length in coap message.
*
* Helper function.
*/
static size_t coap_get_ext_opt_size(uint32_t value) {
int ret = 0;
if (value >= 13 && value <= 0xFF + 13) {
ret = sizeof(uint8_t);
} else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
ret = sizeof(uint16_t);
}
return ret;
}
/*
* Splits given Opt Number/Length into base and ext values.
*
* Helper function.
*/
static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
int ret = 0;
if (value < 13) {
*base = value;
} else if (value >= 13 && value <= 0xFF + 13) {
*base = 13;
*ext = value - 13;
ret = sizeof(uint8_t);
} else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
*base = 14;
*ext = value - 269;
ret = sizeof(uint16_t);
}
return ret;
}
/*
* Puts uint16_t (in network order) into given char stream.
*
* Helper function.
*/
static char *coap_add_uint16(char *ptr, uint16_t val) {
*ptr = val >> 8;
ptr++;
*ptr = val & 0x00FF;
ptr++;
return ptr;
}
/*
* Puts extended value of Opt Number/Length into given char stream.
*
* Helper function.
*/
static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
if (len == sizeof(uint8_t)) {
*ptr = (char) val;
ptr++;
} else if (len == sizeof(uint16_t)) {
ptr = coap_add_uint16(ptr, val);
}
return ptr;
}
/*
* Verifies given mg_coap_message and calculates message size for it.
*
* Helper function.
*/
static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
size_t *len) {
struct mg_coap_option *opt;
uint32_t prev_opt_number;
*len = 4; /* header */
if (cm->msg_type > MG_COAP_MSG_MAX) {
return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
}
if (cm->token.len > 8) {
return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
}
if (cm->code_class > 7) {
return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
}
if (cm->code_detail > 31) {
return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
}
*len += cm->token.len;
if (cm->payload.len != 0) {
*len += cm->payload.len + 1; /* ... + 1; add payload marker */
}
opt = cm->options;
prev_opt_number = 0;
while (opt != NULL) {
*len += 1; /* basic delta/length */
*len += coap_get_ext_opt_size(opt->number - prev_opt_number);
*len += coap_get_ext_opt_size((uint32_t) opt->value.len);
/*
* Current implementation performs check if
* option_number > previous option_number and produces an error
* TODO(alashkin): write design doc with limitations
* May be resorting is more suitable solution.
*/
if ((opt->next != NULL && opt->number > opt->next->number) ||
opt->value.len > 0xFFFF + 269 ||
opt->number - prev_opt_number > 0xFFFF + 269) {
return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
}
*len += opt->value.len;
prev_opt_number = opt->number;
opt = opt->next;
}
return 0;
}
uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
struct mg_coap_option *opt;
uint32_t res, prev_opt_number;
size_t prev_io_len, packet_size;
char *ptr;
res = coap_calculate_packet_size(cm, &packet_size);
if (res != 0) {
return res;
}
/* saving previous lenght to handle non-empty mbuf */
prev_io_len = io->len;
if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR;
ptr = io->buf + prev_io_len;
/*
* since cm is verified, it is possible to use bits shift operator
* without additional zeroing of unused bits
*/
/* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
*ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
ptr++;
/* code class: 3 bits, code detail: 5 bits */
*ptr = (cm->code_class << 5) | (cm->code_detail);
ptr++;
ptr = coap_add_uint16(ptr, cm->msg_id);
if (cm->token.len != 0) {
memcpy(ptr, cm->token.p, cm->token.len);
ptr += cm->token.len;
}
opt = cm->options;
prev_opt_number = 0;
while (opt != NULL) {
uint8_t delta_base = 0, length_base = 0;
uint16_t delta_ext = 0, length_ext = 0;
size_t opt_delta_len =
coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
size_t opt_lenght_len =
coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
*ptr = (delta_base << 4) | length_base;
ptr++;
ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
if (opt->value.len != 0) {
memcpy(ptr, opt->value.p, opt->value.len);
ptr += opt->value.len;
}
prev_opt_number = opt->number;
opt = opt->next;
}
if (cm->payload.len != 0) {
*ptr = (char) -1;
ptr++;
memcpy(ptr, cm->payload.p, cm->payload.len);
}
return 0;
}
uint32_t mg_coap_send_message(struct mg_connection *nc,
struct mg_coap_message *cm) {
struct mbuf packet_out;
uint32_t compose_res;
mbuf_init(&packet_out, 0);
compose_res = mg_coap_compose(cm, &packet_out);
if (compose_res != 0) {
return compose_res; /* LCOV_EXCL_LINE */
}
mg_send(nc, packet_out.buf, (int) packet_out.len);
mbuf_free(&packet_out);
return 0;
}
uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
struct mg_coap_message cm;
memset(&cm, 0, sizeof(cm));
cm.msg_type = MG_COAP_MSG_ACK;
cm.msg_id = msg_id;
return mg_coap_send_message(nc, &cm);
}
static void coap_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &nc->recv_mbuf;
struct mg_coap_message cm;
uint32_t parse_res;
memset(&cm, 0, sizeof(cm));
nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_RECV:
parse_res = mg_coap_parse(io, &cm);
if ((parse_res & MG_COAP_IGNORE) == 0) {
if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
/*
* Since we support UDP only
* MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
*/
cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
} /* LCOV_EXCL_LINE */
nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type,
&cm MG_UD_ARG(user_data));
}
mg_coap_free_options(&cm);
mbuf_remove(io, io->len);
break;
}
}
/*
* Attach built-in CoAP event handler to the given connection.
*
* The user-defined event handler will receive following extra events:
*
* - MG_EV_COAP_CON
* - MG_EV_COAP_NOC
* - MG_EV_COAP_ACK
* - MG_EV_COAP_RST
*/
int mg_set_protocol_coap(struct mg_connection *nc) {
/* supports UDP only */
if ((nc->flags & MG_F_UDP) == 0) {
return -1;
}
nc->proto_handler = coap_handler;
return 0;
}
#endif /* MG_ENABLE_COAP */
-149
View File
@@ -1,149 +0,0 @@
/*
* === CoAP API reference
*
* CoAP message format:
*
* ```
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
* |Ver| T | TKL | Code | Message ID | Token (if any, TKL bytes) ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
* | Options (if any) ... |1 1 1 1 1 1 1 1| Payload (if any) ...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
* ```
*/
#ifndef CS_MONGOOSE_SRC_COAP_H_
#define CS_MONGOOSE_SRC_COAP_H_
#if MG_ENABLE_COAP
#define MG_COAP_MSG_TYPE_FIELD 0x2
#define MG_COAP_CODE_CLASS_FIELD 0x4
#define MG_COAP_CODE_DETAIL_FIELD 0x8
#define MG_COAP_MSG_ID_FIELD 0x10
#define MG_COAP_TOKEN_FIELD 0x20
#define MG_COAP_OPTIOMG_FIELD 0x40
#define MG_COAP_PAYLOAD_FIELD 0x80
#define MG_COAP_ERROR 0x10000
#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)
#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)
#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)
#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)
#define MG_COAP_MSG_CON 0
#define MG_COAP_MSG_NOC 1
#define MG_COAP_MSG_ACK 2
#define MG_COAP_MSG_RST 3
#define MG_COAP_MSG_MAX 3
#define MG_COAP_CODECLASS_REQUEST 0
#define MG_COAP_CODECLASS_RESP_OK 2
#define MG_COAP_CODECLASS_CLIENT_ERR 4
#define MG_COAP_CODECLASS_SRV_ERR 5
#define MG_COAP_EVENT_BASE 300
#define MG_EV_COAP_CON (MG_COAP_EVENT_BASE + MG_COAP_MSG_CON)
#define MG_EV_COAP_NOC (MG_COAP_EVENT_BASE + MG_COAP_MSG_NOC)
#define MG_EV_COAP_ACK (MG_COAP_EVENT_BASE + MG_COAP_MSG_ACK)
#define MG_EV_COAP_RST (MG_COAP_EVENT_BASE + MG_COAP_MSG_RST)
/*
* CoAP options.
* Use mg_coap_add_option and mg_coap_free_options
* for creation and destruction.
*/
struct mg_coap_option {
struct mg_coap_option *next;
uint32_t number;
struct mg_str value;
};
/* CoAP message. See RFC 7252 for details. */
struct mg_coap_message {
uint32_t flags;
uint8_t msg_type;
uint8_t code_class;
uint8_t code_detail;
uint16_t msg_id;
struct mg_str token;
struct mg_coap_option *options;
struct mg_str payload;
struct mg_coap_option *optiomg_tail;
};
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/* Sets CoAP protocol handler - triggers CoAP specific events. */
int mg_set_protocol_coap(struct mg_connection *nc);
/*
* Adds a new option to mg_coap_message structure.
* Returns pointer to the newly created option.
* Note: options must be freed by using mg_coap_free_options
*/
struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
uint32_t number, char *value,
size_t len);
/*
* Frees the memory allocated for options.
* If the cm parameter doesn't contain any option it does nothing.
*/
void mg_coap_free_options(struct mg_coap_message *cm);
/*
* Composes a CoAP message from `mg_coap_message`
* and sends it into `nc` connection.
* Returns 0 on success. On error, it is a bitmask:
*
* - `#define MG_COAP_ERROR 0x10000`
* - `#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)`
* - `#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)`
* - `#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)`
* - `#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)`
*/
uint32_t mg_coap_send_message(struct mg_connection *nc,
struct mg_coap_message *cm);
/*
* Composes CoAP acknowledgement from `mg_coap_message`
* and sends it into `nc` connection.
* Return value: see `mg_coap_send_message()`
*/
uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id);
/*
* Parses CoAP message and fills mg_coap_message and returns cm->flags.
* This is a helper function.
*
* NOTE: usually CoAP works over UDP, so lack of data means format error.
* But, in theory, it is possible to use CoAP over TCP (according to RFC)
*
* The caller has to check results and treat COAP_NOT_ENOUGH_DATA according to
* underlying protocol:
*
* - in case of UDP COAP_NOT_ENOUGH_DATA means COAP_FORMAT_ERROR,
* - in case of TCP client can try to receive more data
*
* Return value: see `mg_coap_send_message()`
*/
uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm);
/*
* Composes CoAP message from mg_coap_message structure.
* This is a helper function.
* Return value: see `mg_coap_send_message()`
*/
uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* MG_ENABLE_COAP */
#endif /* CS_MONGOOSE_SRC_COAP_H_ */
-11
View File
@@ -1,11 +0,0 @@
#ifndef CS_MONGOOSE_SRC_COMMON_H_
#define CS_MONGOOSE_SRC_COMMON_H_
#define MG_VERSION "6.18"
/* Local tweaks, applied before any of Mongoose's own headers. */
#ifdef MG_LOCALS
#include <mg_locals.h>
#endif
#endif /* CS_MONGOOSE_SRC_COMMON_H_ */
-377
View File
@@ -1,377 +0,0 @@
#if MG_ENABLE_DNS
#include "mg_internal.h"
#include "mg_dns.h"
static int mg_dns_tid = 0xa0;
struct mg_dns_header {
uint16_t transaction_id;
uint16_t flags;
uint16_t num_questions;
uint16_t num_answers;
uint16_t num_authority_prs;
uint16_t num_other_prs;
};
struct mg_dns_resource_record *mg_dns_next_record(
struct mg_dns_message *msg, int query,
struct mg_dns_resource_record *prev) {
struct mg_dns_resource_record *rr;
for (rr = (prev == NULL ? msg->answers : prev + 1);
rr - msg->answers < msg->num_answers; rr++) {
if (rr->rtype == query) {
return rr;
}
}
return NULL;
}
int mg_dns_parse_record_data(struct mg_dns_message *msg,
struct mg_dns_resource_record *rr, void *data,
size_t data_len) {
switch (rr->rtype) {
case MG_DNS_A_RECORD:
if (data_len < sizeof(struct in_addr)) {
return -1;
}
if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
return -1;
}
memcpy(data, rr->rdata.p, data_len);
return 0;
#if MG_ENABLE_IPV6
case MG_DNS_AAAA_RECORD:
if (data_len < sizeof(struct in6_addr)) {
return -1; /* LCOV_EXCL_LINE */
}
memcpy(data, rr->rdata.p, data_len);
return 0;
#endif
case MG_DNS_CNAME_RECORD:
mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
return 0;
}
return -1;
}
int mg_dns_insert_header(struct mbuf *io, size_t pos,
struct mg_dns_message *msg) {
struct mg_dns_header header;
memset(&header, 0, sizeof(header));
header.transaction_id = msg->transaction_id;
header.flags = htons(msg->flags);
header.num_questions = htons(msg->num_questions);
header.num_answers = htons(msg->num_answers);
return mbuf_insert(io, pos, &header, sizeof(header));
}
int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) {
unsigned char *begin, *end;
struct mg_dns_resource_record *last_q;
if (msg->num_questions <= 0) return 0;
begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header);
last_q = &msg->questions[msg->num_questions - 1];
end = (unsigned char *) last_q->name.p + last_q->name.len + 4;
return mbuf_append(io, begin, end - begin);
}
int mg_dns_encode_name_s(struct mbuf *io, struct mg_str name) {
const char *s;
unsigned char n;
size_t pos = io->len;
do {
if ((s = mg_strchr(name, '.')) == NULL) {
s = name.p + name.len;
}
if (s - name.p > 127) {
return -1; /* TODO(mkm) cover */
}
n = s - name.p; /* chunk length */
mbuf_append(io, &n, 1); /* send length */
mbuf_append(io, name.p, n);
if (n < name.len && *s == '.') {
n++;
}
name.p += n;
name.len -= n;
} while (name.len > 0);
mbuf_append(io, "\0", 1); /* Mark end of host name */
return io->len - pos;
}
int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
return mg_dns_encode_name_s(io, mg_mk_str_n(name, len));
}
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) {
size_t pos = io->len;
uint16_t u16;
uint32_t u32;
if (rr->kind == MG_DNS_INVALID_RECORD) {
return -1; /* LCOV_EXCL_LINE */
}
if (mg_dns_encode_name(io, name, nlen) == -1) {
return -1;
}
u16 = htons(rr->rtype);
mbuf_append(io, &u16, 2);
u16 = htons(rr->rclass);
mbuf_append(io, &u16, 2);
if (rr->kind == MG_DNS_ANSWER) {
u32 = htonl(rr->ttl);
mbuf_append(io, &u32, 4);
if (rr->rtype == MG_DNS_CNAME_RECORD) {
int clen;
/* fill size after encoding */
size_t off = io->len;
mbuf_append(io, &u16, 2);
if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
return -1;
}
u16 = clen;
io->buf[off] = u16 >> 8;
io->buf[off + 1] = u16 & 0xff;
} else {
u16 = htons((uint16_t) rlen);
mbuf_append(io, &u16, 2);
mbuf_append(io, rdata, rlen);
}
}
return io->len - pos;
}
void mg_send_dns_query(struct mg_connection *nc, const char *name,
int query_type) {
struct mg_dns_message *msg =
(struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
struct mbuf pkt;
struct mg_dns_resource_record *rr = &msg->questions[0];
DBG(("%s %d", name, query_type));
mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
msg->transaction_id = ++mg_dns_tid;
msg->flags = 0x100;
msg->num_questions = 1;
mg_dns_insert_header(&pkt, 0, msg);
rr->rtype = query_type;
rr->rclass = 1; /* Class: inet */
rr->kind = MG_DNS_QUESTION;
if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
/* TODO(mkm): return an error code */
goto cleanup; /* LCOV_EXCL_LINE */
}
/* TCP DNS requires messages to be prefixed with len */
if (!(nc->flags & MG_F_UDP)) {
uint16_t len = htons((uint16_t) pkt.len);
mbuf_insert(&pkt, 0, &len, 2);
}
mg_send(nc, pkt.buf, pkt.len);
mbuf_free(&pkt);
cleanup:
MG_FREE(msg);
}
static unsigned char *mg_parse_dns_resource_record(
unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
int reply) {
unsigned char *name = data;
int chunk_len, data_len;
while (data < end && (chunk_len = *data)) {
if (((unsigned char *) data)[0] & 0xc0) {
data += 1;
break;
}
data += chunk_len + 1;
}
if (data > end - 5) {
return NULL;
}
rr->name.p = (char *) name;
rr->name.len = data - name + 1;
data++;
rr->rtype = data[0] << 8 | data[1];
data += 2;
rr->rclass = data[0] << 8 | data[1];
data += 2;
rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
if (reply) {
if (data >= end - 6) {
return NULL;
}
rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
data[2] << 8 | data[3];
data += 4;
data_len = *data << 8 | *(data + 1);
data += 2;
rr->rdata.p = (char *) data;
rr->rdata.len = data_len;
data += data_len;
}
return data;
}
int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
struct mg_dns_header *header = (struct mg_dns_header *) buf;
unsigned char *data = (unsigned char *) buf + sizeof(*header);
unsigned char *end = (unsigned char *) buf + len;
int i;
memset(msg, 0, sizeof(*msg));
msg->pkt.p = buf;
msg->pkt.len = len;
if (len < (int) sizeof(*header)) return -1;
msg->transaction_id = header->transaction_id;
msg->flags = ntohs(header->flags);
msg->num_questions = ntohs(header->num_questions);
if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
msg->num_questions = (int) ARRAY_SIZE(msg->questions);
}
msg->num_answers = ntohs(header->num_answers);
if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
msg->num_answers = (int) ARRAY_SIZE(msg->answers);
}
for (i = 0; i < msg->num_questions; i++) {
data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
if (data == NULL) return -1;
}
for (i = 0; i < msg->num_answers; i++) {
data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
if (data == NULL) return -1;
}
return 0;
}
size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
char *dst, int dst_len) {
int chunk_len, num_ptrs = 0;
char *old_dst = dst;
const unsigned char *data = (unsigned char *) name->p;
const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
if (data >= end) {
return 0;
}
while ((chunk_len = *data++)) {
int leeway = dst_len - (dst - old_dst);
if (data >= end) {
return 0;
}
if ((chunk_len & 0xc0) == 0xc0) {
uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
if (off >= msg->pkt.len) {
return 0;
}
/* Basic circular loop avoidance: allow up to 16 pointer hops. */
if (++num_ptrs > 15) {
return 0;
}
data = (unsigned char *) msg->pkt.p + off;
continue;
}
if (chunk_len > 63) {
return 0;
}
if (chunk_len > leeway) {
chunk_len = leeway;
}
if (data + chunk_len >= end) {
return 0;
}
memcpy(dst, data, chunk_len);
data += chunk_len;
dst += chunk_len;
leeway -= chunk_len;
if (leeway == 0) {
return dst - old_dst;
}
*dst++ = '.';
}
if (dst != old_dst) {
*--dst = 0;
}
return dst - old_dst;
}
static void dns_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &nc->recv_mbuf;
struct mg_dns_message msg;
/* Pass low-level events to the user handler */
nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_RECV:
if (!(nc->flags & MG_F_UDP)) {
mbuf_remove(&nc->recv_mbuf, 2);
}
if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
/* reply + recursion allowed + format error */
memset(&msg, 0, sizeof(msg));
msg.flags = 0x8081;
mg_dns_insert_header(io, 0, &msg);
if (!(nc->flags & MG_F_UDP)) {
uint16_t len = htons((uint16_t) io->len);
mbuf_insert(io, 0, &len, 2);
}
mg_send(nc, io->buf, io->len);
} else {
/* Call user handler with parsed message */
nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data));
}
mbuf_remove(io, io->len);
break;
}
}
void mg_set_protocol_dns(struct mg_connection *nc) {
nc->proto_handler = dns_handler;
}
#endif /* MG_ENABLE_DNS */
-161
View File
@@ -1,161 +0,0 @@
/*
* === DNS API reference
*/
#ifndef CS_MONGOOSE_SRC_DNS_H_
#define CS_MONGOOSE_SRC_DNS_H_
#include "mg_net.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define MG_DNS_A_RECORD 0x01 /* Lookup IP address */
#define MG_DNS_CNAME_RECORD 0x05 /* Lookup CNAME */
#define MG_DNS_PTR_RECORD 0x0c /* Lookup PTR */
#define MG_DNS_TXT_RECORD 0x10 /* Lookup TXT */
#define MG_DNS_AAAA_RECORD 0x1c /* Lookup IPv6 address */
#define MG_DNS_SRV_RECORD 0x21 /* Lookup SRV */
#define MG_DNS_MX_RECORD 0x0f /* Lookup mail server for domain */
#define MG_DNS_ANY_RECORD 0xff
#define MG_DNS_NSEC_RECORD 0x2f
#define MG_MAX_DNS_QUESTIONS 32
#define MG_MAX_DNS_ANSWERS 32
#define MG_DNS_MESSAGE 100 /* High-level DNS message event */
enum mg_dns_resource_record_kind {
MG_DNS_INVALID_RECORD = 0,
MG_DNS_QUESTION,
MG_DNS_ANSWER
};
/* DNS resource record. */
struct mg_dns_resource_record {
struct mg_str name; /* buffer with compressed name */
int rtype;
int rclass;
int ttl;
enum mg_dns_resource_record_kind kind;
struct mg_str rdata; /* protocol data (can be a compressed name) */
};
/* DNS message (request and response). */
struct mg_dns_message {
struct mg_str pkt; /* packet body */
uint16_t flags;
uint16_t transaction_id;
int num_questions;
int num_answers;
struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS];
struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS];
};
struct mg_dns_resource_record *mg_dns_next_record(
struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev);
/*
* Parses the record data from a DNS resource record.
*
* - A: struct in_addr *ina
* - AAAA: struct in6_addr *ina
* - CNAME: char buffer
*
* Returns -1 on error.
*
* TODO(mkm): MX
*/
int mg_dns_parse_record_data(struct mg_dns_message *msg,
struct mg_dns_resource_record *rr, void *data,
size_t data_len);
/*
* Sends a DNS query to the remote end.
*/
void mg_send_dns_query(struct mg_connection *nc, const char *name,
int query_type);
/*
* Inserts a DNS header to an IO buffer.
*
* Returns the number of bytes inserted.
*/
int mg_dns_insert_header(struct mbuf *io, size_t pos,
struct mg_dns_message *msg);
/*
* Appends already encoded questions from an existing message.
*
* This is useful when generating a DNS reply message which includes
* all question records.
*
* Returns the number of appended bytes.
*/
int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg);
/*
* Encodes and appends a DNS resource record to an IO buffer.
*
* The record metadata is taken from the `rr` parameter, while the name and data
* are taken from the parameters, encoded in the appropriate format depending on
* record type and stored in the IO buffer. The encoded values might contain
* offsets within the IO buffer. It's thus important that the IO buffer doesn't
* get trimmed while a sequence of records are encoded while preparing a DNS
* reply.
*
* This function doesn't update the `name` and `rdata` pointers in the `rr`
* struct because they might be invalidated as soon as the IO buffer grows
* again.
*
* Returns the number of bytes appended or -1 in case of error.
*/
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);
/*
* Encodes a DNS name.
*/
int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len);
int mg_dns_encode_name_s(struct mbuf *io, struct mg_str name);
/* Low-level: parses a DNS response. */
int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg);
/*
* Uncompresses a DNS compressed name.
*
* The containing DNS message is required because of the compressed encoding
* and reference suffixes present elsewhere in the packet.
*
* If the name is less than `dst_len` characters long, the remainder
* of `dst` is terminated with `\0` characters. Otherwise, `dst` is not
* terminated.
*
* If `dst_len` is 0 `dst` can be NULL.
* Returns the uncompressed name length.
*/
size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
char *dst, int dst_len);
/*
* Attaches a built-in DNS event handler to the given listening connection.
*
* The DNS event handler parses the incoming UDP packets, treating them as DNS
* requests. If an incoming packet gets successfully parsed by the DNS event
* handler, a user event handler will receive an `MG_DNS_REQUEST` event, with
* `ev_data` pointing to the parsed `struct mg_dns_message`.
*
* See
* [captive_dns_server](https://github.com/cesanta/mongoose/tree/master/examples/captive_dns_server)
* example on how to handle DNS request and send DNS reply.
*/
void mg_set_protocol_dns(struct mg_connection *nc);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_MONGOOSE_SRC_DNS_H_ */
-67
View File
@@ -1,67 +0,0 @@
#if MG_ENABLE_DNS_SERVER
#include "mg_internal.h"
#include "dns-server.h"
struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
struct mg_dns_message *msg) {
struct mg_dns_reply rep;
rep.msg = msg;
rep.io = io;
rep.start = io->len;
/* reply + recursion allowed */
msg->flags |= 0x8080;
mg_dns_copy_questions(io, msg);
msg->num_answers = 0;
return rep;
}
void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
size_t sent = r->io->len - r->start;
mg_dns_insert_header(r->io, r->start, r->msg);
if (!(nc->flags & MG_F_UDP)) {
uint16_t len = htons((uint16_t) sent);
mbuf_insert(r->io, r->start, &len, 2);
}
if (&nc->send_mbuf != r->io) {
mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
r->io->len = r->start;
}
}
int mg_dns_reply_record(struct mg_dns_reply *reply,
struct mg_dns_resource_record *question,
const char *name, int rtype, int ttl, const void *rdata,
size_t rdata_len) {
struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
char rname[512];
struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
return -1; /* LCOV_EXCL_LINE */
}
if (name == NULL) {
name = rname;
rname[511] = 0;
mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
}
*ans = *question;
ans->kind = MG_DNS_ANSWER;
ans->rtype = rtype;
ans->ttl = ttl;
if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
rdata_len) == -1) {
return -1; /* LCOV_EXCL_LINE */
};
msg->num_answers++;
return 0;
}
#endif /* MG_ENABLE_DNS_SERVER */
-90
View File
@@ -1,90 +0,0 @@
/*
* === DNS server API reference
*
* Disabled by default; enable with `-DMG_ENABLE_DNS_SERVER`.
*/
#ifndef CS_MONGOOSE_SRC_DNS_SERVER_H_
#define CS_MONGOOSE_SRC_DNS_SERVER_H_
#if MG_ENABLE_DNS_SERVER
#include "mg_dns.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define MG_DNS_SERVER_DEFAULT_TTL 3600
struct mg_dns_reply {
struct mg_dns_message *msg;
struct mbuf *io;
size_t start;
};
/*
* Creates a DNS reply.
*
* The reply will be based on an existing query message `msg`.
* The query body will be appended to the output buffer.
* "reply + recursion allowed" will be added to the message flags and the
* message's num_answers will be set to 0.
*
* Answer records can be appended with `mg_dns_send_reply` or by lower
* level function defined in the DNS API.
*
* In order to send a reply use `mg_dns_send_reply`.
* It's possible to use a connection's send buffer as reply buffer,
* and it will work for both UDP and TCP connections.
*
* Example:
*
* ```c
* reply = mg_dns_create_reply(&nc->send_mbuf, msg);
* for (i = 0; i < msg->num_questions; i++) {
* rr = &msg->questions[i];
* if (rr->rtype == MG_DNS_A_RECORD) {
* mg_dns_reply_record(&reply, rr, 3600, &dummy_ip_addr, 4);
* }
* }
* mg_dns_send_reply(nc, &reply);
* ```
*/
struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
struct mg_dns_message *msg);
/*
* Appends a DNS reply record to the IO buffer and to the DNS message.
*
* The message's num_answers field will be incremented. It's the caller's duty
* to ensure num_answers is properly initialised.
*
* Returns -1 on error.
*/
int mg_dns_reply_record(struct mg_dns_reply *reply,
struct mg_dns_resource_record *question,
const char *name, int rtype, int ttl, const void *rdata,
size_t rdata_len);
/*
* Sends a DNS reply through a connection.
*
* The DNS data is stored in an IO buffer pointed by reply structure in `r`.
* This function mutates the content of that buffer in order to ensure that
* the DNS header reflects the size and flags of the message, that might have
* been updated either with `mg_dns_reply_record` or by direct manipulation of
* `r->message`.
*
* Once sent, the IO buffer will be trimmed unless the reply IO buffer
* is the connection's send buffer and the connection is not in UDP mode.
*/
void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* MG_ENABLE_DNS_SERVER */
#endif /* CS_MONGOOSE_SRC_DNS_SERVER_H_ */
-172
View File
@@ -1,172 +0,0 @@
#ifndef CS_MONGOOSE_SRC_FEATURES_H_
#define CS_MONGOOSE_SRC_FEATURES_H_
#ifndef MG_DISABLE_HTTP_DIGEST_AUTH
#define MG_DISABLE_HTTP_DIGEST_AUTH 0
#endif
#ifndef MG_DISABLE_HTTP_KEEP_ALIVE
#define MG_DISABLE_HTTP_KEEP_ALIVE 0
#endif
#ifndef MG_DISABLE_PFS
#define MG_DISABLE_PFS 0
#endif
#ifndef MG_DISABLE_WS_RANDOM_MASK
#define MG_DISABLE_WS_RANDOM_MASK 0
#endif
#ifndef MG_ENABLE_ASYNC_RESOLVER
#define MG_ENABLE_ASYNC_RESOLVER 1
#endif
#ifndef MG_ENABLE_BROADCAST
#define MG_ENABLE_BROADCAST 0
#endif
#ifndef MG_ENABLE_COAP
#define MG_ENABLE_COAP 0
#endif
#ifndef MG_ENABLE_DEBUG
#define MG_ENABLE_DEBUG 0
#endif
#ifndef MG_ENABLE_DIRECTORY_LISTING
#define MG_ENABLE_DIRECTORY_LISTING 0
#endif
#ifndef MG_ENABLE_DNS
#define MG_ENABLE_DNS 1
#endif
#ifndef MG_ENABLE_DNS_SERVER
#define MG_ENABLE_DNS_SERVER 0
#endif
#ifndef MG_ENABLE_FAKE_DAVLOCK
#define MG_ENABLE_FAKE_DAVLOCK 0
#endif
#ifndef MG_ENABLE_FILESYSTEM
#define MG_ENABLE_FILESYSTEM 0
#endif
#ifndef MG_ENABLE_GETADDRINFO
#define MG_ENABLE_GETADDRINFO 0
#endif
#ifndef MG_ENABLE_HEXDUMP
#define MG_ENABLE_HEXDUMP CS_ENABLE_STDIO
#endif
#ifndef MG_ENABLE_HTTP
#define MG_ENABLE_HTTP 1
#endif
#ifndef MG_ENABLE_HTTP_CGI
#define MG_ENABLE_HTTP_CGI 0
#endif
#ifndef MG_ENABLE_HTTP_SSI
#define MG_ENABLE_HTTP_SSI MG_ENABLE_FILESYSTEM
#endif
#ifndef MG_ENABLE_HTTP_SSI_EXEC
#define MG_ENABLE_HTTP_SSI_EXEC 0
#endif
#ifndef MG_ENABLE_HTTP_STREAMING_MULTIPART
#define MG_ENABLE_HTTP_STREAMING_MULTIPART 0
#endif
#ifndef MG_ENABLE_HTTP_WEBDAV
#define MG_ENABLE_HTTP_WEBDAV 0
#endif
#ifndef MG_ENABLE_HTTP_WEBSOCKET
#define MG_ENABLE_HTTP_WEBSOCKET MG_ENABLE_HTTP
#endif
#ifndef MG_ENABLE_IPV6
#define MG_ENABLE_IPV6 0
#endif
#ifndef MG_ENABLE_MQTT
#define MG_ENABLE_MQTT 1
#endif
#ifndef MG_ENABLE_SOCKS
#define MG_ENABLE_SOCKS 0
#endif
#ifndef MG_ENABLE_MQTT_BROKER
#define MG_ENABLE_MQTT_BROKER 0
#endif
#ifndef MG_ENABLE_SSL
#define MG_ENABLE_SSL 0
#endif
#ifndef MG_ENABLE_SYNC_RESOLVER
#define MG_ENABLE_SYNC_RESOLVER 0
#endif
#ifndef MG_ENABLE_STDIO
#define MG_ENABLE_STDIO CS_ENABLE_STDIO
#endif
#ifndef MG_NET_IF
#define MG_NET_IF MG_NET_IF_SOCKET
#endif
#ifndef MG_SSL_IF
#define MG_SSL_IF MG_SSL_IF_OPENSSL
#endif
#ifndef MG_ENABLE_THREADS /* ifdef-ok */
#ifdef _WIN32
#define MG_ENABLE_THREADS 1
#else
#define MG_ENABLE_THREADS 0
#endif
#endif
#if MG_ENABLE_DEBUG && !defined(CS_ENABLE_DEBUG)
#define CS_ENABLE_DEBUG 1
#endif
/* MQTT broker requires MQTT */
#if MG_ENABLE_MQTT_BROKER && !MG_ENABLE_MQTT
#undef MG_ENABLE_MQTT
#define MG_ENABLE_MQTT 1
#endif
#ifndef MG_ENABLE_HTTP_URL_REWRITES
#define MG_ENABLE_HTTP_URL_REWRITES \
(CS_PLATFORM == CS_P_WINDOWS || CS_PLATFORM == CS_P_UNIX)
#endif
#ifndef MG_ENABLE_SNTP
#define MG_ENABLE_SNTP 0
#endif
#ifndef MG_ENABLE_EXTRA_ERRORS_DESC
#define MG_ENABLE_EXTRA_ERRORS_DESC 0
#endif
#ifndef MG_ENABLE_CALLBACK_USERDATA
#define MG_ENABLE_CALLBACK_USERDATA 0
#endif
#if MG_ENABLE_CALLBACK_USERDATA
#define MG_UD_ARG(ud) , ud
#define MG_CB(cb, ud) cb, ud
#else
#define MG_UD_ARG(ud)
#define MG_CB(cb, ud) cb
#endif
#endif /* CS_MONGOOSE_SRC_FEATURES_H_ */
-3158
View File
File diff suppressed because it is too large Load Diff
-367
View File
@@ -1,367 +0,0 @@
/*
* === Common API reference
*/
#ifndef CS_MONGOOSE_SRC_HTTP_H_
#define CS_MONGOOSE_SRC_HTTP_H_
#if MG_ENABLE_HTTP
#include "common/mg_str.h"
#include "mg_net.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef MG_MAX_HTTP_HEADERS
#define MG_MAX_HTTP_HEADERS 20
#endif
#ifndef MG_MAX_HTTP_REQUEST_SIZE
#define MG_MAX_HTTP_REQUEST_SIZE 1024
#endif
#ifndef MG_MAX_HTTP_SEND_MBUF
#define MG_MAX_HTTP_SEND_MBUF 1024
#endif
#ifndef MG_CGI_ENVIRONMENT_SIZE
#define MG_CGI_ENVIRONMENT_SIZE 8192
#endif
/* HTTP message */
struct http_message {
struct mg_str message; /* Whole message: request line + headers + body */
struct mg_str body; /* Message body. 0-length for requests with no body */
/* HTTP Request line (or HTTP response line) */
struct mg_str method; /* "GET" */
struct mg_str uri; /* "/my_file.html" */
struct mg_str proto; /* "HTTP/1.1" -- for both request and response */
/* For responses, code and response status message are set */
int resp_code;
struct mg_str resp_status_msg;
/*
* Query-string part of the URI. For example, for HTTP request
* GET /foo/bar?param1=val1&param2=val2
* | uri | query_string |
*
* Note that question mark character doesn't belong neither to the uri,
* nor to the query_string
*/
struct mg_str query_string;
/* Headers */
struct mg_str header_names[MG_MAX_HTTP_HEADERS];
struct mg_str header_values[MG_MAX_HTTP_HEADERS];
/*
* Value of the Content-Length header if present,
* otherwise MG_HTTP_CONTENT_LENGTH_UNKNOWN.
*/
size_t content_length;
};
#define MG_HTTP_CONTENT_LENGTH_UNKNOWN ((size_t) -1)
#if MG_ENABLE_HTTP_WEBSOCKET
/* WebSocket message */
struct websocket_message {
unsigned char *data;
size_t size;
unsigned char flags;
};
#endif
/* HTTP multipart part */
struct mg_http_multipart_part {
const char *file_name;
const char *var_name;
struct mg_str data;
int status; /* <0 on error */
void *user_data;
/*
* User handler can indicate how much of the data was consumed
* by setting this variable. By default, it is assumed that all
* data has been consumed by the handler.
* If not all data was consumed, user's handler will be invoked again later
* with the remainder.
*/
size_t num_data_consumed;
};
/* SSI call context */
struct mg_ssi_call_ctx {
struct http_message *req; /* The request being processed. */
struct mg_str file; /* Filesystem path of the file being processed. */
struct mg_str arg; /* The argument passed to the tag: <!-- call arg -->. */
};
/* HTTP and websocket events. void *ev_data is described in a comment. */
#define MG_EV_HTTP_REQUEST 100 /* struct http_message * */
#define MG_EV_HTTP_REPLY 101 /* struct http_message * */
#define MG_EV_HTTP_CHUNK 102 /* struct http_message * */
#define MG_EV_SSI_CALL 105 /* char * */
#define MG_EV_SSI_CALL_CTX 106 /* struct mg_ssi_call_ctx * */
#if MG_ENABLE_HTTP_WEBSOCKET
#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST 111 /* struct http_message * */
#define MG_EV_WEBSOCKET_HANDSHAKE_DONE 112 /* struct http_message * */
#define MG_EV_WEBSOCKET_FRAME 113 /* struct websocket_message * */
#define MG_EV_WEBSOCKET_CONTROL_FRAME 114 /* struct websocket_message * */
#endif
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
#define MG_EV_HTTP_MULTIPART_REQUEST 121 /* struct http_message */
#define MG_EV_HTTP_PART_BEGIN 122 /* struct mg_http_multipart_part */
#define MG_EV_HTTP_PART_DATA 123 /* struct mg_http_multipart_part */
#define MG_EV_HTTP_PART_END 124 /* struct mg_http_multipart_part */
/* struct mg_http_multipart_part */
#define MG_EV_HTTP_MULTIPART_REQUEST_END 125
#endif
#define MG_F_WEBSOCKET_NO_DEFRAG MG_F_PROTO_1
#define MG_F_DELETE_CHUNK MG_F_PROTO_2
/*
* Attaches a built-in HTTP event handler to the given connection.
* The user-defined event handler will receive following extra events:
*
* - MG_EV_HTTP_REQUEST: HTTP request has arrived. Parsed HTTP request
* is passed as
* `struct http_message` through the handler's `void *ev_data` pointer.
* - MG_EV_HTTP_REPLY: The HTTP reply has arrived. The parsed HTTP reply is
* passed as `struct http_message` through the handler's `void *ev_data`
* pointer.
* - MG_EV_HTTP_CHUNK: The HTTP chunked-encoding chunk has arrived.
* The parsed HTTP reply is passed as `struct http_message` through the
* handler's `void *ev_data` pointer. `http_message::body` would contain
* incomplete, reassembled HTTP body.
* It will grow with every new chunk that arrives, and it can
* potentially consume a lot of memory. An event handler may process
* the body as chunks are coming, and signal Mongoose to delete processed
* body by setting `MG_F_DELETE_CHUNK` in `mg_connection::flags`. When
* the last zero chunk is received,
* Mongoose sends `MG_EV_HTTP_REPLY` event with
* full reassembled body (if handler did not signal to delete chunks) or
* with empty body (if handler did signal to delete chunks).
* - MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: server has received the WebSocket
* handshake request. `ev_data` contains parsed HTTP request.
* - MG_EV_WEBSOCKET_HANDSHAKE_DONE: server has completed the WebSocket
* handshake. `ev_data` is a `struct http_message` containing the
* client's request (server mode) or server's response (client).
* In client mode handler can examine `resp_code`, which should be 101.
* - MG_EV_WEBSOCKET_FRAME: new WebSocket frame has arrived. `ev_data` is
* `struct websocket_message *`
*
* When compiled with MG_ENABLE_HTTP_STREAMING_MULTIPART, Mongoose parses
* multipart requests and splits them into separate events:
* - MG_EV_HTTP_MULTIPART_REQUEST: Start of the request.
* This event is sent before body is parsed. After this, the user
* should expect a sequence of PART_BEGIN/DATA/END requests.
* This is also the last time when headers and other request fields are
* accessible.
* - MG_EV_HTTP_PART_BEGIN: Start of a part of a multipart message.
* Argument: mg_http_multipart_part with var_name and file_name set
* (if present). No data is passed in this message.
* - MG_EV_HTTP_PART_DATA: new portion of data from the multipart message.
* Argument: mg_http_multipart_part. var_name and file_name are preserved,
* data is available in mg_http_multipart_part.data.
* - MG_EV_HTTP_PART_END: End of the current part. var_name, file_name are
* the same, no data in the message. If status is 0, then the part is
* properly terminated with a boundary, status < 0 means that connection
* was terminated.
* - MG_EV_HTTP_MULTIPART_REQUEST_END: End of the multipart request.
* Argument: mg_http_multipart_part, var_name and file_name are NULL,
* status = 0 means request was properly closed, < 0 means connection
* was terminated (note: in this case both PART_END and REQUEST_END are
* delivered).
*/
void mg_set_protocol_http_websocket(struct mg_connection *nc);
#if MG_ENABLE_HTTP_WEBSOCKET
/*
* Send websocket handshake to the server.
*
* `nc` must be a valid connection, connected to a server. `uri` is an URI
* to fetch, extra_headers` is extra HTTP headers to send or `NULL`.
*
* This function is intended to be used by websocket client.
*
* Note that the Host header is mandatory in HTTP/1.1 and must be
* included in `extra_headers`. `mg_send_websocket_handshake2` offers
* a better API for that.
*
* Deprecated in favour of `mg_send_websocket_handshake2`
*/
void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri,
const char *extra_headers);
/*
* Send websocket handshake to the server.
*
* `nc` must be a valid connection, connected to a server. `uri` is an URI
* to fetch, `host` goes into the `Host` header, `protocol` goes into the
* `Sec-WebSocket-Proto` header (NULL to omit), extra_headers` is extra HTTP
* headers to send or `NULL`.
*
* This function is intended to be used by websocket client.
*/
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
const char *host, const char *protocol,
const char *extra_headers);
/* Like mg_send_websocket_handshake2 but also passes basic auth header */
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);
/* Same as mg_send_websocket_handshake3 but with strings not necessarily
* NUL-temrinated */
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);
/*
* Helper function that creates an outbound WebSocket connection.
*
* `url` is a URL to connect to. It must be properly URL-encoded, e.g. have
* no spaces, etc. By default, `mg_connect_ws()` sends Connection and
* Host headers. `extra_headers` is an extra HTTP header to send, e.g.
* `"User-Agent: my-app\r\n"`.
* If `protocol` is not NULL, then a `Sec-WebSocket-Protocol` header is sent.
*
* Examples:
*
* ```c
* nc1 = mg_connect_ws(mgr, ev_handler_1, "ws://echo.websocket.org", NULL,
* NULL);
* nc2 = mg_connect_ws(mgr, ev_handler_1, "wss://echo.websocket.org", NULL,
* NULL);
* nc3 = mg_connect_ws(mgr, ev_handler_1, "ws://api.cesanta.com",
* "clubby.cesanta.com", NULL);
* ```
*/
struct mg_connection *mg_connect_ws(struct mg_mgr *mgr,
MG_CB(mg_event_handler_t event_handler,
void *user_data),
const char *url, const char *protocol,
const char *extra_headers);
/*
* Helper function that creates an outbound WebSocket connection
*
* Mostly identical to `mg_connect_ws`, but allows to provide extra parameters
* (for example, SSL parameters)
*/
struct mg_connection *mg_connect_ws_opt(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *url, const char *protocol,
const char *extra_headers);
/*
* Send WebSocket frame to the remote end.
*
* `op_and_flags` specifies the frame's type. It's one of:
*
* - WEBSOCKET_OP_CONTINUE
* - WEBSOCKET_OP_TEXT
* - WEBSOCKET_OP_BINARY
* - WEBSOCKET_OP_CLOSE
* - WEBSOCKET_OP_PING
* - WEBSOCKET_OP_PONG
*
* Orred with one of the flags:
*
* - WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent.
*
* `data` and `data_len` contain frame data.
*/
void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags,
const void *data, size_t data_len);
/*
* Like `mg_send_websocket_frame()`, but composes a single frame from multiple
* buffers.
*/
void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags,
const struct mg_str *strings, int num_strings);
/*
* Sends WebSocket frame to the remote end.
*
* Like `mg_send_websocket_frame()`, but allows to create formatted messages
* with `printf()`-like semantics.
*/
void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags,
const char *fmt, ...);
/* Websocket opcodes, from http://tools.ietf.org/html/rfc6455 */
#define WEBSOCKET_OP_CONTINUE 0
#define WEBSOCKET_OP_TEXT 1
#define WEBSOCKET_OP_BINARY 2
#define WEBSOCKET_OP_CLOSE 8
#define WEBSOCKET_OP_PING 9
#define WEBSOCKET_OP_PONG 10
/*
* If set causes the FIN flag to not be set on outbound
* frames. This enables sending multiple fragments of a single
* logical message.
*
* The WebSocket protocol mandates that if the FIN flag of a data
* frame is not set, the next frame must be a WEBSOCKET_OP_CONTINUE.
* The last frame must have the FIN bit set.
*
* Note that mongoose will automatically defragment incoming messages,
* so this flag is used only on outbound messages.
*/
#define WEBSOCKET_DONT_FIN 0x100
#endif /* MG_ENABLE_HTTP_WEBSOCKET */
extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
const size_t *msg_lens, uint8_t *digest);
extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
const size_t *msg_lens, uint8_t *digest);
/*
* Flags for `mg_http_is_authorized()`.
*/
#define MG_AUTH_FLAG_IS_DIRECTORY (1 << 0)
#define MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE (1 << 1)
#define MG_AUTH_FLAG_ALLOW_MISSING_FILE (1 << 2)
/*
* Checks whether an http request is authorized. `domain` is the authentication
* realm, `passwords_file` is a htdigest file (can be created e.g. with
* `htdigest` utility). If either `domain` or `passwords_file` is NULL, this
* function always returns 1; otherwise checks the authentication in the
* http request and returns 1 only if there is a match; 0 otherwise.
*/
int mg_http_is_authorized(struct http_message *hm, struct mg_str path,
const char *domain, const char *passwords_file,
int flags);
/*
* Sends 401 Unauthorized response.
*/
void mg_http_send_digest_auth_request(struct mg_connection *c,
const char *domain);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* MG_ENABLE_HTTP */
#endif /* CS_MONGOOSE_SRC_HTTP_H_ */
-509
View File
@@ -1,509 +0,0 @@
#ifndef _WIN32
#include <signal.h>
#endif
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
#ifndef MG_MAX_CGI_ENVIR_VARS
#define MG_MAX_CGI_ENVIR_VARS 64
#endif
#ifndef MG_ENV_EXPORT_TO_CGI
#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
#endif
#define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1
/*
* This structure helps to create an environment for the spawned CGI program.
* Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
* last element must be NULL.
* However, on Windows there is a requirement that all these VARIABLE=VALUE\0
* strings must reside in a contiguous buffer. The end of the buffer is
* marked by two '\0' characters.
* We satisfy both worlds: we create an envp array (which is vars), all
* entries are actually pointers inside buf.
*/
struct mg_cgi_env_block {
struct mg_connection *nc;
char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
int len; /* Space taken */
int nvars; /* Number of variables in envp[] */
};
#ifdef _WIN32
struct mg_threadparam {
sock_t s;
HANDLE hPipe;
};
static int mg_wait_until_ready(sock_t sock, int for_read) {
fd_set set;
FD_ZERO(&set);
FD_SET(sock, &set);
return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
}
static void *mg_push_to_stdin(void *arg) {
struct mg_threadparam *tp = (struct mg_threadparam *) arg;
int n, sent, stop = 0;
DWORD k;
char buf[BUFSIZ];
while (!stop && mg_wait_until_ready(tp->s, 1) &&
(n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
for (sent = 0; !stop && sent < n; sent += k) {
if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
}
}
DBG(("%s", "FORWARED EVERYTHING TO CGI"));
CloseHandle(tp->hPipe);
MG_FREE(tp);
return NULL;
}
static void *mg_pull_from_stdout(void *arg) {
struct mg_threadparam *tp = (struct mg_threadparam *) arg;
int k = 0, stop = 0;
DWORD n, sent;
char buf[BUFSIZ];
while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
for (sent = 0; !stop && sent < n; sent += k) {
if (mg_wait_until_ready(tp->s, 0) &&
(k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
stop = 1;
}
}
DBG(("%s", "EOF FROM CGI"));
CloseHandle(tp->hPipe);
shutdown(tp->s, 2); // Without this, IO thread may get truncated data
closesocket(tp->s);
MG_FREE(tp);
return NULL;
}
static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
void *(*func)(void *)) {
struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
if (tp != NULL) {
tp->s = sock;
tp->hPipe = hPipe;
mg_start_thread(func, tp);
}
}
static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH];
to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
}
static int mg_start_process(const char *interp, const char *cmd,
const char *env, const char *envp[],
const char *dir, sock_t sock) {
STARTUPINFOW si;
PROCESS_INFORMATION pi;
HANDLE a[2], b[2], me = GetCurrentProcess();
wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH];
char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH],
buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH];
DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
FILE *fp;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
CreatePipe(&a[0], &a[1], NULL, 0);
CreatePipe(&b[0], &b[1], NULL, 0);
DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
buf[0] = buf[1] = '\0';
fgets(buf, sizeof(buf), fp);
buf[sizeof(buf) - 1] = '\0';
if (buf[0] == '#' && buf[1] == '!') {
interp = buf + 2;
/* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
interp++;
}
}
fclose(fp);
}
snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
if (interp != NULL) {
mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
} else {
snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
}
to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
(void *) env, full_dir, &si, &pi) != 0) {
mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
CloseHandle(si.hStdOutput);
CloseHandle(si.hStdInput);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
} else {
CloseHandle(a[1]);
CloseHandle(b[0]);
closesocket(sock);
}
DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
/* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
(void) envp;
return (pi.hProcess != NULL);
}
#else
static int mg_start_process(const char *interp, const char *cmd,
const char *env, const char *envp[],
const char *dir, sock_t sock) {
char buf[500];
pid_t pid = fork();
(void) env;
if (pid == 0) {
/*
* In Linux `chdir` declared with `warn_unused_result` attribute
* To shutup compiler we have yo use result in some way
*/
int tmp = chdir(dir);
(void) tmp;
(void) dup2(sock, 0);
(void) dup2(sock, 1);
closesocket(sock);
/*
* After exec, all signal handlers are restored to their default values,
* with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
* implementation, SIGCHLD's handler will leave unchanged after exec
* if it was set to be ignored. Restore it to default action.
*/
signal(SIGCHLD, SIG_DFL);
if (interp == NULL) {
execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
} else {
execle(interp, interp, cmd, (char *) 0, envp);
}
snprintf(buf, sizeof(buf),
"Status: 500\r\n\r\n"
"500 Server Error: %s%s%s: %s",
interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
strerror(errno));
send(1, buf, strlen(buf), 0);
_exit(EXIT_FAILURE); /* exec call failed */
}
return (pid != 0);
}
#endif /* _WIN32 */
/*
* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
* pointer into the vars array.
*/
static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
int n, space;
char *added = block->buf + block->len;
va_list ap;
/* Calculate how much space is left in the buffer */
space = sizeof(block->buf) - (block->len + 2);
if (space > 0) {
/* Copy VARIABLE=VALUE\0 string into the free space */
va_start(ap, fmt);
n = vsnprintf(added, (size_t) space, fmt, ap);
va_end(ap);
/* Make sure we do not overflow buffer and the envp array */
if (n > 0 && n + 1 < space &&
block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
/* Append a pointer to the added string into the envp array */
block->vars[block->nvars++] = added;
/* Bump up used length counter. Include \0 terminator */
block->len += n + 1;
}
}
return added;
}
static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
const char *s;
if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
}
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) {
const char *s;
struct mg_str *h;
char *p;
size_t i;
char buf[100];
size_t path_info_len = path_info != NULL ? path_info->len : 0;
blk->len = blk->nvars = 0;
blk->nc = nc;
if ((s = getenv("SERVER_NAME")) != NULL) {
mg_addenv(blk, "SERVER_NAME=%s", s);
} else {
mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
mg_addenv(blk, "SERVER_NAME=%s", buf);
}
mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
/* Prepare the environment block */
mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
hm->query_string.p);
mg_conn_addr_to_str(nc, buf, sizeof(buf),
MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP);
mg_addenv(blk, "REMOTE_ADDR=%s", buf);
mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT);
mg_addenv(blk, "SERVER_PORT=%s", buf);
s = hm->uri.p + hm->uri.len - path_info_len - 1;
if (*s == '/') {
const char *base_name = strrchr(prog, DIRSEP);
mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
(base_name != NULL ? base_name + 1 : prog));
} else {
mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
}
mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
if (path_info != NULL && path_info->len > 0) {
mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
/* Not really translated... */
mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
}
#if MG_ENABLE_SSL
mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off"));
#else
mg_addenv(blk, "HTTPS=off");
#endif
if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
NULL) {
mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
}
if (hm->query_string.len > 0) {
mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
hm->query_string.p);
}
if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
NULL) {
mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
}
mg_addenv2(blk, "PATH");
mg_addenv2(blk, "TMP");
mg_addenv2(blk, "TEMP");
mg_addenv2(blk, "TMPDIR");
mg_addenv2(blk, "PERLLIB");
mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
#ifdef _WIN32
mg_addenv2(blk, "COMSPEC");
mg_addenv2(blk, "SYSTEMROOT");
mg_addenv2(blk, "SystemDrive");
mg_addenv2(blk, "ProgramFiles");
mg_addenv2(blk, "ProgramFiles(x86)");
mg_addenv2(blk, "CommonProgramFiles(x86)");
#else
mg_addenv2(blk, "LD_LIBRARY_PATH");
#endif /* _WIN32 */
/* Add all headers as HTTP_* variables */
for (i = 0; hm->header_names[i].len > 0; i++) {
p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
hm->header_names[i].p, (int) hm->header_values[i].len,
hm->header_values[i].p);
/* Convert variable name into uppercase, and change - to _ */
for (; *p != '=' && *p != '\0'; p++) {
if (*p == '-') *p = '_';
*p = (char) toupper(*(unsigned char *) p);
}
}
blk->vars[blk->nvars++] = NULL;
blk->buf[blk->len++] = '\0';
}
static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
#if !MG_ENABLE_CALLBACK_USERDATA
void *user_data = cgi_nc->user_data;
#endif
struct mg_connection *nc = (struct mg_connection *) user_data;
(void) ev_data;
if (nc == NULL) {
/* The corresponding network connection was closed. */
cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
switch (ev) {
case MG_EV_RECV:
/*
* CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
* It outputs headers, then body. Headers might include "Status"
* header, which changes CODE, and it might include "Location" header
* which changes CODE to 302.
*
* Therefore we do not send the output from the CGI script to the user
* until all CGI headers are received.
*
* Here we parse the output from the CGI script, and if all headers has
* been received, send appropriate reply line, and forward all
* received headers to the client.
*/
if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) {
struct mbuf *io = &cgi_nc->recv_mbuf;
int len = mg_http_get_request_len(io->buf, io->len);
if (len == 0) break;
if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
mg_http_send_error(nc, 500, "Bad headers");
} else {
struct http_message hm;
struct mg_str *h;
mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
if (mg_get_http_header(&hm, "Location") != NULL) {
mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
} else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
} else {
mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
}
}
nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS;
}
if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) {
mg_forward(cgi_nc, nc);
}
break;
case MG_EV_CLOSE:
DBG(("%p CLOSE", cgi_nc));
mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi);
nc->flags |= MG_F_SEND_AND_CLOSE;
break;
}
}
MG_INTERNAL 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) {
struct mg_cgi_env_block blk;
char dir[MG_MAX_PATH];
const char *p;
sock_t fds[2];
DBG(("%p [%s]", nc, prog));
mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
/*
* CGI must be executed in its own directory. 'dir' must point to the
* directory containing executable program, 'p' must point to the
* executable program name relative to 'dir'.
*/
if ((p = strrchr(prog, DIRSEP)) == NULL) {
snprintf(dir, sizeof(dir), "%s", ".");
} else {
snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
prog = p + 1;
}
if (!mg_socketpair(fds, SOCK_STREAM)) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
#ifndef _WIN32
struct sigaction sa;
sigemptyset(&sa.sa_mask);
sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;
sigaction(SIGCHLD, &sa, NULL);
#endif
if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
fds[1]) != 0) {
struct mg_connection *cgi_nc =
mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc));
struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc);
cgi_pd->cgi.cgi_nc = cgi_nc;
#if !MG_ENABLE_CALLBACK_USERDATA
cgi_pd->cgi.cgi_nc->user_data = nc;
#endif
nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS;
/* Push POST data to the CGI */
if (hm->body.len > 0) {
mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, hm->body.len);
}
mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
} else {
closesocket(fds[0]);
mg_http_send_error(nc, 500, "CGI failure");
}
#ifndef _WIN32
closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
#endif
}
MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
if (d == NULL) return;
if (d->cgi_nc != NULL) {
d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
d->cgi_nc->user_data = NULL;
}
memset(d, 0, sizeof(*d));
}
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
-62
View File
@@ -1,62 +0,0 @@
/*
* === Client API reference
*/
#ifndef CS_MONGOOSE_SRC_HTTP_CLIENT_H_
#define CS_MONGOOSE_SRC_HTTP_CLIENT_H_
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* Helper function that creates an outbound HTTP connection.
*
* `url` is the URL to fetch. It must be properly URL-encoded, e.g. have
* no spaces, etc. By default, `mg_connect_http()` sends the Connection and
* Host headers. `extra_headers` is an extra HTTP header to send, e.g.
* `"User-Agent: my-app\r\n"`.
* If `post_data` is NULL, then a GET request is created. Otherwise, a POST
* request is created with the specified POST data. Note that if the data being
* posted is a form submission, the `Content-Type` header should be set
* accordingly (see example below).
*
* Examples:
*
* ```c
* nc1 = mg_connect_http(mgr, ev_handler_1, "http://www.google.com", NULL,
* NULL);
* nc2 = mg_connect_http(mgr, ev_handler_1, "https://github.com", NULL, NULL);
* nc3 = mg_connect_http(
* mgr, ev_handler_1, "my_server:8000/form_submit/",
* "Content-Type: application/x-www-form-urlencoded\r\n",
* "var_1=value_1&var_2=value_2");
* ```
*/
struct mg_connection *mg_connect_http(
struct mg_mgr *mgr,
MG_CB(mg_event_handler_t event_handler, void *user_data), const char *url,
const char *extra_headers, const char *post_data);
/*
* Helper function that creates an outbound HTTP connection.
*
* Mostly identical to mg_connect_http, but allows you to provide extra
*parameters
* (for example, SSL parameters)
*/
struct mg_connection *mg_connect_http_opt(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *url, const char *extra_headers,
const char *post_data);
/* Creates digest authentication header for a client request. */
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, const char *nonce);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_MONGOOSE_SRC_HTTP_CLIENT_H_ */
-561
View File
@@ -1,561 +0,0 @@
/*
* === Server API reference
*/
#ifndef CS_MONGOOSE_SRC_HTTP_SERVER_H_
#define CS_MONGOOSE_SRC_HTTP_SERVER_H_
#if MG_ENABLE_HTTP
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* Parses a HTTP message.
*
* `is_req` should be set to 1 if parsing a request, 0 if reply.
*
* Returns the number of bytes parsed. If HTTP message is
* incomplete `0` is returned. On parse error, a negative number is returned.
*/
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req);
/*
* Searches and returns the header `name` in parsed HTTP message `hm`.
* If header is not found, NULL is returned. Example:
*
* struct mg_str *host_hdr = mg_get_http_header(hm, "Host");
*/
struct mg_str *mg_get_http_header(struct http_message *hm, const char *name);
/*
* Parses the HTTP header `hdr`. Finds variable `var_name` and stores its value
* in the buffer `*buf`, `buf_size`. If the buffer size is not enough,
* allocates a buffer of required size and writes it to `*buf`, similar to
* asprintf(). The caller should always check whether the buffer was updated,
* and free it if so.
*
* This function is supposed to parse cookies, authentication headers, etc.
* Example (error handling omitted):
*
* char user_buf[20];
* char *user = user_buf;
* struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
* mg_http_parse_header2(hdr, "username", &user, sizeof(user_buf));
* // ... do something useful with user
* if (user != user_buf) {
* free(user);
* }
*
* Returns the length of the variable's value. If variable is not found, 0 is
* returned.
*/
int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf,
size_t buf_size);
/*
* DEPRECATED: use mg_http_parse_header2() instead.
*
* Same as mg_http_parse_header2(), but takes buffer as a `char *` (instead of
* `char **`), and thus it cannot allocate a new buffer if the provided one
* is not enough, and just returns 0 in that case.
*/
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
size_t buf_size)
#ifdef __GNUC__
__attribute__((deprecated))
#endif
;
/*
* Gets and parses the Authorization: Basic header
* Returns -1 if no Authorization header is found, or if
* mg_parse_http_basic_auth
* fails parsing the resulting header.
*/
int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
char *pass, size_t pass_len);
/*
* Parses the Authorization: Basic header
* Returns -1 iif the authorization type is not "Basic" or any other error such
* as incorrectly encoded base64 user password pair.
*/
int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
char *pass, size_t pass_len);
/*
* Parses the buffer `buf`, `buf_len` that contains multipart form data chunks.
* Stores the chunk name in a `var_name`, `var_name_len` buffer.
* If a chunk is an uploaded file, then `file_name`, `file_name_len` is
* filled with an uploaded file name. `chunk`, `chunk_len`
* points to the chunk data.
*
* Return: number of bytes to skip to the next chunk or 0 if there are
* no more chunks.
*
* Usage example:
*
* ```c
* static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
* switch(ev) {
* case MG_EV_HTTP_REQUEST: {
* struct http_message *hm = (struct http_message *) ev_data;
* char var_name[100], file_name[100];
* const char *chunk;
* size_t chunk_len, n1, n2;
*
* n1 = n2 = 0;
* while ((n2 = mg_parse_multipart(hm->body.p + n1,
* hm->body.len - n1,
* var_name, sizeof(var_name),
* file_name, sizeof(file_name),
* &chunk, &chunk_len)) > 0) {
* printf("var: %s, file_name: %s, size: %d, chunk: [%.*s]\n",
* var_name, file_name, (int) chunk_len,
* (int) chunk_len, chunk);
* n1 += n2;
* }
* }
* break;
* ```
*/
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);
/*
* Fetches a HTTP form variable.
*
* Fetches a variable `name` from a `buf` into a buffer specified by `dst`,
* `dst_len`. The destination is always zero-terminated. Returns the length of
* a fetched variable. If not found, 0 is returned. `buf` must be valid
* url-encoded buffer. If destination is too small or an error occured,
* negative number is returned.
*/
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
size_t dst_len);
#if MG_ENABLE_FILESYSTEM
/*
* This structure defines how `mg_serve_http()` works.
* Best practice is to set only required settings, and leave the rest as NULL.
*/
struct mg_serve_http_opts {
/* Path to web root directory */
const char *document_root;
/* List of index files. Default is "" */
const char *index_files;
/*
* Leave as NULL to disable authentication.
* To enable directory protection with authentication, set this to ".htpasswd"
* Then, creating ".htpasswd" file in any directory automatically protects
* it with digest authentication.
* Use `mongoose` web server binary, or `htdigest` Apache utility to
* create/manipulate passwords file.
* Make sure `auth_domain` is set to a valid domain name.
*/
const char *per_directory_auth_file;
/* Authorization domain (domain name of this web server) */
const char *auth_domain;
/*
* Leave as NULL to disable authentication.
* Normally, only selected directories in the document root are protected.
* If absolutely every access to the web server needs to be authenticated,
* regardless of the URI, set this option to the path to the passwords file.
* Format of that file is the same as ".htpasswd" file. Make sure that file
* is located outside document root to prevent people fetching it.
*/
const char *global_auth_file;
/* Set to "no" to disable directory listing. Enabled by default. */
const char *enable_directory_listing;
/*
* SSI files pattern. If not set, "**.shtml$|**.shtm$" is used.
*
* All files that match ssi_pattern are treated as SSI.
*
* Server Side Includes (SSI) is a simple interpreted server-side scripting
* language which is most commonly used to include the contents of a file
* into a web page. It can be useful when it is desirable to include a common
* piece of code throughout a website, for example, headers and footers.
*
* In order for a webpage to recognize an SSI-enabled HTML file, the
* filename should end with a special extension, by default the extension
* should be either .shtml or .shtm
*
* Unknown SSI directives are silently ignored by Mongoose. Currently,
* the following SSI directives are supported:
* &lt;!--#include FILE_TO_INCLUDE --&gt;
* &lt;!--#exec "COMMAND_TO_EXECUTE" --&gt;
* &lt;!--#call COMMAND --&gt;
*
* Note that &lt;!--#include ...> directive supports three path
*specifications:
*
* &lt;!--#include virtual="path" --&gt; Path is relative to web server root
* &lt;!--#include abspath="path" --&gt; Path is absolute or relative to the
* web server working dir
* &lt;!--#include file="path" --&gt;, Path is relative to current document
* &lt;!--#include "path" --&gt;
*
* The include directive may be used to include the contents of a file or
* the result of running a CGI script.
*
* The exec directive is used to execute
* a command on a server, and show command's output. Example:
*
* &lt;!--#exec "ls -l" --&gt;
*
* The call directive is a way to invoke a C handler from the HTML page.
* On each occurence of &lt;!--#call COMMAND OPTIONAL_PARAMS> directive,
* Mongoose calls a registered event handler with MG_EV_SSI_CALL event,
* and event parameter will point to the COMMAND OPTIONAL_PARAMS string.
* An event handler can output any text, for example by calling
* `mg_printf()`. This is a flexible way of generating a web page on
* server side by calling a C event handler. Example:
*
* &lt;!--#call foo --&gt; ... &lt;!--#call bar --&gt;
*
* In the event handler:
* case MG_EV_SSI_CALL: {
* const char *param = (const char *) ev_data;
* if (strcmp(param, "foo") == 0) {
* mg_printf(c, "hello from foo");
* } else if (strcmp(param, "bar") == 0) {
* mg_printf(c, "hello from bar");
* }
* break;
* }
*/
const char *ssi_pattern;
/* IP ACL. By default, NULL, meaning all IPs are allowed to connect */
const char *ip_acl;
#if MG_ENABLE_HTTP_URL_REWRITES
/* URL rewrites.
*
* Comma-separated list of `uri_pattern=url_file_or_directory_path` rewrites.
* When HTTP request is received, Mongoose constructs a file name from the
* requested URI by combining `document_root` and the URI. However, if the
* rewrite option is used and `uri_pattern` matches requested URI, then
* `document_root` is ignored. Instead, `url_file_or_directory_path` is used,
* which should be a full path name or a path relative to the web server's
* current working directory. It can also be an URI (http:// or https://)
* in which case mongoose will behave as a reverse proxy for that destination.
*
* Note that `uri_pattern`, as all Mongoose patterns, is a prefix pattern.
*
* If uri_pattern starts with `@` symbol, then Mongoose compares it with the
* HOST header of the request. If they are equal, Mongoose sets document root
* to `file_or_directory_path`, implementing virtual hosts support.
* Example: `@foo.com=/document/root/for/foo.com`
*
* If `uri_pattern` starts with `%` symbol, then Mongoose compares it with
* the listening port. If they match, then Mongoose issues a 301 redirect.
* For example, to redirect all HTTP requests to the
* HTTPS port, do `%80=https://my.site.com`. Note that the request URI is
* automatically appended to the redirect location.
*/
const char *url_rewrites;
#endif
/* DAV document root. If NULL, DAV requests are going to fail. */
const char *dav_document_root;
/*
* DAV passwords file. If NULL, DAV requests are going to fail.
* If passwords file is set to "-", then DAV auth is disabled.
*/
const char *dav_auth_file;
/* Glob pattern for the files to hide. */
const char *hidden_file_pattern;
/* Set to non-NULL to enable CGI, e.g. **.cgi$|**.php$" */
const char *cgi_file_pattern;
/* If not NULL, ignore CGI script hashbang and use this interpreter */
const char *cgi_interpreter;
/*
* Comma-separated list of Content-Type overrides for path suffixes, e.g.
* ".txt=text/plain; charset=utf-8,.c=text/plain"
*/
const char *custom_mime_types;
/*
* Extra HTTP headers to add to each server response.
* Example: to enable CORS, set this to "Access-Control-Allow-Origin: *".
*/
const char *extra_headers;
};
/*
* Serves given HTTP request according to the `options`.
*
* Example code snippet:
*
* ```c
* static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
* struct http_message *hm = (struct http_message *) ev_data;
* struct mg_serve_http_opts opts = { .document_root = "/var/www" }; // C99
*
* switch (ev) {
* case MG_EV_HTTP_REQUEST:
* mg_serve_http(nc, hm, opts);
* break;
* default:
* break;
* }
* }
* ```
*/
void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
struct mg_serve_http_opts opts);
/*
* Serves a specific file with a given MIME type and optional extra headers.
*
* Example code snippet:
*
* ```c
* static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
* switch (ev) {
* case MG_EV_HTTP_REQUEST: {
* struct http_message *hm = (struct http_message *) ev_data;
* mg_http_serve_file(nc, hm, "file.txt",
* mg_mk_str("text/plain"), mg_mk_str(""));
* break;
* }
* ...
* }
* }
* ```
*/
void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
const char *path, const struct mg_str mime_type,
const struct mg_str extra_headers);
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
/* Callback prototype for `mg_file_upload_handler()`. */
typedef struct mg_str (*mg_fu_fname_fn)(struct mg_connection *nc,
struct mg_str fname);
/*
* File upload handler.
* This handler can be used to implement file uploads with minimum code.
* This handler will process MG_EV_HTTP_PART_* events and store file data into
* a local file.
* `local_name_fn` will be invoked with whatever name was provided by the client
* and will expect the name of the local file to open. A return value of NULL
* will abort file upload (client will get a "403 Forbidden" response). If
* non-null, the returned string must be heap-allocated and will be freed by
* the caller.
* Exception: it is ok to return the same string verbatim.
*
* Example:
*
* ```c
* struct mg_str upload_fname(struct mg_connection *nc, struct mg_str fname) {
* // Just return the same filename. Do not actually do this except in test!
* // fname is user-controlled and needs to be sanitized.
* return fname;
* }
* void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
* switch (ev) {
* ...
* case MG_EV_HTTP_PART_BEGIN:
* case MG_EV_HTTP_PART_DATA:
* case MG_EV_HTTP_PART_END:
* mg_file_upload_handler(nc, ev, ev_data, upload_fname);
* break;
* }
* }
* ```
*/
void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
mg_fu_fname_fn local_name_fn
MG_UD_ARG(void *user_data));
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
#endif /* MG_ENABLE_FILESYSTEM */
/*
* Registers a callback for a specified http endpoint
* Note: if callback is registered it is called instead of the
* callback provided in mg_bind
*
* Example code snippet:
*
* ```c
* static void handle_hello1(struct mg_connection *nc, int ev, void *ev_data) {
* (void) ev; (void) ev_data;
* mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello1]");
* nc->flags |= MG_F_SEND_AND_CLOSE;
* }
*
* static void handle_hello2(struct mg_connection *nc, int ev, void *ev_data) {
* (void) ev; (void) ev_data;
* mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello2]");
* nc->flags |= MG_F_SEND_AND_CLOSE;
* }
*
* void init() {
* nc = mg_bind(&mgr, local_addr, cb1);
* mg_register_http_endpoint(nc, "/hello1", handle_hello1);
* mg_register_http_endpoint(nc, "/hello1/hello2", handle_hello2);
* }
* ```
*/
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
MG_CB(mg_event_handler_t handler,
void *user_data));
struct mg_http_endpoint_opts {
void *user_data;
/* Authorization domain (realm) */
const char *auth_domain;
const char *auth_file;
};
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);
/*
* Authenticates a HTTP request against an opened password file.
* Returns 1 if authenticated, 0 otherwise.
*/
int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
FILE *fp);
/*
* Authenticates given response params against an opened password file.
* Returns 1 if authenticated, 0 otherwise.
*
* It's used by mg_http_check_digest_auth().
*/
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);
/*
* Sends buffer `buf` of size `len` to the client using chunked HTTP encoding.
* This function sends the buffer size as hex number + newline first, then
* the buffer itself, then the newline. For example,
* `mg_send_http_chunk(nc, "foo", 3)` will append the `3\r\nfoo\r\n` string
* to the `nc->send_mbuf` output IO buffer.
*
* NOTE: The HTTP header "Transfer-Encoding: chunked" should be sent prior to
* using this function.
*
* NOTE: do not forget to send an empty chunk at the end of the response,
* to tell the client that everything was sent. Example:
*
* ```
* mg_printf_http_chunk(nc, "%s", "my response!");
* mg_send_http_chunk(nc, "", 0); // Tell the client we're finished
* ```
*/
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len);
/*
* Sends a printf-formatted HTTP chunk.
* Functionality is similar to `mg_send_http_chunk()`.
*/
void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...);
/*
* Sends the response status line.
* If `extra_headers` is not NULL, then `extra_headers` are also sent
* after the response line. `extra_headers` must NOT end end with new line.
* Example:
*
* mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *");
*
* Will result in:
*
* HTTP/1.1 200 OK\r\n
* Access-Control-Allow-Origin: *\r\n
*/
void mg_send_response_line(struct mg_connection *nc, int status_code,
const char *extra_headers);
/*
* Sends an error response. If reason is NULL, the message will be inferred
* from the error code (if supported).
*/
void mg_http_send_error(struct mg_connection *nc, int code, const char *reason);
/*
* Sends a redirect response.
* `status_code` should be either 301 or 302 and `location` point to the
* new location.
* If `extra_headers` is not empty, then `extra_headers` are also sent
* after the response line. `extra_headers` must NOT end end with new line.
*
* Example:
*
* mg_http_send_redirect(nc, 302, mg_mk_str("/login"), mg_mk_str(NULL));
*/
void mg_http_send_redirect(struct mg_connection *nc, int status_code,
const struct mg_str location,
const struct mg_str extra_headers);
/*
* Sends the response line and headers.
* This function sends the response line with the `status_code`, and
* automatically
* sends one header: either "Content-Length" or "Transfer-Encoding".
* If `content_length` is negative, then "Transfer-Encoding: chunked" header
* is sent, otherwise, "Content-Length" header is sent.
*
* NOTE: If `Transfer-Encoding` is `chunked`, then message body must be sent
* using `mg_send_http_chunk()` or `mg_printf_http_chunk()` functions.
* Otherwise, `mg_send()` or `mg_printf()` must be used.
* Extra headers could be set through `extra_headers`. Note `extra_headers`
* must NOT be terminated by a new line.
*/
void mg_send_head(struct mg_connection *n, int status_code,
int64_t content_length, const char *extra_headers);
/*
* Sends a printf-formatted HTTP chunk, escaping HTML tags.
*/
void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...);
#if MG_ENABLE_HTTP_URL_REWRITES
/*
* Proxies a given request to a given upstream http server. The path prefix
* in `mount` will be stripped of the path requested to the upstream server,
* e.g. if mount is /api and upstream is http://localhost:8001/foo
* then an incoming request to /api/bar will cause a request to
* http://localhost:8001/foo/bar
*
* EXPERIMENTAL API. Please use http_serve_http + url_rewrites if a static
* mapping is good enough.
*/
void mg_http_reverse_proxy(struct mg_connection *nc,
const struct http_message *hm, struct mg_str mount,
struct mg_str upstream);
#endif
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* MG_ENABLE_HTTP */
#endif /* CS_MONGOOSE_SRC_HTTP_SERVER_H_ */
-199
View File
@@ -1,199 +0,0 @@
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
const char *path, FILE *fp, int include_level,
const struct mg_serve_http_opts *opts);
static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
char buf[BUFSIZ];
size_t n;
while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) {
mg_send(nc, buf, n);
}
}
static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm,
const char *ssi, char *tag, int include_level,
const struct mg_serve_http_opts *opts) {
char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p;
FILE *fp;
/*
* sscanf() is safe here, since send_ssi_file() also uses buffer
* of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
*/
if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
/* File name is relative to the webserver root */
if (snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name) < 0) {
return;
}
} else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
/*
* File name is relative to the webserver working directory
* or it is absolute system path
*/
if (snprintf(path, sizeof(path), "%s", file_name) < 0) return;
} else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
/* File name is relative to the currect document */
snprintf(path, sizeof(path), "%s", ssi);
if ((p = strrchr(path, DIRSEP)) != NULL) {
p[1] = '\0';
}
snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
} else {
mg_printf(nc, "Bad SSI #include: [%s]", tag);
return;
}
if ((fp = mg_fopen(path, "rb")) == NULL) {
mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path,
strerror(mg_get_errno()));
} else {
mg_set_close_on_exec((sock_t) fileno(fp));
if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
0) {
mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts);
} else {
mg_send_file_data(nc, fp);
}
fclose(fp);
}
}
#if MG_ENABLE_HTTP_SSI_EXEC
static void do_ssi_exec(struct mg_connection *nc, char *tag) {
char cmd[BUFSIZ];
FILE *fp;
if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
mg_printf(nc, "Bad SSI #exec: [%s]", tag);
} else if ((fp = popen(cmd, "r")) == NULL) {
mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno()));
} else {
mg_send_file_data(nc, fp);
pclose(fp);
}
}
#endif /* MG_ENABLE_HTTP_SSI_EXEC */
/*
* SSI directive has the following format:
* <!--#directive parameter=value parameter=value -->
*/
static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
const char *path, FILE *fp, int include_level,
const struct mg_serve_http_opts *opts) {
static const struct mg_str btag = MG_MK_STR("<!--#");
static const struct mg_str d_include = MG_MK_STR("include");
static const struct mg_str d_call = MG_MK_STR("call");
#if MG_ENABLE_HTTP_SSI_EXEC
static const struct mg_str d_exec = MG_MK_STR("exec");
#endif
char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
int ch, len, in_ssi_tag;
if (include_level > 10) {
mg_printf(nc, "SSI #include level is too deep (%s)", path);
return;
}
in_ssi_tag = len = 0;
while ((ch = fgetc(fp)) != EOF) {
if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
size_t i = len - 2;
in_ssi_tag = 0;
/* Trim closing --> */
buf[i--] = '\0';
while (i > 0 && buf[i] == ' ') {
buf[i--] = '\0';
}
/* Handle known SSI directives */
if (strncmp(p, d_include.p, d_include.len) == 0) {
mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level,
opts);
} else if (strncmp(p, d_call.p, d_call.len) == 0) {
struct mg_ssi_call_ctx cctx;
memset(&cctx, 0, sizeof(cctx));
cctx.req = hm;
cctx.file = mg_mk_str(path);
cctx.arg = mg_mk_str(p + d_call.len + 1);
mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL,
(void *) cctx.arg.p); /* NUL added above */
mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx);
#if MG_ENABLE_HTTP_SSI_EXEC
} else if (strncmp(p, d_exec.p, d_exec.len) == 0) {
do_ssi_exec(nc, p + d_exec.len + 1);
#endif
} else {
/* Silently ignore unknown SSI directive. */
}
len = 0;
} else if (ch == '<') {
in_ssi_tag = 1;
if (len > 0) {
mg_send(nc, buf, (size_t) len);
}
len = 0;
buf[len++] = ch & 0xff;
} else if (in_ssi_tag) {
if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) {
/* Not an SSI tag */
in_ssi_tag = 0;
} else if (len == (int) sizeof(buf) - 2) {
mg_printf(nc, "%s: SSI tag is too large", path);
len = 0;
}
buf[len++] = ch & 0xff;
} else {
buf[len++] = ch & 0xff;
if (len == (int) sizeof(buf)) {
mg_send(nc, buf, (size_t) len);
len = 0;
}
}
}
/* Send the rest of buffered data */
if (len > 0) {
mg_send(nc, buf, (size_t) len);
}
}
MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
struct http_message *hm,
const char *path,
const struct mg_serve_http_opts *opts) {
FILE *fp;
struct mg_str mime_type = MG_NULL_STR, encoding = MG_NULL_STR;
DBG(("%p %s", nc, path));
if ((fp = mg_fopen(path, "rb")) == NULL) {
mg_http_send_error(nc, 404, NULL);
} else {
mg_set_close_on_exec((sock_t) fileno(fp));
if (!mg_get_mime_type_encoding(mg_mk_str(path), &mime_type, &encoding,
opts)) {
mime_type = mg_mk_str("text/plain");
}
mg_send_response_line(nc, 200, opts->extra_headers);
mg_printf(nc,
"Content-Type: %.*s\r\n"
"Connection: close\r\n",
(int) mime_type.len, mime_type.p);
if (encoding.len > 0) {
mg_printf(nc, "Content-Encoding: %.*s\r\n", (int) encoding.len,
encoding.p);
}
mg_send(nc, "\r\n", 2);
mg_send_ssi_file(nc, hm, path, fp, 0, opts);
fclose(fp);
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
#endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */
-265
View File
@@ -1,265 +0,0 @@
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) {
static const char *methods[] = {
"PUT",
"DELETE",
"MKCOL",
"PROPFIND",
"MOVE"
#if MG_ENABLE_FAKE_DAVLOCK
,
"LOCK",
"UNLOCK"
#endif
};
size_t i;
for (i = 0; i < ARRAY_SIZE(methods); i++) {
if (mg_vcmp(s, methods[i]) == 0) {
return 1;
}
}
return 0;
}
static int mg_mkdir(const char *path, uint32_t mode) {
#ifndef _WIN32
return mkdir(path, mode);
#else
(void) mode;
return _mkdir(path);
#endif
}
static void mg_print_props(struct mg_connection *nc, const char *name,
cs_stat_t *stp) {
char mtime[64];
time_t t = stp->st_mtime; /* store in local variable for NDK compile */
struct mg_str name_esc = mg_url_encode(mg_mk_str(name));
mg_gmt_time_string(mtime, sizeof(mtime), &t);
mg_printf(nc,
"<d:response>"
"<d:href>%s</d:href>"
"<d:propstat>"
"<d:prop>"
"<d:resourcetype>%s</d:resourcetype>"
"<d:getcontentlength>%" INT64_FMT
"</d:getcontentlength>"
"<d:getlastmodified>%s</d:getlastmodified>"
"</d:prop>"
"<d:status>HTTP/1.1 200 OK</d:status>"
"</d:propstat>"
"</d:response>\n",
name_esc.p, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
(int64_t) stp->st_size, mtime);
free((void *) name_esc.p);
}
MG_INTERNAL 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 const char header[] =
"HTTP/1.1 207 Multi-Status\r\n"
"Connection: close\r\n"
"Content-Type: text/xml; charset=utf-8\r\n\r\n"
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<d:multistatus xmlns:d='DAV:'>\n";
static const char footer[] = "</d:multistatus>\n";
const struct mg_str *depth = mg_get_http_header(hm, "Depth");
/* Print properties for the requested resource itself */
if (S_ISDIR(stp->st_mode) &&
strcmp(opts->enable_directory_listing, "yes") != 0) {
mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
} else {
char uri[MG_MAX_PATH];
mg_send(nc, header, sizeof(header) - 1);
snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
mg_print_props(nc, uri, stp);
if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
mg_scan_directory(nc, path, opts, mg_print_props);
}
mg_send(nc, footer, sizeof(footer) - 1);
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
#if MG_ENABLE_FAKE_DAVLOCK
/*
* Windows explorer (probably there are another WebDav clients like it)
* requires LOCK support in webdav. W/out this, it still works, but fails
* to save file: shows error message and offers "Save As".
* "Save as" works, but this message is very annoying.
* This is fake lock, which doesn't lock something, just returns LOCK token,
* UNLOCK always answers "OK".
* With this fake LOCK Windows Explorer looks happy and saves file.
* NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
* Windows native DAV client. This is why FAKE LOCK is not enabed by default
*/
MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) {
static const char *reply =
"HTTP/1.1 207 Multi-Status\r\n"
"Connection: close\r\n"
"Content-Type: text/xml; charset=utf-8\r\n\r\n"
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<d:multistatus xmlns:d='DAV:'>\n"
"<D:lockdiscovery>\n"
"<D:activelock>\n"
"<D:locktoken>\n"
"<D:href>\n"
"opaquelocktoken:%s%u"
"</D:href>"
"</D:locktoken>"
"</D:activelock>\n"
"</D:lockdiscovery>"
"</d:multistatus>\n";
mg_printf(nc, reply, path, (unsigned int) mg_time());
nc->flags |= MG_F_SEND_AND_CLOSE;
}
#endif
MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
struct http_message *hm) {
int status_code = 500;
if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
status_code = 415;
} else if (!mg_mkdir(path, 0755)) {
status_code = 201;
} else if (errno == EEXIST) {
status_code = 405;
} else if (errno == EACCES) {
status_code = 403;
} else if (errno == ENOENT) {
status_code = 409;
} else {
status_code = 500;
}
mg_http_send_error(nc, status_code, NULL);
}
static int mg_remove_directory(const struct mg_serve_http_opts *opts,
const char *dir) {
char path[MG_MAX_PATH];
struct dirent *dp;
cs_stat_t st;
DIR *dirp;
if ((dirp = opendir(dir)) == NULL) return 0;
while ((dp = readdir(dirp)) != NULL) {
if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
continue;
}
snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
mg_stat(path, &st);
if (S_ISDIR(st.st_mode)) {
mg_remove_directory(opts, path);
} else {
remove(path);
}
}
closedir(dirp);
rmdir(dir);
return 1;
}
MG_INTERNAL void mg_handle_move(struct mg_connection *c,
const struct mg_serve_http_opts *opts,
const char *path, struct http_message *hm) {
const struct mg_str *dest = mg_get_http_header(hm, "Destination");
if (dest == NULL) {
mg_http_send_error(c, 411, NULL);
} else {
const char *p = (char *) memchr(dest->p, '/', dest->len);
if (p != NULL && p[1] == '/' &&
(p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
char buf[MG_MAX_PATH];
snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
(int) (dest->p + dest->len - p), p);
if (rename(path, buf) == 0) {
mg_http_send_error(c, 200, NULL);
} else {
mg_http_send_error(c, 418, NULL);
}
} else {
mg_http_send_error(c, 500, NULL);
}
}
}
MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
const struct mg_serve_http_opts *opts,
const char *path) {
cs_stat_t st;
if (mg_stat(path, &st) != 0) {
mg_http_send_error(nc, 404, NULL);
} else if (S_ISDIR(st.st_mode)) {
mg_remove_directory(opts, path);
mg_http_send_error(nc, 204, NULL);
} else if (remove(path) == 0) {
mg_http_send_error(nc, 204, NULL);
} else {
mg_http_send_error(nc, 423, NULL);
}
}
/* Return -1 on error, 1 on success. */
static int mg_create_itermediate_directories(const char *path) {
const char *s;
/* Create intermediate directories if they do not exist */
for (s = path + 1; *s != '\0'; s++) {
if (*s == '/') {
char buf[MG_MAX_PATH];
cs_stat_t st;
snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
buf[sizeof(buf) - 1] = '\0';
if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
return -1;
}
}
}
return 1;
}
MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
struct http_message *hm) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
cs_stat_t st;
const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
mg_http_free_proto_data_file(&pd->file);
if ((rc = mg_create_itermediate_directories(path)) == 0) {
mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
} else if (rc == -1) {
mg_http_send_error(nc, 500, NULL);
} else if (cl_hdr == NULL) {
mg_http_send_error(nc, 411, NULL);
} else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) {
mg_http_send_error(nc, 500, NULL);
} else {
const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
int64_t r1 = 0, r2 = 0;
pd->file.type = DATA_PUT;
mg_set_close_on_exec((sock_t) fileno(pd->file.fp));
pd->file.cl = to64(cl_hdr->p);
if (range_hdr != NULL &&
mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
status_code = 206;
fseeko(pd->file.fp, r1, SEEK_SET);
pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
}
mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
/* Remove HTTP request from the mbuf, leave only payload */
mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
mg_http_transfer_file_data(nc);
}
}
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */
-515
View File
@@ -1,515 +0,0 @@
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
#include "common/cs_sha1.h"
#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
#endif
#define FLAGS_MASK_FIN (1 << 7)
#define FLAGS_MASK_OP 0x0f
static int mg_is_ws_fragment(unsigned char flags) {
return (flags & FLAGS_MASK_FIN) == 0 ||
(flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE;
}
static int mg_is_ws_first_fragment(unsigned char flags) {
return (flags & FLAGS_MASK_FIN) == 0 &&
(flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE;
}
static int mg_is_ws_control_frame(unsigned char flags) {
unsigned char op = (flags & FLAGS_MASK_OP);
return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING ||
op == WEBSOCKET_OP_PONG;
}
static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
struct websocket_message *wsm) {
if (wsm->flags & 0x8) {
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
} else {
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm);
}
}
static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) {
struct mg_http_proto_data *htd = mg_http_get_proto_data(nc);
return (htd != NULL ? &htd->ws_data : NULL);
}
/*
* Sends a Close websocket frame with the given data, and closes the underlying
* connection. If `len` is ~0, strlen(data) is used.
*/
static void mg_ws_close(struct mg_connection *nc, const void *data,
size_t len) {
if ((int) len == ~0) {
len = strlen((const char *) data);
}
mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len);
nc->flags |= MG_F_SEND_AND_CLOSE;
}
static int mg_deliver_websocket_data(struct mg_connection *nc) {
/* Using unsigned char *, cause of integer arithmetic below */
uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len,
len, mask_len = 0, header_len = 0;
struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc);
unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf,
*e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len;
uint8_t flags;
int ok, reass;
if (wsd->reass_len > 0) {
/*
* We already have some previously received data which we need to
* reassemble and deliver to the client code when we get the final
* fragment.
*
* NOTE: it doesn't mean that the current message must be a continuation:
* it might be a control frame (Close, Ping or Pong), which should be
* handled without breaking the fragmented message.
*/
size_t existing_len = wsd->reass_len;
assert(new_data_len >= existing_len);
new_data += existing_len;
new_data_len -= existing_len;
}
flags = new_data[0];
reass = new_data_len > 0 && mg_is_ws_fragment(flags) &&
!(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
if (reass && mg_is_ws_control_frame(flags)) {
/*
* Control frames can't be fragmented, so if we encounter fragmented
* control frame, close connection immediately.
*/
mg_ws_close(nc, "fragmented control frames are illegal", ~0);
return 0;
} else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) &&
wsd->reass_len > 0) {
/*
* When in the middle of a fragmented message, only the continuations
* and control frames are allowed.
*/
mg_ws_close(nc, "non-continuation in the middle of a fragmented message",
~0);
return 0;
}
if (new_data_len >= 2) {
len = new_data[1] & 0x7f;
mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0;
if (len < 126 && new_data_len >= mask_len) {
data_len = len;
header_len = 2 + mask_len;
} else if (len == 126 && new_data_len >= 4 + mask_len) {
header_len = 4 + mask_len;
data_len = ntohs(*(uint16_t *) &new_data[2]);
} else if (new_data_len >= 10 + mask_len) {
header_len = 10 + mask_len;
data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) +
ntohl(*(uint32_t *) &new_data[6]);
}
}
frame_len = header_len + data_len;
ok = (frame_len > 0 && frame_len <= new_data_len);
/* Check for overflow */
if (frame_len < header_len || frame_len < data_len) {
ok = 0;
mg_ws_close(nc, "overflowed message", ~0);
}
if (ok) {
size_t cleanup_len = 0;
struct websocket_message wsm;
wsm.size = (size_t) data_len;
wsm.data = new_data + header_len;
wsm.flags = flags;
/* Apply mask if necessary */
if (mask_len > 0) {
for (i = 0; i < data_len; i++) {
new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4];
}
}
if (reass) {
/* This is a message fragment */
if (mg_is_ws_first_fragment(flags)) {
/*
* On the first fragmented frame, skip the first byte (op) and also
* reset size to 1 (op), it'll be incremented with the data len below.
*/
new_data += 1;
wsd->reass_len = 1 /* op */;
}
/* Append this frame to the reassembled buffer */
memmove(new_data, wsm.data, e - wsm.data);
wsd->reass_len += wsm.size;
nc->recv_mbuf.len -= wsm.data - new_data;
if (flags & FLAGS_MASK_FIN) {
/* On last fragmented frame - call user handler and remove data */
wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0];
wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */;
wsm.size = wsd->reass_len - 1 /* op */;
cleanup_len = wsd->reass_len;
wsd->reass_len = 0;
/* Pass reassembled message to the client code. */
mg_handle_incoming_websocket_frame(nc, &wsm);
mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */
}
} else {
/*
* This is a complete message, not a fragment. It might happen in between
* of a fragmented message (in this case, WebSocket protocol requires
* current message to be a control frame).
*/
cleanup_len = (size_t) frame_len;
/* First of all, check if we need to react on a control frame. */
switch (flags & FLAGS_MASK_OP) {
case WEBSOCKET_OP_PING:
mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size);
break;
case WEBSOCKET_OP_CLOSE:
mg_ws_close(nc, wsm.data, wsm.size);
break;
}
/* Pass received message to the client code. */
mg_handle_incoming_websocket_frame(nc, &wsm);
/* Cleanup frame */
memmove(nc->recv_mbuf.buf + wsd->reass_len,
nc->recv_mbuf.buf + wsd->reass_len + cleanup_len,
nc->recv_mbuf.len - wsd->reass_len - cleanup_len);
nc->recv_mbuf.len -= cleanup_len;
}
}
return ok;
}
struct ws_mask_ctx {
size_t pos; /* zero means unmasked */
uint32_t mask;
};
static uint32_t mg_ws_random_mask(void) {
uint32_t mask;
/*
* The spec requires WS client to generate hard to
* guess mask keys. From RFC6455, Section 5.3:
*
* The unpredictability of the masking key is essential to prevent
* authors of malicious applications from selecting the bytes that appear on
* the wire.
*
* Hence this feature is essential when the actual end user of this API
* is untrusted code that wouldn't have access to a lower level net API
* anyway (e.g. web browsers). Hence this feature is low prio for most
* mongoose use cases and thus can be disabled, e.g. when porting to a platform
* that lacks rand().
*/
#if MG_DISABLE_WS_RANDOM_MASK
mask = 0xefbeadde; /* generated with a random number generator, I swear */
#else
if (sizeof(long) >= 4) {
mask = (uint32_t) rand();
} else if (sizeof(long) == 2) {
mask = (uint32_t) rand() << 16 | (uint32_t) rand();
}
#endif
return mask;
}
static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
struct ws_mask_ctx *ctx) {
int header_len;
unsigned char header[10];
header[0] =
(op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP);
if (len < 126) {
header[1] = (unsigned char) len;
header_len = 2;
} else if (len < 65535) {
uint16_t tmp = htons((uint16_t) len);
header[1] = 126;
memcpy(&header[2], &tmp, sizeof(tmp));
header_len = 4;
} else {
uint32_t tmp;
header[1] = 127;
tmp = htonl((uint32_t)((uint64_t) len >> 32));
memcpy(&header[2], &tmp, sizeof(tmp));
tmp = htonl((uint32_t)(len & 0xffffffff));
memcpy(&header[6], &tmp, sizeof(tmp));
header_len = 10;
}
/* client connections enable masking */
if (nc->listener == NULL) {
header[1] |= 1 << 7; /* set masking flag */
mg_send(nc, header, header_len);
ctx->mask = mg_ws_random_mask();
mg_send(nc, &ctx->mask, sizeof(ctx->mask));
ctx->pos = nc->send_mbuf.len;
} else {
mg_send(nc, header, header_len);
ctx->pos = 0;
}
}
static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
size_t i;
if (ctx->pos == 0) return;
for (i = 0; i < (mbuf->len - ctx->pos); i++) {
mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
}
}
void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
size_t len) {
struct ws_mask_ctx ctx;
DBG(("%p %d %d", nc, op, (int) len));
mg_send_ws_header(nc, op, len, &ctx);
mg_send(nc, data, len);
mg_ws_mask_frame(&nc->send_mbuf, &ctx);
if (op == WEBSOCKET_OP_CLOSE) {
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
void mg_send_websocket_framev(struct mg_connection *nc, int op,
const struct mg_str *strv, int strvcnt) {
struct ws_mask_ctx ctx;
int i;
int len = 0;
for (i = 0; i < strvcnt; i++) {
len += strv[i].len;
}
mg_send_ws_header(nc, op, len, &ctx);
for (i = 0; i < strvcnt; i++) {
mg_send(nc, strv[i].p, strv[i].len);
}
mg_ws_mask_frame(&nc->send_mbuf, &ctx);
if (op == WEBSOCKET_OP_CLOSE) {
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
void mg_printf_websocket_frame(struct mg_connection *nc, int op,
const char *fmt, ...) {
char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
va_list ap;
int len;
va_start(ap, fmt);
if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
mg_send_websocket_frame(nc, op, buf, len);
}
va_end(ap);
if (buf != mem && buf != NULL) {
MG_FREE(buf);
}
}
MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
switch (ev) {
case MG_EV_RECV:
do {
} while (mg_deliver_websocket_data(nc));
break;
case MG_EV_POLL:
/* Ping idle websocket connections */
{
time_t now = *(time_t *) ev_data;
if (nc->flags & MG_F_IS_WEBSOCKET &&
now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
}
}
break;
default:
break;
}
#if MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
}
#ifndef MG_EXT_SHA1
void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
const size_t *msg_lens, uint8_t *digest) {
size_t i;
cs_sha1_ctx sha_ctx;
cs_sha1_init(&sha_ctx);
for (i = 0; i < num_msgs; i++) {
cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]);
}
cs_sha1_final(digest, &sha_ctx);
}
#else
extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
const size_t *msg_lens, uint8_t *digest);
#endif
MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
const struct mg_str *key,
struct http_message *hm) {
static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic};
const size_t msg_lens[2] = {key->len, 36};
unsigned char sha[20];
char b64_sha[30];
struct mg_str *s;
mg_hash_sha1_v(2, msgs, msg_lens, sha);
mg_base64_encode(sha, sizeof(sha), b64_sha);
mg_printf(nc, "%s",
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n");
s = mg_get_http_header(hm, "Sec-WebSocket-Protocol");
if (s != NULL) {
mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p);
}
mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n");
DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
}
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
const char *host, const char *protocol,
const char *extra_headers) {
mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
NULL);
}
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) {
mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host),
mg_mk_str(protocol), mg_mk_str(extra_headers),
mg_mk_str(user), mg_mk_str(pass));
}
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) {
struct mbuf auth;
char key[25];
uint32_t nonce[4];
nonce[0] = mg_ws_random_mask();
nonce[1] = mg_ws_random_mask();
nonce[2] = mg_ws_random_mask();
nonce[3] = mg_ws_random_mask();
mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key);
mbuf_init(&auth, 0);
if (user.len > 0) {
mg_basic_auth_header(user, pass, &auth);
}
/*
* NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is
* broken: it doesn't like zero length to be passed to %.*s
* i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`.
* because it handles NULL specially (and incorrectly).
*/
mg_printf(nc,
"GET %.*s HTTP/1.1\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"%.*s"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Key: %s\r\n",
(int) path.len, path.p, (int) auth.len,
(auth.buf == NULL ? "" : auth.buf), key);
/* TODO(mkm): take default hostname from http proto data if host == NULL */
if (host.len > 0) {
int host_len = (int) (path.p - host.p); /* Account for possible :PORT */
mg_printf(nc, "Host: %.*s\r\n", host_len, host.p);
}
if (protocol.len > 0) {
mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len,
protocol.p);
}
if (extra_headers.len > 0) {
mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p);
}
mg_printf(nc, "\r\n");
nc->flags |= MG_F_IS_WEBSOCKET;
mbuf_free(&auth);
}
void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
const char *extra_headers) {
struct mg_str null_str = MG_NULL_STR;
mg_send_websocket_handshake3v(
nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */,
mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */);
}
struct mg_connection *mg_connect_ws_opt(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *url, const char *protocol,
const char *extra_headers) {
struct mg_str null_str = MG_NULL_STR;
struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR;
struct mg_connection *nc =
mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
"ws", "https", "wss", url, &path, &user_info, &host);
if (nc != NULL) {
mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol),
mg_mk_str(extra_headers), user_info,
null_str);
}
return nc;
}
struct mg_connection *mg_connect_ws(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
const char *url, const char *protocol, const char *extra_headers) {
struct mg_connect_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
protocol, extra_headers);
}
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
-158
View File
@@ -1,158 +0,0 @@
#ifndef CS_MONGOOSE_SRC_INTERNAL_H_
#define CS_MONGOOSE_SRC_INTERNAL_H_
#include "common/mg_mem.h"
#ifndef MBUF_REALLOC
#define MBUF_REALLOC MG_REALLOC
#endif
#ifndef MBUF_FREE
#define MBUF_FREE MG_FREE
#endif
#define MG_SET_PTRPTR(_ptr, _v) \
do { \
if (_ptr) *(_ptr) = _v; \
} while (0)
#ifndef MG_INTERNAL
#define MG_INTERNAL static
#endif
#ifdef PICOTCP
#define NO_LIBC
#define MG_DISABLE_PFS
#endif
#include "common/cs_dbg.h"
#include "mg_http.h"
#include "mg_net.h"
#ifndef MG_CTL_MSG_MESSAGE_SIZE
#define MG_CTL_MSG_MESSAGE_SIZE 8192
#endif
/* internals that need to be accessible in unit tests */
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
int proto,
union socket_address *sa);
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
int *proto, char *host, size_t host_len);
MG_INTERNAL void mg_call(struct mg_connection *nc,
mg_event_handler_t ev_handler, void *user_data, int ev,
void *ev_data);
void mg_forward(struct mg_connection *from, struct mg_connection *to);
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
MG_INTERNAL struct mg_connection *mg_create_connection(
struct mg_mgr *mgr, mg_event_handler_t callback,
struct mg_add_sock_opts opts);
#ifdef _WIN32
/* Retur value is the same as for MultiByteToWideChar. */
int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
#endif
struct ctl_msg {
mg_event_handler_t callback;
char message[MG_CTL_MSG_MESSAGE_SIZE];
};
#if MG_ENABLE_MQTT
struct mg_mqtt_message;
#define MG_MQTT_ERROR_INCOMPLETE_MSG -1
#define MG_MQTT_ERROR_MALFORMED_MSG -2
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm);
#endif
/* Forward declarations for testing. */
extern void *(*test_malloc)(size_t size);
extern void *(*test_calloc)(size_t count, size_t size);
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#if MG_ENABLE_HTTP
struct mg_serve_http_opts;
MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data(
struct mg_connection *c);
/*
* Reassemble the content of the buffer (buf, blen) which should be
* in the HTTP chunked encoding, by collapsing data chunks to the
* beginning of the buffer.
*
* If chunks get reassembled, modify hm->body to point to the reassembled
* body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
* in nc->flags, delete reassembled body from the mbuf.
*
* Return reassembled body size.
*/
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
struct http_message *hm, char *buf,
size_t blen);
#if MG_ENABLE_FILESYSTEM
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);
MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st);
#endif
#if MG_ENABLE_HTTP_CGI
MG_INTERNAL 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);
struct mg_http_proto_data_cgi;
MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d);
#endif
#if MG_ENABLE_HTTP_SSI
MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
struct http_message *hm,
const char *path,
const struct mg_serve_http_opts *opts);
#endif
#if MG_ENABLE_HTTP_WEBDAV
MG_INTERNAL int mg_is_dav_request(const struct mg_str *s);
MG_INTERNAL 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);
MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path);
MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
struct http_message *hm);
MG_INTERNAL void mg_handle_move(struct mg_connection *c,
const struct mg_serve_http_opts *opts,
const char *path, struct http_message *hm);
MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
const struct mg_serve_http_opts *opts,
const char *path);
MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
struct http_message *hm);
#endif
#if MG_ENABLE_HTTP_WEBSOCKET
MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data));
MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
const struct mg_str *key,
struct http_message *);
#endif
#endif /* MG_ENABLE_HTTP */
MG_INTERNAL int mg_get_errno(void);
MG_INTERNAL void mg_close_conn(struct mg_connection *conn);
#if MG_ENABLE_SNTP
MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
struct mg_sntp_message *msg);
#endif
#endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */
-529
View File
@@ -1,529 +0,0 @@
#if MG_ENABLE_MQTT
#include <string.h>
#include "mg_internal.h"
#include "mg_mqtt.h"
#define MG_F_MQTT_PING_PENDING MG_F_PROTO_1
static uint16_t getu16(const char *p) {
const uint8_t *up = (const uint8_t *) p;
return (up[0] << 8) + up[1];
}
static const char *scanto(const char *p, struct mg_str *s) {
s->len = getu16(p);
s->p = p + 2;
return s->p + s->len;
}
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
uint8_t header;
uint32_t len, len_len; /* must be 32-bit, see #1055 */
const char *p, *end, *eop = &io->buf[io->len];
unsigned char lc = 0;
int cmd;
if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG;
header = io->buf[0];
cmd = header >> 4;
/* decode mqtt variable length */
len = len_len = 0;
p = io->buf + 1;
while (p < eop) {
lc = *((const unsigned char *) p++);
len += (lc & 0x7f) << 7 * len_len;
len_len++;
if (!(lc & 0x80)) break;
if (len_len > sizeof(len)) return MG_MQTT_ERROR_MALFORMED_MSG;
}
end = p + len;
if (lc & 0x80 || end > eop) return MG_MQTT_ERROR_INCOMPLETE_MSG;
mm->cmd = cmd;
mm->qos = MG_MQTT_GET_QOS(header);
switch (cmd) {
case MG_MQTT_CMD_CONNECT: {
p = scanto(p, &mm->protocol_name);
if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->protocol_version = *(uint8_t *) p++;
mm->connect_flags = *(uint8_t *) p++;
mm->keep_alive_timer = getu16(p);
p += 2;
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->client_id);
if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
if (mm->connect_flags & MG_MQTT_HAS_WILL) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->will_topic);
}
if (mm->connect_flags & MG_MQTT_HAS_WILL) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->will_message);
}
if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->user_name);
}
if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) {
if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
p = scanto(p, &mm->password);
}
if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG;
LOG(LL_DEBUG,
("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
"will_msg [%.*s] user_name [%.*s] password [%.*s]",
(int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
(int) mm->protocol_name.len, mm->protocol_name.p,
(int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
(int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
mm->password.p));
break;
}
case MG_MQTT_CMD_CONNACK:
if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->connack_ret_code = p[1];
break;
case MG_MQTT_CMD_PUBACK:
case MG_MQTT_CMD_PUBREC:
case MG_MQTT_CMD_PUBREL:
case MG_MQTT_CMD_PUBCOMP:
case MG_MQTT_CMD_SUBACK:
if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->message_id = getu16(p);
p += 2;
break;
case MG_MQTT_CMD_PUBLISH: {
p = scanto(p, &mm->topic);
if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
if (mm->qos > 0) {
if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->message_id = getu16(p);
p += 2;
}
mm->payload.p = p;
mm->payload.len = end - p;
break;
}
case MG_MQTT_CMD_SUBSCRIBE:
if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
mm->message_id = getu16(p);
p += 2;
/*
* topic expressions are left in the payload and can be parsed with
* `mg_mqtt_next_subscribe_topic`
*/
mm->payload.p = p;
mm->payload.len = end - p;
break;
default:
/* Unhandled command */
break;
}
mm->len = end - io->buf;
return mm->len;
}
static void mqtt_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &nc->recv_mbuf;
struct mg_mqtt_message mm;
memset(&mm, 0, sizeof(mm));
nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_ACCEPT:
if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
break;
case MG_EV_RECV: {
/* There can be multiple messages in the buffer, process them all. */
while (1) {
int len = parse_mqtt(io, &mm);
if (len < 0) {
if (len == MG_MQTT_ERROR_MALFORMED_MSG) {
/* Protocol error. */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
} else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) {
/* Not fully buffered, let's check if we have a chance to get more
* data later */
if (nc->recv_mbuf_limit > 0 &&
nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
"%lu bytes, and not drained, closing",
nc, (unsigned long) nc->recv_mbuf.len,
(unsigned long) nc->recv_mbuf_limit));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
} else {
/* Should never be here */
LOG(LL_ERROR, ("%p invalid len: %d, closing", nc, len));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
break;
}
if (mm.cmd == MG_MQTT_CMD_PINGRESP) {
LOG(LL_DEBUG, ("Recv PINGRESP"));
nc->flags &= ~MG_F_MQTT_PING_PENDING;
}
nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data));
mbuf_remove(io, len);
}
break;
}
case MG_EV_POLL: {
struct mg_mqtt_proto_data *pd =
(struct mg_mqtt_proto_data *) nc->proto_data;
double now = mg_time();
if (pd->keep_alive > 0 && pd->last_control_time > 0) {
double diff = (now - pd->last_control_time);
if (diff > pd->keep_alive) {
if (diff < 1500000000) {
if (!(nc->flags & MG_F_MQTT_PING_PENDING)) {
LOG(LL_DEBUG, ("Send PINGREQ"));
nc->flags |= MG_F_MQTT_PING_PENDING;
mg_mqtt_ping(nc);
} else {
LOG(LL_DEBUG, ("Ping timeout"));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
} else {
/* Wall time has just been set. Avoid immediate ping,
* more likely than not it is not needed. The standard allows for
* 1.5X interval for ping requests, so even if were just about to
* send one, we should be ok waiting 0.4X more. */
pd->last_control_time = now - pd->keep_alive * 0.6;
}
}
}
break;
}
}
}
static void mg_mqtt_proto_data_destructor(void *proto_data) {
MG_FREE(proto_data);
}
static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) {
struct mg_str res = *topic;
const char *c = mg_strchr(*topic, '/');
if (c != NULL) {
res.len = (c - topic->p);
topic->len -= (res.len + 1);
topic->p += (res.len + 1);
} else {
topic->len = 0;
}
return res;
}
/* Refernce: https://mosquitto.org/man/mqtt-7.html */
int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) {
struct mg_str ec, tc;
if (exp.len == 0) return 0;
while (1) {
ec = mg_mqtt_next_topic_component(&exp);
tc = mg_mqtt_next_topic_component(&topic);
if (ec.len == 0) {
if (tc.len != 0) return 0;
if (exp.len == 0) break;
continue;
}
if (mg_vcmp(&ec, "+") == 0) {
if (tc.len == 0 && topic.len == 0) return 0;
continue;
}
if (mg_vcmp(&ec, "#") == 0) {
/* Must be the last component in the expression or it's invalid. */
return (exp.len == 0);
}
if (mg_strcmp(ec, tc) != 0) {
return 0;
}
}
return (tc.len == 0 && topic.len == 0);
}
int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) {
return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic);
}
void mg_set_protocol_mqtt(struct mg_connection *nc) {
nc->proto_handler = mqtt_handler;
nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
}
static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd,
uint8_t flags, size_t len) {
struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
uint8_t buf[1 + sizeof(size_t)];
uint8_t *vlen = &buf[1];
buf[0] = (cmd << 4) | flags;
/* mqtt variable length encoding */
do {
*vlen = len % 0x80;
len /= 0x80;
if (len > 0) *vlen |= 0x80;
vlen++;
} while (len > 0);
mg_send(nc, buf, vlen - buf);
pd->last_control_time = mg_time();
}
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
static struct mg_send_mqtt_handshake_opts opts;
mg_send_mqtt_handshake_opt(nc, client_id, opts);
}
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
struct mg_send_mqtt_handshake_opts opts) {
struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0;
uint16_t netbytes;
size_t total_len;
if (client_id != NULL) {
id_len = strlen(client_id);
}
total_len = 7 + 1 + 2 + 2 + id_len;
if (opts.user_name != NULL) {
opts.flags |= MG_MQTT_HAS_USER_NAME;
}
if (opts.password != NULL) {
opts.flags |= MG_MQTT_HAS_PASSWORD;
}
if (opts.will_topic != NULL && opts.will_message != NULL) {
wt_len = strlen(opts.will_topic);
wm_len = strlen(opts.will_message);
opts.flags |= MG_MQTT_HAS_WILL;
}
if (opts.keep_alive == 0) {
opts.keep_alive = 60;
}
if (opts.flags & MG_MQTT_HAS_WILL) {
total_len += 2 + wt_len + 2 + wm_len;
}
if (opts.flags & MG_MQTT_HAS_USER_NAME) {
user_len = strlen(opts.user_name);
total_len += 2 + user_len;
}
if (opts.flags & MG_MQTT_HAS_PASSWORD) {
pw_len = strlen(opts.password);
total_len += 2 + pw_len;
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len);
mg_send(nc, "\00\04MQTT\04", 7);
mg_send(nc, &opts.flags, 1);
netbytes = htons(opts.keep_alive);
mg_send(nc, &netbytes, 2);
netbytes = htons(id_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, client_id, id_len);
if (opts.flags & MG_MQTT_HAS_WILL) {
netbytes = htons(wt_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.will_topic, wt_len);
netbytes = htons(wm_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.will_message, wm_len);
}
if (opts.flags & MG_MQTT_HAS_USER_NAME) {
netbytes = htons(user_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.user_name, user_len);
}
if (opts.flags & MG_MQTT_HAS_PASSWORD) {
netbytes = htons(pw_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, opts.password, pw_len);
}
if (pd != NULL) {
pd->keep_alive = opts.keep_alive;
}
}
void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
uint16_t message_id, int flags, const void *data,
size_t len) {
uint16_t netbytes;
uint16_t topic_len = strlen(topic);
size_t total_len = 2 + topic_len + len;
if (MG_MQTT_GET_QOS(flags) > 0) {
total_len += 2;
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len);
netbytes = htons(topic_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, topic, topic_len);
if (MG_MQTT_GET_QOS(flags) > 0) {
netbytes = htons(message_id);
mg_send(nc, &netbytes, 2);
}
mg_send(nc, data, len);
}
void mg_mqtt_subscribe(struct mg_connection *nc,
const struct mg_mqtt_topic_expression *topics,
size_t topics_len, uint16_t message_id) {
uint16_t netbytes;
size_t i;
uint16_t topic_len;
size_t total_len = 2;
for (i = 0; i < topics_len; i++) {
total_len += 2 + strlen(topics[i].topic) + 1;
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len);
netbytes = htons(message_id);
mg_send(nc, (char *) &netbytes, 2);
for (i = 0; i < topics_len; i++) {
topic_len = strlen(topics[i].topic);
netbytes = htons(topic_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, topics[i].topic, topic_len);
mg_send(nc, &topics[i].qos, 1);
}
}
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
struct mg_str *topic, uint8_t *qos, int pos) {
unsigned char *buf = (unsigned char *) msg->payload.p + pos;
int new_pos;
if ((size_t) pos >= msg->payload.len) return -1;
topic->len = buf[0] << 8 | buf[1];
topic->p = (char *) buf + 2;
new_pos = pos + 2 + topic->len + 1;
if ((size_t) new_pos > msg->payload.len) return -1;
*qos = buf[2 + topic->len];
return new_pos;
}
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
size_t topics_len, uint16_t message_id) {
uint16_t netbytes;
size_t i;
uint16_t topic_len;
size_t total_len = 2;
for (i = 0; i < topics_len; i++) {
total_len += 2 + strlen(topics[i]);
}
mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len);
netbytes = htons(message_id);
mg_send(nc, (char *) &netbytes, 2);
for (i = 0; i < topics_len; i++) {
topic_len = strlen(topics[i]);
netbytes = htons(topic_len);
mg_send(nc, &netbytes, 2);
mg_send(nc, topics[i], topic_len);
}
}
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
uint8_t unused = 0;
mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
mg_send(nc, &unused, 1);
mg_send(nc, &return_code, 1);
}
/*
* Sends a command which contains only a `message_id` and a QoS level of 1.
*
* Helper function.
*/
static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
uint16_t message_id) {
uint16_t netbytes;
uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0);
mg_send_mqtt_header(nc, cmd, flags, 2 /* len */);
netbytes = htons(message_id);
mg_send(nc, &netbytes, 2);
}
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
}
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
}
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
}
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
}
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
uint16_t message_id) {
size_t i;
uint16_t netbytes;
mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
netbytes = htons(message_id);
mg_send(nc, &netbytes, 2);
for (i = 0; i < qoss_len; i++) {
mg_send(nc, &qoss[i], 1);
}
}
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
}
void mg_mqtt_ping(struct mg_connection *nc) {
mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
}
void mg_mqtt_pong(struct mg_connection *nc) {
mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
}
void mg_mqtt_disconnect(struct mg_connection *nc) {
mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
}
#endif /* MG_ENABLE_MQTT */
-212
View File
@@ -1,212 +0,0 @@
/*
* === MQTT API reference
*/
#ifndef CS_MONGOOSE_SRC_MQTT_H_
#define CS_MONGOOSE_SRC_MQTT_H_
#include "mg_net.h"
struct mg_mqtt_message {
int cmd;
int qos;
int len; /* message length in the IO buffer */
struct mg_str topic;
struct mg_str payload;
uint8_t connack_ret_code; /* connack */
uint16_t message_id; /* puback */
/* connect */
uint8_t protocol_version;
uint8_t connect_flags;
uint16_t keep_alive_timer;
struct mg_str protocol_name;
struct mg_str client_id;
struct mg_str will_topic;
struct mg_str will_message;
struct mg_str user_name;
struct mg_str password;
};
struct mg_mqtt_topic_expression {
const char *topic;
uint8_t qos;
};
struct mg_send_mqtt_handshake_opts {
unsigned char flags; /* connection flags */
uint16_t keep_alive;
const char *will_topic;
const char *will_message;
const char *user_name;
const char *password;
};
/* mg_mqtt_proto_data should be in header to allow external access to it */
struct mg_mqtt_proto_data {
uint16_t keep_alive;
double last_control_time;
};
/* Message types */
#define MG_MQTT_CMD_CONNECT 1
#define MG_MQTT_CMD_CONNACK 2
#define MG_MQTT_CMD_PUBLISH 3
#define MG_MQTT_CMD_PUBACK 4
#define MG_MQTT_CMD_PUBREC 5
#define MG_MQTT_CMD_PUBREL 6
#define MG_MQTT_CMD_PUBCOMP 7
#define MG_MQTT_CMD_SUBSCRIBE 8
#define MG_MQTT_CMD_SUBACK 9
#define MG_MQTT_CMD_UNSUBSCRIBE 10
#define MG_MQTT_CMD_UNSUBACK 11
#define MG_MQTT_CMD_PINGREQ 12
#define MG_MQTT_CMD_PINGRESP 13
#define MG_MQTT_CMD_DISCONNECT 14
/* MQTT event types */
#define MG_MQTT_EVENT_BASE 200
#define MG_EV_MQTT_CONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNECT)
#define MG_EV_MQTT_CONNACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNACK)
#define MG_EV_MQTT_PUBLISH (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBLISH)
#define MG_EV_MQTT_PUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBACK)
#define MG_EV_MQTT_PUBREC (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREC)
#define MG_EV_MQTT_PUBREL (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREL)
#define MG_EV_MQTT_PUBCOMP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBCOMP)
#define MG_EV_MQTT_SUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBSCRIBE)
#define MG_EV_MQTT_SUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBACK)
#define MG_EV_MQTT_UNSUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBSCRIBE)
#define MG_EV_MQTT_UNSUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBACK)
#define MG_EV_MQTT_PINGREQ (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGREQ)
#define MG_EV_MQTT_PINGRESP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGRESP)
#define MG_EV_MQTT_DISCONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_DISCONNECT)
/* Message flags */
#define MG_MQTT_RETAIN 0x1
#define MG_MQTT_QOS(qos) ((qos) << 1)
#define MG_MQTT_GET_QOS(flags) (((flags) &0x6) >> 1)
#define MG_MQTT_SET_QOS(flags, qos) (flags) = ((flags) & ~0x6) | ((qos) << 1)
#define MG_MQTT_DUP 0x8
/* Connection flags */
#define MG_MQTT_CLEAN_SESSION 0x02
#define MG_MQTT_HAS_WILL 0x04
#define MG_MQTT_WILL_RETAIN 0x20
#define MG_MQTT_HAS_PASSWORD 0x40
#define MG_MQTT_HAS_USER_NAME 0x80
#define MG_MQTT_GET_WILL_QOS(flags) (((flags) &0x18) >> 3)
#define MG_MQTT_SET_WILL_QOS(flags, qos) \
(flags) = ((flags) & ~0x18) | ((qos) << 3)
/* CONNACK return codes */
#define MG_EV_MQTT_CONNACK_ACCEPTED 0
#define MG_EV_MQTT_CONNACK_UNACCEPTABLE_VERSION 1
#define MG_EV_MQTT_CONNACK_IDENTIFIER_REJECTED 2
#define MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE 3
#define MG_EV_MQTT_CONNACK_BAD_AUTH 4
#define MG_EV_MQTT_CONNACK_NOT_AUTHORIZED 5
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* Attaches a built-in MQTT event handler to the given connection.
*
* The user-defined event handler will receive following extra events:
*
* - MG_EV_MQTT_CONNACK
* - MG_EV_MQTT_PUBLISH
* - MG_EV_MQTT_PUBACK
* - MG_EV_MQTT_PUBREC
* - MG_EV_MQTT_PUBREL
* - MG_EV_MQTT_PUBCOMP
* - MG_EV_MQTT_SUBACK
*/
void mg_set_protocol_mqtt(struct mg_connection *nc);
/* Sends an MQTT handshake. */
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id);
/* Sends an MQTT handshake with optional parameters. */
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
struct mg_send_mqtt_handshake_opts);
/* Publishes a message to a given topic. */
void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
uint16_t message_id, int flags, const void *data,
size_t len);
/* Subscribes to a bunch of topics. */
void mg_mqtt_subscribe(struct mg_connection *nc,
const struct mg_mqtt_topic_expression *topics,
size_t topics_len, uint16_t message_id);
/* Unsubscribes from a bunch of topics. */
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
size_t topics_len, uint16_t message_id);
/* Sends a DISCONNECT command. */
void mg_mqtt_disconnect(struct mg_connection *nc);
/* Sends a CONNACK command with a given `return_code`. */
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code);
/* Sends a PUBACK command with a given `message_id`. */
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id);
/* Sends a PUBREC command with a given `message_id`. */
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id);
/* Sends a PUBREL command with a given `message_id`. */
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id);
/* Sends a PUBCOMP command with a given `message_id`. */
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id);
/*
* Sends a SUBACK command with a given `message_id`
* and a sequence of granted QoSs.
*/
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
uint16_t message_id);
/* Sends a UNSUBACK command with a given `message_id`. */
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id);
/* Sends a PINGREQ command. */
void mg_mqtt_ping(struct mg_connection *nc);
/* Sends a PINGRESP command. */
void mg_mqtt_pong(struct mg_connection *nc);
/*
* Extracts the next topic expression from a SUBSCRIBE command payload.
*
* The topic expression name will point to a string in the payload buffer.
* Returns the pos of the next topic expression or -1 when the list
* of topics is exhausted.
*/
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
struct mg_str *topic, uint8_t *qos, int pos);
/*
* Matches a topic against a topic expression
*
* Returns 1 if it matches; 0 otherwise.
*/
int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic);
/*
* Same as `mg_mqtt_match_topic_expression()`, but takes `exp` as a
* NULL-terminated string.
*/
int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_MONGOOSE_SRC_MQTT_H_ */

Some files were not shown because too many files have changed in this diff Show More