LCOV - code coverage report
Current view: top level - progs - mongoose6.cxx (source / functions) Coverage Total Hit
Test: coverage.info Lines: 0.0 % 3637 0
Test Date: 2025-11-11 10:26:08 Functions: 0.0 % 310 0

            Line data    Source code
       1              : #include "mongoose6.h"
       2              : #ifdef MG_MODULE_LINES
       3              : #line 1 "./src/internal.h"
       4              : #endif
       5              : /*
       6              :  * Copyright (c) 2014 Cesanta Software Limited
       7              :  * All rights reserved
       8              :  */
       9              : 
      10              : #ifndef CS_MONGOOSE_SRC_INTERNAL_H_
      11              : #define CS_MONGOOSE_SRC_INTERNAL_H_
      12              : 
      13              : #ifndef MG_MALLOC
      14              : #define MG_MALLOC malloc
      15              : #endif
      16              : 
      17              : #ifndef MG_CALLOC
      18              : #define MG_CALLOC calloc
      19              : #endif
      20              : 
      21              : #ifndef MG_REALLOC
      22              : #define MG_REALLOC realloc
      23              : #endif
      24              : 
      25              : #ifndef MG_FREE
      26              : #define MG_FREE free
      27              : #endif
      28              : 
      29              : #ifndef MBUF_REALLOC
      30              : #define MBUF_REALLOC MG_REALLOC
      31              : #endif
      32              : 
      33              : #ifndef MBUF_FREE
      34              : #define MBUF_FREE MG_FREE
      35              : #endif
      36              : 
      37              : #define MG_SET_PTRPTR(_ptr, _v) \
      38              :   do {                          \
      39              :     if (_ptr) *(_ptr) = _v;     \
      40              :   } while (0)
      41              : 
      42              : #ifndef MG_INTERNAL
      43              : #define MG_INTERNAL static
      44              : #endif
      45              : 
      46              : #ifdef PICOTCP
      47              : #define NO_LIBC
      48              : #define MG_DISABLE_FILESYSTEM
      49              : #define MG_DISABLE_POPEN
      50              : #define MG_DISABLE_CGI
      51              : #define MG_DISABLE_DIRECTORY_LISTING
      52              : #define MG_DISABLE_SOCKETPAIR
      53              : #define MG_DISABLE_PFS
      54              : #endif
      55              : 
      56              : /* Amalgamated: #include "mongoose/src/net.h" */
      57              : /* Amalgamated: #include "mongoose/src/http.h" */
      58              : 
      59              : #define MG_CTL_MSG_MESSAGE_SIZE 8192
      60              : 
      61              : /* internals that need to be accessible in unit tests */
      62              : MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
      63              :                                                 int proto,
      64              :                                                 union socket_address *sa);
      65              : 
      66              : MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
      67              :                                  int *proto, char *host, size_t host_len);
      68              : MG_INTERNAL void mg_call(struct mg_connection *nc,
      69              :                          mg_event_handler_t ev_handler, int ev, void *ev_data);
      70              : void mg_forward(struct mg_connection *from, struct mg_connection *to);
      71              : MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
      72              : MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
      73              : MG_INTERNAL struct mg_connection *mg_create_connection(
      74              :     struct mg_mgr *mgr, mg_event_handler_t callback,
      75              :     struct mg_add_sock_opts opts);
      76              : #ifndef MG_DISABLE_FILESYSTEM
      77              : MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
      78              :                                      const struct mg_serve_http_opts *opts,
      79              :                                      char **local_path,
      80              :                                      struct mg_str *remainder);
      81              : #endif
      82              : #ifdef _WIN32
      83              : /* Retur value is the same as for MultiByteToWideChar. */
      84              : int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
      85              : #endif
      86              : 
      87              : /*
      88              :  * Reassemble the content of the buffer (buf, blen) which should be
      89              :  * in the HTTP chunked encoding, by collapsing data chunks to the
      90              :  * beginning of the buffer.
      91              :  *
      92              :  * If chunks get reassembled, modify hm->body to point to the reassembled
      93              :  * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
      94              :  * in nc->flags, delete reassembled body from the mbuf.
      95              :  *
      96              :  * Return reassembled body size.
      97              :  */
      98              : MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
      99              :                                      struct http_message *hm, char *buf,
     100              :                                      size_t blen);
     101              : 
     102              : #ifndef MG_DISABLE_FILESYSTEM
     103              : MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
     104              : MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st);
     105              : #endif
     106              : 
     107              : struct ctl_msg {
     108              :   mg_event_handler_t callback;
     109              :   char message[MG_CTL_MSG_MESSAGE_SIZE];
     110              : };
     111              : 
     112              : #ifndef MG_DISABLE_MQTT
     113              : struct mg_mqtt_message;
     114              : MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm);
     115              : #endif
     116              : 
     117              : /* Forward declarations for testing. */
     118              : extern void *(*test_malloc)(size_t size);
     119              : extern void *(*test_calloc)(size_t count, size_t size);
     120              : 
     121              : #endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */
     122              : #ifdef MG_MODULE_LINES
     123              : #line 1 "./src/../../common/base64.c"
     124              : #endif
     125              : /*
     126              :  * Copyright (c) 2014 Cesanta Software Limited
     127              :  * All rights reserved
     128              :  */
     129              : 
     130              : #ifndef EXCLUDE_COMMON
     131              : 
     132              : /* Amalgamated: #include "common/base64.h" */
     133              : #include <string.h>
     134              : 
     135              : /* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
     136              : 
     137              : #define NUM_UPPERCASES ('Z' - 'A' + 1)
     138              : #define NUM_LETTERS (NUM_UPPERCASES * 2)
     139              : #define NUM_DIGITS ('9' - '0' + 1)
     140              : 
     141              : /*
     142              :  * Emit a base64 code char.
     143              :  *
     144              :  * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
     145              :  */
     146            0 : static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
     147            0 :   if (v < NUM_UPPERCASES) {
     148            0 :     ctx->b64_putc(v + 'A', ctx->user_data);
     149            0 :   } else if (v < (NUM_LETTERS)) {
     150            0 :     ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
     151            0 :   } else if (v < (NUM_LETTERS + NUM_DIGITS)) {
     152            0 :     ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
     153              :   } else {
     154            0 :     ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
     155              :                   ctx->user_data);
     156              :   }
     157            0 : }
     158              : 
     159            0 : static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
     160              :   int a, b, c;
     161              : 
     162            0 :   a = ctx->chunk[0];
     163            0 :   b = ctx->chunk[1];
     164            0 :   c = ctx->chunk[2];
     165              : 
     166            0 :   cs_base64_emit_code(ctx, a >> 2);
     167            0 :   cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
     168            0 :   if (ctx->chunk_size > 1) {
     169            0 :     cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
     170              :   }
     171            0 :   if (ctx->chunk_size > 2) {
     172            0 :     cs_base64_emit_code(ctx, c & 63);
     173              :   }
     174            0 : }
     175              : 
     176            0 : void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
     177              :                     void *user_data) {
     178            0 :   ctx->chunk_size = 0;
     179            0 :   ctx->b64_putc = b64_putc;
     180            0 :   ctx->user_data = user_data;
     181            0 : }
     182              : 
     183            0 : void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
     184            0 :   const unsigned char *src = (const unsigned char *) str;
     185              :   size_t i;
     186            0 :   for (i = 0; i < len; i++) {
     187            0 :     ctx->chunk[ctx->chunk_size++] = src[i];
     188            0 :     if (ctx->chunk_size == 3) {
     189            0 :       cs_base64_emit_chunk(ctx);
     190            0 :       ctx->chunk_size = 0;
     191              :     }
     192              :   }
     193            0 : }
     194              : 
     195            0 : void cs_base64_finish(struct cs_base64_ctx *ctx) {
     196            0 :   if (ctx->chunk_size > 0) {
     197              :     int i;
     198            0 :     memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
     199            0 :     cs_base64_emit_chunk(ctx);
     200            0 :     for (i = 0; i < (3 - ctx->chunk_size); i++) {
     201            0 :       ctx->b64_putc('=', ctx->user_data);
     202              :     }
     203              :   }
     204            0 : }
     205              : 
     206              : #define BASE64_ENCODE_BODY                                                \
     207              :   static const char *b64 =                                                \
     208              :       "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
     209              :   int i, j, a, b, c;                                                      \
     210              :                                                                           \
     211              :   for (i = j = 0; i < src_len; i += 3) {                                  \
     212              :     a = src[i];                                                           \
     213              :     b = i + 1 >= src_len ? 0 : src[i + 1];                                \
     214              :     c = i + 2 >= src_len ? 0 : src[i + 2];                                \
     215              :                                                                           \
     216              :     BASE64_OUT(b64[a >> 2]);                                              \
     217              :     BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]);                           \
     218              :     if (i + 1 < src_len) {                                                \
     219              :       BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]);                          \
     220              :     }                                                                     \
     221              :     if (i + 2 < src_len) {                                                \
     222              :       BASE64_OUT(b64[c & 63]);                                            \
     223              :     }                                                                     \
     224              :   }                                                                       \
     225              :                                                                           \
     226              :   while (j % 4 != 0) {                                                    \
     227              :     BASE64_OUT('=');                                                      \
     228              :   }                                                                       \
     229              :   BASE64_FLUSH()
     230              : 
     231              : #define BASE64_OUT(ch) \
     232              :   do {                 \
     233              :     dst[j++] = (ch);   \
     234              :   } while (0)
     235              : 
     236              : #define BASE64_FLUSH() \
     237              :   do {                 \
     238              :     dst[j++] = '\0';   \
     239              :   } while (0)
     240              : 
     241            0 : void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
     242            0 :   BASE64_ENCODE_BODY;
     243            0 : }
     244              : 
     245              : #undef BASE64_OUT
     246              : #undef BASE64_FLUSH
     247              : 
     248              : #ifndef CS_DISABLE_STDIO
     249              : #define BASE64_OUT(ch)      \
     250              :   do {                      \
     251              :     fprintf(f, "%c", (ch)); \
     252              :     j++;                    \
     253              :   } while (0)
     254              : 
     255              : #define BASE64_FLUSH()
     256              : 
     257            0 : void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
     258            0 :   BASE64_ENCODE_BODY;
     259            0 : }
     260              : 
     261              : #undef BASE64_OUT
     262              : #undef BASE64_FLUSH
     263              : #endif /* !CS_DISABLE_STDIO */
     264              : 
     265              : /* Convert one byte of encoded base64 input stream to 6-bit chunk */
     266            0 : static unsigned char from_b64(unsigned char ch) {
     267              :   /* Inverse lookup map */
     268              :   static const unsigned char tab[128] = {
     269              :       255, 255, 255, 255,
     270              :       255, 255, 255, 255, /*  0 */
     271              :       255, 255, 255, 255,
     272              :       255, 255, 255, 255, /*  8 */
     273              :       255, 255, 255, 255,
     274              :       255, 255, 255, 255, /*  16 */
     275              :       255, 255, 255, 255,
     276              :       255, 255, 255, 255, /*  24 */
     277              :       255, 255, 255, 255,
     278              :       255, 255, 255, 255, /*  32 */
     279              :       255, 255, 255, 62,
     280              :       255, 255, 255, 63, /*  40 */
     281              :       52,  53,  54,  55,
     282              :       56,  57,  58,  59, /*  48 */
     283              :       60,  61,  255, 255,
     284              :       255, 200, 255, 255, /*  56   '=' is 200, on index 61 */
     285              :       255, 0,   1,   2,
     286              :       3,   4,   5,   6, /*  64 */
     287              :       7,   8,   9,   10,
     288              :       11,  12,  13,  14, /*  72 */
     289              :       15,  16,  17,  18,
     290              :       19,  20,  21,  22, /*  80 */
     291              :       23,  24,  25,  255,
     292              :       255, 255, 255, 255, /*  88 */
     293              :       255, 26,  27,  28,
     294              :       29,  30,  31,  32, /*  96 */
     295              :       33,  34,  35,  36,
     296              :       37,  38,  39,  40, /*  104 */
     297              :       41,  42,  43,  44,
     298              :       45,  46,  47,  48, /*  112 */
     299              :       49,  50,  51,  255,
     300              :       255, 255, 255, 255, /*  120 */
     301              :   };
     302            0 :   return tab[ch & 127];
     303              : }
     304              : 
     305            0 : int cs_base64_decode(const unsigned char *s, int len, char *dst) {
     306              :   unsigned char a, b, c, d;
     307            0 :   int orig_len = len;
     308            0 :   while (len >= 4 && (a = from_b64(s[0])) != 255 &&
     309            0 :          (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
     310            0 :          (d = from_b64(s[3])) != 255) {
     311            0 :     s += 4;
     312            0 :     len -= 4;
     313            0 :     if (a == 200 || b == 200) break; /* '=' can't be there */
     314            0 :     *dst++ = a << 2 | b >> 4;
     315            0 :     if (c == 200) break;
     316            0 :     *dst++ = b << 4 | c >> 2;
     317            0 :     if (d == 200) break;
     318            0 :     *dst++ = c << 6 | d;
     319              :   }
     320            0 :   *dst = 0;
     321            0 :   return orig_len - len;
     322              : }
     323              : 
     324              : #endif /* EXCLUDE_COMMON */
     325              : #ifdef MG_MODULE_LINES
     326              : #line 1 "./src/../../common/cs_dbg.c"
     327              : #endif
     328              : /*
     329              :  * Copyright (c) 2014-2016 Cesanta Software Limited
     330              :  * All rights reserved
     331              :  */
     332              : 
     333              : /* Amalgamated: #include "common/cs_dbg.h" */
     334              : 
     335              : #include <stdarg.h>
     336              : #include <stdio.h>
     337              : 
     338              : /* Amalgamated: #include "common/cs_time.h" */
     339              : 
     340              : enum cs_log_level cs_log_level =
     341              : #ifdef CS_ENABLE_DEBUG
     342              :     LL_VERBOSE_DEBUG;
     343              : #else
     344              :     LL_ERROR;
     345              : #endif
     346              : 
     347              : #ifndef CS_DISABLE_STDIO
     348              : 
     349              : FILE *cs_log_file = NULL;
     350              : 
     351              : #ifdef CS_LOG_TS_DIFF
     352              : double cs_log_ts;
     353              : #endif
     354              : 
     355            0 : void cs_log_print_prefix(const char *func) {
     356            0 :   if (cs_log_file == NULL) cs_log_file = stderr;
     357            0 :   fprintf(cs_log_file, "%-20s ", func);
     358              : #ifdef CS_LOG_TS_DIFF
     359              :   {
     360              :     double now = cs_time();
     361              :     fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000));
     362              :     cs_log_ts = now;
     363              :   }
     364              : #endif
     365            0 : }
     366              : 
     367            0 : void cs_log_printf(const char *fmt, ...) {
     368              :   va_list ap;
     369            0 :   va_start(ap, fmt);
     370            0 :   vfprintf(cs_log_file, fmt, ap);
     371            0 :   va_end(ap);
     372            0 :   fputc('\n', cs_log_file);
     373            0 :   fflush(cs_log_file);
     374            0 : }
     375              : 
     376            0 : void cs_log_set_file(FILE *file) {
     377            0 :   cs_log_file = file;
     378            0 : }
     379              : 
     380              : #endif /* !CS_DISABLE_STDIO */
     381              : 
     382            0 : void cs_log_set_level(enum cs_log_level level) {
     383            0 :   cs_log_level = level;
     384              : #if defined(CS_LOG_TS_DIFF) && !defined(CS_DISABLE_STDIO)
     385              :   cs_log_ts = cs_time();
     386              : #endif
     387            0 : }
     388              : #ifdef MG_MODULE_LINES
     389              : #line 1 "./src/../../common/cs_dirent.c"
     390              : #endif
     391              : /*
     392              :  * Copyright (c) 2015 Cesanta Software Limited
     393              :  * All rights reserved
     394              :  */
     395              : 
     396              : #ifndef EXCLUDE_COMMON
     397              : 
     398              : /* Amalgamated: #include "common/cs_dirent.h" */
     399              : 
     400              : /*
     401              :  * This file contains POSIX opendir/closedir/readdir API implementation
     402              :  * for systems which do not natively support it (e.g. Windows).
     403              :  */
     404              : 
     405              : #ifndef MG_FREE
     406              : #define MG_FREE free
     407              : #endif
     408              : 
     409              : #ifndef MG_MALLOC
     410              : #define MG_MALLOC malloc
     411              : #endif
     412              : 
     413              : #ifdef _WIN32
     414              : DIR *opendir(const char *name) {
     415              :   DIR *dir = NULL;
     416              :   wchar_t wpath[MAX_PATH];
     417              :   DWORD attrs;
     418              : 
     419              :   if (name == NULL) {
     420              :     SetLastError(ERROR_BAD_ARGUMENTS);
     421              :   } else if ((dir = (DIR *) MG_MALLOC(sizeof(*dir))) == NULL) {
     422              :     SetLastError(ERROR_NOT_ENOUGH_MEMORY);
     423              :   } else {
     424              :     to_wchar(name, wpath, ARRAY_SIZE(wpath));
     425              :     attrs = GetFileAttributesW(wpath);
     426              :     if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
     427              :       (void) wcscat(wpath, L"\\*");
     428              :       dir->handle = FindFirstFileW(wpath, &dir->info);
     429              :       dir->result.d_name[0] = '\0';
     430              :     } else {
     431              :       MG_FREE(dir);
     432              :       dir = NULL;
     433              :     }
     434              :   }
     435              : 
     436              :   return dir;
     437              : }
     438              : 
     439              : int closedir(DIR *dir) {
     440              :   int result = 0;
     441              : 
     442              :   if (dir != NULL) {
     443              :     if (dir->handle != INVALID_HANDLE_VALUE)
     444              :       result = FindClose(dir->handle) ? 0 : -1;
     445              :     MG_FREE(dir);
     446              :   } else {
     447              :     result = -1;
     448              :     SetLastError(ERROR_BAD_ARGUMENTS);
     449              :   }
     450              : 
     451              :   return result;
     452              : }
     453              : 
     454              : struct dirent *readdir(DIR *dir) {
     455              :   struct dirent *result = NULL;
     456              : 
     457              :   if (dir) {
     458              :     if (dir->handle != INVALID_HANDLE_VALUE) {
     459              :       result = &dir->result;
     460              :       (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
     461              :                                  result->d_name, sizeof(result->d_name), NULL,
     462              :                                  NULL);
     463              : 
     464              :       if (!FindNextFileW(dir->handle, &dir->info)) {
     465              :         (void) FindClose(dir->handle);
     466              :         dir->handle = INVALID_HANDLE_VALUE;
     467              :       }
     468              : 
     469              :     } else {
     470              :       SetLastError(ERROR_FILE_NOT_FOUND);
     471              :     }
     472              :   } else {
     473              :     SetLastError(ERROR_BAD_ARGUMENTS);
     474              :   }
     475              : 
     476              :   return result;
     477              : }
     478              : #endif
     479              : 
     480              : #ifdef CS_ENABLE_SPIFFS
     481              : 
     482              : DIR *opendir(const char *dir_name) {
     483              :   DIR *dir = NULL;
     484              :   extern spiffs fs;
     485              : 
     486              :   if (dir_name != NULL && (dir = (DIR *) malloc(sizeof(*dir))) != NULL &&
     487              :       SPIFFS_opendir(&fs, (char *) dir_name, &dir->dh) == NULL) {
     488              :     free(dir);
     489              :     dir = NULL;
     490              :   }
     491              : 
     492              :   return dir;
     493              : }
     494              : 
     495              : int closedir(DIR *dir) {
     496              :   if (dir != NULL) {
     497              :     SPIFFS_closedir(&dir->dh);
     498              :     free(dir);
     499              :   }
     500              :   return 0;
     501              : }
     502              : 
     503              : struct dirent *readdir(DIR *dir) {
     504              :   return SPIFFS_readdir(&dir->dh, &dir->de);
     505              : }
     506              : 
     507              : /* SPIFFs doesn't support directory operations */
     508              : int rmdir(const char *path) {
     509              :   (void) path;
     510              :   return ENOTDIR;
     511              : }
     512              : 
     513              : int mkdir(const char *path, mode_t mode) {
     514              :   (void) path;
     515              :   (void) mode;
     516              :   /* for spiffs supports only root dir, which comes from mongoose as '.' */
     517              :   return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
     518              : }
     519              : 
     520              : #endif /* CS_ENABLE_SPIFFS */
     521              : 
     522              : #endif /* EXCLUDE_COMMON */
     523              : 
     524              : /* ISO C requires a translation unit to contain at least one declaration */
     525              : typedef int cs_dirent_dummy;
     526              : #ifdef MG_MODULE_LINES
     527              : #line 1 "./src/../../common/cs_time.c"
     528              : #endif
     529              : /*
     530              :  * Copyright (c) 2014-2016 Cesanta Software Limited
     531              :  * All rights reserved
     532              :  */
     533              : 
     534              : #ifndef _WIN32
     535              : #include <stddef.h>
     536              : #if !defined(CS_PLATFORM) || \
     537              :     (CS_PLATFORM != CS_P_CC3200 && CS_PLATFORM != CS_P_MSP432)
     538              : #include <sys/time.h>
     539              : #endif
     540              : #else
     541              : #include <windows.h>
     542              : #endif
     543              : 
     544            0 : double cs_time() {
     545              :   double now;
     546              : #ifndef _WIN32
     547              :   struct timeval tv;
     548            0 :   if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
     549            0 :   now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
     550              : #else
     551              :   now = GetTickCount() / 1000.0;
     552              : #endif
     553            0 :   return now;
     554              : }
     555              : #ifdef MG_MODULE_LINES
     556              : #line 1 "./src/../deps/frozen/frozen.c"
     557              : #endif
     558              : /*
     559              :  * Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
     560              :  * Copyright (c) 2013 Cesanta Software Limited
     561              :  * All rights reserved
     562              :  *
     563              :  * This library is dual-licensed: you can redistribute it and/or modify
     564              :  * it under the terms of the GNU General Public License version 2 as
     565              :  * published by the Free Software Foundation. For the terms of this
     566              :  * license, see <http: *www.gnu.org/licenses/>.
     567              :  *
     568              :  * You are free to use this library under the terms of the GNU General
     569              :  * Public License, but WITHOUT ANY WARRANTY; without even the implied
     570              :  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     571              :  * See the GNU General Public License for more details.
     572              :  *
     573              :  * Alternatively, you can license this library under a commercial
     574              :  * license, as set out in <http://cesanta.com/products.html>.
     575              :  */
     576              : 
     577              : #ifndef _CRT_SECURE_NO_WARNINGS
     578              : #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005+ */
     579              : #endif
     580              : 
     581              : #include <stdio.h>
     582              : #include <stdlib.h>
     583              : #include <string.h>
     584              : #include <stdarg.h>
     585              : /* Amalgamated: #include "frozen.h" */
     586              : 
     587              : #ifdef _WIN32
     588              : #define snprintf _snprintf
     589              : #endif
     590              : 
     591              : #ifndef FROZEN_REALLOC
     592              : #define FROZEN_REALLOC realloc
     593              : #endif
     594              : 
     595              : #ifndef FROZEN_FREE
     596              : #define FROZEN_FREE free
     597              : #endif
     598              : 
     599              : struct frozen {
     600              :   const char *end;
     601              :   const char *cur;
     602              :   struct json_token *tokens;
     603              :   int max_tokens;
     604              :   int num_tokens;
     605              :   int do_realloc;
     606              : };
     607              : 
     608              : static int parse_object(struct frozen *f);
     609              : static int parse_value(struct frozen *f);
     610              : 
     611              : #define EXPECT(cond, err_code)      \
     612              :   do {                              \
     613              :     if (!(cond)) return (err_code); \
     614              :   } while (0)
     615              : #define TRY(expr)          \
     616              :   do {                     \
     617              :     int _n = expr;         \
     618              :     if (_n < 0) return _n; \
     619              :   } while (0)
     620              : #define END_OF_STRING (-1)
     621              : 
     622            0 : static int left(const struct frozen *f) {
     623            0 :   return f->end - f->cur;
     624              : }
     625              : 
     626            0 : static int is_space(int ch) {
     627            0 :   return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
     628              : }
     629              : 
     630            0 : static void skip_whitespaces(struct frozen *f) {
     631            0 :   while (f->cur < f->end && is_space(*f->cur)) f->cur++;
     632            0 : }
     633              : 
     634            0 : static int cur(struct frozen *f) {
     635            0 :   skip_whitespaces(f);
     636            0 :   return f->cur >= f->end ? END_OF_STRING : *(unsigned char *) f->cur;
     637              : }
     638              : 
     639            0 : static int test_and_skip(struct frozen *f, int expected) {
     640            0 :   int ch = cur(f);
     641            0 :   if (ch == expected) {
     642            0 :     f->cur++;
     643            0 :     return 0;
     644              :   }
     645            0 :   return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
     646              : }
     647              : 
     648            0 : static int test_no_skip(struct frozen *f, int expected) {
     649            0 :   int ch = cur(f);
     650            0 :   if (ch == expected) {
     651            0 :     return 0;
     652              :   }
     653            0 :   return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
     654              : }
     655              : 
     656            0 : static int is_alpha(int ch) {
     657            0 :   return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
     658              : }
     659              : 
     660            0 : static int is_digit(int ch) {
     661            0 :   return ch >= '0' && ch <= '9';
     662              : }
     663              : 
     664            0 : static int is_hex_digit(int ch) {
     665            0 :   return is_digit(ch) || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F');
     666              : }
     667              : 
     668            0 : static int get_escape_len(const char *s, int len) {
     669            0 :   switch (*s) {
     670            0 :     case 'u':
     671            0 :       return len < 6 ? JSON_STRING_INCOMPLETE
     672            0 :                      : is_hex_digit(s[1]) && is_hex_digit(s[2]) &&
     673            0 :                                is_hex_digit(s[3]) && is_hex_digit(s[4])
     674            0 :                            ? 5
     675            0 :                            : JSON_STRING_INVALID;
     676            0 :     case '"':
     677              :     case '\\':
     678              :     case '/':
     679              :     case 'b':
     680              :     case 'f':
     681              :     case 'n':
     682              :     case 'r':
     683              :     case 't':
     684            0 :       return len < 2 ? JSON_STRING_INCOMPLETE : 1;
     685            0 :     default:
     686            0 :       return JSON_STRING_INVALID;
     687              :   }
     688              : }
     689              : 
     690            0 : static int capture_ptr(struct frozen *f, const char *ptr, enum json_type type) {
     691            0 :   if (f->do_realloc && f->num_tokens >= f->max_tokens) {
     692            0 :     int new_size = f->max_tokens == 0 ? 100 : f->max_tokens * 2;
     693            0 :     void *p = FROZEN_REALLOC(f->tokens, new_size * sizeof(f->tokens[0]));
     694            0 :     if (p == NULL) return JSON_TOKEN_ARRAY_TOO_SMALL;
     695            0 :     f->max_tokens = new_size;
     696            0 :     f->tokens = (struct json_token *) p;
     697              :   }
     698            0 :   if (f->tokens == NULL || f->max_tokens == 0) return 0;
     699            0 :   if (f->num_tokens >= f->max_tokens) return JSON_TOKEN_ARRAY_TOO_SMALL;
     700            0 :   f->tokens[f->num_tokens].ptr = ptr;
     701            0 :   f->tokens[f->num_tokens].type = type;
     702            0 :   f->num_tokens++;
     703            0 :   return 0;
     704              : }
     705              : 
     706            0 : static int capture_len(struct frozen *f, int token_index, const char *ptr) {
     707            0 :   if (f->tokens == 0 || f->max_tokens == 0) return 0;
     708            0 :   EXPECT(token_index >= 0 && token_index < f->max_tokens, JSON_STRING_INVALID);
     709            0 :   f->tokens[token_index].len = ptr - f->tokens[token_index].ptr;
     710            0 :   f->tokens[token_index].num_desc = (f->num_tokens - 1) - token_index;
     711            0 :   return 0;
     712              : }
     713              : 
     714              : /* identifier = letter { letter | digit | '_' } */
     715            0 : static int parse_identifier(struct frozen *f) {
     716            0 :   EXPECT(is_alpha(cur(f)), JSON_STRING_INVALID);
     717            0 :   TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING));
     718            0 :   while (f->cur < f->end &&
     719            0 :          (*f->cur == '_' || is_alpha(*f->cur) || is_digit(*f->cur))) {
     720            0 :     f->cur++;
     721              :   }
     722            0 :   capture_len(f, f->num_tokens - 1, f->cur);
     723            0 :   return 0;
     724              : }
     725              : 
     726            0 : static int get_utf8_char_len(unsigned char ch) {
     727            0 :   if ((ch & 0x80) == 0) return 1;
     728            0 :   switch (ch & 0xf0) {
     729            0 :     case 0xf0:
     730            0 :       return 4;
     731            0 :     case 0xe0:
     732            0 :       return 3;
     733            0 :     default:
     734            0 :       return 2;
     735              :   }
     736              : }
     737              : 
     738              : /* string = '"' { quoted_printable_chars } '"' */
     739            0 : static int parse_string(struct frozen *f) {
     740            0 :   int n, ch = 0, len = 0;
     741            0 :   TRY(test_and_skip(f, '"'));
     742            0 :   TRY(capture_ptr(f, f->cur, JSON_TYPE_STRING));
     743            0 :   for (; f->cur < f->end; f->cur += len) {
     744            0 :     ch = *(unsigned char *) f->cur;
     745            0 :     len = get_utf8_char_len((unsigned char) ch);
     746            0 :     EXPECT(ch >= 32 && len > 0, JSON_STRING_INVALID); /* No control chars */
     747            0 :     EXPECT(len < left(f), JSON_STRING_INCOMPLETE);
     748            0 :     if (ch == '\\') {
     749            0 :       EXPECT((n = get_escape_len(f->cur + 1, left(f))) > 0, n);
     750            0 :       len += n;
     751            0 :     } else if (ch == '"') {
     752            0 :       capture_len(f, f->num_tokens - 1, f->cur);
     753            0 :       f->cur++;
     754            0 :       break;
     755              :     };
     756              :   }
     757            0 :   return ch == '"' ? 0 : JSON_STRING_INCOMPLETE;
     758              : }
     759              : 
     760              : /* number = [ '-' ] digit+ [ '.' digit+ ] [ ['e'|'E'] ['+'|'-'] digit+ ] */
     761            0 : static int parse_number(struct frozen *f) {
     762            0 :   int ch = cur(f);
     763            0 :   TRY(capture_ptr(f, f->cur, JSON_TYPE_NUMBER));
     764            0 :   if (ch == '-') f->cur++;
     765            0 :   EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
     766            0 :   EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
     767            0 :   while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
     768            0 :   if (f->cur < f->end && f->cur[0] == '.') {
     769            0 :     f->cur++;
     770            0 :     EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
     771            0 :     EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
     772            0 :     while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
     773              :   }
     774            0 :   if (f->cur < f->end && (f->cur[0] == 'e' || f->cur[0] == 'E')) {
     775            0 :     f->cur++;
     776            0 :     EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
     777            0 :     if ((f->cur[0] == '+' || f->cur[0] == '-')) f->cur++;
     778            0 :     EXPECT(f->cur < f->end, JSON_STRING_INCOMPLETE);
     779            0 :     EXPECT(is_digit(f->cur[0]), JSON_STRING_INVALID);
     780            0 :     while (f->cur < f->end && is_digit(f->cur[0])) f->cur++;
     781              :   }
     782            0 :   capture_len(f, f->num_tokens - 1, f->cur);
     783            0 :   return 0;
     784              : }
     785              : 
     786              : /* array = '[' [ value { ',' value } ] ']' */
     787            0 : static int parse_array(struct frozen *f) {
     788              :   int ind;
     789            0 :   TRY(test_and_skip(f, '['));
     790            0 :   TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_ARRAY));
     791            0 :   ind = f->num_tokens - 1;
     792            0 :   while (cur(f) != ']') {
     793            0 :     TRY(parse_value(f));
     794            0 :     if (cur(f) == ',') f->cur++;
     795              :   }
     796            0 :   TRY(test_and_skip(f, ']'));
     797            0 :   capture_len(f, ind, f->cur);
     798            0 :   return 0;
     799              : }
     800              : 
     801            0 : static int compare(const char *s, const char *str, int len) {
     802            0 :   int i = 0;
     803            0 :   while (i < len && s[i] == str[i]) i++;
     804            0 :   return i == len ? 1 : 0;
     805              : }
     806              : 
     807            0 : static int expect(struct frozen *f, const char *s, int len, enum json_type t) {
     808            0 :   int i, n = left(f);
     809              : 
     810            0 :   TRY(capture_ptr(f, f->cur, t));
     811            0 :   for (i = 0; i < len; i++) {
     812            0 :     if (i >= n) return JSON_STRING_INCOMPLETE;
     813            0 :     if (f->cur[i] != s[i]) return JSON_STRING_INVALID;
     814              :   }
     815            0 :   f->cur += len;
     816            0 :   TRY(capture_len(f, f->num_tokens - 1, f->cur));
     817              : 
     818            0 :   return 0;
     819              : }
     820              : 
     821              : /* value = 'null' | 'true' | 'false' | number | string | array | object */
     822            0 : static int parse_value(struct frozen *f) {
     823            0 :   int ch = cur(f);
     824              : 
     825            0 :   switch (ch) {
     826            0 :     case '"':
     827            0 :       TRY(parse_string(f));
     828            0 :       break;
     829            0 :     case '{':
     830            0 :       TRY(parse_object(f));
     831            0 :       break;
     832            0 :     case '[':
     833            0 :       TRY(parse_array(f));
     834            0 :       break;
     835            0 :     case 'n':
     836            0 :       TRY(expect(f, "null", 4, JSON_TYPE_NULL));
     837            0 :       break;
     838            0 :     case 't':
     839            0 :       TRY(expect(f, "true", 4, JSON_TYPE_TRUE));
     840            0 :       break;
     841            0 :     case 'f':
     842            0 :       TRY(expect(f, "false", 5, JSON_TYPE_FALSE));
     843            0 :       break;
     844            0 :     case '-':
     845              :     case '0':
     846              :     case '1':
     847              :     case '2':
     848              :     case '3':
     849              :     case '4':
     850              :     case '5':
     851              :     case '6':
     852              :     case '7':
     853              :     case '8':
     854              :     case '9':
     855            0 :       TRY(parse_number(f));
     856            0 :       break;
     857            0 :     default:
     858            0 :       return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
     859              :   }
     860              : 
     861            0 :   return 0;
     862              : }
     863              : 
     864              : /* key = identifier | string */
     865            0 : static int parse_key(struct frozen *f) {
     866            0 :   int ch = cur(f);
     867              : #if 0
     868              :   printf("%s 1 [%.*s]\n", __func__, (int) (f->end - f->cur), f->cur);
     869              : #endif
     870            0 :   if (is_alpha(ch)) {
     871            0 :     TRY(parse_identifier(f));
     872            0 :   } else if (ch == '"') {
     873            0 :     TRY(parse_string(f));
     874              :   } else {
     875            0 :     return ch == END_OF_STRING ? JSON_STRING_INCOMPLETE : JSON_STRING_INVALID;
     876              :   }
     877            0 :   return 0;
     878              : }
     879              : 
     880              : /* pair = key ':' value */
     881            0 : static int parse_pair(struct frozen *f) {
     882            0 :   TRY(parse_key(f));
     883            0 :   TRY(test_and_skip(f, ':'));
     884            0 :   TRY(parse_value(f));
     885            0 :   return 0;
     886              : }
     887              : 
     888              : /* object = '{' pair { ',' pair } '}' */
     889            0 : static int parse_object(struct frozen *f) {
     890              :   int ind;
     891            0 :   TRY(test_and_skip(f, '{'));
     892            0 :   TRY(capture_ptr(f, f->cur - 1, JSON_TYPE_OBJECT));
     893            0 :   ind = f->num_tokens - 1;
     894            0 :   while (cur(f) != '}') {
     895            0 :     TRY(parse_pair(f));
     896            0 :     if (cur(f) == ',') f->cur++;
     897              :   }
     898            0 :   TRY(test_and_skip(f, '}'));
     899            0 :   capture_len(f, ind, f->cur);
     900            0 :   return 0;
     901              : }
     902              : 
     903            0 : static int doit(struct frozen *f) {
     904            0 :   int ret = 0;
     905              : 
     906            0 :   if (f->cur == 0 || f->end < f->cur) return JSON_STRING_INVALID;
     907            0 :   if (f->end == f->cur) return JSON_STRING_INCOMPLETE;
     908              : 
     909            0 :   if (0 == (ret = test_no_skip(f, '{'))) {
     910            0 :     TRY(parse_object(f));
     911            0 :   } else if (0 == (ret = test_no_skip(f, '['))) {
     912            0 :     TRY(parse_array(f));
     913              :   } else {
     914            0 :     return ret;
     915              :   }
     916              : 
     917            0 :   TRY(capture_ptr(f, f->cur, JSON_TYPE_EOF));
     918            0 :   capture_len(f, f->num_tokens, f->cur);
     919            0 :   return 0;
     920              : }
     921              : 
     922              : /* json = object */
     923            0 : int parse_json(const char *s, int s_len, struct json_token *arr, int arr_len) {
     924              :   struct frozen frozen;
     925              : 
     926            0 :   memset(&frozen, 0, sizeof(frozen));
     927            0 :   frozen.end = s + s_len;
     928            0 :   frozen.cur = s;
     929            0 :   frozen.tokens = arr;
     930            0 :   frozen.max_tokens = arr_len;
     931              : 
     932            0 :   TRY(doit(&frozen));
     933              : 
     934            0 :   return frozen.cur - s;
     935              : }
     936              : 
     937            0 : struct json_token *parse_json2(const char *s, int s_len) {
     938              :   struct frozen frozen;
     939              : 
     940            0 :   memset(&frozen, 0, sizeof(frozen));
     941            0 :   frozen.end = s + s_len;
     942            0 :   frozen.cur = s;
     943            0 :   frozen.do_realloc = 1;
     944              : 
     945            0 :   if (doit(&frozen) < 0) {
     946            0 :     FROZEN_FREE((void *) frozen.tokens);
     947            0 :     frozen.tokens = NULL;
     948              :   }
     949            0 :   return frozen.tokens;
     950              : }
     951              : 
     952            0 : static int path_part_len(const char *p) {
     953            0 :   int i = 0;
     954            0 :   while (p[i] != '\0' && p[i] != '[' && p[i] != '.') i++;
     955            0 :   return i;
     956              : }
     957              : 
     958            0 : struct json_token *find_json_token(struct json_token *toks, const char *path) {
     959            0 :   while (path != 0 && path[0] != '\0') {
     960            0 :     int i, ind2 = 0, ind = -1, skip = 2, n = path_part_len(path);
     961            0 :     if (path[0] == '[') {
     962            0 :       if (toks->type != JSON_TYPE_ARRAY || !is_digit(path[1])) return 0;
     963            0 :       for (ind = 0, n = 1; path[n] != ']' && path[n] != '\0'; n++) {
     964            0 :         if (!is_digit(path[n])) return 0;
     965            0 :         ind *= 10;
     966            0 :         ind += path[n] - '0';
     967              :       }
     968            0 :       if (path[n++] != ']') return 0;
     969            0 :       skip = 1; /* In objects, we skip 2 elems while iterating, in arrays 1. */
     970            0 :     } else if (toks->type != JSON_TYPE_OBJECT)
     971            0 :       return 0;
     972            0 :     toks++;
     973            0 :     for (i = 0; i < toks[-1].num_desc; i += skip, ind2++) {
     974              :       /* ind == -1 indicated that we're iterating an array, not object */
     975            0 :       if (ind == -1 && toks[i].type != JSON_TYPE_STRING) return 0;
     976            0 :       if (ind2 == ind ||
     977            0 :           (ind == -1 && toks[i].len == n && compare(path, toks[i].ptr, n))) {
     978            0 :         i += skip - 1;
     979            0 :         break;
     980              :       };
     981            0 :       if (toks[i - 1 + skip].type == JSON_TYPE_ARRAY ||
     982            0 :           toks[i - 1 + skip].type == JSON_TYPE_OBJECT) {
     983            0 :         i += toks[i - 1 + skip].num_desc;
     984              :       }
     985              :     }
     986            0 :     if (i == toks[-1].num_desc) return 0;
     987            0 :     path += n;
     988            0 :     if (path[0] == '.') path++;
     989            0 :     if (path[0] == '\0') return &toks[i];
     990            0 :     toks += i;
     991              :   }
     992            0 :   return 0;
     993              : }
     994              : 
     995            0 : int json_emit_long(char *buf, int buf_len, long int value) {
     996              :   char tmp[20];
     997            0 :   int n = snprintf(tmp, sizeof(tmp), "%ld", value);
     998            0 :   strncpy(buf, tmp, buf_len > 0 ? buf_len : 0);
     999            0 :   return n;
    1000              : }
    1001              : 
    1002            0 : int json_emit_double(char *buf, int buf_len, double value) {
    1003              :   char tmp[20];
    1004            0 :   int n = snprintf(tmp, sizeof(tmp), "%g", value);
    1005            0 :   strncpy(buf, tmp, buf_len > 0 ? buf_len : 0);
    1006            0 :   return n;
    1007              : }
    1008              : 
    1009            0 : int json_emit_quoted_str(char *s, int s_len, const char *str, int len) {
    1010            0 :   const char *begin = s, *end = s + s_len, *str_end = str + len;
    1011              :   char ch;
    1012              : 
    1013              : #define EMIT(x)          \
    1014              :   do {                   \
    1015              :     if (s < end) *s = x; \
    1016              :     s++;                 \
    1017              :   } while (0)
    1018              : 
    1019            0 :   EMIT('"');
    1020            0 :   while (str < str_end) {
    1021            0 :     ch = *str++;
    1022            0 :     switch (ch) {
    1023            0 :       case '"':
    1024            0 :         EMIT('\\');
    1025            0 :         EMIT('"');
    1026            0 :         break;
    1027            0 :       case '\\':
    1028            0 :         EMIT('\\');
    1029            0 :         EMIT('\\');
    1030            0 :         break;
    1031            0 :       case '\b':
    1032            0 :         EMIT('\\');
    1033            0 :         EMIT('b');
    1034            0 :         break;
    1035            0 :       case '\f':
    1036            0 :         EMIT('\\');
    1037            0 :         EMIT('f');
    1038            0 :         break;
    1039            0 :       case '\n':
    1040            0 :         EMIT('\\');
    1041            0 :         EMIT('n');
    1042            0 :         break;
    1043            0 :       case '\r':
    1044            0 :         EMIT('\\');
    1045            0 :         EMIT('r');
    1046            0 :         break;
    1047            0 :       case '\t':
    1048            0 :         EMIT('\\');
    1049            0 :         EMIT('t');
    1050            0 :         break;
    1051            0 :       default:
    1052            0 :         EMIT(ch);
    1053              :     }
    1054              :   }
    1055            0 :   EMIT('"');
    1056            0 :   if (s < end) {
    1057            0 :     *s = '\0';
    1058              :   }
    1059              : 
    1060            0 :   return s - begin;
    1061              : }
    1062              : 
    1063            0 : int json_emit_unquoted_str(char *buf, int buf_len, const char *str, int len) {
    1064            0 :   if (buf_len > 0 && len > 0) {
    1065            0 :     int n = len < buf_len ? len : buf_len;
    1066            0 :     memcpy(buf, str, n);
    1067            0 :     if (n < buf_len) {
    1068            0 :       buf[n] = '\0';
    1069              :     }
    1070              :   }
    1071            0 :   return len;
    1072              : }
    1073              : 
    1074            0 : int json_emit_va(char *s, int s_len, const char *fmt, va_list ap) {
    1075            0 :   const char *end = s + s_len, *str, *orig = s;
    1076              :   size_t len;
    1077              : 
    1078            0 :   while (*fmt != '\0') {
    1079            0 :     switch (*fmt) {
    1080            0 :       case '[':
    1081              :       case ']':
    1082              :       case '{':
    1083              :       case '}':
    1084              :       case ',':
    1085              :       case ':':
    1086              :       case ' ':
    1087              :       case '\r':
    1088              :       case '\n':
    1089              :       case '\t':
    1090            0 :         if (s < end) {
    1091            0 :           *s = *fmt;
    1092              :         }
    1093            0 :         s++;
    1094            0 :         break;
    1095            0 :       case 'i':
    1096            0 :         s += json_emit_long(s, end - s, va_arg(ap, long) );
    1097            0 :         break;
    1098            0 :       case 'f':
    1099            0 :         s += json_emit_double(s, end - s, va_arg(ap, double) );
    1100            0 :         break;
    1101            0 :       case 'v':
    1102            0 :         str = va_arg(ap, char *);
    1103            0 :         len = va_arg(ap, size_t);
    1104            0 :         s += json_emit_quoted_str(s, end - s, str, len);
    1105            0 :         break;
    1106            0 :       case 'V':
    1107            0 :         str = va_arg(ap, char *);
    1108            0 :         len = va_arg(ap, size_t);
    1109            0 :         s += json_emit_unquoted_str(s, end - s, str, len);
    1110            0 :         break;
    1111            0 :       case 's':
    1112            0 :         str = va_arg(ap, char *);
    1113            0 :         s += json_emit_quoted_str(s, end - s, str, strlen(str));
    1114            0 :         break;
    1115            0 :       case 'S':
    1116            0 :         str = va_arg(ap, char *);
    1117            0 :         s += json_emit_unquoted_str(s, end - s, str, strlen(str));
    1118            0 :         break;
    1119            0 :       case 'T':
    1120            0 :         s += json_emit_unquoted_str(s, end - s, "true", 4);
    1121            0 :         break;
    1122            0 :       case 'F':
    1123            0 :         s += json_emit_unquoted_str(s, end - s, "false", 5);
    1124            0 :         break;
    1125            0 :       case 'N':
    1126            0 :         s += json_emit_unquoted_str(s, end - s, "null", 4);
    1127            0 :         break;
    1128            0 :       default:
    1129            0 :         return 0;
    1130              :     }
    1131            0 :     fmt++;
    1132              :   }
    1133              : 
    1134              :   /* Best-effort to 0-terminate generated string */
    1135            0 :   if (s < end) {
    1136            0 :     *s = '\0';
    1137              :   }
    1138              : 
    1139            0 :   return s - orig;
    1140              : }
    1141              : 
    1142            0 : int json_emit(char *buf, int buf_len, const char *fmt, ...) {
    1143              :   int len;
    1144              :   va_list ap;
    1145              : 
    1146            0 :   va_start(ap, fmt);
    1147            0 :   len = json_emit_va(buf, buf_len, fmt, ap);
    1148            0 :   va_end(ap);
    1149              : 
    1150            0 :   return len;
    1151              : }
    1152              : #ifdef MG_MODULE_LINES
    1153              : #line 1 "./src/../../common/md5.c"
    1154              : #endif
    1155              : /*
    1156              :  * This code implements the MD5 message-digest algorithm.
    1157              :  * The algorithm is due to Ron Rivest.  This code was
    1158              :  * written by Colin Plumb in 1993, no copyright is claimed.
    1159              :  * This code is in the public domain; do with it what you wish.
    1160              :  *
    1161              :  * Equivalent code is available from RSA Data Security, Inc.
    1162              :  * This code has been tested against that, and is equivalent,
    1163              :  * except that you don't need to include two pages of legalese
    1164              :  * with every copy.
    1165              :  *
    1166              :  * To compute the message digest of a chunk of bytes, declare an
    1167              :  * MD5Context structure, pass it to MD5Init, call MD5Update as
    1168              :  * needed on buffers full of bytes, and then call MD5Final, which
    1169              :  * will fill a supplied 16-byte array with the digest.
    1170              :  */
    1171              : 
    1172              : #if !defined(DISABLE_MD5) && !defined(EXCLUDE_COMMON)
    1173              : 
    1174              : /* Amalgamated: #include "common/md5.h" */
    1175              : 
    1176              : #ifndef CS_ENABLE_NATIVE_MD5
    1177            0 : static void byteReverse(unsigned char *buf, unsigned longs) {
    1178              : /* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
    1179              : #if BYTE_ORDER == BIG_ENDIAN
    1180              :   do {
    1181              :     uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
    1182              :                  ((unsigned) buf[1] << 8 | buf[0]);
    1183              :     *(uint32_t *) buf = t;
    1184              :     buf += 4;
    1185              :   } while (--longs);
    1186              : #else
    1187              :   (void) buf;
    1188              :   (void) longs;
    1189              : #endif
    1190            0 : }
    1191              : 
    1192              : #define F1(x, y, z) (z ^ (x & (y ^ z)))
    1193              : #define F2(x, y, z) F1(z, x, y)
    1194              : #define F3(x, y, z) (x ^ y ^ z)
    1195              : #define F4(x, y, z) (y ^ (x | ~z))
    1196              : 
    1197              : #define MD5STEP(f, w, x, y, z, data, s) \
    1198              :   (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
    1199              : 
    1200              : /*
    1201              :  * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
    1202              :  * initialization constants.
    1203              :  */
    1204            0 : void MD5_Init(MD5_CTX *ctx) {
    1205            0 :   ctx->buf[0] = 0x67452301;
    1206            0 :   ctx->buf[1] = 0xefcdab89;
    1207            0 :   ctx->buf[2] = 0x98badcfe;
    1208            0 :   ctx->buf[3] = 0x10325476;
    1209              : 
    1210            0 :   ctx->bits[0] = 0;
    1211            0 :   ctx->bits[1] = 0;
    1212            0 : }
    1213              : 
    1214            0 : static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
    1215              :   uint32_t a, b, c, d;
    1216              : 
    1217            0 :   a = buf[0];
    1218            0 :   b = buf[1];
    1219            0 :   c = buf[2];
    1220            0 :   d = buf[3];
    1221              : 
    1222            0 :   MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
    1223            0 :   MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
    1224            0 :   MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
    1225            0 :   MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
    1226            0 :   MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
    1227            0 :   MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
    1228            0 :   MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
    1229            0 :   MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
    1230            0 :   MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
    1231            0 :   MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
    1232            0 :   MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
    1233            0 :   MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
    1234            0 :   MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
    1235            0 :   MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
    1236            0 :   MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
    1237            0 :   MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
    1238              : 
    1239            0 :   MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
    1240            0 :   MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
    1241            0 :   MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
    1242            0 :   MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
    1243            0 :   MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
    1244            0 :   MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
    1245            0 :   MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
    1246            0 :   MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
    1247            0 :   MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
    1248            0 :   MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
    1249            0 :   MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
    1250            0 :   MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
    1251            0 :   MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
    1252            0 :   MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
    1253            0 :   MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
    1254            0 :   MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
    1255              : 
    1256            0 :   MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
    1257            0 :   MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
    1258            0 :   MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
    1259            0 :   MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
    1260            0 :   MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
    1261            0 :   MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
    1262            0 :   MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
    1263            0 :   MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
    1264            0 :   MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
    1265            0 :   MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
    1266            0 :   MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
    1267            0 :   MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
    1268            0 :   MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
    1269            0 :   MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
    1270            0 :   MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
    1271            0 :   MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
    1272              : 
    1273            0 :   MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
    1274            0 :   MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
    1275            0 :   MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
    1276            0 :   MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
    1277            0 :   MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
    1278            0 :   MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
    1279            0 :   MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
    1280            0 :   MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
    1281            0 :   MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
    1282            0 :   MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
    1283            0 :   MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
    1284            0 :   MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
    1285            0 :   MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
    1286            0 :   MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
    1287            0 :   MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
    1288            0 :   MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
    1289              : 
    1290            0 :   buf[0] += a;
    1291            0 :   buf[1] += b;
    1292            0 :   buf[2] += c;
    1293            0 :   buf[3] += d;
    1294            0 : }
    1295              : 
    1296            0 : void MD5_Update(MD5_CTX *ctx, const unsigned char *buf, size_t len) {
    1297              :   uint32_t t;
    1298              : 
    1299            0 :   t = ctx->bits[0];
    1300            0 :   if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
    1301            0 :   ctx->bits[1] += (uint32_t) len >> 29;
    1302              : 
    1303            0 :   t = (t >> 3) & 0x3f;
    1304              : 
    1305            0 :   if (t) {
    1306            0 :     unsigned char *p = (unsigned char *) ctx->in + t;
    1307              : 
    1308            0 :     t = 64 - t;
    1309            0 :     if (len < t) {
    1310            0 :       memcpy(p, buf, len);
    1311            0 :       return;
    1312              :     }
    1313            0 :     memcpy(p, buf, t);
    1314            0 :     byteReverse(ctx->in, 16);
    1315            0 :     MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    1316            0 :     buf += t;
    1317            0 :     len -= t;
    1318              :   }
    1319              : 
    1320            0 :   while (len >= 64) {
    1321            0 :     memcpy(ctx->in, buf, 64);
    1322            0 :     byteReverse(ctx->in, 16);
    1323            0 :     MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    1324            0 :     buf += 64;
    1325            0 :     len -= 64;
    1326              :   }
    1327              : 
    1328            0 :   memcpy(ctx->in, buf, len);
    1329              : }
    1330              : 
    1331            0 : void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) {
    1332              :   unsigned count;
    1333              :   unsigned char *p;
    1334              :   uint32_t *a;
    1335              : 
    1336            0 :   count = (ctx->bits[0] >> 3) & 0x3F;
    1337              : 
    1338            0 :   p = ctx->in + count;
    1339            0 :   *p++ = 0x80;
    1340            0 :   count = 64 - 1 - count;
    1341            0 :   if (count < 8) {
    1342            0 :     memset(p, 0, count);
    1343            0 :     byteReverse(ctx->in, 16);
    1344            0 :     MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    1345            0 :     memset(ctx->in, 0, 56);
    1346              :   } else {
    1347            0 :     memset(p, 0, count - 8);
    1348              :   }
    1349            0 :   byteReverse(ctx->in, 14);
    1350              : 
    1351            0 :   a = (uint32_t *) ctx->in;
    1352            0 :   a[14] = ctx->bits[0];
    1353            0 :   a[15] = ctx->bits[1];
    1354              : 
    1355            0 :   MD5Transform(ctx->buf, (uint32_t *) ctx->in);
    1356            0 :   byteReverse((unsigned char *) ctx->buf, 4);
    1357            0 :   memcpy(digest, ctx->buf, 16);
    1358            0 :   memset((char *) ctx, 0, sizeof(*ctx));
    1359            0 : }
    1360              : #endif /* CS_ENABLE_NATIVE_MD5 */
    1361              : 
    1362              : /*
    1363              :  * Stringify binary data. Output buffer size must be 2 * size_of_input + 1
    1364              :  * because each byte of input takes 2 bytes in string representation
    1365              :  * plus 1 byte for the terminating \0 character.
    1366              :  */
    1367            0 : void cs_to_hex(char *to, const unsigned char *p, size_t len) {
    1368              :   static const char *hex = "0123456789abcdef";
    1369              : 
    1370            0 :   for (; len--; p++) {
    1371            0 :     *to++ = hex[p[0] >> 4];
    1372            0 :     *to++ = hex[p[0] & 0x0f];
    1373              :   }
    1374            0 :   *to = '\0';
    1375            0 : }
    1376              : 
    1377            0 : char *cs_md5(char buf[33], ...) {
    1378              :   unsigned char hash[16];
    1379              :   const unsigned char *p;
    1380              :   va_list ap;
    1381              :   MD5_CTX ctx;
    1382              : 
    1383            0 :   MD5_Init(&ctx);
    1384              : 
    1385            0 :   va_start(ap, buf);
    1386            0 :   while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
    1387            0 :     size_t len = va_arg(ap, size_t);
    1388            0 :     MD5_Update(&ctx, p, len);
    1389              :   }
    1390            0 :   va_end(ap);
    1391              : 
    1392            0 :   MD5_Final(hash, &ctx);
    1393            0 :   cs_to_hex(buf, hash, sizeof(hash));
    1394              : 
    1395            0 :   return buf;
    1396              : }
    1397              : 
    1398              : #endif /* EXCLUDE_COMMON */
    1399              : #ifdef MG_MODULE_LINES
    1400              : #line 1 "./src/../../common/mbuf.c"
    1401              : #endif
    1402              : /*
    1403              :  * Copyright (c) 2014 Cesanta Software Limited
    1404              :  * All rights reserved
    1405              :  */
    1406              : 
    1407              : #ifndef EXCLUDE_COMMON
    1408              : 
    1409              : #include <assert.h>
    1410              : #include <string.h>
    1411              : /* Amalgamated: #include "common/mbuf.h" */
    1412              : 
    1413              : #ifndef MBUF_REALLOC
    1414              : #define MBUF_REALLOC realloc
    1415              : #endif
    1416              : 
    1417              : #ifndef MBUF_FREE
    1418              : #define MBUF_FREE free
    1419              : #endif
    1420              : 
    1421            0 : void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
    1422            0 :   mbuf->len = mbuf->size = 0;
    1423            0 :   mbuf->buf = NULL;
    1424            0 :   mbuf_resize(mbuf, initial_size);
    1425            0 : }
    1426              : 
    1427            0 : void mbuf_free(struct mbuf *mbuf) {
    1428            0 :   if (mbuf->buf != NULL) {
    1429            0 :     MBUF_FREE(mbuf->buf);
    1430            0 :     mbuf_init(mbuf, 0);
    1431              :   }
    1432            0 : }
    1433              : 
    1434            0 : void mbuf_resize(struct mbuf *a, size_t new_size) {
    1435            0 :   if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
    1436            0 :     char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
    1437              :     /*
    1438              :      * In case realloc fails, there's not much we can do, except keep things as
    1439              :      * they are. Note that NULL is a valid return value from realloc when
    1440              :      * size == 0, but that is covered too.
    1441              :      */
    1442            0 :     if (buf == NULL && new_size != 0) return;
    1443            0 :     a->buf = buf;
    1444            0 :     a->size = new_size;
    1445              :   }
    1446              : }
    1447              : 
    1448            0 : void mbuf_trim(struct mbuf *mbuf) {
    1449            0 :   mbuf_resize(mbuf, mbuf->len);
    1450            0 : }
    1451              : 
    1452            0 : size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
    1453            0 :   char *p = NULL;
    1454              : 
    1455            0 :   assert(a != NULL);
    1456            0 :   assert(a->len <= a->size);
    1457            0 :   assert(off <= a->len);
    1458              : 
    1459              :   /* check overflow */
    1460            0 :   if (~(size_t) 0 - (size_t) a->buf < len) return 0;
    1461              : 
    1462            0 :   if (a->len + len <= a->size) {
    1463            0 :     memmove(a->buf + off + len, a->buf + off, a->len - off);
    1464            0 :     if (buf != NULL) {
    1465            0 :       memcpy(a->buf + off, buf, len);
    1466              :     }
    1467            0 :     a->len += len;
    1468              :   } else {
    1469            0 :     size_t new_size = (a->len + len) * MBUF_SIZE_MULTIPLIER;
    1470            0 :     if ((p = (char *) MBUF_REALLOC(a->buf, new_size)) != NULL) {
    1471            0 :       a->buf = p;
    1472            0 :       memmove(a->buf + off + len, a->buf + off, a->len - off);
    1473            0 :       if (buf != NULL) memcpy(a->buf + off, buf, len);
    1474            0 :       a->len += len;
    1475            0 :       a->size = new_size;
    1476              :     } else {
    1477            0 :       len = 0;
    1478              :     }
    1479              :   }
    1480              : 
    1481            0 :   return len;
    1482              : }
    1483              : 
    1484            0 : size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
    1485            0 :   return mbuf_insert(a, a->len, buf, len);
    1486              : }
    1487              : 
    1488            0 : void mbuf_remove(struct mbuf *mb, size_t n) {
    1489            0 :   if (n > 0 && n <= mb->len) {
    1490            0 :     memmove(mb->buf, mb->buf + n, mb->len - n);
    1491            0 :     mb->len -= n;
    1492              :   }
    1493            0 : }
    1494              : 
    1495              : #endif /* EXCLUDE_COMMON */
    1496              : #ifdef MG_MODULE_LINES
    1497              : #line 1 "./src/../../common/sha1.c"
    1498              : #endif
    1499              : /* Copyright(c) By Steve Reid <steve@edmweb.com> */
    1500              : /* 100% Public Domain */
    1501              : 
    1502              : #if !defined(DISABLE_SHA1) && !defined(EXCLUDE_COMMON)
    1503              : 
    1504              : /* Amalgamated: #include "common/sha1.h" */
    1505              : 
    1506              : #define SHA1HANDSOFF
    1507              : #if defined(__sun)
    1508              : /* Amalgamated: #include "common/solarisfixes.h" */
    1509              : #endif
    1510              : 
    1511              : union char64long16 {
    1512              :   unsigned char c[64];
    1513              :   uint32_t l[16];
    1514              : };
    1515              : 
    1516              : #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
    1517              : 
    1518            0 : static uint32_t blk0(union char64long16 *block, int i) {
    1519              : /* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
    1520              : #if BYTE_ORDER == LITTLE_ENDIAN
    1521            0 :   block->l[i] =
    1522            0 :       (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
    1523              : #endif
    1524            0 :   return block->l[i];
    1525              : }
    1526              : 
    1527              : /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
    1528              : #undef blk
    1529              : #undef R0
    1530              : #undef R1
    1531              : #undef R2
    1532              : #undef R3
    1533              : #undef R4
    1534              : 
    1535              : #define blk(i)                                                               \
    1536              :   (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
    1537              :                               block->l[(i + 2) & 15] ^ block->l[i & 15],     \
    1538              :                           1))
    1539              : #define R0(v, w, x, y, z, i)                                          \
    1540              :   z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
    1541              :   w = rol(w, 30);
    1542              : #define R1(v, w, x, y, z, i)                                  \
    1543              :   z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
    1544              :   w = rol(w, 30);
    1545              : #define R2(v, w, x, y, z, i)                          \
    1546              :   z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
    1547              :   w = rol(w, 30);
    1548              : #define R3(v, w, x, y, z, i)                                        \
    1549              :   z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
    1550              :   w = rol(w, 30);
    1551              : #define R4(v, w, x, y, z, i)                          \
    1552              :   z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
    1553              :   w = rol(w, 30);
    1554              : 
    1555            0 : void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
    1556              :   uint32_t a, b, c, d, e;
    1557              :   union char64long16 block[1];
    1558              : 
    1559            0 :   memcpy(block, buffer, 64);
    1560            0 :   a = state[0];
    1561            0 :   b = state[1];
    1562            0 :   c = state[2];
    1563            0 :   d = state[3];
    1564            0 :   e = state[4];
    1565            0 :   R0(a, b, c, d, e, 0);
    1566            0 :   R0(e, a, b, c, d, 1);
    1567            0 :   R0(d, e, a, b, c, 2);
    1568            0 :   R0(c, d, e, a, b, 3);
    1569            0 :   R0(b, c, d, e, a, 4);
    1570            0 :   R0(a, b, c, d, e, 5);
    1571            0 :   R0(e, a, b, c, d, 6);
    1572            0 :   R0(d, e, a, b, c, 7);
    1573            0 :   R0(c, d, e, a, b, 8);
    1574            0 :   R0(b, c, d, e, a, 9);
    1575            0 :   R0(a, b, c, d, e, 10);
    1576            0 :   R0(e, a, b, c, d, 11);
    1577            0 :   R0(d, e, a, b, c, 12);
    1578            0 :   R0(c, d, e, a, b, 13);
    1579            0 :   R0(b, c, d, e, a, 14);
    1580            0 :   R0(a, b, c, d, e, 15);
    1581            0 :   R1(e, a, b, c, d, 16);
    1582            0 :   R1(d, e, a, b, c, 17);
    1583            0 :   R1(c, d, e, a, b, 18);
    1584            0 :   R1(b, c, d, e, a, 19);
    1585            0 :   R2(a, b, c, d, e, 20);
    1586            0 :   R2(e, a, b, c, d, 21);
    1587            0 :   R2(d, e, a, b, c, 22);
    1588            0 :   R2(c, d, e, a, b, 23);
    1589            0 :   R2(b, c, d, e, a, 24);
    1590            0 :   R2(a, b, c, d, e, 25);
    1591            0 :   R2(e, a, b, c, d, 26);
    1592            0 :   R2(d, e, a, b, c, 27);
    1593            0 :   R2(c, d, e, a, b, 28);
    1594            0 :   R2(b, c, d, e, a, 29);
    1595            0 :   R2(a, b, c, d, e, 30);
    1596            0 :   R2(e, a, b, c, d, 31);
    1597            0 :   R2(d, e, a, b, c, 32);
    1598            0 :   R2(c, d, e, a, b, 33);
    1599            0 :   R2(b, c, d, e, a, 34);
    1600            0 :   R2(a, b, c, d, e, 35);
    1601            0 :   R2(e, a, b, c, d, 36);
    1602            0 :   R2(d, e, a, b, c, 37);
    1603            0 :   R2(c, d, e, a, b, 38);
    1604            0 :   R2(b, c, d, e, a, 39);
    1605            0 :   R3(a, b, c, d, e, 40);
    1606            0 :   R3(e, a, b, c, d, 41);
    1607            0 :   R3(d, e, a, b, c, 42);
    1608            0 :   R3(c, d, e, a, b, 43);
    1609            0 :   R3(b, c, d, e, a, 44);
    1610            0 :   R3(a, b, c, d, e, 45);
    1611            0 :   R3(e, a, b, c, d, 46);
    1612            0 :   R3(d, e, a, b, c, 47);
    1613            0 :   R3(c, d, e, a, b, 48);
    1614            0 :   R3(b, c, d, e, a, 49);
    1615            0 :   R3(a, b, c, d, e, 50);
    1616            0 :   R3(e, a, b, c, d, 51);
    1617            0 :   R3(d, e, a, b, c, 52);
    1618            0 :   R3(c, d, e, a, b, 53);
    1619            0 :   R3(b, c, d, e, a, 54);
    1620            0 :   R3(a, b, c, d, e, 55);
    1621            0 :   R3(e, a, b, c, d, 56);
    1622            0 :   R3(d, e, a, b, c, 57);
    1623            0 :   R3(c, d, e, a, b, 58);
    1624            0 :   R3(b, c, d, e, a, 59);
    1625            0 :   R4(a, b, c, d, e, 60);
    1626            0 :   R4(e, a, b, c, d, 61);
    1627            0 :   R4(d, e, a, b, c, 62);
    1628            0 :   R4(c, d, e, a, b, 63);
    1629            0 :   R4(b, c, d, e, a, 64);
    1630            0 :   R4(a, b, c, d, e, 65);
    1631            0 :   R4(e, a, b, c, d, 66);
    1632            0 :   R4(d, e, a, b, c, 67);
    1633            0 :   R4(c, d, e, a, b, 68);
    1634            0 :   R4(b, c, d, e, a, 69);
    1635            0 :   R4(a, b, c, d, e, 70);
    1636            0 :   R4(e, a, b, c, d, 71);
    1637            0 :   R4(d, e, a, b, c, 72);
    1638            0 :   R4(c, d, e, a, b, 73);
    1639            0 :   R4(b, c, d, e, a, 74);
    1640            0 :   R4(a, b, c, d, e, 75);
    1641            0 :   R4(e, a, b, c, d, 76);
    1642            0 :   R4(d, e, a, b, c, 77);
    1643            0 :   R4(c, d, e, a, b, 78);
    1644            0 :   R4(b, c, d, e, a, 79);
    1645            0 :   state[0] += a;
    1646            0 :   state[1] += b;
    1647            0 :   state[2] += c;
    1648            0 :   state[3] += d;
    1649            0 :   state[4] += e;
    1650              :   /* Erase working structures. The order of operations is important,
    1651              :    * used to ensure that compiler doesn't optimize those out. */
    1652            0 :   memset(block, 0, sizeof(block));
    1653            0 :   a = b = c = d = e = 0;
    1654              :   (void) a;
    1655              :   (void) b;
    1656              :   (void) c;
    1657              :   (void) d;
    1658              :   (void) e;
    1659            0 : }
    1660              : 
    1661            0 : void cs_sha1_init(cs_sha1_ctx *context) {
    1662            0 :   context->state[0] = 0x67452301;
    1663            0 :   context->state[1] = 0xEFCDAB89;
    1664            0 :   context->state[2] = 0x98BADCFE;
    1665            0 :   context->state[3] = 0x10325476;
    1666            0 :   context->state[4] = 0xC3D2E1F0;
    1667            0 :   context->count[0] = context->count[1] = 0;
    1668            0 : }
    1669              : 
    1670            0 : void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
    1671              :                     uint32_t len) {
    1672              :   uint32_t i, j;
    1673              : 
    1674            0 :   j = context->count[0];
    1675            0 :   if ((context->count[0] += len << 3) < j) context->count[1]++;
    1676            0 :   context->count[1] += (len >> 29);
    1677            0 :   j = (j >> 3) & 63;
    1678            0 :   if ((j + len) > 63) {
    1679            0 :     memcpy(&context->buffer[j], data, (i = 64 - j));
    1680            0 :     cs_sha1_transform(context->state, context->buffer);
    1681            0 :     for (; i + 63 < len; i += 64) {
    1682            0 :       cs_sha1_transform(context->state, &data[i]);
    1683              :     }
    1684            0 :     j = 0;
    1685              :   } else
    1686            0 :     i = 0;
    1687            0 :   memcpy(&context->buffer[j], &data[i], len - i);
    1688            0 : }
    1689              : 
    1690            0 : void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
    1691              :   unsigned i;
    1692              :   unsigned char finalcount[8], c;
    1693              : 
    1694            0 :   for (i = 0; i < 8; i++) {
    1695            0 :     finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
    1696            0 :                                       ((3 - (i & 3)) * 8)) &
    1697              :                                      255);
    1698              :   }
    1699            0 :   c = 0200;
    1700            0 :   cs_sha1_update(context, &c, 1);
    1701            0 :   while ((context->count[0] & 504) != 448) {
    1702            0 :     c = 0000;
    1703            0 :     cs_sha1_update(context, &c, 1);
    1704              :   }
    1705            0 :   cs_sha1_update(context, finalcount, 8);
    1706            0 :   for (i = 0; i < 20; i++) {
    1707            0 :     digest[i] =
    1708            0 :         (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
    1709              :   }
    1710            0 :   memset(context, '\0', sizeof(*context));
    1711            0 :   memset(&finalcount, '\0', sizeof(finalcount));
    1712            0 : }
    1713              : 
    1714            0 : void cs_hmac_sha1(const unsigned char *key, size_t keylen,
    1715              :                   const unsigned char *data, size_t datalen,
    1716              :                   unsigned char out[20]) {
    1717              :   cs_sha1_ctx ctx;
    1718              :   unsigned char buf1[64], buf2[64], tmp_key[20], i;
    1719              : 
    1720            0 :   if (keylen > sizeof(buf1)) {
    1721            0 :     cs_sha1_init(&ctx);
    1722            0 :     cs_sha1_update(&ctx, key, keylen);
    1723            0 :     cs_sha1_final(tmp_key, &ctx);
    1724            0 :     key = tmp_key;
    1725            0 :     keylen = sizeof(tmp_key);
    1726              :   }
    1727              : 
    1728            0 :   memset(buf1, 0, sizeof(buf1));
    1729            0 :   memset(buf2, 0, sizeof(buf2));
    1730            0 :   memcpy(buf1, key, keylen);
    1731            0 :   memcpy(buf2, key, keylen);
    1732              : 
    1733            0 :   for (i = 0; i < sizeof(buf1); i++) {
    1734            0 :     buf1[i] ^= 0x36;
    1735            0 :     buf2[i] ^= 0x5c;
    1736              :   }
    1737              : 
    1738            0 :   cs_sha1_init(&ctx);
    1739            0 :   cs_sha1_update(&ctx, buf1, sizeof(buf1));
    1740            0 :   cs_sha1_update(&ctx, data, datalen);
    1741            0 :   cs_sha1_final(out, &ctx);
    1742              : 
    1743            0 :   cs_sha1_init(&ctx);
    1744            0 :   cs_sha1_update(&ctx, buf2, sizeof(buf2));
    1745            0 :   cs_sha1_update(&ctx, out, 20);
    1746            0 :   cs_sha1_final(out, &ctx);
    1747            0 : }
    1748              : 
    1749              : #endif /* EXCLUDE_COMMON */
    1750              : #ifdef MG_MODULE_LINES
    1751              : #line 1 "./src/../../common/str_util.c"
    1752              : #endif
    1753              : /*
    1754              :  * Copyright (c) 2015 Cesanta Software Limited
    1755              :  * All rights reserved
    1756              :  */
    1757              : 
    1758              : #ifndef EXCLUDE_COMMON
    1759              : 
    1760              : /* Amalgamated: #include "common/platform.h" */
    1761              : /* Amalgamated: #include "common/str_util.h" */
    1762              : 
    1763            0 : size_t c_strnlen(const char *s, size_t maxlen) {
    1764            0 :   size_t l = 0;
    1765            0 :   for (; l < maxlen && s[l] != '\0'; l++) {
    1766              :   }
    1767            0 :   return l;
    1768              : }
    1769              : 
    1770              : #define C_SNPRINTF_APPEND_CHAR(ch)       \
    1771              :   do {                                   \
    1772              :     if (i < (int) buf_size) buf[i] = ch; \
    1773              :     i++;                                 \
    1774              :   } while (0)
    1775              : 
    1776              : #define C_SNPRINTF_FLAG_ZERO 1
    1777              : 
    1778              : #ifdef C_DISABLE_BUILTIN_SNPRINTF
    1779              : int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
    1780              :   return vsnprintf(buf, buf_size, fmt, ap);
    1781              : }
    1782              : #else
    1783            0 : static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
    1784              :                   int field_width) {
    1785              :   char tmp[40];
    1786            0 :   int i = 0, k = 0, neg = 0;
    1787              : 
    1788            0 :   if (num < 0) {
    1789            0 :     neg++;
    1790            0 :     num = -num;
    1791              :   }
    1792              : 
    1793              :   /* Print into temporary buffer - in reverse order */
    1794              :   do {
    1795            0 :     int rem = num % base;
    1796            0 :     if (rem < 10) {
    1797            0 :       tmp[k++] = '0' + rem;
    1798              :     } else {
    1799            0 :       tmp[k++] = 'a' + (rem - 10);
    1800              :     }
    1801            0 :     num /= base;
    1802            0 :   } while (num > 0);
    1803              : 
    1804              :   /* Zero padding */
    1805            0 :   if (flags && C_SNPRINTF_FLAG_ZERO) {
    1806            0 :     while (k < field_width && k < (int) sizeof(tmp) - 1) {
    1807            0 :       tmp[k++] = '0';
    1808              :     }
    1809              :   }
    1810              : 
    1811              :   /* And sign */
    1812            0 :   if (neg) {
    1813            0 :     tmp[k++] = '-';
    1814              :   }
    1815              : 
    1816              :   /* Now output */
    1817            0 :   while (--k >= 0) {
    1818            0 :     C_SNPRINTF_APPEND_CHAR(tmp[k]);
    1819              :   }
    1820              : 
    1821            0 :   return i;
    1822              : }
    1823              : 
    1824            0 : int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
    1825            0 :   int ch, i = 0, len_mod, flags, precision, field_width;
    1826              : 
    1827            0 :   while ((ch = *fmt++) != '\0') {
    1828            0 :     if (ch != '%') {
    1829            0 :       C_SNPRINTF_APPEND_CHAR(ch);
    1830              :     } else {
    1831              :       /*
    1832              :        * Conversion specification:
    1833              :        *   zero or more flags (one of: # 0 - <space> + ')
    1834              :        *   an optional minimum  field  width (digits)
    1835              :        *   an  optional precision (. followed by digits, or *)
    1836              :        *   an optional length modifier (one of: hh h l ll L q j z t)
    1837              :        *   conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
    1838              :        */
    1839            0 :       flags = field_width = precision = len_mod = 0;
    1840              : 
    1841              :       /* Flags. only zero-pad flag is supported. */
    1842            0 :       if (*fmt == '0') {
    1843            0 :         flags |= C_SNPRINTF_FLAG_ZERO;
    1844              :       }
    1845              : 
    1846              :       /* Field width */
    1847            0 :       while (*fmt >= '0' && *fmt <= '9') {
    1848            0 :         field_width *= 10;
    1849            0 :         field_width += *fmt++ - '0';
    1850              :       }
    1851              :       /* Dynamic field width */
    1852            0 :       if (*fmt == '*') {
    1853            0 :         field_width = va_arg(ap, int);
    1854            0 :         fmt++;
    1855              :       }
    1856              : 
    1857              :       /* Precision */
    1858            0 :       if (*fmt == '.') {
    1859            0 :         fmt++;
    1860            0 :         if (*fmt == '*') {
    1861            0 :           precision = va_arg(ap, int);
    1862            0 :           fmt++;
    1863              :         } else {
    1864            0 :           while (*fmt >= '0' && *fmt <= '9') {
    1865            0 :             precision *= 10;
    1866            0 :             precision += *fmt++ - '0';
    1867              :           }
    1868              :         }
    1869              :       }
    1870              : 
    1871              :       /* Length modifier */
    1872            0 :       switch (*fmt) {
    1873            0 :         case 'h':
    1874              :         case 'l':
    1875              :         case 'L':
    1876              :         case 'I':
    1877              :         case 'q':
    1878              :         case 'j':
    1879              :         case 'z':
    1880              :         case 't':
    1881            0 :           len_mod = *fmt++;
    1882            0 :           if (*fmt == 'h') {
    1883            0 :             len_mod = 'H';
    1884            0 :             fmt++;
    1885              :           }
    1886            0 :           if (*fmt == 'l') {
    1887            0 :             len_mod = 'q';
    1888            0 :             fmt++;
    1889              :           }
    1890            0 :           break;
    1891              :       }
    1892              : 
    1893            0 :       ch = *fmt++;
    1894            0 :       if (ch == 's') {
    1895            0 :         const char *s = va_arg(ap, const char *); /* Always fetch parameter */
    1896              :         int j;
    1897            0 :         int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
    1898            0 :         for (j = 0; j < pad; j++) {
    1899            0 :           C_SNPRINTF_APPEND_CHAR(' ');
    1900              :         }
    1901              : 
    1902              :         /* `s` may be NULL in case of %.*s */
    1903            0 :         if (s != NULL) {
    1904              :           /* Ignore negative and 0 precisions */
    1905            0 :           for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
    1906            0 :             C_SNPRINTF_APPEND_CHAR(s[j]);
    1907              :           }
    1908              :         }
    1909            0 :       } else if (ch == 'c') {
    1910            0 :         ch = va_arg(ap, int); /* Always fetch parameter */
    1911            0 :         C_SNPRINTF_APPEND_CHAR(ch);
    1912            0 :       } else if (ch == 'd' && len_mod == 0) {
    1913            0 :         i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
    1914              :                     field_width);
    1915            0 :       } else if (ch == 'd' && len_mod == 'l') {
    1916            0 :         i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
    1917              :                     field_width);
    1918              : #ifdef SSIZE_MAX
    1919            0 :       } else if (ch == 'd' && len_mod == 'z') {
    1920            0 :         i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
    1921              :                     field_width);
    1922              : #endif
    1923            0 :       } else if (ch == 'd' && len_mod == 'q') {
    1924            0 :         i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
    1925              :                     field_width);
    1926            0 :       } else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
    1927            0 :         i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
    1928              :                     ch == 'x' ? 16 : 10, flags, field_width);
    1929            0 :       } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
    1930            0 :         i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
    1931              :                     ch == 'x' ? 16 : 10, flags, field_width);
    1932            0 :       } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
    1933            0 :         i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
    1934              :                     ch == 'x' ? 16 : 10, flags, field_width);
    1935            0 :       } else if (ch == 'p') {
    1936            0 :         unsigned long num = (unsigned long) va_arg(ap, void *);
    1937            0 :         C_SNPRINTF_APPEND_CHAR('0');
    1938            0 :         C_SNPRINTF_APPEND_CHAR('x');
    1939            0 :         i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
    1940              :       } else {
    1941              : #ifndef NO_LIBC
    1942              :         /*
    1943              :          * TODO(lsm): abort is not nice in a library, remove it
    1944              :          * Also, ESP8266 SDK doesn't have it
    1945              :          */
    1946            0 :         abort();
    1947              : #endif
    1948              :       }
    1949              :     }
    1950              :   }
    1951              : 
    1952              :   /* Zero-terminate the result */
    1953            0 :   if (buf_size > 0) {
    1954            0 :     buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
    1955              :   }
    1956              : 
    1957            0 :   return i;
    1958              : }
    1959              : #endif
    1960              : 
    1961            0 : int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
    1962              :   int result;
    1963              :   va_list ap;
    1964            0 :   va_start(ap, fmt);
    1965            0 :   result = c_vsnprintf(buf, buf_size, fmt, ap);
    1966            0 :   va_end(ap);
    1967            0 :   return result;
    1968              : }
    1969              : 
    1970              : #ifdef _WIN32
    1971              : int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
    1972              :   int ret;
    1973              :   char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
    1974              : 
    1975              :   strncpy(buf, path, sizeof(buf));
    1976              :   buf[sizeof(buf) - 1] = '\0';
    1977              : 
    1978              :   /* Trim trailing slashes. Leave backslash for paths like "X:\" */
    1979              :   p = buf + strlen(buf) - 1;
    1980              :   while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
    1981              : 
    1982              :   memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
    1983              :   ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
    1984              : 
    1985              :   /*
    1986              :    * Convert back to Unicode. If doubly-converted string does not match the
    1987              :    * original, something is fishy, reject.
    1988              :    */
    1989              :   WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
    1990              :                       NULL, NULL);
    1991              :   if (strcmp(buf, buf2) != 0) {
    1992              :     wbuf[0] = L'\0';
    1993              :     ret = 0;
    1994              :   }
    1995              : 
    1996              :   return ret;
    1997              : }
    1998              : #endif /* _WIN32 */
    1999              : 
    2000              : /* The simplest O(mn) algorithm. Better implementation are GPLed */
    2001            0 : const char *c_strnstr(const char *s, const char *find, size_t slen) {
    2002            0 :   size_t find_length = strlen(find);
    2003              :   size_t i;
    2004              : 
    2005            0 :   for (i = 0; i < slen; i++) {
    2006            0 :     if (i + find_length > slen) {
    2007            0 :       return NULL;
    2008              :     }
    2009              : 
    2010            0 :     if (strncmp(&s[i], find, find_length) == 0) {
    2011            0 :       return &s[i];
    2012              :     }
    2013              :   }
    2014              : 
    2015            0 :   return NULL;
    2016              : }
    2017              : 
    2018              : #endif /* EXCLUDE_COMMON */
    2019              : #ifdef MG_MODULE_LINES
    2020              : #line 1 "./src/net.c"
    2021              : #endif
    2022              : /*
    2023              :  * Copyright (c) 2014 Cesanta Software Limited
    2024              :  * All rights reserved
    2025              :  *
    2026              :  * This software is dual-licensed: you can redistribute it and/or modify
    2027              :  * it under the terms of the GNU General Public License version 2 as
    2028              :  * published by the Free Software Foundation. For the terms of this
    2029              :  * license, see <http://www.gnu.org/licenses/>.
    2030              :  *
    2031              :  * You are free to use this software under the terms of the GNU General
    2032              :  * Public License, but WITHOUT ANY WARRANTY; without even the implied
    2033              :  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    2034              :  * See the GNU General Public License for more details.
    2035              :  *
    2036              :  * Alternatively, you can license this software under a commercial
    2037              :  * license, as set out in <https://www.cesanta.com/license>.
    2038              :  */
    2039              : 
    2040              : /* Amalgamated: #include "mongoose/src/internal.h" */
    2041              : /* Amalgamated: #include "mongoose/src/util.h" */
    2042              : /* Amalgamated: #include "mongoose/src/dns.h" */
    2043              : /* Amalgamated: #include "mongoose/src/resolv.h" */
    2044              : /* Amalgamated: #include "common/cs_time.h" */
    2045              : 
    2046              : #define MG_MAX_HOST_LEN 200
    2047              : 
    2048              : #define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
    2049              :   memcpy(dst, src, sizeof(*dst));
    2050              : 
    2051              : /* Which flags can be pre-set by the user at connection creation time. */
    2052              : #define _MG_ALLOWED_CONNECT_FLAGS_MASK                                   \
    2053              :   (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
    2054              :    MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG)
    2055              : /* Which flags should be modifiable by user's callbacks. */
    2056              : #define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK                               \
    2057              :   (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
    2058              :    MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE |        \
    2059              :    MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
    2060              : 
    2061              : #ifndef intptr_t
    2062              : #define intptr_t long
    2063              : #endif
    2064              : 
    2065              : int mg_is_error(int n);
    2066              : void mg_set_non_blocking_mode(sock_t sock);
    2067              : 
    2068              : extern void mg_ev_mgr_init(struct mg_mgr *mgr);
    2069              : extern void mg_ev_mgr_free(struct mg_mgr *mgr);
    2070              : extern void mg_ev_mgr_add_conn(struct mg_connection *nc);
    2071              : extern void mg_ev_mgr_remove_conn(struct mg_connection *nc);
    2072              : 
    2073            0 : MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
    2074            0 :   DBG(("%p %p", mgr, c));
    2075              :   //printf("nc %p -> mg_add_conn, mgr %p %p, pd %p, fp %p\n", c, c->mgr, mgr, c->proto_data, (c->proto_data?*(FILE**)c->proto_data:NULL));
    2076            0 :   c->mgr = mgr;
    2077            0 :   c->next = mgr->active_connections;
    2078            0 :   mgr->active_connections = c;
    2079            0 :   c->prev = NULL;
    2080            0 :   if (c->next != NULL) c->next->prev = c;
    2081            0 :   mg_ev_mgr_add_conn(c);
    2082            0 : }
    2083              : 
    2084            0 : MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
    2085            0 :   if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
    2086            0 :   if (conn->prev) conn->prev->next = conn->next;
    2087            0 :   if (conn->next) conn->next->prev = conn->prev;
    2088            0 :   mg_ev_mgr_remove_conn(conn);
    2089            0 : }
    2090              : 
    2091            0 : MG_INTERNAL void mg_call(struct mg_connection *nc,
    2092              :                          mg_event_handler_t ev_handler, int ev, void *ev_data) {
    2093            0 :   if (ev_handler == NULL) {
    2094              :     /*
    2095              :      * If protocol handler is specified, call it. Otherwise, call user-specified
    2096              :      * event handler.
    2097              :      */
    2098            0 :     ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
    2099              :   }
    2100            0 :   DBG(("%p %s ev=%d ev_data=%p flags=%lu rmbl=%d smbl=%d", nc,
    2101              :        ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags,
    2102              :        (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
    2103              : 
    2104              : #if !defined(NO_LIBC) && !defined(MG_DISABLE_HEXDUMP)
    2105              :   /* LCOV_EXCL_START */
    2106              :   if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL &&
    2107              :       ev != MG_EV_SEND /* handled separately */) {
    2108              :     if (ev == MG_EV_RECV) {
    2109              :       mg_hexdump_connection(nc, nc->mgr->hexdump_file, nc->recv_mbuf.buf,
    2110              :                             *(int *) ev_data, ev);
    2111              :     } else {
    2112              :       mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev);
    2113              :     }
    2114              :   }
    2115              : /* LCOV_EXCL_STOP */
    2116              : #endif
    2117            0 :   if (ev_handler != NULL) {
    2118            0 :     unsigned long flags_before = nc->flags;
    2119            0 :     size_t recv_mbuf_before = nc->recv_mbuf.len, recved;
    2120            0 :     ev_handler(nc, ev, ev_data);
    2121            0 :     recved = (recv_mbuf_before - nc->recv_mbuf.len);
    2122              :     /* Prevent user handler from fiddling with system flags. */
    2123            0 :     if (ev_handler == nc->handler && nc->flags != flags_before) {
    2124            0 :       nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
    2125            0 :                   (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
    2126              :     }
    2127            0 :     if (recved > 0 && !(nc->flags & MG_F_UDP)) {
    2128            0 :       mg_if_recved(nc, recved);
    2129              :     }
    2130              :   }
    2131            0 :   DBG(("%p after %s flags=%lu rmbl=%d smbl=%d", nc,
    2132              :        ev_handler == nc->handler ? "user" : "proto", nc->flags,
    2133              :        (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
    2134            0 : }
    2135              : 
    2136            0 : void mg_if_timer(struct mg_connection *c, double now) {
    2137            0 :   if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
    2138            0 :     double old_value = c->ev_timer_time;
    2139            0 :     mg_call(c, NULL, MG_EV_TIMER, &now);
    2140              :     /*
    2141              :      * To prevent timer firing all the time, reset the timer after delivery.
    2142              :      * However, in case user sets it to new value, do not reset.
    2143              :      */
    2144            0 :     if (c->ev_timer_time == old_value) {
    2145            0 :       c->ev_timer_time = 0;
    2146              :     }
    2147              :   }
    2148            0 : }
    2149              : 
    2150            0 : void mg_if_poll(struct mg_connection *nc, time_t now) {
    2151            0 :   if (nc->ssl == NULL || (nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
    2152            0 :     mg_call(nc, NULL, MG_EV_POLL, &now);
    2153              :   }
    2154            0 : }
    2155              : 
    2156            0 : static void mg_destroy_conn(struct mg_connection *conn) {
    2157            0 :   if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) {
    2158            0 :     conn->proto_data_destructor(conn->proto_data);
    2159              :   }
    2160            0 :   mg_if_destroy_conn(conn);
    2161              : #ifdef MG_ENABLE_SSL
    2162              :   if (conn->ssl != NULL) SSL_free(conn->ssl);
    2163              :   if (conn->ssl_ctx != NULL) SSL_CTX_free(conn->ssl_ctx);
    2164              : #endif
    2165            0 :   mbuf_free(&conn->recv_mbuf);
    2166            0 :   mbuf_free(&conn->send_mbuf);
    2167              : 
    2168            0 :   memset(conn, 0, sizeof(*conn));
    2169            0 :   MG_FREE(conn);
    2170            0 : }
    2171              : 
    2172            0 : void mg_close_conn(struct mg_connection *conn) {
    2173            0 :   DBG(("%p %lu", conn, conn->flags));
    2174            0 :   mg_call(conn, NULL, MG_EV_CLOSE, NULL);
    2175            0 :   mg_remove_conn(conn);
    2176            0 :   mg_destroy_conn(conn);
    2177            0 : }
    2178              : 
    2179            0 : void mg_mgr_init(struct mg_mgr *m, void *user_data) {
    2180            0 :   memset(m, 0, sizeof(*m));
    2181              : #ifndef MG_DISABLE_SOCKETPAIR
    2182            0 :   m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
    2183              : #endif
    2184            0 :   m->user_data = user_data;
    2185              : 
    2186              : #ifdef _WIN32
    2187              :   {
    2188              :     WSADATA data;
    2189              :     WSAStartup(MAKEWORD(2, 2), &data);
    2190              :   }
    2191              : #elif defined(__unix__)
    2192              :   /* Ignore SIGPIPE signal, so if client cancels the request, it
    2193              :    * won't kill the whole process. */
    2194            0 :   signal(SIGPIPE, SIG_IGN);
    2195              : #endif
    2196              : 
    2197              : #ifdef MG_ENABLE_SSL
    2198              :   {
    2199              :     static int init_done;
    2200              :     if (!init_done) {
    2201              :       SSL_library_init();
    2202              :       init_done++;
    2203              :     }
    2204              :   }
    2205              : #endif
    2206              : 
    2207            0 :   mg_ev_mgr_init(m);
    2208            0 :   DBG(("=================================="));
    2209            0 :   DBG(("init mgr=%p", m));
    2210            0 : }
    2211              : 
    2212              : #ifdef MG_ENABLE_JAVASCRIPT
    2213              : static enum v7_err mg_send_js(struct v7 *v7, v7_val_t *res) {
    2214              :   v7_val_t arg0 = v7_arg(v7, 0);
    2215              :   v7_val_t arg1 = v7_arg(v7, 1);
    2216              :   struct mg_connection *c = (struct mg_connection *) v7_to_foreign(arg0);
    2217              :   size_t len = 0;
    2218              : 
    2219              :   if (v7_is_string(arg1)) {
    2220              :     const char *data = v7_get_string_data(v7, &arg1, &len);
    2221              :     mg_send(c, data, len);
    2222              :   }
    2223              : 
    2224              :   *res = v7_mk_number(len);
    2225              : 
    2226              :   return V7_OK;
    2227              : }
    2228              : 
    2229              : enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
    2230              :                                  const char *init_file_name) {
    2231              :   v7_val_t v;
    2232              :   m->v7 = v7;
    2233              :   v7_set_method(v7, v7_get_global(v7), "mg_send", mg_send_js);
    2234              :   return v7_exec_file(v7, init_file_name, &v);
    2235              : }
    2236              : #endif
    2237              : 
    2238            0 : void mg_mgr_free(struct mg_mgr *m) {
    2239              :   struct mg_connection *conn, *tmp_conn;
    2240              : 
    2241            0 :   DBG(("%p", m));
    2242            0 :   if (m == NULL) return;
    2243              :   /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
    2244            0 :   mg_mgr_poll(m, 0);
    2245              : 
    2246              : #ifndef MG_DISABLE_SOCKETPAIR
    2247            0 :   if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
    2248            0 :   if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
    2249            0 :   m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
    2250              : #endif
    2251              : 
    2252            0 :   for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
    2253            0 :     tmp_conn = conn->next;
    2254            0 :     mg_close_conn(conn);
    2255              :   }
    2256              : 
    2257            0 :   mg_ev_mgr_free(m);
    2258              : }
    2259              : 
    2260            0 : int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
    2261            0 :   char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
    2262              :   int len;
    2263              : 
    2264            0 :   if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
    2265            0 :     mg_send(nc, buf, len);
    2266              :   }
    2267            0 :   if (buf != mem && buf != NULL) {
    2268              :     MG_FREE(buf); /* LCOV_EXCL_LINE */
    2269              :   }               /* LCOV_EXCL_LINE */
    2270              : 
    2271            0 :   return len;
    2272              : }
    2273              : 
    2274            0 : int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
    2275              :   int len;
    2276              :   va_list ap;
    2277            0 :   va_start(ap, fmt);
    2278            0 :   len = mg_vprintf(conn, fmt, ap);
    2279            0 :   va_end(ap);
    2280            0 :   return len;
    2281              : }
    2282              : 
    2283              : #ifndef MG_DISABLE_SYNC_RESOLVER
    2284              : /* TODO(lsm): use non-blocking resolver */
    2285            0 : static int mg_resolve2(const char *host, struct in_addr *ina) {
    2286              : #ifdef MG_ENABLE_GETADDRINFO
    2287              :   int rv = 0;
    2288              :   struct addrinfo hints, *servinfo, *p;
    2289              :   struct sockaddr_in *h = NULL;
    2290              :   memset(&hints, 0, sizeof hints);
    2291              :   hints.ai_family = AF_INET;
    2292              :   hints.ai_socktype = SOCK_STREAM;
    2293              :   if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
    2294              :     DBG(("getaddrinfo(%s) failed: %s", host, strerror(errno)));
    2295              :     return 0;
    2296              :   }
    2297              :   for (p = servinfo; p != NULL; p = p->ai_next) {
    2298              :     memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
    2299              :     memcpy(ina, &h->sin_addr, sizeof(ina));
    2300              :   }
    2301              :   freeaddrinfo(servinfo);
    2302              :   return 1;
    2303              : #else
    2304              :   struct hostent *he;
    2305            0 :   if ((he = gethostbyname(host)) == NULL) {
    2306            0 :     DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
    2307              :   } else {
    2308            0 :     memcpy(ina, he->h_addr_list[0], sizeof(*ina));
    2309            0 :     return 1;
    2310              :   }
    2311            0 :   return 0;
    2312              : #endif /* MG_ENABLE_GETADDRINFO */
    2313              : }
    2314              : 
    2315            0 : int mg_resolve(const char *host, char *buf, size_t n) {
    2316              :   struct in_addr ad;
    2317            0 :   return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
    2318              : }
    2319              : #endif /* MG_DISABLE_SYNC_RESOLVER */
    2320              : 
    2321            0 : MG_INTERNAL struct mg_connection *mg_create_connection_base(
    2322              :     struct mg_mgr *mgr, mg_event_handler_t callback,
    2323              :     struct mg_add_sock_opts opts) {
    2324              :   struct mg_connection *conn;
    2325              : 
    2326            0 :   if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
    2327            0 :     conn->sock = INVALID_SOCKET;
    2328            0 :     conn->handler = callback;
    2329            0 :     conn->mgr = mgr;
    2330            0 :     conn->last_io_time = mg_time();
    2331            0 :     conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
    2332            0 :     conn->user_data = opts.user_data;
    2333              :     /*
    2334              :      * SIZE_MAX is defined as a long long constant in
    2335              :      * system headers on some platforms and so it
    2336              :      * doesn't compile with pedantic ansi flags.
    2337              :      */
    2338            0 :     conn->recv_mbuf_limit = ~0;
    2339              :   } else {
    2340            0 :     MG_SET_PTRPTR(opts.error_string, "failed to create connection");
    2341              :   }
    2342              : 
    2343            0 :   return conn;
    2344              : }
    2345              : 
    2346            0 : MG_INTERNAL struct mg_connection *mg_create_connection(
    2347              :     struct mg_mgr *mgr, mg_event_handler_t callback,
    2348              :     struct mg_add_sock_opts opts) {
    2349            0 :   struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts);
    2350              : 
    2351            0 :   if (!mg_if_create_conn(conn)) {
    2352            0 :     MG_FREE(conn);
    2353            0 :     conn = NULL;
    2354            0 :     MG_SET_PTRPTR(opts.error_string, "failed to init connection");
    2355              :   }
    2356              : 
    2357            0 :   return conn;
    2358              : }
    2359              : 
    2360              : /*
    2361              :  * Address format: [PROTO://][HOST]:PORT
    2362              :  *
    2363              :  * HOST could be IPv4/IPv6 address or a host name.
    2364              :  * `host` is a destination buffer to hold parsed HOST part. Shoud be at least
    2365              :  * MG_MAX_HOST_LEN bytes long.
    2366              :  * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
    2367              :  *
    2368              :  * Return:
    2369              :  *   -1   on parse error
    2370              :  *    0   if HOST needs DNS lookup
    2371              :  *   >0   length of the address string
    2372              :  */
    2373            0 : MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
    2374              :                                  int *proto, char *host, size_t host_len) {
    2375            0 :   unsigned int a, b, c, d, port = 0;
    2376            0 :   int ch, len = 0;
    2377              : #ifdef MG_ENABLE_IPV6
    2378              :   char buf[100];
    2379              : #endif
    2380              : 
    2381              :   /*
    2382              :    * MacOS needs that. If we do not zero it, subsequent bind() will fail.
    2383              :    * Also, all-zeroes in the socket address means binding to all addresses
    2384              :    * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
    2385              :    */
    2386            0 :   memset(sa, 0, sizeof(*sa));
    2387            0 :   sa->sin.sin_family = AF_INET;
    2388              : 
    2389            0 :   *proto = SOCK_STREAM;
    2390              : 
    2391            0 :   if (strncmp(str, "udp://", 6) == 0) {
    2392            0 :     str += 6;
    2393            0 :     *proto = SOCK_DGRAM;
    2394            0 :   } else if (strncmp(str, "tcp://", 6) == 0) {
    2395            0 :     str += 6;
    2396              :   }
    2397              : 
    2398            0 :   if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
    2399              :     /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
    2400            0 :     sa->sin.sin_addr.s_addr =
    2401            0 :         htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
    2402            0 :     sa->sin.sin_port = htons((uint16_t) port);
    2403              : #ifdef MG_ENABLE_IPV6
    2404              :   } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
    2405              :              inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
    2406              :     /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
    2407              :     sa->sin6.sin6_family = AF_INET6;
    2408              :     sa->sin.sin_port = htons((uint16_t) port);
    2409              : #endif
    2410              : #ifndef MG_DISABLE_RESOLVER
    2411            0 :   } else if (strlen(str) < host_len &&
    2412            0 :              sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
    2413            0 :     sa->sin.sin_port = htons((uint16_t) port);
    2414            0 :     if (mg_resolve_from_hosts_file(host, sa) != 0) {
    2415            0 :       return 0;
    2416              :     }
    2417              : #endif
    2418            0 :   } else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
    2419            0 :              sscanf(str, "%u%n", &port, &len) == 1) {
    2420              :     /* If only port is specified, bind to IPv4, INADDR_ANY */
    2421            0 :     sa->sin.sin_port = htons((uint16_t) port);
    2422              :   } else {
    2423            0 :     return -1;
    2424              :   }
    2425              : 
    2426            0 :   ch = str[len]; /* Character that follows the address */
    2427            0 :   return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
    2428              : }
    2429              : 
    2430              : #ifdef MG_ENABLE_SSL
    2431              : /*
    2432              :  * Certificate generation script is at
    2433              :  * https://github.com/cesanta/mongoose/blob/master/scripts/generate_ssl_certificates.sh
    2434              :  */
    2435              : 
    2436              : #ifndef MG_DISABLE_PFS
    2437              : /*
    2438              :  * Cipher suite options used for TLS negotiation.
    2439              :  * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
    2440              :  */
    2441              : static const char mg_s_cipher_list[] =
    2442              : #if defined(MG_SSL_CRYPTO_MODERN)
    2443              :     "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
    2444              :     "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
    2445              :     "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
    2446              :     "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
    2447              :     "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
    2448              :     "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
    2449              :     "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
    2450              :     "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
    2451              :     "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
    2452              : #elif defined(MG_SSL_CRYPTO_OLD)
    2453              :     "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
    2454              :     "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
    2455              :     "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
    2456              :     "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
    2457              :     "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
    2458              :     "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
    2459              :     "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
    2460              :     "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
    2461              :     "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
    2462              :     "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
    2463              :     "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
    2464              :     "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
    2465              : #else /* Default - intermediate. */
    2466              :     "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
    2467              :     "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
    2468              :     "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
    2469              :     //"ECDHE-RSA-AES128-SHA256:"
    2470              :     "ECDHE-ECDSA-AES128-SHA256:"
    2471              :     //"ECDHE-RSA-AES128-SHA:"
    2472              :     "ECDHE-ECDSA-AES128-SHA:"
    2473              :     //"ECDHE-RSA-AES256-SHA384:"
    2474              :     "ECDHE-ECDSA-AES256-SHA384:"
    2475              :     //"ECDHE-RSA-AES256-SHA:"
    2476              :     "ECDHE-ECDSA-AES256-SHA:"
    2477              :     //"DHE-RSA-AES128-SHA256:"
    2478              :     //"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
    2479              :     //"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
    2480              :     "AES128-GCM-SHA256:AES256-GCM-SHA384:"
    2481              :     "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:"
    2482              :     "AES:"
    2483              :     "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!RSA:!CBC-SHA:!CAMELLIA:"
    2484              :     "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
    2485              : #endif
    2486              :     ;
    2487              : 
    2488              : /*
    2489              :  * Default DH params for PFS cipher negotiation. This is a 2048-bit group.
    2490              :  * Will be used if none are provided by the user in the certificate file.
    2491              :  */
    2492              : static const char mg_s_default_dh_params[] =
    2493              :     "\
    2494              : -----BEGIN DH PARAMETERS-----\n\
    2495              : MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
    2496              : Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
    2497              : +E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
    2498              : ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
    2499              : wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
    2500              : 9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
    2501              : -----END DH PARAMETERS-----\n";
    2502              : #endif
    2503              : 
    2504              : static int mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
    2505              :   if (ctx == NULL) {
    2506              :     return -1;
    2507              :   } else if (cert == NULL || cert[0] == '\0') {
    2508              :     return 0;
    2509              :   }
    2510              :   SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
    2511              :   return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2;
    2512              : }
    2513              : 
    2514              : static int mg_use_cert(SSL_CTX *ctx, const char *pem_file) {
    2515              :   if (ctx == NULL) {
    2516              :     return -1;
    2517              :   } else if (pem_file == NULL || pem_file[0] == '\0') {
    2518              :     return 0;
    2519              :   } else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 ||
    2520              :              SSL_CTX_use_PrivateKey_file(ctx, pem_file, 1) == 0) {
    2521              :     return -2;
    2522              :   } else {
    2523              : #ifndef MG_DISABLE_PFS
    2524              :     BIO *bio = NULL;
    2525              :     DH *dh = NULL;
    2526              : 
    2527              :     /* Try to read DH parameters from the cert/key file. */
    2528              :     bio = BIO_new_file(pem_file, "r");
    2529              :     if (bio != NULL) {
    2530              :       dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
    2531              :       BIO_free(bio);
    2532              :     }
    2533              :     /*
    2534              :      * If there are no DH params in the file, fall back to hard-coded ones.
    2535              :      * Not ideal, but better than nothing.
    2536              :      */
    2537              :     if (dh == NULL) {
    2538              :       bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
    2539              :       dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
    2540              :       BIO_free(bio);
    2541              :     }
    2542              :     if (dh != NULL) {
    2543              :       SSL_CTX_set_tmp_dh(ctx, dh);
    2544              :       SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
    2545              :       DH_free(dh);
    2546              :     }
    2547              : #endif
    2548              :     SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
    2549              :     SSL_CTX_use_certificate_chain_file(ctx, pem_file);
    2550              :     return 0;
    2551              :   }
    2552              : }
    2553              : 
    2554              : /*
    2555              :  * Turn the connection into SSL mode.
    2556              :  * `cert` is the certificate file in PEM format. For listening connections,
    2557              :  * certificate file must contain private key and server certificate,
    2558              :  * concatenated. It may also contain DH params - these will be used for more
    2559              :  * secure key exchange. `ca_cert` is a certificate authority (CA) PEM file, and
    2560              :  * it is optional (can be set to NULL). If `ca_cert` is non-NULL, then
    2561              :  * the connection is so-called two-way-SSL: other peer's certificate is
    2562              :  * checked against the `ca_cert`.
    2563              :  *
    2564              :  * Handy OpenSSL command to generate test self-signed certificate:
    2565              :  *
    2566              :  *    openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 999
    2567              :  *
    2568              :  * Return NULL on success, or error message on failure.
    2569              :  */
    2570              : const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
    2571              :                        const char *ca_cert) {
    2572              :   const char *result = NULL;
    2573              :   DBG(("%p %s %s", nc, (cert ? cert : ""), (ca_cert ? ca_cert : "")));
    2574              : 
    2575              :   if (nc->flags & MG_F_UDP) {
    2576              :     return "SSL for UDP is not supported";
    2577              :   }
    2578              : 
    2579              :   if (nc->ssl != NULL) {
    2580              :     SSL_free(nc->ssl);
    2581              :     nc->ssl = NULL;
    2582              :   }
    2583              :   if (nc->ssl_ctx != NULL) {
    2584              :     SSL_CTX_free(nc->ssl_ctx);
    2585              :     nc->ssl_ctx = NULL;
    2586              :   }
    2587              : 
    2588              :   if ((nc->flags & MG_F_LISTENING) &&
    2589              :       (nc->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
    2590              :     result = "SSL_CTX_new() failed";
    2591              :   } else if (!(nc->flags & MG_F_LISTENING) &&
    2592              :              (nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) {
    2593              :     result = "SSL_CTX_new() failed";
    2594              :   } else if (mg_use_cert(nc->ssl_ctx, cert) != 0) {
    2595              :     result = "Invalid ssl cert";
    2596              :   } else if (mg_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) {
    2597              :     result = "Invalid CA cert";
    2598              :   } else if (!(nc->flags & MG_F_LISTENING) &&
    2599              :              (nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
    2600              :     result = "SSL_new() failed";
    2601              :   } else if (!(nc->flags & MG_F_LISTENING) && nc->sock != INVALID_SOCKET) {
    2602              :     /*
    2603              :      * Socket is open here only if we are connecting to IP address
    2604              :      * and does not open if we are connecting using async DNS resolver
    2605              :      */
    2606              :     SSL_set_fd(nc->ssl, nc->sock);
    2607              :   }
    2608              : 
    2609              :   SSL_CTX_set_options(nc->ssl_ctx, SSL_OP_NO_SSLv2);
    2610              :   SSL_CTX_set_options(nc->ssl_ctx, SSL_OP_NO_SSLv3);
    2611              : 
    2612              : #ifndef MG_DISABLE_PFS
    2613              :   SSL_CTX_set_cipher_list(nc->ssl_ctx, mg_s_cipher_list);
    2614              : #endif
    2615              :   return result;
    2616              : }
    2617              : #endif /* MG_ENABLE_SSL */
    2618              : 
    2619            0 : struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) {
    2620              :   struct mg_add_sock_opts opts;
    2621              :   struct mg_connection *nc;
    2622            0 :   memset(&opts, 0, sizeof(opts));
    2623            0 :   nc = mg_create_connection(lc->mgr, lc->handler, opts);
    2624            0 :   if (nc == NULL) return NULL;
    2625            0 :   nc->listener = lc;
    2626            0 :   nc->proto_handler = lc->proto_handler;
    2627            0 :   nc->user_data = lc->user_data;
    2628            0 :   nc->recv_mbuf_limit = lc->recv_mbuf_limit;
    2629            0 :   mg_add_conn(nc->mgr, nc);
    2630            0 :   DBG(("%p %p %d %d, %p %p", lc, nc, nc->sock, (int) nc->flags, lc->ssl_ctx,
    2631              :        nc->ssl));
    2632            0 :   return nc;
    2633              : }
    2634              : 
    2635            0 : void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
    2636              :                          size_t sa_len) {
    2637              :   (void) sa_len;
    2638            0 :   nc->sa = *sa;
    2639            0 :   mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
    2640            0 : }
    2641              : 
    2642            0 : void mg_send(struct mg_connection *nc, const void *buf, int len) {
    2643            0 :   nc->last_io_time = mg_time();
    2644            0 :   if (nc->flags & MG_F_UDP) {
    2645            0 :     mg_if_udp_send(nc, buf, len);
    2646              :   } else {
    2647            0 :     mg_if_tcp_send(nc, buf, len);
    2648              :   }
    2649              : #if !defined(NO_LIBC) && !defined(MG_DISABLE_HEXDUMP)
    2650            0 :   if (nc->mgr && nc->mgr->hexdump_file != NULL) {
    2651            0 :     mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, len, MG_EV_SEND);
    2652              :   }
    2653              : #endif
    2654            0 : }
    2655              : 
    2656            0 : void mg_if_sent_cb(struct mg_connection *nc, int num_sent) {
    2657            0 :   if (num_sent < 0) {
    2658            0 :     nc->flags |= MG_F_CLOSE_IMMEDIATELY;
    2659              :   }
    2660            0 :   mg_call(nc, NULL, MG_EV_SEND, &num_sent);
    2661            0 : }
    2662              : 
    2663            0 : static void mg_recv_common(struct mg_connection *nc, void *buf, int len) {
    2664            0 :   DBG(("%p %d %u", nc, len, (unsigned int) nc->recv_mbuf.len));
    2665            0 :   if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
    2666            0 :     DBG(("%p discarded %d bytes", nc, len));
    2667              :     /*
    2668              :      * This connection will not survive next poll. Do not deliver events,
    2669              :      * send data to /dev/null without acking.
    2670              :      */
    2671            0 :     MG_FREE(buf);
    2672            0 :     return;
    2673              :   }
    2674            0 :   nc->last_io_time = mg_time();
    2675            0 :   if (nc->recv_mbuf.len == 0) {
    2676              :     /* Adopt buf as recv_mbuf's backing store. */
    2677            0 :     mbuf_free(&nc->recv_mbuf);
    2678            0 :     nc->recv_mbuf.buf = (char *) buf;
    2679            0 :     nc->recv_mbuf.size = nc->recv_mbuf.len = len;
    2680              :   } else {
    2681            0 :     mbuf_append(&nc->recv_mbuf, buf, len);
    2682            0 :     MG_FREE(buf);
    2683              :   }
    2684            0 :   mg_call(nc, NULL, MG_EV_RECV, &len);
    2685              : }
    2686              : 
    2687            0 : void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len) {
    2688            0 :   mg_recv_common(nc, buf, len);
    2689            0 : }
    2690              : 
    2691            0 : void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
    2692              :                        union socket_address *sa, size_t sa_len) {
    2693            0 :   assert(nc->flags & MG_F_UDP);
    2694            0 :   DBG(("%p %u", nc, (unsigned int) len));
    2695            0 :   if (nc->flags & MG_F_LISTENING) {
    2696            0 :     struct mg_connection *lc = nc;
    2697              :     /*
    2698              :      * Do we have an existing connection for this source?
    2699              :      * This is very inefficient for long connection lists.
    2700              :      */
    2701            0 :     for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
    2702            0 :       if (memcmp(&nc->sa.sa, &sa->sa, sa_len) == 0 && nc->listener == lc) {
    2703            0 :         break;
    2704              :       }
    2705              :     }
    2706            0 :     if (nc == NULL) {
    2707              :       struct mg_add_sock_opts opts;
    2708            0 :       memset(&opts, 0, sizeof(opts));
    2709              :       /* Create fake connection w/out sock initialization */
    2710            0 :       nc = mg_create_connection_base(lc->mgr, lc->handler, opts);
    2711            0 :       if (nc != NULL) {
    2712            0 :         nc->sock = lc->sock;
    2713            0 :         nc->listener = lc;
    2714            0 :         nc->sa = *sa;
    2715            0 :         nc->proto_handler = lc->proto_handler;
    2716            0 :         nc->user_data = lc->user_data;
    2717            0 :         nc->recv_mbuf_limit = lc->recv_mbuf_limit;
    2718            0 :         nc->flags = MG_F_UDP;
    2719            0 :         mg_add_conn(lc->mgr, nc);
    2720            0 :         mg_call(nc, NULL, MG_EV_ACCEPT, &nc->sa);
    2721              :       } else {
    2722            0 :         DBG(("OOM"));
    2723              :         /* No return here, we still need to drop on the floor */
    2724              :       }
    2725              :     }
    2726              :   }
    2727            0 :   if (nc != NULL) {
    2728            0 :     mg_recv_common(nc, buf, len);
    2729              :   } else {
    2730              :     /* Drop on the floor. */
    2731            0 :     MG_FREE(buf);
    2732            0 :     mg_if_recved(nc, len);
    2733              :   }
    2734            0 : }
    2735              : 
    2736              : /*
    2737              :  * Schedules an async connect for a resolved address and proto.
    2738              :  * Called from two places: `mg_connect_opt()` and from async resolver.
    2739              :  * When called from the async resolver, it must trigger `MG_EV_CONNECT` event
    2740              :  * with a failure flag to indicate connection failure.
    2741              :  */
    2742            0 : MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
    2743              :                                                 int proto,
    2744              :                                                 union socket_address *sa) {
    2745            0 :   DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
    2746              :        inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
    2747              : 
    2748            0 :   nc->flags |= MG_F_CONNECTING;
    2749            0 :   if (proto == SOCK_DGRAM) {
    2750            0 :     mg_if_connect_udp(nc);
    2751              :   } else {
    2752            0 :     mg_if_connect_tcp(nc, sa);
    2753              :   }
    2754            0 :   mg_add_conn(nc->mgr, nc);
    2755            0 :   return nc;
    2756              : }
    2757              : 
    2758            0 : void mg_if_connect_cb(struct mg_connection *nc, int err) {
    2759            0 :   DBG(("%p connect, err=%d", nc, err));
    2760            0 :   nc->flags &= ~MG_F_CONNECTING;
    2761            0 :   if (err != 0) {
    2762            0 :     nc->flags |= MG_F_CLOSE_IMMEDIATELY;
    2763              :   }
    2764            0 :   mg_call(nc, NULL, MG_EV_CONNECT, &err);
    2765            0 : }
    2766              : 
    2767              : #ifndef MG_DISABLE_RESOLVER
    2768              : /*
    2769              :  * Callback for the async resolver on mg_connect_opt() call.
    2770              :  * Main task of this function is to trigger MG_EV_CONNECT event with
    2771              :  *    either failure (and dealloc the connection)
    2772              :  *    or success (and proceed with connect()
    2773              :  */
    2774            0 : static void resolve_cb(struct mg_dns_message *msg, void *data,
    2775              :                        enum mg_resolve_err e) {
    2776            0 :   struct mg_connection *nc = (struct mg_connection *) data;
    2777              :   int i;
    2778            0 :   int failure = -1;
    2779              : 
    2780            0 :   nc->flags &= ~MG_F_RESOLVING;
    2781            0 :   if (msg != NULL) {
    2782              :     /*
    2783              :      * Take the first DNS A answer and run...
    2784              :      */
    2785            0 :     for (i = 0; i < msg->num_answers; i++) {
    2786            0 :       if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
    2787              :         /*
    2788              :          * Async resolver guarantees that there is at least one answer.
    2789              :          * TODO(lsm): handle IPv6 answers too
    2790              :          */
    2791            0 :         mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
    2792              :                                  4);
    2793            0 :         mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
    2794              :                       &nc->sa);
    2795            0 :         return;
    2796              :       }
    2797              :     }
    2798              :   }
    2799              : 
    2800            0 :   if (e == MG_RESOLVE_TIMEOUT) {
    2801            0 :     double now = mg_time();
    2802            0 :     mg_call(nc, NULL, MG_EV_TIMER, &now);
    2803              :   }
    2804              : 
    2805              :   /*
    2806              :    * If we get there was no MG_DNS_A_RECORD in the answer
    2807              :    */
    2808            0 :   mg_call(nc, NULL, MG_EV_CONNECT, &failure);
    2809            0 :   mg_call(nc, NULL, MG_EV_CLOSE, NULL);
    2810            0 :   mg_destroy_conn(nc);
    2811              : }
    2812              : #endif
    2813              : 
    2814            0 : struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
    2815              :                                  mg_event_handler_t callback) {
    2816              :   struct mg_connect_opts opts;
    2817            0 :   memset(&opts, 0, sizeof(opts));
    2818            0 :   return mg_connect_opt(mgr, address, callback, opts);
    2819              : }
    2820              : 
    2821            0 : struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
    2822              :                                      mg_event_handler_t callback,
    2823              :                                      struct mg_connect_opts opts) {
    2824            0 :   struct mg_connection *nc = NULL;
    2825              :   int proto, rc;
    2826              :   struct mg_add_sock_opts add_sock_opts;
    2827              :   char host[MG_MAX_HOST_LEN];
    2828              : 
    2829            0 :   MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
    2830              : 
    2831            0 :   if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
    2832            0 :     return NULL;
    2833            0 :   } else if ((rc = mg_parse_address(address, &nc->sa, &proto, host,
    2834            0 :                                     sizeof(host))) < 0) {
    2835              :     /* Address is malformed */
    2836            0 :     MG_SET_PTRPTR(opts.error_string, "cannot parse address");
    2837            0 :     mg_destroy_conn(nc);
    2838            0 :     return NULL;
    2839              :   }
    2840            0 :   nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
    2841            0 :   nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
    2842            0 :   nc->user_data = opts.user_data;
    2843              : 
    2844              : #ifdef MG_ENABLE_SSL
    2845              :   if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
    2846              :     const char *err = mg_set_ssl(nc, opts.ssl_cert, opts.ssl_ca_cert);
    2847              :     if (err != NULL) {
    2848              :       MG_SET_PTRPTR(opts.error_string, err);
    2849              :       mg_destroy_conn(nc);
    2850              :       return NULL;
    2851              :     }
    2852              :     if (opts.ssl_ca_cert != NULL && (opts.ssl_server_name == NULL ||
    2853              :                                      strcmp(opts.ssl_server_name, "*") != 0)) {
    2854              :       if (opts.ssl_server_name == NULL) opts.ssl_server_name = host;
    2855              : #ifdef SSL_KRYPTON
    2856              :       SSL_CTX_kr_set_verify_name(nc->ssl_ctx, opts.ssl_server_name);
    2857              : #else
    2858              :       /* TODO(rojer): Implement server name verification on OpenSSL. */
    2859              :       MG_SET_PTRPTR(opts.error_string,
    2860              :                     "Server name verification requested but is not supported");
    2861              :       mg_destroy_conn(nc);
    2862              :       return NULL;
    2863              : #endif /* SSL_KRYPTON */
    2864              :     }
    2865              :   }
    2866              : #endif /* MG_ENABLE_SSL */
    2867              : 
    2868            0 :   if (rc == 0) {
    2869              : #ifndef MG_DISABLE_RESOLVER
    2870              :     /*
    2871              :      * DNS resolution is required for host.
    2872              :      * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
    2873              :      */
    2874            0 :     struct mg_connection *dns_conn = NULL;
    2875              :     struct mg_resolve_async_opts o;
    2876            0 :     memset(&o, 0, sizeof(o));
    2877            0 :     o.dns_conn = &dns_conn;
    2878            0 :     if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc,
    2879            0 :                              o) != 0) {
    2880            0 :       MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
    2881            0 :       mg_destroy_conn(nc);
    2882            0 :       return NULL;
    2883              :     }
    2884            0 :     nc->priv_2 = dns_conn;
    2885            0 :     nc->flags |= MG_F_RESOLVING;
    2886            0 :     return nc;
    2887              : #else
    2888              :     MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
    2889              :     mg_destroy_conn(nc);
    2890              :     return NULL;
    2891              : #endif
    2892              :   } else {
    2893              :     /* Address is parsed and resolved to IP. proceed with connect() */
    2894            0 :     return mg_do_connect(nc, proto, &nc->sa);
    2895              :   }
    2896              : }
    2897              : 
    2898            0 : struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
    2899              :                               mg_event_handler_t event_handler) {
    2900              :   struct mg_bind_opts opts;
    2901            0 :   memset(&opts, 0, sizeof(opts));
    2902            0 :   return mg_bind_opt(srv, address, event_handler, opts);
    2903              : }
    2904              : 
    2905            0 : struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
    2906              :                                   mg_event_handler_t callback,
    2907              :                                   struct mg_bind_opts opts) {
    2908              :   union socket_address sa;
    2909            0 :   struct mg_connection *nc = NULL;
    2910              :   int proto, rc;
    2911              :   struct mg_add_sock_opts add_sock_opts;
    2912              :   char host[MG_MAX_HOST_LEN];
    2913              : 
    2914            0 :   MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
    2915              : 
    2916            0 :   if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
    2917            0 :     MG_SET_PTRPTR(opts.error_string, "cannot parse address");
    2918            0 :     return NULL;
    2919              :   }
    2920              : 
    2921            0 :   nc = mg_create_connection(mgr, callback, add_sock_opts);
    2922            0 :   if (nc == NULL) {
    2923            0 :     return NULL;
    2924              :   }
    2925              : 
    2926            0 :   nc->sa = sa;
    2927            0 :   nc->flags |= MG_F_LISTENING;
    2928            0 :   if (proto == SOCK_DGRAM) {
    2929            0 :     nc->flags |= MG_F_UDP;
    2930            0 :     rc = mg_if_listen_udp(nc, &nc->sa);
    2931              :   } else {
    2932            0 :     rc = mg_if_listen_tcp(nc, &nc->sa);
    2933              :   }
    2934            0 :   if (rc != 0) {
    2935            0 :     DBG(("Failed to open listener: %d", rc));
    2936            0 :     MG_SET_PTRPTR(opts.error_string, "failed to open listener");
    2937            0 :     mg_destroy_conn(nc);
    2938            0 :     return NULL;
    2939              :   }
    2940              : #ifdef MG_ENABLE_SSL
    2941              :   if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
    2942              :     const char *err = mg_set_ssl(nc, opts.ssl_cert, opts.ssl_ca_cert);
    2943              :     if (err != NULL) {
    2944              :       MG_SET_PTRPTR(opts.error_string, err);
    2945              :       mg_destroy_conn(nc);
    2946              :       return NULL;
    2947              :     }
    2948              :   }
    2949              : #endif /* MG_ENABLE_SSL */
    2950            0 :   mg_add_conn(nc->mgr, nc);
    2951              : 
    2952            0 :   return nc;
    2953              : }
    2954              : 
    2955            0 : struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
    2956            0 :   return conn == NULL ? s->active_connections : conn->next;
    2957              : }
    2958              : 
    2959              : #ifndef MG_DISABLE_SOCKETPAIR
    2960            0 : void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
    2961              :                   size_t len) {
    2962              :   struct ctl_msg ctl_msg;
    2963              : 
    2964              :   /*
    2965              :    * Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
    2966              :    * where `mg_broadcast()` pushes the message.
    2967              :    * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
    2968              :    * specified callback for each connection. Thus the callback function executes
    2969              :    * in event manager thread.
    2970              :    */
    2971            0 :   if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
    2972            0 :       len < sizeof(ctl_msg.message)) {
    2973              :     size_t dummy;
    2974              : 
    2975            0 :     ctl_msg.callback = cb;
    2976            0 :     memcpy(ctl_msg.message, data, len);
    2977            0 :     dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
    2978              :                          offsetof(struct ctl_msg, message) + len, 0);
    2979            0 :     dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
    2980              :     (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
    2981              :   }
    2982            0 : }
    2983              : #endif /* MG_DISABLE_SOCKETPAIR */
    2984              : 
    2985            0 : static int isbyte(int n) {
    2986            0 :   return n >= 0 && n <= 255;
    2987              : }
    2988              : 
    2989            0 : static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
    2990            0 :   int n, a, b, c, d, slash = 32, len = 0;
    2991              : 
    2992            0 :   if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
    2993            0 :        sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
    2994            0 :       isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
    2995            0 :       slash < 33) {
    2996            0 :     len = n;
    2997            0 :     *net =
    2998            0 :         ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
    2999            0 :     *mask = slash ? 0xffffffffU << (32 - slash) : 0;
    3000              :   }
    3001              : 
    3002            0 :   return len;
    3003              : }
    3004              : 
    3005            0 : int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
    3006              :   int allowed, flag;
    3007              :   uint32_t net, mask;
    3008              :   struct mg_str vec;
    3009              : 
    3010              :   /* If any ACL is set, deny by default */
    3011            0 :   allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
    3012              : 
    3013            0 :   while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
    3014            0 :     flag = vec.p[0];
    3015            0 :     if ((flag != '+' && flag != '-') ||
    3016            0 :         parse_net(&vec.p[1], &net, &mask) == 0) {
    3017            0 :       return -1;
    3018              :     }
    3019              : 
    3020            0 :     if (net == (remote_ip & mask)) {
    3021            0 :       allowed = flag;
    3022              :     }
    3023              :   }
    3024              : 
    3025            0 :   DBG(("%08x %c", remote_ip, allowed));
    3026            0 :   return allowed == '+';
    3027              : }
    3028              : 
    3029              : /* Move data from one connection to another */
    3030            0 : void mg_forward(struct mg_connection *from, struct mg_connection *to) {
    3031            0 :   mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
    3032            0 :   mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
    3033            0 : }
    3034              : 
    3035            0 : double mg_set_timer(struct mg_connection *c, double timestamp) {
    3036            0 :   double result = c->ev_timer_time;
    3037            0 :   c->ev_timer_time = timestamp;
    3038              :   /*
    3039              :    * If this connection is resolving, it's not in the list of active
    3040              :    * connections, so not processed yet. It has a DNS resolver connection
    3041              :    * linked to it. Set up a timer for the DNS connection.
    3042              :    */
    3043            0 :   DBG(("%p %p %d -> %lu", c, c->priv_2, c->flags & MG_F_RESOLVING,
    3044              :        (unsigned long) timestamp));
    3045            0 :   if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
    3046            0 :     ((struct mg_connection *) c->priv_2)->ev_timer_time = timestamp;
    3047              :   }
    3048            0 :   return result;
    3049              : }
    3050              : 
    3051            0 : struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
    3052              :                                       mg_event_handler_t callback,
    3053              :                                       struct mg_add_sock_opts opts) {
    3054            0 :   struct mg_connection *nc = mg_create_connection_base(s, callback, opts);
    3055            0 :   if (nc != NULL) {
    3056            0 :     mg_sock_set(nc, sock);
    3057            0 :     mg_add_conn(nc->mgr, nc);
    3058              :   }
    3059            0 :   return nc;
    3060              : }
    3061              : 
    3062            0 : struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
    3063              :                                   mg_event_handler_t callback) {
    3064              :   struct mg_add_sock_opts opts;
    3065            0 :   memset(&opts, 0, sizeof(opts));
    3066            0 :   return mg_add_sock_opt(s, sock, callback, opts);
    3067              : }
    3068              : 
    3069            0 : double mg_time() {
    3070            0 :   return cs_time();
    3071              : }
    3072              : #ifdef MG_MODULE_LINES
    3073              : #line 1 "./src/net_if_socket.c"
    3074              : #endif
    3075              : /*
    3076              :  * Copyright (c) 2014-2016 Cesanta Software Limited
    3077              :  * All rights reserved
    3078              :  */
    3079              : 
    3080              : #ifndef MG_DISABLE_SOCKET_IF
    3081              : 
    3082              : /* Amalgamated: #include "mongoose/src/internal.h" */
    3083              : /* Amalgamated: #include "mongoose/src/util.h" */
    3084              : 
    3085              : #define MG_TCP_RECV_BUFFER_SIZE 1024
    3086              : #define MG_UDP_RECV_BUFFER_SIZE 1500
    3087              : 
    3088              : static sock_t mg_open_listening_socket(union socket_address *sa, int proto);
    3089              : #ifdef MG_ENABLE_SSL
    3090              : static void mg_ssl_begin(struct mg_connection *nc);
    3091              : static int mg_ssl_err(struct mg_connection *conn, int res);
    3092              : #endif
    3093              : 
    3094            0 : void mg_set_non_blocking_mode(sock_t sock) {
    3095              : #ifdef _WIN32
    3096              :   unsigned long on = 1;
    3097              :   ioctlsocket(sock, FIONBIO, &on);
    3098              : #elif defined(MG_SOCKET_SIMPLELINK)
    3099              :   SlSockNonblocking_t opt;
    3100              :   opt.NonblockingEnabled = 1;
    3101              :   sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
    3102              : #else
    3103            0 :   int flags = fcntl(sock, F_GETFL, 0);
    3104            0 :   fcntl(sock, F_SETFL, flags | O_NONBLOCK);
    3105              : #endif
    3106            0 : }
    3107              : 
    3108            0 : int mg_is_error(int n) {
    3109              : #ifdef MG_SOCKET_SIMPLELINK
    3110              :   DBG(("n = %d, errno = %d", n, errno));
    3111              :   if (n < 0) errno = n;
    3112              : #endif
    3113            0 :   return n == 0 || (n < 0 && errno != EINTR && errno != EINPROGRESS &&
    3114            0 :                     errno != EAGAIN && errno != EWOULDBLOCK
    3115              : #ifdef MG_SOCKET_SIMPLELINK
    3116              :                     && errno != SL_EALREADY
    3117              : #endif
    3118              : #ifdef _WIN32
    3119              :                     && WSAGetLastError() != WSAEINTR &&
    3120              :                     WSAGetLastError() != WSAEWOULDBLOCK
    3121              : #endif
    3122            0 :                     );
    3123              : }
    3124              : 
    3125            0 : void mg_if_connect_tcp(struct mg_connection *nc,
    3126              :                        const union socket_address *sa) {
    3127              :   int rc;
    3128            0 :   nc->sock = socket(AF_INET, SOCK_STREAM, 0);
    3129            0 :   if (nc->sock < 0) {
    3130            0 :     nc->sock = INVALID_SOCKET;
    3131            0 :     nc->err = errno ? errno : 1;
    3132            0 :     return;
    3133              :   }
    3134              : #if !defined(MG_SOCKET_SIMPLELINK) && !defined(MG_ESP8266)
    3135            0 :   mg_set_non_blocking_mode(nc->sock);
    3136              : #endif
    3137            0 :   rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
    3138            0 :   nc->err = mg_is_error(rc) ? errno : 0;
    3139            0 :   DBG(("%p sock %d err %d", nc, nc->sock, nc->err));
    3140              : }
    3141              : 
    3142            0 : void mg_if_connect_udp(struct mg_connection *nc) {
    3143            0 :   nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
    3144            0 :   if (nc->sock < 0) {
    3145            0 :     nc->sock = INVALID_SOCKET;
    3146            0 :     nc->err = errno ? errno : 1;
    3147            0 :     return;
    3148              :   }
    3149            0 :   nc->err = 0;
    3150              : }
    3151              : 
    3152            0 : int mg_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
    3153            0 :   sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM);
    3154            0 :   if (sock == INVALID_SOCKET) {
    3155            0 :     return (errno ? errno : 1);
    3156              :   }
    3157            0 :   mg_sock_set(nc, sock);
    3158            0 :   return 0;
    3159              : }
    3160              : 
    3161            0 : int mg_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
    3162            0 :   sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM);
    3163            0 :   if (sock < 0) return (errno ? errno : 1);
    3164            0 :   mg_sock_set(nc, sock);
    3165            0 :   return 0;
    3166              : }
    3167              : 
    3168            0 : void mg_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
    3169            0 :   mbuf_append(&nc->send_mbuf, buf, len);
    3170            0 : }
    3171              : 
    3172            0 : void mg_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
    3173            0 :   mbuf_append(&nc->send_mbuf, buf, len);
    3174            0 : }
    3175              : 
    3176            0 : void mg_if_recved(struct mg_connection *nc, size_t len) {
    3177              :   (void) nc;
    3178              :   (void) len;
    3179            0 : }
    3180              : 
    3181            0 : int mg_if_create_conn(struct mg_connection *nc) {
    3182              :   (void) nc;
    3183            0 :   return 1;
    3184              : }
    3185              : 
    3186            0 : void mg_if_destroy_conn(struct mg_connection *nc) {
    3187            0 :   if (nc->sock == INVALID_SOCKET) return;
    3188            0 :   if (!(nc->flags & MG_F_UDP)) {
    3189            0 :     closesocket(nc->sock);
    3190              :   } else {
    3191              :     /* Only close outgoing UDP sockets or listeners. */
    3192            0 :     if (nc->listener == NULL) closesocket(nc->sock);
    3193              :   }
    3194              :   /*
    3195              :    * avoid users accidentally double close a socket
    3196              :    * because it can lead to difficult to debug situations.
    3197              :    * It would happen only if reusing a destroyed mg_connection
    3198              :    * but it's not always possible to run the code through an
    3199              :    * address sanitizer.
    3200              :    */
    3201            0 :   nc->sock = INVALID_SOCKET;
    3202              : }
    3203              : 
    3204            0 : static void mg_accept_conn(struct mg_connection *lc) {
    3205              :   struct mg_connection *nc;
    3206              :   union socket_address sa;
    3207            0 :   socklen_t sa_len = sizeof(sa);
    3208              :   extern int check_midas_acl(const struct sockaddr *sa, int len);
    3209              :   /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
    3210            0 :   sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
    3211            0 :   if (sock < 0) {
    3212            0 :     DBG(("%p: failed to accept: %d", lc, errno));
    3213            0 :     return;
    3214              :   }
    3215            0 :   if (!check_midas_acl(&sa.sa, sa_len)) {
    3216            0 :     closesocket(sock);
    3217            0 :     return;
    3218              :   }
    3219            0 :   nc = mg_if_accept_new_conn(lc);
    3220            0 :   if (nc == NULL) {
    3221            0 :     closesocket(sock);
    3222            0 :     return;
    3223              :   }
    3224            0 :   mg_sock_set(nc, sock);
    3225              : #ifdef MG_ENABLE_SSL
    3226              :   if (lc->ssl_ctx != NULL) {
    3227              :     nc->ssl = SSL_new(lc->ssl_ctx);
    3228              :     if (nc->ssl == NULL || SSL_set_fd(nc->ssl, sock) != 1) {
    3229              :       DBG(("SSL error"));
    3230              :       mg_close_conn(nc);
    3231              :     }
    3232              :   } else
    3233              : #endif
    3234              :   {
    3235            0 :     mg_if_accept_tcp_cb(nc, &sa, sa_len);
    3236              :   }
    3237              : }
    3238              : 
    3239              : /* 'sa' must be an initialized address to bind to */
    3240            0 : static sock_t mg_open_listening_socket(union socket_address *sa, int proto) {
    3241            0 :   socklen_t sa_len =
    3242              :       (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
    3243            0 :   sock_t sock = INVALID_SOCKET;
    3244              : #if !defined(MG_SOCKET_SIMPLELINK) && !defined(MG_LWIP)
    3245            0 :   int on = 1;
    3246              : #endif
    3247              : 
    3248            0 :   if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET &&
    3249              : #if !defined(MG_SOCKET_SIMPLELINK) && \
    3250              :     !defined(MG_LWIP) /* SimpleLink and LWIP don't support either */
    3251              : #if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE)
    3252              :       /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
    3253              :       !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
    3254              :                   sizeof(on)) &&
    3255              : #endif
    3256              : 
    3257              : #if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
    3258              :       /*
    3259              :        * SO_RESUSEADDR is not enabled on Windows because the semantics of
    3260              :        * SO_REUSEADDR on UNIX and Windows is different. On Windows,
    3261              :        * SO_REUSEADDR allows to bind a socket to a port without error even if
    3262              :        * the port is already open by another program. This is not the behavior
    3263              :        * SO_REUSEADDR was designed for, and leads to hard-to-track failure
    3264              :        * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
    3265              :        * SO_EXCLUSIVEADDRUSE is supported and set on a socket.
    3266              :        */
    3267            0 :       !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
    3268              : #endif
    3269              : #endif /* !MG_SOCKET_SIMPLELINK && !MG_LWIP */
    3270              : 
    3271            0 :       !bind(sock, &sa->sa, sa_len) &&
    3272            0 :       (proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
    3273              : #if !defined(MG_SOCKET_SIMPLELINK) && \
    3274              :     !defined(MG_LWIP) /* TODO(rojer): Fix this. */
    3275            0 :     mg_set_non_blocking_mode(sock);
    3276              :     /* In case port was set to 0, get the real port number */
    3277            0 :     (void) getsockname(sock, &sa->sa, &sa_len);
    3278              : #endif
    3279            0 :   } else if (sock != INVALID_SOCKET) {
    3280            0 :     closesocket(sock);
    3281            0 :     sock = INVALID_SOCKET;
    3282              :   }
    3283              : 
    3284            0 :   return sock;
    3285              : }
    3286              : 
    3287            0 : static void mg_write_to_socket(struct mg_connection *nc) {
    3288            0 :   struct mbuf *io = &nc->send_mbuf;
    3289            0 :   int n = 0;
    3290              : 
    3291              : #ifdef MG_LWIP
    3292              :   /* With LWIP we don't know if the socket is ready */
    3293              :   if (io->len == 0) return;
    3294              : #endif
    3295              : 
    3296            0 :   assert(io->len > 0);
    3297              : 
    3298            0 :   if (nc->flags & MG_F_UDP) {
    3299              :     int n =
    3300            0 :         sendto(nc->sock, io->buf, io->len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
    3301            0 :     DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
    3302              :          inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
    3303            0 :     if (n > 0) {
    3304            0 :       mbuf_remove(io, n);
    3305              :     }
    3306            0 :     mg_if_sent_cb(nc, n);
    3307            0 :     return;
    3308              :   }
    3309              : 
    3310              : #ifdef MG_ENABLE_SSL
    3311              :   if (nc->ssl != NULL) {
    3312              :     if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
    3313              :       n = SSL_write(nc->ssl, io->buf, io->len);
    3314              :       DBG(("%p %d bytes -> %d (SSL)", nc, n, nc->sock));
    3315              :       if (n <= 0) {
    3316              :         int ssl_err = mg_ssl_err(nc, n);
    3317              :         if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
    3318              :           return; /* Call us again */
    3319              :         }
    3320              :       } else {
    3321              :         /* Successful SSL operation, clear off SSL wait flags */
    3322              :         nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
    3323              :       }
    3324              :     } else {
    3325              :       mg_ssl_begin(nc);
    3326              :       return;
    3327              :     }
    3328              :   } else
    3329              : #endif
    3330              :   {
    3331            0 :     n = (int) MG_SEND_FUNC(nc->sock, io->buf, io->len, 0);
    3332            0 :     DBG(("%p %d bytes -> %d", nc, n, nc->sock));
    3333              :   }
    3334              : 
    3335            0 :   if (n > 0) {
    3336            0 :     mbuf_remove(io, n);
    3337              :   }
    3338            0 :   mg_if_sent_cb(nc, n);
    3339              : }
    3340              : 
    3341            0 : MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
    3342              :   size_t avail;
    3343            0 :   if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
    3344            0 :   avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
    3345            0 :   return avail > max ? max : avail;
    3346              : }
    3347              : 
    3348            0 : static void mg_read_from_socket(struct mg_connection *conn) {
    3349            0 :   int n = 0;
    3350            0 :   char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
    3351              : 
    3352            0 :   if (buf == NULL) {
    3353            0 :     DBG(("OOM"));
    3354            0 :     return;
    3355              :   }
    3356              : 
    3357              : #ifdef MG_ENABLE_SSL
    3358              :   if (conn->ssl != NULL) {
    3359              :     if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
    3360              :       /* SSL library may have more bytes ready to read then we ask to read.
    3361              :        * Therefore, read in a loop until we read everything. Without the loop,
    3362              :        * we skip to the next select() cycle which can just timeout. */
    3363              :       while ((n = SSL_read(conn->ssl, buf, MG_TCP_RECV_BUFFER_SIZE)) > 0) {
    3364              :         DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock));
    3365              :         mg_if_recv_tcp_cb(conn, buf, n);
    3366              :         buf = NULL;
    3367              :         if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break;
    3368              :         /* buf has been freed, we need a new one. */
    3369              :         buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
    3370              :         if (buf == NULL) break;
    3371              :       }
    3372              :       MG_FREE(buf);
    3373              :       mg_ssl_err(conn, n);
    3374              :     } else {
    3375              :       MG_FREE(buf);
    3376              :       mg_ssl_begin(conn);
    3377              :       return;
    3378              :     }
    3379              :   } else
    3380              : #endif
    3381              :   {
    3382            0 :     n = (int) MG_RECV_FUNC(conn->sock, buf,
    3383              :                            recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
    3384            0 :     if (n > 0) {
    3385            0 :       DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock));
    3386            0 :       mg_if_recv_tcp_cb(conn, buf, n);
    3387              :     } else {
    3388            0 :       MG_FREE(buf);
    3389              :     }
    3390            0 :     if (mg_is_error(n)) {
    3391            0 :       conn->flags |= MG_F_CLOSE_IMMEDIATELY;
    3392              :     }
    3393              :   }
    3394              : }
    3395              : 
    3396            0 : static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa,
    3397              :                        socklen_t *sa_len, char **buf) {
    3398              :   int n;
    3399            0 :   *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
    3400            0 :   if (*buf == NULL) {
    3401            0 :     DBG(("Out of memory"));
    3402            0 :     return -ENOMEM;
    3403              :   }
    3404            0 :   n = recvfrom(nc->sock, *buf, MG_UDP_RECV_BUFFER_SIZE, 0, &sa->sa, sa_len);
    3405            0 :   if (n <= 0) {
    3406            0 :     DBG(("%p recvfrom: %s", nc, strerror(errno)));
    3407            0 :     MG_FREE(*buf);
    3408              :   }
    3409            0 :   return n;
    3410              : }
    3411              : 
    3412            0 : static void mg_handle_udp_read(struct mg_connection *nc) {
    3413            0 :   char *buf = NULL;
    3414              :   union socket_address sa;
    3415            0 :   socklen_t sa_len = sizeof(sa);
    3416            0 :   int n = mg_recvfrom(nc, &sa, &sa_len, &buf);
    3417            0 :   DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
    3418              :        ntohs(nc->sa.sin.sin_port)));
    3419            0 :   mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
    3420            0 : }
    3421              : 
    3422              : #ifdef MG_ENABLE_SSL
    3423              : static int mg_ssl_err(struct mg_connection *conn, int res) {
    3424              :   int ssl_err = SSL_get_error(conn->ssl, res);
    3425              :   DBG(("%p %d -> %d", conn, res, ssl_err));
    3426              :   if (ssl_err == SSL_ERROR_WANT_READ) {
    3427              :     conn->flags |= MG_F_WANT_READ;
    3428              :   } else if (ssl_err == SSL_ERROR_WANT_WRITE) {
    3429              :     conn->flags |= MG_F_WANT_WRITE;
    3430              :   } else {
    3431              :     /* There could be an alert to deliver. Try our best. */
    3432              :     SSL_write(conn->ssl, "", 0);
    3433              :     conn->flags |= MG_F_CLOSE_IMMEDIATELY;
    3434              :   }
    3435              :   return ssl_err;
    3436              : }
    3437              : 
    3438              : static void mg_ssl_begin(struct mg_connection *nc) {
    3439              :   int server_side = (nc->listener != NULL);
    3440              :   int res = server_side ? SSL_accept(nc->ssl) : SSL_connect(nc->ssl);
    3441              :   DBG(("%p %d res %d %d", nc, server_side, res, errno));
    3442              : 
    3443              :   if (res == 1) {
    3444              :     nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
    3445              :     nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
    3446              : 
    3447              :     if (server_side) {
    3448              :       union socket_address sa;
    3449              :       socklen_t sa_len = sizeof(sa);
    3450              :       (void) getpeername(nc->sock, &sa.sa, &sa_len);
    3451              :       mg_if_accept_tcp_cb(nc, &sa, sa_len);
    3452              :     } else {
    3453              :       mg_if_connect_cb(nc, 0);
    3454              :     }
    3455              :   } else {
    3456              :     int ssl_err = mg_ssl_err(nc, res);
    3457              :     if (ssl_err != SSL_ERROR_WANT_READ && ssl_err != SSL_ERROR_WANT_WRITE) {
    3458              :       if (!server_side) {
    3459              :         mg_if_connect_cb(nc, ssl_err);
    3460              :       }
    3461              :       nc->flags |= MG_F_CLOSE_IMMEDIATELY;
    3462              :     }
    3463              :   }
    3464              : }
    3465              : #endif /* MG_ENABLE_SSL */
    3466              : 
    3467              : #define _MG_F_FD_CAN_READ 1
    3468              : #define _MG_F_FD_CAN_WRITE 1 << 1
    3469              : #define _MG_F_FD_ERROR 1 << 2
    3470              : 
    3471            0 : void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
    3472            0 :   DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
    3473              :        fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
    3474              : 
    3475            0 :   if (nc->flags & MG_F_CONNECTING) {
    3476            0 :     if (fd_flags != 0) {
    3477            0 :       int err = 0;
    3478              : #if !defined(MG_SOCKET_SIMPLELINK) && !defined(MG_ESP8266)
    3479            0 :       if (!(nc->flags & MG_F_UDP)) {
    3480            0 :         socklen_t len = sizeof(err);
    3481              :         int ret =
    3482            0 :             getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
    3483            0 :         if (ret != 0) err = 1;
    3484              :       }
    3485              : #else
    3486              : /* On SimpleLink and ESP8266 we use blocking connect. If we got as far as
    3487              :  * this, it means connect() was successful.
    3488              :  * TODO(rojer): Figure out why it fails where blocking succeeds.
    3489              :  */
    3490              : #endif
    3491              : #ifdef MG_ENABLE_SSL
    3492              :       if (nc->ssl != NULL && err == 0) {
    3493              :         SSL_set_fd(nc->ssl, nc->sock);
    3494              :         mg_ssl_begin(nc);
    3495              :       } else {
    3496              :         mg_if_connect_cb(nc, err);
    3497              :       }
    3498              : #else
    3499            0 :       mg_if_connect_cb(nc, err);
    3500              : #endif
    3501            0 :     } else if (nc->err != 0) {
    3502            0 :       mg_if_connect_cb(nc, nc->err);
    3503              :     }
    3504              :   }
    3505              : 
    3506            0 :   if (fd_flags & _MG_F_FD_CAN_READ) {
    3507            0 :     if (nc->flags & MG_F_UDP) {
    3508            0 :       mg_handle_udp_read(nc);
    3509              :     } else {
    3510            0 :       if (nc->flags & MG_F_LISTENING) {
    3511              :         /*
    3512              :          * We're not looping here, and accepting just one connection at
    3513              :          * a time. The reason is that eCos does not respect non-blocking
    3514              :          * flag on a listening socket and hangs in a loop.
    3515              :          */
    3516            0 :         if (fd_flags & _MG_F_FD_CAN_READ) mg_accept_conn(nc);
    3517            0 :         return;
    3518              :       } else {
    3519            0 :         mg_read_from_socket(nc);
    3520              :       }
    3521              :     }
    3522            0 :     if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return;
    3523              :   }
    3524              : 
    3525            0 :   if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
    3526            0 :     mg_write_to_socket(nc);
    3527              :   }
    3528              : 
    3529            0 :   if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) {
    3530            0 :     mg_if_poll(nc, now);
    3531              :   }
    3532            0 :   mg_if_timer(nc, now);
    3533              : 
    3534            0 :   DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
    3535              :        (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
    3536              : }
    3537              : 
    3538              : #ifndef MG_DISABLE_SOCKETPAIR
    3539            0 : static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
    3540              :   struct ctl_msg ctl_msg;
    3541              :   int len =
    3542            0 :       (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
    3543            0 :   size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
    3544            0 :   DBG(("read %d from ctl socket", len));
    3545              :   (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
    3546            0 :   if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
    3547              :     struct mg_connection *nc;
    3548            0 :     for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
    3549            0 :       ctl_msg.callback(nc, MG_EV_POLL, ctl_msg.message);
    3550              :     }
    3551              :   }
    3552            0 : }
    3553              : #endif
    3554              : 
    3555              : /* Associate a socket to a connection. */
    3556            0 : void mg_sock_set(struct mg_connection *nc, sock_t sock) {
    3557            0 :   mg_set_non_blocking_mode(sock);
    3558            0 :   mg_set_close_on_exec(sock);
    3559            0 :   nc->sock = sock;
    3560            0 :   DBG(("%p %d", nc, sock));
    3561            0 : }
    3562              : 
    3563            0 : void mg_ev_mgr_init(struct mg_mgr *mgr) {
    3564              :   (void) mgr;
    3565            0 :   DBG(("%p using select()", mgr));
    3566              : #ifndef MG_DISABLE_SOCKETPAIR
    3567              :   do {
    3568            0 :     mg_socketpair(mgr->ctl, SOCK_DGRAM);
    3569            0 :   } while (mgr->ctl[0] == INVALID_SOCKET);
    3570              : #endif
    3571            0 : }
    3572              : 
    3573            0 : void mg_ev_mgr_free(struct mg_mgr *mgr) {
    3574              :   (void) mgr;
    3575            0 : }
    3576              : 
    3577            0 : void mg_ev_mgr_add_conn(struct mg_connection *nc) {
    3578              :   (void) nc;
    3579            0 : }
    3580              : 
    3581            0 : void mg_ev_mgr_remove_conn(struct mg_connection *nc) {
    3582              :   (void) nc;
    3583            0 : }
    3584              : 
    3585            0 : void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
    3586            0 :   if (sock != INVALID_SOCKET) {
    3587            0 :     FD_SET(sock, set);
    3588            0 :     if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
    3589            0 :       *max_fd = sock;
    3590              :     }
    3591              :   }
    3592            0 : }
    3593              : 
    3594            0 : time_t mg_mgr_poll(struct mg_mgr *mgr, int timeout_ms) {
    3595            0 :   double now = mg_time();
    3596              :   double min_timer;
    3597              :   struct mg_connection *nc, *tmp;
    3598              :   struct timeval tv;
    3599              :   fd_set read_set, write_set, err_set;
    3600            0 :   sock_t max_fd = INVALID_SOCKET;
    3601            0 :   int num_fds, num_ev, num_timers = 0;
    3602              : 
    3603            0 :   FD_ZERO(&read_set);
    3604            0 :   FD_ZERO(&write_set);
    3605            0 :   FD_ZERO(&err_set);
    3606              : #ifndef MG_DISABLE_SOCKETPAIR
    3607            0 :   mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
    3608              : #endif
    3609              : 
    3610              :   /*
    3611              :    * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
    3612              :    * e.g. timer-only "connections".
    3613              :    */
    3614            0 :   min_timer = 0;
    3615            0 :   for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
    3616            0 :     tmp = nc->next;
    3617              : 
    3618              :     //printf("nc %p -> mg_mgr_poll, mgr %p %p, pd %p, fp %p\n", nc, nc->mgr, mgr, nc->proto_data, (nc->proto_data?*(FILE**)nc->proto_data:NULL));
    3619              : 
    3620            0 :     if (nc->sock != INVALID_SOCKET) {
    3621            0 :       num_fds++;
    3622              : 
    3623            0 :       if (!(nc->flags & MG_F_WANT_WRITE) &&
    3624            0 :           nc->recv_mbuf.len < nc->recv_mbuf_limit &&
    3625            0 :           (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
    3626            0 :         mg_add_to_set(nc->sock, &read_set, &max_fd);
    3627              :       }
    3628              : 
    3629            0 :       if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
    3630            0 :           (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
    3631            0 :         mg_add_to_set(nc->sock, &write_set, &max_fd);
    3632            0 :         mg_add_to_set(nc->sock, &err_set, &max_fd);
    3633              :       }
    3634              :     }
    3635              : 
    3636            0 :     if (nc->ev_timer_time > 0) {
    3637            0 :       if (num_timers == 0 || nc->ev_timer_time < min_timer) {
    3638            0 :         min_timer = nc->ev_timer_time;
    3639              :       }
    3640            0 :       num_timers++;
    3641              :     }
    3642              :   }
    3643              : 
    3644              :   /*
    3645              :    * If there is a timer to be fired earlier than the requested timeout,
    3646              :    * adjust the timeout.
    3647              :    */
    3648            0 :   if (num_timers > 0) {
    3649            0 :     double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
    3650            0 :     if (timer_timeout_ms < timeout_ms) {
    3651            0 :       timeout_ms = timer_timeout_ms;
    3652              :     }
    3653              :   }
    3654            0 :   if (timeout_ms < 0) timeout_ms = 0;
    3655              : 
    3656            0 :   tv.tv_sec = timeout_ms / 1000;
    3657            0 :   tv.tv_usec = (timeout_ms % 1000) * 1000;
    3658              : 
    3659            0 :   num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
    3660            0 :   now = mg_time();
    3661            0 :   DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds,
    3662              :        timeout_ms));
    3663              : 
    3664              : #ifndef MG_DISABLE_SOCKETPAIR
    3665            0 :   if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET &&
    3666            0 :       FD_ISSET(mgr->ctl[1], &read_set)) {
    3667            0 :     mg_mgr_handle_ctl_sock(mgr);
    3668              :   }
    3669              : #endif
    3670              : 
    3671            0 :   for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
    3672            0 :     int fd_flags = 0;
    3673            0 :     if (nc->sock != INVALID_SOCKET) {
    3674            0 :       if (num_ev > 0) {
    3675            0 :         fd_flags = (FD_ISSET(nc->sock, &read_set) &&
    3676            0 :                             (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
    3677            0 :                         ? _MG_F_FD_CAN_READ
    3678            0 :                         : 0) |
    3679            0 :                    (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
    3680            0 :                    (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
    3681              :       }
    3682              : #ifdef MG_SOCKET_SIMPLELINK
    3683              :       /* SimpleLink does not report UDP sockets as writeable. */
    3684              :       if (nc->flags & MG_F_UDP &&
    3685              :           (nc->send_mbuf.len > 0 || nc->flags & MG_F_CONNECTING)) {
    3686              :         fd_flags |= _MG_F_FD_CAN_WRITE;
    3687              :       }
    3688              : #endif
    3689              : #ifdef MG_LWIP
    3690              :       /* With LWIP socket emulation layer, we don't get write events */
    3691              :       fd_flags |= _MG_F_FD_CAN_WRITE;
    3692              : #endif
    3693              :     }
    3694            0 :     tmp = nc->next;
    3695            0 :     mg_mgr_handle_conn(nc, fd_flags, now);
    3696              :   }
    3697              : 
    3698            0 :   for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
    3699            0 :     tmp = nc->next;
    3700            0 :     if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
    3701            0 :         (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
    3702              :       //printf("nc %p -> mg_close_conn, mgr %p %p, pd %p, fp %p\n", nc, nc->mgr, mgr, nc->proto_data, (nc->proto_data?*(FILE**)nc->proto_data:NULL));
    3703            0 :       mg_close_conn(nc);
    3704              :     }
    3705              :   }
    3706              : 
    3707            0 :   return now;
    3708              : }
    3709              : 
    3710              : #ifndef MG_DISABLE_SOCKETPAIR
    3711            0 : int mg_socketpair(sock_t sp[2], int sock_type) {
    3712              :   union socket_address sa;
    3713              :   sock_t sock;
    3714            0 :   socklen_t len = sizeof(sa.sin);
    3715            0 :   int ret = 0;
    3716              : 
    3717            0 :   sock = sp[0] = sp[1] = INVALID_SOCKET;
    3718              : 
    3719            0 :   (void) memset(&sa, 0, sizeof(sa));
    3720            0 :   sa.sin.sin_family = AF_INET;
    3721            0 :   sa.sin.sin_port = htons(0);
    3722            0 :   sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
    3723              : 
    3724            0 :   if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
    3725            0 :   } else if (bind(sock, &sa.sa, len) != 0) {
    3726            0 :   } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
    3727            0 :   } else if (getsockname(sock, &sa.sa, &len) != 0) {
    3728            0 :   } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
    3729            0 :   } else if (connect(sp[0], &sa.sa, len) != 0) {
    3730            0 :   } else if (sock_type == SOCK_DGRAM &&
    3731            0 :              (getsockname(sp[0], &sa.sa, &len) != 0 ||
    3732            0 :               connect(sock, &sa.sa, len) != 0)) {
    3733            0 :   } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock
    3734            0 :                                                : accept(sock, &sa.sa, &len))) ==
    3735              :              INVALID_SOCKET) {
    3736              :   } else {
    3737            0 :     mg_set_close_on_exec(sp[0]);
    3738            0 :     mg_set_close_on_exec(sp[1]);
    3739            0 :     if (sock_type == SOCK_STREAM) closesocket(sock);
    3740            0 :     ret = 1;
    3741              :   }
    3742              : 
    3743            0 :   if (!ret) {
    3744            0 :     if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
    3745            0 :     if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
    3746            0 :     if (sock != INVALID_SOCKET) closesocket(sock);
    3747            0 :     sock = sp[0] = sp[1] = INVALID_SOCKET;
    3748              :   }
    3749              : 
    3750            0 :   return ret;
    3751              : }
    3752              : #endif /* MG_DISABLE_SOCKETPAIR */
    3753              : 
    3754              : #ifndef MG_SOCKET_SIMPLELINK
    3755            0 : static void mg_sock_get_addr(sock_t sock, int remote,
    3756              :                              union socket_address *sa) {
    3757            0 :   socklen_t slen = sizeof(*sa);
    3758            0 :   memset(sa, 0, slen);
    3759            0 :   if (remote) {
    3760            0 :     getpeername(sock, &sa->sa, &slen);
    3761              :   } else {
    3762            0 :     getsockname(sock, &sa->sa, &slen);
    3763              :   }
    3764            0 : }
    3765              : 
    3766            0 : void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
    3767              :   union socket_address sa;
    3768            0 :   mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
    3769            0 :   mg_sock_addr_to_str(&sa, buf, len, flags);
    3770            0 : }
    3771              : #endif
    3772              : 
    3773            0 : void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
    3774              :                          union socket_address *sa) {
    3775              : #ifndef MG_SOCKET_SIMPLELINK
    3776            0 :   mg_sock_get_addr(nc->sock, remote, sa);
    3777              : #else
    3778              :   /* SimpleLink does not provide a way to get socket's peer address after
    3779              :    * accept or connect. Address hould have been preserved in the connection,
    3780              :    * so we do our best here by using it. */
    3781              :   if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
    3782              : #endif
    3783            0 : }
    3784              : 
    3785              : #endif /* !MG_DISABLE_SOCKET_IF */
    3786              : #ifdef MG_MODULE_LINES
    3787              : #line 1 "./src/multithreading.c"
    3788              : #endif
    3789              : /*
    3790              :  * Copyright (c) 2014 Cesanta Software Limited
    3791              :  * All rights reserved
    3792              :  */
    3793              : 
    3794              : /* Amalgamated: #include "mongoose/src/internal.h" */
    3795              : /* Amalgamated: #include "mongoose/src/util.h" */
    3796              : 
    3797              : #ifdef MG_ENABLE_THREADS
    3798              : 
    3799              : static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p);
    3800              : 
    3801              : /*
    3802              :  * This thread function executes user event handler.
    3803              :  * It runs an event manager that has only one connection, until that
    3804              :  * connection is alive.
    3805              :  */
    3806            0 : static void *per_connection_thread_function(void *param) {
    3807            0 :   struct mg_connection *c = (struct mg_connection *) param;
    3808              :   struct mg_mgr m;
    3809              : 
    3810            0 :   mg_mgr_init(&m, NULL);
    3811            0 :   mg_add_conn(&m, c);
    3812            0 :   while (m.active_connections != NULL) {
    3813            0 :     mg_mgr_poll(&m, 1000);
    3814              :   }
    3815            0 :   mg_mgr_free(&m);
    3816              : 
    3817            0 :   return param;
    3818              : }
    3819              : 
    3820            0 : static void link_conns(struct mg_connection *c1, struct mg_connection *c2) {
    3821            0 :   c1->priv_2 = c2;
    3822            0 :   c2->priv_2 = c1;
    3823            0 : }
    3824              : 
    3825            0 : static void unlink_conns(struct mg_connection *c) {
    3826            0 :   struct mg_connection *peer = (struct mg_connection *) c->priv_2;
    3827            0 :   if (peer != NULL) {
    3828            0 :     peer->flags |= MG_F_SEND_AND_CLOSE;
    3829            0 :     peer->priv_2 = NULL;
    3830              :   }
    3831            0 :   c->priv_2 = NULL;
    3832            0 : }
    3833              : 
    3834            0 : static void forwarder_ev_handler(struct mg_connection *c, int ev, void *p) {
    3835              :   (void) p;
    3836            0 :   if (ev == MG_EV_RECV && c->priv_2) {
    3837            0 :     mg_forward(c, (struct mg_connection *) c->priv_2);
    3838            0 :   } else if (ev == MG_EV_CLOSE) {
    3839            0 :     unlink_conns(c);
    3840              :   }
    3841            0 : }
    3842              : 
    3843            0 : static void spawn_handling_thread(struct mg_connection *nc) {
    3844              :   struct mg_mgr dummy;
    3845              :   sock_t sp[2];
    3846              :   struct mg_connection *c[2];
    3847              : 
    3848              :   /*
    3849              :    * Create a socket pair, and wrap each socket into the connection with
    3850              :    * dummy event manager.
    3851              :    * c[0] stays in this thread, c[1] goes to another thread.
    3852              :    */
    3853            0 :   mg_socketpair(sp, SOCK_STREAM);
    3854            0 :   memset(&dummy, 0, sizeof(dummy));
    3855            0 :   c[0] = mg_add_sock(&dummy, sp[0], forwarder_ev_handler);
    3856            0 :   c[1] = mg_add_sock(&dummy, sp[1], nc->listener->priv_1.f);
    3857              : 
    3858              :   /* Interlink client connection with c[0] */
    3859            0 :   link_conns(c[0], nc);
    3860              : 
    3861              :   /*
    3862              :    * Switch c[0] manager from the dummy one to the real one. c[1] manager
    3863              :    * will be set in another thread, allocated on stack of that thread.
    3864              :    */
    3865            0 :   mg_add_conn(nc->mgr, c[0]);
    3866              : 
    3867              :   /*
    3868              :    * Dress c[1] as nc.
    3869              :    * TODO(lsm): code in accept_conn() looks similar. Refactor.
    3870              :    */
    3871            0 :   c[1]->listener = nc->listener;
    3872            0 :   c[1]->proto_handler = nc->proto_handler;
    3873            0 :   c[1]->proto_data = nc->proto_data;
    3874            0 :   c[1]->user_data = nc->user_data;
    3875              : 
    3876              :   //printf("dup proto_data %p, nc %p\n", nc->proto_data, nc);
    3877              : 
    3878              :   // fix https://github.com/cesanta/mongoose/issues/646
    3879            0 :   nc->proto_data = NULL;
    3880              : 
    3881            0 :   mg_start_thread(per_connection_thread_function, c[1]);
    3882            0 : }
    3883              : 
    3884            0 : static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p) {
    3885              :   (void) p;
    3886            0 :   if (ev == MG_EV_ACCEPT) {
    3887            0 :     spawn_handling_thread(c);
    3888            0 :     c->handler = forwarder_ev_handler;
    3889              :   }
    3890            0 : }
    3891              : 
    3892            0 : void mg_enable_multithreading(struct mg_connection *nc) {
    3893              :   /* Wrap user event handler into our multithreaded_ev_handler */
    3894            0 :   nc->priv_1.f = nc->handler;
    3895            0 :   nc->handler = multithreaded_ev_handler;
    3896            0 : }
    3897              : #endif
    3898              : #ifdef MG_MODULE_LINES
    3899              : #line 1 "./src/uri.c"
    3900              : #endif
    3901              : /*
    3902              :  * Copyright (c) 2014 Cesanta Software Limited
    3903              :  * All rights reserved
    3904              :  */
    3905              : 
    3906              : /* Amalgamated: #include "mongoose/src/internal.h" */
    3907              : /* Amalgamated: #include "mongoose/src/uri.h" */
    3908              : 
    3909              : /*
    3910              :  * scan string until `sep`, keeping track of component boundaries in `res`.
    3911              :  *
    3912              :  * `p` will point to the char after the separator or it will be `end`.
    3913              :  */
    3914            0 : static void parse_uri_component(const char **p, const char *end, char sep,
    3915              :                                 struct mg_str *res) {
    3916            0 :   res->p = *p;
    3917            0 :   for (; *p < end; (*p)++) {
    3918            0 :     if (**p == sep) {
    3919            0 :       break;
    3920              :     }
    3921              :   }
    3922            0 :   res->len = (*p) - res->p;
    3923            0 :   if (*p < end) (*p)++;
    3924            0 : }
    3925              : 
    3926            0 : int mg_parse_uri(struct mg_str uri, struct mg_str *scheme,
    3927              :                  struct mg_str *user_info, struct mg_str *host,
    3928              :                  unsigned int *port, struct mg_str *path, struct mg_str *query,
    3929              :                  struct mg_str *fragment) {
    3930            0 :   struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
    3931            0 :                 rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
    3932            0 :   unsigned int rport = 0;
    3933              :   enum {
    3934              :     P_START,
    3935              :     P_SCHEME_OR_PORT,
    3936              :     P_USER_INFO,
    3937              :     P_HOST,
    3938              :     P_PORT,
    3939              :     P_REST
    3940            0 :   } state = P_START;
    3941              : 
    3942            0 :   const char *p = uri.p, *end = p + uri.len;
    3943            0 :   while (p < end) {
    3944            0 :     switch (state) {
    3945            0 :       case P_START:
    3946              :         /*
    3947              :          * expecting on of:
    3948              :          * - `scheme://xxxx`
    3949              :          * - `xxxx:port`
    3950              :          * - `xxxx/path`
    3951              :          */
    3952            0 :         for (; p < end; p++) {
    3953            0 :           if (*p == ':') {
    3954            0 :             state = P_SCHEME_OR_PORT;
    3955            0 :             break;
    3956            0 :           } else if (*p == '/') {
    3957            0 :             state = P_REST;
    3958            0 :             break;
    3959              :           }
    3960              :         }
    3961            0 :         if (state == P_START || state == P_REST) {
    3962            0 :           rhost.p = uri.p;
    3963            0 :           rhost.len = p - uri.p;
    3964              :         }
    3965            0 :         break;
    3966            0 :       case P_SCHEME_OR_PORT:
    3967            0 :         if (end - p >= 3 && memcmp(p, "://", 3) == 0) {
    3968            0 :           rscheme.p = uri.p;
    3969            0 :           rscheme.len = p - uri.p;
    3970            0 :           state = P_USER_INFO;
    3971            0 :           p += 2; /* point to last separator char */
    3972              :         } else {
    3973            0 :           rhost.p = uri.p;
    3974            0 :           rhost.len = p - uri.p;
    3975            0 :           state = P_PORT;
    3976              :         }
    3977            0 :         break;
    3978            0 :       case P_USER_INFO:
    3979            0 :         p++;
    3980            0 :         ruser_info.p = p;
    3981            0 :         for (; p < end; p++) {
    3982            0 :           if (*p == '@') {
    3983            0 :             state = P_HOST;
    3984            0 :             break;
    3985            0 :           } else if (*p == '/') {
    3986            0 :             break;
    3987              :           }
    3988              :         }
    3989            0 :         if (p == end || *p == '/') {
    3990              :           /* backtrack and parse as host */
    3991            0 :           state = P_HOST;
    3992            0 :           p = ruser_info.p;
    3993              :         }
    3994            0 :         ruser_info.len = p - ruser_info.p;
    3995            0 :         break;
    3996            0 :       case P_HOST:
    3997            0 :         if (*p == '@') p++;
    3998            0 :         rhost.p = p;
    3999            0 :         for (; p < end; p++) {
    4000            0 :           if (*p == ':') {
    4001            0 :             state = P_PORT;
    4002            0 :             break;
    4003            0 :           } else if (*p == '/') {
    4004            0 :             state = P_REST;
    4005            0 :             break;
    4006              :           }
    4007              :         }
    4008            0 :         rhost.len = p - rhost.p;
    4009            0 :         break;
    4010            0 :       case P_PORT:
    4011            0 :         p++;
    4012            0 :         for (; p < end; p++) {
    4013            0 :           if (*p == '/') {
    4014            0 :             state = P_REST;
    4015            0 :             break;
    4016              :           }
    4017            0 :           rport *= 10;
    4018            0 :           rport += *p - '0';
    4019              :         }
    4020            0 :         break;
    4021            0 :       case P_REST:
    4022              :         /* `p` points to separator. `path` includes the separator */
    4023            0 :         parse_uri_component(&p, end, '?', &rpath);
    4024            0 :         parse_uri_component(&p, end, '#', &rquery);
    4025            0 :         parse_uri_component(&p, end, '\0', &rfragment);
    4026            0 :         break;
    4027              :     }
    4028              :   }
    4029              : 
    4030            0 :   if (scheme != 0) *scheme = rscheme;
    4031            0 :   if (user_info != 0) *user_info = ruser_info;
    4032            0 :   if (host != 0) *host = rhost;
    4033            0 :   if (port != 0) *port = rport;
    4034            0 :   if (path != 0) *path = rpath;
    4035            0 :   if (query != 0) *query = rquery;
    4036            0 :   if (fragment != 0) *fragment = rfragment;
    4037              : 
    4038            0 :   return 0;
    4039              : }
    4040              : 
    4041              : /* Normalize the URI path. Remove/resolve "." and "..". */
    4042            0 : int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) {
    4043            0 :   const char *s = in->p, *se = s + in->len;
    4044            0 :   char *cp = (char *) out->p, *d;
    4045              : 
    4046            0 :   if (in->len == 0 || *s != '/') {
    4047            0 :     out->len = 0;
    4048            0 :     return 0;
    4049              :   }
    4050              : 
    4051            0 :   d = cp;
    4052              : 
    4053            0 :   while (s < se) {
    4054            0 :     const char *next = s;
    4055              :     struct mg_str component;
    4056            0 :     parse_uri_component(&next, se, '/', &component);
    4057            0 :     if (mg_vcmp(&component, ".") == 0) {
    4058              :       /* Yum. */
    4059            0 :     } else if (mg_vcmp(&component, "..") == 0) {
    4060              :       /* Backtrack to previous slash. */
    4061            0 :       if (d > cp + 1 && *(d - 1) == '/') d--;
    4062            0 :       while (d > cp && *(d - 1) != '/') d--;
    4063              :     } else {
    4064            0 :       memmove(d, s, next - s);
    4065            0 :       d += next - s;
    4066              :     }
    4067            0 :     s = next;
    4068              :   }
    4069            0 :   if (d == cp) *d++ = '/';
    4070              : 
    4071            0 :   out->p = cp;
    4072            0 :   out->len = d - cp;
    4073            0 :   return 1;
    4074              : }
    4075              : #ifdef MG_MODULE_LINES
    4076              : #line 1 "./src/http.c"
    4077              : #endif
    4078              : /*
    4079              :  * Copyright (c) 2014 Cesanta Software Limited
    4080              :  * All rights reserved
    4081              :  */
    4082              : 
    4083              : #ifndef MG_DISABLE_HTTP
    4084              : 
    4085              : /* Amalgamated: #include "mongoose/src/internal.h" */
    4086              : /* Amalgamated: #include "mongoose/src/util.h" */
    4087              : /* Amalgamated: #include "common/sha1.h" */
    4088              : /* Amalgamated: #include "common/md5.h" */
    4089              : 
    4090              : #ifndef MG_DISABLE_HTTP_WEBSOCKET
    4091              : #define MG_WS_NO_HOST_HEADER_MAGIC ((char *) 0x1)
    4092              : #endif
    4093              : 
    4094              : enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT };
    4095              : 
    4096              : struct mg_http_proto_data_file {
    4097              :   FILE *fp;     /* Opened file. */
    4098              :   int64_t cl;   /* Content-Length. How many bytes to send. */
    4099              :   int64_t sent; /* How many bytes have been already sent. */
    4100              :   enum mg_http_proto_data_type type;
    4101              : };
    4102              : 
    4103              : struct mg_http_proto_data_cgi {
    4104              :   struct mg_connection *cgi_nc;
    4105              : };
    4106              : 
    4107              : struct mg_http_proto_data_chuncked {
    4108              :   int64_t body_len; /* How many bytes of chunked body was reassembled. */
    4109              : };
    4110              : 
    4111              : struct mg_http_endpoint {
    4112              :   struct mg_http_endpoint *next;
    4113              :   const char *name;
    4114              :   size_t name_len;
    4115              :   mg_event_handler_t handler;
    4116              : };
    4117              : 
    4118              : enum mg_http_multipart_stream_state {
    4119              :   MPS_BEGIN,
    4120              :   MPS_WAITING_FOR_BOUNDARY,
    4121              :   MPS_WAITING_FOR_CHUNK,
    4122              :   MPS_GOT_CHUNK,
    4123              :   MPS_GOT_BOUNDARY,
    4124              :   MPS_FINALIZE,
    4125              :   MPS_FINISHED
    4126              : };
    4127              : 
    4128              : struct mg_http_multipart_stream {
    4129              :   const char *boundary;
    4130              :   int boundary_len;
    4131              :   const char *var_name;
    4132              :   const char *file_name;
    4133              :   void *user_data;
    4134              :   int prev_io_len;
    4135              :   enum mg_http_multipart_stream_state state;
    4136              :   int processing_part;
    4137              : };
    4138              : 
    4139              : struct mg_http_proto_data {
    4140              : #ifndef MG_DISABLE_FILESYSTEM
    4141              :   struct mg_http_proto_data_file file;
    4142              : #endif
    4143              : #ifndef MG_DISABLE_CGI
    4144              :   struct mg_http_proto_data_cgi cgi;
    4145              : #endif
    4146              : #ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
    4147              :   struct mg_http_multipart_stream mp_stream;
    4148              : #endif
    4149              :   struct mg_http_proto_data_chuncked chunk;
    4150              :   struct mg_http_endpoint *endpoints;
    4151              :   mg_event_handler_t endpoint_handler;
    4152              : };
    4153              : 
    4154              : static void mg_http_conn_destructor(void *proto_data);
    4155              : 
    4156            0 : static struct mg_http_proto_data *mg_http_get_proto_data(
    4157              :     struct mg_connection *c) {
    4158            0 :   if (c->proto_data == NULL) {
    4159            0 :     c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
    4160            0 :     c->proto_data_destructor = mg_http_conn_destructor;
    4161              :     //printf("conn_new, pd %p, fp %p\n", c->proto_data, (c->proto_data?*(FILE**)c->proto_data:NULL));
    4162              :   }
    4163              : 
    4164              :   //printf("nc %p -> get_proto_data, pd %p, fp %p\n", c, c->proto_data, (c->proto_data?*(FILE**)c->proto_data:NULL));
    4165              : 
    4166            0 :   return (struct mg_http_proto_data *) c->proto_data;
    4167              : }
    4168              : 
    4169              : #ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
    4170              : static void mg_http_free_proto_data_mp_stream(
    4171              :     struct mg_http_multipart_stream *mp) {
    4172              :   free((void *) mp->boundary);
    4173              :   mp->boundary = NULL;
    4174              :   free((void *) mp->var_name);
    4175              :   mp->var_name = NULL;
    4176              :   free((void *) mp->file_name);
    4177              :   mp->file_name = NULL;
    4178              : }
    4179              : #endif
    4180              : 
    4181              : #ifndef MG_DISABLE_FILESYSTEM
    4182            0 : static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) {
    4183            0 :   if (d != NULL) {
    4184            0 :     if (d->fp != NULL) {
    4185            0 :       fclose(d->fp);
    4186              :     }
    4187            0 :     memset(d, 0, sizeof(struct mg_http_proto_data_file));
    4188              :   }
    4189            0 : }
    4190              : #endif
    4191              : 
    4192              : #ifndef MG_DISABLE_CGI
    4193              : static void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
    4194              :   if (d != NULL) {
    4195              :     if (d->cgi_nc != NULL) d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
    4196              :     memset(d, 0, sizeof(struct mg_http_proto_data_cgi));
    4197              :   }
    4198              : }
    4199              : #endif
    4200              : 
    4201            0 : static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) {
    4202            0 :   struct mg_http_endpoint *current = *ep;
    4203              : 
    4204            0 :   while (current != NULL) {
    4205            0 :     struct mg_http_endpoint *tmp = current->next;
    4206            0 :     free((void *) current->name);
    4207            0 :     free(current);
    4208            0 :     current = tmp;
    4209              :   }
    4210              : 
    4211            0 :   ep = NULL;
    4212            0 : }
    4213              : 
    4214            0 : static void mg_http_conn_destructor(void *proto_data) {
    4215            0 :   struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data;
    4216              :   //printf("conn_destructor, pd %p, fp %p\n", proto_data, (proto_data?*(FILE**)proto_data:NULL));
    4217              : #ifndef MG_DISABLE_FILESYSTEM
    4218            0 :   mg_http_free_proto_data_file(&pd->file);
    4219              : #endif
    4220              : #ifndef MG_DISABLE_CGI
    4221              :   mg_http_free_proto_data_cgi(&pd->cgi);
    4222              : #endif
    4223              : #ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
    4224              :   mg_http_free_proto_data_mp_stream(&pd->mp_stream);
    4225              : #endif
    4226            0 :   mg_http_free_proto_data_endpoints(&pd->endpoints);
    4227            0 :   free(proto_data);
    4228            0 : }
    4229              : 
    4230              : /*
    4231              :  * This structure helps to create an environment for the spawned CGI program.
    4232              :  * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
    4233              :  * last element must be NULL.
    4234              :  * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
    4235              :  * strings must reside in a contiguous buffer. The end of the buffer is
    4236              :  * marked by two '\0' characters.
    4237              :  * We satisfy both worlds: we create an envp array (which is vars), all
    4238              :  * entries are actually pointers inside buf.
    4239              :  */
    4240              : struct mg_cgi_env_block {
    4241              :   struct mg_connection *nc;
    4242              :   char buf[MG_CGI_ENVIRONMENT_SIZE];       /* Environment buffer */
    4243              :   const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
    4244              :   int len;                                 /* Space taken */
    4245              :   int nvars;                               /* Number of variables in envp[] */
    4246              : };
    4247              : 
    4248              : #define MIME_ENTRY(_ext, _type) \
    4249              :   { _ext, sizeof(_ext) - 1, _type }
    4250              : static const struct {
    4251              :   const char *extension;
    4252              :   size_t ext_len;
    4253              :   const char *mime_type;
    4254              : } mg_static_builtin_mime_types[] = {
    4255              :     MIME_ENTRY("html", "text/html"),
    4256              :     MIME_ENTRY("html", "text/html"),
    4257              :     MIME_ENTRY("htm", "text/html"),
    4258              :     MIME_ENTRY("shtm", "text/html"),
    4259              :     MIME_ENTRY("shtml", "text/html"),
    4260              :     MIME_ENTRY("css", "text/css"),
    4261              :     MIME_ENTRY("js", "application/x-javascript"),
    4262              :     MIME_ENTRY("ico", "image/x-icon"),
    4263              :     MIME_ENTRY("gif", "image/gif"),
    4264              :     MIME_ENTRY("jpg", "image/jpeg"),
    4265              :     MIME_ENTRY("jpeg", "image/jpeg"),
    4266              :     MIME_ENTRY("png", "image/png"),
    4267              :     MIME_ENTRY("svg", "image/svg+xml"),
    4268              :     MIME_ENTRY("txt", "text/plain"),
    4269              :     MIME_ENTRY("torrent", "application/x-bittorrent"),
    4270              :     MIME_ENTRY("wav", "audio/x-wav"),
    4271              :     MIME_ENTRY("mp3", "audio/x-mp3"),
    4272              :     MIME_ENTRY("mid", "audio/mid"),
    4273              :     MIME_ENTRY("m3u", "audio/x-mpegurl"),
    4274              :     MIME_ENTRY("ogg", "application/ogg"),
    4275              :     MIME_ENTRY("ram", "audio/x-pn-realaudio"),
    4276              :     MIME_ENTRY("xml", "text/xml"),
    4277              :     MIME_ENTRY("ttf", "application/x-font-ttf"),
    4278              :     MIME_ENTRY("json", "application/json"),
    4279              :     MIME_ENTRY("xslt", "application/xml"),
    4280              :     MIME_ENTRY("xsl", "application/xml"),
    4281              :     MIME_ENTRY("ra", "audio/x-pn-realaudio"),
    4282              :     MIME_ENTRY("doc", "application/msword"),
    4283              :     MIME_ENTRY("exe", "application/octet-stream"),
    4284              :     MIME_ENTRY("zip", "application/x-zip-compressed"),
    4285              :     MIME_ENTRY("xls", "application/excel"),
    4286              :     MIME_ENTRY("tgz", "application/x-tar-gz"),
    4287              :     MIME_ENTRY("tar", "application/x-tar"),
    4288              :     MIME_ENTRY("gz", "application/x-gunzip"),
    4289              :     MIME_ENTRY("arj", "application/x-arj-compressed"),
    4290              :     MIME_ENTRY("rar", "application/x-rar-compressed"),
    4291              :     MIME_ENTRY("rtf", "application/rtf"),
    4292              :     MIME_ENTRY("pdf", "application/pdf"),
    4293              :     MIME_ENTRY("swf", "application/x-shockwave-flash"),
    4294              :     MIME_ENTRY("mpg", "video/mpeg"),
    4295              :     MIME_ENTRY("webm", "video/webm"),
    4296              :     MIME_ENTRY("mpeg", "video/mpeg"),
    4297              :     MIME_ENTRY("mov", "video/quicktime"),
    4298              :     MIME_ENTRY("mp4", "video/mp4"),
    4299              :     MIME_ENTRY("m4v", "video/x-m4v"),
    4300              :     MIME_ENTRY("asf", "video/x-ms-asf"),
    4301              :     MIME_ENTRY("avi", "video/x-msvideo"),
    4302              :     MIME_ENTRY("bmp", "image/bmp"),
    4303              :     {NULL, 0, NULL}};
    4304              : 
    4305              : #ifndef MG_DISABLE_FILESYSTEM
    4306              : 
    4307              : #ifndef MG_DISABLE_DAV
    4308            0 : static int mg_mkdir(const char *path, uint32_t mode) {
    4309              : #ifndef _WIN32
    4310            0 :   return mkdir(path, mode);
    4311              : #else
    4312              :   (void) mode;
    4313              :   return _mkdir(path);
    4314              : #endif
    4315              : }
    4316              : #endif
    4317              : 
    4318            0 : static struct mg_str mg_get_mime_type(const char *path, const char *dflt,
    4319              :                                       const struct mg_serve_http_opts *opts) {
    4320              :   const char *ext, *overrides;
    4321              :   size_t i, path_len;
    4322              :   struct mg_str r, k, v;
    4323              : 
    4324            0 :   path_len = strlen(path);
    4325              : 
    4326            0 :   overrides = opts->custom_mime_types;
    4327            0 :   while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
    4328            0 :     ext = path + (path_len - k.len);
    4329            0 :     if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
    4330            0 :       return v;
    4331              :     }
    4332              :   }
    4333              : 
    4334            0 :   for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
    4335            0 :     ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len);
    4336            0 :     if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
    4337            0 :         mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) {
    4338            0 :       r.p = mg_static_builtin_mime_types[i].mime_type;
    4339            0 :       r.len = strlen(r.p);
    4340            0 :       return r;
    4341              :     }
    4342              :   }
    4343              : 
    4344            0 :   r.p = dflt;
    4345            0 :   r.len = strlen(r.p);
    4346            0 :   return r;
    4347              : }
    4348              : #endif
    4349              : 
    4350              : /*
    4351              :  * Check whether full request is buffered. Return:
    4352              :  *   -1  if request is malformed
    4353              :  *    0  if request is not yet fully buffered
    4354              :  *   >0  actual request length, including last \r\n\r\n
    4355              :  */
    4356            0 : static int mg_http_get_request_len(const char *s, int buf_len) {
    4357            0 :   const unsigned char *buf = (unsigned char *) s;
    4358              :   int i;
    4359              : 
    4360            0 :   for (i = 0; i < buf_len; i++) {
    4361            0 :     if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
    4362            0 :       return -1;
    4363            0 :     } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
    4364            0 :       return i + 2;
    4365            0 :     } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
    4366            0 :                buf[i + 2] == '\n') {
    4367            0 :       return i + 3;
    4368              :     }
    4369              :   }
    4370              : 
    4371            0 :   return 0;
    4372              : }
    4373              : 
    4374            0 : static const char *mg_http_parse_headers(const char *s, const char *end,
    4375              :                                          int len, struct http_message *req) {
    4376              :   int i;
    4377            0 :   for (i = 0; i < (int) ARRAY_SIZE(req->header_names) - 1; i++) {
    4378            0 :     struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
    4379              : 
    4380            0 :     s = mg_skip(s, end, ": ", k);
    4381            0 :     s = mg_skip(s, end, "\r\n", v);
    4382              : 
    4383            0 :     while (v->len > 0 && v->p[v->len - 1] == ' ') {
    4384            0 :       v->len--; /* Trim trailing spaces in header value */
    4385              :     }
    4386              : 
    4387            0 :     if (k->len == 0 || v->len == 0) {
    4388            0 :       k->p = v->p = NULL;
    4389            0 :       k->len = v->len = 0;
    4390            0 :       break;
    4391              :     }
    4392              : 
    4393            0 :     if (!mg_ncasecmp(k->p, "Content-Length", 14)) {
    4394            0 :       req->body.len = to64(v->p);
    4395            0 :       req->message.len = len + req->body.len;
    4396              :     }
    4397              :   }
    4398              : 
    4399            0 :   return s;
    4400              : }
    4401              : 
    4402            0 : int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
    4403              :   const char *end, *qs;
    4404            0 :   int len = mg_http_get_request_len(s, n);
    4405              : 
    4406            0 :   if (len <= 0) return len;
    4407              : 
    4408            0 :   memset(hm, 0, sizeof(*hm));
    4409            0 :   hm->message.p = s;
    4410            0 :   hm->body.p = s + len;
    4411            0 :   hm->message.len = hm->body.len = (size_t) ~0;
    4412            0 :   end = s + len;
    4413              : 
    4414              :   /* Request is fully buffered. Skip leading whitespaces. */
    4415            0 :   while (s < end && isspace(*(unsigned char *) s)) s++;
    4416              : 
    4417            0 :   if (is_req) {
    4418              :     /* Parse request line: method, URI, proto */
    4419            0 :     s = mg_skip(s, end, " ", &hm->method);
    4420            0 :     s = mg_skip(s, end, " ", &hm->uri);
    4421            0 :     s = mg_skip(s, end, "\r\n", &hm->proto);
    4422            0 :     if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
    4423              : 
    4424              :     /* If URI contains '?' character, initialize query_string */
    4425            0 :     if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
    4426            0 :       hm->query_string.p = qs + 1;
    4427            0 :       hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
    4428            0 :       hm->uri.len = qs - hm->uri.p;
    4429              :     }
    4430              :   } else {
    4431            0 :     s = mg_skip(s, end, " ", &hm->proto);
    4432            0 :     if (end - s < 4 || s[3] != ' ') return -1;
    4433            0 :     hm->resp_code = atoi(s);
    4434            0 :     if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
    4435            0 :     s += 4;
    4436            0 :     s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
    4437              :   }
    4438              : 
    4439            0 :   s = mg_http_parse_headers(s, end, len, hm);
    4440              : 
    4441              :   /*
    4442              :    * mg_parse_http() is used to parse both HTTP requests and HTTP
    4443              :    * responses. If HTTP response does not have Content-Length set, then
    4444              :    * body is read until socket is closed, i.e. body.len is infinite (~0).
    4445              :    *
    4446              :    * For HTTP requests though, according to
    4447              :    * http://tools.ietf.org/html/rfc7231#section-8.1.3,
    4448              :    * only POST and PUT methods have defined body semantics.
    4449              :    * Therefore, if Content-Length is not specified and methods are
    4450              :    * not one of PUT or POST, set body length to 0.
    4451              :    *
    4452              :    * So,
    4453              :    * if it is HTTP request, and Content-Length is not set,
    4454              :    * and method is not (PUT or POST) then reset body length to zero.
    4455              :    */
    4456            0 :   if (hm->body.len == (size_t) ~0 && is_req &&
    4457            0 :       mg_vcasecmp(&hm->method, "PUT") != 0 &&
    4458            0 :       mg_vcasecmp(&hm->method, "POST") != 0) {
    4459            0 :     hm->body.len = 0;
    4460            0 :     hm->message.len = len;
    4461              :   }
    4462              : 
    4463            0 :   return len;
    4464              : }
    4465              : 
    4466            0 : struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
    4467            0 :   size_t i, len = strlen(name);
    4468              : 
    4469            0 :   for (i = 0; hm->header_names[i].len > 0; i++) {
    4470            0 :     struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
    4471            0 :     if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
    4472            0 :       return v;
    4473              :   }
    4474              : 
    4475            0 :   return NULL;
    4476              : }
    4477              : 
    4478              : #ifndef MG_DISABLE_HTTP_WEBSOCKET
    4479              : 
    4480            0 : static int mg_is_ws_fragment(unsigned char flags) {
    4481            0 :   return (flags & 0x80) == 0 || (flags & 0x0f) == 0;
    4482              : }
    4483              : 
    4484            0 : static int mg_is_ws_first_fragment(unsigned char flags) {
    4485            0 :   return (flags & 0x80) == 0 && (flags & 0x0f) != 0;
    4486              : }
    4487              : 
    4488            0 : static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
    4489              :                                                struct websocket_message *wsm) {
    4490            0 :   if (wsm->flags & 0x8) {
    4491            0 :     mg_call(nc, nc->handler, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
    4492              :   } else {
    4493            0 :     mg_call(nc, nc->handler, MG_EV_WEBSOCKET_FRAME, wsm);
    4494              :   }
    4495            0 : }
    4496              : 
    4497            0 : static int mg_deliver_websocket_data(struct mg_connection *nc) {
    4498              :   /* Using unsigned char *, cause of integer arithmetic below */
    4499            0 :   uint64_t i, data_len = 0, frame_len = 0, buf_len = nc->recv_mbuf.len, len,
    4500            0 :               mask_len = 0, header_len = 0;
    4501            0 :   unsigned char *p = (unsigned char *) nc->recv_mbuf.buf, *buf = p,
    4502            0 :                 *e = p + buf_len;
    4503            0 :   unsigned *sizep = (unsigned *) &p[1]; /* Size ptr for defragmented frames */
    4504            0 :   int ok, reass = buf_len > 0 && mg_is_ws_fragment(p[0]) &&
    4505            0 :                   !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
    4506              : 
    4507              :   /* If that's a continuation frame that must be reassembled, handle it */
    4508            0 :   if (reass && !mg_is_ws_first_fragment(p[0]) &&
    4509            0 :       buf_len >= 1 + sizeof(*sizep) && buf_len >= 1 + sizeof(*sizep) + *sizep) {
    4510            0 :     buf += 1 + sizeof(*sizep) + *sizep;
    4511            0 :     buf_len -= 1 + sizeof(*sizep) + *sizep;
    4512              :   }
    4513              : 
    4514            0 :   if (buf_len >= 2) {
    4515            0 :     len = buf[1] & 127;
    4516            0 :     mask_len = buf[1] & 128 ? 4 : 0;
    4517            0 :     if (len < 126 && buf_len >= mask_len) {
    4518            0 :       data_len = len;
    4519            0 :       header_len = 2 + mask_len;
    4520            0 :     } else if (len == 126 && buf_len >= 4 + mask_len) {
    4521            0 :       header_len = 4 + mask_len;
    4522            0 :       data_len = ntohs(*(uint16_t *) &buf[2]);
    4523            0 :     } else if (buf_len >= 10 + mask_len) {
    4524            0 :       header_len = 10 + mask_len;
    4525            0 :       data_len = (((uint64_t) ntohl(*(uint32_t *) &buf[2])) << 32) +
    4526            0 :                  ntohl(*(uint32_t *) &buf[6]);
    4527              :     }
    4528              :   }
    4529              : 
    4530            0 :   frame_len = header_len + data_len;
    4531            0 :   ok = frame_len > 0 && frame_len <= buf_len;
    4532              : 
    4533            0 :   if (ok) {
    4534              :     struct websocket_message wsm;
    4535              : 
    4536            0 :     wsm.size = (size_t) data_len;
    4537            0 :     wsm.data = buf + header_len;
    4538            0 :     wsm.flags = buf[0];
    4539              : 
    4540              :     /* Apply mask if necessary */
    4541            0 :     if (mask_len > 0) {
    4542            0 :       for (i = 0; i < data_len; i++) {
    4543            0 :         buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
    4544              :       }
    4545              :     }
    4546              : 
    4547            0 :     if (reass) {
    4548              :       /* On first fragmented frame, nullify size */
    4549            0 :       if (mg_is_ws_first_fragment(wsm.flags)) {
    4550            0 :         mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.size + sizeof(*sizep));
    4551            0 :         p[0] &= ~0x0f; /* Next frames will be treated as continuation */
    4552            0 :         buf = p + 1 + sizeof(*sizep);
    4553            0 :         *sizep = 0; /* TODO(lsm): fix. this can stomp over frame data */
    4554              :       }
    4555              : 
    4556              :       /* Append this frame to the reassembled buffer */
    4557            0 :       memmove(buf, wsm.data, e - wsm.data);
    4558            0 :       (*sizep) += wsm.size;
    4559            0 :       nc->recv_mbuf.len -= wsm.data - buf;
    4560              : 
    4561              :       /* On last fragmented frame - call user handler and remove data */
    4562            0 :       if (wsm.flags & 0x80) {
    4563            0 :         wsm.data = p + 1 + sizeof(*sizep);
    4564            0 :         wsm.size = *sizep;
    4565            0 :         mg_handle_incoming_websocket_frame(nc, &wsm);
    4566            0 :         mbuf_remove(&nc->recv_mbuf, 1 + sizeof(*sizep) + *sizep);
    4567              :       }
    4568              :     } else {
    4569              :       /* TODO(lsm): properly handle OOB control frames during defragmentation */
    4570            0 :       mg_handle_incoming_websocket_frame(nc, &wsm);
    4571            0 :       mbuf_remove(&nc->recv_mbuf, (size_t) frame_len); /* Cleanup frame */
    4572              :     }
    4573              : 
    4574              :     /* If client closes, close too */
    4575            0 :     if ((buf[0] & 0x0f) == WEBSOCKET_OP_CLOSE) {
    4576            0 :       nc->flags |= MG_F_SEND_AND_CLOSE;
    4577              :     }
    4578              :   }
    4579              : 
    4580            0 :   return ok;
    4581              : }
    4582              : 
    4583              : struct ws_mask_ctx {
    4584              :   size_t pos; /* zero means unmasked */
    4585              :   uint32_t mask;
    4586              : };
    4587              : 
    4588            0 : static uint32_t mg_ws_random_mask(void) {
    4589              :   uint32_t mask;
    4590              : /*
    4591              :  * The spec requires WS client to generate hard to
    4592              :  * guess mask keys. From RFC6455, Section 5.3:
    4593              :  *
    4594              :  * The unpredictability of the masking key is essential to prevent
    4595              :  * authors of malicious applications from selecting the bytes that appear on
    4596              :  * the wire.
    4597              :  *
    4598              :  * Hence this feature is essential when the actual end user of this API
    4599              :  * is untrusted code that wouldn't have access to a lower level net API
    4600              :  * anyway (e.g. web browsers). Hence this feature is low prio for most
    4601              :  * mongoose use cases and thus can be disabled, e.g. when porting to a platform
    4602              :  * that lacks random().
    4603              :  */
    4604              : #ifdef MG_DISABLE_WS_RANDOM_MASK
    4605              :   mask = 0xefbeadde; /* generated with a random number generator, I swear */
    4606              : #else
    4607              :   if (sizeof(long) >= 4) {
    4608            0 :     mask = (uint32_t) random();
    4609              :   } else if (sizeof(long) == 2) {
    4610              :     mask = (uint32_t) random() << 16 | (uint32_t) random();
    4611              :   }
    4612              : #endif
    4613            0 :   return mask;
    4614              : }
    4615              : 
    4616            0 : static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
    4617              :                               struct ws_mask_ctx *ctx) {
    4618              :   int header_len;
    4619              :   unsigned char header[10];
    4620              : 
    4621            0 :   header[0] = (op & WEBSOCKET_DONT_FIN ? 0x0 : 0x80) + (op & 0x0f);
    4622            0 :   if (len < 126) {
    4623            0 :     header[1] = len;
    4624            0 :     header_len = 2;
    4625            0 :   } else if (len < 65535) {
    4626            0 :     uint16_t tmp = htons((uint16_t) len);
    4627            0 :     header[1] = 126;
    4628            0 :     memcpy(&header[2], &tmp, sizeof(tmp));
    4629            0 :     header_len = 4;
    4630              :   } else {
    4631              :     uint32_t tmp;
    4632            0 :     header[1] = 127;
    4633            0 :     tmp = htonl((uint32_t)((uint64_t) len >> 32));
    4634            0 :     memcpy(&header[2], &tmp, sizeof(tmp));
    4635            0 :     tmp = htonl((uint32_t)(len & 0xffffffff));
    4636            0 :     memcpy(&header[6], &tmp, sizeof(tmp));
    4637            0 :     header_len = 10;
    4638              :   }
    4639              : 
    4640              :   /* client connections enable masking */
    4641            0 :   if (nc->listener == NULL) {
    4642            0 :     header[1] |= 1 << 7; /* set masking flag */
    4643            0 :     mg_send(nc, header, header_len);
    4644            0 :     ctx->mask = mg_ws_random_mask();
    4645            0 :     mg_send(nc, &ctx->mask, sizeof(ctx->mask));
    4646            0 :     ctx->pos = nc->send_mbuf.len;
    4647              :   } else {
    4648            0 :     mg_send(nc, header, header_len);
    4649            0 :     ctx->pos = 0;
    4650              :   }
    4651            0 : }
    4652              : 
    4653            0 : static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
    4654              :   size_t i;
    4655            0 :   if (ctx->pos == 0) return;
    4656            0 :   for (i = 0; i < (mbuf->len - ctx->pos); i++) {
    4657            0 :     mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
    4658              :   }
    4659              : }
    4660              : 
    4661            0 : void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
    4662              :                              size_t len) {
    4663              :   struct ws_mask_ctx ctx;
    4664            0 :   DBG(("%p %d %d", nc, op, (int) len));
    4665            0 :   mg_send_ws_header(nc, op, len, &ctx);
    4666            0 :   mg_send(nc, data, len);
    4667              : 
    4668            0 :   mg_ws_mask_frame(&nc->send_mbuf, &ctx);
    4669              : 
    4670            0 :   if (op == WEBSOCKET_OP_CLOSE) {
    4671            0 :     nc->flags |= MG_F_SEND_AND_CLOSE;
    4672              :   }
    4673            0 : }
    4674              : 
    4675            0 : void mg_send_websocket_framev(struct mg_connection *nc, int op,
    4676              :                               const struct mg_str *strv, int strvcnt) {
    4677              :   struct ws_mask_ctx ctx;
    4678              :   int i;
    4679            0 :   int len = 0;
    4680            0 :   for (i = 0; i < strvcnt; i++) {
    4681            0 :     len += strv[i].len;
    4682              :   }
    4683              : 
    4684            0 :   mg_send_ws_header(nc, op, len, &ctx);
    4685              : 
    4686            0 :   for (i = 0; i < strvcnt; i++) {
    4687            0 :     mg_send(nc, strv[i].p, strv[i].len);
    4688              :   }
    4689              : 
    4690            0 :   mg_ws_mask_frame(&nc->send_mbuf, &ctx);
    4691              : 
    4692            0 :   if (op == WEBSOCKET_OP_CLOSE) {
    4693            0 :     nc->flags |= MG_F_SEND_AND_CLOSE;
    4694              :   }
    4695            0 : }
    4696              : 
    4697            0 : void mg_printf_websocket_frame(struct mg_connection *nc, int op,
    4698              :                                const char *fmt, ...) {
    4699            0 :   char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
    4700              :   va_list ap;
    4701              :   int len;
    4702              : 
    4703            0 :   va_start(ap, fmt);
    4704            0 :   if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
    4705            0 :     mg_send_websocket_frame(nc, op, buf, len);
    4706              :   }
    4707            0 :   va_end(ap);
    4708              : 
    4709            0 :   if (buf != mem && buf != NULL) {
    4710            0 :     MG_FREE(buf);
    4711              :   }
    4712            0 : }
    4713              : 
    4714            0 : static void mg_websocket_handler(struct mg_connection *nc, int ev,
    4715              :                                  void *ev_data) {
    4716            0 :   mg_call(nc, nc->handler, ev, ev_data);
    4717              : 
    4718            0 :   switch (ev) {
    4719            0 :     case MG_EV_RECV:
    4720              :       do {
    4721            0 :       } while (mg_deliver_websocket_data(nc));
    4722            0 :       break;
    4723            0 :     case MG_EV_POLL:
    4724              :       /* Ping idle websocket connections */
    4725              :       {
    4726            0 :         time_t now = *(time_t *) ev_data;
    4727            0 :         if (nc->flags & MG_F_IS_WEBSOCKET &&
    4728            0 :             now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
    4729            0 :           mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
    4730              :         }
    4731              :       }
    4732            0 :       break;
    4733            0 :     default:
    4734            0 :       break;
    4735              :   }
    4736            0 : }
    4737              : 
    4738            0 : static void mg_ws_handshake(struct mg_connection *nc,
    4739              :                             const struct mg_str *key) {
    4740              :   static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    4741              :   char buf[MG_VPRINTF_BUFFER_SIZE], sha[20], b64_sha[sizeof(sha) * 2];
    4742              :   cs_sha1_ctx sha_ctx;
    4743              : 
    4744            0 :   snprintf(buf, sizeof(buf), "%.*s%s", (int) key->len, key->p, magic);
    4745              : 
    4746            0 :   cs_sha1_init(&sha_ctx);
    4747            0 :   cs_sha1_update(&sha_ctx, (unsigned char *) buf, strlen(buf));
    4748            0 :   cs_sha1_final((unsigned char *) sha, &sha_ctx);
    4749              : 
    4750            0 :   mg_base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
    4751            0 :   mg_printf(nc, "%s%s%s",
    4752              :             "HTTP/1.1 101 Switching Protocols\r\n"
    4753              :             "Upgrade: websocket\r\n"
    4754              :             "Connection: Upgrade\r\n"
    4755              :             "Sec-WebSocket-Accept: ",
    4756              :             b64_sha, "\r\n\r\n");
    4757            0 :   DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
    4758            0 : }
    4759              : 
    4760              : #endif /* MG_DISABLE_HTTP_WEBSOCKET */
    4761              : 
    4762              : #ifndef MG_DISABLE_FILESYSTEM
    4763            0 : static void mg_http_transfer_file_data(struct mg_connection *nc) {
    4764            0 :   struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
    4765              :   char buf[MG_MAX_HTTP_SEND_MBUF];
    4766            0 :   int64_t left = pd->file.cl - pd->file.sent;
    4767            0 :   size_t n = 0, to_read = 0;
    4768              : 
    4769            0 :   if (pd->file.type == DATA_FILE) {
    4770            0 :     struct mbuf *io = &nc->send_mbuf;
    4771            0 :     if (io->len < sizeof(buf)) {
    4772            0 :       to_read = sizeof(buf) - io->len;
    4773              :     }
    4774              : 
    4775            0 :     if (left > 0 && to_read > (size_t) left) {
    4776            0 :       to_read = left;
    4777              :     }
    4778              : 
    4779            0 :     if (to_read == 0) {
    4780              :       /* Rate limiting. send_mbuf is too full, wait until it's drained. */
    4781            0 :     } else if (pd->file.sent < pd->file.cl &&
    4782            0 :                (n = fread(buf, 1, to_read, pd->file.fp)) > 0) {
    4783            0 :       mg_send(nc, buf, n);
    4784            0 :       pd->file.sent += n;
    4785              :     } else {
    4786            0 :       mg_http_free_proto_data_file(&pd->file);
    4787              : #ifdef MG_DISABLE_HTTP_KEEP_ALIVE
    4788              :       nc->flags |= MG_F_SEND_AND_CLOSE;
    4789              : #endif
    4790              :     }
    4791            0 :   } else if (pd->file.type == DATA_PUT) {
    4792            0 :     struct mbuf *io = &nc->recv_mbuf;
    4793            0 :     size_t to_write =
    4794            0 :         left <= 0 ? 0 : left < (int64_t) io->len ? (size_t) left : io->len;
    4795            0 :     size_t n = fwrite(io->buf, 1, to_write, pd->file.fp);
    4796            0 :     if (n > 0) {
    4797            0 :       mbuf_remove(io, n);
    4798            0 :       pd->file.sent += n;
    4799              :     }
    4800            0 :     if (n == 0 || pd->file.sent >= pd->file.cl) {
    4801            0 :       mg_http_free_proto_data_file(&pd->file);
    4802              : #ifdef MG_DISABLE_HTTP_KEEP_ALIVE
    4803              :       nc->flags |= MG_F_SEND_AND_CLOSE;
    4804              : #endif
    4805              :     }
    4806              :   }
    4807              : #ifndef MG_DISABLE_CGI
    4808              :   else if (pd->cgi.cgi_nc != NULL) {
    4809              :     /* This is POST data that needs to be forwarded to the CGI process */
    4810              :     if (pd->cgi.cgi_nc != NULL) {
    4811              :       mg_forward(nc, pd->cgi.cgi_nc);
    4812              :     } else {
    4813              :       nc->flags |= MG_F_SEND_AND_CLOSE;
    4814              :     }
    4815              :   }
    4816              : #endif
    4817            0 : }
    4818              : #endif /* MG_DISABLE_FILESYSTEM */
    4819              : 
    4820              : /*
    4821              :  * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
    4822              :  * if it's incomplete. If the chunk is fully buffered, return total number of
    4823              :  * bytes in a chunk, and store data in `data`, `data_len`.
    4824              :  */
    4825            0 : static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data,
    4826              :                                   size_t *chunk_len) {
    4827            0 :   unsigned char *s = (unsigned char *) buf;
    4828            0 :   size_t n = 0; /* scanned chunk length */
    4829            0 :   size_t i = 0; /* index in s */
    4830              : 
    4831              :   /* Scan chunk length. That should be a hexadecimal number. */
    4832            0 :   while (i < len && isxdigit(s[i])) {
    4833            0 :     n *= 16;
    4834            0 :     n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
    4835            0 :     i++;
    4836              :   }
    4837              : 
    4838              :   /* Skip new line */
    4839            0 :   if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
    4840            0 :     return 0;
    4841              :   }
    4842            0 :   i += 2;
    4843              : 
    4844              :   /* Record where the data is */
    4845            0 :   *chunk_data = (char *) s + i;
    4846            0 :   *chunk_len = n;
    4847              : 
    4848              :   /* Skip data */
    4849            0 :   i += n;
    4850              : 
    4851              :   /* Skip new line */
    4852            0 :   if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
    4853            0 :     return 0;
    4854              :   }
    4855            0 :   return i + 2;
    4856              : }
    4857              : 
    4858            0 : MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
    4859              :                                      struct http_message *hm, char *buf,
    4860              :                                      size_t blen) {
    4861            0 :   struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
    4862              :   char *data;
    4863            0 :   size_t i, n, data_len, body_len, zero_chunk_received = 0;
    4864              : 
    4865              :   /* Find out piece of received data that is not yet reassembled */
    4866            0 :   body_len = pd->chunk.body_len;
    4867            0 :   assert(blen >= body_len);
    4868              : 
    4869              :   /* Traverse all fully buffered chunks */
    4870            0 :   for (i = body_len;
    4871            0 :        (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
    4872            0 :        i += n) {
    4873              :     /* Collapse chunk data to the rest of HTTP body */
    4874            0 :     memmove(buf + body_len, data, data_len);
    4875            0 :     body_len += data_len;
    4876            0 :     hm->body.len = body_len;
    4877              : 
    4878            0 :     if (data_len == 0) {
    4879            0 :       zero_chunk_received = 1;
    4880            0 :       i += n;
    4881            0 :       break;
    4882              :     }
    4883              :   }
    4884              : 
    4885            0 :   if (i > body_len) {
    4886              :     /* Shift unparsed content to the parsed body */
    4887            0 :     assert(i <= blen);
    4888            0 :     memmove(buf + body_len, buf + i, blen - i);
    4889            0 :     memset(buf + body_len + blen - i, 0, i - body_len);
    4890            0 :     nc->recv_mbuf.len -= i - body_len;
    4891            0 :     pd->chunk.body_len = body_len;
    4892              : 
    4893              :     /* Send MG_EV_HTTP_CHUNK event */
    4894            0 :     nc->flags &= ~MG_F_DELETE_CHUNK;
    4895            0 :     mg_call(nc, nc->handler, MG_EV_HTTP_CHUNK, hm);
    4896              : 
    4897              :     /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
    4898            0 :     if (nc->flags & MG_F_DELETE_CHUNK) {
    4899            0 :       memset(buf, 0, body_len);
    4900            0 :       memmove(buf, buf + body_len, blen - i);
    4901            0 :       nc->recv_mbuf.len -= body_len;
    4902            0 :       hm->body.len = pd->chunk.body_len = 0;
    4903              :     }
    4904              : 
    4905            0 :     if (zero_chunk_received) {
    4906            0 :       hm->message.len = pd->chunk.body_len + blen - i;
    4907              :     }
    4908              :   }
    4909              : 
    4910            0 :   return body_len;
    4911              : }
    4912              : 
    4913            0 : static mg_event_handler_t mg_http_get_endpoint_handler(
    4914              :     struct mg_connection *nc, struct mg_str *uri_path) {
    4915              :   struct mg_http_proto_data *pd;
    4916            0 :   mg_event_handler_t ret = NULL;
    4917            0 :   int matched, matched_max = 0;
    4918              :   struct mg_http_endpoint *ep;
    4919              : 
    4920            0 :   if (nc == NULL) {
    4921            0 :     return NULL;
    4922              :   }
    4923              : 
    4924            0 :   pd = mg_http_get_proto_data(nc);
    4925              : 
    4926            0 :   ep = pd->endpoints;
    4927            0 :   while (ep != NULL) {
    4928            0 :     const struct mg_str name_s = {ep->name, ep->name_len};
    4929            0 :     if ((matched = mg_match_prefix_n(name_s, *uri_path)) != -1) {
    4930            0 :       if (matched > matched_max) {
    4931              :         /* Looking for the longest suitable handler */
    4932            0 :         ret = ep->handler;
    4933            0 :         matched_max = matched;
    4934              :       }
    4935              :     }
    4936              : 
    4937            0 :     ep = ep->next;
    4938              :   }
    4939              : 
    4940            0 :   return ret;
    4941              : }
    4942              : 
    4943            0 : static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
    4944              :                                           struct http_message *hm) {
    4945            0 :   struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
    4946              : 
    4947            0 :   if (pd->endpoint_handler == NULL || ev == MG_EV_HTTP_REQUEST) {
    4948            0 :     pd->endpoint_handler =
    4949              :         ev == MG_EV_HTTP_REQUEST
    4950            0 :             ? mg_http_get_endpoint_handler(nc->listener, &hm->uri)
    4951              :             : NULL;
    4952              :   }
    4953            0 :   mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler, ev,
    4954              :           hm);
    4955            0 : }
    4956              : 
    4957              : #ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
    4958              : static void mg_http_multipart_continue(struct mg_connection *nc);
    4959              : 
    4960              : static void mg_http_multipart_begin(struct mg_connection *nc,
    4961              :                                     struct http_message *hm, int req_len);
    4962              : 
    4963              : #endif
    4964              : 
    4965              : /*
    4966              :  * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
    4967              :  * If a big structure is declared in a big function, lx106 gcc will make it
    4968              :  * even bigger (round up to 4k, from 700 bytes of actual size).
    4969              :  */
    4970              : #ifdef __xtensa__
    4971              : static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data,
    4972              :                              struct http_message *hm) __attribute__((noinline));
    4973              : 
    4974              : void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data) {
    4975              :   struct http_message hm;
    4976              :   mg_http_handler2(nc, ev, ev_data, &hm);
    4977              : }
    4978              : 
    4979              : static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data,
    4980              :                              struct http_message *hm) {
    4981              : #else  /* !__XTENSA__ */
    4982            0 : void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data) {
    4983              :   struct http_message shm;
    4984            0 :   struct http_message *hm = &shm;
    4985              : #endif /* __XTENSA__ */
    4986            0 :   struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
    4987            0 :   struct mbuf *io = &nc->recv_mbuf;
    4988              :   int req_len;
    4989            0 :   const int is_req = (nc->listener != NULL);
    4990              : #ifndef MG_DISABLE_HTTP_WEBSOCKET
    4991              :   struct mg_str *vec;
    4992              : #endif
    4993            0 :   if (ev == MG_EV_CLOSE) {
    4994              : #ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
    4995              :     if (pd->mp_stream.boundary != NULL) {
    4996              :       /*
    4997              :        * Multipart message is in progress, but we get close
    4998              :        * MG_EV_HTTP_PART_END with error flag
    4999              :        */
    5000              :       struct mg_http_multipart_part mp;
    5001              :       memset(&mp, 0, sizeof(mp));
    5002              : 
    5003              :       mp.status = -1;
    5004              :       mp.var_name = pd->mp_stream.var_name;
    5005              :       mp.file_name = pd->mp_stream.file_name;
    5006              :       mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
    5007              :               MG_EV_HTTP_PART_END, &mp);
    5008              :     } else
    5009              : #endif
    5010            0 :         if (io->len > 0 && mg_parse_http(io->buf, io->len, hm, is_req) > 0) {
    5011              :       /*
    5012              :       * For HTTP messages without Content-Length, always send HTTP message
    5013              :       * before MG_EV_CLOSE message.
    5014              :       */
    5015            0 :       int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
    5016            0 :       hm->message.len = io->len;
    5017            0 :       hm->body.len = io->buf + io->len - hm->body.p;
    5018            0 :       mg_http_call_endpoint_handler(nc, ev2, hm);
    5019              :     }
    5020              :   }
    5021              : 
    5022              : #ifndef MG_DISABLE_FILESYSTEM
    5023            0 :   if (pd->file.fp)
    5024            0 :     printf("nc %p, pd %p, file fp %p cl %d\n", nc, pd, pd->file.fp, (int)pd->file.cl);
    5025              :   //printf("fp %p\n", pd->file.fp);
    5026            0 :   assert(pd->file.fp == NULL);
    5027            0 :   if (pd->file.fp != NULL) {
    5028            0 :     mg_http_transfer_file_data(nc);
    5029              :   }
    5030              : #endif
    5031              : 
    5032            0 :   mg_call(nc, nc->handler, ev, ev_data);
    5033              : 
    5034            0 :   if (ev == MG_EV_RECV) {
    5035              :     struct mg_str *s;
    5036              : 
    5037              : #ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
    5038              :     if (pd->mp_stream.boundary != NULL) {
    5039              :       mg_http_multipart_continue(nc);
    5040              :       return;
    5041              :     }
    5042              : #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
    5043              : 
    5044            0 :     req_len = mg_parse_http(io->buf, io->len, hm, is_req);
    5045              : 
    5046            0 :     if (req_len > 0 &&
    5047            0 :         (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
    5048            0 :         mg_vcasecmp(s, "chunked") == 0) {
    5049            0 :       mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
    5050              :     }
    5051              : 
    5052              : #ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
    5053              :     if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL &&
    5054              :         s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) {
    5055              :       mg_http_multipart_begin(nc, hm, req_len);
    5056              :       mg_http_multipart_continue(nc);
    5057              :       return;
    5058              :     }
    5059              : #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
    5060              : 
    5061              :     /* TODO(alashkin): refactor this ifelseifelseifelseifelse */
    5062            0 :     if ((req_len < 0 ||
    5063            0 :          (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) {
    5064            0 :       DBG(("invalid request"));
    5065            0 :       nc->flags |= MG_F_CLOSE_IMMEDIATELY;
    5066            0 :     } else if (req_len == 0) {
    5067              :       /* Do nothing, request is not yet fully buffered */
    5068              :     }
    5069              : #ifndef MG_DISABLE_HTTP_WEBSOCKET
    5070            0 :     else if (nc->listener == NULL &&
    5071            0 :              mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
    5072              :       /* We're websocket client, got handshake response from server. */
    5073              :       /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
    5074            0 :       mbuf_remove(io, req_len);
    5075            0 :       nc->proto_handler = mg_websocket_handler;
    5076            0 :       nc->flags |= MG_F_IS_WEBSOCKET;
    5077            0 :       mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
    5078            0 :       mg_websocket_handler(nc, MG_EV_RECV, ev_data);
    5079            0 :     } else if (nc->listener != NULL &&
    5080            0 :                (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
    5081              :       /* This is a websocket request. Switch protocol handlers. */
    5082            0 :       mbuf_remove(io, req_len);
    5083            0 :       nc->proto_handler = mg_websocket_handler;
    5084            0 :       nc->flags |= MG_F_IS_WEBSOCKET;
    5085              : 
    5086              :       /* Send handshake */
    5087            0 :       mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST, hm);
    5088            0 :       if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
    5089            0 :         if (nc->send_mbuf.len == 0) {
    5090            0 :           mg_ws_handshake(nc, vec);
    5091              :         }
    5092            0 :         mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
    5093            0 :         mg_websocket_handler(nc, MG_EV_RECV, ev_data);
    5094              :       }
    5095              : #endif /* MG_DISABLE_HTTP_WEBSOCKET */
    5096            0 :     } else if (hm->message.len <= io->len) {
    5097            0 :       int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
    5098              : 
    5099              : /* Whole HTTP message is fully buffered, call event handler */
    5100              : 
    5101              : #ifdef MG_ENABLE_JAVASCRIPT
    5102              :       v7_val_t v1, v2, headers, req, args, res;
    5103              :       struct v7 *v7 = nc->mgr->v7;
    5104              :       const char *ev_name = trigger_ev == MG_EV_HTTP_REPLY ? "onsnd" : "onrcv";
    5105              :       int i, js_callback_handled_request = 0;
    5106              : 
    5107              :       if (v7 != NULL) {
    5108              :         /* Lookup JS callback */
    5109              :         v1 = v7_get(v7, v7_get_global(v7), "Http", ~0);
    5110              :         v2 = v7_get(v7, v1, ev_name, ~0);
    5111              : 
    5112              :         /* Create callback params. TODO(lsm): own/disown those */
    5113              :         args = v7_mk_array(v7);
    5114              :         req = v7_mk_object(v7);
    5115              :         headers = v7_mk_object(v7);
    5116              : 
    5117              :         /* Populate request object */
    5118              :         v7_set(v7, req, "method", ~0,
    5119              :                v7_mk_string(v7, hm->method.p, hm->method.len, 1));
    5120              :         v7_set(v7, req, "uri", ~0, v7_mk_string(v7, hm->uri.p, hm->uri.len, 1));
    5121              :         v7_set(v7, req, "body", ~0,
    5122              :                v7_mk_string(v7, hm->body.p, hm->body.len, 1));
    5123              :         v7_set(v7, req, "headers", ~0, headers);
    5124              :         for (i = 0; hm->header_names[i].len > 0; i++) {
    5125              :           const struct mg_str *name = &hm->header_names[i];
    5126              :           const struct mg_str *value = &hm->header_values[i];
    5127              :           v7_set(v7, headers, name->p, name->len,
    5128              :                  v7_mk_string(v7, value->p, value->len, 1));
    5129              :         }
    5130              : 
    5131              :         /* Invoke callback. TODO(lsm): report errors */
    5132              :         v7_array_push(v7, args, v7_mk_foreign(nc));
    5133              :         v7_array_push(v7, args, req);
    5134              :         if (v7_apply(v7, v2, v7_mk_undefined(), args, &res) == V7_OK &&
    5135              :             v7_is_truthy(v7, res)) {
    5136              :           js_callback_handled_request++;
    5137              :         }
    5138              :       }
    5139              : 
    5140              :       /* If JS callback returns true, stop request processing */
    5141              :       if (js_callback_handled_request) {
    5142              :         nc->flags |= MG_F_SEND_AND_CLOSE;
    5143              :       } else {
    5144              :         mg_http_call_endpoint_handler(nc, trigger_ev, hm);
    5145              :       }
    5146              : #else
    5147            0 :     mg_http_call_endpoint_handler(nc, trigger_ev, hm);
    5148              : #endif
    5149            0 :       mbuf_remove(io, hm->message.len);
    5150              :     }
    5151              :   }
    5152              :   (void) pd;
    5153            0 : }
    5154              : 
    5155            0 : static size_t mg_get_line_len(const char *buf, size_t buf_len) {
    5156            0 :   size_t len = 0;
    5157            0 :   while (len < buf_len && buf[len] != '\n') len++;
    5158            0 :   return len == buf_len ? 0 : len + 1;
    5159              : }
    5160              : 
    5161              : #ifdef MG_ENABLE_HTTP_STREAMING_MULTIPART
    5162              : static void mg_http_multipart_begin(struct mg_connection *nc,
    5163              :                                     struct http_message *hm, int req_len) {
    5164              :   struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
    5165              :   struct mg_str *ct;
    5166              :   struct mbuf *io = &nc->recv_mbuf;
    5167              : 
    5168              :   char boundary[100];
    5169              :   int boundary_len;
    5170              : 
    5171              :   if (nc->listener == NULL) {
    5172              :     /* No streaming for replies now */
    5173              :     goto exit_mp;
    5174              :   }
    5175              : 
    5176              :   ct = mg_get_http_header(hm, "Content-Type");
    5177              :   if (ct == NULL) {
    5178              :     /* We need more data - or it isn't multipart mesage */
    5179              :     goto exit_mp;
    5180              :   }
    5181              : 
    5182              :   /* Content-type should start with "multipart" */
    5183              :   if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) {
    5184              :     goto exit_mp;
    5185              :   }
    5186              : 
    5187              :   boundary_len =
    5188              :       mg_http_parse_header(ct, "boundary", boundary, sizeof(boundary));
    5189              :   if (boundary_len == 0) {
    5190              :     /*
    5191              :      * Content type is multipart, but there is no boundary,
    5192              :      * probably malformed request
    5193              :      */
    5194              :     nc->flags = MG_F_CLOSE_IMMEDIATELY;
    5195              :     DBG(("invalid request"));
    5196              :     goto exit_mp;
    5197              :   }
    5198              : 
    5199              :   /* If we reach this place - that is multipart request */
    5200              : 
    5201              :   if (pd->mp_stream.boundary != NULL) {
    5202              :     /*
    5203              :      * Another streaming request was in progress,
    5204              :      * looks like protocol error
    5205              :      */
    5206              :     nc->flags |= MG_F_CLOSE_IMMEDIATELY;
    5207              :   } else {
    5208              :     pd->mp_stream.boundary = strdup(boundary);
    5209              :     pd->mp_stream.boundary_len = strlen(boundary);
    5210              :     pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
    5211              : 
    5212              :     pd->endpoint_handler = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
    5213              :     if (pd->endpoint_handler == NULL) {
    5214              :       pd->endpoint_handler = nc->handler;
    5215              :     }
    5216              : 
    5217              :     mg_call(nc, pd->endpoint_handler, MG_EV_HTTP_MULTIPART_REQUEST, hm);
    5218              : 
    5219              :     mbuf_remove(io, req_len);
    5220              :   }
    5221              : exit_mp:
    5222              :   ;
    5223              : }
    5224              : 
    5225              : #define CONTENT_DISPOSITION "Content-Disposition: "
    5226              : 
    5227              : static void mg_http_multipart_call_handler(struct mg_connection *c, int ev,
    5228              :                                            const char *data, size_t data_len) {
    5229              :   struct mg_http_multipart_part mp;
    5230              :   struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
    5231              :   memset(&mp, 0, sizeof(mp));
    5232              : 
    5233              :   mp.var_name = pd->mp_stream.var_name;
    5234              :   mp.file_name = pd->mp_stream.file_name;
    5235              :   mp.user_data = pd->mp_stream.user_data;
    5236              :   mp.data.p = data;
    5237              :   mp.data.len = data_len;
    5238              :   mg_call(c, pd->endpoint_handler, ev, &mp);
    5239              :   pd->mp_stream.user_data = mp.user_data;
    5240              : }
    5241              : 
    5242              : static int mg_http_multipart_got_chunk(struct mg_connection *c) {
    5243              :   struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
    5244              :   struct mbuf *io = &c->recv_mbuf;
    5245              : 
    5246              :   mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf,
    5247              :                                  pd->mp_stream.prev_io_len);
    5248              :   mbuf_remove(io, pd->mp_stream.prev_io_len);
    5249              :   pd->mp_stream.prev_io_len = 0;
    5250              :   pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
    5251              : 
    5252              :   return 0;
    5253              : }
    5254              : 
    5255              : static int mg_http_multipart_finalize(struct mg_connection *c) {
    5256              :   struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
    5257              : 
    5258              :   mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
    5259              :   mg_http_free_proto_data_mp_stream(&pd->mp_stream);
    5260              :   pd->mp_stream.state = MPS_FINISHED;
    5261              : 
    5262              :   return 1;
    5263              : }
    5264              : 
    5265              : static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) {
    5266              :   const char *boundary;
    5267              :   struct mbuf *io = &c->recv_mbuf;
    5268              :   struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
    5269              : 
    5270              :   if ((int) io->len < pd->mp_stream.boundary_len + 2) {
    5271              :     return 0;
    5272              :   }
    5273              : 
    5274              :   boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
    5275              :   if (boundary != NULL) {
    5276              :     if (io->len - (boundary - io->buf) < 4) {
    5277              :       return 0;
    5278              :     }
    5279              :     if (memcmp(boundary + pd->mp_stream.boundary_len, "--", 2) == 0) {
    5280              :       pd->mp_stream.state = MPS_FINALIZE;
    5281              :     } else {
    5282              :       pd->mp_stream.state = MPS_GOT_BOUNDARY;
    5283              :     }
    5284              :   } else {
    5285              :     return 0;
    5286              :   }
    5287              : 
    5288              :   return 1;
    5289              : }
    5290              : 
    5291              : static int mg_http_multipart_process_boundary(struct mg_connection *c) {
    5292              :   int data_size;
    5293              :   const char *boundary, *block_begin;
    5294              :   struct mbuf *io = &c->recv_mbuf;
    5295              :   struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
    5296              :   char file_name[100], var_name[100];
    5297              :   int line_len;
    5298              :   boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
    5299              :   block_begin = boundary + pd->mp_stream.boundary_len + 2;
    5300              :   data_size = io->len - (block_begin - io->buf);
    5301              : 
    5302              :   while (data_size > 0 &&
    5303              :          (line_len = mg_get_line_len(block_begin, data_size)) != 0) {
    5304              :     if (line_len > (int) sizeof(CONTENT_DISPOSITION) &&
    5305              :         mg_ncasecmp(block_begin, CONTENT_DISPOSITION,
    5306              :                     sizeof(CONTENT_DISPOSITION) - 1) == 0) {
    5307              :       struct mg_str header;
    5308              : 
    5309              :       header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
    5310              :       header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
    5311              :       mg_http_parse_header(&header, "name", var_name, sizeof(var_name) - 2);
    5312              :       mg_http_parse_header(&header, "filename", file_name,
    5313              :                            sizeof(file_name) - 2);
    5314              :       block_begin += line_len;
    5315              :       data_size -= line_len;
    5316              :       continue;
    5317              :     }
    5318              : 
    5319              :     if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
    5320              :       mbuf_remove(io, block_begin - io->buf + 2);
    5321              : 
    5322              :       if (pd->mp_stream.processing_part != 0) {
    5323              :         mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
    5324              :       }
    5325              : 
    5326              :       free((void *) pd->mp_stream.file_name);
    5327              :       pd->mp_stream.file_name = strdup(file_name);
    5328              :       free((void *) pd->mp_stream.var_name);
    5329              :       pd->mp_stream.var_name = strdup(var_name);
    5330              : 
    5331              :       mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0);
    5332              :       pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
    5333              :       pd->mp_stream.processing_part++;
    5334              :       return 1;
    5335              :     }
    5336              : 
    5337              :     block_begin += line_len;
    5338              :   }
    5339              : 
    5340              :   pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
    5341              : 
    5342              :   return 0;
    5343              : }
    5344              : 
    5345              : static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) {
    5346              :   struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
    5347              :   struct mbuf *io = &c->recv_mbuf;
    5348              : 
    5349              :   const char *boundary;
    5350              :   if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) {
    5351              :     return 0;
    5352              :   }
    5353              : 
    5354              :   boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
    5355              :   if (boundary == NULL && pd->mp_stream.prev_io_len == 0) {
    5356              :     pd->mp_stream.prev_io_len = io->len;
    5357              :     return 0;
    5358              :   } else if (boundary == NULL &&
    5359              :              (int) io->len >
    5360              :                  pd->mp_stream.prev_io_len + pd->mp_stream.boundary_len + 4) {
    5361              :     pd->mp_stream.state = MPS_GOT_CHUNK;
    5362              :     return 1;
    5363              :   } else if (boundary != NULL) {
    5364              :     int data_size = (boundary - io->buf - 4);
    5365              :     mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf, data_size);
    5366              :     mbuf_remove(io, (boundary - io->buf));
    5367              :     pd->mp_stream.prev_io_len = 0;
    5368              :     pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
    5369              :     return 1;
    5370              :   } else {
    5371              :     return 0;
    5372              :   }
    5373              : }
    5374              : 
    5375              : static void mg_http_multipart_continue(struct mg_connection *c) {
    5376              :   struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
    5377              :   while (1) {
    5378              :     switch (pd->mp_stream.state) {
    5379              :       case MPS_BEGIN: {
    5380              :         pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
    5381              :         break;
    5382              :       }
    5383              :       case MPS_WAITING_FOR_BOUNDARY: {
    5384              :         if (mg_http_multipart_wait_for_boundary(c) == 0) {
    5385              :           return;
    5386              :         }
    5387              :         break;
    5388              :       }
    5389              :       case MPS_GOT_BOUNDARY: {
    5390              :         if (mg_http_multipart_process_boundary(c) == 0) {
    5391              :           return;
    5392              :         }
    5393              :         break;
    5394              :       }
    5395              :       case MPS_WAITING_FOR_CHUNK: {
    5396              :         if (mg_http_multipart_continue_wait_for_chunk(c) == 0) {
    5397              :           return;
    5398              :         }
    5399              :         break;
    5400              :       }
    5401              :       case MPS_GOT_CHUNK: {
    5402              :         if (mg_http_multipart_got_chunk(c) == 0) {
    5403              :           return;
    5404              :         }
    5405              :         break;
    5406              :       }
    5407              :       case MPS_FINALIZE: {
    5408              :         if (mg_http_multipart_finalize(c) == 0) {
    5409              :           return;
    5410              :         }
    5411              :         break;
    5412              :       }
    5413              :       case MPS_FINISHED: {
    5414              :         mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
    5415              :         return;
    5416              :       }
    5417              :     }
    5418              :   }
    5419              : }
    5420              : 
    5421              : struct file_upload_state {
    5422              :   char *lfn;
    5423              :   size_t num_recd;
    5424              :   FILE *fp;
    5425              : };
    5426              : 
    5427              : void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
    5428              :                             mg_fu_fname_fn local_name_fn) {
    5429              :   switch (ev) {
    5430              :     case MG_EV_HTTP_PART_BEGIN: {
    5431              :       struct mg_http_multipart_part *mp =
    5432              :           (struct mg_http_multipart_part *) ev_data;
    5433              :       struct file_upload_state *fus =
    5434              :           (struct file_upload_state *) calloc(1, sizeof(*fus));
    5435              :       mp->user_data = NULL;
    5436              : 
    5437              :       struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
    5438              :       if (lfn.p == NULL || lfn.len == 0) {
    5439              :         LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name));
    5440              :         mg_printf(nc,
    5441              :                   "HTTP/1.1 403 Not Allowed\r\n"
    5442              :                   "Content-Type: text/plain\r\n"
    5443              :                   "Connection: close\r\n\r\n"
    5444              :                   "Not allowed to upload %s\r\n",
    5445              :                   mp->file_name);
    5446              :         nc->flags |= MG_F_SEND_AND_CLOSE;
    5447              :         return;
    5448              :       }
    5449              :       fus->lfn = (char *) malloc(lfn.len + 1);
    5450              :       memcpy(fus->lfn, lfn.p, lfn.len);
    5451              :       fus->lfn[lfn.len] = '\0';
    5452              :       if (lfn.p != mp->file_name) free((char *) lfn.p);
    5453              :       LOG(LL_DEBUG,
    5454              :           ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn));
    5455              :       fus->fp = fopen(fus->lfn, "w");
    5456              :       if (fus->fp == NULL) {
    5457              :         mg_printf(nc,
    5458              :                   "HTTP/1.1 500 Internal Server Error\r\n"
    5459              :                   "Content-Type: text/plain\r\n"
    5460              :                   "Connection: close\r\n\r\n");
    5461              :         LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, errno));
    5462              :         mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, errno);
    5463              :         /* Do not close the connection just yet, discard remainder of the data.
    5464              :          * This is because at the time of writing some browsers (Chrome) fail to
    5465              :          * render response before all the data is sent. */
    5466              :       }
    5467              :       mp->user_data = (void *) fus;
    5468              :       break;
    5469              :     }
    5470              :     case MG_EV_HTTP_PART_DATA: {
    5471              :       struct mg_http_multipart_part *mp =
    5472              :           (struct mg_http_multipart_part *) ev_data;
    5473              :       struct file_upload_state *fus =
    5474              :           (struct file_upload_state *) mp->user_data;
    5475              :       if (fus == NULL || fus->fp == NULL) break;
    5476              :       if (fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) {
    5477              :         LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn, errno,
    5478              :                        (int) fus->num_recd));
    5479              :         if (errno == ENOSPC
    5480              : #ifdef SPIFFS_ERR_FULL
    5481              :             || errno == SPIFFS_ERR_FULL
    5482              : #endif
    5483              :             ) {
    5484              :           mg_printf(nc,
    5485              :                     "HTTP/1.1 413 Payload Too Large\r\n"
    5486              :                     "Content-Type: text/plain\r\n"
    5487              :                     "Connection: close\r\n\r\n");
    5488              :           mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n",
    5489              :                     fus->lfn, (int) fus->num_recd);
    5490              :         } else {
    5491              :           mg_printf(nc,
    5492              :                     "HTTP/1.1 500 Internal Server Error\r\n"
    5493              :                     "Content-Type: text/plain\r\n"
    5494              :                     "Connection: close\r\n\r\n");
    5495              :           mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name,
    5496              :                     errno, (int) fus->num_recd);
    5497              :         }
    5498              :         fclose(fus->fp);
    5499              :         remove(fus->lfn);
    5500              :         fus->fp = NULL;
    5501              :         /* Do not close the connection just yet, discard remainder of the data.
    5502              :          * This is because at the time of writing some browsers (Chrome) fail to
    5503              :          * render response before all the data is sent. */
    5504              :         return;
    5505              :       }
    5506              :       fus->num_recd += mp->data.len;
    5507              :       LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len,
    5508              :                      (int) fus->num_recd));
    5509              :       break;
    5510              :     }
    5511              :     case MG_EV_HTTP_PART_END: {
    5512              :       struct mg_http_multipart_part *mp =
    5513              :           (struct mg_http_multipart_part *) ev_data;
    5514              :       struct file_upload_state *fus =
    5515              :           (struct file_upload_state *) mp->user_data;
    5516              :       if (fus == NULL) break;
    5517              :       if (mp->status >= 0 && fus->fp != NULL) {
    5518              :         LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name,
    5519              :                        fus->lfn, (int) fus->num_recd));
    5520              :         mg_printf(nc,
    5521              :                   "HTTP/1.1 200 OK\r\n"
    5522              :                   "Content-Type: text/plain\r\n"
    5523              :                   "Connection: close\r\n\r\n"
    5524              :                   "Ok, %s - %d bytes.\r\n",
    5525              :                   mp->file_name, (int) fus->num_recd);
    5526              :       } else {
    5527              :         LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn));
    5528              :         /*
    5529              :          * mp->status < 0 means connection was terminated, so no reason to send
    5530              :          * HTTP reply
    5531              :          */
    5532              :       }
    5533              :       if (fus->fp != NULL) fclose(fus->fp);
    5534              :       free(fus->lfn);
    5535              :       free(fus);
    5536              :       mp->user_data = NULL;
    5537              :       nc->flags |= MG_F_SEND_AND_CLOSE;
    5538              :       break;
    5539              :     }
    5540              :   }
    5541              : }
    5542              : 
    5543              : #endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
    5544              : 
    5545            0 : void mg_set_protocol_http_websocket(struct mg_connection *nc) {
    5546            0 :   nc->proto_handler = mg_http_handler;
    5547            0 : }
    5548              : 
    5549              : #ifndef MG_DISABLE_HTTP_WEBSOCKET
    5550              : 
    5551            0 : void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
    5552              :                                   const char *host, const char *protocol,
    5553              :                                   const char *extra_headers) {
    5554              :   /* pretty poor source of randomness, TODO fix */
    5555            0 :   unsigned long random = (unsigned long) path;
    5556              :   char key[sizeof(random) * 3];
    5557              : 
    5558            0 :   mg_base64_encode((unsigned char *) &random, sizeof(random), key);
    5559            0 :   mg_printf(nc,
    5560              :             "GET %s HTTP/1.1\r\n"
    5561              :             "Upgrade: websocket\r\n"
    5562              :             "Connection: Upgrade\r\n"
    5563              :             "Sec-WebSocket-Version: 13\r\n"
    5564              :             "Sec-WebSocket-Key: %s\r\n",
    5565              :             path, key);
    5566              : 
    5567              :   /* TODO(mkm): take default hostname from http proto data if host == NULL */
    5568            0 :   if (host != MG_WS_NO_HOST_HEADER_MAGIC) {
    5569            0 :     mg_printf(nc, "Host: %s\r\n", host);
    5570              :   }
    5571            0 :   if (protocol != NULL) {
    5572            0 :     mg_printf(nc, "Sec-WebSocket-Protocol: %s\r\n", protocol);
    5573              :   }
    5574            0 :   if (extra_headers != NULL) {
    5575            0 :     mg_printf(nc, "%s", extra_headers);
    5576              :   }
    5577            0 :   mg_printf(nc, "\r\n");
    5578            0 : }
    5579              : 
    5580            0 : void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
    5581              :                                  const char *extra_headers) {
    5582            0 :   mg_send_websocket_handshake2(nc, path, MG_WS_NO_HOST_HEADER_MAGIC, NULL,
    5583              :                                extra_headers);
    5584            0 : }
    5585              : 
    5586              : #endif /* MG_DISABLE_HTTP_WEBSOCKET */
    5587              : 
    5588            0 : void mg_send_response_line(struct mg_connection *nc, int status_code,
    5589              :                            const char *extra_headers) {
    5590            0 :   const char *status_message = "OK";
    5591            0 :   switch (status_code) {
    5592            0 :     case 206:
    5593            0 :       status_message = "Partial Content";
    5594            0 :       break;
    5595            0 :     case 301:
    5596            0 :       status_message = "Moved";
    5597            0 :       break;
    5598            0 :     case 302:
    5599            0 :       status_message = "Found";
    5600            0 :       break;
    5601            0 :     case 401:
    5602            0 :       status_message = "Unauthorized";
    5603            0 :       break;
    5604            0 :     case 403:
    5605            0 :       status_message = "Forbidden";
    5606            0 :       break;
    5607            0 :     case 404:
    5608            0 :       status_message = "Not Found";
    5609            0 :       break;
    5610            0 :     case 416:
    5611            0 :       status_message = "Requested range not satisfiable";
    5612            0 :       break;
    5613            0 :     case 418:
    5614            0 :       status_message = "I'm a teapot";
    5615            0 :       break;
    5616            0 :     case 500:
    5617            0 :       status_message = "Internal Server Error";
    5618            0 :       break;
    5619              :   }
    5620            0 :   mg_printf(nc, "HTTP/1.1 %d %s\r\n", status_code, status_message);
    5621            0 :   if (extra_headers != NULL) {
    5622            0 :     mg_printf(nc, "%s\r\n", extra_headers);
    5623              :   }
    5624            0 : }
    5625              : 
    5626            0 : void mg_send_head(struct mg_connection *c, int status_code,
    5627              :                   int64_t content_length, const char *extra_headers) {
    5628            0 :   mg_send_response_line(c, status_code, extra_headers);
    5629            0 :   if (content_length < 0) {
    5630            0 :     mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n");
    5631              :   } else {
    5632            0 :     mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length);
    5633              :   }
    5634            0 :   mg_send(c, "\r\n", 2);
    5635            0 : }
    5636              : 
    5637              : #ifdef MG_DISABLE_FILESYSTEM
    5638              : void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
    5639              :                    struct mg_serve_http_opts opts) {
    5640              :   mg_send_head(nc, 501, 0, NULL);
    5641              : }
    5642              : #else
    5643            0 : static void mg_http_send_error(struct mg_connection *nc, int code,
    5644              :                                const char *reason) {
    5645            0 :   if (!reason) reason = "";
    5646            0 :   DBG(("%p %d %s", nc, code, reason));
    5647            0 :   mg_send_head(nc, code, strlen(reason),
    5648              :                "Content-Type: text/plain\r\nConnection: close");
    5649            0 :   mg_send(nc, reason, strlen(reason));
    5650            0 :   nc->flags |= MG_F_SEND_AND_CLOSE;
    5651            0 : }
    5652              : #ifndef MG_DISABLE_SSI
    5653              : static void mg_send_ssi_file(struct mg_connection *, const char *, FILE *, int,
    5654              :                              const struct mg_serve_http_opts *);
    5655              : 
    5656            0 : static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
    5657              :   char buf[BUFSIZ];
    5658              :   size_t n;
    5659            0 :   while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
    5660            0 :     mg_send(nc, buf, n);
    5661              :   }
    5662            0 : }
    5663              : 
    5664              : #if 0
    5665              : static void mg_do_ssi_include(struct mg_connection *nc, const char *ssi,
    5666              :                               char *tag, int include_level,
    5667              :                               const struct mg_serve_http_opts *opts) {
    5668              :   char file_name[BUFSIZ], path[MAX_PATH_SIZE], *p;
    5669              :   FILE *fp;
    5670              : 
    5671              :   /*
    5672              :    * sscanf() is safe here, since send_ssi_file() also uses buffer
    5673              :    * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
    5674              :    */
    5675              :   if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
    5676              :     /* File name is relative to the webserver root */
    5677              :     snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
    5678              :   } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
    5679              :     /*
    5680              :      * File name is relative to the webserver working directory
    5681              :      * or it is absolute system path
    5682              :      */
    5683              :     snprintf(path, sizeof(path), "%s", file_name);
    5684              :   } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
    5685              :              sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
    5686              :     /* File name is relative to the currect document */
    5687              :     snprintf(path, sizeof(path), "%s", ssi);
    5688              :     if ((p = strrchr(path, DIRSEP)) != NULL) {
    5689              :       p[1] = '\0';
    5690              :     }
    5691              :     snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
    5692              :   } else {
    5693              :     mg_printf(nc, "Bad SSI #include: [%s]", tag);
    5694              :     return;
    5695              :   }
    5696              : 
    5697              :   if ((fp = fopen(path, "rb")) == NULL) {
    5698              :     mg_printf(nc, "SSI include error: fopen(%s): %s", path, strerror(errno));
    5699              :   } else {
    5700              :     mg_set_close_on_exec(fileno(fp));
    5701              :     if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
    5702              :         0) {
    5703              :       mg_send_ssi_file(nc, path, fp, include_level + 1, opts);
    5704              :     } else {
    5705              :       mg_send_file_data(nc, fp);
    5706              :     }
    5707              :     fclose(fp);
    5708              :   }
    5709              : }
    5710              : #endif
    5711              : 
    5712              : #ifndef MG_DISABLE_POPEN
    5713            0 : static void do_ssi_exec(struct mg_connection *nc, char *tag) {
    5714              :   char cmd[BUFSIZ];
    5715              :   FILE *fp;
    5716              : 
    5717            0 :   if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
    5718            0 :     mg_printf(nc, "Bad SSI #exec: [%s]", tag);
    5719            0 :   } else if ((fp = popen(cmd, "r")) == NULL) {
    5720            0 :     mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
    5721              :   } else {
    5722            0 :     mg_send_file_data(nc, fp);
    5723            0 :     pclose(fp);
    5724              :   }
    5725            0 : }
    5726              : #endif /* !MG_DISABLE_POPEN */
    5727              : 
    5728            0 : static void mg_do_ssi_call(struct mg_connection *nc, char *tag) {
    5729            0 :   mg_call(nc, NULL, MG_EV_SSI_CALL, tag);
    5730            0 : }
    5731              : 
    5732              : /*
    5733              :  * SSI directive has the following format:
    5734              :  * <!--#directive parameter=value parameter=value -->
    5735              :  */
    5736            0 : static void mg_send_ssi_file(struct mg_connection *nc, const char *path,
    5737              :                              FILE *fp, int include_level,
    5738              :                              const struct mg_serve_http_opts *opts) {
    5739            0 :   abort();
    5740              : #if 0
    5741              :   static const struct mg_str btag = MG_MK_STR("<!--#");
    5742              :   static const struct mg_str d_include = MG_MK_STR("include");
    5743              :   static const struct mg_str d_call = MG_MK_STR("call");
    5744              : #ifndef MG_DISABLE_POPEN
    5745              :   static const struct mg_str d_exec = MG_MK_STR("exec");
    5746              : #endif
    5747              :   char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
    5748              :   int ch, len, in_ssi_tag;
    5749              : 
    5750              :   if (include_level > 10) {
    5751              :     mg_printf(nc, "SSI #include level is too deep (%s)", path);
    5752              :     return;
    5753              :   }
    5754              : 
    5755              :   in_ssi_tag = len = 0;
    5756              :   while ((ch = fgetc(fp)) != EOF) {
    5757              :     if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
    5758              :       size_t i = len - 2;
    5759              :       in_ssi_tag = 0;
    5760              : 
    5761              :       /* Trim closing --> */
    5762              :       buf[i--] = '\0';
    5763              :       while (i > 0 && buf[i] == ' ') {
    5764              :         buf[i--] = '\0';
    5765              :       }
    5766              : 
    5767              :       /* Handle known SSI directives */
    5768              :       if (memcmp(p, d_include.p, d_include.len) == 0) {
    5769              :         mg_do_ssi_include(nc, path, p + d_include.len + 1, include_level, opts);
    5770              :       } else if (memcmp(p, d_call.p, d_call.len) == 0) {
    5771              :         mg_do_ssi_call(nc, p + d_call.len + 1);
    5772              : #ifndef MG_DISABLE_POPEN
    5773              :       } else if (memcmp(p, d_exec.p, d_exec.len) == 0) {
    5774              :         do_ssi_exec(nc, p + d_exec.len + 1);
    5775              : #endif
    5776              :       } else {
    5777              :         /* Silently ignore unknown SSI directive. */
    5778              :       }
    5779              :       len = 0;
    5780              :     } else if (ch == '<') {
    5781              :       in_ssi_tag = 1;
    5782              :       if (len > 0) {
    5783              :         mg_send(nc, buf, (size_t) len);
    5784              :       }
    5785              :       len = 0;
    5786              :       buf[len++] = ch & 0xff;
    5787              :     } else if (in_ssi_tag) {
    5788              :       if (len == (int) btag.len && memcmp(buf, btag.p, btag.len) != 0) {
    5789              :         /* Not an SSI tag */
    5790              :         in_ssi_tag = 0;
    5791              :       } else if (len == (int) sizeof(buf) - 2) {
    5792              :         mg_printf(nc, "%s: SSI tag is too large", path);
    5793              :         len = 0;
    5794              :       }
    5795              :       buf[len++] = ch & 0xff;
    5796              :     } else {
    5797              :       buf[len++] = ch & 0xff;
    5798              :       if (len == (int) sizeof(buf)) {
    5799              :         mg_send(nc, buf, (size_t) len);
    5800              :         len = 0;
    5801              :       }
    5802              :     }
    5803              :   }
    5804              : 
    5805              :   /* Send the rest of buffered data */
    5806              :   if (len > 0) {
    5807              :     mg_send(nc, buf, (size_t) len);
    5808              :   }
    5809              : #endif
    5810              : }
    5811              : 
    5812            0 : static void mg_handle_ssi_request(struct mg_connection *nc, const char *path,
    5813              :                                   const struct mg_serve_http_opts *opts) {
    5814              :   FILE *fp;
    5815              :   struct mg_str mime_type;
    5816              : 
    5817            0 :   if ((fp = fopen(path, "rb")) == NULL) {
    5818            0 :     mg_http_send_error(nc, 404, NULL);
    5819              :   } else {
    5820            0 :     mg_set_close_on_exec(fileno(fp));
    5821              : 
    5822            0 :     mime_type = mg_get_mime_type(path, "text/plain", opts);
    5823            0 :     mg_send_response_line(nc, 200, opts->extra_headers);
    5824            0 :     mg_printf(nc,
    5825              :               "Content-Type: %.*s\r\n"
    5826              :               "Connection: close\r\n\r\n",
    5827            0 :               (int) mime_type.len, mime_type.p);
    5828            0 :     mg_send_ssi_file(nc, path, fp, 0, opts);
    5829            0 :     fclose(fp);
    5830            0 :     nc->flags |= MG_F_SEND_AND_CLOSE;
    5831              :   }
    5832            0 : }
    5833              : #else
    5834              : static void mg_handle_ssi_request(struct mg_connection *nc, const char *path,
    5835              :                                   const struct mg_serve_http_opts *opts) {
    5836              :   (void) path;
    5837              :   (void) opts;
    5838              :   mg_http_send_error(nc, 500, "SSI disabled");
    5839              : }
    5840              : #endif /* MG_DISABLE_SSI */
    5841              : 
    5842            0 : static void mg_http_construct_etag(char *buf, size_t buf_len,
    5843              :                                    const cs_stat_t *st) {
    5844            0 :   snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
    5845            0 :            (int64_t) st->st_size);
    5846            0 : }
    5847            0 : static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
    5848            0 :   strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
    5849            0 : }
    5850              : 
    5851            0 : static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a,
    5852              :                                       int64_t *b) {
    5853              :   /*
    5854              :    * There is no snscanf. Headers are not guaranteed to be NUL-terminated,
    5855              :    * so we have this. Ugh.
    5856              :    */
    5857              :   int result;
    5858            0 :   char *p = (char *) MG_MALLOC(header->len + 1);
    5859            0 :   if (p == NULL) return 0;
    5860            0 :   memcpy(p, header->p, header->len);
    5861            0 :   p[header->len] = '\0';
    5862            0 :   result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
    5863            0 :   MG_FREE(p);
    5864            0 :   return result;
    5865              : }
    5866              : 
    5867            0 : static void mg_http_send_file2(struct mg_connection *nc, const char *path,
    5868              :                                cs_stat_t *st, struct http_message *hm,
    5869              :                                struct mg_serve_http_opts *opts) {
    5870            0 :   struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
    5871              :   struct mg_str mime_type;
    5872              : 
    5873            0 :   DBG(("%p [%s]", nc, path));
    5874            0 :   mg_http_free_proto_data_file(&pd->file);
    5875            0 :   if ((pd->file.fp = fopen(path, "rb")) == NULL) {
    5876              :     int code;
    5877            0 :     switch (errno) {
    5878            0 :       case EACCES:
    5879            0 :         code = 403;
    5880            0 :         break;
    5881            0 :       case ENOENT:
    5882            0 :         code = 404;
    5883            0 :         break;
    5884            0 :       default:
    5885            0 :         code = 500;
    5886              :     };
    5887            0 :     mg_http_send_error(nc, code, "Open failed");
    5888            0 :   } else if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern),
    5889            0 :                              path) > 0) {
    5890            0 :     mg_handle_ssi_request(nc, path, opts);
    5891              :   } else {
    5892              :     char etag[50], current_time[50], last_modified[50], range[70];
    5893            0 :     time_t t = time(NULL);
    5894            0 :     int64_t r1 = 0, r2 = 0, cl = st->st_size;
    5895            0 :     struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
    5896            0 :     int n, status_code = 200;
    5897              : 
    5898              :     /* Handle Range header */
    5899            0 :     range[0] = '\0';
    5900            0 :     if (range_hdr != NULL &&
    5901            0 :         (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
    5902            0 :         r2 >= 0) {
    5903              :       /* If range is specified like "400-", set second limit to content len */
    5904            0 :       if (n == 1) {
    5905            0 :         r2 = cl - 1;
    5906              :       }
    5907            0 :       if (r1 > r2 || r2 >= cl) {
    5908            0 :         status_code = 416;
    5909            0 :         cl = 0;
    5910            0 :         snprintf(range, sizeof(range),
    5911              :                  "Content-Range: bytes */%" INT64_FMT "\r\n",
    5912            0 :                  (int64_t) st->st_size);
    5913              :       } else {
    5914            0 :         status_code = 206;
    5915            0 :         cl = r2 - r1 + 1;
    5916            0 :         snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT
    5917              :                                        "-%" INT64_FMT "/%" INT64_FMT "\r\n",
    5918            0 :                  r1, r1 + cl - 1, (int64_t) st->st_size);
    5919              : #if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
    5920              :     _XOPEN_SOURCE >= 600
    5921            0 :         fseeko(pd->file.fp, r1, SEEK_SET);
    5922              : #else
    5923              :         fseek(pd->file.fp, r1, SEEK_SET);
    5924              : #endif
    5925              :       }
    5926              :     }
    5927              : 
    5928            0 :     mg_http_construct_etag(etag, sizeof(etag), st);
    5929            0 :     mg_gmt_time_string(current_time, sizeof(current_time), &t);
    5930            0 :     mg_gmt_time_string(last_modified, sizeof(last_modified), &st->st_mtime);
    5931            0 :     mime_type = mg_get_mime_type(path, "text/plain", opts);
    5932              :     /*
    5933              :      * Content length casted to size_t because:
    5934              :      * 1) that's the maximum buffer size anyway
    5935              :      * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
    5936              :      *    position
    5937              :      * TODO(mkm): fix ESP8266 RTOS SDK
    5938              :      */
    5939            0 :     mg_send_response_line(nc, status_code, opts->extra_headers);
    5940            0 :     mg_printf(nc,
    5941              :               "Date: %s\r\n"
    5942              :               "Last-Modified: %s\r\n"
    5943              :               "Accept-Ranges: bytes\r\n"
    5944              :               "Content-Type: %.*s\r\n"
    5945              : #ifdef MG_DISABLE_HTTP_KEEP_ALIVE
    5946              :               "Connection: close\r\n"
    5947              : #endif
    5948              :               "Content-Length: %" SIZE_T_FMT
    5949              :               "\r\n"
    5950              :               "%sEtag: %s\r\n\r\n",
    5951            0 :               current_time, last_modified, (int) mime_type.len, mime_type.p,
    5952              :               (size_t) cl, range, etag);
    5953              : 
    5954            0 :     pd->file.cl = cl;
    5955            0 :     pd->file.type = DATA_FILE;
    5956            0 :     mg_http_transfer_file_data(nc);
    5957              :   }
    5958            0 : }
    5959              : 
    5960              : #endif
    5961              : 
    5962            0 : int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
    5963              :                   int is_form_url_encoded) {
    5964              :   int i, j, a, b;
    5965              : #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
    5966              : 
    5967            0 :   for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
    5968            0 :     if (src[i] == '%') {
    5969            0 :       if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
    5970            0 :           isxdigit(*(const unsigned char *) (src + i + 2))) {
    5971            0 :         a = tolower(*(const unsigned char *) (src + i + 1));
    5972            0 :         b = tolower(*(const unsigned char *) (src + i + 2));
    5973            0 :         dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
    5974            0 :         i += 2;
    5975              :       } else {
    5976            0 :         return -1;
    5977              :       }
    5978            0 :     } else if (is_form_url_encoded && src[i] == '+') {
    5979            0 :       dst[j] = ' ';
    5980              :     } else {
    5981            0 :       dst[j] = src[i];
    5982              :     }
    5983              :   }
    5984              : 
    5985            0 :   dst[j] = '\0'; /* Null-terminate the destination */
    5986              : 
    5987            0 :   return i >= src_len ? j : -1;
    5988              : }
    5989              : 
    5990            0 : int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
    5991              :                     size_t dst_len) {
    5992              :   const char *p, *e, *s;
    5993              :   size_t name_len;
    5994              :   int len;
    5995              : 
    5996            0 :   if (dst == NULL || dst_len == 0) {
    5997            0 :     len = -2;
    5998            0 :   } else if (buf->p == NULL || name == NULL || buf->len == 0) {
    5999            0 :     len = -1;
    6000            0 :     dst[0] = '\0';
    6001              :   } else {
    6002            0 :     name_len = strlen(name);
    6003            0 :     e = buf->p + buf->len;
    6004            0 :     len = -1;
    6005            0 :     dst[0] = '\0';
    6006              : 
    6007            0 :     for (p = buf->p; p + name_len < e; p++) {
    6008            0 :       if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
    6009            0 :           !mg_ncasecmp(name, p, name_len)) {
    6010            0 :         p += name_len + 1;
    6011            0 :         s = (const char *) memchr(p, '&', (size_t)(e - p));
    6012            0 :         if (s == NULL) {
    6013            0 :           s = e;
    6014              :         }
    6015            0 :         len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
    6016            0 :         if (len == -1) {
    6017            0 :           len = -2;
    6018              :         }
    6019            0 :         break;
    6020              :       }
    6021              :     }
    6022              :   }
    6023              : 
    6024            0 :   return len;
    6025              : }
    6026              : 
    6027            0 : void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
    6028              :   char chunk_size[50];
    6029              :   int n;
    6030              : 
    6031            0 :   n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
    6032            0 :   mg_send(nc, chunk_size, n);
    6033            0 :   mg_send(nc, buf, len);
    6034            0 :   mg_send(nc, "\r\n", 2);
    6035            0 : }
    6036              : 
    6037            0 : void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
    6038            0 :   char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
    6039              :   int len;
    6040              :   va_list ap;
    6041              : 
    6042            0 :   va_start(ap, fmt);
    6043            0 :   len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
    6044            0 :   va_end(ap);
    6045              : 
    6046            0 :   if (len >= 0) {
    6047            0 :     mg_send_http_chunk(nc, buf, len);
    6048              :   }
    6049              : 
    6050              :   /* LCOV_EXCL_START */
    6051              :   if (buf != mem && buf != NULL) {
    6052              :     MG_FREE(buf);
    6053              :   }
    6054              :   /* LCOV_EXCL_STOP */
    6055            0 : }
    6056              : 
    6057            0 : void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
    6058            0 :   char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
    6059              :   int i, j, len;
    6060              :   va_list ap;
    6061              : 
    6062            0 :   va_start(ap, fmt);
    6063            0 :   len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
    6064            0 :   va_end(ap);
    6065              : 
    6066            0 :   if (len >= 0) {
    6067            0 :     for (i = j = 0; i < len; i++) {
    6068            0 :       if (buf[i] == '<' || buf[i] == '>') {
    6069            0 :         mg_send(nc, buf + j, i - j);
    6070            0 :         mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4);
    6071            0 :         j = i + 1;
    6072              :       }
    6073              :     }
    6074            0 :     mg_send(nc, buf + j, i - j);
    6075              :   }
    6076              : 
    6077              :   /* LCOV_EXCL_START */
    6078              :   if (buf != mem && buf != NULL) {
    6079              :     MG_FREE(buf);
    6080              :   }
    6081              :   /* LCOV_EXCL_STOP */
    6082            0 : }
    6083              : 
    6084            0 : int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
    6085              :                          size_t buf_size) {
    6086            0 :   int ch = ' ', ch1 = ',', len = 0, n = strlen(var_name);
    6087            0 :   const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
    6088              : 
    6089            0 :   if (buf != NULL && buf_size > 0) buf[0] = '\0';
    6090            0 :   if (hdr == NULL) return 0;
    6091              : 
    6092              :   /* Find where variable starts */
    6093            0 :   for (s = hdr->p; s != NULL && s + n < end; s++) {
    6094            0 :     if ((s == hdr->p || s[-1] == ch || s[-1] == ch1) && s[n] == '=' &&
    6095            0 :         !memcmp(s, var_name, n))
    6096            0 :       break;
    6097              :   }
    6098              : 
    6099            0 :   if (s != NULL && &s[n + 1] < end) {
    6100            0 :     s += n + 1;
    6101            0 :     if (*s == '"' || *s == '\'') {
    6102            0 :       ch = ch1 = *s++;
    6103              :     }
    6104            0 :     p = s;
    6105            0 :     while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) {
    6106            0 :       if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
    6107            0 :       buf[len++] = *p++;
    6108              :     }
    6109            0 :     if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
    6110            0 :       len = 0;
    6111              :     } else {
    6112            0 :       if (len > 0 && s[len - 1] == ',') len--;
    6113            0 :       if (len > 0 && s[len - 1] == ';') len--;
    6114            0 :       buf[len] = '\0';
    6115              :     }
    6116              :   }
    6117              : 
    6118            0 :   return len;
    6119              : }
    6120              : 
    6121              : #ifndef MG_DISABLE_FILESYSTEM
    6122            0 : static int mg_is_file_hidden(const char *path,
    6123              :                              const struct mg_serve_http_opts *opts,
    6124              :                              int exclude_specials) {
    6125            0 :   const char *p1 = opts->per_directory_auth_file;
    6126            0 :   const char *p2 = opts->hidden_file_pattern;
    6127              : 
    6128              :   /* Strip directory path from the file name */
    6129            0 :   const char *pdir = strrchr(path, DIRSEP);
    6130            0 :   if (pdir != NULL) {
    6131            0 :     path = pdir + 1;
    6132              :   }
    6133              : 
    6134            0 :   return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) ||
    6135            0 :          (p1 != NULL &&
    6136            0 :           mg_match_prefix(p1, strlen(p1), path) == (int) strlen(p1)) ||
    6137            0 :          (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
    6138              : }
    6139              : 
    6140              : #ifndef MG_DISABLE_HTTP_DIGEST_AUTH
    6141            0 : static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri,
    6142              :                          size_t uri_len, const char *ha1, size_t ha1_len,
    6143              :                          const char *nonce, size_t nonce_len, const char *nc,
    6144              :                          size_t nc_len, const char *cnonce, size_t cnonce_len,
    6145              :                          const char *qop, size_t qop_len, char *resp) {
    6146              :   static const char colon[] = ":";
    6147              :   static const size_t one = 1;
    6148              :   char ha2[33];
    6149              : 
    6150            0 :   cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
    6151            0 :   cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
    6152              :          nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
    6153              :          colon, one, ha2, sizeof(ha2) - 1, NULL);
    6154            0 : }
    6155              : 
    6156            0 : int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
    6157              :                                       const char *method, const char *uri,
    6158              :                                       const char *auth_domain, const char *user,
    6159              :                                       const char *passwd) {
    6160              :   static const char colon[] = ":", qop[] = "auth";
    6161              :   static const size_t one = 1;
    6162              :   char ha1[33], resp[33], cnonce[40];
    6163              : 
    6164            0 :   snprintf(cnonce, sizeof(cnonce), "%x", (unsigned int) time(NULL));
    6165            0 :   cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
    6166              :          (size_t) strlen(auth_domain), colon, one, passwd,
    6167              :          (size_t) strlen(passwd), NULL);
    6168            0 :   mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
    6169              :                cnonce, strlen(cnonce), "1", one, cnonce, strlen(cnonce), qop,
    6170              :                sizeof(qop) - 1, resp);
    6171            0 :   return snprintf(buf, buf_len,
    6172              :                   "Authorization: Digest username=\"%s\","
    6173              :                   "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
    6174              :                   "nonce=%s,response=%s\r\n",
    6175            0 :                   user, auth_domain, uri, qop, cnonce, cnonce, resp);
    6176              : }
    6177              : 
    6178              : /*
    6179              :  * Check for authentication timeout.
    6180              :  * Clients send time stamp encoded in nonce. Make sure it is not too old,
    6181              :  * to prevent replay attacks.
    6182              :  * Assumption: nonce is a hexadecimal number of seconds since 1970.
    6183              :  */
    6184            0 : static int mg_check_nonce(const char *nonce) {
    6185            0 :   unsigned long now = (unsigned long) time(NULL);
    6186            0 :   unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
    6187            0 :   return now < val || now - val < 3600;
    6188              : }
    6189              : 
    6190              : /*
    6191              :  * Authenticate HTTP request against opened passwords file.
    6192              :  * Returns 1 if authenticated, 0 otherwise.
    6193              :  */
    6194            0 : static int mg_http_check_digest_auth(struct http_message *hm,
    6195              :                                      const char *auth_domain, FILE *fp) {
    6196              :   struct mg_str *hdr;
    6197              :   char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
    6198              :   char user[50], cnonce[33], response[40], uri[200], qop[20], nc[20], nonce[30];
    6199              :   char expected_response[33];
    6200              : 
    6201              :   /* Parse "Authorization:" header, fail fast on parse error */
    6202            0 :   if (hm == NULL || fp == NULL ||
    6203            0 :       (hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
    6204            0 :       mg_http_parse_header(hdr, "username", user, sizeof(user)) == 0 ||
    6205            0 :       mg_http_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce)) == 0 ||
    6206            0 :       mg_http_parse_header(hdr, "response", response, sizeof(response)) == 0 ||
    6207            0 :       mg_http_parse_header(hdr, "uri", uri, sizeof(uri)) == 0 ||
    6208            0 :       mg_http_parse_header(hdr, "qop", qop, sizeof(qop)) == 0 ||
    6209            0 :       mg_http_parse_header(hdr, "nc", nc, sizeof(nc)) == 0 ||
    6210            0 :       mg_http_parse_header(hdr, "nonce", nonce, sizeof(nonce)) == 0 ||
    6211            0 :       mg_check_nonce(nonce) == 0) {
    6212            0 :     return 0;
    6213              :   }
    6214              : 
    6215              :   /*
    6216              :    * Read passwords file line by line. If should have htdigest format,
    6217              :    * i.e. each line should be a colon-separated sequence:
    6218              :    * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
    6219              :    */
    6220            0 :   while (fgets(buf, sizeof(buf), fp) != NULL) {
    6221            0 :     if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
    6222            0 :         strcmp(user, f_user) == 0 &&
    6223              :         /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
    6224            0 :         strcmp(auth_domain, f_domain) == 0) {
    6225              :       /* User and domain matched, check the password */
    6226            0 :       mg_mkmd5resp(
    6227              :           hm->method.p, hm->method.len, hm->uri.p,
    6228            0 :           hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0),
    6229              :           f_ha1, strlen(f_ha1), nonce, strlen(nonce), nc, strlen(nc), cnonce,
    6230              :           strlen(cnonce), qop, strlen(qop), expected_response);
    6231            0 :       return mg_casecmp(response, expected_response) == 0;
    6232              :     }
    6233              :   }
    6234              : 
    6235              :   /* None of the entries in the passwords file matched - return failure */
    6236            0 :   return 0;
    6237              : }
    6238              : 
    6239            0 : static int mg_is_authorized(struct http_message *hm, const char *path,
    6240              :                             int is_directory, const char *domain,
    6241              :                             const char *passwords_file,
    6242              :                             int is_global_pass_file) {
    6243              :   char buf[MG_MAX_PATH];
    6244              :   const char *p;
    6245              :   FILE *fp;
    6246            0 :   int authorized = 1;
    6247              : 
    6248            0 :   if (domain != NULL && passwords_file != NULL) {
    6249            0 :     if (is_global_pass_file) {
    6250            0 :       fp = fopen(passwords_file, "r");
    6251            0 :     } else if (is_directory) {
    6252            0 :       snprintf(buf, sizeof(buf), "%s%c%s", path, DIRSEP, passwords_file);
    6253            0 :       fp = fopen(buf, "r");
    6254              :     } else {
    6255            0 :       p = strrchr(path, DIRSEP);
    6256            0 :       if (p == NULL) p = path;
    6257            0 :       snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path), path, DIRSEP,
    6258              :                passwords_file);
    6259            0 :       fp = fopen(buf, "r");
    6260              :     }
    6261              : 
    6262            0 :     if (fp != NULL) {
    6263            0 :       authorized = mg_http_check_digest_auth(hm, domain, fp);
    6264            0 :       fclose(fp);
    6265              :     }
    6266              :   }
    6267              : 
    6268            0 :   DBG(("%s %s %d %d", path, passwords_file ? passwords_file : "",
    6269              :        is_global_pass_file, authorized));
    6270            0 :   return authorized;
    6271              : }
    6272              : #else
    6273              : static int mg_is_authorized(struct http_message *hm, const char *path,
    6274              :                             int is_directory, const char *domain,
    6275              :                             const char *passwords_file,
    6276              :                             int is_global_pass_file) {
    6277              :   (void) hm;
    6278              :   (void) path;
    6279              :   (void) is_directory;
    6280              :   (void) domain;
    6281              :   (void) passwords_file;
    6282              :   (void) is_global_pass_file;
    6283              :   return 1;
    6284              : }
    6285              : #endif
    6286              : 
    6287              : #ifndef MG_DISABLE_DIRECTORY_LISTING
    6288            0 : static size_t mg_url_encode(const char *src, size_t s_len, char *dst,
    6289              :                             size_t dst_len) {
    6290              :   static const char *dont_escape = "._-$,;~()/";
    6291              :   static const char *hex = "0123456789abcdef";
    6292            0 :   size_t i = 0, j = 0;
    6293              : 
    6294            0 :   for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
    6295            0 :     if (isalnum(*(const unsigned char *) (src + i)) ||
    6296            0 :         strchr(dont_escape, *(const unsigned char *) (src + i)) != NULL) {
    6297            0 :       dst[j] = src[i];
    6298            0 :     } else if (j + 3 < dst_len) {
    6299            0 :       dst[j] = '%';
    6300            0 :       dst[j + 1] = hex[(*(const unsigned char *) (src + i)) >> 4];
    6301            0 :       dst[j + 2] = hex[(*(const unsigned char *) (src + i)) & 0xf];
    6302            0 :       j += 2;
    6303              :     }
    6304              :   }
    6305              : 
    6306            0 :   dst[j] = '\0';
    6307            0 :   return j;
    6308              : }
    6309              : 
    6310            0 : static void mg_escape(const char *src, char *dst, size_t dst_len) {
    6311            0 :   size_t n = 0;
    6312            0 :   while (*src != '\0' && n + 5 < dst_len) {
    6313            0 :     unsigned char ch = *(unsigned char *) src++;
    6314            0 :     if (ch == '<') {
    6315            0 :       n += snprintf(dst + n, dst_len - n, "%s", "&lt;");
    6316              :     } else {
    6317            0 :       dst[n++] = ch;
    6318              :     }
    6319              :   }
    6320            0 :   dst[n] = '\0';
    6321            0 : }
    6322              : 
    6323            0 : static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name,
    6324              :                                cs_stat_t *stp) {
    6325              :   char size[64], mod[64], href[MAX_PATH_SIZE * 3], path[MAX_PATH_SIZE];
    6326            0 :   int64_t fsize = stp->st_size;
    6327            0 :   int is_dir = S_ISDIR(stp->st_mode);
    6328            0 :   const char *slash = is_dir ? "/" : "";
    6329              : 
    6330            0 :   if (is_dir) {
    6331            0 :     snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
    6332              :   } else {
    6333              :     /*
    6334              :      * We use (double) cast below because MSVC 6 compiler cannot
    6335              :      * convert unsigned __int64 to double.
    6336              :      */
    6337            0 :     if (fsize < 1024) {
    6338            0 :       snprintf(size, sizeof(size), "%d", (int) fsize);
    6339            0 :     } else if (fsize < 0x100000) {
    6340            0 :       snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
    6341            0 :     } else if (fsize < 0x40000000) {
    6342            0 :       snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
    6343              :     } else {
    6344            0 :       snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
    6345              :     }
    6346              :   }
    6347            0 :   strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
    6348            0 :   mg_escape(file_name, path, sizeof(path));
    6349            0 :   mg_url_encode(file_name, strlen(file_name), href, sizeof(href));
    6350            0 :   mg_printf_http_chunk(nc,
    6351              :                        "<tr><td><a href=\"%s%s\">%s%s</a></td>"
    6352              :                        "<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
    6353              :                        href, slash, path, slash, mod, is_dir ? -1 : fsize,
    6354              :                        size);
    6355            0 : }
    6356              : 
    6357            0 : static void mg_scan_directory(struct mg_connection *nc, const char *dir,
    6358              :                               const struct mg_serve_http_opts *opts,
    6359              :                               void (*func)(struct mg_connection *, const char *,
    6360              :                                            cs_stat_t *)) {
    6361              :   char path[MAX_PATH_SIZE];
    6362              :   cs_stat_t st;
    6363              :   struct dirent *dp;
    6364              :   DIR *dirp;
    6365              : 
    6366            0 :   DBG(("%p [%s]", nc, dir));
    6367            0 :   if ((dirp = (opendir(dir))) != NULL) {
    6368            0 :     while ((dp = readdir(dirp)) != NULL) {
    6369              :       /* Do not show current dir and hidden files */
    6370            0 :       if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
    6371            0 :         continue;
    6372              :       }
    6373            0 :       snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
    6374            0 :       if (mg_stat(path, &st) == 0) {
    6375            0 :         func(nc, (const char *) dp->d_name, &st);
    6376              :       }
    6377              :     }
    6378            0 :     closedir(dirp);
    6379              :   } else {
    6380            0 :     DBG(("%p opendir(%s) -> %d", nc, dir, errno));
    6381              :   }
    6382            0 : }
    6383              : 
    6384            0 : static void mg_send_directory_listing(struct mg_connection *nc, const char *dir,
    6385              :                                       struct http_message *hm,
    6386              :                                       struct mg_serve_http_opts *opts) {
    6387              :   static const char *sort_js_code =
    6388              :       "<script>function srt(tb, col) {"
    6389              :       "var tr = Array.prototype.slice.call(tb.rows, 0),"
    6390              :       "tr = tr.sort(function (a, b) { var c1 = a.cells[col], c2 = b.cells[col],"
    6391              :       "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
    6392              :       "t1 = a.cells[2].getAttribute('name'), "
    6393              :       "t2 = b.cells[2].getAttribute('name'); "
    6394              :       "return t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
    6395              :       "n1 ? parseInt(n2) - parseInt(n1) : "
    6396              :       "c1.textContent.trim().localeCompare(c2.textContent.trim()); });";
    6397              :   static const char *sort_js_code2 =
    6398              :       "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]);}"
    6399              :       "window.onload = function() { "
    6400              :       "var tb = document.getElementById('tb');"
    6401              :       "document.onclick = function(ev){ "
    6402              :       "var c = ev.target.rel; if (c) srt(tb, c)}; srt(tb, 2); };</script>";
    6403              : 
    6404            0 :   mg_send_response_line(nc, 200, opts->extra_headers);
    6405            0 :   mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked",
    6406              :             "Content-Type", "text/html; charset=utf-8");
    6407              : 
    6408            0 :   mg_printf_http_chunk(
    6409              :       nc,
    6410              :       "<html><head><title>Index of %.*s</title>%s%s"
    6411              :       "<style>th,td {text-align: left; padding-right: 1em; }</style></head>"
    6412              :       "<body><h1>Index of %.*s</h1><pre><table cellpadding=\"0\"><thead>"
    6413              :       "<tr><th><a href=# rel=0>Name</a></th><th>"
    6414              :       "<a href=# rel=1>Modified</a</th>"
    6415              :       "<th><a href=# rel=2>Size</a></th></tr>"
    6416              :       "<tr><td colspan=\"3\"><hr></td></tr></thead><tbody id=tb>",
    6417            0 :       (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
    6418            0 :       (int) hm->uri.len, hm->uri.p);
    6419            0 :   mg_scan_directory(nc, dir, opts, mg_print_dir_entry);
    6420            0 :   mg_printf_http_chunk(nc, "%s", "</tbody></body></html>");
    6421            0 :   mg_send_http_chunk(nc, "", 0);
    6422              :   /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
    6423            0 :   nc->flags |= MG_F_SEND_AND_CLOSE;
    6424            0 : }
    6425              : #endif /* MG_DISABLE_DIRECTORY_LISTING */
    6426              : 
    6427              : #ifndef MG_DISABLE_DAV
    6428            0 : static void mg_print_props(struct mg_connection *nc, const char *name,
    6429              :                            cs_stat_t *stp) {
    6430              :   char mtime[64], buf[MAX_PATH_SIZE * 3];
    6431            0 :   time_t t = stp->st_mtime; /* store in local variable for NDK compile */
    6432            0 :   mg_gmt_time_string(mtime, sizeof(mtime), &t);
    6433            0 :   mg_url_encode(name, strlen(name), buf, sizeof(buf));
    6434            0 :   mg_printf(nc,
    6435              :             "<d:response>"
    6436              :             "<d:href>%s</d:href>"
    6437              :             "<d:propstat>"
    6438              :             "<d:prop>"
    6439              :             "<d:resourcetype>%s</d:resourcetype>"
    6440              :             "<d:getcontentlength>%" INT64_FMT
    6441              :             "</d:getcontentlength>"
    6442              :             "<d:getlastmodified>%s</d:getlastmodified>"
    6443              :             "</d:prop>"
    6444              :             "<d:status>HTTP/1.1 200 OK</d:status>"
    6445              :             "</d:propstat>"
    6446              :             "</d:response>\n",
    6447            0 :             buf, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
    6448            0 :             (int64_t) stp->st_size, mtime);
    6449            0 : }
    6450              : 
    6451            0 : static void mg_handle_propfind(struct mg_connection *nc, const char *path,
    6452              :                                cs_stat_t *stp, struct http_message *hm,
    6453              :                                struct mg_serve_http_opts *opts) {
    6454              :   static const char header[] =
    6455              :       "HTTP/1.1 207 Multi-Status\r\n"
    6456              :       "Connection: close\r\n"
    6457              :       "Content-Type: text/xml; charset=utf-8\r\n\r\n"
    6458              :       "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    6459              :       "<d:multistatus xmlns:d='DAV:'>\n";
    6460              :   static const char footer[] = "</d:multistatus>\n";
    6461            0 :   const struct mg_str *depth = mg_get_http_header(hm, "Depth");
    6462              : 
    6463              :   /* Print properties for the requested resource itself */
    6464            0 :   if (S_ISDIR(stp->st_mode) &&
    6465            0 :       strcmp(opts->enable_directory_listing, "yes") != 0) {
    6466            0 :     mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
    6467              :   } else {
    6468              :     char uri[MAX_PATH_SIZE];
    6469            0 :     mg_send(nc, header, sizeof(header) - 1);
    6470            0 :     snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
    6471            0 :     mg_print_props(nc, uri, stp);
    6472            0 :     if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
    6473            0 :       mg_scan_directory(nc, path, opts, mg_print_props);
    6474              :     }
    6475            0 :     mg_send(nc, footer, sizeof(footer) - 1);
    6476            0 :     nc->flags |= MG_F_SEND_AND_CLOSE;
    6477              :   }
    6478            0 : }
    6479              : 
    6480              : #ifdef MG_ENABLE_FAKE_DAVLOCK
    6481              : /*
    6482              :  * Windows explorer (probably there are another WebDav clients like it)
    6483              :  * requires LOCK support in webdav. W/out this, it still works, but fails
    6484              :  * to save file: shows error message and offers "Save As".
    6485              :  * "Save as" works, but this message is very annoying.
    6486              :  * This is fake lock, which doesn't lock something, just returns LOCK token,
    6487              :  * UNLOCK always answers "OK".
    6488              :  * With this fake LOCK Windows Explorer looks happy and saves file.
    6489              :  * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
    6490              :  * Windows native DAV client. This is why FAKE LOCK is not enabed by default
    6491              :  */
    6492              : static void mg_handle_lock(struct mg_connection *nc, const char *path) {
    6493              :   static const char *reply =
    6494              :       "HTTP/1.1 207 Multi-Status\r\n"
    6495              :       "Connection: close\r\n"
    6496              :       "Content-Type: text/xml; charset=utf-8\r\n\r\n"
    6497              :       "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
    6498              :       "<d:multistatus xmlns:d='DAV:'>\n"
    6499              :       "<D:lockdiscovery>\n"
    6500              :       "<D:activelock>\n"
    6501              :       "<D:locktoken>\n"
    6502              :       "<D:href>\n"
    6503              :       "opaquelocktoken:%s%u"
    6504              :       "</D:href>"
    6505              :       "</D:locktoken>"
    6506              :       "</D:activelock>\n"
    6507              :       "</D:lockdiscovery>"
    6508              :       "</d:multistatus>\n";
    6509              :   mg_printf(nc, reply, path, (unsigned int) time(NULL));
    6510              :   nc->flags |= MG_F_SEND_AND_CLOSE;
    6511              : }
    6512              : #endif
    6513              : 
    6514            0 : static void mg_handle_mkcol(struct mg_connection *nc, const char *path,
    6515              :                             struct http_message *hm) {
    6516            0 :   int status_code = 500;
    6517            0 :   if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
    6518            0 :     status_code = 415;
    6519            0 :   } else if (!mg_mkdir(path, 0755)) {
    6520            0 :     status_code = 201;
    6521            0 :   } else if (errno == EEXIST) {
    6522            0 :     status_code = 405;
    6523            0 :   } else if (errno == EACCES) {
    6524            0 :     status_code = 403;
    6525            0 :   } else if (errno == ENOENT) {
    6526            0 :     status_code = 409;
    6527              :   } else {
    6528            0 :     status_code = 500;
    6529              :   }
    6530            0 :   mg_http_send_error(nc, status_code, NULL);
    6531            0 : }
    6532              : 
    6533            0 : static int mg_remove_directory(const struct mg_serve_http_opts *opts,
    6534              :                                const char *dir) {
    6535              :   char path[MAX_PATH_SIZE];
    6536              :   struct dirent *dp;
    6537              :   cs_stat_t st;
    6538              :   DIR *dirp;
    6539              : 
    6540            0 :   if ((dirp = opendir(dir)) == NULL) return 0;
    6541              : 
    6542            0 :   while ((dp = readdir(dirp)) != NULL) {
    6543            0 :     if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
    6544            0 :       continue;
    6545              :     }
    6546            0 :     snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
    6547            0 :     mg_stat(path, &st);
    6548            0 :     if (S_ISDIR(st.st_mode)) {
    6549            0 :       mg_remove_directory(opts, path);
    6550              :     } else {
    6551            0 :       remove(path);
    6552              :     }
    6553              :   }
    6554            0 :   closedir(dirp);
    6555            0 :   rmdir(dir);
    6556              : 
    6557            0 :   return 1;
    6558              : }
    6559              : 
    6560            0 : static void mg_handle_move(struct mg_connection *c,
    6561              :                            const struct mg_serve_http_opts *opts,
    6562              :                            const char *path, struct http_message *hm) {
    6563            0 :   const struct mg_str *dest = mg_get_http_header(hm, "Destination");
    6564            0 :   if (dest == NULL) {
    6565            0 :     mg_http_send_error(c, 411, NULL);
    6566              :   } else {
    6567            0 :     const char *p = (char *) memchr(dest->p, '/', dest->len);
    6568            0 :     if (p != NULL && p[1] == '/' &&
    6569            0 :         (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
    6570              :       char buf[MAX_PATH_SIZE];
    6571            0 :       snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
    6572            0 :                (int) (dest->p + dest->len - p), p);
    6573            0 :       if (rename(path, buf) == 0) {
    6574            0 :         mg_http_send_error(c, 200, NULL);
    6575              :       } else {
    6576            0 :         mg_http_send_error(c, 418, NULL);
    6577              :       }
    6578              :     } else {
    6579            0 :       mg_http_send_error(c, 500, NULL);
    6580              :     }
    6581              :   }
    6582            0 : }
    6583              : 
    6584            0 : static void mg_handle_delete(struct mg_connection *nc,
    6585              :                              const struct mg_serve_http_opts *opts,
    6586              :                              const char *path) {
    6587              :   cs_stat_t st;
    6588            0 :   if (mg_stat(path, &st) != 0) {
    6589            0 :     mg_http_send_error(nc, 404, NULL);
    6590            0 :   } else if (S_ISDIR(st.st_mode)) {
    6591            0 :     mg_remove_directory(opts, path);
    6592            0 :     mg_http_send_error(nc, 204, NULL);
    6593            0 :   } else if (remove(path) == 0) {
    6594            0 :     mg_http_send_error(nc, 204, NULL);
    6595              :   } else {
    6596            0 :     mg_http_send_error(nc, 423, NULL);
    6597              :   }
    6598            0 : }
    6599              : 
    6600              : /* Return -1 on error, 1 on success. */
    6601            0 : static int mg_create_itermediate_directories(const char *path) {
    6602              :   const char *s;
    6603              : 
    6604              :   /* Create intermediate directories if they do not exist */
    6605            0 :   for (s = path + 1; *s != '\0'; s++) {
    6606            0 :     if (*s == '/') {
    6607              :       char buf[MAX_PATH_SIZE];
    6608              :       cs_stat_t st;
    6609            0 :       snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
    6610            0 :       buf[sizeof(buf) - 1] = '\0';
    6611            0 :       if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
    6612            0 :         return -1;
    6613              :       }
    6614              :     }
    6615              :   }
    6616              : 
    6617            0 :   return 1;
    6618              : }
    6619              : 
    6620            0 : static void mg_handle_put(struct mg_connection *nc, const char *path,
    6621              :                           struct http_message *hm) {
    6622            0 :   struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
    6623              :   cs_stat_t st;
    6624            0 :   const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
    6625            0 :   int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
    6626              : 
    6627            0 :   mg_http_free_proto_data_file(&pd->file);
    6628            0 :   if ((rc = mg_create_itermediate_directories(path)) == 0) {
    6629            0 :     mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
    6630            0 :   } else if (rc == -1) {
    6631            0 :     mg_http_send_error(nc, 500, NULL);
    6632            0 :   } else if (cl_hdr == NULL) {
    6633            0 :     mg_http_send_error(nc, 411, NULL);
    6634            0 :   } else if ((pd->file.fp = fopen(path, "w+b")) == NULL) {
    6635            0 :     mg_http_send_error(nc, 500, NULL);
    6636              :   } else {
    6637            0 :     const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
    6638            0 :     int64_t r1 = 0, r2 = 0;
    6639            0 :     pd->file.type = DATA_PUT;
    6640            0 :     mg_set_close_on_exec(fileno(pd->file.fp));
    6641            0 :     pd->file.cl = to64(cl_hdr->p);
    6642            0 :     if (range_hdr != NULL &&
    6643            0 :         mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
    6644            0 :       status_code = 206;
    6645            0 :       fseeko(pd->file.fp, r1, SEEK_SET);
    6646            0 :       pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
    6647              :     }
    6648            0 :     mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
    6649              :     /* Remove HTTP request from the mbuf, leave only payload */
    6650            0 :     mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
    6651            0 :     mg_http_transfer_file_data(nc);
    6652              :   }
    6653            0 : }
    6654              : #endif /* MG_DISABLE_DAV */
    6655              : 
    6656            0 : static int mg_is_dav_request(const struct mg_str *s) {
    6657              :   static const char *methods[] = {"PUT", "DELETE", "MKCOL", "PROPFIND", "MOVE"
    6658              : #ifdef MG_ENABLE_FAKE_DAVLOCK
    6659              :                                   ,
    6660              :                                   "LOCK", "UNLOCK"
    6661              : #endif
    6662              :   };
    6663              :   size_t i;
    6664              : 
    6665            0 :   for (i = 0; i < ARRAY_SIZE(methods); i++) {
    6666            0 :     if (mg_vcmp(s, methods[i]) == 0) {
    6667            0 :       return 1;
    6668              :     }
    6669              :   }
    6670              : 
    6671            0 :   return 0;
    6672              : }
    6673              : 
    6674              : /*
    6675              :  * Given a directory path, find one of the files specified in the
    6676              :  * comma-separated list of index files `list`.
    6677              :  * First found index file wins. If an index file is found, then gets
    6678              :  * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
    6679              :  * If index file is not found, then `path` and `stp` remain unchanged.
    6680              :  */
    6681            0 : MG_INTERNAL void mg_find_index_file(const char *path, const char *list,
    6682              :                                     char **index_file, cs_stat_t *stp) {
    6683              :   struct mg_str vec;
    6684            0 :   size_t path_len = strlen(path);
    6685            0 :   int found = 0;
    6686            0 :   *index_file = NULL;
    6687              : 
    6688              :   /* Traverse index files list. For each entry, append it to the given */
    6689              :   /* path and see if the file exists. If it exists, break the loop */
    6690            0 :   while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
    6691              :     cs_stat_t st;
    6692            0 :     size_t len = path_len + 1 + vec.len + 1;
    6693            0 :     *index_file = (char *) MG_REALLOC(*index_file, len);
    6694            0 :     if (*index_file == NULL) break;
    6695            0 :     snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p);
    6696              : 
    6697              :     /* Does it exist? Is it a file? */
    6698            0 :     if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
    6699              :       /* Yes it does, break the loop */
    6700            0 :       *stp = st;
    6701            0 :       found = 1;
    6702            0 :       break;
    6703              :     }
    6704              :   }
    6705            0 :   if (!found) {
    6706            0 :     MG_FREE(*index_file);
    6707            0 :     *index_file = NULL;
    6708              :   }
    6709            0 :   DBG(("[%s] [%s]", path, (*index_file ? *index_file : "")));
    6710            0 : }
    6711              : 
    6712            0 : static int mg_http_send_port_based_redirect(
    6713              :     struct mg_connection *c, struct http_message *hm,
    6714              :     const struct mg_serve_http_opts *opts) {
    6715            0 :   const char *rewrites = opts->url_rewrites;
    6716              :   struct mg_str a, b;
    6717            0 :   char local_port[20] = {'%'};
    6718              : 
    6719            0 :   mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
    6720              :                       MG_SOCK_STRINGIFY_PORT);
    6721              : 
    6722            0 :   while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
    6723            0 :     if (mg_vcmp(&a, local_port) == 0) {
    6724            0 :       mg_send_response_line(c, 301, NULL);
    6725            0 :       mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
    6726            0 :                 (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
    6727              :                 hm->uri.p);
    6728            0 :       return 1;
    6729              :     }
    6730              :   }
    6731              : 
    6732            0 :   return 0;
    6733              : }
    6734              : 
    6735            0 : MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
    6736              :                                      const struct mg_serve_http_opts *opts,
    6737              :                                      char **local_path,
    6738              :                                      struct mg_str *remainder) {
    6739            0 :   int ok = 1;
    6740            0 :   const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len;
    6741            0 :   struct mg_str root = {NULL, 0};
    6742            0 :   const char *file_uri_start = cp;
    6743            0 :   *local_path = NULL;
    6744            0 :   remainder->p = NULL;
    6745            0 :   remainder->len = 0;
    6746              : 
    6747              :   { /* 1. Determine which root to use. */
    6748            0 :     const char *rewrites = opts->url_rewrites;
    6749            0 :     struct mg_str *hh = mg_get_http_header(hm, "Host");
    6750              :     struct mg_str a, b;
    6751              :     /* Check rewrites first. */
    6752            0 :     while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
    6753            0 :       if (a.len > 1 && a.p[0] == '@') {
    6754              :         /* Host rewrite. */
    6755            0 :         if (hh != NULL && hh->len == a.len - 1 &&
    6756            0 :             mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) {
    6757            0 :           root = b;
    6758            0 :           break;
    6759              :         }
    6760              :       } else {
    6761              :         /* Regular rewrite, URI=directory */
    6762            0 :         int match_len = mg_match_prefix_n(a, hm->uri);
    6763            0 :         if (match_len > 0) {
    6764            0 :           file_uri_start = hm->uri.p + match_len;
    6765            0 :           if (*file_uri_start == '/' || file_uri_start == cp_end) {
    6766              :             /* Match ended at component boundary, ok. */
    6767            0 :           } else if (*(file_uri_start - 1) == '/') {
    6768              :             /* Pattern ends with '/', backtrack. */
    6769            0 :             file_uri_start--;
    6770              :           } else {
    6771              :             /* No match: must fall on the component boundary. */
    6772            0 :             continue;
    6773              :           }
    6774            0 :           root = b;
    6775            0 :           break;
    6776              :         }
    6777              :       }
    6778              :     }
    6779              :     /* If no rewrite rules matched, use DAV or regular document root. */
    6780            0 :     if (root.p == NULL) {
    6781              : #ifndef MG_DISABLE_DAV
    6782            0 :       if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) {
    6783            0 :         root.p = opts->dav_document_root;
    6784            0 :         root.len = strlen(opts->dav_document_root);
    6785              :       } else
    6786              : #endif
    6787              :       {
    6788            0 :         root.p = opts->document_root;
    6789            0 :         root.len = strlen(opts->document_root);
    6790              :       }
    6791              :     }
    6792            0 :     assert(root.p != NULL && root.len > 0);
    6793              :   }
    6794              : 
    6795              :   { /* 2. Find where in the canonical URI path the local path ends. */
    6796            0 :     const char *u = file_uri_start + 1;
    6797            0 :     char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1);
    6798            0 :     char *lp_end = lp + root.len + hm->uri.len + 1;
    6799            0 :     char *p = lp, *ps;
    6800            0 :     int exists = 1;
    6801            0 :     if (lp == NULL) {
    6802            0 :       ok = 0;
    6803            0 :       goto out;
    6804              :     }
    6805            0 :     memcpy(p, root.p, root.len);
    6806            0 :     p += root.len;
    6807            0 :     if (*(p - 1) == DIRSEP) p--;
    6808            0 :     *p = '\0';
    6809            0 :     ps = p;
    6810              : 
    6811              :     /* Chop off URI path components one by one and build local path. */
    6812            0 :     while (u <= cp_end) {
    6813            0 :       const char *next = u;
    6814              :       struct mg_str component;
    6815            0 :       if (exists) {
    6816              :         cs_stat_t st;
    6817            0 :         exists = (mg_stat(lp, &st) == 0);
    6818            0 :         if (exists && S_ISREG(st.st_mode)) {
    6819              :           /* We found the terminal, the rest of the URI (if any) is path_info.
    6820              :            */
    6821            0 :           if (*(u - 1) == '/') u--;
    6822            0 :           break;
    6823              :         }
    6824              :       }
    6825            0 :       if (u >= cp_end) break;
    6826            0 :       parse_uri_component((const char **) &next, cp_end, '/', &component);
    6827            0 :       if (component.len > 0) {
    6828              :         int len;
    6829            0 :         memmove(p + 1, component.p, component.len);
    6830            0 :         len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0);
    6831            0 :         if (len <= 0) {
    6832            0 :           ok = 0;
    6833            0 :           break;
    6834              :         }
    6835            0 :         component.p = p + 1;
    6836            0 :         component.len = len;
    6837            0 :         if (mg_vcmp(&component, ".") == 0) {
    6838              :           /* Yum. */
    6839            0 :         } else if (mg_vcmp(&component, "..") == 0) {
    6840            0 :           while (p > ps && *p != DIRSEP) p--;
    6841            0 :           *p = '\0';
    6842              :         } else {
    6843              :           size_t i;
    6844              : #ifdef _WIN32
    6845              :           /* On Windows, make sure it's valid Unicode (no funny stuff). */
    6846              :           wchar_t buf[MG_MAX_PATH * 2];
    6847              :           if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) {
    6848              :             DBG(("[%.*s] smells funny", (int) component.len, component.p));
    6849              :             ok = 0;
    6850              :             break;
    6851              :           }
    6852              : #endif
    6853            0 :           *p++ = DIRSEP;
    6854              :           /* No NULs and DIRSEPs in the component (percent-encoded). */
    6855            0 :           for (i = 0; i < component.len; i++, p++) {
    6856            0 :             if (*p == '\0' || *p == DIRSEP
    6857              : #ifdef _WIN32
    6858              :                 /* On Windows, "/" is also accepted, so check for that too. */
    6859              :                 ||
    6860              :                 *p == '/'
    6861              : #endif
    6862              :                 ) {
    6863            0 :               ok = 0;
    6864            0 :               break;
    6865              :             }
    6866              :           }
    6867              :         }
    6868              :       }
    6869            0 :       u = next;
    6870              :     }
    6871            0 :     if (ok) {
    6872            0 :       *local_path = lp;
    6873            0 :       remainder->p = u;
    6874            0 :       remainder->len = cp_end - u;
    6875              :     } else {
    6876            0 :       MG_FREE(lp);
    6877              :     }
    6878              :   }
    6879              : 
    6880            0 : out:
    6881            0 :   DBG(("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p,
    6882              :        *local_path ? *local_path : "", (int) remainder->len, remainder->p));
    6883            0 :   return ok;
    6884              : }
    6885              : 
    6886              : #ifndef MG_DISABLE_CGI
    6887              : #ifdef _WIN32
    6888              : struct mg_threadparam {
    6889              :   sock_t s;
    6890              :   HANDLE hPipe;
    6891              : };
    6892              : 
    6893              : static int mg_wait_until_ready(sock_t sock, int for_read) {
    6894              :   fd_set set;
    6895              :   FD_ZERO(&set);
    6896              :   FD_SET(sock, &set);
    6897              :   return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
    6898              : }
    6899              : 
    6900              : static void *mg_push_to_stdin(void *arg) {
    6901              :   struct mg_threadparam *tp = (struct mg_threadparam *) arg;
    6902              :   int n, sent, stop = 0;
    6903              :   DWORD k;
    6904              :   char buf[BUFSIZ];
    6905              : 
    6906              :   while (!stop && mg_wait_until_ready(tp->s, 1) &&
    6907              :          (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
    6908              :     if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
    6909              :     for (sent = 0; !stop && sent < n; sent += k) {
    6910              :       if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
    6911              :     }
    6912              :   }
    6913              :   DBG(("%s", "FORWARED EVERYTHING TO CGI"));
    6914              :   CloseHandle(tp->hPipe);
    6915              :   MG_FREE(tp);
    6916              :   _endthread();
    6917              :   return NULL;
    6918              : }
    6919              : 
    6920              : static void *mg_pull_from_stdout(void *arg) {
    6921              :   struct mg_threadparam *tp = (struct mg_threadparam *) arg;
    6922              :   int k = 0, stop = 0;
    6923              :   DWORD n, sent;
    6924              :   char buf[BUFSIZ];
    6925              : 
    6926              :   while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
    6927              :     for (sent = 0; !stop && sent < n; sent += k) {
    6928              :       if (mg_wait_until_ready(tp->s, 0) &&
    6929              :           (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
    6930              :         stop = 1;
    6931              :     }
    6932              :   }
    6933              :   DBG(("%s", "EOF FROM CGI"));
    6934              :   CloseHandle(tp->hPipe);
    6935              :   shutdown(tp->s, 2);  // Without this, IO thread may get truncated data
    6936              :   closesocket(tp->s);
    6937              :   MG_FREE(tp);
    6938              :   _endthread();
    6939              :   return NULL;
    6940              : }
    6941              : 
    6942              : static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
    6943              :                                   void *(*func)(void *)) {
    6944              :   struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
    6945              :   if (tp != NULL) {
    6946              :     tp->s = sock;
    6947              :     tp->hPipe = hPipe;
    6948              :     mg_start_thread(func, tp);
    6949              :   }
    6950              : }
    6951              : 
    6952              : static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
    6953              :   wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
    6954              :   to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
    6955              :   GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
    6956              :   WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
    6957              : }
    6958              : 
    6959              : static pid_t mg_start_process(const char *interp, const char *cmd,
    6960              :                               const char *env, const char *envp[],
    6961              :                               const char *dir, sock_t sock) {
    6962              :   STARTUPINFOW si;
    6963              :   PROCESS_INFORMATION pi;
    6964              :   HANDLE a[2], b[2], me = GetCurrentProcess();
    6965              :   wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
    6966              :   char buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
    6967              :       buf4[MAX_PATH_SIZE], cmdline[MAX_PATH_SIZE];
    6968              :   DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
    6969              :   FILE *fp;
    6970              : 
    6971              :   memset(&si, 0, sizeof(si));
    6972              :   memset(&pi, 0, sizeof(pi));
    6973              : 
    6974              :   si.cb = sizeof(si);
    6975              :   si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
    6976              :   si.wShowWindow = SW_HIDE;
    6977              :   si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
    6978              : 
    6979              :   CreatePipe(&a[0], &a[1], NULL, 0);
    6980              :   CreatePipe(&b[0], &b[1], NULL, 0);
    6981              :   DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
    6982              :   DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
    6983              : 
    6984              :   if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
    6985              :     buf[0] = buf[1] = '\0';
    6986              :     fgets(buf, sizeof(buf), fp);
    6987              :     buf[sizeof(buf) - 1] = '\0';
    6988              :     if (buf[0] == '#' && buf[1] == '!') {
    6989              :       interp = buf + 2;
    6990              :       /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
    6991              :       while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
    6992              :         interp++;
    6993              :       }
    6994              :     }
    6995              :     fclose(fp);
    6996              :   }
    6997              : 
    6998              :   snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
    6999              :   mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
    7000              : 
    7001              :   mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
    7002              :   to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
    7003              : 
    7004              :   if (interp != NULL) {
    7005              :     mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
    7006              :     snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
    7007              :   } else {
    7008              :     snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
    7009              :   }
    7010              :   to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
    7011              : 
    7012              :   if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
    7013              :                      (void *) env, full_dir, &si, &pi) != 0) {
    7014              :     mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
    7015              :     mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
    7016              :   } else {
    7017              :     CloseHandle(a[1]);
    7018              :     CloseHandle(b[0]);
    7019              :     closesocket(sock);
    7020              :   }
    7021              :   DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
    7022              : 
    7023              :   /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
    7024              :   CloseHandle(si.hStdOutput);
    7025              :   CloseHandle(si.hStdInput);
    7026              :   /* TODO(lsm): check if we need close process and thread handles too */
    7027              :   /* CloseHandle(pi.hThread); */
    7028              :   /* CloseHandle(pi.hProcess); */
    7029              : 
    7030              :   return pi.hProcess;
    7031              : }
    7032              : #else
    7033              : static pid_t mg_start_process(const char *interp, const char *cmd,
    7034              :                               const char *env, const char *envp[],
    7035              :                               const char *dir, sock_t sock) {
    7036              :   char buf[500];
    7037              :   pid_t pid = fork();
    7038              :   (void) env;
    7039              : 
    7040              :   if (pid == 0) {
    7041              :     /*
    7042              :      * In Linux `chdir` declared with `warn_unused_result` attribute
    7043              :      * To shutup compiler we have yo use result in some way
    7044              :      */
    7045              :     int tmp = chdir(dir);
    7046              :     (void) tmp;
    7047              :     (void) dup2(sock, 0);
    7048              :     (void) dup2(sock, 1);
    7049              :     closesocket(sock);
    7050              : 
    7051              :     /*
    7052              :      * After exec, all signal handlers are restored to their default values,
    7053              :      * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
    7054              :      * implementation, SIGCHLD's handler will leave unchanged after exec
    7055              :      * if it was set to be ignored. Restore it to default action.
    7056              :      */
    7057              :     signal(SIGCHLD, SIG_DFL);
    7058              : 
    7059              :     if (interp == NULL) {
    7060              :       execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
    7061              :     } else {
    7062              :       execle(interp, interp, cmd, (char *) 0, envp);
    7063              :     }
    7064              :     snprintf(buf, sizeof(buf),
    7065              :              "Status: 500\r\n\r\n"
    7066              :              "500 Server Error: %s%s%s: %s",
    7067              :              interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
    7068              :              strerror(errno));
    7069              :     send(1, buf, strlen(buf), 0);
    7070              :     exit(EXIT_FAILURE); /* exec call failed */
    7071              :   }
    7072              : 
    7073              :   return pid;
    7074              : }
    7075              : #endif /* _WIN32 */
    7076              : 
    7077              : /*
    7078              :  * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
    7079              :  * pointer into the vars array.
    7080              :  */
    7081              : static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
    7082              :   int n, space;
    7083              :   char *added = block->buf + block->len;
    7084              :   va_list ap;
    7085              : 
    7086              :   /* Calculate how much space is left in the buffer */
    7087              :   space = sizeof(block->buf) - (block->len + 2);
    7088              :   if (space > 0) {
    7089              :     /* Copy VARIABLE=VALUE\0 string into the free space */
    7090              :     va_start(ap, fmt);
    7091              :     n = vsnprintf(added, (size_t) space, fmt, ap);
    7092              :     va_end(ap);
    7093              : 
    7094              :     /* Make sure we do not overflow buffer and the envp array */
    7095              :     if (n > 0 && n + 1 < space &&
    7096              :         block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
    7097              :       /* Append a pointer to the added string into the envp array */
    7098              :       block->vars[block->nvars++] = added;
    7099              :       /* Bump up used length counter. Include \0 terminator */
    7100              :       block->len += n + 1;
    7101              :     }
    7102              :   }
    7103              : 
    7104              :   return added;
    7105              : }
    7106              : 
    7107              : static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
    7108              :   const char *s;
    7109              :   if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
    7110              : }
    7111              : 
    7112              : static void mg_prepare_cgi_environment(struct mg_connection *nc,
    7113              :                                        const char *prog,
    7114              :                                        const struct mg_str *path_info,
    7115              :                                        const struct http_message *hm,
    7116              :                                        const struct mg_serve_http_opts *opts,
    7117              :                                        struct mg_cgi_env_block *blk) {
    7118              :   const char *s;
    7119              :   struct mg_str *h;
    7120              :   char *p;
    7121              :   size_t i;
    7122              : 
    7123              :   blk->len = blk->nvars = 0;
    7124              :   blk->nc = nc;
    7125              : 
    7126              :   if ((s = getenv("SERVER_NAME")) != NULL) {
    7127              :     mg_addenv(blk, "SERVER_NAME=%s", s);
    7128              :   } else {
    7129              :     char buf[100];
    7130              :     mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
    7131              :     mg_addenv(blk, "SERVER_NAME=%s", buf);
    7132              :   }
    7133              :   mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
    7134              :   mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
    7135              :   mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
    7136              : 
    7137              :   /* Prepare the environment block */
    7138              :   mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
    7139              :   mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
    7140              :   mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
    7141              : 
    7142              :   /* TODO(lsm): fix this for IPv6 case */
    7143              :   /*addenv(blk, "SERVER_PORT=%d", ri->remote_port); */
    7144              : 
    7145              :   mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
    7146              : #if 0
    7147              :   addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
    7148              :   addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
    7149              : #endif
    7150              :   mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
    7151              :             hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
    7152              :             hm->query_string.p);
    7153              : 
    7154              :   s = hm->uri.p + hm->uri.len - path_info->len - 1;
    7155              :   if (*s == '/') {
    7156              :     const char *base_name = strrchr(prog, DIRSEP);
    7157              :     mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
    7158              :               (base_name != NULL ? base_name + 1 : prog));
    7159              :   } else {
    7160              :     mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
    7161              :   }
    7162              :   mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
    7163              : 
    7164              :   if (path_info != NULL && path_info->len > 0) {
    7165              :     mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
    7166              :     /* Not really translated... */
    7167              :     mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
    7168              :   }
    7169              : 
    7170              :   mg_addenv(blk, "HTTPS=%s", nc->ssl != NULL ? "on" : "off");
    7171              : 
    7172              :   if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
    7173              :       NULL) {
    7174              :     mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
    7175              :   }
    7176              : 
    7177              :   if (hm->query_string.len > 0) {
    7178              :     mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
    7179              :               hm->query_string.p);
    7180              :   }
    7181              : 
    7182              :   if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
    7183              :       NULL) {
    7184              :     mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
    7185              :   }
    7186              : 
    7187              :   mg_addenv2(blk, "PATH");
    7188              :   mg_addenv2(blk, "TMP");
    7189              :   mg_addenv2(blk, "TEMP");
    7190              :   mg_addenv2(blk, "TMPDIR");
    7191              :   mg_addenv2(blk, "PERLLIB");
    7192              :   mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
    7193              : 
    7194              : #if defined(_WIN32)
    7195              :   mg_addenv2(blk, "COMSPEC");
    7196              :   mg_addenv2(blk, "SYSTEMROOT");
    7197              :   mg_addenv2(blk, "SystemDrive");
    7198              :   mg_addenv2(blk, "ProgramFiles");
    7199              :   mg_addenv2(blk, "ProgramFiles(x86)");
    7200              :   mg_addenv2(blk, "CommonProgramFiles(x86)");
    7201              : #else
    7202              :   mg_addenv2(blk, "LD_LIBRARY_PATH");
    7203              : #endif /* _WIN32 */
    7204              : 
    7205              :   /* Add all headers as HTTP_* variables */
    7206              :   for (i = 0; hm->header_names[i].len > 0; i++) {
    7207              :     p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
    7208              :                   hm->header_names[i].p, (int) hm->header_values[i].len,
    7209              :                   hm->header_values[i].p);
    7210              : 
    7211              :     /* Convert variable name into uppercase, and change - to _ */
    7212              :     for (; *p != '=' && *p != '\0'; p++) {
    7213              :       if (*p == '-') *p = '_';
    7214              :       *p = (char) toupper(*(unsigned char *) p);
    7215              :     }
    7216              :   }
    7217              : 
    7218              :   blk->vars[blk->nvars++] = NULL;
    7219              :   blk->buf[blk->len++] = '\0';
    7220              : }
    7221              : 
    7222              : static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
    7223              :                               void *ev_data) {
    7224              :   struct mg_connection *nc = (struct mg_connection *) cgi_nc->user_data;
    7225              :   (void) ev_data;
    7226              : 
    7227              :   if (nc == NULL) return;
    7228              : 
    7229              :   switch (ev) {
    7230              :     case MG_EV_RECV:
    7231              :       /*
    7232              :        * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
    7233              :        * It outputs headers, then body. Headers might include "Status"
    7234              :        * header, which changes CODE, and it might include "Location" header
    7235              :        * which changes CODE to 302.
    7236              :        *
    7237              :        * Therefore we do not send the output from the CGI script to the user
    7238              :        * until all CGI headers are received.
    7239              :        *
    7240              :        * Here we parse the output from the CGI script, and if all headers has
    7241              :        * been received, send appropriate reply line, and forward all
    7242              :        * received headers to the client.
    7243              :        */
    7244              :       if (nc->flags & MG_F_USER_1) {
    7245              :         struct mbuf *io = &cgi_nc->recv_mbuf;
    7246              :         int len = mg_http_get_request_len(io->buf, io->len);
    7247              : 
    7248              :         if (len == 0) break;
    7249              :         if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
    7250              :           cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
    7251              :           mg_http_send_error(nc, 500, "Bad headers");
    7252              :         } else {
    7253              :           struct http_message hm;
    7254              :           struct mg_str *h;
    7255              :           mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
    7256              :           if (mg_get_http_header(&hm, "Location") != NULL) {
    7257              :             mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
    7258              :           } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
    7259              :             mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
    7260              :           } else {
    7261              :             mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
    7262              :           }
    7263              :         }
    7264              :         nc->flags &= ~MG_F_USER_1;
    7265              :       }
    7266              :       if (!(nc->flags & MG_F_USER_1)) {
    7267              :         mg_forward(cgi_nc, nc);
    7268              :       }
    7269              :       break;
    7270              :     case MG_EV_CLOSE:
    7271              :       mg_http_free_proto_data_cgi(&mg_http_get_proto_data(cgi_nc)->cgi);
    7272              :       nc->flags |= MG_F_SEND_AND_CLOSE;
    7273              :       break;
    7274              :   }
    7275              : }
    7276              : 
    7277              : static void mg_handle_cgi(struct mg_connection *nc, const char *prog,
    7278              :                           const struct mg_str *path_info,
    7279              :                           const struct http_message *hm,
    7280              :                           const struct mg_serve_http_opts *opts) {
    7281              :   struct mg_cgi_env_block blk;
    7282              :   char dir[MAX_PATH_SIZE];
    7283              :   const char *p;
    7284              :   sock_t fds[2];
    7285              : 
    7286              :   DBG(("%p [%s]", nc, prog));
    7287              :   mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
    7288              :   /*
    7289              :    * CGI must be executed in its own directory. 'dir' must point to the
    7290              :    * directory containing executable program, 'p' must point to the
    7291              :    * executable program name relative to 'dir'.
    7292              :    */
    7293              :   if ((p = strrchr(prog, DIRSEP)) == NULL) {
    7294              :     snprintf(dir, sizeof(dir), "%s", ".");
    7295              :   } else {
    7296              :     snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
    7297              :     prog = p + 1;
    7298              :   }
    7299              : 
    7300              :   /*
    7301              :    * Try to create socketpair in a loop until success. mg_socketpair()
    7302              :    * can be interrupted by a signal and fail.
    7303              :    * TODO(lsm): use sigaction to restart interrupted syscall
    7304              :    */
    7305              :   do {
    7306              :     mg_socketpair(fds, SOCK_STREAM);
    7307              :   } while (fds[0] == INVALID_SOCKET);
    7308              : 
    7309              :   if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
    7310              :                        fds[1]) != 0) {
    7311              :     size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len);
    7312              :     struct mg_connection *cgi_nc =
    7313              :         mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler);
    7314              :     struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(cgi_nc);
    7315              :     cgi_pd->cgi.cgi_nc = cgi_nc;
    7316              :     cgi_pd->cgi.cgi_nc->user_data = nc;
    7317              :     nc->flags |= MG_F_USER_1;
    7318              :     /* Push POST data to the CGI */
    7319              :     if (n > 0 && n < nc->recv_mbuf.len) {
    7320              :       mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, n);
    7321              :     }
    7322              :     mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
    7323              :   } else {
    7324              :     closesocket(fds[0]);
    7325              :     mg_http_send_error(nc, 500, "CGI failure");
    7326              :   }
    7327              : 
    7328              : #ifndef _WIN32
    7329              :   closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
    7330              : #endif
    7331              : }
    7332              : #endif
    7333              : 
    7334            0 : static int mg_get_month_index(const char *s) {
    7335              :   static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
    7336              :                                       "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    7337              :   size_t i;
    7338              : 
    7339            0 :   for (i = 0; i < ARRAY_SIZE(month_names); i++)
    7340            0 :     if (!strcmp(s, month_names[i])) return (int) i;
    7341              : 
    7342            0 :   return -1;
    7343              : }
    7344              : 
    7345            0 : static int mg_num_leap_years(int year) {
    7346            0 :   return year / 4 - year / 100 + year / 400;
    7347              : }
    7348              : 
    7349              : /* Parse UTC date-time string, and return the corresponding time_t value. */
    7350            0 : MG_INTERNAL time_t mg_parse_date_string(const char *datetime) {
    7351              :   static const unsigned short days_before_month[] = {
    7352              :       0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
    7353              :   char month_str[32];
    7354              :   int second, minute, hour, day, month, year, leap_days, days;
    7355            0 :   time_t result = (time_t) 0;
    7356              : 
    7357            0 :   if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
    7358            0 :                &minute, &second) == 6) ||
    7359            0 :        (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
    7360            0 :                &minute, &second) == 6) ||
    7361            0 :        (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
    7362            0 :                &hour, &minute, &second) == 6) ||
    7363            0 :        (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
    7364            0 :                &minute, &second) == 6)) &&
    7365            0 :       year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
    7366            0 :     leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970);
    7367            0 :     year -= 1970;
    7368            0 :     days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
    7369            0 :     result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
    7370              :   }
    7371              : 
    7372            0 :   return result;
    7373              : }
    7374              : 
    7375            0 : MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) {
    7376              :   struct mg_str *hdr;
    7377            0 :   if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
    7378              :     char etag[64];
    7379            0 :     mg_http_construct_etag(etag, sizeof(etag), st);
    7380            0 :     return mg_vcasecmp(hdr, etag) == 0;
    7381            0 :   } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
    7382            0 :     return st->st_mtime <= mg_parse_date_string(hdr->p);
    7383              :   } else {
    7384            0 :     return 0;
    7385              :   }
    7386              : }
    7387              : 
    7388            0 : static void mg_http_send_digest_auth_request(struct mg_connection *c,
    7389              :                                              const char *domain) {
    7390            0 :   mg_printf(c,
    7391              :             "HTTP/1.1 401 Unauthorized\r\n"
    7392              :             "WWW-Authenticate: Digest qop=\"auth\", "
    7393              :             "realm=\"%s\", nonce=\"%lu\"\r\n"
    7394              :             "Content-Length: 0\r\n\r\n",
    7395            0 :             domain, (unsigned long) time(NULL));
    7396            0 : }
    7397              : 
    7398            0 : static void mg_http_send_options(struct mg_connection *nc) {
    7399            0 :   mg_printf(nc, "%s",
    7400              :             "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, OPTIONS"
    7401              : #ifndef MG_DISABLE_DAV
    7402              :             ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
    7403              : #endif
    7404              :             "\r\n\r\n");
    7405            0 :   nc->flags |= MG_F_SEND_AND_CLOSE;
    7406            0 : }
    7407              : 
    7408            0 : static int mg_is_creation_request(const struct http_message *hm) {
    7409            0 :   return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0;
    7410              : }
    7411              : 
    7412            0 : MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path,
    7413              :                                    const struct mg_str *path_info,
    7414              :                                    struct http_message *hm,
    7415              :                                    struct mg_serve_http_opts *opts) {
    7416            0 :   int exists, is_directory, is_dav = mg_is_dav_request(&hm->method);
    7417              :   int is_cgi;
    7418            0 :   char *index_file = NULL;
    7419              :   cs_stat_t st;
    7420              : 
    7421            0 :   exists = (mg_stat(path, &st) == 0);
    7422            0 :   is_directory = exists && S_ISDIR(st.st_mode);
    7423              : 
    7424            0 :   if (is_directory)
    7425            0 :     mg_find_index_file(path, opts->index_files, &index_file, &st);
    7426              : 
    7427            0 :   is_cgi =
    7428            0 :       (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
    7429            0 :                        index_file ? index_file : path) > 0);
    7430              : 
    7431            0 :   DBG(("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc,
    7432              :        (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav,
    7433              :        is_cgi, index_file ? index_file : ""));
    7434              : 
    7435            0 :   if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) {
    7436            0 :     mg_printf(nc,
    7437              :               "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
    7438              :               "Content-Length: 0\r\n\r\n",
    7439            0 :               (int) hm->uri.len, hm->uri.p);
    7440            0 :     MG_FREE(index_file);
    7441            0 :     return;
    7442              :   }
    7443              : 
    7444              :   /* If we have path_info, the only way to handle it is CGI. */
    7445            0 :   if (path_info->len > 0 && !is_cgi) {
    7446            0 :     mg_http_send_error(nc, 501, NULL);
    7447            0 :     MG_FREE(index_file);
    7448            0 :     return;
    7449              :   }
    7450              : 
    7451            0 :   if (is_dav && opts->dav_document_root == NULL) {
    7452            0 :     mg_http_send_error(nc, 501, NULL);
    7453            0 :   } else if (!mg_is_authorized(hm, path, is_directory, opts->auth_domain,
    7454            0 :                                opts->global_auth_file, 1) ||
    7455            0 :              !mg_is_authorized(hm, path, is_directory, opts->auth_domain,
    7456              :                                opts->per_directory_auth_file, 0)) {
    7457            0 :     mg_http_send_digest_auth_request(nc, opts->auth_domain);
    7458            0 :   } else if (is_cgi) {
    7459              : #if !defined(MG_DISABLE_CGI)
    7460              :     mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
    7461              : #else
    7462            0 :     mg_http_send_error(nc, 501, NULL);
    7463              : #endif /* MG_DISABLE_CGI */
    7464            0 :   } else if ((!exists ||
    7465            0 :               mg_is_file_hidden(path, opts, 0 /* specials are ok */)) &&
    7466            0 :              !mg_is_creation_request(hm)) {
    7467            0 :     mg_http_send_error(nc, 404, NULL);
    7468              : #ifndef MG_DISABLE_DAV
    7469            0 :   } else if (!mg_vcmp(&hm->method, "PROPFIND")) {
    7470            0 :     mg_handle_propfind(nc, path, &st, hm, opts);
    7471              : #ifndef MG_DISABLE_DAV_AUTH
    7472            0 :   } else if (is_dav &&
    7473            0 :              (opts->dav_auth_file == NULL ||
    7474            0 :               (strcmp(opts->dav_auth_file, "-") != 0 &&
    7475            0 :                !mg_is_authorized(hm, path, is_directory, opts->auth_domain,
    7476              :                                  opts->dav_auth_file, 1)))) {
    7477            0 :     mg_http_send_digest_auth_request(nc, opts->auth_domain);
    7478              : #endif
    7479            0 :   } else if (!mg_vcmp(&hm->method, "MKCOL")) {
    7480            0 :     mg_handle_mkcol(nc, path, hm);
    7481            0 :   } else if (!mg_vcmp(&hm->method, "DELETE")) {
    7482            0 :     mg_handle_delete(nc, opts, path);
    7483            0 :   } else if (!mg_vcmp(&hm->method, "PUT")) {
    7484            0 :     mg_handle_put(nc, path, hm);
    7485            0 :   } else if (!mg_vcmp(&hm->method, "MOVE")) {
    7486            0 :     mg_handle_move(nc, opts, path, hm);
    7487              : #ifdef MG_ENABLE_FAKE_DAVLOCK
    7488              :   } else if (!mg_vcmp(&hm->method, "LOCK")) {
    7489              :     mg_handle_lock(nc, path);
    7490              : #endif
    7491              : #endif
    7492            0 :   } else if (!mg_vcmp(&hm->method, "OPTIONS")) {
    7493            0 :     mg_http_send_options(nc);
    7494            0 :   } else if (is_directory && index_file == NULL) {
    7495              : #ifndef MG_DISABLE_DIRECTORY_LISTING
    7496            0 :     if (strcmp(opts->enable_directory_listing, "yes") == 0) {
    7497            0 :       mg_send_directory_listing(nc, path, hm, opts);
    7498              :     } else {
    7499            0 :       mg_http_send_error(nc, 403, NULL);
    7500              :     }
    7501              : #else
    7502              :     mg_http_send_error(nc, 501, NULL);
    7503              : #endif
    7504            0 :   } else if (mg_is_not_modified(hm, &st)) {
    7505            0 :     mg_http_send_error(nc, 304, "Not Modified");
    7506              :   } else {
    7507            0 :     mg_http_send_file2(nc, index_file ? index_file : path, &st, hm, opts);
    7508              :   }
    7509            0 :   MG_FREE(index_file);
    7510              : }
    7511              : 
    7512            0 : void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
    7513              :                    struct mg_serve_http_opts opts) {
    7514            0 :   char *path = NULL;
    7515              :   struct mg_str *hdr, path_info;
    7516            0 :   uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
    7517              : 
    7518            0 :   if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) {
    7519              :     /* Not allowed to connect */
    7520            0 :     mg_http_send_error(nc, 403, NULL);
    7521            0 :     nc->flags |= MG_F_SEND_AND_CLOSE;
    7522            0 :     return;
    7523              :   }
    7524              : 
    7525            0 :   if (mg_http_send_port_based_redirect(nc, hm, &opts)) {
    7526            0 :     return;
    7527              :   }
    7528              : 
    7529            0 :   if (opts.document_root == NULL) {
    7530            0 :     opts.document_root = ".";
    7531              :   }
    7532            0 :   if (opts.per_directory_auth_file == NULL) {
    7533            0 :     opts.per_directory_auth_file = ".htpasswd";
    7534              :   }
    7535            0 :   if (opts.enable_directory_listing == NULL) {
    7536            0 :     opts.enable_directory_listing = "yes";
    7537              :   }
    7538            0 :   if (opts.cgi_file_pattern == NULL) {
    7539            0 :     opts.cgi_file_pattern = "**.cgi$|**.php$";
    7540              :   }
    7541            0 :   if (opts.ssi_pattern == NULL) {
    7542            0 :     opts.ssi_pattern = "**.shtml$|**.shtm$";
    7543              :   }
    7544            0 :   if (opts.index_files == NULL) {
    7545            0 :     opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
    7546              :   }
    7547              :   /* Normalize path - resolve "." and ".." (in-place). */
    7548            0 :   if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
    7549            0 :     mg_http_send_error(nc, 400, NULL);
    7550            0 :     return;
    7551              :   }
    7552            0 :   if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) {
    7553            0 :     mg_http_send_error(nc, 404, NULL);
    7554            0 :     return;
    7555              :   }
    7556            0 :   mg_send_http_file(nc, path, &path_info, hm, &opts);
    7557              : 
    7558            0 :   MG_FREE(path);
    7559            0 :   path = NULL;
    7560              : 
    7561              :   /* Close connection for non-keep-alive requests */
    7562            0 :   if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
    7563            0 :       ((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
    7564            0 :        mg_vcmp(hdr, "keep-alive") != 0)) {
    7565              : #if 0
    7566              :     nc->flags |= MG_F_SEND_AND_CLOSE;
    7567              : #endif
    7568              :   }
    7569              : }
    7570              : 
    7571              : #endif /* MG_DISABLE_FILESYSTEM */
    7572              : 
    7573              : /* returns 0 on success, -1 on error */
    7574            0 : static int mg_http_common_url_parse(const char *url, const char *schema,
    7575              :                                     const char *schema_tls, int *use_ssl,
    7576              :                                     char **addr, int *port_i,
    7577              :                                     const char **path) {
    7578            0 :   int addr_len = 0;
    7579              : 
    7580            0 :   if (memcmp(url, schema, strlen(schema)) == 0) {
    7581            0 :     url += strlen(schema);
    7582            0 :   } else if (memcmp(url, schema_tls, strlen(schema_tls)) == 0) {
    7583            0 :     url += strlen(schema_tls);
    7584            0 :     *use_ssl = 1;
    7585              : #ifndef MG_ENABLE_SSL
    7586            0 :     return -1; /* SSL is not enabled, cannot do HTTPS URLs */
    7587              : #endif
    7588              :   }
    7589              : 
    7590            0 :   while (*url != '\0') {
    7591            0 :     *addr = (char *) MG_REALLOC(*addr, addr_len + 5 /* space for port too. */);
    7592            0 :     if (*addr == NULL) {
    7593            0 :       DBG(("OOM"));
    7594            0 :       return -1;
    7595              :     }
    7596            0 :     if (*url == '/') {
    7597            0 :       break;
    7598              :     }
    7599            0 :     if (*url == ':') *port_i = addr_len;
    7600            0 :     (*addr)[addr_len++] = *url;
    7601            0 :     (*addr)[addr_len] = '\0';
    7602            0 :     url++;
    7603              :   }
    7604            0 :   if (addr_len == 0) goto cleanup;
    7605            0 :   if (*port_i < 0) {
    7606            0 :     *port_i = addr_len;
    7607            0 :     strcpy(*addr + *port_i, *use_ssl ? ":443" : ":80");
    7608              :   } else {
    7609            0 :     *port_i = -1;
    7610              :   }
    7611              : 
    7612            0 :   if (*path == NULL) *path = url;
    7613              : 
    7614            0 :   if (**path == '\0') *path = "/";
    7615              : 
    7616            0 :   DBG(("%s %s", *addr, *path));
    7617              : 
    7618            0 :   return 0;
    7619              : 
    7620            0 : cleanup:
    7621            0 :   MG_FREE(*addr);
    7622            0 :   return -1;
    7623              : }
    7624              : 
    7625            0 : struct mg_connection *mg_connect_http_base(
    7626              :     struct mg_mgr *mgr, mg_event_handler_t ev_handler,
    7627              :     struct mg_connect_opts opts, const char *schema, const char *schema_ssl,
    7628              :     const char *url, const char **path, char **addr) {
    7629            0 :   struct mg_connection *nc = NULL;
    7630            0 :   int port_i = -1;
    7631            0 :   int use_ssl = 0;
    7632              : 
    7633            0 :   if (mg_http_common_url_parse(url, schema, schema_ssl, &use_ssl, addr, &port_i,
    7634            0 :                                path) < 0) {
    7635            0 :     return NULL;
    7636              :   }
    7637              : 
    7638              : #ifndef MG_ENABLE_SSL
    7639            0 :   if (use_ssl) {
    7640            0 :     MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
    7641            0 :     MG_FREE(addr);
    7642            0 :     return NULL;
    7643              :   }
    7644              : #endif
    7645              : 
    7646            0 :   if ((nc = mg_connect_opt(mgr, *addr, ev_handler, opts)) != NULL) {
    7647              : #ifdef MG_ENABLE_SSL
    7648              :     if (use_ssl && nc->ssl_ctx == NULL) {
    7649              :       /*
    7650              :        * Schema requires SSL, but no SSL parameters were provided in
    7651              :        * opts. In order to maintain backward compatibility, use
    7652              :        * NULL, NULL
    7653              :        */
    7654              :       mg_set_ssl(nc, NULL, NULL);
    7655              :     }
    7656              : #endif
    7657            0 :     mg_set_protocol_http_websocket(nc);
    7658              : 
    7659              :     /* If the port was addred by us, restore the original host. */
    7660            0 :     if (port_i >= 0) (*addr)[port_i] = '\0';
    7661              :   }
    7662              : 
    7663            0 :   return nc;
    7664              : }
    7665              : 
    7666            0 : struct mg_connection *mg_connect_http_opt(struct mg_mgr *mgr,
    7667              :                                           mg_event_handler_t ev_handler,
    7668              :                                           struct mg_connect_opts opts,
    7669              :                                           const char *url,
    7670              :                                           const char *extra_headers,
    7671              :                                           const char *post_data) {
    7672            0 :   char *addr = NULL;
    7673            0 :   const char *path = NULL;
    7674            0 :   struct mg_connection *nc = mg_connect_http_base(
    7675              :       mgr, ev_handler, opts, "http://", "https://", url, &path, &addr);
    7676              : 
    7677            0 :   if (nc == NULL) {
    7678            0 :     return NULL;
    7679              :   }
    7680              : 
    7681            0 :   mg_printf(nc, "%s %s HTTP/1.1\r\nHost: %s\r\nContent-Length: %" SIZE_T_FMT
    7682              :                 "\r\n%s\r\n%s",
    7683              :             post_data == NULL ? "GET" : "POST", path, addr,
    7684            0 :             post_data == NULL ? 0 : strlen(post_data),
    7685              :             extra_headers == NULL ? "" : extra_headers,
    7686              :             post_data == NULL ? "" : post_data);
    7687              : 
    7688            0 :   MG_FREE(addr);
    7689            0 :   return nc;
    7690              : }
    7691              : 
    7692            0 : struct mg_connection *mg_connect_http(struct mg_mgr *mgr,
    7693              :                                       mg_event_handler_t ev_handler,
    7694              :                                       const char *url,
    7695              :                                       const char *extra_headers,
    7696              :                                       const char *post_data) {
    7697              :   struct mg_connect_opts opts;
    7698            0 :   memset(&opts, 0, sizeof(opts));
    7699            0 :   return mg_connect_http_opt(mgr, ev_handler, opts, url, extra_headers,
    7700            0 :                              post_data);
    7701              : }
    7702              : 
    7703            0 : struct mg_connection *mg_connect_ws_opt(struct mg_mgr *mgr,
    7704              :                                         mg_event_handler_t ev_handler,
    7705              :                                         struct mg_connect_opts opts,
    7706              :                                         const char *url, const char *protocol,
    7707              :                                         const char *extra_headers) {
    7708            0 :   char *addr = NULL;
    7709            0 :   const char *path = NULL;
    7710            0 :   struct mg_connection *nc = mg_connect_http_base(
    7711              :       mgr, ev_handler, opts, "ws://", "wss://", url, &path, &addr);
    7712              : 
    7713            0 :   if (nc == NULL) {
    7714            0 :     return NULL;
    7715              :   }
    7716              : 
    7717            0 :   mg_send_websocket_handshake2(nc, path, addr, protocol, extra_headers);
    7718              : 
    7719            0 :   MG_FREE(addr);
    7720            0 :   return nc;
    7721              : }
    7722              : 
    7723            0 : struct mg_connection *mg_connect_ws(struct mg_mgr *mgr,
    7724              :                                     mg_event_handler_t ev_handler,
    7725              :                                     const char *url, const char *protocol,
    7726              :                                     const char *extra_headers) {
    7727              :   struct mg_connect_opts opts;
    7728            0 :   memset(&opts, 0, sizeof(opts));
    7729            0 :   return mg_connect_ws_opt(mgr, ev_handler, opts, url, protocol, extra_headers);
    7730              : }
    7731              : 
    7732            0 : size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
    7733              :                           size_t var_name_len, char *file_name,
    7734              :                           size_t file_name_len, const char **data,
    7735              :                           size_t *data_len) {
    7736              :   static const char cd[] = "Content-Disposition: ";
    7737            0 :   size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
    7738              : 
    7739            0 :   if (buf == NULL || buf_len <= 0) return 0;
    7740            0 :   if ((hl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
    7741            0 :   if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
    7742              : 
    7743              :   /* Get boundary length */
    7744            0 :   bl = mg_get_line_len(buf, buf_len);
    7745              : 
    7746              :   /* Loop through headers, fetch variable name and file name */
    7747            0 :   var_name[0] = file_name[0] = '\0';
    7748            0 :   for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
    7749            0 :     if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
    7750              :       struct mg_str header;
    7751            0 :       header.p = buf + n + cdl;
    7752            0 :       header.len = ll - (cdl + 2);
    7753            0 :       mg_http_parse_header(&header, "name", var_name, var_name_len);
    7754            0 :       mg_http_parse_header(&header, "filename", file_name, file_name_len);
    7755              :     }
    7756              :   }
    7757              : 
    7758              :   /* Scan through the body, search for terminating boundary */
    7759            0 :   for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
    7760            0 :     if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
    7761            0 :       if (data_len != NULL) *data_len = (pos - 2) - hl;
    7762            0 :       if (data != NULL) *data = buf + hl;
    7763            0 :       return pos;
    7764              :     }
    7765              :   }
    7766              : 
    7767            0 :   return 0;
    7768              : }
    7769              : 
    7770            0 : void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
    7771              :                                mg_event_handler_t handler) {
    7772            0 :   struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
    7773              :   struct mg_http_endpoint *new_ep =
    7774            0 :       (struct mg_http_endpoint *) calloc(1, sizeof(*new_ep));
    7775            0 :   new_ep->name = strdup(uri_path);
    7776            0 :   new_ep->name_len = strlen(new_ep->name);
    7777            0 :   new_ep->handler = handler;
    7778            0 :   new_ep->next = pd->endpoints;
    7779            0 :   pd->endpoints = new_ep;
    7780            0 : }
    7781              : 
    7782              : #endif /* MG_DISABLE_HTTP */
    7783              : #ifdef MG_MODULE_LINES
    7784              : #line 1 "./src/util.c"
    7785              : #endif
    7786              : /*
    7787              :  * Copyright (c) 2014 Cesanta Software Limited
    7788              :  * All rights reserved
    7789              :  */
    7790              : 
    7791              : /* Amalgamated: #include "common/base64.h" */
    7792              : /* Amalgamated: #include "mongoose/src/internal.h" */
    7793              : /* Amalgamated: #include "mongoose/src/util.h" */
    7794              : 
    7795            0 : const char *mg_skip(const char *s, const char *end, const char *delims,
    7796              :                     struct mg_str *v) {
    7797            0 :   v->p = s;
    7798            0 :   while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
    7799            0 :   v->len = s - v->p;
    7800            0 :   while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
    7801            0 :   return s;
    7802              : }
    7803              : 
    7804            0 : static int lowercase(const char *s) {
    7805            0 :   return tolower(*(const unsigned char *) s);
    7806              : }
    7807              : 
    7808            0 : int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
    7809            0 :   int diff = 0;
    7810              : 
    7811            0 :   if (len > 0) do {
    7812            0 :       diff = lowercase(s1++) - lowercase(s2++);
    7813            0 :     } while (diff == 0 && s1[-1] != '\0' && --len > 0);
    7814              : 
    7815            0 :   return diff;
    7816              : }
    7817              : 
    7818            0 : int mg_casecmp(const char *s1, const char *s2) {
    7819            0 :   return mg_ncasecmp(s1, s2, (size_t) ~0);
    7820              : }
    7821              : 
    7822            0 : int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
    7823            0 :   size_t n2 = strlen(str2), n1 = str1->len;
    7824            0 :   int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
    7825            0 :   if (r == 0) {
    7826            0 :     return n1 - n2;
    7827              :   }
    7828            0 :   return r;
    7829              : }
    7830              : 
    7831            0 : int mg_vcmp(const struct mg_str *str1, const char *str2) {
    7832            0 :   size_t n2 = strlen(str2), n1 = str1->len;
    7833            0 :   int r = memcmp(str1->p, str2, (n1 < n2) ? n1 : n2);
    7834            0 :   if (r == 0) {
    7835            0 :     return n1 - n2;
    7836              :   }
    7837            0 :   return r;
    7838              : }
    7839              : 
    7840              : #ifndef MG_DISABLE_FILESYSTEM
    7841            0 : int mg_stat(const char *path, cs_stat_t *st) {
    7842              : #ifdef _WIN32
    7843              :   wchar_t wpath[MAX_PATH_SIZE];
    7844              :   to_wchar(path, wpath, ARRAY_SIZE(wpath));
    7845              :   DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
    7846              :   return _wstati64(wpath, (struct _stati64 *) st);
    7847              : #else
    7848            0 :   return stat(path, st);
    7849              : #endif
    7850              : }
    7851              : 
    7852            0 : FILE *mg_fopen(const char *path, const char *mode) {
    7853              : #ifdef _WIN32
    7854              :   wchar_t wpath[MAX_PATH_SIZE], wmode[10];
    7855              :   to_wchar(path, wpath, ARRAY_SIZE(wpath));
    7856              :   to_wchar(mode, wmode, ARRAY_SIZE(wmode));
    7857              :   return _wfopen(wpath, wmode);
    7858              : #else
    7859            0 :   return fopen(path, mode);
    7860              : #endif
    7861              : }
    7862              : 
    7863              : int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
    7864              : #ifdef _WIN32
    7865              :   wchar_t wpath[MAX_PATH_SIZE];
    7866              :   to_wchar(path, wpath, ARRAY_SIZE(wpath));
    7867              :   return _wopen(wpath, flag, mode);
    7868              : #else
    7869              :   return open(path, flag, mode); /* LCOV_EXCL_LINE */
    7870              : #endif
    7871              : }
    7872              : #endif
    7873              : 
    7874            0 : void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
    7875            0 :   cs_base64_encode(src, src_len, dst);
    7876            0 : }
    7877              : 
    7878            0 : int mg_base64_decode(const unsigned char *s, int len, char *dst) {
    7879            0 :   return cs_base64_decode(s, len, dst);
    7880              : }
    7881              : 
    7882              : #ifdef MG_ENABLE_THREADS
    7883            0 : void *mg_start_thread(void *(*f)(void *), void *p) {
    7884              : #ifdef _WIN32
    7885              :   return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
    7886              : #else
    7887            0 :   pthread_t thread_id = (pthread_t) 0;
    7888              :   pthread_attr_t attr;
    7889              : 
    7890            0 :   (void) pthread_attr_init(&attr);
    7891            0 :   (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    7892              : 
    7893              : #if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
    7894              :   (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
    7895              : #endif
    7896              : 
    7897            0 :   pthread_create(&thread_id, &attr, f, p);
    7898            0 :   pthread_attr_destroy(&attr);
    7899              : 
    7900            0 :   return (void *) thread_id;
    7901              : #endif
    7902              : }
    7903              : #endif /* MG_ENABLE_THREADS */
    7904              : 
    7905              : /* Set close-on-exec bit for a given socket. */
    7906            0 : void mg_set_close_on_exec(sock_t sock) {
    7907              : #ifdef _WIN32
    7908              :   (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
    7909              : #elif defined(__unix__)
    7910            0 :   fcntl(sock, F_SETFD, FD_CLOEXEC);
    7911              : #else
    7912              :   (void) sock;
    7913              : #endif
    7914            0 : }
    7915              : 
    7916            0 : void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
    7917              :                          int flags) {
    7918              :   int is_v6;
    7919            0 :   if (buf == NULL || len <= 0) return;
    7920            0 :   buf[0] = '\0';
    7921              : #if defined(MG_ENABLE_IPV6)
    7922              :   is_v6 = sa->sa.sa_family == AF_INET6;
    7923              : #else
    7924            0 :   is_v6 = 0;
    7925              : #endif
    7926            0 :   if (flags & MG_SOCK_STRINGIFY_IP) {
    7927              : #if defined(MG_ENABLE_IPV6)
    7928              :     const void *addr = NULL;
    7929              :     char *start = buf;
    7930              :     socklen_t capacity = len;
    7931              :     if (!is_v6) {
    7932              :       addr = &sa->sin.sin_addr;
    7933              :     } else {
    7934              :       addr = (void *) &sa->sin6.sin6_addr;
    7935              :       if (flags & MG_SOCK_STRINGIFY_PORT) {
    7936              :         *buf = '[';
    7937              :         start++;
    7938              :         capacity--;
    7939              :       }
    7940              :     }
    7941              :     if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
    7942              :       *buf = '\0';
    7943              :     }
    7944              : #elif defined(_WIN32) || defined(MG_LWIP)
    7945              :     /* Only Windoze Vista (and newer) have inet_ntop() */
    7946              :     strncpy(buf, inet_ntoa(sa->sin.sin_addr), len);
    7947              : #else
    7948            0 :     inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len);
    7949              : #endif
    7950              :   }
    7951            0 :   if (flags & MG_SOCK_STRINGIFY_PORT) {
    7952            0 :     int port = ntohs(sa->sin.sin_port);
    7953            0 :     if (flags & MG_SOCK_STRINGIFY_IP) {
    7954            0 :       snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s:%d",
    7955              :                (is_v6 ? "]" : ""), port);
    7956              :     } else {
    7957            0 :       snprintf(buf, len, "%d", port);
    7958              :     }
    7959              :   }
    7960              : }
    7961              : 
    7962            0 : void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
    7963              :                          int flags) {
    7964              :   union socket_address sa;
    7965            0 :   memset(&sa, 0, sizeof(sa));
    7966            0 :   mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
    7967            0 :   mg_sock_addr_to_str(&sa, buf, len, flags);
    7968            0 : }
    7969              : 
    7970              : #ifndef MG_DISABLE_HEXDUMP
    7971            0 : int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
    7972            0 :   const unsigned char *p = (const unsigned char *) buf;
    7973            0 :   char ascii[17] = "";
    7974            0 :   int i, idx, n = 0;
    7975              : 
    7976            0 :   for (i = 0; i < len; i++) {
    7977            0 :     idx = i % 16;
    7978            0 :     if (idx == 0) {
    7979            0 :       if (i > 0) n += snprintf(dst + n, dst_len - n, "  %s\n", ascii);
    7980            0 :       n += snprintf(dst + n, dst_len - n, "%04x ", i);
    7981              :     }
    7982            0 :     n += snprintf(dst + n, dst_len - n, " %02x", p[i]);
    7983            0 :     ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
    7984            0 :     ascii[idx + 1] = '\0';
    7985              :   }
    7986              : 
    7987            0 :   while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", "   ");
    7988            0 :   n += snprintf(dst + n, dst_len - n, "  %s\n\n", ascii);
    7989              : 
    7990            0 :   return n;
    7991              : }
    7992              : #endif
    7993              : 
    7994            0 : int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
    7995              :   va_list ap_copy;
    7996              :   int len;
    7997              : 
    7998            0 :   va_copy(ap_copy, ap);
    7999            0 :   len = vsnprintf(*buf, size, fmt, ap_copy);
    8000            0 :   va_end(ap_copy);
    8001              : 
    8002            0 :   if (len < 0) {
    8003              :     /* eCos and Windows are not standard-compliant and return -1 when
    8004              :      * the buffer is too small. Keep allocating larger buffers until we
    8005              :      * succeed or out of memory. */
    8006              :     *buf = NULL; /* LCOV_EXCL_START */
    8007              :     while (len < 0) {
    8008              :       MG_FREE(*buf);
    8009              :       size *= 2;
    8010              :       if ((*buf = (char *) MG_MALLOC(size)) == NULL) break;
    8011              :       va_copy(ap_copy, ap);
    8012              :       len = vsnprintf(*buf, size, fmt, ap_copy);
    8013              :       va_end(ap_copy);
    8014              :     }
    8015              :     /* LCOV_EXCL_STOP */
    8016            0 :   } else if (len >= (int) size) {
    8017              :     /* Standard-compliant code path. Allocate a buffer that is large enough. */
    8018            0 :     if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
    8019              :       len = -1; /* LCOV_EXCL_LINE */
    8020              :     } else {    /* LCOV_EXCL_LINE */
    8021            0 :       va_copy(ap_copy, ap);
    8022            0 :       len = vsnprintf(*buf, len + 1, fmt, ap_copy);
    8023            0 :       va_end(ap_copy);
    8024              :     }
    8025              :   }
    8026              : 
    8027            0 :   return len;
    8028              : }
    8029              : 
    8030              : #if !defined(MG_DISABLE_HEXDUMP)
    8031            0 : void mg_hexdump_connection(struct mg_connection *nc, const char *path,
    8032              :                            const void *buf, int num_bytes, int ev) {
    8033              : #if !defined(NO_LIBC) && !defined(MG_DISABLE_STDIO)
    8034            0 :   FILE *fp = NULL;
    8035              :   char *hexbuf, src[60], dst[60];
    8036            0 :   int buf_size = num_bytes * 5 + 100;
    8037              : 
    8038            0 :   if (strcmp(path, "-") == 0) {
    8039            0 :     fp = stdout;
    8040            0 :   } else if (strcmp(path, "--") == 0) {
    8041            0 :     fp = stderr;
    8042              : #ifndef MG_DISABLE_FILESYSTEM
    8043              :   } else {
    8044            0 :     fp = fopen(path, "a");
    8045              : #endif
    8046              :   }
    8047            0 :   if (fp == NULL) return;
    8048              : 
    8049            0 :   mg_conn_addr_to_str(nc, src, sizeof(src),
    8050              :                       MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
    8051            0 :   mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
    8052              :                                                 MG_SOCK_STRINGIFY_PORT |
    8053              :                                                 MG_SOCK_STRINGIFY_REMOTE);
    8054            0 :   fprintf(
    8055            0 :       fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL), (void *) nc, src,
    8056              :       ev == MG_EV_RECV ? "<-" : ev == MG_EV_SEND
    8057              :                                     ? "->"
    8058              :                                     : ev == MG_EV_ACCEPT
    8059              :                                           ? "<A"
    8060              :                                           : ev == MG_EV_CONNECT ? "C>" : "XX",
    8061              :       dst, num_bytes);
    8062            0 :   if (num_bytes > 0 && (hexbuf = (char *) MG_MALLOC(buf_size)) != NULL) {
    8063            0 :     mg_hexdump(buf, num_bytes, hexbuf, buf_size);
    8064            0 :     fprintf(fp, "%s", hexbuf);
    8065            0 :     MG_FREE(hexbuf);
    8066              :   }
    8067            0 :   if (fp != stdin && fp != stdout) fclose(fp);
    8068              : #endif
    8069              : }
    8070              : #endif
    8071              : 
    8072            0 : int mg_is_big_endian(void) {
    8073              :   static const int n = 1;
    8074              :   /* TODO(mkm) use compiletime check with 4-byte char literal */
    8075            0 :   return ((char *) &n)[0] == 0;
    8076              : }
    8077              : 
    8078            0 : const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
    8079              :                                      struct mg_str *eq_val) {
    8080            0 :   if (list == NULL || *list == '\0') {
    8081              :     /* End of the list */
    8082            0 :     list = NULL;
    8083              :   } else {
    8084            0 :     val->p = list;
    8085            0 :     if ((list = strchr(val->p, ',')) != NULL) {
    8086              :       /* Comma found. Store length and shift the list ptr */
    8087            0 :       val->len = list - val->p;
    8088            0 :       list++;
    8089              :     } else {
    8090              :       /* This value is the last one */
    8091            0 :       list = val->p + strlen(val->p);
    8092            0 :       val->len = list - val->p;
    8093              :     }
    8094              : 
    8095            0 :     if (eq_val != NULL) {
    8096              :       /* Value has form "x=y", adjust pointers and lengths */
    8097              :       /* so that val points to "x", and eq_val points to "y". */
    8098            0 :       eq_val->len = 0;
    8099            0 :       eq_val->p = (const char *) memchr(val->p, '=', val->len);
    8100            0 :       if (eq_val->p != NULL) {
    8101            0 :         eq_val->p++; /* Skip over '=' character */
    8102            0 :         eq_val->len = val->p + val->len - eq_val->p;
    8103            0 :         val->len = (eq_val->p - val->p) - 1;
    8104              :       }
    8105              :     }
    8106              :   }
    8107              : 
    8108            0 :   return list;
    8109              : }
    8110              : 
    8111            0 : int mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
    8112              :   const char *or_str;
    8113            0 :   size_t len, i = 0, j = 0;
    8114              :   int res;
    8115              : 
    8116            0 :   if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL) {
    8117            0 :     struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
    8118            0 :     res = mg_match_prefix_n(pstr, str);
    8119            0 :     if (res > 0) return res;
    8120            0 :     pstr.p = or_str + 1;
    8121            0 :     pstr.len = (pattern.p + pattern.len) - (or_str + 1);
    8122            0 :     return mg_match_prefix_n(pstr, str);
    8123              :   }
    8124              : 
    8125            0 :   for (; i < pattern.len; i++, j++) {
    8126            0 :     if (pattern.p[i] == '?' && j != str.len) {
    8127            0 :       continue;
    8128            0 :     } else if (pattern.p[i] == '$') {
    8129            0 :       return j == str.len ? (int) j : -1;
    8130            0 :     } else if (pattern.p[i] == '*') {
    8131            0 :       i++;
    8132            0 :       if (pattern.p[i] == '*') {
    8133            0 :         i++;
    8134            0 :         len = str.len - j;
    8135              :       } else {
    8136            0 :         len = 0;
    8137            0 :         while (j + len != str.len && str.p[len] != '/') {
    8138            0 :           len++;
    8139              :         }
    8140              :       }
    8141            0 :       if (i == pattern.len) {
    8142            0 :         return j + len;
    8143              :       }
    8144              :       do {
    8145            0 :         const struct mg_str pstr = {pattern.p + i, pattern.len - i};
    8146            0 :         const struct mg_str sstr = {str.p + j + len, str.len - j - len};
    8147            0 :         res = mg_match_prefix_n(pstr, sstr);
    8148            0 :       } while (res == -1 && len-- > 0);
    8149            0 :       return res == -1 ? -1 : (int) (j + res + len);
    8150            0 :     } else if (lowercase(&pattern.p[i]) != lowercase(&str.p[j])) {
    8151            0 :       return -1;
    8152              :     }
    8153              :   }
    8154            0 :   return j;
    8155              : }
    8156              : 
    8157            0 : int mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
    8158            0 :   const struct mg_str pstr = {pattern, (size_t) pattern_len};
    8159            0 :   return mg_match_prefix_n(pstr, mg_mk_str(str));
    8160              : }
    8161              : 
    8162            0 : struct mg_str mg_mk_str(const char *s) {
    8163            0 :   struct mg_str ret = {s, 0};
    8164            0 :   if (s != NULL) ret.len = strlen(s);
    8165            0 :   return ret;
    8166              : }
    8167              : #ifdef MG_MODULE_LINES
    8168              : #line 1 "./src/json-rpc.c"
    8169              : #endif
    8170              : /* Copyright (c) 2014 Cesanta Software Limited */
    8171              : /* All rights reserved */
    8172              : 
    8173              : #ifndef MG_DISABLE_JSON_RPC
    8174              : 
    8175              : /* Amalgamated: #include "mongoose/src/internal.h" */
    8176              : /* Amalgamated: #include "mongoose/src/json-rpc.h" */
    8177              : /* Amalgamated: #include "mongoose/deps/frozen/frozen.h" */
    8178              : 
    8179            0 : int mg_rpc_create_reply(char *buf, int len, const struct mg_rpc_request *req,
    8180              :                         const char *result_fmt, ...) {
    8181              :   static const struct json_token null_tok = {"null", 4, 0, JSON_TYPE_NULL};
    8182            0 :   const struct json_token *id = req->id == NULL ? &null_tok : req->id;
    8183              :   va_list ap;
    8184            0 :   int n = 0;
    8185              : 
    8186            0 :   n += json_emit(buf + n, len - n, "{s:s,s:", "jsonrpc", "2.0", "id");
    8187            0 :   if (id->type == JSON_TYPE_STRING) {
    8188            0 :     n += json_emit_quoted_str(buf + n, len - n, id->ptr, id->len);
    8189              :   } else {
    8190            0 :     n += json_emit_unquoted_str(buf + n, len - n, id->ptr, id->len);
    8191              :   }
    8192            0 :   n += json_emit(buf + n, len - n, ",s:", "result");
    8193              : 
    8194            0 :   va_start(ap, result_fmt);
    8195            0 :   n += json_emit_va(buf + n, len - n, result_fmt, ap);
    8196            0 :   va_end(ap);
    8197              : 
    8198            0 :   n += json_emit(buf + n, len - n, "}");
    8199              : 
    8200            0 :   return n;
    8201              : }
    8202              : 
    8203            0 : int mg_rpc_create_request(char *buf, int len, const char *method,
    8204              :                           const char *id, const char *params_fmt, ...) {
    8205              :   va_list ap;
    8206            0 :   int n = 0;
    8207              : 
    8208            0 :   n += json_emit(buf + n, len - n, "{s:s,s:s,s:s,s:", "jsonrpc", "2.0", "id",
    8209              :                  id, "method", method, "params");
    8210            0 :   va_start(ap, params_fmt);
    8211            0 :   n += json_emit_va(buf + n, len - n, params_fmt, ap);
    8212            0 :   va_end(ap);
    8213              : 
    8214            0 :   n += json_emit(buf + n, len - n, "}");
    8215              : 
    8216            0 :   return n;
    8217              : }
    8218              : 
    8219            0 : int mg_rpc_create_error(char *buf, int len, struct mg_rpc_request *req,
    8220              :                         int code, const char *message, const char *fmt, ...) {
    8221              :   va_list ap;
    8222            0 :   int n = 0;
    8223              : 
    8224            0 :   n += json_emit(buf + n, len - n, "{s:s,s:V,s:{s:i,s:s,s:", "jsonrpc", "2.0",
    8225            0 :                  "id", req->id == NULL ? "null" : req->id->ptr,
    8226            0 :                  req->id == NULL ? 4 : req->id->len, "error", "code",
    8227              :                  (long) code, "message", message, "data");
    8228            0 :   va_start(ap, fmt);
    8229            0 :   n += json_emit_va(buf + n, len - n, fmt, ap);
    8230            0 :   va_end(ap);
    8231              : 
    8232            0 :   n += json_emit(buf + n, len - n, "}}");
    8233              : 
    8234            0 :   return n;
    8235              : }
    8236              : 
    8237            0 : int mg_rpc_create_std_error(char *buf, int len, struct mg_rpc_request *req,
    8238              :                             int code) {
    8239            0 :   const char *message = NULL;
    8240              : 
    8241            0 :   switch (code) {
    8242            0 :     case JSON_RPC_PARSE_ERROR:
    8243            0 :       message = "parse error";
    8244            0 :       break;
    8245            0 :     case JSON_RPC_INVALID_REQUEST_ERROR:
    8246            0 :       message = "invalid request";
    8247            0 :       break;
    8248            0 :     case JSON_RPC_METHOD_NOT_FOUND_ERROR:
    8249            0 :       message = "method not found";
    8250            0 :       break;
    8251            0 :     case JSON_RPC_INVALID_PARAMS_ERROR:
    8252            0 :       message = "invalid parameters";
    8253            0 :       break;
    8254            0 :     case JSON_RPC_SERVER_ERROR:
    8255            0 :       message = "server error";
    8256            0 :       break;
    8257            0 :     default:
    8258            0 :       message = "unspecified error";
    8259            0 :       break;
    8260              :   }
    8261              : 
    8262            0 :   return mg_rpc_create_error(buf, len, req, code, message, "N");
    8263              : }
    8264              : 
    8265            0 : int mg_rpc_dispatch(const char *buf, int len, char *dst, int dst_len,
    8266              :                     const char **methods, mg_rpc_handler_t *handlers) {
    8267              :   struct json_token tokens[200];
    8268              :   struct mg_rpc_request req;
    8269              :   int i, n;
    8270              : 
    8271            0 :   memset(&req, 0, sizeof(req));
    8272            0 :   n = parse_json(buf, len, tokens, sizeof(tokens) / sizeof(tokens[0]));
    8273            0 :   if (n <= 0) {
    8274            0 :     int err_code = (n == JSON_STRING_INVALID) ? JSON_RPC_PARSE_ERROR
    8275              :                                               : JSON_RPC_SERVER_ERROR;
    8276            0 :     return mg_rpc_create_std_error(dst, dst_len, &req, err_code);
    8277              :   }
    8278              : 
    8279            0 :   req.message = tokens;
    8280            0 :   req.id = find_json_token(tokens, "id");
    8281            0 :   req.method = find_json_token(tokens, "method");
    8282            0 :   req.params = find_json_token(tokens, "params");
    8283              : 
    8284            0 :   if (req.id == NULL || req.method == NULL) {
    8285            0 :     return mg_rpc_create_std_error(dst, dst_len, &req,
    8286            0 :                                    JSON_RPC_INVALID_REQUEST_ERROR);
    8287              :   }
    8288              : 
    8289            0 :   for (i = 0; methods[i] != NULL; i++) {
    8290            0 :     int mlen = strlen(methods[i]);
    8291            0 :     if (mlen == req.method->len &&
    8292            0 :         memcmp(methods[i], req.method->ptr, mlen) == 0)
    8293            0 :       break;
    8294              :   }
    8295              : 
    8296            0 :   if (methods[i] == NULL) {
    8297            0 :     return mg_rpc_create_std_error(dst, dst_len, &req,
    8298            0 :                                    JSON_RPC_METHOD_NOT_FOUND_ERROR);
    8299              :   }
    8300              : 
    8301            0 :   return handlers[i](dst, dst_len, &req);
    8302              : }
    8303              : 
    8304            0 : int mg_rpc_parse_reply(const char *buf, int len, struct json_token *toks,
    8305              :                        int max_toks, struct mg_rpc_reply *rep,
    8306              :                        struct mg_rpc_error *er) {
    8307            0 :   int n = parse_json(buf, len, toks, max_toks);
    8308              : 
    8309            0 :   memset(rep, 0, sizeof(*rep));
    8310            0 :   memset(er, 0, sizeof(*er));
    8311              : 
    8312            0 :   if (n > 0) {
    8313            0 :     if ((rep->result = find_json_token(toks, "result")) != NULL) {
    8314            0 :       rep->message = toks;
    8315            0 :       rep->id = find_json_token(toks, "id");
    8316              :     } else {
    8317            0 :       er->message = toks;
    8318            0 :       er->id = find_json_token(toks, "id");
    8319            0 :       er->error_code = find_json_token(toks, "error.code");
    8320            0 :       er->error_message = find_json_token(toks, "error.message");
    8321            0 :       er->error_data = find_json_token(toks, "error.data");
    8322              :     }
    8323              :   }
    8324            0 :   return n;
    8325              : }
    8326              : 
    8327              : #endif /* MG_DISABLE_JSON_RPC */
    8328              : #ifdef MG_MODULE_LINES
    8329              : #line 1 "./src/mqtt.c"
    8330              : #endif
    8331              : /*
    8332              :  * Copyright (c) 2014 Cesanta Software Limited
    8333              :  * All rights reserved
    8334              :  */
    8335              : 
    8336              : #ifndef MG_DISABLE_MQTT
    8337              : 
    8338              : /* Amalgamated: #include "mongoose/src/internal.h" */
    8339              : /* Amalgamated: #include "mongoose/src/mqtt.h" */
    8340              : 
    8341            0 : MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
    8342              :   uint8_t header;
    8343              :   int cmd;
    8344            0 :   size_t len = 0;
    8345            0 :   int var_len = 0;
    8346            0 :   char *vlen = &io->buf[1];
    8347              : 
    8348            0 :   if (io->len < 2) return -1;
    8349              : 
    8350            0 :   header = io->buf[0];
    8351            0 :   cmd = header >> 4;
    8352              : 
    8353              :   /* decode mqtt variable length */
    8354              :   do {
    8355            0 :     len += (*vlen & 127) << 7 * (vlen - &io->buf[1]);
    8356            0 :   } while ((*vlen++ & 128) != 0 && ((size_t)(vlen - io->buf) <= io->len));
    8357              : 
    8358            0 :   if (len != 0 && io->len < (size_t)(len - 1)) return -1;
    8359              : 
    8360            0 :   mbuf_remove(io, 1 + (vlen - &io->buf[1]));
    8361            0 :   mm->cmd = cmd;
    8362            0 :   mm->qos = MG_MQTT_GET_QOS(header);
    8363              : 
    8364            0 :   switch (cmd) {
    8365            0 :     case MG_MQTT_CMD_CONNECT:
    8366              :       /* TODO(mkm): parse keepalive and will */
    8367            0 :       break;
    8368            0 :     case MG_MQTT_CMD_CONNACK:
    8369            0 :       mm->connack_ret_code = io->buf[1];
    8370            0 :       var_len = 2;
    8371            0 :       break;
    8372            0 :     case MG_MQTT_CMD_PUBACK:
    8373              :     case MG_MQTT_CMD_PUBREC:
    8374              :     case MG_MQTT_CMD_PUBREL:
    8375              :     case MG_MQTT_CMD_PUBCOMP:
    8376              :     case MG_MQTT_CMD_SUBACK:
    8377            0 :       mm->message_id = ntohs(*(uint16_t *) io->buf);
    8378            0 :       var_len = 2;
    8379            0 :       break;
    8380            0 :     case MG_MQTT_CMD_PUBLISH: {
    8381            0 :       uint16_t topic_len = ntohs(*(uint16_t *) io->buf);
    8382            0 :       mm->topic = (char *) MG_MALLOC(topic_len + 1);
    8383            0 :       mm->topic[topic_len] = 0;
    8384            0 :       strncpy(mm->topic, io->buf + 2, topic_len);
    8385            0 :       var_len = topic_len + 2;
    8386              : 
    8387            0 :       if (MG_MQTT_GET_QOS(header) > 0) {
    8388            0 :         mm->message_id = ntohs(*(uint16_t *) io->buf);
    8389            0 :         var_len += 2;
    8390              :       }
    8391            0 :     } break;
    8392            0 :     case MG_MQTT_CMD_SUBSCRIBE:
    8393              :       /*
    8394              :        * topic expressions are left in the payload and can be parsed with
    8395              :        * `mg_mqtt_next_subscribe_topic`
    8396              :        */
    8397            0 :       mm->message_id = ntohs(*(uint16_t *) io->buf);
    8398            0 :       var_len = 2;
    8399            0 :       break;
    8400            0 :     default:
    8401              :       /* Unhandled command */
    8402            0 :       break;
    8403              :   }
    8404              : 
    8405            0 :   mbuf_remove(io, var_len);
    8406            0 :   return len - var_len;
    8407              : }
    8408              : 
    8409            0 : static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data) {
    8410              :   int len;
    8411            0 :   struct mbuf *io = &nc->recv_mbuf;
    8412              :   struct mg_mqtt_message mm;
    8413            0 :   memset(&mm, 0, sizeof(mm));
    8414              : 
    8415            0 :   nc->handler(nc, ev, ev_data);
    8416              : 
    8417            0 :   switch (ev) {
    8418            0 :     case MG_EV_RECV:
    8419            0 :       len = parse_mqtt(io, &mm);
    8420            0 :       if (len == -1) break; /* not fully buffered */
    8421            0 :       mm.payload.p = io->buf;
    8422            0 :       mm.payload.len = len;
    8423              : 
    8424            0 :       nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm);
    8425              : 
    8426            0 :       if (mm.topic) {
    8427            0 :         MG_FREE(mm.topic);
    8428              :       }
    8429            0 :       mbuf_remove(io, mm.payload.len);
    8430            0 :       break;
    8431              :   }
    8432            0 : }
    8433              : 
    8434            0 : void mg_set_protocol_mqtt(struct mg_connection *nc) {
    8435            0 :   nc->proto_handler = mqtt_handler;
    8436            0 : }
    8437              : 
    8438            0 : void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
    8439              :   static struct mg_send_mqtt_handshake_opts opts;
    8440            0 :   mg_send_mqtt_handshake_opt(nc, client_id, opts);
    8441            0 : }
    8442              : 
    8443            0 : void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
    8444              :                                 struct mg_send_mqtt_handshake_opts opts) {
    8445            0 :   uint8_t header = MG_MQTT_CMD_CONNECT << 4;
    8446              :   uint8_t rem_len;
    8447              :   uint16_t keep_alive;
    8448              :   uint16_t client_id_len;
    8449              : 
    8450              :   /*
    8451              :    * 9: version_header(len, magic_string, version_number), 1: flags, 2:
    8452              :    * keep-alive timer,
    8453              :    * 2: client_identifier_len, n: client_id
    8454              :    */
    8455            0 :   rem_len = 9 + 1 + 2 + 2 + strlen(client_id);
    8456              : 
    8457            0 :   mg_send(nc, &header, 1);
    8458            0 :   mg_send(nc, &rem_len, 1);
    8459            0 :   mg_send(nc, "\00\06MQIsdp\03", 9);
    8460            0 :   mg_send(nc, &opts.flags, 1);
    8461              : 
    8462            0 :   if (opts.keep_alive == 0) {
    8463            0 :     opts.keep_alive = 60;
    8464              :   }
    8465            0 :   keep_alive = htons(opts.keep_alive);
    8466            0 :   mg_send(nc, &keep_alive, 2);
    8467              : 
    8468            0 :   client_id_len = htons(strlen(client_id));
    8469            0 :   mg_send(nc, &client_id_len, 2);
    8470            0 :   mg_send(nc, client_id, strlen(client_id));
    8471            0 : }
    8472              : 
    8473            0 : static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd,
    8474              :                                    uint8_t flags, size_t len) {
    8475            0 :   size_t off = nc->send_mbuf.len - len;
    8476            0 :   uint8_t header = cmd << 4 | (uint8_t) flags;
    8477              : 
    8478              :   uint8_t buf[1 + sizeof(size_t)];
    8479            0 :   uint8_t *vlen = &buf[1];
    8480              : 
    8481            0 :   assert(nc->send_mbuf.len >= len);
    8482              : 
    8483            0 :   buf[0] = header;
    8484              : 
    8485              :   /* mqtt variable length encoding */
    8486              :   do {
    8487            0 :     *vlen = len % 0x80;
    8488            0 :     len /= 0x80;
    8489            0 :     if (len > 0) *vlen |= 0x80;
    8490            0 :     vlen++;
    8491            0 :   } while (len > 0);
    8492              : 
    8493            0 :   mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf);
    8494            0 : }
    8495              : 
    8496            0 : void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
    8497              :                      uint16_t message_id, int flags, const void *data,
    8498              :                      size_t len) {
    8499            0 :   size_t old_len = nc->send_mbuf.len;
    8500              : 
    8501            0 :   uint16_t topic_len = htons(strlen(topic));
    8502            0 :   uint16_t message_id_net = htons(message_id);
    8503              : 
    8504            0 :   mg_send(nc, &topic_len, 2);
    8505            0 :   mg_send(nc, topic, strlen(topic));
    8506            0 :   if (MG_MQTT_GET_QOS(flags) > 0) {
    8507            0 :     mg_send(nc, &message_id_net, 2);
    8508              :   }
    8509            0 :   mg_send(nc, data, len);
    8510              : 
    8511            0 :   mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags,
    8512            0 :                          nc->send_mbuf.len - old_len);
    8513            0 : }
    8514              : 
    8515            0 : void mg_mqtt_subscribe(struct mg_connection *nc,
    8516              :                        const struct mg_mqtt_topic_expression *topics,
    8517              :                        size_t topics_len, uint16_t message_id) {
    8518            0 :   size_t old_len = nc->send_mbuf.len;
    8519              : 
    8520            0 :   uint16_t message_id_n = htons(message_id);
    8521              :   size_t i;
    8522              : 
    8523            0 :   mg_send(nc, (char *) &message_id_n, 2);
    8524            0 :   for (i = 0; i < topics_len; i++) {
    8525            0 :     uint16_t topic_len_n = htons(strlen(topics[i].topic));
    8526            0 :     mg_send(nc, &topic_len_n, 2);
    8527            0 :     mg_send(nc, topics[i].topic, strlen(topics[i].topic));
    8528            0 :     mg_send(nc, &topics[i].qos, 1);
    8529              :   }
    8530              : 
    8531            0 :   mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1),
    8532            0 :                          nc->send_mbuf.len - old_len);
    8533            0 : }
    8534              : 
    8535            0 : int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
    8536              :                                  struct mg_str *topic, uint8_t *qos, int pos) {
    8537            0 :   unsigned char *buf = (unsigned char *) msg->payload.p + pos;
    8538            0 :   if ((size_t) pos >= msg->payload.len) {
    8539            0 :     return -1;
    8540              :   }
    8541              : 
    8542            0 :   topic->len = buf[0] << 8 | buf[1];
    8543            0 :   topic->p = (char *) buf + 2;
    8544            0 :   *qos = buf[2 + topic->len];
    8545            0 :   return pos + 2 + topic->len + 1;
    8546              : }
    8547              : 
    8548            0 : void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
    8549              :                          size_t topics_len, uint16_t message_id) {
    8550            0 :   size_t old_len = nc->send_mbuf.len;
    8551              : 
    8552            0 :   uint16_t message_id_n = htons(message_id);
    8553              :   size_t i;
    8554              : 
    8555            0 :   mg_send(nc, (char *) &message_id_n, 2);
    8556            0 :   for (i = 0; i < topics_len; i++) {
    8557            0 :     uint16_t topic_len_n = htons(strlen(topics[i]));
    8558            0 :     mg_send(nc, &topic_len_n, 2);
    8559            0 :     mg_send(nc, topics[i], strlen(topics[i]));
    8560              :   }
    8561              : 
    8562            0 :   mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1),
    8563            0 :                          nc->send_mbuf.len - old_len);
    8564            0 : }
    8565              : 
    8566            0 : void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
    8567            0 :   uint8_t unused = 0;
    8568            0 :   mg_send(nc, &unused, 1);
    8569            0 :   mg_send(nc, &return_code, 1);
    8570            0 :   mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
    8571            0 : }
    8572              : 
    8573              : /*
    8574              :  * Sends a command which contains only a `message_id` and a QoS level of 1.
    8575              :  *
    8576              :  * Helper function.
    8577              :  */
    8578            0 : static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
    8579              :                                        uint16_t message_id) {
    8580            0 :   uint16_t message_id_net = htons(message_id);
    8581            0 :   mg_send(nc, &message_id_net, 2);
    8582            0 :   mg_mqtt_prepend_header(nc, cmd, MG_MQTT_QOS(1), 2);
    8583            0 : }
    8584              : 
    8585            0 : void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
    8586            0 :   mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
    8587            0 : }
    8588              : 
    8589            0 : void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
    8590            0 :   mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
    8591            0 : }
    8592              : 
    8593            0 : void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
    8594            0 :   mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
    8595            0 : }
    8596              : 
    8597            0 : void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
    8598            0 :   mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
    8599            0 : }
    8600              : 
    8601            0 : void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
    8602              :                     uint16_t message_id) {
    8603              :   size_t i;
    8604            0 :   uint16_t message_id_net = htons(message_id);
    8605            0 :   mg_send(nc, &message_id_net, 2);
    8606            0 :   for (i = 0; i < qoss_len; i++) {
    8607            0 :     mg_send(nc, &qoss[i], 1);
    8608              :   }
    8609            0 :   mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
    8610            0 : }
    8611              : 
    8612            0 : void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
    8613            0 :   mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
    8614            0 : }
    8615              : 
    8616            0 : void mg_mqtt_ping(struct mg_connection *nc) {
    8617            0 :   mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
    8618            0 : }
    8619              : 
    8620            0 : void mg_mqtt_pong(struct mg_connection *nc) {
    8621            0 :   mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
    8622            0 : }
    8623              : 
    8624            0 : void mg_mqtt_disconnect(struct mg_connection *nc) {
    8625            0 :   mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
    8626            0 : }
    8627              : 
    8628              : #endif /* MG_DISABLE_MQTT */
    8629              : #ifdef MG_MODULE_LINES
    8630              : #line 1 "./src/mqtt-broker.c"
    8631              : #endif
    8632              : /*
    8633              :  * Copyright (c) 2014 Cesanta Software Limited
    8634              :  * All rights reserved
    8635              :  */
    8636              : 
    8637              : /* Amalgamated: #include "mongoose/src/internal.h" */
    8638              : /* Amalgamated: #include "mongoose/src/mqtt-broker.h" */
    8639              : 
    8640              : #ifdef MG_ENABLE_MQTT_BROKER
    8641              : 
    8642              : static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
    8643              :                                  struct mg_mqtt_session *s,
    8644              :                                  struct mg_connection *nc) {
    8645              :   s->brk = brk;
    8646              :   s->subscriptions = NULL;
    8647              :   s->num_subscriptions = 0;
    8648              :   s->nc = nc;
    8649              : }
    8650              : 
    8651              : static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
    8652              :   s->next = s->brk->sessions;
    8653              :   s->brk->sessions = s;
    8654              :   s->prev = NULL;
    8655              :   if (s->next != NULL) s->next->prev = s;
    8656              : }
    8657              : 
    8658              : static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
    8659              :   if (s->prev == NULL) s->brk->sessions = s->next;
    8660              :   if (s->prev) s->prev->next = s->next;
    8661              :   if (s->next) s->next->prev = s->prev;
    8662              : }
    8663              : 
    8664              : static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
    8665              :   size_t i;
    8666              :   for (i = 0; i < s->num_subscriptions; i++) {
    8667              :     MG_FREE((void *) s->subscriptions[i].topic);
    8668              :   }
    8669              :   MG_FREE(s->subscriptions);
    8670              :   MG_FREE(s);
    8671              : }
    8672              : 
    8673              : static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
    8674              :   mg_mqtt_remove_session(s);
    8675              :   mg_mqtt_destroy_session(s);
    8676              : }
    8677              : 
    8678              : void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
    8679              :   brk->sessions = NULL;
    8680              :   brk->user_data = user_data;
    8681              : }
    8682              : 
    8683              : static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
    8684              :                                           struct mg_connection *nc) {
    8685              :   struct mg_mqtt_session *s = (struct mg_mqtt_session *) malloc(sizeof *s);
    8686              :   if (s == NULL) {
    8687              :     /* LCOV_EXCL_START */
    8688              :     mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
    8689              :     return;
    8690              :     /* LCOV_EXCL_STOP */
    8691              :   }
    8692              : 
    8693              :   /* TODO(mkm): check header (magic and version) */
    8694              : 
    8695              :   mg_mqtt_session_init(brk, s, nc);
    8696              :   s->user_data = nc->user_data;
    8697              :   nc->user_data = s;
    8698              :   mg_mqtt_add_session(s);
    8699              : 
    8700              :   mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
    8701              : }
    8702              : 
    8703              : static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
    8704              :                                             struct mg_mqtt_message *msg) {
    8705              :   struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->user_data;
    8706              :   uint8_t qoss[512];
    8707              :   size_t qoss_len = 0;
    8708              :   struct mg_str topic;
    8709              :   uint8_t qos;
    8710              :   int pos;
    8711              :   struct mg_mqtt_topic_expression *te;
    8712              : 
    8713              :   for (pos = 0;
    8714              :        (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
    8715              :     qoss[qoss_len++] = qos;
    8716              :   }
    8717              : 
    8718              :   ss->subscriptions = (struct mg_mqtt_topic_expression *) realloc(
    8719              :       ss->subscriptions, sizeof(*ss->subscriptions) * qoss_len);
    8720              :   for (pos = 0;
    8721              :        (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
    8722              :        ss->num_subscriptions++) {
    8723              :     te = &ss->subscriptions[ss->num_subscriptions];
    8724              :     te->topic = (char *) malloc(topic.len + 1);
    8725              :     te->qos = qos;
    8726              :     strncpy((char *) te->topic, topic.p, topic.len + 1);
    8727              :   }
    8728              : 
    8729              :   mg_mqtt_suback(nc, qoss, qoss_len, msg->message_id);
    8730              : }
    8731              : 
    8732              : /*
    8733              :  * Matches a topic against a topic expression
    8734              :  *
    8735              :  * See http://goo.gl/iWk21X
    8736              :  *
    8737              :  * Returns 1 if it matches; 0 otherwise.
    8738              :  */
    8739              : static int mg_mqtt_match_topic_expression(const char *exp, const char *topic) {
    8740              :   /* TODO(mkm): implement real matching */
    8741              :   int len = strlen(exp);
    8742              :   if (strchr(exp, '#')) {
    8743              :     len -= 2;
    8744              :   }
    8745              :   return strncmp(exp, topic, len) == 0;
    8746              : }
    8747              : 
    8748              : static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
    8749              :                                           struct mg_mqtt_message *msg) {
    8750              :   struct mg_mqtt_session *s;
    8751              :   size_t i;
    8752              : 
    8753              :   for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
    8754              :     for (i = 0; i < s->num_subscriptions; i++) {
    8755              :       if (mg_mqtt_match_topic_expression(s->subscriptions[i].topic,
    8756              :                                          msg->topic)) {
    8757              :         mg_mqtt_publish(s->nc, msg->topic, 0, 0, msg->payload.p,
    8758              :                         msg->payload.len);
    8759              :         break;
    8760              :       }
    8761              :     }
    8762              :   }
    8763              : }
    8764              : 
    8765              : void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
    8766              :   struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
    8767              :   struct mg_mqtt_broker *brk;
    8768              : 
    8769              :   if (nc->listener) {
    8770              :     brk = (struct mg_mqtt_broker *) nc->listener->user_data;
    8771              :   } else {
    8772              :     brk = (struct mg_mqtt_broker *) nc->user_data;
    8773              :   }
    8774              : 
    8775              :   switch (ev) {
    8776              :     case MG_EV_ACCEPT:
    8777              :       mg_set_protocol_mqtt(nc);
    8778              :       break;
    8779              :     case MG_EV_MQTT_CONNECT:
    8780              :       mg_mqtt_broker_handle_connect(brk, nc);
    8781              :       break;
    8782              :     case MG_EV_MQTT_SUBSCRIBE:
    8783              :       mg_mqtt_broker_handle_subscribe(nc, msg);
    8784              :       break;
    8785              :     case MG_EV_MQTT_PUBLISH:
    8786              :       mg_mqtt_broker_handle_publish(brk, msg);
    8787              :       break;
    8788              :     case MG_EV_CLOSE:
    8789              :       if (nc->listener) {
    8790              :         mg_mqtt_close_session((struct mg_mqtt_session *) nc->user_data);
    8791              :       }
    8792              :       break;
    8793              :   }
    8794              : }
    8795              : 
    8796              : struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
    8797              :                                      struct mg_mqtt_session *s) {
    8798              :   return s == NULL ? brk->sessions : s->next;
    8799              : }
    8800              : 
    8801              : #endif /* MG_ENABLE_MQTT_BROKER */
    8802              : #ifdef MG_MODULE_LINES
    8803              : #line 1 "./src/dns.c"
    8804              : #endif
    8805              : /*
    8806              :  * Copyright (c) 2014 Cesanta Software Limited
    8807              :  * All rights reserved
    8808              :  */
    8809              : 
    8810              : #ifndef MG_DISABLE_DNS
    8811              : 
    8812              : /* Amalgamated: #include "mongoose/src/internal.h" */
    8813              : /* Amalgamated: #include "mongoose/src/dns.h" */
    8814              : 
    8815              : static int mg_dns_tid = 0xa0;
    8816              : 
    8817              : struct mg_dns_header {
    8818              :   uint16_t transaction_id;
    8819              :   uint16_t flags;
    8820              :   uint16_t num_questions;
    8821              :   uint16_t num_answers;
    8822              :   uint16_t num_authority_prs;
    8823              :   uint16_t num_other_prs;
    8824              : };
    8825              : 
    8826            0 : struct mg_dns_resource_record *mg_dns_next_record(
    8827              :     struct mg_dns_message *msg, int query,
    8828              :     struct mg_dns_resource_record *prev) {
    8829              :   struct mg_dns_resource_record *rr;
    8830              : 
    8831            0 :   for (rr = (prev == NULL ? msg->answers : prev + 1);
    8832            0 :        rr - msg->answers < msg->num_answers; rr++) {
    8833            0 :     if (rr->rtype == query) {
    8834            0 :       return rr;
    8835              :     }
    8836              :   }
    8837            0 :   return NULL;
    8838              : }
    8839              : 
    8840            0 : int mg_dns_parse_record_data(struct mg_dns_message *msg,
    8841              :                              struct mg_dns_resource_record *rr, void *data,
    8842              :                              size_t data_len) {
    8843            0 :   switch (rr->rtype) {
    8844            0 :     case MG_DNS_A_RECORD:
    8845            0 :       if (data_len < sizeof(struct in_addr)) {
    8846            0 :         return -1;
    8847              :       }
    8848            0 :       if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
    8849            0 :         return -1;
    8850              :       }
    8851            0 :       memcpy(data, rr->rdata.p, data_len);
    8852            0 :       return 0;
    8853              : #ifdef MG_ENABLE_IPV6
    8854              :     case MG_DNS_AAAA_RECORD:
    8855              :       if (data_len < sizeof(struct in6_addr)) {
    8856              :         return -1; /* LCOV_EXCL_LINE */
    8857              :       }
    8858              :       memcpy(data, rr->rdata.p, data_len);
    8859              :       return 0;
    8860              : #endif
    8861            0 :     case MG_DNS_CNAME_RECORD:
    8862            0 :       mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
    8863            0 :       return 0;
    8864              :   }
    8865              : 
    8866            0 :   return -1;
    8867              : }
    8868              : 
    8869            0 : int mg_dns_insert_header(struct mbuf *io, size_t pos,
    8870              :                          struct mg_dns_message *msg) {
    8871              :   struct mg_dns_header header;
    8872              : 
    8873            0 :   memset(&header, 0, sizeof(header));
    8874            0 :   header.transaction_id = msg->transaction_id;
    8875            0 :   header.flags = htons(msg->flags);
    8876            0 :   header.num_questions = htons(msg->num_questions);
    8877            0 :   header.num_answers = htons(msg->num_answers);
    8878              : 
    8879            0 :   return mbuf_insert(io, pos, &header, sizeof(header));
    8880              : }
    8881              : 
    8882            0 : int mg_dns_copy_body(struct mbuf *io, struct mg_dns_message *msg) {
    8883            0 :   return mbuf_append(io, msg->pkt.p + sizeof(struct mg_dns_header),
    8884            0 :                      msg->pkt.len - sizeof(struct mg_dns_header));
    8885              : }
    8886              : 
    8887            0 : static int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
    8888              :   const char *s;
    8889              :   unsigned char n;
    8890            0 :   size_t pos = io->len;
    8891              : 
    8892              :   do {
    8893            0 :     if ((s = strchr(name, '.')) == NULL) {
    8894            0 :       s = name + len;
    8895              :     }
    8896              : 
    8897            0 :     if (s - name > 127) {
    8898            0 :       return -1; /* TODO(mkm) cover */
    8899              :     }
    8900            0 :     n = s - name;           /* chunk length */
    8901            0 :     mbuf_append(io, &n, 1); /* send length */
    8902            0 :     mbuf_append(io, name, n);
    8903              : 
    8904            0 :     if (*s == '.') {
    8905            0 :       n++;
    8906              :     }
    8907              : 
    8908            0 :     name += n;
    8909            0 :     len -= n;
    8910            0 :   } while (*s != '\0');
    8911            0 :   mbuf_append(io, "\0", 1); /* Mark end of host name */
    8912              : 
    8913            0 :   return io->len - pos;
    8914              : }
    8915              : 
    8916            0 : int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
    8917              :                          const char *name, size_t nlen, const void *rdata,
    8918              :                          size_t rlen) {
    8919            0 :   size_t pos = io->len;
    8920              :   uint16_t u16;
    8921              :   uint32_t u32;
    8922              : 
    8923            0 :   if (rr->kind == MG_DNS_INVALID_RECORD) {
    8924              :     return -1; /* LCOV_EXCL_LINE */
    8925              :   }
    8926              : 
    8927            0 :   if (mg_dns_encode_name(io, name, nlen) == -1) {
    8928            0 :     return -1;
    8929              :   }
    8930              : 
    8931            0 :   u16 = htons(rr->rtype);
    8932            0 :   mbuf_append(io, &u16, 2);
    8933            0 :   u16 = htons(rr->rclass);
    8934            0 :   mbuf_append(io, &u16, 2);
    8935              : 
    8936            0 :   if (rr->kind == MG_DNS_ANSWER) {
    8937            0 :     u32 = htonl(rr->ttl);
    8938            0 :     mbuf_append(io, &u32, 4);
    8939              : 
    8940            0 :     if (rr->rtype == MG_DNS_CNAME_RECORD) {
    8941              :       int clen;
    8942              :       /* fill size after encoding */
    8943            0 :       size_t off = io->len;
    8944            0 :       mbuf_append(io, &u16, 2);
    8945            0 :       if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
    8946            0 :         return -1;
    8947              :       }
    8948            0 :       u16 = clen;
    8949            0 :       io->buf[off] = u16 >> 8;
    8950            0 :       io->buf[off + 1] = u16 & 0xff;
    8951              :     } else {
    8952            0 :       u16 = htons(rlen);
    8953            0 :       mbuf_append(io, &u16, 2);
    8954            0 :       mbuf_append(io, rdata, rlen);
    8955              :     }
    8956              :   }
    8957              : 
    8958            0 :   return io->len - pos;
    8959              : }
    8960              : 
    8961            0 : void mg_send_dns_query(struct mg_connection *nc, const char *name,
    8962              :                        int query_type) {
    8963              :   struct mg_dns_message *msg =
    8964            0 :       (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
    8965              :   struct mbuf pkt;
    8966            0 :   struct mg_dns_resource_record *rr = &msg->questions[0];
    8967              : 
    8968            0 :   DBG(("%s %d", name, query_type));
    8969              : 
    8970            0 :   mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
    8971              : 
    8972            0 :   msg->transaction_id = ++mg_dns_tid;
    8973            0 :   msg->flags = 0x100;
    8974            0 :   msg->num_questions = 1;
    8975              : 
    8976            0 :   mg_dns_insert_header(&pkt, 0, msg);
    8977              : 
    8978            0 :   rr->rtype = query_type;
    8979            0 :   rr->rclass = 1; /* Class: inet */
    8980            0 :   rr->kind = MG_DNS_QUESTION;
    8981              : 
    8982            0 :   if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
    8983              :     /* TODO(mkm): return an error code */
    8984              :     goto cleanup; /* LCOV_EXCL_LINE */
    8985              :   }
    8986              : 
    8987              :   /* TCP DNS requires messages to be prefixed with len */
    8988            0 :   if (!(nc->flags & MG_F_UDP)) {
    8989            0 :     uint16_t len = htons(pkt.len);
    8990            0 :     mbuf_insert(&pkt, 0, &len, 2);
    8991              :   }
    8992              : 
    8993            0 :   mg_send(nc, pkt.buf, pkt.len);
    8994            0 :   mbuf_free(&pkt);
    8995              : 
    8996            0 : cleanup:
    8997            0 :   MG_FREE(msg);
    8998            0 : }
    8999              : 
    9000            0 : static unsigned char *mg_parse_dns_resource_record(
    9001              :     unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
    9002              :     int reply) {
    9003            0 :   unsigned char *name = data;
    9004              :   int chunk_len, data_len;
    9005              : 
    9006            0 :   while (data < end && (chunk_len = *data)) {
    9007            0 :     if (((unsigned char *) data)[0] & 0xc0) {
    9008            0 :       data += 1;
    9009            0 :       break;
    9010              :     }
    9011            0 :     data += chunk_len + 1;
    9012              :   }
    9013              : 
    9014            0 :   if (data > end - 5) {
    9015            0 :     return NULL;
    9016              :   }
    9017              : 
    9018            0 :   rr->name.p = (char *) name;
    9019            0 :   rr->name.len = data - name + 1;
    9020            0 :   data++;
    9021              : 
    9022            0 :   rr->rtype = data[0] << 8 | data[1];
    9023            0 :   data += 2;
    9024              : 
    9025            0 :   rr->rclass = data[0] << 8 | data[1];
    9026            0 :   data += 2;
    9027              : 
    9028            0 :   rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
    9029            0 :   if (reply) {
    9030            0 :     if (data >= end - 6) {
    9031            0 :       return NULL;
    9032              :     }
    9033              : 
    9034            0 :     rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
    9035            0 :               data[2] << 8 | data[3];
    9036            0 :     data += 4;
    9037              : 
    9038            0 :     data_len = *data << 8 | *(data + 1);
    9039            0 :     data += 2;
    9040              : 
    9041            0 :     rr->rdata.p = (char *) data;
    9042            0 :     rr->rdata.len = data_len;
    9043            0 :     data += data_len;
    9044              :   }
    9045            0 :   return data;
    9046              : }
    9047              : 
    9048            0 : int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
    9049            0 :   struct mg_dns_header *header = (struct mg_dns_header *) buf;
    9050            0 :   unsigned char *data = (unsigned char *) buf + sizeof(*header);
    9051            0 :   unsigned char *end = (unsigned char *) buf + len;
    9052              :   int i;
    9053              : 
    9054            0 :   memset(msg, 0, sizeof(*msg));
    9055            0 :   msg->pkt.p = buf;
    9056            0 :   msg->pkt.len = len;
    9057              : 
    9058            0 :   if (len < (int) sizeof(*header)) return -1;
    9059              : 
    9060            0 :   msg->transaction_id = header->transaction_id;
    9061            0 :   msg->flags = ntohs(header->flags);
    9062            0 :   msg->num_questions = ntohs(header->num_questions);
    9063            0 :   if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
    9064            0 :     msg->num_questions = (int) ARRAY_SIZE(msg->questions);
    9065              :   }
    9066            0 :   msg->num_answers = ntohs(header->num_answers);
    9067            0 :   if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
    9068            0 :     msg->num_answers = (int) ARRAY_SIZE(msg->answers);
    9069              :   }
    9070              : 
    9071            0 :   for (i = 0; i < msg->num_questions; i++) {
    9072            0 :     data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
    9073            0 :     if (data == NULL) return -1;
    9074              :   }
    9075              : 
    9076            0 :   for (i = 0; i < msg->num_answers; i++) {
    9077            0 :     data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
    9078            0 :     if (data == NULL) return -1;
    9079              :   }
    9080              : 
    9081            0 :   return 0;
    9082              : }
    9083              : 
    9084            0 : size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
    9085              :                               char *dst, int dst_len) {
    9086              :   int chunk_len;
    9087            0 :   char *old_dst = dst;
    9088            0 :   const unsigned char *data = (unsigned char *) name->p;
    9089            0 :   const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
    9090              : 
    9091            0 :   if (data >= end) {
    9092            0 :     return 0;
    9093              :   }
    9094              : 
    9095            0 :   while ((chunk_len = *data++)) {
    9096            0 :     int leeway = dst_len - (dst - old_dst);
    9097            0 :     if (data >= end) {
    9098            0 :       return 0;
    9099              :     }
    9100              : 
    9101            0 :     if (chunk_len & 0xc0) {
    9102            0 :       uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
    9103            0 :       if (off >= msg->pkt.len) {
    9104            0 :         return 0;
    9105              :       }
    9106            0 :       data = (unsigned char *) msg->pkt.p + off;
    9107            0 :       continue;
    9108            0 :     }
    9109            0 :     if (chunk_len > leeway) {
    9110            0 :       chunk_len = leeway;
    9111              :     }
    9112              : 
    9113            0 :     if (data + chunk_len >= end) {
    9114            0 :       return 0;
    9115              :     }
    9116              : 
    9117            0 :     memcpy(dst, data, chunk_len);
    9118            0 :     data += chunk_len;
    9119            0 :     dst += chunk_len;
    9120            0 :     leeway -= chunk_len;
    9121            0 :     if (leeway == 0) {
    9122            0 :       return dst - old_dst;
    9123              :     }
    9124            0 :     *dst++ = '.';
    9125              :   }
    9126              : 
    9127            0 :   if (dst != old_dst) {
    9128            0 :     *--dst = 0;
    9129              :   }
    9130            0 :   return dst - old_dst;
    9131              : }
    9132              : 
    9133            0 : static void dns_handler(struct mg_connection *nc, int ev, void *ev_data) {
    9134            0 :   struct mbuf *io = &nc->recv_mbuf;
    9135              :   struct mg_dns_message msg;
    9136              : 
    9137              :   /* Pass low-level events to the user handler */
    9138            0 :   nc->handler(nc, ev, ev_data);
    9139              : 
    9140            0 :   switch (ev) {
    9141            0 :     case MG_EV_RECV:
    9142            0 :       if (!(nc->flags & MG_F_UDP)) {
    9143            0 :         mbuf_remove(&nc->recv_mbuf, 2);
    9144              :       }
    9145            0 :       if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
    9146              :         /* reply + recursion allowed + format error */
    9147            0 :         memset(&msg, 0, sizeof(msg));
    9148            0 :         msg.flags = 0x8081;
    9149            0 :         mg_dns_insert_header(io, 0, &msg);
    9150            0 :         if (!(nc->flags & MG_F_UDP)) {
    9151            0 :           uint16_t len = htons(io->len);
    9152            0 :           mbuf_insert(io, 0, &len, 2);
    9153              :         }
    9154            0 :         mg_send(nc, io->buf, io->len);
    9155              :       } else {
    9156              :         /* Call user handler with parsed message */
    9157            0 :         nc->handler(nc, MG_DNS_MESSAGE, &msg);
    9158              :       }
    9159            0 :       mbuf_remove(io, io->len);
    9160            0 :       break;
    9161              :   }
    9162            0 : }
    9163              : 
    9164            0 : void mg_set_protocol_dns(struct mg_connection *nc) {
    9165            0 :   nc->proto_handler = dns_handler;
    9166            0 : }
    9167              : 
    9168              : #endif /* MG_DISABLE_DNS */
    9169              : #ifdef MG_MODULE_LINES
    9170              : #line 1 "./src/dns-server.c"
    9171              : #endif
    9172              : /*
    9173              :  * Copyright (c) 2014 Cesanta Software Limited
    9174              :  * All rights reserved
    9175              :  */
    9176              : 
    9177              : #ifdef MG_ENABLE_DNS_SERVER
    9178              : 
    9179              : /* Amalgamated: #include "mongoose/src/internal.h" */
    9180              : /* Amalgamated: #include "mongoose/src/dns-server.h" */
    9181              : 
    9182              : struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
    9183              :                                         struct mg_dns_message *msg) {
    9184              :   struct mg_dns_reply rep;
    9185              :   rep.msg = msg;
    9186              :   rep.io = io;
    9187              :   rep.start = io->len;
    9188              : 
    9189              :   /* reply + recursion allowed */
    9190              :   msg->flags |= 0x8080;
    9191              :   mg_dns_copy_body(io, msg);
    9192              : 
    9193              :   msg->num_answers = 0;
    9194              :   return rep;
    9195              : }
    9196              : 
    9197              : void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
    9198              :   size_t sent = r->io->len - r->start;
    9199              :   mg_dns_insert_header(r->io, r->start, r->msg);
    9200              :   if (!(nc->flags & MG_F_UDP)) {
    9201              :     uint16_t len = htons(sent);
    9202              :     mbuf_insert(r->io, r->start, &len, 2);
    9203              :   }
    9204              : 
    9205              :   if (&nc->send_mbuf != r->io) {
    9206              :     mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
    9207              :     r->io->len = r->start;
    9208              :   }
    9209              : }
    9210              : 
    9211              : int mg_dns_reply_record(struct mg_dns_reply *reply,
    9212              :                         struct mg_dns_resource_record *question,
    9213              :                         const char *name, int rtype, int ttl, const void *rdata,
    9214              :                         size_t rdata_len) {
    9215              :   struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
    9216              :   char rname[512];
    9217              :   struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
    9218              :   if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
    9219              :     return -1; /* LCOV_EXCL_LINE */
    9220              :   }
    9221              : 
    9222              :   if (name == NULL) {
    9223              :     name = rname;
    9224              :     rname[511] = 0;
    9225              :     mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
    9226              :   }
    9227              : 
    9228              :   *ans = *question;
    9229              :   ans->kind = MG_DNS_ANSWER;
    9230              :   ans->rtype = rtype;
    9231              :   ans->ttl = ttl;
    9232              : 
    9233              :   if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
    9234              :                            rdata_len) == -1) {
    9235              :     return -1; /* LCOV_EXCL_LINE */
    9236              :   };
    9237              : 
    9238              :   msg->num_answers++;
    9239              :   return 0;
    9240              : }
    9241              : 
    9242              : #endif /* MG_ENABLE_DNS_SERVER */
    9243              : #ifdef MG_MODULE_LINES
    9244              : #line 1 "./src/resolv.c"
    9245              : #endif
    9246              : /*
    9247              :  * Copyright (c) 2014 Cesanta Software Limited
    9248              :  * All rights reserved
    9249              :  */
    9250              : 
    9251              : #ifndef MG_DISABLE_RESOLVER
    9252              : 
    9253              : /* Amalgamated: #include "mongoose/src/internal.h" */
    9254              : /* Amalgamated: #include "mongoose/src/resolv.h" */
    9255              : 
    9256              : #ifndef MG_DEFAULT_NAMESERVER
    9257              : #define MG_DEFAULT_NAMESERVER "8.8.8.8"
    9258              : #endif
    9259              : 
    9260              : static const char *mg_default_dns_server = "udp://" MG_DEFAULT_NAMESERVER ":53";
    9261              : 
    9262              : MG_INTERNAL char mg_dns_server[300];
    9263              : 
    9264              : struct mg_resolve_async_request {
    9265              :   char name[1024];
    9266              :   int query;
    9267              :   mg_resolve_callback_t callback;
    9268              :   void *data;
    9269              :   time_t timeout;
    9270              :   int max_retries;
    9271              :   enum mg_resolve_err err;
    9272              : 
    9273              :   /* state */
    9274              :   time_t last_time;
    9275              :   int retries;
    9276              : };
    9277              : 
    9278              : /*
    9279              :  * Find what nameserver to use.
    9280              :  *
    9281              :  * Return 0 if OK, -1 if error
    9282              :  */
    9283            0 : static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
    9284            0 :   int ret = -1;
    9285              : 
    9286              : #ifdef _WIN32
    9287              :   int i;
    9288              :   LONG err;
    9289              :   HKEY hKey, hSub;
    9290              :   char subkey[512], value[128],
    9291              :       *key = "SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
    9292              : 
    9293              :   if ((err = RegOpenKeyA(HKEY_LOCAL_MACHINE, key, &hKey)) != ERROR_SUCCESS) {
    9294              :     fprintf(stderr, "cannot open reg key %s: %d\n", key, err);
    9295              :     ret = -1;
    9296              :   } else {
    9297              :     for (ret = -1, i = 0;
    9298              :          RegEnumKeyA(hKey, i, subkey, sizeof(subkey)) == ERROR_SUCCESS; i++) {
    9299              :       DWORD type, len = sizeof(value);
    9300              :       if (RegOpenKeyA(hKey, subkey, &hSub) == ERROR_SUCCESS &&
    9301              :           (RegQueryValueExA(hSub, "NameServer", 0, &type, (void *) value,
    9302              :                             &len) == ERROR_SUCCESS ||
    9303              :            RegQueryValueExA(hSub, "DhcpNameServer", 0, &type, (void *) value,
    9304              :                             &len) == ERROR_SUCCESS)) {
    9305              :         /*
    9306              :          * See https://github.com/cesanta/mongoose/issues/176
    9307              :          * The value taken from the registry can be empty, a single
    9308              :          * IP address, or multiple IP addresses separated by comma.
    9309              :          * If it's empty, check the next interface.
    9310              :          * If it's multiple IP addresses, take the first one.
    9311              :          */
    9312              :         char *comma = strchr(value, ',');
    9313              :         if (value[0] == '\0') {
    9314              :           continue;
    9315              :         }
    9316              :         if (comma != NULL) {
    9317              :           *comma = '\0';
    9318              :         }
    9319              :         snprintf(name, name_len, "udp://%s:53", value);
    9320              :         ret = 0;
    9321              :         RegCloseKey(hSub);
    9322              :         break;
    9323              :       }
    9324              :     }
    9325              :     RegCloseKey(hKey);
    9326              :   }
    9327              : #elif !defined(MG_DISABLE_FILESYSTEM)
    9328              :   FILE *fp;
    9329              :   char line[512];
    9330              : 
    9331            0 :   if ((fp = fopen("/etc/resolv.conf", "r")) == NULL) {
    9332            0 :     ret = -1;
    9333              :   } else {
    9334              :     /* Try to figure out what nameserver to use */
    9335            0 :     for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
    9336              :       char buf[256];
    9337            0 :       if (sscanf(line, "nameserver %255[^\n\t #]s", buf) == 1) {
    9338            0 :         snprintf(name, name_len, "udp://%s:53", buf);
    9339            0 :         ret = 0;
    9340            0 :         break;
    9341              :       }
    9342              :     }
    9343            0 :     (void) fclose(fp);
    9344              :   }
    9345              : #else
    9346              :   snprintf(name, name_len, "%s", mg_default_dns_server);
    9347              : #endif /* _WIN32 */
    9348              : 
    9349            0 :   return ret;
    9350              : }
    9351              : 
    9352            0 : int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
    9353              : #ifndef MG_DISABLE_FILESYSTEM
    9354              :   /* TODO(mkm) cache /etc/hosts */
    9355              :   FILE *fp;
    9356              :   char line[1024];
    9357              :   char *p;
    9358              :   char alias[256];
    9359              :   unsigned int a, b, c, d;
    9360            0 :   int len = 0;
    9361              : 
    9362            0 :   if ((fp = fopen("/etc/hosts", "r")) == NULL) {
    9363            0 :     return -1;
    9364              :   }
    9365              : 
    9366            0 :   for (; fgets(line, sizeof(line), fp) != NULL;) {
    9367            0 :     if (line[0] == '#') continue;
    9368              : 
    9369            0 :     if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
    9370              :       /* TODO(mkm): handle ipv6 */
    9371            0 :       continue;
    9372              :     }
    9373            0 :     for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
    9374            0 :       if (strcmp(alias, name) == 0) {
    9375            0 :         usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
    9376            0 :         fclose(fp);
    9377            0 :         return 0;
    9378              :       }
    9379              :     }
    9380              :   }
    9381              : 
    9382            0 :   fclose(fp);
    9383              : #endif
    9384              : 
    9385            0 :   return -1;
    9386              : }
    9387              : 
    9388            0 : static void mg_resolve_async_eh(struct mg_connection *nc, int ev, void *data) {
    9389            0 :   time_t now = time(NULL);
    9390              :   struct mg_resolve_async_request *req;
    9391              :   struct mg_dns_message *msg;
    9392              : 
    9393            0 :   DBG(("ev=%d", ev));
    9394              : 
    9395            0 :   req = (struct mg_resolve_async_request *) nc->user_data;
    9396              : 
    9397            0 :   switch (ev) {
    9398            0 :     case MG_EV_CONNECT:
    9399              :     case MG_EV_POLL:
    9400            0 :       if (req->retries > req->max_retries) {
    9401            0 :         req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT;
    9402            0 :         nc->flags |= MG_F_CLOSE_IMMEDIATELY;
    9403            0 :         break;
    9404              :       }
    9405            0 :       if (now - req->last_time >= req->timeout) {
    9406            0 :         mg_send_dns_query(nc, req->name, req->query);
    9407            0 :         req->last_time = now;
    9408            0 :         req->retries++;
    9409              :       }
    9410            0 :       break;
    9411            0 :     case MG_EV_RECV:
    9412            0 :       msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
    9413            0 :       if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
    9414            0 :           msg->num_answers > 0) {
    9415            0 :         req->callback(msg, req->data, MG_RESOLVE_OK);
    9416            0 :         nc->user_data = NULL;
    9417            0 :         MG_FREE(req);
    9418              :       } else {
    9419            0 :         req->err = MG_RESOLVE_NO_ANSWERS;
    9420              :       }
    9421            0 :       MG_FREE(msg);
    9422            0 :       nc->flags |= MG_F_CLOSE_IMMEDIATELY;
    9423            0 :       break;
    9424            0 :     case MG_EV_SEND:
    9425              :       /*
    9426              :        * If a send error occurs, prevent closing of the connection by the core.
    9427              :        * We will retry after timeout.
    9428              :        */
    9429            0 :       nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
    9430            0 :       mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
    9431            0 :       break;
    9432            0 :     case MG_EV_TIMER:
    9433            0 :       req->err = MG_RESOLVE_TIMEOUT;
    9434            0 :       nc->flags |= MG_F_CLOSE_IMMEDIATELY;
    9435            0 :       break;
    9436            0 :     case MG_EV_CLOSE:
    9437              :       /* If we got here with request still not done, fire an error callback. */
    9438            0 :       if (req != NULL) {
    9439            0 :         req->callback(NULL, req->data, req->err);
    9440            0 :         nc->user_data = NULL;
    9441            0 :         MG_FREE(req);
    9442              :       }
    9443            0 :       break;
    9444              :   }
    9445            0 : }
    9446              : 
    9447            0 : int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
    9448              :                      mg_resolve_callback_t cb, void *data) {
    9449              :   struct mg_resolve_async_opts opts;
    9450            0 :   memset(&opts, 0, sizeof(opts));
    9451            0 :   return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
    9452              : }
    9453              : 
    9454            0 : int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
    9455              :                          mg_resolve_callback_t cb, void *data,
    9456              :                          struct mg_resolve_async_opts opts) {
    9457              :   struct mg_resolve_async_request *req;
    9458              :   struct mg_connection *dns_nc;
    9459            0 :   const char *nameserver = opts.nameserver_url;
    9460              : 
    9461            0 :   DBG(("%s %d %p", name, query, opts.dns_conn));
    9462              : 
    9463              :   /* resolve with DNS */
    9464            0 :   req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
    9465            0 :   if (req == NULL) {
    9466            0 :     return -1;
    9467              :   }
    9468              : 
    9469            0 :   memset(req->name, 0, sizeof(req->name));
    9470            0 :   strncpy(req->name, name, sizeof(req->name)-1);
    9471            0 :   req->query = query;
    9472            0 :   req->callback = cb;
    9473            0 :   req->data = data;
    9474              :   /* TODO(mkm): parse defaults out of resolve.conf */
    9475            0 :   req->max_retries = opts.max_retries ? opts.max_retries : 2;
    9476            0 :   req->timeout = opts.timeout ? opts.timeout : 5;
    9477              : 
    9478              :   /* Lazily initialize dns server */
    9479            0 :   if (nameserver == NULL && mg_dns_server[0] == '\0' &&
    9480            0 :       mg_get_ip_address_of_nameserver(mg_dns_server, sizeof(mg_dns_server)) ==
    9481              :           -1) {
    9482            0 :     strncpy(mg_dns_server, mg_default_dns_server, sizeof(mg_dns_server));
    9483              :   }
    9484              : 
    9485            0 :   if (nameserver == NULL) {
    9486            0 :     nameserver = mg_dns_server;
    9487              :   }
    9488              : 
    9489            0 :   dns_nc = mg_connect(mgr, nameserver, mg_resolve_async_eh);
    9490            0 :   if (dns_nc == NULL) {
    9491            0 :     free(req);
    9492            0 :     return -1;
    9493              :   }
    9494            0 :   dns_nc->user_data = req;
    9495            0 :   if (opts.dns_conn != NULL) {
    9496            0 :     *opts.dns_conn = dns_nc;
    9497              :   }
    9498              : 
    9499            0 :   return 0;
    9500              : }
    9501              : 
    9502              : #endif /* MG_DISABLE_RESOLVE */
    9503              : #ifdef MG_MODULE_LINES
    9504              : #line 1 "./src/coap.c"
    9505              : #endif
    9506              : /*
    9507              :  * Copyright (c) 2015 Cesanta Software Limited
    9508              :  * All rights reserved
    9509              :  * This software is dual-licensed: you can redistribute it and/or modify
    9510              :  * it under the terms of the GNU General Public License version 2 as
    9511              :  * published by the Free Software Foundation. For the terms of this
    9512              :  * license, see <http://www.gnu.org/licenses/>.
    9513              :  *
    9514              :  * You are free to use this software under the terms of the GNU General
    9515              :  * Public License, but WITHOUT ANY WARRANTY; without even the implied
    9516              :  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
    9517              :  * See the GNU General Public License for more details.
    9518              :  *
    9519              :  * Alternatively, you can license this software under a commercial
    9520              :  * license, as set out in <https://www.cesanta.com/license>.
    9521              :  */
    9522              : 
    9523              : /* Amalgamated: #include "mongoose/src/internal.h" */
    9524              : /* Amalgamated: #include "mongoose/src/coap.h" */
    9525              : 
    9526              : #ifdef MG_ENABLE_COAP
    9527              : 
    9528              : void mg_coap_free_options(struct mg_coap_message *cm) {
    9529              :   while (cm->options != NULL) {
    9530              :     struct mg_coap_option *next = cm->options->next;
    9531              :     MG_FREE(cm->options);
    9532              :     cm->options = next;
    9533              :   }
    9534              : }
    9535              : 
    9536              : struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
    9537              :                                           uint32_t number, char *value,
    9538              :                                           size_t len) {
    9539              :   struct mg_coap_option *new_option =
    9540              :       (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
    9541              : 
    9542              :   new_option->number = number;
    9543              :   new_option->value.p = value;
    9544              :   new_option->value.len = len;
    9545              : 
    9546              :   if (cm->options == NULL) {
    9547              :     cm->options = cm->optiomg_tail = new_option;
    9548              :   } else {
    9549              :     /*
    9550              :      * A very simple attention to help clients to compose options:
    9551              :      * CoAP wants to see options ASC ordered.
    9552              :      * Could be change by using sort in coap_compose
    9553              :      */
    9554              :     if (cm->optiomg_tail->number <= new_option->number) {
    9555              :       /* if option is already ordered just add it */
    9556              :       cm->optiomg_tail = cm->optiomg_tail->next = new_option;
    9557              :     } else {
    9558              :       /* looking for appropriate position */
    9559              :       struct mg_coap_option *current_opt = cm->options;
    9560              :       struct mg_coap_option *prev_opt = 0;
    9561              : 
    9562              :       while (current_opt != NULL) {
    9563              :         if (current_opt->number > new_option->number) {
    9564              :           break;
    9565              :         }
    9566              :         prev_opt = current_opt;
    9567              :         current_opt = current_opt->next;
    9568              :       }
    9569              : 
    9570              :       if (prev_opt != NULL) {
    9571              :         prev_opt->next = new_option;
    9572              :         new_option->next = current_opt;
    9573              :       } else {
    9574              :         /* insert new_option to the beginning */
    9575              :         new_option->next = cm->options;
    9576              :         cm->options = new_option;
    9577              :       }
    9578              :     }
    9579              :   }
    9580              : 
    9581              :   return new_option;
    9582              : }
    9583              : 
    9584              : /*
    9585              :  * Fills CoAP header in mg_coap_message.
    9586              :  *
    9587              :  * Helper function.
    9588              :  */
    9589              : static char *coap_parse_header(char *ptr, struct mbuf *io,
    9590              :                                struct mg_coap_message *cm) {
    9591              :   if (io->len < sizeof(uint32_t)) {
    9592              :     cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
    9593              :     return NULL;
    9594              :   }
    9595              : 
    9596              :   /*
    9597              :    * Version (Ver):  2-bit unsigned integer.  Indicates the CoAP version
    9598              :    * number.  Implementations of this specification MUST set this field
    9599              :    * to 1 (01 binary).  Other values are reserved for future versions.
    9600              :    * Messages with unknown version numbers MUST be silently ignored.
    9601              :    */
    9602              :   if (((uint8_t) *ptr >> 6) != 1) {
    9603              :     cm->flags |= MG_COAP_IGNORE;
    9604              :     return NULL;
    9605              :   }
    9606              : 
    9607              :   /*
    9608              :    * Type (T):  2-bit unsigned integer.  Indicates if this message is of
    9609              :    * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
    9610              :    * Reset (3).
    9611              :    */
    9612              :   cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
    9613              :   cm->flags |= MG_COAP_MSG_TYPE_FIELD;
    9614              : 
    9615              :   /*
    9616              :    * Token Length (TKL):  4-bit unsigned integer.  Indicates the length of
    9617              :    * the variable-length Token field (0-8 bytes).  Lengths 9-15 are
    9618              :    * reserved, MUST NOT be sent, and MUST be processed as a message
    9619              :    * format error.
    9620              :    */
    9621              :   cm->token.len = *ptr & 0x0F;
    9622              :   if (cm->token.len > 8) {
    9623              :     cm->flags |= MG_COAP_FORMAT_ERROR;
    9624              :     return NULL;
    9625              :   }
    9626              : 
    9627              :   ptr++;
    9628              : 
    9629              :   /*
    9630              :    * Code:  8-bit unsigned integer, split into a 3-bit class (most
    9631              :    * significant bits) and a 5-bit detail (least significant bits)
    9632              :    */
    9633              :   cm->code_class = (uint8_t) *ptr >> 5;
    9634              :   cm->code_detail = *ptr & 0x1F;
    9635              :   cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
    9636              : 
    9637              :   ptr++;
    9638              : 
    9639              :   /* Message ID:  16-bit unsigned integer in network byte order. */
    9640              :   cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
    9641              :   cm->flags |= MG_COAP_MSG_ID_FIELD;
    9642              : 
    9643              :   ptr += 2;
    9644              : 
    9645              :   return ptr;
    9646              : }
    9647              : 
    9648              : /*
    9649              :  * Fills token information in mg_coap_message.
    9650              :  *
    9651              :  * Helper function.
    9652              :  */
    9653              : static char *coap_get_token(char *ptr, struct mbuf *io,
    9654              :                             struct mg_coap_message *cm) {
    9655              :   if (cm->token.len != 0) {
    9656              :     if (ptr + cm->token.len > io->buf + io->len) {
    9657              :       cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
    9658              :       return NULL;
    9659              :     } else {
    9660              :       cm->token.p = ptr;
    9661              :       ptr += cm->token.len;
    9662              :       cm->flags |= MG_COAP_TOKEN_FIELD;
    9663              :     }
    9664              :   }
    9665              : 
    9666              :   return ptr;
    9667              : }
    9668              : 
    9669              : /*
    9670              :  * Returns Option Delta or Length.
    9671              :  *
    9672              :  * Helper function.
    9673              :  */
    9674              : static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
    9675              :   int ret = 0;
    9676              : 
    9677              :   if (*opt_info == 13) {
    9678              :     /*
    9679              :      * 13:  An 8-bit unsigned integer follows the initial byte and
    9680              :      * indicates the Option Delta/Length minus 13.
    9681              :      */
    9682              :     if (ptr < io->buf + io->len) {
    9683              :       *opt_info = (uint8_t) *ptr + 13;
    9684              :       ret = sizeof(uint8_t);
    9685              :     } else {
    9686              :       ret = -1; /* LCOV_EXCL_LINE */
    9687              :     }
    9688              :   } else if (*opt_info == 14) {
    9689              :     /*
    9690              :      * 14:  A 16-bit unsigned integer in network byte order follows the
    9691              :      * initial byte and indicates the Option Delta/Length minus 269.
    9692              :      */
    9693              :     if (ptr + sizeof(uint8_t) < io->buf + io->len) {
    9694              :       *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
    9695              :       ret = sizeof(uint16_t);
    9696              :     } else {
    9697              :       ret = -1; /* LCOV_EXCL_LINE */
    9698              :     }
    9699              :   }
    9700              : 
    9701              :   return ret;
    9702              : }
    9703              : 
    9704              : /*
    9705              :  * Fills options in mg_coap_message.
    9706              :  *
    9707              :  * Helper function.
    9708              :  *
    9709              :  * General options format:
    9710              :  * +---------------+---------------+
    9711              :  * | Option Delta  | Option Length |  1 byte
    9712              :  * +---------------+---------------+
    9713              :  * \    Option Delta (extended)    \  0-2 bytes
    9714              :  * +-------------------------------+
    9715              :  * / Option Length  (extended)     \  0-2 bytes
    9716              :  * +-------------------------------+
    9717              :  * \         Option Value          \  0 or more bytes
    9718              :  * +-------------------------------+
    9719              :  */
    9720              : static char *coap_get_options(char *ptr, struct mbuf *io,
    9721              :                               struct mg_coap_message *cm) {
    9722              :   uint16_t prev_opt = 0;
    9723              : 
    9724              :   if (ptr == io->buf + io->len) {
    9725              :     /* end of packet, ok */
    9726              :     return NULL;
    9727              :   }
    9728              : 
    9729              :   /* 0xFF is payload marker */
    9730              :   while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
    9731              :     uint16_t option_delta, option_lenght;
    9732              :     int optinfo_len;
    9733              : 
    9734              :     /* Option Delta:  4-bit unsigned integer */
    9735              :     option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
    9736              :     /* Option Length:  4-bit unsigned integer */
    9737              :     option_lenght = *ptr & 0x0F;
    9738              : 
    9739              :     if (option_delta == 15 || option_lenght == 15) {
    9740              :       /*
    9741              :        * 15:  Reserved for future use.  If the field is set to this value,
    9742              :        * it MUST be processed as a message format error
    9743              :        */
    9744              :       cm->flags |= MG_COAP_FORMAT_ERROR;
    9745              :       break;
    9746              :     }
    9747              : 
    9748              :     ptr++;
    9749              : 
    9750              :     /* check for extended option delta */
    9751              :     optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
    9752              :     if (optinfo_len == -1) {
    9753              :       cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
    9754              :       break;                                /* LCOV_EXCL_LINE */
    9755              :     }
    9756              : 
    9757              :     ptr += optinfo_len;
    9758              : 
    9759              :     /* check or extended option lenght */
    9760              :     optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
    9761              :     if (optinfo_len == -1) {
    9762              :       cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
    9763              :       break;                                /* LCOV_EXCL_LINE */
    9764              :     }
    9765              : 
    9766              :     ptr += optinfo_len;
    9767              : 
    9768              :     /*
    9769              :      * Instead of specifying the Option Number directly, the instances MUST
    9770              :      * appear in order of their Option Numbers and a delta encoding is used
    9771              :      * between them.
    9772              :      */
    9773              :     option_delta += prev_opt;
    9774              : 
    9775              :     mg_coap_add_option(cm, option_delta, ptr, option_lenght);
    9776              : 
    9777              :     prev_opt = option_delta;
    9778              : 
    9779              :     if (ptr + option_lenght > io->buf + io->len) {
    9780              :       cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
    9781              :       break;                                /* LCOV_EXCL_LINE */
    9782              :     }
    9783              : 
    9784              :     ptr += option_lenght;
    9785              :   }
    9786              : 
    9787              :   if ((cm->flags & MG_COAP_ERROR) != 0) {
    9788              :     mg_coap_free_options(cm);
    9789              :     return NULL;
    9790              :   }
    9791              : 
    9792              :   cm->flags |= MG_COAP_OPTIOMG_FIELD;
    9793              : 
    9794              :   if (ptr == io->buf + io->len) {
    9795              :     /* end of packet, ok */
    9796              :     return NULL;
    9797              :   }
    9798              : 
    9799              :   ptr++;
    9800              : 
    9801              :   return ptr;
    9802              : }
    9803              : 
    9804              : uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
    9805              :   char *ptr;
    9806              : 
    9807              :   memset(cm, 0, sizeof(*cm));
    9808              : 
    9809              :   if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
    9810              :     return cm->flags;
    9811              :   }
    9812              : 
    9813              :   if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
    9814              :     return cm->flags;
    9815              :   }
    9816              : 
    9817              :   if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
    9818              :     return cm->flags;
    9819              :   }
    9820              : 
    9821              :   /* the rest is payload */
    9822              :   cm->payload.len = io->len - (ptr - io->buf);
    9823              :   if (cm->payload.len != 0) {
    9824              :     cm->payload.p = ptr;
    9825              :     cm->flags |= MG_COAP_PAYLOAD_FIELD;
    9826              :   }
    9827              : 
    9828              :   return cm->flags;
    9829              : }
    9830              : 
    9831              : /*
    9832              :  * Calculates extended size of given Opt Number/Length in coap message.
    9833              :  *
    9834              :  * Helper function.
    9835              :  */
    9836              : static size_t coap_get_ext_opt_size(uint32_t value) {
    9837              :   int ret = 0;
    9838              : 
    9839              :   if (value >= 13 && value <= 0xFF + 13) {
    9840              :     ret = sizeof(uint8_t);
    9841              :   } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
    9842              :     ret = sizeof(uint16_t);
    9843              :   }
    9844              : 
    9845              :   return ret;
    9846              : }
    9847              : 
    9848              : /*
    9849              :  * Splits given Opt Number/Length into base and ext values.
    9850              :  *
    9851              :  * Helper function.
    9852              :  */
    9853              : static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
    9854              :   int ret = 0;
    9855              : 
    9856              :   if (value < 13) {
    9857              :     *base = value;
    9858              :   } else if (value >= 13 && value <= 0xFF + 13) {
    9859              :     *base = 13;
    9860              :     *ext = value - 13;
    9861              :     ret = sizeof(uint8_t);
    9862              :   } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
    9863              :     *base = 14;
    9864              :     *ext = value - 269;
    9865              :     ret = sizeof(uint16_t);
    9866              :   }
    9867              : 
    9868              :   return ret;
    9869              : }
    9870              : 
    9871              : /*
    9872              :  * Puts uint16_t (in network order) into given char stream.
    9873              :  *
    9874              :  * Helper function.
    9875              :  */
    9876              : static char *coap_add_uint16(char *ptr, uint16_t val) {
    9877              :   *ptr = val >> 8;
    9878              :   ptr++;
    9879              :   *ptr = val & 0x00FF;
    9880              :   ptr++;
    9881              :   return ptr;
    9882              : }
    9883              : 
    9884              : /*
    9885              :  * Puts extended value of Opt Number/Length into given char stream.
    9886              :  *
    9887              :  * Helper function.
    9888              :  */
    9889              : static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
    9890              :   if (len == sizeof(uint8_t)) {
    9891              :     *ptr = val;
    9892              :     ptr++;
    9893              :   } else if (len == sizeof(uint16_t)) {
    9894              :     ptr = coap_add_uint16(ptr, val);
    9895              :   }
    9896              : 
    9897              :   return ptr;
    9898              : }
    9899              : 
    9900              : /*
    9901              :  * Verifies given mg_coap_message and calculates message size for it.
    9902              :  *
    9903              :  * Helper function.
    9904              :  */
    9905              : static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
    9906              :                                            size_t *len) {
    9907              :   struct mg_coap_option *opt;
    9908              :   uint32_t prev_opt_number;
    9909              : 
    9910              :   *len = 4; /* header */
    9911              :   if (cm->msg_type > MG_COAP_MSG_MAX) {
    9912              :     return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
    9913              :   }
    9914              :   if (cm->token.len > 8) {
    9915              :     return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
    9916              :   }
    9917              :   if (cm->code_class > 7) {
    9918              :     return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
    9919              :   }
    9920              :   if (cm->code_detail > 31) {
    9921              :     return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
    9922              :   }
    9923              : 
    9924              :   *len += cm->token.len;
    9925              :   if (cm->payload.len != 0) {
    9926              :     *len += cm->payload.len + 1; /* ... + 1; add payload marker */
    9927              :   }
    9928              : 
    9929              :   opt = cm->options;
    9930              :   prev_opt_number = 0;
    9931              :   while (opt != NULL) {
    9932              :     *len += 1; /* basic delta/length */
    9933              :     *len += coap_get_ext_opt_size(opt->number);
    9934              :     *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
    9935              :     /*
    9936              :      * Current implementation performs check if
    9937              :      * option_number > previous option_number and produces an error
    9938              :      * TODO(alashkin): write design doc with limitations
    9939              :      * May be resorting is more suitable solution.
    9940              :      */
    9941              :     if ((opt->next != NULL && opt->number > opt->next->number) ||
    9942              :         opt->value.len > 0xFFFF + 269 ||
    9943              :         opt->number - prev_opt_number > 0xFFFF + 269) {
    9944              :       return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
    9945              :     }
    9946              :     *len += opt->value.len;
    9947              :     opt = opt->next;
    9948              :   }
    9949              : 
    9950              :   return 0;
    9951              : }
    9952              : 
    9953              : uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
    9954              :   struct mg_coap_option *opt;
    9955              :   uint32_t res, prev_opt_number;
    9956              :   size_t prev_io_len, packet_size;
    9957              :   char *ptr;
    9958              : 
    9959              :   res = coap_calculate_packet_size(cm, &packet_size);
    9960              :   if (res != 0) {
    9961              :     return res;
    9962              :   }
    9963              : 
    9964              :   /* saving previous lenght to handle non-empty mbuf */
    9965              :   prev_io_len = io->len;
    9966              :   mbuf_append(io, NULL, packet_size);
    9967              :   ptr = io->buf + prev_io_len;
    9968              : 
    9969              :   /*
    9970              :    * since cm is verified, it is possible to use bits shift operator
    9971              :    * without additional zeroing of unused bits
    9972              :    */
    9973              : 
    9974              :   /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
    9975              :   *ptr = (1 << 6) | (cm->msg_type << 4) | (cm->token.len);
    9976              :   ptr++;
    9977              : 
    9978              :   /* code class: 3 bits, code detail: 5 bits */
    9979              :   *ptr = (cm->code_class << 5) | (cm->code_detail);
    9980              :   ptr++;
    9981              : 
    9982              :   ptr = coap_add_uint16(ptr, cm->msg_id);
    9983              : 
    9984              :   if (cm->token.len != 0) {
    9985              :     memcpy(ptr, cm->token.p, cm->token.len);
    9986              :     ptr += cm->token.len;
    9987              :   }
    9988              : 
    9989              :   opt = cm->options;
    9990              :   prev_opt_number = 0;
    9991              :   while (opt != NULL) {
    9992              :     uint8_t delta_base = 0, length_base = 0;
    9993              :     uint16_t delta_ext, length_ext;
    9994              : 
    9995              :     size_t opt_delta_len =
    9996              :         coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
    9997              :     size_t opt_lenght_len =
    9998              :         coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
    9999              : 
   10000              :     *ptr = (delta_base << 4) | length_base;
   10001              :     ptr++;
   10002              : 
   10003              :     ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
   10004              :     ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
   10005              : 
   10006              :     if (opt->value.len != 0) {
   10007              :       memcpy(ptr, opt->value.p, opt->value.len);
   10008              :       ptr += opt->value.len;
   10009              :     }
   10010              : 
   10011              :     prev_opt_number = opt->number;
   10012              :     opt = opt->next;
   10013              :   }
   10014              : 
   10015              :   if (cm->payload.len != 0) {
   10016              :     *ptr = -1;
   10017              :     ptr++;
   10018              :     memcpy(ptr, cm->payload.p, cm->payload.len);
   10019              :   }
   10020              : 
   10021              :   return 0;
   10022              : }
   10023              : 
   10024              : uint32_t mg_coap_send_message(struct mg_connection *nc,
   10025              :                               struct mg_coap_message *cm) {
   10026              :   struct mbuf packet_out;
   10027              :   uint32_t compose_res;
   10028              : 
   10029              :   mbuf_init(&packet_out, 0);
   10030              :   compose_res = mg_coap_compose(cm, &packet_out);
   10031              :   if (compose_res != 0) {
   10032              :     return compose_res; /* LCOV_EXCL_LINE */
   10033              :   }
   10034              : 
   10035              :   mg_send(nc, packet_out.buf, (int) packet_out.len);
   10036              :   mbuf_free(&packet_out);
   10037              : 
   10038              :   return 0;
   10039              : }
   10040              : 
   10041              : uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
   10042              :   struct mg_coap_message cm;
   10043              :   memset(&cm, 0, sizeof(cm));
   10044              :   cm.msg_type = MG_COAP_MSG_ACK;
   10045              :   cm.msg_id = msg_id;
   10046              : 
   10047              :   return mg_coap_send_message(nc, &cm);
   10048              : }
   10049              : 
   10050              : static void coap_handler(struct mg_connection *nc, int ev, void *ev_data) {
   10051              :   struct mbuf *io = &nc->recv_mbuf;
   10052              :   struct mg_coap_message cm;
   10053              :   uint32_t parse_res;
   10054              : 
   10055              :   memset(&cm, 0, sizeof(cm));
   10056              : 
   10057              :   nc->handler(nc, ev, ev_data);
   10058              : 
   10059              :   switch (ev) {
   10060              :     case MG_EV_RECV:
   10061              :       parse_res = mg_coap_parse(io, &cm);
   10062              :       if ((parse_res & MG_COAP_IGNORE) == 0) {
   10063              :         if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
   10064              :           /*
   10065              :            * Since we support UDP only
   10066              :            * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
   10067              :            */
   10068              :           cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
   10069              :         }                                   /* LCOV_EXCL_LINE */
   10070              :         nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type, &cm);
   10071              :       }
   10072              : 
   10073              :       mg_coap_free_options(&cm);
   10074              :       mbuf_remove(io, io->len);
   10075              :       break;
   10076              :   }
   10077              : }
   10078              : /*
   10079              :  * Attach built-in CoAP event handler to the given connection.
   10080              :  *
   10081              :  * The user-defined event handler will receive following extra events:
   10082              :  *
   10083              :  * - MG_EV_COAP_CON
   10084              :  * - MG_EV_COAP_NOC
   10085              :  * - MG_EV_COAP_ACK
   10086              :  * - MG_EV_COAP_RST
   10087              :  */
   10088              : int mg_set_protocol_coap(struct mg_connection *nc) {
   10089              :   /* supports UDP only */
   10090              :   if ((nc->flags & MG_F_UDP) == 0) {
   10091              :     return -1;
   10092              :   }
   10093              : 
   10094              :   nc->proto_handler = coap_handler;
   10095              : 
   10096              :   return 0;
   10097              : }
   10098              : 
   10099              : #endif /* MG_DISABLE_COAP */
   10100              : #ifdef MG_MODULE_LINES
   10101              : #line 1 "./src/../../common/platforms/cc3200/cc3200_libc.c"
   10102              : #endif
   10103              : /*
   10104              :  * Copyright (c) 2014-2016 Cesanta Software Limited
   10105              :  * All rights reserved
   10106              :  */
   10107              : 
   10108              : #if CS_PLATFORM == CS_P_CC3200
   10109              : 
   10110              : #include <stdio.h>
   10111              : #include <string.h>
   10112              : 
   10113              : #ifndef __TI_COMPILER_VERSION__
   10114              : #include <reent.h>
   10115              : #include <sys/stat.h>
   10116              : #include <sys/time.h>
   10117              : #include <unistd.h>
   10118              : #endif
   10119              : 
   10120              : #include <inc/hw_types.h>
   10121              : #include <inc/hw_memmap.h>
   10122              : #include <driverlib/prcm.h>
   10123              : #include <driverlib/rom.h>
   10124              : #include <driverlib/rom_map.h>
   10125              : #include <driverlib/uart.h>
   10126              : #include <driverlib/utils.h>
   10127              : 
   10128              : #define CONSOLE_UART UARTA0_BASE
   10129              : 
   10130              : #ifndef __TI_COMPILER_VERSION__
   10131              : int _gettimeofday_r(struct _reent *r, struct timeval *tp, void *tzp) {
   10132              : #else
   10133              : int gettimeofday(struct timeval *tp, void *tzp) {
   10134              : #endif
   10135              :   unsigned long long r1 = 0, r2;
   10136              :   /* Achieve two consecutive reads of the same value. */
   10137              :   do {
   10138              :     r2 = r1;
   10139              :     r1 = PRCMSlowClkCtrFastGet();
   10140              :   } while (r1 != r2);
   10141              :   /* This is a 32768 Hz counter. */
   10142              :   tp->tv_sec = (r1 >> 15);
   10143              :   /* 1/32768-th of a second is 30.517578125 microseconds, approx. 31,
   10144              :    * but we round down so it doesn't overflow at 32767 */
   10145              :   tp->tv_usec = (r1 & 0x7FFF) * 30;
   10146              :   return 0;
   10147              : }
   10148              : 
   10149              : long int random(void) {
   10150              :   return 42; /* FIXME */
   10151              : }
   10152              : 
   10153              : void fprint_str(FILE *fp, const char *str) {
   10154              :   while (*str != '\0') {
   10155              :     if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
   10156              :     MAP_UARTCharPut(CONSOLE_UART, *str++);
   10157              :   }
   10158              : }
   10159              : 
   10160              : void _exit(int status) {
   10161              :   fprint_str(stderr, "_exit\n");
   10162              :   /* cause an unaligned access exception, that will drop you into gdb */
   10163              :   *(int *) 1 = status;
   10164              :   while (1)
   10165              :     ; /* avoid gcc warning because stdlib abort() has noreturn attribute */
   10166              : }
   10167              : 
   10168              : void _not_implemented(const char *what) {
   10169              :   fprint_str(stderr, what);
   10170              :   fprint_str(stderr, " is not implemented\n");
   10171              :   _exit(42);
   10172              : }
   10173              : 
   10174              : int _kill(int pid, int sig) {
   10175              :   (void) pid;
   10176              :   (void) sig;
   10177              :   _not_implemented("_kill");
   10178              :   return -1;
   10179              : }
   10180              : 
   10181              : int _getpid() {
   10182              :   fprint_str(stderr, "_getpid is not implemented\n");
   10183              :   return 42;
   10184              : }
   10185              : 
   10186              : int _isatty(int fd) {
   10187              :   /* 0, 1 and 2 are TTYs. */
   10188              :   return fd < 2;
   10189              : }
   10190              : 
   10191              : #endif /* CS_PLATFORM == CS_P_CC3200 */
   10192              : #ifdef MG_MODULE_LINES
   10193              : #line 1 "./src/../../common/platforms/msp432/msp432_libc.c"
   10194              : #endif
   10195              : /*
   10196              :  * Copyright (c) 2014-2016 Cesanta Software Limited
   10197              :  * All rights reserved
   10198              :  */
   10199              : 
   10200              : #if CS_PLATFORM == CS_P_MSP432
   10201              : 
   10202              : #include <ti/sysbios/BIOS.h>
   10203              : #include <ti/sysbios/knl/Clock.h>
   10204              : 
   10205              : int gettimeofday(struct timeval *tp, void *tzp) {
   10206              :   uint32_t ticks = Clock_getTicks();
   10207              :   tp->tv_sec = ticks / 1000;
   10208              :   tp->tv_usec = (ticks % 1000) * 1000;
   10209              :   return 0;
   10210              : }
   10211              : 
   10212              : long int random(void) {
   10213              :   return 42; /* FIXME */
   10214              : }
   10215              : 
   10216              : #endif /* CS_PLATFORM == CS_P_MSP432 */
   10217              : #ifdef MG_MODULE_LINES
   10218              : #line 1 "./src/../../common/platforms/simplelink/sl_fs_slfs.h"
   10219              : #endif
   10220              : /*
   10221              :  * Copyright (c) 2014-2016 Cesanta Software Limited
   10222              :  * All rights reserved
   10223              :  */
   10224              : 
   10225              : #ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
   10226              : #define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
   10227              : 
   10228              : #if defined(MG_FS_SLFS)
   10229              : 
   10230              : #include <stdio.h>
   10231              : #ifndef __TI_COMPILER_VERSION__
   10232              : #include <unistd.h>
   10233              : #include <sys/stat.h>
   10234              : #endif
   10235              : 
   10236              : #define MAX_OPEN_SLFS_FILES 8
   10237              : 
   10238              : /* Indirect libc interface - same functions, different names. */
   10239              : int fs_slfs_open(const char *pathname, int flags, mode_t mode);
   10240              : int fs_slfs_close(int fd);
   10241              : ssize_t fs_slfs_read(int fd, void *buf, size_t count);
   10242              : ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
   10243              : int fs_slfs_stat(const char *pathname, struct stat *s);
   10244              : int fs_slfs_fstat(int fd, struct stat *s);
   10245              : off_t fs_slfs_lseek(int fd, off_t offset, int whence);
   10246              : int fs_slfs_unlink(const char *filename);
   10247              : int fs_slfs_rename(const char *from, const char *to);
   10248              : 
   10249              : #endif /* defined(MG_FS_SLFS) */
   10250              : 
   10251              : #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
   10252              : #ifdef MG_MODULE_LINES
   10253              : #line 1 "./src/../../common/platforms/simplelink/sl_fs_slfs.c"
   10254              : #endif
   10255              : /*
   10256              :  * Copyright (c) 2014-2016 Cesanta Software Limited
   10257              :  * All rights reserved
   10258              :  */
   10259              : 
   10260              : /* Standard libc interface to TI SimpleLink FS. */
   10261              : 
   10262              : #if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
   10263              : 
   10264              : /* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
   10265              : 
   10266              : #include <errno.h>
   10267              : 
   10268              : #if CS_PLATFORM == CS_P_CC3200
   10269              : #include <inc/hw_types.h>
   10270              : #endif
   10271              : #include <simplelink/include/simplelink.h>
   10272              : #include <simplelink/include/fs.h>
   10273              : 
   10274              : /* Amalgamated: #include "common/cs_dbg.h" */
   10275              : 
   10276              : extern int set_errno(int e); /* From sl_fs.c */
   10277              : 
   10278              : /*
   10279              :  * With SLFS, you have to pre-declare max file size. Yes. Really.
   10280              :  * 64K should be enough for everyone. Right?
   10281              :  */
   10282              : #ifndef FS_SLFS_MAX_FILE_SIZE
   10283              : #define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
   10284              : #endif
   10285              : 
   10286              : struct sl_fd_info {
   10287              :   _i32 fh;
   10288              :   _off_t pos;
   10289              :   size_t size;
   10290              : };
   10291              : 
   10292              : static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
   10293              : 
   10294              : static int sl_fs_to_errno(_i32 r) {
   10295              :   DBG(("SL error: %d", (int) r));
   10296              :   switch (r) {
   10297              :     case SL_FS_OK:
   10298              :       return 0;
   10299              :     case SL_FS_FILE_NAME_EXIST:
   10300              :       return EEXIST;
   10301              :     case SL_FS_WRONG_FILE_NAME:
   10302              :       return EINVAL;
   10303              :     case SL_FS_ERR_NO_AVAILABLE_NV_INDEX:
   10304              :     case SL_FS_ERR_NO_AVAILABLE_BLOCKS:
   10305              :       return ENOSPC;
   10306              :     case SL_FS_ERR_FAILED_TO_ALLOCATE_MEM:
   10307              :       return ENOMEM;
   10308              :     case SL_FS_ERR_FILE_NOT_EXISTS:
   10309              :       return ENOENT;
   10310              :     case SL_FS_ERR_NOT_SUPPORTED:
   10311              :       return ENOTSUP;
   10312              :   }
   10313              :   return ENXIO;
   10314              : }
   10315              : 
   10316              : int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
   10317              :   int fd;
   10318              :   for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
   10319              :     if (s_sl_fds[fd].fh <= 0) break;
   10320              :   }
   10321              :   if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
   10322              :   struct sl_fd_info *fi = &s_sl_fds[fd];
   10323              : 
   10324              :   _u32 am = 0;
   10325              :   fi->size = (size_t) -1;
   10326              :   if (pathname[0] == '/') pathname++;
   10327              :   int rw = (flags & 3);
   10328              :   if (rw == O_RDONLY) {
   10329              :     SlFsFileInfo_t sl_fi;
   10330              :     _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
   10331              :     if (r == SL_FS_OK) {
   10332              :       fi->size = sl_fi.FileLen;
   10333              :     }
   10334              :     am = FS_MODE_OPEN_READ;
   10335              :   } else {
   10336              :     if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
   10337              :       // FailFS files cannot be opened for append and will be truncated
   10338              :       // when opened for write.
   10339              :       return set_errno(ENOTSUP);
   10340              :     }
   10341              :     if (flags & O_CREAT) {
   10342              :       am = FS_MODE_OPEN_CREATE(FS_SLFS_MAX_FILE_SIZE, 0);
   10343              :     } else {
   10344              :       am = FS_MODE_OPEN_WRITE;
   10345              :     }
   10346              :   }
   10347              :   _i32 r = sl_FsOpen((_u8 *) pathname, am, NULL, &fi->fh);
   10348              :   DBG(("sl_FsOpen(%s, 0x%x) = %d, %d", pathname, (int) am, (int) r,
   10349              :        (int) fi->fh));
   10350              :   if (r == SL_FS_OK) {
   10351              :     fi->pos = 0;
   10352              :     r = fd;
   10353              :   } else {
   10354              :     fi->fh = -1;
   10355              :     r = set_errno(sl_fs_to_errno(r));
   10356              :   }
   10357              :   return r;
   10358              : }
   10359              : 
   10360              : int fs_slfs_close(int fd) {
   10361              :   struct sl_fd_info *fi = &s_sl_fds[fd];
   10362              :   if (fi->fh <= 0) return set_errno(EBADF);
   10363              :   _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
   10364              :   DBG(("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
   10365              :   s_sl_fds[fd].fh = -1;
   10366              :   return set_errno(sl_fs_to_errno(r));
   10367              : }
   10368              : 
   10369              : ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
   10370              :   struct sl_fd_info *fi = &s_sl_fds[fd];
   10371              :   if (fi->fh <= 0) return set_errno(EBADF);
   10372              :   /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
   10373              :    */
   10374              :   if (fi->pos == fi->size) return 0;
   10375              :   _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
   10376              :   DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
   10377              :        (int) r));
   10378              :   if (r >= 0) {
   10379              :     fi->pos += r;
   10380              :     return r;
   10381              :   }
   10382              :   return set_errno(sl_fs_to_errno(r));
   10383              : }
   10384              : 
   10385              : ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
   10386              :   struct sl_fd_info *fi = &s_sl_fds[fd];
   10387              :   if (fi->fh <= 0) return set_errno(EBADF);
   10388              :   _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
   10389              :   DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
   10390              :        (int) r));
   10391              :   if (r >= 0) {
   10392              :     fi->pos += r;
   10393              :     return r;
   10394              :   }
   10395              :   return set_errno(sl_fs_to_errno(r));
   10396              : }
   10397              : 
   10398              : int fs_slfs_stat(const char *pathname, struct stat *s) {
   10399              :   SlFsFileInfo_t sl_fi;
   10400              :   _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
   10401              :   if (r == SL_FS_OK) {
   10402              :     s->st_mode = S_IFREG | 0666;
   10403              :     s->st_nlink = 1;
   10404              :     s->st_size = sl_fi.FileLen;
   10405              :     return 0;
   10406              :   }
   10407              :   return set_errno(sl_fs_to_errno(r));
   10408              : }
   10409              : 
   10410              : int fs_slfs_fstat(int fd, struct stat *s) {
   10411              :   struct sl_fd_info *fi = &s_sl_fds[fd];
   10412              :   if (fi->fh <= 0) return set_errno(EBADF);
   10413              :   s->st_mode = 0666;
   10414              :   s->st_mode = S_IFREG | 0666;
   10415              :   s->st_nlink = 1;
   10416              :   s->st_size = fi->size;
   10417              :   return 0;
   10418              : }
   10419              : 
   10420              : off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
   10421              :   if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
   10422              :   switch (whence) {
   10423              :     case SEEK_SET:
   10424              :       s_sl_fds[fd].pos = offset;
   10425              :       break;
   10426              :     case SEEK_CUR:
   10427              :       s_sl_fds[fd].pos += offset;
   10428              :       break;
   10429              :     case SEEK_END:
   10430              :       return set_errno(ENOTSUP);
   10431              :   }
   10432              :   return 0;
   10433              : }
   10434              : 
   10435              : int fs_slfs_unlink(const char *filename) {
   10436              :   return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) filename, 0)));
   10437              : }
   10438              : 
   10439              : int fs_slfs_rename(const char *from, const char *to) {
   10440              :   return set_errno(ENOTSUP);
   10441              : }
   10442              : 
   10443              : #endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
   10444              : #ifdef MG_MODULE_LINES
   10445              : #line 1 "./src/../../common/platforms/simplelink/sl_fs.c"
   10446              : #endif
   10447              : /*
   10448              :  * Copyright (c) 2014-2016 Cesanta Software Limited
   10449              :  * All rights reserved
   10450              :  */
   10451              : 
   10452              : #if defined(MG_SOCKET_SIMPLELINK) && \
   10453              :     (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
   10454              : 
   10455              : #include <errno.h>
   10456              : #include <stdio.h>
   10457              : #include <stdlib.h>
   10458              : #include <string.h>
   10459              : #ifdef __TI_COMPILER_VERSION__
   10460              : #include <file.h>
   10461              : #endif
   10462              : 
   10463              : #if CS_PLATFORM == CS_P_CC3200
   10464              : #include <inc/hw_types.h>
   10465              : #include <inc/hw_memmap.h>
   10466              : #include <driverlib/rom.h>
   10467              : #include <driverlib/rom_map.h>
   10468              : #include <driverlib/uart.h>
   10469              : #endif
   10470              : 
   10471              : /* Amalgamated: #include "common/cs_dbg.h" */
   10472              : /* Amalgamated: #include "common/platform.h" */
   10473              : 
   10474              : #ifdef CC3200_FS_SPIFFS
   10475              : /* Amalgamated: #include "cc3200_fs_spiffs.h" */
   10476              : #endif
   10477              : 
   10478              : #ifdef MG_FS_SLFS
   10479              : /* Amalgamated: #include "sl_fs_slfs.h" */
   10480              : #endif
   10481              : 
   10482              : #define NUM_SYS_FDS 3
   10483              : #define SPIFFS_FD_BASE 10
   10484              : #define SLFS_FD_BASE 100
   10485              : 
   10486              : #define CONSOLE_UART UARTA0_BASE
   10487              : 
   10488              : int set_errno(int e) {
   10489              :   errno = e;
   10490              :   return -e;
   10491              : }
   10492              : 
   10493              : static int is_sl_fname(const char *fname) {
   10494              :   return strncmp(fname, "SL:", 3) == 0;
   10495              : }
   10496              : 
   10497              : static const char *sl_fname(const char *fname) {
   10498              :   return fname + 3;
   10499              : }
   10500              : 
   10501              : static const char *drop_dir(const char *fname) {
   10502              :   if (*fname == '.') fname++;
   10503              :   if (*fname == '/') fname++;
   10504              :   return fname;
   10505              : }
   10506              : 
   10507              : enum fd_type {
   10508              :   FD_INVALID,
   10509              :   FD_SYS,
   10510              : #ifdef CC3200_FS_SPIFFS
   10511              :   FD_SPIFFS,
   10512              : #endif
   10513              : #ifdef MG_FS_SLFS
   10514              :   FD_SLFS
   10515              : #endif
   10516              : };
   10517              : static int fd_type(int fd) {
   10518              :   if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
   10519              : #ifdef CC3200_FS_SPIFFS
   10520              :   if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
   10521              :     return FD_SPIFFS;
   10522              :   }
   10523              : #endif
   10524              : #ifdef MG_FS_SLFS
   10525              :   if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
   10526              :     return FD_SLFS;
   10527              :   }
   10528              : #endif
   10529              :   return FD_INVALID;
   10530              : }
   10531              : 
   10532              : int _open(const char *pathname, int flags, mode_t mode) {
   10533              :   int fd = -1;
   10534              :   pathname = drop_dir(pathname);
   10535              :   if (is_sl_fname(pathname)) {
   10536              : #ifdef MG_FS_SLFS
   10537              :     fd = fs_slfs_open(sl_fname(pathname), flags, mode);
   10538              :     if (fd >= 0) fd += SLFS_FD_BASE;
   10539              : #endif
   10540              :   } else {
   10541              : #ifdef CC3200_FS_SPIFFS
   10542              :     fd = fs_spiffs_open(pathname, flags, mode);
   10543              :     if (fd >= 0) fd += SPIFFS_FD_BASE;
   10544              : #endif
   10545              :   }
   10546              :   DBG(("open(%s, 0x%x) = %d", pathname, flags, fd));
   10547              :   return fd;
   10548              : }
   10549              : 
   10550              : int _stat(const char *pathname, struct stat *st) {
   10551              :   int res = -1;
   10552              :   const char *fname = pathname;
   10553              :   int is_sl = is_sl_fname(pathname);
   10554              :   if (is_sl) fname = sl_fname(pathname);
   10555              :   fname = drop_dir(fname);
   10556              :   memset(st, 0, sizeof(*st));
   10557              :   /* Simulate statting the root directory. */
   10558              :   if (strcmp(fname, "") == 0) {
   10559              :     st->st_ino = 0;
   10560              :     st->st_mode = S_IFDIR | 0777;
   10561              :     st->st_nlink = 1;
   10562              :     st->st_size = 0;
   10563              :     return 0;
   10564              :   }
   10565              :   if (is_sl) {
   10566              : #ifdef MG_FS_SLFS
   10567              :     res = fs_slfs_stat(fname, st);
   10568              : #endif
   10569              :   } else {
   10570              : #ifdef CC3200_FS_SPIFFS
   10571              :     res = fs_spiffs_stat(fname, st);
   10572              : #endif
   10573              :   }
   10574              :   DBG(("stat(%s) = %d; fname = %s", pathname, res, fname));
   10575              :   return res;
   10576              : }
   10577              : 
   10578              : int _close(int fd) {
   10579              :   int r = -1;
   10580              :   switch (fd_type(fd)) {
   10581              :     case FD_INVALID:
   10582              :       r = set_errno(EBADF);
   10583              :       break;
   10584              :     case FD_SYS:
   10585              :       r = set_errno(EACCES);
   10586              :       break;
   10587              : #ifdef CC3200_FS_SPIFFS
   10588              :     case FD_SPIFFS:
   10589              :       r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
   10590              :       break;
   10591              : #endif
   10592              : #ifdef MG_FS_SLFS
   10593              :     case FD_SLFS:
   10594              :       r = fs_slfs_close(fd - SLFS_FD_BASE);
   10595              :       break;
   10596              : #endif
   10597              :   }
   10598              :   DBG(("close(%d) = %d", fd, r));
   10599              :   return r;
   10600              : }
   10601              : 
   10602              : off_t _lseek(int fd, off_t offset, int whence) {
   10603              :   int r = -1;
   10604              :   switch (fd_type(fd)) {
   10605              :     case FD_INVALID:
   10606              :       r = set_errno(EBADF);
   10607              :       break;
   10608              :     case FD_SYS:
   10609              :       r = set_errno(ESPIPE);
   10610              :       break;
   10611              : #ifdef CC3200_FS_SPIFFS
   10612              :     case FD_SPIFFS:
   10613              :       r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
   10614              :       break;
   10615              : #endif
   10616              : #ifdef MG_FS_SLFS
   10617              :     case FD_SLFS:
   10618              :       r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
   10619              :       break;
   10620              : #endif
   10621              :   }
   10622              :   DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
   10623              :   return r;
   10624              : }
   10625              : 
   10626              : int _fstat(int fd, struct stat *s) {
   10627              :   int r = -1;
   10628              :   memset(s, 0, sizeof(*s));
   10629              :   switch (fd_type(fd)) {
   10630              :     case FD_INVALID:
   10631              :       r = set_errno(EBADF);
   10632              :       break;
   10633              :     case FD_SYS: {
   10634              :       /* Create barely passable stats for STD{IN,OUT,ERR}. */
   10635              :       memset(s, 0, sizeof(*s));
   10636              :       s->st_ino = fd;
   10637              :       s->st_mode = S_IFCHR | 0666;
   10638              :       r = 0;
   10639              :       break;
   10640              :     }
   10641              : #ifdef CC3200_FS_SPIFFS
   10642              :     case FD_SPIFFS:
   10643              :       r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
   10644              :       break;
   10645              : #endif
   10646              : #ifdef MG_FS_SLFS
   10647              :     case FD_SLFS:
   10648              :       r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
   10649              :       break;
   10650              : #endif
   10651              :   }
   10652              :   DBG(("fstat(%d) = %d", fd, r));
   10653              :   return r;
   10654              : }
   10655              : 
   10656              : ssize_t _read(int fd, void *buf, size_t count) {
   10657              :   int r = -1;
   10658              :   switch (fd_type(fd)) {
   10659              :     case FD_INVALID:
   10660              :       r = set_errno(EBADF);
   10661              :       break;
   10662              :     case FD_SYS: {
   10663              :       if (fd != 0) {
   10664              :         r = set_errno(EACCES);
   10665              :         break;
   10666              :       }
   10667              :       /* Should we allow reading from stdin = uart? */
   10668              :       r = set_errno(ENOTSUP);
   10669              :       break;
   10670              :     }
   10671              : #ifdef CC3200_FS_SPIFFS
   10672              :     case FD_SPIFFS:
   10673              :       r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
   10674              :       break;
   10675              : #endif
   10676              : #ifdef MG_FS_SLFS
   10677              :     case FD_SLFS:
   10678              :       r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
   10679              :       break;
   10680              : #endif
   10681              :   }
   10682              :   DBG(("read(%d, %u) = %d", fd, count, r));
   10683              :   return r;
   10684              : }
   10685              : 
   10686              : ssize_t _write(int fd, const void *buf, size_t count) {
   10687              :   int r = -1;
   10688              :   size_t i = 0;
   10689              :   switch (fd_type(fd)) {
   10690              :     case FD_INVALID:
   10691              :       r = set_errno(EBADF);
   10692              :       break;
   10693              :     case FD_SYS: {
   10694              :       if (fd == 0) {
   10695              :         r = set_errno(EACCES);
   10696              :         break;
   10697              :       }
   10698              : #if CS_PLATFORM == CS_P_CC3200
   10699              :       for (i = 0; i < count; i++) {
   10700              :         const char c = ((const char *) buf)[i];
   10701              :         if (c == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
   10702              :         MAP_UARTCharPut(CONSOLE_UART, c);
   10703              :       }
   10704              : #else
   10705              :       (void) i;
   10706              : #endif
   10707              :       r = count;
   10708              :       break;
   10709              :     }
   10710              : #ifdef CC3200_FS_SPIFFS
   10711              :     case FD_SPIFFS:
   10712              :       r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
   10713              :       break;
   10714              : #endif
   10715              : #ifdef MG_FS_SLFS
   10716              :     case FD_SLFS:
   10717              :       r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
   10718              :       break;
   10719              : #endif
   10720              :   }
   10721              :   return r;
   10722              : }
   10723              : 
   10724              : int _rename(const char *from, const char *to) {
   10725              :   int r = -1;
   10726              :   from = drop_dir(from);
   10727              :   to = drop_dir(to);
   10728              :   if (is_sl_fname(from) || is_sl_fname(to)) {
   10729              : #ifdef MG_FS_SLFS
   10730              :     r = fs_slfs_rename(sl_fname(from), sl_fname(to));
   10731              : #endif
   10732              :   } else {
   10733              : #ifdef CC3200_FS_SPIFFS
   10734              :     r = fs_spiffs_rename(from, to);
   10735              : #endif
   10736              :   }
   10737              :   DBG(("rename(%s, %s) = %d", from, to, r));
   10738              :   return r;
   10739              : }
   10740              : 
   10741              : int _link(const char *from, const char *to) {
   10742              :   DBG(("link(%s, %s)", from, to));
   10743              :   return set_errno(ENOTSUP);
   10744              : }
   10745              : 
   10746              : int _unlink(const char *filename) {
   10747              :   int r = -1;
   10748              :   filename = drop_dir(filename);
   10749              :   if (is_sl_fname(filename)) {
   10750              : #ifdef MG_FS_SLFS
   10751              :     r = fs_slfs_unlink(sl_fname(filename));
   10752              : #endif
   10753              :   } else {
   10754              : #ifdef CC3200_FS_SPIFFS
   10755              :     r = fs_spiffs_unlink(filename);
   10756              : #endif
   10757              :   }
   10758              :   DBG(("unlink(%s) = %d", filename, r));
   10759              :   return r;
   10760              : }
   10761              : 
   10762              : #ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
   10763              : DIR *opendir(const char *dir_name) {
   10764              :   DIR *r = NULL;
   10765              :   if (is_sl_fname(dir_name)) {
   10766              :     r = NULL;
   10767              :     set_errno(ENOTSUP);
   10768              :   } else {
   10769              :     r = fs_spiffs_opendir(dir_name);
   10770              :   }
   10771              :   DBG(("opendir(%s) = %p", dir_name, r));
   10772              :   return r;
   10773              : }
   10774              : 
   10775              : struct dirent *readdir(DIR *dir) {
   10776              :   struct dirent *res = fs_spiffs_readdir(dir);
   10777              :   DBG(("readdir(%p) = %p", dir, res));
   10778              :   return res;
   10779              : }
   10780              : 
   10781              : int closedir(DIR *dir) {
   10782              :   int res = fs_spiffs_closedir(dir);
   10783              :   DBG(("closedir(%p) = %d", dir, res));
   10784              :   return res;
   10785              : }
   10786              : 
   10787              : int rmdir(const char *path) {
   10788              :   return fs_spiffs_rmdir(path);
   10789              : }
   10790              : 
   10791              : int mkdir(const char *path, mode_t mode) {
   10792              :   (void) path;
   10793              :   (void) mode;
   10794              :   /* for spiffs supports only root dir, which comes from mongoose as '.' */
   10795              :   return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
   10796              : }
   10797              : #endif
   10798              : 
   10799              : int sl_fs_init() {
   10800              :   int ret = 1;
   10801              : #ifdef __TI_COMPILER_VERSION__
   10802              : #ifdef MG_FS_SLFS
   10803              :   ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
   10804              :                     fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
   10805              :                     fs_slfs_rename) == 0);
   10806              : #endif
   10807              : #endif
   10808              :   return ret;
   10809              : }
   10810              : 
   10811              : #endif /* defined(MG_SOCKET_SIMPLELINK) && (defined(MG_FS_SLFS) || \
   10812              :           defined(MG_FS_SPIFFS)) */
   10813              : #ifdef MG_MODULE_LINES
   10814              : #line 1 "./src/../../common/platforms/simplelink/sl_socket.c"
   10815              : #endif
   10816              : /*
   10817              :  * Copyright (c) 2014-2016 Cesanta Software Limited
   10818              :  * All rights reserved
   10819              :  */
   10820              : 
   10821              : #ifdef MG_SOCKET_SIMPLELINK
   10822              : 
   10823              : #include <errno.h>
   10824              : #include <stdio.h>
   10825              : 
   10826              : /* Amalgamated: #include "common/platform.h" */
   10827              : 
   10828              : #include <simplelink/include/netapp.h>
   10829              : 
   10830              : const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
   10831              :   int res;
   10832              :   struct in_addr *in = (struct in_addr *) src;
   10833              :   if (af != AF_INET) {
   10834              :     errno = EAFNOSUPPORT;
   10835              :     return NULL;
   10836              :   }
   10837              :   res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
   10838              :                  SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
   10839              :                  SL_IPV4_BYTE(in->s_addr, 3));
   10840              :   return res > 0 ? dst : NULL;
   10841              : }
   10842              : 
   10843              : char *inet_ntoa(struct in_addr n) {
   10844              :   static char a[16];
   10845              :   return (char *) inet_ntop(AF_INET, &n, a, sizeof(n));
   10846              : }
   10847              : 
   10848              : int inet_pton(int af, const char *src, void *dst) {
   10849              :   uint32_t a0, a1, a2, a3;
   10850              :   uint8_t *db = (uint8_t *) dst;
   10851              :   if (af != AF_INET) {
   10852              :     errno = EAFNOSUPPORT;
   10853              :     return 0;
   10854              :   }
   10855              :   if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
   10856              :     return 0;
   10857              :   }
   10858              :   *db = a3;
   10859              :   *(db + 1) = a2;
   10860              :   *(db + 2) = a1;
   10861              :   *(db + 3) = a0;
   10862              :   return 1;
   10863              : }
   10864              : 
   10865              : #endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_SOCKET_C_ */
   10866              : #ifdef MG_MODULE_LINES
   10867              : #line 1 "./src/../../common/platforms/simplelink/sl_mg_task.c"
   10868              : #endif
   10869              : #if defined(MG_SOCKET_SIMPLELINK)
   10870              : 
   10871              : /* Amalgamated: #include "mg_task.h" */
   10872              : 
   10873              : #include <oslib/osi.h>
   10874              : 
   10875              : enum mg_q_msg_type {
   10876              :   MG_Q_MSG_CB,
   10877              : };
   10878              : struct mg_q_msg {
   10879              :   enum mg_q_msg_type type;
   10880              :   void (*cb)(struct mg_mgr *mgr, void *arg);
   10881              :   void *arg;
   10882              : };
   10883              : static OsiMsgQ_t s_mg_q;
   10884              : static void mg_task(void *arg);
   10885              : 
   10886              : bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
   10887              :   if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
   10888              :     return false;
   10889              :   }
   10890              :   if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
   10891              :                      (void *) mg_init, priority, NULL) != OSI_OK) {
   10892              :     return false;
   10893              :   }
   10894              :   return true;
   10895              : }
   10896              : 
   10897              : static void mg_task(void *arg) {
   10898              :   struct mg_mgr mgr;
   10899              :   mg_init_cb mg_init = (mg_init_cb) arg;
   10900              :   mg_mgr_init(&mgr, NULL);
   10901              :   mg_init(&mgr);
   10902              :   while (1) {
   10903              :     struct mg_q_msg msg;
   10904              :     mg_mgr_poll(&mgr, 1);
   10905              :     if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
   10906              :     switch (msg.type) {
   10907              :       case MG_Q_MSG_CB: {
   10908              :         msg.cb(&mgr, msg.arg);
   10909              :       }
   10910              :     }
   10911              :   }
   10912              : }
   10913              : 
   10914              : void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
   10915              :   struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
   10916              :   osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
   10917              : }
   10918              : 
   10919              : #endif /* defined(MG_SOCKET_SIMPLELINK) */
        

Generated by: LCOV version 2.0-1