diff --git a/.drone.yml b/.drone.yml
index 6e3a605..4b72953 100644
--- a/.drone.yml
+++ b/.drone.yml
@@ -20,9 +20,7 @@ steps:
     api_key:
       from_secret: gitea_token
     base_url: https://git.serguzim.me
-    files:
-    - build/controller
-    - build/controller.ini
+    title: ${DRONE_TAG}
   when:
     event: tag
 
diff --git a/CMakeLists.txt b/CMakeLists.txt
deleted file mode 100644
index 3223e1c..0000000
--- a/CMakeLists.txt
+++ /dev/null
@@ -1,67 +0,0 @@
-cmake_minimum_required (VERSION 3.7)
-project(controller
-        VERSION 0.3.7
-        LANGUAGES C)
-
-add_executable(controller src/main.c)
-
-target_link_libraries(controller -lwiringPi)
-target_link_libraries(controller -lwiringPiDev)
-target_link_libraries(controller -lsqlite3)
-target_link_libraries(controller -luuid)
-
-option(WIRING_PI_DEBUG "Use WiringPi Debugging Tool (OFF)" OFF)
-
-set(CMAKE_C_FLAGS "$ENV{CFLAGS}")
-SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3 -std=gnu99 -Wpedantic -Werror -Wall -Wextra -ffile-prefix-map=${CMAKE_SOURCE_DIR}/src/=")
-
-set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -g -fprofile-arcs -ftest-coverage")
-
-if(WIRING_PI_DEBUG)
-    message("Showing wiringPi calls as debug")
-    add_definitions("-DWIRING_PI_DEBUG")
-endif(WIRING_PI_DEBUG)
-
-aux_source_directory(src/ SRC_DIR)
-aux_source_directory(src/models MODELS_SRC)
-aux_source_directory(src/helpers HELPERS_SRC)
-aux_source_directory(src/handlers HANDLERS_SRC)
-aux_source_directory(src/drivers DRIVERS_SRC)
-aux_source_directory(src/runners RUNNERS_SRC)
-aux_source_directory(vendor VENDOR_SRC)
-
-add_dependencies(controller sql)
-
-configure_file("controller.ini" "controller.ini" COPYONLY)
-configure_file("version.h.in" "version.h" @ONLY)
-
-
-target_sources(controller PRIVATE ${SRC_DIR} ${MODELS_SRC} ${HELPERS_SRC} ${HANDLERS_SRC} ${DRIVERS_SRC} ${RUNNERS_SRC} ${VENDOR_SRC})
-target_include_directories(controller PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include)
-target_include_directories(controller PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/vendor)
-target_include_directories(controller PRIVATE ${CMAKE_BINARY_DIR})
-
-add_custom_target(sql
-    COMMAND ./compile_sql.sh
-    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
-)
-
-add_custom_target(run
-    COMMAND ./controller start
-    DEPENDS controller
-    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
-)
-add_custom_target(debug
-    COMMAND valgrind ./controller start
-    DEPENDS controller
-    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
-)
-add_custom_target(debug-full
-    COMMAND valgrind --leak-check=full --show-leak-kinds=all ./controller start
-    DEPENDS controller
-    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
-)
-add_custom_target(docs
-    COMMAND doxygen
-    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
-)
diff --git a/controller.ini b/controller.ini
deleted file mode 100644
index dfec8e3..0000000
--- a/controller.ini
+++ /dev/null
@@ -1,69 +0,0 @@
-[controller]
-name = new emgauwa device
-
-: 4422 for testing; 4421 for dev-env; 4420 for testing-env; 4419 for prod-env
-discovery-port = 4421
-: 1886 for testing; 1885 for dev-env; 1884 for testing-env; 1883 for prod-env
-mqtt-port = 1885
-mqtt-host = localhost
-
-relay-count = 10
-relays-init = 1
-
-database = controller.sqlite
-log-level = debug
-log-file = stdout
-
-[relay-0]
-driver = piface
-pin = 0
-inverted = 0
-init = 0
-
-[relay-1]
-driver = piface
-pin = 1
-inverted = 0
-init = 1
-
-[relay-2]
-driver = gpio
-pin = 5
-inverted = 1
-
-[relay-3]
-driver = gpio
-pin = 4
-inverted = 1
-
-[relay-4]
-driver = gpio
-pin = 3
-inverted = 1
-
-[relay-5]
-driver = gpio
-pin = 2
-inverted = 1
-
-[relay-6]
-driver = gpio
-pin = 1
-inverted = 1
-pulse-duration = 3
-
-[relay-7]
-driver = gpio
-pin = 0
-inverted = 1
-pulse-duration = 3
-
-[relay-8]
-driver = gpio
-pin = 16
-inverted = 1
-
-[relay-9]
-driver = gpio
-pin = 15
-inverted = 1
diff --git a/emgauwa-controller.conf b/emgauwa-controller.conf
new file mode 100644
index 0000000..dcf6f9b
--- /dev/null
+++ b/emgauwa-controller.conf
@@ -0,0 +1,66 @@
+[controller]
+database = "emgauwa-controller.sqlite"
+
+mqtt-host = "127.0.0.1"
+
+[ports]
+# 4422 for testing; 4421 for dev-env; 4420 for testing-env; 4419 for prod-env
+discovery = 4421
+# 1886 for testing; 1885 for dev-env; 1884 for testing-env; 1883 for prod-env
+mqtt = 1885
+
+[logging]
+level = "debug"
+file = "stdout"
+
+[[relays]]
+driver = "piface"
+pin = 0
+inverted = 0
+
+[[relays]]
+driver = "piface"
+pin = 1
+inverted = 0
+
+[[relays]]
+driver = "gpio"
+pin = 5
+inverted = 1
+
+[[relays]]
+driver = "gpio"
+pin = 4
+inverted = 1
+
+[[relays]]
+driver = "gpio"
+pin = 3
+inverted = 1
+
+[[relays]]
+driver = "gpio"
+pin = 2
+inverted = 1
+
+[[relays]]
+driver = "gpio"
+pin = 1
+inverted = 1
+pulse-duration = 3
+
+[[relays]]
+driver = "gpio"
+pin = 0
+inverted = 1
+pulse-duration = 3
+
+[[relays]]
+driver = "gpio"
+pin = 16
+inverted = 1
+
+[[relays]]
+driver = "gpio"
+pin = 15
+inverted = 1
diff --git a/emgauwa-controller.sqlite b/emgauwa-controller.sqlite
new file mode 100644
index 0000000..2adcfc3
Binary files /dev/null and b/emgauwa-controller.sqlite differ
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..b745413
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,3 @@
+module emgauwa.app/controller
+
+go 1.15
diff --git a/include/colors.h b/include/colors.h
deleted file mode 100644
index 2d32aee..0000000
--- a/include/colors.h
+++ /dev/null
@@ -1,18 +0,0 @@
-#ifndef CONTROLLER_COLORS_H
-#define CONTROLLER_COLORS_H
-
-#define COLOR_RED "\033[0;31m"
-#define COLORB_RED "\033[1;31m"
-#define COLOR_GREEN "\033[0;32m"
-#define COLORB_GREEN "\033[1;32m"
-#define COLOR_YELLOW "\033[0;33m"
-#define COLORB_YELLOW "\033[1;33m"
-#define COLOR_BLUE "\033[0;34m"
-#define COLORB_BLUE "\033[1;34m"
-#define COLOR_MAGENTA "\033[0;35m"
-#define COLORB_MAGENTA "\033[1;35m"
-#define COLOR_CYAN "\033[0;36m"
-#define COLORB_CYAN "\033[1;36m"
-#define COLOR_NONE "\033[0m"
-
-#endif //CONTROLLER_COLORS_H
diff --git a/include/config.h b/include/config.h
deleted file mode 100644
index fe5b66a..0000000
--- a/include/config.h
+++ /dev/null
@@ -1,42 +0,0 @@
-#ifndef CONTROLLER_CONFIG_H
-#define CONTROLLER_CONFIG_H
-
-#include <stdint.h>
-#include <confini.h>
-
-#include <constants.h>
-#include <enums.h>
-
-typedef struct
-{
-    uint8_t pin;
-    int inverted;
-    int init;
-    relay_driver_t driver;
-    uint8_t pulse_duration;
-} config_relay_t;
-
-int
-config_load(IniDispatch *disp, void *config_void);
-
-typedef struct
-{
-    char *file;
-    char database[256];
-    char user[256];
-    char group[256];
-    int log_level;
-    FILE *log_file;
-    run_type_t run_type;
-    char name[MAX_NAME_LENGTH + 1];
-    uint16_t discovery_port;
-    uint16_t mqtt_port;
-    char mqtt_host[256];
-    uint8_t relay_count;
-    int relays_init;
-    config_relay_t *relay_configs;
-} config_t;
-
-extern config_t global_config;
-
-#endif //CONTROLLER_CONFIG_H
diff --git a/include/connections.h b/include/connections.h
deleted file mode 100644
index fdb268e..0000000
--- a/include/connections.h
+++ /dev/null
@@ -1,17 +0,0 @@
-#ifndef CONTROLLER_CONNECTIONS_H
-#define CONTROLLER_CONNECTIONS_H
-
-#include <mongoose.h>
-
-struct mg_connection*
-connection_discovery_bind(struct mg_mgr *mgr);
-
-struct mg_connection*
-connection_command_bind(struct mg_mgr *mgr);
-
-struct mg_connection*
-connection_mqtt_connect(struct mg_mgr *mgr);
-
-extern struct mg_connection *global_connection_mqtt;
-
-#endif /* CONTROLLER_CONNECTIONS_H */
diff --git a/include/constants.h b/include/constants.h
deleted file mode 100644
index 0d27ab7..0000000
--- a/include/constants.h
+++ /dev/null
@@ -1,31 +0,0 @@
-#ifndef CONTROLLER_CONTANTS_H
-#define CONTROLLER_CONTANTS_H
-
-#define SECONDS_PER_DAY 86400 // 60 * 60 * 24
-
-#define SECONDS_PER_MINUTE 60
-
-#define POLL_FDS_COUNT 2
-
-/**
- * @brief Limit the maximum length of a controller/relay/etc name
- *
- * The NULL terminator is not included. Arrays of length #MAX_NAME_LENGTH + 1 are required.
- */
-#define MAX_NAME_LENGTH 128
-
-/**
- * @brief Maximum number of dbs for the databases for the MDB_env
- *
- * Used when calling mdb_env_set_maxdbs() in database_setup()
- */
-#define MDB_MAXDBS 8
-
-/**
- * @brief How many milli seconds to wait until poll timeout in main loop
- */
-#define ACCEPT_TIMEOUT_MSECONDS 1000
-
-#define PIFACE_GPIO_BASE 200
-
-#endif /* CONTROLLER_CONTANTS_H */
diff --git a/include/database.h b/include/database.h
deleted file mode 100644
index 6408d9c..0000000
--- a/include/database.h
+++ /dev/null
@@ -1,40 +0,0 @@
-#ifndef CONTROLLER_DATABASE_H
-#define CONTROLLER_DATABASE_H
-
-#include <sqlite3.h>
-
-extern sqlite3 *global_database;
-
-void
-database_init();
-
-void
-database_free();
-
-void
-database_migrate();
-
-
-int
-database_transaction_begin();
-
-void
-database_transaction_commit();
-
-void
-database_transaction_rollback();
-
-
-int
-database_helper_get_id(sqlite3_stmt *stmt);
-
-int*
-database_helper_get_ids(sqlite3_stmt *stmt);
-
-char*
-database_helper_get_string(sqlite3_stmt *stmt);
-
-char**
-database_helper_get_strings(sqlite3_stmt *stmt);
-
-#endif /* CONTROLLER_DATABASE_H */
diff --git a/include/drivers.h b/include/drivers.h
deleted file mode 100644
index 2abf97d..0000000
--- a/include/drivers.h
+++ /dev/null
@@ -1,13 +0,0 @@
-#ifndef CONTROLLER_DRIVERS_H
-#define CONTROLLER_DRIVERS_H
-
-#include <models/relay.h>
-#include <enums.h>
-
-void
-driver_piface_set(int pin, int value);
-
-void
-driver_gpio_set(int pin, int value);
-
-#endif /* CONTROLLER_DRIVERS_H */
diff --git a/include/enums.h b/include/enums.h
deleted file mode 100644
index 032622a..0000000
--- a/include/enums.h
+++ /dev/null
@@ -1,31 +0,0 @@
-#ifndef CONTROLLER_ENUMS_H
-#define CONTROLLER_ENUMS_H
-
-typedef enum
-{
-    POLL_FDS_DISCOVERY,
-    POLL_FDS_COMMAND
-} poll_fds_t;
-
-typedef enum
-{
-    DISCOVERY_MAPPING_ID = 0,
-    DISCOVERY_MAPPING_NAME = 1,
-    DISCOVERY_MAPPING_COMMAND_PORT = 2,
-    DISCOVERY_MAPPING_RELAY_COUNT = 3,
-} discovery_mapping_t;
-
-typedef enum
-{
-    RELAY_DRIVER_NONE,
-    RELAY_DRIVER_GPIO,
-    RELAY_DRIVER_PIFACE,
-} relay_driver_t;
-
-typedef enum
-{
-    RUN_TYPE_START,
-    RUN_TYPE_TEST,
-} run_type_t;
-
-#endif /* CONTROLLER_ENUMS_H */
diff --git a/include/handlers.h b/include/handlers.h
deleted file mode 100644
index 4b5a374..0000000
--- a/include/handlers.h
+++ /dev/null
@@ -1,32 +0,0 @@
-#ifndef CONTROLLER_HANDLERS_H
-#define CONTROLLER_HANDLERS_H
-
-#include <mongoose.h>
-
-#include <models/controller.h>
-
-/**
- * @brief Handle the command processing
- *
- * @param fd File descriptor to receive initial data from
- * @param controller Controller to use for answering command
- */
-void
-handler_command(struct mg_connection *c, int ev, void *ev_data);
-
-/**
- * @brief Handle the discovery processing
- *
- * @param fd File descriptor to receive initial data from
- * @param controller Controller to use for answering discovery
- */
-void
-handler_discovery(struct mg_connection *c, int ev, void *ev_data);
-
-void
-handler_mqtt(struct mg_connection *c, int ev, void *ev_data);
-
-void
-handler_loop(struct mg_connection *c_mqtt);
-
-#endif /* CONTROLLER_HANDLERS_H */
diff --git a/include/helpers.h b/include/helpers.h
deleted file mode 100644
index d1d3a38..0000000
--- a/include/helpers.h
+++ /dev/null
@@ -1,37 +0,0 @@
-#ifndef CONTROLLER_HELPERS_H
-#define CONTROLLER_HELPERS_H
-
-#include <time.h>
-#include <config.h>
-
-int
-helper_connect_tcp_server(char* host, uint16_t port);
-
-int
-helper_bind_tcp_server(char* addr, uint16_t port, int max_client_backlog);
-
-uint16_t
-helper_get_port(int sock);
-
-/**
- * @brief Open socket for discovery
- *
- * Will exit program when unable to open socket.
- *
- * @param discovery_port Port number to listen on for discovery broadcasts
- *
- * @return Open socket to accept discovery broadcasts on
- */
-int
-helper_open_discovery_socket(uint16_t discovery_port);
-
-void
-helper_parse_cli(int argc, const char **argv, config_t *config);
-
-int
-helper_get_weekday(const struct tm *time_struct);
-
-int
-helper_drop_privileges();
-
-#endif /* CONTROLLER_HELPERS_H */
diff --git a/include/logger.h b/include/logger.h
deleted file mode 100644
index fc207f5..0000000
--- a/include/logger.h
+++ /dev/null
@@ -1,22 +0,0 @@
-#ifndef EMGAUWA_LOGGER_H
-#define EMGAUWA_LOGGER_H
-
-#include <stdio.h>
-#include <time.h>
-#include <syslog.h>
-
-#include <colors.h>
-#include <config.h>
-
-void
-logger_log(int level, const char *filename, int line, const char *func, const char *msg, ...);
-
-#define LOGGER_DEBUG(...)   logger_log(LOG_DEBUG  , __FILE__, __LINE__, __func__, ##__VA_ARGS__)
-#define LOGGER_INFO(...)    logger_log(LOG_INFO   , __FILE__, __LINE__, __func__, ##__VA_ARGS__)
-#define LOGGER_NOTICE(...)  logger_log(LOG_NOTICE , __FILE__, __LINE__, __func__, ##__VA_ARGS__)
-#define LOGGER_WARNING(...) logger_log(LOG_WARNING, __FILE__, __LINE__, __func__, ##__VA_ARGS__)
-#define LOGGER_ERR(...)     logger_log(LOG_ERR    , __FILE__, __LINE__, __func__, ##__VA_ARGS__)
-#define LOGGER_CRIT(...)    logger_log(LOG_CRIT   , __FILE__, __LINE__, __func__, ##__VA_ARGS__)
-#define LOGGER_EMERG(...)   logger_log(LOG_EMERG  , __FILE__, __LINE__, __func__, ##__VA_ARGS__)
-
-#endif //EMGAUWA_LOGGER_H
diff --git a/include/macros.h b/include/macros.h
deleted file mode 100644
index 63a0b93..0000000
--- a/include/macros.h
+++ /dev/null
@@ -1,6 +0,0 @@
-#ifndef CONTROLLER_MACROS_H
-#define CONTROLLER_MACROS_H
-
-#define STRLEN(s) ((sizeof(s)/sizeof(s[0])) - sizeof(s[0]))
-
-#endif /* CONTROLLER_MACROS_H */
diff --git a/include/models/controller.h b/include/models/controller.h
deleted file mode 100644
index 1cf4fad..0000000
--- a/include/models/controller.h
+++ /dev/null
@@ -1,107 +0,0 @@
-#ifndef CONTROLLER_CONTROLLER_H
-#define CONTROLLER_CONTROLLER_H
-
-#include <uuid/uuid.h>
-#include <stdint.h>
-#include <lmdb.h>
-
-#include <config.h>
-#include <models/relay.h>
-
-/**
- * @brief Information about this controller
- */
-typedef struct
-{
-    int id;
-
-    /**
-     * @brief A unique UUID for this controller
-     */
-    uuid_t uid;
-    /**
-     * @brief The name of this controller
-     *
-     * Includes a \0 terminator.
-     */
-    char name[MAX_NAME_LENGTH + 1];
-    /**
-     * @brief The command port the controller was bound to
-     */
-    uint16_t command_port;
-
-    relay_t **relays;
-
-} controller_t;
-
-/**
- * @brief Key to save controller information in database
- */
-typedef enum
-{
-    DB_KEY_CONTROLLER_ID = 0,
-    DB_KEY_CONTROLLER_NAME = 1,
-    DB_KEY_CONTROLLER_COMMAND_PORT = 2,
-    DB_KEY_CONTROLLER_DISCOVERY_PORT = 3,
-} db_key_controller_e;
-
-/**
- * @brief Create a new instance of controller
- *
- * This should not fail. The instance will be created with malloc and genric default values
- *
- * @return A new instance of #controller
- */
-controller_t*
-controller_create(void);
-
-
-/**
- * @brief Load a controller for database or create a new one
- *
- * Will return NULL when transaction can't start.
- *
- * @param mdb_env An opened MDB_env to load from
- *
- * @return A loaded or new instance of controller or NULL on database error
- */
-controller_t*
-controller_load();
-
-/**
- * @brief Save a controller to the database
- *
- * @param controller Instance of a controller
- * @param mdb_env Already created MDB_env
- *
- * @return Indicator to show success (0) or failure (!0)
- */
-int
-controller_save();
-
-/**
- * @brief Sets a name to a controller.
- * This function won't perform any checks (e.g. no NULL checks)
- *
- * @param controller Set the name to this controller
- * @param name Name to be set
- */
-void
-controller_set_name(controller_t *controller, const char *name);
-
-void
-controller_free(controller_t *controller);
-
-/**
- * @brief Debug an instance of #controller
- *
- * Will use #LOG_DEBUG to log. So log will be depending on #LOG_LEVEL
- *
- * @param cntrlr #controller to debug
- */
-void
-controller_debug(controller_t *controller);
-
-extern controller_t *global_controller;
-
-#endif //CONTROLLER_CONTROLLER_H
diff --git a/include/models/junction_relay_schedule.h b/include/models/junction_relay_schedule.h
deleted file mode 100644
index ebc0755..0000000
--- a/include/models/junction_relay_schedule.h
+++ /dev/null
@@ -1,16 +0,0 @@
-#ifndef CONTROLLER_MODELS_JUNCTION_RELAY_SCHEDULE_H
-#define CONTROLLER_MODELS_JUNCTION_RELAY_SCHEDULE_H
-
-int
-junction_relay_schedule_insert(uint8_t weekday, int relay_id, int schedule_id);
-
-int
-junction_relay_schedule_remove_for_relay(int relay_id);
-
-int
-junction_relay_schedule_insert_weekdays(int relay_id, int *schedule_ids);
-
-int*
-junction_relay_schedule_get_relay_ids_with_schedule(int schedule_id);
-
-#endif /* CONTROLLER_MODELS_JUNCTION_RELAY_SCHEDULE_H */
diff --git a/include/models/period.h b/include/models/period.h
deleted file mode 100644
index b264ce0..0000000
--- a/include/models/period.h
+++ /dev/null
@@ -1,16 +0,0 @@
-#ifndef CONTROLLER_PERIOD_H
-#define CONTROLLER_PERIOD_H
-
-#include <stdint.h>
-#include <time.h>
-
-typedef struct
-{
-    uint16_t start;
-    uint16_t end;
-} period_t;
-
-int
-period_includes_time(period_t period, struct tm *time_struct);
-
-#endif /* CONTROLLER_PERIOD_H */
diff --git a/include/models/relay.h b/include/models/relay.h
deleted file mode 100644
index bbac159..0000000
--- a/include/models/relay.h
+++ /dev/null
@@ -1,54 +0,0 @@
-#ifndef CONTROLLER_RELAY_H
-#define CONTROLLER_RELAY_H
-
-#include <stdint.h>
-#include <time.h>
-#include <lmdb.h>
-
-#include <constants.h>
-#include <models/schedule.h>
-
-typedef struct
-{
-    int id;
-    uint8_t number;
-    int is_on;
-    int pulse_timer;
-    int sent_to_broker;
-    char name[MAX_NAME_LENGTH + 1];
-    schedule_t *schedules[7];
-} relay_t;
-
-/**
- * @brief Key to save relay information in database
- */
-typedef enum
-{
-    DB_KEY_RELAY_NAME = 0,
-} db_key_relay_e;
-
-relay_t*
-relay_create(uint8_t number);
-
-void
-relay_set_name(relay_t *relay, const char *name);
-
-relay_t*
-relay_load(uint8_t number);
-
-int
-relay_save(relay_t *relay);
-
-void
-relay_reload_schedules(relay_t *relay);
-
-int
-relay_is_on_schedule(relay_t *relay, struct tm *time_struct);
-
-void
-relay_free(relay_t *relay);
-
-void
-relay_debug(relay_t *relay);
-
-#endif //CONTROLLER_RELAY_H
diff --git a/include/models/schedule.h b/include/models/schedule.h
deleted file mode 100644
index 212cd81..0000000
--- a/include/models/schedule.h
+++ /dev/null
@@ -1,58 +0,0 @@
-#ifndef CONTROLLER_SCHEDULE_H
-#define CONTROLLER_SCHEDULE_H
-
-#include <stdint.h>
-#include <uuid/uuid.h>
-#include <lmdb.h>
-
-#include <models/period.h>
-
-typedef struct
-{
-    int id;
-    uuid_t uid;
-    uint8_t weekday;
-    uint16_t periods_count;
-    period_t *periods;
-} schedule_t;
-
-/**
- * @brief Key to save schedule information in database
- */
-typedef enum
-{
-    DB_KEY_SCHEDULE_ID = 0,
-    DB_KEY_SCHEDULE_PERIODS = 1,
-} db_key_schedule_e;
-
-schedule_t*
-schedule_create(uuid_t uid, uint16_t length, uint16_t *periods_blob);
-
-int
-schedule_save(schedule_t *schedule);
-
-schedule_t*
-schedule_get_by_uid(uuid_t uid);
-
-schedule_t**
-schedule_get_relay_weekdays(int relay_id);
-
-uint16_t*
-schedule_periods_to_blob(schedule_t *schedule);
-
-void
-schedule_free(schedule_t *schedule);
-
-void
-schedule_free_list(schedule_t **schedules_list);
-
-void
-schedule_debug(schedule_t *schedule);
-
-int
-schedule_uid_parse(const char *uid_str, uuid_t result);
-
-void
-schedule_uid_unparse(const uuid_t uid, char *result);
-
-#endif /* CONTROLLER_SCHEDULE_H */
diff --git a/include/runners.h b/include/runners.h
deleted file mode 100644
index 1eecf37..0000000
--- a/include/runners.h
+++ /dev/null
@@ -1,11 +0,0 @@
-#ifndef CONTROLLER_RUNNERS_H
-#define CONTROLLER_RUNNERS_H
-
-#include <stdint.h>
-
-#include <models/controller.h>
-
-void
-runner_test();
-
-#endif /* CONTROLLER_RUNNERS_H */
diff --git a/include/sql/.gitkeep b/include/sql/.gitkeep
deleted file mode 100644
index e69de29..0000000
diff --git a/include/wiring_debug.h b/include/wiring_debug.h
deleted file mode 100644
index f897697..0000000
--- a/include/wiring_debug.h
+++ /dev/null
@@ -1,16 +0,0 @@
-#ifndef CONTROLLER_WIRING_DEBUG_H
-#define CONTROLLER_WIRING_DEBUG_H
-
-#include <logger.h>
-
-#ifdef WIRING_PI_DEBUG
-    #define LOG_WIRING_PI LOGGER_DEBUG
-    #define wiringPiSetup() LOG_WIRING_PI("wiringPi wiringPiSetup()\n")
-    #define wiringPiSetupSys() LOG_WIRING_PI("wiringPi wiringPiSetupSys()\n")
-    #define pinMode(x,y) LOG_WIRING_PI("wiringPi pinMode(%d, %d)\n", x, y)
-    #define digitalWrite(x,y) LOG_WIRING_PI("wiringPi digitalWrite(%d, %d)\n", x, y)
-
-    #define piFaceSetup(x) LOG_WIRING_PI("wiringPi piFaceSetup(%d)\n", x)
-#endif
-
-#endif /* CONTROLLER_WIRING_DEBUG_H */
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..e2633eb
--- /dev/null
+++ b/main.go
@@ -0,0 +1,100 @@
+package main
+
+/*
+#cgo CFLAGS: -g -Wall
+#cgo LDFLAGS: -lwiringPi -lwiringPiDev
+#include <wiringPi.h>
+*/
+import "C"
+import (
+	"net/http"
+	"strings"
+
+	"github.com/go-playground/validator/v10"
+	"github.com/spf13/viper"
+
+	"emgauwa.app/emgauwa-core/models"
+	"emgauwa.app/emgauwa-core/utils"
+)
+
+type (
+	EmgauwaValidator struct {
+		validator *validator.Validate
+	}
+)
+
+func (cv *EmgauwaValidator) Validate(i interface{}) error {
+	return cv.validator.Struct(i)
+}
+
+func SkipperSwagger(c echo.Context) bool {
+	if strings.Contains(c.Request().URL.Path, "swagger") {
+		return true
+	}
+	return false
+}
+
+func init() {
+	utils.ConfigInit()
+	utils.LoggerInit()
+	models.DatabaseInit()
+}
+
+// @title Emgauwa API
+// @version 1.0
+// @description This is a sample server server.
+// @termsOfService http://swagger.io/terms/
+
+// @contact.name Tobias Reisinger
+// @contact.url https://serguzim.me
+// @contact.email tobias@msrg.cc
+func main() {
+
+	C.wiringPiSetup()
+
+	e := echo.New()
+
+	v := validator.New()
+	v.RegisterValidation("hhmmformat", utils.ValidatorsHHMMFormat)
+	e.Validator = &EmgauwaValidator{validator: v}
+
+	e.Pre(middleware.RemoveTrailingSlash())
+
+	e.Use(middleware.CORS())
+	e.Use(middleware.GzipWithConfig(middleware.GzipConfig{
+		Skipper: SkipperSwagger,
+	}))
+	e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
+		Format: "${time_rfc3339} [${method}] ${uri} > ${status} (${latency_human})\n",
+	}))
+	e.Use(middleware.Recover())
+	e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
+		Skipper: SkipperSwagger,
+		Root:    viper.GetString("content-dir"),
+		HTML5:   true,
+	}))
+
+	e.GET("api/swagger/*", echoSwagger.WrapHandler)
+	e.GET("api/swagger", func(c echo.Context) error {
+		return c.Redirect(http.StatusMovedPermanently, "/api/swagger/index.html")
+	})
+
+	r_api_v1 := e.Group("api/v1")
+	{
+
+		r_api_v1.GET("/schedules", api_v1.Schedules_GET)
+		r_api_v1.POST("/schedules", api_v1.Schedules_POST)
+		r_api_v1.GET("/schedules/:schedule_uid", api_v1.Schedules_UID_GET)
+		r_api_v1.PUT("/schedules/:schedule_uid", api_v1.Schedules_UID_PUT)
+		r_api_v1.DELETE("/schedules/:schedule_uid", api_v1.Schedules_UID_DELETE)
+		r_api_v1.GET("/schedules/tag/:tag", api_v1.Schedules_Tag_TAG_GET)
+		r_api_v1.POST("/schedules/list", api_v1.Schedules_List_POST)
+
+		r_api_v1.GET("/controllers", api_v1.Controllers_GET)
+
+		r_api_v1.GET("/tags", api_v1.Tags_GET)
+		r_api_v1.GET("/ws/relays", api_v1.WS_Relays_GET)
+	}
+
+	e.Start(viper.GetString("bind.http"))
+}
diff --git a/sql/migration_0.sql b/sql/migration_0.sql
deleted file mode 100644
index e9dc18a..0000000
--- a/sql/migration_0.sql
+++ /dev/null
@@ -1,49 +0,0 @@
-create table controllers
-(
-    id      INTEGER
-            PRIMARY KEY
-            AUTOINCREMENT,
-    uid     BLOB
-            NOT NULL
-            UNIQUE,
-    name            VARCHAR(128),
-    command_port    INTEGER
-);
-
-create table relays
-(
-    id      INTEGER
-            PRIMARY KEY
-            AUTOINCREMENT,
-    number  INTEGER
-            NOT NULL,
-    name    VARCHAR(128)
-);
-
-create table schedules
-(
-    id      INTEGER
-            PRIMARY KEY
-            AUTOINCREMENT,
-    uid     BLOB
-            NOT NULL
-            UNIQUE,
-    name    VARCHAR(128),
-    periods BLOB
-);
-
-create table junction_relay_schedule
-(
-    weekday         SMALLINT
-                    NOT NULL,
-    relay_id        INTEGER
-                    REFERENCES relays (id)
-                    ON DELETE CASCADE,
-    schedule_id     INTEGER
-                    DEFAULT 1
-                    REFERENCES schedules (id)
-                    ON DELETE SET DEFAULT
-);
-
-INSERT INTO schedules (uid, name, periods) VALUES (x'6f666600000000000000000000000000', 'off', x'00');
-INSERT INTO schedules (uid, name, periods) VALUES (x'6f6e0000000000000000000000000000',  'on', x'010000009F05');
diff --git a/src/config.c b/src/config.c
deleted file mode 100644
index 2e2fe47..0000000
--- a/src/config.c
+++ /dev/null
@@ -1,191 +0,0 @@
-#include <stdlib.h>
-#include <string.h>
-
-#include <helpers.h>
-#include <config.h>
-#include <logger.h>
-#include <confini.h>
-
-#define CONFINI_IS_KEY(SECTION, KEY) \
-    (ini_array_match(SECTION, disp->append_to, '.', disp->format) && \
-     ini_string_match_ii(KEY, disp->data, disp->format))
-
-static int
-config_load_log_level(IniDispatch *disp, config_t *config)
-{
-    if(strcasecmp(disp->value, "debug") == 0)
-    {
-        setlogmask(LOG_UPTO(LOG_DEBUG));
-        config->log_level = LOG_DEBUG;
-        return 0;
-    }
-    if(strcasecmp(disp->value, "info") == 0)
-    {
-        setlogmask(LOG_UPTO(LOG_INFO));
-        config->log_level = LOG_INFO;
-        return 0;
-    }
-    if(strcasecmp(disp->value, "notice") == 0)
-    {
-        setlogmask(LOG_UPTO(LOG_NOTICE));
-        config->log_level = LOG_NOTICE;
-        return 0;
-    }
-    if(strcasecmp(disp->value, "warning") == 0)
-    {
-        setlogmask(LOG_UPTO(LOG_WARNING));
-        config->log_level = LOG_WARNING;
-        return 0;
-    }
-    if(strcasecmp(disp->value, "err") == 0)
-    {
-        setlogmask(LOG_UPTO(LOG_ERR));
-        config->log_level = LOG_ERR;
-        return 0;
-    }
-    if(strcasecmp(disp->value, "crit") == 0)
-    {
-        setlogmask(LOG_UPTO(LOG_CRIT));
-        config->log_level = LOG_CRIT;
-        return 0;
-    }
-    if(strcasecmp(disp->value, "emerg") == 0)
-    {
-        setlogmask(LOG_UPTO(LOG_EMERG));
-        config->log_level = LOG_EMERG;
-        return 0;
-    }
-    LOGGER_WARNING("invalid log-level '%s'\n", disp->value);
-    return 0;
-}
-
-static int
-config_load_log_file(IniDispatch *disp, config_t *config)
-{
-    if(strcasecmp(disp->value, "stdout") == 0)
-    {
-        config->log_file = stdout;
-        return 0;
-    }
-    if(strcasecmp(disp->value, "stderr") == 0)
-    {
-        config->log_file = stderr;
-        return 0;
-    }
-    config->log_file = fopen(disp->value, "a+");
-    return 0;
-}
-
-int
-config_load(IniDispatch *disp, void *config_void)
-{
-    config_t *config = (config_t*)config_void;
-    char relay_section_name[10]; // "relay-255\0" is longest name 
-
-    if(disp->type == INI_KEY)
-    {
-        if(CONFINI_IS_KEY("controller", "name"))
-        {
-            strncpy(config->name, disp->value, MAX_NAME_LENGTH);
-            config->name[MAX_NAME_LENGTH] = '\0';
-            return 0;
-        }
-        if(CONFINI_IS_KEY("controller", "database"))
-        {
-            strcpy(config->database, disp->value);
-            return 0;
-        }
-        if(CONFINI_IS_KEY("controller", "user"))
-        {
-            strcpy(config->user, disp->value);
-            return 0;
-        }
-        if(CONFINI_IS_KEY("controller", "group"))
-        {
-            strcpy(config->group, disp->value);
-            return 0;
-        }
-        if(CONFINI_IS_KEY("controller", "log-level"))
-        {
-            return config_load_log_level(disp, config);
-        }
-        if(CONFINI_IS_KEY("controller", "log-file"))
-        {
-            return config_load_log_file(disp, config);
-        }
-        if(CONFINI_IS_KEY("controller", "discovery-port"))
-        {
-            config->discovery_port = atoi(disp->value);
-            return 0;
-        }
-        if(CONFINI_IS_KEY("controller", "mqtt-port"))
-        {
-            config->mqtt_port = atoi(disp->value);
-            return 0;
-        }
-        if(CONFINI_IS_KEY("controller", "mqtt-host"))
-        {
-            strcpy(config->mqtt_host, disp->value);
-            return 0;
-        }
-        if(CONFINI_IS_KEY("controller", "relays-init"))
-        {
-            config->relays_init = atoi(disp->value);
-            return 0;
-        }
-        if(CONFINI_IS_KEY("controller", "relay-count"))
-        {
-            config->relay_count = atoi(disp->value);
-            config->relay_configs = malloc(sizeof(config_relay_t) * config->relay_count);
-            for(uint8_t i = 0; i < config->relay_count; ++i)
-            {
-                config->relay_configs[i].driver = RELAY_DRIVER_NONE;
-                config->relay_configs[i].inverted = 0;
-                config->relay_configs[i].init = -1;
-                config->relay_configs[i].pin = 0;
-                config->relay_configs[i].pulse_duration = 0;
-            }
-            return 0;
-        }
-        for(uint8_t i = 0; i < config->relay_count; ++i)
-        {
-            sprintf(relay_section_name, "relay-%u", i);
-            if(CONFINI_IS_KEY(relay_section_name, "pin"))
-            {
-                config->relay_configs[i].pin = atoi(disp->value);
-                return 0;
-            }
-            if(CONFINI_IS_KEY(relay_section_name, "inverted"))
-            {
-                config->relay_configs[i].inverted = atoi(disp->value);
-                return 0;
-            }
-            if(CONFINI_IS_KEY(relay_section_name, "init"))
-            {
-                config->relay_configs[i].init = atoi(disp->value);
-                return 0;
-            }
-            if(CONFINI_IS_KEY(relay_section_name, "pulse-duration"))
-            {
-                config->relay_configs[i].pulse_duration = atoi(disp->value);
-                return 0;
-            }
-            if(CONFINI_IS_KEY(relay_section_name, "driver"))
-            {
-                if(strcasecmp(disp->value, "gpio") == 0)
-                {
-                    config->relay_configs[i].driver = RELAY_DRIVER_GPIO;
-                    return 0;
-                }
-                if(strcasecmp(disp->value, "piface") == 0)
-                {
-                    config->relay_configs[i].driver = RELAY_DRIVER_PIFACE;
-                    return 0;
-                }
-                LOGGER_WARNING("invalid driver '%s' in section '%s'\n", disp->value, relay_section_name);
-                return 0;
-            }
-        }
-    }
-    return 0;
-}
diff --git a/src/connections.c b/src/connections.c
deleted file mode 100644
index f32c062..0000000
--- a/src/connections.c
+++ /dev/null
@@ -1,35 +0,0 @@
-#include <stdio.h>
-
-#include <connections.h>
-#include <models/controller.h>
-#include <config.h>
-#include <handlers.h>
-
-struct mg_connection *global_connection_mqtt;
-
-struct mg_connection*
-connection_discovery_bind(struct mg_mgr *mgr)
-{
-    char address[32];
-    sprintf(address, "udp://0.0.0.0:%u", global_config.discovery_port);
-    struct mg_connection *c = mg_bind(mgr, address, handler_discovery);
-    return c;
-}
-
-struct mg_connection*
-connection_command_bind(struct mg_mgr *mgr)
-{
-    char address[32];
-    sprintf(address, "tcp://0.0.0.0:%u", global_controller->command_port);
-    struct mg_connection *c = mg_bind(mgr, address, handler_command);
-    return c;
-}
-
-struct mg_connection*
-connection_mqtt_connect(struct mg_mgr *mgr)
-{
-    char address[512];
-    sprintf(address, "tcp://%s:%u", global_config.mqtt_host, global_config.mqtt_port);
-    struct mg_connection *c = mg_connect(mgr, address, handler_mqtt);
-    return c;
-}
diff --git a/src/database.c b/src/database.c
deleted file mode 100644
index 1b6b36e..0000000
--- a/src/database.c
+++ /dev/null
@@ -1,264 +0,0 @@
-#include <stdint.h>
-#include <stddef.h>
-#include <string.h>
-#include <stdlib.h>
-
-#include <logger.h>
-#include <database.h>
-
-#include <sql/migration_0.h>
-
-sqlite3 *global_database;
-static int in_transaction;
-
-void
-database_init()
-{
-    int rc = sqlite3_open(global_config.database, &global_database);
-
-    if(rc)
-    {
-        LOGGER_CRIT("can't open database: %s\n", sqlite3_errmsg(global_database));
-        exit(1);
-    }
-
-    database_migrate();
-
-    sqlite3_exec(global_database, "PRAGMA foreign_keys = ON", 0, 0, 0);
-    in_transaction = 0;
-}
-
-void
-database_free()
-{
-    sqlite3_close(global_database);
-}
-
-void
-database_migrate()
-{
-    uint16_t version_num = 0;
-    int s, rc;
-    sqlite3_stmt *stmt;
-    sqlite3_prepare_v2(global_database, "PRAGMA user_version;", -1, &stmt, NULL);
-    s = sqlite3_step(stmt);
-    if (s == SQLITE_ROW)
-    {
-        version_num = sqlite3_column_int(stmt, 0);
-    }
-    else
-    {
-        version_num = 0;
-    }
-
-    uint16_t new_version_num = version_num;
-    char* err_msg;
-
-    sqlite3_finalize(stmt);
-
-    switch(version_num)
-    {
-        case 0:
-            LOGGER_INFO("migrating LEVEL 0\n");
-            rc = sqlite3_exec(global_database, (const char *)sql_migration_0_sql, NULL, NULL, &err_msg);
-            if(rc)
-            {
-                LOGGER_CRIT("couldn't migrate LEVEL 0 (%s)\n", err_msg);
-                exit(1);
-            }
-            new_version_num = 1;
-        default:
-            break;
-    }
-
-    char pragma_query[32];
-    sprintf(pragma_query, "PRAGMA user_version=%d;", new_version_num);
-    sqlite3_exec(global_database, pragma_query, 0, 0, 0);
-    LOGGER_DEBUG("storing new user_version %d\n", new_version_num);
-
-    return;
-}
-
-int
-database_transaction_begin()
-{
-    if(!in_transaction)
-    {
-        LOGGER_DEBUG("beginning transaction\n");
-        sqlite3_exec(global_database, "BEGIN TRANSACTION;", NULL, NULL, NULL);
-        in_transaction = 1;
-        return 1;
-    }
-    return 0;
-}
-
-void
-database_transaction_commit()
-{
-    LOGGER_DEBUG("commiting transaction\n");
-    sqlite3_exec(global_database, "COMMIT TRANSACTION;", NULL, NULL, NULL);
-    in_transaction = 0;
-}
-
-void
-database_transaction_rollback()
-{
-    LOGGER_DEBUG("rolling back transaction\n");
-    sqlite3_exec(global_database, "ROLLBACK TRANSACTION;", NULL, NULL, NULL);
-    in_transaction = 0;
-}
-
-int
-database_helper_get_id(sqlite3_stmt *stmt)
-{
-    int result = 0;
-
-    for(;;)
-    {
-        int s;
-
-        s = sqlite3_step(stmt);
-        if (s == SQLITE_ROW)
-        {
-            result = sqlite3_column_int(stmt, 0);
-        }
-        else
-        {
-            if (s == SQLITE_DONE)
-            {
-                break;
-            }
-            else
-            {
-                LOGGER_ERR("error selecting id from database: %s\n", sqlite3_errstr(s));
-                sqlite3_finalize(stmt);
-                return 0;
-            }
-        }
-    }
-
-    sqlite3_finalize(stmt);
-
-    return result;
-}
-
-int*
-database_helper_get_ids(sqlite3_stmt *stmt)
-{
-    int *result = malloc(sizeof(int));
-    int new_id;
-
-    int row = 0;
-
-    for(;;)
-    {
-        int s;
-
-        s = sqlite3_step(stmt);
-        if (s == SQLITE_ROW)
-        {
-            new_id = sqlite3_column_int(stmt, 0);
-            if(new_id != 0) // found row for other target (relay <> schedule)
-            {
-                row++;
-
-                result = (int*)realloc(result, sizeof(int) * (row + 1));
-                result[row - 1] = new_id;
-            }
-        }
-        else
-        {
-            if (s == SQLITE_DONE)
-            {
-                break;
-            }
-            else
-            {
-                LOGGER_ERR("error selecting ids from database: %s\n", sqlite3_errstr(s));
-                sqlite3_finalize(stmt);
-                return NULL;
-            }
-        }
-    }
-
-    sqlite3_finalize(stmt);
-    result[row] = 0;
-
-    return result;
-}
-
-char*
-database_helper_get_string(sqlite3_stmt *stmt)
-{
-    char *result = NULL;
-
-    for(;;)
-    {
-        int s;
-
-        s = sqlite3_step(stmt);
-        if (s == SQLITE_ROW)
-        {
-            const char *found_string = (const char *)sqlite3_column_text(stmt, 0);
-            result = (char*)malloc(sizeof(char) * (strlen(found_string) + 1));
-            strcpy(result, found_string);
-        }
-        else
-        {
-            if (s == SQLITE_DONE)
-            {
-                break;
-            }
-            else
-            {
-                LOGGER_ERR("error selecting string from database: %s\n", sqlite3_errstr(s));
-                sqlite3_finalize(stmt);
-                return NULL;
-            }
-        }
-    }
-
-    sqlite3_finalize(stmt);
-
-    return result;
-}
-
-char**
-database_helper_get_strings(sqlite3_stmt *stmt)
-{
-    char **result = malloc(sizeof(char*));
-
-    int row = 0;
-
-    for(;;)
-    {
-        int s;
-
-        s = sqlite3_step(stmt);
-        if (s == SQLITE_ROW)
-        {
-            const char *new_string = (const char *)sqlite3_column_text(stmt, 0);
-            int new_string_len = strlen(new_string);
-            row++;
-
-            result = (char**)realloc(result, sizeof(char*) * (row + 1));
-            result[row - 1] = malloc(sizeof(char) * (new_string_len + 1));
-            strcpy(result[row - 1], new_string);
-        }
-        else
-        {
-            if(s == SQLITE_DONE)
-            {
-                break;
-            }
-            else
-            {
-                LOGGER_ERR("error selecting strings from database: %s\n", sqlite3_errstr(s));
-                break;
-            }
-        }
-    }
-    sqlite3_finalize(stmt);
-    result[row] = NULL;
-    return result;
-}
diff --git a/src/drivers/gpio.c b/src/drivers/gpio.c
deleted file mode 100644
index cdd969e..0000000
--- a/src/drivers/gpio.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include <wiringPi.h>
-#include <piFace.h>
-#include <wiring_debug.h>
-
-#include <drivers.h>
-
-void
-driver_gpio_set(int pin, int value)
-{
-    digitalWrite(pin, value);
-}
diff --git a/src/drivers/piface.c b/src/drivers/piface.c
deleted file mode 100644
index a7018c0..0000000
--- a/src/drivers/piface.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include <wiringPi.h>
-#include <piFace.h>
-#include <wiring_debug.h>
-
-#include <drivers.h>
-
-void
-driver_piface_set(int pin, int value)
-{
-    digitalWrite(PIFACE_GPIO_BASE + pin, value);
-}
diff --git a/src/handlers/command.c b/src/handlers/command.c
deleted file mode 100644
index d2c04c9..0000000
--- a/src/handlers/command.c
+++ /dev/null
@@ -1,251 +0,0 @@
-#include <string.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <uuid/uuid.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <arpa/inet.h>
-#include <unistd.h>
-#include <netdb.h>
-#include <errno.h>
-
-#include <logger.h>
-#include <database.h>
-#include <handlers.h>
-#include <helpers.h>
-#include <mpack.h>
-#include <models/controller.h>
-#include <models/relay.h>
-#include <models/schedule.h>
-#include <models/junction_relay_schedule.h>
-
-typedef enum
-{
-    COMMAND_CODE_CONTROLLER_ID_GET = 0,
-    COMMAND_CODE_CONTROLLER_TIME_GET = 1,
-    COMMAND_CODE_CONTROLLER_NAME_SET = 2,
-    COMMAND_CODE_CONTROLLER_NAME_GET = 3,
-
-    COMMAND_CODE_RELAY_SCHEDULES_SET = 100,
-    COMMAND_CODE_RELAY_SCHEDULES_GET = 101,
-    COMMAND_CODE_RELAY_NAME_SET = 102,
-    COMMAND_CODE_RELAY_NAME_GET = 103,
-    COMMAND_CODE_RELAY_PULSE = 200,
-
-    COMMAND_CODE_SCHEDULE_UPDATE = 300
-} command_code_t;
-
-typedef enum
-{
-    COMMAND_MAPPING_CODE = 0,
-    COMMAND_MAPPING_NAME = 1,
-    COMMAND_MAPPING_RELAY_NUM = 2,
-    COMMAND_MAPPING_SCHEDULES_ARRAY = 3,
-    COMMAND_MAPPING_SCHEDULE_ID = 4,
-    COMMAND_MAPPING_PERIODS_COUNT = 5,
-    COMMAND_MAPPING_PERIODS_BLOB = 6,
-    COMMAND_MAPPING_PULSE_DURATION = 7,
-} control_mapping_t;
-
-static void
-handler_command_relay_pulse(mpack_node_t map)
-{
-    uint8_t relay_num = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_RELAY_NUM));
-
-    if(relay_num > global_config.relay_count)
-    {
-        LOGGER_WARNING("relay %d is not available (relay count: %d\n", relay_num, global_config.relay_count);
-        return;
-    }
-
-    relay_t *target_relay = global_controller->relays[relay_num];
-    (void)target_relay;
-
-    int duration = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_PULSE_DURATION));
-    if(duration == 0)
-    {
-        duration = global_config.relay_configs[relay_num].pulse_duration;
-    }
-    target_relay->pulse_timer = duration;
-    LOGGER_DEBUG("pulsing relay %d for %ds\n", relay_num, duration);
-}
-
-static void
-handler_command_controller_name_set(mpack_node_t map)
-{
-    char name_buffer[MAX_NAME_LENGTH + 1];
-    mpack_node_copy_cstr(mpack_node_map_uint(map, COMMAND_MAPPING_NAME), name_buffer, MAX_NAME_LENGTH + 1);
-    controller_set_name(global_controller, name_buffer);
-    LOGGER_DEBUG("setting new name %s for controller\n", name_buffer);
-    controller_save();
-}
-
-static void
-handler_command_relay_name_set(mpack_node_t map)
-{
-    uint8_t relay_num = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_RELAY_NUM));
-    const char *relay_name = mpack_node_str(mpack_node_map_uint(map, COMMAND_MAPPING_NAME));
-
-    if(relay_num > global_config.relay_count)
-    {
-        LOGGER_WARNING("relay %d is not available (relay count: %d\n", relay_num, global_config.relay_count);
-        return;
-    }
-    relay_set_name(global_controller->relays[relay_num], relay_name);
-    LOGGER_DEBUG("setting new name %s for relay %d\n", relay_name, relay_num);
-    relay_save(global_controller->relays[relay_num]);
-}
-
-static void
-handler_command_schedule_update(mpack_node_t map)
-{
-    uuid_t schedule_uid;
-    memcpy(schedule_uid, mpack_node_data(mpack_node_map_uint(map, COMMAND_MAPPING_SCHEDULE_ID)), sizeof(uuid_t));
-
-    uint16_t periods_count = mpack_node_u16(mpack_node_map_uint(map, COMMAND_MAPPING_PERIODS_COUNT));
-    uint16_t *periods = (uint16_t*)mpack_node_bin_data(mpack_node_map_uint(map, COMMAND_MAPPING_PERIODS_BLOB));
-
-    schedule_t *schedule = schedule_get_by_uid(schedule_uid);
-
-    schedule_t *new_schedule = schedule_create(schedule_uid, periods_count, periods);
-
-    if(schedule)
-    {
-        new_schedule->id = schedule->id;
-        schedule_free(schedule);
-    }
-
-    schedule_save(new_schedule);
-
-    int *relay_ids = junction_relay_schedule_get_relay_ids_with_schedule(new_schedule->id);
-
-    for(int i = 0; i < global_config.relay_count; ++i)
-    {
-        for(int j = 0; relay_ids[j] != 0; ++j)
-        {
-            if(global_controller->relays[i]->id == relay_ids[j])
-            {
-                relay_reload_schedules(global_controller->relays[i]);
-            }
-        }
-    }
-
-    free(relay_ids);
-    schedule_free(new_schedule);
-}
-
-static void
-handler_command_relay_schedules_set(mpack_node_t map)
-{
-    uint8_t relay_num = mpack_node_u8(mpack_node_map_uint(map, COMMAND_MAPPING_RELAY_NUM));
-
-    if(relay_num > global_config.relay_count)
-    {
-        LOGGER_WARNING("relay %d is not available (relay count: %d\n", relay_num, global_config.relay_count);
-        return;
-    }
-
-    LOGGER_DEBUG("setting schedules for relay %d\n", relay_num);
-    relay_t *target_relay = global_controller->relays[relay_num];
-
-    database_transaction_begin();
-
-    junction_relay_schedule_remove_for_relay(target_relay->id);
-
-    mpack_node_t schedules_array = mpack_node_map_uint(map, COMMAND_MAPPING_SCHEDULES_ARRAY);
-
-    for(int i = 0; i < 7; ++i)
-    {
-        mpack_node_t schedule_map = mpack_node_array_at(schedules_array, i);
-
-        uuid_t schedule_uid;
-        memcpy(schedule_uid, mpack_node_data(mpack_node_map_uint(schedule_map, COMMAND_MAPPING_SCHEDULE_ID)), sizeof(uuid_t));
-
-        uint16_t periods_count = mpack_node_u16(mpack_node_map_uint(schedule_map, COMMAND_MAPPING_PERIODS_COUNT));
-        uint16_t *periods = (uint16_t*)mpack_node_bin_data(mpack_node_map_uint(schedule_map, COMMAND_MAPPING_PERIODS_BLOB));
-
-        schedule_t *schedule = schedule_get_by_uid(schedule_uid);
-
-        schedule_t *new_schedule = schedule_create(schedule_uid, periods_count, periods);
-
-        if(schedule)
-        {
-            new_schedule->id = schedule->id;
-            schedule_free(schedule);
-        }
-
-        schedule_save(new_schedule);
-
-        junction_relay_schedule_insert(i, target_relay->id, new_schedule->id);
-    }
-
-    relay_reload_schedules(target_relay);
-
-    database_transaction_commit();
-}
-
-void
-handler_command(struct mg_connection *c, int ev, void *ev_data)
-{
-    (void)ev_data;
-    if(ev != MG_EV_RECV)
-    {
-        return;
-    }
-    uint32_t payload_length = *((uint32_t*)c->recv_mbuf.buf);
-
-    if(c->recv_mbuf.len < payload_length + sizeof(payload_length))
-    {
-        return;
-    }
-
-    char *payload = c->recv_mbuf.buf + sizeof(payload_length);
-
-    mpack_tree_t tree;
-    mpack_tree_init_data(&tree, payload, payload_length);
-    mpack_tree_parse(&tree);
-    mpack_node_t root = mpack_tree_root(&tree);
-
-    uint16_t command_code = mpack_node_u16(mpack_node_map_uint(root, COMMAND_MAPPING_CODE));
-
-    LOGGER_DEBUG("received command %d\n", command_code);
-
-    switch(command_code)
-    {
-        case COMMAND_CODE_CONTROLLER_ID_GET:
-            break;
-        case COMMAND_CODE_CONTROLLER_TIME_GET:
-            break;
-        case COMMAND_CODE_CONTROLLER_NAME_SET:
-            handler_command_controller_name_set(root);
-            break;
-        case COMMAND_CODE_CONTROLLER_NAME_GET:
-            break;
-        case COMMAND_CODE_RELAY_SCHEDULES_SET:
-            handler_command_relay_schedules_set(root);
-            break;
-        case COMMAND_CODE_RELAY_SCHEDULES_GET:
-            break;
-        case COMMAND_CODE_RELAY_NAME_SET:
-            handler_command_relay_name_set(root);
-            break;
-        case COMMAND_CODE_RELAY_NAME_GET:
-            break;
-        case COMMAND_CODE_RELAY_PULSE:
-            handler_command_relay_pulse(root);
-            break;
-        case COMMAND_CODE_SCHEDULE_UPDATE:
-            handler_command_schedule_update(root);
-            break;
-        default:
-            LOGGER_ERR("received invalid command\n");
-    }
-
-    if(mpack_tree_destroy(&tree) != mpack_ok)
-    {
-        LOGGER_WARNING("error when destroying mpack tree\n");
-    }
-    LOGGER_DEBUG("done with command %d - closing connection\n", command_code);
-    c->flags |= MG_F_SEND_AND_CLOSE;
-}
diff --git a/src/handlers/discovery.c b/src/handlers/discovery.c
deleted file mode 100644
index db95e08..0000000
--- a/src/handlers/discovery.c
+++ /dev/null
@@ -1,95 +0,0 @@
-#include <string.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <uuid/uuid.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <arpa/inet.h>
-#include <unistd.h>
-#include <netdb.h>
-#include <errno.h>
-
-#include <logger.h>
-#include <mongoose.h>
-#include <handlers.h>
-#include <helpers.h>
-#include <mpack.h>
-#include <enums.h>
-
-void
-handler_discovery(struct mg_connection *c, int ev, void *ev_data)
-{
-    (void)ev_data;
-    if(ev == MG_EV_RECV)
-    {
-        uint16_t discovery_answer_port;
-        char ip_buf[32];
-        mg_conn_addr_to_str(c, ip_buf, sizeof(ip_buf), MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_REMOTE);
-
-        if(c->recv_mbuf.len != sizeof(discovery_answer_port))
-        {
-            LOGGER_ERR("received invalid discovery from %s\n", ip_buf);
-            return;
-        }
-        discovery_answer_port = *((uint16_t*)c->recv_mbuf.buf);
-
-        LOGGER_INFO("received discovery from %s:%d\n", ip_buf, discovery_answer_port);
-
-        if(discovery_answer_port == 0)
-        {
-            LOGGER_ERR("invalid port received\n");
-            return;
-        }
-
-        char* payload;
-        size_t payload_size;
-        mpack_writer_t writer;
-        mpack_writer_init_growable(&writer, &payload, &payload_size);
-
-        mpack_start_map(&writer, 4);
-        mpack_write_uint(&writer, DISCOVERY_MAPPING_ID);
-        mpack_write_bin(&writer, (char*)global_controller->uid, sizeof(uuid_t));
-        mpack_write_uint(&writer, DISCOVERY_MAPPING_COMMAND_PORT);
-        mpack_write_u16(&writer, global_controller->command_port);
-        mpack_write_uint(&writer, DISCOVERY_MAPPING_RELAY_COUNT);
-        mpack_write_u8(&writer, global_config.relay_count);
-        mpack_write_uint(&writer, DISCOVERY_MAPPING_NAME);
-        mpack_write_cstr(&writer, global_controller->name);
-        mpack_finish_map(&writer);
-
-        // finish writing
-        if(mpack_writer_destroy(&writer) != mpack_ok)
-        {
-            LOGGER_ERR("error writing discovery answer payload\n");
-            return;
-
-        }
-
-        size_t bytes_transferred;
-        int fd_answer = helper_connect_tcp_server(ip_buf, discovery_answer_port);
-        if(fd_answer == -1)
-        {
-            LOGGER_ERR("error during connecting\n");
-            free(payload);
-            return;
-        }
-
-        if((bytes_transferred = send(fd_answer, &payload_size, sizeof(payload_size), 0)) <= 0)
-        {
-            LOGGER_ERR("error during sending\n");
-            free(payload);
-            close(fd_answer);
-            return;
-        }
-        if((bytes_transferred = send(fd_answer, payload, payload_size, 0)) <= 0)
-        {
-            LOGGER_ERR("error during sending\n");
-            free(payload);
-            close(fd_answer);
-            return;
-        }
-
-        free(payload);
-    }
-}
diff --git a/src/handlers/loop.c b/src/handlers/loop.c
deleted file mode 100644
index 2076952..0000000
--- a/src/handlers/loop.c
+++ /dev/null
@@ -1,92 +0,0 @@
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <time.h>
-#include <uuid/uuid.h>
-
-#include <logger.h>
-#include <models/controller.h>
-#include <handlers.h>
-#include <drivers.h>
-#include <enums.h>
-#include <helpers.h>
-#include <wiringPi.h>
-#include <wiring_debug.h>
-
-void
-handler_loop(struct mg_connection *c_mqtt)
-{
-    char topic_buf[100];
-    char payload_buf[2];
-    char controller_uid[UUID_STR_LEN];
-    uuid_unparse(global_controller->uid, controller_uid);
-
-    struct tm time_last, time_now;
-    time_t timestamp;
-
-    timestamp = time(NULL) - 1;
-    localtime_r(&timestamp, &time_last);
-    timestamp = time(NULL);
-    localtime_r(&timestamp, &time_now);
-    for(uint_fast8_t i = 0; i < global_config.relay_count; ++i)
-    {
-        relay_t *relay = global_controller->relays[i];
-        int is_on = 0;
-        
-        int is_on_schedule = relay_is_on_schedule(relay, &time_now);
-        int pulse_relay = global_config.relay_configs[i].pulse_duration;
-
-        if(is_on_schedule)
-        {
-            if(!pulse_relay)
-            {
-                is_on = 1;
-                LOGGER_DEBUG("relay %d is active\n", i);
-            }
-            if(pulse_relay && relay->pulse_timer)
-            {
-                is_on = 1;
-                --relay->pulse_timer;
-                LOGGER_DEBUG("relay %d is pulsing for %d more seconds\n", i, relay->pulse_timer);
-            }
-        }
-        else
-        {
-            relay->pulse_timer = 0;
-        }
-
-        if(relay->is_on != is_on)
-        {
-            relay->sent_to_broker = 0;
-        }
-        if(!relay->sent_to_broker && c_mqtt)
-        {
-            sprintf(topic_buf, "controller/%s/relay/%u", controller_uid, i);
-            sprintf(payload_buf, "%u", is_on);
-            mg_mqtt_publish(c_mqtt, topic_buf, 0, MG_MQTT_QOS(0), payload_buf, strlen(payload_buf));
-            relay->sent_to_broker = (rand() % 45) + 15;
-            LOGGER_DEBUG("sent relay %d status (%d) to mqtt broker\n", i, is_on);
-        }
-        if(relay->sent_to_broker)
-        {
-            --relay->sent_to_broker;
-        }
-        relay->is_on = is_on;
-
-        if(global_config.relay_configs[i].inverted)
-        {
-            is_on = !is_on;
-        }
-        switch(global_config.relay_configs[i].driver)
-        {
-            case RELAY_DRIVER_GPIO:
-                driver_gpio_set(global_config.relay_configs[i].pin, is_on);
-                break;
-            case RELAY_DRIVER_PIFACE:
-                driver_piface_set(global_config.relay_configs[i].pin, is_on);
-                break;
-            default:
-                LOGGER_WARNING("relay %d is not using a driver\n", i);
-        }
-    }
-}
diff --git a/src/handlers/mqtt.c b/src/handlers/mqtt.c
deleted file mode 100644
index 7ac6e13..0000000
--- a/src/handlers/mqtt.c
+++ /dev/null
@@ -1,43 +0,0 @@
-#include <logger.h>
-#include <handlers.h>
-#include <connections.h>
-#include <models/controller.h>
-
-void
-handler_mqtt(struct mg_connection *nc, int ev, void *p) {
-    struct mg_mqtt_message *msg = (struct mg_mqtt_message *) p;
-    (void) nc;
-
-    switch (ev)
-    {
-        case MG_EV_CONNECT:
-            {
-                struct mg_send_mqtt_handshake_opts opts;
-                memset(&opts, 0, sizeof(opts));
-                // TODO add password
-
-                mg_set_protocol_mqtt(nc);
-                mg_send_mqtt_handshake_opt(nc, global_controller->name, opts);
-                break;
-            }
-        case MG_EV_MQTT_CONNACK:
-            if(msg->connack_ret_code != MG_EV_MQTT_CONNACK_ACCEPTED)
-            {
-                LOGGER_INFO("Got MQTT connection error: %d\n", msg->connack_ret_code);
-                break;
-            }
-            if(!global_connection_mqtt)
-            {
-                LOGGER_DEBUG("connected to MQTT server\n");
-                global_connection_mqtt = nc;
-            }
-            break;
-        case MG_EV_CLOSE:
-            if(global_connection_mqtt)
-            {
-                LOGGER_DEBUG("disconnected from MQTT server\n");
-            }
-            global_connection_mqtt = NULL;
-            break;
-    }
-}
diff --git a/src/helpers/bind_server.c b/src/helpers/bind_server.c
deleted file mode 100644
index b0878e5..0000000
--- a/src/helpers/bind_server.c
+++ /dev/null
@@ -1,52 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <netdb.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <errno.h>
-
-#include <logger.h>
-#include <helpers.h>
-
-int
-helper_bind_tcp_server(char* addr, uint16_t port, int max_client_backlog)
-{
-    char port_str[6];
-    sprintf(port_str, "%d", port);
-
-    struct addrinfo hints, *res;
-    int fd;
-    int status;
-
-    memset(&hints, 0, sizeof hints);
-    hints.ai_family = AF_UNSPEC;
-    hints.ai_socktype = SOCK_STREAM;
-    hints.ai_flags = AI_PASSIVE;
-
-    if ((status = getaddrinfo(addr, port_str, &hints, &res)) != 0)
-    {
-        LOGGER_ERR("getaddrinfo: %s\n", gai_strerror(status));
-        return -1;
-    }
-
-    fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
-
-    if ((status = bind(fd, res->ai_addr, res->ai_addrlen)) == -1)
-    {
-        LOGGER_ERR("error binding socket: %s\n", strerror(errno));
-        freeaddrinfo(res);
-        return -1;
-    }
-
-    if ((status = listen(fd, max_client_backlog)) == -1)
-    {
-        LOGGER_ERR("error setting up listener: %s\n", strerror(errno));
-        freeaddrinfo(res);
-        return -1;
-    }
-
-    freeaddrinfo(res);
-
-    return fd;
-}
diff --git a/src/helpers/connect_server.c b/src/helpers/connect_server.c
deleted file mode 100644
index dbfdc80..0000000
--- a/src/helpers/connect_server.c
+++ /dev/null
@@ -1,39 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <netdb.h>
-#include <sys/socket.h>
-
-#include <logger.h>
-#include <helpers.h>
-
-int
-helper_connect_tcp_server(char* host, uint16_t port)
-{
-    char port_str[6];
-    sprintf(port_str, "%d", port);
-
-    int s, status;
-    struct addrinfo hints, *res;
-    memset(&hints, 0, sizeof hints);
-    hints.ai_family = AF_INET; //set IP Protocol flag (IPv4 or IPv6 - we don't care)
-    hints.ai_socktype = SOCK_STREAM; //set socket flag
-
-    if ((status = getaddrinfo(host, port_str, &hints, &res)) != 0) { //getaddrinfo() will evaluate the given address, using the hints-flags and port, and return an IP address and other server infos
-        LOGGER_ERR("getaddrinfo: %s\n", gai_strerror(status));
-        return -1;
-    }
-
-    //res got filled out by getaddrinfo() for us
-    s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); //creating Socket
-
-    if ((status = connect(s, res->ai_addr, res->ai_addrlen)) != 0) {
-        LOGGER_ERR("connect() failed\n");
-        freeaddrinfo(res);
-        return -1;
-    }
-
-    freeaddrinfo(res);
-
-    return s;
-}
diff --git a/src/helpers/drop_privileges.c b/src/helpers/drop_privileges.c
deleted file mode 100644
index e2dde8a..0000000
--- a/src/helpers/drop_privileges.c
+++ /dev/null
@@ -1,81 +0,0 @@
-#include <sys/types.h>
-#include <pwd.h>
-#include <grp.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdio.h>
-
-#include <config.h>
-#include <logger.h>
-
-static uid_t
-get_uid_for_user(char *user)
-{
-    if(user == NULL || user[0] == '\0')
-    {
-        return getuid();
-    }
-    struct passwd *pwd = calloc(1, sizeof(struct passwd));
-    size_t buffer_len = sysconf(_SC_GETPW_R_SIZE_MAX) * sizeof(char);
-    char *buffer = malloc(buffer_len);
-    getpwnam_r(user, pwd, buffer, buffer_len, &pwd);
-
-    if(pwd == NULL)
-    {
-        LOGGER_CRIT("couldn't find user to drop privileges\n");
-        exit(1);
-    }
-
-    uid_t result = pwd->pw_uid;
-    free(buffer);
-    free(pwd);
-    return result;
-}
-
-static gid_t
-get_gid_for_group(char *group)
-{
-    if(group == NULL || group[0] == '\0')
-    {
-        return getgid();
-    }
-    struct group *grp = calloc(1, sizeof(struct group));
-    size_t buffer_len = sysconf(_SC_GETPW_R_SIZE_MAX) * sizeof(char);
-    char *buffer = malloc(buffer_len);
-    getgrnam_r(group, grp, buffer, buffer_len, &grp);
-
-    if(grp == NULL)
-    {
-        LOGGER_CRIT("couldn't find group to drop privileges\n");
-        exit(1);
-    }
-
-    gid_t result = grp->gr_gid;
-    free(buffer);
-    free(grp);
-    return result;
-}
-
-int
-helper_drop_privileges()
-{
-    uid_t uid = get_uid_for_user(global_config.user);
-    gid_t gid = get_gid_for_group(global_config.group);
-
-    LOGGER_DEBUG("drop privileges to %lu:%lu\n", uid, gid);
-
-    if (setgid(gid) == -1)
-    {
-        LOGGER_CRIT("failed to drop group privileges\n");
-        exit(1);
-    }
-    if (setuid(uid) == -1)
-    {
-        LOGGER_CRIT("failed to drop user privileges\n");
-        exit(1);
-    }
-
-    return 0;
-}
-
-
diff --git a/src/helpers/get_port.c b/src/helpers/get_port.c
deleted file mode 100644
index 904d10f..0000000
--- a/src/helpers/get_port.c
+++ /dev/null
@@ -1,24 +0,0 @@
-#include <sys/socket.h>
-#include <arpa/inet.h>
-#include <stdint.h>
-#include <errno.h>
-#include <string.h>
-
-#include <helpers.h>
-#include <logger.h>
-
-uint16_t
-helper_get_port(int sock)
-{
-    struct sockaddr_in sin;
-    socklen_t len = sizeof(sin);
-    if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
-    {
-        LOGGER_ERR("could not get socket name for port: %s\n", strerror(errno));
-        return 0;
-    }
-    else
-    {
-        return ntohs(sin.sin_port);
-    }
-}
diff --git a/src/helpers/get_weekday.c b/src/helpers/get_weekday.c
deleted file mode 100644
index 68f029e..0000000
--- a/src/helpers/get_weekday.c
+++ /dev/null
@@ -1,11 +0,0 @@
-#include <time.h>
-
-#include <helpers.h>
-
-int
-helper_get_weekday(const struct tm *time_struct)
-{
-    int wday_sun_sat = time_struct->tm_wday;
-    int wday_mon_sun = (wday_sun_sat + 6) % 7;
-    return wday_mon_sun;
-}
diff --git a/src/helpers/open_discovery_socket.c b/src/helpers/open_discovery_socket.c
deleted file mode 100644
index 42fcc7c..0000000
--- a/src/helpers/open_discovery_socket.c
+++ /dev/null
@@ -1,57 +0,0 @@
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <netdb.h>
-#include <sys/socket.h>
-
-#include <logger.h>
-#include <helpers.h>
-
-int
-helper_open_discovery_socket(uint16_t discovery_port)
-{
-    struct addrinfo hints, *res;
-    int fd, status;
-
-    memset(&hints, 0, sizeof hints);
-    hints.ai_family = AF_INET; // use ipv4
-    hints.ai_socktype = SOCK_DGRAM; //set socket flag
-    hints.ai_flags = AI_PASSIVE; // get my IP
-
-    char discovery_port_str[6];
-    sprintf(discovery_port_str, "%u", discovery_port);
-
-    //get connection info for our computer
-    if ((status = getaddrinfo(NULL, discovery_port_str, &hints, &res)) != 0)
-    {
-        LOGGER_CRIT("getaddrinfo: %s\n", gai_strerror(status));
-        freeaddrinfo(res);
-        exit(EXIT_FAILURE);
-    }
-
-    //creating socket
-    fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
-    int yes = 1;
-
-    // lose the pesky "Address already in use" error message
-    if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1)
-    {
-        LOGGER_CRIT("setsockopt: %s\n", strerror(errno));
-        freeaddrinfo(res);
-        exit(EXIT_FAILURE);
-    }
-
-    if (bind(fd, res->ai_addr, res->ai_addrlen) == -1)
-    {
-        LOGGER_CRIT("bind: %s\n", strerror(errno));
-        freeaddrinfo(res);
-        exit(EXIT_FAILURE);
-    }
-
-    freeaddrinfo(res);
-
-    LOGGER_INFO("opened discovery socket on port %u\n", discovery_port);
-
-    return fd;
-}
diff --git a/src/helpers/parse_cli.c b/src/helpers/parse_cli.c
deleted file mode 100644
index af93eaf..0000000
--- a/src/helpers/parse_cli.c
+++ /dev/null
@@ -1,70 +0,0 @@
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-
-#include <argparse.h>
-#include <config.h>
-#include <logger.h>
-#include <helpers.h>
-#include <version.h>
-
-static const char *const usage[] = {
-    "controller [options] [[--] args]",
-    "controller [options]",
-    NULL,
-};
-
-#define PERM_READ  (1<<0)
-#define PERM_WRITE (1<<1)
-#define PERM_EXEC  (1<<2)
-
-void
-helper_parse_cli(int argc, const char **argv, config_t *config)
-{
-    int version = 0;
-    struct argparse_option options[] =
-    {
-        OPT_HELP(),
-        OPT_GROUP("Basic options"),
-        OPT_STRING('c', "config", &config->file, "path to config file", NULL, 0, OPT_NONEG),
-        OPT_BOOLEAN('v', "version", &version, "print version", NULL, 0, OPT_NONEG),
-        OPT_END(),
-    };
-
-    struct argparse argparse;
-    argparse_init(&argparse, options, usage, 0);
-    argparse_describe(
-            &argparse,
-            "\nA brief description of what the program does and how it works.",
-            "\nAdditional description of the program after the description of the arguments."
-    );
-    argc = argparse_parse(&argparse, argc, argv);
-
-    if(version)
-    {
-        printf("%s\n", EMGAUWA_CONTROLLER_VERSION);
-        exit(0);
-    }
-
-    if(argc == 1)
-    {
-        if(strcmp(argv[0], "start") == 0)
-        {
-            config->run_type = RUN_TYPE_START;
-            return;
-        }
-        if(strcmp(argv[0], "test") == 0)
-        {
-            config->run_type = RUN_TYPE_TEST;
-            return;
-        }
-        LOGGER_CRIT("bad action '%s' given ('start', 'test')\n", argv[0]);
-        exit(1);
-    }
-    else
-    {
-        LOGGER_CRIT("no action given ('start', 'test')\n");
-        exit(1);
-    }
-    return;
-}
diff --git a/src/logger.c b/src/logger.c
deleted file mode 100644
index 2869668..0000000
--- a/src/logger.c
+++ /dev/null
@@ -1,85 +0,0 @@
-#include <stdio.h>
-#include <stdarg.h>
-#include <string.h>
-#include <stdlib.h>
-
-#include <config.h>
-#include <logger.h>
-
-const char *COLOR_DEBUG = COLOR_GREEN;
-const char *COLOR_INFO = COLOR_CYAN;
-const char *COLOR_NOTICE = COLOR_CYAN;
-const char *COLOR_WARNING = COLOR_YELLOW;
-const char *COLOR_ERR = COLOR_RED;
-const char *COLOR_CRIT = COLOR_MAGENTA;
-const char *COLOR_EMERG = COLOR_MAGENTA;
-
-void
-logger_log(int level, const char *filename, int line, const char *func, const char *msg, ...)
-{
-    if(global_config.log_level < level)
-    {
-        return;
-    }
-    const char *level_str;
-    const char *color;
-
-    switch(level)
-    {
-        case LOG_DEBUG:
-            color = COLOR_DEBUG;
-            level_str = "DEBUG";
-            break;
-        case LOG_INFO:
-            color = COLOR_INFO;
-            level_str = "INFO";
-            break;
-        case LOG_NOTICE:
-            color = COLOR_NOTICE;
-            level_str = "NOTE";
-            break;
-        case LOG_WARNING:
-            color = COLOR_WARNING;
-            level_str = "WARN";
-            break;
-        case LOG_ERR:
-            color = COLOR_ERR;
-            level_str = "ERROR";
-            break;
-        case LOG_CRIT:
-            color = COLOR_CRIT;
-            level_str = "CRIT";
-            break;
-        case LOG_EMERG:
-            color = COLOR_EMERG;
-            level_str = "EMERG";
-            break;
-        default:
-            return;
-    }
-
-    char timestamp_str[32];
-    time_t rawtime;
-    time(&rawtime);
-    strftime(timestamp_str, 32, "%Y-%m-%d %H:%M:%S", localtime(&rawtime));
-
-    char *buffer = malloc(sizeof(char) * (128 + strlen(msg)));
-    sprintf(buffer, "%s[%5s] %s:%d:%s " COLOR_NONE "%s", color, level_str, filename, line, func, msg);
-
-    //fprintf(stream, "%s %s:%d:%s " COLOR_NONE, timestamp_str, filename, line, func);
-
-    va_list args;
-    va_start(args, msg);
-    vsyslog(level, buffer, args);
-    va_end(args);
-
-    char *buffer_timed = malloc(sizeof(char) * (strlen(timestamp_str) + strlen(buffer) + 2));
-    sprintf(buffer_timed, "%s %s", timestamp_str, buffer);
-    va_start(args, msg);
-    vfprintf(global_config.log_file, buffer_timed, args);
-    fflush(global_config.log_file);
-    va_end(args);
-
-    free(buffer);
-    free(buffer_timed);
-}
diff --git a/src/main.c b/src/main.c
deleted file mode 100644
index 17149e2..0000000
--- a/src/main.c
+++ /dev/null
@@ -1,208 +0,0 @@
-#include <stdlib.h>
-#include <string.h>
-#include <stdio.h>
-#include <time.h>
-#include <lmdb.h>
-#include <signal.h>
-#include <syslog.h>
-
-#include <logger.h>
-#include <mongoose.h>
-#include <models/controller.h>
-#include <database.h>
-#include <config.h>
-#include <connections.h>
-#include <constants.h>
-#include <handlers.h>
-#include <drivers.h>
-#include <enums.h>
-#include <runners.h>
-#include <helpers.h>
-#include <wiringPi.h>
-#include <piFace.h>
-#include <wiring_debug.h>
-#include <confini.h>
-
-config_t global_config;
-
-static struct mg_mgr mgr;
-
-static void
-terminate(int signum)
-{
-    LOGGER_INFO("terminating controller (%d)\n", signum);
-
-    // TODO fix mg_mgr_free() causing loop (can't terminate)
-    //LOGGER_DEBUG("freeing mongoose manager\n");
-    //mg_mgr_free(&mgr);
-
-    LOGGER_DEBUG("closing database\n");
-    database_free();
-
-    LOGGER_DEBUG("freeing global controller\n");
-    controller_free(global_controller);
-
-    LOGGER_DEBUG("freeing relay configs config\n");
-    free(global_config.relay_configs);
-
-    exit(signum);
-}
-
-/**
- * @brief The main function
- *
- * @param argc UNUSED
- * @param argv UNUSED
- *
- * @return Statuscode to indicate success (0) or failure (!0)
- */
-int
-main(int argc, const char** argv)
-{
-    (void)argc;
-    (void)argv;
-
-    signal(SIGINT, terminate);
-    signal(SIGABRT, terminate);
-    signal(SIGTERM, terminate);
-
-    setlogmask(LOG_UPTO(LOG_INFO));
-
-
-    /******************** LOAD CONFIG ********************/
-
-    global_config.file = "controller.ini";
-    global_config.discovery_port = 4421;
-    global_config.mqtt_port = 1885;
-
-    global_config.relay_count = 0;
-    global_config.relays_init = -1;
-
-    global_config.log_level = LOG_INFO;
-    global_config.log_file = stdout;
-
-    strcpy(global_config.user, "");
-    strcpy(global_config.group, "");
-
-    helper_parse_cli(argc, argv, &global_config);
-
-    FILE * const ini_file = fopen(global_config.file, "rb");
-    if(ini_file == NULL)
-    {
-        LOGGER_CRIT("config file '%s' was not found\n", global_config.file);
-        exit(1);
-    }
-    if(load_ini_file( ini_file, INI_DEFAULT_FORMAT, NULL, config_load, &global_config))
-    {
-        LOGGER_CRIT("unable to parse ini file\n");
-        exit(1);
-    }
- 
-    fclose(ini_file);
-
-    if(global_config.log_file == NULL)
-    {
-        global_config.log_file = stdout;
-    }
-    openlog("emgauwa-controller", 0, LOG_USER);
-
-    if(sizeof(time_t) < 8)
-    {
-        LOGGER_WARNING("this system is not using 8-bit time\n");
-    }
-
-
-    /******************** INIT DATABASE, SOCKETS AND THIS CONTROLLER ********************/
-
-    mg_mgr_init(&mgr, NULL);
-
-    database_init();
-
-    global_controller = controller_load();
-    if(!global_controller)
-    {
-        global_controller = controller_create();
-        controller_save();
-    }
-
-    connection_discovery_bind(&mgr);
-    connection_mqtt_connect(&mgr);
-    struct mg_connection *c_command = connection_command_bind(&mgr);
-
-    if(global_controller->command_port == 0)
-    {
-        global_controller->command_port = helper_get_port(c_command->sock);
-        controller_save();
-    }
-
-    controller_debug(global_controller);
-
-    helper_drop_privileges();
-
-    
-    /******************** SETUP WIRINGPI ********************/
-
-    wiringPiSetup();
-
-    int piface_setup = 0;
-
-    for(uint_fast8_t i = 0; i < global_config.relay_count; ++i)
-    {
-        int relay_default = global_config.relay_configs[i].init;
-        if(relay_default == -1)
-        {
-            relay_default = global_config.relays_init;
-        }
-        if(relay_default == -1)
-        {
-            relay_default = global_config.relay_configs[i].inverted;
-        }
-
-        if(global_config.relay_configs[i].driver == RELAY_DRIVER_GPIO)
-        {
-            pinMode(global_config.relay_configs[i].pin, OUTPUT);
-            driver_gpio_set(global_config.relay_configs[i].pin, relay_default);
-        }
-        if(global_config.relay_configs[i].driver == RELAY_DRIVER_PIFACE)
-        {
-            if(!piface_setup)
-            {
-                piFaceSetup(PIFACE_GPIO_BASE);
-                piface_setup = 1;
-            }
-            driver_piface_set(global_config.relay_configs[i].pin, relay_default);
-        }
-    }
-
-
-    /******************** CHECK FOR TESTING RUN ********************/
-
-    if(global_config.run_type == RUN_TYPE_TEST)
-    {
-        runner_test(global_controller);
-        terminate(0);
-    }
-    
-
-    /******************** START MAIN LOOP ********************/
-
-    time_t timer = 0;
-
-    for (;;)
-    {
-        mg_mgr_poll(&mgr, 200);
-        if(time(NULL) - timer >= 1)
-        {
-            if(!global_connection_mqtt)
-            {
-                connection_mqtt_connect(&mgr);
-            }
-            handler_loop(global_connection_mqtt);
-            timer = time(NULL);
-        }
-    }
-
-    terminate(0);
-
-    return 0;
-}
diff --git a/src/models/controller.c b/src/models/controller.c
deleted file mode 100644
index 729404b..0000000
--- a/src/models/controller.c
+++ /dev/null
@@ -1,256 +0,0 @@
-#include <stdio.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-#include <uuid/uuid.h>
-
-#include <sqlite3.h>
-#include <models/controller.h>
-#include <logger.h>
-#include <config.h>
-#include <constants.h>
-#include <database.h>
-
-controller_t *global_controller;
-
-static int
-db_update_insert(controller_t *controller, sqlite3_stmt *stmt)
-{
-    LOGGER_DEBUG("saving controller '%s' into database (id: %d)\n", controller->name, controller->id);
-    int rc;
-
-    sqlite3_bind_int(stmt, 1, controller->id);
-    sqlite3_bind_blob(stmt, 2, controller->uid, sizeof(uuid_t), SQLITE_STATIC);
-    sqlite3_bind_text(stmt, 3, controller->name, -1, SQLITE_STATIC);
-    sqlite3_bind_int(stmt, 4, controller->command_port);
-
-    rc = sqlite3_step(stmt);
-
-    sqlite3_finalize(stmt);
-
-    return rc != SQLITE_DONE;
-}
-
-static controller_t*
-controller_db_select_mapper(sqlite3_stmt *stmt)
-{
-    controller_t *new_controller = malloc(sizeof(controller_t));
-    for(int i = 0; i < sqlite3_column_count(stmt); i++)
-    {
-        const char *name = sqlite3_column_name(stmt, i);
-        switch(name[0])
-        {
-            case 'i': // id
-                new_controller->id = sqlite3_column_int(stmt, i);
-                break;
-            case 'c': // command_port
-                new_controller->command_port = sqlite3_column_int(stmt, i);
-                break;
-            case 'n': // name
-                strncpy(new_controller->name, (const char*)sqlite3_column_text(stmt, i), 127);
-                break;
-            case 'u': // uid
-                uuid_copy(new_controller->uid, (const unsigned char*)sqlite3_column_blob(stmt, i));
-                break;
-            default: // ignore columns not implemented
-                break;
-        }
-    }
-    new_controller->relays = malloc(sizeof(relay_t) * global_config.relay_count);
-    uint8_t i;
-    for(i = 0; i < global_config.relay_count; ++i)
-    {
-        new_controller->relays[i] = relay_load(i);
-        if(!new_controller->relays[i])
-        {
-            new_controller->relays[i] = relay_create(i);
-            relay_save(new_controller->relays[i]);
-        }
-    }
-    return new_controller;
-}
-
-static controller_t**
-controller_db_select(sqlite3_stmt *stmt)
-{
-    controller_t **all_controllers = malloc(sizeof(controller_t*));
-
-    int row = 0;
-
-    for(;;)
-    {
-        int s;
-
-        s = sqlite3_step(stmt);
-        if (s == SQLITE_ROW)
-        {
-            controller_t *new_controller = controller_db_select_mapper(stmt);
-            row++;
-
-            all_controllers = (controller_t**)realloc(all_controllers, sizeof(controller_t*) * (row + 1));
-            all_controllers[row - 1] = new_controller;
-        }
-        else
-        {
-            if(s == SQLITE_DONE)
-            {
-                break;
-            }
-            else
-            {
-                LOGGER_ERR("error selecting controllers from database: %s\n", sqlite3_errstr(s));
-                break;
-            }
-        }
-    }
-    sqlite3_finalize(stmt);
-    all_controllers[row] = NULL;
-    return all_controllers;
-}
-
-int
-controller_save()
-{
-    int opened_transaction = database_transaction_begin();
-     
-    sqlite3_stmt *stmt;
-    if(global_controller->id)
-    {
-        sqlite3_prepare_v2(global_database, "UPDATE controllers set uid = ?2, name = ?3, command_port = ?4 WHERE id = ?1;", -1, &stmt, NULL);
-    }
-    else
-    {
-        sqlite3_prepare_v2(global_database, "INSERT INTO controllers(uid, name, command_port) values (?2, ?3, ?4);", -1, &stmt, NULL);
-    }
-
-    int result = db_update_insert(global_controller, stmt);
-
-    if(result)
-    {
-        if(global_controller->id)
-        {
-            LOGGER_ERR("error inserting data: %s\n", sqlite3_errmsg(global_database));
-        }
-        else
-        {
-            LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database));
-        }
-
-        if(opened_transaction)
-        {
-            database_transaction_rollback();
-        }
-    }
-    else
-    {
-        if(!global_controller->id)
-        {
-            global_controller->id = sqlite3_last_insert_rowid(global_database);
-        }
-
-        if(opened_transaction)
-        {
-            database_transaction_commit();
-        }
-    }
-
-    return result;
-}
-
-controller_t*
-controller_load()
-{
-    LOGGER_DEBUG("getting controller from database\n");
-    sqlite3_stmt *stmt;
-
-    sqlite3_prepare_v2(global_database, "SELECT * FROM controllers LIMIT 1;", -1, &stmt, NULL);
-
-    controller_t **sql_result = controller_db_select(stmt);
-
-    controller_t *result = sql_result[0];
-    free(sql_result);
-    return result;
-}
-
-int
-controller_remove(controller_t *controller)
-{
-    sqlite3_stmt *stmt;
-    if(!controller->id)
-    {
-        return 0;
-    }
-
-    sqlite3_prepare_v2(global_database, "DELETE FROM controllers WHERE id=?1;", -1, &stmt, NULL);
-    sqlite3_bind_int(stmt, 1, controller->id);
-
-    int rc = sqlite3_step(stmt);
-
-    sqlite3_finalize(stmt);
-
-    return rc != SQLITE_DONE;
-}
-
-controller_t*
-controller_create(void)
-{
-    controller_t *new_controller = malloc(sizeof(*new_controller));
-    new_controller->id = 0;
-    uuid_generate(new_controller->uid);
-
-    strncpy(new_controller->name, global_config.name, MAX_NAME_LENGTH);
-    new_controller->name[MAX_NAME_LENGTH] = '\0';
-
-    new_controller->command_port = 0;
-
-    new_controller->relays = malloc(sizeof(relay_t) * global_config.relay_count);
-    uint8_t i;
-    for(i = 0; i < global_config.relay_count; ++i)
-    {
-        new_controller->relays[i] = relay_load(i);
-        if(!new_controller->relays[i])
-        {
-            new_controller->relays[i] = relay_create(i);
-            relay_save(new_controller->relays[i]);
-        }
-    }
-
-    return new_controller;
-}
-
-void
-controller_set_name(controller_t *controller, const char *name)
-{
-    strncpy(controller->name, name, MAX_NAME_LENGTH);
-    controller->name[MAX_NAME_LENGTH] = '\0';
-}
-
-void
-controller_free(controller_t *controller)
-{
-    for(int i = 0; i < global_config.relay_count; ++i)
-    {
-        relay_free(controller->relays[i]);
-    }
-    free(controller->relays);
-    free(controller);
-}
-
-void
-controller_debug(controller_t *controller)
-{
-    if(controller == NULL)
-    {
-        LOGGER_DEBUG("controller is NULL\n");
-        return;
-    }
-    char uuid_str[37];
-    uuid_unparse(controller->uid, uuid_str);
-    LOGGER_DEBUG("(1/3) %s @ %p\n", uuid_str, (void*)controller);
-    LOGGER_DEBUG("(2/3) name: %s\n", controller->name);
-    LOGGER_DEBUG("(3/3) relays @ %p:\n", (void*)controller->relays);
-    for(int i = 0; i < global_config.relay_count; ++i)
-    {
-        relay_debug(controller->relays[i]);
-    }
-}
diff --git a/src/models/junction_relay_schedule.c b/src/models/junction_relay_schedule.c
deleted file mode 100644
index 8d623c0..0000000
--- a/src/models/junction_relay_schedule.c
+++ /dev/null
@@ -1,102 +0,0 @@
-#include <stdlib.h>
-#include <stdint.h>
-#include <stddef.h>
-#include <string.h>
-
-#include <models/junction_relay_schedule.h>
-#include <logger.h>
-#include <macros.h>
-#include <database.h>
-
-int
-junction_relay_schedule_insert(uint8_t weekday, int relay_id, int schedule_id)
-{
-    int rc;
-    sqlite3_stmt *stmt;
-
-    sqlite3_prepare_v2(global_database, "INSERT INTO junction_relay_schedule(weekday, schedule_id, relay_id) values (?1, ?2, ?3);", -1, &stmt, NULL);
-
-    sqlite3_bind_int(stmt, 1, weekday);
-    sqlite3_bind_int(stmt, 2, schedule_id);
-    sqlite3_bind_int(stmt, 3, relay_id);
-
-    rc = sqlite3_step(stmt);
-    if (rc != SQLITE_DONE)
-    {
-        LOGGER_ERR("error inserting data: %s\n", sqlite3_errmsg(global_database));
-        return false;
-    }
-
-    sqlite3_finalize(stmt);
-
-    return true;
-}
-
-int
-junction_relay_schedule_insert_weekdays(int relay_id, int *schedule_ids)
-{
-    int rc;
-    sqlite3_stmt *stmt;
-
-    static const char query_base[] = "INSERT INTO junction_relay_schedule (weekday, schedule_id, relay_id) VALUES";
-    static const char query_extender[] = " (?, ?, ?)";
-
-    size_t query_len = STRLEN(query_base) + (7 * (STRLEN(query_extender) + 1)) + 1;
-    char *query = malloc(sizeof(char) * query_len + 1);
-    strncpy(query, query_base, query_len);
-    query_len -= STRLEN(query_base);
-    for(int i = 0; i < 7; ++i)
-    {
-        strncat(query, query_extender, query_len);
-        query_len -= STRLEN(query_extender);
-        char *query_divider = (i < 7 - 1) ? "," : ";";
-        strncat(query, query_divider, query_len);
-        query_len -= 1;
-    }
-
-    sqlite3_prepare_v2(global_database, query, -1, &stmt, NULL);
-
-    for(int i = 0; i < 7; ++i)
-    {
-        sqlite3_bind_int(stmt, i * 3 + 1, i);
-        sqlite3_bind_int(stmt, i * 3 + 2, schedule_ids[i]);
-        sqlite3_bind_int(stmt, i * 3 + 3, relay_id);
-    }
-
-    rc = sqlite3_step(stmt);
-    if (rc != SQLITE_DONE)
-    {
-        LOGGER_ERR("error inserting data: %s", sqlite3_errmsg(global_database));
-        return false;
-    }
-
-    sqlite3_finalize(stmt);
-
-    return true;
-}
-
-int
-junction_relay_schedule_remove_for_relay(int relay_id)
-{
-    sqlite3_stmt *stmt;
-    int rc;
-
-    sqlite3_prepare_v2(global_database, "DELETE FROM junction_relay_schedule WHERE relay_id=?1;", -1, &stmt, NULL);
-    sqlite3_bind_int(stmt, 1, relay_id);
-    rc = sqlite3_step(stmt);
-    sqlite3_finalize(stmt);
-
-    return rc == SQLITE_DONE;
-}
-
-
-int*
-junction_relay_schedule_get_relay_ids_with_schedule(int schedule_id)
-{
-    sqlite3_stmt *stmt;
-
-    sqlite3_prepare_v2(global_database, "SELECT DISTINCT relay_id FROM junction_relay_schedule WHERE schedule_id=?1;", -1, &stmt, NULL);
-    sqlite3_bind_int(stmt, 1, schedule_id);
-
-    return database_helper_get_ids(stmt);
-}
diff --git a/src/models/period.c b/src/models/period.c
deleted file mode 100644
index 8ad53c4..0000000
--- a/src/models/period.c
+++ /dev/null
@@ -1,37 +0,0 @@
-#include <stdlib.h>
-
-#include <logger.h>
-#include <constants.h>
-#include <models/period.h>
-
-int
-period_includes_time(period_t period, struct tm *time_struct)
-{
-    uint16_t start = period.start;
-    uint16_t end = period.end;
-
-    time_t timestamp = time_struct->tm_hour * 60;
-    timestamp += time_struct->tm_min;
-
-    // "normal" timespan
-    if(start < end)
-    {
-        if(start <= timestamp && end > timestamp)
-        {
-            return 1;
-        }
-        return 0;
-    }
-
-    // timespan goes through 00:00
-    if(end < start)
-    {
-        if(start >= timestamp && end < timestamp)
-        {
-            return 1;
-        }
-        return 0;
-    }
-
-    return 0;
-}
diff --git a/src/models/relay.c b/src/models/relay.c
deleted file mode 100644
index 38c3aa0..0000000
--- a/src/models/relay.c
+++ /dev/null
@@ -1,293 +0,0 @@
-#include <stdlib.h>
-#include <string.h>
-#include <uuid/uuid.h>
-
-#include <logger.h>
-#include <helpers.h>
-#include <database.h>
-#include <models/relay.h>
-#include <models/junction_relay_schedule.h>
-
-static int
-db_update_insert(relay_t *relay, sqlite3_stmt *stmt)
-{
-    LOGGER_DEBUG("saving relay '%s' into database (id: %d)\n", relay->name, relay->id);
-    int rc;
-
-    sqlite3_bind_int(stmt, 1, relay->id);
-    sqlite3_bind_int(stmt, 2, relay->number);
-    sqlite3_bind_text(stmt, 3, relay->name, -1, SQLITE_STATIC);
-
-    rc = sqlite3_step(stmt);
-
-    sqlite3_finalize(stmt);
-
-    return rc != SQLITE_DONE;
-}
-static relay_t*
-relay_db_select_mapper(sqlite3_stmt *stmt)
-{
-    relay_t *new_relay = malloc(sizeof(relay_t));
-    new_relay->is_on = 0;
-
-    for(int i = 0; i < sqlite3_column_count(stmt); i++)
-    {
-        const char *name = sqlite3_column_name(stmt, i);
-        switch(name[0])
-        {
-            case 'i':
-                new_relay->id = sqlite3_column_int(stmt, i);
-                break;
-            case 'n':
-                switch(name[1])
-                {
-                    case 'a': // name
-                        strncpy(new_relay->name, (const char*)sqlite3_column_text(stmt, i), 127);
-                        break;
-                    case 'u': // number
-                        new_relay->number = sqlite3_column_int(stmt, i);
-                        break;
-                    default:
-                        break;
-                }
-                break;
-            default: // ignore columns not implemented
-                break;
-        }
-    }
-    
-    memset(new_relay->schedules, 0, sizeof(schedule_t*) * 7);
-    relay_reload_schedules(new_relay);
-
-    new_relay->is_on = -1;
-    new_relay->pulse_timer = 0;
-    new_relay->sent_to_broker = 0;
-
-    return new_relay;
-}
-
-static relay_t**
-relay_db_select(sqlite3_stmt *stmt)
-{
-    relay_t **all_relays = malloc(sizeof(relay_t*));
-
-    int row = 0;
-
-    while(true)
-    {
-        int s;
-
-        s = sqlite3_step(stmt);
-        if (s == SQLITE_ROW)
-        {
-            relay_t *new_relay = relay_db_select_mapper(stmt);
-            row++;
-
-            all_relays = (relay_t**)realloc(all_relays, sizeof(relay_t*) * (row + 1));
-            all_relays[row - 1] = new_relay;
-        }
-        else
-        {
-            if(s == SQLITE_DONE)
-            {
-                break;
-            }
-            else
-            {
-                LOGGER_ERR("error selecting relays from database: %s\n", sqlite3_errstr(s));
-                break;
-            }
-        }
-    }
-    sqlite3_finalize(stmt);
-    all_relays[row] = NULL;
-    return all_relays;
-}
-
-int
-relay_save(relay_t *relay)
-{
-    int opened_transaction = database_transaction_begin();
-     
-    sqlite3_stmt *stmt;
-    if(relay->id)
-    {
-        sqlite3_prepare_v2(global_database, "UPDATE relays set number = ?2, name = ?3 WHERE id = ?1;", -1, &stmt, NULL);
-    }
-    else
-    {
-        sqlite3_prepare_v2(global_database, "INSERT INTO relays(number, name) values (?2, ?3);", -1, &stmt, NULL);
-    }
-
-    int result = db_update_insert(relay, stmt);
-
-    if(result)
-    {
-        if(relay->id)
-        {
-            LOGGER_ERR("error inserting data: %s\n", sqlite3_errmsg(global_database));
-        }
-        else
-        {
-            LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database));
-        }
-
-        if(opened_transaction)
-        {
-            database_transaction_rollback();
-        }
-    }
-    else
-    {
-        if(relay->id == 0)
-        {
-            relay->id = sqlite3_last_insert_rowid(global_database);
-            LOGGER_DEBUG("new relay - new id: %d\n", relay->id);
-        }
-
-        LOGGER_DEBUG("cleaning relay_schedule junction\n");
-        junction_relay_schedule_remove_for_relay(relay->id);
-
-        LOGGER_DEBUG("rebuilding relay_schedule junction\n");
-        int schedule_ids[7];
-        for(int i = 0; i < 7; ++i)
-        {
-            schedule_ids[i] = relay->schedules[i]->id;
-        }
-        junction_relay_schedule_insert_weekdays(relay->id, schedule_ids);
-
-        if(opened_transaction)
-        {
-            database_transaction_commit();
-        }
-    }
-
-    return result;
-}
-
-
-relay_t*
-relay_create(uint8_t number)
-{
-    relay_t *new_relay = malloc(sizeof(relay_t));
-
-    new_relay->id = 0;
-    new_relay->number = number;
-    new_relay->name[0] = '\0';
-
-    new_relay->is_on = -1;
-    new_relay->pulse_timer = 0;
-    new_relay->sent_to_broker = 0;
-
-    uuid_t off_id;
-    memset(off_id, 0, sizeof(uuid_t));
-    memcpy(off_id, "off", 3);
-
-    for(int i = 0; i < 7; ++i)
-    {
-        new_relay->schedules[i] = schedule_get_by_uid(off_id);
-    }
-
-    return new_relay;
-}
-
-relay_t*
-relay_load(uint8_t number)
-{
-    sqlite3_stmt *stmt;
-
-    sqlite3_prepare_v2(global_database, "SELECT * FROM relays WHERE number = ?1;", -1, &stmt, NULL);
-    sqlite3_bind_int(stmt, 1, number);
-
-    relay_t **sql_result = relay_db_select(stmt);
-
-    relay_t *result = sql_result[0];
-    free(sql_result);
-
-    return result;
-}
-
-void
-relay_reload_schedules(relay_t *relay)
-{
-    schedule_t **schedules = schedule_get_relay_weekdays(relay->id);
-
-    uuid_t off_id;
-    memset(off_id, 0, sizeof(uuid_t));
-    memcpy(off_id, "off", 3);
-
-    int fill_with_off = 0;
-    for(int i = 0; i < 7; ++i)
-    {
-        if(schedules[i] == NULL || fill_with_off)
-        {
-            LOGGER_WARNING("got only %d/7 schedules for relay_id %d\n", i, relay->id);
-            relay->schedules[i] = schedule_get_by_uid(off_id);
-
-            fill_with_off = 1;
-        }
-        else
-        {
-            if(relay->schedules[i])
-            {
-                schedule_free(relay->schedules[i]);
-            }
-            relay->schedules[i] = schedules[i];
-        }
-    }
-
-    free(schedules); // don't free list, because contents are kept in relay->schedules
-}
-
-void
-relay_set_name(relay_t *relay, const char *name)
-{
-    strncpy(relay->name, name, MAX_NAME_LENGTH);
-    relay->name[MAX_NAME_LENGTH] = '\0';
-}
-
-int
-relay_is_on_schedule(relay_t *relay, struct tm *time_struct)
-{
-    schedule_t *schedule = relay->schedules[helper_get_weekday(time_struct)];
-    if(schedule->periods_count == 0)
-    {
-        return 0;
-    }
-
-    for(uint16_t i = 0; i < schedule->periods_count; ++i)
-    {
-        if(period_includes_time(schedule->periods[i], time_struct))
-        {
-            return 1;
-        }
-    }
-    return 0;
-}
-
-void
-relay_debug(relay_t *relay)
-{
-    if(relay == NULL)
-    {
-        LOGGER_DEBUG("relay is NULL\n");
-        return;
-    }
-    LOGGER_DEBUG("(1/3) %3d @ %p\n", relay->number, (void*)relay);
-    LOGGER_DEBUG("(2/3) id: %3d; name: %s\n", relay->id, relay->name);
-    LOGGER_DEBUG("(3/3) schedules @ %p:\n", (void*)relay->schedules);
-    for(int i = 0; i < 7; ++i)
-    {
-        schedule_debug(relay->schedules[i]);
-    }
-}
-
-void
-relay_free(relay_t *relay)
-{
-    for(int i = 0; i < 7; ++i)
-    {
-        schedule_free(relay->schedules[i]);
-    }
-    free(relay);
-}
diff --git a/src/models/schedule.c b/src/models/schedule.c
deleted file mode 100644
index 4c279c9..0000000
--- a/src/models/schedule.c
+++ /dev/null
@@ -1,322 +0,0 @@
-#include <stdlib.h>
-#include <string.h>
-
-#include <logger.h>
-#include <database.h>
-#include <models/schedule.h>
-#include <models/junction_relay_schedule.h>
-
-static int
-db_update_insert(schedule_t *schedule, sqlite3_stmt *stmt)
-{
-    char uuid_str[UUID_STR_LEN];
-    uuid_unparse(schedule->uid, uuid_str);
-    LOGGER_DEBUG("saving schedule '%s' into database (id: %d)\n", uuid_str, schedule->id);
-
-    int rc;
-    uint16_t *periods_blob = schedule_periods_to_blob(schedule);
-    int blob_size = (int)sizeof(uint16_t) * ((periods_blob[0] * 2) + 1);
-
-    sqlite3_bind_int(stmt, 1, schedule->id);
-    sqlite3_bind_blob(stmt, 2, schedule->uid, sizeof(uuid_t), SQLITE_STATIC);
-    sqlite3_bind_blob(stmt, 3, periods_blob, blob_size, SQLITE_STATIC);
-
-    rc = sqlite3_step(stmt);
-
-    sqlite3_finalize(stmt);
-
-    free(periods_blob);
-
-    return rc != SQLITE_DONE;
-}
-static schedule_t*
-schedule_db_select_mapper(sqlite3_stmt *stmt)
-{
-    const uint16_t *periods_blob;
-    schedule_t *new_schedule = malloc(sizeof(schedule_t));
-    for(int i = 0; i < sqlite3_column_count(stmt); i++)
-    {
-        const char *name = sqlite3_column_name(stmt, i);
-        switch(name[0])
-        {
-            case 'i': // id
-                new_schedule->id = sqlite3_column_int(stmt, i);
-                break;
-            case 'p': // periods
-                periods_blob = sqlite3_column_blob(stmt, i);
-                new_schedule->periods_count = periods_blob[0];
-                new_schedule->periods = malloc(sizeof(period_t) * periods_blob[0]);
-
-                for(int i = 0; i < periods_blob[0]; ++i)
-                {
-                    new_schedule->periods[i].start = periods_blob[(i * 2) + 1];
-                    new_schedule->periods[i].end   = periods_blob[(i * 2) + 2];
-                }
-
-                break;
-            case 'u': // uid
-                uuid_copy(new_schedule->uid, (const unsigned char*)sqlite3_column_blob(stmt, i));
-                break;
-            default: // ignore columns not implemented
-                break;
-        }
-    }
-    return new_schedule;
-}
-
-static schedule_t**
-schedule_db_select(sqlite3_stmt *stmt)
-{
-    schedule_t **all_schedules = malloc(sizeof(schedule_t*));
-
-    int row = 0;
-
-    for(;;)
-    {
-        int s;
-
-        s = sqlite3_step(stmt);
-        if (s == SQLITE_ROW)
-        {
-            schedule_t *new_schedule = schedule_db_select_mapper(stmt);
-            row++;
-
-            all_schedules = (schedule_t**)realloc(all_schedules, sizeof(schedule_t*) * (row + 1));
-            all_schedules[row - 1] = new_schedule;
-        }
-        else
-        {
-            if(s == SQLITE_DONE)
-            {
-                break;
-            }
-            else
-            {
-                LOGGER_ERR("error selecting schedules from database: %s\n", sqlite3_errstr(s));
-                break;
-            }
-        }
-    }
-    sqlite3_finalize(stmt);
-    all_schedules[row] = NULL;
-    return all_schedules;
-}
-
-int
-schedule_save(schedule_t *schedule)
-{
-    int opened_transaction = database_transaction_begin();
-     
-    sqlite3_stmt *stmt;
-    if(schedule->id)
-    {
-        sqlite3_prepare_v2(global_database, "UPDATE schedules SET uid = ?2, periods = ?3 WHERE id=?1;", -1, &stmt, NULL);
-    }
-    else
-    {
-        sqlite3_prepare_v2(global_database, "INSERT INTO schedules(uid, periods) values (?2, ?3);", -1, &stmt, NULL);
-    }
-
-    int result = db_update_insert(schedule, stmt);
-
-    if(result)
-    {
-        if(schedule->id)
-        {
-            LOGGER_ERR("error inserting data: %s\n", sqlite3_errmsg(global_database));
-        }
-        else
-        {
-            LOGGER_ERR("error updating data: %s\n", sqlite3_errmsg(global_database));
-        }
-
-        if(opened_transaction)
-        {
-            database_transaction_rollback();
-        }
-    }
-    else
-    {
-        if(!schedule->id)
-        {
-            schedule->id = sqlite3_last_insert_rowid(global_database);
-        }
-
-        if(opened_transaction)
-        {
-            database_transaction_commit();
-        }
-    }
-
-    return result;
-}
-
-schedule_t**
-schedule_get_relay_weekdays(int relay_id)
-{
-    LOGGER_DEBUG("getting schedules [relay_id=%d] from database\n", relay_id);
-    sqlite3_stmt *stmt;
-
-    sqlite3_prepare_v2(global_database, "SELECT schedules.* FROM schedules INNER JOIN junction_relay_schedule ON schedules.id == junction_relay_schedule.schedule_id WHERE junction_relay_schedule.relay_id = ?1 ORDER BY junction_relay_schedule.weekday ASC", -1, &stmt, NULL);
-    sqlite3_bind_int(stmt, 1, relay_id);
-
-    return schedule_db_select(stmt);
-}
-
-schedule_t*
-schedule_get_by_uid(uuid_t uid)
-{
-    char uuid_str[UUID_STR_LEN];
-    schedule_uid_unparse(uid, uuid_str);
-    LOGGER_DEBUG("getting schedule [uid=%s] from database\n", uuid_str);
-    sqlite3_stmt *stmt;
-
-    sqlite3_prepare_v2(global_database, "SELECT * FROM schedules WHERE uid = ?1;", -1, &stmt, NULL);
-    sqlite3_bind_blob(stmt, 1, uid, sizeof(uuid_t), SQLITE_STATIC);
-
-    schedule_t **sql_result = schedule_db_select(stmt);
-
-    schedule_t *result = sql_result[0];
-    free(sql_result);
-
-    return result;
-}
-
-schedule_t*
-schedule_create(uuid_t uid, uint16_t length, uint16_t *periods_blob)
-{
-    schedule_t *new_schedule = malloc(sizeof(schedule_t));
-
-    new_schedule->id = 0;
-    memmove(new_schedule->uid, uid, sizeof(uuid_t));
-
-    new_schedule->periods_count = length;
-    new_schedule->periods = NULL;
-
-    if(length)
-    {
-        new_schedule->periods = malloc(sizeof(period_t) * length);
-
-        for(uint16_t i = 0; i < length; ++i)
-        {
-            new_schedule->periods[i].start = periods_blob[0 + (i * 2)];
-            new_schedule->periods[i].end = periods_blob[1 + (i * 2)];
-        }
-    }
-
-    return new_schedule;
-}
-
-uint16_t*
-schedule_periods_to_blob(schedule_t *schedule)
-{
-    uint16_t *periods_blob = malloc(sizeof(uint16_t) * ((2 * schedule->periods_count) + 1));
-    periods_blob[0] = schedule->periods_count;
-
-    for(uint16_t i = 0; i < schedule->periods_count; ++i)
-    {
-
-        periods_blob[1 + (i * 2)] = schedule->periods[i].start;
-        periods_blob[2 + (i * 2)] = schedule->periods[i].end;
-    }
-
-    return periods_blob;
-}
-
-int
-schedule_uid_parse(const char *uid_str, uuid_t result)
-{
-    if(strcmp("off", uid_str) == 0)
-    {
-        memset(result, 0, sizeof(uuid_t));
-        memcpy(result, "off", 3);
-        return 0;
-    }
-    if(strcmp("on", uid_str) == 0)
-    {
-        memset(result, 0, sizeof(uuid_t));
-        memcpy(result, "on", 2);
-        return 0;
-    }
-
-    if(uuid_parse(uid_str, result))
-    {
-        return 1;
-    }
-    return 0;
-}
-
-void
-schedule_uid_unparse(const uuid_t uid, char *result)
-{
-    uuid_t tmp_uuid;
-
-    memset(tmp_uuid, 0, sizeof(uuid_t));
-    memcpy(tmp_uuid, "off", 3);
-    if(uuid_compare(uid, tmp_uuid) == 0)
-    {
-        strcpy(result, "off");
-        return;
-    }
-
-    memset(tmp_uuid, 0, sizeof(uuid_t));
-    memcpy(tmp_uuid, "on", 2);
-    if(uuid_compare(uid, tmp_uuid) == 0)
-    {
-        strcpy(result, "on");
-        return;
-    }
-
-    uuid_unparse(uid, result);
-}
-
-void
-schedule_free(schedule_t *schedule)
-{
-    free(schedule->periods);
-    free(schedule);
-}
-
-void
-schedule_free_list(schedule_t **schedules)
-{
-    for(int i = 0; schedules[i] != NULL; ++i)
-    {
-        schedule_free(schedules[i]);
-    }
-    free(schedules);
-}
-
-void
-schedule_debug(schedule_t *schedule)
-{
-    if(schedule == NULL)
-    {
-        LOGGER_DEBUG("schedule is NULL\n");
-        return;
-    }
-    char uuid_str[UUID_STR_LEN];
-    schedule_uid_unparse(schedule->uid, uuid_str);
-    LOGGER_DEBUG("(1/3) %s @ %p\n", uuid_str, (void*)schedule);
-    LOGGER_DEBUG("(2/3) id: %3d; period count: %3d\n", schedule->id, schedule->periods_count);
-
-    // one block: "HH:MM-HH:MM, " --> size: 13 (14 with '\0')
-    char *periods_debug_str = malloc(sizeof(char) * ((schedule->periods_count * 13) + 1));
-    periods_debug_str[0] = '\0';
-
-    for(uint16_t i = 0; i < schedule->periods_count; ++i)
-    {
-        sprintf(
-            periods_debug_str + (13 * i),
-            "%02d:%02d-%02d:%02d, ",
-            schedule->periods[i].start / 60,
-            schedule->periods[i].start % 60,
-            schedule->periods[i].end / 60,
-            schedule->periods[i].end % 60
-        );
-    }
-
-    LOGGER_DEBUG("(3/3) periods: %s\n", periods_debug_str);
-
-    free(periods_debug_str);
-}
diff --git a/src/runners/test.c b/src/runners/test.c
deleted file mode 100644
index 2eec714..0000000
--- a/src/runners/test.c
+++ /dev/null
@@ -1,35 +0,0 @@
-#include <unistd.h>   
-
-#include <runners.h>
-#include <logger.h>
-#include <drivers.h>
-#include <drivers.h>
-
-void
-runner_test()
-{
-    // from x down to 0 to turn all relays off in the end
-    for(uint_fast8_t i = 0; i < global_config.relay_count; ++i)
-    {
-        for(int test_run = 2; test_run >= 0; --test_run)
-        {
-            int is_active = test_run % 2;
-            if(global_config.relay_configs[i].inverted)
-            {
-                is_active = !is_active;
-            }
-            switch(global_config.relay_configs[i].driver)
-            {
-                case RELAY_DRIVER_GPIO:
-                    driver_gpio_set(global_config.relay_configs[i].pin, is_active);
-                    break;
-                case RELAY_DRIVER_PIFACE:
-                    driver_piface_set(global_config.relay_configs[i].pin, is_active);
-                    break;
-                default:
-                    LOGGER_WARNING("relay %d is not using a driver\n", i);
-            }
-            sleep(1);
-        }
-    }
-}
diff --git a/vendor/argparse.c b/vendor/argparse.c
deleted file mode 100644
index ec86bba..0000000
--- a/vendor/argparse.c
+++ /dev/null
@@ -1,384 +0,0 @@
-/**
- * Copyright (C) 2012-2015 Yecheng Fu <cofyc.jackson at gmail dot com>
- * All rights reserved.
- *
- * Use of this source code is governed by a MIT-style license that can be found
- * in the LICENSE file.
- */
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <assert.h>
-#include <errno.h>
-#include "argparse.h"
-
-#define OPT_UNSET 1
-#define OPT_LONG  (1 << 1)
-
-static const char *
-prefix_skip(const char *str, const char *prefix)
-{
-    size_t len = strlen(prefix);
-    return strncmp(str, prefix, len) ? NULL : str + len;
-}
-
-static int
-prefix_cmp(const char *str, const char *prefix)
-{
-    for (;; str++, prefix++)
-        if (!*prefix) {
-            return 0;
-        } else if (*str != *prefix) {
-            return (unsigned char)*prefix - (unsigned char)*str;
-        }
-}
-
-static void
-argparse_error(struct argparse *self, const struct argparse_option *opt,
-               const char *reason, int flags)
-{
-    (void)self;
-    if (flags & OPT_LONG) {
-        fprintf(stderr, "error: option `--%s` %s\n", opt->long_name, reason);
-    } else {
-        fprintf(stderr, "error: option `-%c` %s\n", opt->short_name, reason);
-    }
-    exit(1);
-}
-
-static int
-argparse_getvalue(struct argparse *self, const struct argparse_option *opt,
-                  int flags)
-{
-    const char *s = NULL;
-    if (!opt->value)
-        goto skipped;
-    switch (opt->type) {
-    case ARGPARSE_OPT_BOOLEAN:
-        if (flags & OPT_UNSET) {
-            *(int *)opt->value = *(int *)opt->value - 1;
-        } else {
-            *(int *)opt->value = *(int *)opt->value + 1;
-        }
-        if (*(int *)opt->value < 0) {
-            *(int *)opt->value = 0;
-        }
-        break;
-    case ARGPARSE_OPT_BIT:
-        if (flags & OPT_UNSET) {
-            *(int *)opt->value &= ~opt->data;
-        } else {
-            *(int *)opt->value |= opt->data;
-        }
-        break;
-    case ARGPARSE_OPT_STRING:
-        if (self->optvalue) {
-            *(const char **)opt->value = self->optvalue;
-            self->optvalue             = NULL;
-        } else if (self->argc > 1) {
-            self->argc--;
-            *(const char **)opt->value = *++self->argv;
-        } else {
-            argparse_error(self, opt, "requires a value", flags);
-        }
-        break;
-    case ARGPARSE_OPT_INTEGER:
-        errno = 0;
-        if (self->optvalue) {
-            *(int *)opt->value = strtol(self->optvalue, (char **)&s, 0);
-            self->optvalue     = NULL;
-        } else if (self->argc > 1) {
-            self->argc--;
-            *(int *)opt->value = strtol(*++self->argv, (char **)&s, 0);
-        } else {
-            argparse_error(self, opt, "requires a value", flags);
-        }
-        if (errno)
-            argparse_error(self, opt, strerror(errno), flags);
-        if (s[0] != '\0')
-            argparse_error(self, opt, "expects an integer value", flags);
-        break;
-    case ARGPARSE_OPT_FLOAT:
-        errno = 0;
-        if (self->optvalue) {
-            *(float *)opt->value = strtof(self->optvalue, (char **)&s);
-            self->optvalue       = NULL;
-        } else if (self->argc > 1) {
-            self->argc--;
-            *(float *)opt->value = strtof(*++self->argv, (char **)&s);
-        } else {
-            argparse_error(self, opt, "requires a value", flags);
-        }
-        if (errno)
-            argparse_error(self, opt, strerror(errno), flags);
-        if (s[0] != '\0')
-            argparse_error(self, opt, "expects a numerical value", flags);
-        break;
-    default:
-        assert(0);
-    }
-
-skipped:
-    if (opt->callback) {
-        return opt->callback(self, opt);
-    }
-
-    return 0;
-}
-
-static void
-argparse_options_check(const struct argparse_option *options)
-{
-    for (; options->type != ARGPARSE_OPT_END; options++) {
-        switch (options->type) {
-        case ARGPARSE_OPT_END:
-        case ARGPARSE_OPT_BOOLEAN:
-        case ARGPARSE_OPT_BIT:
-        case ARGPARSE_OPT_INTEGER:
-        case ARGPARSE_OPT_FLOAT:
-        case ARGPARSE_OPT_STRING:
-        case ARGPARSE_OPT_GROUP:
-            continue;
-        default:
-            fprintf(stderr, "wrong option type: %d", options->type);
-            break;
-        }
-    }
-}
-
-static int
-argparse_short_opt(struct argparse *self, const struct argparse_option *options)
-{
-    for (; options->type != ARGPARSE_OPT_END; options++) {
-        if (options->short_name == *self->optvalue) {
-            self->optvalue = self->optvalue[1] ? self->optvalue + 1 : NULL;
-            return argparse_getvalue(self, options, 0);
-        }
-    }
-    return -2;
-}
-
-static int
-argparse_long_opt(struct argparse *self, const struct argparse_option *options)
-{
-    for (; options->type != ARGPARSE_OPT_END; options++) {
-        const char *rest;
-        int opt_flags = 0;
-        if (!options->long_name)
-            continue;
-
-        rest = prefix_skip(self->argv[0] + 2, options->long_name);
-        if (!rest) {
-            // negation disabled?
-            if (options->flags & OPT_NONEG) {
-                continue;
-            }
-            // only OPT_BOOLEAN/OPT_BIT supports negation
-            if (options->type != ARGPARSE_OPT_BOOLEAN && options->type !=
-                ARGPARSE_OPT_BIT) {
-                continue;
-            }
-
-            if (prefix_cmp(self->argv[0] + 2, "no-")) {
-                continue;
-            }
-            rest = prefix_skip(self->argv[0] + 2 + 3, options->long_name);
-            if (!rest)
-                continue;
-            opt_flags |= OPT_UNSET;
-        }
-        if (*rest) {
-            if (*rest != '=')
-                continue;
-            self->optvalue = rest + 1;
-        }
-        return argparse_getvalue(self, options, opt_flags | OPT_LONG);
-    }
-    return -2;
-}
-
-int
-argparse_init(struct argparse *self, struct argparse_option *options,
-              const char *const *usages, int flags)
-{
-    memset(self, 0, sizeof(*self));
-    self->options     = options;
-    self->usages      = usages;
-    self->flags       = flags;
-    self->description = NULL;
-    self->epilog      = NULL;
-    return 0;
-}
-
-void
-argparse_describe(struct argparse *self, const char *description,
-                  const char *epilog)
-{
-    self->description = description;
-    self->epilog      = epilog;
-}
-
-int
-argparse_parse(struct argparse *self, int argc, const char **argv)
-{
-    self->argc = argc - 1;
-    self->argv = argv + 1;
-    self->out  = argv;
-
-    argparse_options_check(self->options);
-
-    for (; self->argc; self->argc--, self->argv++) {
-        const char *arg = self->argv[0];
-        if (arg[0] != '-' || !arg[1]) {
-            if (self->flags & ARGPARSE_STOP_AT_NON_OPTION) {
-                goto end;
-            }
-            // if it's not option or is a single char '-', copy verbatim
-            self->out[self->cpidx++] = self->argv[0];
-            continue;
-        }
-        // short option
-        if (arg[1] != '-') {
-            self->optvalue = arg + 1;
-            switch (argparse_short_opt(self, self->options)) {
-            case -1:
-                break;
-            case -2:
-                goto unknown;
-            }
-            while (self->optvalue) {
-                switch (argparse_short_opt(self, self->options)) {
-                case -1:
-                    break;
-                case -2:
-                    goto unknown;
-                }
-            }
-            continue;
-        }
-        // if '--' presents
-        if (!arg[2]) {
-            self->argc--;
-            self->argv++;
-            break;
-        }
-        // long option
-        switch (argparse_long_opt(self, self->options)) {
-        case -1:
-            break;
-        case -2:
-            goto unknown;
-        }
-        continue;
-
-unknown:
-        fprintf(stderr, "error: unknown option `%s`\n", self->argv[0]);
-        argparse_usage(self);
-        exit(1);
-    }
-
-end:
-    memmove(self->out + self->cpidx, self->argv,
-            self->argc * sizeof(*self->out));
-    self->out[self->cpidx + self->argc] = NULL;
-
-    return self->cpidx + self->argc;
-}
-
-void
-argparse_usage(struct argparse *self)
-{
-    if (self->usages) {
-        fprintf(stdout, "Usage: %s\n", *self->usages++);
-        while (*self->usages && **self->usages)
-            fprintf(stdout, "   or: %s\n", *self->usages++);
-    } else {
-        fprintf(stdout, "Usage:\n");
-    }
-
-    // print description
-    if (self->description)
-        fprintf(stdout, "%s\n", self->description);
-
-    fputc('\n', stdout);
-
-    const struct argparse_option *options;
-
-    // figure out best width
-    size_t usage_opts_width = 0;
-    size_t len;
-    options = self->options;
-    for (; options->type != ARGPARSE_OPT_END; options++) {
-        len = 0;
-        if ((options)->short_name) {
-            len += 2;
-        }
-        if ((options)->short_name && (options)->long_name) {
-            len += 2;           // separator ", "
-        }
-        if ((options)->long_name) {
-            len += strlen((options)->long_name) + 2;
-        }
-        if (options->type == ARGPARSE_OPT_INTEGER) {
-            len += strlen("=<int>");
-        }
-        if (options->type == ARGPARSE_OPT_FLOAT) {
-            len += strlen("=<flt>");
-        } else if (options->type == ARGPARSE_OPT_STRING) {
-            len += strlen("=<str>");
-        }
-        len = (len + 3) - ((len + 3) & 3);
-        if (usage_opts_width < len) {
-            usage_opts_width = len;
-        }
-    }
-    usage_opts_width += 4;      // 4 spaces prefix
-
-    options = self->options;
-    for (; options->type != ARGPARSE_OPT_END; options++) {
-        size_t pos = 0;
-        int pad    = 0;
-        if (options->type == ARGPARSE_OPT_GROUP) {
-            fputc('\n', stdout);
-            fprintf(stdout, "%s", options->help);
-            fputc('\n', stdout);
-            continue;
-        }
-        pos = fprintf(stdout, "    ");
-        if (options->short_name) {
-            pos += fprintf(stdout, "-%c", options->short_name);
-        }
-        if (options->long_name && options->short_name) {
-            pos += fprintf(stdout, ", ");
-        }
-        if (options->long_name) {
-            pos += fprintf(stdout, "--%s", options->long_name);
-        }
-        if (options->type == ARGPARSE_OPT_INTEGER) {
-            pos += fprintf(stdout, "=<int>");
-        } else if (options->type == ARGPARSE_OPT_FLOAT) {
-            pos += fprintf(stdout, "=<flt>");
-        } else if (options->type == ARGPARSE_OPT_STRING) {
-            pos += fprintf(stdout, "=<str>");
-        }
-        if (pos <= usage_opts_width) {
-            pad = usage_opts_width - pos;
-        } else {
-            fputc('\n', stdout);
-            pad = usage_opts_width;
-        }
-        fprintf(stdout, "%*s%s\n", pad + 2, "", options->help);
-    }
-
-    // print epilog
-    if (self->epilog)
-        fprintf(stdout, "%s\n", self->epilog);
-}
-
-int
-argparse_help_cb(struct argparse *self, const struct argparse_option *option)
-{
-    (void)option;
-    argparse_usage(self);
-    exit(0);
-}
diff --git a/vendor/argparse.h b/vendor/argparse.h
deleted file mode 100644
index 44ce835..0000000
--- a/vendor/argparse.h
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- * Copyright (C) 2012-2015 Yecheng Fu <cofyc.jackson at gmail dot com>
- * All rights reserved.
- *
- * Use of this source code is governed by a MIT-style license that can be found
- * in the LICENSE file.
- */
-#ifndef ARGPARSE_H
-#define ARGPARSE_H
-
-/* For c++ compatibility */
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <stdint.h>
-
-struct argparse;
-struct argparse_option;
-
-typedef int argparse_callback (struct argparse *self,
-                               const struct argparse_option *option);
-
-enum argparse_flag {
-    ARGPARSE_STOP_AT_NON_OPTION = 1,
-};
-
-enum argparse_option_type {
-    /* special */
-    ARGPARSE_OPT_END,
-    ARGPARSE_OPT_GROUP,
-    /* options with no arguments */
-    ARGPARSE_OPT_BOOLEAN,
-    ARGPARSE_OPT_BIT,
-    /* options with arguments (optional or required) */
-    ARGPARSE_OPT_INTEGER,
-    ARGPARSE_OPT_FLOAT,
-    ARGPARSE_OPT_STRING,
-};
-
-enum argparse_option_flags {
-    OPT_NONEG = 1,              /* disable negation */
-};
-
-/**
- *  argparse option
- *
- *  `type`:
- *    holds the type of the option, you must have an ARGPARSE_OPT_END last in your
- *    array.
- *
- *  `short_name`:
- *    the character to use as a short option name, '\0' if none.
- *
- *  `long_name`:
- *    the long option name, without the leading dash, NULL if none.
- *
- *  `value`:
- *    stores pointer to the value to be filled.
- *
- *  `help`:
- *    the short help message associated to what the option does.
- *    Must never be NULL (except for ARGPARSE_OPT_END).
- *
- *  `callback`:
- *    function is called when corresponding argument is parsed.
- *
- *  `data`:
- *    associated data. Callbacks can use it like they want.
- *
- *  `flags`:
- *    option flags.
- */
-struct argparse_option {
-    enum argparse_option_type type;
-    const char short_name;
-    const char *long_name;
-    void *value;
-    const char *help;
-    argparse_callback *callback;
-    intptr_t data;
-    int flags;
-};
-
-/**
- * argpparse
- */
-struct argparse {
-    // user supplied
-    const struct argparse_option *options;
-    const char *const *usages;
-    int flags;
-    const char *description;    // a description after usage
-    const char *epilog;         // a description at the end
-    // internal context
-    int argc;
-    const char **argv;
-    const char **out;
-    int cpidx;
-    const char *optvalue;       // current option value
-};
-
-// built-in callbacks
-int argparse_help_cb(struct argparse *self,
-                     const struct argparse_option *option);
-
-// built-in option macros
-#define OPT_END()        { ARGPARSE_OPT_END, 0, NULL, NULL, 0, NULL, 0, 0 }
-#define OPT_BOOLEAN(...) { ARGPARSE_OPT_BOOLEAN, __VA_ARGS__ }
-#define OPT_BIT(...)     { ARGPARSE_OPT_BIT, __VA_ARGS__ }
-#define OPT_INTEGER(...) { ARGPARSE_OPT_INTEGER, __VA_ARGS__ }
-#define OPT_FLOAT(...)   { ARGPARSE_OPT_FLOAT, __VA_ARGS__ }
-#define OPT_STRING(...)  { ARGPARSE_OPT_STRING, __VA_ARGS__ }
-#define OPT_GROUP(h)     { ARGPARSE_OPT_GROUP, 0, NULL, NULL, h, NULL, 0, 0 }
-#define OPT_HELP()       OPT_BOOLEAN('h', "help", NULL,                 \
-                                     "show this help message and exit", \
-                                     argparse_help_cb, 0, OPT_NONEG)
-
-int argparse_init(struct argparse *self, struct argparse_option *options,
-                  const char *const *usages, int flags);
-void argparse_describe(struct argparse *self, const char *description,
-                       const char *epilog);
-int argparse_parse(struct argparse *self, int argc, const char **argv);
-void argparse_usage(struct argparse *self);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/vendor/confini.c b/vendor/confini.c
deleted file mode 100644
index 25353a7..0000000
--- a/vendor/confini.c
+++ /dev/null
@@ -1,5016 +0,0 @@
-/*  -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
-/*  Please make sure that the TAB width in your editor is set to 4 spaces  */
-
-/**
-
-	@file		confini.c
-	@brief		libconfini functions
-	@author		Stefano Gioffr&eacute;
-	@copyright	GNU General Public License, version 3 or any later version
-	@version	1.14.0
-	@date		2016-2020
-	@see		https://madmurphy.github.io/libconfini
-
-**/
-
-
-           /*/|
-          (_|_)      _ _ _                      __ _       _
-                    | (_) |__   ___ ___  _ __  / _(_)_ __ (_)
-                    | | | '_ \ / __/ _ \| '_ \| |_| | '_ \| |
-                    | | | |_) | (_| (_) | | | |  _| | | | | |
-                    |_|_|_.__/ \___\___/|_| |_|_| |_|_| |_|_|      _ _
-                                                                  ( | )
-                                                                  |/*/
-
-
-
-/**
-
-
-	@def		INIFORMAT_TABLE_AS(_____)
-
-	Content of the table:
-
-	- Bits 1-19: INI syntax
-	- Bits 20-22: INI semantics
-	- Bits 23-24: Human syntax (disabled entries)
-
-
-
-	@typedef	int (* IniStatsHandler) (
-					IniStatistics * statistics,
-					void * user_data
-				)
-
-	@param		statistics
-					A pointer to the #IniStatistics to handle
-	@param		user_data
-					The custom argument previously passed to the caller function
-
-
-
-	@typedef	int (* IniDispHandler) (
-					IniDispatch *dispatch,
-					void * user_data
-				)
-
-	@param		dispatch
-					A pointer to the #IniDispatch to handle
-	@param		user_data
-					The custom argument previously passed to the caller function
-
-
-
-	@typedef	int (* IniStrHandler) (
-					char * ini_string,
-					size_t string_length,
-					size_t string_num,
-					IniFormat format,
-					void * user_data
-				)
-
-	@param		ini_string
-					The INI string to handle
-	@param		string_length
-					The length of the INI string in bytes
-	@param		string_num
-					The unique number that identifies @p ini_string within a
-					sequence of INI strings; it equals zero if @p ini_string is the
-					first or the only member of the sequence
-	@param		format
-					The format of the INI file from which @p ini_string has been extracted
-	@param		user_data
-					The custom argument previously passed to the caller function
-
-
-
-	@typedef	int (* IniSubstrHandler) (
-					const char * ini_string,
-					size_t fragm_offset,
-					size_t fragm_length,
-					size_t fragm_num,
-					IniFormat format,
-					void * user_data
-				)
-
-	@param		ini_string
-					The INI string containing the fragment to handle
-	@param		fragm_offset
-					The offset of the selected fragment in bytes
-	@param		fragm_length
-					The length of the selected fragment in bytes
-	@param		fragm_num
-					The unique number that identifies the selected fragment within a
-					sequence of fragments of @p ini_string; it equals zero if the
-					fragment is the first or the only member of the sequence
-	@param		format
-					The format of the INI file from which @p ini_string has been
-					extracted
-	@param		user_data
-					The custom argument previously passed to the caller function
-
-
-
-	@struct		IniFormat
-
-	@property	IniFormat::delimiter_symbol
-					The key-value delimiter character (ASCII only allowed); if set
-					to `\0`, any space is delimiter
-					(`/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`); if, within the format
-					given, `IniFormat::delimiter_symbol` matches a metacharacter
-					(`'\\'`, `'\''`, `'\"'`), its role as metacharacter will have
-					higher priority than its role as delimiter symbol (i.e., the
-					format will have no key-value delimiter); you may use the
-					#IniDelimiters `enum` for this.
-	@property	IniFormat::case_sensitive
-					If set to `true`, string comparisons will be always
-					case-sensitive.
-	@property	IniFormat::semicolon_marker
-					The rule of the semicolon character (use `enum`
-					#IniCommentMarker for this).
-	@property	IniFormat::hash_marker
-					The rule of the hash character (use `enum` #IniCommentMarker for
-					this).
-	@property	IniFormat::section_paths
-					Defines whether and how the format supports sections (use `enum`
-					#IniSectionPaths for this).
-	@property	IniFormat::multiline_nodes
-					Defines which class of entries are allowed to be multi-line (use
-					`enum` #IniMultiline for this).
-	@property	IniFormat::no_spaces_in_names
-					If set to `true`, key and section names containing spaces (even
-					within quotes) will be rendered as #INI_UNKNOWN. Note that
-					setting #IniFormat::delimiter_symbol to #INI_ANY_SPACE will not
-					automatically set this option to `true` (spaces will still be
-					allowed in section names).
-	@property	IniFormat::no_single_quotes
-					If set to `true`, the single-quote character (`'`) will be
-					considered as a normal character.
-	@property	IniFormat::no_double_quotes
-					If set to `true`, the double-quote character (`"`) will be
-					considered as a normal character.
-	@property	IniFormat::implicit_is_not_empty
-					If set to `true`, implicit keys (see @ref libconfini) will
-					be always dispatched using the values given by the global
-					variables #INI_GLOBAL_IMPLICIT_VALUE and
-					#INI_GLOBAL_IMPLICIT_V_LEN for the fields #IniDispatch::value
-					and to #IniDispatch::v_len respectively; if set to `false`,
-					implicit keys will be considered to be empty keys.
-	@property	IniFormat::do_not_collapse_values
-					If set to `true`, sequences of one or more spaces in values
-					(`/\s+/`) will be dispatched verbatim.
-	@property	IniFormat::preserve_empty_quotes
-					If set to `true`, and if single/double quotes are
-					metacharacters, ensures that, within values, empty strings
-					enclosed between quotes (`""` or `''`) will not be collapsed
-					together with the spaces that surround them. This option is
-					useful for values containing space-delimited arrays, in order to
-					preserve their empty members -- as in, for instance:
-					`coordinates = "" ""`. Note that, in section and key names,
-					empty strings enclosed between quotes are _always_ collapsed
-					together with their surrounding spaces.
-	@property	IniFormat::disabled_after_space
-					If set to `true`, what follows `/[#;]\s/` is allowed to be
-					parsed as a disabled entry.
-	@property	IniFormat::disabled_can_be_implicit
-					If set to `false`, comments that do not contain a key-value
-					delimiter will never be parsed as disabled keys, but always as
-					simple comments (even if the format supports implicit keys).
-
-
-
-	@struct		IniStatistics
-
-	@property	IniStatistics::format
-					The format of the INI file (see #IniFormat)
-	@property	IniStatistics::bytes
-					The size in bytes of the parsed file
-	@property	IniStatistics::members
-					The size in number of members (nodes) of the parsed file -- this
-					number always equals the number of dispatches that will be sent
-					by #load_ini_file(), #load_ini_path() or #strip_ini_cache()
-
-
-
-	@struct		IniDispatch
-
-	@property	IniDispatch::format
-					The format of the INI file (see #IniFormat)
-	@property	IniDispatch::type
-					The dispatch type (see `enum` #IniNodeType)
-	@property	IniDispatch::data
-					#IniDispatch::data can contain a comment, a section path or a
-					key name depending, on #IniDispatch::type; cannot be `NULL`
-	@property	IniDispatch::value
-					It can be the value of a key element, an empty string or it can
-					point to the address pointed by the global variable
-					#INI_GLOBAL_IMPLICIT_VALUE (_the latter is the only case in
-					which `IniDispatch::value` can be `NULL`_)
-	@property	IniDispatch::append_to
-					The current section path; cannot be `NULL`
-	@property	IniDispatch::d_len
-					The length of the string #IniDispatch::data
-	@property	IniDispatch::v_len
-					The length of the string #IniDispatch::value
-	@property	IniDispatch::at_len
-					The length of the string #IniDispatch::append_to
-	@property	IniDispatch::dispatch_id
-					The dispatch number (the first dispatch is number zero)
-
-
-**/
-
-
-
-		/*\
-		|*|
-		|*|     LOCAL ENVIRONMENT
-		|*|    ________________________________
-		\*/
-
-
-
-		/*  PREPROCESSOR PREAMBLE  */
-
-
-/*  String concatenation facilities  */
-#define __PP_CAT__(STR1, STR2) STR1##STR2
-#define __PP_UCAT__(STR1, STR2) STR1##_##STR2
-#define __PP_EVALUCAT__(STR1, STR2) __PP_UCAT__(STR1, STR2)
-
-
-
-		/*  PREPROCESSOR ENVIRONMENT  */
-
-
-#ifndef CONFINI_IO_FLAVOR
-/**
-
-	@brief			The I/O API to use (possibly overridden via
-					`-DCONFINI_IO_FLAVOR=[FLAVOR]`)
-
-	Possible values are `CONFINI_STANDARD` and `CONFINI_POSIX`
-
-**/
-#define CONFINI_IO_FLAVOR CONFINI_STANDARD
-#endif
-
-
-
-		/*  PREPROCESSOR GLUE  */
-
-
-#define _LIBCONFINI_PRIVATE_ITEM_(GROUP, ITEM) \
-	__PP_EVALUCAT__(__PP_CAT__(_LIB, GROUP), __PP_CAT__(ITEM, _))
-#define _LIBCONFINI_CURRENT_FLAVOR_GET_(NAME) \
-	_LIBCONFINI_PRIVATE_ITEM_(CONFINI_IO_FLAVOR, NAME)
-#define _LIBCONFINI_IS_FLAVOR_(NAME) \
-	_LIBCONFINI_PRIVATE_ITEM_(CONFINI_IO_FLAVOR, FLAVOR) == \
-		_LIBCONFINI_PRIVATE_ITEM_(NAME, FLAVOR)
-
-
-
-		/*  AVAILABLE I/O FLAVORS  */
-
-
-/*  `-DCONFINI_IO_FLAVOR=CONFINI_STANDARD` (C99 Standard, default, REQUIRED)  */
-#define _LIBCONFINI_STANDARD_SEOF_FN_(FILEPTR) fseek(FILEPTR, 0, SEEK_END)
-#define _LIBCONFINI_STANDARD_FT_FN_(FILEPTR) ftell(FILEPTR)
-#define _LIBCONFINI_STANDARD_FT_T_ long signed int
-/*  Any unique non-zero integer to identify this I/O API  */
-#define _LIBCONFINI_STANDARD_FLAVOR_ 1
-
-/*  `-DCONFINI_IO_FLAVOR=CONFINI_POSIX`  */
-#define _LIBCONFINI_POSIX_SEOF_FN_(FILEPTR) fseeko(FILEPTR, 0, SEEK_END)
-#define _LIBCONFINI_POSIX_FT_FN_(FILEPTR) ftello(FILEPTR)
-#define _LIBCONFINI_POSIX_FT_T_ off_t
-/*  Any unique non-zero integer to identify this I/O API  */
-#define _LIBCONFINI_POSIX_FLAVOR_ 2
-
-/*  Define `_POSIX_C_SOURCE` macro when `CONFINI_IO_FLAVOR == CONFINI_POSIX`  */
-#if _LIBCONFINI_IS_FLAVOR_(CONFINI_POSIX)
-#ifndef _POSIX_C_SOURCE
-#define _POSIX_C_SOURCE 200809L
-#endif
-#endif
-
-/*  It is possible to add other I/O APIs here. Feel	free to contribute!  */
-
-
-
-		/*  CHECKS  */
-
-
-#if _LIBCONFINI_PRIVATE_ITEM_(CONFINI_IO_FLAVOR, FLAVOR) == 0
-#error Unsupported I/O API defined in macro CONFINI_IO_FLAVOR
-#endif
-
-
-
-		/*  HEADERS  */
-
-#include <stdlib.h>
-#include "confini.h"
-
-
-
-		/*  ALIASES  */
-
-
-#define _LIBCONFINI_FALSE_ 0
-#define _LIBCONFINI_TRUE_ 1
-#define _LIBCONFINI_CHARBOOL_ unsigned char
-#define _LIBCONFINI_SIMPLE_SPACE_ ' '
-#define _LIBCONFINI_HT_ '\t'
-#define _LIBCONFINI_FF_ '\f'
-#define _LIBCONFINI_VT_ '\v'
-#define _LIBCONFINI_CR_ '\r'
-#define _LIBCONFINI_LF_ '\n'
-#define _LIBCONFINI_BACKSLASH_ '\\'
-#define _LIBCONFINI_OPEN_SECTION_ '['
-#define _LIBCONFINI_CLOSE_SECTION_ ']'
-#define _LIBCONFINI_SUBSECTION_ '.'
-#define _LIBCONFINI_SEMICOLON_ ';'
-#define _LIBCONFINI_HASH_ '#'
-#define _LIBCONFINI_DOUBLE_QUOTES_ '"'
-#define _LIBCONFINI_SINGLE_QUOTES_ '\''
-#define _LIBCONFINI_SEEK_EOF_(FILEPTR) \
-	_LIBCONFINI_CURRENT_FLAVOR_GET_(SEOF_FN)(FILEPTR)
-#define _LIBCONFINI_FTELL_(FILEPTR) \
-	_LIBCONFINI_CURRENT_FLAVOR_GET_(FT_FN)(FILEPTR)
-#define _LIBCONFINI_OFF_T_ \
-	_LIBCONFINI_CURRENT_FLAVOR_GET_(FT_T)
-
-
-
-		/*  FUNCTIONAL MACROS AND CONSTANTS  */
-
-
-/*  The character that will replace sequences of one or more spaces (`/\s+/`)  */
-#define _LIBCONFINI_COLLAPSED_ _LIBCONFINI_SIMPLE_SPACE_
-
-
-/*
-
-	These may be any character in theory... But after the left-trim of each node
-	leading spaces work pretty well as metacharacters...
-
-*/
-/*  Internal marker of standard comments  */
-#define _LIBCONFINI_SC_INT_MARKER_ _LIBCONFINI_SIMPLE_SPACE_
-/*  Internal marker of inline comments  */
-#define _LIBCONFINI_IC_INT_MARKER_ _LIBCONFINI_HT_
-
-
-/*
-
-	Checks whether a character can be escaped within a given format
-
-*/
-#define _LIBCONFINI_IS_ESC_CHAR_(CHR, FMT) ( \
-		CHR == _LIBCONFINI_BACKSLASH_ ? \
-			!INIFORMAT_HAS_NO_ESC(FMT) \
-		: CHR == _LIBCONFINI_DOUBLE_QUOTES_ ? \
-			!FMT.no_double_quotes \
-		: \
-			CHR == _LIBCONFINI_SINGLE_QUOTES_ && !FMT.no_single_quotes \
-	)
-
-
-/*
-
-	Checks whether a character represents any marker within a given format
-
-*/
-#define _LIBCONFINI_IS_ANY_MARKER_(CHR, FMT) ( \
-		CHR == _LIBCONFINI_HASH_ ? \
-			FMT.hash_marker != INI_IS_NOT_A_MARKER \
-		: \
-			CHR == _LIBCONFINI_SEMICOLON_ && FMT.semicolon_marker != INI_IS_NOT_A_MARKER \
-	)
-
-
-/*
-
-	Checks whether a character represents any marker except `INI_IGNORE` within a
-	given format
-
-*/
-#define _LIBCONFINI_IS_COM_MARKER_(CHR, FMT) ( \
-		CHR == _LIBCONFINI_HASH_ ? \
-			FMT.hash_marker != INI_IS_NOT_A_MARKER && FMT.hash_marker != INI_IGNORE \
-		: \
-			CHR == _LIBCONFINI_SEMICOLON_ && FMT.semicolon_marker != INI_IS_NOT_A_MARKER && FMT.semicolon_marker != INI_IGNORE \
-	)
-
-
-/*
-
-	Checks whether a character represents a marker of type `INI_DISABLED_OR_COMMENT`
-	within a given format
-
-*/
-#define _LIBCONFINI_IS_DIS_MARKER_(CHR, FMT) ( \
-		CHR == _LIBCONFINI_HASH_ ? \
-			FMT.hash_marker == INI_DISABLED_OR_COMMENT \
-		: \
-			CHR == _LIBCONFINI_SEMICOLON_ && FMT.semicolon_marker == INI_DISABLED_OR_COMMENT \
-	)
-
-
-/*
-
-	Checks whether a character represents a marker of type `INI_IGNORE` within a
-	given format
-
-*/
-#define _LIBCONFINI_IS_IGN_MARKER_(CHR, FMT) ( \
-		CHR == _LIBCONFINI_HASH_ ? \
-			FMT.hash_marker == INI_IGNORE \
-		: \
-			CHR == _LIBCONFINI_SEMICOLON_ && FMT.semicolon_marker == INI_IGNORE \
-	)
-
-
-/*
-
-	Checks whether a pointer is within the range
-	`INI_GLOBAL_IMPLICIT_VALUE >= PTR <= INI_GLOBAL_IMPLICIT_VALUE + INI_GLOBAL_IMPLICIT_V_LEN`
-
-*/
-#define _LIBCONFINI_IMPLICIT_RANGE_(PTR) \
-	(PTR >= INI_GLOBAL_IMPLICIT_VALUE && PTR <= INI_GLOBAL_IMPLICIT_VALUE + INI_GLOBAL_IMPLICIT_V_LEN)
-
-
-/*
-
-	Maybe in the future there will be support for UTF-8 casefold (although probably
-	not -- see "Code considerations" in the Manual), but for now only ASCII...
-
-*/
-#define _LIBCONFINI_CHR_CASEFOLD_(CHR) (CHR > 0x40 && CHR < 0x5b ? CHR | 0x60 : CHR)
-
-
-/*
-
-	Possible depths of `_LIBCONFINI_SPACES_` (see function #is_some_space()).
-
-	Please, consider the following three constants as belonging together to a
-	virtual opaque `enum`.
-
-*/
-#define _LIBCONFINI_WITH_EOL_ -1
-#define _LIBCONFINI_NO_EOL_ 1
-#define _LIBCONFINI_JUST_S_T_ 3
-
-
-/*
-
-	Other constants related to `_LIBCONFINI_SPACES_`
-
-*/
-#define _LIBCONFINI_EOL_IDX_ 0
-#define _LIBCONFINI_SPALEN_ 6
-
-
-/*
-
-	The list of space characters -- do not change its order or its content!
-
-*/
-static const char _LIBCONFINI_SPACES_[_LIBCONFINI_SPALEN_] = {
-	_LIBCONFINI_LF_,
-	_LIBCONFINI_CR_,
-	_LIBCONFINI_VT_,
-	_LIBCONFINI_FF_,
-	_LIBCONFINI_HT_,
-	_LIBCONFINI_SIMPLE_SPACE_
-};
-
-
-/**
-
-	@brief			A list of possible string representations of boolean pairs
-
-	There may be infinite pairs here. Each pair must be organized according to the
-	following order:
-
-	1. Signifier of `false`
-	2. Signifier of `true`
-
-	@note	Everything **must** be lowercase in this list.
-
-**/
-static const char * const INI_BOOLEANS[][2] = {
-	{ "no", "yes" },
-	{ "false", "true" },
-	{ "off", "on" }
-};
-
-
-
-		/*  ABSTRACT UTILITIES  */
-
-
-/**
-
-	@brief			Checks whether a character is a space
-	@param			chr				The target character
-	@param			depth			What is actually considered a space (possible
-									values: `_LIBCONFINI_WITH_EOL_`,
-									`_LIBCONFINI_NO_EOL_`, `_LIBCONFINI_JUST_S_T_`)
-	@return			A boolean: `true` if the character matches, `false` otherwise
-
-**/
-static inline _LIBCONFINI_CHARBOOL_ is_some_space (const char chr, const int8_t depth) {
-	register int8_t idx = depth;
-	while (++idx < _LIBCONFINI_SPALEN_ && chr != _LIBCONFINI_SPACES_[idx]);
-	return idx < _LIBCONFINI_SPALEN_;
-}
-
-
-/**
-
-	@brief			Soft left trim -- does not change the buffer
-	@param			str				The target string
-	@param			offs			The offset where to start the left trim
-	@param			depth			What is actually considered a space (possible
-									values: `_LIBCONFINI_WITH_EOL_`,
-									`_LIBCONFINI_NO_EOL_`, `_LIBCONFINI_JUST_S_T_`)
-	@return			The offset of the first non-space character
-
-**/
-static inline size_t ltrim_s (const char * const str, const size_t offs, const int8_t depth) {
-	register size_t idx = offs;
-	while (is_some_space(str[idx++], depth));
-	return idx - 1;
-}
-
-
-/**
-
-	@brief			Hard left trim -- **does** change the buffer
-	@param			str				The target string
-	@param			offs			The offset where to start the left trim
-	@param			depth			What is actually considered a space (possible
-									values: `_LIBCONFINI_WITH_EOL_`,
-									`_LIBCONFINI_NO_EOL_`, `_LIBCONFINI_JUST_S_T_`)
-	@return			The offset of the first non-space character
-
-**/
-static inline size_t ltrim_h (char * const str, const size_t offs, const int8_t depth) {
-	register size_t idx = offs;
-	while (is_some_space(str[idx], depth)) { str[idx++] = '\0'; }
-	return idx;
-}
-
-
-/**
-
-	@brief			Shifting left trim -- **does** change the buffer
-	@param			str				The target string
-	@param			offs			The offset where to start the left trim
-	@param			depth			What is actually considered a space (possible
-									values: `_LIBCONFINI_WITH_EOL_`,
-									`_LIBCONFINI_NO_EOL_`, `_LIBCONFINI_JUST_S_T_`)
-	@return			The new length of the string
-
-**/
-static inline size_t ltrim_hh (char * const str, const size_t offs, const int8_t depth) {
-	register size_t idx_d = offs, idx_s = offs;
-	while (is_some_space(str[idx_s++], depth));
-	if (--idx_s - idx_d) {
-		while ((str[idx_d++] = str[idx_s++]));
-		for (idx_s = idx_d; str[idx_s]; str[idx_s++] = '\0');
-		return idx_d - 1;
-	}
-	while (str[idx_s++]);
-	return idx_s - 1;
-}
-
-
-/**
-
-	@brief			Soft right trim -- does not change the buffer
-	@param			str				The target string
-	@param			len				The length of the string
-	@param			depth			What is actually considered a space (possible
-									values: `_LIBCONFINI_WITH_EOL_`,
-									`_LIBCONFINI_NO_EOL_`, `_LIBCONFINI_JUST_S_T_`)
-	@return			The length of the string until the last non-space character
-
-**/
-static inline size_t rtrim_s (const char * const str, const size_t len, const int8_t depth) {
-	register size_t idx = len + 1;
-	while (--idx > 0 && is_some_space(str[idx - 1], depth));
-	return idx;
-}
-
-
-/**
-
-	@brief			Hard right trim -- **does** change the buffer
-	@param			str				The target string
-	@param			len				The length of the string
-	@param			depth			What is actually considered a space (possible
-									values: `_LIBCONFINI_WITH_EOL_`,
-									`_LIBCONFINI_NO_EOL_`, `_LIBCONFINI_JUST_S_T_`)
-	@return			The new length of the string
-
-**/
-static inline size_t rtrim_h (char * const str, const size_t len, const int8_t depth) {
-	register size_t idx = len;
-	while (idx > 0 && is_some_space(str[idx - 1], depth)) { str[--idx] = '\0'; }
-	return idx;
-}
-
-
-/**
-
-	@brief			Unescaped soft right trim (right trim of `/(?:\s|\\[\n\r])+$/`)
-					-- does not change the buffer
-	@param			str				The target string
-	@param			len				The length of the string
-	@return			The length of the string until the last non-space character
-
-**/
-static inline size_t urtrim_s (const char * const str, const size_t len) {
-
-	register uint8_t abcd = 1;
-	register size_t idx = len;
-
-
-	/* \                                /\
-	\ */     continue_urtrim:          /* \
-	 \/     ______________________     \ */
-
-
-	if (idx < 1) {
-
-		return idx;
-
-	}
-
-	switch (str[--idx]) {
-
-		case _LIBCONFINI_VT_:
-		case _LIBCONFINI_FF_:
-		case _LIBCONFINI_HT_:
-		case _LIBCONFINI_SIMPLE_SPACE_:
-
-			abcd = 1;
-			goto continue_urtrim;
-
-		case _LIBCONFINI_LF_:
-		case _LIBCONFINI_CR_:
-
-			abcd = 3;
-			goto continue_urtrim;
-
-		case _LIBCONFINI_BACKSLASH_:
-
-			if (abcd >>= 1) {
-
-				goto continue_urtrim;
-
-			}
-
-	}
-
-	return idx + 1;
-
-}
-
-
-/**
-
-	@brief			Converts an ASCII string to lower case
-	@param			str			The target string
-	@return			Nothing
-
-**/
-static inline void string_tolower (char * const str) {
-	for (register char * chrptr = str; *chrptr; chrptr++) {
-		*chrptr = _LIBCONFINI_CHR_CASEFOLD_(*chrptr);
-	}
-}
-
-
-
-		/*  CONCRETE UTILITIES  */
-
-
-/**
-
-	@brief			Unparsed hard left trim (left trim of
-					`/^(?:\s+|\\[\n\r]|''|"")+/`) -- **does** change the buffer
-	@param			srcstr			The target string (it may contain multi-line
-									escape sequences)
-	@param			offs			The offset where to start the left trim
-	@param			format			The format of the INI file
-	@return			The offset of the first non-trivial character
-
-**/
-static inline size_t qultrim_h (char * const srcstr, const size_t offs, const IniFormat format) {
-
-	/*
-
-	Mask `abcd` (8 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Unescaped single quotes are odd right now
-		FLAG_8		Unescaped double quotes are odd right now
-		FLAG_16		We are in an odd sequence of backslashes
-		FLAG_32		Erase the previous character
-		FLAG_64		Erase this character
-		FLAG_128	Continue the loop
-
-	*/
-
-	register uint8_t abcd = (format.no_double_quotes ? 130 : 128) | format.no_single_quotes;
-	size_t idx = offs;
-
-	do {
-
-		abcd	=	!(abcd & 28) && is_some_space(srcstr[idx], _LIBCONFINI_NO_EOL_) ?
-						(abcd & 207) | 64
-					: !(abcd & 12) && (srcstr[idx] == _LIBCONFINI_LF_ || srcstr[idx] == _LIBCONFINI_CR_) ?
-						(
-							abcd & 16 ?
-								(abcd & 239) | 96
-							:
-								abcd | 64
-						)
-					: !(abcd & 25) && srcstr[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						(
-							abcd & 4 ?
-								(abcd & 235) | 96
-							:
-								(abcd & 143) | 4
-						)
-					: !(abcd & 22) && srcstr[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						(
-							abcd & 8 ?
-								(abcd & 231) | 96
-							:
-								(abcd & 159) | 8
-						)
-					: srcstr[idx] == _LIBCONFINI_BACKSLASH_ ?
-						(abcd & 159) ^ 16
-					:
-						abcd & 31;
-
-
-		if (abcd & 32) {
-
-			srcstr[idx - 1] = '\0';
-
-		}
-
-		if (abcd & 64) {
-
-			srcstr[idx] = '\0';
-
-		}
-
-		idx++;
-
-	} while (abcd & 128);
-
-	return abcd & 28 ? idx - 2 : idx - 1;
-
-}
-
-
-/**
-
-	@brief			Soft left trim within an unparsed disabled entry (left trim of
-					`/(?:(?:^|\\?[\n\r])[ \t\v\f]*(?:#(?:[ \t\v\f]|''|"")*)?)+/`)
-					-- does not change the buffer
-	@param			srcstr			The target string (it may contain multi-line
-									escape sequences)
-	@param			offs			The offset where to start the left trim
-	@param			format			The format of the INI file
-	@return			The offset of the first non-trivial character
-
-**/
-static inline size_t dqultrim_s (const char * const srcstr, const size_t offs, const IniFormat format) {
-
-	/*
-
-	Mask `abcd` (7 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Unescaped single quotes are odd right now
-		FLAG_8		Unescaped double quotes are odd right now
-		FLAG_16		We are in an odd sequence of backslashes
-		FLAG_32		A new line has just begun
-		FLAG_64		Continue the left trim
-
-	*/
-
-
-	register uint16_t abcd	=	format.no_single_quotes |
-								(format.no_double_quotes << 1) |
-								96;
-
-	register size_t idx = offs;
-
-	do {
-
-		abcd	=	is_some_space(srcstr[idx], _LIBCONFINI_NO_EOL_) ?
-						(
-							abcd & 28 ?
-								abcd & 63
-							:
-								abcd
-						)
-					: srcstr[idx] == _LIBCONFINI_LF_ || srcstr[idx] == _LIBCONFINI_CR_ ?
-						(
-							abcd & 12 ?
-								(abcd & 47) | 32
-							:
-								(abcd & 111) | 32
-						)
-					: srcstr[idx] == _LIBCONFINI_BACKSLASH_ ?
-						(
-							abcd & 28 ?
-								(abcd & 31) | 16
-							:
-								(abcd & 95) | 16
-						)
-					: (abcd & 32) && _LIBCONFINI_IS_ANY_MARKER_(srcstr[idx], format) ?
-						abcd & 79
-					: !(abcd & 54) && srcstr[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						(abcd & 95) ^ 8
-					: !(abcd & 57) && srcstr[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						(abcd & 95) ^ 4
-					: srcstr[idx] ?
-						abcd & 31
-					:
-						abcd & 19;
-
-
-		idx++;
-
-	} while (abcd & 64);
-
-	return abcd & 28 ? idx - 2 : idx - 1;
-
-}
-
-
-/**
-
-	@brief			Gets the position of the first occurence out of quotes of a
-					given character, stopping after a given number of charcters
-	@param			str				The string where to search
-	@param			chr				The character to to search
-	@param			len				The maximum number of characters to read
-	@param			format			The format of the INI file
-	@return			The offset of the first occurence of @p chr, or @p len if
-					@p chr has not been not found
-
-**/
-static inline size_t getn_metachar_pos (const char * const str, const char chr, const size_t len, const IniFormat format) {
-
-	size_t idx = 0;
-
-	/*
-
-	Mask `abcd` (5 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Unescaped single quotes are odd right now
-		FLAG_8		Unescaped double quotes are odd right now
-		FLAG_16		We are in an odd sequence of backslashes
-
-	*/
-
-	for (
-
-		register uint8_t abcd = (format.no_double_quotes << 1) | format.no_single_quotes;
-
-			idx < len && ((abcd & 12) || (chr ? str[idx] != chr : !is_some_space(str[idx], _LIBCONFINI_WITH_EOL_)));
-
-		abcd	=	str[idx] == _LIBCONFINI_BACKSLASH_ ? abcd ^ 16
-					: !(abcd & 22) && str[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ? abcd ^ 8
-					: !(abcd & 25) && str[idx] == _LIBCONFINI_SINGLE_QUOTES_ ? abcd ^ 4
-					: abcd & 15,
-		idx++
-
-	);
-
-	return idx;
-
-}
-
-
-/**
-
-	@brief			Gets the position of the first occurence out of quotes of a
-					given character
-	@param			str				The string where to search
-	@param			chr				The character to to search
-	@param			format			The format of the INI file
-	@return			The offset of the first occurence of @p chr or the length of
-					@p str if @p chr has not been not found
-
-**/
-static inline size_t get_metachar_pos (const char * const str, const char chr, const IniFormat format) {
-
-	size_t idx = 0;
-
-	/*
-
-	Mask `abcd` (5 bits used):
-
-		--> As in #getn_metachar_pos()
-
-	*/
-
-	for (
-
-		register uint8_t abcd = (format.no_double_quotes << 1) | format.no_single_quotes;
-
-			str[idx] && ((abcd & 12) || (chr ? str[idx] != chr : !is_some_space(str[idx], _LIBCONFINI_NO_EOL_)));
-
-		abcd	=	str[idx] == _LIBCONFINI_BACKSLASH_ ? abcd ^ 16
-					: !(abcd & 22) && str[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ? abcd ^ 8
-					: !(abcd & 25) && str[idx] == _LIBCONFINI_SINGLE_QUOTES_ ? abcd ^ 4
-					: abcd & 15,
-		idx++
-
-	);
-
-	return idx;
-
-}
-
-
-/**
-
-	@brief			Replaces `/\\(\n\r?|\r\n?)[\t \v\f]*[#;]/` or `/\\(\n\r?|\r\n?)/`
-					with `"$1"`
-	@param			srcstr			The target string (it may contain multi-line
-									escape sequences)
-	@param			len				Length of the string
-	@param			is_disabled		The string represents a disabled entry
-	@param			format			The format of the INI file
-	@return			The new length of the string
-
-**/
-static size_t unescape_cr_lf (char * const srcstr, const size_t len, const _LIBCONFINI_CHARBOOL_ is_disabled, const IniFormat format) {
-
-	register size_t idx_s = 0, idx_d = 0;
-	register uint8_t eol_i = _LIBCONFINI_EOL_IDX_;
-	register _LIBCONFINI_CHARBOOL_ is_escaped = _LIBCONFINI_FALSE_;
-	size_t probe;
-
-	while (idx_s < len) {
-
-		if (
-			is_escaped && (
-				srcstr[idx_s] == _LIBCONFINI_SPACES_[eol_i] || srcstr[idx_s] == _LIBCONFINI_SPACES_[eol_i ^= 1]
-			)
-		) {
-
-			srcstr[idx_d - 1] = srcstr[idx_s++];
-
-			if (srcstr[idx_s] == _LIBCONFINI_SPACES_[eol_i ^ 1]) {
-
-				srcstr[idx_d++] = srcstr[idx_s++];
-
-			}
-
-			if (is_disabled) {
-
-				probe = ltrim_s(srcstr, idx_s, _LIBCONFINI_NO_EOL_);
-
-				if (_LIBCONFINI_IS_DIS_MARKER_(srcstr[probe], format)) {
-
-					idx_s = probe + 1;
-
-				}
-
-			}
-
-			is_escaped = _LIBCONFINI_FALSE_;
-
-		} else {
-
-			is_escaped	=	srcstr[idx_s] == _LIBCONFINI_BACKSLASH_ ?
-								!is_escaped
-							:
-								_LIBCONFINI_FALSE_;
-
-
-			srcstr[idx_d++] = srcstr[idx_s++];
-
-		}
-
-	}
-
-	for (idx_s = idx_d; idx_s < len; srcstr[idx_s++] = '\0');
-
-	return idx_d;
-
-}
-
-
-/**
-
-	@brief			Sanitizes a section path
-	@param			secpath			The section path
-	@param			format			The format of the INI file
-	@return			The new length of the string
-
-	Out of quotes, similar to ECMAScript
-	`secpath.replace(/\.*\s*$|(?:\s*(\.))+\s*|^\s+/g, "$1").replace(/\s+/g, " ")`
-
-	A section path can start with a dot (append), but cannot end with a dot. Spaces
-	surrounding dots will be removed. Fragments surrounded by single or double
-	quotes (if these are enabled) are prevented from changes.
-
-**/
-static size_t sanitize_section_path (char * const secpath, const IniFormat format) {
-
-	/*
-
-	Mask `abcd` (12 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Unescaped single quotes are odd right now
-		FLAG_8		Unescaped double quotes are odd right now
-		FLAG_16		We are in an odd sequence of backslashes
-		FLAG_32		These are initial spaces
-		FLAG_64		This is a space out of quotes
-		FLAG_128	This is a dot out of quotes
-		FLAG_256	This is anything *but* an opening single/double quote
-		FLAG_512	Don't ignore the last two characters
-		FLAG_1024	Don't overwrite the previous character
-		FLAG_2048	Path contains at least one name
-
-	*/
-
-	register uint16_t abcd = (format.no_double_quotes ? 1826 : 1824) | format.no_single_quotes;
-	register size_t idx_s = 0, idx_d = 0;
-
-	for (; secpath[idx_s]; idx_s++) {
-
-		/*  Revision #2  */
-
-		abcd	=	!(abcd & 12) && is_some_space(secpath[idx_s], _LIBCONFINI_WITH_EOL_) ?
-						(
-							abcd & 224 ?
-								(abcd & 3055) | 832
-							:
-								(abcd & 4079) | 1856
-						)
-					: !(abcd & 12) && secpath[idx_s] == _LIBCONFINI_SUBSECTION_ ?
-						(
-							abcd & (abcd & 32 ? 128 : 192) ?
-								(abcd & 2959) | 896
-							:
-								(abcd & 3983) | 1920
-						)
-					: !(abcd & 25) && secpath[idx_s] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						(
-							~abcd & 4 ?
-								(abcd & 3839) | 1540
-							: abcd & 256 ?
-								(abcd & 3867) | 3840
-							:
-								(abcd & 3579) | 1280
-						)
-					: !(abcd & 22) && secpath[idx_s] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						(
-							~abcd & 8 ?
-								(abcd & 3839) | 1544
-							: abcd & 256 ?
-								(abcd & 3863) | 3840
-							:
-								(abcd & 3575) | 1280
-						)
-					: secpath[idx_s] == _LIBCONFINI_BACKSLASH_ ?
-						((abcd & 3871) | 3840) ^ 16
-					:
-						(abcd & 3855) | 3840;
-
-
-		if (abcd & 512) {
-
-			secpath[
-				abcd & 1024 ?
-					idx_d++
-				: idx_d ?
-					idx_d - 1
-				:
-					idx_d
-			]					=	!(~abcd & 384) ?
-										_LIBCONFINI_SUBSECTION_
-									: !(~abcd & 320) ?
-										_LIBCONFINI_COLLAPSED_
-									:
-										secpath[idx_s];
-
-		} else if (idx_d) {
-
-			idx_d--;
-
-		}
-
-	}
-
-	for (
-
-		idx_s	=	idx_d && (abcd & 2048) && (abcd & 192) ?
-						--idx_d
-					:
-						idx_d;
-
-			secpath[idx_s];
-
-		secpath[idx_s++] = '\0'
-
-	);
-
-	return idx_d;
-
-}
-
-
-/**
-
-	@brief			Out of quotes similar to ECMAScript
-					`ini_string.replace(/''|""/g, "").replace(/^[\n\r]\s*|\s+/g, " ")`
-	@param			ini_string		The string to collapse -- multi-line escape
-									sequences must be already unescaped at
-									this stage
-	@param			format			The format of the INI file
-	@return			The new length of the string
-
-**/
-static size_t collapse_everything (char * const ini_string, const IniFormat format) {
-
-	/*
-
-	Mask `abcd` (9 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Unescaped single quotes are odd right now
-		FLAG_8		Unescaped double quotes are odd right now
-		FLAG_16		We are in an odd sequence of backslashes
-		FLAG_32		This is *not* a space out of quotes
-		FLAG_64		This is an opening single/double quote
-		FLAG_128	Don't ignore this character
-		FLAG_256	Jump this character and the one before this
-
-	*/
-
-	register size_t idx_s = 0, idx_d = 0;
-
-	register uint16_t abcd	=	(is_some_space(*ini_string, _LIBCONFINI_WITH_EOL_) ? 128 : 160) |
-								(format.no_double_quotes << 1) |
-								format.no_single_quotes;
-
-
-	for (; ini_string[idx_s]; idx_s++) {
-
-		/*  Revision #2  */
-
-		abcd	=	!(abcd & 12) && is_some_space(ini_string[idx_s], _LIBCONFINI_WITH_EOL_) ?
-						(
-							abcd & 32 ?
-								(abcd & 143) | 128
-							:
-								abcd & 47
-						)
-					: !(abcd & 25) && ini_string[idx_s] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						(
-							~abcd & 4 ?
-								(abcd & 239) | 196
-							: abcd & 64 ?
-								(abcd & 299) | 256
-							:
-								(abcd & 171) | 160
-						)
-					: !(abcd & 22) && ini_string[idx_s] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						(
-							~abcd & 8 ?
-								(abcd & 239) | 200
-							: abcd & 64 ?
-								(abcd & 295) | 256
-							:
-								(abcd & 167) | 160
-						)
-					: ini_string[idx_s] == _LIBCONFINI_BACKSLASH_ ?
-						((abcd & 191) | 160) ^ 16
-					:
-						(abcd & 175) | 160;
-
-
-		if (abcd & 256) {
-
-			idx_d--;
-
-		} else if (abcd & 128) {
-
-			ini_string[idx_d++] = abcd & 44 ? ini_string[idx_s] : _LIBCONFINI_COLLAPSED_;
-
-		}
-
-	}
-
-	for (
-
-		idx_s	=	!(abcd & 32) && idx_d ?
-						--idx_d
-					:
-						idx_d;
-
-			ini_string[idx_s];
-
-		ini_string[idx_s++] = '\0'
-
-	);
-
-	return idx_d;
-
-}
-
-
-/**
-
-	@brief			Out of quotes similar to ECMAScript
-					`ini_string.replace(/\s+/g, " ")`
-	@param			ini_string		The string to collapse -- multi-line escape
-									sequences must be already unescaped at this
-									stage
-	@param			format			The format of the INI file
-	@return			The new length of the string
-
-**/
-static size_t collapse_spaces (char * const ini_string, const IniFormat format) {
-
-	/*
-
-	Mask `abcd` (7 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Unescaped single quotes are odd right now
-		FLAG_8		Unescaped double quotes are odd right now
-		FLAG_16		We are in an odd sequence of backslashes
-		FLAG_32		This is a space out of quotes
-		FLAG_64		Jump this character
-
-	*/
-
-	register uint8_t abcd = (format.no_double_quotes ? 34 : 32) | format.no_single_quotes;
-	register size_t idx_s = 0;
-	size_t idx_d = 0;
-
-	for (; ini_string[idx_s]; idx_s++) {
-
-		/*  Revision #1  */
-
-		abcd	=	!(abcd & 12) && is_some_space(ini_string[idx_s], _LIBCONFINI_WITH_EOL_) ?
-						(
-							abcd & 32 ?
-								(abcd & 111) | 64
-							:
-								(abcd & 47) | 32
-						)
-					: !(abcd & 25) && ini_string[idx_s] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						(abcd & 15) ^ 4
-					: !(abcd & 22) && ini_string[idx_s] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						(abcd & 15) ^ 8
-					: ini_string[idx_s] == _LIBCONFINI_BACKSLASH_ ?
-						(abcd & 31) ^ 16
-					:
-						abcd & 15;
-
-
-		if (~abcd & 64) {
-
-			ini_string[idx_d++] = abcd & 32 ? _LIBCONFINI_COLLAPSED_ : ini_string[idx_s];
-
-		}
-
-	}
-
-	for (
-
-		idx_s	=	(abcd & 32) && idx_d ?
-						--idx_d
-					:
-						idx_d;
-
-			ini_string[idx_s];
-
-		ini_string[idx_s++] = '\0'
-
-	);
-
-	return idx_d;
-
-}
-
-
-/**
-
-	@brief			Similar to ECMAScript `str.replace(/''|""/g, "")`
-	@param			str				The string to collapse
-	@param			format			The format of the INI file
-	@return			The new length of the string
-
-**/
-static size_t collapse_empty_quotes (char * const str, const IniFormat format) {
-
-	/*
-
-	Mask `abcd` (7 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Unescaped single quotes are odd right now
-		FLAG_8		Unescaped double quotes are odd right now
-		FLAG_16		We are in an odd sequence of backslashes
-		FLAG_32		This is an opening single/double quote
-		FLAG_64		These are empty quotes
-
-	*/
-
-	register uint8_t abcd = (format.no_double_quotes << 1) | format.no_single_quotes;
-	register size_t lshift = ltrim_s(str, 0, _LIBCONFINI_WITH_EOL_), idx = lshift;
-
-	for (; str[idx]; idx++) {
-
-		/*  Revision #1  */
-
-		abcd	=	str[idx] == _LIBCONFINI_BACKSLASH_ ?
-						(abcd & 31) ^ 16
-					: !(abcd & 22) && str[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						(
-							~abcd & 40 ?
-								((abcd & 47) | 32) ^ 8
-							:
-								(abcd & 71) | 64
-						)
-					: !(abcd & 25) && str[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						(
-							~abcd & 36 ?
-								((abcd & 47) | 32) ^ 4
-							:
-								(abcd & 75) | 64
-						)
-					:
-						abcd & 15;
-
-
-		str[idx - lshift] = str[idx];
-
-		if (abcd & 64) {
-
-			lshift += 2;
-
-		}
-
-	}
-
-	for (idx -= lshift; str[idx]; str[idx++] = '\0');
-
-	return rtrim_h(str, idx - lshift, _LIBCONFINI_WITH_EOL_);
-
-}
-
-
-/**
-
-	@brief			Removes all comment initializers (`#` and/or `;`) from the
-					beginning of each line of a comment
-	@param			srcstr			The comment to parse (it may contain multi-line
-									escape sequences)
-	@param			len				The length of @p srcstr
-	@param			format			The format of the INI file
-	@return			The new length of the string
-
-	- In multi-line comments: `srcstr.replace(/^[#;]+|(\n\r?|\r\n?)[\t \v\f]*[#;]+/g, "$1")`
-	- In single-line comments: `srcstr.replace(/^[#;]+/, "")`
-
-	The argument @p srcstr may begin with a comment initializer (`#` or `;`
-	depending on the format), or with the character that immediately follows it.
-
-**/
-static size_t uncomment (char * const srcstr, size_t len, const IniFormat format) {
-
-	register size_t idx_s = 0, idx_d = 0;
-
-	if (format.multiline_nodes == INI_MULTILINE_EVERYWHERE) {
-
-		/*
-
-			The comment can be multi-line
-
-		*/
-
-		/*
-
-		Mask `abcd` (6 bits used):
-
-			FLAG_1		Don't erase any character
-			FLAG_2		We are in an odd sequence of backslashes
-			FLAG_4		This new line character is escaped
-			FLAG_8		This character is a comment character and follows
-						`/(\n\s*|\r\s*)/`
-			FLAG_16		This character is a part of a group of spaces that follow
-						a new line (`/(\n|\r)[\t \v\f]+/`)
-			FLAG_32		This character is *not* a new line character (`/[\r\n]/`)
-
-		*/
-
-		for (register uint8_t abcd = 8; idx_s < len; idx_s++) {
-
-			abcd	=	srcstr[idx_s] == _LIBCONFINI_BACKSLASH_ ?
-							((abcd & 35) | 32) ^ 2
-						: srcstr[idx_s] == _LIBCONFINI_LF_ || srcstr[idx_s] == _LIBCONFINI_CR_ ?
-							(abcd << 1) & 4
-						: !(abcd & 32) && _LIBCONFINI_IS_ANY_MARKER_(srcstr[idx_s], format) ?
-							(abcd & 40) | 8
-						: !(abcd & 40) && is_some_space(srcstr[idx_s], _LIBCONFINI_NO_EOL_) ?
-							(abcd & 57) | 16
-						:
-							(abcd & 33) | 32;
-
-
-			if (!(abcd & 25)) {
-
-				srcstr[abcd & 4 ? idx_d - 1 : idx_d++] = srcstr[idx_s];
-
-			} else if (!(abcd & 28)) {
-
-				idx_d++;
-
-			}
-
-		}
-
-	} else {
-
-		/*
-
-			The comment cannot be multi-line
-
-		*/
-
-		for (; idx_s < len && _LIBCONFINI_IS_ANY_MARKER_(srcstr[idx_s], format); idx_s++);
-
-		if (!idx_s) {
-
-			return len;
-
-		}
-
-		for (; idx_s < len; srcstr[idx_d++] = srcstr[idx_s++]);
-
-	}
-
-	for (idx_s = idx_d; idx_s < len; srcstr[idx_s++] = '\0');
-
-	return idx_d;
-
-}
-
-
-/**
-
-	@brief			Tries to determine the type of a member "as if it was active"
-	@param			srcstr			String containing an individual node (it may
-									contain multi-line escape sequences)
-	@param			len				Length of the node
-	@param			allow_implicit	A boolean: `true` if keys without a key-value
-									delimiter are allowed, `false` otherwise
-	@param			format			The format of the INI file
-	@return			The node type (see header)
-
-**/
-static uint8_t get_type_as_active (
-	const char * const srcstr,
-	const size_t len,
-	const _LIBCONFINI_CHARBOOL_ allow_implicit,
-	const IniFormat format
-) {
-
-	const _LIBCONFINI_CHARBOOL_ invalid_delimiter = _LIBCONFINI_IS_ESC_CHAR_(format.delimiter_symbol, format);
-
-	if (
-		!len || _LIBCONFINI_IS_ANY_MARKER_(*srcstr, format) || (
-			*((unsigned char *) srcstr) == format.delimiter_symbol && !invalid_delimiter
-		)
-	) {
-
-		return INI_UNKNOWN;
-
-	}
-
-	register uint16_t abcd;
-	register size_t idx;
-
-	if (format.section_paths != INI_NO_SECTIONS && *srcstr == _LIBCONFINI_OPEN_SECTION_) {
-
-		if (format.no_spaces_in_names) {
-
-			/*
-
-				Search for the CLOSE SECTION character and possible spaces in names
-				-- i.e., ECMAScript `/[^\.\s]\s+[^\.\s]/g.test(srcstr)`. The
-				algorithm is made more complex by the fact that LF and CR characters
-				are still escaped at this stage.
-
-			*/
-
-			/*
-
-			Mask `abcd` (10 bits used):
-
-				FLAG_1		Single quotes are not metacharacters (const)
-				FLAG_2		Double quotes are not metacharacters (const)
-				FLAG_4		Only one level of nesting is allowed (const)
-				FLAG_8		Unescaped single quotes are odd right now
-				FLAG_16		Unescaped double quotes are odd right now
-				FLAG_32		We are in an odd sequence of backslashes
-				FLAG_64		This is a space
-				FLAG_128	What follows cannot contain spaces
-				FLAG_256	Continue the loop
-				FLAG_512	Section path is *not* valid
-
-			*/
-
-
-			idx = 1;
-
-			abcd	=	(format.section_paths == INI_ONE_LEVEL_ONLY ? 772: 768) |
-						(format.no_double_quotes << 1) |
-						format.no_single_quotes;
-
-
-			do {
-
-				/*  Revision #2  */
-
-				abcd	=	idx >= len ?
-								abcd & 767
-							: !(abcd & 42) && srcstr[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-								(abcd & 991) ^ 16
-							: !(abcd & 49) && srcstr[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-								(abcd & 991) ^ 8
-							: srcstr[idx] == _LIBCONFINI_LF_ || srcstr[idx] == _LIBCONFINI_CR_ ?
-								(abcd & 991) | 64
-							: is_some_space(srcstr[idx], _LIBCONFINI_NO_EOL_) ?
-								(
-									~abcd & 32 ?
-										abcd | 64
-									: ~abcd & 192 ?
-										(abcd & 991) | 192
-									:
-										(abcd & 767) | 128
-								)
-							: !(abcd & 28) && srcstr[idx] == _LIBCONFINI_SUBSECTION_ ?
-								(
-									~abcd & 224 ?
-										abcd & 799
-									:
-										abcd & 767
-								)
-							: !(abcd & 24) && srcstr[idx] == _LIBCONFINI_CLOSE_SECTION_ ?
-								(
-									~abcd & 224 ?
-										abcd & 159
-									:
-										abcd & 767
-								)
-							: srcstr[idx] == _LIBCONFINI_BACKSLASH_ ?
-								(
-									~abcd & 32 ?
-										abcd | 32
-									: ~abcd & 192 ?
-										(abcd & 991) | 128
-									:
-										(abcd & 735)
-								)
-							: ~abcd & 192 ?
-								(abcd & 927) | 128
-							:
-								(abcd & 671) | 128;
-
-
-				idx++;
-
-			} while (abcd & 256);
-
-			if (abcd & 512) {
-
-				return INI_UNKNOWN;
-
-			}
-
-		} else if ((idx = getn_metachar_pos(srcstr, _LIBCONFINI_CLOSE_SECTION_, len, format) + 1) > len) {
-
-			return INI_UNKNOWN;
-
-		}
-
-		/*
-
-			Scan for possible non-space characters following the CLOSE SECTION
-			character: if found the node cannot represent a section path (but it can
-			possibly represent a key). Empty quotes surrounded by spaces will be
-			tolerated.
-
-		*/
-
-		/*
-
-		Recycling variable `abcd` (6 bits used)...:
-
-			FLAG_1		Single quotes are not metacharacters (const)
-			FLAG_2		Double quotes are not metacharacters (const)
-			FLAG_4		Unescaped single quotes are odd right now
-			FLAG_8		Unescaped double quotes are odd right now
-			FLAG_16		We are in an odd sequence of backslashes
-			FLAG_32		Continue the loop
-
-		*/
-
-		abcd = 32 | (format.no_double_quotes << 1) | format.no_single_quotes;
-
-
-		/* \                                /\
-		\ */     nonspace_check:           /* \
-		 \/     ______________________     \ */
-
-
-		if (abcd) {
-
-			if (idx >= len) {
-
-				return INI_SECTION;
-
-			}
-
-			switch (srcstr[idx++]) {
-
-				case _LIBCONFINI_VT_:
-				case _LIBCONFINI_FF_:
-				case _LIBCONFINI_HT_:
-				case _LIBCONFINI_SIMPLE_SPACE_:
-
-					abcd = abcd & 28 ? 0 : abcd & 47;
-					goto nonspace_check;
-
-				case _LIBCONFINI_LF_:
-				case _LIBCONFINI_CR_:
-
-					abcd = abcd & 12 ? 0 : abcd & 47;
-					goto nonspace_check;
-
-				case _LIBCONFINI_BACKSLASH_:
-
-					abcd = abcd & 28 ? 0 : abcd | 16;
-					goto nonspace_check;
-
-				case _LIBCONFINI_DOUBLE_QUOTES_:
-
-					abcd = abcd & 22 ? 0 : (abcd & 47) ^ 8;
-					goto nonspace_check;
-
-				case _LIBCONFINI_SINGLE_QUOTES_:
-
-					abcd = abcd & 25 ? 0 : (abcd & 47) ^ 4;
-					goto nonspace_check;
-
-			}
-
-		}
-
-	}
-
-	/*
-
-		It can be just a key...
-
-	*/
-
-	if (invalid_delimiter && !allow_implicit) {
-
-		return INI_UNKNOWN;
-
-	}
-
-	/*
-
-	Recycling variable `abcd` (2 bits used)...:
-
-		FLAG_1		The delimiter **must** be present
-		FLAG_2		Search for spaces in names
-
-	*/
-
-	abcd = (format.no_spaces_in_names << 1) | (allow_implicit ? 0 : 1);
-
-	if (abcd) {
-
-		idx = getn_metachar_pos(srcstr, (char) format.delimiter_symbol, len, format);
-
-		if ((abcd & 1) && idx == len) {
-
-			return INI_UNKNOWN;
-
-		}
-
-		if (abcd & 2) {
-
-			idx = urtrim_s(srcstr, idx);
-
-			do {
-
-				if (is_some_space(srcstr[--idx], _LIBCONFINI_WITH_EOL_)) {
-
-					return INI_UNKNOWN;
-
-				}
-
-			} while (idx);
-
-		}
-
-	}
-
-	return INI_KEY;
-
-}
-
-
-/**
-
-	@brief			Examines a (single-/multi-line) segment and checks whether
-					it contains more than just one node
-	@param			srcstr			Segment to examine (it may contain multi-line
-									escape sequences)
-	@param			format			The format of the INI file
-	@return			Number of entries found
-
-**/
-static size_t further_cuts (char * const srcstr, const IniFormat format) {
-
-	/*
-
-	Shared flags of mask `abcd` (8 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Do not allow disabled entries after space (const)
-		FLAG_8		Formats supports multi-line entries everywhere (const)
-		FLAG_16		Formats supports multi-line entries everywhere except in
-					comments (const)
-		FLAG_32		Unescaped single quotes are odd right now
-		FLAG_64		Unescaped double quotes are odd right now
-		FLAG_128	We are in an odd sequence of backslashes
-
-	*/
-
-	register uint16_t	abcd	=	((format.disabled_after_space << 2) ^ 4) |
-									(format.no_double_quotes << 1) |
-									format.no_single_quotes | (
-										format.multiline_nodes == INI_MULTILINE_EVERYWHERE ?
-											8
-										: format.multiline_nodes == INI_BUT_COMMENTS ?
-											16
-										:
-											0
-									);
-
-
-	register size_t idx;
-	size_t focus_at, unparsable_at, search_at = 0, num_entries = 0;
-
-
-	/* \                                /\
-	\ */     search_for_cuts:          /* \
-	 \/     ______________________     \ */
-
-
-	if (!srcstr[search_at]) {
-
-		return num_entries;
-
-	}
-
-	unparsable_at = 0;
-
-	abcd	=	_LIBCONFINI_IS_DIS_MARKER_(srcstr[search_at], format) && (
-					!(abcd & 4) || !is_some_space(srcstr[search_at + 1], _LIBCONFINI_NO_EOL_)
-				) ?
-					(abcd & 31) | 2560
-				: _LIBCONFINI_IS_IGN_MARKER_(srcstr[search_at], format) ?
-					(abcd & 8 ? (abcd & 31) | 1024 : abcd & 31)
-				: (abcd & 8) && (
-					srcstr[search_at] == _LIBCONFINI_IC_INT_MARKER_ || _LIBCONFINI_IS_ANY_MARKER_(srcstr[search_at], format)
-				) ?
-					(abcd & 31) | 3072
-				:
-					(abcd & 31) | 2048;
-
-
-	if (abcd & 2048) {
-
-		num_entries++;
-
-	}
-
-	if (abcd & 1536) {
-
-		/*
-
-			Node starts with `/[;#]/` and can be a disabled entry in any format, or
-			a simple comment or a block that must be ignored in multi-line formats
-
-		*/
-
-		/*
-
-		Mask `abcd` (14 bits used):
-
-			FLAG_256	This or the previous character was not a space
-			FLAG_512	We are in a disabled entry or a comment (semi-const)
-			FLAG_1024	We are in a simple comment or in a block that must be ignored
-						and format supports multi-line entries (semi-const)
-			FLAG_2048	We are *not* in a block that must be ignored (semi-const)
-			FLAG_4096	We have *not* just found an inline comment nested within a
-						disabled entry
-			FLAG_8192	We had previously found an inline comment nested in this
-						segment, but the entry that preceded it had been checked and
-						did not seem to represent a valid disabled entry
-
-			NOTE:	For FLAG_1-FLAG_16 I will keep the values already assigned at
-					the beginning of the function; all other flags are already set
-					to zero. For the meaning of flags FLAG_1-FLAG_128 see the
-					beginning of the function.
-
-		*/
-
-		idx = ltrim_s(srcstr, search_at + 1, _LIBCONFINI_NO_EOL_) - 1;
-
-
-		/* \                                /\
-		\ */     inactive_cut:             /* \
-		 \/     ______________________     \ */
-
-
-		switch (srcstr[++idx]) {
-
-			case '\0':
-
-				/*  End of string  */
-
-				if (~abcd & 8) {
-
-					/*
-
-						Check if this is a valid disabled entry. If it is not,
-						search for line breaks.
-
-						If the code has reached this point it means that according
-						to the format disabled entries can be multi-line but
-						comments cannot, and #get_type_as_active() has never been
-						invoked on this entry.
-
-					*/
-
-					focus_at = dqultrim_s(srcstr, search_at, format);
-
-					if (
-						srcstr[focus_at] && !get_type_as_active(
-							srcstr + focus_at,
-							idx - focus_at,
-							format.disabled_can_be_implicit,
-							format
-						)
-					) {
-
-						srcstr[search_at] = _LIBCONFINI_SC_INT_MARKER_;
-						unparsable_at = search_at + 1;
-
-					}
-
-				}
-
-				break;
-
-			case _LIBCONFINI_LF_:
-			case _LIBCONFINI_CR_:
-
-				/*
-
-					Line break has been found in a multi-line disabled entry or
-					a comment. Search for `/\\(?:\n\r?|\r\n?)\s*[^;#]/`.
-
-				*/
-
-				focus_at = dqultrim_s(srcstr, search_at, format);
-				idx = ltrim_s(srcstr, idx + 1, _LIBCONFINI_WITH_EOL_);
-
-				if (
-					abcd & 2048 ?
-						!(
-							_LIBCONFINI_IS_DIS_MARKER_(srcstr[idx], format) && (abcd & 24) && (
-								(~abcd & 516) || !is_some_space(srcstr[idx + 1], _LIBCONFINI_NO_EOL_)
-							)
-						) && !(
-							_LIBCONFINI_IS_COM_MARKER_(srcstr[idx], format) && (abcd & 8) && (
-								((abcd ^ 512) & 8704) || !get_type_as_active(
-									srcstr + focus_at,
-									idx - focus_at,
-									format.disabled_can_be_implicit,
-									format
-								)
-							)
-						)
-					:
-						!_LIBCONFINI_IS_IGN_MARKER_(srcstr[idx], format)
-				) {
-
-					rtrim_h(srcstr, idx, _LIBCONFINI_WITH_EOL_);
-					search_at = qultrim_h(srcstr, idx, format);
-					goto search_for_cuts;
-
-				}
-
-				/*
-
-					No case break here, keep it like this! `case /[ \t\v\f]/` must
-					follow (switch case fallthrough).
-
-				*/
-                __attribute__((fallthrough));
-
-			case _LIBCONFINI_VT_:
-			case _LIBCONFINI_FF_:
-			case _LIBCONFINI_HT_:
-			case _LIBCONFINI_SIMPLE_SPACE_:
-
-				abcd = (abcd & 15999) | 4096;
-				goto inactive_cut;
-
-			case _LIBCONFINI_BACKSLASH_:
-
-				abcd = (abcd | 4352) ^ 128;
-				goto inactive_cut;
-
-			default:
-
-				abcd	=	!(abcd & 1376) && (~abcd & 8200) && _LIBCONFINI_IS_ANY_MARKER_(srcstr[idx], format) ?
-								(abcd & 12159) | 256
-							: !(abcd & 162) && srcstr[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-								((abcd & 16255) | 4352) ^ 64
-							: !(abcd & 193) && srcstr[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-								((abcd & 16255) | 4352) ^ 32
-							:
-								(abcd & 16255) | 4352;
-
-
-				if (abcd & 4096) {
-
-					goto inactive_cut;
-
-				}
-
-				if (~abcd & 8192) {
-
-					/*
-
-						Inline comment has been found in a (supposedly) disabled entry.
-
-					*/
-
-					focus_at = dqultrim_s(srcstr, search_at, format);
-
-					if (get_type_as_active(
-						srcstr + focus_at,
-						idx - focus_at,
-						format.disabled_can_be_implicit,
-						format
-					)) {
-
-						if (!_LIBCONFINI_IS_IGN_MARKER_(srcstr[idx], format)) {
-
-							srcstr[idx] = _LIBCONFINI_IC_INT_MARKER_;
-							num_entries++;
-
-						}
-
-						srcstr[idx - 1] = '\0';
-
-						if (abcd & 8) {
-
-							goto inactive_cut;
-
-						}
-
-						unparsable_at = idx + 1;
-
-					} else {
-
-						abcd |= 8192;
-						srcstr[search_at] = _LIBCONFINI_SC_INT_MARKER_;
-
-						if (abcd & 8) {
-
-							goto inactive_cut;
-
-						}
-
-						unparsable_at = search_at + 1;
-
-					}
-
-				}
-
-				/*  No case break here (last case)  */
-
-		}
-
-	} else if (_LIBCONFINI_IS_ANY_MARKER_(srcstr[search_at], format)) {
-
-		/*
-
-			Node starts with `/[;#]/` but cannot be multi-line or represent a
-			disabled entry
-
-		*/
-
-		unparsable_at = search_at + 1;
-
-	} else {
-
-		/*
-
-			Node is active: search for inline comments
-
-		*/
-
-		/*
-
-		Recycling variable `abcd` (11 bits used)...:
-
-			FLAG_256	Comment marker follows an escaped new line made of only one
-						character (i.e., `"\\\n"` or `"\\\r"` but neither `"\\\r\n"`
-						or `"\\\n\r"`)
-			FLAG_512	This was neither a hash nor a semicolon character
-			FLAG_1024	This was not a space
-
-		NOTE:	For FLAG_1-FLAG_16 I will keep the values already assigned at the
-				beginning of the function; all other flags are already set to zero
-				(see previous usage of `abcd` within this function), with the only
-				exception of FLAG_2048, which I am going to overwrite immediately.
-				For the meaning of flags FLAG_1-FLAG_128 see the beginning of the
-				function.
-
-		*/
-
-		abcd = (abcd & 2047) | 1536;
-		idx = search_at;
-
-
-		/* \                                /\
-		\ */     active_cut:               /* \
-		 \/     ______________________     \ */
-
-
-		switch (srcstr[++idx]) {
-
-			case '\0':
-
-				/*  End of string  */
-				break;
-
-			case _LIBCONFINI_VT_:
-			case _LIBCONFINI_FF_:
-			case _LIBCONFINI_HT_:
-			case _LIBCONFINI_SIMPLE_SPACE_:
-
-				abcd = (abcd & 639) | 512;
-				goto active_cut;
-
-			case _LIBCONFINI_LF_:
-			case _LIBCONFINI_CR_:
-
-				abcd = (abcd & 639) | ((abcd << 1) & 256) | 512;
-				goto active_cut;
-
-			case _LIBCONFINI_BACKSLASH_:
-
-				abcd = ((abcd & 1791) | 1536) ^ 128;
-				goto active_cut;
-
-			default:
-
-				abcd	=	_LIBCONFINI_IS_ANY_MARKER_(srcstr[idx], format) ?
-								abcd & 1407
-							: !(abcd & 162) && srcstr[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-								((abcd & 1791) | 1536) ^ 64
-							: !(abcd & 193) && srcstr[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-								((abcd & 1791) | 1536) ^ 32
-							:
-								(abcd & 1791) | 1536;
-
-				if (abcd & 1760) {
-
-					goto active_cut;
-
-				}
-
-				/*
-
-					Inline comment has been found in an active entry.
-
-				*/
-
-				if (abcd & 256) {
-
-					/*
-
-						Remove the backslash if the comment immediately follows an
-						escaped new line expressed by one chararacter
-						(`/\\[\r\n]/`). In case of CR + LF or LF + CR
-						(`/\\\n\r|\\\r\n/`) the backslash will be removed later by
-						#strip_ini_cache().
-
-					*/
-
-					srcstr[idx - 2] = '\0';
-
-				}
-
-				srcstr[idx - 1] = '\0';
-
-				if (!_LIBCONFINI_IS_IGN_MARKER_(srcstr[idx], format)) {
-
-					srcstr[idx] = _LIBCONFINI_IC_INT_MARKER_;
-
-					if (abcd & 8) {
-
-						search_at = idx;
-						goto search_for_cuts;
-
-					}
-
-					num_entries++;
-
-				} else if (abcd & 8) {
-
-					search_at = idx;
-					goto search_for_cuts;
-
-				}
-
-				unparsable_at = idx + 1;
-				/*  No case break here (last case)  */
-
-		}
-
-	}
-
-	if (unparsable_at) {
-
-		/*
-
-			Cut unparsable multi-line comments
-
-		*/
-
-		for (idx = unparsable_at; srcstr[idx]; idx++) {
-
-			if (srcstr[idx] == _LIBCONFINI_LF_ || srcstr[idx] == _LIBCONFINI_CR_) {
-
-				search_at = qultrim_h(srcstr, idx, format);
-				goto search_for_cuts;
-
-			}
-
-		}
-
-	}
-
-	return num_entries;
-
-}
-
-/** @startfnlist **/
-
-
-
-		/*\
-		|*|
-		|*|     GLOBAL ENVIRONMENT
-		|*|    ________________________________
-		\*/
-
-
-
-		/*  LIBRARY'S MAIN FUNCTIONS  */
-
-
-												/** @utility{strip_ini_cache} **/
-/**
-
-	@brief			Parses and tokenizes a buffer containing an INI file, then
-					dispatches its content to a custom callback
-	@param			ini_source		The buffer containing the INI file to tokenize
-	@param			ini_length		The length of @p ini_source without counting the
-									NUL terminator (if any -- se below)
-	@param			format			The format of the INI file
-	@param			f_init			The function that will be invoked before the
-									first dispatch, or `NULL`
-	@param			f_foreach		The function that will be invoked for each
-									dispatch, or `NULL`
-	@param			user_data		A custom argument, or `NULL`
-	@return			Zero for success, otherwise an error code (see `enum`
-					#ConfiniInterruptNo)
-
-	The @p ini_source parameter must be a valid pointer to a buffer of size
-	@p ini_length + 1 and cannot be `NULL`. The @p ini_source string does not need
-	to be NUL-terminated, but _it does need one extra byte where to append a NUL
-	terminator_ -- in fact, as soon as this function is invoked,
-	`ini_source[ini_length]` will be immediately set to `\0`.
-
-	In most cases, as when using `strlen()` for computing @p ini_length, this is not
-	a concern, since `ini_source[ini_length]` will always be `\0` by the very
-	definition of `strlen()`, and will only get overwritten with the same value.
-	However, if you are passing a substring of a string, for example the fragment
-	`foo=bar` of the string `foo=barracuda`, you must expect the string to be
-	immediately truncated into `foo=bar\0acuda`.
-
-	In other words, @p ini_source must point to a memory location where at least
-	`ini_length + 1` bytes are freely usable.
-
-	The user given function @p f_init (see #IniStatsHandler data type) will be
-	invoked with two arguments: `statistics` (a pointer to an #IniStatistics
-	structure containing some properties about the file read) and `user_data` (the
-	custom argument @p user_data previously passed). If @p f_init returns a non-zero
-	value the caller function will be interrupted.
-
-	The user given function @p f_foreach (see #IniDispHandler data type) will be
-	invoked with two arguments: `dispatch` (a pointer to an #IniDispatch structure
-	containing the parsed member of the INI file) and `user_data` (the custom
-	argument @p user_data previously passed). If @p f_foreach returns a non-zero
-	value the caller function will be interrupted.
-
-	After invoking `strip_ini_cache()`, the buffer pointed by the @p ini_source
-	parameter must be considered as a _corrupted buffer_ and should be freed or
-	overwritten. For more information about this function, please refer to the
-	@ref libconfini.
-
-	The parsing algorithms used by **libconfini** are able to parse any type of file
-	encoded in 8-bit code units, as long as the characters that match the regular
-	expression `/[\s\[\]\.\\;#"']/` refer to the same code points they refer to in
-	ASCII (as they do, for example, in UTF-8 and ISO-8859-1), independently of
-	platform-specific conventions.
-
-	@note	In order to be null-byte-injection-safe, before dispatching the parsed
-			content this function will strip all `NUL` characters possibly present
-			in the buffer (with the exception of the last one).
-
-	Possible return values are: #CONFINI_SUCCESS, #CONFINI_IINTR, #CONFINI_FEINTR,
-	#CONFINI_EOOR.
-
-	@include topics/strip_ini_cache.c
-
-**/
-int strip_ini_cache (
-	register char * const ini_source,
-	const size_t ini_length,
-	const IniFormat format,
-	const IniStatsHandler f_init,
-	const IniDispHandler f_foreach,
-	void * const user_data
-) {
-
-	const _LIBCONFINI_CHARBOOL_ valid_delimiter = !_LIBCONFINI_IS_ESC_CHAR_(format.delimiter_symbol, format);
-	_LIBCONFINI_CHARBOOL_ tmp_bool;
-	register size_t idx, tmp_fast_size_t_1, tmp_fast_size_t_2;
-	size_t tmp_size_t_1, tmp_size_t_2;
-
-	ini_source[ini_length] = '\0';
-
-	/*
-
-		PART ONE: Examine and isolate each segment
-
-	*/
-
-	#define __ISNT_ESCAPED__ tmp_bool
-	#define __LSHIFT__ tmp_fast_size_t_1
-	#define __EOL_N__ tmp_fast_size_t_2
-	#define __N_MEMBERS__ tmp_size_t_1
-	#define __NODE_AT__ tmp_size_t_2
-
-	/*  UTF-8 BOM  */
-	__LSHIFT__	=	*((unsigned char *) ini_source) == 0xEF &&
-					*((unsigned char *) ini_source + 1) == 0xBB &&
-					*((unsigned char *) ini_source + 2) == 0xBF
-					? 3 : 0;
-
-
-	for (
-
-		__N_MEMBERS__ = 0,
-		__EOL_N__ = _LIBCONFINI_EOL_IDX_,
-		__ISNT_ESCAPED__ = _LIBCONFINI_TRUE_,
-		__NODE_AT__ = 0,
-		idx = __LSHIFT__;
-
-			idx < ini_length;
-
-		idx++
-
-	) {
-
-		ini_source[idx - __LSHIFT__] = ini_source[idx];
-
-		if (ini_source[idx] == _LIBCONFINI_SPACES_[__EOL_N__] || ini_source[idx] == _LIBCONFINI_SPACES_[__EOL_N__ ^= 1]) {
-
-			if (format.multiline_nodes == INI_NO_MULTILINE || __ISNT_ESCAPED__) {
-
-				ini_source[idx - __LSHIFT__] = '\0';
-				__N_MEMBERS__ += further_cuts(ini_source + qultrim_h(ini_source, __NODE_AT__, format), format);
-				__NODE_AT__ = idx - __LSHIFT__ + 1;
-
-			} else if (ini_source[idx + 1] == _LIBCONFINI_SPACES_[__EOL_N__ ^ 1]) {
-
-				idx++;
-				ini_source[idx - __LSHIFT__] = ini_source[idx];
-
-			}
-
-			__ISNT_ESCAPED__ = _LIBCONFINI_TRUE_;
-
-		} else if (ini_source[idx] == _LIBCONFINI_BACKSLASH_) {
-
-			__ISNT_ESCAPED__ = !__ISNT_ESCAPED__;
-
-		} else if (ini_source[idx]) {
-
-			__ISNT_ESCAPED__ = _LIBCONFINI_TRUE_;
-
-		} else {
-
-			/*  Remove `NUL` characters from the buffer (if any)  */
-			__LSHIFT__++;
-
-		}
-
-	}
-
-	const size_t real_length = idx - __LSHIFT__;
-
-	while (idx > real_length) {
-
-		ini_source[--idx] = '\0';
-
-	}
-
-	__N_MEMBERS__ += further_cuts(ini_source + qultrim_h(ini_source, __NODE_AT__, format), format);
-
-	/*  Debug  */
-
-	/*
-
-	for (size_t tmp = 0; tmp < ini_length + 1; tmp++) {
-		putchar(ini_source[tmp] == 0 ? '$' : ini_source[tmp]);
-	}
-	putchar('\n');
-
-	*/
-
-	IniStatistics this_doc = {
-		.format = format,
-		.bytes = ini_length,
-		.members = __N_MEMBERS__
-	};
-
-	if (f_init && f_init(&this_doc, user_data)) {
-
-		return CONFINI_IINTR;
-
-	}
-
-	#undef __NODE_AT__
-	#undef __N_MEMBERS__
-	#undef __EOL_N__
-	#undef __LSHIFT__
-	#undef __ISNT_ESCAPED__
-
-	/*
-
-		PART TWO: Dispatch the parsed input
-
-	*/
-
-	if (!f_foreach) {
-
-		return CONFINI_SUCCESS;
-
-	}
-
-	#define __ITER__ tmp_fast_size_t_1
-	#define __NODE_AT__ tmp_fast_size_t_2
-	#define __PARENT_IS_DISABLED__ tmp_bool
-	#define __REAL_PARENT_LEN__ tmp_size_t_1
-	#define __CURR_PARENT_LEN__ tmp_size_t_2
-
-	__REAL_PARENT_LEN__ = 0, __CURR_PARENT_LEN__ = 0;
-
-	char
-		* curr_parent_str = ini_source + real_length,
-		* subparent_str = curr_parent_str,
-		* real_parent_str = curr_parent_str;
-
-	IniDispatch dsp = {
-		.format = format,
-		.dispatch_id = 0
-	};
-
-	__PARENT_IS_DISABLED__ = _LIBCONFINI_FALSE_;
-
-	for (__NODE_AT__ = 0, idx = 0; idx <= real_length; idx++) {
-
-		if (ini_source[idx]) {
-
-			continue;
-
-		}
-
-		if (!ini_source[__NODE_AT__] || _LIBCONFINI_IS_IGN_MARKER_(ini_source[__NODE_AT__], format)) {
-
-			__NODE_AT__ = idx + 1;
-			continue;
-
-		}
-
-		if (dsp.dispatch_id >= this_doc.members) {
-
-			return CONFINI_EOOR;
-
-		}
-
-		dsp.data = ini_source + __NODE_AT__;
-		dsp.d_len = idx - __NODE_AT__;
-
-		/*  Set `dsp.value` to an empty string  */
-		dsp.value = ini_source + idx;
-
-		if (
-			_LIBCONFINI_IS_DIS_MARKER_(*dsp.data, format) && (
-				format.disabled_after_space || !is_some_space(dsp.data[1], _LIBCONFINI_NO_EOL_)
-			)
-		) {
-
-			__ITER__ = dqultrim_s(dsp.data, 0, format);
-
-			dsp.type = get_type_as_active(
-				dsp.data + __ITER__,
-				dsp.d_len - __ITER__,
-				format.disabled_can_be_implicit,
-				format
-			);
-
-			if (dsp.type) {
-
-				dsp.data += __ITER__;
-				dsp.d_len -= __ITER__;
-
-				/*
-
-				// Not strictly needed...
-				for (; __ITER__ > 0; dsp.data[--__ITER__] = '\0');
-
-				*/
-
-			}
-
-			dsp.type |= 4;
-
-		} else {
-
-			switch (*dsp.data) {
-
-				default:
-
-					if (!_LIBCONFINI_IS_ANY_MARKER_(*dsp.data, format)) {
-
-						dsp.type = get_type_as_active(dsp.data, dsp.d_len, _LIBCONFINI_TRUE_, format);
-						break;
-
-					}
-
-					/*
-
-						No case break here, keep it like this!
-						`case _LIBCONFINI_SC_INT_MARKER_` must follow
-						(switch case fallthrough).
-
-					*/
-                    __attribute__((fallthrough));
-
-				case _LIBCONFINI_SC_INT_MARKER_:
-
-					/*
-
-					// Not strictly needed...
-					*dsp.data = '\0';
-
-					*/
-
-					dsp.type = INI_COMMENT;
-
-					break;
-
-				case _LIBCONFINI_IC_INT_MARKER_:
-
-					/*
-
-					// Not strictly needed...
-					*dsp.data = '\0';
-
-					*/
-
-					dsp.type = INI_INLINE_COMMENT;
-					/*  No case break here (last case)  */
-
-			}
-
-		}
-
-		if (__CURR_PARENT_LEN__ && *subparent_str) {
-
-			__ITER__ = 0;
-
-			do {
-
-				curr_parent_str[__ITER__ + __CURR_PARENT_LEN__] = subparent_str[__ITER__];
-
-			} while (subparent_str[__ITER__++]);
-
-			__CURR_PARENT_LEN__ += __ITER__ - 1;
-			subparent_str = curr_parent_str + __CURR_PARENT_LEN__;
-
-		}
-
-		if (__PARENT_IS_DISABLED__ && !(dsp.type & 4)) {
-
-			real_parent_str[__REAL_PARENT_LEN__] = '\0';
-			__CURR_PARENT_LEN__ = __REAL_PARENT_LEN__;
-			curr_parent_str = real_parent_str;
-			__PARENT_IS_DISABLED__ = _LIBCONFINI_FALSE_;
-
-		} else if (!__PARENT_IS_DISABLED__ && dsp.type == INI_DISABLED_SECTION) {
-
-			__REAL_PARENT_LEN__ = __CURR_PARENT_LEN__;
-			real_parent_str = curr_parent_str;
-			__PARENT_IS_DISABLED__ = _LIBCONFINI_TRUE_;
-
-		}
-
-		dsp.append_to = curr_parent_str;
-		dsp.at_len = __CURR_PARENT_LEN__;
-
-		if (dsp.type == INI_COMMENT || dsp.type == INI_INLINE_COMMENT) {
-
-			dsp.d_len = uncomment(++dsp.data, dsp.d_len - 1, format);
-
-		} else if (format.multiline_nodes != INI_NO_MULTILINE) {
-
-			dsp.d_len = unescape_cr_lf(dsp.data, dsp.d_len, dsp.type & 4, format);
-
-		}
-
-		switch (dsp.type) {
-
-			/*
-
-			case INI_UNKNOWN:
-
-				// Do nothing
-
-				break;
-
-			*/
-
-			case INI_SECTION:
-			case INI_DISABLED_SECTION:
-
-				*dsp.data++ = '\0';
-				__ITER__ = getn_metachar_pos(dsp.data, _LIBCONFINI_CLOSE_SECTION_, dsp.d_len, format);
-
-				while (dsp.data[__ITER__]) {
-
-					dsp.data[__ITER__++] = '\0';
-
-				}
-
-				dsp.d_len	=	format.section_paths == INI_ONE_LEVEL_ONLY ?
-									collapse_everything(dsp.data, format)
-								:
-									sanitize_section_path(dsp.data, format);
-
-
-				if (format.section_paths == INI_ONE_LEVEL_ONLY || *dsp.data != _LIBCONFINI_SUBSECTION_) {
-
-					/*
-
-						Append to root (this is an absolute path)
-
-					*/
-
-					curr_parent_str = dsp.data;
-					__CURR_PARENT_LEN__ = dsp.d_len;
-					subparent_str = ini_source + idx;
-					dsp.append_to = subparent_str;
-					dsp.at_len = 0;
-
-				} else if (format.section_paths == INI_ABSOLUTE_ONLY || !__CURR_PARENT_LEN__) {
-
-					/*
-
-						Append to root and remove the leading dot (parent is root or
-						relative paths are not allowed)
-
-					*/
-
-					curr_parent_str = ++dsp.data;
-					__CURR_PARENT_LEN__ = --dsp.d_len;
-					subparent_str = ini_source + idx;
-					dsp.append_to = subparent_str;
-					dsp.at_len = 0;
-
-				} else if (dsp.d_len != 1) {
-
-					/*
-
-						Append to the current parent (this is a relative path
-						and parent is not root)
-
-					*/
-
-					subparent_str = dsp.data;
-
-				}
-
-				if (INI_GLOBAL_LOWERCASE_MODE && !format.case_sensitive) {
-
-					string_tolower(dsp.data);
-
-				}
-
-				break;
-
-			case INI_KEY:
-			case INI_DISABLED_KEY:
-
-				if (
-					valid_delimiter && (
-						__ITER__ = getn_metachar_pos(dsp.data, (char) dsp.format.delimiter_symbol, dsp.d_len, format)
-					) < dsp.d_len
-				) {
-
-					dsp.data[__ITER__] = '\0';
-					dsp.value = dsp.data + __ITER__ + 1;
-
-
-					switch ((format.preserve_empty_quotes << 1) | format.do_not_collapse_values) {
-
-						case 0:	dsp.v_len = collapse_everything(dsp.value, format); break;
-
-						case 1:	dsp.v_len = collapse_empty_quotes(dsp.value, format); break;
-
-						case 2:	dsp.v_len = collapse_spaces(dsp.value, format); break;
-
-						case 4:
-
-							dsp.value += ltrim_h(dsp.value, 0, _LIBCONFINI_WITH_EOL_);
-							dsp.v_len = rtrim_h(dsp.value, dsp.d_len + dsp.data - dsp.value, _LIBCONFINI_WITH_EOL_);
-							/*  No case break here (last case)  */
-
-					}
-
-				} else if (format.implicit_is_not_empty) {
-
-					dsp.value = INI_GLOBAL_IMPLICIT_VALUE;
-					dsp.v_len = INI_GLOBAL_IMPLICIT_V_LEN;
-
-				}
-
-				dsp.d_len = collapse_everything(dsp.data, format);
-
-				if (INI_GLOBAL_LOWERCASE_MODE && !format.case_sensitive) {
-
-					string_tolower(dsp.data);
-
-				}
-
-				break;
-
-			case INI_COMMENT:
-			case INI_INLINE_COMMENT:
-
-				dsp.append_to = ini_source + idx;
-				dsp.at_len = 0;
-				/*  No case break here (last case)  */
-
-		}
-
-		if (f_foreach(&dsp, user_data)) {
-
-			return CONFINI_FEINTR;
-
-		}
-
-		dsp.dispatch_id++;
-		__NODE_AT__ = idx + 1;
-
-	}
-
-	#undef __CURR_PARENT_LEN__
-	#undef __REAL_PARENT_LEN__
-	#undef __PARENT_IS_DISABLED__
-	#undef __NODE_AT__
-	#undef __ITER__
-
-	return CONFINI_SUCCESS;
-
-}
-
-
-													/** @utility{load_ini_file} **/
-/**
-
-	@brief			Parses an INI file and dispatches its content to a custom
-					callback using a `FILE` structure as argument
-	@param			ini_file		The `FILE` handle pointing to the INI file to
-									parse
-	@param			format			The format of the INI file
-	@param			f_init			The function that will be invoked before the
-									first dispatch, or `NULL`
-	@param			f_foreach		The function that will be invoked for each
-									dispatch, or `NULL`
-	@param			user_data		A custom argument, or `NULL`
-	@return			Zero for success, otherwise an error code (see `enum`
-					#ConfiniInterruptNo)
-
-	@note	This function is absent if the `--without-io-api` option was passed to
-			the `configure` script when the library was compiled
-
-	The @p ini_file parameter must be a `FILE` handle with read privileges. On some
-	platforms, such as Microsoft Windows, it might be needed to add the binary
-	specifier to the mode string (`"b"`) in order to prevent discrepancies between
-	the physical size of the file and its computed size:
-
-	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.c}
-	FILE * my_file = fopen("example.conf", "rb");
-	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-	For the two parameters @p f_init and @p f_foreach see function
-	#strip_ini_cache().
-
-	The parsing algorithms used by **libconfini** are able to parse any type of file
-	encoded in 8-bit code units, as long as the characters that match the regular
-	expression `/[\s\[\]\.\\;#"']/` refer to the same code points they refer to in
-	ASCII (as they do, for example, in UTF-8 and ISO-8859-1), independently of
-	platform-specific conventions.
-
-	@note	In order to be null-byte-injection safe, `NUL` characters, if present in
-			the file, will be removed from the dispatched strings.
-
-	Possible return values are: #CONFINI_SUCCESS, #CONFINI_IINTR, #CONFINI_FEINTR,
-	#CONFINI_ENOMEM, #CONFINI_EIO, #CONFINI_EOOR, #CONFINI_EBADF, #CONFINI_EFBIG.
-
-	@include topics/load_ini_file.c
-
-**/
-int load_ini_file (
-	FILE * const ini_file,
-	const IniFormat format,
-	const IniStatsHandler f_init,
-	const IniDispHandler f_foreach,
-	void * const user_data
-) {
-
-	_LIBCONFINI_OFF_T_ file_size;
-
-	if (_LIBCONFINI_SEEK_EOF_(ini_file) || (file_size = _LIBCONFINI_FTELL_(ini_file)) < 0) {
-
-		return CONFINI_EBADF;
-
-	}
-
-	if ((size_t) file_size > SIZE_MAX) {
-
-		return CONFINI_EFBIG;
-
-	}
-
-	char * const cache = (char *) malloc((size_t) file_size + 1);
-
-	if (!cache) {
-
-		return CONFINI_ENOMEM;
-
-	}
-
-	rewind(ini_file);
-
-	if (fread(cache, 1, (size_t) file_size, ini_file) < (size_t) file_size) {
-
-		free(cache);
-		return CONFINI_EIO;
-
-	}
-
-	const int return_value = strip_ini_cache(cache, (size_t) file_size, format, f_init, f_foreach, user_data);
-
-	free(cache);
-	return return_value;
-
-}
-
-
-													/** @utility{load_ini_path} **/
-/**
-
-	@brief			Parses an INI file and dispatches its content to a custom
-					callback using a path as argument
-	@param			path			The path of the INI file
-	@param			format			The format of the INI file
-	@param			f_init			The function that will be invoked before the
-									first dispatch, or `NULL`
-	@param			f_foreach		The function that will be invoked for each
-									dispatch, or `NULL`
-	@param			user_data		A custom argument, or `NULL`
-	@return			Zero for success, otherwise an error code (see `enum`
-					#ConfiniInterruptNo)
-
-	@note	This function is absent if the `--without-io-api` option was passed to
-			the `configure` script when the library was compiled
-
-	For the two parameters @p f_init and @p f_foreach see function
-	#strip_ini_cache().
-
-	The parsing algorithms used by **libconfini** are able to parse any type of file
-	encoded in 8-bit code units, as long as the characters that match the regular
-	expression `/[\s\[\]\.\\;#"']/` refer to the same code points they refer to in
-	ASCII (as they do, for example, in UTF-8 and ISO-8859-1), independently of
-	platform-specific conventions.
-
-	@note	In order to be null-byte-injection safe, `NUL` characters, if present in
-			the file, will be removed from the dispatched strings.
-
-	Possible return values are: #CONFINI_SUCCESS, #CONFINI_IINTR, #CONFINI_FEINTR,
-	#CONFINI_ENOENT, #CONFINI_ENOMEM, #CONFINI_EIO, #CONFINI_EOOR, #CONFINI_EBADF,
-	#CONFINI_EFBIG.
-
-	@include topics/load_ini_path.c
-
-**/
-int load_ini_path (
-	const char * const path,
-	const IniFormat format,
-	const IniStatsHandler f_init,
-	const IniDispHandler f_foreach,
-	void * const user_data
-) {
-
-	FILE * const ini_file = fopen(path, "rb");
-
-	if (!ini_file) {
-
-		return CONFINI_ENOENT;
-
-	}
-
-	_LIBCONFINI_OFF_T_ file_size;
-
-	if (_LIBCONFINI_SEEK_EOF_(ini_file) || (file_size = _LIBCONFINI_FTELL_(ini_file)) < 0) {
-
-		return CONFINI_EBADF;
-
-	}
-
-	if ((size_t) file_size > SIZE_MAX) {
-
-		return CONFINI_EFBIG;
-
-	}
-
-	char * const cache = (char *) malloc((size_t) file_size + 1);
-
-	if (!cache) {
-
-		return CONFINI_ENOMEM;
-
-	}
-
-	rewind(ini_file);
-
-	if (fread(cache, 1, (size_t) file_size, ini_file) < (size_t) file_size) {
-
-		free(cache);
-		return CONFINI_EIO;
-
-	}
-
-	/*  No checks here, as there is nothing we can do about it...  */
-	fclose(ini_file);
-
-	const int return_value = strip_ini_cache(cache, (size_t) file_size, format, f_init, f_foreach, user_data);
-
-	free(cache);
-	return return_value;
-
-}
-
-
-
-		/*  OTHER UTILITIES (NOT REQUIRED BY LIBCONFINI'S MAIN FUNCTIONS)  */
-
-
-											/** @utility{ini_string_match_ss} **/
-/**
-
-	@brief			Compares two simple strings and checks whether they match
-	@param			simple_string_a		The first simple string
-	@param			simple_string_b		The second simple string
-	@param			format				The format of the INI file
-	@return			A boolean: `true` if the two strings match, `false` otherwise
-
-	Simple strings are user-given strings or the result of #ini_string_parse(). The
-	@p format argument is used for the following fields:
-
-	- `format.case_sensitive`
-
-**/
-bool ini_string_match_ss (
-	const char * const simple_string_a,
-	const char * const simple_string_b,
-	const IniFormat format
-) {
-
-	register size_t idx = 0;
-
-	if (format.case_sensitive) {
-
-		do {
-
-			if (simple_string_a[idx] != simple_string_b[idx]) {
-
-				return _LIBCONFINI_FALSE_;
-
-			}
-
-		} while (simple_string_a[idx++]);
-
-		return _LIBCONFINI_TRUE_;
-
-	}
-
-	do {
-
-		if (_LIBCONFINI_CHR_CASEFOLD_(simple_string_a[idx]) != _LIBCONFINI_CHR_CASEFOLD_(simple_string_b[idx])) {
-
-			return _LIBCONFINI_FALSE_;
-
-		}
-
-	} while (simple_string_a[idx++]);
-
-	return _LIBCONFINI_TRUE_;
-
-}
-
-
-											/** @utility{ini_string_match_si} **/
-/**
-
-	@brief			Compares a simple string and an INI string and and checks
-					whether they match
-	@param			ini_string		The INI string escaped according to
-									@p format
-	@param			simple_string	The simple string
-	@param			format			The format of the INI file
-	@return			A boolean: `true` if the two strings match, `false` otherwise
-
-	This function grants that the result of the comparison between a simple string
-	and an INI string
-
-	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.c}
-	printf(
-		"%s\n",
-		ini_string_match_si(my_simple_string, my_ini_string, format) ?
-			"They match"
-		:
-			"They don't match"
-	);
-	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-	will always match the result of the _literal_ comparison between the simple
-	string and the INI string after the latter has been parsed by
-	#ini_string_parse() when `format.do_not_collapse_values` is set to `false`.
-
-	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.c}
-	ini_string_parse(my_ini_string, format);
-
-	printf(
-		"%s\n",
-		ini_string_match_ss(my_simple_string, my_ini_string, format) ?
-			"They match"
-		:
-			"They don't match"
-	);
-	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-	INI strings are the strings typically dispatched by #load_ini_file(),
-	#load_ini_path() or #strip_ini_cache(), which may contain quotes and the three
-	escape sequences `\\`, `\'` and `\"`. Simple strings are user-given strings or
-	the result of #ini_string_parse().
-
-	In order to be suitable for both names and values, **this function always
-	considers sequences of one or more spaces out of quotes in the INI string as
-	collapsed**, even when `format.do_not_collapse_values` is set to `true`.
-
-	The @p format argument is used for the following fields:
-
-	- `format.case_sensitive`
-	- `format.no_double_quotes`
-	- `format.no_single_quotes`
-	- `format.multiline_nodes`
-
-	@include topics/ini_string_match_si.c
-
-**/
-bool ini_string_match_si (
-	const char * const simple_string,
-	const char * const ini_string,
-	const IniFormat format
-) {
-
-	/*
-
-	Mask `abcd` (8 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Format supports escape sequences (const)
-		FLAG_8		Unescaped single quotes are odd right now
-		FLAG_16		Unescaped double quotes are odd right now
-		FLAG_32		This is an escaped single/double quote in a format that supports
-					single/double quotes
-		FLAG_64		This is a space
-		FLAG_128	Skip this character
-
-	*/
-
-	register uint8_t abcd	=	INIFORMAT_HAS_NO_ESC(format) ?
-									67
-								:
-									68 | (format.no_double_quotes << 1) | format.no_single_quotes;
-
-	register size_t idx_i = 0;
-	size_t idx_s = 0, nbacksl = 0;
-
-
-	/* \                                /\
-	\ */     si_match:                 /* \
-	 \/     ______________________     \ */
-
-
-	if ((abcd & 4) && ini_string[idx_i] == _LIBCONFINI_BACKSLASH_) {
-
-		for (abcd &= 63, nbacksl++; ini_string[++idx_i] == _LIBCONFINI_BACKSLASH_; nbacksl++);
-
-	}
-
-	abcd	=	!(abcd & 10) && ini_string[idx_i] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-					(
-						nbacksl & 1 ?
-							(abcd & 63) | 32
-						:
-							((abcd & 223) | 128) ^ 16
-					)
-				: !(abcd & 17) && ini_string[idx_i] == _LIBCONFINI_SINGLE_QUOTES_ ?
-					(
-						nbacksl & 1 ?
-							(abcd & 63) | 32
-						:
-							((abcd & 223) | 128) ^ 8
-					)
-				: (abcd & 24) || !is_some_space(ini_string[idx_i], _LIBCONFINI_WITH_EOL_) ?
-					abcd & 31
-				: abcd & 64 ?
-					(abcd & 223) | 128
-				:
-					(abcd & 95) | 64;
-
-
-	if (nbacksl) {
-
-		nbacksl = ((abcd & 32 ? nbacksl : nbacksl + 1) >> 1) + 1;
-
-		while (--nbacksl) {
-
-			if (simple_string[idx_s++] != _LIBCONFINI_BACKSLASH_) {
-
-				return _LIBCONFINI_FALSE_;
-
-			}
-
-		}
-
-	}
-
-	if ((abcd & 128) || ((abcd & 64) && !simple_string[idx_s])) {
-
-		idx_i++;
-		goto si_match;
-
-	}
-
-	if (
-		abcd & 64 ?
-			simple_string[idx_s] != _LIBCONFINI_COLLAPSED_ || !simple_string[idx_s + 1]
-		: format.case_sensitive ?
-			ini_string[idx_i] != simple_string[idx_s]
-		:
-			_LIBCONFINI_CHR_CASEFOLD_(ini_string[idx_i]) != _LIBCONFINI_CHR_CASEFOLD_(simple_string[idx_s])
-	) {
-
-		return _LIBCONFINI_FALSE_;
-
-	}
-
-	idx_s++;
-
-	if (ini_string[idx_i++]) {
-
-		goto si_match;
-
-	}
-
-	return _LIBCONFINI_TRUE_;
-
-}
-
-
-											/** @utility{ini_string_match_ii} **/
-/**
-
-	@brief			Compares two INI strings and checks whether they match
-	@param			ini_string_a	The first INI string unescaped according to
-									@p format
-	@param			ini_string_b	The second INI string unescaped according to
-									@p format
-	@param			format			The format of the INI file
-	@return			A boolean: `true` if the two strings match, `false` otherwise
-
-	This function grants that the result of the comparison between two INI strings
-
-	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.c}
-	printf(
-		"%s\n",
-		ini_string_match_ii(my_ini_string_1, my_ini_string_2, format) ?
-			"They match"
-		:
-			"They don't match"
-	);
-	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-	will always match the result of the _literal_ comparison between the same two
-	INI strings after these have been parsed by #ini_string_parse() when
-	`format.do_not_collapse_values` is set to `false`.
-
-	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.c}
-	ini_string_parse(my_ini_string_1, format);
-	ini_string_parse(my_ini_string_2, format);
-
-	printf("%s\n",
-		ini_string_match_ss(my_ini_string_1, my_ini_string_2, format) ?
-			"They match"
-		:
-			"They don't match"
-	);
-	~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-	INI strings are the strings typically dispatched by #load_ini_file(),
-	#load_ini_path() or #strip_ini_cache(), which may contain quotes and the three
-	escape sequences `\\`, `\'` and `\"`.
-
-	In order to be suitable for both names and values, **this function always
-	considers sequences of one or more spaces out of quotes in both strings as
-	collapsed**, even when `format.do_not_collapse_values` is set to `true`.
-
-	The @p format argument is used for the following fields:
-
-	- `format.case_sensitive`
-	- `format.no_double_quotes`
-	- `format.no_single_quotes`
-	- `format.multiline_nodes`
-
-**/
-bool ini_string_match_ii (
-	const char * const ini_string_a,
-	const char * const ini_string_b,
-	const IniFormat format
-) {
-
-	const _LIBCONFINI_CHARBOOL_ has_escape = !INIFORMAT_HAS_NO_ESC(format);
-	register uint8_t side = 1;
-	register _LIBCONFINI_CHARBOOL_ turn_allowed = _LIBCONFINI_TRUE_;
-	uint8_t abcd_pair[2];
-	const char * chrptr_pair[2] = { ini_string_a, ini_string_b };
-	size_t nbacksl_pair[2];
-
-	/*
-
-	Masks `abcd_pair[0]` and  `abcd_pair[1]` (7 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Unescaped single quotes are odd right now
-		FLAG_8		Unescaped double quotes are odd right now
-		FLAG_16		We are in an odd sequence of backslashes and format supports
-					escape sequences
-		FLAG_32		This is a space
-		FLAG_64		Skip this character
-
-	*/
-
-	abcd_pair[1] = *abcd_pair = 32 | (format.no_double_quotes << 1) | format.no_single_quotes;
-
-
-	/* \                                /\
-	\ */     ii_match:                 /* \
-	 \/     ______________________     \ */
-
-
-	nbacksl_pair[side] = 0;
-
-	if (has_escape && *chrptr_pair[side] == _LIBCONFINI_BACKSLASH_) {
-
-		for (nbacksl_pair[side]++; *(++chrptr_pair[side]) == _LIBCONFINI_BACKSLASH_; nbacksl_pair[side]++);
-
-		abcd_pair[side] = nbacksl_pair[side] & 1 ? (abcd_pair[side] & 31) | 16 : abcd_pair[side] & 15;
-
-		if (
-			(
-				(abcd_pair[side] & 9) || *chrptr_pair[side] != _LIBCONFINI_SINGLE_QUOTES_
-			) && (
-				(abcd_pair[side] & 6) || *chrptr_pair[side] != _LIBCONFINI_DOUBLE_QUOTES_
-			)
-		) {
-
-			nbacksl_pair[side]++;
-
-		}
-
-	} else {
-
-		abcd_pair[side]	=	!(abcd_pair[side] & 25) && *chrptr_pair[side] == _LIBCONFINI_SINGLE_QUOTES_ ?
-								((abcd_pair[side] & 111) | 64) ^ 4
-							: !(abcd_pair[side] & 22) && *chrptr_pair[side] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-								((abcd_pair[side] & 111) | 64) ^ 8
-							: !(abcd_pair[side] & 12) && is_some_space(*chrptr_pair[side], _LIBCONFINI_WITH_EOL_) ?
-								(abcd_pair[side] & 111) | 96
-							: *chrptr_pair[side] ?
-								abcd_pair[side] & 47
-							:
-								abcd_pair[side] & 15;
-
-
-		if (abcd_pair[side] & 64) {
-
-			chrptr_pair[side]++;
-			goto ii_match;
-
-		}
-
-	}
-
-	if (side && turn_allowed) {
-
-		side ^= 1;
-		goto ii_match;
-
-	}
-
-	turn_allowed = _LIBCONFINI_TRUE_;
-
-	if (*nbacksl_pair || nbacksl_pair[1]) {
-
-		if (*nbacksl_pair >> 1 != nbacksl_pair[1] >> 1) {
-
-			return _LIBCONFINI_FALSE_;
-
-		}
-
-		side = 1;
-		goto ii_match;
-
-	}
-
-	if (
-		(
-			abcd_pair[side ^ 1] & 32 ?
-				!(abcd_pair[side] & 32)
-			:
-				abcd_pair[(side ^= 1) ^ 1] & 32
-		) && *chrptr_pair[side]
-	) {
-
-		if (*chrptr_pair[side]++ != _LIBCONFINI_COLLAPSED_) {
-
-			return _LIBCONFINI_FALSE_;
-
-		}
-
-		abcd_pair[side ^ 1] &= 95;
-		turn_allowed = _LIBCONFINI_FALSE_;
-		goto ii_match;
-
-	}
-
-	if (
-		format.case_sensitive ?
-			**chrptr_pair != *chrptr_pair[1]
-		:
-			_LIBCONFINI_CHR_CASEFOLD_(**chrptr_pair) != _LIBCONFINI_CHR_CASEFOLD_(*chrptr_pair[1])
-	) {
-
-		return _LIBCONFINI_FALSE_;
-
-	}
-
-	if (**chrptr_pair) {
-
-		(*chrptr_pair)++;
-
-	}
-
-	if (*chrptr_pair[1]) {
-
-		chrptr_pair[1]++;
-
-	}
-
-	if (**chrptr_pair || *chrptr_pair[1]) {
-
-		*abcd_pair &= 95;
-		abcd_pair[1] &= 95;
-		side = 1;
-		goto ii_match;
-
-	}
-
-	return _LIBCONFINI_TRUE_;
-
-}
-
-
-												/** @utility{ini_array_match} **/
-/**
-
-	@brief			Compares two INI arrays and checks whether they match
-	@param			ini_string_a	The first INI array
-	@param			ini_string_b	The second INI array
-	@param			delimiter		The delimiter between the array members -- if
-									zero (see #INI_ANY_SPACE), any space is
-									delimiter (`/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`)
-	@param			format			The format of the INI file
-	@return			A boolean: `true` if the two arrays match, `false` otherwise
-
-	This function grants that the result of the comparison between two INI arrays
-	will always match the the _literal_ comparison between the individual members
-	of both arrays after these have been parsed, one by one, by #ini_string_parse()
-	(with `format.do_not_collapse_values` set to `false`).
-
-	This function can be used, with `'.'` as delimiter, to compare section paths.
-
-	INI strings are the strings typically dispatched by #load_ini_file(),
-	#load_ini_path() or #strip_ini_cache(), which may contain quotes and the three
-	escape sequences `\\`, `\'` and `\"`.
-
-	In order to be suitable for both names and values, **this function always
-	considers sequences of one or more spaces out of quotes in both strings as
-	collapsed**, even when `format.do_not_collapse_values` is set to `true`.
-
-	The @p format argument is used for the following fields:
-
-	- `format.case_sensitive`
-	- `format.no_double_quotes`
-	- `format.no_single_quotes`
-	- `format.multiline_nodes`
-
-**/
-bool ini_array_match (
-	const char * const ini_string_a,
-	const char * const ini_string_b,
-	const char delimiter,
-	const IniFormat format
-) {
-
-	if (_LIBCONFINI_IS_ESC_CHAR_(delimiter, format)) {
-
-		/*
-
-			We have no delimiters (array has only one member)
-
-		*/
-
-		return ini_string_match_ii(ini_string_a, ini_string_b, format);
-
-	}
-
-	const _LIBCONFINI_CHARBOOL_ has_escape = !INIFORMAT_HAS_NO_ESC(format);
-	register uint8_t side = 1;
-	register _LIBCONFINI_CHARBOOL_ turn_allowed = _LIBCONFINI_TRUE_;
-	uint8_t abcd_pair[2];
-	size_t nbacksl_pair[2];
-	const char * chrptr_pair[2] = {
-		ini_string_a + ltrim_s(ini_string_a, 0, _LIBCONFINI_WITH_EOL_),
-		ini_string_b + ltrim_s(ini_string_b, 0, _LIBCONFINI_WITH_EOL_)
-	};
-
-	/*
-
-	Masks `abcd_pair[0]` and  `abcd_pair[1]` (8 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Unescaped single quotes are odd right now
-		FLAG_8		Unescaped double quotes are odd right now
-		FLAG_16		We are in an odd sequence of backslashes and format supports
-					escape sequences
-		FLAG_32		This is a space
-		FLAG_64		This is a delimiter
-		FLAG_128	Skip this character
-
-	*/
-
-	abcd_pair[1] = *abcd_pair = 32 | (format.no_double_quotes << 1) | format.no_single_quotes;
-
-
-	/* \                                /\
-	\ */     delimited_match:          /* \
-	 \/     ______________________     \ */
-
-
-	nbacksl_pair[side] = 0;
-
-	if (has_escape && *chrptr_pair[side] == _LIBCONFINI_BACKSLASH_) {
-
-		for (nbacksl_pair[side]++; *(++chrptr_pair[side]) == _LIBCONFINI_BACKSLASH_; nbacksl_pair[side]++);
-
-		abcd_pair[side] = nbacksl_pair[side] & 1 ? (abcd_pair[side] & 31) | 16 : abcd_pair[side] & 15;
-
-		if (
-			(
-				(abcd_pair[side] & 9) || *chrptr_pair[side] != _LIBCONFINI_SINGLE_QUOTES_
-			) && (
-				(abcd_pair[side] & 6) || *chrptr_pair[side] != _LIBCONFINI_DOUBLE_QUOTES_
-			)
-		) {
-
-			nbacksl_pair[side]++;
-
-		}
-
-	} else {
-
-		abcd_pair[side]	=	!(abcd_pair[side] & 12) && is_some_space(*chrptr_pair[side], _LIBCONFINI_WITH_EOL_) ?
-								(
-									delimiter || (abcd_pair[side] & 64) ?
-										(abcd_pair[side] & 239) | 160
-									:
-										(abcd_pair[side] & 111) | 96
-								)
-							: delimiter && !(abcd_pair[side] & 12) && *chrptr_pair[side] == delimiter ?
-								(abcd_pair[side] & 111) | 96
-							: !(abcd_pair[side] & 25) && *chrptr_pair[side] == _LIBCONFINI_SINGLE_QUOTES_ ?
-								((abcd_pair[side] & 175) | 128) ^ 4
-							: !(abcd_pair[side] & 22) && *chrptr_pair[side] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-								((abcd_pair[side] & 175) | 128) ^ 8
-							: *chrptr_pair[side] ?
-								abcd_pair[side] & 47
-							: delimiter ?
-								abcd_pair[side] & 15
-							:
-								(abcd_pair[side] & 79) ^ 64;
-
-
-		if (abcd_pair[side] & 128) {
-
-			chrptr_pair[side]++;
-			goto delimited_match;
-
-		}
-
-	}
-
-	if (side && turn_allowed) {
-
-		side ^= 1;
-		goto delimited_match;
-
-	}
-
-	turn_allowed = _LIBCONFINI_TRUE_;
-
-	if (*nbacksl_pair || nbacksl_pair[1]) {
-
-		if (*nbacksl_pair >> 1 != nbacksl_pair[1] >> 1) {
-
-			return _LIBCONFINI_FALSE_;
-
-		}
-
-		side = 1;
-		goto delimited_match;
-
-	}
-
-	if ((*abcd_pair ^ abcd_pair[1]) & 64) {
-
-		return _LIBCONFINI_FALSE_;
-
-	}
-
-	if (
-		!(
-			abcd_pair[side ^ 1] & 32 ?
-				abcd_pair[side] & 96
-			:
-				(abcd_pair[(side ^= 1) ^ 1] & 96) ^ 32
-		) && *chrptr_pair[side]
-	) {
-
-		if (*chrptr_pair[side]++ != _LIBCONFINI_COLLAPSED_) {
-
-			return _LIBCONFINI_FALSE_;
-
-		}
-
-		abcd_pair[side ^ 1] &= 223;
-		turn_allowed = _LIBCONFINI_FALSE_;
-		goto delimited_match;
-
-	}
-
-	if (~*abcd_pair & 64) {
-
-		if (
-			format.case_sensitive ?
-				**chrptr_pair != *chrptr_pair[1]
-			:
-				_LIBCONFINI_CHR_CASEFOLD_(**chrptr_pair) != _LIBCONFINI_CHR_CASEFOLD_(*chrptr_pair[1])
-		) {
-
-			return _LIBCONFINI_FALSE_;
-
-		}
-
-		*abcd_pair &= 223;
-		abcd_pair[1] &= 223;
-
-	}
-
-	if (**chrptr_pair) {
-
-		(*chrptr_pair)++;
-
-	}
-
-	if (*chrptr_pair[1]) {
-
-		chrptr_pair[1]++;
-
-	}
-
-	if (**chrptr_pair || *chrptr_pair[1]) {
-
-		side = 1;
-		goto delimited_match;
-
-	}
-
-	return _LIBCONFINI_TRUE_;
-
-}
-
-
-													/** @utility{ini_unquote} **/
-/**
-
-	@brief			Unescapes `\'`, `\"`, and `\\` and removes all unescaped quotes
-					(if single/double quotes are considered metacharacters in
-					respect to the format given)
-	@param			ini_string		The string to be unescaped
-	@param			format			The format of the INI file
-	@return			The new length of the string
-
-	This function is very similar to #ini_string_parse(), except that does not
-	bother collapsing the sequences of more than one space that might result from
-	removing empty quotes. Its purpose is to be used to parse key and section names,
-	since these are always dispatched as already collapsed. In order to parse
-	values, or array parts listed in values, please use #ini_string_parse().
-
-	If you only need to compare @p ini_string with another string, consider to use
-	#ini_string_match_si() and #ini_string_match_ii() instead of parsing the former
-	and perform a simple comparison afterwards. These two functions are in fact able
-	to check directly for equality between unparsed INI strings without actually
-	modifiyng them.
-
-	Usually @p ini_string comes from an #IniDispatch (but any other string may be
-	used as well). If the string does not contain quotes, or if quotes are
-	considered to be normal characters, no changes will be made.
-
-	@note	If @p ini_string comes from #INI_GLOBAL_IMPLICIT_VALUE this function is
-			no-op and will only return the value of #INI_GLOBAL_IMPLICIT_V_LEN minus
-			the offset of @p ini_string within #INI_GLOBAL_IMPLICIT_VALUE.
-
-	The @p format argument is used for the following fields:
-
-	- `format.no_single_quotes`
-	- `format.no_double_quotes`
-	- `format.multiline_nodes`
-
-	@include topics/ini_string_parse.c
-
-**/
-size_t ini_unquote (char * const ini_string, const IniFormat format) {
-
-	if (_LIBCONFINI_IMPLICIT_RANGE_(ini_string)) {
-
-		return INI_GLOBAL_IMPLICIT_V_LEN + INI_GLOBAL_IMPLICIT_VALUE - ini_string;
-
-	}
-
-	register size_t idx = 0;
-
-	if (INIFORMAT_HAS_NO_ESC(format)) {
-
-		/*
-
-			There are no escape sequences... I will just return the length of the
-			string...
-
-		*/
-
-		while (ini_string[idx++]);
-
-		return idx - 1;
-
-	}
-
-	size_t lshift = 0, nbacksl = 0;
-
-	/*
-
-	Mask `abcd` (6 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Unescaped single quotes are odd right now
-		FLAG_8		Unescaped double quotes are odd right now
-		FLAG_16		This is an unescaped single quote and format supports single
-					quotes
-		FLAG_32		This is an unescaped double quote and format supports double
-					quotes
-
-	*/
-
-	for (register uint8_t abcd = (format.no_double_quotes << 1) | format.no_single_quotes; ini_string[idx]; idx++) {
-
-		abcd	=	!(abcd & 6) && ini_string[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						(abcd & 47) | 32
-					: !(abcd & 9) && ini_string[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						(abcd & 31) | 16
-					:
-						abcd & 15;
-
-
-		if (!(nbacksl & 1) && (abcd & 48)) {
-
-			abcd ^= (abcd >> 2) & 12;
-			lshift++;
-			continue;
-
-		}
-
-		if (ini_string[idx] == _LIBCONFINI_BACKSLASH_) {
-
-			nbacksl++;
-
-		} else {
-
-			if ((nbacksl & 1) && (abcd & 48)) {
-
-				lshift++;
-
-			}
-
-			lshift += nbacksl >> 1;
-			nbacksl = 0;
-
-		}
-
-		if (lshift) {
-
-			ini_string[idx - lshift] = ini_string[idx];
-
-		}
-
-	}
-
-	lshift += nbacksl >> 1;
-
-	for (idx -= lshift; ini_string[idx]; ini_string[idx++] = '\0');
-
-	return idx - lshift;
-
-}
-
-
-												/** @utility{ini_string_parse} **/
-/**
-
-	@brief			Unescapes `\'`, `\"`, and `\\` and removes all unescaped quotes
-					(if single/double quotes are considered metacharacters in
-					respect to the format given); if the format allows it, sequences
-					of one or more spaces out of quotes will be collapsed
-	@param			ini_string		The string to be unescaped
-	@param			format			The format of the INI file
-	@return			The new length of the string
-
-	This function is meant to be used to parse values. In order to parse key and
-	section names please use #ini_unquote().
-
-	If you only need to compare @p ini_string with another string, consider to use
-	#ini_string_match_si() and #ini_string_match_ii() instead of parsing the former
-	and perform a simple comparison afterwards. These two functions are in fact able
-	to check directly for equality between unparsed INI strings without actually
-	modifying them.
-
-	Usually @p ini_string comes from an #IniDispatch (but any other string may be
-	used as well). If `format.do_not_collapse_values` is set to non-zero, spaces
-	surrounding empty quotes will be collapsed together with the latter.
-
-	@note	If @p ini_string comes from #INI_GLOBAL_IMPLICIT_VALUE this function is
-			no-op and will only return the value of #INI_GLOBAL_IMPLICIT_V_LEN minus
-			the offset of @p ini_string within #INI_GLOBAL_IMPLICIT_VALUE.
-
-	The @p format argument is used for the following fields:
-
-	- `format.no_single_quotes`
-	- `format.no_double_quotes`
-	- `format.multiline_nodes`
-	- `format.do_not_collapse_values`
-
-	@note	`format.multiline_nodes` is used only to figure out whether there are
-			escape sequences or not. For all other purposes new line characters will
-			be considered to be equal to any other space character, even if the
-			format is not multi-line -- new line characters should never appear in
-			non-multi-line formats.
-
-	@include topics/ini_string_parse.c
-
-**/
-size_t ini_string_parse (char * const ini_string, const IniFormat format) {
-
-	if (_LIBCONFINI_IMPLICIT_RANGE_(ini_string)) {
-
-		return INI_GLOBAL_IMPLICIT_V_LEN + INI_GLOBAL_IMPLICIT_VALUE - ini_string;
-
-	}
-
-	/*
-
-	Mask `abcd` (8 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Do not collapse spaces within members (const)
-		FLAG_8		Unescaped single quotes are odd right now
-		FLAG_16		Unescaped double quotes are odd right now
-		FLAG_32		This is an *escaped* single/double quote and format supports
-					single/double quotes
-		FLAG_64		This is a space
-		FLAG_128	Skip this character
-
-	*/
-
-	register uint8_t abcd	=	(format.do_not_collapse_values ? 68 : 64) |
-								(format.no_double_quotes << 1) |
-								format.no_single_quotes;
-
-	size_t idx, lshift;
-
-	if (format.multiline_nodes == INI_NO_MULTILINE) {
-
-		switch (abcd) {
-
-			case 64 | 2 | 1 :
-
-				/*
-
-					There are no escape sequences, but spaces might still need to
-					be collapsed.
-
-				*/
-
-				for (idx = 0, lshift = 0; ini_string[idx]; idx++) {
-
-					abcd = !is_some_space(ini_string[idx], _LIBCONFINI_WITH_EOL_) ? 3 : abcd & 64 ? 195 : 67;
-
-					if (abcd & 128) {
-
-						lshift++;
-
-					} else {
-
-						ini_string[idx - lshift] = abcd & 64 ? _LIBCONFINI_COLLAPSED_ : ini_string[idx];
-
-					}
-
-				}
-
-				for (
-
-					idx	-=	(abcd & 64) && lshift < idx ?
-								++lshift
-							:
-								lshift;
-
-						ini_string[idx];
-
-					ini_string[idx++] = '\0'
-
-				);
-
-				return idx - lshift;
-
-			case 64 | 4 | 2 | 1 :
-
-				/*
-
-					There are no escape sequences and spaces don't need to be
-					collapsed, but left and right trim might still be necessary.
-
-				*/
-
-				return rtrim_h(ini_string, ltrim_hh(ini_string, 0, _LIBCONFINI_WITH_EOL_), _LIBCONFINI_WITH_EOL_);
-
-		}
-
-	}
-
-	/*
-
-		There might be escape sequences...
-
-	*/
-
-	size_t nbacksl = 0;
-
-	for (idx = lshift = 0; ini_string[idx]; idx++) {
-
-		abcd	=	!(abcd & 10) && ini_string[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						(
-							nbacksl & 1 ?
-								(abcd & 63) | 32
-							:
-								((abcd & 223) | 128) ^ 16
-						)
-					: !(abcd & 17) && ini_string[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						(
-							nbacksl & 1 ?
-								(abcd & 63) | 32
-							:
-								((abcd & 223) | 128) ^ 8
-						)
-					: (abcd & 28) || !is_some_space(ini_string[idx], _LIBCONFINI_WITH_EOL_) ?
-						abcd & 31
-					: abcd & 64 ?
-						(abcd & 223) | 128
-					:
-						(abcd & 95) | 64;
-
-
-		if (abcd & 128) {
-
-			lshift++;
-			continue;
-
-		}
-
-		if (ini_string[idx] == _LIBCONFINI_BACKSLASH_) {
-
-			nbacksl++;
-
-		} else {
-
-			if (abcd & 32) {
-
-				lshift++;
-
-			}
-
-			lshift += nbacksl >> 1;
-			nbacksl = 0;
-
-		}
-
-		ini_string[idx - lshift] = abcd & 64 ? _LIBCONFINI_COLLAPSED_ : ini_string[idx];
-
-	}
-
-	lshift += nbacksl >> 1;
-
-	for (
-
-		idx	-=	(abcd & 64) && lshift < idx ?
-					++lshift
-				:
-					lshift;
-
-			ini_string[idx];
-
-		ini_string[idx++] = '\0'
-
-	);
-
-	return	(abcd & 28) ^ 4 ?
-				idx - lshift
-			:
-				rtrim_h(ini_string, idx - lshift, _LIBCONFINI_WITH_EOL_);
-
-}
-
-
-											/** @utility{ini_array_get_length} **/
-/**
-
-	@brief			Gets the length of a stringified INI array in number of members
-	@param			ini_string		The stringified array (it can be `NULL`)
-	@param			delimiter		The delimiter between the array members -- if
-									zero (see #INI_ANY_SPACE), any space is
-									delimiter (`/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`)
-	@param			format			The format of the INI file
-	@return			The length of the INI array
-
-	Usually @p ini_string comes from an #IniDispatch (but any other string may be
-	used as well).
-
-	@note	If @p delimiter matches a metacharacter within the format given (`'\\'`,
-			`'\''` or `'\"'`), its role as metacharacter will have higher priority
-			than its role as delimiter (i.e., the array will have no delimiters and
-			will contain only one member).
-
-**/
-size_t ini_array_get_length (
-	const char * const ini_string,
-	const char delimiter,
-	const IniFormat format
-) {
-
-	if (!ini_string) {
-
-		return 0;
-
-	}
-
-	if (_LIBCONFINI_IS_ESC_CHAR_(delimiter, format)) {
-
-		/*
-
-			We have no delimiters (array has only one member)
-
-		*/
-
-		return 1;
-
-	}
-
-	/*
-
-	Mask `abcd` (8 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Delimiter is not any space (const)
-		FLAG_8		Unescaped single quotes are odd right now
-		FLAG_16		Unescaped double quotes are odd right now
-		FLAG_32		We are in an odd sequence of backslashes
-		FLAG_64		This is a space
-		FLAG_128	This is a delimiter
-
-	*/
-
-	register uint8_t abcd	=	(delimiter ? 64 : 68) |
-								(format.no_double_quotes << 1) |
-								format.no_single_quotes;
-
-	size_t counter = 0;
-
-	for (size_t idx = 0; ini_string[idx]; idx++) {
-
-		/*  Revision #1  */
-
-		abcd	=	!(abcd & 28) && ini_string[idx] == delimiter ?
-						(abcd & 159) | 128
-					: !(abcd & 24) && is_some_space(ini_string[idx], _LIBCONFINI_WITH_EOL_) ?
-						(
-							(abcd & 68) ^ 4 ?
-								(abcd & 95) | 64
-							:
-								(abcd & 223) | 192
-						)
-					: ini_string[idx] == _LIBCONFINI_BACKSLASH_ ?
-						(abcd & 63) ^ 32
-					: !(abcd & 42) && ini_string[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						(abcd & 31) ^ 16
-					: !(abcd & 49) && ini_string[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						(abcd & 31) ^ 8
-					:
-						abcd & 31;
-
-
-		if (abcd & 128) {
-
-			counter++;
-
-		}
-
-	}
-
-	return	!counter || (~abcd & 68) ?
-				counter + 1
-			:
-				counter;
-
-}
-
-
-												/** @utility{ini_array_foreach} **/
-/**
-
-	@brief			Calls a custom function for each member of a stringified INI
-					array, without modifying the content of the buffer -- useful for
-					read-only (`const`) stringified arrays
-	@param			ini_string		The stringified array (it can be `NULL`)
-	@param			delimiter		The delimiter between the array members -- if
-									zero (see #INI_ANY_SPACE), any space is
-									delimiter (`/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`)
-	@param			format			The format of the INI file
-	@param			f_foreach		The function that will be invoked for each array
-									member
-	@param			user_data		A custom argument, or `NULL`
-	@return			Zero for success, otherwise an error code (see `enum`
-					#ConfiniInterruptNo)
-
-	Usually @p ini_string comes from an #IniDispatch (but any other string may be
-	used as well).
-
-	The user given function @p f_foreach (see #IniSubstrHandler data type) will be
-	invoked with six arguments: `ini_string`, `memb_offset` (the offset of the
-	member in bytes), `memb_length` (the length of the member in bytes), `memb_num`
-	(the offset of the member in number of members), `format` (the format of the INI
-	file), `user_data` (the custom argument @p user_data previously passed). If
-	@p f_foreach returns a non-zero value the function #ini_array_foreach() will be
-	interrupted.
-
-	@note	If @p delimiter matches a metacharacter within the format given (`'\\'`,
-			`'\''` or `'\"'`), its role as metacharacter will have higher priority
-			than its role as delimiter (i.e., the array will have no delimiters and
-			will contain only one member).
-
-	Possible return values are: #CONFINI_SUCCESS, #CONFINI_FEINTR.
-
-	@include topics/ini_array_foreach.c.
-
-**/
-int ini_array_foreach (
-	const char * const ini_string,
-	const char delimiter,
-	const IniFormat format,
-	const IniSubstrHandler f_foreach,
-	void * const user_data
-) {
-
-	if (!ini_string) {
-
-		return CONFINI_SUCCESS;
-
-	}
-
-	/*
-
-	Mask `abcd` (8 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Delimiter is not any space (const)
-		FLAG_8		Unescaped single quotes are odd until now
-		FLAG_16		Unescaped double quotes are odd until now
-		FLAG_32		We are in an odd sequence of backslashes
-		FLAG_64		This is not a delimiter
-		FLAG_128	Stop the loop
-
-	*/
-
-	register size_t idx;
-	size_t offs = ltrim_s(ini_string, 0, _LIBCONFINI_WITH_EOL_);
-
-	if (_LIBCONFINI_IS_ESC_CHAR_(delimiter, format)) {
-
-		/*
-
-			We have no delimiters (array has only one member)
-
-		*/
-
-		idx = 0;
-
-		while (ini_string[idx++]);
-
-		return	f_foreach(ini_string, offs, rtrim_s(ini_string + offs, idx - offs - 1, _LIBCONFINI_WITH_EOL_), 0, format, user_data) ?
-					CONFINI_FEINTR
-				:
-					CONFINI_SUCCESS;
-
-	}
-
-	register uint8_t abcd	=	(delimiter ? 4 : 0) |
-								(format.no_double_quotes << 1) |
-								format.no_single_quotes;
-
-	size_t memb_num = 0;
-
-	idx = offs;
-
-	do {
-
-		abcd	=	(delimiter ? ini_string[idx] == delimiter : is_some_space(ini_string[idx], _LIBCONFINI_WITH_EOL_)) ?
-						abcd & 159
-					: ini_string[idx] == _LIBCONFINI_BACKSLASH_ ?
-						(abcd | 64) ^ 32
-					: !(abcd & 42) && ini_string[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						((abcd & 223) | 64) ^ 16
-					: !(abcd & 49) && ini_string[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						((abcd & 223) | 64) ^ 8
-					: ini_string[idx] ?
-						(abcd & 223) | 64
-					:
-						128;
-
-
-		if (!(abcd & 88)) {
-
-			if (
-				f_foreach(
-					ini_string,
-					offs,
-					rtrim_s(ini_string + offs, idx - offs, _LIBCONFINI_WITH_EOL_),
-					memb_num++,
-					format,
-					user_data
-				)
-			) {
-
-				return CONFINI_FEINTR;
-
-			}
-
-			offs = abcd & 128 ? idx + 1 : ltrim_s(ini_string, idx + 1, _LIBCONFINI_WITH_EOL_);
-
-		}
-
-		idx = abcd & 216 ? idx + 1 : offs;
-
-	} while (!(abcd & 128) && ((abcd & 92) || ini_string[idx]));
-
-	return CONFINI_SUCCESS;
-
-}
-
-
-												/** @utility{ini_array_shift} **/
-/**
-
-	@brief			Shifts the location pointed by @p ini_strptr to the next member
-					of the INI array (without modifying the content of the buffer),
-					or to `NULL` if the INI array has no more members  -- useful for
-					read-only (`const`) stringified arrays
-	@param			ini_strptr		The memory location of the stringified array --
-									it cannot be `NULL`, but it can point to `NULL`
-	@param			delimiter		The delimiter between the array members -- if
-									zero (see #INI_ANY_SPACE), any space is
-									delimiter (`/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`)
-	@param			format			The format of the INI file
-	@return			The length of the array member that has been left behind
-
-	Usually @p ini_strptr comes from an #IniDispatch (but any other string may be
-	used as well).
-
-	@note	If @p delimiter matches a metacharacter within the format given (`'\\'`,
-			`'\''` or `'\"'`), its role as metacharacter will have higher priority
-			than its role as delimiter (i.e., the array will have no delimiters and
-			will contain only one member).
-
-	@include topics/ini_array_shift.c
-
-**/
-size_t ini_array_shift (const char ** const ini_strptr, const char delimiter, const IniFormat format) {
-
-	size_t toklen = 0;
-
-	if (*ini_strptr && !_LIBCONFINI_IS_ESC_CHAR_(delimiter, format)) {
-
-		if (!delimiter) {
-
-			toklen = ltrim_s(*ini_strptr, 0, _LIBCONFINI_WITH_EOL_);
-
-		}
-
-		toklen += get_metachar_pos(*ini_strptr + toklen, delimiter, format);
-		*ini_strptr += toklen;
-		toklen = rtrim_s(*ini_strptr - toklen, toklen, _LIBCONFINI_WITH_EOL_);
-
-		if (**ini_strptr) {
-
-			*ini_strptr += ltrim_s(*ini_strptr, 1, _LIBCONFINI_WITH_EOL_);
-
-			if (delimiter || **ini_strptr) {
-
-				return toklen;
-
-			}
-
-		}
-
-	}
-
-	*ini_strptr = (char *) 0;
-	return toklen;
-
-}
-
-
-												/** @utility{ini_array_collapse} **/
-/**
-
-	@brief			Compresses the distribution of the data in a stringified INI
-					array by removing all the white spaces that surround its
-					delimiters, empty quotes, collapsable spaces, etc
-	@param			ini_string		The stringified array
-	@param			delimiter		The delimiter between the array members --
-									if zero (`INI_ANY_SPACE`) any space is
-									delimiter (`/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`)
-	@param			format			The format of the INI file
-	@return			The new length of the stringified array
-
-	Out of quotes similar to ECMAScript
-	`ini_string.replace(new RegExp("^\\s+|\\s*(?:(" + delimiter + ")\\s*|($))", "g"), "$1$2")`.
-	If #INI_ANY_SPACE (`0`) is used as delimiter, one or more different spaces
-	(`/[\t \v\f\n\r]+/`) will be always collapsed to one space, independently of
-	what the format says.
-
-	Usually @p ini_string comes from an #IniDispatch (but any other string may be
-	used as well).
-
-	This function can be useful before invoking `memcpy()` using @p ini_string as
-	source, when saving memory is a priority.
-
-	The @p format argument is used for the following fields:
-
-	- `format.no_single_quotes`
-	- `format.no_double_quotes`
-	- `format.do_not_collapse_values`
-	- `format.preserve_empty_quotes`
-
-	Examples:
-
-	1. Using comma as delimiter:
-	   - Before: `&nbsp;first&nbsp;&nbsp; ,&nbsp;&nbsp;&nbsp; second&nbsp;&nbsp;
-	     ,&nbsp;&nbsp; third&nbsp;&nbsp; ,&nbsp; etc.&nbsp;&nbsp;`
-	   - After: `first,second,third,etc.`
-	2. Using `INI_ANY_SPACE` as delimiter:
-	   - Before: `&nbsp;&nbsp;first&nbsp;&nbsp;&nbsp; second&nbsp;&nbsp;&nbsp;
-	     third&nbsp;&nbsp;&nbsp;&nbsp; etc.&nbsp;&nbsp;&nbsp;`
-	   - After: `first second third etc.`
-
-	@note	If @p ini_string comes from #INI_GLOBAL_IMPLICIT_VALUE this function is
-			no-op and will only return the value of #INI_GLOBAL_IMPLICIT_V_LEN minus
-			the offset of @p ini_string within #INI_GLOBAL_IMPLICIT_VALUE.
-
-	@note	If @p delimiter matches a metacharacter within the format given (`'\\'`,
-			`'\''` or `'\"'`), its role as metacharacter will have higher priority
-			than its role as delimiter (i.e., the array will have no delimiters and
-			will contain only one member).
-
-	@include topics/ini_array_collapse.c
-
-	@note	The actual space occupied by the array might get reduced further after
-			each member is parsed by #ini_string_parse().
-
-**/
-size_t ini_array_collapse (char * const ini_string, const char delimiter, const IniFormat format) {
-
-	if (_LIBCONFINI_IMPLICIT_RANGE_(ini_string)) {
-
-		return INI_GLOBAL_IMPLICIT_V_LEN + INI_GLOBAL_IMPLICIT_VALUE - ini_string;
-
-	}
-
-	if (_LIBCONFINI_IS_ESC_CHAR_(delimiter, format)) {
-
-		/*
-
-			We have no delimiters (array has only one member)
-
-		*/
-
-		switch ((format.preserve_empty_quotes << 1) | format.do_not_collapse_values) {
-
-			case 0: return collapse_everything(ini_string, format);
-			case 1: return collapse_empty_quotes(ini_string, format);
-			case 2: return collapse_spaces(ini_string, format);
-			case 3: return rtrim_h(ini_string, ltrim_hh(ini_string, 0, _LIBCONFINI_WITH_EOL_), _LIBCONFINI_WITH_EOL_);
-
-		}
-
-	}
-
-	/*
-
-	Mask `abcd` (16 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Do not collapse spaces within members (const)
-		FLAG_8		Preserve empty quotes (const)
-		FLAG_16		Any space is delimiter (const)
-		FLAG_32		Unescaped single quotes are odd right now
-		FLAG_64		Unescaped double quotes are odd right now
-		FLAG_128	We are in an odd sequence of backslashes
-		FLAG_256	This is *not* a delimiter out of quotes
-		FLAG_512	This is *not* a space out of quotes
-		FLAG_1024	These are some quotes
-		FLAG_2048	These are some quotes or among the last spaces are some empty
-					quotes
-		FLAG_4096	Save current `idx_d` in `fallback`
-		FLAG_8192	Restore `idx_d` from `fallback` before writing
-		FLAG_16384	Decrease `idx_d` before writing
-		FLAG_32768	Keep increasing `idx_d` after writing
-
-	*/
-
-	size_t idx_s = 0, idx_d = 0, fallback = 0;
-
-	register uint16_t abcd		=	(delimiter ? 0 : 16) |
-									(format.preserve_empty_quotes << 3) |
-									(format.do_not_collapse_values << 2) |
-									(format.no_double_quotes << 1) |
-									format.no_single_quotes;
-
-
-	for (; ini_string[idx_s]; idx_s++) {
-
-		/*  Revision #1  */
-
-		abcd	=	!(abcd & 112) && ini_string[idx_s] == delimiter ?
-						(
-							(abcd & 536) && ((abcd & 1560) ^ 8) && ((abcd & 1560) ^ 1544) && ((abcd & 1304) ^ 1032) ?
-								(abcd & 33407) | 33280
-							:
-								(abcd & 41599) | 41472
-						)
-					: !(abcd & 96) && is_some_space(ini_string[idx_s], _LIBCONFINI_WITH_EOL_) ?
-						(
-							!((abcd & 1816) ^ 1800) ?
-								(abcd & 43391) | 40960
-							: !(~abcd & 1560) ?
-								(abcd & 41087) | 40960
-							: !((abcd & 536) ^ 528) || !((abcd & 1560) ^ 536) || !((abcd & 1560) ^ 1048) ?
-								(abcd & 32895) | 32768
-							: !(abcd & 540) || !((abcd & 1564) ^ 8) || !((abcd & 536) ^ 16) || !((abcd & 1560) ^ 24) ?
-								abcd & 2431
-							: ((abcd & 540) ^ 4) && ((abcd & 796) ^ 12) && ((abcd & 1564) ^ 12) && ((abcd & 1308) ^ 1032) ?
-								(abcd & 39295) | 36864
-							:
-								(abcd & 35199) | 32768
-						)
-					: !(abcd & 193) && ini_string[idx_s] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						(
-							!((abcd & 3896) ^ 8) ?
-								(abcd & 44927) | 44064
-							: !((abcd & 3896) ^ 2056) ?
-								(abcd & 36735) | 36128
-							: !((abcd & 1056) ^ 32) ?
-								(abcd & 33631) | 33536
-							: !(abcd & 40) || !(~abcd & 1064) ?
-								((abcd & 36735) | 35840) ^ 32
-							: ((abcd & 1064) ^ 1032) && ((abcd & 1064) ^ 1056) ?
-								(abcd & 40831) | 39968
-							:
-								((abcd & 20351) | 19456) ^ 32
-						)
-					: !(abcd & 162) && ini_string[idx_s] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						(
-							!((abcd & 3928) ^ 8) ?
-								(abcd & 44927) | 44096
-							: !((abcd & 3928) ^ 2056) ?
-								(abcd & 36735) | 36160
-							: !((abcd & 1088) ^ 64) ?
-								(abcd & 33599) | 33536
-							: !(abcd & 72) || !(~abcd & 1096) ?
-								((abcd & 36735) | 35840) ^ 64
-							: ((abcd & 1096) ^ 1088) && ((abcd & 1096) ^ 1032) ?
-								(abcd & 40831) | 40000
-							:
-								((abcd & 20351) | 19456) ^ 64
-						)
-					: ini_string[idx_s] == _LIBCONFINI_BACKSLASH_ ?
-						(
-							(abcd & 888) && ((abcd & 1144) ^ 1032) && ((abcd & 1144) ^ 1048) && ((abcd & 2936) ^ 8) ?
-								((abcd & 33791) | 33536) ^ 128
-							:
-								((abcd & 41983) | 41728) ^ 128
-						)
-					: (abcd & 888) && ((abcd & 1144) ^ 1032) && ((abcd & 1144) ^ 1048) && ((abcd & 2936) ^ 8) ?
-						(abcd & 33663) | 33536
-					:
-						(abcd & 41855) | 41728;
-
-
-		ini_string[
-			abcd & 16384 ?
-				--idx_d
-			: abcd & 8192 ?
-				(idx_d = fallback)
-			: abcd & 4096 ?
-				(fallback = idx_d)
-			:
-				idx_d
-		]							=	(abcd & 1636) && ((abcd & 1392) ^ 16) ?
-											ini_string[idx_s]
-										:
-											_LIBCONFINI_COLLAPSED_;
-
-
-		if (abcd & 32768) {
-
-			idx_d++;
-
-		}
-
-	}
-
-	for (
-
-		idx_s	=	((abcd & 16) && !idx_d) || (!(~abcd & 1040) && idx_d < 4) ?
-						(idx_d = 0)
-					: !(abcd & 536) || !(~abcd & 1544) || !((abcd & 1560) ^ 8) || !((abcd & 1304) ^ 1032) ?
-						(idx_d = fallback)
-					: !((abcd & 1624) ^ 1104) || !((abcd & 1592) ^ 1072) ?
-						(idx_d -= 2)
-					: ((abcd & 1552) ^ 16) && ((abcd & 632) ^ 16) && ((abcd & 1624) ^ 1616) && ((abcd & 1592) ^ 1584) ?
-						idx_d
-					:
-						--idx_d;
-
-			ini_string[idx_s];
-
-		ini_string[idx_s++] = '\0'
-
-	);
-
-	return idx_d;
-
-}
-
-
-												/** @utility{ini_array_break} **/
-/**
-
-	@brief			Replaces the first delimiter found (together with the spaces
-					that surround it) with `\0`
-	@param			ini_string		The stringified array (it can be `NULL`)
-	@param			delimiter		The delimiter between the array members -- if
-									zero (see #INI_ANY_SPACE), any space is
-									delimiter (`/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`)
-	@param			format			The format of the INI file
-	@return			A pointer to the remaining INI array or `NULL` if the remaining
-					array is empty
-
-	Usually @p ini_string comes from an #IniDispatch (but any other string may be
-	used as well).
-
-	Similarly to `strtok_r()` this function can be used only once for a given
-	string.
-
-	@note	If @p ini_string comes from #INI_GLOBAL_IMPLICIT_VALUE this function is
-			no-op and will return `NULL`.
-
-	@note	If @p delimiter matches a metacharacter within the format given (`'\\'`,
-			`'\''` or `'\"'`), its role as metacharacter will have higher priority
-			than its role as delimiter (i.e., the array will have no delimiters and
-			will contain only one member).
-
-	@include topics/ini_array_break.c
-
-**/
-char * ini_array_break (char * const ini_string, const char delimiter, const IniFormat format) {
-
-	if (ini_string && !_LIBCONFINI_IMPLICIT_RANGE_(ini_string)) {
-
-		char * remnant;
-
-		if (_LIBCONFINI_IS_ESC_CHAR_(delimiter, format)) {
-
-			/*
-
-				We have no delimiters (array has only one member)
-
-			*/
-
-			remnant = ini_string;
-
-			while (*remnant++);
-
-			rtrim_h(ini_string, remnant - ini_string - 1, _LIBCONFINI_WITH_EOL_);
-
-		} else {
-
-			remnant = ini_string + get_metachar_pos(ini_string, delimiter, format);
-
-			if (*remnant) {
-
-				*remnant = '\0';
-				rtrim_h(ini_string, remnant - ini_string, _LIBCONFINI_WITH_EOL_);
-				remnant += ltrim_h(remnant, 1, _LIBCONFINI_WITH_EOL_);
-
-				if (delimiter || *remnant) {
-
-					return remnant;
-
-				}
-
-			}
-
-		}
-
-	}
-
-	return (char *) 0;
-
-}
-
-
-												/** @utility{ini_array_release} **/
-/**
-
-	@brief			Replaces the first delimiter found (together with the spaces
-					that surround it) with `\0`, then shifts the location pointed by
-					@p ini_strptr to the next member of the INI array, or to `NULL`
-					if the INI array has no more members
-	@param			ini_strptr		The memory location of the stringified array --
-									it cannot be `NULL`, but it can point to `NULL`
-	@param			delimiter		The delimiter between the array members -- if
-									zero (see #INI_ANY_SPACE), any space is
-									delimiter (`/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`)
-	@param			format			The format of the INI file
-	@return			The array member that has been released
-
-	Usually @p ini_strptr comes from an #IniDispatch (but any other string may be
-	used as well).
-
-	Similarly to `strtok_r()` this function can be used only once for a given
-	string.
-
-	@note	If @p ini_string comes from #INI_GLOBAL_IMPLICIT_VALUE this function is
-			no-op and will set @p ini_strptr to `NULL`.
-
-	@note	If @p delimiter matches a metacharacter within the format given (`'\\'`,
-			`'\''` or `'\"'`), its role as metacharacter will have higher priority
-			than its role as delimiter (i.e., the array will have no delimiters and
-			will contain only one member).
-
-	@include topics/ini_array_release.c
-
-**/
-char * ini_array_release (char ** const ini_strptr, const char delimiter, const IniFormat format) {
-
-	char * const token = *ini_strptr;
-
-	if (token && !_LIBCONFINI_IMPLICIT_RANGE_(token) && !_LIBCONFINI_IS_ESC_CHAR_(delimiter, format)) {
-
-		*ini_strptr += get_metachar_pos(*ini_strptr, delimiter, format);
-
-		if (**ini_strptr) {
-
-			**ini_strptr = '\0';
-			rtrim_h(token, *ini_strptr - token, _LIBCONFINI_WITH_EOL_);
-			*ini_strptr += ltrim_h(*ini_strptr, 1, _LIBCONFINI_WITH_EOL_);
-
-			if (delimiter || **ini_strptr) {
-
-				return token;
-
-			}
-
-		}
-
-	}
-
-	*ini_strptr = (char *) 0;
-	return token;
-
-}
-
-
-												/** @utility{ini_array_split} **/
-/**
-
-	@brief			Splits a stringified INI array into NUL-separated members and
-					calls a custom function for each member
-	@param			ini_string		The stringified array (it cannot be `NULL`)
-	@param			delimiter		The delimiter between the array members -- if
-									zero (see #INI_ANY_SPACE), any space is
-									delimiter (`/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`)
-	@param			format			The format of the INI file
-	@param			f_foreach		The function that will be invoked for each array
-									member
-	@param			user_data		A custom argument, or `NULL`
-	@return			Zero for success, otherwise an error code (see `enum`
-					#ConfiniInterruptNo)
-
-	Usually @p ini_string comes from an #IniDispatch (but any other string may be
-	used as well).
-
-	The user given function @p f_foreach (see #IniStrHandler data type) will be
-	invoked with five arguments: `member` (the member of the array), `memb_length`
-	(the length of the member in bytes), `memb_num` (the offset of the member in
-	number of members), `format` (the format of the INI file), `user_data` (the
-	custom argument @p user_data previously passed). If @p f_foreach returns a
-	non-zero value the function #ini_array_split() will be interrupted.
-
-	Similarly to `strtok_r()` this function can be used only once for a given
-	string.
-
-	@note	If @p ini_string comes from #INI_GLOBAL_IMPLICIT_VALUE or is `NULL` this
-			function is no-op and will return an error code.
-
-	@note	If @p delimiter matches a metacharacter within the format given (`'\\'`,
-			`'\''` or `'\"'`), its role as metacharacter will have higher priority
-			than its role as delimiter (i.e., the array will have no delimiters and
-			will contain only one member).
-
-	Possible return values are: #CONFINI_SUCCESS, #CONFINI_EROADDR, #CONFINI_FEINTR.
-
-	@include topics/ini_array_split.c.
-
-**/
-int ini_array_split (
-	char * const ini_string,
-	const char delimiter,
-	const IniFormat format,
-	const IniStrHandler f_foreach,
-	void * const user_data
-) {
-
-	if (!ini_string || _LIBCONFINI_IMPLICIT_RANGE_(ini_string)) {
-
-		return CONFINI_EROADDR;
-
-	}
-
-	/*
-
-	Mask `abcd` (8 bits used):
-
-		FLAG_1		Single quotes are not metacharacters (const)
-		FLAG_2		Double quotes are not metacharacters (const)
-		FLAG_4		Delimiter is not any space (const)
-		FLAG_8		Unescaped single quotes are odd until now
-		FLAG_16		Unescaped double quotes are odd until now
-		FLAG_32		We are in an odd sequence of backslashes
-		FLAG_64		This is not a delimiter
-		FLAG_128	Stop the loop
-
-	*/
-
-	register size_t idx;
-	size_t offs = ltrim_h(ini_string, 0, _LIBCONFINI_WITH_EOL_);
-
-	if (_LIBCONFINI_IS_ESC_CHAR_(delimiter, format)) {
-
-		/*
-
-			We have no delimiters (array has only one member)
-
-		*/
-
-		idx = 0;
-
-		while (ini_string[idx++]);
-
-		return	f_foreach(ini_string + offs, rtrim_h(ini_string + offs, idx - offs - 1, _LIBCONFINI_WITH_EOL_), 0, format, user_data) ?
-					CONFINI_FEINTR
-				:
-					CONFINI_SUCCESS;
-
-	}
-
-	register uint8_t abcd	=	(delimiter ? 4 : 0) |
-								(format.no_double_quotes << 1) |
-								format.no_single_quotes;
-
-	size_t memb_num = 0;
-
-	idx = offs;
-
-
-	do {
-
-		abcd	=	(delimiter ? ini_string[idx] == delimiter : is_some_space(ini_string[idx], _LIBCONFINI_WITH_EOL_)) ?
-						abcd & 159
-					: ini_string[idx] == _LIBCONFINI_BACKSLASH_ ?
-						(abcd | 64) ^ 32
-					: !(abcd & 42) && ini_string[idx] == _LIBCONFINI_DOUBLE_QUOTES_ ?
-						((abcd & 223) | 64) ^ 16
-					: !(abcd & 49) && ini_string[idx] == _LIBCONFINI_SINGLE_QUOTES_ ?
-						((abcd & 223) | 64) ^ 8
-					: ini_string[idx] ?
-						(abcd & 223) | 64
-					:
-						128;
-
-
-		if (!(abcd & 88)) {
-
-			ini_string[idx] = '\0';
-
-			if (
-				f_foreach(
-					ini_string + offs,
-					rtrim_h(ini_string + offs, idx - offs, _LIBCONFINI_WITH_EOL_),
-					memb_num++,
-					format,
-					user_data
-				)
-			) {
-
-				return CONFINI_FEINTR;
-
-			}
-
-			offs = abcd & 128 ? idx + 1 : ltrim_h(ini_string, idx + 1, _LIBCONFINI_WITH_EOL_);
-
-		}
-
-		idx = abcd & 216 ? idx + 1 : offs;
-
-	} while (!(abcd & 128) && ((abcd & 92) || ini_string[idx]));
-
-	return CONFINI_SUCCESS;
-
-}
-
-
-									/** @utility{ini_global_set_lowercase_mode} **/
-/**
-
-	@brief			Sets the value of the global variable
-					#INI_GLOBAL_LOWERCASE_MODE
-	@param			lowercase		The new value
-	@return			Nothing
-
-	If @p lowercase is `true`, key and section names in case-insensitive INI formats
-	will be dispatched lowercase, verbatim otherwise (default value: `true`).
-
-	@warning	This function changes the value of one or more global variables. In
-				order to be thread-safe this function should be used only once at
-				beginning of execution, or otherwise a mutex logic must be
-				introduced.
-
-**/
-void ini_global_set_lowercase_mode (const bool lowercase) {
-
-	INI_GLOBAL_LOWERCASE_MODE = lowercase;
-
-}
-
-
-									/** @utility{ini_global_set_implicit_value} **/
-/**
-
-	@brief			Sets the value to be to be assigned to implicit keys
-	@param			implicit_value		The string to be used as implicit value
-										(usually `"YES"`, or `"TRUE"`)
-	@param			implicit_v_len		The length of @p implicit_value (usually
-										`0`, independently of its real length)
-	@return			Nothing
-
-	@warning	This function changes the value of one or more global variables. In
-				order to be thread-safe this function should be used only once at
-				beginning of execution, or otherwise a mutex logic must be
-				introduced.
-
-	@include topics/ini_global_set_implicit_value.c
-
-**/
-void ini_global_set_implicit_value (char * const implicit_value, const size_t implicit_v_len) {
-
-	INI_GLOBAL_IMPLICIT_VALUE = implicit_value;
-	INI_GLOBAL_IMPLICIT_V_LEN = implicit_v_len;
-
-}
-
-
-														/** @utility{ini_fton} **/
-/**
-
-	@brief			Calculates the #IniFormatNum of an #IniFormat
-	@param			source			The #IniFormat to compute
-	@return			The unique unsigned integer that identifies the format given
-
-**/
-IniFormatNum ini_fton (const IniFormat source) {
-
-	#define __INIFORMAT_ID__(NAME, OFFSET, SIZE, DEFVAL) (source.NAME << OFFSET) |
-
-	return INIFORMAT_TABLE_AS(__INIFORMAT_ID__) 0;
-
-	#undef __INIFORMAT_ID__
-
-}
-
-
-														/** @utility{ini_ntof} **/
-/**
-
-	@brief			Constructs a new #IniFormat according to an #IniFormatNum
-	@param			format_num		The #IniFormatNum to parse
-	@return			The new #IniFormat constructed
-
-	@note	If @p format_num `>` `16777215` it will be truncated to 24 bits.
-
-**/
-IniFormat ini_ntof (const IniFormatNum format_num) {
-
-	#define __MAX_1_BITS__ 1
-	#define __MAX_2_BITS__ 3
-	#define __MAX_3_BITS__ 7
-	#define __MAX_4_BITS__ 15
-	#define __MAX_5_BITS__ 31
-	#define __MAX_6_BITS__ 63
-	#define __MAX_7_BITS__ 127
-	#define __MAX_8_BITS__ 255
-	#define __INIFORMAT_PROPERTIES__(NAME, OFFSET, SIZE, DEFVAL) \
-		(unsigned char) ((format_num >> OFFSET) & __MAX_##SIZE##_BITS__),
-
-	return (IniFormat) { INIFORMAT_TABLE_AS(__INIFORMAT_PROPERTIES__) };
-
-	#undef __INIFORMAT_PROPERTIES__
-	#undef __MAX_8_BITS__
-	#undef __MAX_7_BITS__
-	#undef __MAX_6_BITS__
-	#undef __MAX_5_BITS__
-	#undef __MAX_4_BITS__
-	#undef __MAX_3_BITS__
-	#undef __MAX_2_BITS__
-	#undef __MAX_1_BITS__
-
-}
-
-
-													/** @utility{ini_get_bool} **/
-/**
-
-	@brief			Checks whether a string matches one of the booleans listed in
-					the private constant #INI_BOOLEANS (case-insensitive)
-	@param			ini_string			A string to check (it can be `NULL`)
-	@param			when_fail			A value that is returned if no matching
-										boolean is found
-	@return			The matching boolean (`0` or `1`) or @p when_fail if
-					@p ini_string does not contain a valid INI boolean
-
-	Usually @p ini_string comes from an #IniDispatch (but any other string may be
-	used as well).
-
-	@include miscellanea/typed_ini.c
-
-**/
-int ini_get_bool (const char * const ini_string, const int when_fail) {
-
-	if (!ini_string) {
-
-		return when_fail;
-
-	}
-
-	register uint8_t bool_idx;
-	register size_t pair_idx, chr_idx;
-
-	for (pair_idx = 0; pair_idx < sizeof(INI_BOOLEANS) / sizeof(const char * const [2]); pair_idx++) {
-
-		for (bool_idx = 0; bool_idx < 2; bool_idx++) {
-
-			chr_idx = 0;
-
-			while (_LIBCONFINI_CHR_CASEFOLD_(ini_string[chr_idx]) == INI_BOOLEANS[pair_idx][bool_idx][chr_idx]) {
-
-				if (!ini_string[chr_idx++]) {
-
-					return (int) bool_idx;
-
-				}
-
-			}
-
-		}
-
-	}
-
-	return when_fail;
-
-}
-
-
-
-		/*  LINKS - In case you don't have `#include <stdlib.h>` in your source  */
-
-
-/**
-
-	@alias{ini_get_int}
-		Pointer to
-		[`atoi()`](http://www.gnu.org/software/libc/manual/html_node/Parsing-of-Integers.html#index-atoi)
-	@alias{ini_get_lint}
-		Pointer to
-		[`atol()`](http://www.gnu.org/software/libc/manual/html_node/Parsing-of-Integers.html#index-atol)
-	@alias{ini_get_llint}
-		Pointer to
-		[`atoll()`](http://www.gnu.org/software/libc/manual/html_node/Parsing-of-Integers.html#index-atoll)
-	@alias{ini_get_double}
-		Pointer to
-		[`atof()`](http://www.gnu.org/software/libc/manual/html_node/Parsing-of-Integers.html#index-atof)
-
-**/
-
-int (* const ini_get_int) (const char * ini_string) = atoi;
-
-long int (* const ini_get_lint) (const char * ini_string) = atol;
-
-long long int (* const ini_get_llint) (const char * ini_string) = atoll;
-
-double (* const ini_get_double) (const char * ini_string) = atof;
-
-/*  Legacy support -- please **do not use this**!  */
-#ifdef ini_get_float
-#undef ini_get_float
-#endif
-double (* const ini_get_float) (const char * ini_string) = atof;
-
-
-
-		/*  GLOBAL VARIABLES  */
-
-
-bool INI_GLOBAL_LOWERCASE_MODE = _LIBCONFINI_FALSE_;
-
-char * INI_GLOBAL_IMPLICIT_VALUE = (char *) 0;
-
-size_t INI_GLOBAL_IMPLICIT_V_LEN = 0;
-
-
-
-/** @endfnlist **/
-
-/*  EOF  */
-
diff --git a/vendor/confini.h b/vendor/confini.h
deleted file mode 100644
index c4c0068..0000000
--- a/vendor/confini.h
+++ /dev/null
@@ -1,547 +0,0 @@
-/*  -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*-  */
-
-/**
-
-    @file       confini.h
-    @brief      libconfini header
-    @author     Stefano Gioffr&eacute;
-    @copyright  GNU General Public License, version 3 or any later version
-    @version    1.14.0
-    @date       2016-2020
-    @see        https://madmurphy.github.io/libconfini
-
-**/
-
-
-#ifndef _LIBCONFINI_HEADER_
-#define _LIBCONFINI_HEADER_
-
-
-
-#include <stdio.h>
-#include <stdbool.h>
-#include <stdint.h>
-
-
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-
-/*  PRIVATE (HEADER-SCOPED) MACROS  */
-
-
-#define __INIFORMAT_TABLE_CB_FIELDS__(NAME, OFFSET, SIZE, DEFVAL) \
-    unsigned char NAME:SIZE;
-#define __INIFORMAT_TABLE_CB_DEFAULT__(NAME, OFFSET, SIZE, DEFVAL) DEFVAL,
-#define __INIFORMAT_TABLE_CB_ZERO__(NAME, OFFSET, SIZE, DEFVAL) 0,
-#define _LIBCONFINI_INIFORMAT_TYPE_ \
-    struct IniFormat { INIFORMAT_TABLE_AS(__INIFORMAT_TABLE_CB_FIELDS__) }
-#define _LIBCONFINI_DEFAULT_FORMAT_ \
-    { INIFORMAT_TABLE_AS(__INIFORMAT_TABLE_CB_DEFAULT__) }
-#define _LIBCONFINI_UNIXLIKE_FORMAT_ \
-    { INIFORMAT_TABLE_AS(__INIFORMAT_TABLE_CB_ZERO__) }
-
-
-
-/*  PUBLIC MACROS  */
-
-
-/**
-    @brief  Calls a user-given macro (that accepts four arguments) for each row
-            of the table
-**/
-/*
-    NOTE: The following table and the order of its rows **define** (and link
-    together) both the #IniFormat and #IniFormatNum data types declared in this
-    header
-*/
-#define INIFORMAT_TABLE_AS(_____)                 /*  IniFormat table  *\
-
-        NAME                      BIT  SIZE DEFAULT
-                                                                      */\
- _____( delimiter_symbol,         0,   7,   INI_EQUALS                ) \
- _____( case_sensitive,           7,   1,   false                     )/*
-                                                                      */\
- _____( semicolon_marker,         8,   2,   INI_DISABLED_OR_COMMENT   ) \
- _____( hash_marker,              10,  2,   INI_DISABLED_OR_COMMENT   ) \
- _____( section_paths,            12,  2,   INI_ABSOLUTE_AND_RELATIVE ) \
- _____( multiline_nodes,          14,  2,   INI_MULTILINE_EVERYWHERE  )/*
-                                                                      */\
- _____( no_single_quotes,         16,  1,   false                     ) \
- _____( no_double_quotes,         17,  1,   false                     ) \
- _____( no_spaces_in_names,       18,  1,   false                     ) \
- _____( implicit_is_not_empty,    19,  1,   false                     ) \
- _____( do_not_collapse_values,   20,  1,   false                     ) \
- _____( preserve_empty_quotes,    21,  1,   false                     ) \
- _____( disabled_after_space,     22,  1,   false                     ) \
- _____( disabled_can_be_implicit, 23,  1,   false                     )
-
-
-
-/**
-    @brief  Checks whether a format does **not** support escape sequences
-**/
-#define INIFORMAT_HAS_NO_ESC(FORMAT) \
-    (FORMAT.multiline_nodes == INI_NO_MULTILINE && \
-    FORMAT.no_double_quotes && FORMAT.no_single_quotes)
-
-
-
-/*  PUBLIC TYPEDEFS  */
-
-
-/**
-    @brief  24-bit bitfield representing the format of an INI file (INI
-            dialect)
-**/
-typedef _LIBCONFINI_INIFORMAT_TYPE_ IniFormat;
-
-
-/**
-    @brief  Global statistics about an INI file
-**/
-typedef struct IniStatistics {
-    const IniFormat format;
-    const size_t bytes;
-    const size_t members;
-} IniStatistics;
-
-
-/**
-    @brief  Dispatch of a single INI node
-**/
-typedef struct IniDispatch {
-    const IniFormat format;
-    uint8_t type;
-    char * data;
-    char * value;
-    const char * append_to;
-    size_t d_len;
-    size_t v_len;
-    size_t at_len;
-    size_t dispatch_id;
-} IniDispatch;
-
-
-/**
-    @brief  The unique ID of an INI format (24-bit maximum)
-**/
-typedef uint32_t IniFormatNum;
-
-
-/**
-    @brief  Callback function for handling an #IniStatistics structure
-**/
-typedef int (* IniStatsHandler) (
-    IniStatistics * statistics,
-    void * user_data
-);
-
-
-/**
-    @brief  Callback function for handling an #IniDispatch structure
-**/
-typedef int (* IniDispHandler) (
-    IniDispatch * dispatch,
-    void * user_data
-);
-
-
-/**
-    @brief  Callback function for handling an INI string belonging to a
-            sequence of INI strings
-**/
-typedef int (* IniStrHandler) (
-    char * ini_string,
-    size_t string_length,
-    size_t string_num,
-    IniFormat format,
-    void * user_data
-);
-
-
-/**
-    @brief  Callback function for handling a selected fragment of an INI string
-**/
-typedef int (* IniSubstrHandler) (
-    const char * ini_string,
-    size_t fragm_offset,
-    size_t fragm_length,
-    size_t fragm_num,
-    IniFormat format,
-    void * user_data
-);
-
-
-
-/*  PUBLIC FUNCTIONS  */
-
-
-extern int strip_ini_cache (
-    register char * const ini_source,
-    const size_t ini_length,
-    const IniFormat format,
-    const IniStatsHandler f_init,
-    const IniDispHandler f_foreach,
-    void * const user_data
-);
-
-
-extern int load_ini_file (
-    FILE * const ini_file,
-    const IniFormat format,
-    const IniStatsHandler f_init,
-    const IniDispHandler f_foreach,
-    void * const user_data
-);
-
-
-extern int load_ini_path (
-    const char * const path,
-    const IniFormat format,
-    const IniStatsHandler f_init,
-    const IniDispHandler f_foreach,
-    void * const user_data
-);
-
-
-extern bool ini_string_match_ss (
-    const char * const simple_string_a,
-    const char * const simple_string_b,
-    const IniFormat format
-);
-
-
-extern bool ini_string_match_si (
-    const char * const simple_string,
-    const char * const ini_string,
-    const IniFormat format
-);
-
-
-extern bool ini_string_match_ii (
-    const char * const ini_string_a,
-    const char * const ini_string_b,
-    const IniFormat format
-);
-
-
-extern bool ini_array_match (
-    const char * const ini_string_a,
-    const char * const ini_string_b,
-    const char delimiter,
-    const IniFormat format
-);
-
-
-extern size_t ini_unquote (
-    char * const ini_string,
-    const IniFormat format
-);
-
-
-extern size_t ini_string_parse (
-    char * const ini_string,
-    const IniFormat format
-);
-
-
-extern size_t ini_array_get_length (
-    const char * const ini_string,
-    const char delimiter,
-    const IniFormat format
-);
-
-
-extern int ini_array_foreach (
-    const char * const ini_string,
-    const char delimiter,
-    const IniFormat format,
-    const IniSubstrHandler f_foreach,
-    void * const user_data
-);
-
-
-extern size_t ini_array_shift (
-    const char ** const ini_strptr,
-    const char delimiter,
-    const IniFormat format
-);
-
-
-extern size_t ini_array_collapse (
-    char * const ini_string,
-    const char delimiter,
-    const IniFormat format
-);
-
-
-extern char * ini_array_break (
-    char * const ini_string,
-    const char delimiter,
-    const IniFormat format
-);
-
-
-extern char * ini_array_release (
-    char ** const ini_strptr,
-    const char delimiter,
-    const IniFormat format
-);
-
-
-extern int ini_array_split (
-    char * const ini_string,
-    const char delimiter,
-    const IniFormat format,
-    const IniStrHandler f_foreach,
-    void * const user_data
-);
-
-
-extern void ini_global_set_lowercase_mode (
-    const bool lowercase
-);
-
-
-extern void ini_global_set_implicit_value (
-    char * const implicit_value,
-    const size_t implicit_v_len
-);
-
-
-extern IniFormatNum ini_fton (
-    const IniFormat format
-);
-
-
-extern IniFormat ini_ntof (
-    const IniFormatNum format_id
-);
-
-
-extern int ini_get_bool (
-    const char * const ini_string,
-    const int when_fail
-);
-
-
-
-/*  PUBLIC LINKS  */
-
-
-extern int (* const ini_get_int) (
-    const char * ini_string
-);
-
-
-extern long int (* const ini_get_lint) (
-    const char * ini_string
-);
-
-
-extern long long int (* const ini_get_llint) (
-    const char * ini_string
-);
-
-
-extern double (* const ini_get_double) (
-    const char * ini_string
-);
-
-
-/**
-    @brief  Legacy support, soon to be replaced with a `float` data type --
-            please **do not use `ini_get_float()`!**
-**/
-#define ini_get_float \
-    _Pragma("GCC warning \"function `ini_get_float()` is deprecated for parsing a `double` data type; use `ini_get_double()` instead\"") \
-    ini_get_double
-
-
-
-/*  PUBLIC CONSTANTS AND VARIABLES  */
-
-
-/**
-    @brief  Error mask (flags not present in user-generated interruptions)
-**/
-#define CONFINI_ERROR 252
-
-
-/**
-    @brief  Error codes
-**/
-enum ConfiniInterruptNo {
-    CONFINI_SUCCESS = 0,    /**< There have been no interruptions, everything
-                                 went well [value=0] **/
-    CONFINI_IINTR = 1,      /**< Interrupted by the user during `f_init()`
-                                 [value=1] **/
-    CONFINI_FEINTR = 2,     /**< Interrupted by the user during `f_foreach()`
-                                 [value=2] **/
-    CONFINI_ENOENT = 4,     /**< File inaccessible [value=4] **/
-    CONFINI_ENOMEM = 5,     /**< Error allocating virtual memory [value=5] **/
-    CONFINI_EIO = 6,        /**< Error reading the file [value=6] **/
-    CONFINI_EOOR = 7,       /**< Out-of-range error: callbacks are more than
-                                 expected [value=7] **/
-    CONFINI_EBADF = 8,      /**< The stream specified is not a seekable stream
-                                 [value=8] **/
-    CONFINI_EFBIG = 9,      /**< File too large [value=9] **/
-    CONFINI_EROADDR = 10    /**< Address is read-only [value=10] **/
-};
-
-
-/**
-    @brief  INI node types
-**/
-enum IniNodeType {
-    INI_UNKNOWN = 0,            /**< This is a node impossible to categorize
-                                     [value=0] **/
-    INI_VALUE = 1,              /**< Not used by **libconfini** (values are
-                                     dispatched together with keys) -- but
-                                     available for user's implementations
-                                     [value=1] **/
-    INI_KEY = 2,                /**< This is a key [value=2] **/
-    INI_SECTION = 3,            /**< This is a section or a section path
-                                     [value=3] **/
-    INI_COMMENT = 4,            /**< This is a comment [value=4] **/
-    INI_INLINE_COMMENT = 5,     /**< This is an inline comment [value=5] **/
-    INI_DISABLED_KEY = 6,       /**< This is a disabled key [value=6] **/
-    INI_DISABLED_SECTION = 7    /**< This is a disabled section path
-                                     [value=7] **/
-};
-
-
-/**
-    @brief  Common array and key-value delimiters (but a delimiter may also be
-            any other ASCII character not present in this list)
-**/
-enum IniDelimiters {
-    INI_ANY_SPACE = 0,  /**< In multi-line INIs:
-                             `/(?:\\(?:\n\r?|\r\n?)|[\t \v\f])+/`, in
-                             non-multi-line INIs: `/[\t \v\f])+/` **/
-    INI_EQUALS = '=',   /**< Equals character (`=`) **/
-    INI_COLON = ':',    /**< Colon character (`:`) **/
-    INI_DOT = '.',      /**< Dot character (`.`) **/
-    INI_COMMA = ','     /**< Comma character (`,`) **/
-};
-
-
-/**
-    @brief  Possible values of #IniFormat::semicolon_marker and
-            #IniFormat::hash_marker (i.e., meaning of `/\s+;/` and `/\s+#/` in
-            respect to a format)
-**/
-enum IniCommentMarker {
-    INI_DISABLED_OR_COMMENT = 0,    /**< This marker opens a comment or a
-                                         disabled entry **/
-    INI_ONLY_COMMENT = 1,           /**< This marker opens a comment **/
-    INI_IGNORE = 2,                 /**< This marker opens a comment that has
-                                         been marked for deletion and must not
-                                         be dispatched or counted **/
-    INI_IS_NOT_A_MARKER = 3         /**< This is not a marker at all, but a
-                                         normal character instead **/
-};
-
-
-/**
-    @brief  Possible values of #IniFormat::section_paths
-**/
-enum IniSectionPaths {
-    INI_ABSOLUTE_AND_RELATIVE = 0,  /**< Section paths starting with a dot
-                                         express nesting to the current parent,
-                                         to root otherwise **/
-    INI_ABSOLUTE_ONLY = 1,          /**< Section paths starting with a dot will
-                                         be cleaned of their leading dot and
-                                         appended to root **/
-    INI_ONE_LEVEL_ONLY = 2,         /**< Format supports sections, but the dot
-                                         does not express nesting and is not a
-                                         meta-character **/
-    INI_NO_SECTIONS = 3             /**< Format does *not* support sections --
-                                         `/\[[^\]]*\]/g`, if any, will be
-                                         treated as keys! **/
-};
-
-
-/**
-    @brief  Possible values of #IniFormat::multiline_nodes
-**/
-enum IniMultiline {
-    INI_MULTILINE_EVERYWHERE = 0,       /**< Comments, section paths and keys
-                                             -- disabled or not -- are allowed
-                                             to be multi-line **/
-    INI_BUT_COMMENTS = 1,               /**< Only section paths and keys --
-                                             disabled or not -- are allowed to
-                                             be multi-line **/
-    INI_BUT_DISABLED_AND_COMMENTS = 2,  /**< Only active section paths and
-                                             active keys are allowed to be
-                                             multi-line **/
-    INI_NO_MULTILINE = 3                /**< Multi-line escape sequences are
-                                             disabled **/
-};
-
-
-/**
-    @brief  A model format for standard INI files
-**/
-static const IniFormat INI_DEFAULT_FORMAT = _LIBCONFINI_DEFAULT_FORMAT_;
-
-
-/**
-    @brief  A model format for Unix-like .conf files (where space characters
-            are delimiters between keys and values)
-**/
-/*  All fields are set to `0` here.  */
-static const IniFormat INI_UNIXLIKE_FORMAT = _LIBCONFINI_UNIXLIKE_FORMAT_;
-
-
-/**
-    @brief  If set to `true`, key and section names in case-insensitive INI
-            formats will be dispatched lowercase, verbatim otherwise (default
-            value: `false`)
-**/
-extern bool INI_GLOBAL_LOWERCASE_MODE;
-
-
-/**
-    @brief  Value to be assigned to implicit keys (default value: `NULL`)
-**/
-extern char * INI_GLOBAL_IMPLICIT_VALUE;
-
-
-/**
-    @brief  Length of the value assigned to implicit keys (default value: `0`)
-**/
-extern size_t INI_GLOBAL_IMPLICIT_V_LEN;
-
-
-
-/*  CLEAN THE PRIVATE ENVIRONMENT  */
-
-
-#undef _LIBCONFINI_UNIXLIKE_FORMAT_
-#undef _LIBCONFINI_DEFAULT_FORMAT_
-#undef _LIBCONFINI_INIFORMAT_TYPE_
-#undef __INIFORMAT_TABLE_CB_ZERO__
-#undef __INIFORMAT_TABLE_CB_DEFAULT__
-#undef __INIFORMAT_TABLE_CB_FIELDS__
-
-
-
-/*  END OF `_LIBCONFINI_HEADER_`  */
-
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif
-
-
-
-/*  EOF  */
-
diff --git a/vendor/mongoose.c b/vendor/mongoose.c
deleted file mode 100644
index e2088d0..0000000
--- a/vendor/mongoose.c
+++ /dev/null
@@ -1,16173 +0,0 @@
-/*
- * Copyright (c) 2004-2013 Sergey Lyubka
- * Copyright (c) 2013-2020 Cesanta Software Limited
- * All rights reserved
- *
- * This software is dual-licensed: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License version 2 as
- * published by the Free Software Foundation. For the terms of this
- * license, see <http://www.gnu.org/licenses/>.
- *
- * You are free to use this software under the terms of the GNU General
- * Public License, but WITHOUT ANY WARRANTY; without even the implied
- * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- * See the GNU General Public License for more details.
- *
- * Alternatively, you can license this software under a commercial
- * license, as set out in <https://www.cesanta.com/license>.
- */
-
-#include "mongoose.h"
-#ifdef MG_MODULE_LINES
-#line 1 "mongoose/src/mg_internal.h"
-#endif
-
-#ifndef CS_MONGOOSE_SRC_INTERNAL_H_
-#define CS_MONGOOSE_SRC_INTERNAL_H_
-
-/* Amalgamated: #include "common/mg_mem.h" */
-
-#ifndef MBUF_REALLOC
-#define MBUF_REALLOC MG_REALLOC
-#endif
-
-#ifndef MBUF_FREE
-#define MBUF_FREE MG_FREE
-#endif
-
-#define MG_SET_PTRPTR(_ptr, _v) \
-  do {                          \
-    if (_ptr) *(_ptr) = _v;     \
-  } while (0)
-
-#ifndef MG_INTERNAL
-#define MG_INTERNAL static
-#endif
-
-#ifdef PICOTCP
-#define NO_LIBC
-#define MG_DISABLE_PFS
-#endif
-
-/* Amalgamated: #include "common/cs_dbg.h" */
-/* Amalgamated: #include "mg_http.h" */
-/* Amalgamated: #include "mg_net.h" */
-
-#ifndef MG_CTL_MSG_MESSAGE_SIZE
-#define MG_CTL_MSG_MESSAGE_SIZE 8192
-#endif
-
-/* internals that need to be accessible in unit tests */
-MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
-                                                int proto,
-                                                union socket_address *sa);
-
-MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
-                                 int *proto, char *host, size_t host_len);
-MG_INTERNAL void mg_call(struct mg_connection *nc,
-                         mg_event_handler_t ev_handler, void *user_data, int ev,
-                         void *ev_data);
-void mg_forward(struct mg_connection *from, struct mg_connection *to);
-MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
-MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
-MG_INTERNAL struct mg_connection *mg_create_connection(
-    struct mg_mgr *mgr, mg_event_handler_t callback,
-    struct mg_add_sock_opts opts);
-#ifdef _WIN32
-/* Retur value is the same as for MultiByteToWideChar. */
-int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
-#endif
-
-struct ctl_msg {
-  mg_event_handler_t callback;
-  char message[MG_CTL_MSG_MESSAGE_SIZE];
-};
-
-#if MG_ENABLE_MQTT
-struct mg_mqtt_message;
-
-#define MG_MQTT_ERROR_INCOMPLETE_MSG -1
-#define MG_MQTT_ERROR_MALFORMED_MSG -2
-
-MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm);
-#endif
-
-/* Forward declarations for testing. */
-extern void *(*test_malloc)(size_t size);
-extern void *(*test_calloc)(size_t count, size_t size);
-
-#ifndef MIN
-#define MIN(a, b) ((a) < (b) ? (a) : (b))
-#endif
-
-#if MG_ENABLE_HTTP
-struct mg_serve_http_opts;
-
-MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data(
-    struct mg_connection *c);
-
-/*
- * Reassemble the content of the buffer (buf, blen) which should be
- * in the HTTP chunked encoding, by collapsing data chunks to the
- * beginning of the buffer.
- *
- * If chunks get reassembled, modify hm->body to point to the reassembled
- * body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
- * in nc->flags, delete reassembled body from the mbuf.
- *
- * Return reassembled body size.
- */
-MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
-                                     struct http_message *hm, char *buf,
-                                     size_t blen);
-
-#if MG_ENABLE_FILESYSTEM
-MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
-                                     const struct mg_serve_http_opts *opts,
-                                     char **local_path,
-                                     struct mg_str *remainder);
-MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
-MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st);
-#endif
-#if MG_ENABLE_HTTP_CGI
-MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
-                               const struct mg_str *path_info,
-                               const struct http_message *hm,
-                               const struct mg_serve_http_opts *opts);
-struct mg_http_proto_data_cgi;
-MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d);
-#endif
-#if MG_ENABLE_HTTP_SSI
-MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
-                                       struct http_message *hm,
-                                       const char *path,
-                                       const struct mg_serve_http_opts *opts);
-#endif
-#if MG_ENABLE_HTTP_WEBDAV
-MG_INTERNAL int mg_is_dav_request(const struct mg_str *s);
-MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
-                                    cs_stat_t *stp, struct http_message *hm,
-                                    struct mg_serve_http_opts *opts);
-MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path);
-MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
-                                 struct http_message *hm);
-MG_INTERNAL void mg_handle_move(struct mg_connection *c,
-                                const struct mg_serve_http_opts *opts,
-                                const char *path, struct http_message *hm);
-MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
-                                  const struct mg_serve_http_opts *opts,
-                                  const char *path);
-MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
-                               struct http_message *hm);
-#endif
-#if MG_ENABLE_HTTP_WEBSOCKET
-MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
-                               void *ev_data MG_UD_ARG(void *user_data));
-MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
-                                 const struct mg_str *key,
-                                 struct http_message *);
-#endif
-#endif /* MG_ENABLE_HTTP */
-
-MG_INTERNAL int mg_get_errno(void);
-
-MG_INTERNAL void mg_close_conn(struct mg_connection *conn);
-
-#if MG_ENABLE_SNTP
-MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
-                                    struct mg_sntp_message *msg);
-#endif
-
-#endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "common/mg_mem.h"
-#endif
-
-#ifndef CS_COMMON_MG_MEM_H_
-#define CS_COMMON_MG_MEM_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef MG_MALLOC
-#define MG_MALLOC malloc
-#endif
-
-#ifndef MG_CALLOC
-#define MG_CALLOC calloc
-#endif
-
-#ifndef MG_REALLOC
-#define MG_REALLOC realloc
-#endif
-
-#ifndef MG_FREE
-#define MG_FREE free
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CS_COMMON_MG_MEM_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "common/cs_base64.c"
-#endif
-
-#ifndef EXCLUDE_COMMON
-
-/* Amalgamated: #include "common/cs_base64.h" */
-
-#include <string.h>
-
-/* Amalgamated: #include "common/cs_dbg.h" */
-
-/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
-
-#define NUM_UPPERCASES ('Z' - 'A' + 1)
-#define NUM_LETTERS (NUM_UPPERCASES * 2)
-#define NUM_DIGITS ('9' - '0' + 1)
-
-/*
- * Emit a base64 code char.
- *
- * Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
- */
-static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
-  if (v < NUM_UPPERCASES) {
-    ctx->b64_putc(v + 'A', ctx->user_data);
-  } else if (v < (NUM_LETTERS)) {
-    ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
-  } else if (v < (NUM_LETTERS + NUM_DIGITS)) {
-    ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
-  } else {
-    ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
-                  ctx->user_data);
-  }
-}
-
-static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
-  int a, b, c;
-
-  a = ctx->chunk[0];
-  b = ctx->chunk[1];
-  c = ctx->chunk[2];
-
-  cs_base64_emit_code(ctx, a >> 2);
-  cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
-  if (ctx->chunk_size > 1) {
-    cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
-  }
-  if (ctx->chunk_size > 2) {
-    cs_base64_emit_code(ctx, c & 63);
-  }
-}
-
-void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
-                    void *user_data) {
-  ctx->chunk_size = 0;
-  ctx->b64_putc = b64_putc;
-  ctx->user_data = user_data;
-}
-
-void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
-  const unsigned char *src = (const unsigned char *) str;
-  size_t i;
-  for (i = 0; i < len; i++) {
-    ctx->chunk[ctx->chunk_size++] = src[i];
-    if (ctx->chunk_size == 3) {
-      cs_base64_emit_chunk(ctx);
-      ctx->chunk_size = 0;
-    }
-  }
-}
-
-void cs_base64_finish(struct cs_base64_ctx *ctx) {
-  if (ctx->chunk_size > 0) {
-    int i;
-    memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
-    cs_base64_emit_chunk(ctx);
-    for (i = 0; i < (3 - ctx->chunk_size); i++) {
-      ctx->b64_putc('=', ctx->user_data);
-    }
-  }
-}
-
-#define BASE64_ENCODE_BODY                                                \
-  static const char *b64 =                                                \
-      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
-  int i, j, a, b, c;                                                      \
-                                                                          \
-  for (i = j = 0; i < src_len; i += 3) {                                  \
-    a = src[i];                                                           \
-    b = i + 1 >= src_len ? 0 : src[i + 1];                                \
-    c = i + 2 >= src_len ? 0 : src[i + 2];                                \
-                                                                          \
-    BASE64_OUT(b64[a >> 2]);                                              \
-    BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]);                           \
-    if (i + 1 < src_len) {                                                \
-      BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]);                          \
-    }                                                                     \
-    if (i + 2 < src_len) {                                                \
-      BASE64_OUT(b64[c & 63]);                                            \
-    }                                                                     \
-  }                                                                       \
-                                                                          \
-  while (j % 4 != 0) {                                                    \
-    BASE64_OUT('=');                                                      \
-  }                                                                       \
-  BASE64_FLUSH()
-
-#define BASE64_OUT(ch) \
-  do {                 \
-    dst[j++] = (ch);   \
-  } while (0)
-
-#define BASE64_FLUSH() \
-  do {                 \
-    dst[j++] = '\0';   \
-  } while (0)
-
-void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
-  BASE64_ENCODE_BODY;
-}
-
-#undef BASE64_OUT
-#undef BASE64_FLUSH
-
-#if CS_ENABLE_STDIO
-#define BASE64_OUT(ch)      \
-  do {                      \
-    fprintf(f, "%c", (ch)); \
-    j++;                    \
-  } while (0)
-
-#define BASE64_FLUSH()
-
-void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
-  BASE64_ENCODE_BODY;
-}
-
-#undef BASE64_OUT
-#undef BASE64_FLUSH
-#endif /* CS_ENABLE_STDIO */
-
-/* Convert one byte of encoded base64 input stream to 6-bit chunk */
-static unsigned char from_b64(unsigned char ch) {
-  /* Inverse lookup map */
-  static const unsigned char tab[128] = {
-      255, 255, 255, 255,
-      255, 255, 255, 255, /*  0 */
-      255, 255, 255, 255,
-      255, 255, 255, 255, /*  8 */
-      255, 255, 255, 255,
-      255, 255, 255, 255, /*  16 */
-      255, 255, 255, 255,
-      255, 255, 255, 255, /*  24 */
-      255, 255, 255, 255,
-      255, 255, 255, 255, /*  32 */
-      255, 255, 255, 62,
-      255, 255, 255, 63, /*  40 */
-      52,  53,  54,  55,
-      56,  57,  58,  59, /*  48 */
-      60,  61,  255, 255,
-      255, 200, 255, 255, /*  56   '=' is 200, on index 61 */
-      255, 0,   1,   2,
-      3,   4,   5,   6, /*  64 */
-      7,   8,   9,   10,
-      11,  12,  13,  14, /*  72 */
-      15,  16,  17,  18,
-      19,  20,  21,  22, /*  80 */
-      23,  24,  25,  255,
-      255, 255, 255, 255, /*  88 */
-      255, 26,  27,  28,
-      29,  30,  31,  32, /*  96 */
-      33,  34,  35,  36,
-      37,  38,  39,  40, /*  104 */
-      41,  42,  43,  44,
-      45,  46,  47,  48, /*  112 */
-      49,  50,  51,  255,
-      255, 255, 255, 255, /*  120 */
-  };
-  return tab[ch & 127];
-}
-
-int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) {
-  unsigned char a, b, c, d;
-  int orig_len = len;
-  char *orig_dst = dst;
-  while (len >= 4 && (a = from_b64(s[0])) != 255 &&
-         (b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
-         (d = from_b64(s[3])) != 255) {
-    s += 4;
-    len -= 4;
-    if (a == 200 || b == 200) break; /* '=' can't be there */
-    *dst++ = a << 2 | b >> 4;
-    if (c == 200) break;
-    *dst++ = b << 4 | c >> 2;
-    if (d == 200) break;
-    *dst++ = c << 6 | d;
-  }
-  *dst = 0;
-  if (dec_len != NULL) *dec_len = (dst - orig_dst);
-  return orig_len - len;
-}
-
-#endif /* EXCLUDE_COMMON */
-#ifdef MG_MODULE_LINES
-#line 1 "common/cs_dbg.h"
-#endif
-
-#ifndef CS_COMMON_CS_DBG_H_
-#define CS_COMMON_CS_DBG_H_
-
-/* Amalgamated: #include "common/platform.h" */
-
-#if CS_ENABLE_STDIO
-#include <stdio.h>
-#endif
-
-#ifndef CS_ENABLE_DEBUG
-#define CS_ENABLE_DEBUG 0
-#endif
-
-#ifndef CS_LOG_PREFIX_LEN
-#define CS_LOG_PREFIX_LEN 24
-#endif
-
-#ifndef CS_LOG_ENABLE_TS_DIFF
-#define CS_LOG_ENABLE_TS_DIFF 0
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-/*
- * Log level; `LL_INFO` is the default. Use `cs_log_set_level()` to change it.
- */
-enum cs_log_level {
-  LL_NONE = -1,
-  LL_ERROR = 0,
-  LL_WARN = 1,
-  LL_INFO = 2,
-  LL_DEBUG = 3,
-  LL_VERBOSE_DEBUG = 4,
-
-  _LL_MIN = -2,
-  _LL_MAX = 5,
-};
-
-/*
- * Set max log level to print; messages with the level above the given one will
- * not be printed.
- */
-void cs_log_set_level(enum cs_log_level level);
-
-/*
- * A comma-separated set of prefix=level.
- * prefix is matched against the log prefix exactly as printed, including line
- * number, but partial match is ok. Check stops on first matching entry.
- * If nothing matches, default level is used.
- *
- * Examples:
- *   main.c:=4 - everything from main C at verbose debug level.
- *   mongoose.c=1,mjs.c=1,=4 - everything at verbose debug except mg_* and mjs_*
- *
- */
-void cs_log_set_file_level(const char *file_level);
-
-/*
- * Helper function which prints message prefix with the given `level`.
- * If message should be printed (according to the current log level
- * and filter), prints the prefix and returns 1, otherwise returns 0.
- *
- * Clients should typically just use `LOG()` macro.
- */
-int cs_log_print_prefix(enum cs_log_level level, const char *fname, int line);
-
-extern enum cs_log_level cs_log_level;
-
-#if CS_ENABLE_STDIO
-
-/*
- * Set file to write logs into. If `NULL`, logs go to `stderr`.
- */
-void cs_log_set_file(FILE *file);
-
-/*
- * Prints log to the current log file, appends "\n" in the end and flushes the
- * stream.
- */
-void cs_log_printf(const char *fmt, ...) PRINTF_LIKE(1, 2);
-
-#if CS_ENABLE_STDIO
-
-/*
- * Format and print message `x` with the given level `l`. Example:
- *
- * ```c
- * LOG(LL_INFO, ("my info message: %d", 123));
- * LOG(LL_DEBUG, ("my debug message: %d", 123));
- * ```
- */
-#define LOG(l, x)                                     \
-  do {                                                \
-    if (cs_log_print_prefix(l, __FILE__, __LINE__)) { \
-      cs_log_printf x;                                \
-    }                                                 \
-  } while (0)
-
-#else
-
-#define LOG(l, x) ((void) l)
-
-#endif
-
-#ifndef CS_NDEBUG
-
-/*
- * Shortcut for `LOG(LL_VERBOSE_DEBUG, (...))`
- */
-#define DBG(x) LOG(LL_VERBOSE_DEBUG, x)
-
-#else /* NDEBUG */
-
-#define DBG(x)
-
-#endif
-
-#else /* CS_ENABLE_STDIO */
-
-#define LOG(l, x)
-#define DBG(x)
-
-#endif
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_COMMON_CS_DBG_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "common/cs_dbg.c"
-#endif
-
-/* Amalgamated: #include "common/cs_dbg.h" */
-
-#include <stdarg.h>
-#include <stdio.h>
-#include <string.h>
-
-/* Amalgamated: #include "common/cs_time.h" */
-/* Amalgamated: #include "common/str_util.h" */
-
-enum cs_log_level cs_log_level WEAK =
-#if CS_ENABLE_DEBUG
-    LL_VERBOSE_DEBUG;
-#else
-    LL_ERROR;
-#endif
-
-#if CS_ENABLE_STDIO
-static char *s_file_level = NULL;
-
-void cs_log_set_file_level(const char *file_level) WEAK;
-
-FILE *cs_log_file WEAK = NULL;
-
-#if CS_LOG_ENABLE_TS_DIFF
-double cs_log_ts WEAK;
-#endif
-
-enum cs_log_level cs_log_cur_msg_level WEAK = LL_NONE;
-
-void cs_log_set_file_level(const char *file_level) {
-  char *fl = s_file_level;
-  if (file_level != NULL) {
-    s_file_level = strdup(file_level);
-  } else {
-    s_file_level = NULL;
-  }
-  free(fl);
-}
-
-int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) WEAK;
-int cs_log_print_prefix(enum cs_log_level level, const char *file, int ln) {
-  char prefix[CS_LOG_PREFIX_LEN], *q;
-  const char *p;
-  size_t fl = 0, ll = 0, pl = 0;
-
-  if (level > cs_log_level && s_file_level == NULL) return 0;
-
-  p = file + strlen(file);
-
-  while (p != file) {
-    const char c = *(p - 1);
-    if (c == '/' || c == '\\') break;
-    p--;
-    fl++;
-  }
-
-  ll = (ln < 10000 ? (ln < 1000 ? (ln < 100 ? (ln < 10 ? 1 : 2) : 3) : 4) : 5);
-  if (fl > (sizeof(prefix) - ll - 2)) fl = (sizeof(prefix) - ll - 2);
-
-  pl = fl + 1 + ll;
-  memcpy(prefix, p, fl);
-  q = prefix + pl;
-  memset(q, ' ', sizeof(prefix) - pl);
-  do {
-    *(--q) = '0' + (ln % 10);
-    ln /= 10;
-  } while (ln > 0);
-  *(--q) = ':';
-
-  if (s_file_level != NULL) {
-    enum cs_log_level pll = cs_log_level;
-    struct mg_str fl = mg_mk_str(s_file_level), ps = MG_MK_STR_N(prefix, pl);
-    struct mg_str k, v;
-    while ((fl = mg_next_comma_list_entry_n(fl, &k, &v)).p != NULL) {
-      bool yes = !(!mg_str_starts_with(ps, k) || v.len == 0);
-      if (!yes) continue;
-      pll = (enum cs_log_level)(*v.p - '0');
-      break;
-    }
-    if (level > pll) return 0;
-  }
-
-  if (cs_log_file == NULL) cs_log_file = stderr;
-  cs_log_cur_msg_level = level;
-  fwrite(prefix, 1, sizeof(prefix), cs_log_file);
-#if CS_LOG_ENABLE_TS_DIFF
-  {
-    double now = cs_time();
-    fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000));
-    cs_log_ts = now;
-  }
-#endif
-  return 1;
-}
-
-void cs_log_printf(const char *fmt, ...) WEAK;
-void cs_log_printf(const char *fmt, ...) {
-  va_list ap;
-  va_start(ap, fmt);
-  vfprintf(cs_log_file, fmt, ap);
-  va_end(ap);
-  fputc('\n', cs_log_file);
-  fflush(cs_log_file);
-  cs_log_cur_msg_level = LL_NONE;
-}
-
-void cs_log_set_file(FILE *file) WEAK;
-void cs_log_set_file(FILE *file) {
-  cs_log_file = file;
-}
-
-#else
-
-void cs_log_set_file_level(const char *file_level) {
-  (void) file_level;
-}
-
-#endif /* CS_ENABLE_STDIO */
-
-void cs_log_set_level(enum cs_log_level level) WEAK;
-void cs_log_set_level(enum cs_log_level level) {
-  cs_log_level = level;
-#if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO
-  cs_log_ts = cs_time();
-#endif
-}
-#ifdef MG_MODULE_LINES
-#line 1 "common/cs_dirent.h"
-#endif
-
-#ifndef CS_COMMON_CS_DIRENT_H_
-#define CS_COMMON_CS_DIRENT_H_
-
-#include <limits.h>
-
-/* Amalgamated: #include "common/platform.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#ifdef CS_DEFINE_DIRENT
-typedef struct { int dummy; } DIR;
-
-struct dirent {
-  int d_ino;
-#ifdef _WIN32
-  char d_name[MAX_PATH];
-#else
-  /* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */
-  char d_name[256];
-#endif
-};
-
-DIR *opendir(const char *dir_name);
-int closedir(DIR *dir);
-struct dirent *readdir(DIR *dir);
-#endif /* CS_DEFINE_DIRENT */
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_COMMON_CS_DIRENT_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "common/cs_dirent.c"
-#endif
-
-#ifndef EXCLUDE_COMMON
-
-/* Amalgamated: #include "common/mg_mem.h" */
-/* Amalgamated: #include "common/cs_dirent.h" */
-
-/*
- * This file contains POSIX opendir/closedir/readdir API implementation
- * for systems which do not natively support it (e.g. Windows).
- */
-
-#ifdef _WIN32
-struct win32_dir {
-  DIR d;
-  HANDLE handle;
-  WIN32_FIND_DATAW info;
-  struct dirent result;
-};
-
-DIR *opendir(const char *name) {
-  struct win32_dir *dir = NULL;
-  wchar_t wpath[MAX_PATH];
-  DWORD attrs;
-
-  if (name == NULL) {
-    SetLastError(ERROR_BAD_ARGUMENTS);
-  } else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) {
-    SetLastError(ERROR_NOT_ENOUGH_MEMORY);
-  } else {
-    to_wchar(name, wpath, ARRAY_SIZE(wpath));
-    attrs = GetFileAttributesW(wpath);
-    if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
-      (void) wcscat(wpath, L"\\*");
-      dir->handle = FindFirstFileW(wpath, &dir->info);
-      dir->result.d_name[0] = '\0';
-    } else {
-      MG_FREE(dir);
-      dir = NULL;
-    }
-  }
-
-  return (DIR *) dir;
-}
-
-int closedir(DIR *d) {
-  struct win32_dir *dir = (struct win32_dir *) d;
-  int result = 0;
-
-  if (dir != NULL) {
-    if (dir->handle != INVALID_HANDLE_VALUE)
-      result = FindClose(dir->handle) ? 0 : -1;
-    MG_FREE(dir);
-  } else {
-    result = -1;
-    SetLastError(ERROR_BAD_ARGUMENTS);
-  }
-
-  return result;
-}
-
-struct dirent *readdir(DIR *d) {
-  struct win32_dir *dir = (struct win32_dir *) d;
-  struct dirent *result = NULL;
-
-  if (dir) {
-    memset(&dir->result, 0, sizeof(dir->result));
-    if (dir->handle != INVALID_HANDLE_VALUE) {
-      result = &dir->result;
-      (void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
-                                 result->d_name, sizeof(result->d_name), NULL,
-                                 NULL);
-
-      if (!FindNextFileW(dir->handle, &dir->info)) {
-        (void) FindClose(dir->handle);
-        dir->handle = INVALID_HANDLE_VALUE;
-      }
-
-    } else {
-      SetLastError(ERROR_FILE_NOT_FOUND);
-    }
-  } else {
-    SetLastError(ERROR_BAD_ARGUMENTS);
-  }
-
-  return result;
-}
-#endif
-
-#endif /* EXCLUDE_COMMON */
-
-/* ISO C requires a translation unit to contain at least one declaration */
-typedef int cs_dirent_dummy;
-#ifdef MG_MODULE_LINES
-#line 1 "common/cs_time.c"
-#endif
-
-/* Amalgamated: #include "common/cs_time.h" */
-
-#ifndef _WIN32
-#include <stddef.h>
-/*
- * There is no sys/time.h on ARMCC.
- */
-#if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \
-    !defined(__TI_COMPILER_VERSION__) &&                  \
-    (!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC)
-#include <sys/time.h>
-#endif
-#else
-#include <windows.h>
-#endif
-
-double cs_time(void) WEAK;
-double cs_time(void) {
-  double now;
-#ifndef _WIN32
-  struct timeval tv;
-  if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
-  now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
-#else
-  SYSTEMTIME sysnow;
-  FILETIME ftime;
-  GetLocalTime(&sysnow);
-  SystemTimeToFileTime(&sysnow, &ftime);
-  /*
-   * 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64
-   * This should not cause a problems in this (21th) century
-   * 2. Windows FILETIME is a number of 100-nanosecond intervals since January
-   * 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC,
-   * thus, we need to convert to seconds and adjust amount (subtract 11644473600
-   * seconds)
-   */
-  now = (double) (((int64_t) ftime.dwLowDateTime +
-                   ((int64_t) ftime.dwHighDateTime << 32)) /
-                  10000000.0) -
-        11644473600;
-#endif /* _WIN32 */
-  return now;
-}
-
-double cs_timegm(const struct tm *tm) {
-  /* Month-to-day offset for non-leap-years. */
-  static const int month_day[12] = {0,   31,  59,  90,  120, 151,
-                                    181, 212, 243, 273, 304, 334};
-
-  /* Most of the calculation is easy; leap years are the main difficulty. */
-  int month = tm->tm_mon % 12;
-  int year = tm->tm_year + tm->tm_mon / 12;
-  int year_for_leap;
-  int64_t rt;
-
-  if (month < 0) { /* Negative values % 12 are still negative. */
-    month += 12;
-    --year;
-  }
-
-  /* This is the number of Februaries since 1900. */
-  year_for_leap = (month > 1) ? year + 1 : year;
-
-  rt =
-      tm->tm_sec /* Seconds */
-      +
-      60 *
-          (tm->tm_min /* Minute = 60 seconds */
-           +
-           60 * (tm->tm_hour /* Hour = 60 minutes */
-                 +
-                 24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */
-                       + 365 * (year - 70)                /* Year = 365 days */
-                       + (year_for_leap - 69) / 4 /* Every 4 years is leap... */
-                       - (year_for_leap - 1) / 100 /* Except centuries... */
-                       + (year_for_leap + 299) / 400))); /* Except 400s. */
-  return rt < 0 ? -1 : (double) rt;
-}
-#ifdef MG_MODULE_LINES
-#line 1 "common/cs_endian.h"
-#endif
-
-#ifndef CS_COMMON_CS_ENDIAN_H_
-#define CS_COMMON_CS_ENDIAN_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * clang with std=-c99 uses __LITTLE_ENDIAN, by default
- * while for ex, RTOS gcc - LITTLE_ENDIAN, by default
- * it depends on __USE_BSD, but let's have everything
- */
-#if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
-#define BYTE_ORDER __BYTE_ORDER
-#ifndef LITTLE_ENDIAN
-#define LITTLE_ENDIAN __LITTLE_ENDIAN
-#endif /* LITTLE_ENDIAN */
-#ifndef BIG_ENDIAN
-#define BIG_ENDIAN __LITTLE_ENDIAN
-#endif /* BIG_ENDIAN */
-#endif /* BYTE_ORDER */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CS_COMMON_CS_ENDIAN_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "common/cs_md5.c"
-#endif
-/*
- * This code implements the MD5 message-digest algorithm.
- * The algorithm is due to Ron Rivest.  This code was
- * written by Colin Plumb in 1993, no copyright is claimed.
- * This code is in the public domain; do with it what you wish.
- *
- * Equivalent code is available from RSA Data Security, Inc.
- * This code has been tested against that, and is equivalent,
- * except that you don't need to include two pages of legalese
- * with every copy.
- *
- * To compute the message digest of a chunk of bytes, declare an
- * MD5Context structure, pass it to MD5Init, call MD5Update as
- * needed on buffers full of bytes, and then call MD5Final, which
- * will fill a supplied 16-byte array with the digest.
- */
-
-/* Amalgamated: #include "common/cs_md5.h" */
-/* Amalgamated: #include "common/str_util.h" */
-
-#if !defined(EXCLUDE_COMMON)
-#if !CS_DISABLE_MD5
-
-/* Amalgamated: #include "common/cs_endian.h" */
-
-static void byteReverse(unsigned char *buf, unsigned longs) {
-/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
-#if BYTE_ORDER == BIG_ENDIAN
-  do {
-    uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
-                 ((unsigned) buf[1] << 8 | buf[0]);
-    *(uint32_t *) buf = t;
-    buf += 4;
-  } while (--longs);
-#else
-  (void) buf;
-  (void) longs;
-#endif
-}
-
-#define F1(x, y, z) (z ^ (x & (y ^ z)))
-#define F2(x, y, z) F1(z, x, y)
-#define F3(x, y, z) (x ^ y ^ z)
-#define F4(x, y, z) (y ^ (x | ~z))
-
-#define MD5STEP(f, w, x, y, z, data, s) \
-  (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
-
-/*
- * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious
- * initialization constants.
- */
-void cs_md5_init(cs_md5_ctx *ctx) {
-  ctx->buf[0] = 0x67452301;
-  ctx->buf[1] = 0xefcdab89;
-  ctx->buf[2] = 0x98badcfe;
-  ctx->buf[3] = 0x10325476;
-
-  ctx->bits[0] = 0;
-  ctx->bits[1] = 0;
-}
-
-static void cs_md5_transform(uint32_t buf[4], uint32_t const in[16]) {
-  register uint32_t a, b, c, d;
-
-  a = buf[0];
-  b = buf[1];
-  c = buf[2];
-  d = buf[3];
-
-  MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
-  MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
-  MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
-  MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
-  MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
-  MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
-  MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
-  MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
-  MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
-  MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
-  MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
-  MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
-  MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
-  MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
-  MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
-  MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
-
-  MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
-  MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
-  MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
-  MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
-  MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
-  MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
-  MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
-  MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
-  MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
-  MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
-  MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
-  MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
-  MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
-  MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
-  MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
-  MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
-
-  MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
-  MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
-  MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
-  MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
-  MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
-  MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
-  MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
-  MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
-  MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
-  MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
-  MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
-  MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
-  MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
-  MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
-  MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
-  MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
-
-  MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
-  MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
-  MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
-  MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
-  MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
-  MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
-  MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
-  MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
-  MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
-  MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
-  MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
-  MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
-  MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
-  MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
-  MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
-  MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
-
-  buf[0] += a;
-  buf[1] += b;
-  buf[2] += c;
-  buf[3] += d;
-}
-
-void cs_md5_update(cs_md5_ctx *ctx, const unsigned char *buf, size_t len) {
-  uint32_t t;
-
-  t = ctx->bits[0];
-  if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
-  ctx->bits[1] += (uint32_t) len >> 29;
-
-  t = (t >> 3) & 0x3f;
-
-  if (t) {
-    unsigned char *p = (unsigned char *) ctx->in + t;
-
-    t = 64 - t;
-    if (len < t) {
-      memcpy(p, buf, len);
-      return;
-    }
-    memcpy(p, buf, t);
-    byteReverse(ctx->in, 16);
-    cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
-    buf += t;
-    len -= t;
-  }
-
-  while (len >= 64) {
-    memcpy(ctx->in, buf, 64);
-    byteReverse(ctx->in, 16);
-    cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
-    buf += 64;
-    len -= 64;
-  }
-
-  memcpy(ctx->in, buf, len);
-}
-
-void cs_md5_final(unsigned char digest[16], cs_md5_ctx *ctx) {
-  unsigned count;
-  unsigned char *p;
-  uint32_t *a;
-
-  count = (ctx->bits[0] >> 3) & 0x3F;
-
-  p = ctx->in + count;
-  *p++ = 0x80;
-  count = 64 - 1 - count;
-  if (count < 8) {
-    memset(p, 0, count);
-    byteReverse(ctx->in, 16);
-    cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
-    memset(ctx->in, 0, 56);
-  } else {
-    memset(p, 0, count - 8);
-  }
-  byteReverse(ctx->in, 14);
-
-  a = (uint32_t *) ctx->in;
-  a[14] = ctx->bits[0];
-  a[15] = ctx->bits[1];
-
-  cs_md5_transform(ctx->buf, (uint32_t *) ctx->in);
-  byteReverse((unsigned char *) ctx->buf, 4);
-  memcpy(digest, ctx->buf, 16);
-  memset((char *) ctx, 0, sizeof(*ctx));
-}
-
-#endif /* CS_DISABLE_MD5 */
-#endif /* EXCLUDE_COMMON */
-#ifdef MG_MODULE_LINES
-#line 1 "common/cs_sha1.c"
-#endif
-/* Copyright(c) By Steve Reid <steve@edmweb.com> */
-/* 100% Public Domain */
-
-/* Amalgamated: #include "common/cs_sha1.h" */
-
-#if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON)
-
-/* Amalgamated: #include "common/cs_endian.h" */
-
-#define SHA1HANDSOFF
-#if defined(__sun)
-/* Amalgamated: #include "common/solarisfixes.h" */
-#endif
-
-union char64long16 {
-  unsigned char c[64];
-  uint32_t l[16];
-};
-
-#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
-
-static uint32_t blk0(union char64long16 *block, int i) {
-/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
-#if BYTE_ORDER == LITTLE_ENDIAN
-  block->l[i] =
-      (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
-#endif
-  return block->l[i];
-}
-
-/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
-#undef blk
-#undef R0
-#undef R1
-#undef R2
-#undef R3
-#undef R4
-
-#define blk(i)                                                               \
-  (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
-                              block->l[(i + 2) & 15] ^ block->l[i & 15],     \
-                          1))
-#define R0(v, w, x, y, z, i)                                          \
-  z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
-  w = rol(w, 30);
-#define R1(v, w, x, y, z, i)                                  \
-  z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
-  w = rol(w, 30);
-#define R2(v, w, x, y, z, i)                          \
-  z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
-  w = rol(w, 30);
-#define R3(v, w, x, y, z, i)                                        \
-  z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
-  w = rol(w, 30);
-#define R4(v, w, x, y, z, i)                          \
-  z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
-  w = rol(w, 30);
-
-void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
-  uint32_t a, b, c, d, e;
-  union char64long16 block[1];
-
-  memcpy(block, buffer, 64);
-  a = state[0];
-  b = state[1];
-  c = state[2];
-  d = state[3];
-  e = state[4];
-  R0(a, b, c, d, e, 0);
-  R0(e, a, b, c, d, 1);
-  R0(d, e, a, b, c, 2);
-  R0(c, d, e, a, b, 3);
-  R0(b, c, d, e, a, 4);
-  R0(a, b, c, d, e, 5);
-  R0(e, a, b, c, d, 6);
-  R0(d, e, a, b, c, 7);
-  R0(c, d, e, a, b, 8);
-  R0(b, c, d, e, a, 9);
-  R0(a, b, c, d, e, 10);
-  R0(e, a, b, c, d, 11);
-  R0(d, e, a, b, c, 12);
-  R0(c, d, e, a, b, 13);
-  R0(b, c, d, e, a, 14);
-  R0(a, b, c, d, e, 15);
-  R1(e, a, b, c, d, 16);
-  R1(d, e, a, b, c, 17);
-  R1(c, d, e, a, b, 18);
-  R1(b, c, d, e, a, 19);
-  R2(a, b, c, d, e, 20);
-  R2(e, a, b, c, d, 21);
-  R2(d, e, a, b, c, 22);
-  R2(c, d, e, a, b, 23);
-  R2(b, c, d, e, a, 24);
-  R2(a, b, c, d, e, 25);
-  R2(e, a, b, c, d, 26);
-  R2(d, e, a, b, c, 27);
-  R2(c, d, e, a, b, 28);
-  R2(b, c, d, e, a, 29);
-  R2(a, b, c, d, e, 30);
-  R2(e, a, b, c, d, 31);
-  R2(d, e, a, b, c, 32);
-  R2(c, d, e, a, b, 33);
-  R2(b, c, d, e, a, 34);
-  R2(a, b, c, d, e, 35);
-  R2(e, a, b, c, d, 36);
-  R2(d, e, a, b, c, 37);
-  R2(c, d, e, a, b, 38);
-  R2(b, c, d, e, a, 39);
-  R3(a, b, c, d, e, 40);
-  R3(e, a, b, c, d, 41);
-  R3(d, e, a, b, c, 42);
-  R3(c, d, e, a, b, 43);
-  R3(b, c, d, e, a, 44);
-  R3(a, b, c, d, e, 45);
-  R3(e, a, b, c, d, 46);
-  R3(d, e, a, b, c, 47);
-  R3(c, d, e, a, b, 48);
-  R3(b, c, d, e, a, 49);
-  R3(a, b, c, d, e, 50);
-  R3(e, a, b, c, d, 51);
-  R3(d, e, a, b, c, 52);
-  R3(c, d, e, a, b, 53);
-  R3(b, c, d, e, a, 54);
-  R3(a, b, c, d, e, 55);
-  R3(e, a, b, c, d, 56);
-  R3(d, e, a, b, c, 57);
-  R3(c, d, e, a, b, 58);
-  R3(b, c, d, e, a, 59);
-  R4(a, b, c, d, e, 60);
-  R4(e, a, b, c, d, 61);
-  R4(d, e, a, b, c, 62);
-  R4(c, d, e, a, b, 63);
-  R4(b, c, d, e, a, 64);
-  R4(a, b, c, d, e, 65);
-  R4(e, a, b, c, d, 66);
-  R4(d, e, a, b, c, 67);
-  R4(c, d, e, a, b, 68);
-  R4(b, c, d, e, a, 69);
-  R4(a, b, c, d, e, 70);
-  R4(e, a, b, c, d, 71);
-  R4(d, e, a, b, c, 72);
-  R4(c, d, e, a, b, 73);
-  R4(b, c, d, e, a, 74);
-  R4(a, b, c, d, e, 75);
-  R4(e, a, b, c, d, 76);
-  R4(d, e, a, b, c, 77);
-  R4(c, d, e, a, b, 78);
-  R4(b, c, d, e, a, 79);
-  state[0] += a;
-  state[1] += b;
-  state[2] += c;
-  state[3] += d;
-  state[4] += e;
-  /* Erase working structures. The order of operations is important,
-   * used to ensure that compiler doesn't optimize those out. */
-  memset(block, 0, sizeof(block));
-  a = b = c = d = e = 0;
-  (void) a;
-  (void) b;
-  (void) c;
-  (void) d;
-  (void) e;
-}
-
-void cs_sha1_init(cs_sha1_ctx *context) {
-  context->state[0] = 0x67452301;
-  context->state[1] = 0xEFCDAB89;
-  context->state[2] = 0x98BADCFE;
-  context->state[3] = 0x10325476;
-  context->state[4] = 0xC3D2E1F0;
-  context->count[0] = context->count[1] = 0;
-}
-
-void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
-                    uint32_t len) {
-  uint32_t i, j;
-
-  j = context->count[0];
-  if ((context->count[0] += len << 3) < j) context->count[1]++;
-  context->count[1] += (len >> 29);
-  j = (j >> 3) & 63;
-  if ((j + len) > 63) {
-    memcpy(&context->buffer[j], data, (i = 64 - j));
-    cs_sha1_transform(context->state, context->buffer);
-    for (; i + 63 < len; i += 64) {
-      cs_sha1_transform(context->state, &data[i]);
-    }
-    j = 0;
-  } else
-    i = 0;
-  memcpy(&context->buffer[j], &data[i], len - i);
-}
-
-void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
-  unsigned i;
-  unsigned char finalcount[8], c;
-
-  for (i = 0; i < 8; i++) {
-    finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
-                                      ((3 - (i & 3)) * 8)) &
-                                     255);
-  }
-  c = 0200;
-  cs_sha1_update(context, &c, 1);
-  while ((context->count[0] & 504) != 448) {
-    c = 0000;
-    cs_sha1_update(context, &c, 1);
-  }
-  cs_sha1_update(context, finalcount, 8);
-  for (i = 0; i < 20; i++) {
-    digest[i] =
-        (unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
-  }
-  memset(context, '\0', sizeof(*context));
-  memset(&finalcount, '\0', sizeof(finalcount));
-}
-
-void cs_hmac_sha1(const unsigned char *key, size_t keylen,
-                  const unsigned char *data, size_t datalen,
-                  unsigned char out[20]) {
-  cs_sha1_ctx ctx;
-  unsigned char buf1[64], buf2[64], tmp_key[20], i;
-
-  if (keylen > sizeof(buf1)) {
-    cs_sha1_init(&ctx);
-    cs_sha1_update(&ctx, key, keylen);
-    cs_sha1_final(tmp_key, &ctx);
-    key = tmp_key;
-    keylen = sizeof(tmp_key);
-  }
-
-  memset(buf1, 0, sizeof(buf1));
-  memset(buf2, 0, sizeof(buf2));
-  memcpy(buf1, key, keylen);
-  memcpy(buf2, key, keylen);
-
-  for (i = 0; i < sizeof(buf1); i++) {
-    buf1[i] ^= 0x36;
-    buf2[i] ^= 0x5c;
-  }
-
-  cs_sha1_init(&ctx);
-  cs_sha1_update(&ctx, buf1, sizeof(buf1));
-  cs_sha1_update(&ctx, data, datalen);
-  cs_sha1_final(out, &ctx);
-
-  cs_sha1_init(&ctx);
-  cs_sha1_update(&ctx, buf2, sizeof(buf2));
-  cs_sha1_update(&ctx, out, 20);
-  cs_sha1_final(out, &ctx);
-}
-
-#endif /* EXCLUDE_COMMON */
-#ifdef MG_MODULE_LINES
-#line 1 "common/mbuf.c"
-#endif
-
-#ifndef EXCLUDE_COMMON
-
-#include <assert.h>
-#include <string.h>
-/* Amalgamated: #include "common/mbuf.h" */
-
-#ifndef MBUF_REALLOC
-#define MBUF_REALLOC realloc
-#endif
-
-#ifndef MBUF_FREE
-#define MBUF_FREE free
-#endif
-
-void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK;
-void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
-  mbuf->len = mbuf->size = 0;
-  mbuf->buf = NULL;
-  mbuf_resize(mbuf, initial_size);
-}
-
-void mbuf_free(struct mbuf *mbuf) WEAK;
-void mbuf_free(struct mbuf *mbuf) {
-  if (mbuf->buf != NULL) {
-    MBUF_FREE(mbuf->buf);
-    mbuf_init(mbuf, 0);
-  }
-}
-
-void mbuf_resize(struct mbuf *a, size_t new_size) WEAK;
-void mbuf_resize(struct mbuf *a, size_t new_size) {
-  if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
-    char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
-    /*
-     * In case realloc fails, there's not much we can do, except keep things as
-     * they are. Note that NULL is a valid return value from realloc when
-     * size == 0, but that is covered too.
-     */
-    if (buf == NULL && new_size != 0) return;
-    a->buf = buf;
-    a->size = new_size;
-  }
-}
-
-void mbuf_trim(struct mbuf *mbuf) WEAK;
-void mbuf_trim(struct mbuf *mbuf) {
-  mbuf_resize(mbuf, mbuf->len);
-}
-
-size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK;
-size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
-  char *p = NULL;
-
-  assert(a != NULL);
-  assert(a->len <= a->size);
-  assert(off <= a->len);
-
-  /* check overflow */
-  if (~(size_t) 0 - (size_t) a->buf < len) return 0;
-
-  if (a->len + len <= a->size) {
-    memmove(a->buf + off + len, a->buf + off, a->len - off);
-    if (buf != NULL) {
-      memcpy(a->buf + off, buf, len);
-    }
-    a->len += len;
-  } else {
-    size_t min_size = (a->len + len);
-    size_t new_size = (size_t)(min_size * MBUF_SIZE_MULTIPLIER);
-    if (new_size - min_size > MBUF_SIZE_MAX_HEADROOM) {
-      new_size = min_size + MBUF_SIZE_MAX_HEADROOM;
-    }
-    p = (char *) MBUF_REALLOC(a->buf, new_size);
-    if (p == NULL && new_size != min_size) {
-      new_size = min_size;
-      p = (char *) MBUF_REALLOC(a->buf, new_size);
-    }
-    if (p != NULL) {
-      a->buf = p;
-      if (off != a->len) {
-        memmove(a->buf + off + len, a->buf + off, a->len - off);
-      }
-      if (buf != NULL) memcpy(a->buf + off, buf, len);
-      a->len += len;
-      a->size = new_size;
-    } else {
-      len = 0;
-    }
-  }
-
-  return len;
-}
-
-size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK;
-size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
-  return mbuf_insert(a, a->len, buf, len);
-}
-
-size_t mbuf_append_and_free(struct mbuf *a, void *buf, size_t len) WEAK;
-size_t mbuf_append_and_free(struct mbuf *a, void *data, size_t len) {
-  size_t ret;
-  /* Optimization: if the buffer is currently empty,
-   * take over the user-provided buffer. */
-  if (a->len == 0) {
-    if (a->buf != NULL) free(a->buf);
-    a->buf = (char *) data;
-    a->len = a->size = len;
-    return len;
-  }
-  ret = mbuf_insert(a, a->len, data, len);
-  free(data);
-  return ret;
-}
-
-void mbuf_remove(struct mbuf *mb, size_t n) WEAK;
-void mbuf_remove(struct mbuf *mb, size_t n) {
-  if (n > 0 && n <= mb->len) {
-    memmove(mb->buf, mb->buf + n, mb->len - n);
-    mb->len -= n;
-  }
-}
-
-void mbuf_clear(struct mbuf *mb) WEAK;
-void mbuf_clear(struct mbuf *mb) {
-  mb->len = 0;
-}
-
-void mbuf_move(struct mbuf *from, struct mbuf *to) WEAK;
-void mbuf_move(struct mbuf *from, struct mbuf *to) {
-  memcpy(to, from, sizeof(*to));
-  memset(from, 0, sizeof(*from));
-}
-
-#endif /* EXCLUDE_COMMON */
-#ifdef MG_MODULE_LINES
-#line 1 "common/mg_str.c"
-#endif
-
-/* Amalgamated: #include "common/mg_mem.h" */
-/* Amalgamated: #include "common/mg_str.h" */
-/* Amalgamated: #include "common/platform.h" */
-
-#include <ctype.h>
-#include <stdlib.h>
-#include <string.h>
-
-int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
-
-struct mg_str mg_mk_str(const char *s) WEAK;
-struct mg_str mg_mk_str(const char *s) {
-  struct mg_str ret = {s, 0};
-  if (s != NULL) ret.len = strlen(s);
-  return ret;
-}
-
-struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK;
-struct mg_str mg_mk_str_n(const char *s, size_t len) {
-  struct mg_str ret = {s, len};
-  return ret;
-}
-
-int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK;
-int mg_vcmp(const struct mg_str *str1, const char *str2) {
-  size_t n2 = strlen(str2), n1 = str1->len;
-  int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2);
-  if (r == 0) {
-    return n1 - n2;
-  }
-  return r;
-}
-
-int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK;
-int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
-  size_t n2 = strlen(str2), n1 = str1->len;
-  int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
-  if (r == 0) {
-    return n1 - n2;
-  }
-  return r;
-}
-
-static struct mg_str mg_strdup_common(const struct mg_str s,
-                                      int nul_terminate) {
-  struct mg_str r = {NULL, 0};
-  if (s.len > 0 && s.p != NULL) {
-    char *sc = (char *) MG_MALLOC(s.len + (nul_terminate ? 1 : 0));
-    if (sc != NULL) {
-      memcpy(sc, s.p, s.len);
-      if (nul_terminate) sc[s.len] = '\0';
-      r.p = sc;
-      r.len = s.len;
-    }
-  }
-  return r;
-}
-
-struct mg_str mg_strdup(const struct mg_str s) WEAK;
-struct mg_str mg_strdup(const struct mg_str s) {
-  return mg_strdup_common(s, 0 /* NUL-terminate */);
-}
-
-struct mg_str mg_strdup_nul(const struct mg_str s) WEAK;
-struct mg_str mg_strdup_nul(const struct mg_str s) {
-  return mg_strdup_common(s, 1 /* NUL-terminate */);
-}
-
-const char *mg_strchr(const struct mg_str s, int c) WEAK;
-const char *mg_strchr(const struct mg_str s, int c) {
-  size_t i;
-  for (i = 0; i < s.len; i++) {
-    if (s.p[i] == c) return &s.p[i];
-  }
-  return NULL;
-}
-
-int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK;
-int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
-  size_t i = 0;
-  while (i < str1.len && i < str2.len) {
-    int c1 = str1.p[i];
-    int c2 = str2.p[i];
-    if (c1 < c2) return -1;
-    if (c1 > c2) return 1;
-    i++;
-  }
-  if (i < str1.len) return 1;
-  if (i < str2.len) return -1;
-  return 0;
-}
-
-int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK;
-int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) {
-  struct mg_str s1 = str1;
-  struct mg_str s2 = str2;
-
-  if (s1.len > n) {
-    s1.len = n;
-  }
-  if (s2.len > n) {
-    s2.len = n;
-  }
-  return mg_strcmp(s1, s2);
-}
-
-int mg_strcasecmp(const struct mg_str str1, const struct mg_str str2) WEAK;
-int mg_strcasecmp(const struct mg_str str1, const struct mg_str str2) {
-  size_t i = 0;
-  while (i < str1.len && i < str2.len) {
-    int c1 = tolower((int) str1.p[i]);
-    int c2 = tolower((int) str2.p[i]);
-    if (c1 < c2) return -1;
-    if (c1 > c2) return 1;
-    i++;
-  }
-  if (i < str1.len) return 1;
-  if (i < str2.len) return -1;
-  return 0;
-}
-
-void mg_strfree(struct mg_str *s) WEAK;
-void mg_strfree(struct mg_str *s) {
-  char *sp = (char *) s->p;
-  s->p = NULL;
-  s->len = 0;
-  if (sp != NULL) free(sp);
-}
-
-const char *mg_strstr(const struct mg_str haystack,
-                      const struct mg_str needle) WEAK;
-const char *mg_strstr(const struct mg_str haystack,
-                      const struct mg_str needle) {
-  size_t i;
-  if (needle.len > haystack.len) return NULL;
-  for (i = 0; i <= haystack.len - needle.len; i++) {
-    if (memcmp(haystack.p + i, needle.p, needle.len) == 0) {
-      return haystack.p + i;
-    }
-  }
-  return NULL;
-}
-
-struct mg_str mg_strstrip(struct mg_str s) WEAK;
-struct mg_str mg_strstrip(struct mg_str s) {
-  while (s.len > 0 && isspace((int) *s.p)) {
-    s.p++;
-    s.len--;
-  }
-  while (s.len > 0 && isspace((int) *(s.p + s.len - 1))) {
-    s.len--;
-  }
-  return s;
-}
-
-int mg_str_starts_with(struct mg_str s, struct mg_str prefix) WEAK;
-int mg_str_starts_with(struct mg_str s, struct mg_str prefix) {
-  const struct mg_str sp = MG_MK_STR_N(s.p, prefix.len);
-  if (s.len < prefix.len) return 0;
-  return (mg_strcmp(sp, prefix) == 0);
-}
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/str_util.c"
-#endif
-
-#ifndef EXCLUDE_COMMON
-
-/* Amalgamated: #include "common/str_util.h" */
-/* Amalgamated: #include "common/mg_mem.h" */
-/* Amalgamated: #include "common/platform.h" */
-
-#ifndef C_DISABLE_BUILTIN_SNPRINTF
-#define C_DISABLE_BUILTIN_SNPRINTF 0
-#endif
-
-/* Amalgamated: #include "common/mg_mem.h" */
-
-size_t c_strnlen(const char *s, size_t maxlen) WEAK;
-size_t c_strnlen(const char *s, size_t maxlen) {
-  size_t l = 0;
-  for (; l < maxlen && s[l] != '\0'; l++) {
-  }
-  return l;
-}
-
-#define C_SNPRINTF_APPEND_CHAR(ch)       \
-  do {                                   \
-    if (i < (int) buf_size) buf[i] = ch; \
-    i++;                                 \
-  } while (0)
-
-#define C_SNPRINTF_FLAG_ZERO 1
-
-#if C_DISABLE_BUILTIN_SNPRINTF
-int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
-int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
-  return vsnprintf(buf, buf_size, fmt, ap);
-}
-#else
-static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
-                  int field_width) {
-  char tmp[40];
-  int i = 0, k = 0, neg = 0;
-
-  if (num < 0) {
-    neg++;
-    num = -num;
-  }
-
-  /* Print into temporary buffer - in reverse order */
-  do {
-    int rem = num % base;
-    if (rem < 10) {
-      tmp[k++] = '0' + rem;
-    } else {
-      tmp[k++] = 'a' + (rem - 10);
-    }
-    num /= base;
-  } while (num > 0);
-
-  /* Zero padding */
-  if (flags && C_SNPRINTF_FLAG_ZERO) {
-    while (k < field_width && k < (int) sizeof(tmp) - 1) {
-      tmp[k++] = '0';
-    }
-  }
-
-  /* And sign */
-  if (neg) {
-    tmp[k++] = '-';
-  }
-
-  /* Now output */
-  while (--k >= 0) {
-    C_SNPRINTF_APPEND_CHAR(tmp[k]);
-  }
-
-  return i;
-}
-
-int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
-int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
-  int ch, i = 0, len_mod, flags, precision, field_width;
-
-  while ((ch = *fmt++) != '\0') {
-    if (ch != '%') {
-      C_SNPRINTF_APPEND_CHAR(ch);
-    } else {
-      /*
-       * Conversion specification:
-       *   zero or more flags (one of: # 0 - <space> + ')
-       *   an optional minimum  field  width (digits)
-       *   an  optional precision (. followed by digits, or *)
-       *   an optional length modifier (one of: hh h l ll L q j z t)
-       *   conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
-       */
-      flags = field_width = precision = len_mod = 0;
-
-      /* Flags. only zero-pad flag is supported. */
-      if (*fmt == '0') {
-        flags |= C_SNPRINTF_FLAG_ZERO;
-      }
-
-      /* Field width */
-      while (*fmt >= '0' && *fmt <= '9') {
-        field_width *= 10;
-        field_width += *fmt++ - '0';
-      }
-      /* Dynamic field width */
-      if (*fmt == '*') {
-        field_width = va_arg(ap, int);
-        fmt++;
-      }
-
-      /* Precision */
-      if (*fmt == '.') {
-        fmt++;
-        if (*fmt == '*') {
-          precision = va_arg(ap, int);
-          fmt++;
-        } else {
-          while (*fmt >= '0' && *fmt <= '9') {
-            precision *= 10;
-            precision += *fmt++ - '0';
-          }
-        }
-      }
-
-      /* Length modifier */
-      switch (*fmt) {
-        case 'h':
-        case 'l':
-        case 'L':
-        case 'I':
-        case 'q':
-        case 'j':
-        case 'z':
-        case 't':
-          len_mod = *fmt++;
-          if (*fmt == 'h') {
-            len_mod = 'H';
-            fmt++;
-          }
-          if (*fmt == 'l') {
-            len_mod = 'q';
-            fmt++;
-          }
-          break;
-      }
-
-      ch = *fmt++;
-      if (ch == 's') {
-        const char *s = va_arg(ap, const char *); /* Always fetch parameter */
-        int j;
-        int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
-        for (j = 0; j < pad; j++) {
-          C_SNPRINTF_APPEND_CHAR(' ');
-        }
-
-        /* `s` may be NULL in case of %.*s */
-        if (s != NULL) {
-          /* Ignore negative and 0 precisions */
-          for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
-            C_SNPRINTF_APPEND_CHAR(s[j]);
-          }
-        }
-      } else if (ch == 'c') {
-        ch = va_arg(ap, int); /* Always fetch parameter */
-        C_SNPRINTF_APPEND_CHAR(ch);
-      } else if (ch == 'd' && len_mod == 0) {
-        i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
-                    field_width);
-      } else if (ch == 'd' && len_mod == 'l') {
-        i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
-                    field_width);
-#ifdef SSIZE_MAX
-      } else if (ch == 'd' && len_mod == 'z') {
-        i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
-                    field_width);
-#endif
-      } else if (ch == 'd' && len_mod == 'q') {
-        i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
-                    field_width);
-      } else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
-        i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
-                    ch == 'x' ? 16 : 10, flags, field_width);
-      } else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
-        i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
-                    ch == 'x' ? 16 : 10, flags, field_width);
-      } else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
-        i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
-                    ch == 'x' ? 16 : 10, flags, field_width);
-      } else if (ch == 'p') {
-        unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *);
-        C_SNPRINTF_APPEND_CHAR('0');
-        C_SNPRINTF_APPEND_CHAR('x');
-        i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
-      } else {
-#ifndef NO_LIBC
-        /*
-         * TODO(lsm): abort is not nice in a library, remove it
-         * Also, ESP8266 SDK doesn't have it
-         */
-        abort();
-#endif
-      }
-    }
-  }
-
-  /* Zero-terminate the result */
-  if (buf_size > 0) {
-    buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
-  }
-
-  return i;
-}
-#endif
-
-int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK;
-int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
-  int result;
-  va_list ap;
-  va_start(ap, fmt);
-  result = c_vsnprintf(buf, buf_size, fmt, ap);
-  va_end(ap);
-  return result;
-}
-
-#ifdef _WIN32
-int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
-  int ret;
-  char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
-
-  strncpy(buf, path, sizeof(buf));
-  buf[sizeof(buf) - 1] = '\0';
-
-  /* Trim trailing slashes. Leave backslash for paths like "X:\" */
-  p = buf + strlen(buf) - 1;
-  while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
-
-  memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
-  ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
-
-  /*
-   * Convert back to Unicode. If doubly-converted string does not match the
-   * original, something is fishy, reject.
-   */
-  WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
-                      NULL, NULL);
-  if (strcmp(buf, buf2) != 0) {
-    wbuf[0] = L'\0';
-    ret = 0;
-  }
-
-  return ret;
-}
-#endif /* _WIN32 */
-
-/* The simplest O(mn) algorithm. Better implementation are GPLed */
-const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK;
-const char *c_strnstr(const char *s, const char *find, size_t slen) {
-  size_t find_length = strlen(find);
-  size_t i;
-
-  for (i = 0; i < slen; i++) {
-    if (i + find_length > slen) {
-      return NULL;
-    }
-
-    if (strncmp(&s[i], find, find_length) == 0) {
-      return &s[i];
-    }
-  }
-
-  return NULL;
-}
-
-#if CS_ENABLE_STRDUP
-char *strdup(const char *src) WEAK;
-char *strdup(const char *src) {
-  size_t len = strlen(src) + 1;
-  char *ret = MG_MALLOC(len);
-  if (ret != NULL) {
-    strcpy(ret, src);
-  }
-  return ret;
-}
-#endif
-
-void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK;
-void cs_to_hex(char *to, const unsigned char *p, size_t len) {
-  static const char *hex = "0123456789abcdef";
-
-  for (; len--; p++) {
-    *to++ = hex[p[0] >> 4];
-    *to++ = hex[p[0] & 0x0f];
-  }
-  *to = '\0';
-}
-
-static int fourbit(int ch) {
-  if (ch >= '0' && ch <= '9') {
-    return ch - '0';
-  } else if (ch >= 'a' && ch <= 'f') {
-    return ch - 'a' + 10;
-  } else if (ch >= 'A' && ch <= 'F') {
-    return ch - 'A' + 10;
-  }
-  return 0;
-}
-
-void cs_from_hex(char *to, const char *p, size_t len) WEAK;
-void cs_from_hex(char *to, const char *p, size_t len) {
-  size_t i;
-
-  for (i = 0; i < len; i += 2) {
-    *to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]);
-  }
-  *to = '\0';
-}
-
-#if CS_ENABLE_TO64
-int64_t cs_to64(const char *s) WEAK;
-int64_t cs_to64(const char *s) {
-  int64_t result = 0;
-  int64_t neg = 1;
-  while (*s && isspace((unsigned char) *s)) s++;
-  if (*s == '-') {
-    neg = -1;
-    s++;
-  }
-  while (isdigit((unsigned char) *s)) {
-    result *= 10;
-    result += (*s - '0');
-    s++;
-  }
-  return result * neg;
-}
-#endif
-
-static int str_util_lowercase(const char *s) {
-  return tolower(*(const unsigned char *) s);
-}
-
-int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
-int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
-  int diff = 0;
-
-  if (len > 0) do {
-      diff = str_util_lowercase(s1++) - str_util_lowercase(s2++);
-    } while (diff == 0 && s1[-1] != '\0' && --len > 0);
-
-  return diff;
-}
-
-int mg_casecmp(const char *s1, const char *s2) WEAK;
-int mg_casecmp(const char *s1, const char *s2) {
-  return mg_ncasecmp(s1, s2, (size_t) ~0);
-}
-
-int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK;
-int mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
-  int ret;
-  va_list ap;
-  va_start(ap, fmt);
-  ret = mg_avprintf(buf, size, fmt, ap);
-  va_end(ap);
-  return ret;
-}
-
-int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK;
-int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
-  va_list ap_copy;
-  int len;
-
-  va_copy(ap_copy, ap);
-  len = vsnprintf(*buf, size, fmt, ap_copy);
-  va_end(ap_copy);
-
-  if (len < 0) {
-    /* eCos and Windows are not standard-compliant and return -1 when
-     * the buffer is too small. Keep allocating larger buffers until we
-     * succeed or out of memory. */
-    *buf = NULL; /* LCOV_EXCL_START */
-    while (len < 0) {
-      MG_FREE(*buf);
-      if (size == 0) {
-        size = 5;
-      }
-      size *= 2;
-      if ((*buf = (char *) MG_MALLOC(size)) == NULL) {
-        len = -1;
-        break;
-      }
-      va_copy(ap_copy, ap);
-      len = vsnprintf(*buf, size - 1, fmt, ap_copy);
-      va_end(ap_copy);
-    }
-
-    /*
-     * Microsoft version of vsnprintf() is not always null-terminated, so put
-     * the terminator manually
-     */
-    (*buf)[len] = 0;
-    /* LCOV_EXCL_STOP */
-  } else if (len >= (int) size) {
-    /* Standard-compliant code path. Allocate a buffer that is large enough. */
-    if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
-      len = -1; /* LCOV_EXCL_LINE */
-    } else {    /* LCOV_EXCL_LINE */
-      va_copy(ap_copy, ap);
-      len = vsnprintf(*buf, len + 1, fmt, ap_copy);
-      va_end(ap_copy);
-    }
-  }
-
-  return len;
-}
-
-const char *mg_next_comma_list_entry(const char *, struct mg_str *,
-                                     struct mg_str *) WEAK;
-const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
-                                     struct mg_str *eq_val) {
-  struct mg_str ret = mg_next_comma_list_entry_n(mg_mk_str(list), val, eq_val);
-  return ret.p;
-}
-
-struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
-                                         struct mg_str *eq_val) WEAK;
-struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
-                                         struct mg_str *eq_val) {
-  if (list.len == 0) {
-    /* End of the list */
-    list = mg_mk_str(NULL);
-  } else {
-    const char *chr = NULL;
-    *val = list;
-
-    if ((chr = mg_strchr(*val, ',')) != NULL) {
-      /* Comma found. Store length and shift the list ptr */
-      val->len = chr - val->p;
-      chr++;
-      list.len -= (chr - list.p);
-      list.p = chr;
-    } else {
-      /* This value is the last one */
-      list = mg_mk_str_n(list.p + list.len, 0);
-    }
-
-    if (eq_val != NULL) {
-      /* Value has form "x=y", adjust pointers and lengths */
-      /* so that val points to "x", and eq_val points to "y". */
-      eq_val->len = 0;
-      eq_val->p = (const char *) memchr(val->p, '=', val->len);
-      if (eq_val->p != NULL) {
-        eq_val->p++; /* Skip over '=' character */
-        eq_val->len = val->p + val->len - eq_val->p;
-        val->len = (eq_val->p - val->p) - 1;
-      }
-    }
-  }
-
-  return list;
-}
-
-size_t mg_match_prefix_n(const struct mg_str, const struct mg_str) WEAK;
-size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
-  const char *or_str;
-  size_t res = 0, len = 0, i = 0, j = 0;
-
-  if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL ||
-      (or_str = (const char *) memchr(pattern.p, ',', pattern.len)) != NULL) {
-    struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
-    res = mg_match_prefix_n(pstr, str);
-    if (res > 0) return res;
-    pstr.p = or_str + 1;
-    pstr.len = (pattern.p + pattern.len) - (or_str + 1);
-    return mg_match_prefix_n(pstr, str);
-  }
-
-  for (; i < pattern.len && j < str.len; i++, j++) {
-    if (pattern.p[i] == '?') {
-      continue;
-    } else if (pattern.p[i] == '*') {
-      i++;
-      if (i < pattern.len && pattern.p[i] == '*') {
-        i++;
-        len = str.len - j;
-      } else {
-        len = 0;
-        while (j + len < str.len && str.p[j + len] != '/') len++;
-      }
-      if (i == pattern.len || (pattern.p[i] == '$' && i == pattern.len - 1))
-        return j + len;
-      do {
-        const struct mg_str pstr = {pattern.p + i, pattern.len - i};
-        const struct mg_str sstr = {str.p + j + len, str.len - j - len};
-        res = mg_match_prefix_n(pstr, sstr);
-      } while (res == 0 && len != 0 && len-- > 0);
-      return res == 0 ? 0 : j + res + len;
-    } else if (str_util_lowercase(&pattern.p[i]) !=
-               str_util_lowercase(&str.p[j])) {
-      break;
-    }
-  }
-  if (i < pattern.len && pattern.p[i] == '$') {
-    return j == str.len ? str.len : 0;
-  }
-  return i == pattern.len ? j : 0;
-}
-
-size_t mg_match_prefix(const char *, int, const char *) WEAK;
-size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
-  const struct mg_str pstr = {pattern, (size_t) pattern_len};
-  struct mg_str s = {str, 0};
-  if (str != NULL) s.len = strlen(str);
-  return mg_match_prefix_n(pstr, s);
-}
-
-#endif /* EXCLUDE_COMMON */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_net.c"
-#endif
-
-/* Amalgamated: #include "common/cs_time.h" */
-/* Amalgamated: #include "mg_dns.h" */
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_resolv.h" */
-/* Amalgamated: #include "mg_util.h" */
-
-#define MG_MAX_HOST_LEN 200
-
-#ifndef MG_TCP_IO_SIZE
-#define MG_TCP_IO_SIZE 1460
-#endif
-#ifndef MG_UDP_IO_SIZE
-#define MG_UDP_IO_SIZE 1460
-#endif
-
-#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
-  memcpy(dst, src, sizeof(*dst));
-
-/* Which flags can be pre-set by the user at connection creation time. */
-#define _MG_ALLOWED_CONNECT_FLAGS_MASK                                   \
-  (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
-   MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST)
-/* Which flags should be modifiable by user's callbacks. */
-#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK                               \
-  (MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
-   MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE |        \
-   MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
-
-#ifndef intptr_t
-#define intptr_t long
-#endif
-
-MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
-  DBG(("%p %p", (void*)mgr, (void*)c));
-  c->mgr = mgr;
-  c->next = mgr->active_connections;
-  mgr->active_connections = c;
-  c->prev = NULL;
-  if (c->next != NULL) c->next->prev = c;
-  if (c->sock != INVALID_SOCKET) {
-    c->iface->vtable->add_conn(c);
-  }
-}
-
-MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
-  if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
-  if (conn->prev) conn->prev->next = conn->next;
-  if (conn->next) conn->next->prev = conn->prev;
-  conn->prev = conn->next = NULL;
-  conn->iface->vtable->remove_conn(conn);
-}
-
-MG_INTERNAL void mg_call(struct mg_connection *nc,
-                         mg_event_handler_t ev_handler, void *user_data, int ev,
-                         void *ev_data) {
-  if (ev_handler == NULL) {
-    /*
-     * If protocol handler is specified, call it. Otherwise, call user-specified
-     * event handler.
-     */
-    ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
-  }
-  if (ev != MG_EV_POLL) {
-    DBG(("%p %s ev=%d ev_data=%p flags=0x%lx rmbl=%d smbl=%d", (void*)nc,
-         ev_handler == nc->handler ? "user" : "proto", ev, (void*)ev_data, nc->flags,
-         (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
-  }
-
-#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
-  if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL && ev != MG_EV_RECV &&
-      ev != MG_EV_SEND /* handled separately */) {
-    mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev);
-  }
-#endif
-  if (ev_handler != NULL) {
-    unsigned long flags_before = nc->flags;
-    ev_handler(nc, ev, ev_data MG_UD_ARG(user_data));
-    /* Prevent user handler from fiddling with system flags. */
-    if (ev_handler == nc->handler && nc->flags != flags_before) {
-      nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
-                  (nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
-    }
-  }
-  if (ev != MG_EV_POLL) nc->mgr->num_calls++;
-  if (ev != MG_EV_POLL) {
-    DBG(("%p after %s flags=0x%lx rmbl=%d smbl=%d", (void*)nc,
-         ev_handler == nc->handler ? "user" : "proto", nc->flags,
-         (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
-  }
-#if !MG_ENABLE_CALLBACK_USERDATA
-  (void) user_data;
-#endif
-}
-
-MG_INTERNAL void mg_timer(struct mg_connection *c, double now) {
-  if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
-    double old_value = c->ev_timer_time;
-    c->ev_timer_time = 0;
-    mg_call(c, NULL, c->user_data, MG_EV_TIMER, &old_value);
-  }
-}
-
-MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
-  size_t avail;
-  if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
-  avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
-  return avail > max ? max : avail;
-}
-
-static int mg_do_recv(struct mg_connection *nc);
-
-int mg_if_poll(struct mg_connection *nc, double now) {
-  if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
-    mg_close_conn(nc);
-    return 0;
-  } else if (nc->flags & MG_F_SEND_AND_CLOSE) {
-    if (nc->send_mbuf.len == 0) {
-      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-      mg_close_conn(nc);
-      return 0;
-    }
-  } else if (nc->flags & MG_F_RECV_AND_CLOSE) {
-    mg_close_conn(nc);
-    return 0;
-  }
-#if MG_ENABLE_SSL
-  if ((nc->flags & (MG_F_SSL | MG_F_LISTENING | MG_F_CONNECTING)) == MG_F_SSL) {
-    /* SSL library may have data to be delivered to the app in its buffers,
-     * drain them. */
-    int recved = 0;
-    do {
-      if (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE)) break;
-      if (recv_avail_size(nc, MG_TCP_IO_SIZE) <= 0) break;
-      recved = mg_do_recv(nc);
-    } while (recved > 0);
-  }
-#endif /* MG_ENABLE_SSL */
-  mg_timer(nc, now);
-  {
-    time_t now_t = (time_t) now;
-    mg_call(nc, NULL, nc->user_data, MG_EV_POLL, &now_t);
-  }
-  return 1;
-}
-
-void mg_destroy_conn(struct mg_connection *conn, int destroy_if) {
-  if (conn->sock != INVALID_SOCKET) { /* Don't print timer-only conns */
-    LOG(LL_DEBUG, ("%p 0x%lx %d", (void*)conn, conn->flags, destroy_if));
-  }
-  if (destroy_if) conn->iface->vtable->destroy_conn(conn);
-  if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) {
-    conn->proto_data_destructor(conn->proto_data);
-  }
-#if MG_ENABLE_SSL
-  mg_ssl_if_conn_free(conn);
-#endif
-  mbuf_free(&conn->recv_mbuf);
-  mbuf_free(&conn->send_mbuf);
-
-  memset(conn, 0, sizeof(*conn));
-  MG_FREE(conn);
-}
-
-void mg_close_conn(struct mg_connection *conn) {
-  /* See if there's any remaining data to deliver. Skip if user completely
-   * throttled the connection there will be no progress anyway. */
-  if (conn->sock != INVALID_SOCKET && mg_do_recv(conn) == -2) {
-    /* Receive is throttled, wait. */
-    conn->flags |= MG_F_RECV_AND_CLOSE;
-    return;
-  }
-#if MG_ENABLE_SSL
-  if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
-    mg_ssl_if_conn_close_notify(conn);
-  }
-#endif
-  /*
-   * Clearly mark the connection as going away (if not already).
-   * Some net_if impls (LwIP) need this for cleanly handling half-dead conns.
-   */
-  conn->flags |= MG_F_CLOSE_IMMEDIATELY;
-  mg_remove_conn(conn);
-  conn->iface->vtable->destroy_conn(conn);
-  mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL);
-  mg_destroy_conn(conn, 0 /* destroy_if */);
-}
-
-void mg_mgr_init(struct mg_mgr *m, void *user_data) {
-  struct mg_mgr_init_opts opts;
-  memset(&opts, 0, sizeof(opts));
-  mg_mgr_init_opt(m, user_data, opts);
-}
-
-void mg_mgr_init_opt(struct mg_mgr *m, void *user_data,
-                     struct mg_mgr_init_opts opts) {
-  memset(m, 0, sizeof(*m));
-#if MG_ENABLE_BROADCAST
-  m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
-#endif
-  m->user_data = user_data;
-
-#ifdef _WIN32
-  {
-    WSADATA data;
-    WSAStartup(MAKEWORD(2, 2), &data);
-  }
-#elif defined(__unix__)
-  /* Ignore SIGPIPE signal, so if client cancels the request, it
-   * won't kill the whole process. */
-  signal(SIGPIPE, SIG_IGN);
-#endif
-
-  {
-    int i;
-    if (opts.num_ifaces == 0) {
-      opts.num_ifaces = mg_num_ifaces;
-      opts.ifaces = mg_ifaces;
-    }
-    if (opts.main_iface != NULL) {
-      opts.ifaces[MG_MAIN_IFACE] = opts.main_iface;
-    }
-    m->num_ifaces = opts.num_ifaces;
-    m->ifaces =
-        (struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces);
-    for (i = 0; i < opts.num_ifaces; i++) {
-      m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m);
-      m->ifaces[i]->vtable->init(m->ifaces[i]);
-    }
-  }
-  if (opts.nameserver != NULL) {
-    m->nameserver = strdup(opts.nameserver);
-  }
-  DBG(("=================================="));
-  DBG(("init mgr=%p", (void*)m));
-#if MG_ENABLE_SSL
-  {
-    static int init_done;
-    if (!init_done) {
-      mg_ssl_if_init();
-      init_done++;
-    }
-  }
-#endif
-}
-
-void mg_mgr_free(struct mg_mgr *m) {
-  struct mg_connection *conn, *tmp_conn;
-
-  DBG(("%p", (void*)m));
-  if (m == NULL) return;
-  /* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
-  mg_mgr_poll(m, 0);
-
-#if MG_ENABLE_BROADCAST
-  if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
-  if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
-  m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
-#endif
-
-  for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
-    tmp_conn = conn->next;
-    conn->flags |= MG_F_CLOSE_IMMEDIATELY;
-    mg_close_conn(conn);
-  }
-
-  {
-    int i;
-    for (i = 0; i < m->num_ifaces; i++) {
-      m->ifaces[i]->vtable->free(m->ifaces[i]);
-      MG_FREE(m->ifaces[i]);
-    }
-    MG_FREE(m->ifaces);
-  }
-
-  MG_FREE((char *) m->nameserver);
-}
-
-int mg_mgr_poll(struct mg_mgr *m, int timeout_ms) {
-  int i, num_calls_before = m->num_calls;
-
-  for (i = 0; i < m->num_ifaces; i++) {
-    m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms);
-  }
-
-  return (m->num_calls - num_calls_before);
-}
-
-int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
-  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
-  int len;
-
-  if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
-    mg_send(nc, buf, len);
-  }
-  if (buf != mem && buf != NULL) {
-    MG_FREE(buf); /* LCOV_EXCL_LINE */
-  }               /* LCOV_EXCL_LINE */
-
-  return len;
-}
-
-int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
-  int len;
-  va_list ap;
-  va_start(ap, fmt);
-  len = mg_vprintf(conn, fmt, ap);
-  va_end(ap);
-  return len;
-}
-
-#if MG_ENABLE_SYNC_RESOLVER
-/* TODO(lsm): use non-blocking resolver */
-static int mg_resolve2(const char *host, struct in_addr *ina) {
-#if MG_ENABLE_GETADDRINFO
-  int rv = 0;
-  struct addrinfo hints, *servinfo, *p;
-  struct sockaddr_in *h = NULL;
-  memset(&hints, 0, sizeof hints);
-  hints.ai_family = AF_INET;
-  hints.ai_socktype = SOCK_STREAM;
-  if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
-    DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno())));
-    return 0;
-  }
-  for (p = servinfo; p != NULL; p = p->ai_next) {
-    memcpy(&h, &p->ai_addr, sizeof(h));
-    memcpy(ina, &h->sin_addr, sizeof(*ina));
-  }
-  freeaddrinfo(servinfo);
-  return 1;
-#else
-  struct hostent *he;
-  if ((he = gethostbyname(host)) == NULL) {
-    DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno())));
-  } else {
-    memcpy(ina, he->h_addr_list[0], sizeof(*ina));
-    return 1;
-  }
-  return 0;
-#endif /* MG_ENABLE_GETADDRINFO */
-}
-
-int mg_resolve(const char *host, char *buf, size_t n) {
-  struct in_addr ad;
-  return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
-}
-#endif /* MG_ENABLE_SYNC_RESOLVER */
-
-MG_INTERNAL struct mg_connection *mg_create_connection_base(
-    struct mg_mgr *mgr, mg_event_handler_t callback,
-    struct mg_add_sock_opts opts) {
-  struct mg_connection *conn;
-
-  if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
-    conn->sock = INVALID_SOCKET;
-    conn->handler = callback;
-    conn->mgr = mgr;
-    conn->last_io_time = (time_t) mg_time();
-    conn->iface =
-        (opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]);
-    conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
-    conn->user_data = opts.user_data;
-    /*
-     * SIZE_MAX is defined as a long long constant in
-     * system headers on some platforms and so it
-     * doesn't compile with pedantic ansi flags.
-     */
-    conn->recv_mbuf_limit = ~0;
-  } else {
-    MG_SET_PTRPTR(opts.error_string, "failed to create connection");
-  }
-
-  return conn;
-}
-
-MG_INTERNAL struct mg_connection *mg_create_connection(
-    struct mg_mgr *mgr, mg_event_handler_t callback,
-    struct mg_add_sock_opts opts) {
-  struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts);
-
-  if (conn != NULL && !conn->iface->vtable->create_conn(conn)) {
-    MG_FREE(conn);
-    conn = NULL;
-  }
-  if (conn == NULL) {
-    MG_SET_PTRPTR(opts.error_string, "failed to init connection");
-  }
-
-  return conn;
-}
-
-/*
- * Address format: [PROTO://][HOST]:PORT
- *
- * HOST could be IPv4/IPv6 address or a host name.
- * `host` is a destination buffer to hold parsed HOST part. Should be at least
- * MG_MAX_HOST_LEN bytes long.
- * `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
- *
- * Return:
- *   -1   on parse error
- *    0   if HOST needs DNS lookup
- *   >0   length of the address string
- */
-MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
-                                 int *proto, char *host, size_t host_len) {
-  unsigned int a, b, c, d, port = 0;
-  int ch, len = 0;
-#if MG_ENABLE_IPV6
-  char buf[100];
-#endif
-
-  /*
-   * MacOS needs that. If we do not zero it, subsequent bind() will fail.
-   * Also, all-zeroes in the socket address means binding to all addresses
-   * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
-   */
-  memset(sa, 0, sizeof(*sa));
-  sa->sin.sin_family = AF_INET;
-
-  *proto = SOCK_STREAM;
-
-  if (strncmp(str, "udp://", 6) == 0) {
-    str += 6;
-    *proto = SOCK_DGRAM;
-  } else if (strncmp(str, "tcp://", 6) == 0) {
-    str += 6;
-  }
-
-  if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
-    /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
-    sa->sin.sin_addr.s_addr =
-        htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
-    sa->sin.sin_port = htons((uint16_t) port);
-#if MG_ENABLE_IPV6
-  } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
-             inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
-    /* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
-    sa->sin6.sin6_family = AF_INET6;
-    sa->sin.sin_port = htons((uint16_t) port);
-#endif
-#if MG_ENABLE_ASYNC_RESOLVER
-  } else if (strlen(str) < host_len &&
-             sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
-    sa->sin.sin_port = htons((uint16_t) port);
-    if (mg_resolve_from_hosts_file(host, sa) != 0) {
-      /*
-       * if resolving from hosts file failed and the host
-       * we are trying to resolve is `localhost` - we should
-       * try to resolve it using `gethostbyname` and do not try
-       * to resolve it via DNS server if gethostbyname has failed too
-       */
-      if (mg_ncasecmp(host, "localhost", 9) != 0) {
-        return 0;
-      }
-
-#if MG_ENABLE_SYNC_RESOLVER
-      if (!mg_resolve2(host, &sa->sin.sin_addr)) {
-        return -1;
-      }
-#else
-      return -1;
-#endif
-    }
-#endif
-  } else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
-             sscanf(str, "%u%n", &port, &len) == 1) {
-    /* If only port is specified, bind to IPv4, INADDR_ANY */
-    sa->sin.sin_port = htons((uint16_t) port);
-  } else {
-    return -1;
-  }
-
-  /* Required for MG_ENABLE_ASYNC_RESOLVER=0 */
-  (void) host;
-  (void) host_len;
-
-  ch = str[len]; /* Character that follows the address */
-  return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
-}
-
-#if MG_ENABLE_SSL
-MG_INTERNAL void mg_ssl_handshake(struct mg_connection *nc) {
-  int err = 0;
-  int server_side = (nc->listener != NULL);
-  enum mg_ssl_if_result res;
-  if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) return;
-  res = mg_ssl_if_handshake(nc);
-
-  if (res == MG_SSL_OK) {
-    nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
-    nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
-    if (server_side) {
-      mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
-    } else {
-      mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
-    }
-  } else if (res == MG_SSL_WANT_READ) {
-    nc->flags |= MG_F_WANT_READ;
-  } else if (res == MG_SSL_WANT_WRITE) {
-    nc->flags |= MG_F_WANT_WRITE;
-  } else {
-    if (!server_side) {
-      err = res;
-      mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
-    }
-    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-  }
-}
-#endif /* MG_ENABLE_SSL */
-
-struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) {
-  struct mg_add_sock_opts opts;
-  struct mg_connection *nc;
-  memset(&opts, 0, sizeof(opts));
-  nc = mg_create_connection(lc->mgr, lc->handler, opts);
-  if (nc == NULL) return NULL;
-  nc->listener = lc;
-  nc->proto_handler = lc->proto_handler;
-  nc->user_data = lc->user_data;
-  nc->recv_mbuf_limit = lc->recv_mbuf_limit;
-  nc->iface = lc->iface;
-  if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL;
-  mg_add_conn(nc->mgr, nc);
-  LOG(LL_DEBUG, ("%p %p %d %#x", (void*)lc, (void*)nc, (int) nc->sock, (int) nc->flags));
-  return nc;
-}
-
-void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
-                         size_t sa_len) {
-  LOG(LL_DEBUG, ("%p %s://%s:%hu", (void*)nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"),
-                 inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
-  nc->sa = *sa;
-#if MG_ENABLE_SSL
-  if (nc->listener->flags & MG_F_SSL) {
-    nc->flags |= MG_F_SSL;
-    if (mg_ssl_if_conn_accept(nc, nc->listener) == MG_SSL_OK) {
-      mg_ssl_handshake(nc);
-    } else {
-      mg_close_conn(nc);
-    }
-  } else
-#endif
-  {
-    mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
-  }
-  (void) sa_len;
-}
-
-void mg_send(struct mg_connection *nc, const void *buf, int len) {
-  nc->last_io_time = (time_t) mg_time();
-  mbuf_append(&nc->send_mbuf, buf, len);
-}
-
-static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len);
-static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len);
-
-static int mg_do_recv(struct mg_connection *nc) {
-  int res = 0;
-  char *buf = NULL;
-  size_t len = (nc->flags & MG_F_UDP ? MG_UDP_IO_SIZE : MG_TCP_IO_SIZE);
-  if ((nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) ||
-      ((nc->flags & MG_F_LISTENING) && !(nc->flags & MG_F_UDP))) {
-    return -1;
-  }
-  do {
-    len = recv_avail_size(nc, len);
-    if (len == 0) {
-      res = -2;
-      break;
-    }
-    if (nc->recv_mbuf.size < nc->recv_mbuf.len + len) {
-      mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.len + len);
-    }
-    buf = nc->recv_mbuf.buf + nc->recv_mbuf.len;
-    len = nc->recv_mbuf.size - nc->recv_mbuf.len;
-    if (nc->flags & MG_F_UDP) {
-      res = mg_recv_udp(nc, buf, len);
-    } else {
-      res = mg_recv_tcp(nc, buf, len);
-    }
-  } while (res > 0 && !(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_UDP)));
-  return res;
-}
-
-void mg_if_can_recv_cb(struct mg_connection *nc) {
-  mg_do_recv(nc);
-}
-
-static int mg_recv_tcp(struct mg_connection *nc, char *buf, size_t len) {
-  int n = 0;
-#if MG_ENABLE_SSL
-  if (nc->flags & MG_F_SSL) {
-    if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
-      n = mg_ssl_if_read(nc, buf, len);
-      DBG(("%p <- %d bytes (SSL)", (void*)nc, n));
-      if (n < 0) {
-        if (n == MG_SSL_WANT_READ) {
-          nc->flags |= MG_F_WANT_READ;
-          n = 0;
-        } else {
-          nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-        }
-      } else if (n > 0) {
-        nc->flags &= ~MG_F_WANT_READ;
-      }
-    } else {
-      mg_ssl_handshake(nc);
-    }
-  } else
-#endif
-  {
-    n = nc->iface->vtable->tcp_recv(nc, buf, len);
-    DBG(("%p <- %d bytes", (void*)nc, n));
-  }
-  if (n > 0) {
-    nc->recv_mbuf.len += n;
-    nc->last_io_time = (time_t) mg_time();
-#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
-    if (nc->mgr && nc->mgr->hexdump_file != NULL) {
-      mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV);
-    }
-#endif
-    mbuf_trim(&nc->recv_mbuf);
-    mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
-  } else if (n < 0) {
-    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-  }
-  mbuf_trim(&nc->recv_mbuf);
-  return n;
-}
-
-static int mg_recv_udp(struct mg_connection *nc, char *buf, size_t len) {
-  int n = 0;
-  struct mg_connection *lc = nc;
-  union socket_address sa;
-  size_t sa_len = sizeof(sa);
-  n = nc->iface->vtable->udp_recv(lc, buf, len, &sa, &sa_len);
-  if (n < 0) {
-    lc->flags |= MG_F_CLOSE_IMMEDIATELY;
-    goto out;
-  }
-  if (nc->flags & MG_F_LISTENING) {
-    /*
-     * Do we have an existing connection for this source?
-     * This is very inefficient for long connection lists.
-     */
-    lc = nc;
-    for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
-      if (memcmp(&nc->sa.sa, &sa.sa, sa_len) == 0 && nc->listener == lc) {
-        break;
-      }
-    }
-    if (nc == NULL) {
-      struct mg_add_sock_opts opts;
-      memset(&opts, 0, sizeof(opts));
-      /* Create fake connection w/out sock initialization */
-      nc = mg_create_connection_base(lc->mgr, lc->handler, opts);
-      if (nc != NULL) {
-        nc->sock = lc->sock;
-        nc->listener = lc;
-        nc->sa = sa;
-        nc->proto_handler = lc->proto_handler;
-        nc->user_data = lc->user_data;
-        nc->recv_mbuf_limit = lc->recv_mbuf_limit;
-        nc->flags = MG_F_UDP;
-        /*
-         * Long-lived UDP "connections" i.e. interactions that involve more
-         * than one request and response are rare, most are transactional:
-         * response is sent and the "connection" is closed. Or - should be.
-         * But users (including ourselves) tend to forget about that part,
-         * because UDP is connectionless and one does not think about
-         * processing a UDP request as handling a connection that needs to be
-         * closed. Thus, we begin with SEND_AND_CLOSE flag set, which should
-         * be a reasonable default for most use cases, but it is possible to
-         * turn it off the connection should be kept alive after processing.
-         */
-        nc->flags |= MG_F_SEND_AND_CLOSE;
-        mg_add_conn(lc->mgr, nc);
-        mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
-      }
-    }
-  }
-  if (nc != NULL) {
-    DBG(("%p <- %d bytes from %s:%d", (void*)nc, n, inet_ntoa(nc->sa.sin.sin_addr),
-         ntohs(nc->sa.sin.sin_port)));
-    if (nc == lc) {
-      nc->recv_mbuf.len += n;
-    } else {
-      mbuf_append(&nc->recv_mbuf, buf, n);
-    }
-    lc->last_io_time = nc->last_io_time = (time_t) mg_time();
-#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
-    if (nc->mgr && nc->mgr->hexdump_file != NULL) {
-      mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_RECV);
-    }
-#endif
-    mbuf_trim(&lc->recv_mbuf);
-    if (n != 0) {
-      mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &n);
-    }
-  }
-
-out:
-  mbuf_free(&lc->recv_mbuf);
-  return n;
-}
-
-void mg_if_can_send_cb(struct mg_connection *nc) {
-  int n = 0;
-  const char *buf = nc->send_mbuf.buf;
-  size_t len = nc->send_mbuf.len;
-
-  if (nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_CONNECTING)) {
-    return;
-  }
-  if (!(nc->flags & MG_F_UDP)) {
-    if (nc->flags & MG_F_LISTENING) return;
-    if (len > MG_TCP_IO_SIZE) len = MG_TCP_IO_SIZE;
-  }
-#if MG_ENABLE_SSL
-  if (nc->flags & MG_F_SSL) {
-    if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
-      if (len > 0) {
-        n = mg_ssl_if_write(nc, buf, len);
-        DBG(("%p -> %d bytes (SSL)", (void*)nc, n));
-      }
-      if (n < 0) {
-        if (n == MG_SSL_WANT_WRITE) {
-          nc->flags |= MG_F_WANT_WRITE;
-          n = 0;
-        } else {
-          nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-        }
-      } else {
-        nc->flags &= ~MG_F_WANT_WRITE;
-      }
-    } else {
-      mg_ssl_handshake(nc);
-    }
-  } else
-#endif
-      if (len > 0) {
-    if (nc->flags & MG_F_UDP) {
-      n = nc->iface->vtable->udp_send(nc, buf, len);
-    } else {
-      n = nc->iface->vtable->tcp_send(nc, buf, len);
-    }
-    DBG(("%p -> %d bytes", (void*)nc, n));
-  }
-
-#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
-  if (n > 0 && nc->mgr && nc->mgr->hexdump_file != NULL) {
-    mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, n, MG_EV_SEND);
-  }
-#endif
-  if (n < 0) {
-    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-  } else if (n > 0) {
-    nc->last_io_time = (time_t) mg_time();
-    mbuf_remove(&nc->send_mbuf, n);
-    mbuf_trim(&nc->send_mbuf);
-  }
-  if (n != 0) mg_call(nc, NULL, nc->user_data, MG_EV_SEND, &n);
-}
-
-/*
- * Schedules an async connect for a resolved address and proto.
- * Called from two places: `mg_connect_opt()` and from async resolver.
- * When called from the async resolver, it must trigger `MG_EV_CONNECT` event
- * with a failure flag to indicate connection failure.
- */
-MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
-                                                int proto,
-                                                union socket_address *sa) {
-  LOG(LL_DEBUG, ("%p %s://%s:%hu", (void*)nc, proto == SOCK_DGRAM ? "udp" : "tcp",
-                 inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
-
-  nc->flags |= MG_F_CONNECTING;
-  if (proto == SOCK_DGRAM) {
-    nc->iface->vtable->connect_udp(nc);
-  } else {
-    nc->iface->vtable->connect_tcp(nc, sa);
-  }
-  mg_add_conn(nc->mgr, nc);
-  return nc;
-}
-
-void mg_if_connect_cb(struct mg_connection *nc, int err) {
-  LOG(LL_DEBUG,
-      ("%p %s://%s:%hu -> %d", (void*)nc, (nc->flags & MG_F_UDP ? "udp" : "tcp"),
-       inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port), err));
-  nc->flags &= ~MG_F_CONNECTING;
-  if (err != 0) {
-    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-  }
-#if MG_ENABLE_SSL
-  if (err == 0 && (nc->flags & MG_F_SSL)) {
-    mg_ssl_handshake(nc);
-  } else
-#endif
-  {
-    mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
-  }
-}
-
-#if MG_ENABLE_ASYNC_RESOLVER
-/*
- * Callback for the async resolver on mg_connect_opt() call.
- * Main task of this function is to trigger MG_EV_CONNECT event with
- *    either failure (and dealloc the connection)
- *    or success (and proceed with connect()
- */
-static void resolve_cb(struct mg_dns_message *msg, void *data,
-                       enum mg_resolve_err e) {
-  struct mg_connection *nc = (struct mg_connection *) data;
-  int i;
-  int failure = -1;
-
-  nc->flags &= ~MG_F_RESOLVING;
-  if (msg != NULL) {
-    /*
-     * Take the first DNS A answer and run...
-     */
-    for (i = 0; i < msg->num_answers; i++) {
-      if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
-        /*
-         * Async resolver guarantees that there is at least one answer.
-         * TODO(lsm): handle IPv6 answers too
-         */
-        mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
-                                 4);
-        mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
-                      &nc->sa);
-        return;
-      }
-    }
-  }
-
-  if (e == MG_RESOLVE_TIMEOUT) {
-    double now = mg_time();
-    mg_call(nc, NULL, nc->user_data, MG_EV_TIMER, &now);
-  }
-
-  /*
-   * If we get there was no MG_DNS_A_RECORD in the answer
-   */
-  mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &failure);
-  mg_call(nc, NULL, nc->user_data, MG_EV_CLOSE, NULL);
-  mg_destroy_conn(nc, 1 /* destroy_if */);
-}
-#endif
-
-struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
-                                 MG_CB(mg_event_handler_t callback,
-                                       void *user_data)) {
-  struct mg_connect_opts opts;
-  memset(&opts, 0, sizeof(opts));
-  return mg_connect_opt(mgr, address, MG_CB(callback, user_data), opts);
-}
-
-void mg_ev_handler_empty(struct mg_connection *c, int ev,
-                         void *ev_data MG_UD_ARG(void *user_data)) {
-  (void) c;
-  (void) ev;
-  (void) ev_data;
-#if MG_ENABLE_CALLBACK_USERDATA
-  (void) user_data;
-#endif
-}
-
-struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
-                                     MG_CB(mg_event_handler_t callback,
-                                           void *user_data),
-                                     struct mg_connect_opts opts) {
-  struct mg_connection *nc = NULL;
-  int proto, rc;
-  struct mg_add_sock_opts add_sock_opts;
-  char host[MG_MAX_HOST_LEN];
-
-  MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
-
-  if (callback == NULL) callback = mg_ev_handler_empty;
-
-  if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
-    return NULL;
-  }
-
-  if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) <
-      0) {
-    /* Address is malformed */
-    MG_SET_PTRPTR(opts.error_string, "cannot parse address");
-    mg_destroy_conn(nc, 1 /* destroy_if */);
-    return NULL;
-  }
-
-  nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
-  nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
-#if MG_ENABLE_CALLBACK_USERDATA
-  nc->user_data = user_data;
-#else
-  nc->user_data = opts.user_data;
-#endif
-
-#if MG_ENABLE_SSL
-  LOG(LL_DEBUG,
-      ("%p %s %s,%s,%s", (void*)nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
-       (opts.ssl_key ? opts.ssl_key : "-"),
-       (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
-
-  if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL ||
-      opts.ssl_psk_identity != NULL) {
-    const char *err_msg = NULL;
-    struct mg_ssl_if_conn_params params;
-    if (nc->flags & MG_F_UDP) {
-      MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
-      mg_destroy_conn(nc, 1 /* destroy_if */);
-      return NULL;
-    }
-    memset(&params, 0, sizeof(params));
-    params.cert = opts.ssl_cert;
-    params.key = opts.ssl_key;
-    params.ca_cert = opts.ssl_ca_cert;
-    params.cipher_suites = opts.ssl_cipher_suites;
-    params.psk_identity = opts.ssl_psk_identity;
-    params.psk_key = opts.ssl_psk_key;
-    if (opts.ssl_ca_cert != NULL) {
-      if (opts.ssl_server_name != NULL) {
-        if (strcmp(opts.ssl_server_name, "*") != 0) {
-          params.server_name = opts.ssl_server_name;
-        }
-      } else if (rc == 0) { /* If it's a DNS name, use host. */
-        params.server_name = host;
-      }
-    }
-    if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
-      MG_SET_PTRPTR(opts.error_string, err_msg);
-      mg_destroy_conn(nc, 1 /* destroy_if */);
-      return NULL;
-    }
-    nc->flags |= MG_F_SSL;
-  }
-#endif /* MG_ENABLE_SSL */
-
-  if (rc == 0) {
-#if MG_ENABLE_ASYNC_RESOLVER
-    /*
-     * DNS resolution is required for host.
-     * mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
-     */
-    struct mg_connection *dns_conn = NULL;
-    struct mg_resolve_async_opts o;
-    memset(&o, 0, sizeof(o));
-    o.dns_conn = &dns_conn;
-    o.nameserver = opts.nameserver;
-    if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc,
-                             o) != 0) {
-      MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
-      mg_destroy_conn(nc, 1 /* destroy_if */);
-      return NULL;
-    }
-    nc->priv_2 = dns_conn;
-    nc->flags |= MG_F_RESOLVING;
-    return nc;
-#else
-    MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
-    mg_destroy_conn(nc, 1 /* destroy_if */);
-    return NULL;
-#endif
-  } else {
-    /* Address is parsed and resolved to IP. proceed with connect() */
-    return mg_do_connect(nc, proto, &nc->sa);
-  }
-}
-
-struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
-                              MG_CB(mg_event_handler_t event_handler,
-                                    void *user_data)) {
-  struct mg_bind_opts opts;
-  memset(&opts, 0, sizeof(opts));
-  return mg_bind_opt(srv, address, MG_CB(event_handler, user_data), opts);
-}
-
-struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
-                                  MG_CB(mg_event_handler_t callback,
-                                        void *user_data),
-                                  struct mg_bind_opts opts) {
-  union socket_address sa;
-  struct mg_connection *nc = NULL;
-  int proto, rc;
-  struct mg_add_sock_opts add_sock_opts;
-  char host[MG_MAX_HOST_LEN];
-
-#if MG_ENABLE_CALLBACK_USERDATA
-  opts.user_data = user_data;
-#endif
-
-  if (callback == NULL) callback = mg_ev_handler_empty;
-
-  MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
-
-  if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
-    MG_SET_PTRPTR(opts.error_string, "cannot parse address");
-    return NULL;
-  }
-
-  nc = mg_create_connection(mgr, callback, add_sock_opts);
-  if (nc == NULL) {
-    return NULL;
-  }
-
-  nc->sa = sa;
-  nc->flags |= MG_F_LISTENING;
-  if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP;
-
-#if MG_ENABLE_SSL
-  DBG(("%p %s %s,%s,%s", (void*)nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
-       (opts.ssl_key ? opts.ssl_key : "-"),
-       (opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
-
-  if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
-    const char *err_msg = NULL;
-    struct mg_ssl_if_conn_params params;
-    if (nc->flags & MG_F_UDP) {
-      MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
-      mg_destroy_conn(nc, 1 /* destroy_if */);
-      return NULL;
-    }
-    memset(&params, 0, sizeof(params));
-    params.cert = opts.ssl_cert;
-    params.key = opts.ssl_key;
-    params.ca_cert = opts.ssl_ca_cert;
-    params.cipher_suites = opts.ssl_cipher_suites;
-    if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
-      MG_SET_PTRPTR(opts.error_string, err_msg);
-      mg_destroy_conn(nc, 1 /* destroy_if */);
-      return NULL;
-    }
-    nc->flags |= MG_F_SSL;
-  }
-#endif /* MG_ENABLE_SSL */
-
-  if (nc->flags & MG_F_UDP) {
-    rc = nc->iface->vtable->listen_udp(nc, &nc->sa);
-  } else {
-    rc = nc->iface->vtable->listen_tcp(nc, &nc->sa);
-  }
-  if (rc != 0) {
-    DBG(("Failed to open listener: %d", rc));
-    MG_SET_PTRPTR(opts.error_string, "failed to open listener");
-    mg_destroy_conn(nc, 1 /* destroy_if */);
-    return NULL;
-  }
-  mg_add_conn(nc->mgr, nc);
-
-  return nc;
-}
-
-struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
-  return conn == NULL ? s->active_connections : conn->next;
-}
-
-#if MG_ENABLE_BROADCAST
-void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
-                  size_t len) {
-  struct ctl_msg ctl_msg;
-
-  /*
-   * Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
-   * where `mg_broadcast()` pushes the message.
-   * `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
-   * specified callback for each connection. Thus the callback function executes
-   * in event manager thread.
-   */
-  if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
-      len < sizeof(ctl_msg.message)) {
-    size_t dummy;
-
-    ctl_msg.callback = cb;
-    memcpy(ctl_msg.message, data, len);
-    dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
-                         offsetof(struct ctl_msg, message) + len, 0);
-    dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
-    (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
-  }
-}
-#endif /* MG_ENABLE_BROADCAST */
-
-static int isbyte(int n) {
-  return n >= 0 && n <= 255;
-}
-
-static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
-  int n, a, b, c, d, slash = 32, len = 0;
-
-  if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
-       sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
-      isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
-      slash < 33) {
-    len = n;
-    *net =
-        ((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
-    *mask = slash ? 0xffffffffU << (32 - slash) : 0;
-  }
-
-  return len;
-}
-
-int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
-  int allowed, flag;
-  uint32_t net, mask;
-  struct mg_str vec;
-
-  /* If any ACL is set, deny by default */
-  allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
-
-  while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
-    flag = vec.p[0];
-    if ((flag != '+' && flag != '-') ||
-        parse_net(&vec.p[1], &net, &mask) == 0) {
-      return -1;
-    }
-
-    if (net == (remote_ip & mask)) {
-      allowed = flag;
-    }
-  }
-
-  DBG(("%08x %c", (unsigned int) remote_ip, allowed));
-  return allowed == '+';
-}
-
-/* Move data from one connection to another */
-void mg_forward(struct mg_connection *from, struct mg_connection *to) {
-  mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
-  mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
-}
-
-double mg_set_timer(struct mg_connection *c, double timestamp) {
-  double result = c->ev_timer_time;
-  c->ev_timer_time = timestamp;
-  /*
-   * If this connection is resolving, it's not in the list of active
-   * connections, so not processed yet. It has a DNS resolver connection
-   * linked to it. Set up a timer for the DNS connection.
-   */
-  DBG(("%p %p %d -> %lu", (void*)c, (void*)c->priv_2, (c->flags & MG_F_RESOLVING ? 1 : 0),
-       (unsigned long) timestamp));
-  if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
-    mg_set_timer((struct mg_connection *) c->priv_2, timestamp);
-  }
-  return result;
-}
-
-void mg_sock_set(struct mg_connection *nc, sock_t sock) {
-  if (sock != INVALID_SOCKET) {
-    nc->iface->vtable->sock_set(nc, sock);
-  }
-}
-
-void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
-                         union socket_address *sa) {
-  nc->iface->vtable->get_conn_addr(nc, remote, sa);
-}
-
-struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
-                                      MG_CB(mg_event_handler_t callback,
-                                            void *user_data),
-                                      struct mg_add_sock_opts opts) {
-#if MG_ENABLE_CALLBACK_USERDATA
-  opts.user_data = user_data;
-#endif
-
-  struct mg_connection *nc = mg_create_connection_base(s, callback, opts);
-  if (nc != NULL) {
-    mg_sock_set(nc, sock);
-    mg_add_conn(nc->mgr, nc);
-  }
-  return nc;
-}
-
-struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
-                                  MG_CB(mg_event_handler_t callback,
-                                        void *user_data)) {
-  struct mg_add_sock_opts opts;
-  memset(&opts, 0, sizeof(opts));
-  return mg_add_sock_opt(s, sock, MG_CB(callback, user_data), opts);
-}
-
-double mg_time(void) {
-  return cs_time();
-}
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_net_if_socket.h"
-#endif
-
-#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
-#define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
-
-/* Amalgamated: #include "mg_net_if.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#ifndef MG_ENABLE_NET_IF_SOCKET
-#define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET
-#endif
-
-extern const struct mg_iface_vtable mg_socket_iface_vtable;
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_net_if_socks.h"
-#endif
-
-#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
-#define CS_MONGOOSE_SRC_NET_IF_SOCKS_H_
-
-#if MG_ENABLE_SOCKS
-/* Amalgamated: #include "mg_net_if.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-extern const struct mg_iface_vtable mg_socks_iface_vtable;
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-#endif /* MG_ENABLE_SOCKS */
-#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKS_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_net_if.c"
-#endif
-/* Amalgamated: #include "mg_net_if.h" */
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_net_if_socket.h" */
-
-extern const struct mg_iface_vtable mg_default_iface_vtable;
-
-const struct mg_iface_vtable *mg_ifaces[] = {
-    &mg_default_iface_vtable,
-};
-
-int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0]));
-
-struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable,
-                                    struct mg_mgr *mgr) {
-  struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface));
-  iface->mgr = mgr;
-  iface->data = NULL;
-  iface->vtable = vtable;
-  return iface;
-}
-
-struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
-                               const struct mg_iface_vtable *vtable,
-                               struct mg_iface *from) {
-  int i = 0;
-  if (from != NULL) {
-    for (i = 0; i < mgr->num_ifaces; i++) {
-      if (mgr->ifaces[i] == from) {
-        i++;
-        break;
-      }
-    }
-  }
-
-  for (; i < mgr->num_ifaces; i++) {
-    if (mgr->ifaces[i]->vtable == vtable) {
-      return mgr->ifaces[i];
-    }
-  }
-  return NULL;
-}
-
-double mg_mgr_min_timer(const struct mg_mgr *mgr) {
-  double min_timer = 0;
-  struct mg_connection *nc;
-  for (nc = mgr->active_connections; nc != NULL; nc = nc->next) {
-    if (nc->ev_timer_time <= 0) continue;
-    if (min_timer == 0 || nc->ev_timer_time < min_timer) {
-      min_timer = nc->ev_timer_time;
-    }
-  }
-  return min_timer;
-}
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_net_if_null.c"
-#endif
-
-static void mg_null_if_connect_tcp(struct mg_connection *c,
-                                   const union socket_address *sa) {
-  c->flags |= MG_F_CLOSE_IMMEDIATELY;
-  (void) sa;
-}
-
-static void mg_null_if_connect_udp(struct mg_connection *c) {
-  c->flags |= MG_F_CLOSE_IMMEDIATELY;
-}
-
-static int mg_null_if_listen_tcp(struct mg_connection *c,
-                                 union socket_address *sa) {
-  (void) c;
-  (void) sa;
-  return -1;
-}
-
-static int mg_null_if_listen_udp(struct mg_connection *c,
-                                 union socket_address *sa) {
-  (void) c;
-  (void) sa;
-  return -1;
-}
-
-static int mg_null_if_tcp_send(struct mg_connection *c, const void *buf,
-                               size_t len) {
-  (void) c;
-  (void) buf;
-  (void) len;
-  return -1;
-}
-
-static int mg_null_if_udp_send(struct mg_connection *c, const void *buf,
-                               size_t len) {
-  (void) c;
-  (void) buf;
-  (void) len;
-  return -1;
-}
-
-int mg_null_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) {
-  (void) c;
-  (void) buf;
-  (void) len;
-  return -1;
-}
-
-int mg_null_if_udp_recv(struct mg_connection *c, void *buf, size_t len,
-                        union socket_address *sa, size_t *sa_len) {
-  (void) c;
-  (void) buf;
-  (void) len;
-  (void) sa;
-  (void) sa_len;
-  return -1;
-}
-
-static int mg_null_if_create_conn(struct mg_connection *c) {
-  (void) c;
-  return 1;
-}
-
-static void mg_null_if_destroy_conn(struct mg_connection *c) {
-  (void) c;
-}
-
-static void mg_null_if_sock_set(struct mg_connection *c, sock_t sock) {
-  (void) c;
-  (void) sock;
-}
-
-static void mg_null_if_init(struct mg_iface *iface) {
-  (void) iface;
-}
-
-static void mg_null_if_free(struct mg_iface *iface) {
-  (void) iface;
-}
-
-static void mg_null_if_add_conn(struct mg_connection *c) {
-  c->sock = INVALID_SOCKET;
-  c->flags |= MG_F_CLOSE_IMMEDIATELY;
-}
-
-static void mg_null_if_remove_conn(struct mg_connection *c) {
-  (void) c;
-}
-
-static time_t mg_null_if_poll(struct mg_iface *iface, int timeout_ms) {
-  struct mg_mgr *mgr = iface->mgr;
-  struct mg_connection *nc, *tmp;
-  double now = mg_time();
-  /* We basically just run timers and poll. */
-  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
-    tmp = nc->next;
-    mg_if_poll(nc, now);
-  }
-  (void) timeout_ms;
-  return (time_t) now;
-}
-
-static void mg_null_if_get_conn_addr(struct mg_connection *c, int remote,
-                                     union socket_address *sa) {
-  (void) c;
-  (void) remote;
-  (void) sa;
-}
-
-#define MG_NULL_IFACE_VTABLE                                                   \
-  {                                                                            \
-    mg_null_if_init, mg_null_if_free, mg_null_if_add_conn,                     \
-        mg_null_if_remove_conn, mg_null_if_poll, mg_null_if_listen_tcp,        \
-        mg_null_if_listen_udp, mg_null_if_connect_tcp, mg_null_if_connect_udp, \
-        mg_null_if_tcp_send, mg_null_if_udp_send, mg_null_if_tcp_recv,         \
-        mg_null_if_udp_recv, mg_null_if_create_conn, mg_null_if_destroy_conn,  \
-        mg_null_if_sock_set, mg_null_if_get_conn_addr,                         \
-  }
-
-const struct mg_iface_vtable mg_null_iface_vtable = MG_NULL_IFACE_VTABLE;
-
-#if MG_NET_IF == MG_NET_IF_NULL
-const struct mg_iface_vtable mg_default_iface_vtable = MG_NULL_IFACE_VTABLE;
-#endif /* MG_NET_IF == MG_NET_IF_NULL */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_net_if_socket.c"
-#endif
-
-#if MG_ENABLE_NET_IF_SOCKET
-
-/* Amalgamated: #include "mg_net_if_socket.h" */
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_util.h" */
-
-static sock_t mg_open_listening_socket(union socket_address *sa, int type,
-                                       int proto);
-
-void mg_set_non_blocking_mode(sock_t sock) {
-#ifdef _WIN32
-  unsigned long on = 1;
-  ioctlsocket(sock, FIONBIO, &on);
-#else
-  int flags = fcntl(sock, F_GETFL, 0);
-  fcntl(sock, F_SETFL, flags | O_NONBLOCK);
-#endif
-}
-
-static int mg_is_error(void) {
-  int err = mg_get_errno();
-  return err != EINPROGRESS && err != EWOULDBLOCK
-#ifndef WINCE
-         && err != EAGAIN && err != EINTR
-#endif
-#ifdef _WIN32
-         && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
-#endif
-      ;
-}
-
-void mg_socket_if_connect_tcp(struct mg_connection *nc,
-                              const union socket_address *sa) {
-  int rc, proto = 0;
-  nc->sock = socket(AF_INET, SOCK_STREAM, proto);
-  if (nc->sock == INVALID_SOCKET) {
-    nc->err = mg_get_errno() ? mg_get_errno() : 1;
-    return;
-  }
-#if !defined(MG_ESP8266)
-  mg_set_non_blocking_mode(nc->sock);
-#endif
-  rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
-  nc->err = rc < 0 && mg_is_error() ? mg_get_errno() : 0;
-  DBG(("%p sock %d rc %d errno %d err %d", (void*)nc, (int) nc->sock, rc,
-      mg_get_errno(), nc->err));
-}
-
-void mg_socket_if_connect_udp(struct mg_connection *nc) {
-  nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
-  if (nc->sock == INVALID_SOCKET) {
-    nc->err = mg_get_errno() ? mg_get_errno() : 1;
-    return;
-  }
-  if (nc->flags & MG_F_ENABLE_BROADCAST) {
-    int optval = 1;
-    if (setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval,
-                   sizeof(optval)) < 0) {
-      nc->err = mg_get_errno() ? mg_get_errno() : 1;
-      return;
-    }
-  }
-  nc->err = 0;
-}
-
-int mg_socket_if_listen_tcp(struct mg_connection *nc,
-                            union socket_address *sa) {
-  int proto = 0;
-  sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
-  if (sock == INVALID_SOCKET) {
-    return (mg_get_errno() ? mg_get_errno() : 1);
-  }
-  mg_sock_set(nc, sock);
-  return 0;
-}
-
-static int mg_socket_if_listen_udp(struct mg_connection *nc,
-                                   union socket_address *sa) {
-  sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
-  if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1);
-  mg_sock_set(nc, sock);
-  return 0;
-}
-
-static int mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf,
-                                 size_t len) {
-  int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0);
-  if (n < 0 && !mg_is_error()) n = 0;
-  return n;
-}
-
-static int mg_socket_if_udp_send(struct mg_connection *nc, const void *buf,
-                                 size_t len) {
-  int n = sendto(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
-  if (n < 0 && !mg_is_error()) n = 0;
-  return n;
-}
-
-static int mg_socket_if_tcp_recv(struct mg_connection *nc, void *buf,
-                                 size_t len) {
-  int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0);
-  if (n == 0) {
-    /* Orderly shutdown of the socket, try flushing output. */
-    nc->flags |= MG_F_SEND_AND_CLOSE;
-  } else if (n < 0 && !mg_is_error()) {
-    n = 0;
-  }
-  return n;
-}
-
-static int mg_socket_if_udp_recv(struct mg_connection *nc, void *buf,
-                                 size_t len, union socket_address *sa,
-                                 size_t *sa_len) {
-  socklen_t sa_len_st = *sa_len;
-  int n = recvfrom(nc->sock, buf, len, 0, &sa->sa, &sa_len_st);
-  *sa_len = sa_len_st;
-  if (n < 0 && !mg_is_error()) n = 0;
-  return n;
-}
-
-int mg_socket_if_create_conn(struct mg_connection *nc) {
-  (void) nc;
-  return 1;
-}
-
-void mg_socket_if_destroy_conn(struct mg_connection *nc) {
-  if (nc->sock == INVALID_SOCKET) return;
-  if (!(nc->flags & MG_F_UDP)) {
-    closesocket(nc->sock);
-  } else {
-    /* Only close outgoing UDP sockets or listeners. */
-    if (nc->listener == NULL) closesocket(nc->sock);
-  }
-  nc->sock = INVALID_SOCKET;
-}
-
-static int mg_accept_conn(struct mg_connection *lc) {
-  struct mg_connection *nc;
-  union socket_address sa;
-  socklen_t sa_len = sizeof(sa);
-  /* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
-  sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
-  if (sock == INVALID_SOCKET) {
-    if (mg_is_error()) {
-      DBG(("%p: failed to accept: %d", (void*)lc, mg_get_errno()));
-    }
-    return 0;
-  }
-  nc = mg_if_accept_new_conn(lc);
-  if (nc == NULL) {
-    closesocket(sock);
-    return 0;
-  }
-  DBG(("%p conn from %s:%d", (void*)nc, inet_ntoa(sa.sin.sin_addr),
-       ntohs(sa.sin.sin_port)));
-  mg_sock_set(nc, sock);
-  mg_if_accept_tcp_cb(nc, &sa, sa_len);
-  return 1;
-}
-
-/* 'sa' must be an initialized address to bind to */
-static sock_t mg_open_listening_socket(union socket_address *sa, int type,
-                                       int proto) {
-  socklen_t sa_len =
-      (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
-  sock_t sock = INVALID_SOCKET;
-#if !MG_LWIP
-  int on = 1;
-#endif
-
-  if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET &&
-#if !MG_LWIP /* LWIP doesn't support either */
-#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE)
-      /* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
-      !setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
-                  sizeof(on)) &&
-#endif
-
-#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
-      /*
-       * SO_RESUSEADDR is not enabled on Windows because the semantics of
-       * SO_REUSEADDR on UNIX and Windows is different. On Windows,
-       * SO_REUSEADDR allows to bind a socket to a port without error even if
-       * the port is already open by another program. This is not the behavior
-       * SO_REUSEADDR was designed for, and leads to hard-to-track failure
-       * scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
-       * SO_EXCLUSIVEADDRUSE is supported and set on a socket.
-       */
-      !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
-#endif
-#endif /* !MG_LWIP */
-
-      !bind(sock, &sa->sa, sa_len) &&
-      (type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
-#if !MG_LWIP
-    mg_set_non_blocking_mode(sock);
-    /* In case port was set to 0, get the real port number */
-    (void) getsockname(sock, &sa->sa, &sa_len);
-#endif
-  } else if (sock != INVALID_SOCKET) {
-    closesocket(sock);
-    sock = INVALID_SOCKET;
-  }
-
-  return sock;
-}
-
-#define _MG_F_FD_CAN_READ 1
-#define _MG_F_FD_CAN_WRITE 1 << 1
-#define _MG_F_FD_ERROR 1 << 2
-
-void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
-  int worth_logging =
-      fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE));
-  if (worth_logging) {
-    DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", (void*)nc,
-         (int) nc->sock, fd_flags, nc->flags, (int) nc->recv_mbuf.len,
-         (int) nc->send_mbuf.len));
-  }
-
-  if (!mg_if_poll(nc, now)) return;
-
-  if (nc->flags & MG_F_CONNECTING) {
-    if (fd_flags != 0) {
-      int err = 0;
-#if !defined(MG_ESP8266)
-      if (!(nc->flags & MG_F_UDP)) {
-        socklen_t len = sizeof(err);
-        int ret =
-            getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
-        if (ret != 0) {
-          err = 1;
-        } else if (err == EAGAIN || err == EWOULDBLOCK) {
-          err = 0;
-        }
-      }
-#else
-      /*
-       * On ESP8266 we use blocking connect.
-       */
-      err = nc->err;
-#endif
-      mg_if_connect_cb(nc, err);
-    } else if (nc->err != 0) {
-      mg_if_connect_cb(nc, nc->err);
-    }
-  }
-
-  if (fd_flags & _MG_F_FD_CAN_READ) {
-    if (nc->flags & MG_F_UDP) {
-      mg_if_can_recv_cb(nc);
-    } else {
-      if (nc->flags & MG_F_LISTENING) {
-        /*
-         * We're not looping here, and accepting just one connection at
-         * a time. The reason is that eCos does not respect non-blocking
-         * flag on a listening socket and hangs in a loop.
-         */
-        mg_accept_conn(nc);
-      } else {
-        mg_if_can_recv_cb(nc);
-      }
-    }
-  }
-
-  if (fd_flags & _MG_F_FD_CAN_WRITE) mg_if_can_send_cb(nc);
-
-  if (worth_logging) {
-    DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", (void*)nc, (int) nc->sock,
-         nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
-  }
-}
-
-#if MG_ENABLE_BROADCAST
-static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
-  struct ctl_msg ctl_msg;
-  int len = (int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
-  size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
-  DBG(("read %d from ctl socket", len));
-  (void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
-  if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
-    struct mg_connection *nc;
-    for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
-      ctl_msg.callback(nc, MG_EV_POLL,
-                       ctl_msg.message MG_UD_ARG(nc->user_data));
-    }
-  }
-}
-#endif
-
-/* Associate a socket to a connection. */
-void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) {
-  mg_set_non_blocking_mode(sock);
-  mg_set_close_on_exec(sock);
-  nc->sock = sock;
-  DBG(("%p %d", (void*)nc, (int) sock));
-}
-
-void mg_socket_if_init(struct mg_iface *iface) {
-  (void) iface;
-  DBG(("%p using select()", (void*)iface->mgr));
-#if MG_ENABLE_BROADCAST
-  mg_socketpair(iface->mgr->ctl, SOCK_DGRAM);
-#endif
-}
-
-void mg_socket_if_free(struct mg_iface *iface) {
-  (void) iface;
-}
-
-void mg_socket_if_add_conn(struct mg_connection *nc) {
-  (void) nc;
-}
-
-void mg_socket_if_remove_conn(struct mg_connection *nc) {
-  (void) nc;
-}
-
-void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
-  if (sock != INVALID_SOCKET
-#ifdef __unix__
-      && sock < (sock_t) FD_SETSIZE
-#endif
-      ) {
-    FD_SET(sock, set);
-    if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
-      *max_fd = sock;
-    }
-  }
-}
-
-time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) {
-  struct mg_mgr *mgr = iface->mgr;
-  double now = mg_time();
-  double min_timer;
-  struct mg_connection *nc, *tmp;
-  struct timeval tv;
-  fd_set read_set, write_set, err_set;
-  sock_t max_fd = INVALID_SOCKET;
-  int num_fds, num_ev, num_timers = 0;
-#ifdef __unix__
-  int try_dup = 1;
-#endif
-
-  FD_ZERO(&read_set);
-  FD_ZERO(&write_set);
-  FD_ZERO(&err_set);
-#if MG_ENABLE_BROADCAST
-  mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
-#endif
-
-  /*
-   * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
-   * e.g. timer-only "connections".
-   */
-  min_timer = 0;
-  for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
-    tmp = nc->next;
-
-    if (nc->sock != INVALID_SOCKET) {
-      num_fds++;
-
-#ifdef __unix__
-      /* A hack to make sure all our file descriptos fit into FD_SETSIZE. */
-      if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) {
-        int new_sock = dup(nc->sock);
-        if (new_sock >= 0) {
-          if (new_sock < (sock_t) FD_SETSIZE) {
-            closesocket(nc->sock);
-            DBG(("new sock %d -> %d", nc->sock, new_sock));
-            nc->sock = new_sock;
-          } else {
-            closesocket(new_sock);
-            DBG(("new sock is still larger than FD_SETSIZE, disregard"));
-            try_dup = 0;
-          }
-        } else {
-          try_dup = 0;
-        }
-      }
-#endif
-
-      if (nc->recv_mbuf.len < nc->recv_mbuf_limit &&
-          (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
-        mg_add_to_set(nc->sock, &read_set, &max_fd);
-      }
-
-      if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
-          (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
-        mg_add_to_set(nc->sock, &write_set, &max_fd);
-        mg_add_to_set(nc->sock, &err_set, &max_fd);
-      }
-    }
-
-    if (nc->ev_timer_time > 0) {
-      if (num_timers == 0 || nc->ev_timer_time < min_timer) {
-        min_timer = nc->ev_timer_time;
-      }
-      num_timers++;
-    }
-  }
-
-  /*
-   * If there is a timer to be fired earlier than the requested timeout,
-   * adjust the timeout.
-   */
-  if (num_timers > 0) {
-    double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
-    if (timer_timeout_ms < timeout_ms) {
-      timeout_ms = (int) timer_timeout_ms;
-    }
-  }
-  if (timeout_ms < 0) timeout_ms = 0;
-
-  tv.tv_sec = timeout_ms / 1000;
-  tv.tv_usec = (timeout_ms % 1000) * 1000;
-
-  num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
-  now = mg_time();
-#if 0
-  DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds,
-       timeout_ms));
-#endif
-
-#if MG_ENABLE_BROADCAST
-  if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET &&
-      FD_ISSET(mgr->ctl[1], &read_set)) {
-    mg_mgr_handle_ctl_sock(mgr);
-  }
-#endif
-
-  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
-    int fd_flags = 0;
-    if (nc->sock != INVALID_SOCKET) {
-      if (num_ev > 0) {
-        fd_flags = (FD_ISSET(nc->sock, &read_set) &&
-                            (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
-                        ? _MG_F_FD_CAN_READ
-                        : 0) |
-                   (FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
-                   (FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
-      }
-#if MG_LWIP
-      /* With LWIP socket emulation layer, we don't get write events for UDP */
-      if ((nc->flags & MG_F_UDP) && nc->listener == NULL) {
-        fd_flags |= _MG_F_FD_CAN_WRITE;
-      }
-#endif
-    }
-    tmp = nc->next;
-    mg_mgr_handle_conn(nc, fd_flags, now);
-  }
-
-  return (time_t) now;
-}
-
-#if MG_ENABLE_BROADCAST
-MG_INTERNAL void mg_socketpair_close(sock_t *sock) {
-  while (1) {
-    if (closesocket(*sock) == -1 && errno == EINTR) continue;
-    break;
-  }
-  *sock = INVALID_SOCKET;
-}
-
-MG_INTERNAL sock_t
-mg_socketpair_accept(sock_t sock, union socket_address *sa, socklen_t sa_len) {
-  sock_t rc;
-  while (1) {
-    if ((rc = accept(sock, &sa->sa, &sa_len)) == INVALID_SOCKET &&
-        errno == EINTR)
-      continue;
-    break;
-  }
-  return rc;
-}
-
-int mg_socketpair(sock_t sp[2], int sock_type) {
-  union socket_address sa, sa2;
-  sock_t sock;
-  socklen_t len = sizeof(sa.sin);
-  int ret = 0;
-
-  sock = sp[0] = sp[1] = INVALID_SOCKET;
-
-  (void) memset(&sa, 0, sizeof(sa));
-  sa.sin.sin_family = AF_INET;
-  sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
-  sa2 = sa;
-
-  if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
-  } else if (bind(sock, &sa.sa, len) != 0) {
-  } else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
-  } else if (getsockname(sock, &sa.sa, &len) != 0) {
-  } else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
-  } else if (sock_type == SOCK_STREAM && connect(sp[0], &sa.sa, len) != 0) {
-  } else if (sock_type == SOCK_DGRAM &&
-             (bind(sp[0], &sa2.sa, len) != 0 ||
-              getsockname(sp[0], &sa2.sa, &len) != 0 ||
-              connect(sp[0], &sa.sa, len) != 0 ||
-              connect(sock, &sa2.sa, len) != 0)) {
-  } else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock : mg_socketpair_accept(
-                                                            sock, &sa, len))) ==
-             INVALID_SOCKET) {
-  } else {
-    mg_set_close_on_exec(sp[0]);
-    mg_set_close_on_exec(sp[1]);
-    if (sock_type == SOCK_STREAM) mg_socketpair_close(&sock);
-    ret = 1;
-  }
-
-  if (!ret) {
-    if (sp[0] != INVALID_SOCKET) mg_socketpair_close(&sp[0]);
-    if (sp[1] != INVALID_SOCKET) mg_socketpair_close(&sp[1]);
-    if (sock != INVALID_SOCKET) mg_socketpair_close(&sock);
-  }
-
-  return ret;
-}
-#endif /* MG_ENABLE_BROADCAST */
-
-static void mg_sock_get_addr(sock_t sock, int remote,
-                             union socket_address *sa) {
-  socklen_t slen = sizeof(*sa);
-  memset(sa, 0, slen);
-  if (remote) {
-    getpeername(sock, &sa->sa, &slen);
-  } else {
-    getsockname(sock, &sa->sa, &slen);
-  }
-}
-
-void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
-  union socket_address sa;
-  mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
-  mg_sock_addr_to_str(&sa, buf, len, flags);
-}
-
-void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote,
-                                union socket_address *sa) {
-  if ((nc->flags & MG_F_UDP) && remote) {
-    memcpy(sa, &nc->sa, sizeof(*sa));
-    return;
-  }
-  mg_sock_get_addr(nc->sock, remote, sa);
-}
-
-/* clang-format off */
-#define MG_SOCKET_IFACE_VTABLE                                          \
-  {                                                                     \
-    mg_socket_if_init,                                                  \
-    mg_socket_if_free,                                                  \
-    mg_socket_if_add_conn,                                              \
-    mg_socket_if_remove_conn,                                           \
-    mg_socket_if_poll,                                                  \
-    mg_socket_if_listen_tcp,                                            \
-    mg_socket_if_listen_udp,                                            \
-    mg_socket_if_connect_tcp,                                           \
-    mg_socket_if_connect_udp,                                           \
-    mg_socket_if_tcp_send,                                              \
-    mg_socket_if_udp_send,                                              \
-    mg_socket_if_tcp_recv,                                              \
-    mg_socket_if_udp_recv,                                              \
-    mg_socket_if_create_conn,                                           \
-    mg_socket_if_destroy_conn,                                          \
-    mg_socket_if_sock_set,                                              \
-    mg_socket_if_get_conn_addr,                                         \
-  }
-/* clang-format on */
-
-const struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE;
-#if MG_NET_IF == MG_NET_IF_SOCKET
-const struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE;
-#endif
-
-#endif /* MG_ENABLE_NET_IF_SOCKET */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_net_if_socks.c"
-#endif
-
-#if MG_ENABLE_SOCKS
-
-struct socksdata {
-  char *proxy_addr;        /* HOST:PORT of the socks5 proxy server */
-  struct mg_connection *s; /* Respective connection to the server */
-  struct mg_connection *c; /* Connection to the client */
-};
-
-static void socks_if_disband(struct socksdata *d) {
-  LOG(LL_DEBUG, ("disbanding proxy %p %p", (void*)d->c, (void*)d->s));
-  if (d->c) {
-    d->c->flags |= MG_F_SEND_AND_CLOSE;
-    d->c->user_data = NULL;
-    d->c = NULL;
-  }
-  if (d->s) {
-    d->s->flags |= MG_F_SEND_AND_CLOSE;
-    d->s->user_data = NULL;
-    d->s = NULL;
-  }
-}
-
-static void socks_if_relay(struct mg_connection *s) {
-  struct socksdata *d = (struct socksdata *) s->user_data;
-  if (d == NULL || d->c == NULL || !(s->flags & MG_SOCKS_CONNECT_DONE) ||
-      d->s == NULL) {
-    return;
-  }
-  if (s->recv_mbuf.len > 0) mg_if_can_recv_cb(d->c);
-  if (d->c->send_mbuf.len > 0 && s->send_mbuf.len == 0) mg_if_can_send_cb(d->c);
-}
-
-static void socks_if_handler(struct mg_connection *c, int ev, void *ev_data) {
-  struct socksdata *d = (struct socksdata *) c->user_data;
-  if (d == NULL) return;
-  if (ev == MG_EV_CONNECT) {
-    int res = *(int *) ev_data;
-    if (res == 0) {
-      /* Send handshake to the proxy server */
-      unsigned char buf[] = {MG_SOCKS_VERSION, 1, MG_SOCKS_HANDSHAKE_NOAUTH};
-      mg_send(d->s, buf, sizeof(buf));
-      LOG(LL_DEBUG, ("Sent handshake to %s", d->proxy_addr));
-    } else {
-      LOG(LL_ERROR, ("Cannot connect to %s: %d", d->proxy_addr, res));
-      d->c->flags |= MG_F_CLOSE_IMMEDIATELY;
-    }
-  } else if (ev == MG_EV_CLOSE) {
-    socks_if_disband(d);
-  } else if (ev == MG_EV_RECV) {
-    /* Handle handshake reply */
-    if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) {
-      /* TODO(lsm): process IPv6 too */
-      unsigned char buf[10] = {MG_SOCKS_VERSION, MG_SOCKS_CMD_CONNECT, 0,
-                               MG_SOCKS_ADDR_IPV4};
-      if (c->recv_mbuf.len < 2) return;
-      if ((unsigned char) c->recv_mbuf.buf[1] == MG_SOCKS_HANDSHAKE_FAILURE) {
-        LOG(LL_ERROR, ("Server kicked us out"));
-        socks_if_disband(d);
-        return;
-      }
-      mbuf_remove(&c->recv_mbuf, 2);
-      c->flags |= MG_SOCKS_HANDSHAKE_DONE;
-
-      /* Send connect request */
-      memcpy(buf + 4, &d->c->sa.sin.sin_addr, 4);
-      memcpy(buf + 8, &d->c->sa.sin.sin_port, 2);
-      mg_send(c, buf, sizeof(buf));
-      LOG(LL_DEBUG, ("%p Sent connect request", (void*)c));
-    }
-    /* Process connect request */
-    if ((c->flags & MG_SOCKS_HANDSHAKE_DONE) &&
-        !(c->flags & MG_SOCKS_CONNECT_DONE)) {
-      if (c->recv_mbuf.len < 10) return;
-      if (c->recv_mbuf.buf[1] != MG_SOCKS_SUCCESS) {
-        LOG(LL_ERROR, ("Socks connection error: %d", c->recv_mbuf.buf[1]));
-        socks_if_disband(d);
-        return;
-      }
-      mbuf_remove(&c->recv_mbuf, 10);
-      c->flags |= MG_SOCKS_CONNECT_DONE;
-      LOG(LL_DEBUG, ("%p Connect done %p", (void*)c, (void*)d->c));
-      mg_if_connect_cb(d->c, 0);
-    }
-    socks_if_relay(c);
-  } else if (ev == MG_EV_SEND || ev == MG_EV_POLL) {
-    socks_if_relay(c);
-  }
-}
-
-static void mg_socks_if_connect_tcp(struct mg_connection *c,
-                                    const union socket_address *sa) {
-  struct socksdata *d = (struct socksdata *) c->iface->data;
-  d->c = c;
-  d->s = mg_connect(c->mgr, d->proxy_addr, socks_if_handler);
-  d->s->user_data = d;
-  LOG(LL_DEBUG, ("%p %s %p %p", (void*)c, d->proxy_addr, (void*)d, (void*)d->s));
-  (void) sa;
-}
-
-static void mg_socks_if_connect_udp(struct mg_connection *c) {
-  (void) c;
-}
-
-static int mg_socks_if_listen_tcp(struct mg_connection *c,
-                                  union socket_address *sa) {
-  (void) c;
-  (void) sa;
-  return 0;
-}
-
-static int mg_socks_if_listen_udp(struct mg_connection *c,
-                                  union socket_address *sa) {
-  (void) c;
-  (void) sa;
-  return -1;
-}
-
-static int mg_socks_if_tcp_send(struct mg_connection *c, const void *buf,
-                                size_t len) {
-  int res;
-  struct socksdata *d = (struct socksdata *) c->iface->data;
-  if (d->s == NULL) return -1;
-  res = (int) mbuf_append(&d->s->send_mbuf, buf, len);
-  DBG(("%p -> %d -> %p", (void*)c, res, (void*)d->s));
-  return res;
-}
-
-static int mg_socks_if_udp_send(struct mg_connection *c, const void *buf,
-                                size_t len) {
-  (void) c;
-  (void) buf;
-  (void) len;
-  return -1;
-}
-
-int mg_socks_if_tcp_recv(struct mg_connection *c, void *buf, size_t len) {
-  struct socksdata *d = (struct socksdata *) c->iface->data;
-  if (d->s == NULL) return -1;
-  if (len > d->s->recv_mbuf.len) len = d->s->recv_mbuf.len;
-  if (len > 0) {
-    memcpy(buf, d->s->recv_mbuf.buf, len);
-    mbuf_remove(&d->s->recv_mbuf, len);
-  }
-  DBG(("%p <- %d <- %p", (void*)c, (int) len, (void*)d->s));
-  return len;
-}
-
-int mg_socks_if_udp_recv(struct mg_connection *c, void *buf, size_t len,
-                         union socket_address *sa, size_t *sa_len) {
-  (void) c;
-  (void) buf;
-  (void) len;
-  (void) sa;
-  (void) sa_len;
-  return -1;
-}
-
-static int mg_socks_if_create_conn(struct mg_connection *c) {
-  (void) c;
-  return 1;
-}
-
-static void mg_socks_if_destroy_conn(struct mg_connection *c) {
-  c->iface->vtable->free(c->iface);
-  MG_FREE(c->iface);
-  c->iface = NULL;
-  LOG(LL_DEBUG, ("%p", (void*)c));
-}
-
-static void mg_socks_if_sock_set(struct mg_connection *c, sock_t sock) {
-  (void) c;
-  (void) sock;
-}
-
-static void mg_socks_if_init(struct mg_iface *iface) {
-  (void) iface;
-}
-
-static void mg_socks_if_free(struct mg_iface *iface) {
-  struct socksdata *d = (struct socksdata *) iface->data;
-  LOG(LL_DEBUG, ("%p", (void*)iface));
-  if (d != NULL) {
-    socks_if_disband(d);
-    MG_FREE(d->proxy_addr);
-    MG_FREE(d);
-    iface->data = NULL;
-  }
-}
-
-static void mg_socks_if_add_conn(struct mg_connection *c) {
-  c->sock = INVALID_SOCKET;
-}
-
-static void mg_socks_if_remove_conn(struct mg_connection *c) {
-  (void) c;
-}
-
-static time_t mg_socks_if_poll(struct mg_iface *iface, int timeout_ms) {
-  LOG(LL_DEBUG, ("%p", (void*)iface));
-  (void) iface;
-  (void) timeout_ms;
-  return (time_t) cs_time();
-}
-
-static void mg_socks_if_get_conn_addr(struct mg_connection *c, int remote,
-                                      union socket_address *sa) {
-  LOG(LL_DEBUG, ("%p", (void*)c));
-  (void) c;
-  (void) remote;
-  (void) sa;
-}
-
-const struct mg_iface_vtable mg_socks_iface_vtable = {
-    mg_socks_if_init,          mg_socks_if_free,
-    mg_socks_if_add_conn,      mg_socks_if_remove_conn,
-    mg_socks_if_poll,          mg_socks_if_listen_tcp,
-    mg_socks_if_listen_udp,    mg_socks_if_connect_tcp,
-    mg_socks_if_connect_udp,   mg_socks_if_tcp_send,
-    mg_socks_if_udp_send,      mg_socks_if_tcp_recv,
-    mg_socks_if_udp_recv,      mg_socks_if_create_conn,
-    mg_socks_if_destroy_conn,  mg_socks_if_sock_set,
-    mg_socks_if_get_conn_addr,
-};
-
-struct mg_iface *mg_socks_mk_iface(struct mg_mgr *mgr, const char *proxy_addr) {
-  struct mg_iface *iface = mg_if_create_iface(&mg_socks_iface_vtable, mgr);
-  iface->data = MG_CALLOC(1, sizeof(struct socksdata));
-  ((struct socksdata *) iface->data)->proxy_addr = strdup(proxy_addr);
-  return iface;
-}
-
-#endif
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_ssl_if_openssl.c"
-#endif
-
-#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL
-
-#ifdef __APPLE__
-#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
-#endif
-
-#include <openssl/ssl.h>
-#include <openssl/err.h>
-#ifndef KR_VERSION
-#include <openssl/tls1.h>
-#endif
-
-static const char *mg_default_session_id_context = "mongoose";
-
-struct mg_ssl_if_ctx {
-  SSL *ssl;
-  SSL_CTX *ssl_ctx;
-  struct mbuf psk;
-  size_t identity_len;
-};
-
-void mg_ssl_if_init(void) {
-  SSL_library_init();
-}
-
-enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
-                                            struct mg_connection *lc) {
-  struct mg_ssl_if_ctx *ctx =
-      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
-  struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
-  nc->ssl_if_data = ctx;
-  if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
-  ctx->ssl_ctx = lc_ctx->ssl_ctx;
-  if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
-    return MG_SSL_ERROR;
-  }
-  return MG_SSL_OK;
-}
-
-static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
-                                         const char *key, const char **err_msg);
-static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert);
-static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl);
-static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
-                                                    const char *identity,
-                                                    const char *key_str);
-
-enum mg_ssl_if_result mg_ssl_if_conn_init(
-    struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
-    const char **err_msg) {
-  struct mg_ssl_if_ctx *ctx =
-      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
-  DBG(("%p %s,%s,%s", (void*)nc, (params->cert ? params->cert : ""),
-       (params->key ? params->key : ""),
-       (params->ca_cert ? params->ca_cert : "")));
-  if (ctx == NULL) {
-    MG_SET_PTRPTR(err_msg, "Out of memory");
-    return MG_SSL_ERROR;
-  }
-  nc->ssl_if_data = ctx;
-  if (nc->flags & MG_F_LISTENING) {
-    ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
-  } else {
-    ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
-  }
-  if (ctx->ssl_ctx == NULL) {
-    MG_SET_PTRPTR(err_msg, "Failed to create SSL context");
-    return MG_SSL_ERROR;
-  }
-
-#ifndef KR_VERSION
-  /* Disable deprecated protocols. */
-  SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv2);
-  SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_SSLv3);
-  SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_TLSv1);
-  SSL_CTX_set_session_id_context(
-      ctx->ssl_ctx,
-      (const unsigned char *) mg_default_session_id_context,
-      strlen(mg_default_session_id_context));
-#ifdef MG_SSL_OPENSSL_NO_COMPRESSION
-  SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_NO_COMPRESSION);
-#endif
-#ifdef MG_SSL_OPENSSL_CIPHER_SERVER_PREFERENCE
-  SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
-#endif
-#else
-/* Krypton only supports TLSv1.2 anyway. */
-#endif
-
-  if (params->cert != NULL &&
-      mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) !=
-          MG_SSL_OK) {
-    return MG_SSL_ERROR;
-  }
-
-  if (params->ca_cert != NULL &&
-      mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) {
-    MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
-    return MG_SSL_ERROR;
-  }
-
-  if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) {
-    MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
-    return MG_SSL_ERROR;
-  }
-
-  mbuf_init(&ctx->psk, 0);
-  if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) !=
-      MG_SSL_OK) {
-    MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
-    return MG_SSL_ERROR;
-  }
-
-  if (!(nc->flags & MG_F_LISTENING) &&
-      (ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
-    MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
-    return MG_SSL_ERROR;
-  }
-
-  if (params->server_name != NULL) {
-#ifdef KR_VERSION
-    SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name);
-#else
-    SSL_set_tlsext_host_name(ctx->ssl, params->server_name);
-#endif
-  }
-
-  nc->flags |= MG_F_SSL;
-
-  return MG_SSL_OK;
-}
-
-static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc,
-                                               int res) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  int err = SSL_get_error(ctx->ssl, res);
-  /*
-   * We've just fetched the last error from the queue.
-   * Now we need to clear the error queue. If we do not, then the following
-   * can happen (actually reported):
-   *  - A new connection is accept()-ed with cert error (e.g. self-signed cert)
-   *  - Since all accept()-ed connections share listener's context,
-   *  - *ALL* SSL accepted connection report read error on the next poll cycle.
-   *    Thus a single errored connection can close all the rest, unrelated ones.
-   * Clearing the error keeps the shared SSL_CTX in an OK state.
-   */
-  ERR_clear_error();
-  if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ;
-  if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE;
-  DBG(("%p %p SSL error: %d %d", (void*)nc, (void*)ctx->ssl_ctx, res, err));
-  nc->err = err;
-  return MG_SSL_ERROR;
-}
-
-enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  int server_side = (nc->listener != NULL);
-  int res;
-  /* If descriptor is not yet set, do it now. */
-  if (SSL_get_fd(ctx->ssl) < 0) {
-    if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR;
-  }
-  res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl);
-  if (res != 1) return mg_ssl_if_ssl_err(nc, res);
-  return MG_SSL_OK;
-}
-
-int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  int n = SSL_read(ctx->ssl, buf, buf_size);
-  DBG(("%p %d -> %d", (void*)nc, (int) buf_size, n));
-  if (n < 0) return mg_ssl_if_ssl_err(nc, n);
-  if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-  return n;
-}
-
-int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  int n = SSL_write(ctx->ssl, data, len);
-  DBG(("%p %d -> %d", (void*)nc, (int) len, n));
-  if (n <= 0) return mg_ssl_if_ssl_err(nc, n);
-  return n;
-}
-
-void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  if (ctx == NULL) return;
-  SSL_shutdown(ctx->ssl);
-}
-
-void mg_ssl_if_conn_free(struct mg_connection *nc) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  if (ctx == NULL) return;
-  nc->ssl_if_data = NULL;
-  if (ctx->ssl != NULL) SSL_free(ctx->ssl);
-  if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx);
-  mbuf_free(&ctx->psk);
-  memset(ctx, 0, sizeof(*ctx));
-  MG_FREE(ctx);
-}
-
-/*
- * Cipher suite options used for TLS negotiation.
- * https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
- */
-static const char mg_s_cipher_list[] =
-#if defined(MG_SSL_CRYPTO_MODERN)
-    "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
-    "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
-    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
-    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
-    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
-    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
-    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
-    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
-    "!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
-#elif defined(MG_SSL_CRYPTO_OLD)
-    "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
-    "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
-    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
-    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
-    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
-    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
-    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
-    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
-    "ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
-    "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
-    "HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
-    "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
-#else /* Default - intermediate. */
-    "ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
-    "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
-    "DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
-    "ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
-    "ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
-    "ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
-    "DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
-    "DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
-    "AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
-    "DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
-    "!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
-#endif
-    ;
-
-/*
- * Default DH params for PFS cipher negotiation. This is a 2048-bit group.
- * Will be used if none are provided by the user in the certificate file.
- */
-#if !MG_DISABLE_PFS && !defined(KR_VERSION)
-static const char mg_s_default_dh_params[] =
-    "\
------BEGIN DH PARAMETERS-----\n\
-MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
-Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
-+E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
-ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
-wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
-9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
------END DH PARAMETERS-----\n";
-#endif
-
-static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
-  if (cert == NULL || strcmp(cert, "*") == 0) {
-    return MG_SSL_OK;
-  }
-  SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
-  return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK
-                                                             : MG_SSL_ERROR;
-}
-
-static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
-                                         const char *key,
-                                         const char **err_msg) {
-  if (key == NULL) key = cert;
-  if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
-    return MG_SSL_OK;
-  } else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) {
-    MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
-    return MG_SSL_ERROR;
-  } else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) {
-    MG_SET_PTRPTR(err_msg, "Invalid SSL key");
-    return MG_SSL_ERROR;
-  } else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) {
-    MG_SET_PTRPTR(err_msg, "Invalid CA bundle");
-    return MG_SSL_ERROR;
-  } else {
-    SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
-#if !MG_DISABLE_PFS && !defined(KR_VERSION)
-    BIO *bio = NULL;
-    DH *dh = NULL;
-
-    /* Try to read DH parameters from the cert/key file. */
-    bio = BIO_new_file(cert, "r");
-    if (bio != NULL) {
-      dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
-      BIO_free(bio);
-    }
-    /*
-     * If there are no DH params in the file, fall back to hard-coded ones.
-     * Not ideal, but better than nothing.
-     */
-    if (dh == NULL) {
-      bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
-      dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
-      BIO_free(bio);
-    }
-    if (dh != NULL) {
-      SSL_CTX_set_tmp_dh(ctx, dh);
-      SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
-      DH_free(dh);
-    }
-#if OPENSSL_VERSION_NUMBER > 0x10002000L
-    SSL_CTX_set_ecdh_auto(ctx, 1);
-#endif
-#endif
-  }
-  return MG_SSL_OK;
-}
-
-static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) {
-  return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1
-              ? MG_SSL_OK
-              : MG_SSL_ERROR);
-}
-
-#if !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER)
-static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint,
-                                          char *identity,
-                                          unsigned int max_identity_len,
-                                          unsigned char *psk,
-                                          unsigned int max_psk_len) {
-  struct mg_ssl_if_ctx *ctx =
-      (struct mg_ssl_if_ctx *) SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl));
-  size_t key_len = ctx->psk.len - ctx->identity_len - 1;
-  DBG(("hint: '%s'", (hint ? hint : "")));
-  if (ctx->identity_len + 1 > max_identity_len) {
-    DBG(("identity too long"));
-    return 0;
-  }
-  if (key_len > max_psk_len) {
-    DBG(("key too long"));
-    return 0;
-  }
-  memcpy(identity, ctx->psk.buf, ctx->identity_len + 1);
-  memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len);
-  (void) ssl;
-  return key_len;
-}
-
-static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
-                                                    const char *identity,
-                                                    const char *key_str) {
-  unsigned char key[32];
-  size_t key_len;
-  size_t i = 0;
-  if (identity == NULL && key_str == NULL) return MG_SSL_OK;
-  if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
-  key_len = strlen(key_str);
-  if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
-  memset(key, 0, sizeof(key));
-  key_len = 0;
-  for (i = 0; key_str[i] != '\0'; i++) {
-    unsigned char c;
-    char hc = tolower((int) key_str[i]);
-    if (hc >= '0' && hc <= '9') {
-      c = hc - '0';
-    } else if (hc >= 'a' && hc <= 'f') {
-      c = hc - 'a' + 0xa;
-    } else {
-      return MG_SSL_ERROR;
-    }
-    key_len = i / 2;
-    key[key_len] <<= 4;
-    key[key_len] |= c;
-  }
-  key_len++;
-  DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
-  ctx->identity_len = strlen(identity);
-  mbuf_append(&ctx->psk, identity, ctx->identity_len + 1);
-  mbuf_append(&ctx->psk, key, key_len);
-  SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb);
-  SSL_CTX_set_app_data(ctx->ssl_ctx, ctx);
-  return MG_SSL_OK;
-}
-#else
-static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
-                                                    const char *identity,
-                                                    const char *key_str) {
-  (void) ctx;
-  (void) identity;
-  (void) key_str;
-  /* Krypton / LibreSSL does not support PSK. */
-  return MG_SSL_ERROR;
-}
-#endif /* !defined(KR_VERSION) && !defined(LIBRESSL_VERSION_NUMBER) */
-
-const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
-                       const char *ca_cert) {
-  const char *err_msg = NULL;
-  struct mg_ssl_if_conn_params params;
-  memset(&params, 0, sizeof(params));
-  params.cert = cert;
-  params.ca_cert = ca_cert;
-  if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
-    return err_msg;
-  }
-  return NULL;
-}
-
-#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_ssl_if_mbedtls.c"
-#endif
-
-#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS
-
-#include <mbedtls/debug.h>
-#include <mbedtls/ecp.h>
-#include <mbedtls/net.h>
-#include <mbedtls/platform.h>
-#include <mbedtls/ssl.h>
-#include <mbedtls/ssl_internal.h>
-#include <mbedtls/x509_crt.h>
-#include <mbedtls/version.h>
-
-static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line,
-                            const char *str) {
-  enum cs_log_level cs_level;
-  switch (level) {
-    case 1:
-      cs_level = LL_ERROR;
-      break;
-    case 2:
-      cs_level = LL_INFO;
-      break;
-    case 3:
-      cs_level = LL_DEBUG;
-      break;
-    default:
-      cs_level = LL_VERBOSE_DEBUG;
-  }
-  /* mbedTLS passes strings with \n at the end, strip it. */
-  LOG(cs_level, ("%p %.*s", (void*)ctx, (int) (strlen(str) - 1), str));
-  (void) ctx;
-  (void) str;
-  (void) file;
-  (void) line;
-  (void) cs_level;
-}
-
-struct mg_ssl_if_ctx {
-  mbedtls_ssl_config *conf;
-  mbedtls_ssl_context *ssl;
-  mbedtls_x509_crt *cert;
-  mbedtls_pk_context *key;
-#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
-  char *ca_chain_file;
-#else
-  mbedtls_x509_crt *ca_cert;
-#endif
-  struct mbuf cipher_suites;
-  size_t saved_len;
-};
-
-/* Must be provided by the platform. ctx is struct mg_connection. */
-extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len);
-
-void mg_ssl_if_init(void) {
-  LOG(LL_INFO, ("%s", MBEDTLS_VERSION_STRING_FULL));
-}
-
-enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
-                                            struct mg_connection *lc) {
-  struct mg_ssl_if_ctx *ctx =
-      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
-  struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
-  nc->ssl_if_data = ctx;
-  if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
-  ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
-  if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) {
-    return MG_SSL_ERROR;
-  }
-  return MG_SSL_OK;
-}
-
-static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
-                                         const char *cert, const char *key,
-                                         const char **err_msg);
-static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
-                                            const char *cert);
-static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
-                                                const char *ciphers);
-#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
-static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
-                                                    const char *identity,
-                                                    const char *key);
-#endif
-
-enum mg_ssl_if_result mg_ssl_if_conn_init(
-    struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
-    const char **err_msg) {
-  struct mg_ssl_if_ctx *ctx =
-      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
-  DBG(("%p %s,%s,%s", (void*)nc, (params->cert ? params->cert : ""),
-       (params->key ? params->key : ""),
-       (params->ca_cert ? params->ca_cert : "")));
-
-  if (ctx == NULL) {
-    MG_SET_PTRPTR(err_msg, "Out of memory");
-    return MG_SSL_ERROR;
-  }
-  nc->ssl_if_data = ctx;
-  ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf));
-  mbuf_init(&ctx->cipher_suites, 0);
-  mbedtls_ssl_config_init(ctx->conf);
-  mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc);
-  if (mbedtls_ssl_config_defaults(
-          ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER
-                                                 : MBEDTLS_SSL_IS_CLIENT),
-          MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) {
-    MG_SET_PTRPTR(err_msg, "Failed to init SSL config");
-    return MG_SSL_ERROR;
-  }
-
-  /* TLS 1.2 and up */
-  mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
-                               MBEDTLS_SSL_MINOR_VERSION_3);
-  mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc);
-
-  if (params->cert != NULL &&
-      mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) {
-    return MG_SSL_ERROR;
-  }
-
-  if (params->ca_cert != NULL &&
-      mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) {
-    MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
-    return MG_SSL_ERROR;
-  }
-
-  if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) {
-    MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
-    return MG_SSL_ERROR;
-  }
-
-#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
-  if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) !=
-      MG_SSL_OK) {
-    MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
-    return MG_SSL_ERROR;
-  }
-#endif
-
-  if (!(nc->flags & MG_F_LISTENING)) {
-    ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
-    mbedtls_ssl_init(ctx->ssl);
-    if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) {
-      MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
-      return MG_SSL_ERROR;
-    }
-    if (params->server_name != NULL &&
-        mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) {
-      return MG_SSL_ERROR;
-    }
-  }
-
-#ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
-  if (mbedtls_ssl_conf_max_frag_len(ctx->conf,
-#if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512
-                                    MBEDTLS_SSL_MAX_FRAG_LEN_512
-#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024
-                                    MBEDTLS_SSL_MAX_FRAG_LEN_1024
-#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048
-                                    MBEDTLS_SSL_MAX_FRAG_LEN_2048
-#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096
-                                    MBEDTLS_SSL_MAX_FRAG_LEN_4096
-#else
-#error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
-#endif
-                                    ) != 0) {
-    return MG_SSL_ERROR;
-  }
-#endif
-
-  nc->flags |= MG_F_SSL;
-
-  return MG_SSL_OK;
-}
-
-static int mg_ssl_if_mbed_send(void *ctx, const unsigned char *buf,
-                               size_t len) {
-  struct mg_connection *nc = (struct mg_connection *) ctx;
-  int n = nc->iface->vtable->tcp_send(nc, buf, len);
-  if (n > 0) return n;
-  if (n == 0) return MBEDTLS_ERR_SSL_WANT_WRITE;
-  return MBEDTLS_ERR_NET_SEND_FAILED;
-}
-
-static int mg_ssl_if_mbed_recv(void *ctx, unsigned char *buf, size_t len) {
-  struct mg_connection *nc = (struct mg_connection *) ctx;
-  int n = nc->iface->vtable->tcp_recv(nc, buf, len);
-  if (n > 0) return n;
-  if (n == 0) return MBEDTLS_ERR_SSL_WANT_READ;
-  return MBEDTLS_ERR_NET_RECV_FAILED;
-}
-
-static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc,
-                                                int ret) {
-  enum mg_ssl_if_result res = MG_SSL_OK;
-  if (ret == MBEDTLS_ERR_SSL_WANT_READ) {
-    res = MG_SSL_WANT_READ;
-  } else if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) {
-    res = MG_SSL_WANT_WRITE;
-  } else if (ret == MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) {
-    LOG(LL_DEBUG, ("%p TLS connection closed by peer", (void*)nc));
-    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-    res = MG_SSL_OK;
-  } else {
-    LOG(LL_ERROR, ("%p mbedTLS error: -0x%04x", (void*)nc, -ret));
-    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-    res = MG_SSL_ERROR;
-  }
-  nc->err = ret;
-  return res;
-}
-
-static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) {
-  if (ctx->cert != NULL) {
-    mbedtls_x509_crt_free(ctx->cert);
-    MG_FREE(ctx->cert);
-    ctx->cert = NULL;
-    mbedtls_pk_free(ctx->key);
-    MG_FREE(ctx->key);
-    ctx->key = NULL;
-  }
-#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
-  MG_FREE(ctx->ca_chain_file);
-  ctx->ca_chain_file = NULL;
-#else
-  if (ctx->ca_cert != NULL) {
-    mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
-    mbedtls_x509_crt_free(ctx->ca_cert);
-    MG_FREE(ctx->ca_cert);
-    ctx->ca_cert = NULL;
-  }
-#endif
-}
-
-enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  int err;
-  /* If bio is not yet set, do it now. */
-  if (ctx->ssl->p_bio == NULL) {
-    mbedtls_ssl_set_bio(ctx->ssl, nc, mg_ssl_if_mbed_send, mg_ssl_if_mbed_recv,
-                        NULL);
-  }
-  err = mbedtls_ssl_handshake(ctx->ssl);
-  if (err != 0) return mg_ssl_if_mbed_err(nc, err);
-#ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS
-  /*
-   * Free the peer certificate, we don't need it after handshake.
-   * Note that this effectively disables renegotiation.
-   */
-  mbedtls_x509_crt_free(ctx->ssl->session->peer_cert);
-  mbedtls_free(ctx->ssl->session->peer_cert);
-  ctx->ssl->session->peer_cert = NULL;
-  /* On a client connection we can also free our own and CA certs. */
-  if (nc->listener == NULL) {
-    if (ctx->conf->key_cert != NULL) {
-      /* Note that this assumes one key_cert entry, which matches our init. */
-      MG_FREE(ctx->conf->key_cert);
-      ctx->conf->key_cert = NULL;
-    }
-    mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
-    mg_ssl_if_mbed_free_certs_and_keys(ctx);
-  }
-#endif
-  return MG_SSL_OK;
-}
-
-int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, len);
-  DBG(("%p %d -> %d", (void*)nc, (int) len, n));
-  if (n < 0) return mg_ssl_if_mbed_err(nc, n);
-  if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-  return n;
-}
-
-int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  /* Per mbedTLS docs, if write returns WANT_READ or WANT_WRITE, the operation
-   * should be retried with the same data and length.
-   * Here we assume that the data being pushed will remain the same but the
-   * amount may grow between calls so we save the length that was used and
-   * retry. The assumption being that the data itself won't change and won't
-   * be removed. */
-  size_t l = len;
-  if (ctx->saved_len > 0 && ctx->saved_len < l) l = ctx->saved_len;
-  int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) buf, l);
-  DBG(("%p %d,%d,%d -> %d", (void*)nc, (int) len, (int) ctx->saved_len, (int) l, n));
-  if (n < 0) {
-    if (n == MBEDTLS_ERR_SSL_WANT_READ || n == MBEDTLS_ERR_SSL_WANT_WRITE) {
-      ctx->saved_len = len;
-    }
-    return mg_ssl_if_mbed_err(nc, n);
-  } else if (n > 0) {
-    ctx->saved_len = 0;
-  }
-  return n;
-}
-
-void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  if (ctx == NULL) return;
-  mbedtls_ssl_close_notify(ctx->ssl);
-}
-
-void mg_ssl_if_conn_free(struct mg_connection *nc) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  if (ctx == NULL) return;
-  nc->ssl_if_data = NULL;
-  if (ctx->ssl != NULL) {
-    mbedtls_ssl_free(ctx->ssl);
-    MG_FREE(ctx->ssl);
-  }
-  if (ctx->conf != NULL) {
-    mbedtls_ssl_config_free(ctx->conf);
-    MG_FREE(ctx->conf);
-  }
-  mg_ssl_if_mbed_free_certs_and_keys(ctx);
-  mbuf_free(&ctx->cipher_suites);
-  memset(ctx, 0, sizeof(*ctx));
-  MG_FREE(ctx);
-}
-
-static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
-                                            const char *ca_cert) {
-  if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) {
-    mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_NONE);
-    return MG_SSL_OK;
-  }
-#ifdef MBEDTLS_X509_CA_CHAIN_ON_DISK
-  ctx->ca_chain_file = strdup(ca_cert);
-  if (ctx->ca_chain_file == NULL) return MG_SSL_ERROR;
-  if (mbedtls_ssl_conf_ca_chain_file(ctx->conf, ctx->ca_chain_file, NULL) != 0) {
-    return MG_SSL_ERROR;
-  }
-#else
-  ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert));
-  mbedtls_x509_crt_init(ctx->ca_cert);
-  if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) {
-    return MG_SSL_ERROR;
-  }
-  mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL);
-#endif
-  mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
-  return MG_SSL_OK;
-}
-
-static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
-                                         const char *cert, const char *key,
-                                         const char **err_msg) {
-  if (key == NULL) key = cert;
-  if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
-    return MG_SSL_OK;
-  }
-  ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert));
-  mbedtls_x509_crt_init(ctx->cert);
-  ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key));
-  mbedtls_pk_init(ctx->key);
-  if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) {
-    MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
-    return MG_SSL_ERROR;
-  }
-  if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) {
-    MG_SET_PTRPTR(err_msg, "Invalid SSL key");
-    return MG_SSL_ERROR;
-  }
-  if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) {
-    MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert");
-    return MG_SSL_ERROR;
-  }
-  return MG_SSL_OK;
-}
-
-static const int mg_s_cipher_list[] = {
-#if CS_PLATFORM != CS_P_ESP8266
-    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
-    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
-    MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
-#else
-    /*
-     * ECDHE is way too slow on ESP8266 w/o cryptochip, this sometimes results
-     * in WiFi STA deauths. Use weaker but faster cipher suites. Sad but true.
-     * Disable DHE completely because it's just hopelessly slow.
-     */
-    MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
-    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
-    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
-    MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
-    MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA,
-#endif /* CS_PLATFORM != CS_P_ESP8266 */
-    0,
-};
-
-/*
- * Ciphers can be specified as a colon-separated list of cipher suite names.
- * These can be found in
- * https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267
- * E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM
- */
-static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
-                                                const char *ciphers) {
-  if (ciphers != NULL) {
-    int l, id;
-    const char *s = ciphers, *e;
-    char tmp[50];
-    while (s != NULL) {
-      e = strchr(s, ':');
-      l = (e != NULL ? (e - s) : (int) strlen(s));
-      strncpy(tmp, s, l);
-      tmp[l] = '\0';
-      id = mbedtls_ssl_get_ciphersuite_id(tmp);
-      DBG(("%s -> %04x", tmp, id));
-      if (id != 0) {
-        mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
-      }
-      s = (e != NULL ? e + 1 : NULL);
-    }
-    if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR;
-    id = 0;
-    mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
-    mbuf_trim(&ctx->cipher_suites);
-    mbedtls_ssl_conf_ciphersuites(ctx->conf,
-                                  (const int *) ctx->cipher_suites.buf);
-  } else {
-    mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list);
-  }
-  return MG_SSL_OK;
-}
-
-#ifdef MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED
-static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
-                                                    const char *identity,
-                                                    const char *key_str) {
-  unsigned char key[32];
-  size_t key_len;
-  if (identity == NULL && key_str == NULL) return MG_SSL_OK;
-  if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
-  key_len = strlen(key_str);
-  if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
-  size_t i = 0;
-  memset(key, 0, sizeof(key));
-  key_len = 0;
-  for (i = 0; key_str[i] != '\0'; i++) {
-    unsigned char c;
-    char hc = tolower((int) key_str[i]);
-    if (hc >= '0' && hc <= '9') {
-      c = hc - '0';
-    } else if (hc >= 'a' && hc <= 'f') {
-      c = hc - 'a' + 0xa;
-    } else {
-      return MG_SSL_ERROR;
-    }
-    key_len = i / 2;
-    key[key_len] <<= 4;
-    key[key_len] |= c;
-  }
-  key_len++;
-  DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
-  /* mbedTLS makes copies of psk and identity. */
-  if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len,
-                           (const unsigned char *) identity,
-                           strlen(identity)) != 0) {
-    return MG_SSL_ERROR;
-  }
-  return MG_SSL_OK;
-}
-#endif
-
-const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
-                       const char *ca_cert) {
-  const char *err_msg = NULL;
-  struct mg_ssl_if_conn_params params;
-  memset(&params, 0, sizeof(params));
-  params.cert = cert;
-  params.ca_cert = ca_cert;
-  if (mg_ssl_if_conn_init(nc, &params, &err_msg) != MG_SSL_OK) {
-    return err_msg;
-  }
-  return NULL;
-}
-
-/* Lazy RNG. Warning: it would be a bad idea to do this in production! */
-#ifdef MG_SSL_MBED_DUMMY_RANDOM
-int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) {
-  (void) ctx;
-  while (len--) *buf++ = rand();
-  return 0;
-}
-#endif
-
-#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_uri.c"
-#endif
-
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_uri.h" */
-
-/*
- * scan string until encountering one of `seps`, keeping track of component
- * boundaries in `res`.
- *
- * `p` will point to the char after the separator or it will be `end`.
- */
-static void parse_uri_component(const char **p, const char *end,
-                                const char *seps, struct mg_str *res) {
-  const char *q;
-  res->p = *p;
-  for (; *p < end; (*p)++) {
-    for (q = seps; *q != '\0'; q++) {
-      if (**p == *q) break;
-    }
-    if (*q != '\0') break;
-  }
-  res->len = (*p) - res->p;
-  if (*p < end) (*p)++;
-}
-
-int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme,
-                 struct mg_str *user_info, struct mg_str *host,
-                 unsigned int *port, struct mg_str *path, struct mg_str *query,
-                 struct mg_str *fragment) {
-  struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
-                rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
-  unsigned int rport = 0;
-  enum {
-    P_START,
-    P_SCHEME_OR_PORT,
-    P_USER_INFO,
-    P_HOST,
-    P_PORT,
-    P_REST
-  } state = P_START;
-
-  const char *p = uri.p, *end = p + uri.len;
-  while (p < end) {
-    switch (state) {
-      case P_START:
-        /*
-         * expecting on of:
-         * - `scheme://xxxx`
-         * - `xxxx:port`
-         * - `[a:b:c]:port`
-         * - `xxxx/path`
-         */
-        if (*p == '[') {
-          state = P_HOST;
-          break;
-        }
-        for (; p < end; p++) {
-          if (*p == ':') {
-            state = P_SCHEME_OR_PORT;
-            break;
-          } else if (*p == '/') {
-            state = P_REST;
-            break;
-          }
-        }
-        if (state == P_START || state == P_REST) {
-          rhost.p = uri.p;
-          rhost.len = p - uri.p;
-        }
-        break;
-      case P_SCHEME_OR_PORT:
-        if (end - p >= 3 && strncmp(p, "://", 3) == 0) {
-          rscheme.p = uri.p;
-          rscheme.len = p - uri.p;
-          state = P_USER_INFO;
-          p += 3;
-        } else {
-          rhost.p = uri.p;
-          rhost.len = p - uri.p;
-          state = P_PORT;
-        }
-        break;
-      case P_USER_INFO:
-        ruser_info.p = p;
-        for (; p < end; p++) {
-          if (*p == '@' || *p == '[' || *p == '/') {
-            break;
-          }
-        }
-        if (p == end || *p == '/' || *p == '[') {
-          /* backtrack and parse as host */
-          p = ruser_info.p;
-        }
-        ruser_info.len = p - ruser_info.p;
-        state = P_HOST;
-        break;
-      case P_HOST:
-        if (*p == '@') p++;
-        rhost.p = p;
-        if (*p == '[') {
-          int found = 0;
-          for (; !found && p < end; p++) {
-            found = (*p == ']');
-          }
-          if (!found) return -1;
-        } else {
-          for (; p < end; p++) {
-            if (*p == ':' || *p == '/') break;
-          }
-        }
-        rhost.len = p - rhost.p;
-        if (p < end) {
-          if (*p == ':') {
-            state = P_PORT;
-            break;
-          } else if (*p == '/') {
-            state = P_REST;
-            break;
-          }
-        }
-        break;
-      case P_PORT:
-        p++;
-        for (; p < end; p++) {
-          if (*p == '/') {
-            state = P_REST;
-            break;
-          }
-          rport *= 10;
-          rport += *p - '0';
-        }
-        break;
-      case P_REST:
-        /* `p` points to separator. `path` includes the separator */
-        parse_uri_component(&p, end, "?#", &rpath);
-        if (p < end && *(p - 1) == '?') {
-          parse_uri_component(&p, end, "#", &rquery);
-        }
-        parse_uri_component(&p, end, "", &rfragment);
-        break;
-    }
-  }
-
-  if (scheme != 0) *scheme = rscheme;
-  if (user_info != 0) *user_info = ruser_info;
-  if (host != 0) *host = rhost;
-  if (port != 0) *port = rport;
-  if (path != 0) *path = rpath;
-  if (query != 0) *query = rquery;
-  if (fragment != 0) *fragment = rfragment;
-
-  return 0;
-}
-
-/* Normalize the URI path. Remove/resolve "." and "..". */
-int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) {
-  const char *s = in->p, *se = s + in->len;
-  char *cp = (char *) out->p, *d;
-
-  if (in->len == 0 || *s != '/') {
-    out->len = 0;
-    return 0;
-  }
-
-  d = cp;
-
-  while (s < se) {
-    const char *next = s;
-    struct mg_str component;
-    parse_uri_component(&next, se, "/", &component);
-    if (mg_vcmp(&component, ".") == 0) {
-      /* Yum. */
-    } else if (mg_vcmp(&component, "..") == 0) {
-      /* Backtrack to previous slash. */
-      if (d > cp + 1 && *(d - 1) == '/') d--;
-      while (d > cp && *(d - 1) != '/') d--;
-    } else {
-      memmove(d, s, next - s);
-      d += next - s;
-    }
-    s = next;
-  }
-  if (d == cp) *d++ = '/';
-
-  out->p = cp;
-  out->len = d - cp;
-  return 1;
-}
-
-int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info,
-                    const struct mg_str *host, unsigned int port,
-                    const struct mg_str *path, const struct mg_str *query,
-                    const struct mg_str *fragment, int normalize_path,
-                    struct mg_str *uri) {
-  int result = -1;
-  struct mbuf out;
-  mbuf_init(&out, 0);
-
-  if (scheme != NULL && scheme->len > 0) {
-    mbuf_append(&out, scheme->p, scheme->len);
-    mbuf_append(&out, "://", 3);
-  }
-
-  if (user_info != NULL && user_info->len > 0) {
-    mbuf_append(&out, user_info->p, user_info->len);
-    mbuf_append(&out, "@", 1);
-  }
-
-  if (host != NULL && host->len > 0) {
-    mbuf_append(&out, host->p, host->len);
-  }
-
-  if (port != 0) {
-    char port_str[20];
-    int port_str_len = sprintf(port_str, ":%u", port);
-    mbuf_append(&out, port_str, port_str_len);
-  }
-
-  if (path != NULL && path->len > 0) {
-    if (normalize_path) {
-      struct mg_str npath = mg_strdup(*path);
-      if (npath.len != path->len) goto out;
-      if (!mg_normalize_uri_path(path, &npath)) {
-        free((void *) npath.p);
-        goto out;
-      }
-      mbuf_append(&out, npath.p, npath.len);
-      free((void *) npath.p);
-    } else {
-      mbuf_append(&out, path->p, path->len);
-    }
-  } else if (normalize_path) {
-    mbuf_append(&out, "/", 1);
-  }
-
-  if (query != NULL && query->len > 0) {
-    mbuf_append(&out, "?", 1);
-    mbuf_append(&out, query->p, query->len);
-  }
-
-  if (fragment != NULL && fragment->len > 0) {
-    mbuf_append(&out, "#", 1);
-    mbuf_append(&out, fragment->p, fragment->len);
-  }
-
-  result = 0;
-
-out:
-  if (result == 0) {
-    uri->p = out.buf;
-    uri->len = out.len;
-  } else {
-    mbuf_free(&out);
-    uri->p = NULL;
-    uri->len = 0;
-  }
-  return result;
-}
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_http.c"
-#endif
-
-#if MG_ENABLE_HTTP
-
-/* Amalgamated: #include "common/cs_md5.h" */
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_util.h" */
-
-/* altbuf {{{ */
-
-/*
- * Alternate buffer: fills the client-provided buffer with data; and if it's
- * not large enough, allocates another buffer (via mbuf), similar to asprintf.
- */
-struct altbuf {
-  struct mbuf m;
-  char *user_buf;
-  size_t len;
-  size_t user_buf_size;
-};
-
-/*
- * Initializes altbuf; `buf`, `buf_size` is the client-provided buffer.
- */
-MG_INTERNAL void altbuf_init(struct altbuf *ab, char *buf, size_t buf_size) {
-  mbuf_init(&ab->m, 0);
-  ab->user_buf = buf;
-  ab->user_buf_size = buf_size;
-  ab->len = 0;
-}
-
-/*
- * Appends a single char to the altbuf.
- */
-MG_INTERNAL void altbuf_append(struct altbuf *ab, char c) {
-  if (ab->len < ab->user_buf_size) {
-    /* The data fits into the original buffer */
-    ab->user_buf[ab->len++] = c;
-  } else {
-    /* The data can't fit into the original buffer, so write it to mbuf.  */
-
-    /*
-     * First of all, see if that's the first byte which overflows the original
-     * buffer: if so, copy the existing data from there to a newly allocated
-     * mbuf.
-     */
-    if (ab->len > 0 && ab->m.len == 0) {
-      mbuf_append(&ab->m, ab->user_buf, ab->len);
-    }
-
-    mbuf_append(&ab->m, &c, 1);
-    ab->len = ab->m.len;
-  }
-}
-
-/*
- * Resets any data previously appended to altbuf.
- */
-MG_INTERNAL void altbuf_reset(struct altbuf *ab) {
-  mbuf_free(&ab->m);
-  ab->len = 0;
-}
-
-/*
- * Returns whether the additional buffer was allocated (and thus the data
- * is in the mbuf, not the client-provided buffer)
- */
-MG_INTERNAL int altbuf_reallocated(struct altbuf *ab) {
-  return ab->len > ab->user_buf_size;
-}
-
-/*
- * Returns the actual buffer with data, either the client-provided or a newly
- * allocated one. If `trim` is non-zero, mbuf-backed buffer is trimmed first.
- */
-MG_INTERNAL char *altbuf_get_buf(struct altbuf *ab, int trim) {
-  if (altbuf_reallocated(ab)) {
-    if (trim) {
-      mbuf_trim(&ab->m);
-    }
-    return ab->m.buf;
-  } else {
-    return ab->user_buf;
-  }
-}
-
-/* }}} */
-
-static const char *mg_version_header = "Mongoose/" MG_VERSION;
-
-enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT };
-
-struct mg_http_proto_data_file {
-  FILE *fp;      /* Opened file. */
-  int64_t cl;    /* Content-Length. How many bytes to send. */
-  int64_t sent;  /* How many bytes have been already sent. */
-  int keepalive; /* Keep connection open after sending. */
-  enum mg_http_proto_data_type type;
-};
-
-#if MG_ENABLE_HTTP_CGI
-struct mg_http_proto_data_cgi {
-  struct mg_connection *cgi_nc;
-};
-#endif
-
-struct mg_http_proto_data_chuncked {
-  int64_t body_len; /* How many bytes of chunked body was reassembled. */
-};
-
-struct mg_http_endpoint {
-  struct mg_http_endpoint *next;
-  struct mg_str uri_pattern; /* owned */
-  char *auth_domain;         /* owned */
-  char *auth_file;           /* owned */
-
-  mg_event_handler_t handler;
-#if MG_ENABLE_CALLBACK_USERDATA
-  void *user_data;
-#endif
-};
-
-enum mg_http_multipart_stream_state {
-  MPS_BEGIN,
-  MPS_WAITING_FOR_BOUNDARY,
-  MPS_WAITING_FOR_CHUNK,
-  MPS_GOT_BOUNDARY,
-  MPS_FINALIZE,
-  MPS_FINISHED
-};
-
-struct mg_http_multipart_stream {
-  const char *boundary;
-  int boundary_len;
-  const char *var_name;
-  const char *file_name;
-  void *user_data;
-  enum mg_http_multipart_stream_state state;
-  int processing_part;
-  int data_avail;
-};
-
-struct mg_reverse_proxy_data {
-  struct mg_connection *linked_conn;
-};
-
-struct mg_ws_proto_data {
-  /*
-   * Defragmented size of the frame so far.
-   *
-   * First byte of nc->recv_mbuf.buf is an op, the rest of the data is
-   * defragmented data.
-   */
-  size_t reass_len;
-};
-
-struct mg_http_proto_data {
-#if MG_ENABLE_FILESYSTEM
-  struct mg_http_proto_data_file file;
-#endif
-#if MG_ENABLE_HTTP_CGI
-  struct mg_http_proto_data_cgi cgi;
-#endif
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-  struct mg_http_multipart_stream mp_stream;
-#endif
-#if MG_ENABLE_HTTP_WEBSOCKET
-  struct mg_ws_proto_data ws_data;
-#endif
-  struct mg_http_proto_data_chuncked chunk;
-  struct mg_http_endpoint *endpoints;
-  mg_event_handler_t endpoint_handler;
-  struct mg_reverse_proxy_data reverse_proxy_data;
-  size_t rcvd;           /* How many bytes we have received. */
-  size_t body_rcvd;      /* How many bytes of body we have received. */
-  size_t body_processed; /* How many bytes of body we have processed. */
-  int finished;
-};
-
-static void mg_http_proto_data_destructor(void *proto_data);
-
-struct mg_connection *mg_connect_http_base(
-    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
-    struct mg_connect_opts opts, const char *scheme1, const char *scheme2,
-    const char *scheme_ssl1, const char *scheme_ssl2, const char *url,
-    struct mg_str *path, struct mg_str *user_info, struct mg_str *host);
-
-MG_INTERNAL struct mg_http_proto_data *mg_http_create_proto_data(
-    struct mg_connection *c) {
-  /* If we have proto data from previous connection, flush it. */
-  if (c->proto_data != NULL) {
-    void *pd = c->proto_data;
-    c->proto_data = NULL;
-    mg_http_proto_data_destructor(pd);
-  }
-  c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
-  c->proto_data_destructor = mg_http_proto_data_destructor;
-  return (struct mg_http_proto_data *) c->proto_data;
-}
-
-static struct mg_http_proto_data *mg_http_get_proto_data(
-    struct mg_connection *c) {
-  return (struct mg_http_proto_data *) c->proto_data;
-}
-
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-static void mg_http_free_proto_data_mp_stream(
-    struct mg_http_multipart_stream *mp) {
-  MG_FREE((void *) mp->boundary);
-  MG_FREE((void *) mp->var_name);
-  MG_FREE((void *) mp->file_name);
-  memset(mp, 0, sizeof(*mp));
-}
-#endif
-
-#if MG_ENABLE_FILESYSTEM
-static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) {
-  if (d != NULL) {
-    if (d->fp != NULL) {
-      fclose(d->fp);
-    }
-    memset(d, 0, sizeof(struct mg_http_proto_data_file));
-  }
-}
-#endif
-
-static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) {
-  struct mg_http_endpoint *current = *ep;
-
-  while (current != NULL) {
-    struct mg_http_endpoint *tmp = current->next;
-    MG_FREE((void *) current->uri_pattern.p);
-    MG_FREE((void *) current->auth_domain);
-    MG_FREE((void *) current->auth_file);
-    MG_FREE(current);
-    current = tmp;
-  }
-
-  *ep = NULL;
-}
-
-static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) {
-  if (rpd->linked_conn != NULL) {
-    /*
-     * Connection has linked one, we have to unlink & close it
-     * since _this_ connection is going to die and
-     * it doesn't make sense to keep another one
-     */
-    struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn);
-    if (pd->reverse_proxy_data.linked_conn != NULL) {
-      pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
-      pd->reverse_proxy_data.linked_conn = NULL;
-    }
-    rpd->linked_conn = NULL;
-  }
-}
-
-static void mg_http_proto_data_destructor(void *proto_data) {
-  struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data;
-#if MG_ENABLE_FILESYSTEM
-  mg_http_free_proto_data_file(&pd->file);
-#endif
-#if MG_ENABLE_HTTP_CGI
-  mg_http_free_proto_data_cgi(&pd->cgi);
-#endif
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-  mg_http_free_proto_data_mp_stream(&pd->mp_stream);
-#endif
-  mg_http_free_proto_data_endpoints(&pd->endpoints);
-  mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data);
-  MG_FREE(proto_data);
-}
-
-#if MG_ENABLE_FILESYSTEM
-
-#define MIME_ENTRY(_ext, _type) \
-  { _ext, sizeof(_ext) - 1, _type }
-static const struct {
-  const char *extension;
-  size_t ext_len;
-  const char *mime_type;
-} mg_static_builtin_mime_types[] = {
-    MIME_ENTRY("html", "text/html"),
-    MIME_ENTRY("html", "text/html"),
-    MIME_ENTRY("htm", "text/html"),
-    MIME_ENTRY("shtm", "text/html"),
-    MIME_ENTRY("shtml", "text/html"),
-    MIME_ENTRY("css", "text/css"),
-    MIME_ENTRY("js", "application/x-javascript"),
-    MIME_ENTRY("ico", "image/x-icon"),
-    MIME_ENTRY("gif", "image/gif"),
-    MIME_ENTRY("jpg", "image/jpeg"),
-    MIME_ENTRY("jpeg", "image/jpeg"),
-    MIME_ENTRY("png", "image/png"),
-    MIME_ENTRY("svg", "image/svg+xml"),
-    MIME_ENTRY("txt", "text/plain"),
-    MIME_ENTRY("torrent", "application/x-bittorrent"),
-    MIME_ENTRY("wav", "audio/x-wav"),
-    MIME_ENTRY("mp3", "audio/x-mp3"),
-    MIME_ENTRY("mid", "audio/mid"),
-    MIME_ENTRY("m3u", "audio/x-mpegurl"),
-    MIME_ENTRY("ogg", "application/ogg"),
-    MIME_ENTRY("ram", "audio/x-pn-realaudio"),
-    MIME_ENTRY("xml", "text/xml"),
-    MIME_ENTRY("ttf", "application/x-font-ttf"),
-    MIME_ENTRY("json", "application/json"),
-    MIME_ENTRY("xslt", "application/xml"),
-    MIME_ENTRY("xsl", "application/xml"),
-    MIME_ENTRY("ra", "audio/x-pn-realaudio"),
-    MIME_ENTRY("doc", "application/msword"),
-    MIME_ENTRY("exe", "application/octet-stream"),
-    MIME_ENTRY("zip", "application/x-zip-compressed"),
-    MIME_ENTRY("xls", "application/excel"),
-    MIME_ENTRY("tgz", "application/x-tar-gz"),
-    MIME_ENTRY("tar", "application/x-tar"),
-    MIME_ENTRY("gz", "application/x-gunzip"),
-    MIME_ENTRY("arj", "application/x-arj-compressed"),
-    MIME_ENTRY("rar", "application/x-rar-compressed"),
-    MIME_ENTRY("rtf", "application/rtf"),
-    MIME_ENTRY("pdf", "application/pdf"),
-    MIME_ENTRY("swf", "application/x-shockwave-flash"),
-    MIME_ENTRY("mpg", "video/mpeg"),
-    MIME_ENTRY("webm", "video/webm"),
-    MIME_ENTRY("mpeg", "video/mpeg"),
-    MIME_ENTRY("mov", "video/quicktime"),
-    MIME_ENTRY("mp4", "video/mp4"),
-    MIME_ENTRY("m4v", "video/x-m4v"),
-    MIME_ENTRY("asf", "video/x-ms-asf"),
-    MIME_ENTRY("avi", "video/x-msvideo"),
-    MIME_ENTRY("bmp", "image/bmp"),
-    {NULL, 0, NULL},
-};
-
-static struct mg_str mg_get_mime_types_entry(struct mg_str path) {
-  size_t i;
-  for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
-    if (path.len < mg_static_builtin_mime_types[i].ext_len + 1) continue;
-    struct mg_str ext = MG_MK_STR_N(mg_static_builtin_mime_types[i].extension,
-                                    mg_static_builtin_mime_types[i].ext_len);
-    struct mg_str pext = MG_MK_STR_N(path.p + (path.len - ext.len), ext.len);
-    if (pext.p[-1] == '.' && mg_strcasecmp(ext, pext) == 0) {
-      return mg_mk_str(mg_static_builtin_mime_types[i].mime_type);
-    }
-  }
-  return mg_mk_str(NULL);
-}
-
-MG_INTERNAL int mg_get_mime_type_encoding(
-    struct mg_str path, struct mg_str *type, struct mg_str *encoding,
-    const struct mg_serve_http_opts *opts) {
-  const char *ext, *overrides;
-  struct mg_str k, v;
-
-  overrides = opts->custom_mime_types;
-  while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
-    ext = path.p + (path.len - k.len);
-    if (path.len > k.len && mg_vcasecmp(&k, ext) == 0) {
-      *type = v;
-      return 1;
-    }
-  }
-
-  *type = mg_get_mime_types_entry(path);
-
-  /* Check for .html.gz, .js.gz, etc. */
-  if (mg_vcmp(type, "application/x-gunzip") == 0) {
-    struct mg_str path2 = mg_mk_str_n(path.p, path.len - 3);
-    struct mg_str type2 = mg_get_mime_types_entry(path2);
-    LOG(LL_ERROR, ("'%.*s' '%.*s' '%.*s'", (int) path.len, path.p,
-                   (int) path2.len, path2.p, (int) type2.len, type2.p));
-    if (type2.len > 0) {
-      *type = type2;
-      *encoding = mg_mk_str("gzip");
-    }
-  }
-
-  return (type->len > 0);
-}
-#endif
-
-/*
- * Check whether full request is buffered. Return:
- *   -1  if request is malformed
- *    0  if request is not yet fully buffered
- *   >0  actual request length, including last \r\n\r\n
- */
-static int mg_http_get_request_len(const char *s, int buf_len) {
-  const unsigned char *buf = (unsigned char *) s;
-  int i;
-
-  for (i = 0; i < buf_len; i++) {
-    if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
-      return -1;
-    } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
-      return i + 2;
-    } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
-               buf[i + 2] == '\n') {
-      return i + 3;
-    }
-  }
-
-  return 0;
-}
-
-static const char *mg_http_parse_headers(const char *s, const char *end,
-                                         int len, struct http_message *req) {
-  int i = 0;
-  req->content_length = MG_HTTP_CONTENT_LENGTH_UNKNOWN;
-  while (i < (int) ARRAY_SIZE(req->header_names) - 1) {
-    struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
-
-    s = mg_skip(s, end, ": ", k);
-    s = mg_skip(s, end, "\r\n", v);
-
-    while (v->len > 0 && v->p[v->len - 1] == ' ') {
-      v->len--; /* Trim trailing spaces in header value */
-    }
-
-    /*
-     * If header value is empty - skip it and go to next (if any).
-     * NOTE: Do not add it to headers_values because such addition changes API
-     * behaviour
-     */
-    if (k->len != 0 && v->len == 0) {
-      continue;
-    }
-
-    if (k->len == 0 || v->len == 0) {
-      k->p = v->p = NULL;
-      k->len = v->len = 0;
-      break;
-    }
-
-    if (mg_ncasecmp(k->p, "Content-Length", 14) == 0) {
-      req->body.len = (size_t) to64(v->p);
-      req->message.len = len + req->body.len;
-      req->content_length = req->body.len;
-    }
-
-    i++;
-  }
-
-  return s;
-}
-
-int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
-  const char *end, *qs;
-  int len = mg_http_get_request_len(s, n);
-
-  if (len <= 0) return len;
-
-  memset(hm, 0, sizeof(*hm));
-  hm->message.p = s;
-  hm->body.p = s + len;
-  hm->message.len = hm->body.len = (size_t) ~0;
-  end = s + len;
-
-  /* Request is fully buffered. Skip leading whitespaces. */
-  while (s < end && isspace(*(unsigned char *) s)) s++;
-
-  if (is_req) {
-    /* Parse request line: method, URI, proto */
-    s = mg_skip(s, end, " ", &hm->method);
-    s = mg_skip(s, end, " ", &hm->uri);
-    s = mg_skip(s, end, "\r\n", &hm->proto);
-    if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
-
-    /* If URI contains '?' character, initialize query_string */
-    if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
-      hm->query_string.p = qs + 1;
-      hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
-      hm->uri.len = qs - hm->uri.p;
-    }
-  } else {
-    s = mg_skip(s, end, " ", &hm->proto);
-    if (end - s < 4 || s[0] < '0' || s[0] > '9' || s[3] != ' ') return -1;
-    hm->resp_code = atoi(s);
-    if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
-    s += 4;
-    s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
-  }
-
-  s = mg_http_parse_headers(s, end, len, hm);
-
-  /*
-   * mg_parse_http() is used to parse both HTTP requests and HTTP
-   * responses. If HTTP response does not have Content-Length set, then
-   * body is read until socket is closed, i.e. body.len is infinite (~0).
-   *
-   * For HTTP requests though, according to
-   * http://tools.ietf.org/html/rfc7231#section-8.1.3,
-   * only POST and PUT methods have defined body semantics.
-   * Therefore, if Content-Length is not specified and methods are
-   * not one of PUT or POST, set body length to 0.
-   *
-   * So,
-   * if it is HTTP request, and Content-Length is not set,
-   * and method is not (PUT or POST) then reset body length to zero.
-   */
-  if (hm->body.len == (size_t) ~0 && is_req &&
-      mg_vcasecmp(&hm->method, "PUT") != 0 &&
-      mg_vcasecmp(&hm->method, "POST") != 0) {
-    hm->body.len = 0;
-    hm->message.len = len;
-  }
-
-  return len;
-}
-
-struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
-  size_t i, len = strlen(name);
-
-  for (i = 0; hm->header_names[i].len > 0; i++) {
-    struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
-    if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
-      return v;
-  }
-
-  return NULL;
-}
-
-#if MG_ENABLE_FILESYSTEM
-static void mg_http_transfer_file_data(struct mg_connection *nc) {
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
-  char buf[MG_MAX_HTTP_SEND_MBUF];
-  size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent);
-
-  if (pd->file.type == DATA_FILE) {
-    struct mbuf *io = &nc->send_mbuf;
-    if (io->len >= MG_MAX_HTTP_SEND_MBUF) {
-      to_read = 0;
-    } else {
-      to_read = MG_MAX_HTTP_SEND_MBUF - io->len;
-    }
-    if (to_read > left) {
-      to_read = left;
-    }
-    if (to_read > 0) {
-      n = mg_fread(buf, 1, to_read, pd->file.fp);
-      if (n > 0) {
-        mg_send(nc, buf, n);
-        pd->file.sent += n;
-        DBG(("%p sent %d (total %d)", (void*)nc, (int) n, (int) pd->file.sent));
-      }
-    } else {
-      /* Rate-limited */
-    }
-    if (pd->file.sent >= pd->file.cl) {
-      LOG(LL_DEBUG, ("%p done, %d bytes, ka %d", (void*)nc, (int) pd->file.sent,
-                     pd->file.keepalive));
-      if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
-      mg_http_free_proto_data_file(&pd->file);
-      pd->finished = 1;
-    }
-  } else if (pd->file.type == DATA_PUT) {
-    struct mbuf *io = &nc->recv_mbuf;
-    size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len;
-    size_t n = mg_fwrite(io->buf, 1, to_write, pd->file.fp);
-    if (n > 0) {
-      mbuf_remove(io, n);
-      pd->file.sent += n;
-    }
-    if (n == 0 || pd->file.sent >= pd->file.cl) {
-      if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
-      mg_http_free_proto_data_file(&pd->file);
-      pd->finished = 1;
-    }
-  }
-#if MG_ENABLE_HTTP_CGI
-  else if (pd->cgi.cgi_nc != NULL) {
-    /* This is POST data that needs to be forwarded to the CGI process */
-    if (pd->cgi.cgi_nc != NULL) {
-      mg_forward(nc, pd->cgi.cgi_nc);
-    } else {
-      nc->flags |= MG_F_SEND_AND_CLOSE;
-    }
-  }
-#endif
-}
-#endif /* MG_ENABLE_FILESYSTEM */
-
-/*
- * Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
- * if it's incomplete. If the chunk is fully buffered, return total number of
- * bytes in a chunk, and store data in `data`, `data_len`.
- */
-static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data,
-                                  size_t *chunk_len) {
-  unsigned char *s = (unsigned char *) buf;
-  size_t n = 0; /* scanned chunk length */
-  size_t i = 0; /* index in s */
-
-  /* Scan chunk length. That should be a hexadecimal number. */
-  while (i < len && isxdigit(s[i])) {
-    n *= 16;
-    n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
-    i++;
-    if (i > 6) {
-      /* Chunk size is unreasonable. */
-      return 0;
-    }
-  }
-
-  /* Skip new line */
-  if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
-    return 0;
-  }
-  i += 2;
-
-  /* Record where the data is */
-  *chunk_data = (char *) s + i;
-  *chunk_len = n;
-
-  /* Skip data */
-  i += n;
-
-  /* Skip new line */
-  if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
-    return 0;
-  }
-  return i + 2;
-}
-
-MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
-                                     struct http_message *hm, char *buf,
-                                     size_t blen) {
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
-  char *data;
-  size_t i, n, data_len, body_len, zero_chunk_received = 0;
-  /* Find out piece of received data that is not yet reassembled */
-  body_len = (size_t) pd->chunk.body_len;
-  assert(blen >= body_len);
-
-  /* Traverse all fully buffered chunks */
-  for (i = body_len;
-       (n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
-       i += n) {
-    /* Collapse chunk data to the rest of HTTP body */
-    memmove(buf + body_len, data, data_len);
-    body_len += data_len;
-    hm->body.len = body_len;
-
-    if (data_len == 0) {
-      zero_chunk_received = 1;
-      i += n;
-      break;
-    }
-  }
-
-  if (i > body_len) {
-    /* Shift unparsed content to the parsed body */
-    assert(i <= blen);
-    memmove(buf + body_len, buf + i, blen - i);
-    memset(buf + body_len + blen - i, 0, i - body_len);
-    nc->recv_mbuf.len -= i - body_len;
-    pd->chunk.body_len = body_len;
-
-    /* Send MG_EV_HTTP_CHUNK event */
-    nc->flags &= ~MG_F_DELETE_CHUNK;
-    mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm);
-
-    /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
-    if (nc->flags & MG_F_DELETE_CHUNK) {
-      memset(buf, 0, body_len);
-      memmove(buf, buf + body_len, blen - i);
-      nc->recv_mbuf.len -= body_len;
-      hm->body.len = 0;
-      pd->chunk.body_len = 0;
-    }
-
-    if (zero_chunk_received) {
-      /* Total message size is len(body) + len(headers) */
-      hm->message.len =
-          (size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p);
-    }
-  }
-
-  return body_len;
-}
-
-struct mg_http_endpoint *mg_http_get_endpoint_handler(struct mg_connection *nc,
-                                                      struct mg_str *uri_path) {
-  struct mg_http_proto_data *pd;
-  struct mg_http_endpoint *ret = NULL;
-  int matched, matched_max = 0;
-  struct mg_http_endpoint *ep;
-
-  if (nc == NULL) return NULL;
-
-  pd = mg_http_get_proto_data(nc);
-
-  if (pd == NULL) return NULL;
-
-  ep = pd->endpoints;
-  while (ep != NULL) {
-    if ((matched = mg_match_prefix_n(ep->uri_pattern, *uri_path)) > 0) {
-      if (matched > matched_max) {
-        /* Looking for the longest suitable handler */
-        ret = ep;
-        matched_max = matched;
-      }
-    }
-
-    ep = ep->next;
-  }
-
-  return ret;
-}
-
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-static void mg_http_multipart_continue(struct mg_connection *nc);
-
-static void mg_http_multipart_begin(struct mg_connection *nc,
-                                    struct http_message *hm, int req_len);
-
-#endif
-
-static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
-                                          struct http_message *hm);
-
-static void deliver_chunk(struct mg_connection *c, struct http_message *hm,
-                          struct mg_http_proto_data *pd, int req_len) {
-  /* Incomplete message received. Send MG_EV_HTTP_CHUNK event */
-  hm->body.len = c->recv_mbuf.len - req_len;
-  if (hm->content_length != MG_HTTP_CONTENT_LENGTH_UNKNOWN) {
-    size_t body_remain = hm->content_length - pd->body_processed;
-    if (hm->body.len > body_remain) {
-      hm->body.len = body_remain;
-    }
-  }
-  if (pd != NULL) {
-    pd->body_rcvd = pd->body_processed + hm->body.len;
-  }
-  c->flags &= ~MG_F_DELETE_CHUNK;
-  mg_call(c, c->handler, c->user_data, MG_EV_HTTP_CHUNK, hm);
-  /* Delete processed data if user set MG_F_DELETE_CHUNK flag */
-  if (c->flags & MG_F_DELETE_CHUNK) {
-    pd->body_processed += hm->body.len;
-    c->recv_mbuf.len = req_len;
-    hm->body.len = 0;
-  }
-}
-
-/*
- * lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
- * If a big structure is declared in a big function, lx106 gcc will make it
- * even bigger (round up to 4k, from 700 bytes of actual size).
- */
-#ifdef __xtensa__
-static void mg_http_handler2(struct mg_connection *nc, int ev,
-                             void *ev_data MG_UD_ARG(void *user_data),
-                             struct http_message *hm) __attribute__((noinline));
-
-void mg_http_handler(struct mg_connection *nc, int ev,
-                     void *ev_data MG_UD_ARG(void *user_data)) {
-  struct http_message hm;
-  mg_http_handler2(nc, ev, ev_data MG_UD_ARG(user_data), &hm);
-}
-
-static void mg_http_handler2(struct mg_connection *nc, int ev,
-                             void *ev_data MG_UD_ARG(void *user_data),
-                             struct http_message *hm) {
-#else  /* !__XTENSA__ */
-void mg_http_handler(struct mg_connection *nc, int ev,
-                     void *ev_data MG_UD_ARG(void *user_data)) {
-  struct http_message shm, *hm = &shm;
-#endif /* __XTENSA__ */
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
-  struct mbuf *io = &nc->recv_mbuf;
-  int req_len;
-  const int is_req = (nc->listener != NULL);
-#if MG_ENABLE_HTTP_WEBSOCKET
-  struct mg_str *vec;
-#endif
-  if (ev == MG_EV_CLOSE) {
-#if MG_ENABLE_HTTP_CGI
-    /* Close associated CGI forwarder connection */
-    if (pd != NULL && pd->cgi.cgi_nc != NULL) {
-      pd->cgi.cgi_nc->user_data = NULL;
-      pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-    }
-#endif
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-    if (pd != NULL && pd->mp_stream.boundary != NULL) {
-      /*
-       * Multipart message is in progress, but connection is closed.
-       * Finish part and request with an error flag.
-       */
-      struct mg_http_multipart_part mp;
-      memset(&mp, 0, sizeof(mp));
-      mp.status = -1;
-      mp.user_data = pd->mp_stream.user_data;
-      mp.var_name = pd->mp_stream.var_name;
-      mp.file_name = pd->mp_stream.file_name;
-      mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
-              nc->user_data, MG_EV_HTTP_PART_END, &mp);
-      mp.var_name = NULL;
-      mp.file_name = NULL;
-      mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
-              nc->user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp);
-    } else
-#endif
-        if (io->len > 0 &&
-            (req_len = mg_parse_http(io->buf, io->len, hm, is_req)) > 0) {
-      /*
-       * For HTTP messages without Content-Length, always send HTTP message
-       * before MG_EV_CLOSE message.
-       */
-      int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
-      hm->message.len = io->len;
-      hm->body.len = io->buf + io->len - hm->body.p;
-      deliver_chunk(nc, hm, pd, req_len);
-      mg_http_call_endpoint_handler(nc, ev2, hm);
-    }
-    if (pd != NULL && pd->endpoint_handler != NULL &&
-        pd->endpoint_handler != nc->handler) {
-      mg_call(nc, pd->endpoint_handler, nc->user_data, ev, NULL);
-    }
-  }
-
-#if MG_ENABLE_FILESYSTEM
-  if (pd != NULL && pd->file.fp != NULL) {
-    mg_http_transfer_file_data(nc);
-    if (pd->finished) {
-    }
-  }
-#endif
-
-  mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
-
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-  if (pd != NULL && pd->mp_stream.boundary != NULL &&
-      (ev == MG_EV_RECV || ev == MG_EV_POLL)) {
-    if (ev == MG_EV_RECV) {
-      pd->rcvd += *(int *) ev_data;
-      mg_http_multipart_continue(nc);
-    } else if (pd->mp_stream.data_avail) {
-      /* Try re-delivering the data. */
-      mg_http_multipart_continue(nc);
-    }
-    return;
-  }
-#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
-
-  if (ev == MG_EV_RECV) {
-    struct mg_str *s;
-
-  again:
-    req_len = mg_parse_http(io->buf, io->len, hm, is_req);
-    if (req_len > 0 && (pd == NULL || pd->finished)) {
-      /* New request - new proto data */
-      pd = mg_http_create_proto_data(nc);
-      pd->rcvd = io->len;
-    }
-
-    if (req_len > 0 &&
-        (s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
-        mg_vcasecmp(s, "chunked") == 0) {
-      mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
-    }
-
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-    if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL &&
-        s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) {
-      mg_http_multipart_begin(nc, hm, req_len);
-      mg_http_multipart_continue(nc);
-      return;
-    }
-#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
-
-    /* TODO(alashkin): refactor this ifelseifelseifelseifelse */
-    if ((req_len < 0 ||
-         (req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) {
-      DBG(("invalid request"));
-      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-    } else if (req_len == 0) {
-      /* Do nothing, request is not yet fully buffered */
-    }
-#if MG_ENABLE_HTTP_WEBSOCKET
-    else if (nc->listener == NULL && (nc->flags & MG_F_IS_WEBSOCKET)) {
-      /* We're websocket client, got handshake response from server. */
-      DBG(("%p WebSocket upgrade code %d", (void*)nc, hm->resp_code));
-      if (hm->resp_code == 101 &&
-          mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
-        /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
-        mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
-                hm);
-        mbuf_remove(io, req_len);
-        nc->proto_handler = mg_ws_handler;
-        mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
-      } else {
-        mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
-                hm);
-        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-        mbuf_remove(io, req_len);
-      }
-    } else if (nc->listener != NULL &&
-               (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
-      struct mg_http_endpoint *ep;
-
-      /* This is a websocket request. Switch protocol handlers. */
-      mbuf_remove(io, req_len);
-      nc->proto_handler = mg_ws_handler;
-      nc->flags |= MG_F_IS_WEBSOCKET;
-
-      /*
-       * If we have a handler set up with mg_register_http_endpoint(),
-       * deliver subsequent websocket events to this handler after the
-       * protocol switch.
-       */
-      ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
-      if (ep != NULL) {
-        nc->handler = ep->handler;
-#if MG_ENABLE_CALLBACK_USERDATA
-        nc->user_data = ep->user_data;
-#endif
-      }
-
-      /* Send handshake */
-      mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST,
-              hm);
-      if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) {
-        if (nc->send_mbuf.len == 0) {
-          mg_ws_handshake(nc, vec, hm);
-        }
-        mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
-                hm);
-        mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
-      }
-    }
-#endif /* MG_ENABLE_HTTP_WEBSOCKET */
-    else {
-      deliver_chunk(nc, hm, pd, req_len);
-      if (hm->message.len > pd->rcvd &&
-          (hm->content_length == MG_HTTP_CONTENT_LENGTH_UNKNOWN ||
-           pd->body_rcvd < hm->content_length)) {
-        /* Not yet received all HTTP body, deliver MG_EV_HTTP_CHUNK */
-        if (nc->recv_mbuf_limit > 0 &&
-            nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
-          LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
-                         "%lu bytes, and not drained, closing",
-                         (void*)nc, (unsigned long) nc->recv_mbuf.len,
-                         (unsigned long) nc->recv_mbuf_limit));
-          nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-        }
-      } else {
-        /* We did receive all HTTP body. */
-        int request_done = 1;
-        int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
-        char addr[32];
-        mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr),
-                            MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
-        DBG(("%p %s %.*s %.*s", (void*)nc, addr, (int) hm->method.len, hm->method.p,
-             (int) hm->uri.len, hm->uri.p));
-        /* Whole HTTP message is fully buffered, call event handler */
-        mg_http_call_endpoint_handler(nc, trigger_ev, hm);
-        mbuf_remove(io, req_len + hm->body.len);
-        pd->rcvd -= hm->message.len;
-        pd->body_rcvd = 0;
-#if MG_ENABLE_FILESYSTEM
-        /* We don't have a generic mechanism of communicating that we are done
-         * responding to a request (should probably add one). But if we are
-         * serving
-         * a file, we are definitely not done. */
-        if (pd->file.fp != NULL) request_done = 0;
-#endif
-#if MG_ENABLE_HTTP_CGI
-        /* If this is a CGI request, we are not done either. */
-        if (pd->cgi.cgi_nc != NULL) request_done = 0;
-#endif
-        pd->finished = request_done;
-        DBG(("%p finished %d ml %d bl %d", (void*)nc, pd->finished,
-             (int) hm->message.len, (int) hm->body.len));
-        if (request_done && io->len > 0) goto again;
-      }
-    }
-  }
-}
-
-static size_t mg_get_line_len(const char *buf, size_t buf_len) {
-  size_t len = 0;
-  while (len < buf_len && buf[len] != '\n') len++;
-  return len == buf_len ? 0 : len + 1;
-}
-
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-static void mg_http_multipart_begin(struct mg_connection *nc,
-                                    struct http_message *hm, int req_len) {
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
-  struct mg_str *ct;
-  struct mbuf *io = &nc->recv_mbuf;
-
-  char boundary_buf[100];
-  char *boundary = boundary_buf;
-  int boundary_len;
-
-  ct = mg_get_http_header(hm, "Content-Type");
-  if (ct == NULL) {
-    /* We need more data - or it isn't multipart mesage */
-    goto exit_mp;
-  }
-
-  /* Content-type should start with "multipart" */
-  if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) {
-    goto exit_mp;
-  }
-
-  boundary_len =
-      mg_http_parse_header2(ct, "boundary", &boundary, sizeof(boundary_buf));
-  if (boundary_len == 0) {
-    /*
-     * Content type is multipart, but there is no boundary,
-     * probably malformed request
-     */
-    nc->flags = MG_F_CLOSE_IMMEDIATELY;
-    DBG(("invalid request"));
-    goto exit_mp;
-  }
-
-  /* If we reach this place - that is multipart request */
-
-  if (pd->mp_stream.boundary != NULL) {
-    /*
-     * Another streaming request was in progress,
-     * looks like protocol error
-     */
-    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-  } else {
-    struct mg_http_endpoint *ep = NULL;
-    pd->mp_stream.state = MPS_BEGIN;
-    pd->mp_stream.boundary = strdup(boundary);
-    pd->mp_stream.boundary_len = strlen(boundary);
-    pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
-    pd->endpoint_handler = nc->handler;
-
-    ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
-    if (ep != NULL) {
-      pd->endpoint_handler = ep->handler;
-    }
-
-    mg_http_call_endpoint_handler(nc, MG_EV_HTTP_MULTIPART_REQUEST, hm);
-
-    mbuf_remove(io, req_len);
-  }
-exit_mp:
-  if (boundary != boundary_buf) MG_FREE(boundary);
-}
-
-#define CONTENT_DISPOSITION "Content-Disposition: "
-
-static size_t mg_http_multipart_call_handler(struct mg_connection *c, int ev,
-                                             const char *data,
-                                             size_t data_len) {
-  struct mg_http_multipart_part mp;
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
-  memset(&mp, 0, sizeof(mp));
-
-  mp.var_name = pd->mp_stream.var_name;
-  mp.file_name = pd->mp_stream.file_name;
-  mp.user_data = pd->mp_stream.user_data;
-  mp.data.p = data;
-  mp.data.len = data_len;
-  mp.num_data_consumed = data_len;
-  mg_call(c, pd->endpoint_handler, c->user_data, ev, &mp);
-  pd->mp_stream.user_data = mp.user_data;
-  pd->mp_stream.data_avail = (mp.num_data_consumed != data_len);
-  return mp.num_data_consumed;
-}
-
-static int mg_http_multipart_finalize(struct mg_connection *c) {
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
-
-  mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
-  MG_FREE((void *) pd->mp_stream.file_name);
-  pd->mp_stream.file_name = NULL;
-  MG_FREE((void *) pd->mp_stream.var_name);
-  pd->mp_stream.var_name = NULL;
-  mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0);
-  mg_http_free_proto_data_mp_stream(&pd->mp_stream);
-  pd->mp_stream.state = MPS_FINISHED;
-
-  return 1;
-}
-
-static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) {
-  const char *boundary;
-  struct mbuf *io = &c->recv_mbuf;
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
-
-  if (pd->mp_stream.boundary == NULL) {
-    pd->mp_stream.state = MPS_FINALIZE;
-    DBG(("Invalid request: boundary not initialized"));
-    return 0;
-  }
-
-  if ((int) io->len < pd->mp_stream.boundary_len + 2) {
-    return 0;
-  }
-
-  boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
-  if (boundary != NULL) {
-    const char *boundary_end = (boundary + pd->mp_stream.boundary_len);
-    if (io->len - (boundary_end - io->buf) < 4) {
-      return 0;
-    }
-    if (strncmp(boundary_end, "--\r\n", 4) == 0) {
-      pd->mp_stream.state = MPS_FINALIZE;
-      mbuf_remove(io, (boundary_end - io->buf) + 4);
-    } else {
-      pd->mp_stream.state = MPS_GOT_BOUNDARY;
-    }
-  } else {
-    return 0;
-  }
-
-  return 1;
-}
-
-static void mg_http_parse_header_internal(struct mg_str *hdr,
-                                          const char *var_name,
-                                          struct altbuf *ab);
-
-static int mg_http_multipart_process_boundary(struct mg_connection *c) {
-  int data_size;
-  const char *boundary, *block_begin;
-  struct mbuf *io = &c->recv_mbuf;
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
-  struct altbuf ab_file_name, ab_var_name;
-  int line_len;
-  boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
-  block_begin = boundary + pd->mp_stream.boundary_len + 2;
-  data_size = io->len - (block_begin - io->buf);
-
-  altbuf_init(&ab_file_name, NULL, 0);
-  altbuf_init(&ab_var_name, NULL, 0);
-
-  while (data_size > 0 &&
-         (line_len = mg_get_line_len(block_begin, data_size)) != 0) {
-    if (line_len > (int) sizeof(CONTENT_DISPOSITION) &&
-        mg_ncasecmp(block_begin, CONTENT_DISPOSITION,
-                    sizeof(CONTENT_DISPOSITION) - 1) == 0) {
-      struct mg_str header;
-
-      header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
-      header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
-
-      altbuf_reset(&ab_var_name);
-      mg_http_parse_header_internal(&header, "name", &ab_var_name);
-
-      altbuf_reset(&ab_file_name);
-      mg_http_parse_header_internal(&header, "filename", &ab_file_name);
-
-      block_begin += line_len;
-      data_size -= line_len;
-
-      continue;
-    }
-
-    if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
-      mbuf_remove(io, block_begin - io->buf + 2);
-
-      if (pd->mp_stream.processing_part != 0) {
-        mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
-      }
-
-      /* Reserve 2 bytes for "\r\n" in file_name and var_name */
-      altbuf_append(&ab_file_name, '\0');
-      altbuf_append(&ab_file_name, '\0');
-      altbuf_append(&ab_var_name, '\0');
-      altbuf_append(&ab_var_name, '\0');
-
-      MG_FREE((void *) pd->mp_stream.file_name);
-      pd->mp_stream.file_name = altbuf_get_buf(&ab_file_name, 1 /* trim */);
-      MG_FREE((void *) pd->mp_stream.var_name);
-      pd->mp_stream.var_name = altbuf_get_buf(&ab_var_name, 1 /* trim */);
-
-      mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0);
-      pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
-      pd->mp_stream.processing_part++;
-      return 1;
-    }
-
-    block_begin += line_len;
-  }
-
-  pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
-
-  altbuf_reset(&ab_var_name);
-  altbuf_reset(&ab_file_name);
-
-  return 0;
-}
-
-static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) {
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
-  struct mbuf *io = &c->recv_mbuf;
-
-  const char *boundary;
-  if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) {
-    return 0;
-  }
-
-  boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
-  if (boundary == NULL) {
-    int data_len = (io->len - (pd->mp_stream.boundary_len + 6));
-    if (data_len > 0) {
-      size_t consumed = mg_http_multipart_call_handler(
-          c, MG_EV_HTTP_PART_DATA, io->buf, (size_t) data_len);
-      mbuf_remove(io, consumed);
-    }
-    return 0;
-  } else if (boundary != NULL) {
-    size_t data_len = ((size_t)(boundary - io->buf) - 4);
-    size_t consumed = mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA,
-                                                     io->buf, data_len);
-    mbuf_remove(io, consumed);
-    if (consumed == data_len) {
-      mbuf_remove(io, 4);
-      pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
-      return 1;
-    } else {
-      return 0;
-    }
-  } else {
-    return 0;
-  }
-}
-
-static void mg_http_multipart_continue(struct mg_connection *c) {
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
-  while (1) {
-    switch (pd->mp_stream.state) {
-      case MPS_BEGIN: {
-        pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
-        break;
-      }
-      case MPS_WAITING_FOR_BOUNDARY: {
-        if (mg_http_multipart_wait_for_boundary(c) == 0) {
-          return;
-        }
-        break;
-      }
-      case MPS_GOT_BOUNDARY: {
-        if (mg_http_multipart_process_boundary(c) == 0) {
-          return;
-        }
-        break;
-      }
-      case MPS_WAITING_FOR_CHUNK: {
-        if (mg_http_multipart_continue_wait_for_chunk(c) == 0) {
-          return;
-        }
-        break;
-      }
-      case MPS_FINALIZE: {
-        if (mg_http_multipart_finalize(c) == 0) {
-          return;
-        }
-        break;
-      }
-      case MPS_FINISHED: {
-        return;
-      }
-    }
-  }
-}
-
-struct file_upload_state {
-  char *lfn;
-  size_t num_recd;
-  FILE *fp;
-};
-
-#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
-
-void mg_set_protocol_http_websocket(struct mg_connection *nc) {
-  nc->proto_handler = mg_http_handler;
-}
-
-const char *mg_status_message(int status_code) {
-  switch (status_code) {
-    case 206:
-      return "Partial Content";
-    case 301:
-      return "Moved";
-    case 302:
-      return "Found";
-    case 400:
-      return "Bad Request";
-    case 401:
-      return "Unauthorized";
-    case 403:
-      return "Forbidden";
-    case 404:
-      return "Not Found";
-    case 416:
-      return "Requested Range Not Satisfiable";
-    case 418:
-      return "I'm a teapot";
-    case 500:
-      return "Internal Server Error";
-    case 502:
-      return "Bad Gateway";
-    case 503:
-      return "Service Unavailable";
-
-#if MG_ENABLE_EXTRA_ERRORS_DESC
-    case 100:
-      return "Continue";
-    case 101:
-      return "Switching Protocols";
-    case 102:
-      return "Processing";
-    case 200:
-      return "OK";
-    case 201:
-      return "Created";
-    case 202:
-      return "Accepted";
-    case 203:
-      return "Non-Authoritative Information";
-    case 204:
-      return "No Content";
-    case 205:
-      return "Reset Content";
-    case 207:
-      return "Multi-Status";
-    case 208:
-      return "Already Reported";
-    case 226:
-      return "IM Used";
-    case 300:
-      return "Multiple Choices";
-    case 303:
-      return "See Other";
-    case 304:
-      return "Not Modified";
-    case 305:
-      return "Use Proxy";
-    case 306:
-      return "Switch Proxy";
-    case 307:
-      return "Temporary Redirect";
-    case 308:
-      return "Permanent Redirect";
-    case 402:
-      return "Payment Required";
-    case 405:
-      return "Method Not Allowed";
-    case 406:
-      return "Not Acceptable";
-    case 407:
-      return "Proxy Authentication Required";
-    case 408:
-      return "Request Timeout";
-    case 409:
-      return "Conflict";
-    case 410:
-      return "Gone";
-    case 411:
-      return "Length Required";
-    case 412:
-      return "Precondition Failed";
-    case 413:
-      return "Payload Too Large";
-    case 414:
-      return "URI Too Long";
-    case 415:
-      return "Unsupported Media Type";
-    case 417:
-      return "Expectation Failed";
-    case 422:
-      return "Unprocessable Entity";
-    case 423:
-      return "Locked";
-    case 424:
-      return "Failed Dependency";
-    case 426:
-      return "Upgrade Required";
-    case 428:
-      return "Precondition Required";
-    case 429:
-      return "Too Many Requests";
-    case 431:
-      return "Request Header Fields Too Large";
-    case 451:
-      return "Unavailable For Legal Reasons";
-    case 501:
-      return "Not Implemented";
-    case 504:
-      return "Gateway Timeout";
-    case 505:
-      return "HTTP Version Not Supported";
-    case 506:
-      return "Variant Also Negotiates";
-    case 507:
-      return "Insufficient Storage";
-    case 508:
-      return "Loop Detected";
-    case 510:
-      return "Not Extended";
-    case 511:
-      return "Network Authentication Required";
-#endif /* MG_ENABLE_EXTRA_ERRORS_DESC */
-
-    default:
-      return "OK";
-  }
-}
-
-void mg_send_response_line_s(struct mg_connection *nc, int status_code,
-                             const struct mg_str extra_headers) {
-  mg_printf(nc, "HTTP/1.1 %d %s\r\n", status_code,
-            mg_status_message(status_code));
-#ifndef MG_HIDE_SERVER_INFO
-  mg_printf(nc, "Server: %s\r\n", mg_version_header);
-#endif
-  if (extra_headers.len > 0) {
-    mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p);
-  }
-}
-
-void mg_send_response_line(struct mg_connection *nc, int status_code,
-                           const char *extra_headers) {
-  mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers));
-}
-
-void mg_http_send_redirect(struct mg_connection *nc, int status_code,
-                           const struct mg_str location,
-                           const struct mg_str extra_headers) {
-  char bbody[100], *pbody = bbody;
-  int bl = mg_asprintf(&pbody, sizeof(bbody),
-                       "<p>Moved <a href='%.*s'>here</a>.\r\n",
-                       (int) location.len, location.p);
-  char bhead[150], *phead = bhead;
-  mg_asprintf(&phead, sizeof(bhead),
-              "Location: %.*s\r\n"
-              "Content-Type: text/html\r\n"
-              "Content-Length: %d\r\n"
-              "Cache-Control: no-cache\r\n"
-              "%.*s%s",
-              (int) location.len, location.p, bl, (int) extra_headers.len,
-              extra_headers.p, (extra_headers.len > 0 ? "\r\n" : ""));
-  mg_send_response_line(nc, status_code, phead);
-  if (phead != bhead) MG_FREE(phead);
-  mg_send(nc, pbody, bl);
-  if (pbody != bbody) MG_FREE(pbody);
-}
-
-void mg_send_head(struct mg_connection *c, int status_code,
-                  int64_t content_length, const char *extra_headers) {
-  mg_send_response_line(c, status_code, extra_headers);
-  if (content_length < 0) {
-    mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n");
-  } else {
-    mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length);
-  }
-  mg_send(c, "\r\n", 2);
-}
-
-void mg_http_send_error(struct mg_connection *nc, int code,
-                        const char *reason) {
-  if (!reason) reason = mg_status_message(code);
-  LOG(LL_DEBUG, ("%p %d %s", (void*)nc, code, reason));
-  mg_send_head(nc, code, strlen(reason),
-               "Content-Type: text/plain\r\nConnection: close");
-  mg_send(nc, reason, strlen(reason));
-  nc->flags |= MG_F_SEND_AND_CLOSE;
-}
-
-#if MG_ENABLE_FILESYSTEM
-static void mg_http_construct_etag(char *buf, size_t buf_len,
-                                   const cs_stat_t *st) {
-  snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
-           (int64_t) st->st_size);
-}
-
-#ifndef WINCE
-static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
-  strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
-}
-#else
-/* Look wince_lib.c for WindowsCE implementation */
-static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t);
-#endif
-
-static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a,
-                                      int64_t *b) {
-  /*
-   * There is no snscanf. Headers are not guaranteed to be NUL-terminated,
-   * so we have this. Ugh.
-   */
-  int result;
-  char *p = (char *) MG_MALLOC(header->len + 1);
-  if (p == NULL) return 0;
-  memcpy(p, header->p, header->len);
-  p[header->len] = '\0';
-  result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
-  MG_FREE(p);
-  return result;
-}
-
-void mg_http_serve_file_internal(struct mg_connection *nc,
-                                 struct http_message *hm, const char *path,
-                                 struct mg_str mime_type,
-                                 struct mg_str encoding,
-                                 struct mg_str extra_headers) {
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
-  cs_stat_t st;
-  LOG(LL_DEBUG, ("%p [%s] %.*s %.*s", (void*)nc, path, (int) mime_type.len,
-                 mime_type.p, (int) encoding.len, encoding.p));
-  if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) {
-    int code, err = mg_get_errno();
-    switch (err) {
-      case EACCES:
-        code = 403;
-        break;
-      case ENOENT:
-        code = 404;
-        break;
-      default:
-        code = 500;
-    };
-    mg_http_send_error(nc, code, "Open failed");
-  } else {
-    char etag[50], current_time[50], last_modified[50], range[70];
-    time_t t = (time_t) mg_time();
-    int64_t r1 = 0, r2 = 0, cl = st.st_size;
-    struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
-    int n, status_code = 200;
-
-    /* Handle Range header */
-    range[0] = '\0';
-    if (range_hdr != NULL &&
-        (n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
-        r2 >= 0) {
-      /* If range is specified like "400-", set second limit to content len */
-      if (n == 1) {
-        r2 = cl - 1;
-      }
-      if (r1 > r2 || r2 >= cl) {
-        status_code = 416;
-        cl = 0;
-        snprintf(range, sizeof(range),
-                 "Content-Range: bytes */%" INT64_FMT "\r\n",
-                 (int64_t) st.st_size);
-      } else {
-        status_code = 206;
-        cl = r2 - r1 + 1;
-        snprintf(range, sizeof(range),
-                 "Content-Range: bytes %" INT64_FMT "-%" INT64_FMT
-                 "/%" INT64_FMT "\r\n",
-                 r1, r1 + cl - 1, (int64_t) st.st_size);
-#if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
-    _XOPEN_SOURCE >= 600
-        fseeko(pd->file.fp, r1, SEEK_SET);
-#else
-        fseek(pd->file.fp, (long) r1, SEEK_SET);
-#endif
-      }
-    }
-
-#if !MG_DISABLE_HTTP_KEEP_ALIVE
-    {
-      struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection");
-      if (conn_hdr != NULL) {
-        pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0);
-      } else {
-        pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0);
-      }
-    }
-#endif
-
-    mg_http_construct_etag(etag, sizeof(etag), &st);
-    mg_gmt_time_string(current_time, sizeof(current_time), &t);
-    mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime);
-    mg_send_response_line_s(nc, status_code, extra_headers);
-    mg_printf(nc,
-              "Date: %s\r\n"
-              "Last-Modified: %s\r\n"
-              "Accept-Ranges: bytes\r\n"
-              "Content-Type: %.*s\r\n"
-              "Connection: %s\r\n"
-              "Content-Length: %" SIZE_T_FMT
-              "\r\n"
-              "%s"
-              "Etag: %s\r\n",
-              current_time, last_modified, (int) mime_type.len, mime_type.p,
-              (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range,
-              etag);
-    if (encoding.len > 0) {
-      mg_printf(nc, "Content-Encoding: %.*s\r\n", (int) encoding.len,
-                encoding.p);
-    }
-    mg_send(nc, "\r\n", 2);
-    pd->file.cl = cl;
-    pd->file.type = DATA_FILE;
-    mg_http_transfer_file_data(nc);
-  }
-}
-
-void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
-                        const char *path, const struct mg_str mime_type,
-                        const struct mg_str extra_headers) {
-  mg_http_serve_file_internal(nc, hm, path, mime_type, mg_mk_str(NULL),
-                              extra_headers);
-}
-
-static void mg_http_serve_file2(struct mg_connection *nc, const char *path,
-                                struct http_message *hm,
-                                struct mg_serve_http_opts *opts) {
-#if MG_ENABLE_HTTP_SSI
-  if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) {
-    mg_handle_ssi_request(nc, hm, path, opts);
-    return;
-  }
-#endif
-  struct mg_str type = MG_NULL_STR, encoding = MG_NULL_STR;
-  if (!mg_get_mime_type_encoding(mg_mk_str(path), &type, &encoding, opts)) {
-    type = mg_mk_str("text/plain");
-  }
-  mg_http_serve_file_internal(nc, hm, path, type, encoding,
-                              mg_mk_str(opts->extra_headers));
-}
-
-#endif
-
-int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
-                  int is_form_url_encoded) {
-  int i, j, a, b;
-#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
-
-  for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
-    if (src[i] == '%') {
-      if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
-          isxdigit(*(const unsigned char *) (src + i + 2))) {
-        a = tolower(*(const unsigned char *) (src + i + 1));
-        b = tolower(*(const unsigned char *) (src + i + 2));
-        dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
-        i += 2;
-      } else {
-        return -1;
-      }
-    } else if (is_form_url_encoded && src[i] == '+') {
-      dst[j] = ' ';
-    } else {
-      dst[j] = src[i];
-    }
-  }
-
-  dst[j] = '\0'; /* Null-terminate the destination */
-
-  return i >= src_len ? j : -1;
-}
-
-int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
-                    size_t dst_len) {
-  const char *p, *e, *s;
-  size_t name_len;
-  int len;
-
-  /*
-   * According to the documentation function returns negative
-   * value in case of error. For debug purposes it returns:
-   * -1 - src is wrong (NUUL)
-   * -2 - dst is wrong (NULL)
-   * -3 - failed to decode url or dst is to small
-   * -4 - name does not exist
-   */
-  if (dst == NULL || dst_len == 0) {
-    len = -2;
-  } else if (buf->p == NULL || name == NULL || buf->len == 0) {
-    len = -1;
-    dst[0] = '\0';
-  } else {
-    name_len = strlen(name);
-    e = buf->p + buf->len;
-    len = -4;
-    dst[0] = '\0';
-
-    for (p = buf->p; p + name_len < e; p++) {
-      if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
-          !mg_ncasecmp(name, p, name_len)) {
-        p += name_len + 1;
-        s = (const char *) memchr(p, '&', (size_t)(e - p));
-        if (s == NULL) {
-          s = e;
-        }
-        len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
-        /* -1 means: failed to decode or dst is too small */
-        if (len == -1) {
-          len = -3;
-        }
-        break;
-      }
-    }
-  }
-
-  return len;
-}
-
-void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
-  char chunk_size[50];
-  int n;
-
-  n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
-  mg_send(nc, chunk_size, n);
-  mg_send(nc, buf, len);
-  mg_send(nc, "\r\n", 2);
-}
-
-void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
-  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
-  int len;
-  va_list ap;
-
-  va_start(ap, fmt);
-  len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
-  va_end(ap);
-
-  if (len >= 0) {
-    mg_send_http_chunk(nc, buf, len);
-  }
-
-  /* LCOV_EXCL_START */
-  if (buf != mem && buf != NULL) {
-    MG_FREE(buf);
-  }
-  /* LCOV_EXCL_STOP */
-}
-
-void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
-  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
-  int i, j, len;
-  va_list ap;
-
-  va_start(ap, fmt);
-  len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
-  va_end(ap);
-
-  if (len >= 0) {
-    for (i = j = 0; i < len; i++) {
-      if (buf[i] == '<' || buf[i] == '>') {
-        mg_send(nc, buf + j, i - j);
-        mg_send(nc, buf[i] == '<' ? "&lt;" : "&gt;", 4);
-        j = i + 1;
-      }
-    }
-    mg_send(nc, buf + j, i - j);
-  }
-
-  /* LCOV_EXCL_START */
-  if (buf != mem && buf != NULL) {
-    MG_FREE(buf);
-  }
-  /* LCOV_EXCL_STOP */
-}
-
-static void mg_http_parse_header_internal(struct mg_str *hdr,
-                                          const char *var_name,
-                                          struct altbuf *ab) {
-  int ch = ' ', ch1 = ',', ch2 = ';', n = strlen(var_name);
-  const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
-
-  /* Find where variable starts */
-  for (s = hdr->p; s != NULL && s + n < end; s++) {
-    if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') &&
-        s[n] == '=' && !strncmp(s, var_name, n))
-      break;
-  }
-
-  if (s != NULL && &s[n + 1] < end) {
-    s += n + 1;
-    if (*s == '"' || *s == '\'') {
-      ch = ch1 = ch2 = *s++;
-    }
-    p = s;
-    while (p < end && p[0] != ch && p[0] != ch1 && p[0] != ch2) {
-      if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
-      altbuf_append(ab, *p++);
-    }
-
-    if (ch != ' ' && *p != ch) {
-      altbuf_reset(ab);
-    }
-  }
-
-  /* If there is some data, append a NUL. */
-  if (ab->len > 0) {
-    altbuf_append(ab, '\0');
-  }
-}
-
-int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf,
-                          size_t buf_size) {
-  struct altbuf ab;
-  altbuf_init(&ab, *buf, buf_size);
-  if (hdr == NULL) return 0;
-  if (*buf != NULL && buf_size > 0) *buf[0] = '\0';
-
-  mg_http_parse_header_internal(hdr, var_name, &ab);
-
-  /*
-   * Get a (trimmed) buffer, and return a len without a NUL byte which might
-   * have been added.
-   */
-  *buf = altbuf_get_buf(&ab, 1 /* trim */);
-  return ab.len > 0 ? ab.len - 1 : 0;
-}
-
-int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
-                         size_t buf_size) {
-  char *buf2 = buf;
-
-  int len = mg_http_parse_header2(hdr, var_name, &buf2, buf_size);
-
-  if (buf2 != buf) {
-    /* Buffer was not enough and was reallocated: free it and just return 0 */
-    MG_FREE(buf2);
-    return 0;
-  }
-
-  return len;
-}
-
-int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
-                           char *pass, size_t pass_len) {
-  struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
-  if (hdr == NULL) return -1;
-  return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len);
-}
-
-int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
-                             char *pass, size_t pass_len) {
-  char *buf = NULL;
-  char fmt[64];
-  int res = 0;
-
-  if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1;
-
-  buf = (char *) MG_MALLOC(hdr->len);
-  cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL);
-
-  /* e.g. "%123[^:]:%321[^\n]" */
-  snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]",
-           user_len - 1, pass_len - 1);
-  if (sscanf(buf, fmt, user, pass) == 0) {
-    res = -1;
-  }
-
-  MG_FREE(buf);
-  return res;
-}
-
-#if MG_ENABLE_FILESYSTEM
-static int mg_is_file_hidden(const char *path,
-                             const struct mg_serve_http_opts *opts,
-                             int exclude_specials) {
-  const char *p1 = opts->per_directory_auth_file;
-  const char *p2 = opts->hidden_file_pattern;
-
-  /* Strip directory path from the file name */
-  const char *pdir = strrchr(path, DIRSEP);
-  if (pdir != NULL) {
-    path = pdir + 1;
-  }
-
-  return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) ||
-         (p1 != NULL && mg_match_prefix(p1, strlen(p1), path) == strlen(p1)) ||
-         (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
-}
-
-#if !MG_DISABLE_HTTP_DIGEST_AUTH
-
-#ifndef MG_EXT_MD5
-void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
-                   const size_t *msg_lens, uint8_t *digest) {
-  size_t i;
-  cs_md5_ctx md5_ctx;
-  cs_md5_init(&md5_ctx);
-  for (i = 0; i < num_msgs; i++) {
-    cs_md5_update(&md5_ctx, msgs[i], msg_lens[i]);
-  }
-  cs_md5_final(digest, &md5_ctx);
-}
-#else
-extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
-                          const size_t *msg_lens, uint8_t *digest);
-#endif
-
-void cs_md5(char buf[33], ...) {
-  unsigned char hash[16];
-  const uint8_t *msgs[20], *p;
-  size_t msg_lens[20];
-  size_t num_msgs = 0;
-  va_list ap;
-
-  va_start(ap, buf);
-  while ((p = va_arg(ap, const unsigned char *)) != NULL) {
-    msgs[num_msgs] = p;
-    msg_lens[num_msgs] = va_arg(ap, size_t);
-    num_msgs++;
-  }
-  va_end(ap);
-
-  mg_hash_md5_v(num_msgs, msgs, msg_lens, hash);
-  cs_to_hex(buf, hash, sizeof(hash));
-}
-
-static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri,
-                         size_t uri_len, const char *ha1, size_t ha1_len,
-                         const char *nonce, size_t nonce_len, const char *nc,
-                         size_t nc_len, const char *cnonce, size_t cnonce_len,
-                         const char *qop, size_t qop_len, char *resp) {
-  static const char colon[] = ":";
-  static const size_t one = 1;
-  char ha2[33];
-  cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
-  cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
-         nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
-         colon, one, ha2, sizeof(ha2) - 1, NULL);
-}
-
-int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
-                                      const char *method, const char *uri,
-                                      const char *auth_domain, const char *user,
-                                      const char *passwd, const char *nonce) {
-  static const char colon[] = ":", qop[] = "auth";
-  static const size_t one = 1;
-  char ha1[33], resp[33], cnonce[40];
-
-  snprintf(cnonce, sizeof(cnonce), "%lx", (unsigned long) mg_time());
-  cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
-         (size_t) strlen(auth_domain), colon, one, passwd,
-         (size_t) strlen(passwd), NULL);
-  mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
-               nonce, strlen(nonce), "1", one, cnonce, strlen(cnonce), qop,
-               sizeof(qop) - 1, resp);
-  return snprintf(buf, buf_len,
-                  "Authorization: Digest username=\"%s\","
-                  "realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
-                  "nonce=%s,response=%s\r\n",
-                  user, auth_domain, uri, qop, cnonce, nonce, resp);
-}
-
-/*
- * Check for authentication timeout.
- * Clients send time stamp encoded in nonce. Make sure it is not too old,
- * to prevent replay attacks.
- * Assumption: nonce is a hexadecimal number of seconds since 1970.
- */
-static int mg_check_nonce(const char *nonce) {
-  unsigned long now = (unsigned long) mg_time();
-  unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
-  return (now >= val) && (now - val < 60 * 60);
-}
-
-int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
-                              FILE *fp) {
-  int ret = 0;
-  struct mg_str *hdr;
-  char username_buf[50], cnonce_buf[64], response_buf[40], uri_buf[200],
-      qop_buf[20], nc_buf[20], nonce_buf[16];
-
-  char *username = username_buf, *cnonce = cnonce_buf, *response = response_buf,
-       *uri = uri_buf, *qop = qop_buf, *nc = nc_buf, *nonce = nonce_buf;
-
-  /* Parse "Authorization:" header, fail fast on parse error */
-  if (hm == NULL || fp == NULL ||
-      (hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
-      mg_http_parse_header2(hdr, "username", &username, sizeof(username_buf)) ==
-          0 ||
-      mg_http_parse_header2(hdr, "cnonce", &cnonce, sizeof(cnonce_buf)) == 0 ||
-      mg_http_parse_header2(hdr, "response", &response, sizeof(response_buf)) ==
-          0 ||
-      mg_http_parse_header2(hdr, "uri", &uri, sizeof(uri_buf)) == 0 ||
-      mg_http_parse_header2(hdr, "qop", &qop, sizeof(qop_buf)) == 0 ||
-      mg_http_parse_header2(hdr, "nc", &nc, sizeof(nc_buf)) == 0 ||
-      mg_http_parse_header2(hdr, "nonce", &nonce, sizeof(nonce_buf)) == 0 ||
-      mg_check_nonce(nonce) == 0) {
-    ret = 0;
-    goto clean;
-  }
-
-  /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
-
-  ret = mg_check_digest_auth(
-      hm->method,
-      mg_mk_str_n(
-          hm->uri.p,
-          hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0)),
-      mg_mk_str(username), mg_mk_str(cnonce), mg_mk_str(response),
-      mg_mk_str(qop), mg_mk_str(nc), mg_mk_str(nonce), mg_mk_str(auth_domain),
-      fp);
-
-clean:
-  if (username != username_buf) MG_FREE(username);
-  if (cnonce != cnonce_buf) MG_FREE(cnonce);
-  if (response != response_buf) MG_FREE(response);
-  if (uri != uri_buf) MG_FREE(uri);
-  if (qop != qop_buf) MG_FREE(qop);
-  if (nc != nc_buf) MG_FREE(nc);
-  if (nonce != nonce_buf) MG_FREE(nonce);
-
-  return ret;
-}
-
-int mg_check_digest_auth(struct mg_str method, struct mg_str uri,
-                         struct mg_str username, struct mg_str cnonce,
-                         struct mg_str response, struct mg_str qop,
-                         struct mg_str nc, struct mg_str nonce,
-                         struct mg_str auth_domain, FILE *fp) {
-  char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
-  char exp_resp[33];
-
-  /*
-   * Read passwords file line by line. If should have htdigest format,
-   * i.e. each line should be a colon-separated sequence:
-   * USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
-   */
-  while (fgets(buf, sizeof(buf), fp) != NULL) {
-    if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
-        mg_vcmp(&username, f_user) == 0 &&
-        mg_vcmp(&auth_domain, f_domain) == 0) {
-      /* Username and domain matched, check the password */
-      mg_mkmd5resp(method.p, method.len, uri.p, uri.len, f_ha1, strlen(f_ha1),
-                   nonce.p, nonce.len, nc.p, nc.len, cnonce.p, cnonce.len,
-                   qop.p, qop.len, exp_resp);
-      LOG(LL_DEBUG, ("%.*s %s %.*s %s", (int) username.len, username.p,
-                     f_domain, (int) response.len, response.p, exp_resp));
-      return mg_ncasecmp(response.p, exp_resp, strlen(exp_resp)) == 0;
-    }
-  }
-
-  /* None of the entries in the passwords file matched - return failure */
-  return 0;
-}
-
-int mg_http_is_authorized(struct http_message *hm, struct mg_str path,
-                          const char *domain, const char *passwords_file,
-                          int flags) {
-  char buf[MG_MAX_PATH];
-  const char *p;
-  FILE *fp;
-  int authorized = 1;
-
-  if (domain != NULL && passwords_file != NULL) {
-    if (flags & MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE) {
-      fp = mg_fopen(passwords_file, "r");
-    } else if (flags & MG_AUTH_FLAG_IS_DIRECTORY) {
-      snprintf(buf, sizeof(buf), "%.*s%c%s", (int) path.len, path.p, DIRSEP,
-               passwords_file);
-      fp = mg_fopen(buf, "r");
-    } else {
-      p = strrchr(path.p, DIRSEP);
-      if (p == NULL) p = path.p;
-      snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path.p), path.p, DIRSEP,
-               passwords_file);
-      fp = mg_fopen(buf, "r");
-    }
-
-    if (fp != NULL) {
-      authorized = mg_http_check_digest_auth(hm, domain, fp);
-      fclose(fp);
-    } else if (!(flags & MG_AUTH_FLAG_ALLOW_MISSING_FILE)) {
-      authorized = 0;
-    }
-  }
-
-  LOG(LL_DEBUG, ("%.*s %s %x %d", (int) path.len, path.p,
-                 passwords_file ? passwords_file : "", flags, authorized));
-  return authorized;
-}
-#else
-int mg_http_is_authorized(struct http_message *hm, const struct mg_str path,
-                          const char *domain, const char *passwords_file,
-                          int flags) {
-  (void) hm;
-  (void) path;
-  (void) domain;
-  (void) passwords_file;
-  (void) flags;
-  return 1;
-}
-#endif
-
-#if MG_ENABLE_DIRECTORY_LISTING
-static void mg_escape(const char *src, char *dst, size_t dst_len) {
-  size_t n = 0;
-  while (*src != '\0' && n + 5 < dst_len) {
-    unsigned char ch = *(unsigned char *) src++;
-    if (ch == '<') {
-      n += snprintf(dst + n, dst_len - n, "%s", "&lt;");
-    } else {
-      dst[n++] = ch;
-    }
-  }
-  dst[n] = '\0';
-}
-
-static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name,
-                               cs_stat_t *stp) {
-  char size[64], mod[64], path[MG_MAX_PATH];
-  int64_t fsize = stp->st_size;
-  int is_dir = S_ISDIR(stp->st_mode);
-  const char *slash = is_dir ? "/" : "";
-  struct mg_str href;
-
-  if (is_dir) {
-    snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
-  } else {
-    /*
-     * We use (double) cast below because MSVC 6 compiler cannot
-     * convert unsigned __int64 to double.
-     */
-    if (fsize < 1024) {
-      snprintf(size, sizeof(size), "%d", (int) fsize);
-    } else if (fsize < 0x100000) {
-      snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
-    } else if (fsize < 0x40000000) {
-      snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
-    } else {
-      snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
-    }
-  }
-  strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
-  mg_escape(file_name, path, sizeof(path));
-  href = mg_url_encode(mg_mk_str(file_name));
-  mg_printf_http_chunk(nc,
-                       "<tr><td><a href=\"%s%s\">%s%s</a></td>"
-                       "<td>%s</td><td name=\"%" INT64_FMT "\">%s</td></tr>",
-                       href.p, slash, path, slash, mod, is_dir ? -1 : fsize,
-                       size);
-  free((void *) href.p);
-}
-
-static void mg_scan_directory(struct mg_connection *nc, const char *dir,
-                              const struct mg_serve_http_opts *opts,
-                              void (*func)(struct mg_connection *, const char *,
-                                           cs_stat_t *)) {
-  char path[MG_MAX_PATH + 1];
-  cs_stat_t st;
-  struct dirent *dp;
-  DIR *dirp;
-
-  LOG(LL_DEBUG, ("%p [%s]", (void*)nc, dir));
-  if ((dirp = (opendir(dir))) != NULL) {
-    while ((dp = readdir(dirp)) != NULL) {
-      /* Do not show current dir and hidden files */
-      if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
-        continue;
-      }
-      snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
-      if (mg_stat(path, &st) == 0) {
-        func(nc, (const char *) dp->d_name, &st);
-      }
-    }
-    closedir(dirp);
-  } else {
-    LOG(LL_DEBUG, ("%p opendir(%s) -> %d", (void*)nc, dir, mg_get_errno()));
-  }
-}
-
-static void mg_send_directory_listing(struct mg_connection *nc, const char *dir,
-                                      struct http_message *hm,
-                                      struct mg_serve_http_opts *opts) {
-  static const char *sort_js_code =
-      "<script>function srt(tb, sc, so, d) {"
-      "var tr = Array.prototype.slice.call(tb.rows, 0),"
-      "tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
-      "n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
-      "t1 = a.cells[2].getAttribute('name'), "
-      "t2 = b.cells[2].getAttribute('name'); "
-      "return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
-      "n1 ? parseInt(n2) - parseInt(n1) : "
-      "c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
-  static const char *sort_js_code2 =
-      "for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
-      "if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
-      "};"
-      "window.onload = function() {"
-      "var tb = document.getElementById('tb');"
-      "var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
-      "var sc = m[1], so = m[2]; document.onclick = function(ev) { "
-      "var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
-      "sc = c; ev.preventDefault();}};"
-      "srt(tb, sc, so, true);"
-      "}"
-      "</script>";
-
-  mg_send_response_line(nc, 200, opts->extra_headers);
-  mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked",
-            "Content-Type", "text/html; charset=utf-8");
-
-  mg_printf_http_chunk(
-      nc,
-      "<!DOCTYPE html><html><head><title>Index of %.*s</title>%s%s"
-      "<style>th,td {text-align: left; padding-right: 1em; "
-      "font-family: monospace; }</style></head>"
-      "<body><h1>Index of %.*s</h1><table cellpadding=\"0\"><thead>"
-      "<tr><th><a href=\"#\" rel=\"0\">Name</a></th><th>"
-      "<a href=\"#\" rel=\"1\">Modified</a></th>"
-      "<th><a href=\"#\" rel=\"2\">Size</a></th></tr>"
-      "<tr><td colspan=\"3\"><hr></td></tr>"
-      "</thead>"
-      "<tbody id=\"tb\">",
-      (int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
-      (int) hm->uri.len, hm->uri.p);
-  mg_scan_directory(nc, dir, opts, mg_print_dir_entry);
-  mg_printf_http_chunk(nc,
-                       "</tbody>"
-                       "<tfoot><tr><td colspan=\"3\"><hr></td></tr></tfoot>"
-                       "</table>"
-                       "<address>%s</address>"
-                       "</body></html>",
-                       mg_version_header);
-  mg_send_http_chunk(nc, "", 0);
-  /* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
-  nc->flags |= MG_F_SEND_AND_CLOSE;
-}
-#endif /* MG_ENABLE_DIRECTORY_LISTING */
-
-/*
- * Given a directory path, find one of the files specified in the
- * comma-separated list of index files `list`.
- * First found index file wins. If an index file is found, then gets
- * appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
- * If index file is not found, then `path` and `stp` remain unchanged.
- */
-MG_INTERNAL void mg_find_index_file(const char *path, const char *list,
-                                    char **index_file, cs_stat_t *stp) {
-  struct mg_str vec;
-  size_t path_len = strlen(path);
-  int found = 0;
-  *index_file = NULL;
-
-  /* Traverse index files list. For each entry, append it to the given */
-  /* path and see if the file exists. If it exists, break the loop */
-  while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
-    cs_stat_t st;
-    size_t len = path_len + 1 + vec.len + 1;
-    *index_file = (char *) MG_REALLOC(*index_file, len);
-    if (*index_file == NULL) break;
-    snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p);
-
-    /* Does it exist? Is it a file? */
-    if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
-      /* Yes it does, break the loop */
-      *stp = st;
-      found = 1;
-      break;
-    }
-  }
-  if (!found) {
-    MG_FREE(*index_file);
-    *index_file = NULL;
-  }
-  LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : "")));
-}
-
-#if MG_ENABLE_HTTP_URL_REWRITES
-static int mg_http_send_port_based_redirect(
-    struct mg_connection *c, struct http_message *hm,
-    const struct mg_serve_http_opts *opts) {
-  const char *rewrites = opts->url_rewrites;
-  struct mg_str a, b;
-  char local_port[20] = {'%'};
-
-  mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
-                      MG_SOCK_STRINGIFY_PORT);
-
-  while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
-    if (mg_vcmp(&a, local_port) == 0) {
-      mg_send_response_line(c, 301, NULL);
-      mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
-                (int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
-                hm->uri.p);
-      return 1;
-    }
-  }
-
-  return 0;
-}
-
-static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev,
-                                     void *ev_data MG_UD_ARG(void *user_data)) {
-  struct http_message *hm = (struct http_message *) ev_data;
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
-
-  if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) {
-    DBG(("%p: upstream closed", (void*)nc));
-    return;
-  }
-
-  switch (ev) {
-    case MG_EV_CONNECT:
-      if (*(int *) ev_data != 0) {
-        mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL);
-      }
-      break;
-    /* TODO(mkm): handle streaming */
-    case MG_EV_HTTP_REPLY:
-      mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p,
-              hm->message.len);
-      pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
-      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-      break;
-    case MG_EV_CLOSE:
-      pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
-      break;
-  }
-
-#if MG_ENABLE_CALLBACK_USERDATA
-  (void) user_data;
-#endif
-}
-
-void mg_http_reverse_proxy(struct mg_connection *nc,
-                           const struct http_message *hm, struct mg_str mount,
-                           struct mg_str upstream) {
-  struct mg_connection *be;
-  char burl[256], *purl = burl;
-  int i;
-  const char *error;
-  struct mg_connect_opts opts;
-  struct mg_str path = MG_NULL_STR, user_info = MG_NULL_STR, host = MG_NULL_STR;
-  memset(&opts, 0, sizeof(opts));
-  opts.error_string = &error;
-
-  mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p,
-              (int) (hm->uri.len - mount.len), hm->uri.p + mount.len);
-
-  be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL),
-                            opts, "http", NULL, "https", NULL, purl, &path,
-                            &user_info, &host);
-  LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len,
-                 hm->uri.p, purl, (int) mount.len, mount.p));
-
-  if (be == NULL) {
-    LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error));
-    mg_http_send_error(nc, 502, NULL);
-    goto cleanup;
-  }
-
-  /* link connections to each other, they must live and die together */
-  mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc;
-  mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be;
-
-  /* send request upstream */
-  mg_printf(be, "%.*s %.*s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p,
-            (int) path.len, path.p);
-
-  mg_printf(be, "Host: %.*s\r\n", (int) host.len, host.p);
-  for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) {
-    struct mg_str hn = hm->header_names[i];
-    struct mg_str hv = hm->header_values[i];
-
-    /* we rewrite the host header */
-    if (mg_vcasecmp(&hn, "Host") == 0) continue;
-    /*
-     * Don't pass chunked transfer encoding to the client because hm->body is
-     * already dechunked when we arrive here.
-     */
-    if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 &&
-        mg_vcasecmp(&hv, "chunked") == 0) {
-      mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len);
-      continue;
-    }
-    /* We don't support proxying Expect: 100-continue. */
-    if (mg_vcasecmp(&hn, "Expect") == 0 &&
-        mg_vcasecmp(&hv, "100-continue") == 0) {
-      continue;
-    }
-
-    mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p);
-  }
-
-  mg_send(be, "\r\n", 2);
-  mg_send(be, hm->body.p, hm->body.len);
-
-cleanup:
-  if (purl != burl) MG_FREE(purl);
-}
-
-static int mg_http_handle_forwarding(struct mg_connection *nc,
-                                     struct http_message *hm,
-                                     const struct mg_serve_http_opts *opts) {
-  const char *rewrites = opts->url_rewrites;
-  struct mg_str a, b;
-  struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://");
-
-  while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
-    if (mg_strncmp(a, hm->uri, a.len) == 0) {
-      if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) {
-        mg_http_reverse_proxy(nc, hm, a, b);
-        return 1;
-      }
-    }
-  }
-
-  return 0;
-}
-#endif /* MG_ENABLE_FILESYSTEM */
-
-MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
-                                     const struct mg_serve_http_opts *opts,
-                                     char **local_path,
-                                     struct mg_str *remainder) {
-  int ok = 1;
-  const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len;
-  struct mg_str root = {NULL, 0};
-  const char *file_uri_start = cp;
-  *local_path = NULL;
-  remainder->p = NULL;
-  remainder->len = 0;
-
-  { /* 1. Determine which root to use. */
-
-#if MG_ENABLE_HTTP_URL_REWRITES
-    const char *rewrites = opts->url_rewrites;
-#else
-    const char *rewrites = "";
-#endif
-    struct mg_str *hh = mg_get_http_header(hm, "Host");
-    struct mg_str a, b;
-    /* Check rewrites first. */
-    while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
-      if (a.len > 1 && a.p[0] == '@') {
-        /* Host rewrite. */
-        if (hh != NULL && hh->len == a.len - 1 &&
-            mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) {
-          root = b;
-          break;
-        }
-      } else {
-        /* Regular rewrite, URI=directory */
-        size_t match_len = mg_match_prefix_n(a, hm->uri);
-        if (match_len > 0) {
-          file_uri_start = hm->uri.p + match_len;
-          if (*file_uri_start == '/' || file_uri_start == cp_end) {
-            /* Match ended at component boundary, ok. */
-          } else if (*(file_uri_start - 1) == '/') {
-            /* Pattern ends with '/', backtrack. */
-            file_uri_start--;
-          } else {
-            /* No match: must fall on the component boundary. */
-            continue;
-          }
-          root = b;
-          break;
-        }
-      }
-    }
-    /* If no rewrite rules matched, use DAV or regular document root. */
-    if (root.p == NULL) {
-#if MG_ENABLE_HTTP_WEBDAV
-      if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) {
-        root.p = opts->dav_document_root;
-        root.len = strlen(opts->dav_document_root);
-      } else
-#endif
-      {
-        root.p = opts->document_root;
-        root.len = strlen(opts->document_root);
-      }
-    }
-    assert(root.p != NULL && root.len > 0);
-  }
-
-  { /* 2. Find where in the canonical URI path the local path ends. */
-    const char *u = file_uri_start + 1;
-    char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1);
-    char *lp_end = lp + root.len + hm->uri.len + 1;
-    char *p = lp, *ps;
-    int exists = 1;
-    if (lp == NULL) {
-      ok = 0;
-      goto out;
-    }
-    memcpy(p, root.p, root.len);
-    p += root.len;
-    if (*(p - 1) == DIRSEP) p--;
-    *p = '\0';
-    ps = p;
-
-    /* Chop off URI path components one by one and build local path. */
-    while (u <= cp_end) {
-      const char *next = u;
-      struct mg_str component;
-      if (exists) {
-        cs_stat_t st;
-        exists = (mg_stat(lp, &st) == 0);
-        if (exists && S_ISREG(st.st_mode)) {
-          /* We found the terminal, the rest of the URI (if any) is path_info.
-           */
-          if (*(u - 1) == '/') u--;
-          break;
-        }
-      }
-      if (u >= cp_end) break;
-      parse_uri_component((const char **) &next, cp_end, "/", &component);
-      if (component.len > 0) {
-        int len;
-        memmove(p + 1, component.p, component.len);
-        len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0);
-        if (len <= 0) {
-          ok = 0;
-          break;
-        }
-        component.p = p + 1;
-        component.len = len;
-        if (mg_vcmp(&component, ".") == 0) {
-          /* Yum. */
-        } else if (mg_vcmp(&component, "..") == 0) {
-          while (p > ps && *p != DIRSEP) p--;
-          *p = '\0';
-        } else {
-          size_t i;
-#ifdef _WIN32
-          /* On Windows, make sure it's valid Unicode (no funny stuff). */
-          wchar_t buf[MG_MAX_PATH * 2];
-          if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) {
-            DBG(("[%.*s] smells funny", (int) component.len, component.p));
-            ok = 0;
-            break;
-          }
-#endif
-          *p++ = DIRSEP;
-          /* No NULs and DIRSEPs in the component (percent-encoded). */
-          for (i = 0; i < component.len; i++, p++) {
-            if (*p == '\0' ||
-                *p == DIRSEP
-#ifdef _WIN32
-                /* On Windows, "/" is also accepted, so check for that too. */
-                || *p == '/'
-#endif
-            ) {
-              ok = 0;
-              break;
-            }
-          }
-        }
-      }
-      u = next;
-    }
-    if (ok) {
-      *local_path = lp;
-      if (u > cp_end) u = cp_end;
-      remainder->p = u;
-      remainder->len = cp_end - u;
-    } else {
-      MG_FREE(lp);
-    }
-  }
-
-out:
-  LOG(LL_DEBUG,
-      ("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p,
-       *local_path ? *local_path : "", (int) remainder->len, remainder->p));
-  return ok;
-}
-
-static int mg_get_month_index(const char *s) {
-  static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
-                                      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
-  size_t i;
-
-  for (i = 0; i < ARRAY_SIZE(month_names); i++)
-    if (!strcmp(s, month_names[i])) return (int) i;
-
-  return -1;
-}
-
-static int mg_num_leap_years(int year) {
-  return year / 4 - year / 100 + year / 400;
-}
-
-/* Parse UTC date-time string, and return the corresponding time_t value. */
-MG_INTERNAL time_t mg_parse_date_string(const char *datetime) {
-  static const unsigned short days_before_month[] = {
-      0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
-  char month_str[32];
-  int second, minute, hour, day, month, year, leap_days, days;
-  time_t result = (time_t) 0;
-
-  if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
-               &minute, &second) == 6) ||
-       (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
-               &minute, &second) == 6) ||
-       (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
-               &hour, &minute, &second) == 6) ||
-       (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
-               &minute, &second) == 6)) &&
-      year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
-    leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970);
-    year -= 1970;
-    days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
-    result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
-  }
-
-  return result;
-}
-
-MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) {
-  struct mg_str *hdr;
-  if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
-    char etag[64];
-    mg_http_construct_etag(etag, sizeof(etag), st);
-    return mg_vcasecmp(hdr, etag) == 0;
-  } else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
-    return st->st_mtime <= mg_parse_date_string(hdr->p);
-  } else {
-    return 0;
-  }
-}
-
-void mg_http_send_digest_auth_request(struct mg_connection *c,
-                                      const char *domain) {
-  mg_printf(c,
-            "HTTP/1.1 401 Unauthorized\r\n"
-            "WWW-Authenticate: Digest qop=\"auth\", "
-            "realm=\"%s\", nonce=\"%lx\"\r\n"
-            "Content-Length: 0\r\n\r\n",
-            domain, (unsigned long) mg_time());
-}
-
-static void mg_http_send_options(struct mg_connection *nc,
-                                 struct mg_serve_http_opts *opts) {
-  mg_send_response_line(nc, 200, opts->extra_headers);
-  mg_printf(nc, "%s",
-            "Allow: GET, POST, HEAD, CONNECT, OPTIONS"
-#if MG_ENABLE_HTTP_WEBDAV
-            ", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
-#endif
-            "\r\n\r\n");
-  nc->flags |= MG_F_SEND_AND_CLOSE;
-}
-
-static int mg_is_creation_request(const struct http_message *hm) {
-  return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0;
-}
-
-MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path,
-                                   const struct mg_str *path_info,
-                                   struct http_message *hm,
-                                   struct mg_serve_http_opts *opts) {
-  int exists, is_directory, is_cgi;
-#if MG_ENABLE_HTTP_WEBDAV
-  int is_dav = mg_is_dav_request(&hm->method);
-#else
-  int is_dav = 0;
-#endif
-  char *index_file = NULL;
-  cs_stat_t st;
-
-  exists = (mg_stat(path, &st) == 0);
-  is_directory = exists && S_ISDIR(st.st_mode);
-
-  if (is_directory)
-    mg_find_index_file(path, opts->index_files, &index_file, &st);
-
-  is_cgi =
-      (mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
-                       index_file ? index_file : path) > 0);
-
-  LOG(LL_DEBUG,
-      ("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", (void*)nc,
-       (int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav,
-       is_cgi, index_file ? index_file : ""));
-
-  if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) {
-    mg_printf(nc,
-              "HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
-              "Content-Length: 0\r\n\r\n",
-              (int) hm->uri.len, hm->uri.p);
-    MG_FREE(index_file);
-    return;
-  }
-
-  /* If we have path_info, the only way to handle it is CGI. */
-  if (path_info->len > 0 && !is_cgi) {
-    mg_http_send_error(nc, 501, NULL);
-    MG_FREE(index_file);
-    return;
-  }
-
-  if (is_dav && opts->dav_document_root == NULL) {
-    mg_http_send_error(nc, 501, NULL);
-  } else if (!mg_http_is_authorized(
-                 hm, mg_mk_str(path), opts->auth_domain, opts->global_auth_file,
-                 ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
-                  MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE |
-                  MG_AUTH_FLAG_ALLOW_MISSING_FILE)) ||
-             !mg_http_is_authorized(
-                 hm, mg_mk_str(path), opts->auth_domain,
-                 opts->per_directory_auth_file,
-                 ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
-                  MG_AUTH_FLAG_ALLOW_MISSING_FILE))) {
-    mg_http_send_digest_auth_request(nc, opts->auth_domain);
-  } else if (is_cgi) {
-#if MG_ENABLE_HTTP_CGI
-    mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
-#else
-    mg_http_send_error(nc, 501, NULL);
-#endif /* MG_ENABLE_HTTP_CGI */
-  } else if ((!exists ||
-              mg_is_file_hidden(path, opts, 0 /* specials are ok */)) &&
-             !mg_is_creation_request(hm)) {
-    mg_http_send_error(nc, 404, NULL);
-#if MG_ENABLE_HTTP_WEBDAV
-  } else if (!mg_vcmp(&hm->method, "PROPFIND")) {
-    mg_handle_propfind(nc, path, &st, hm, opts);
-#if !MG_DISABLE_DAV_AUTH
-  } else if (is_dav &&
-             (opts->dav_auth_file == NULL ||
-              (strcmp(opts->dav_auth_file, "-") != 0 &&
-               !mg_http_is_authorized(
-                   hm, mg_mk_str(path), opts->auth_domain, opts->dav_auth_file,
-                   ((is_directory ? MG_AUTH_FLAG_IS_DIRECTORY : 0) |
-                    MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE |
-                    MG_AUTH_FLAG_ALLOW_MISSING_FILE))))) {
-    mg_http_send_digest_auth_request(nc, opts->auth_domain);
-#endif
-  } else if (!mg_vcmp(&hm->method, "MKCOL")) {
-    mg_handle_mkcol(nc, path, hm);
-  } else if (!mg_vcmp(&hm->method, "DELETE")) {
-    mg_handle_delete(nc, opts, path);
-  } else if (!mg_vcmp(&hm->method, "PUT")) {
-    mg_handle_put(nc, path, hm);
-  } else if (!mg_vcmp(&hm->method, "MOVE")) {
-    mg_handle_move(nc, opts, path, hm);
-#if MG_ENABLE_FAKE_DAVLOCK
-  } else if (!mg_vcmp(&hm->method, "LOCK")) {
-    mg_handle_lock(nc, path);
-#endif
-#endif /* MG_ENABLE_HTTP_WEBDAV */
-  } else if (!mg_vcmp(&hm->method, "OPTIONS")) {
-    mg_http_send_options(nc, opts);
-  } else if (is_directory && index_file == NULL) {
-#if MG_ENABLE_DIRECTORY_LISTING
-    if (strcmp(opts->enable_directory_listing, "yes") == 0) {
-      mg_send_directory_listing(nc, path, hm, opts);
-    } else {
-      mg_http_send_error(nc, 403, NULL);
-    }
-#else
-    mg_http_send_error(nc, 501, NULL);
-#endif
-  } else if (mg_is_not_modified(hm, &st)) {
-    /* Note: not using mg_http_send_error in order to keep connection alive */
-    /* Note: passing extra headers allow users to control session cookies */
-    mg_send_head(nc, 304, 0, opts->extra_headers);
-  } else {
-    mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts);
-  }
-  MG_FREE(index_file);
-}
-
-void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
-                   struct mg_serve_http_opts opts) {
-  char *path = NULL;
-  struct mg_str *hdr, path_info;
-  uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
-
-  if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) {
-    /* Not allowed to connect */
-    mg_http_send_error(nc, 403, NULL);
-    nc->flags |= MG_F_SEND_AND_CLOSE;
-    return;
-  }
-
-#if MG_ENABLE_HTTP_URL_REWRITES
-  if (mg_http_handle_forwarding(nc, hm, &opts)) {
-    return;
-  }
-
-  if (mg_http_send_port_based_redirect(nc, hm, &opts)) {
-    return;
-  }
-#endif
-
-  if (opts.document_root == NULL) {
-    opts.document_root = ".";
-  }
-  if (opts.per_directory_auth_file == NULL) {
-    opts.per_directory_auth_file = ".htpasswd";
-  }
-  if (opts.enable_directory_listing == NULL) {
-    opts.enable_directory_listing = "yes";
-  }
-  if (opts.cgi_file_pattern == NULL) {
-    opts.cgi_file_pattern = "**.cgi$|**.php$";
-  }
-  if (opts.ssi_pattern == NULL) {
-    opts.ssi_pattern = "**.shtml$|**.shtm$";
-  }
-  if (opts.index_files == NULL) {
-    opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
-  }
-  /* Normalize path - resolve "." and ".." (in-place). */
-  if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
-    mg_http_send_error(nc, 400, NULL);
-    return;
-  }
-  if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) {
-    mg_http_send_error(nc, 404, NULL);
-    return;
-  }
-  mg_send_http_file(nc, path, &path_info, hm, &opts);
-
-  MG_FREE(path);
-  path = NULL;
-
-  /* Close connection for non-keep-alive requests */
-  if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
-      ((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
-       mg_vcmp(hdr, "keep-alive") != 0)) {
-#if 0
-    nc->flags |= MG_F_SEND_AND_CLOSE;
-#endif
-  }
-}
-
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
-                            mg_fu_fname_fn local_name_fn
-                                MG_UD_ARG(void *user_data)) {
-  switch (ev) {
-    case MG_EV_HTTP_PART_BEGIN: {
-      struct mg_http_multipart_part *mp =
-          (struct mg_http_multipart_part *) ev_data;
-      struct file_upload_state *fus;
-      struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
-      mp->user_data = NULL;
-      if (lfn.p == NULL || lfn.len == 0) {
-        LOG(LL_ERROR, ("%p Not allowed to upload %s", (void*)nc, mp->file_name));
-        mg_printf(nc,
-                  "HTTP/1.1 403 Not Allowed\r\n"
-                  "Content-Type: text/plain\r\n"
-                  "Connection: close\r\n\r\n"
-                  "Not allowed to upload %s\r\n",
-                  mp->file_name);
-        nc->flags |= MG_F_SEND_AND_CLOSE;
-        return;
-      }
-      fus = (struct file_upload_state *) MG_CALLOC(1, sizeof(*fus));
-      if (fus == NULL) {
-        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-        return;
-      }
-      fus->lfn = (char *) MG_MALLOC(lfn.len + 1);
-      memcpy(fus->lfn, lfn.p, lfn.len);
-      fus->lfn[lfn.len] = '\0';
-      if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p);
-      LOG(LL_DEBUG,
-          ("%p Receiving file %s -> %s", (void*)nc, mp->file_name, fus->lfn));
-      fus->fp = mg_fopen(fus->lfn, "wb");
-      if (fus->fp == NULL) {
-        mg_printf(nc,
-                  "HTTP/1.1 500 Internal Server Error\r\n"
-                  "Content-Type: text/plain\r\n"
-                  "Connection: close\r\n\r\n");
-        LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno()));
-        mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno());
-        /* Do not close the connection just yet, discard remainder of the data.
-         * This is because at the time of writing some browsers (Chrome) fail to
-         * render response before all the data is sent. */
-      }
-      mp->user_data = (void *) fus;
-      break;
-    }
-    case MG_EV_HTTP_PART_DATA: {
-      struct mg_http_multipart_part *mp =
-          (struct mg_http_multipart_part *) ev_data;
-      struct file_upload_state *fus =
-          (struct file_upload_state *) mp->user_data;
-      if (fus == NULL || fus->fp == NULL) break;
-      if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) {
-        LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn,
-                       mg_get_errno(), (int) fus->num_recd));
-        if (mg_get_errno() == ENOSPC
-#ifdef SPIFFS_ERR_FULL
-            || mg_get_errno() == SPIFFS_ERR_FULL
-#endif
-        ) {
-          mg_printf(nc,
-                    "HTTP/1.1 413 Payload Too Large\r\n"
-                    "Content-Type: text/plain\r\n"
-                    "Connection: close\r\n\r\n");
-          mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n",
-                    fus->lfn, (int) fus->num_recd);
-        } else {
-          mg_printf(nc,
-                    "HTTP/1.1 500 Internal Server Error\r\n"
-                    "Content-Type: text/plain\r\n"
-                    "Connection: close\r\n\r\n");
-          mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name,
-                    mg_get_errno(), (int) fus->num_recd);
-        }
-        fclose(fus->fp);
-        remove(fus->lfn);
-        fus->fp = NULL;
-        /* Do not close the connection just yet, discard remainder of the data.
-         * This is because at the time of writing some browsers (Chrome) fail to
-         * render response before all the data is sent. */
-        return;
-      }
-      fus->num_recd += mp->data.len;
-      LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", (void*)nc, (int) mp->data.len,
-                     (int) fus->num_recd));
-      break;
-    }
-    case MG_EV_HTTP_PART_END: {
-      struct mg_http_multipart_part *mp =
-          (struct mg_http_multipart_part *) ev_data;
-      struct file_upload_state *fus =
-          (struct file_upload_state *) mp->user_data;
-      if (fus == NULL) break;
-      if (mp->status >= 0 && fus->fp != NULL) {
-        LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", (void*)nc, mp->file_name,
-                       fus->lfn, (int) fus->num_recd));
-      } else {
-        LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn));
-        /*
-         * mp->status < 0 means connection was terminated, so no reason to send
-         * HTTP reply
-         */
-      }
-      if (fus->fp != NULL) fclose(fus->fp);
-      MG_FREE(fus->lfn);
-      MG_FREE(fus);
-      mp->user_data = NULL;
-      /* Don't close the connection yet, there may be more files to come. */
-      break;
-    }
-    case MG_EV_HTTP_MULTIPART_REQUEST_END: {
-      mg_printf(nc,
-                "HTTP/1.1 200 OK\r\n"
-                "Content-Type: text/plain\r\n"
-                "Connection: close\r\n\r\n"
-                "Ok.\r\n");
-      nc->flags |= MG_F_SEND_AND_CLOSE;
-      break;
-    }
-  }
-
-#if MG_ENABLE_CALLBACK_USERDATA
-  (void) user_data;
-#endif
-}
-
-#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
-#endif /* MG_ENABLE_FILESYSTEM */
-
-struct mg_connection *mg_connect_http_base(
-    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
-    struct mg_connect_opts opts, const char *scheme1, const char *scheme2,
-    const char *scheme_ssl1, const char *scheme_ssl2, const char *url,
-    struct mg_str *path, struct mg_str *user_info, struct mg_str *host) {
-  struct mg_connection *nc = NULL;
-  unsigned int port_i = 0;
-  int use_ssl = 0;
-  struct mg_str scheme, query, fragment;
-  char conn_addr_buf[2];
-  char *conn_addr = conn_addr_buf;
-
-  if (mg_parse_uri(mg_mk_str(url), &scheme, user_info, host, &port_i, path,
-                   &query, &fragment) != 0) {
-    MG_SET_PTRPTR(opts.error_string, "cannot parse url");
-    goto out;
-  }
-
-  /* If query is present, do not strip it. Pass to the caller. */
-  if (query.len > 0) path->len += query.len + 1;
-
-  if (scheme.len == 0 || mg_vcmp(&scheme, scheme1) == 0 ||
-      (scheme2 != NULL && mg_vcmp(&scheme, scheme2) == 0)) {
-    use_ssl = 0;
-    if (port_i == 0) port_i = 80;
-  } else if (mg_vcmp(&scheme, scheme_ssl1) == 0 ||
-             (scheme2 != NULL && mg_vcmp(&scheme, scheme_ssl2) == 0)) {
-    use_ssl = 1;
-    if (port_i == 0) port_i = 443;
-  } else {
-    goto out;
-  }
-
-  mg_asprintf(&conn_addr, sizeof(conn_addr_buf), "tcp://%.*s:%u",
-              (int) host->len, host->p, port_i);
-  if (conn_addr == NULL) goto out;
-
-  LOG(LL_DEBUG, ("%s use_ssl? %d %s", url, use_ssl, conn_addr));
-  if (use_ssl) {
-#if MG_ENABLE_SSL
-    /*
-     * Schema requires SSL, but no SSL parameters were provided in opts.
-     * In order to maintain backward compatibility, use a faux-SSL with no
-     * verification.
-     */
-    if (opts.ssl_ca_cert == NULL) {
-      opts.ssl_ca_cert = "*";
-    }
-#else
-    MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
-    goto out;
-#endif
-  }
-
-  if ((nc = mg_connect_opt(mgr, conn_addr, MG_CB(ev_handler, user_data),
-                           opts)) != NULL) {
-    mg_set_protocol_http_websocket(nc);
-  }
-
-out:
-  if (conn_addr != NULL && conn_addr != conn_addr_buf) MG_FREE(conn_addr);
-  return nc;
-}
-
-struct mg_connection *mg_connect_http_opt(
-    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
-    struct mg_connect_opts opts, const char *url, const char *extra_headers,
-    const char *post_data) {
-  struct mg_str user = MG_NULL_STR, null_str = MG_NULL_STR;
-  struct mg_str host = MG_NULL_STR, path = MG_NULL_STR;
-  struct mbuf auth;
-  struct mg_connection *nc =
-      mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
-                           NULL, "https", NULL, url, &path, &user, &host);
-
-  if (nc == NULL) {
-    return NULL;
-  }
-
-  mbuf_init(&auth, 0);
-  if (user.len > 0) {
-    mg_basic_auth_header(user, null_str, &auth);
-  }
-
-  if (post_data == NULL) post_data = "";
-  if (extra_headers == NULL) extra_headers = "";
-  if (path.len == 0) path = mg_mk_str("/");
-  if (host.len == 0) host = mg_mk_str("");
-
-  mg_printf(nc,
-            "%s %.*s HTTP/1.1\r\nHost: %.*s\r\nContent-Length: %" SIZE_T_FMT
-            "\r\n%.*s%s\r\n%s",
-            (post_data[0] == '\0' ? "GET" : "POST"), (int) path.len, path.p,
-            (int) (path.p - host.p), host.p, strlen(post_data), (int) auth.len,
-            (auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
-
-  mbuf_free(&auth);
-  return nc;
-}
-
-struct mg_connection *mg_connect_http(
-    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
-    const char *url, const char *extra_headers, const char *post_data) {
-  struct mg_connect_opts opts;
-  memset(&opts, 0, sizeof(opts));
-  return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
-                             extra_headers, post_data);
-}
-
-size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
-                          size_t var_name_len, char *file_name,
-                          size_t file_name_len, const char **data,
-                          size_t *data_len) {
-  static const char cd[] = "Content-Disposition: ";
-  size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
-  int shl;
-
-  if (buf == NULL || buf_len <= 0) return 0;
-  if ((shl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
-  hl = shl;
-  if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
-
-  /* Get boundary length */
-  bl = mg_get_line_len(buf, buf_len);
-
-  /* Loop through headers, fetch variable name and file name */
-  var_name[0] = file_name[0] = '\0';
-  for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
-    if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
-      struct mg_str header;
-      header.p = buf + n + cdl;
-      header.len = ll - (cdl + 2);
-      {
-        char *var_name2 = var_name;
-        mg_http_parse_header2(&header, "name", &var_name2, var_name_len);
-        /* TODO: handle reallocated buffer correctly */
-        if (var_name2 != var_name) {
-          MG_FREE(var_name2);
-          var_name[0] = '\0';
-        }
-      }
-      {
-        char *file_name2 = file_name;
-        mg_http_parse_header2(&header, "filename", &file_name2, file_name_len);
-        /* TODO: handle reallocated buffer correctly */
-        if (file_name2 != file_name) {
-          MG_FREE(file_name2);
-          file_name[0] = '\0';
-        }
-      }
-    }
-  }
-
-  /* Scan through the body, search for terminating boundary */
-  for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
-    if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) {
-      if (data_len != NULL) *data_len = (pos - 2) - hl;
-      if (data != NULL) *data = buf + hl;
-      return pos;
-    }
-  }
-
-  return 0;
-}
-
-void mg_register_http_endpoint_opt(struct mg_connection *nc,
-                                   const char *uri_path,
-                                   mg_event_handler_t handler,
-                                   struct mg_http_endpoint_opts opts) {
-  struct mg_http_proto_data *pd = NULL;
-  struct mg_http_endpoint *new_ep = NULL;
-
-  if (nc == NULL) return;
-  new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep));
-  if (new_ep == NULL) return;
-
-  pd = mg_http_get_proto_data(nc);
-  if (pd == NULL) pd = mg_http_create_proto_data(nc);
-  new_ep->uri_pattern = mg_strdup(mg_mk_str(uri_path));
-  if (opts.auth_domain != NULL && opts.auth_file != NULL) {
-    new_ep->auth_domain = strdup(opts.auth_domain);
-    new_ep->auth_file = strdup(opts.auth_file);
-  }
-  new_ep->handler = handler;
-#if MG_ENABLE_CALLBACK_USERDATA
-  new_ep->user_data = opts.user_data;
-#endif
-  new_ep->next = pd->endpoints;
-  pd->endpoints = new_ep;
-}
-
-static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
-                                          struct http_message *hm) {
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
-  void *user_data = nc->user_data;
-
-  if (ev == MG_EV_HTTP_REQUEST
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-      || ev == MG_EV_HTTP_MULTIPART_REQUEST
-#endif
-  ) {
-    struct mg_http_endpoint *ep =
-        mg_http_get_endpoint_handler(nc->listener, &hm->uri);
-    if (ep != NULL) {
-#if MG_ENABLE_FILESYSTEM && !MG_DISABLE_HTTP_DIGEST_AUTH
-      if (!mg_http_is_authorized(hm, hm->uri, ep->auth_domain, ep->auth_file,
-                                 MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE)) {
-        mg_http_send_digest_auth_request(nc, ep->auth_domain);
-        return;
-      }
-#endif
-      pd->endpoint_handler = ep->handler;
-#if MG_ENABLE_CALLBACK_USERDATA
-      user_data = ep->user_data;
-#endif
-    }
-  }
-  mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler,
-          user_data, ev, hm);
-}
-
-void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
-                               MG_CB(mg_event_handler_t handler,
-                                     void *user_data)) {
-  struct mg_http_endpoint_opts opts;
-  memset(&opts, 0, sizeof(opts));
-#if MG_ENABLE_CALLBACK_USERDATA
-  opts.user_data = user_data;
-#endif
-  mg_register_http_endpoint_opt(nc, uri_path, handler, opts);
-}
-
-#endif /* MG_ENABLE_HTTP */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_http_cgi.c"
-#endif
-
-#ifndef _WIN32
-#include <signal.h>
-#endif
-
-#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
-
-#ifndef MG_MAX_CGI_ENVIR_VARS
-#define MG_MAX_CGI_ENVIR_VARS 64
-#endif
-
-#ifndef MG_ENV_EXPORT_TO_CGI
-#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
-#endif
-
-#define MG_F_HTTP_CGI_PARSE_HEADERS MG_F_USER_1
-
-/*
- * This structure helps to create an environment for the spawned CGI program.
- * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
- * last element must be NULL.
- * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
- * strings must reside in a contiguous buffer. The end of the buffer is
- * marked by two '\0' characters.
- * We satisfy both worlds: we create an envp array (which is vars), all
- * entries are actually pointers inside buf.
- */
-struct mg_cgi_env_block {
-  struct mg_connection *nc;
-  char buf[MG_CGI_ENVIRONMENT_SIZE];       /* Environment buffer */
-  const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
-  int len;                                 /* Space taken */
-  int nvars;                               /* Number of variables in envp[] */
-};
-
-#ifdef _WIN32
-struct mg_threadparam {
-  sock_t s;
-  HANDLE hPipe;
-};
-
-static int mg_wait_until_ready(sock_t sock, int for_read) {
-  fd_set set;
-  FD_ZERO(&set);
-  FD_SET(sock, &set);
-  return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
-}
-
-static void *mg_push_to_stdin(void *arg) {
-  struct mg_threadparam *tp = (struct mg_threadparam *) arg;
-  int n, sent, stop = 0;
-  DWORD k;
-  char buf[BUFSIZ];
-
-  while (!stop && mg_wait_until_ready(tp->s, 1) &&
-         (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
-    if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
-    for (sent = 0; !stop && sent < n; sent += k) {
-      if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
-    }
-  }
-  DBG(("%s", "FORWARED EVERYTHING TO CGI"));
-  CloseHandle(tp->hPipe);
-  MG_FREE(tp);
-  return NULL;
-}
-
-static void *mg_pull_from_stdout(void *arg) {
-  struct mg_threadparam *tp = (struct mg_threadparam *) arg;
-  int k = 0, stop = 0;
-  DWORD n, sent;
-  char buf[BUFSIZ];
-
-  while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
-    for (sent = 0; !stop && sent < n; sent += k) {
-      if (mg_wait_until_ready(tp->s, 0) &&
-          (k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
-        stop = 1;
-    }
-  }
-  DBG(("%s", "EOF FROM CGI"));
-  CloseHandle(tp->hPipe);
-  shutdown(tp->s, 2);  // Without this, IO thread may get truncated data
-  closesocket(tp->s);
-  MG_FREE(tp);
-  return NULL;
-}
-
-static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
-                                  void *(*func)(void *)) {
-  struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
-  if (tp != NULL) {
-    tp->s = sock;
-    tp->hPipe = hPipe;
-    mg_start_thread(func, tp);
-  }
-}
-
-static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
-  wchar_t buf[MG_MAX_PATH], buf2[MG_MAX_PATH];
-  to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
-  GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
-  WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
-}
-
-static int mg_start_process(const char *interp, const char *cmd,
-                            const char *env, const char *envp[],
-                            const char *dir, sock_t sock) {
-  STARTUPINFOW si;
-  PROCESS_INFORMATION pi;
-  HANDLE a[2], b[2], me = GetCurrentProcess();
-  wchar_t wcmd[MG_MAX_PATH], full_dir[MG_MAX_PATH];
-  char buf[MG_MAX_PATH], buf2[MG_MAX_PATH], buf5[MG_MAX_PATH],
-      buf4[MG_MAX_PATH], cmdline[MG_MAX_PATH];
-  DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
-  FILE *fp;
-
-  memset(&si, 0, sizeof(si));
-  memset(&pi, 0, sizeof(pi));
-
-  si.cb = sizeof(si);
-  si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
-  si.wShowWindow = SW_HIDE;
-  si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
-
-  CreatePipe(&a[0], &a[1], NULL, 0);
-  CreatePipe(&b[0], &b[1], NULL, 0);
-  DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
-  DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
-
-  if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
-    buf[0] = buf[1] = '\0';
-    fgets(buf, sizeof(buf), fp);
-    buf[sizeof(buf) - 1] = '\0';
-    if (buf[0] == '#' && buf[1] == '!') {
-      interp = buf + 2;
-      /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
-      while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
-        interp++;
-      }
-    }
-    fclose(fp);
-  }
-
-  snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
-  mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
-
-  mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
-  to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
-
-  if (interp != NULL) {
-    mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
-    snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
-  } else {
-    snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
-  }
-  to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
-
-  if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
-                     (void *) env, full_dir, &si, &pi) != 0) {
-    mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
-    mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
-
-    CloseHandle(si.hStdOutput);
-    CloseHandle(si.hStdInput);
-
-    CloseHandle(pi.hThread);
-    CloseHandle(pi.hProcess);
-  } else {
-    CloseHandle(a[1]);
-    CloseHandle(b[0]);
-    closesocket(sock);
-  }
-  DBG(("CGI command: [%ls] -> %p", wcmd, (void*)pi.hProcess));
-
-  /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
-  (void) envp;
-  return (pi.hProcess != NULL);
-}
-#else
-static int mg_start_process(const char *interp, const char *cmd,
-                            const char *env, const char *envp[],
-                            const char *dir, sock_t sock) {
-  char buf[500];
-  pid_t pid = fork();
-  (void) env;
-
-  if (pid == 0) {
-    /*
-     * In Linux `chdir` declared with `warn_unused_result` attribute
-     * To shutup compiler we have yo use result in some way
-     */
-    int tmp = chdir(dir);
-    (void) tmp;
-    (void) dup2(sock, 0);
-    (void) dup2(sock, 1);
-    closesocket(sock);
-
-    /*
-     * After exec, all signal handlers are restored to their default values,
-     * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
-     * implementation, SIGCHLD's handler will leave unchanged after exec
-     * if it was set to be ignored. Restore it to default action.
-     */
-    signal(SIGCHLD, SIG_DFL);
-
-    if (interp == NULL) {
-      execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
-    } else {
-      execle(interp, interp, cmd, (char *) 0, envp);
-    }
-    snprintf(buf, sizeof(buf),
-             "Status: 500\r\n\r\n"
-             "500 Server Error: %s%s%s: %s",
-             interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
-             strerror(errno));
-    send(1, buf, strlen(buf), 0);
-    _exit(EXIT_FAILURE); /* exec call failed */
-  }
-
-  return (pid != 0);
-}
-#endif /* _WIN32 */
-
-/*
- * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
- * pointer into the vars array.
- */
-static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
-  int n, space;
-  char *added = block->buf + block->len;
-  va_list ap;
-
-  /* Calculate how much space is left in the buffer */
-  space = sizeof(block->buf) - (block->len + 2);
-  if (space > 0) {
-    /* Copy VARIABLE=VALUE\0 string into the free space */
-    va_start(ap, fmt);
-    n = vsnprintf(added, (size_t) space, fmt, ap);
-    va_end(ap);
-
-    /* Make sure we do not overflow buffer and the envp array */
-    if (n > 0 && n + 1 < space &&
-        block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
-      /* Append a pointer to the added string into the envp array */
-      block->vars[block->nvars++] = added;
-      /* Bump up used length counter. Include \0 terminator */
-      block->len += n + 1;
-    }
-  }
-
-  return added;
-}
-
-static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
-  const char *s;
-  if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
-}
-
-static void mg_prepare_cgi_environment(struct mg_connection *nc,
-                                       const char *prog,
-                                       const struct mg_str *path_info,
-                                       const struct http_message *hm,
-                                       const struct mg_serve_http_opts *opts,
-                                       struct mg_cgi_env_block *blk) {
-  const char *s;
-  struct mg_str *h;
-  char *p;
-  size_t i;
-  char buf[100];
-  size_t path_info_len = path_info != NULL ? path_info->len : 0;
-
-  blk->len = blk->nvars = 0;
-  blk->nc = nc;
-
-  if ((s = getenv("SERVER_NAME")) != NULL) {
-    mg_addenv(blk, "SERVER_NAME=%s", s);
-  } else {
-    mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
-    mg_addenv(blk, "SERVER_NAME=%s", buf);
-  }
-  mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
-  mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
-  mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
-
-  /* Prepare the environment block */
-  mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
-  mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
-  mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
-
-  mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
-
-  mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
-            hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
-            hm->query_string.p);
-
-  mg_conn_addr_to_str(nc, buf, sizeof(buf),
-                      MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP);
-  mg_addenv(blk, "REMOTE_ADDR=%s", buf);
-  mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT);
-  mg_addenv(blk, "SERVER_PORT=%s", buf);
-
-  s = hm->uri.p + hm->uri.len - path_info_len - 1;
-  if (*s == '/') {
-    const char *base_name = strrchr(prog, DIRSEP);
-    mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
-              (base_name != NULL ? base_name + 1 : prog));
-  } else {
-    mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
-  }
-  mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
-
-  if (path_info != NULL && path_info->len > 0) {
-    mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
-    /* Not really translated... */
-    mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
-  }
-
-#if MG_ENABLE_SSL
-  mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off"));
-#else
-  mg_addenv(blk, "HTTPS=off");
-#endif
-
-  if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
-      NULL) {
-    mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
-  }
-
-  if (hm->query_string.len > 0) {
-    mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
-              hm->query_string.p);
-  }
-
-  if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
-      NULL) {
-    mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
-  }
-
-  mg_addenv2(blk, "PATH");
-  mg_addenv2(blk, "TMP");
-  mg_addenv2(blk, "TEMP");
-  mg_addenv2(blk, "TMPDIR");
-  mg_addenv2(blk, "PERLLIB");
-  mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
-
-#ifdef _WIN32
-  mg_addenv2(blk, "COMSPEC");
-  mg_addenv2(blk, "SYSTEMROOT");
-  mg_addenv2(blk, "SystemDrive");
-  mg_addenv2(blk, "ProgramFiles");
-  mg_addenv2(blk, "ProgramFiles(x86)");
-  mg_addenv2(blk, "CommonProgramFiles(x86)");
-#else
-  mg_addenv2(blk, "LD_LIBRARY_PATH");
-#endif /* _WIN32 */
-
-  /* Add all headers as HTTP_* variables */
-  for (i = 0; hm->header_names[i].len > 0; i++) {
-    p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
-                  hm->header_names[i].p, (int) hm->header_values[i].len,
-                  hm->header_values[i].p);
-
-    /* Convert variable name into uppercase, and change - to _ */
-    for (; *p != '=' && *p != '\0'; p++) {
-      if (*p == '-') *p = '_';
-      *p = (char) toupper(*(unsigned char *) p);
-    }
-  }
-
-  blk->vars[blk->nvars++] = NULL;
-  blk->buf[blk->len++] = '\0';
-}
-
-static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
-                              void *ev_data MG_UD_ARG(void *user_data)) {
-#if !MG_ENABLE_CALLBACK_USERDATA
-  void *user_data = cgi_nc->user_data;
-#endif
-  struct mg_connection *nc = (struct mg_connection *) user_data;
-  (void) ev_data;
-
-  if (nc == NULL) {
-    /* The corresponding network connection was closed. */
-    cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-    return;
-  }
-
-  switch (ev) {
-    case MG_EV_RECV:
-      /*
-       * CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
-       * It outputs headers, then body. Headers might include "Status"
-       * header, which changes CODE, and it might include "Location" header
-       * which changes CODE to 302.
-       *
-       * Therefore we do not send the output from the CGI script to the user
-       * until all CGI headers are received.
-       *
-       * Here we parse the output from the CGI script, and if all headers has
-       * been received, send appropriate reply line, and forward all
-       * received headers to the client.
-       */
-      if (nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS) {
-        struct mbuf *io = &cgi_nc->recv_mbuf;
-        int len = mg_http_get_request_len(io->buf, io->len);
-
-        if (len == 0) break;
-        if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
-          cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-          mg_http_send_error(nc, 500, "Bad headers");
-        } else {
-          struct http_message hm;
-          struct mg_str *h;
-          mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
-          if (mg_get_http_header(&hm, "Location") != NULL) {
-            mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
-          } else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
-            mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
-          } else {
-            mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
-          }
-        }
-        nc->flags &= ~MG_F_HTTP_CGI_PARSE_HEADERS;
-      }
-      if (!(nc->flags & MG_F_HTTP_CGI_PARSE_HEADERS)) {
-        mg_forward(cgi_nc, nc);
-      }
-      break;
-    case MG_EV_CLOSE:
-      DBG(("%p CLOSE", (void*)cgi_nc));
-      mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi);
-      nc->flags |= MG_F_SEND_AND_CLOSE;
-      break;
-  }
-}
-
-MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
-                               const struct mg_str *path_info,
-                               const struct http_message *hm,
-                               const struct mg_serve_http_opts *opts) {
-  struct mg_cgi_env_block blk;
-  char dir[MG_MAX_PATH];
-  const char *p;
-  sock_t fds[2];
-
-  DBG(("%p [%s]", (void*)nc, prog));
-  mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
-  /*
-   * CGI must be executed in its own directory. 'dir' must point to the
-   * directory containing executable program, 'p' must point to the
-   * executable program name relative to 'dir'.
-   */
-  if ((p = strrchr(prog, DIRSEP)) == NULL) {
-    snprintf(dir, sizeof(dir), "%s", ".");
-  } else {
-    snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
-    prog = p + 1;
-  }
-
-  if (!mg_socketpair(fds, SOCK_STREAM)) {
-    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-    return;
-  }
-
-#ifndef _WIN32
-  struct sigaction sa;
-
-  sigemptyset(&sa.sa_mask);
-  sa.sa_handler = SIG_IGN;
-  sa.sa_flags = 0;
-  sigaction(SIGCHLD, &sa, NULL);
-#endif
-
-  if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
-                       fds[1]) != 0) {
-    struct mg_connection *cgi_nc =
-        mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc));
-    struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc);
-    cgi_pd->cgi.cgi_nc = cgi_nc;
-#if !MG_ENABLE_CALLBACK_USERDATA
-    cgi_pd->cgi.cgi_nc->user_data = nc;
-#endif
-    nc->flags |= MG_F_HTTP_CGI_PARSE_HEADERS;
-    /* Push POST data to the CGI */
-    if (hm->body.len > 0) {
-      mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, hm->body.len);
-    }
-    mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
-  } else {
-    closesocket(fds[0]);
-    mg_http_send_error(nc, 500, "CGI failure");
-  }
-
-#ifndef _WIN32
-  closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
-#endif
-}
-
-MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
-  if (d == NULL) return;
-  if (d->cgi_nc != NULL) {
-    d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-    d->cgi_nc->user_data = NULL;
-  }
-  memset(d, 0, sizeof(*d));
-}
-
-#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_http_ssi.c"
-#endif
-
-#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
-
-static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
-                             const char *path, FILE *fp, int include_level,
-                             const struct mg_serve_http_opts *opts);
-
-static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
-  char buf[BUFSIZ];
-  size_t n;
-  while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) {
-    mg_send(nc, buf, n);
-  }
-}
-
-static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm,
-                              const char *ssi, char *tag, int include_level,
-                              const struct mg_serve_http_opts *opts) {
-  char file_name[MG_MAX_PATH], path[MG_MAX_PATH], *p;
-  FILE *fp;
-
-  /*
-   * sscanf() is safe here, since send_ssi_file() also uses buffer
-   * of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
-   */
-  if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
-    /* File name is relative to the webserver root */
-    if (snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name) < 0) {
-      return;
-    }
-  } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
-    /*
-     * File name is relative to the webserver working directory
-     * or it is absolute system path
-     */
-    if (snprintf(path, sizeof(path), "%s", file_name) < 0) return;
-  } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
-             sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
-    /* File name is relative to the currect document */
-    snprintf(path, sizeof(path), "%s", ssi);
-    if ((p = strrchr(path, DIRSEP)) != NULL) {
-      p[1] = '\0';
-    }
-    snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
-  } else {
-    mg_printf(nc, "Bad SSI #include: [%s]", tag);
-    return;
-  }
-
-  if ((fp = mg_fopen(path, "rb")) == NULL) {
-    mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path,
-              strerror(mg_get_errno()));
-  } else {
-    mg_set_close_on_exec((sock_t) fileno(fp));
-    if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
-        0) {
-      mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts);
-    } else {
-      mg_send_file_data(nc, fp);
-    }
-    fclose(fp);
-  }
-}
-
-#if MG_ENABLE_HTTP_SSI_EXEC
-static void do_ssi_exec(struct mg_connection *nc, char *tag) {
-  char cmd[BUFSIZ];
-  FILE *fp;
-
-  if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
-    mg_printf(nc, "Bad SSI #exec: [%s]", tag);
-  } else if ((fp = popen(cmd, "r")) == NULL) {
-    mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno()));
-  } else {
-    mg_send_file_data(nc, fp);
-    pclose(fp);
-  }
-}
-#endif /* MG_ENABLE_HTTP_SSI_EXEC */
-
-/*
- * SSI directive has the following format:
- * <!--#directive parameter=value parameter=value -->
- */
-static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
-                             const char *path, FILE *fp, int include_level,
-                             const struct mg_serve_http_opts *opts) {
-  static const struct mg_str btag = MG_MK_STR("<!--#");
-  static const struct mg_str d_include = MG_MK_STR("include");
-  static const struct mg_str d_call = MG_MK_STR("call");
-#if MG_ENABLE_HTTP_SSI_EXEC
-  static const struct mg_str d_exec = MG_MK_STR("exec");
-#endif
-  char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
-  int ch, len, in_ssi_tag;
-
-  if (include_level > 10) {
-    mg_printf(nc, "SSI #include level is too deep (%s)", path);
-    return;
-  }
-
-  in_ssi_tag = len = 0;
-  while ((ch = fgetc(fp)) != EOF) {
-    if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
-      size_t i = len - 2;
-      in_ssi_tag = 0;
-
-      /* Trim closing --> */
-      buf[i--] = '\0';
-      while (i > 0 && buf[i] == ' ') {
-        buf[i--] = '\0';
-      }
-
-      /* Handle known SSI directives */
-      if (strncmp(p, d_include.p, d_include.len) == 0) {
-        mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level,
-                          opts);
-      } else if (strncmp(p, d_call.p, d_call.len) == 0) {
-        struct mg_ssi_call_ctx cctx;
-        memset(&cctx, 0, sizeof(cctx));
-        cctx.req = hm;
-        cctx.file = mg_mk_str(path);
-        cctx.arg = mg_mk_str(p + d_call.len + 1);
-        mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL,
-                (void *) cctx.arg.p); /* NUL added above */
-        mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx);
-#if MG_ENABLE_HTTP_SSI_EXEC
-      } else if (strncmp(p, d_exec.p, d_exec.len) == 0) {
-        do_ssi_exec(nc, p + d_exec.len + 1);
-#endif
-      } else {
-        /* Silently ignore unknown SSI directive. */
-      }
-      len = 0;
-    } else if (ch == '<') {
-      in_ssi_tag = 1;
-      if (len > 0) {
-        mg_send(nc, buf, (size_t) len);
-      }
-      len = 0;
-      buf[len++] = ch & 0xff;
-    } else if (in_ssi_tag) {
-      if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) {
-        /* Not an SSI tag */
-        in_ssi_tag = 0;
-      } else if (len == (int) sizeof(buf) - 2) {
-        mg_printf(nc, "%s: SSI tag is too large", path);
-        len = 0;
-      }
-      buf[len++] = ch & 0xff;
-    } else {
-      buf[len++] = ch & 0xff;
-      if (len == (int) sizeof(buf)) {
-        mg_send(nc, buf, (size_t) len);
-        len = 0;
-      }
-    }
-  }
-
-  /* Send the rest of buffered data */
-  if (len > 0) {
-    mg_send(nc, buf, (size_t) len);
-  }
-}
-
-MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
-                                       struct http_message *hm,
-                                       const char *path,
-                                       const struct mg_serve_http_opts *opts) {
-  FILE *fp;
-  struct mg_str mime_type = MG_NULL_STR, encoding = MG_NULL_STR;
-  DBG(("%p %s", (void*)nc, path));
-
-  if ((fp = mg_fopen(path, "rb")) == NULL) {
-    mg_http_send_error(nc, 404, NULL);
-  } else {
-    mg_set_close_on_exec((sock_t) fileno(fp));
-
-    if (!mg_get_mime_type_encoding(mg_mk_str(path), &mime_type, &encoding,
-                                   opts)) {
-      mime_type = mg_mk_str("text/plain");
-    }
-    mg_send_response_line(nc, 200, opts->extra_headers);
-    mg_printf(nc,
-              "Content-Type: %.*s\r\n"
-              "Connection: close\r\n",
-              (int) mime_type.len, mime_type.p);
-    if (encoding.len > 0) {
-      mg_printf(nc, "Content-Encoding: %.*s\r\n", (int) encoding.len,
-                encoding.p);
-    }
-    mg_send(nc, "\r\n", 2);
-    mg_send_ssi_file(nc, hm, path, fp, 0, opts);
-    fclose(fp);
-    nc->flags |= MG_F_SEND_AND_CLOSE;
-  }
-}
-
-#endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_http_webdav.c"
-#endif
-
-#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
-
-MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) {
-  static const char *methods[] = {
-    "PUT",
-    "DELETE",
-    "MKCOL",
-    "PROPFIND",
-    "MOVE"
-#if MG_ENABLE_FAKE_DAVLOCK
-    ,
-    "LOCK",
-    "UNLOCK"
-#endif
-  };
-  size_t i;
-
-  for (i = 0; i < ARRAY_SIZE(methods); i++) {
-    if (mg_vcmp(s, methods[i]) == 0) {
-      return 1;
-    }
-  }
-
-  return 0;
-}
-
-static int mg_mkdir(const char *path, uint32_t mode) {
-#ifndef _WIN32
-  return mkdir(path, mode);
-#else
-  (void) mode;
-  return _mkdir(path);
-#endif
-}
-
-static void mg_print_props(struct mg_connection *nc, const char *name,
-                           cs_stat_t *stp) {
-  char mtime[64];
-  time_t t = stp->st_mtime; /* store in local variable for NDK compile */
-  struct mg_str name_esc = mg_url_encode(mg_mk_str(name));
-  mg_gmt_time_string(mtime, sizeof(mtime), &t);
-  mg_printf(nc,
-            "<d:response>"
-            "<d:href>%s</d:href>"
-            "<d:propstat>"
-            "<d:prop>"
-            "<d:resourcetype>%s</d:resourcetype>"
-            "<d:getcontentlength>%" INT64_FMT
-            "</d:getcontentlength>"
-            "<d:getlastmodified>%s</d:getlastmodified>"
-            "</d:prop>"
-            "<d:status>HTTP/1.1 200 OK</d:status>"
-            "</d:propstat>"
-            "</d:response>\n",
-            name_esc.p, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
-            (int64_t) stp->st_size, mtime);
-  free((void *) name_esc.p);
-}
-
-MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
-                                    cs_stat_t *stp, struct http_message *hm,
-                                    struct mg_serve_http_opts *opts) {
-  static const char header[] =
-      "HTTP/1.1 207 Multi-Status\r\n"
-      "Connection: close\r\n"
-      "Content-Type: text/xml; charset=utf-8\r\n\r\n"
-      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
-      "<d:multistatus xmlns:d='DAV:'>\n";
-  static const char footer[] = "</d:multistatus>\n";
-  const struct mg_str *depth = mg_get_http_header(hm, "Depth");
-
-  /* Print properties for the requested resource itself */
-  if (S_ISDIR(stp->st_mode) &&
-      strcmp(opts->enable_directory_listing, "yes") != 0) {
-    mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
-  } else {
-    char uri[MG_MAX_PATH];
-    mg_send(nc, header, sizeof(header) - 1);
-    snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
-    mg_print_props(nc, uri, stp);
-    if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
-      mg_scan_directory(nc, path, opts, mg_print_props);
-    }
-    mg_send(nc, footer, sizeof(footer) - 1);
-    nc->flags |= MG_F_SEND_AND_CLOSE;
-  }
-}
-
-#if MG_ENABLE_FAKE_DAVLOCK
-/*
- * Windows explorer (probably there are another WebDav clients like it)
- * requires LOCK support in webdav. W/out this, it still works, but fails
- * to save file: shows error message and offers "Save As".
- * "Save as" works, but this message is very annoying.
- * This is fake lock, which doesn't lock something, just returns LOCK token,
- * UNLOCK always answers "OK".
- * With this fake LOCK Windows Explorer looks happy and saves file.
- * NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
- * Windows native DAV client. This is why FAKE LOCK is not enabed by default
- */
-MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) {
-  static const char *reply =
-      "HTTP/1.1 207 Multi-Status\r\n"
-      "Connection: close\r\n"
-      "Content-Type: text/xml; charset=utf-8\r\n\r\n"
-      "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
-      "<d:multistatus xmlns:d='DAV:'>\n"
-      "<D:lockdiscovery>\n"
-      "<D:activelock>\n"
-      "<D:locktoken>\n"
-      "<D:href>\n"
-      "opaquelocktoken:%s%u"
-      "</D:href>"
-      "</D:locktoken>"
-      "</D:activelock>\n"
-      "</D:lockdiscovery>"
-      "</d:multistatus>\n";
-  mg_printf(nc, reply, path, (unsigned int) mg_time());
-  nc->flags |= MG_F_SEND_AND_CLOSE;
-}
-#endif
-
-MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
-                                 struct http_message *hm) {
-  int status_code = 500;
-  if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
-    status_code = 415;
-  } else if (!mg_mkdir(path, 0755)) {
-    status_code = 201;
-  } else if (errno == EEXIST) {
-    status_code = 405;
-  } else if (errno == EACCES) {
-    status_code = 403;
-  } else if (errno == ENOENT) {
-    status_code = 409;
-  } else {
-    status_code = 500;
-  }
-  mg_http_send_error(nc, status_code, NULL);
-}
-
-static int mg_remove_directory(const struct mg_serve_http_opts *opts,
-                               const char *dir) {
-  char path[MG_MAX_PATH];
-  struct dirent *dp;
-  cs_stat_t st;
-  DIR *dirp;
-
-  if ((dirp = opendir(dir)) == NULL) return 0;
-
-  while ((dp = readdir(dirp)) != NULL) {
-    if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
-      continue;
-    }
-    snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
-    mg_stat(path, &st);
-    if (S_ISDIR(st.st_mode)) {
-      mg_remove_directory(opts, path);
-    } else {
-      remove(path);
-    }
-  }
-  closedir(dirp);
-  rmdir(dir);
-
-  return 1;
-}
-
-MG_INTERNAL void mg_handle_move(struct mg_connection *c,
-                                const struct mg_serve_http_opts *opts,
-                                const char *path, struct http_message *hm) {
-  const struct mg_str *dest = mg_get_http_header(hm, "Destination");
-  if (dest == NULL) {
-    mg_http_send_error(c, 411, NULL);
-  } else {
-    const char *p = (char *) memchr(dest->p, '/', dest->len);
-    if (p != NULL && p[1] == '/' &&
-        (p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
-      char buf[MG_MAX_PATH];
-      snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
-               (int) (dest->p + dest->len - p), p);
-      if (rename(path, buf) == 0) {
-        mg_http_send_error(c, 200, NULL);
-      } else {
-        mg_http_send_error(c, 418, NULL);
-      }
-    } else {
-      mg_http_send_error(c, 500, NULL);
-    }
-  }
-}
-
-MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
-                                  const struct mg_serve_http_opts *opts,
-                                  const char *path) {
-  cs_stat_t st;
-  if (mg_stat(path, &st) != 0) {
-    mg_http_send_error(nc, 404, NULL);
-  } else if (S_ISDIR(st.st_mode)) {
-    mg_remove_directory(opts, path);
-    mg_http_send_error(nc, 204, NULL);
-  } else if (remove(path) == 0) {
-    mg_http_send_error(nc, 204, NULL);
-  } else {
-    mg_http_send_error(nc, 423, NULL);
-  }
-}
-
-/* Return -1 on error, 1 on success. */
-static int mg_create_itermediate_directories(const char *path) {
-  const char *s;
-
-  /* Create intermediate directories if they do not exist */
-  for (s = path + 1; *s != '\0'; s++) {
-    if (*s == '/') {
-      char buf[MG_MAX_PATH];
-      cs_stat_t st;
-      snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
-      buf[sizeof(buf) - 1] = '\0';
-      if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
-        return -1;
-      }
-    }
-  }
-
-  return 1;
-}
-
-MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
-                               struct http_message *hm) {
-  struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
-  cs_stat_t st;
-  const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
-  int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
-
-  mg_http_free_proto_data_file(&pd->file);
-  if ((rc = mg_create_itermediate_directories(path)) == 0) {
-    mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
-  } else if (rc == -1) {
-    mg_http_send_error(nc, 500, NULL);
-  } else if (cl_hdr == NULL) {
-    mg_http_send_error(nc, 411, NULL);
-  } else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) {
-    mg_http_send_error(nc, 500, NULL);
-  } else {
-    const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
-    int64_t r1 = 0, r2 = 0;
-    pd->file.type = DATA_PUT;
-    mg_set_close_on_exec((sock_t) fileno(pd->file.fp));
-    pd->file.cl = to64(cl_hdr->p);
-    if (range_hdr != NULL &&
-        mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
-      status_code = 206;
-      fseeko(pd->file.fp, r1, SEEK_SET);
-      pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
-    }
-    mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
-    /* Remove HTTP request from the mbuf, leave only payload */
-    mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
-    mg_http_transfer_file_data(nc);
-  }
-}
-
-#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_http_websocket.c"
-#endif
-
-#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
-
-/* Amalgamated: #include "common/cs_sha1.h" */
-
-#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
-#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
-#endif
-
-#define FLAGS_MASK_FIN (1 << 7)
-#define FLAGS_MASK_OP 0x0f
-
-static int mg_is_ws_fragment(unsigned char flags) {
-  return (flags & FLAGS_MASK_FIN) == 0 ||
-         (flags & FLAGS_MASK_OP) == WEBSOCKET_OP_CONTINUE;
-}
-
-static int mg_is_ws_first_fragment(unsigned char flags) {
-  return (flags & FLAGS_MASK_FIN) == 0 &&
-         (flags & FLAGS_MASK_OP) != WEBSOCKET_OP_CONTINUE;
-}
-
-static int mg_is_ws_control_frame(unsigned char flags) {
-  unsigned char op = (flags & FLAGS_MASK_OP);
-  return op == WEBSOCKET_OP_CLOSE || op == WEBSOCKET_OP_PING ||
-         op == WEBSOCKET_OP_PONG;
-}
-
-static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
-                                               struct websocket_message *wsm) {
-  if (wsm->flags & 0x8) {
-    mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
-  } else {
-    mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm);
-  }
-}
-
-static struct mg_ws_proto_data *mg_ws_get_proto_data(struct mg_connection *nc) {
-  struct mg_http_proto_data *htd = mg_http_get_proto_data(nc);
-  return (htd != NULL ? &htd->ws_data : NULL);
-}
-
-/*
- * Sends a Close websocket frame with the given data, and closes the underlying
- * connection. If `len` is ~0, strlen(data) is used.
- */
-static void mg_ws_close(struct mg_connection *nc, const void *data,
-                        size_t len) {
-  if ((int) len == ~0) {
-    len = strlen((const char *) data);
-  }
-  mg_send_websocket_frame(nc, WEBSOCKET_OP_CLOSE, data, len);
-  nc->flags |= MG_F_SEND_AND_CLOSE;
-}
-
-static int mg_deliver_websocket_data(struct mg_connection *nc) {
-  /* Using unsigned char *, cause of integer arithmetic below */
-  uint64_t i, data_len = 0, frame_len = 0, new_data_len = nc->recv_mbuf.len,
-              len, mask_len = 0, header_len = 0;
-  struct mg_ws_proto_data *wsd = mg_ws_get_proto_data(nc);
-  unsigned char *new_data = (unsigned char *) nc->recv_mbuf.buf,
-                *e = (unsigned char *) nc->recv_mbuf.buf + nc->recv_mbuf.len;
-  uint8_t flags;
-  int ok, reass;
-
-  if (wsd->reass_len > 0) {
-    /*
-     * We already have some previously received data which we need to
-     * reassemble and deliver to the client code when we get the final
-     * fragment.
-     *
-     * NOTE: it doesn't mean that the current message must be a continuation:
-     * it might be a control frame (Close, Ping or Pong), which should be
-     * handled without breaking the fragmented message.
-     */
-
-    size_t existing_len = wsd->reass_len;
-    assert(new_data_len >= existing_len);
-
-    new_data += existing_len;
-    new_data_len -= existing_len;
-  }
-
-  flags = new_data[0];
-
-  reass = new_data_len > 0 && mg_is_ws_fragment(flags) &&
-          !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
-
-  if (reass && mg_is_ws_control_frame(flags)) {
-    /*
-     * Control frames can't be fragmented, so if we encounter fragmented
-     * control frame, close connection immediately.
-     */
-    mg_ws_close(nc, "fragmented control frames are illegal", ~0);
-    return 0;
-  } else if (new_data_len > 0 && !reass && !mg_is_ws_control_frame(flags) &&
-             wsd->reass_len > 0) {
-    /*
-     * When in the middle of a fragmented message, only the continuations
-     * and control frames are allowed.
-     */
-    mg_ws_close(nc, "non-continuation in the middle of a fragmented message",
-                ~0);
-    return 0;
-  }
-
-  if (new_data_len >= 2) {
-    len = new_data[1] & 0x7f;
-    mask_len = new_data[1] & FLAGS_MASK_FIN ? 4 : 0;
-    if (len < 126 && new_data_len >= mask_len) {
-      data_len = len;
-      header_len = 2 + mask_len;
-    } else if (len == 126 && new_data_len >= 4 + mask_len) {
-      header_len = 4 + mask_len;
-      data_len = ntohs(*(uint16_t *) &new_data[2]);
-    } else if (new_data_len >= 10 + mask_len) {
-      header_len = 10 + mask_len;
-      data_len = (((uint64_t) ntohl(*(uint32_t *) &new_data[2])) << 32) +
-                 ntohl(*(uint32_t *) &new_data[6]);
-    }
-  }
-
-  frame_len = header_len + data_len;
-  ok = (frame_len > 0 && frame_len <= new_data_len);
-
-  /* Check for overflow */
-  if (frame_len < header_len || frame_len < data_len) {
-    ok = 0;
-    mg_ws_close(nc, "overflowed message", ~0);
-  }
-
-  if (ok) {
-    size_t cleanup_len = 0;
-    struct websocket_message wsm;
-
-    wsm.size = (size_t) data_len;
-    wsm.data = new_data + header_len;
-    wsm.flags = flags;
-
-    /* Apply mask if necessary */
-    if (mask_len > 0) {
-      for (i = 0; i < data_len; i++) {
-        new_data[i + header_len] ^= (new_data + header_len - mask_len)[i % 4];
-      }
-    }
-
-    if (reass) {
-      /* This is a message fragment */
-
-      if (mg_is_ws_first_fragment(flags)) {
-        /*
-         * On the first fragmented frame, skip the first byte (op) and also
-         * reset size to 1 (op), it'll be incremented with the data len below.
-         */
-        new_data += 1;
-        wsd->reass_len = 1 /* op */;
-      }
-
-      /* Append this frame to the reassembled buffer */
-      memmove(new_data, wsm.data, e - wsm.data);
-      wsd->reass_len += wsm.size;
-      nc->recv_mbuf.len -= wsm.data - new_data;
-
-      if (flags & FLAGS_MASK_FIN) {
-        /* On last fragmented frame - call user handler and remove data */
-        wsm.flags = FLAGS_MASK_FIN | nc->recv_mbuf.buf[0];
-        wsm.data = (unsigned char *) nc->recv_mbuf.buf + 1 /* op */;
-        wsm.size = wsd->reass_len - 1 /* op */;
-        cleanup_len = wsd->reass_len;
-        wsd->reass_len = 0;
-
-        /* Pass reassembled message to the client code. */
-        mg_handle_incoming_websocket_frame(nc, &wsm);
-        mbuf_remove(&nc->recv_mbuf, cleanup_len); /* Cleanup frame */
-      }
-    } else {
-      /*
-       * This is a complete message, not a fragment. It might happen in between
-       * of a fragmented message (in this case, WebSocket protocol requires
-       * current message to be a control frame).
-       */
-      cleanup_len = (size_t) frame_len;
-
-      /* First of all, check if we need to react on a control frame. */
-      switch (flags & FLAGS_MASK_OP) {
-        case WEBSOCKET_OP_PING:
-          mg_send_websocket_frame(nc, WEBSOCKET_OP_PONG, wsm.data, wsm.size);
-          break;
-
-        case WEBSOCKET_OP_CLOSE:
-          mg_ws_close(nc, wsm.data, wsm.size);
-          break;
-      }
-
-      /* Pass received message to the client code. */
-      mg_handle_incoming_websocket_frame(nc, &wsm);
-
-      /* Cleanup frame */
-      memmove(nc->recv_mbuf.buf + wsd->reass_len,
-              nc->recv_mbuf.buf + wsd->reass_len + cleanup_len,
-              nc->recv_mbuf.len - wsd->reass_len - cleanup_len);
-      nc->recv_mbuf.len -= cleanup_len;
-    }
-  }
-
-  return ok;
-}
-
-struct ws_mask_ctx {
-  size_t pos; /* zero means unmasked */
-  uint32_t mask;
-};
-
-static uint32_t mg_ws_random_mask(void) {
-  uint32_t mask;
-/*
- * The spec requires WS client to generate hard to
- * guess mask keys. From RFC6455, Section 5.3:
- *
- * The unpredictability of the masking key is essential to prevent
- * authors of malicious applications from selecting the bytes that appear on
- * the wire.
- *
- * Hence this feature is essential when the actual end user of this API
- * is untrusted code that wouldn't have access to a lower level net API
- * anyway (e.g. web browsers). Hence this feature is low prio for most
- * mongoose use cases and thus can be disabled, e.g. when porting to a platform
- * that lacks rand().
- */
-#if MG_DISABLE_WS_RANDOM_MASK
-  mask = 0xefbeadde; /* generated with a random number generator, I swear */
-#else
-  if (sizeof(long) >= 4) {
-    mask = (uint32_t) rand();
-  } else if (sizeof(long) == 2) {
-    mask = (uint32_t) rand() << 16 | (uint32_t) rand();
-  }
-#endif
-  return mask;
-}
-
-static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
-                              struct ws_mask_ctx *ctx) {
-  int header_len;
-  unsigned char header[10];
-
-  header[0] =
-      (op & WEBSOCKET_DONT_FIN ? 0x0 : FLAGS_MASK_FIN) | (op & FLAGS_MASK_OP);
-  if (len < 126) {
-    header[1] = (unsigned char) len;
-    header_len = 2;
-  } else if (len < 65535) {
-    uint16_t tmp = htons((uint16_t) len);
-    header[1] = 126;
-    memcpy(&header[2], &tmp, sizeof(tmp));
-    header_len = 4;
-  } else {
-    uint32_t tmp;
-    header[1] = 127;
-    tmp = htonl((uint32_t)((uint64_t) len >> 32));
-    memcpy(&header[2], &tmp, sizeof(tmp));
-    tmp = htonl((uint32_t)(len & 0xffffffff));
-    memcpy(&header[6], &tmp, sizeof(tmp));
-    header_len = 10;
-  }
-
-  /* client connections enable masking */
-  if (nc->listener == NULL) {
-    header[1] |= 1 << 7; /* set masking flag */
-    mg_send(nc, header, header_len);
-    ctx->mask = mg_ws_random_mask();
-    mg_send(nc, &ctx->mask, sizeof(ctx->mask));
-    ctx->pos = nc->send_mbuf.len;
-  } else {
-    mg_send(nc, header, header_len);
-    ctx->pos = 0;
-  }
-}
-
-static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
-  size_t i;
-  if (ctx->pos == 0) return;
-  for (i = 0; i < (mbuf->len - ctx->pos); i++) {
-    mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
-  }
-}
-
-void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
-                             size_t len) {
-  struct ws_mask_ctx ctx;
-  DBG(("%p %d %d", (void*)nc, op, (int) len));
-  mg_send_ws_header(nc, op, len, &ctx);
-  mg_send(nc, data, len);
-
-  mg_ws_mask_frame(&nc->send_mbuf, &ctx);
-
-  if (op == WEBSOCKET_OP_CLOSE) {
-    nc->flags |= MG_F_SEND_AND_CLOSE;
-  }
-}
-
-void mg_send_websocket_framev(struct mg_connection *nc, int op,
-                              const struct mg_str *strv, int strvcnt) {
-  struct ws_mask_ctx ctx;
-  int i;
-  int len = 0;
-  for (i = 0; i < strvcnt; i++) {
-    len += strv[i].len;
-  }
-
-  mg_send_ws_header(nc, op, len, &ctx);
-
-  for (i = 0; i < strvcnt; i++) {
-    mg_send(nc, strv[i].p, strv[i].len);
-  }
-
-  mg_ws_mask_frame(&nc->send_mbuf, &ctx);
-
-  if (op == WEBSOCKET_OP_CLOSE) {
-    nc->flags |= MG_F_SEND_AND_CLOSE;
-  }
-}
-
-void mg_printf_websocket_frame(struct mg_connection *nc, int op,
-                               const char *fmt, ...) {
-  char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
-  va_list ap;
-  int len;
-
-  va_start(ap, fmt);
-  if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
-    mg_send_websocket_frame(nc, op, buf, len);
-  }
-  va_end(ap);
-
-  if (buf != mem && buf != NULL) {
-    MG_FREE(buf);
-  }
-}
-
-MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
-                               void *ev_data MG_UD_ARG(void *user_data)) {
-  mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
-
-  switch (ev) {
-    case MG_EV_RECV:
-      do {
-      } while (mg_deliver_websocket_data(nc));
-      break;
-    case MG_EV_POLL:
-      /* Ping idle websocket connections */
-      {
-        time_t now = *(time_t *) ev_data;
-        if (nc->flags & MG_F_IS_WEBSOCKET &&
-            now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
-          mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
-        }
-      }
-      break;
-    default:
-      break;
-  }
-#if MG_ENABLE_CALLBACK_USERDATA
-  (void) user_data;
-#endif
-}
-
-#ifndef MG_EXT_SHA1
-void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
-                    const size_t *msg_lens, uint8_t *digest) {
-  size_t i;
-  cs_sha1_ctx sha_ctx;
-  cs_sha1_init(&sha_ctx);
-  for (i = 0; i < num_msgs; i++) {
-    cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]);
-  }
-  cs_sha1_final(digest, &sha_ctx);
-}
-#else
-extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
-                           const size_t *msg_lens, uint8_t *digest);
-#endif
-
-MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
-                                 const struct mg_str *key,
-                                 struct http_message *hm) {
-  static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
-  const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic};
-  const size_t msg_lens[2] = {key->len, 36};
-  unsigned char sha[20];
-  char b64_sha[30];
-  struct mg_str *s;
-
-  mg_hash_sha1_v(2, msgs, msg_lens, sha);
-  mg_base64_encode(sha, sizeof(sha), b64_sha);
-  mg_printf(nc, "%s",
-            "HTTP/1.1 101 Switching Protocols\r\n"
-            "Upgrade: websocket\r\n"
-            "Connection: Upgrade\r\n");
-
-  s = mg_get_http_header(hm, "Sec-WebSocket-Protocol");
-  if (s != NULL) {
-    mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) s->len, s->p);
-  }
-  mg_printf(nc, "Sec-WebSocket-Accept: %s%s", b64_sha, "\r\n\r\n");
-
-  DBG(("%p %.*s %s", (void*)nc, (int) key->len, key->p, b64_sha));
-}
-
-void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
-                                  const char *host, const char *protocol,
-                                  const char *extra_headers) {
-  mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
-                               NULL);
-}
-
-void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
-                                  const char *host, const char *protocol,
-                                  const char *extra_headers, const char *user,
-                                  const char *pass) {
-  mg_send_websocket_handshake3v(nc, mg_mk_str(path), mg_mk_str(host),
-                                mg_mk_str(protocol), mg_mk_str(extra_headers),
-                                mg_mk_str(user), mg_mk_str(pass));
-}
-
-void mg_send_websocket_handshake3v(struct mg_connection *nc,
-                                   const struct mg_str path,
-                                   const struct mg_str host,
-                                   const struct mg_str protocol,
-                                   const struct mg_str extra_headers,
-                                   const struct mg_str user,
-                                   const struct mg_str pass) {
-  struct mbuf auth;
-  char key[25];
-  uint32_t nonce[4];
-  nonce[0] = mg_ws_random_mask();
-  nonce[1] = mg_ws_random_mask();
-  nonce[2] = mg_ws_random_mask();
-  nonce[3] = mg_ws_random_mask();
-  mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key);
-
-  mbuf_init(&auth, 0);
-  if (user.len > 0) {
-    mg_basic_auth_header(user, pass, &auth);
-  }
-
-  /*
-   * NOTE: the  (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is
-   * broken: it doesn't like zero length to be passed to %.*s
-   * i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`.
-   * because it handles NULL specially (and incorrectly).
-   */
-  mg_printf(nc,
-            "GET %.*s HTTP/1.1\r\n"
-            "Upgrade: websocket\r\n"
-            "Connection: Upgrade\r\n"
-            "%.*s"
-            "Sec-WebSocket-Version: 13\r\n"
-            "Sec-WebSocket-Key: %s\r\n",
-            (int) path.len, path.p, (int) auth.len,
-            (auth.buf == NULL ? "" : auth.buf), key);
-
-  /* TODO(mkm): take default hostname from http proto data if host == NULL */
-  if (host.len > 0) {
-    int host_len = (int) (path.p - host.p); /* Account for possible :PORT */
-    mg_printf(nc, "Host: %.*s\r\n", host_len, host.p);
-  }
-  if (protocol.len > 0) {
-    mg_printf(nc, "Sec-WebSocket-Protocol: %.*s\r\n", (int) protocol.len,
-              protocol.p);
-  }
-  if (extra_headers.len > 0) {
-    mg_printf(nc, "%.*s", (int) extra_headers.len, extra_headers.p);
-  }
-  mg_printf(nc, "\r\n");
-
-  nc->flags |= MG_F_IS_WEBSOCKET;
-
-  mbuf_free(&auth);
-}
-
-void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
-                                 const char *extra_headers) {
-  struct mg_str null_str = MG_NULL_STR;
-  mg_send_websocket_handshake3v(
-      nc, mg_mk_str(path), null_str /* host */, null_str /* protocol */,
-      mg_mk_str(extra_headers), null_str /* user */, null_str /* pass */);
-}
-
-struct mg_connection *mg_connect_ws_opt(
-    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
-    struct mg_connect_opts opts, const char *url, const char *protocol,
-    const char *extra_headers) {
-  struct mg_str null_str = MG_NULL_STR;
-  struct mg_str host = MG_NULL_STR, path = MG_NULL_STR, user_info = MG_NULL_STR;
-  struct mg_connection *nc =
-      mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http",
-                           "ws", "https", "wss", url, &path, &user_info, &host);
-  if (nc != NULL) {
-    mg_send_websocket_handshake3v(nc, path, host, mg_mk_str(protocol),
-                                  mg_mk_str(extra_headers), user_info,
-                                  null_str);
-  }
-  return nc;
-}
-
-struct mg_connection *mg_connect_ws(
-    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
-    const char *url, const char *protocol, const char *extra_headers) {
-  struct mg_connect_opts opts;
-  memset(&opts, 0, sizeof(opts));
-  return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
-                           protocol, extra_headers);
-}
-#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_util.c"
-#endif
-
-/* Amalgamated: #include "common/cs_base64.h" */
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_util.h" */
-
-/* For platforms with limited libc */
-#ifndef MAX
-#define MAX(a, b) ((a) > (b) ? (a) : (b))
-#endif
-
-const char *mg_skip(const char *s, const char *end, const char *delims,
-                    struct mg_str *v) {
-  v->p = s;
-  while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
-  v->len = s - v->p;
-  while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
-  return s;
-}
-
-#if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS)
-int mg_stat(const char *path, cs_stat_t *st) {
-#ifdef _WIN32
-  wchar_t wpath[MG_MAX_PATH];
-  to_wchar(path, wpath, ARRAY_SIZE(wpath));
-  DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
-  return _wstati64(wpath, st);
-#else
-  return stat(path, st);
-#endif
-}
-
-FILE *mg_fopen(const char *path, const char *mode) {
-#ifdef _WIN32
-  wchar_t wpath[MG_MAX_PATH], wmode[10];
-  to_wchar(path, wpath, ARRAY_SIZE(wpath));
-  to_wchar(mode, wmode, ARRAY_SIZE(wmode));
-  return _wfopen(wpath, wmode);
-#else
-  return fopen(path, mode);
-#endif
-}
-
-int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
-#if defined(_WIN32) && !defined(WINCE)
-  wchar_t wpath[MG_MAX_PATH];
-  to_wchar(path, wpath, ARRAY_SIZE(wpath));
-  return _wopen(wpath, flag, mode);
-#else
-  return open(path, flag, mode); /* LCOV_EXCL_LINE */
-#endif
-}
-
-size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) {
-  return fread(ptr, size, count, f);
-}
-
-size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) {
-  return fwrite(ptr, size, count, f);
-}
-#endif
-
-void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
-  cs_base64_encode(src, src_len, dst);
-}
-
-int mg_base64_decode(const unsigned char *s, int len, char *dst) {
-  return cs_base64_decode(s, len, dst, NULL);
-}
-
-#if MG_ENABLE_THREADS
-void *mg_start_thread(void *(*f)(void *), void *p) {
-#ifdef WINCE
-  return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL);
-#elif defined(_WIN32)
-  return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
-#else
-  pthread_t thread_id = (pthread_t) 0;
-  pthread_attr_t attr;
-
-  (void) pthread_attr_init(&attr);
-  (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
-
-#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
-  (void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
-#endif
-
-  pthread_create(&thread_id, &attr, f, p);
-  pthread_attr_destroy(&attr);
-
-  return (void *) thread_id;
-#endif
-}
-#endif /* MG_ENABLE_THREADS */
-
-/* Set close-on-exec bit for a given socket. */
-void mg_set_close_on_exec(sock_t sock) {
-#if defined(_WIN32) && !defined(WINCE)
-  (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
-#elif defined(__unix__)
-  fcntl(sock, F_SETFD, FD_CLOEXEC);
-#else
-  (void) sock;
-#endif
-}
-
-int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
-                        int flags) {
-  int is_v6;
-  if (buf == NULL || len <= 0) return 0;
-  memset(buf, 0, len);
-#if MG_ENABLE_IPV6
-  is_v6 = sa->sa.sa_family == AF_INET6;
-#else
-  is_v6 = 0;
-#endif
-  if (flags & MG_SOCK_STRINGIFY_IP) {
-#if MG_ENABLE_IPV6
-    const void *addr = NULL;
-    char *start = buf;
-    socklen_t capacity = len;
-    if (!is_v6) {
-      addr = &sa->sin.sin_addr;
-    } else {
-      addr = (void *) &sa->sin6.sin6_addr;
-      if (flags & MG_SOCK_STRINGIFY_PORT) {
-        *buf = '[';
-        start++;
-        capacity--;
-      }
-    }
-    if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
-      goto cleanup;
-    }
-#elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
-    /* Only Windoze Vista (and newer) have inet_ntop() */
-    char *addr_str = inet_ntoa(sa->sin.sin_addr);
-    if (addr_str != NULL) {
-      strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1);
-    } else {
-      goto cleanup;
-    }
-#else
-    if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len) == NULL) {
-      goto cleanup;
-    }
-#endif
-  }
-  if (flags & MG_SOCK_STRINGIFY_PORT) {
-    int port = ntohs(sa->sin.sin_port);
-    if (flags & MG_SOCK_STRINGIFY_IP) {
-      int buf_len = strlen(buf);
-      snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""),
-               port);
-    } else {
-      snprintf(buf, len, "%d", port);
-    }
-  }
-
-  return strlen(buf);
-
-cleanup:
-  *buf = '\0';
-  return 0;
-}
-
-int mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
-                        int flags) {
-  union socket_address sa;
-  memset(&sa, 0, sizeof(sa));
-  mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
-  return mg_sock_addr_to_str(&sa, buf, len, flags);
-}
-
-#if MG_ENABLE_HEXDUMP
-static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len,
-                        int offset) {
-  const unsigned char *p = (const unsigned char *) buf;
-  char ascii[17] = "";
-  int i, idx, n = 0;
-
-  for (i = 0; i < len; i++) {
-    idx = i % 16;
-    if (idx == 0) {
-      if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), "  %s\n", ascii);
-      n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset);
-    }
-    if (dst_len - n < 0) {
-      return n;
-    }
-    n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]);
-    ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
-    ascii[idx + 1] = '\0';
-  }
-
-  while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", "   ");
-  n += snprintf(dst + n, MAX(dst_len - n, 0), "  %s\n", ascii);
-
-  return n;
-}
-
-int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
-  return mg_hexdump_n(buf, len, dst, dst_len, 0);
-}
-
-void mg_hexdumpf(FILE *fp, const void *buf, int len) {
-  char tmp[80];
-  int offset = 0, n;
-  while (len > 0) {
-    n = (len < 16 ? len : 16);
-    mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset);
-    fputs(tmp, fp);
-    offset += n;
-    len -= n;
-  }
-}
-
-void mg_hexdump_connection(struct mg_connection *nc, const char *path,
-                           const void *buf, int num_bytes, int ev) {
-  FILE *fp = NULL;
-  char src[60], dst[60];
-  const char *tag = NULL;
-  switch (ev) {
-    case MG_EV_RECV:
-      tag = "<-";
-      break;
-    case MG_EV_SEND:
-      tag = "->";
-      break;
-    case MG_EV_ACCEPT:
-      tag = "<A";
-      break;
-    case MG_EV_CONNECT:
-      tag = "C>";
-      break;
-    case MG_EV_CLOSE:
-      tag = "XX";
-      break;
-  }
-  if (tag == NULL) return; /* Don't log MG_EV_TIMER, etc */
-
-  if (strcmp(path, "-") == 0) {
-    fp = stdout;
-  } else if (strcmp(path, "--") == 0) {
-    fp = stderr;
-#if MG_ENABLE_FILESYSTEM
-  } else {
-    fp = mg_fopen(path, "a");
-#endif
-  }
-  if (fp == NULL) return;
-
-  mg_conn_addr_to_str(nc, src, sizeof(src),
-                      MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
-  mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
-                                                MG_SOCK_STRINGIFY_PORT |
-                                                MG_SOCK_STRINGIFY_REMOTE);
-  fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void*)nc,
-          src, tag, dst, (int) num_bytes);
-  if (num_bytes > 0) {
-    mg_hexdumpf(fp, buf, num_bytes);
-  }
-  if (fp != stdout && fp != stderr) fclose(fp);
-}
-#endif
-
-int mg_is_big_endian(void) {
-  static const int n = 1;
-  /* TODO(mkm) use compiletime check with 4-byte char literal */
-  return ((char *) &n)[0] == 0;
-}
-
-DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) {
-#ifndef WINCE
-  return errno;
-#else
-  /* TODO(alashkin): translate error codes? */
-  return GetLastError();
-#endif
-}
-
-void mg_mbuf_append_base64_putc(char ch, void *user_data) {
-  struct mbuf *mbuf = (struct mbuf *) user_data;
-  mbuf_append(mbuf, &ch, sizeof(ch));
-}
-
-void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) {
-  struct cs_base64_ctx ctx;
-  cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf);
-  cs_base64_update(&ctx, (const char *) data, len);
-  cs_base64_finish(&ctx);
-}
-
-void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass,
-                          struct mbuf *buf) {
-  const char *header_prefix = "Authorization: Basic ";
-  const char *header_suffix = "\r\n";
-
-  struct cs_base64_ctx ctx;
-  cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf);
-
-  mbuf_append(buf, header_prefix, strlen(header_prefix));
-
-  cs_base64_update(&ctx, user.p, user.len);
-  if (pass.len > 0) {
-    cs_base64_update(&ctx, ":", 1);
-    cs_base64_update(&ctx, pass.p, pass.len);
-  }
-  cs_base64_finish(&ctx);
-  mbuf_append(buf, header_suffix, strlen(header_suffix));
-}
-
-struct mg_str mg_url_encode_opt(const struct mg_str src,
-                                const struct mg_str safe, unsigned int flags) {
-  const char *hex =
-      (flags & MG_URL_ENCODE_F_UPPERCASE_HEX ? "0123456789ABCDEF"
-                                             : "0123456789abcdef");
-  size_t i = 0;
-  struct mbuf mb;
-  mbuf_init(&mb, src.len);
-
-  for (i = 0; i < src.len; i++) {
-    const unsigned char c = *((const unsigned char *) src.p + i);
-    if (isalnum(c) || mg_strchr(safe, c) != NULL) {
-      mbuf_append(&mb, &c, 1);
-    } else if (c == ' ' && (flags & MG_URL_ENCODE_F_SPACE_AS_PLUS)) {
-      mbuf_append(&mb, "+", 1);
-    } else {
-      mbuf_append(&mb, "%", 1);
-      mbuf_append(&mb, &hex[c >> 4], 1);
-      mbuf_append(&mb, &hex[c & 15], 1);
-    }
-  }
-  mbuf_append(&mb, "", 1);
-  mbuf_trim(&mb);
-  return mg_mk_str_n(mb.buf, mb.len - 1);
-}
-
-struct mg_str mg_url_encode(const struct mg_str src) {
-  return mg_url_encode_opt(src, mg_mk_str("._-$,;~()/"), 0);
-}
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_mqtt.c"
-#endif
-
-#if MG_ENABLE_MQTT
-
-#include <string.h>
-
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_mqtt.h" */
-
-#define MG_F_MQTT_PING_PENDING MG_F_PROTO_1
-
-static uint16_t getu16(const char *p) {
-  const uint8_t *up = (const uint8_t *) p;
-  return (up[0] << 8) + up[1];
-}
-
-static const char *scanto(const char *p, struct mg_str *s) {
-  s->len = getu16(p);
-  s->p = p + 2;
-  return s->p + s->len;
-}
-
-MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
-  uint8_t header;
-  uint32_t len, len_len; /* must be 32-bit, see #1055 */
-  const char *p, *end, *eop = &io->buf[io->len];
-  unsigned char lc = 0;
-  int cmd;
-
-  if (io->len < 2) return MG_MQTT_ERROR_INCOMPLETE_MSG;
-  header = io->buf[0];
-  cmd = header >> 4;
-
-  /* decode mqtt variable length */
-  len = len_len = 0;
-  p = io->buf + 1;
-  while (p < eop) {
-    lc = *((const unsigned char *) p++);
-    len += (lc & 0x7f) << 7 * len_len;
-    len_len++;
-    if (!(lc & 0x80)) break;
-    if (len_len > sizeof(len)) return MG_MQTT_ERROR_MALFORMED_MSG;
-  }
-
-  end = p + len;
-  if (lc & 0x80 || end > eop) return MG_MQTT_ERROR_INCOMPLETE_MSG;
-
-  mm->cmd = cmd;
-  mm->qos = MG_MQTT_GET_QOS(header);
-
-  switch (cmd) {
-    case MG_MQTT_CMD_CONNECT: {
-      p = scanto(p, &mm->protocol_name);
-      if (p > end - 4) return MG_MQTT_ERROR_MALFORMED_MSG;
-      mm->protocol_version = *(uint8_t *) p++;
-      mm->connect_flags = *(uint8_t *) p++;
-      mm->keep_alive_timer = getu16(p);
-      p += 2;
-      if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
-      p = scanto(p, &mm->client_id);
-      if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
-      if (mm->connect_flags & MG_MQTT_HAS_WILL) {
-        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
-        p = scanto(p, &mm->will_topic);
-      }
-      if (mm->connect_flags & MG_MQTT_HAS_WILL) {
-        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
-        p = scanto(p, &mm->will_message);
-      }
-      if (mm->connect_flags & MG_MQTT_HAS_USER_NAME) {
-        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
-        p = scanto(p, &mm->user_name);
-      }
-      if (mm->connect_flags & MG_MQTT_HAS_PASSWORD) {
-        if (p >= end) return MG_MQTT_ERROR_MALFORMED_MSG;
-        p = scanto(p, &mm->password);
-      }
-      if (p != end) return MG_MQTT_ERROR_MALFORMED_MSG;
-
-      LOG(LL_DEBUG,
-          ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
-           "will_msg [%.*s] user_name [%.*s] password [%.*s]",
-           (int) len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
-           (int) mm->protocol_name.len, mm->protocol_name.p,
-           (int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
-           mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
-           (int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
-           mm->password.p));
-      break;
-    }
-    case MG_MQTT_CMD_CONNACK:
-      if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
-      mm->connack_ret_code = p[1];
-      break;
-    case MG_MQTT_CMD_PUBACK:
-    case MG_MQTT_CMD_PUBREC:
-    case MG_MQTT_CMD_PUBREL:
-    case MG_MQTT_CMD_PUBCOMP:
-    case MG_MQTT_CMD_SUBACK:
-      if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
-      mm->message_id = getu16(p);
-      p += 2;
-      break;
-    case MG_MQTT_CMD_PUBLISH: {
-      p = scanto(p, &mm->topic);
-      if (p > end) return MG_MQTT_ERROR_MALFORMED_MSG;
-      if (mm->qos > 0) {
-        if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
-        mm->message_id = getu16(p);
-        p += 2;
-      }
-      mm->payload.p = p;
-      mm->payload.len = end - p;
-      break;
-    }
-    case MG_MQTT_CMD_SUBSCRIBE:
-      if (end - p < 2) return MG_MQTT_ERROR_MALFORMED_MSG;
-      mm->message_id = getu16(p);
-      p += 2;
-      /*
-       * topic expressions are left in the payload and can be parsed with
-       * `mg_mqtt_next_subscribe_topic`
-       */
-      mm->payload.p = p;
-      mm->payload.len = end - p;
-      break;
-    default:
-      /* Unhandled command */
-      break;
-  }
-
-  mm->len = end - io->buf;
-  return mm->len;
-}
-
-static void mqtt_handler(struct mg_connection *nc, int ev,
-                         void *ev_data MG_UD_ARG(void *user_data)) {
-  struct mbuf *io = &nc->recv_mbuf;
-  struct mg_mqtt_message mm;
-  memset(&mm, 0, sizeof(mm));
-
-  nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
-
-  switch (ev) {
-    case MG_EV_ACCEPT:
-      if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
-      break;
-    case MG_EV_RECV: {
-      /* There can be multiple messages in the buffer, process them all. */
-      while (1) {
-        int len = parse_mqtt(io, &mm);
-        if (len < 0) {
-          if (len == MG_MQTT_ERROR_MALFORMED_MSG) {
-            /* Protocol error. */
-            nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-          } else if (len == MG_MQTT_ERROR_INCOMPLETE_MSG) {
-            /* Not fully buffered, let's check if we have a chance to get more
-             * data later */
-            if (nc->recv_mbuf_limit > 0 &&
-                nc->recv_mbuf.len >= nc->recv_mbuf_limit) {
-              LOG(LL_ERROR, ("%p recv buffer (%lu bytes) exceeds the limit "
-                             "%lu bytes, and not drained, closing",
-                             (void*)nc, (unsigned long) nc->recv_mbuf.len,
-                             (unsigned long) nc->recv_mbuf_limit));
-              nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-            }
-          } else {
-            /* Should never be here */
-            LOG(LL_ERROR, ("%p invalid len: %d, closing", (void*)nc, len));
-            nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-          }
-          break;
-        }
-        if (mm.cmd == MG_MQTT_CMD_PINGRESP) {
-          LOG(LL_DEBUG, ("Recv PINGRESP"));
-          nc->flags &= ~MG_F_MQTT_PING_PENDING;
-        }
-
-        nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data));
-        mbuf_remove(io, len);
-      }
-      break;
-    }
-    case MG_EV_POLL: {
-      struct mg_mqtt_proto_data *pd =
-          (struct mg_mqtt_proto_data *) nc->proto_data;
-      double now = mg_time();
-      if (pd->keep_alive > 0 && pd->last_control_time > 0) {
-        double diff = (now - pd->last_control_time);
-        if (diff > pd->keep_alive) {
-          if (diff < 1500000000) {
-            if (!(nc->flags & MG_F_MQTT_PING_PENDING)) {
-              LOG(LL_DEBUG, ("Send PINGREQ"));
-              nc->flags |= MG_F_MQTT_PING_PENDING;
-              mg_mqtt_ping(nc);
-            } else {
-              LOG(LL_DEBUG, ("Ping timeout"));
-              nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-            }
-          } else {
-            /* Wall time has just been set. Avoid immediate ping,
-             * more likely than not it is not needed. The standard allows for
-             * 1.5X interval for ping requests, so even if were just about to
-             * send one, we should be ok waiting 0.4X more. */
-            pd->last_control_time = now - pd->keep_alive * 0.6;
-          }
-        }
-      }
-      break;
-    }
-  }
-}
-
-static void mg_mqtt_proto_data_destructor(void *proto_data) {
-  MG_FREE(proto_data);
-}
-
-static struct mg_str mg_mqtt_next_topic_component(struct mg_str *topic) {
-  struct mg_str res = *topic;
-  const char *c = mg_strchr(*topic, '/');
-  if (c != NULL) {
-    res.len = (c - topic->p);
-    topic->len -= (res.len + 1);
-    topic->p += (res.len + 1);
-  } else {
-    topic->len = 0;
-  }
-  return res;
-}
-
-/* Refernce: https://mosquitto.org/man/mqtt-7.html */
-int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) {
-  struct mg_str ec, tc;
-  if (exp.len == 0) return 0;
-  while (1) {
-    ec = mg_mqtt_next_topic_component(&exp);
-    tc = mg_mqtt_next_topic_component(&topic);
-    if (ec.len == 0) {
-      if (tc.len != 0) return 0;
-      if (exp.len == 0) break;
-      continue;
-    }
-    if (mg_vcmp(&ec, "+") == 0) {
-      if (tc.len == 0 && topic.len == 0) return 0;
-      continue;
-    }
-    if (mg_vcmp(&ec, "#") == 0) {
-      /* Must be the last component in the expression or it's invalid. */
-      return (exp.len == 0);
-    }
-    if (mg_strcmp(ec, tc) != 0) {
-      return 0;
-    }
-  }
-  return (tc.len == 0 && topic.len == 0);
-}
-
-int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) {
-  return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic);
-}
-
-void mg_set_protocol_mqtt(struct mg_connection *nc) {
-  nc->proto_handler = mqtt_handler;
-  nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
-  nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
-}
-
-static void mg_send_mqtt_header(struct mg_connection *nc, uint8_t cmd,
-                                uint8_t flags, size_t len) {
-  struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
-  uint8_t buf[1 + sizeof(size_t)];
-  uint8_t *vlen = &buf[1];
-
-  buf[0] = (cmd << 4) | flags;
-
-  /* mqtt variable length encoding */
-  do {
-    *vlen = len % 0x80;
-    len /= 0x80;
-    if (len > 0) *vlen |= 0x80;
-    vlen++;
-  } while (len > 0);
-
-  mg_send(nc, buf, vlen - buf);
-  pd->last_control_time = mg_time();
-}
-
-void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
-  static struct mg_send_mqtt_handshake_opts opts;
-  mg_send_mqtt_handshake_opt(nc, client_id, opts);
-}
-
-void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
-                                struct mg_send_mqtt_handshake_opts opts) {
-  struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
-  uint16_t id_len = 0, wt_len = 0, wm_len = 0, user_len = 0, pw_len = 0;
-  uint16_t netbytes;
-  size_t total_len;
-
-  if (client_id != NULL) {
-    id_len = strlen(client_id);
-  }
-
-  total_len = 7 + 1 + 2 + 2 + id_len;
-
-  if (opts.user_name != NULL) {
-    opts.flags |= MG_MQTT_HAS_USER_NAME;
-  }
-  if (opts.password != NULL) {
-    opts.flags |= MG_MQTT_HAS_PASSWORD;
-  }
-  if (opts.will_topic != NULL && opts.will_message != NULL) {
-    wt_len = strlen(opts.will_topic);
-    wm_len = strlen(opts.will_message);
-    opts.flags |= MG_MQTT_HAS_WILL;
-  }
-  if (opts.keep_alive == 0) {
-    opts.keep_alive = 60;
-  }
-
-  if (opts.flags & MG_MQTT_HAS_WILL) {
-    total_len += 2 + wt_len + 2 + wm_len;
-  }
-  if (opts.flags & MG_MQTT_HAS_USER_NAME) {
-    user_len = strlen(opts.user_name);
-    total_len += 2 + user_len;
-  }
-  if (opts.flags & MG_MQTT_HAS_PASSWORD) {
-    pw_len = strlen(opts.password);
-    total_len += 2 + pw_len;
-  }
-
-  mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNECT, 0, total_len);
-  mg_send(nc, "\00\04MQTT\04", 7);
-  mg_send(nc, &opts.flags, 1);
-
-  netbytes = htons(opts.keep_alive);
-  mg_send(nc, &netbytes, 2);
-
-  netbytes = htons(id_len);
-  mg_send(nc, &netbytes, 2);
-  mg_send(nc, client_id, id_len);
-
-  if (opts.flags & MG_MQTT_HAS_WILL) {
-    netbytes = htons(wt_len);
-    mg_send(nc, &netbytes, 2);
-    mg_send(nc, opts.will_topic, wt_len);
-
-    netbytes = htons(wm_len);
-    mg_send(nc, &netbytes, 2);
-    mg_send(nc, opts.will_message, wm_len);
-  }
-
-  if (opts.flags & MG_MQTT_HAS_USER_NAME) {
-    netbytes = htons(user_len);
-    mg_send(nc, &netbytes, 2);
-    mg_send(nc, opts.user_name, user_len);
-  }
-  if (opts.flags & MG_MQTT_HAS_PASSWORD) {
-    netbytes = htons(pw_len);
-    mg_send(nc, &netbytes, 2);
-    mg_send(nc, opts.password, pw_len);
-  }
-
-  if (pd != NULL) {
-    pd->keep_alive = opts.keep_alive;
-  }
-}
-
-void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
-                     uint16_t message_id, int flags, const void *data,
-                     size_t len) {
-  uint16_t netbytes;
-  uint16_t topic_len = strlen(topic);
-
-  size_t total_len = 2 + topic_len + len;
-  if (MG_MQTT_GET_QOS(flags) > 0) {
-    total_len += 2;
-  }
-
-  mg_send_mqtt_header(nc, MG_MQTT_CMD_PUBLISH, flags, total_len);
-
-  netbytes = htons(topic_len);
-  mg_send(nc, &netbytes, 2);
-  mg_send(nc, topic, topic_len);
-
-  if (MG_MQTT_GET_QOS(flags) > 0) {
-    netbytes = htons(message_id);
-    mg_send(nc, &netbytes, 2);
-  }
-
-  mg_send(nc, data, len);
-}
-
-void mg_mqtt_subscribe(struct mg_connection *nc,
-                       const struct mg_mqtt_topic_expression *topics,
-                       size_t topics_len, uint16_t message_id) {
-  uint16_t netbytes;
-  size_t i;
-  uint16_t topic_len;
-  size_t total_len = 2;
-
-  for (i = 0; i < topics_len; i++) {
-    total_len += 2 + strlen(topics[i].topic) + 1;
-  }
-
-  mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1), total_len);
-
-  netbytes = htons(message_id);
-  mg_send(nc, (char *) &netbytes, 2);
-
-  for (i = 0; i < topics_len; i++) {
-    topic_len = strlen(topics[i].topic);
-    netbytes = htons(topic_len);
-    mg_send(nc, &netbytes, 2);
-    mg_send(nc, topics[i].topic, topic_len);
-    mg_send(nc, &topics[i].qos, 1);
-  }
-}
-
-int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
-                                 struct mg_str *topic, uint8_t *qos, int pos) {
-  unsigned char *buf = (unsigned char *) msg->payload.p + pos;
-  int new_pos;
-
-  if ((size_t) pos >= msg->payload.len) return -1;
-
-  topic->len = buf[0] << 8 | buf[1];
-  topic->p = (char *) buf + 2;
-  new_pos = pos + 2 + topic->len + 1;
-  if ((size_t) new_pos > msg->payload.len) return -1;
-  *qos = buf[2 + topic->len];
-  return new_pos;
-}
-
-void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
-                         size_t topics_len, uint16_t message_id) {
-  uint16_t netbytes;
-  size_t i;
-  uint16_t topic_len;
-  size_t total_len = 2;
-
-  for (i = 0; i < topics_len; i++) {
-    total_len += 2 + strlen(topics[i]);
-  }
-
-  mg_send_mqtt_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1), total_len);
-
-  netbytes = htons(message_id);
-  mg_send(nc, (char *) &netbytes, 2);
-
-  for (i = 0; i < topics_len; i++) {
-    topic_len = strlen(topics[i]);
-    netbytes = htons(topic_len);
-    mg_send(nc, &netbytes, 2);
-    mg_send(nc, topics[i], topic_len);
-  }
-}
-
-void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
-  uint8_t unused = 0;
-  mg_send_mqtt_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
-  mg_send(nc, &unused, 1);
-  mg_send(nc, &return_code, 1);
-}
-
-/*
- * Sends a command which contains only a `message_id` and a QoS level of 1.
- *
- * Helper function.
- */
-static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
-                                       uint16_t message_id) {
-  uint16_t netbytes;
-  uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0);
-
-  mg_send_mqtt_header(nc, cmd, flags, 2 /* len */);
-
-  netbytes = htons(message_id);
-  mg_send(nc, &netbytes, 2);
-}
-
-void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
-  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
-}
-
-void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
-  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
-}
-
-void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
-  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
-}
-
-void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
-  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
-}
-
-void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
-                    uint16_t message_id) {
-  size_t i;
-  uint16_t netbytes;
-
-  mg_send_mqtt_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
-
-  netbytes = htons(message_id);
-  mg_send(nc, &netbytes, 2);
-
-  for (i = 0; i < qoss_len; i++) {
-    mg_send(nc, &qoss[i], 1);
-  }
-}
-
-void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
-  mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
-}
-
-void mg_mqtt_ping(struct mg_connection *nc) {
-  mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
-}
-
-void mg_mqtt_pong(struct mg_connection *nc) {
-  mg_send_mqtt_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
-}
-
-void mg_mqtt_disconnect(struct mg_connection *nc) {
-  mg_send_mqtt_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
-}
-
-#endif /* MG_ENABLE_MQTT */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_mqtt_server.c"
-#endif
-
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_mqtt_server.h" */
-
-#if MG_ENABLE_MQTT_BROKER
-
-static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
-                                 struct mg_mqtt_session *s,
-                                 struct mg_connection *nc) {
-  s->brk = brk;
-  s->subscriptions = NULL;
-  s->num_subscriptions = 0;
-  s->nc = nc;
-}
-
-static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
-  LIST_INSERT_HEAD(&s->brk->sessions, s, link);
-}
-
-static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
-  LIST_REMOVE(s, link);
-}
-
-static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
-  size_t i;
-  for (i = 0; i < s->num_subscriptions; i++) {
-    MG_FREE((void *) s->subscriptions[i].topic);
-  }
-  MG_FREE(s->subscriptions);
-  MG_FREE(s);
-}
-
-static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
-  mg_mqtt_remove_session(s);
-  mg_mqtt_destroy_session(s);
-}
-
-void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
-  LIST_INIT(&brk->sessions);
-  brk->user_data = user_data;
-}
-
-static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
-                                          struct mg_connection *nc) {
-  struct mg_mqtt_session *s =
-      (struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s);
-  if (s == NULL) {
-    /* LCOV_EXCL_START */
-    mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
-    return;
-    /* LCOV_EXCL_STOP */
-  }
-
-  /* TODO(mkm): check header (magic and version) */
-
-  mg_mqtt_session_init(brk, s, nc);
-  nc->priv_2 = s;
-  mg_mqtt_add_session(s);
-
-  mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
-}
-
-static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
-                                            struct mg_mqtt_message *msg) {
-  struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->priv_2;
-  uint8_t qoss[MG_MQTT_MAX_SESSION_SUBSCRIPTIONS];
-  size_t num_subs = 0;
-  struct mg_str topic;
-  uint8_t qos;
-  int pos;
-  struct mg_mqtt_topic_expression *te;
-
-  for (pos = 0;
-       (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
-    if (num_subs >= sizeof(MG_MQTT_MAX_SESSION_SUBSCRIPTIONS) ||
-        (ss->num_subscriptions + num_subs >=
-         MG_MQTT_MAX_SESSION_SUBSCRIPTIONS)) {
-      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-      return;
-    }
-    qoss[num_subs++] = qos;
-  }
-
-  if (num_subs > 0) {
-    te = (struct mg_mqtt_topic_expression *) MG_REALLOC(
-        ss->subscriptions,
-        sizeof(*ss->subscriptions) * (ss->num_subscriptions + num_subs));
-    if (te == NULL) {
-      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-      return;
-    }
-    ss->subscriptions = te;
-    for (pos = 0;
-         pos < (int) msg->payload.len &&
-             (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
-         ss->num_subscriptions++) {
-      te = &ss->subscriptions[ss->num_subscriptions];
-      te->topic = (char *) MG_MALLOC(topic.len + 1);
-      te->qos = qos;
-      memcpy((char *) te->topic, topic.p, topic.len);
-      ((char *) te->topic)[topic.len] = '\0';
-    }
-  }
-
-  if (pos == (int) msg->payload.len) {
-    mg_mqtt_suback(nc, qoss, num_subs, msg->message_id);
-  } else {
-    /* We did not fully parse the payload, something must be wrong. */
-    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-  }
-}
-
-static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
-                                          struct mg_mqtt_message *msg) {
-  struct mg_mqtt_session *s;
-  size_t i;
-
-  for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
-    for (i = 0; i < s->num_subscriptions; i++) {
-      if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic,
-                                          msg->topic)) {
-        char buf[100], *p = buf;
-        mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len,
-                    msg->topic.p);
-        if (p == NULL) {
-          return;
-        }
-        mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len);
-        if (p != buf) {
-          MG_FREE(p);
-        }
-        break;
-      }
-    }
-  }
-}
-
-void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
-  struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
-  struct mg_mqtt_broker *brk;
-
-  if (nc->listener) {
-    brk = (struct mg_mqtt_broker *) nc->listener->priv_2;
-  } else {
-    brk = (struct mg_mqtt_broker *) nc->priv_2;
-  }
-
-  switch (ev) {
-    case MG_EV_ACCEPT:
-      if (nc->proto_data == NULL) mg_set_protocol_mqtt(nc);
-      nc->priv_2 = NULL; /* Clear up the inherited pointer to broker */
-      break;
-    case MG_EV_MQTT_CONNECT:
-      if (nc->priv_2 == NULL) {
-        mg_mqtt_broker_handle_connect(brk, nc);
-      } else {
-        /* Repeated CONNECT */
-        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-      }
-      break;
-    case MG_EV_MQTT_SUBSCRIBE:
-      if (nc->priv_2 != NULL) {
-        mg_mqtt_broker_handle_subscribe(nc, msg);
-      } else {
-        /* Subscribe before CONNECT */
-        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-      }
-      break;
-    case MG_EV_MQTT_PUBLISH:
-      if (nc->priv_2 != NULL) {
-        mg_mqtt_broker_handle_publish(brk, msg);
-      } else {
-        /* Publish before CONNECT */
-        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-      }
-      break;
-    case MG_EV_CLOSE:
-      if (nc->listener && nc->priv_2 != NULL) {
-        mg_mqtt_close_session((struct mg_mqtt_session *) nc->priv_2);
-      }
-      break;
-  }
-}
-
-struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
-                                     struct mg_mqtt_session *s) {
-  return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link);
-}
-
-#endif /* MG_ENABLE_MQTT_BROKER */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_dns.c"
-#endif
-
-#if MG_ENABLE_DNS
-
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_dns.h" */
-
-static int mg_dns_tid = 0xa0;
-
-struct mg_dns_header {
-  uint16_t transaction_id;
-  uint16_t flags;
-  uint16_t num_questions;
-  uint16_t num_answers;
-  uint16_t num_authority_prs;
-  uint16_t num_other_prs;
-};
-
-struct mg_dns_resource_record *mg_dns_next_record(
-    struct mg_dns_message *msg, int query,
-    struct mg_dns_resource_record *prev) {
-  struct mg_dns_resource_record *rr;
-
-  for (rr = (prev == NULL ? msg->answers : prev + 1);
-       rr - msg->answers < msg->num_answers; rr++) {
-    if (rr->rtype == query) {
-      return rr;
-    }
-  }
-  return NULL;
-}
-
-int mg_dns_parse_record_data(struct mg_dns_message *msg,
-                             struct mg_dns_resource_record *rr, void *data,
-                             size_t data_len) {
-  switch (rr->rtype) {
-    case MG_DNS_A_RECORD:
-      if (data_len < sizeof(struct in_addr)) {
-        return -1;
-      }
-      if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
-        return -1;
-      }
-      memcpy(data, rr->rdata.p, data_len);
-      return 0;
-#if MG_ENABLE_IPV6
-    case MG_DNS_AAAA_RECORD:
-      if (data_len < sizeof(struct in6_addr)) {
-        return -1; /* LCOV_EXCL_LINE */
-      }
-      memcpy(data, rr->rdata.p, data_len);
-      return 0;
-#endif
-    case MG_DNS_CNAME_RECORD:
-      mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
-      return 0;
-  }
-
-  return -1;
-}
-
-int mg_dns_insert_header(struct mbuf *io, size_t pos,
-                         struct mg_dns_message *msg) {
-  struct mg_dns_header header;
-
-  memset(&header, 0, sizeof(header));
-  header.transaction_id = msg->transaction_id;
-  header.flags = htons(msg->flags);
-  header.num_questions = htons(msg->num_questions);
-  header.num_answers = htons(msg->num_answers);
-
-  return mbuf_insert(io, pos, &header, sizeof(header));
-}
-
-int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) {
-  unsigned char *begin, *end;
-  struct mg_dns_resource_record *last_q;
-  if (msg->num_questions <= 0) return 0;
-  begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header);
-  last_q = &msg->questions[msg->num_questions - 1];
-  end = (unsigned char *) last_q->name.p + last_q->name.len + 4;
-  return mbuf_append(io, begin, end - begin);
-}
-
-int mg_dns_encode_name_s(struct mbuf *io, struct mg_str name) {
-  const char *s;
-  unsigned char n;
-  size_t pos = io->len;
-
-  do {
-    if ((s = mg_strchr(name, '.')) == NULL) {
-      s = name.p + name.len;
-    }
-
-    if (s - name.p > 127) {
-      return -1; /* TODO(mkm) cover */
-    }
-    n = s - name.p;         /* chunk length */
-    mbuf_append(io, &n, 1); /* send length */
-    mbuf_append(io, name.p, n);
-
-    if (n < name.len && *s == '.') {
-      n++;
-    }
-
-    name.p += n;
-    name.len -= n;
-  } while (name.len > 0);
-  mbuf_append(io, "\0", 1); /* Mark end of host name */
-
-  return io->len - pos;
-}
-
-int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
-  return mg_dns_encode_name_s(io, mg_mk_str_n(name, len));
-}
-
-int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
-                         const char *name, size_t nlen, const void *rdata,
-                         size_t rlen) {
-  size_t pos = io->len;
-  uint16_t u16;
-  uint32_t u32;
-
-  if (rr->kind == MG_DNS_INVALID_RECORD) {
-    return -1; /* LCOV_EXCL_LINE */
-  }
-
-  if (mg_dns_encode_name(io, name, nlen) == -1) {
-    return -1;
-  }
-
-  u16 = htons(rr->rtype);
-  mbuf_append(io, &u16, 2);
-  u16 = htons(rr->rclass);
-  mbuf_append(io, &u16, 2);
-
-  if (rr->kind == MG_DNS_ANSWER) {
-    u32 = htonl(rr->ttl);
-    mbuf_append(io, &u32, 4);
-
-    if (rr->rtype == MG_DNS_CNAME_RECORD) {
-      int clen;
-      /* fill size after encoding */
-      size_t off = io->len;
-      mbuf_append(io, &u16, 2);
-      if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
-        return -1;
-      }
-      u16 = clen;
-      io->buf[off] = u16 >> 8;
-      io->buf[off + 1] = u16 & 0xff;
-    } else {
-      u16 = htons((uint16_t) rlen);
-      mbuf_append(io, &u16, 2);
-      mbuf_append(io, rdata, rlen);
-    }
-  }
-
-  return io->len - pos;
-}
-
-void mg_send_dns_query(struct mg_connection *nc, const char *name,
-                       int query_type) {
-  struct mg_dns_message *msg =
-      (struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
-  struct mbuf pkt;
-  struct mg_dns_resource_record *rr = &msg->questions[0];
-
-  DBG(("%s %d", name, query_type));
-
-  mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
-
-  msg->transaction_id = ++mg_dns_tid;
-  msg->flags = 0x100;
-  msg->num_questions = 1;
-
-  mg_dns_insert_header(&pkt, 0, msg);
-
-  rr->rtype = query_type;
-  rr->rclass = 1; /* Class: inet */
-  rr->kind = MG_DNS_QUESTION;
-
-  if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
-    /* TODO(mkm): return an error code */
-    goto cleanup; /* LCOV_EXCL_LINE */
-  }
-
-  /* TCP DNS requires messages to be prefixed with len */
-  if (!(nc->flags & MG_F_UDP)) {
-    uint16_t len = htons((uint16_t) pkt.len);
-    mbuf_insert(&pkt, 0, &len, 2);
-  }
-
-  mg_send(nc, pkt.buf, pkt.len);
-  mbuf_free(&pkt);
-
-cleanup:
-  MG_FREE(msg);
-}
-
-static unsigned char *mg_parse_dns_resource_record(
-    unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
-    int reply) {
-  unsigned char *name = data;
-  int chunk_len, data_len;
-
-  while (data < end && (chunk_len = *data)) {
-    if (((unsigned char *) data)[0] & 0xc0) {
-      data += 1;
-      break;
-    }
-    data += chunk_len + 1;
-  }
-
-  if (data > end - 5) {
-    return NULL;
-  }
-
-  rr->name.p = (char *) name;
-  rr->name.len = data - name + 1;
-  data++;
-
-  rr->rtype = data[0] << 8 | data[1];
-  data += 2;
-
-  rr->rclass = data[0] << 8 | data[1];
-  data += 2;
-
-  rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
-  if (reply) {
-    if (data >= end - 6) {
-      return NULL;
-    }
-
-    rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
-              data[2] << 8 | data[3];
-    data += 4;
-
-    data_len = *data << 8 | *(data + 1);
-    data += 2;
-
-    rr->rdata.p = (char *) data;
-    rr->rdata.len = data_len;
-    data += data_len;
-  }
-  return data;
-}
-
-int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
-  struct mg_dns_header *header = (struct mg_dns_header *) buf;
-  unsigned char *data = (unsigned char *) buf + sizeof(*header);
-  unsigned char *end = (unsigned char *) buf + len;
-  int i;
-
-  memset(msg, 0, sizeof(*msg));
-  msg->pkt.p = buf;
-  msg->pkt.len = len;
-
-  if (len < (int) sizeof(*header)) return -1;
-
-  msg->transaction_id = header->transaction_id;
-  msg->flags = ntohs(header->flags);
-  msg->num_questions = ntohs(header->num_questions);
-  if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
-    msg->num_questions = (int) ARRAY_SIZE(msg->questions);
-  }
-  msg->num_answers = ntohs(header->num_answers);
-  if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
-    msg->num_answers = (int) ARRAY_SIZE(msg->answers);
-  }
-
-  for (i = 0; i < msg->num_questions; i++) {
-    data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
-    if (data == NULL) return -1;
-  }
-
-  for (i = 0; i < msg->num_answers; i++) {
-    data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
-    if (data == NULL) return -1;
-  }
-
-  return 0;
-}
-
-size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
-                              char *dst, int dst_len) {
-  int chunk_len, num_ptrs = 0;
-  char *old_dst = dst;
-  const unsigned char *data = (unsigned char *) name->p;
-  const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
-
-  if (data >= end) {
-    return 0;
-  }
-
-  while ((chunk_len = *data++)) {
-    int leeway = dst_len - (dst - old_dst);
-    if (data >= end) {
-      return 0;
-    }
-
-    if ((chunk_len & 0xc0) == 0xc0) {
-      uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
-      if (off >= msg->pkt.len) {
-        return 0;
-      }
-      /* Basic circular loop avoidance: allow up to 16 pointer hops. */
-      if (++num_ptrs > 15) {
-        return 0;
-      }
-      data = (unsigned char *) msg->pkt.p + off;
-      continue;
-    }
-    if (chunk_len > 63) {
-      return 0;
-    }
-    if (chunk_len > leeway) {
-      chunk_len = leeway;
-    }
-
-    if (data + chunk_len >= end) {
-      return 0;
-    }
-
-    memcpy(dst, data, chunk_len);
-    data += chunk_len;
-    dst += chunk_len;
-    leeway -= chunk_len;
-    if (leeway == 0) {
-      return dst - old_dst;
-    }
-    *dst++ = '.';
-  }
-
-  if (dst != old_dst) {
-    *--dst = 0;
-  }
-  return dst - old_dst;
-}
-
-static void dns_handler(struct mg_connection *nc, int ev,
-                        void *ev_data MG_UD_ARG(void *user_data)) {
-  struct mbuf *io = &nc->recv_mbuf;
-  struct mg_dns_message msg;
-
-  /* Pass low-level events to the user handler */
-  nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
-
-  switch (ev) {
-    case MG_EV_RECV:
-      if (!(nc->flags & MG_F_UDP)) {
-        mbuf_remove(&nc->recv_mbuf, 2);
-      }
-      if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
-        /* reply + recursion allowed + format error */
-        memset(&msg, 0, sizeof(msg));
-        msg.flags = 0x8081;
-        mg_dns_insert_header(io, 0, &msg);
-        if (!(nc->flags & MG_F_UDP)) {
-          uint16_t len = htons((uint16_t) io->len);
-          mbuf_insert(io, 0, &len, 2);
-        }
-        mg_send(nc, io->buf, io->len);
-      } else {
-        /* Call user handler with parsed message */
-        nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data));
-      }
-      mbuf_remove(io, io->len);
-      break;
-  }
-}
-
-void mg_set_protocol_dns(struct mg_connection *nc) {
-  nc->proto_handler = dns_handler;
-}
-
-#endif /* MG_ENABLE_DNS */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_dns_server.c"
-#endif
-
-#if MG_ENABLE_DNS_SERVER
-
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "dns-server.h" */
-
-struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
-                                        struct mg_dns_message *msg) {
-  struct mg_dns_reply rep;
-  rep.msg = msg;
-  rep.io = io;
-  rep.start = io->len;
-
-  /* reply + recursion allowed */
-  msg->flags |= 0x8080;
-  mg_dns_copy_questions(io, msg);
-
-  msg->num_answers = 0;
-  return rep;
-}
-
-void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
-  size_t sent = r->io->len - r->start;
-  mg_dns_insert_header(r->io, r->start, r->msg);
-  if (!(nc->flags & MG_F_UDP)) {
-    uint16_t len = htons((uint16_t) sent);
-    mbuf_insert(r->io, r->start, &len, 2);
-  }
-
-  if (&nc->send_mbuf != r->io) {
-    mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
-    r->io->len = r->start;
-  }
-}
-
-int mg_dns_reply_record(struct mg_dns_reply *reply,
-                        struct mg_dns_resource_record *question,
-                        const char *name, int rtype, int ttl, const void *rdata,
-                        size_t rdata_len) {
-  struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
-  char rname[512];
-  struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
-  if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
-    return -1; /* LCOV_EXCL_LINE */
-  }
-
-  if (name == NULL) {
-    name = rname;
-    rname[511] = 0;
-    mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
-  }
-
-  *ans = *question;
-  ans->kind = MG_DNS_ANSWER;
-  ans->rtype = rtype;
-  ans->ttl = ttl;
-
-  if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
-                           rdata_len) == -1) {
-    return -1; /* LCOV_EXCL_LINE */
-  };
-
-  msg->num_answers++;
-  return 0;
-}
-
-#endif /* MG_ENABLE_DNS_SERVER */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_resolv.c"
-#endif
-
-#if MG_ENABLE_ASYNC_RESOLVER
-
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_resolv.h" */
-
-#ifndef MG_DEFAULT_NAMESERVER
-#define MG_DEFAULT_NAMESERVER "8.8.8.8"
-#endif
-
-struct mg_resolve_async_request {
-  char name[1024];
-  int query;
-  mg_resolve_callback_t callback;
-  void *data;
-  time_t timeout;
-  int max_retries;
-  enum mg_resolve_err err;
-
-  /* state */
-  time_t last_time;
-  int retries;
-};
-
-/*
- * Find what nameserver to use.
- *
- * Return 0 if OK, -1 if error
- */
-static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
-  int ret = -1;
-
-#ifdef _WIN32
-  int i;
-  LONG err;
-  HKEY hKey, hSub;
-  wchar_t subkey[512], value[128],
-      *key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
-
-  if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) !=
-      ERROR_SUCCESS) {
-    fprintf(stderr, "cannot open reg key %S: %ld\n", key, err);
-    ret = -1;
-  } else {
-    for (ret = -1, i = 0; 1; i++) {
-      DWORD subkey_size = sizeof(subkey), type, len = sizeof(value);
-      if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL,
-                        NULL) != ERROR_SUCCESS) {
-        break;
-      }
-      if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS &&
-          ((RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value,
-                             &len) == ERROR_SUCCESS &&
-            value[0] != '\0') ||
-           (RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value,
-                             &len) == ERROR_SUCCESS &&
-            value[0] != '\0'))) {
-        /*
-         * See https://github.com/cesanta/mongoose/issues/176
-         * The value taken from the registry can be empty, a single
-         * IP address, or multiple IP addresses separated by comma.
-         * If it's empty, check the next interface.
-         * If it's multiple IP addresses, take the first one.
-         */
-        wchar_t *comma = wcschr(value, ',');
-        if (comma != NULL) {
-          *comma = '\0';
-        }
-        /* %S will convert wchar_t -> char */
-        snprintf(name, name_len, "%S", value);
-        ret = 0;
-        RegCloseKey(hSub);
-        break;
-      }
-    }
-    RegCloseKey(hKey);
-  }
-#elif MG_ENABLE_FILESYSTEM && defined(MG_RESOLV_CONF_FILE_NAME)
-  FILE *fp;
-  char line[512];
-
-  if ((fp = mg_fopen(MG_RESOLV_CONF_FILE_NAME, "r")) == NULL) {
-    ret = -1;
-  } else {
-    /* Try to figure out what nameserver to use */
-    for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
-      unsigned int a, b, c, d;
-      if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) {
-        snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d);
-        ret = 0;
-        break;
-      }
-    }
-    (void) fclose(fp);
-  }
-#else
-  snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER);
-#endif /* _WIN32 */
-
-  return ret;
-}
-
-int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
-#if MG_ENABLE_FILESYSTEM && defined(MG_HOSTS_FILE_NAME)
-  /* TODO(mkm) cache /etc/hosts */
-  FILE *fp;
-  char line[1024];
-  char *p;
-  char alias[256];
-  unsigned int a, b, c, d;
-  int len = 0;
-
-  if ((fp = mg_fopen(MG_HOSTS_FILE_NAME, "r")) == NULL) {
-    return -1;
-  }
-
-  for (; fgets(line, sizeof(line), fp) != NULL;) {
-    if (line[0] == '#') continue;
-
-    if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
-      /* TODO(mkm): handle ipv6 */
-      continue;
-    }
-    for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
-      if (strcmp(alias, name) == 0) {
-        usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
-        fclose(fp);
-        return 0;
-      }
-    }
-  }
-
-  fclose(fp);
-#else
-  (void) name;
-  (void) usa;
-#endif
-
-  return -1;
-}
-
-static void mg_resolve_async_eh(struct mg_connection *nc, int ev,
-                                void *data MG_UD_ARG(void *user_data)) {
-  time_t now = (time_t) mg_time();
-  struct mg_resolve_async_request *req;
-  struct mg_dns_message *msg;
-#if !MG_ENABLE_CALLBACK_USERDATA
-  void *user_data = nc->user_data;
-#endif
-
-  if (ev != MG_EV_POLL) {
-    DBG(("ev=%d user_data=%p", ev, (void*)user_data));
-  }
-
-  req = (struct mg_resolve_async_request *) user_data;
-
-  if (req == NULL) {
-    return;
-  }
-
-  switch (ev) {
-    case MG_EV_POLL:
-      if (req->retries > req->max_retries) {
-        req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT;
-        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-        break;
-      }
-      if (nc->flags & MG_F_CONNECTING) break;
-    /* fallthrough */
-    case MG_EV_CONNECT:
-      if (req->retries == 0 || now - req->last_time >= req->timeout) {
-        mg_send_dns_query(nc, req->name, req->query);
-        req->last_time = now;
-        req->retries++;
-      }
-      break;
-    case MG_EV_RECV:
-      msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
-      if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
-          msg->num_answers > 0) {
-        req->callback(msg, req->data, MG_RESOLVE_OK);
-        nc->user_data = NULL;
-        MG_FREE(req);
-      } else {
-        req->err = MG_RESOLVE_NO_ANSWERS;
-      }
-      MG_FREE(msg);
-      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-      break;
-    case MG_EV_SEND:
-      /*
-       * If a send error occurs, prevent closing of the connection by the core.
-       * We will retry after timeout.
-       */
-      nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
-      mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
-      break;
-    case MG_EV_TIMER:
-      req->err = MG_RESOLVE_TIMEOUT;
-      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-      break;
-    case MG_EV_CLOSE:
-      /* If we got here with request still not done, fire an error callback. */
-      if (req != NULL) {
-        char addr[32];
-        mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr), MG_SOCK_STRINGIFY_IP);
-#ifdef MG_LOG_DNS_FAILURES
-        LOG(LL_ERROR, ("Failed to resolve '%s', server %s", req->name, addr));
-#endif
-        req->callback(NULL, req->data, req->err);
-        nc->user_data = NULL;
-        MG_FREE(req);
-      }
-      break;
-  }
-}
-
-int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
-                     mg_resolve_callback_t cb, void *data) {
-  struct mg_resolve_async_opts opts;
-  memset(&opts, 0, sizeof(opts));
-  return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
-}
-
-int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
-                         mg_resolve_callback_t cb, void *data,
-                         struct mg_resolve_async_opts opts) {
-  struct mg_resolve_async_request *req;
-  struct mg_connection *dns_nc;
-  const char *nameserver = opts.nameserver;
-  char dns_server_buff[17], nameserver_url[26];
-
-  if (nameserver == NULL) {
-    nameserver = mgr->nameserver;
-  }
-
-  DBG(("%s %d %p", name, query, (void*)opts.dns_conn));
-
-  /* resolve with DNS */
-  req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
-  if (req == NULL) {
-    return -1;
-  }
-
-  strncpy(req->name, name, sizeof(req->name));
-  req->name[sizeof(req->name) - 1] = '\0';
-
-  req->query = query;
-  req->callback = cb;
-  req->data = data;
-  /* TODO(mkm): parse defaults out of resolve.conf */
-  req->max_retries = opts.max_retries ? opts.max_retries : 2;
-  req->timeout = opts.timeout ? opts.timeout : 5;
-
-  /* Lazily initialize dns server */
-  if (nameserver == NULL) {
-    if (mg_get_ip_address_of_nameserver(dns_server_buff,
-                                        sizeof(dns_server_buff)) != -1) {
-      nameserver = dns_server_buff;
-    } else {
-      nameserver = MG_DEFAULT_NAMESERVER;
-    }
-  }
-
-  snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver);
-
-  dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL));
-  if (dns_nc == NULL) {
-    MG_FREE(req);
-    return -1;
-  }
-  dns_nc->user_data = req;
-  if (opts.dns_conn != NULL) {
-    *opts.dns_conn = dns_nc;
-  }
-
-  return 0;
-}
-
-void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) {
-  MG_FREE((char *) mgr->nameserver);
-  mgr->nameserver = NULL;
-  if (nameserver != NULL) {
-    mgr->nameserver = strdup(nameserver);
-  }
-}
-
-#endif /* MG_ENABLE_ASYNC_RESOLVER */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_coap.c"
-#endif
-
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_coap.h" */
-
-#if MG_ENABLE_COAP
-
-void mg_coap_free_options(struct mg_coap_message *cm) {
-  while (cm->options != NULL) {
-    struct mg_coap_option *next = cm->options->next;
-    MG_FREE(cm->options);
-    cm->options = next;
-  }
-}
-
-struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
-                                          uint32_t number, char *value,
-                                          size_t len) {
-  struct mg_coap_option *new_option =
-      (struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
-
-  new_option->number = number;
-  new_option->value.p = value;
-  new_option->value.len = len;
-
-  if (cm->options == NULL) {
-    cm->options = cm->optiomg_tail = new_option;
-  } else {
-    /*
-     * A very simple attention to help clients to compose options:
-     * CoAP wants to see options ASC ordered.
-     * Could be change by using sort in coap_compose
-     */
-    if (cm->optiomg_tail->number <= new_option->number) {
-      /* if option is already ordered just add it */
-      cm->optiomg_tail = cm->optiomg_tail->next = new_option;
-    } else {
-      /* looking for appropriate position */
-      struct mg_coap_option *current_opt = cm->options;
-      struct mg_coap_option *prev_opt = 0;
-
-      while (current_opt != NULL) {
-        if (current_opt->number > new_option->number) {
-          break;
-        }
-        prev_opt = current_opt;
-        current_opt = current_opt->next;
-      }
-
-      if (prev_opt != NULL) {
-        prev_opt->next = new_option;
-        new_option->next = current_opt;
-      } else {
-        /* insert new_option to the beginning */
-        new_option->next = cm->options;
-        cm->options = new_option;
-      }
-    }
-  }
-
-  return new_option;
-}
-
-/*
- * Fills CoAP header in mg_coap_message.
- *
- * Helper function.
- */
-static char *coap_parse_header(char *ptr, struct mbuf *io,
-                               struct mg_coap_message *cm) {
-  if (io->len < sizeof(uint32_t)) {
-    cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
-    return NULL;
-  }
-
-  /*
-   * Version (Ver):  2-bit unsigned integer.  Indicates the CoAP version
-   * number.  Implementations of this specification MUST set this field
-   * to 1 (01 binary).  Other values are reserved for future versions.
-   * Messages with unknown version numbers MUST be silently ignored.
-   */
-  if (((uint8_t) *ptr >> 6) != 1) {
-    cm->flags |= MG_COAP_IGNORE;
-    return NULL;
-  }
-
-  /*
-   * Type (T):  2-bit unsigned integer.  Indicates if this message is of
-   * type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
-   * Reset (3).
-   */
-  cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
-  cm->flags |= MG_COAP_MSG_TYPE_FIELD;
-
-  /*
-   * Token Length (TKL):  4-bit unsigned integer.  Indicates the length of
-   * the variable-length Token field (0-8 bytes).  Lengths 9-15 are
-   * reserved, MUST NOT be sent, and MUST be processed as a message
-   * format error.
-   */
-  cm->token.len = *ptr & 0x0F;
-  if (cm->token.len > 8) {
-    cm->flags |= MG_COAP_FORMAT_ERROR;
-    return NULL;
-  }
-
-  ptr++;
-
-  /*
-   * Code:  8-bit unsigned integer, split into a 3-bit class (most
-   * significant bits) and a 5-bit detail (least significant bits)
-   */
-  cm->code_class = (uint8_t) *ptr >> 5;
-  cm->code_detail = *ptr & 0x1F;
-  cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
-
-  ptr++;
-
-  /* Message ID:  16-bit unsigned integer in network byte order. */
-  cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
-  cm->flags |= MG_COAP_MSG_ID_FIELD;
-
-  ptr += 2;
-
-  return ptr;
-}
-
-/*
- * Fills token information in mg_coap_message.
- *
- * Helper function.
- */
-static char *coap_get_token(char *ptr, struct mbuf *io,
-                            struct mg_coap_message *cm) {
-  if (cm->token.len != 0) {
-    if (ptr + cm->token.len > io->buf + io->len) {
-      cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
-      return NULL;
-    } else {
-      cm->token.p = ptr;
-      ptr += cm->token.len;
-      cm->flags |= MG_COAP_TOKEN_FIELD;
-    }
-  }
-
-  return ptr;
-}
-
-/*
- * Returns Option Delta or Length.
- *
- * Helper function.
- */
-static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
-  int ret = 0;
-
-  if (*opt_info == 13) {
-    /*
-     * 13:  An 8-bit unsigned integer follows the initial byte and
-     * indicates the Option Delta/Length minus 13.
-     */
-    if (ptr < io->buf + io->len) {
-      *opt_info = (uint8_t) *ptr + 13;
-      ret = sizeof(uint8_t);
-    } else {
-      ret = -1; /* LCOV_EXCL_LINE */
-    }
-  } else if (*opt_info == 14) {
-    /*
-     * 14:  A 16-bit unsigned integer in network byte order follows the
-     * initial byte and indicates the Option Delta/Length minus 269.
-     */
-    if (ptr + sizeof(uint8_t) < io->buf + io->len) {
-      *opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
-      ret = sizeof(uint16_t);
-    } else {
-      ret = -1; /* LCOV_EXCL_LINE */
-    }
-  }
-
-  return ret;
-}
-
-/*
- * Fills options in mg_coap_message.
- *
- * Helper function.
- *
- * General options format:
- * +---------------+---------------+
- * | Option Delta  | Option Length |  1 byte
- * +---------------+---------------+
- * \    Option Delta (extended)    \  0-2 bytes
- * +-------------------------------+
- * / Option Length  (extended)     \  0-2 bytes
- * +-------------------------------+
- * \         Option Value          \  0 or more bytes
- * +-------------------------------+
- */
-static char *coap_get_options(char *ptr, struct mbuf *io,
-                              struct mg_coap_message *cm) {
-  uint16_t prev_opt = 0;
-
-  if (ptr == io->buf + io->len) {
-    /* end of packet, ok */
-    return NULL;
-  }
-
-  /* 0xFF is payload marker */
-  while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
-    uint16_t option_delta, option_lenght;
-    int optinfo_len;
-
-    /* Option Delta:  4-bit unsigned integer */
-    option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
-    /* Option Length:  4-bit unsigned integer */
-    option_lenght = *ptr & 0x0F;
-
-    if (option_delta == 15 || option_lenght == 15) {
-      /*
-       * 15:  Reserved for future use.  If the field is set to this value,
-       * it MUST be processed as a message format error
-       */
-      cm->flags |= MG_COAP_FORMAT_ERROR;
-      break;
-    }
-
-    ptr++;
-
-    /* check for extended option delta */
-    optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
-    if (optinfo_len == -1) {
-      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
-      break;                                /* LCOV_EXCL_LINE */
-    }
-
-    ptr += optinfo_len;
-
-    /* check or extended option lenght */
-    optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
-    if (optinfo_len == -1) {
-      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
-      break;                                /* LCOV_EXCL_LINE */
-    }
-
-    ptr += optinfo_len;
-
-    /*
-     * Instead of specifying the Option Number directly, the instances MUST
-     * appear in order of their Option Numbers and a delta encoding is used
-     * between them.
-     */
-    option_delta += prev_opt;
-
-    mg_coap_add_option(cm, option_delta, ptr, option_lenght);
-
-    prev_opt = option_delta;
-
-    if (ptr + option_lenght > io->buf + io->len) {
-      cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
-      break;                                /* LCOV_EXCL_LINE */
-    }
-
-    ptr += option_lenght;
-  }
-
-  if ((cm->flags & MG_COAP_ERROR) != 0) {
-    mg_coap_free_options(cm);
-    return NULL;
-  }
-
-  cm->flags |= MG_COAP_OPTIOMG_FIELD;
-
-  if (ptr == io->buf + io->len) {
-    /* end of packet, ok */
-    return NULL;
-  }
-
-  ptr++;
-
-  return ptr;
-}
-
-uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
-  char *ptr;
-
-  memset(cm, 0, sizeof(*cm));
-
-  if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
-    return cm->flags;
-  }
-
-  if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
-    return cm->flags;
-  }
-
-  if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
-    return cm->flags;
-  }
-
-  /* the rest is payload */
-  cm->payload.len = io->len - (ptr - io->buf);
-  if (cm->payload.len != 0) {
-    cm->payload.p = ptr;
-    cm->flags |= MG_COAP_PAYLOAD_FIELD;
-  }
-
-  return cm->flags;
-}
-
-/*
- * Calculates extended size of given Opt Number/Length in coap message.
- *
- * Helper function.
- */
-static size_t coap_get_ext_opt_size(uint32_t value) {
-  int ret = 0;
-
-  if (value >= 13 && value <= 0xFF + 13) {
-    ret = sizeof(uint8_t);
-  } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
-    ret = sizeof(uint16_t);
-  }
-
-  return ret;
-}
-
-/*
- * Splits given Opt Number/Length into base and ext values.
- *
- * Helper function.
- */
-static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
-  int ret = 0;
-
-  if (value < 13) {
-    *base = value;
-  } else if (value >= 13 && value <= 0xFF + 13) {
-    *base = 13;
-    *ext = value - 13;
-    ret = sizeof(uint8_t);
-  } else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
-    *base = 14;
-    *ext = value - 269;
-    ret = sizeof(uint16_t);
-  }
-
-  return ret;
-}
-
-/*
- * Puts uint16_t (in network order) into given char stream.
- *
- * Helper function.
- */
-static char *coap_add_uint16(char *ptr, uint16_t val) {
-  *ptr = val >> 8;
-  ptr++;
-  *ptr = val & 0x00FF;
-  ptr++;
-  return ptr;
-}
-
-/*
- * Puts extended value of Opt Number/Length into given char stream.
- *
- * Helper function.
- */
-static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
-  if (len == sizeof(uint8_t)) {
-    *ptr = (char) val;
-    ptr++;
-  } else if (len == sizeof(uint16_t)) {
-    ptr = coap_add_uint16(ptr, val);
-  }
-
-  return ptr;
-}
-
-/*
- * Verifies given mg_coap_message and calculates message size for it.
- *
- * Helper function.
- */
-static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
-                                           size_t *len) {
-  struct mg_coap_option *opt;
-  uint32_t prev_opt_number;
-
-  *len = 4; /* header */
-  if (cm->msg_type > MG_COAP_MSG_MAX) {
-    return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
-  }
-  if (cm->token.len > 8) {
-    return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
-  }
-  if (cm->code_class > 7) {
-    return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
-  }
-  if (cm->code_detail > 31) {
-    return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
-  }
-
-  *len += cm->token.len;
-  if (cm->payload.len != 0) {
-    *len += cm->payload.len + 1; /* ... + 1; add payload marker */
-  }
-
-  opt = cm->options;
-  prev_opt_number = 0;
-  while (opt != NULL) {
-    *len += 1; /* basic delta/length */
-    *len += coap_get_ext_opt_size(opt->number - prev_opt_number);
-    *len += coap_get_ext_opt_size((uint32_t) opt->value.len);
-    /*
-     * Current implementation performs check if
-     * option_number > previous option_number and produces an error
-     * TODO(alashkin): write design doc with limitations
-     * May be resorting is more suitable solution.
-     */
-    if ((opt->next != NULL && opt->number > opt->next->number) ||
-        opt->value.len > 0xFFFF + 269 ||
-        opt->number - prev_opt_number > 0xFFFF + 269) {
-      return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
-    }
-    *len += opt->value.len;
-    prev_opt_number = opt->number;
-    opt = opt->next;
-  }
-
-  return 0;
-}
-
-uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
-  struct mg_coap_option *opt;
-  uint32_t res, prev_opt_number;
-  size_t prev_io_len, packet_size;
-  char *ptr;
-
-  res = coap_calculate_packet_size(cm, &packet_size);
-  if (res != 0) {
-    return res;
-  }
-
-  /* saving previous lenght to handle non-empty mbuf */
-  prev_io_len = io->len;
-  if (mbuf_append(io, NULL, packet_size) == 0) return MG_COAP_ERROR;
-  ptr = io->buf + prev_io_len;
-
-  /*
-   * since cm is verified, it is possible to use bits shift operator
-   * without additional zeroing of unused bits
-   */
-
-  /* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
-  *ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
-  ptr++;
-
-  /* code class: 3 bits, code detail: 5 bits */
-  *ptr = (cm->code_class << 5) | (cm->code_detail);
-  ptr++;
-
-  ptr = coap_add_uint16(ptr, cm->msg_id);
-
-  if (cm->token.len != 0) {
-    memcpy(ptr, cm->token.p, cm->token.len);
-    ptr += cm->token.len;
-  }
-
-  opt = cm->options;
-  prev_opt_number = 0;
-  while (opt != NULL) {
-    uint8_t delta_base = 0, length_base = 0;
-    uint16_t delta_ext = 0, length_ext = 0;
-
-    size_t opt_delta_len =
-        coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
-    size_t opt_lenght_len =
-        coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
-
-    *ptr = (delta_base << 4) | length_base;
-    ptr++;
-
-    ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
-    ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
-
-    if (opt->value.len != 0) {
-      memcpy(ptr, opt->value.p, opt->value.len);
-      ptr += opt->value.len;
-    }
-
-    prev_opt_number = opt->number;
-    opt = opt->next;
-  }
-
-  if (cm->payload.len != 0) {
-    *ptr = (char) -1;
-    ptr++;
-    memcpy(ptr, cm->payload.p, cm->payload.len);
-  }
-
-  return 0;
-}
-
-uint32_t mg_coap_send_message(struct mg_connection *nc,
-                              struct mg_coap_message *cm) {
-  struct mbuf packet_out;
-  uint32_t compose_res;
-
-  mbuf_init(&packet_out, 0);
-  compose_res = mg_coap_compose(cm, &packet_out);
-  if (compose_res != 0) {
-    return compose_res; /* LCOV_EXCL_LINE */
-  }
-
-  mg_send(nc, packet_out.buf, (int) packet_out.len);
-  mbuf_free(&packet_out);
-
-  return 0;
-}
-
-uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
-  struct mg_coap_message cm;
-  memset(&cm, 0, sizeof(cm));
-  cm.msg_type = MG_COAP_MSG_ACK;
-  cm.msg_id = msg_id;
-
-  return mg_coap_send_message(nc, &cm);
-}
-
-static void coap_handler(struct mg_connection *nc, int ev,
-                         void *ev_data MG_UD_ARG(void *user_data)) {
-  struct mbuf *io = &nc->recv_mbuf;
-  struct mg_coap_message cm;
-  uint32_t parse_res;
-
-  memset(&cm, 0, sizeof(cm));
-
-  nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
-
-  switch (ev) {
-    case MG_EV_RECV:
-      parse_res = mg_coap_parse(io, &cm);
-      if ((parse_res & MG_COAP_IGNORE) == 0) {
-        if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
-          /*
-           * Since we support UDP only
-           * MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
-           */
-          cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
-        }                                   /* LCOV_EXCL_LINE */
-        nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type,
-                    &cm MG_UD_ARG(user_data));
-      }
-
-      mg_coap_free_options(&cm);
-      mbuf_remove(io, io->len);
-      break;
-  }
-}
-/*
- * Attach built-in CoAP event handler to the given connection.
- *
- * The user-defined event handler will receive following extra events:
- *
- * - MG_EV_COAP_CON
- * - MG_EV_COAP_NOC
- * - MG_EV_COAP_ACK
- * - MG_EV_COAP_RST
- */
-int mg_set_protocol_coap(struct mg_connection *nc) {
-  /* supports UDP only */
-  if ((nc->flags & MG_F_UDP) == 0) {
-    return -1;
-  }
-
-  nc->proto_handler = coap_handler;
-
-  return 0;
-}
-
-#endif /* MG_ENABLE_COAP */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_sntp.c"
-#endif
-
-/* Amalgamated: #include "mg_internal.h" */
-/* Amalgamated: #include "mg_sntp.h" */
-/* Amalgamated: #include "mg_util.h" */
-
-#if MG_ENABLE_SNTP
-
-#define SNTP_TIME_OFFSET 2208988800
-
-#ifndef SNTP_TIMEOUT
-#define SNTP_TIMEOUT 10
-#endif
-
-#ifndef SNTP_ATTEMPTS
-#define SNTP_ATTEMPTS 3
-#endif
-
-static uint64_t mg_get_sec(uint64_t val) {
-  return (val & 0xFFFFFFFF00000000) >> 32;
-}
-
-static uint64_t mg_get_usec(uint64_t val) {
-  uint64_t tmp = (val & 0x00000000FFFFFFFF);
-  tmp *= 1000000;
-  tmp >>= 32;
-  return tmp;
-}
-
-static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) {
-  uint64_t tmp;
-  tmp = mg_get_sec(val);
-  tmp -= SNTP_TIME_OFFSET;
-  tv->tv_sec = tmp;
-  tv->tv_usec = mg_get_usec(val);
-}
-
-static void mg_get_ntp_ts(const char *ntp, uint64_t *val) {
-  uint32_t tmp;
-  memcpy(&tmp, ntp, sizeof(tmp));
-  tmp = ntohl(tmp);
-  *val = (uint64_t) tmp << 32;
-  memcpy(&tmp, ntp + 4, sizeof(tmp));
-  tmp = ntohl(tmp);
-  *val |= tmp;
-}
-
-void mg_sntp_send_request(struct mg_connection *c) {
-  uint8_t buf[48] = {0};
-  /*
-   * header - 8 bit:
-   * LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version),
-   * mode (3 bit) - 3 (client)
-   */
-  buf[0] = (3 << 6) | (4 << 3) | 3;
-
-/*
- * Next fields should be empty in client request
- * stratum, 8 bit
- * poll interval, 8 bit
- * rrecision, 8 bit
- * root delay, 32 bit
- * root dispersion, 32 bit
- * ref id, 32 bit
- * ref timestamp, 64 bit
- * originate Timestamp, 64 bit
- * receive Timestamp, 64 bit
-*/
-
-/*
- * convert time to sntp format (sntp starts from 00:00:00 01.01.1900)
- * according to rfc868 it is 2208988800L sec
- * this information is used to correct roundtrip delay
- * but if local clock is absolutely broken (and doesn't work even
- * as simple timer), it is better to disable it
-*/
-#ifndef MG_SNTP_NO_DELAY_CORRECTION
-  uint32_t sec;
-  sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET));
-  memcpy(&buf[40], &sec, sizeof(sec));
-#endif
-
-  mg_send(c, buf, sizeof(buf));
-}
-
-#ifndef MG_SNTP_NO_DELAY_CORRECTION
-static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) {
-  /* roundloop delay = (T4 - T1) - (T3 - T2) */
-  uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) -
-                (mg_get_sec(t1) * 1000000 + mg_get_usec(t1));
-  uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) -
-                (mg_get_sec(t2) * 1000000 + mg_get_usec(t2));
-
-  return (d1 > d2) ? d1 - d2 : 0;
-}
-#endif
-
-MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
-                                    struct mg_sntp_message *msg) {
-  uint8_t hdr;
-  uint64_t trsm_ts_T3, delay = 0;
-  int mode;
-  struct timeval tv;
-
-  if (len < 48) {
-    return -1;
-  }
-
-  hdr = buf[0];
-
-  if ((hdr & 0x38) >> 3 != 4) {
-    /* Wrong version */
-    return -1;
-  }
-
-  mode = hdr & 0x7;
-  if (mode != 4 && mode != 5) {
-    /* Not a server reply */
-    return -1;
-  }
-
-  memset(msg, 0, sizeof(*msg));
-
-  msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */
-
-  mg_get_ntp_ts(&buf[40], &trsm_ts_T3);
-
-#ifndef MG_SNTP_NO_DELAY_CORRECTION
-  {
-    uint64_t orig_ts_T1, recv_ts_T2;
-    mg_get_ntp_ts(&buf[24], &orig_ts_T1);
-    mg_get_ntp_ts(&buf[32], &recv_ts_T2);
-    delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3);
-  }
-#endif
-
-  mg_ntp_to_tv(trsm_ts_T3, &tv);
-
-  msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0);
-
-  return 0;
-}
-
-static void mg_sntp_handler(struct mg_connection *c, int ev,
-                            void *ev_data MG_UD_ARG(void *user_data)) {
-  struct mbuf *io = &c->recv_mbuf;
-  struct mg_sntp_message msg;
-
-  c->handler(c, ev, ev_data MG_UD_ARG(user_data));
-
-  switch (ev) {
-    case MG_EV_RECV: {
-      if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) {
-        DBG(("Invalid SNTP packet received (%d)", (int) io->len));
-        c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data));
-      } else {
-        c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data));
-      }
-
-      mbuf_remove(io, io->len);
-      break;
-    }
-  }
-}
-
-int mg_set_protocol_sntp(struct mg_connection *c) {
-  if ((c->flags & MG_F_UDP) == 0) {
-    return -1;
-  }
-
-  c->proto_handler = mg_sntp_handler;
-
-  return 0;
-}
-
-struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
-                                      MG_CB(mg_event_handler_t event_handler,
-                                            void *user_data),
-                                      const char *sntp_server_name) {
-  struct mg_connection *c = NULL;
-  char url[100], *p_url = url;
-  const char *proto = "", *port = "", *tmp;
-
-  /* If port is not specified, use default (123) */
-  tmp = strchr(sntp_server_name, ':');
-  if (tmp != NULL && *(tmp + 1) == '/') {
-    tmp = strchr(tmp + 1, ':');
-  }
-
-  if (tmp == NULL) {
-    port = ":123";
-  }
-
-  /* Add udp:// if needed */
-  if (strncmp(sntp_server_name, "udp://", 6) != 0) {
-    proto = "udp://";
-  }
-
-  mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port);
-
-  c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data));
-
-  if (c == NULL) {
-    goto cleanup;
-  }
-
-  mg_set_protocol_sntp(c);
-
-cleanup:
-  if (p_url != url) {
-    MG_FREE(p_url);
-  }
-
-  return c;
-}
-
-struct sntp_data {
-  mg_event_handler_t hander;
-  int count;
-};
-
-static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev,
-                                    void *ev_data MG_UD_ARG(void *user_data)) {
-#if !MG_ENABLE_CALLBACK_USERDATA
-  void *user_data = c->user_data;
-#endif
-  struct sntp_data *sd = (struct sntp_data *) user_data;
-
-  switch (ev) {
-    case MG_EV_CONNECT:
-      if (*(int *) ev_data != 0) {
-        mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
-        break;
-      }
-    /* fallthrough */
-    case MG_EV_TIMER:
-      if (sd->count <= SNTP_ATTEMPTS) {
-        mg_sntp_send_request(c);
-        mg_set_timer(c, mg_time() + 10);
-        sd->count++;
-      } else {
-        mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
-        c->flags |= MG_F_CLOSE_IMMEDIATELY;
-      }
-      break;
-    case MG_SNTP_MALFORMED_REPLY:
-      mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
-      c->flags |= MG_F_CLOSE_IMMEDIATELY;
-      break;
-    case MG_SNTP_REPLY:
-      mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data);
-      c->flags |= MG_F_CLOSE_IMMEDIATELY;
-      break;
-    case MG_EV_CLOSE:
-      MG_FREE(user_data);
-      c->user_data = NULL;
-      break;
-  }
-}
-
-struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
-                                       mg_event_handler_t event_handler,
-                                       const char *sntp_server_name) {
-  struct mg_connection *c;
-  struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd));
-  if (sd == NULL) {
-    return NULL;
-  }
-
-  c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd),
-                      sntp_server_name);
-  if (c == NULL) {
-    MG_FREE(sd);
-    return NULL;
-  }
-
-  sd->hander = event_handler;
-#if !MG_ENABLE_CALLBACK_USERDATA
-  c->user_data = sd;
-#endif
-
-  return c;
-}
-
-#endif /* MG_ENABLE_SNTP */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_socks.c"
-#endif
-
-#if MG_ENABLE_SOCKS
-
-/* Amalgamated: #include "mg_socks.h" */
-/* Amalgamated: #include "mg_internal.h" */
-
-/*
- *  https://www.ietf.org/rfc/rfc1928.txt paragraph 3, handle client handshake
- *
- *  +----+----------+----------+
- *  |VER | NMETHODS | METHODS  |
- *  +----+----------+----------+
- *  | 1  |    1     | 1 to 255 |
- *  +----+----------+----------+
- */
-static void mg_socks5_handshake(struct mg_connection *c) {
-  struct mbuf *r = &c->recv_mbuf;
-  if (r->buf[0] != MG_SOCKS_VERSION) {
-    c->flags |= MG_F_CLOSE_IMMEDIATELY;
-  } else if (r->len > 2 && (size_t) r->buf[1] + 2 <= r->len) {
-    /* https://www.ietf.org/rfc/rfc1928.txt paragraph 3 */
-    unsigned char reply[2] = {MG_SOCKS_VERSION, MG_SOCKS_HANDSHAKE_FAILURE};
-    int i;
-    for (i = 2; i < r->buf[1] + 2; i++) {
-      /* TODO(lsm): support other auth methods */
-      if (r->buf[i] == MG_SOCKS_HANDSHAKE_NOAUTH) reply[1] = r->buf[i];
-    }
-    mbuf_remove(r, 2 + r->buf[1]);
-    mg_send(c, reply, sizeof(reply));
-    c->flags |= MG_SOCKS_HANDSHAKE_DONE; /* Mark handshake done */
-  }
-}
-
-static void disband(struct mg_connection *c) {
-  struct mg_connection *c2 = (struct mg_connection *) c->user_data;
-  if (c2 != NULL) {
-    c2->flags |= MG_F_SEND_AND_CLOSE;
-    c2->user_data = NULL;
-  }
-  c->flags |= MG_F_SEND_AND_CLOSE;
-  c->user_data = NULL;
-}
-
-static void relay_data(struct mg_connection *c) {
-  struct mg_connection *c2 = (struct mg_connection *) c->user_data;
-  if (c2 != NULL) {
-    mg_send(c2, c->recv_mbuf.buf, c->recv_mbuf.len);
-    mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
-  } else {
-    c->flags |= MG_F_SEND_AND_CLOSE;
-  }
-}
-
-static void serv_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
-  if (ev == MG_EV_CLOSE) {
-    disband(c);
-  } else if (ev == MG_EV_RECV) {
-    relay_data(c);
-  } else if (ev == MG_EV_CONNECT) {
-    int res = *(int *) ev_data;
-    if (res != 0) LOG(LL_ERROR, ("connect error: %d", res));
-  }
-}
-
-static void mg_socks5_connect(struct mg_connection *c, const char *addr) {
-  struct mg_connection *serv = mg_connect(c->mgr, addr, serv_ev_handler);
-  serv->user_data = c;
-  c->user_data = serv;
-}
-
-/*
- *  Request, https://www.ietf.org/rfc/rfc1928.txt paragraph 4
- *
- *  +----+-----+-------+------+----------+----------+
- *  |VER | CMD |  RSV  | ATYP | DST.ADDR | DST.PORT |
- *  +----+-----+-------+------+----------+----------+
- *  | 1  |  1  | X'00' |  1   | Variable |    2     |
- *  +----+-----+-------+------+----------+----------+
- */
-static void mg_socks5_handle_request(struct mg_connection *c) {
-  struct mbuf *r = &c->recv_mbuf;
-  unsigned char *p = (unsigned char *) r->buf;
-  unsigned char addr_len = 4, reply = MG_SOCKS_SUCCESS;
-  int ver, cmd, atyp;
-  char addr[300];
-
-  if (r->len < 8) return; /* return if not fully buffered. min DST.ADDR is 2 */
-  ver = p[0];
-  cmd = p[1];
-  atyp = p[3];
-
-  /* TODO(lsm): support other commands */
-  if (ver != MG_SOCKS_VERSION || cmd != MG_SOCKS_CMD_CONNECT) {
-    reply = MG_SOCKS_CMD_NOT_SUPPORTED;
-  } else if (atyp == MG_SOCKS_ADDR_IPV4) {
-    addr_len = 4;
-    if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
-    snprintf(addr, sizeof(addr), "%d.%d.%d.%d:%d", p[4], p[5], p[6], p[7],
-             p[8] << 8 | p[9]);
-    mg_socks5_connect(c, addr);
-  } else if (atyp == MG_SOCKS_ADDR_IPV6) {
-    addr_len = 16;
-    if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
-    snprintf(addr, sizeof(addr), "[%x:%x:%x:%x:%x:%x:%x:%x]:%d",
-             p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9],
-             p[10] << 8 | p[11], p[12] << 8 | p[13], p[14] << 8 | p[15],
-             p[16] << 8 | p[17], p[18] << 8 | p[19], p[20] << 8 | p[21]);
-    mg_socks5_connect(c, addr);
-  } else if (atyp == MG_SOCKS_ADDR_DOMAIN) {
-    addr_len = p[4] + 1;
-    if (r->len < (size_t) addr_len + 6) return; /* return if not buffered */
-    snprintf(addr, sizeof(addr), "%.*s:%d", p[4], p + 5,
-             p[4 + addr_len] << 8 | p[4 + addr_len + 1]);
-    mg_socks5_connect(c, addr);
-  } else {
-    reply = MG_SOCKS_ADDR_NOT_SUPPORTED;
-  }
-
-  /*
-   *  Reply, https://www.ietf.org/rfc/rfc1928.txt paragraph 5
-   *
-   *  +----+-----+-------+------+----------+----------+
-   *  |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
-   *  +----+-----+-------+------+----------+----------+
-   *  | 1  |  1  | X'00' |  1   | Variable |    2     |
-   *  +----+-----+-------+------+----------+----------+
-   */
-  {
-    unsigned char buf[] = {MG_SOCKS_VERSION, reply, 0};
-    mg_send(c, buf, sizeof(buf));
-  }
-  mg_send(c, r->buf + 3, addr_len + 1 + 2);
-
-  mbuf_remove(r, 6 + addr_len);      /* Remove request from the input stream */
-  c->flags |= MG_SOCKS_CONNECT_DONE; /* Mark ourselves as connected */
-}
-
-static void socks_handler(struct mg_connection *c, int ev, void *ev_data) {
-  if (ev == MG_EV_RECV) {
-    if (!(c->flags & MG_SOCKS_HANDSHAKE_DONE)) mg_socks5_handshake(c);
-    if (c->flags & MG_SOCKS_HANDSHAKE_DONE &&
-        !(c->flags & MG_SOCKS_CONNECT_DONE)) {
-      mg_socks5_handle_request(c);
-    }
-    if (c->flags & MG_SOCKS_CONNECT_DONE) relay_data(c);
-  } else if (ev == MG_EV_CLOSE) {
-    disband(c);
-  }
-  (void) ev_data;
-}
-
-void mg_set_protocol_socks(struct mg_connection *c) {
-  c->proto_handler = socks_handler;
-}
-#endif
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/cc3200/cc3200_libc.c"
-#endif
-
-#if CS_PLATFORM == CS_P_CC3200
-
-/* Amalgamated: #include "common/mg_mem.h" */
-#include <stdio.h>
-#include <string.h>
-
-#ifndef __TI_COMPILER_VERSION__
-#include <reent.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <unistd.h>
-#endif
-
-#include <inc/hw_types.h>
-#include <inc/hw_memmap.h>
-#include <driverlib/prcm.h>
-#include <driverlib/rom.h>
-#include <driverlib/rom_map.h>
-#include <driverlib/uart.h>
-#include <driverlib/utils.h>
-
-#define CONSOLE_UART UARTA0_BASE
-
-#ifdef __TI_COMPILER_VERSION__
-int asprintf(char **strp, const char *fmt, ...) {
-  va_list ap;
-  int len;
-
-  *strp = MG_MALLOC(BUFSIZ);
-  if (*strp == NULL) return -1;
-
-  va_start(ap, fmt);
-  len = vsnprintf(*strp, BUFSIZ, fmt, ap);
-  va_end(ap);
-
-  if (len > 0) {
-    *strp = MG_REALLOC(*strp, len + 1);
-    if (*strp == NULL) return -1;
-  }
-
-  if (len >= BUFSIZ) {
-    va_start(ap, fmt);
-    len = vsnprintf(*strp, len + 1, fmt, ap);
-    va_end(ap);
-  }
-
-  return len;
-}
-
-#if MG_TI_NO_HOST_INTERFACE
-time_t HOSTtime() {
-  struct timeval tp;
-  gettimeofday(&tp, NULL);
-  return tp.tv_sec;
-}
-#endif
-
-#endif /* __TI_COMPILER_VERSION__ */
-
-void fprint_str(FILE *fp, const char *str) {
-  while (*str != '\0') {
-    if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
-    MAP_UARTCharPut(CONSOLE_UART, *str++);
-  }
-}
-
-void _exit(int status) {
-  fprint_str(stderr, "_exit\n");
-  /* cause an unaligned access exception, that will drop you into gdb */
-  *(int *) 1 = status;
-  while (1)
-    ; /* avoid gcc warning because stdlib abort() has noreturn attribute */
-}
-
-void _not_implemented(const char *what) {
-  fprint_str(stderr, what);
-  fprint_str(stderr, " is not implemented\n");
-  _exit(42);
-}
-
-int _kill(int pid, int sig) {
-  (void) pid;
-  (void) sig;
-  _not_implemented("_kill");
-  return -1;
-}
-
-int _getpid() {
-  fprint_str(stderr, "_getpid is not implemented\n");
-  return 42;
-}
-
-int _isatty(int fd) {
-  /* 0, 1 and 2 are TTYs. */
-  return fd < 2;
-}
-
-#endif /* CS_PLATFORM == CS_P_CC3200 */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/msp432/msp432_libc.c"
-#endif
-
-#if CS_PLATFORM == CS_P_MSP432
-
-#include <ti/sysbios/BIOS.h>
-#include <ti/sysbios/knl/Clock.h>
-
-int gettimeofday(struct timeval *tp, void *tzp) {
-  uint32_t ticks = Clock_getTicks();
-  tp->tv_sec = ticks / 1000;
-  tp->tv_usec = (ticks % 1000) * 1000;
-  return 0;
-}
-
-#endif /* CS_PLATFORM == CS_P_MSP432 */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/nrf5/nrf5_libc.c"
-#endif
-
-#if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
-    defined(__ARMCC_VERSION)
-int gettimeofday(struct timeval *tp, void *tzp) {
-  /* TODO */
-  tp->tv_sec = 0;
-  tp->tv_usec = 0;
-  return 0;
-}
-#endif
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/simplelink/sl_fs_slfs.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
-#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
-
-#if defined(MG_FS_SLFS)
-
-#include <stdio.h>
-#ifndef __TI_COMPILER_VERSION__
-#include <unistd.h>
-#include <sys/stat.h>
-#endif
-
-#define MAX_OPEN_SLFS_FILES 8
-
-/* Indirect libc interface - same functions, different names. */
-int fs_slfs_open(const char *pathname, int flags, mode_t mode);
-int fs_slfs_close(int fd);
-ssize_t fs_slfs_read(int fd, void *buf, size_t count);
-ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
-int fs_slfs_stat(const char *pathname, struct stat *s);
-int fs_slfs_fstat(int fd, struct stat *s);
-off_t fs_slfs_lseek(int fd, off_t offset, int whence);
-int fs_slfs_unlink(const char *filename);
-int fs_slfs_rename(const char *from, const char *to);
-
-void fs_slfs_set_file_size(const char *name, size_t size);
-void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token);
-void fs_slfs_unset_file_flags(const char *name);
-
-#endif /* defined(MG_FS_SLFS) */
-
-#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/simplelink/sl_fs_slfs.c"
-#endif
-
-/* Standard libc interface to TI SimpleLink FS. */
-
-#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
-
-/* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
-
-#include <errno.h>
-
-#if CS_PLATFORM == CS_P_CC3200
-#include <inc/hw_types.h>
-#endif
-
-/* Amalgamated: #include "common/cs_dbg.h" */
-/* Amalgamated: #include "common/mg_mem.h" */
-
-#if SL_MAJOR_VERSION_NUM < 2
-int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) {
-  _i32 fh;
-  _i32 r = sl_FsOpen(fname, flags, (unsigned long *) token, &fh);
-  return (r < 0 ? r : fh);
-}
-#else /* SL_MAJOR_VERSION_NUM >= 2 */
-int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token) {
-  return sl_FsOpen(fname, flags, (unsigned long *) token);
-}
-#endif
-
-/* From sl_fs.c */
-int set_errno(int e);
-const char *drop_dir(const char *fname, bool *is_slfs);
-
-/*
- * With SLFS, you have to pre-declare max file size. Yes. Really.
- * 64K should be enough for everyone. Right?
- */
-#ifndef FS_SLFS_MAX_FILE_SIZE
-#define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
-#endif
-
-struct sl_file_open_info {
-  char *name;
-  size_t size;
-  uint32_t flags;
-  uint32_t *token;
-};
-
-struct sl_fd_info {
-  _i32 fh;
-  _off_t pos;
-  size_t size;
-};
-
-static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
-static struct sl_file_open_info s_sl_file_open_infos[MAX_OPEN_SLFS_FILES];
-
-static struct sl_file_open_info *fs_slfs_find_foi(const char *name,
-                                                  bool create);
-
-static int sl_fs_to_errno(_i32 r) {
-  DBG(("SL error: %d", (int) r));
-  switch (r) {
-    case SL_FS_OK:
-      return 0;
-    case SL_ERROR_FS_FILE_NAME_EXIST:
-      return EEXIST;
-    case SL_ERROR_FS_WRONG_FILE_NAME:
-      return EINVAL;
-    case SL_ERROR_FS_NO_AVAILABLE_NV_INDEX:
-    case SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE:
-      return ENOSPC;
-    case SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM:
-      return ENOMEM;
-    case SL_ERROR_FS_FILE_NOT_EXISTS:
-      return ENOENT;
-    case SL_ERROR_FS_NOT_SUPPORTED:
-      return ENOTSUP;
-  }
-  return ENXIO;
-}
-
-int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
-  int fd;
-  for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
-    if (s_sl_fds[fd].fh <= 0) break;
-  }
-  if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
-  struct sl_fd_info *fi = &s_sl_fds[fd];
-
-  /*
-   * Apply path manipulations again, in case we got here directly
-   * (via TI libc's "add_device").
-   */
-  pathname = drop_dir(pathname, NULL);
-
-  _u32 am = 0;
-  fi->size = (size_t) -1;
-  int rw = (flags & 3);
-  size_t new_size = 0;
-  struct sl_file_open_info *foi =
-      fs_slfs_find_foi(pathname, false /* create */);
-  if (foi != NULL) {
-    LOG(LL_DEBUG, ("FOI for %s: %d 0x%x %p", pathname, (int) foi->size,
-                   (unsigned int) foi->flags, (void*)foi->token));
-  }
-  if (rw == O_RDONLY) {
-    SlFsFileInfo_t sl_fi;
-    _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
-    if (r == SL_FS_OK) {
-      fi->size = SL_FI_FILE_SIZE(sl_fi);
-    }
-    am = SL_FS_READ;
-  } else {
-    if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
-      // FailFS files cannot be opened for append and will be truncated
-      // when opened for write.
-      return set_errno(ENOTSUP);
-    }
-    if (flags & O_CREAT) {
-      if (foi->size > 0) {
-        new_size = foi->size;
-      } else {
-        new_size = FS_SLFS_MAX_FILE_SIZE;
-      }
-      am = FS_MODE_OPEN_CREATE(new_size, 0);
-    } else {
-      am = SL_FS_WRITE;
-    }
-#if SL_MAJOR_VERSION_NUM >= 2
-    am |= SL_FS_OVERWRITE;
-#endif
-  }
-  uint32_t *token = NULL;
-  if (foi != NULL) {
-    am |= foi->flags;
-    token = foi->token;
-  }
-  fi->fh = slfs_open((_u8 *) pathname, am, token);
-  LOG(LL_DEBUG, ("sl_FsOpen(%s, 0x%x, %p) sz %u = %d", pathname, (int) am,
-                 (void*)token, (unsigned int) new_size, (int) fi->fh));
-  int r;
-  if (fi->fh >= 0) {
-    fi->pos = 0;
-    r = fd;
-  } else {
-    r = set_errno(sl_fs_to_errno(fi->fh));
-  }
-  return r;
-}
-
-int fs_slfs_close(int fd) {
-  struct sl_fd_info *fi = &s_sl_fds[fd];
-  if (fi->fh <= 0) return set_errno(EBADF);
-  _i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
-  LOG(LL_DEBUG, ("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
-  s_sl_fds[fd].fh = -1;
-  return set_errno(sl_fs_to_errno(r));
-}
-
-ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
-  struct sl_fd_info *fi = &s_sl_fds[fd];
-  if (fi->fh <= 0) return set_errno(EBADF);
-  /* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
-   */
-  if (fi->pos == fi->size) return 0;
-  _i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
-  DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
-       (int) r));
-  if (r >= 0) {
-    fi->pos += r;
-    return r;
-  }
-  return set_errno(sl_fs_to_errno(r));
-}
-
-ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
-  struct sl_fd_info *fi = &s_sl_fds[fd];
-  if (fi->fh <= 0) return set_errno(EBADF);
-  _i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
-  DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
-       (int) r));
-  if (r >= 0) {
-    fi->pos += r;
-    return r;
-  }
-  return set_errno(sl_fs_to_errno(r));
-}
-
-int fs_slfs_stat(const char *pathname, struct stat *s) {
-  SlFsFileInfo_t sl_fi;
-  /*
-   * Apply path manipulations again, in case we got here directly
-   * (via TI libc's "add_device").
-   */
-  pathname = drop_dir(pathname, NULL);
-  _i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
-  if (r == SL_FS_OK) {
-    s->st_mode = S_IFREG | 0666;
-    s->st_nlink = 1;
-    s->st_size = SL_FI_FILE_SIZE(sl_fi);
-    return 0;
-  }
-  return set_errno(sl_fs_to_errno(r));
-}
-
-int fs_slfs_fstat(int fd, struct stat *s) {
-  struct sl_fd_info *fi = &s_sl_fds[fd];
-  if (fi->fh <= 0) return set_errno(EBADF);
-  s->st_mode = 0666;
-  s->st_mode = S_IFREG | 0666;
-  s->st_nlink = 1;
-  s->st_size = fi->size;
-  return 0;
-}
-
-off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
-  if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
-  switch (whence) {
-    case SEEK_SET:
-      s_sl_fds[fd].pos = offset;
-      break;
-    case SEEK_CUR:
-      s_sl_fds[fd].pos += offset;
-      break;
-    case SEEK_END:
-      return set_errno(ENOTSUP);
-  }
-  return 0;
-}
-
-int fs_slfs_unlink(const char *pathname) {
-  /*
-   * Apply path manipulations again, in case we got here directly
-   * (via TI libc's "add_device").
-   */
-  pathname = drop_dir(pathname, NULL);
-  return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0)));
-}
-
-int fs_slfs_rename(const char *from, const char *to) {
-  return set_errno(ENOTSUP);
-}
-
-static struct sl_file_open_info *fs_slfs_find_foi(const char *name,
-                                                  bool create) {
-  int i = 0;
-  for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
-    if (s_sl_file_open_infos[i].name != NULL &&
-        strcmp(drop_dir(s_sl_file_open_infos[i].name, NULL), name) == 0) {
-      break;
-    }
-  }
-  if (i != MAX_OPEN_SLFS_FILES) return &s_sl_file_open_infos[i];
-  if (!create) return NULL;
-  for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
-    if (s_sl_file_open_infos[i].name == NULL) break;
-  }
-  if (i == MAX_OPEN_SLFS_FILES) {
-    i = 0; /* Evict a random slot. */
-  }
-  if (s_sl_file_open_infos[i].name != NULL) {
-    free(s_sl_file_open_infos[i].name);
-  }
-  s_sl_file_open_infos[i].name = strdup(name);
-  return &s_sl_file_open_infos[i];
-}
-
-void fs_slfs_set_file_size(const char *name, size_t size) {
-  struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */);
-  foi->size = size;
-}
-
-void fs_slfs_set_file_flags(const char *name, uint32_t flags, uint32_t *token) {
-  struct sl_file_open_info *foi = fs_slfs_find_foi(name, true /* create */);
-  foi->flags = flags;
-  foi->token = token;
-}
-
-void fs_slfs_unset_file_flags(const char *name) {
-  struct sl_file_open_info *foi = fs_slfs_find_foi(name, false /* create */);
-  if (foi == NULL) return;
-  free(foi->name);
-  memset(foi, 0, sizeof(*foi));
-}
-
-#endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/simplelink/sl_fs.c"
-#endif
-
-#if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
-    (defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
-
-int set_errno(int e) {
-  errno = e;
-  return (e == 0 ? 0 : -1);
-}
-
-const char *drop_dir(const char *fname, bool *is_slfs) {
-  if (is_slfs != NULL) {
-    *is_slfs = (strncmp(fname, "SL:", 3) == 0);
-    if (*is_slfs) fname += 3;
-  }
-  /* Drop "./", if any */
-  if (fname[0] == '.' && fname[1] == '/') {
-    fname += 2;
-  }
-  /*
-   * Drop / if it is the only one in the path.
-   * This allows use of /pretend/directories but serves /file.txt as normal.
-   */
-  if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) {
-    fname++;
-  }
-  return fname;
-}
-
-#if !defined(MG_FS_NO_VFS)
-
-#include <errno.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#ifdef __TI_COMPILER_VERSION__
-#include <file.h>
-#endif
-
-/* Amalgamated: #include "common/cs_dbg.h" */
-/* Amalgamated: #include "common/platform.h" */
-
-#ifdef CC3200_FS_SPIFFS
-/* Amalgamated: #include "cc3200_fs_spiffs.h" */
-#endif
-
-#ifdef MG_FS_SLFS
-/* Amalgamated: #include "sl_fs_slfs.h" */
-#endif
-
-#define NUM_SYS_FDS 3
-#define SPIFFS_FD_BASE 10
-#define SLFS_FD_BASE 100
-
-#if !defined(MG_UART_CHAR_PUT) && !defined(MG_UART_WRITE)
-#if CS_PLATFORM == CS_P_CC3200
-#include <inc/hw_types.h>
-#include <inc/hw_memmap.h>
-#include <driverlib/rom.h>
-#include <driverlib/rom_map.h>
-#include <driverlib/uart.h>
-#define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
-#else
-#define MG_UART_WRITE(fd, buf, len)
-#endif /* CS_PLATFORM == CS_P_CC3200 */
-#endif /* !MG_UART_CHAR_PUT */
-
-enum fd_type {
-  FD_INVALID,
-  FD_SYS,
-#ifdef CC3200_FS_SPIFFS
-  FD_SPIFFS,
-#endif
-#ifdef MG_FS_SLFS
-  FD_SLFS
-#endif
-};
-static int fd_type(int fd) {
-  if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
-#ifdef CC3200_FS_SPIFFS
-  if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
-    return FD_SPIFFS;
-  }
-#endif
-#ifdef MG_FS_SLFS
-  if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
-    return FD_SLFS;
-  }
-#endif
-  return FD_INVALID;
-}
-
-#if MG_TI_NO_HOST_INTERFACE
-int open(const char *pathname, unsigned flags, int mode) {
-#else
-int _open(const char *pathname, int flags, mode_t mode) {
-#endif
-  int fd = -1;
-  bool is_sl;
-  const char *fname = drop_dir(pathname, &is_sl);
-  if (is_sl) {
-#ifdef MG_FS_SLFS
-    fd = fs_slfs_open(fname, flags, mode);
-    if (fd >= 0) fd += SLFS_FD_BASE;
-#endif
-  } else {
-#ifdef CC3200_FS_SPIFFS
-    fd = fs_spiffs_open(fname, flags, mode);
-    if (fd >= 0) fd += SPIFFS_FD_BASE;
-#endif
-  }
-  LOG(LL_DEBUG,
-      ("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
-  return fd;
-}
-
-int _stat(const char *pathname, struct stat *st) {
-  int res = -1;
-  bool is_sl;
-  const char *fname = drop_dir(pathname, &is_sl);
-  memset(st, 0, sizeof(*st));
-  /* Simulate statting the root directory. */
-  if (fname[0] == '\0' || strcmp(fname, ".") == 0) {
-    st->st_ino = 0;
-    st->st_mode = S_IFDIR | 0777;
-    st->st_nlink = 1;
-    st->st_size = 0;
-    return 0;
-  }
-  if (is_sl) {
-#ifdef MG_FS_SLFS
-    res = fs_slfs_stat(fname, st);
-#endif
-  } else {
-#ifdef CC3200_FS_SPIFFS
-    res = fs_spiffs_stat(fname, st);
-#endif
-  }
-  LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname));
-  return res;
-}
-
-#if MG_TI_NO_HOST_INTERFACE
-int close(int fd) {
-#else
-int _close(int fd) {
-#endif
-  int r = -1;
-  switch (fd_type(fd)) {
-    case FD_INVALID:
-      r = set_errno(EBADF);
-      break;
-    case FD_SYS:
-      r = set_errno(EACCES);
-      break;
-#ifdef CC3200_FS_SPIFFS
-    case FD_SPIFFS:
-      r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
-      break;
-#endif
-#ifdef MG_FS_SLFS
-    case FD_SLFS:
-      r = fs_slfs_close(fd - SLFS_FD_BASE);
-      break;
-#endif
-  }
-  DBG(("close(%d) = %d", fd, r));
-  return r;
-}
-
-#if MG_TI_NO_HOST_INTERFACE
-off_t lseek(int fd, off_t offset, int whence) {
-#else
-off_t _lseek(int fd, off_t offset, int whence) {
-#endif
-  int r = -1;
-  switch (fd_type(fd)) {
-    case FD_INVALID:
-      r = set_errno(EBADF);
-      break;
-    case FD_SYS:
-      r = set_errno(ESPIPE);
-      break;
-#ifdef CC3200_FS_SPIFFS
-    case FD_SPIFFS:
-      r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
-      break;
-#endif
-#ifdef MG_FS_SLFS
-    case FD_SLFS:
-      r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
-      break;
-#endif
-  }
-  DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
-  return r;
-}
-
-int _fstat(int fd, struct stat *s) {
-  int r = -1;
-  memset(s, 0, sizeof(*s));
-  switch (fd_type(fd)) {
-    case FD_INVALID:
-      r = set_errno(EBADF);
-      break;
-    case FD_SYS: {
-      /* Create barely passable stats for STD{IN,OUT,ERR}. */
-      memset(s, 0, sizeof(*s));
-      s->st_ino = fd;
-      s->st_mode = S_IFCHR | 0666;
-      r = 0;
-      break;
-    }
-#ifdef CC3200_FS_SPIFFS
-    case FD_SPIFFS:
-      r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
-      break;
-#endif
-#ifdef MG_FS_SLFS
-    case FD_SLFS:
-      r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
-      break;
-#endif
-  }
-  DBG(("fstat(%d) = %d", fd, r));
-  return r;
-}
-
-#if MG_TI_NO_HOST_INTERFACE
-int read(int fd, char *buf, unsigned count) {
-#else
-ssize_t _read(int fd, void *buf, size_t count) {
-#endif
-  int r = -1;
-  switch (fd_type(fd)) {
-    case FD_INVALID:
-      r = set_errno(EBADF);
-      break;
-    case FD_SYS: {
-      if (fd != 0) {
-        r = set_errno(EACCES);
-        break;
-      }
-      /* Should we allow reading from stdin = uart? */
-      r = set_errno(ENOTSUP);
-      break;
-    }
-#ifdef CC3200_FS_SPIFFS
-    case FD_SPIFFS:
-      r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
-      break;
-#endif
-#ifdef MG_FS_SLFS
-    case FD_SLFS:
-      r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
-      break;
-#endif
-  }
-  DBG(("read(%d, %u) = %d", fd, count, r));
-  return r;
-}
-
-#if MG_TI_NO_HOST_INTERFACE
-int write(int fd, const char *buf, unsigned count) {
-#else
-ssize_t _write(int fd, const void *buf, size_t count) {
-#endif
-  int r = -1;
-  switch (fd_type(fd)) {
-    case FD_INVALID:
-      r = set_errno(EBADF);
-      break;
-    case FD_SYS: {
-      if (fd == 0) {
-        r = set_errno(EACCES);
-        break;
-      }
-#ifdef MG_UART_WRITE
-      MG_UART_WRITE(fd, buf, count);
-#elif defined(MG_UART_CHAR_PUT)
-      {
-        size_t i;
-        for (i = 0; i < count; i++) {
-          const char c = ((const char *) buf)[i];
-          if (c == '\n') MG_UART_CHAR_PUT(fd, '\r');
-          MG_UART_CHAR_PUT(fd, c);
-        }
-      }
-#endif
-      r = count;
-      break;
-    }
-#ifdef CC3200_FS_SPIFFS
-    case FD_SPIFFS:
-      r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
-      break;
-#endif
-#ifdef MG_FS_SLFS
-    case FD_SLFS:
-      r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
-      break;
-#endif
-  }
-  return r;
-}
-
-/*
- * On Newlib we override rename directly too, because the default
- * implementation using _link and _unlink doesn't work for us.
- */
-#if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
-int rename(const char *frompath, const char *topath) {
-  int r = -1;
-  bool is_sl_from, is_sl_to;
-  const char *from = drop_dir(frompath, &is_sl_from);
-  const char *to = drop_dir(topath, &is_sl_to);
-  if (is_sl_from || is_sl_to) {
-    set_errno(ENOTSUP);
-  } else {
-#ifdef CC3200_FS_SPIFFS
-    r = fs_spiffs_rename(from, to);
-#endif
-  }
-  DBG(("rename(%s, %s) = %d", from, to, r));
-  return r;
-}
-#endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */
-
-#if MG_TI_NO_HOST_INTERFACE
-int unlink(const char *pathname) {
-#else
-int _unlink(const char *pathname) {
-#endif
-  int r = -1;
-  bool is_sl;
-  const char *fname = drop_dir(pathname, &is_sl);
-  if (is_sl) {
-#ifdef MG_FS_SLFS
-    r = fs_slfs_unlink(fname);
-#endif
-  } else {
-#ifdef CC3200_FS_SPIFFS
-    r = fs_spiffs_unlink(fname);
-#endif
-  }
-  DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname));
-  return r;
-}
-
-#ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
-DIR *opendir(const char *dir_name) {
-  DIR *r = NULL;
-  bool is_sl;
-  drop_dir(dir_name, &is_sl);
-  if (is_sl) {
-    r = NULL;
-    set_errno(ENOTSUP);
-  } else {
-    r = fs_spiffs_opendir(dir_name);
-  }
-  DBG(("opendir(%s) = %p", dir_name, (void*)r));
-  return r;
-}
-
-struct dirent *readdir(DIR *dir) {
-  struct dirent *res = fs_spiffs_readdir(dir);
-  DBG(("readdir(%p) = %p", (void*)dir, (void*)res));
-  return res;
-}
-
-int closedir(DIR *dir) {
-  int res = fs_spiffs_closedir(dir);
-  DBG(("closedir(%p) = %d", (void*)dir, res));
-  return res;
-}
-
-int rmdir(const char *path) {
-  return fs_spiffs_rmdir(path);
-}
-
-int mkdir(const char *path, mode_t mode) {
-  (void) path;
-  (void) mode;
-  /* for spiffs supports only root dir, which comes from mongoose as '.' */
-  return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
-}
-#endif
-
-int sl_fs_init(void) {
-  int ret = 1;
-#ifdef __TI_COMPILER_VERSION__
-#ifdef MG_FS_SLFS
-#pragma diag_push
-#pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \
-                             */
-  ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
-                    fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
-                    fs_slfs_rename) == 0);
-#pragma diag_pop
-#endif
-#endif
-  return ret;
-}
-
-#endif /* !defined(MG_FS_NO_VFS) */
-#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \
-          defined(MG_FS_SPIFFS)) */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/simplelink/sl_socket.c"
-#endif
-
-#if MG_NET_IF == MG_NET_IF_SIMPLELINK
-
-#include <errno.h>
-#include <stdio.h>
-
-/* Amalgamated: #include "common/platform.h" */
-
-const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
-  int res;
-  struct in_addr *in = (struct in_addr *) src;
-  if (af != AF_INET) {
-    errno = ENOTSUP;
-    return NULL;
-  }
-  res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
-                 SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
-                 SL_IPV4_BYTE(in->s_addr, 3));
-  return res > 0 ? dst : NULL;
-}
-
-char *inet_ntoa(struct in_addr n) {
-  static char a[16];
-  return (char *) inet_ntop(AF_INET, &n, a, sizeof(a));
-}
-
-int inet_pton(int af, const char *src, void *dst) {
-  uint32_t a0, a1, a2, a3;
-  uint8_t *db = (uint8_t *) dst;
-  if (af != AF_INET) {
-    errno = ENOTSUP;
-    return 0;
-  }
-  if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
-    return 0;
-  }
-  *db = a3;
-  *(db + 1) = a2;
-  *(db + 2) = a1;
-  *(db + 3) = a0;
-  return 1;
-}
-
-#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/simplelink/sl_mg_task.c"
-#endif
-#if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
-
-/* Amalgamated: #include "mg_task.h" */
-
-#include <oslib/osi.h>
-
-enum mg_q_msg_type {
-  MG_Q_MSG_CB,
-};
-struct mg_q_msg {
-  enum mg_q_msg_type type;
-  void (*cb)(struct mg_mgr *mgr, void *arg);
-  void *arg;
-};
-static OsiMsgQ_t s_mg_q;
-static void mg_task(void *arg);
-
-bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
-  if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
-    return false;
-  }
-  if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
-                     (void *) mg_init, priority, NULL) != OSI_OK) {
-    return false;
-  }
-  return true;
-}
-
-static void mg_task(void *arg) {
-  struct mg_mgr mgr;
-  mg_init_cb mg_init = (mg_init_cb) arg;
-  mg_mgr_init(&mgr, NULL);
-  mg_init(&mgr);
-  while (1) {
-    struct mg_q_msg msg;
-    mg_mgr_poll(&mgr, 1);
-    if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
-    switch (msg.type) {
-      case MG_Q_MSG_CB: {
-        msg.cb(&mgr, msg.arg);
-      }
-    }
-  }
-}
-
-void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
-  struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
-  osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
-}
-
-#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \
-          */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/simplelink/sl_net_if.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
-#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
-
-/* Amalgamated: #include "mongoose/src/net_if.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#ifndef MG_ENABLE_NET_IF_SIMPLELINK
-#define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
-#endif
-
-extern const struct mg_iface_vtable mg_simplelink_iface_vtable;
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/simplelink/sl_net_if.c"
-#endif
-
-/* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */
-
-#if MG_ENABLE_NET_IF_SIMPLELINK
-
-/* Amalgamated: #include "mongoose/src/internal.h" */
-/* Amalgamated: #include "mongoose/src/util.h" */
-
-#define MG_TCP_RECV_BUFFER_SIZE 1024
-#define MG_UDP_RECV_BUFFER_SIZE 1500
-
-static sock_t mg_open_listening_socket(struct mg_connection *nc,
-                                       union socket_address *sa, int type,
-                                       int proto);
-
-static void mg_set_non_blocking_mode(sock_t sock) {
-  SlSockNonblocking_t opt;
-#if SL_MAJOR_VERSION_NUM < 2
-  opt.NonblockingEnabled = 1;
-#else
-  opt.NonBlockingEnabled = 1;
-#endif
-  sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
-}
-
-static int mg_is_error(int n) {
-  return (n < 0 && n != SL_ERROR_BSD_EALREADY && n != SL_ERROR_BSD_EAGAIN);
-}
-
-static void mg_sl_if_connect_tcp(struct mg_connection *nc,
-                                 const union socket_address *sa) {
-  int proto = 0;
-#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
-  if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
-#endif
-  sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
-  if (sock < 0) {
-    nc->err = sock;
-    goto out;
-  }
-  mg_sock_set(nc, sock);
-#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
-  nc->err = sl_set_ssl_opts(sock, nc);
-  if (nc->err != 0) goto out;
-#endif
-  nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin));
-out:
-  DBG(("%p to %s:%d sock %d %d err %d", (void*)nc, inet_ntoa(sa->sin.sin_addr),
-       ntohs(sa->sin.sin_port), nc->sock, proto, nc->err));
-}
-
-static void mg_sl_if_connect_udp(struct mg_connection *nc) {
-  sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
-  if (sock < 0) {
-    nc->err = sock;
-    return;
-  }
-  mg_sock_set(nc, sock);
-  nc->err = 0;
-}
-
-static int mg_sl_if_listen_tcp(struct mg_connection *nc,
-                               union socket_address *sa) {
-  int proto = 0;
-  if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
-  sock_t sock = mg_open_listening_socket(nc, sa, SOCK_STREAM, proto);
-  if (sock < 0) return sock;
-  mg_sock_set(nc, sock);
-  return 0;
-}
-
-static int mg_sl_if_listen_udp(struct mg_connection *nc,
-                               union socket_address *sa) {
-  sock_t sock = mg_open_listening_socket(nc, sa, SOCK_DGRAM, 0);
-  if (sock == INVALID_SOCKET) return (errno ? errno : 1);
-  mg_sock_set(nc, sock);
-  return 0;
-}
-
-static int mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf,
-                             size_t len) {
-  int n = (int) sl_Send(nc->sock, buf, len, 0);
-  if (n < 0 && !mg_is_error(n)) n = 0;
-  return n;
-}
-
-static int mg_sl_if_udp_send(struct mg_connection *nc, const void *buf,
-                             size_t len) {
-  int n = sl_SendTo(nc->sock, buf, len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
-  if (n < 0 && !mg_is_error(n)) n = 0;
-  return n;
-}
-
-static int mg_sl_if_tcp_recv(struct mg_connection *nc, void *buf, size_t len) {
-  int n = sl_Recv(nc->sock, buf, len, 0);
-  if (n == 0) {
-    /* Orderly shutdown of the socket, try flushing output. */
-    nc->flags |= MG_F_SEND_AND_CLOSE;
-  } else if (n < 0 && !mg_is_error(n)) {
-    n = 0;
-  }
-  return n;
-}
-
-static int mg_sl_if_udp_recv(struct mg_connection *nc, void *buf, size_t len,
-                             union socket_address *sa, size_t *sa_len) {
-  SlSocklen_t sa_len_t = *sa_len;
-  int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0,
-                      (SlSockAddr_t *) sa, &sa_len_t);
-  *sa_len = sa_len_t;
-  if (n < 0 && !mg_is_error(n)) n = 0;
-  return n;
-}
-
-static int mg_sl_if_create_conn(struct mg_connection *nc) {
-  (void) nc;
-  return 1;
-}
-
-void mg_sl_if_destroy_conn(struct mg_connection *nc) {
-  if (nc->sock == INVALID_SOCKET) return;
-  /* For UDP, only close outgoing sockets or listeners. */
-  if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
-    sl_Close(nc->sock);
-  }
-  nc->sock = INVALID_SOCKET;
-}
-
-static int mg_accept_conn(struct mg_connection *lc) {
-  struct mg_connection *nc;
-  union socket_address sa;
-  socklen_t sa_len = sizeof(sa);
-  sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len);
-  if (sock < 0) {
-    DBG(("%p: failed to accept: %d", (void*)lc, sock));
-    return 0;
-  }
-  nc = mg_if_accept_new_conn(lc);
-  if (nc == NULL) {
-    sl_Close(sock);
-    return 0;
-  }
-  DBG(("%p conn from %s:%d", (void*)nc, inet_ntoa(sa.sin.sin_addr),
-       ntohs(sa.sin.sin_port)));
-  mg_sock_set(nc, sock);
-  mg_if_accept_tcp_cb(nc, &sa, sa_len);
-  return 1;
-}
-
-/* 'sa' must be an initialized address to bind to */
-static sock_t mg_open_listening_socket(struct mg_connection *nc,
-                                       union socket_address *sa, int type,
-                                       int proto) {
-  int r;
-  socklen_t sa_len =
-      (sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
-  sock_t sock = sl_Socket(sa->sa.sa_family, type, proto);
-  if (sock < 0) return sock;
-#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
-  if ((r = sl_set_ssl_opts(sock, nc)) < 0) goto clean;
-#endif
-  if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) goto clean;
-  if (type != SOCK_DGRAM) {
-    if ((r = sl_Listen(sock, SOMAXCONN)) < 0) goto clean;
-  }
-  mg_set_non_blocking_mode(sock);
-clean:
-  if (r < 0) {
-    sl_Close(sock);
-    sock = r;
-  }
-  return sock;
-}
-
-#define _MG_F_FD_CAN_READ 1
-#define _MG_F_FD_CAN_WRITE 1 << 1
-#define _MG_F_FD_ERROR 1 << 2
-
-void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
-  DBG(("%p fd=%d fd_flags=%d nc_flags=0x%lx rmbl=%d smbl=%d", (void*)nc, nc->sock,
-       fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
-
-  if (!mg_if_poll(nc, now)) return;
-
-  if (nc->flags & MG_F_CONNECTING) {
-    if ((nc->flags & MG_F_UDP) || nc->err != SL_ERROR_BSD_EALREADY) {
-      mg_if_connect_cb(nc, nc->err);
-    } else {
-      /* In SimpleLink, to get status of non-blocking connect() we need to wait
-       * until socket is writable and repeat the call to sl_Connect again,
-       * which will now return the real status. */
-      if (fd_flags & _MG_F_FD_CAN_WRITE) {
-        nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin));
-        DBG(("%p conn res=%d", (void*)nc, nc->err));
-        if (nc->err == SL_ERROR_BSD_ESECSNOVERIFY ||
-            /* TODO(rojer): Provide API to set the date for verification. */
-            nc->err == SL_ERROR_BSD_ESECDATEERROR
-#if SL_MAJOR_VERSION_NUM >= 2
-            /* Per SWRU455, this error does not mean verification failed,
-             * it only means that the cert used is not present in the trusted
-             * root CA catalog. Which is perfectly fine. */
-            ||
-            nc->err == SL_ERROR_BSD_ESECUNKNOWNROOTCA
-#endif
-            ) {
-          nc->err = 0;
-        }
-        mg_if_connect_cb(nc, nc->err);
-      }
-    }
-    /* Ignore read/write in further processing, we've handled it. */
-    fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE);
-  }
-
-  if (fd_flags & _MG_F_FD_CAN_READ) {
-    if (nc->flags & MG_F_UDP) {
-      mg_if_can_recv_cb(nc);
-    } else {
-      if (nc->flags & MG_F_LISTENING) {
-        mg_accept_conn(nc);
-      } else {
-        mg_if_can_recv_cb(nc);
-      }
-    }
-  }
-
-  if (fd_flags & _MG_F_FD_CAN_WRITE) {
-    mg_if_can_send_cb(nc);
-  }
-
-  DBG(("%p after fd=%d nc_flags=0x%lx rmbl=%d smbl=%d", (void*)nc, nc->sock, nc->flags,
-       (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
-}
-
-/* Associate a socket to a connection. */
-void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) {
-  mg_set_non_blocking_mode(sock);
-  nc->sock = sock;
-  DBG(("%p %d", (void*)nc, sock));
-}
-
-void mg_sl_if_init(struct mg_iface *iface) {
-  (void) iface;
-  DBG(("%p using sl_Select()", (void*)iface->mgr));
-}
-
-void mg_sl_if_free(struct mg_iface *iface) {
-  (void) iface;
-}
-
-void mg_sl_if_add_conn(struct mg_connection *nc) {
-  (void) nc;
-}
-
-void mg_sl_if_remove_conn(struct mg_connection *nc) {
-  (void) nc;
-}
-
-time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) {
-  struct mg_mgr *mgr = iface->mgr;
-  double now = mg_time();
-  double min_timer;
-  struct mg_connection *nc, *tmp;
-  struct SlTimeval_t tv;
-  SlFdSet_t read_set, write_set, err_set;
-  sock_t max_fd = INVALID_SOCKET;
-  int num_fds, num_ev = 0, num_timers = 0;
-
-  SL_SOCKET_FD_ZERO(&read_set);
-  SL_SOCKET_FD_ZERO(&write_set);
-  SL_SOCKET_FD_ZERO(&err_set);
-
-  /*
-   * Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
-   * e.g. timer-only "connections".
-   */
-  min_timer = 0;
-  for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
-    tmp = nc->next;
-
-    if (nc->sock != INVALID_SOCKET) {
-      num_fds++;
-
-      if (!(nc->flags & MG_F_WANT_WRITE) &&
-          nc->recv_mbuf.len < nc->recv_mbuf_limit &&
-          (!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
-        SL_SOCKET_FD_SET(nc->sock, &read_set);
-        if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
-      }
-
-      if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
-          (nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
-        SL_SOCKET_FD_SET(nc->sock, &write_set);
-        SL_SOCKET_FD_SET(nc->sock, &err_set);
-        if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
-      }
-    }
-
-    if (nc->ev_timer_time > 0) {
-      if (num_timers == 0 || nc->ev_timer_time < min_timer) {
-        min_timer = nc->ev_timer_time;
-      }
-      num_timers++;
-    }
-  }
-
-  /*
-   * If there is a timer to be fired earlier than the requested timeout,
-   * adjust the timeout.
-   */
-  if (num_timers > 0) {
-    double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
-    if (timer_timeout_ms < timeout_ms) {
-      timeout_ms = timer_timeout_ms;
-    }
-  }
-  if (timeout_ms < 0) timeout_ms = 0;
-
-  tv.tv_sec = timeout_ms / 1000;
-  tv.tv_usec = (timeout_ms % 1000) * 1000;
-
-  if (num_fds > 0) {
-    num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
-  }
-
-  now = mg_time();
-  DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev,
-       num_fds, timeout_ms));
-
-  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
-    int fd_flags = 0;
-    if (nc->sock != INVALID_SOCKET) {
-      if (num_ev > 0) {
-        fd_flags =
-            (SL_SOCKET_FD_ISSET(nc->sock, &read_set) &&
-                     (!(nc->flags & MG_F_UDP) || nc->listener == NULL)
-                 ? _MG_F_FD_CAN_READ
-                 : 0) |
-            (SL_SOCKET_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE
-                                                      : 0) |
-            (SL_SOCKET_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
-      }
-      /* SimpleLink does not report UDP sockets as writable. */
-      if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) {
-        fd_flags |= _MG_F_FD_CAN_WRITE;
-      }
-    }
-    tmp = nc->next;
-    mg_mgr_handle_conn(nc, fd_flags, now);
-  }
-
-  return now;
-}
-
-void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote,
-                            union socket_address *sa) {
-  /* SimpleLink does not provide a way to get socket's peer address after
-   * accept or connect. Address should have been preserved in the connection,
-   * so we do our best here by using it. */
-  if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
-}
-
-void sl_restart_cb(struct mg_mgr *mgr) {
-  /*
-   * SimpleLink has been restarted, meaning all sockets have been invalidated.
-   * We try our best - we'll restart the listeners, but for outgoing
-   * connections we have no option but to terminate.
-   */
-  struct mg_connection *nc;
-  for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
-    if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */
-    if (nc->flags & MG_F_LISTENING) {
-      DBG(("restarting %p %s:%d", (void*)nc, inet_ntoa(nc->sa.sin.sin_addr),
-           ntohs(nc->sa.sin.sin_port)));
-      int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa)
-                                      : mg_sl_if_listen_tcp(nc, &nc->sa));
-      if (res == 0) continue;
-      /* Well, we tried and failed. Fall through to closing. */
-    }
-    nc->sock = INVALID_SOCKET;
-    DBG(("terminating %p %s:%d", (void*)nc, inet_ntoa(nc->sa.sin.sin_addr),
-         ntohs(nc->sa.sin.sin_port)));
-    /* TODO(rojer): Outgoing UDP? */
-    nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-  }
-}
-
-/* clang-format off */
-#define MG_SL_IFACE_VTABLE                                              \
-  {                                                                     \
-    mg_sl_if_init,                                                      \
-    mg_sl_if_free,                                                      \
-    mg_sl_if_add_conn,                                                  \
-    mg_sl_if_remove_conn,                                               \
-    mg_sl_if_poll,                                                      \
-    mg_sl_if_listen_tcp,                                                \
-    mg_sl_if_listen_udp,                                                \
-    mg_sl_if_connect_tcp,                                               \
-    mg_sl_if_connect_udp,                                               \
-    mg_sl_if_tcp_send,                                                  \
-    mg_sl_if_udp_send,                                                  \
-    mg_sl_if_tcp_recv,                                                  \
-    mg_sl_if_udp_recv,                                                  \
-    mg_sl_if_create_conn,                                               \
-    mg_sl_if_destroy_conn,                                              \
-    mg_sl_if_sock_set,                                                  \
-    mg_sl_if_get_conn_addr,                                             \
-  }
-/* clang-format on */
-
-const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE;
-#if MG_NET_IF == MG_NET_IF_SIMPLELINK
-const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE;
-#endif
-
-#endif /* MG_ENABLE_NET_IF_SIMPLELINK */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/simplelink/sl_ssl_if.c"
-#endif
-
-#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
-
-/* Amalgamated: #include "common/mg_mem.h" */
-
-#ifndef MG_SSL_IF_SIMPLELINK_SLFS_PREFIX
-#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "SL:"
-#endif
-
-#define MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN \
-  (sizeof(MG_SSL_IF_SIMPLELINK_SLFS_PREFIX) - 1)
-
-struct mg_ssl_if_ctx {
-  char *ssl_cert;
-  char *ssl_key;
-  char *ssl_ca_cert;
-  char *ssl_server_name;
-};
-
-void mg_ssl_if_init() {
-}
-
-enum mg_ssl_if_result mg_ssl_if_conn_init(
-    struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
-    const char **err_msg) {
-  struct mg_ssl_if_ctx *ctx =
-      (struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
-  if (ctx == NULL) {
-    MG_SET_PTRPTR(err_msg, "Out of memory");
-    return MG_SSL_ERROR;
-  }
-  nc->ssl_if_data = ctx;
-
-  if (params->cert != NULL || params->key != NULL) {
-    if (params->cert != NULL && params->key != NULL) {
-      ctx->ssl_cert = strdup(params->cert);
-      ctx->ssl_key = strdup(params->key);
-    } else {
-      MG_SET_PTRPTR(err_msg, "Both cert and key are required.");
-      return MG_SSL_ERROR;
-    }
-  }
-  if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) {
-    ctx->ssl_ca_cert = strdup(params->ca_cert);
-  }
-  /* TODO(rojer): cipher_suites. */
-  if (params->server_name != NULL) {
-    ctx->ssl_server_name = strdup(params->server_name);
-  }
-  return MG_SSL_OK;
-}
-
-enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
-                                            struct mg_connection *lc) {
-  /* SimpleLink does everything for us, nothing for us to do. */
-  (void) nc;
-  (void) lc;
-  return MG_SSL_OK;
-}
-
-enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
-  /* SimpleLink has already performed the handshake, nothing to do. */
-  return MG_SSL_OK;
-}
-
-int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t len) {
-  /* SimpelLink handles TLS, so this is just a pass-through. */
-  int n = nc->iface->vtable->tcp_recv(nc, buf, len);
-  if (n == 0) nc->flags |= MG_F_WANT_READ;
-  return n;
-}
-
-int mg_ssl_if_write(struct mg_connection *nc, const void *buf, size_t len) {
-  /* SimpelLink handles TLS, so this is just a pass-through. */
-  return nc->iface->vtable->tcp_send(nc, buf, len);
-}
-
-void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
-  /* Nothing to do */
-  (void) nc;
-}
-
-void mg_ssl_if_conn_free(struct mg_connection *nc) {
-  struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  if (ctx == NULL) return;
-  nc->ssl_if_data = NULL;
-  MG_FREE(ctx->ssl_cert);
-  MG_FREE(ctx->ssl_key);
-  MG_FREE(ctx->ssl_ca_cert);
-  MG_FREE(ctx->ssl_server_name);
-  memset(ctx, 0, sizeof(*ctx));
-  MG_FREE(ctx);
-}
-
-bool pem_to_der(const char *pem_file, const char *der_file) {
-  bool ret = false;
-  FILE *pf = NULL, *df = NULL;
-  bool writing = false;
-  pf = fopen(pem_file, "r");
-  if (pf == NULL) goto clean;
-  remove(der_file);
-  fs_slfs_set_file_size(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN, 2048);
-  df = fopen(der_file, "w");
-  fs_slfs_unset_file_flags(der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN);
-  if (df == NULL) goto clean;
-  while (1) {
-    char pem_buf[70];
-    char der_buf[48];
-    if (!fgets(pem_buf, sizeof(pem_buf), pf)) break;
-    if (writing) {
-      if (strstr(pem_buf, "-----END ") != NULL) {
-        ret = true;
-        break;
-      }
-      int l = 0;
-      while (!isspace((unsigned int) pem_buf[l])) l++;
-      int der_len = 0;
-      cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf),
-                       der_buf, &der_len);
-      if (der_len <= 0) break;
-      if (fwrite(der_buf, 1, der_len, df) != der_len) break;
-    } else if (strstr(pem_buf, "-----BEGIN ") != NULL) {
-      writing = true;
-    }
-  }
-
-clean:
-  if (pf != NULL) fclose(pf);
-  if (df != NULL) {
-    fclose(df);
-    if (!ret) remove(der_file);
-  }
-  return ret;
-}
-
-#if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
-/* If the file's extension is .pem, convert it to DER format and put on SLFS. */
-static char *sl_pem2der(const char *pem_file) {
-  const char *pem_ext = strstr(pem_file, ".pem");
-  if (pem_ext == NULL || *(pem_ext + 4) != '\0') {
-    return strdup(pem_file);
-  }
-  char *der_file = NULL;
-  /* DER file must be located on SLFS, add prefix. */
-  int l = mg_asprintf(&der_file, 0, MG_SSL_IF_SIMPLELINK_SLFS_PREFIX "%.*s.der",
-                      (int) (pem_ext - pem_file), pem_file);
-  if (der_file == NULL) return NULL;
-  bool result = false;
-  cs_stat_t st;
-  if (mg_stat(der_file, &st) != 0) {
-    result = pem_to_der(pem_file, der_file);
-    LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result));
-  } else {
-    /* File exists, assume it's already been converted. */
-    result = true;
-  }
-  if (result) {
-    /* Strip the SL: prefix we added since NWP does not expect it. */
-    memmove(der_file, der_file + MG_SSL_IF_SIMPLELINK_SLFS_PREFIX_LEN,
-            l - 2 /* including \0 */);
-  } else {
-    MG_FREE(der_file);
-    der_file = NULL;
-  }
-  return der_file;
-}
-#else
-static char *sl_pem2der(const char *pem_file) {
-  return strdup(pem_file);
-}
-#endif
-
-int sl_set_ssl_opts(int sock, struct mg_connection *nc) {
-  int err;
-  const struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
-  DBG(("%p ssl ctx: %p", (void*)nc, ctx));
-
-  if (ctx == NULL) return 0;
-  DBG(("%p %s,%s,%s,%s", (void*)nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
-       (ctx->ssl_key ? ctx->ssl_cert : "-"),
-       (ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
-       (ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
-  if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
-    char *ssl_cert = sl_pem2der(ctx->ssl_cert), *ssl_key = NULL;
-    if (ssl_cert != NULL) {
-      err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
-                          SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
-                          strlen(ssl_cert));
-      MG_FREE(ssl_cert);
-      LOG(LL_DEBUG, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
-      ssl_key = sl_pem2der(ctx->ssl_key);
-      if (ssl_key != NULL) {
-        err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
-                            SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
-                            strlen(ssl_key));
-        MG_FREE(ssl_key);
-        LOG(LL_DEBUG, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
-      } else {
-        err = -1;
-      }
-    } else {
-      err = -1;
-    }
-    if (err != 0) return err;
-  }
-  if (ctx->ssl_ca_cert != NULL) {
-    if (ctx->ssl_ca_cert[0] != '\0') {
-      char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
-      if (ssl_ca_cert != NULL) {
-        err =
-            sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME,
-                          ssl_ca_cert, strlen(ssl_ca_cert));
-        LOG(LL_DEBUG, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
-      } else {
-        err = -1;
-      }
-      MG_FREE(ssl_ca_cert);
-      if (err != 0) return err;
-    }
-  }
-  if (ctx->ssl_server_name != NULL) {
-    err = sl_SetSockOpt(sock, SL_SOL_SOCKET,
-                        SL_SO_SECURE_DOMAIN_NAME_VERIFICATION,
-                        ctx->ssl_server_name, strlen(ctx->ssl_server_name));
-    DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
-    /* Domain name verificationw as added in a NWP service pack, older
-     * versions return SL_ERROR_BSD_ENOPROTOOPT. There isn't much we can do
-     * about it,
-     * so we ignore the error. */
-    if (err != 0 && err != SL_ERROR_BSD_ENOPROTOOPT) return err;
-  }
-  return 0;
-}
-
-#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/lwip/mg_lwip_net_if.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
-#define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
-
-#ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
-#define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
-#endif
-
-#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
-
-#include <stdint.h>
-
-extern const struct mg_iface_vtable mg_lwip_iface_vtable;
-
-struct mg_lwip_conn_state {
-  struct mg_connection *nc;
-  struct mg_connection *lc;
-  union {
-    struct tcp_pcb *tcp;
-    struct udp_pcb *udp;
-  } pcb;
-  err_t err;
-  size_t num_sent; /* Number of acknowledged bytes to be reported to the core */
-  struct pbuf *rx_chain; /* Chain of incoming data segments. */
-  size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */
-  /* Last SSL write size, for retries. */
-  int last_ssl_write_size;
-  /* Whether MG_SIG_RECV is already pending for this connection */
-  int recv_pending;
-  /* Whether the connection is about to close, just `rx_chain` needs to drain */
-  int draining_rx_chain;
-};
-
-enum mg_sig_type {
-  MG_SIG_CONNECT_RESULT = 1,
-  MG_SIG_RECV = 2,
-  MG_SIG_CLOSE_CONN = 3,
-  MG_SIG_TOMBSTONE = 4,
-  MG_SIG_ACCEPT = 5,
-};
-
-void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc);
-
-/* To be implemented by the platform. */
-void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr);
-
-#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
-
-#endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/lwip/mg_lwip_net_if.c"
-#endif
-
-#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
-
-/* Amalgamated: #include "common/mg_mem.h" */
-
-#include <lwip/init.h>
-#include <lwip/pbuf.h>
-#include <lwip/tcp.h>
-#include <lwip/tcpip.h>
-#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
-#include <lwip/priv/tcp_priv.h>   /* For tcp_seg */
-#include <lwip/priv/tcpip_priv.h> /* For tcpip_api_call */
-#else
-#include <lwip/tcp_impl.h>
-#endif
-#include <lwip/udp.h>
-
-/* Amalgamated: #include "common/cs_dbg.h" */
-
-/*
- * Newest versions of LWIP have ip_2_ip4, older have ipX_2_ip,
- * even older have nothing.
- */
-#ifndef ip_2_ip4
-#ifdef ipX_2_ip
-#define ip_2_ip4(addr) ipX_2_ip(addr)
-#else
-#define ip_2_ip4(addr) (addr)
-#endif
-#endif
-
-/*
- * Depending on whether Mongoose is compiled with ipv6 support, use right
- * lwip functions
- */
-#if MG_ENABLE_IPV6
-#define TCP_NEW tcp_new_ip6
-#define TCP_BIND tcp_bind_ip6
-#define UDP_BIND udp_bind_ip6
-#define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
-#define SET_ADDR(dst, src)                               \
-  memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
-         sizeof((dst)->sin6.sin6_addr.s6_addr))
-#else
-#define TCP_NEW tcp_new
-#define TCP_BIND tcp_bind
-#define UDP_BIND udp_bind
-#define IPADDR_NTOA ipaddr_ntoa
-#define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = ip_2_ip4(src)->addr
-#endif
-
-#if !NO_SYS
-#if LWIP_TCPIP_CORE_LOCKING
-/* With locking tcpip_api_call is just a function call wrapped in lock/unlock,
- * so we can get away with just casting. */
-void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) {
-  tcpip_api_call((tcpip_api_call_fn) fn, (struct tcpip_api_call_data *) arg);
-}
-#else
-static sys_sem_t s_tcpip_call_lock_sem = NULL;
-static sys_sem_t s_tcpip_call_sync_sem = NULL;
-struct mg_lwip_netif_tcpip_call_ctx {
-  void (*fn)(void *);
-  void *arg;
-};
-static void xxx_tcpip(void *arg) {
-  struct mg_lwip_netif_tcpip_call_ctx *ctx =
-      (struct mg_lwip_netif_tcpip_call_ctx *) arg;
-  ctx->fn(ctx->arg);
-  sys_sem_signal(&s_tcpip_call_sync_sem);
-}
-void mg_lwip_netif_run_on_tcpip(void (*fn)(void *), void *arg) {
-  struct mg_lwip_netif_tcpip_call_ctx ctx = {.fn = fn, .arg = arg};
-  sys_arch_sem_wait(&s_tcpip_call_lock_sem, 0);
-  tcpip_send_msg_wait_sem(xxx_tcpip, &ctx, &s_tcpip_call_sync_sem);
-  sys_sem_signal(&s_tcpip_call_lock_sem);
-}
-#endif
-#else
-#define mg_lwip_netif_run_on_tcpip(fn, arg) (fn)(arg)
-#endif
-
-void mg_lwip_if_init(struct mg_iface *iface);
-void mg_lwip_if_free(struct mg_iface *iface);
-void mg_lwip_if_add_conn(struct mg_connection *nc);
-void mg_lwip_if_remove_conn(struct mg_connection *nc);
-time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms);
-
-// If compiling for Mongoose OS.
-#ifdef MGOS
-extern void mgos_lock();
-extern void mgos_unlock();
-#else
-#define mgos_lock()
-#define mgos_unlock()
-#endif
-
-static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p);
-
-#if LWIP_TCP_KEEPALIVE
-void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
-                                  int interval, int count) {
-  if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) {
-    return;
-  }
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  struct tcp_pcb *tpcb = cs->pcb.tcp;
-  if (idle > 0 && interval > 0 && count > 0) {
-    tpcb->keep_idle = idle * 1000;
-    tpcb->keep_intvl = interval * 1000;
-    tpcb->keep_cnt = count;
-    tpcb->so_options |= SOF_KEEPALIVE;
-  } else {
-    tpcb->so_options &= ~SOF_KEEPALIVE;
-  }
-}
-#elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
-#warning LWIP TCP keepalive is disabled. Please consider enabling it.
-#endif /* LWIP_TCP_KEEPALIVE */
-
-static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
-  struct mg_connection *nc = (struct mg_connection *) arg;
-  DBG(("%p connect to %s:%u = %d", (void*)nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
-       tpcb->remote_port, err));
-  if (nc == NULL) {
-    tcp_abort(tpcb);
-    return ERR_ARG;
-  }
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  cs->err = err;
-#if LWIP_TCP_KEEPALIVE
-  if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6);
-#endif
-  mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
-  return ERR_OK;
-}
-
-static void mg_lwip_tcp_error_cb(void *arg, err_t err) {
-  struct mg_connection *nc = (struct mg_connection *) arg;
-  DBG(("%p conn error %d", (void*)nc, err));
-  if (nc == NULL || (nc->flags & MG_F_CLOSE_IMMEDIATELY)) return;
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  cs->pcb.tcp = NULL; /* Has already been deallocated */
-  if (nc->flags & MG_F_CONNECTING) {
-    cs->err = err;
-    mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
-  } else {
-    mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
-  }
-}
-
-static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb,
-                                 struct pbuf *p, err_t err) {
-  struct mg_connection *nc = (struct mg_connection *) arg;
-  struct mg_lwip_conn_state *cs =
-      (nc ? (struct mg_lwip_conn_state *) nc->sock : NULL);
-  DBG(("%p %p %p %p %u %d", (void*)nc, (void*)cs, (void*)tpcb, (void*)p, (p != NULL ? p->tot_len : 0),
-       err));
-  if (p == NULL) {
-    if (nc != NULL && !(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
-      if (cs->rx_chain != NULL) {
-        /*
-         * rx_chain still contains non-consumed data, don't close the
-         * connection
-         */
-        cs->draining_rx_chain = 1;
-      } else {
-        mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
-      }
-    } else {
-      /* Tombstoned connection, do nothing. */
-    }
-    return ERR_OK;
-  } else if (nc == NULL) {
-    tcp_abort(tpcb);
-    return ERR_ARG;
-  }
-  /*
-   * If we get a chain of more than one segment at once, we need to bump
-   * refcount on the subsequent bufs to make them independent.
-   */
-  if (p->next != NULL) {
-    struct pbuf *q = p->next;
-    for (; q != NULL; q = q->next) pbuf_ref(q);
-  }
-  mgos_lock();
-  if (cs->rx_chain == NULL) {
-    cs->rx_offset = 0;
-  } else if (pbuf_clen(cs->rx_chain) >= 4) {
-    /* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX
-     * will be completely blocked. We already have at least 4 in the chain,
-     * this one is the last, so we have to make a copy and release this one. */
-    struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
-    if (np != NULL) {
-      pbuf_copy(np, p);
-      pbuf_free(p);
-      p = np;
-    }
-  }
-  mg_lwip_recv_common(nc, p);
-  mgos_unlock();
-  (void) err;
-  return ERR_OK;
-}
-
-static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb,
-                                 u16_t num_sent) {
-  struct mg_connection *nc = (struct mg_connection *) arg;
-  DBG(("%p %p %u %p %p", (void*)nc, (void*)tpcb, num_sent, (void*)tpcb->unsent, (void*)tpcb->unacked));
-  if (nc == NULL) return ERR_OK;
-  if ((nc->flags & MG_F_SEND_AND_CLOSE) && !(nc->flags & MG_F_WANT_WRITE) &&
-      nc->send_mbuf.len == 0 && tpcb->unsent == NULL && tpcb->unacked == NULL) {
-    mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
-  }
-  if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) {
-    mg_lwip_mgr_schedule_poll(nc->mgr);
-  }
-  (void) num_sent;
-  return ERR_OK;
-}
-
-struct mg_lwip_if_connect_tcp_ctx {
-  struct mg_connection *nc;
-  const union socket_address *sa;
-};
-
-static void mg_lwip_if_connect_tcp_tcpip(void *arg) {
-  struct mg_lwip_if_connect_tcp_ctx *ctx =
-      (struct mg_lwip_if_connect_tcp_ctx *) arg;
-  struct mg_connection *nc = ctx->nc;
-  const union socket_address *sa = ctx->sa;
-
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  struct tcp_pcb *tpcb = TCP_NEW();
-  cs->pcb.tcp = tpcb;
-  ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
-  u16_t port = ntohs(sa->sin.sin_port);
-  tcp_arg(tpcb, nc);
-  tcp_err(tpcb, mg_lwip_tcp_error_cb);
-  tcp_sent(tpcb, mg_lwip_tcp_sent_cb);
-  tcp_recv(tpcb, mg_lwip_tcp_recv_cb);
-  cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */);
-  DBG(("%p tcp_bind = %d", (void*)nc, cs->err));
-  if (cs->err != ERR_OK) {
-    mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
-    return;
-  }
-  cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb);
-  DBG(("%p tcp_connect %p = %d", (void*)nc, tpcb, cs->err));
-  if (cs->err != ERR_OK) {
-    mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
-    return;
-  }
-}
-
-void mg_lwip_if_connect_tcp(struct mg_connection *nc,
-                            const union socket_address *sa) {
-  struct mg_lwip_if_connect_tcp_ctx ctx = {.nc = nc, .sa = sa};
-  mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_tcp_tcpip, &ctx);
-}
-
-/*
- * Lwip included in the SDKs for nRF5x chips has different type for the
- * callback of `udp_recv()`
- */
-#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
-static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
-                                const ip_addr_t *addr, u16_t port)
-#else
-static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
-                                ip_addr_t *addr, u16_t port)
-#endif
-{
-  struct mg_connection *nc = (struct mg_connection *) arg;
-  DBG(("%p %s:%u %p %u %u", (void*)nc, IPADDR_NTOA(addr), port, (void*)p, p->ref, p->len));
-  /* Put address in a separate pbuf and tack it onto the packet. */
-  struct pbuf *sap =
-      pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM);
-  if (sap == NULL) {
-    pbuf_free(p);
-    return;
-  }
-  union socket_address *sa = (union socket_address *) sap->payload;
-#if ((LWIP_VERSION_MAJOR << 8) | LWIP_VERSION_MINOR) >= 0x0105
-  sa->sin.sin_addr.s_addr = ip_2_ip4(addr)->addr;
-#else
-  sa->sin.sin_addr.s_addr = addr->addr;
-#endif
-  sa->sin.sin_port = htons(port);
-  /* Logic in the recv handler requires that there be exactly one data pbuf. */
-  p = pbuf_coalesce(p, PBUF_RAW);
-  pbuf_chain(sap, p);
-  mgos_lock();
-  mg_lwip_recv_common(nc, sap);
-  mgos_unlock();
-  (void) pcb;
-}
-
-static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) {
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  if (cs->rx_chain == NULL) {
-    cs->rx_chain = p;
-  } else {
-    pbuf_chain(cs->rx_chain, p);
-  }
-  if (!cs->recv_pending) {
-    cs->recv_pending = 1;
-    mg_lwip_post_signal(MG_SIG_RECV, nc);
-  }
-}
-
-static int mg_lwip_if_udp_recv(struct mg_connection *nc, void *buf, size_t len,
-                               union socket_address *sa, size_t *sa_len) {
-  /*
-   * For UDP, RX chain consists of interleaved address and packet bufs:
-   * Address pbuf followed by exactly one data pbuf (recv_cb took care of that).
-   */
-  int res = 0;
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  if (nc->sock == INVALID_SOCKET) return -1;
-  mgos_lock();
-  if (cs->rx_chain != NULL) {
-    struct pbuf *ap = cs->rx_chain;
-    struct pbuf *dp = ap->next;
-    cs->rx_chain = pbuf_dechain(dp);
-    res = MIN(dp->len, len);
-    pbuf_copy_partial(dp, buf, res, 0);
-    pbuf_free(dp);
-    pbuf_copy_partial(ap, sa, MIN(*sa_len, ap->len), 0);
-    pbuf_free(ap);
-  }
-  mgos_unlock();
-  return res;
-}
-
-static void mg_lwip_if_connect_udp_tcpip(void *arg) {
-  struct mg_connection *nc = (struct mg_connection *) arg;
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  struct udp_pcb *upcb = udp_new();
-  cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */);
-  DBG(("%p udp_bind %p = %d", (void*)nc, (void*)upcb, cs->err));
-  if (cs->err == ERR_OK) {
-    udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
-    cs->pcb.udp = upcb;
-  } else {
-    udp_remove(upcb);
-  }
-  mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
-}
-
-void mg_lwip_if_connect_udp(struct mg_connection *nc) {
-  mg_lwip_netif_run_on_tcpip(mg_lwip_if_connect_udp_tcpip, nc);
-}
-
-static void tcp_close_tcpip(void *arg) {
-  tcp_close((struct tcp_pcb *) arg);
-}
-
-void mg_lwip_handle_accept(struct mg_connection *nc) {
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  if (cs->pcb.tcp == NULL) return;
-  union socket_address sa;
-  struct tcp_pcb *tpcb = cs->pcb.tcp;
-  SET_ADDR(&sa, &tpcb->remote_ip);
-  sa.sin.sin_port = htons(tpcb->remote_port);
-  mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin));
-}
-
-static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) {
-  struct mg_connection *lc = (struct mg_connection *) arg, *nc;
-  struct mg_lwip_conn_state *lcs, *cs;
-  struct tcp_pcb_listen *lpcb;
-  LOG(LL_DEBUG,
-      ("%p conn %p from %s:%u", (void*)lc, (void*)newtpcb,
-       IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
-  if (lc == NULL) {
-    tcp_abort(newtpcb);
-    return ERR_ABRT;
-  }
-  lcs = (struct mg_lwip_conn_state *) lc->sock;
-  lpcb = (struct tcp_pcb_listen *) lcs->pcb.tcp;
-#if TCP_LISTEN_BACKLOG
-  tcp_accepted(lpcb);
-#endif
-  nc = mg_if_accept_new_conn(lc);
-  if (nc == NULL) {
-    tcp_abort(newtpcb);
-    return ERR_ABRT;
-  }
-  cs = (struct mg_lwip_conn_state *) nc->sock;
-  cs->lc = lc;
-  cs->pcb.tcp = newtpcb;
-  /* We need to set up callbacks before returning because data may start
-   * arriving immediately. */
-  tcp_arg(newtpcb, nc);
-  tcp_err(newtpcb, mg_lwip_tcp_error_cb);
-  tcp_sent(newtpcb, mg_lwip_tcp_sent_cb);
-  tcp_recv(newtpcb, mg_lwip_tcp_recv_cb);
-#if LWIP_TCP_KEEPALIVE
-  mg_lwip_set_keepalive_params(nc, 60, 10, 6);
-#endif
-  mg_lwip_post_signal(MG_SIG_ACCEPT, nc);
-  (void) err;
-  (void) lpcb;
-  return ERR_OK;
-}
-
-struct mg_lwip_if_listen_ctx {
-  struct mg_connection *nc;
-  union socket_address *sa;
-  int ret;
-};
-
-static void mg_lwip_if_listen_tcp_tcpip(void *arg) {
-  struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
-  struct mg_connection *nc = ctx->nc;
-  union socket_address *sa = ctx->sa;
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  struct tcp_pcb *tpcb = TCP_NEW();
-  ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
-  u16_t port = ntohs(sa->sin.sin_port);
-  cs->err = TCP_BIND(tpcb, ip, port);
-  DBG(("%p tcp_bind(%s:%u) = %d", (void*)nc, IPADDR_NTOA(ip), port, cs->err));
-  if (cs->err != ERR_OK) {
-    tcp_close(tpcb);
-    ctx->ret = -1;
-    return;
-  }
-  tcp_arg(tpcb, nc);
-  tpcb = tcp_listen(tpcb);
-  cs->pcb.tcp = tpcb;
-  tcp_accept(tpcb, mg_lwip_accept_cb);
-  ctx->ret = 0;
-}
-
-int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
-  struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
-  mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_tcp_tcpip, &ctx);
-  return ctx.ret;
-}
-
-static void mg_lwip_if_listen_udp_tcpip(void *arg) {
-  struct mg_lwip_if_listen_ctx *ctx = (struct mg_lwip_if_listen_ctx *) arg;
-  struct mg_connection *nc = ctx->nc;
-  union socket_address *sa = ctx->sa;
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  struct udp_pcb *upcb = udp_new();
-  ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
-  u16_t port = ntohs(sa->sin.sin_port);
-  cs->err = UDP_BIND(upcb, ip, port);
-  DBG(("%p udb_bind(%s:%u) = %d", (void*)nc, IPADDR_NTOA(ip), port, cs->err));
-  if (cs->err != ERR_OK) {
-    udp_remove(upcb);
-    ctx->ret = -1;
-  } else {
-    udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
-    cs->pcb.udp = upcb;
-    ctx->ret = 0;
-  }
-}
-
-int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
-  struct mg_lwip_if_listen_ctx ctx = {.nc = nc, .sa = sa};
-  mg_lwip_netif_run_on_tcpip(mg_lwip_if_listen_udp_tcpip, &ctx);
-  return ctx.ret;
-}
-
-struct mg_lwip_tcp_write_ctx {
-  struct mg_connection *nc;
-  const void *data;
-  uint16_t len;
-  int ret;
-};
-
-static void tcp_output_tcpip(void *arg) {
-  tcp_output((struct tcp_pcb *) arg);
-}
-
-static void mg_lwip_tcp_write_tcpip(void *arg) {
-  struct mg_lwip_tcp_write_ctx *ctx = (struct mg_lwip_tcp_write_ctx *) arg;
-  struct mg_connection *nc = ctx->nc;
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  struct tcp_pcb *tpcb = cs->pcb.tcp;
-  size_t len = MIN(tpcb->mss, MIN(ctx->len, tpcb->snd_buf));
-  size_t unsent, unacked;
-  if (len == 0) {
-    DBG(("%p no buf avail %u %u %p %p", (void*)tpcb, tpcb->snd_buf, tpcb->snd_queuelen,
-         (void*)tpcb->unsent, (void*)tpcb->unacked));
-    mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, tpcb);
-    ctx->ret = 0;
-    return;
-  }
-  unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
-  unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
-/*
- * On ESP8266 we only allow one TCP segment in flight at any given time.
- * This may increase latency and reduce efficiency of tcp windowing,
- * but memory is scarce and precious on that platform so we do this to
- * reduce footprint.
- */
-#if CS_PLATFORM == CS_P_ESP8266
-  if (unacked > 0) {
-    ctx->ret = 0;
-    return;
-  }
-  len = MIN(len, (TCP_MSS - unsent));
-#endif
-  cs->err = tcp_write(tpcb, ctx->data, len, TCP_WRITE_FLAG_COPY);
-  unsent = (tpcb->unsent != NULL ? tpcb->unsent->len : 0);
-  unacked = (tpcb->unacked != NULL ? tpcb->unacked->len : 0);
-  DBG(("%p tcp_write %u = %d, %u %u", (void*)tpcb, len, cs->err, unsent, unacked));
-  if (cs->err != ERR_OK) {
-    /*
-     * We ignore ERR_MEM because memory will be freed up when the data is sent
-     * and we'll retry.
-     */
-    ctx->ret = (cs->err == ERR_MEM ? 0 : -1);
-    return;
-  }
-  ctx->ret = len;
-  (void) unsent;
-  (void) unacked;
-}
-
-int mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
-  struct mg_lwip_tcp_write_ctx ctx = {.nc = nc, .data = buf, .len = len};
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  if (nc->sock == INVALID_SOCKET) return -1;
-  struct tcp_pcb *tpcb = cs->pcb.tcp;
-  if (tpcb == NULL) return -1;
-  if (tpcb->snd_buf <= 0) return 0;
-  mg_lwip_netif_run_on_tcpip(mg_lwip_tcp_write_tcpip, &ctx);
-  return ctx.ret;
-}
-
-struct udp_sendto_ctx {
-  struct udp_pcb *upcb;
-  struct pbuf *p;
-  ip_addr_t *ip;
-  uint16_t port;
-  int ret;
-};
-
-static void udp_sendto_tcpip(void *arg) {
-  struct udp_sendto_ctx *ctx = (struct udp_sendto_ctx *) arg;
-  ctx->ret = udp_sendto(ctx->upcb, ctx->p, ctx->ip, ctx->port);
-}
-
-static int mg_lwip_if_udp_send(struct mg_connection *nc, const void *data,
-                               size_t len) {
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) return -1;
-  struct udp_pcb *upcb = cs->pcb.udp;
-  struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
-#if defined(LWIP_IPV4) && LWIP_IPV4 && defined(LWIP_IPV6) && LWIP_IPV6
-  ip_addr_t ip = {.u_addr.ip4.addr = nc->sa.sin.sin_addr.s_addr, .type = 0};
-#else
-  ip_addr_t ip = {.addr = nc->sa.sin.sin_addr.s_addr};
-#endif
-  u16_t port = ntohs(nc->sa.sin.sin_port);
-  if (p == NULL) return 0;
-  memcpy(p->payload, data, len);
-  struct udp_sendto_ctx ctx = {.upcb = upcb, .p = p, .ip = &ip, .port = port};
-  mg_lwip_netif_run_on_tcpip(udp_sendto_tcpip, &ctx);
-  cs->err = ctx.ret;
-  pbuf_free(p);
-  return (cs->err == ERR_OK ? (int) len : -2);
-}
-
-static int mg_lwip_if_can_send(struct mg_connection *nc,
-                               struct mg_lwip_conn_state *cs) {
-  int can_send = 0;
-  if (nc->send_mbuf.len > 0 || (nc->flags & MG_F_WANT_WRITE)) {
-    /* We have stuff to send, but can we? */
-    if (nc->flags & MG_F_UDP) {
-      /* UDP is always ready for sending. */
-      can_send = (cs->pcb.udp != NULL);
-    } else {
-      can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0);
-/* See comment above. */
-#if CS_PLATFORM == CS_P_ESP8266
-      if (cs->pcb.tcp->unacked != NULL) can_send = 0;
-#endif
-    }
-  }
-  return can_send;
-}
-
-struct tcp_recved_ctx {
-  struct tcp_pcb *tpcb;
-  size_t len;
-};
-
-void tcp_recved_tcpip(void *arg) {
-  struct tcp_recved_ctx *ctx = (struct tcp_recved_ctx *) arg;
-  if (ctx->tpcb != NULL) tcp_recved(ctx->tpcb, ctx->len);
-}
-
-static int mg_lwip_if_tcp_recv(struct mg_connection *nc, void *buf,
-                               size_t len) {
-  int res = 0;
-  char *bufp = buf;
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  if (nc->sock == INVALID_SOCKET) return -1;
-  mgos_lock();
-  while (cs->rx_chain != NULL && len > 0) {
-    struct pbuf *seg = cs->rx_chain;
-    size_t seg_len = (seg->len - cs->rx_offset);
-    size_t copy_len = MIN(len, seg_len);
-
-    pbuf_copy_partial(seg, bufp, copy_len, cs->rx_offset);
-    len -= copy_len;
-    res += copy_len;
-    bufp += copy_len;
-    cs->rx_offset += copy_len;
-    if (cs->rx_offset == cs->rx_chain->len) {
-      cs->rx_chain = pbuf_dechain(cs->rx_chain);
-      pbuf_free(seg);
-      cs->rx_offset = 0;
-    }
-  }
-  mgos_unlock();
-  if (res > 0) {
-    struct tcp_recved_ctx ctx = {.tpcb = cs->pcb.tcp, .len = res};
-    mg_lwip_netif_run_on_tcpip(tcp_recved_tcpip, &ctx);
-  }
-  return res;
-}
-
-int mg_lwip_if_create_conn(struct mg_connection *nc) {
-  struct mg_lwip_conn_state *cs =
-      (struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs));
-  if (cs == NULL) return 0;
-  cs->nc = nc;
-  nc->sock = (intptr_t) cs;
-  return 1;
-}
-
-static void udp_remove_tcpip(void *arg) {
-  udp_remove((struct udp_pcb *) arg);
-}
-
-void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
-  if (nc->sock == INVALID_SOCKET) return;
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  if (!(nc->flags & MG_F_UDP)) {
-    struct tcp_pcb *tpcb = cs->pcb.tcp;
-    if (tpcb != NULL) {
-      tcp_arg(tpcb, NULL);
-      DBG(("%p tcp_close %p", (void*)nc, (void*)tpcb));
-      tcp_arg(tpcb, NULL);
-      mg_lwip_netif_run_on_tcpip(tcp_close_tcpip, tpcb);
-    }
-    while (cs->rx_chain != NULL) {
-      struct pbuf *seg = cs->rx_chain;
-      cs->rx_chain = pbuf_dechain(cs->rx_chain);
-      pbuf_free(seg);
-    }
-    memset(cs, 0, sizeof(*cs));
-    MG_FREE(cs);
-  } else if (nc->listener == NULL) {
-    /* Only close outgoing UDP pcb or listeners. */
-    struct udp_pcb *upcb = cs->pcb.udp;
-    if (upcb != NULL) {
-      DBG(("%p udp_remove %p", (void*)nc, (void*)upcb));
-      mg_lwip_netif_run_on_tcpip(udp_remove_tcpip, upcb);
-    }
-    memset(cs, 0, sizeof(*cs));
-    MG_FREE(cs);
-  }
-  nc->sock = INVALID_SOCKET;
-}
-
-void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
-                              union socket_address *sa) {
-  memset(sa, 0, sizeof(*sa));
-  if (nc == NULL || nc->sock == INVALID_SOCKET) return;
-  struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-  if (nc->flags & MG_F_UDP) {
-    struct udp_pcb *upcb = cs->pcb.udp;
-    if (remote) {
-      memcpy(sa, &nc->sa, sizeof(*sa));
-    } else if (upcb != NULL) {
-      sa->sin.sin_port = htons(upcb->local_port);
-      SET_ADDR(sa, &upcb->local_ip);
-    }
-  } else {
-    struct tcp_pcb *tpcb = cs->pcb.tcp;
-    if (remote) {
-      memcpy(sa, &nc->sa, sizeof(*sa));
-    } else if (tpcb != NULL) {
-      sa->sin.sin_port = htons(tpcb->local_port);
-      SET_ADDR(sa, &tpcb->local_ip);
-    }
-  }
-}
-
-void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) {
-  nc->sock = sock;
-}
-
-/* clang-format off */
-#define MG_LWIP_IFACE_VTABLE                                          \
-  {                                                                   \
-    mg_lwip_if_init,                                                  \
-    mg_lwip_if_free,                                                  \
-    mg_lwip_if_add_conn,                                              \
-    mg_lwip_if_remove_conn,                                           \
-    mg_lwip_if_poll,                                                  \
-    mg_lwip_if_listen_tcp,                                            \
-    mg_lwip_if_listen_udp,                                            \
-    mg_lwip_if_connect_tcp,                                           \
-    mg_lwip_if_connect_udp,                                           \
-    mg_lwip_if_tcp_send,                                              \
-    mg_lwip_if_udp_send,                                              \
-    mg_lwip_if_tcp_recv,                                              \
-    mg_lwip_if_udp_recv,                                              \
-    mg_lwip_if_create_conn,                                           \
-    mg_lwip_if_destroy_conn,                                          \
-    mg_lwip_if_sock_set,                                              \
-    mg_lwip_if_get_conn_addr,                                         \
-  }
-/* clang-format on */
-
-const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE;
-#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
-const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE;
-#endif
-
-#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/lwip/mg_lwip_ev_mgr.c"
-#endif
-
-#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
-
-#ifndef MG_SIG_QUEUE_LEN
-#define MG_SIG_QUEUE_LEN 32
-#endif
-
-struct mg_ev_mgr_lwip_signal {
-  int sig;
-  struct mg_connection *nc;
-};
-
-struct mg_ev_mgr_lwip_data {
-  struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN];
-  int sig_queue_len;
-  int start_index;
-};
-
-void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) {
-  struct mg_ev_mgr_lwip_data *md =
-      (struct mg_ev_mgr_lwip_data *) nc->iface->data;
-  mgos_lock();
-  if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) {
-    mgos_unlock();
-    return;
-  }
-  int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN;
-  md->sig_queue[end_index].sig = sig;
-  md->sig_queue[end_index].nc = nc;
-  md->sig_queue_len++;
-  mg_lwip_mgr_schedule_poll(nc->mgr);
-  mgos_unlock();
-}
-
-void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) {
-  struct mg_ev_mgr_lwip_data *md =
-      (struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data;
-  while (md->sig_queue_len > 0) {
-    mgos_lock();
-    int i = md->start_index;
-    int sig = md->sig_queue[i].sig;
-    struct mg_connection *nc = md->sig_queue[i].nc;
-    struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-    md->start_index = (i + 1) % MG_SIG_QUEUE_LEN;
-    md->sig_queue_len--;
-    mgos_unlock();
-    if (nc->iface == NULL || nc->mgr == NULL) continue;
-    switch (sig) {
-      case MG_SIG_CONNECT_RESULT: {
-        mg_if_connect_cb(nc, cs->err);
-        break;
-      }
-      case MG_SIG_CLOSE_CONN: {
-        mg_close_conn(nc);
-        break;
-      }
-      case MG_SIG_RECV: {
-        cs->recv_pending = 0;
-        mg_if_can_recv_cb(nc);
-        mbuf_trim(&nc->recv_mbuf);
-        break;
-      }
-      case MG_SIG_TOMBSTONE: {
-        break;
-      }
-      case MG_SIG_ACCEPT: {
-        mg_lwip_handle_accept(nc);
-        break;
-      }
-    }
-  }
-}
-
-void mg_lwip_if_init(struct mg_iface *iface) {
-  LOG(LL_INFO, ("Mongoose %s, LwIP %u.%u.%u", MG_VERSION, LWIP_VERSION_MAJOR,
-                LWIP_VERSION_MINOR, LWIP_VERSION_REVISION));
-  iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data));
-#if !NO_SYS && !LWIP_TCPIP_CORE_LOCKING
-  sys_sem_new(&s_tcpip_call_lock_sem, 1);
-  sys_sem_new(&s_tcpip_call_sync_sem, 0);
-#endif
-}
-
-void mg_lwip_if_free(struct mg_iface *iface) {
-  MG_FREE(iface->data);
-  iface->data = NULL;
-}
-
-void mg_lwip_if_add_conn(struct mg_connection *nc) {
-  (void) nc;
-}
-
-void mg_lwip_if_remove_conn(struct mg_connection *nc) {
-  struct mg_ev_mgr_lwip_data *md =
-      (struct mg_ev_mgr_lwip_data *) nc->iface->data;
-  /* Walk the queue and null-out further signals for this conn. */
-  for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) {
-    if (md->sig_queue[i].nc == nc) {
-      md->sig_queue[i].sig = MG_SIG_TOMBSTONE;
-    }
-  }
-}
-
-time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) {
-  struct mg_mgr *mgr = iface->mgr;
-  int n = 0;
-  double now = mg_time();
-  struct mg_connection *nc, *tmp;
-  double min_timer = 0;
-  int num_timers = 0;
-#if 0
-  DBG(("begin poll @%u", (unsigned int) (now * 1000)));
-#endif
-  mg_ev_mgr_lwip_process_signals(mgr);
-  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
-    struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
-    tmp = nc->next;
-    n++;
-    if (!mg_if_poll(nc, now)) continue;
-    if (nc->sock != INVALID_SOCKET &&
-        !(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL &&
-        cs->pcb.tcp->unsent != NULL) {
-      mg_lwip_netif_run_on_tcpip(tcp_output_tcpip, cs->pcb.tcp);
-    }
-    if (nc->ev_timer_time > 0) {
-      if (num_timers == 0 || nc->ev_timer_time < min_timer) {
-        min_timer = nc->ev_timer_time;
-      }
-      num_timers++;
-    }
-
-    if (nc->sock != INVALID_SOCKET) {
-      if (mg_lwip_if_can_send(nc, cs)) {
-        mg_if_can_send_cb(nc);
-        mbuf_trim(&nc->send_mbuf);
-      }
-      if (cs->rx_chain != NULL) {
-        mg_if_can_recv_cb(nc);
-      } else if (cs->draining_rx_chain) {
-        /*
-         * If the connection is about to close, and rx_chain is finally empty,
-         * send the MG_SIG_CLOSE_CONN signal
-         */
-        mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
-      }
-    }
-  }
-#if 0
-  DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms",
-       (unsigned int) (now * 1000), n, num_timers,
-       (unsigned int) (min_timer * 1000), timeout_ms));
-#endif
-  (void) timeout_ms;
-  return now;
-}
-
-#endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/wince/wince_libc.c"
-#endif
-
-#ifdef WINCE
-
-const char *strerror(int err) {
-  /*
-   * TODO(alashkin): there is no strerror on WinCE;
-   * look for similar wce_xxxx function
-   */
-  static char buf[10];
-  snprintf(buf, sizeof(buf), "%d", err);
-  return buf;
-}
-
-int open(const char *filename, int oflag, int pmode) {
-  /*
-   * TODO(alashkin): mg_open function is not used in mongoose
-   * but exists in documentation as utility function
-   * Shall we delete it at all or implement for WinCE as well?
-   */
-  DebugBreak();
-  return 0; /* for compiler */
-}
-
-int _wstati64(const wchar_t *path, cs_stat_t *st) {
-  DWORD fa = GetFileAttributesW(path);
-  if (fa == INVALID_FILE_ATTRIBUTES) {
-    return -1;
-  }
-  memset(st, 0, sizeof(*st));
-  if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
-    HANDLE h;
-    FILETIME ftime;
-    st->st_mode |= _S_IFREG;
-    h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
-                    FILE_ATTRIBUTE_NORMAL, NULL);
-    if (h == INVALID_HANDLE_VALUE) {
-      return -1;
-    }
-    st->st_size = GetFileSize(h, NULL);
-    GetFileTime(h, NULL, NULL, &ftime);
-    st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
-                                ((uint64_t) ftime.dwHighDateTime << 32)) /
-                               10000000.0) -
-                              11644473600);
-    CloseHandle(h);
-  } else {
-    st->st_mode |= _S_IFDIR;
-  }
-  return 0;
-}
-
-/* Windows CE doesn't have neither gmtime nor strftime */
-static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
-  FILETIME ft;
-  SYSTEMTIME systime;
-  if (t != NULL) {
-    uint64_t filetime = (*t + 11644473600) * 10000000;
-    ft.dwLowDateTime = filetime & 0xFFFFFFFF;
-    ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
-    FileTimeToSystemTime(&ft, &systime);
-  } else {
-    GetSystemTime(&systime);
-  }
-  /* There is no PRIu16 in WinCE SDK */
-  snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear,
-           (int) systime.wMonth, (int) systime.wDay, (int) systime.wHour,
-           (int) systime.wMinute, (int) systime.wSecond);
-}
-
-#endif
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/pic32/pic32_net_if.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
-#define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
-
-/* Amalgamated: #include "mongoose/src/net_if.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#ifndef MG_ENABLE_NET_IF_PIC32
-#define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
-#endif
-
-extern const struct mg_iface_vtable mg_pic32_iface_vtable;
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/pic32/pic32_net_if.c"
-#endif
-
-#if MG_ENABLE_NET_IF_PIC32
-
-int mg_pic32_if_create_conn(struct mg_connection *nc) {
-  (void) nc;
-  return 1;
-}
-
-void mg_pic32_if_recved(struct mg_connection *nc, size_t len) {
-  (void) nc;
-  (void) len;
-}
-
-void mg_pic32_if_add_conn(struct mg_connection *nc) {
-  (void) nc;
-}
-
-void mg_pic32_if_init(struct mg_iface *iface) {
-  (void) iface;
-  (void) mg_get_errno(); /* Shutup compiler */
-}
-
-void mg_pic32_if_free(struct mg_iface *iface) {
-  (void) iface;
-}
-
-void mg_pic32_if_remove_conn(struct mg_connection *nc) {
-  (void) nc;
-}
-
-void mg_pic32_if_destroy_conn(struct mg_connection *nc) {
-  if (nc->sock == INVALID_SOCKET) return;
-  /* For UDP, only close outgoing sockets or listeners. */
-  if (!(nc->flags & MG_F_UDP)) {
-    /* Close TCP */
-    TCPIP_TCP_Close((TCP_SOCKET) nc->sock);
-  } else if (nc->listener == NULL) {
-    /* Only close outgoing UDP or listeners. */
-    TCPIP_UDP_Close((UDP_SOCKET) nc->sock);
-  }
-
-  nc->sock = INVALID_SOCKET;
-}
-
-int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
-  nc->sock = TCPIP_UDP_ServerOpen(
-      sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
-                                    : IP_ADDRESS_TYPE_IPV6,
-      ntohs(sa->sin.sin_port),
-      sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
-  if (nc->sock == INVALID_SOCKET) {
-    return -1;
-  }
-  return 0;
-}
-
-void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf,
-                          size_t len) {
-  mbuf_append(&nc->send_mbuf, buf, len);
-}
-
-void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf,
-                          size_t len) {
-  mbuf_append(&nc->send_mbuf, buf, len);
-}
-
-int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
-  nc->sock = TCPIP_TCP_ServerOpen(
-      sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
-                                    : IP_ADDRESS_TYPE_IPV6,
-      ntohs(sa->sin.sin_port),
-      sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
-  memcpy(&nc->sa, sa, sizeof(*sa));
-  if (nc->sock == INVALID_SOCKET) {
-    return -1;
-  }
-  return 0;
-}
-
-static int mg_accept_conn(struct mg_connection *lc) {
-  struct mg_connection *nc;
-  TCP_SOCKET_INFO si;
-  union socket_address sa;
-
-  nc = mg_if_accept_new_conn(lc);
-
-  if (nc == NULL) {
-    return 0;
-  }
-
-  nc->sock = lc->sock;
-  nc->flags &= ~MG_F_LISTENING;
-
-  if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) {
-    return 0;
-  }
-
-  if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
-    sa.sin.sin_family = AF_INET;
-    sa.sin.sin_port = htons(si.remotePort);
-    sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
-  } else {
-    /* TODO(alashkin): do something with _potential_ IPv6 */
-    memset(&sa, 0, sizeof(sa));
-  }
-
-  mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa));
-
-  return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0;
-}
-
-char *inet_ntoa(struct in_addr in) {
-  static char addr[17];
-  snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1,
-           (int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3,
-           (int) in.S_un.S_un_b.s_b4);
-  return addr;
-}
-
-static void mg_handle_send(struct mg_connection *nc) {
-  uint16_t bytes_written = 0;
-  if (nc->flags & MG_F_UDP) {
-    if (!TCPIP_UDP_RemoteBind(
-            (UDP_SOCKET) nc->sock,
-            nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
-                                             : IP_ADDRESS_TYPE_IPV6,
-            ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) {
-      nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-      return;
-    }
-    bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0);
-    if (bytes_written >= nc->send_mbuf.len) {
-      if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock,
-                             (uint8_t *) nc->send_mbuf.buf,
-                             nc->send_mbuf.len) != nc->send_mbuf.len) {
-        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-        bytes_written = 0;
-      }
-    }
-  } else {
-    bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock);
-    if (bytes_written != 0) {
-      if (bytes_written > nc->send_mbuf.len) {
-        bytes_written = nc->send_mbuf.len;
-      }
-      if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock,
-                             (uint8_t *) nc->send_mbuf.buf,
-                             bytes_written) != bytes_written) {
-        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-        bytes_written = 0;
-      }
-    }
-  }
-
-  mg_if_sent_cb(nc, bytes_written);
-}
-
-static void mg_handle_recv(struct mg_connection *nc) {
-  uint16_t bytes_read = 0;
-  uint8_t *buf = NULL;
-  if (nc->flags & MG_F_UDP) {
-    bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock);
-    if (bytes_read != 0 &&
-        (nc->recv_mbuf_limit == -1 ||
-         nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) {
-      buf = (uint8_t *) MG_MALLOC(bytes_read);
-      if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) !=
-          bytes_read) {
-        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-        bytes_read = 0;
-        MG_FREE(buf);
-      }
-    }
-  } else {
-    bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock);
-    if (bytes_read != 0) {
-      if (nc->recv_mbuf_limit != -1 &&
-          nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) {
-        bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len;
-      }
-      buf = (uint8_t *) MG_MALLOC(bytes_read);
-      if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) !=
-          bytes_read) {
-        nc->flags |= MG_F_CLOSE_IMMEDIATELY;
-        MG_FREE(buf);
-        bytes_read = 0;
-      }
-    }
-  }
-
-  if (bytes_read != 0) {
-    mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */);
-  }
-}
-
-time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) {
-  struct mg_mgr *mgr = iface->mgr;
-  double now = mg_time();
-  struct mg_connection *nc, *tmp;
-
-  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
-    tmp = nc->next;
-
-    if (nc->flags & MG_F_CONNECTING) {
-      /* processing connections */
-      if (nc->flags & MG_F_UDP ||
-          TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
-        mg_if_connect_cb(nc, 0);
-      }
-    } else if (nc->flags & MG_F_LISTENING) {
-      if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
-        /* accept new connections */
-        mg_accept_conn(nc);
-      }
-    } else {
-      if (nc->send_mbuf.len != 0) {
-        mg_handle_send(nc);
-      }
-
-      if (nc->recv_mbuf_limit == -1 ||
-          nc->recv_mbuf.len < nc->recv_mbuf_limit) {
-        mg_handle_recv(nc);
-      }
-    }
-  }
-
-  for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
-    tmp = nc->next;
-    if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
-        (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
-      mg_close_conn(nc);
-    }
-  }
-
-  return now;
-}
-
-void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) {
-  nc->sock = sock;
-}
-
-void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote,
-                               union socket_address *sa) {
-  /* TODO(alaskin): not implemented yet */
-}
-
-void mg_pic32_if_connect_tcp(struct mg_connection *nc,
-                             const union socket_address *sa) {
-  nc->sock = TCPIP_TCP_ClientOpen(
-      sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
-                                    : IP_ADDRESS_TYPE_IPV6,
-      ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin);
-  nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
-}
-
-void mg_pic32_if_connect_udp(struct mg_connection *nc) {
-  nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
-  nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
-}
-
-/* clang-format off */
-#define MG_PIC32_IFACE_VTABLE                                   \
-  {                                                             \
-    mg_pic32_if_init,                                           \
-    mg_pic32_if_free,                                           \
-    mg_pic32_if_add_conn,                                       \
-    mg_pic32_if_remove_conn,                                    \
-    mg_pic32_if_poll,                                           \
-    mg_pic32_if_listen_tcp,                                     \
-    mg_pic32_if_listen_udp,                                     \
-    mg_pic32_if_connect_tcp,                                    \
-    mg_pic32_if_connect_udp,                                    \
-    mg_pic32_if_tcp_send,                                       \
-    mg_pic32_if_udp_send,                                       \
-    mg_pic32_if_recved,                                         \
-    mg_pic32_if_create_conn,                                    \
-    mg_pic32_if_destroy_conn,                                   \
-    mg_pic32_if_sock_set,                                       \
-    mg_pic32_if_get_conn_addr,                                  \
-  }
-/* clang-format on */
-
-const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE;
-#if MG_NET_IF == MG_NET_IF_PIC32
-const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE;
-#endif
-
-#endif /* MG_ENABLE_NET_IF_PIC32 */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/windows/windows_direct.c"
-#endif
-
-#ifdef _WIN32
-
-int rmdir(const char *dirname) {
-  return _rmdir(dirname);
-}
-
-unsigned int sleep(unsigned int seconds) {
-  Sleep(seconds * 1000);
-  return 0;
-}
-
-#endif /* _WIN32 */
diff --git a/vendor/mongoose.h b/vendor/mongoose.h
deleted file mode 100644
index 7808e91..0000000
--- a/vendor/mongoose.h
+++ /dev/null
@@ -1,6285 +0,0 @@
-/*
- * Copyright (c) 2004-2013 Sergey Lyubka
- * Copyright (c) 2013-2020 Cesanta Software Limited
- * All rights reserved
- *
- * This software is dual-licensed: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License version 2 as
- * published by the Free Software Foundation. For the terms of this
- * license, see <http://www.gnu.org/licenses/>.
- *
- * You are free to use this software under the terms of the GNU General
- * Public License, but WITHOUT ANY WARRANTY; without even the implied
- * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
- * See the GNU General Public License for more details.
- *
- * Alternatively, you can license this software under a commercial
- * license, as set out in <https://www.cesanta.com/license>.
- */
-
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_common.h"
-#endif
-#ifndef CS_MONGOOSE_SRC_COMMON_H_
-#define CS_MONGOOSE_SRC_COMMON_H_
-
-#define MG_VERSION "6.18"
-
-/* Local tweaks, applied before any of Mongoose's own headers. */
-#ifdef MG_LOCALS
-#include <mg_locals.h>
-#endif
-
-#endif /* CS_MONGOOSE_SRC_COMMON_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platform.h"
-#endif
-#ifndef CS_COMMON_PLATFORM_H_
-#define CS_COMMON_PLATFORM_H_
-
-/*
- * For the "custom" platform, includes and dependencies can be
- * provided through mg_locals.h.
- */
-#define CS_P_CUSTOM 0
-#define CS_P_UNIX 1
-#define CS_P_WINDOWS 2
-#define CS_P_ESP32 15
-#define CS_P_ESP8266 3
-#define CS_P_CC3100 6
-#define CS_P_CC3200 4
-#define CS_P_CC3220 17
-#define CS_P_MSP432 5
-#define CS_P_TM4C129 14
-#define CS_P_MBED 7
-#define CS_P_WINCE 8
-#define CS_P_NXP_LPC 13
-#define CS_P_NXP_KINETIS 9
-#define CS_P_NRF51 12
-#define CS_P_NRF52 10
-#define CS_P_PIC32 11
-#define CS_P_RS14100 18
-#define CS_P_STM32 16
-/* Next id: 19 */
-
-/* If not specified explicitly, we guess platform by defines. */
-#ifndef CS_PLATFORM
-
-#if defined(TARGET_IS_MSP432P4XX) || defined(__MSP432P401R__)
-#define CS_PLATFORM CS_P_MSP432
-#elif defined(cc3200) || defined(TARGET_IS_CC3200)
-#define CS_PLATFORM CS_P_CC3200
-#elif defined(cc3220) || defined(TARGET_IS_CC3220)
-#define CS_PLATFORM CS_P_CC3220
-#elif defined(__unix__) || defined(__APPLE__)
-#define CS_PLATFORM CS_P_UNIX
-#elif defined(WINCE)
-#define CS_PLATFORM CS_P_WINCE
-#elif defined(_WIN32)
-#define CS_PLATFORM CS_P_WINDOWS
-#elif defined(__MBED__)
-#define CS_PLATFORM CS_P_MBED
-#elif defined(__USE_LPCOPEN)
-#define CS_PLATFORM CS_P_NXP_LPC
-#elif defined(FRDM_K64F) || defined(FREEDOM)
-#define CS_PLATFORM CS_P_NXP_KINETIS
-#elif defined(PIC32)
-#define CS_PLATFORM CS_P_PIC32
-#elif defined(ESP_PLATFORM)
-#define CS_PLATFORM CS_P_ESP32
-#elif defined(ICACHE_FLASH)
-#define CS_PLATFORM CS_P_ESP8266
-#elif defined(TARGET_IS_TM4C129_RA0) || defined(TARGET_IS_TM4C129_RA1) || \
-    defined(TARGET_IS_TM4C129_RA2)
-#define CS_PLATFORM CS_P_TM4C129
-#elif defined(RS14100)
-#define CS_PLATFORM CS_P_RS14100
-#elif defined(STM32)
-#define CS_PLATFORM CS_P_STM32
-#endif
-
-#ifndef CS_PLATFORM
-#error "CS_PLATFORM is not specified and we couldn't guess it."
-#endif
-
-#endif /* !defined(CS_PLATFORM) */
-
-#define MG_NET_IF_SOCKET 1
-#define MG_NET_IF_SIMPLELINK 2
-#define MG_NET_IF_LWIP_LOW_LEVEL 3
-#define MG_NET_IF_PIC32 4
-#define MG_NET_IF_NULL 5
-
-#define MG_SSL_IF_OPENSSL 1
-#define MG_SSL_IF_MBEDTLS 2
-#define MG_SSL_IF_SIMPLELINK 3
-
-/* Amalgamated: #include "common/platforms/platform_unix.h" */
-/* Amalgamated: #include "common/platforms/platform_windows.h" */
-/* Amalgamated: #include "common/platforms/platform_esp32.h" */
-/* Amalgamated: #include "common/platforms/platform_esp8266.h" */
-/* Amalgamated: #include "common/platforms/platform_cc3100.h" */
-/* Amalgamated: #include "common/platforms/platform_cc3200.h" */
-/* Amalgamated: #include "common/platforms/platform_cc3220.h" */
-/* Amalgamated: #include "common/platforms/platform_mbed.h" */
-/* Amalgamated: #include "common/platforms/platform_nrf51.h" */
-/* Amalgamated: #include "common/platforms/platform_nrf52.h" */
-/* Amalgamated: #include "common/platforms/platform_wince.h" */
-/* Amalgamated: #include "common/platforms/platform_nxp_lpc.h" */
-/* Amalgamated: #include "common/platforms/platform_nxp_kinetis.h" */
-/* Amalgamated: #include "common/platforms/platform_pic32.h" */
-/* Amalgamated: #include "common/platforms/platform_rs14100.h" */
-/* Amalgamated: #include "common/platforms/platform_stm32.h" */
-#if CS_PLATFORM == CS_P_CUSTOM
-#include <platform_custom.h>
-#endif
-
-/* Common stuff */
-
-#if !defined(PRINTF_LIKE)
-#if defined(__GNUC__) || defined(__clang__) || defined(__TI_COMPILER_VERSION__)
-#define PRINTF_LIKE(f, a) __attribute__((format(printf, f, a)))
-#else
-#define PRINTF_LIKE(f, a)
-#endif
-#endif
-
-#if !defined(WEAK)
-#if (defined(__GNUC__) || defined(__clang__) || \
-     defined(__TI_COMPILER_VERSION__)) &&       \
-    !defined(_WIN32)
-#define WEAK __attribute__((weak))
-#else
-#define WEAK
-#endif
-#endif
-
-#ifdef __GNUC__
-#define NORETURN __attribute__((noreturn))
-#define NOINLINE __attribute__((noinline))
-#define WARN_UNUSED_RESULT __attribute__((warn_unused_result))
-#define NOINSTR __attribute__((no_instrument_function))
-#define DO_NOT_WARN_UNUSED __attribute__((unused))
-#else
-#define NORETURN
-#define NOINLINE
-#define WARN_UNUSED_RESULT
-#define NOINSTR
-#define DO_NOT_WARN_UNUSED
-#endif /* __GNUC__ */
-
-#ifndef ARRAY_SIZE
-#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
-#endif
-
-#endif /* CS_COMMON_PLATFORM_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_windows.h"
-#endif
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_
-#if CS_PLATFORM == CS_P_WINDOWS
-
-/*
- * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)
- * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)
- * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012)
- * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010)
- * MSVC++ 9.0  _MSC_VER == 1500 (Visual Studio 2008)
- * MSVC++ 8.0  _MSC_VER == 1400 (Visual Studio 2005)
- * MSVC++ 7.1  _MSC_VER == 1310 (Visual Studio 2003)
- * MSVC++ 7.0  _MSC_VER == 1300
- * MSVC++ 6.0  _MSC_VER == 1200
- * MSVC++ 5.0  _MSC_VER == 1100
- */
-#ifdef _MSC_VER
-#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */
-#pragma warning(disable : 4204) /* missing c99 support */
-#endif
-
-#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
-#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
-#endif
-
-#ifndef _CRT_SECURE_NO_WARNINGS
-#define _CRT_SECURE_NO_WARNINGS
-#endif
-
-#include <assert.h>
-#include <direct.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <io.h>
-#include <limits.h>
-#include <signal.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <sys/stat.h>
-#include <time.h>
-#include <ctype.h>
-
-#ifdef _MSC_VER
-#pragma comment(lib, "ws2_32.lib") /* Linking with winsock library */
-#endif
-
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#include <windows.h>
-#include <process.h>
-
-#if defined(_MSC_VER) && (_MSC_VER < 1700)
-typedef int bool;
-#else
-#include <stdbool.h>
-#endif
-
-#if defined(_MSC_VER) && _MSC_VER >= 1800
-#define strdup _strdup
-#endif
-
-#ifndef EINPROGRESS
-#define EINPROGRESS WSAEINPROGRESS
-#endif
-#ifndef EWOULDBLOCK
-#define EWOULDBLOCK WSAEWOULDBLOCK
-#endif
-#ifndef __func__
-#define STRX(x) #x
-#define STR(x) STRX(x)
-#define __func__ __FILE__ ":" STR(__LINE__)
-#endif
-#define snprintf _snprintf
-#define vsnprintf _vsnprintf
-#define to64(x) _atoi64(x)
-#if !defined(__MINGW32__) && !defined(__MINGW64__)
-#define popen(x, y) _popen((x), (y))
-#define pclose(x) _pclose(x)
-#define fileno _fileno
-#endif
-#if defined(_MSC_VER) && _MSC_VER >= 1400
-#define fseeko(x, y, z) _fseeki64((x), (y), (z))
-#else
-#define fseeko(x, y, z) fseek((x), (y), (z))
-#endif
-#if defined(_MSC_VER) && _MSC_VER <= 1200
-typedef unsigned long uintptr_t;
-typedef long intptr_t;
-#endif
-typedef int socklen_t;
-#if _MSC_VER >= 1700
-#include <stdint.h>
-#else
-typedef signed char int8_t;
-typedef unsigned char uint8_t;
-typedef int int32_t;
-typedef unsigned int uint32_t;
-typedef short int16_t;
-typedef unsigned short uint16_t;
-typedef __int64 int64_t;
-typedef unsigned __int64 uint64_t;
-#endif
-typedef SOCKET sock_t;
-typedef uint32_t in_addr_t;
-#ifndef UINT16_MAX
-#define UINT16_MAX 65535
-#endif
-#ifndef UINT32_MAX
-#define UINT32_MAX 4294967295
-#endif
-#ifndef pid_t
-#define pid_t HANDLE
-#endif
-#define INT64_FMT "I64d"
-#define INT64_X_FMT "I64x"
-#define SIZE_T_FMT "Iu"
-typedef struct _stati64 cs_stat_t;
-#ifndef S_ISDIR
-#define S_ISDIR(x) (((x) &_S_IFMT) == _S_IFDIR)
-#endif
-#ifndef S_ISREG
-#define S_ISREG(x) (((x) &_S_IFMT) == _S_IFREG)
-#endif
-#define DIRSEP '\\'
-#define CS_DEFINE_DIRENT
-
-#ifndef va_copy
-#ifdef __va_copy
-#define va_copy __va_copy
-#else
-#define va_copy(x, y) (x) = (y)
-#endif
-#endif
-
-#ifndef MG_MAX_HTTP_REQUEST_SIZE
-#define MG_MAX_HTTP_REQUEST_SIZE 8192
-#endif
-
-#ifndef MG_MAX_HTTP_SEND_MBUF
-#define MG_MAX_HTTP_SEND_MBUF 4096
-#endif
-
-#ifndef MG_MAX_HTTP_HEADERS
-#define MG_MAX_HTTP_HEADERS 40
-#endif
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#ifndef MG_ENABLE_BROADCAST
-#define MG_ENABLE_BROADCAST 1
-#endif
-
-#ifndef MG_ENABLE_DIRECTORY_LISTING
-#define MG_ENABLE_DIRECTORY_LISTING 1
-#endif
-
-#ifndef MG_ENABLE_FILESYSTEM
-#define MG_ENABLE_FILESYSTEM 1
-#endif
-
-#ifndef MG_ENABLE_HTTP_CGI
-#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM
-#endif
-
-#ifndef MG_NET_IF
-#define MG_NET_IF MG_NET_IF_SOCKET
-#endif
-
-unsigned int sleep(unsigned int seconds);
-
-/* https://stackoverflow.com/questions/16647819/timegm-cross-platform */
-#define timegm _mkgmtime
-
-#define gmtime_r(a, b) \
-  do {                 \
-    *(b) = *gmtime(a); \
-  } while (0)
-
-#endif /* CS_PLATFORM == CS_P_WINDOWS */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINDOWS_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_unix.h"
-#endif
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_
-#if CS_PLATFORM == CS_P_UNIX
-
-#ifndef _XOPEN_SOURCE
-#define _XOPEN_SOURCE 600
-#endif
-
-/* <inttypes.h> wants this for C++ */
-#ifndef __STDC_FORMAT_MACROS
-#define __STDC_FORMAT_MACROS
-#endif
-
-/* C++ wants that for INT64_MAX */
-#ifndef __STDC_LIMIT_MACROS
-#define __STDC_LIMIT_MACROS
-#endif
-
-/* Enable fseeko() and ftello() functions */
-#ifndef _LARGEFILE_SOURCE
-#define _LARGEFILE_SOURCE
-#endif
-
-/* Enable 64-bit file offsets */
-#ifndef _FILE_OFFSET_BITS
-#define _FILE_OFFSET_BITS 64
-#endif
-
-#include <arpa/inet.h>
-#include <assert.h>
-#include <ctype.h>
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <stdint.h>
-#include <limits.h>
-#include <math.h>
-#include <netdb.h>
-#include <netinet/in.h>
-#include <pthread.h>
-#include <signal.h>
-#include <stdarg.h>
-#include <stdbool.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/param.h>
-#include <sys/socket.h>
-#include <sys/select.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#ifdef __APPLE__
-#include <machine/endian.h>
-#ifndef BYTE_ORDER
-#define LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN
-#define BIG_ENDIAN __DARWIN_BIG_ENDIAN
-#define PDP_ENDIAN __DARWIN_PDP_ENDIAN
-#define BYTE_ORDER __DARWIN_BYTE_ORDER
-#endif
-#endif
-
-/*
- * osx correctly avoids defining strtoll when compiling in strict ansi mode.
- * c++ 11 standard defines strtoll as well.
- * We require strtoll, and if your embedded pre-c99 compiler lacks one, please
- * implement a shim.
- */
-#if !(defined(__cplusplus) && __cplusplus >= 201103L) && \
-    !(defined(__DARWIN_C_LEVEL) && __DARWIN_C_LEVEL >= 200809L)
-long long strtoll(const char *, char **, int);
-#endif
-
-typedef int sock_t;
-#define INVALID_SOCKET (-1)
-#define SIZE_T_FMT "zu"
-typedef struct stat cs_stat_t;
-#define DIRSEP '/'
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT PRId64
-#define INT64_X_FMT PRIx64
-
-#ifndef __cdecl
-#define __cdecl
-#endif
-
-#ifndef va_copy
-#ifdef __va_copy
-#define va_copy __va_copy
-#else
-#define va_copy(x, y) (x) = (y)
-#endif
-#endif
-
-#define closesocket(x) close(x)
-
-#ifndef MG_MAX_HTTP_REQUEST_SIZE
-#define MG_MAX_HTTP_REQUEST_SIZE 8192
-#endif
-
-#ifndef MG_MAX_HTTP_SEND_MBUF
-#define MG_MAX_HTTP_SEND_MBUF 4096
-#endif
-
-#ifndef MG_MAX_HTTP_HEADERS
-#define MG_MAX_HTTP_HEADERS 40
-#endif
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#ifndef MG_ENABLE_BROADCAST
-#define MG_ENABLE_BROADCAST 1
-#endif
-
-#ifndef MG_ENABLE_DIRECTORY_LISTING
-#define MG_ENABLE_DIRECTORY_LISTING 1
-#endif
-
-#ifndef MG_ENABLE_FILESYSTEM
-#define MG_ENABLE_FILESYSTEM 1
-#endif
-
-#ifndef MG_ENABLE_HTTP_CGI
-#define MG_ENABLE_HTTP_CGI MG_ENABLE_FILESYSTEM
-#endif
-
-#ifndef MG_NET_IF
-#define MG_NET_IF MG_NET_IF_SOCKET
-#endif
-
-#ifndef MG_HOSTS_FILE_NAME
-#define MG_HOSTS_FILE_NAME "/etc/hosts"
-#endif
-
-#ifndef MG_RESOLV_CONF_FILE_NAME
-#define MG_RESOLV_CONF_FILE_NAME "/etc/resolv.conf"
-#endif
-
-#endif /* CS_PLATFORM == CS_P_UNIX */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_UNIX_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_esp32.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_
-#if CS_PLATFORM == CS_P_ESP32
-
-#include <assert.h>
-#include <ctype.h>
-#include <dirent.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <machine/endian.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-
-#define SIZE_T_FMT "u"
-typedef struct stat cs_stat_t;
-#define DIRSEP '/'
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT PRId64
-#define INT64_X_FMT PRIx64
-#define __cdecl
-#define _FILE_OFFSET_BITS 32
-
-#define MG_LWIP 1
-
-#ifndef MG_NET_IF
-#define MG_NET_IF MG_NET_IF_SOCKET
-#endif
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#endif /* CS_PLATFORM == CS_P_ESP32 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP32_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_esp8266.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_
-#if CS_PLATFORM == CS_P_ESP8266
-
-#include <assert.h>
-#include <ctype.h>
-#include <fcntl.h>
-#include <inttypes.h>
-#include <machine/endian.h>
-#include <stdbool.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-
-#define SIZE_T_FMT "u"
-typedef struct stat cs_stat_t;
-#define DIRSEP '/'
-#if !defined(MGOS_VFS_DEFINE_DIRENT)
-#define CS_DEFINE_DIRENT
-#endif
-
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT PRId64
-#define INT64_X_FMT PRIx64
-#define __cdecl
-#define _FILE_OFFSET_BITS 32
-
-#define MG_LWIP 1
-
-/* struct timeval is defined in sys/time.h. */
-#define LWIP_TIMEVAL_PRIVATE 0
-
-#ifndef MG_NET_IF
-#include <lwip/opt.h>
-#if LWIP_SOCKET /* RTOS SDK has LWIP sockets */
-#define MG_NET_IF MG_NET_IF_SOCKET
-#else
-#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
-#endif
-#endif
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#define inet_ntop(af, src, dst, size)                                          \
-  (((af) == AF_INET) ? ipaddr_ntoa_r((const ip_addr_t *) (src), (dst), (size)) \
-                     : NULL)
-#define inet_pton(af, src, dst) \
-  (((af) == AF_INET) ? ipaddr_aton((src), (ip_addr_t *) (dst)) : 0)
-
-#endif /* CS_PLATFORM == CS_P_ESP8266 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_ESP8266_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_cc3100.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_
-#if CS_PLATFORM == CS_P_CC3100
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <inttypes.h>
-#include <stdint.h>
-#include <string.h>
-#include <time.h>
-
-#define MG_NET_IF MG_NET_IF_SIMPLELINK
-#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
-
-/*
- * CC3100 SDK and STM32 SDK include headers w/out path, just like
- * #include "simplelink.h". As result, we have to add all required directories
- * into Makefile IPATH and do the same thing (include w/out path)
- */
-
-#include <simplelink.h>
-#include <netapp.h>
-#undef timeval
-
-typedef int sock_t;
-#define INVALID_SOCKET (-1)
-
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT PRId64
-#define INT64_X_FMT PRIx64
-#define SIZE_T_FMT "u"
-
-#define SOMAXCONN 8
-
-const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
-char *inet_ntoa(struct in_addr in);
-int inet_pton(int af, const char *src, void *dst);
-
-#endif /* CS_PLATFORM == CS_P_CC3100 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3100_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_cc3200.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_
-#if CS_PLATFORM == CS_P_CC3200
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <string.h>
-#include <time.h>
-
-#ifndef __TI_COMPILER_VERSION__
-#include <fcntl.h>
-#include <sys/time.h>
-#endif
-
-#define MG_NET_IF MG_NET_IF_SIMPLELINK
-#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
-
-/* Only SPIFFS supports directories, SLFS does not. */
-#if defined(CC3200_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING)
-#define MG_ENABLE_DIRECTORY_LISTING 1
-#endif
-
-/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */
-
-typedef int sock_t;
-#define INVALID_SOCKET (-1)
-#define SIZE_T_FMT "u"
-typedef struct stat cs_stat_t;
-#define DIRSEP '/'
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT PRId64
-#define INT64_X_FMT PRIx64
-#define __cdecl
-
-#define fileno(x) -1
-
-/* Some functions we implement for Mongoose. */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef __TI_COMPILER_VERSION__
-struct SlTimeval_t;
-#define timeval SlTimeval_t
-int gettimeofday(struct timeval *t, void *tz);
-int settimeofday(const struct timeval *tv, const void *tz);
-
-int asprintf(char **strp, const char *fmt, ...);
-
-#endif
-
-/* TI's libc does not have stat & friends, add them. */
-#ifdef __TI_COMPILER_VERSION__
-
-#include <file.h>
-
-typedef unsigned int mode_t;
-typedef size_t _off_t;
-typedef long ssize_t;
-
-struct stat {
-  int st_ino;
-  mode_t st_mode;
-  int st_nlink;
-  time_t st_mtime;
-  off_t st_size;
-};
-
-int _stat(const char *pathname, struct stat *st);
-int stat(const char *pathname, struct stat *st);
-
-#define __S_IFMT 0170000
-
-#define __S_IFDIR 0040000
-#define __S_IFCHR 0020000
-#define __S_IFREG 0100000
-
-#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask))
-
-#define S_IFDIR __S_IFDIR
-#define S_IFCHR __S_IFCHR
-#define S_IFREG __S_IFREG
-#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR)
-#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
-
-/* 5.x series compilers don't have va_copy, 16.x do. */
-#if __TI_COMPILER_VERSION__ < 16000000
-#define va_copy(apc, ap) ((apc) = (ap))
-#endif
-
-#endif /* __TI_COMPILER_VERSION__ */
-
-#ifdef CC3200_FS_SLFS
-#define MG_FS_SLFS
-#endif
-
-#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \
-    !defined(MG_ENABLE_FILESYSTEM)
-#define MG_ENABLE_FILESYSTEM 1
-#define CS_DEFINE_DIRENT
-#endif
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CS_PLATFORM == CS_P_CC3200 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_cc3220.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_CC3220_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_CC3220_H_
-#if CS_PLATFORM == CS_P_CC3220
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <string.h>
-#include <time.h>
-
-#ifndef __TI_COMPILER_VERSION__
-#include <fcntl.h>
-#include <sys/time.h>
-#endif
-
-#define MG_NET_IF MG_NET_IF_SIMPLELINK
-#ifndef MG_SSL_IF
-#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
-#endif
-
-/* Only SPIFFS supports directories, SLFS does not. */
-#if defined(CC3220_FS_SPIFFS) && !defined(MG_ENABLE_DIRECTORY_LISTING)
-#define MG_ENABLE_DIRECTORY_LISTING 1
-#endif
-
-/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */
-
-typedef int sock_t;
-#define INVALID_SOCKET (-1)
-#define SIZE_T_FMT "u"
-typedef struct stat cs_stat_t;
-#define DIRSEP '/'
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT PRId64
-#define INT64_X_FMT PRIx64
-#define __cdecl
-
-#define fileno(x) -1
-
-/* Some functions we implement for Mongoose. */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef __TI_COMPILER_VERSION__
-struct SlTimeval_t;
-#define timeval SlTimeval_t
-int gettimeofday(struct timeval *t, void *tz);
-int settimeofday(const struct timeval *tv, const void *tz);
-
-int asprintf(char **strp, const char *fmt, ...);
-
-#endif
-
-/* TI's libc does not have stat & friends, add them. */
-#ifdef __TI_COMPILER_VERSION__
-
-#include <file.h>
-
-typedef unsigned int mode_t;
-typedef size_t _off_t;
-typedef long ssize_t;
-
-struct stat {
-  int st_ino;
-  mode_t st_mode;
-  int st_nlink;
-  time_t st_mtime;
-  off_t st_size;
-};
-
-int _stat(const char *pathname, struct stat *st);
-int stat(const char *pathname, struct stat *st);
-
-#define __S_IFMT 0170000
-
-#define __S_IFDIR 0040000
-#define __S_IFCHR 0020000
-#define __S_IFREG 0100000
-
-#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask))
-
-#define S_IFDIR __S_IFDIR
-#define S_IFCHR __S_IFCHR
-#define S_IFREG __S_IFREG
-#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR)
-#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
-
-#endif /* __TI_COMPILER_VERSION__ */
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CS_PLATFORM == CS_P_CC3220 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_CC3200_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_msp432.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_
-#if CS_PLATFORM == CS_P_MSP432
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <inttypes.h>
-#include <stdint.h>
-#include <string.h>
-#include <time.h>
-
-#ifndef __TI_COMPILER_VERSION__
-#include <fcntl.h>
-#include <sys/time.h>
-#endif
-
-#define MG_NET_IF MG_NET_IF_SIMPLELINK
-#define MG_SSL_IF MG_SSL_IF_SIMPLELINK
-
-/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */
-
-typedef int sock_t;
-#define INVALID_SOCKET (-1)
-#define SIZE_T_FMT "u"
-typedef struct stat cs_stat_t;
-#define DIRSEP '/'
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT PRId64
-#define INT64_X_FMT PRIx64
-#define __cdecl
-
-#define fileno(x) -1
-
-/* Some functions we implement for Mongoose. */
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef __TI_COMPILER_VERSION__
-struct SlTimeval_t;
-#define timeval SlTimeval_t
-int gettimeofday(struct timeval *t, void *tz);
-#endif
-
-/* TI's libc does not have stat & friends, add them. */
-#ifdef __TI_COMPILER_VERSION__
-
-#include <file.h>
-
-typedef unsigned int mode_t;
-typedef size_t _off_t;
-typedef long ssize_t;
-
-struct stat {
-  int st_ino;
-  mode_t st_mode;
-  int st_nlink;
-  time_t st_mtime;
-  off_t st_size;
-};
-
-int _stat(const char *pathname, struct stat *st);
-#define stat(a, b) _stat(a, b)
-
-#define __S_IFMT 0170000
-
-#define __S_IFDIR 0040000
-#define __S_IFCHR 0020000
-#define __S_IFREG 0100000
-
-#define __S_ISTYPE(mode, mask) (((mode) &__S_IFMT) == (mask))
-
-#define S_IFDIR __S_IFDIR
-#define S_IFCHR __S_IFCHR
-#define S_IFREG __S_IFREG
-#define S_ISDIR(mode) __S_ISTYPE((mode), __S_IFDIR)
-#define S_ISREG(mode) __S_ISTYPE((mode), __S_IFREG)
-
-/* As of 5.2.7, TI compiler does not support va_copy() yet. */
-#define va_copy(apc, ap) ((apc) = (ap))
-
-#endif /* __TI_COMPILER_VERSION__ */
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#if (defined(CC3200_FS_SPIFFS) || defined(CC3200_FS_SLFS)) && \
-    !defined(MG_ENABLE_FILESYSTEM)
-#define MG_ENABLE_FILESYSTEM 1
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CS_PLATFORM == CS_P_MSP432 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_MSP432_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_tm4c129.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_
-#if CS_PLATFORM == CS_P_TM4C129
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <inttypes.h>
-#include <stdint.h>
-#include <string.h>
-#include <time.h>
-
-#ifndef __TI_COMPILER_VERSION__
-#include <fcntl.h>
-#include <sys/time.h>
-#endif
-
-#define SIZE_T_FMT "u"
-typedef struct stat cs_stat_t;
-#define DIRSEP '/'
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT PRId64
-#define INT64_X_FMT PRIx64
-#define __cdecl
-
-#ifndef MG_NET_IF
-#include <lwip/opt.h>
-#if LWIP_SOCKET
-#define MG_NET_IF MG_NET_IF_SOCKET
-#else
-#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
-#endif
-#define MG_LWIP 1
-#elif MG_NET_IF == MG_NET_IF_SIMPLELINK
-/* Amalgamated: #include "common/platforms/simplelink/cs_simplelink.h" */
-#endif
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#ifdef __TI_COMPILER_VERSION__
-/* As of 5.2.8, TI compiler does not support va_copy() yet. */
-#define va_copy(apc, ap) ((apc) = (ap))
-#endif /* __TI_COMPILER_VERSION__ */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CS_PLATFORM == CS_P_TM4C129 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_TM4C129_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_mbed.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_MBED_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_MBED_H_
-#if CS_PLATFORM == CS_P_MBED
-
-/*
- * mbed.h contains C++ code (e.g. templates), thus, it should be processed
- * only if included directly to startup file (ex: main.cpp)
- */
-#ifdef __cplusplus
-/* Amalgamated: #include "mbed.h" */
-#endif /* __cplusplus */
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <inttypes.h>
-#include <stdint.h>
-#include <string.h>
-#include <time.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <fcntl.h>
-#include <stdio.h>
-
-typedef struct stat cs_stat_t;
-#define DIRSEP '/'
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-/*
- * mbed can be compiled with the ARM compiler which
- * just doesn't come with a gettimeofday shim
- * because it's a BSD API and ARM targets embedded
- * non-unix platforms.
- */
-#if defined(__ARMCC_VERSION) || defined(__ICCARM__)
-#define _TIMEVAL_DEFINED
-#define gettimeofday _gettimeofday
-
-/* copied from GCC on ARM; for some reason useconds are signed */
-typedef long suseconds_t; /* microseconds (signed) */
-struct timeval {
-  time_t tv_sec;       /* seconds */
-  suseconds_t tv_usec; /* and microseconds */
-};
-
-#endif
-
-#if MG_NET_IF == MG_NET_IF_SIMPLELINK
-
-#define MG_SIMPLELINK_NO_OSI 1
-
-#include <simplelink.h>
-
-typedef int sock_t;
-#define INVALID_SOCKET (-1)
-
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT PRId64
-#define INT64_X_FMT PRIx64
-#define SIZE_T_FMT "u"
-
-#define SOMAXCONN 8
-
-const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
-char *inet_ntoa(struct in_addr in);
-int inet_pton(int af, const char *src, void *dst);
-int inet_aton(const char *cp, struct in_addr *inp);
-in_addr_t inet_addr(const char *cp);
-
-#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
-
-#endif /* CS_PLATFORM == CS_P_MBED */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_MBED_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_nrf51.h"
-#endif
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_
-#if CS_PLATFORM == CS_P_NRF51
-
-#include <assert.h>
-#include <ctype.h>
-#include <inttypes.h>
-#include <stdint.h>
-#include <string.h>
-#include <time.h>
-
-#define to64(x) strtoll(x, NULL, 10)
-
-#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
-#define MG_LWIP 1
-#define MG_ENABLE_IPV6 1
-
-/*
- * For ARM C Compiler, make lwip to export `struct timeval`; for other
- * compilers, suppress it.
- */
-#if !defined(__ARMCC_VERSION)
-#define LWIP_TIMEVAL_PRIVATE 0
-#else
-struct timeval;
-int gettimeofday(struct timeval *tp, void *tzp);
-#endif
-
-#define INT64_FMT PRId64
-#define SIZE_T_FMT "u"
-
-/*
- * ARM C Compiler doesn't have strdup, so we provide it
- */
-#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION)
-
-#endif /* CS_PLATFORM == CS_P_NRF51 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF51_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_nrf52.h"
-#endif
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_
-#if CS_PLATFORM == CS_P_NRF52
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <inttypes.h>
-#include <stdbool.h>
-#include <stdint.h>
-#include <string.h>
-#include <time.h>
-
-#define to64(x) strtoll(x, NULL, 10)
-
-#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
-#define MG_LWIP 1
-#define MG_ENABLE_IPV6 1
-
-#if !defined(ENOSPC)
-#define ENOSPC 28 /* No space left on device */
-#endif
-
-/*
- * For ARM C Compiler, make lwip to export `struct timeval`; for other
- * compilers, suppress it.
- */
-#if !defined(__ARMCC_VERSION)
-#define LWIP_TIMEVAL_PRIVATE 0
-#endif
-
-#define INT64_FMT PRId64
-#define SIZE_T_FMT "u"
-
-/*
- * ARM C Compiler doesn't have strdup, so we provide it
- */
-#define CS_ENABLE_STRDUP defined(__ARMCC_VERSION)
-
-#endif /* CS_PLATFORM == CS_P_NRF52 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_NRF52_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/simplelink/cs_simplelink.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_
-#define CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_
-
-#if defined(MG_NET_IF) && MG_NET_IF == MG_NET_IF_SIMPLELINK
-
-/* If simplelink.h is already included, all bets are off. */
-#if !defined(__SIMPLELINK_H__)
-
-#include <stdbool.h>
-
-#ifndef __TI_COMPILER_VERSION__
-#undef __CONCAT
-#undef FD_CLR
-#undef FD_ISSET
-#undef FD_SET
-#undef FD_SETSIZE
-#undef FD_ZERO
-#undef fd_set
-#endif
-
-#if CS_PLATFORM == CS_P_CC3220
-#include <ti/drivers/net/wifi/porting/user.h>
-#include <ti/drivers/net/wifi/simplelink.h>
-#include <ti/drivers/net/wifi/sl_socket.h>
-#include <ti/drivers/net/wifi/netapp.h>
-#else
-/* We want to disable SL_INC_STD_BSD_API_NAMING, so we include user.h ourselves
- * and undef it. */
-#define PROVISIONING_API_H_
-#include <simplelink/user.h>
-#undef PROVISIONING_API_H_
-#undef SL_INC_STD_BSD_API_NAMING
-
-#include <simplelink/include/simplelink.h>
-#include <simplelink/include/netapp.h>
-#endif /* CS_PLATFORM == CS_P_CC3220 */
-
-/* Now define only the subset of the BSD API that we use.
- * Notably, close(), read() and write() are not defined. */
-#define AF_INET SL_AF_INET
-
-#define socklen_t SlSocklen_t
-#define sockaddr SlSockAddr_t
-#define sockaddr_in SlSockAddrIn_t
-#define in_addr SlInAddr_t
-
-#define SOCK_STREAM SL_SOCK_STREAM
-#define SOCK_DGRAM SL_SOCK_DGRAM
-
-#define htonl sl_Htonl
-#define ntohl sl_Ntohl
-#define htons sl_Htons
-#define ntohs sl_Ntohs
-
-#ifndef EACCES
-#define EACCES SL_EACCES
-#endif
-#ifndef EAFNOSUPPORT
-#define EAFNOSUPPORT SL_EAFNOSUPPORT
-#endif
-#ifndef EAGAIN
-#define EAGAIN SL_EAGAIN
-#endif
-#ifndef EBADF
-#define EBADF SL_EBADF
-#endif
-#ifndef EINVAL
-#define EINVAL SL_EINVAL
-#endif
-#ifndef ENOMEM
-#define ENOMEM SL_ENOMEM
-#endif
-#ifndef EWOULDBLOCK
-#define EWOULDBLOCK SL_EWOULDBLOCK
-#endif
-
-#define SOMAXCONN 8
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
-char *inet_ntoa(struct in_addr in);
-int inet_pton(int af, const char *src, void *dst);
-
-struct mg_mgr;
-struct mg_connection;
-
-typedef void (*mg_init_cb)(struct mg_mgr *mgr);
-bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init);
-
-void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg);
-
-int sl_fs_init(void);
-
-void sl_restart_cb(struct mg_mgr *mgr);
-
-int sl_set_ssl_opts(int sock, struct mg_connection *nc);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* !defined(__SIMPLELINK_H__) */
-
-/* Compatibility with older versions of SimpleLink */
-#if SL_MAJOR_VERSION_NUM < 2
-
-#define SL_ERROR_BSD_EAGAIN SL_EAGAIN
-#define SL_ERROR_BSD_EALREADY SL_EALREADY
-#define SL_ERROR_BSD_ENOPROTOOPT SL_ENOPROTOOPT
-#define SL_ERROR_BSD_ESECDATEERROR SL_ESECDATEERROR
-#define SL_ERROR_BSD_ESECSNOVERIFY SL_ESECSNOVERIFY
-#define SL_ERROR_FS_FAILED_TO_ALLOCATE_MEM SL_FS_ERR_FAILED_TO_ALLOCATE_MEM
-#define SL_ERROR_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY \
-  SL_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY
-#define SL_ERROR_FS_FILE_NAME_EXIST SL_FS_FILE_NAME_EXIST
-#define SL_ERROR_FS_FILE_NOT_EXISTS SL_FS_ERR_FILE_NOT_EXISTS
-#define SL_ERROR_FS_NO_AVAILABLE_NV_INDEX SL_FS_ERR_NO_AVAILABLE_NV_INDEX
-#define SL_ERROR_FS_NOT_ENOUGH_STORAGE_SPACE SL_FS_ERR_NO_AVAILABLE_BLOCKS
-#define SL_ERROR_FS_NOT_SUPPORTED SL_FS_ERR_NOT_SUPPORTED
-#define SL_ERROR_FS_WRONG_FILE_NAME SL_FS_WRONG_FILE_NAME
-#define SL_ERROR_FS_INVALID_HANDLE SL_FS_ERR_INVALID_HANDLE
-#define SL_NETCFG_MAC_ADDRESS_GET SL_MAC_ADDRESS_GET
-#define SL_SOCKET_FD_ZERO SL_FD_ZERO
-#define SL_SOCKET_FD_SET SL_FD_SET
-#define SL_SOCKET_FD_ISSET SL_FD_ISSET
-#define SL_SO_SECURE_DOMAIN_NAME_VERIFICATION SO_SECURE_DOMAIN_NAME_VERIFICATION
-
-#define SL_FS_READ FS_MODE_OPEN_READ
-#define SL_FS_WRITE FS_MODE_OPEN_WRITE
-
-#define SL_FI_FILE_SIZE(fi) ((fi).FileLen)
-#define SL_FI_FILE_MAX_SIZE(fi) ((fi).AllocatedLen)
-
-#define SlDeviceVersion_t SlVersionFull
-#define sl_DeviceGet sl_DevGet
-#define SL_DEVICE_GENERAL SL_DEVICE_GENERAL_CONFIGURATION
-#define SL_LEN_TYPE _u8
-#define SL_OPT_TYPE _u8
-
-#else /* SL_MAJOR_VERSION_NUM >= 2 */
-
-#define FS_MODE_OPEN_CREATE(max_size, flag) \
-  (SL_FS_CREATE | SL_FS_CREATE_MAX_SIZE(max_size))
-#define SL_FI_FILE_SIZE(fi) ((fi).Len)
-#define SL_FI_FILE_MAX_SIZE(fi) ((fi).MaxSize)
-
-#define SL_LEN_TYPE _u16
-#define SL_OPT_TYPE _u16
-
-#endif /* SL_MAJOR_VERSION_NUM < 2 */
-
-int slfs_open(const unsigned char *fname, uint32_t flags, uint32_t *token);
-
-#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
-
-#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_CS_SIMPLELINK_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_wince.h"
-#endif
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_
-
-#if CS_PLATFORM == CS_P_WINCE
-
-/*
- * MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015)
- * MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013)
- * MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012)
- * MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010)
- * MSVC++ 9.0  _MSC_VER == 1500 (Visual Studio 2008)
- * MSVC++ 8.0  _MSC_VER == 1400 (Visual Studio 2005)
- * MSVC++ 7.1  _MSC_VER == 1310 (Visual Studio 2003)
- * MSVC++ 7.0  _MSC_VER == 1300
- * MSVC++ 6.0  _MSC_VER == 1200
- * MSVC++ 5.0  _MSC_VER == 1100
- */
-#pragma warning(disable : 4127) /* FD_SET() emits warning, disable it */
-#pragma warning(disable : 4204) /* missing c99 support */
-
-#ifndef _WINSOCK_DEPRECATED_NO_WARNINGS
-#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
-#endif
-
-#ifndef _CRT_SECURE_NO_WARNINGS
-#define _CRT_SECURE_NO_WARNINGS
-#endif
-
-#include <assert.h>
-#include <limits.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <time.h>
-
-#pragma comment(lib, "ws2.lib") /* Linking with WinCE winsock library */
-
-#include <winsock2.h>
-#include <ws2tcpip.h>
-#include <windows.h>
-
-#define strdup _strdup
-
-#ifndef EINPROGRESS
-#define EINPROGRESS WSAEINPROGRESS
-#endif
-
-#ifndef EWOULDBLOCK
-#define EWOULDBLOCK WSAEWOULDBLOCK
-#endif
-
-#ifndef EAGAIN
-#define EAGAIN EWOULDBLOCK
-#endif
-
-#ifndef __func__
-#define STRX(x) #x
-#define STR(x) STRX(x)
-#define __func__ __FILE__ ":" STR(__LINE__)
-#endif
-
-#define snprintf _snprintf
-#define fileno _fileno
-#define vsnprintf _vsnprintf
-#define sleep(x) Sleep((x) *1000)
-#define to64(x) _atoi64(x)
-#define rmdir _rmdir
-
-#if defined(_MSC_VER) && _MSC_VER >= 1400
-#define fseeko(x, y, z) _fseeki64((x), (y), (z))
-#else
-#define fseeko(x, y, z) fseek((x), (y), (z))
-#endif
-
-typedef int socklen_t;
-
-#if _MSC_VER >= 1700
-#include <stdint.h>
-#else
-typedef signed char int8_t;
-typedef unsigned char uint8_t;
-typedef int int32_t;
-typedef unsigned int uint32_t;
-typedef short int16_t;
-typedef unsigned short uint16_t;
-typedef __int64 int64_t;
-typedef unsigned __int64 uint64_t;
-#endif
-
-typedef SOCKET sock_t;
-typedef uint32_t in_addr_t;
-
-#ifndef UINT16_MAX
-#define UINT16_MAX 65535
-#endif
-
-#ifndef UINT32_MAX
-#define UINT32_MAX 4294967295
-#endif
-
-#ifndef pid_t
-#define pid_t HANDLE
-#endif
-
-#define INT64_FMT "I64d"
-#define INT64_X_FMT "I64x"
-/* TODO(alashkin): check if this is correct */
-#define SIZE_T_FMT "u"
-
-#define DIRSEP '\\'
-#define CS_DEFINE_DIRENT
-
-#ifndef va_copy
-#ifdef __va_copy
-#define va_copy __va_copy
-#else
-#define va_copy(x, y) (x) = (y)
-#endif
-#endif
-
-#ifndef MG_MAX_HTTP_REQUEST_SIZE
-#define MG_MAX_HTTP_REQUEST_SIZE 8192
-#endif
-
-#ifndef MG_MAX_HTTP_SEND_MBUF
-#define MG_MAX_HTTP_SEND_MBUF 4096
-#endif
-
-#ifndef MG_MAX_HTTP_HEADERS
-#define MG_MAX_HTTP_HEADERS 40
-#endif
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#define abort() DebugBreak();
-
-#ifndef BUFSIZ
-#define BUFSIZ 4096
-#endif
-/*
- * Explicitly disabling MG_ENABLE_THREADS for WinCE
- * because they are enabled for _WIN32 by default
- */
-#ifndef MG_ENABLE_THREADS
-#define MG_ENABLE_THREADS 0
-#endif
-
-#ifndef MG_ENABLE_FILESYSTEM
-#define MG_ENABLE_FILESYSTEM 1
-#endif
-
-#ifndef MG_NET_IF
-#define MG_NET_IF MG_NET_IF_SOCKET
-#endif
-
-typedef struct _stati64 {
-  uint32_t st_mtime;
-  uint32_t st_size;
-  uint32_t st_mode;
-} cs_stat_t;
-
-/*
- * WinCE 6.0 has a lot of useful definitions in ATL (not windows.h) headers
- * use #ifdefs to avoid conflicts
- */
-
-#ifndef ENOENT
-#define ENOENT ERROR_PATH_NOT_FOUND
-#endif
-
-#ifndef EACCES
-#define EACCES ERROR_ACCESS_DENIED
-#endif
-
-#ifndef ENOMEM
-#define ENOMEM ERROR_NOT_ENOUGH_MEMORY
-#endif
-
-#ifndef _UINTPTR_T_DEFINED
-typedef unsigned int *uintptr_t;
-#endif
-
-#define _S_IFREG 2
-#define _S_IFDIR 4
-
-#ifndef S_ISDIR
-#define S_ISDIR(x) (((x) &_S_IFDIR) != 0)
-#endif
-
-#ifndef S_ISREG
-#define S_ISREG(x) (((x) &_S_IFREG) != 0)
-#endif
-
-int open(const char *filename, int oflag, int pmode);
-int _wstati64(const wchar_t *path, cs_stat_t *st);
-const char *strerror();
-
-#endif /* CS_PLATFORM == CS_P_WINCE */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_WINCE_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_nxp_lpc.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_
-
-#if CS_PLATFORM == CS_P_NXP_LPC
-
-#include <ctype.h>
-#include <stdint.h>
-#include <string.h>
-
-#define SIZE_T_FMT "u"
-typedef struct stat cs_stat_t;
-#define INT64_FMT "lld"
-#define INT64_X_FMT "llx"
-#define __cdecl
-
-#define MG_LWIP 1
-
-#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
-
-/*
- * LPCXpress comes with 3 C library implementations: Newlib, NewlibNano and
- *Redlib.
- * See https://community.nxp.com/message/630860 for more details.
- *
- * Redlib is the default and lacks certain things, so we provide them.
- */
-#ifdef __REDLIB_INTERFACE_VERSION__
-
-/* Let LWIP define timeval for us. */
-#define LWIP_TIMEVAL_PRIVATE 1
-
-#define va_copy(d, s) __builtin_va_copy(d, s)
-
-#define CS_ENABLE_TO64 1
-#define to64(x) cs_to64(x)
-
-#define CS_ENABLE_STRDUP 1
-
-#else
-
-#include <sys/time.h>
-#define LWIP_TIMEVAL_PRIVATE 0
-#define to64(x) strtoll(x, NULL, 10)
-
-#endif
-
-#endif /* CS_PLATFORM == CS_P_NXP_LPC */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_LPC_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_nxp_kinetis.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_
-
-#if CS_PLATFORM == CS_P_NXP_KINETIS
-
-#include <ctype.h>
-#include <inttypes.h>
-#include <string.h>
-#include <sys/time.h>
-
-#define SIZE_T_FMT "u"
-typedef struct stat cs_stat_t;
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT "lld"
-#define INT64_X_FMT "llx"
-#define __cdecl
-
-#define MG_LWIP 1
-
-#define MG_NET_IF MG_NET_IF_LWIP_LOW_LEVEL
-
-/* struct timeval is defined in sys/time.h. */
-#define LWIP_TIMEVAL_PRIVATE 0
-
-#endif /* CS_PLATFORM == CS_P_NXP_KINETIS */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_NXP_KINETIS_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_pic32.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_
-
-#if CS_PLATFORM == CS_P_PIC32
-
-#define MG_NET_IF MG_NET_IF_PIC32
-
-#include <stdint.h>
-#include <time.h>
-#include <ctype.h>
-#include <stdlib.h>
-
-#include <system_config.h>
-#include <system_definitions.h>
-
-#include <sys/types.h>
-
-typedef TCP_SOCKET sock_t;
-#define to64(x) strtoll(x, NULL, 10)
-
-#define SIZE_T_FMT "lu"
-#define INT64_FMT "lld"
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-char *inet_ntoa(struct in_addr in);
-
-#endif /* CS_PLATFORM == CS_P_PIC32 */
-
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_PIC32_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_rs14100.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_RS14100_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_RS14100_H_
-#if CS_PLATFORM == CS_P_RS14100
-
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#ifdef MGOS_HAVE_VFS_COMMON
-#include <mgos_vfs.h>
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT "lld"
-#define SIZE_T_FMT "u"
-typedef struct stat cs_stat_t;
-#define DIRSEP '/'
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#ifndef MG_ENABLE_FILESYSTEM
-#define MG_ENABLE_FILESYSTEM 1
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CS_PLATFORM == CS_P_RS14100 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_RS14100_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/platform_stm32.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_PLATFORM_STM32_H_
-#define CS_COMMON_PLATFORMS_PLATFORM_STM32_H_
-#if CS_PLATFORM == CS_P_STM32
-
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdint.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <dirent.h>
-
-#include <stm32_sdk_hal.h>
-
-#define to64(x) strtoll(x, NULL, 10)
-#define INT64_FMT "lld"
-#define SIZE_T_FMT "u"
-typedef struct stat cs_stat_t;
-#define DIRSEP '/'
-
-#ifndef CS_ENABLE_STDIO
-#define CS_ENABLE_STDIO 1
-#endif
-
-#ifndef MG_ENABLE_FILESYSTEM
-#define MG_ENABLE_FILESYSTEM 1
-#endif
-
-#endif /* CS_PLATFORM == CS_P_STM32 */
-#endif /* CS_COMMON_PLATFORMS_PLATFORM_STM32_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/platforms/lwip/mg_lwip.h"
-#endif
-
-#ifndef CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_
-#define CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_
-
-#ifndef MG_LWIP
-#define MG_LWIP 0
-#endif
-
-#if MG_LWIP
-
-/*
- * When compiling for nRF5x chips with arm-none-eabi-gcc, it has BYTE_ORDER
- * already defined, so in order to avoid warnings in lwip, we have to undefine
- * it.
- *
- * TODO: Check if in the future versions of nRF5 SDK that changes.
- *       Current version of nRF51 SDK: 0.8.0
- *                          nRF5 SDK:  0.9.0
- */
-#if CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52
-#undef BYTE_ORDER
-#endif
-
-#include <lwip/opt.h>
-#include <lwip/err.h>
-#include <lwip/ip_addr.h>
-#include <lwip/inet.h>
-#include <lwip/netdb.h>
-#include <lwip/dns.h>
-
-#ifndef LWIP_PROVIDE_ERRNO
-#include <errno.h>
-#endif
-
-#if LWIP_SOCKET
-#include <lwip/sockets.h>
-#else
-/* We really need the definitions from sockets.h. */
-#undef LWIP_SOCKET
-#define LWIP_SOCKET 1
-#include <lwip/sockets.h>
-#undef LWIP_SOCKET
-#define LWIP_SOCKET 0
-#endif
-
-#define INVALID_SOCKET (-1)
-#define SOMAXCONN 10
-typedef int sock_t;
-
-#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
-struct mg_mgr;
-struct mg_connection;
-void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
-                                  int interval, int count);
-#endif
-
-/* For older version of LWIP */
-#ifndef ipX_2_ip
-#define ipX_2_ip(x) (x)
-#endif
-
-#endif /* MG_LWIP */
-
-#endif /* CS_COMMON_PLATFORMS_LWIP_MG_LWIP_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/cs_md5.h"
-#endif
-
-#ifndef CS_COMMON_MD5_H_
-#define CS_COMMON_MD5_H_
-
-/* Amalgamated: #include "common/platform.h" */
-
-#ifndef CS_DISABLE_MD5
-#define CS_DISABLE_MD5 0
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-typedef struct {
-  uint32_t buf[4];
-  uint32_t bits[2];
-  unsigned char in[64];
-} cs_md5_ctx;
-
-void cs_md5_init(cs_md5_ctx *c);
-void cs_md5_update(cs_md5_ctx *c, const unsigned char *data, size_t len);
-void cs_md5_final(unsigned char *md, cs_md5_ctx *c);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_COMMON_MD5_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/cs_sha1.h"
-#endif
-
-#ifndef CS_COMMON_SHA1_H_
-#define CS_COMMON_SHA1_H_
-
-#ifndef CS_DISABLE_SHA1
-#define CS_DISABLE_SHA1 0
-#endif
-
-#if !CS_DISABLE_SHA1
-
-/* Amalgamated: #include "common/platform.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-typedef struct {
-  uint32_t state[5];
-  uint32_t count[2];
-  unsigned char buffer[64];
-} cs_sha1_ctx;
-
-void cs_sha1_init(cs_sha1_ctx *);
-void cs_sha1_update(cs_sha1_ctx *, const unsigned char *data, uint32_t len);
-void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *);
-void cs_hmac_sha1(const unsigned char *key, size_t key_len,
-                  const unsigned char *text, size_t text_len,
-                  unsigned char out[20]);
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_DISABLE_SHA1 */
-
-#endif /* CS_COMMON_SHA1_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/cs_time.h"
-#endif
-
-#ifndef CS_COMMON_CS_TIME_H_
-#define CS_COMMON_CS_TIME_H_
-
-#include <time.h>
-
-/* Amalgamated: #include "common/platform.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-/* Sub-second granularity time(). */
-double cs_time(void);
-
-/*
- * Similar to (non-standard) timegm, converts broken-down time into the number
- * of seconds since Unix Epoch.
- */
-double cs_timegm(const struct tm *tm);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_COMMON_CS_TIME_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/mg_str.h"
-#endif
-
-#ifndef CS_COMMON_MG_STR_H_
-#define CS_COMMON_MG_STR_H_
-
-#include <stddef.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Describes chunk of memory */
-struct mg_str {
-  const char *p; /* Memory chunk pointer */
-  size_t len;    /* Memory chunk length */
-};
-
-/*
- * Helper function for creating mg_str struct from plain C string.
- * `NULL` is allowed and becomes `{NULL, 0}`.
- */
-struct mg_str mg_mk_str(const char *s);
-
-/*
- * Like `mg_mk_str`, but takes string length explicitly.
- */
-struct mg_str mg_mk_str_n(const char *s, size_t len);
-
-/* Macro for initializing mg_str. */
-#define MG_MK_STR(str_literal) \
-  { str_literal, sizeof(str_literal) - 1 }
-#define MG_MK_STR_N(str_literal, len) \
-  { str_literal, len }
-#define MG_NULL_STR \
-  { NULL, 0 }
-
-/*
- * Cross-platform version of `strcmp()` where where first string is
- * specified by `struct mg_str`.
- */
-int mg_vcmp(const struct mg_str *str2, const char *str1);
-
-/*
- * Cross-platform version of `strncasecmp()` where first string is
- * specified by `struct mg_str`.
- */
-int mg_vcasecmp(const struct mg_str *str2, const char *str1);
-
-/* Creates a copy of s (heap-allocated). */
-struct mg_str mg_strdup(const struct mg_str s);
-
-/*
- * Creates a copy of s (heap-allocated).
- * Resulting string is NUL-terminated (but NUL is not included in len).
- */
-struct mg_str mg_strdup_nul(const struct mg_str s);
-
-/*
- * Locates character in a string.
- */
-const char *mg_strchr(const struct mg_str s, int c);
-
-/*
- * Compare two `mg_str`s; return value is the same as `strcmp`.
- */
-int mg_strcmp(const struct mg_str str1, const struct mg_str str2);
-
-/*
- * Like `mg_strcmp`, but compares at most `n` characters.
- */
-int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n);
-
-/*
- * Compare two `mg_str`s ignoreing case; return value is the same as `strcmp`.
- */
-int mg_strcasecmp(const struct mg_str str1, const struct mg_str str2);
-
-/*
- * Free the string (assuming it was heap allocated).
- */
-void mg_strfree(struct mg_str *s);
-
-/*
- * Finds the first occurrence of a substring `needle` in the `haystack`.
- */
-const char *mg_strstr(const struct mg_str haystack, const struct mg_str needle);
-
-/* Strip whitespace at the start and the end of s */
-struct mg_str mg_strstrip(struct mg_str s);
-
-/* Returns 1 if s starts with the given prefix. */
-int mg_str_starts_with(struct mg_str s, struct mg_str prefix);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CS_COMMON_MG_STR_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/mbuf.h"
-#endif
-
-/*
- * Mbufs are mutable/growing memory buffers, like C++ strings.
- * Mbuf can append data to the end of a buffer or insert data into arbitrary
- * position in the middle of a buffer. The buffer grows automatically when
- * needed.
- */
-
-#ifndef CS_COMMON_MBUF_H_
-#define CS_COMMON_MBUF_H_
-
-#include <stdlib.h>
-/* Amalgamated: #include "common/platform.h" */
-
-#if defined(__cplusplus)
-extern "C" {
-#endif
-
-#ifndef MBUF_SIZE_MULTIPLIER
-#define MBUF_SIZE_MULTIPLIER 1.5
-#endif
-
-#ifndef MBUF_SIZE_MAX_HEADROOM
-#ifdef BUFSIZ
-#define MBUF_SIZE_MAX_HEADROOM BUFSIZ
-#else
-#define MBUF_SIZE_MAX_HEADROOM 1024
-#endif
-#endif
-
-/* Memory buffer descriptor */
-struct mbuf {
-  char *buf;   /* Buffer pointer */
-  size_t len;  /* Data length. Data is located between offset 0 and len. */
-  size_t size; /* Buffer size allocated by realloc(1). Must be >= len */
-};
-
-/*
- * Initialises an Mbuf.
- * `initial_capacity` specifies the initial capacity of the mbuf.
- */
-void mbuf_init(struct mbuf *, size_t initial_capacity);
-
-/* Frees the space allocated for the mbuffer and resets the mbuf structure. */
-void mbuf_free(struct mbuf *);
-
-/*
- * Appends data to the Mbuf.
- *
- * Returns the number of bytes appended or 0 if out of memory.
- */
-size_t mbuf_append(struct mbuf *, const void *data, size_t data_size);
-
-/*
- * Appends data to the Mbuf and frees it (data must be heap-allocated).
- *
- * Returns the number of bytes appended or 0 if out of memory.
- * data is freed irrespective of return value.
- */
-size_t mbuf_append_and_free(struct mbuf *, void *data, size_t data_size);
-
-/*
- * Inserts data at a specified offset in the Mbuf.
- *
- * Existing data will be shifted forwards and the buffer will
- * be grown if necessary.
- * Returns the number of bytes inserted.
- */
-size_t mbuf_insert(struct mbuf *, size_t, const void *, size_t);
-
-/* Removes `data_size` bytes from the beginning of the buffer. */
-void mbuf_remove(struct mbuf *, size_t data_size);
-
-/*
- * Resizes an Mbuf.
- *
- * If `new_size` is smaller than buffer's `len`, the
- * resize is not performed.
- */
-void mbuf_resize(struct mbuf *, size_t new_size);
-
-/* Moves the state from one mbuf to the other. */
-void mbuf_move(struct mbuf *from, struct mbuf *to);
-
-/* Removes all the data from mbuf (if any). */
-void mbuf_clear(struct mbuf *);
-
-/* Shrinks an Mbuf by resizing its `size` to `len`. */
-void mbuf_trim(struct mbuf *);
-
-#if defined(__cplusplus)
-}
-#endif /* __cplusplus */
-
-#endif /* CS_COMMON_MBUF_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/cs_base64.h"
-#endif
-
-#ifndef CS_COMMON_CS_BASE64_H_
-#define CS_COMMON_CS_BASE64_H_
-
-#ifndef DISABLE_BASE64
-#define DISABLE_BASE64 0
-#endif
-
-#if !DISABLE_BASE64
-
-#include <stdio.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef void (*cs_base64_putc_t)(char, void *);
-
-struct cs_base64_ctx {
-  /* cannot call it putc because it's a macro on some environments */
-  cs_base64_putc_t b64_putc;
-  unsigned char chunk[3];
-  int chunk_size;
-  void *user_data;
-};
-
-void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t putc,
-                    void *user_data);
-void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len);
-void cs_base64_finish(struct cs_base64_ctx *ctx);
-
-void cs_base64_encode(const unsigned char *src, int src_len, char *dst);
-void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len);
-
-/*
- * Decodes a base64 string `s` length `len` into `dst`.
- * `dst` must have enough space to hold the result.
- * `*dec_len` will contain the resulting length of the string in `dst`
- * while return value will return number of processed bytes in `src`.
- * Return value == len indicates successful processing of all the data.
- */
-int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* DISABLE_BASE64 */
-
-#endif /* CS_COMMON_CS_BASE64_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/str_util.h"
-#endif
-
-#ifndef CS_COMMON_STR_UTIL_H_
-#define CS_COMMON_STR_UTIL_H_
-
-#include <stdarg.h>
-#include <stdlib.h>
-
-/* Amalgamated: #include "common/mg_str.h" */
-/* Amalgamated: #include "common/platform.h" */
-
-#ifndef CS_ENABLE_STRDUP
-#define CS_ENABLE_STRDUP 0
-#endif
-
-#ifndef CS_ENABLE_TO64
-#define CS_ENABLE_TO64 0
-#endif
-
-/*
- * Expands to a string representation of its argument: e.g.
- * `CS_STRINGIFY_LIT(5) expands to "5"`
- */
-#if !defined(_MSC_VER) || _MSC_VER >= 1900
-#define CS_STRINGIFY_LIT(...) #__VA_ARGS__
-#else
-#define CS_STRINGIFY_LIT(x) #x
-#endif
-
-/*
- * Expands to a string representation of its argument, which is allowed
- * to be a macro: e.g.
- *
- * #define FOO 123
- * CS_STRINGIFY_MACRO(FOO)
- *
- * expands to 123.
- */
-#define CS_STRINGIFY_MACRO(x) CS_STRINGIFY_LIT(x)
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*
- * Equivalent of standard `strnlen()`.
- */
-size_t c_strnlen(const char *s, size_t maxlen);
-
-/*
- * Equivalent of standard `snprintf()`.
- */
-int c_snprintf(char *buf, size_t buf_size, const char *format, ...)
-    PRINTF_LIKE(3, 4);
-
-/*
- * Equivalent of standard `vsnprintf()`.
- */
-int c_vsnprintf(char *buf, size_t buf_size, const char *format, va_list ap);
-
-/*
- * Find the first occurrence of find in s, where the search is limited to the
- * first slen characters of s.
- */
-const char *c_strnstr(const char *s, const char *find, size_t slen);
-
-/*
- * Stringify binary data. Output buffer size must be 2 * size_of_input + 1
- * because each byte of input takes 2 bytes in string representation
- * plus 1 byte for the terminating \0 character.
- */
-void cs_to_hex(char *to, const unsigned char *p, size_t len);
-
-/*
- * Convert stringified binary data back to binary.
- * Does the reverse of `cs_to_hex()`.
- */
-void cs_from_hex(char *to, const char *p, size_t len);
-
-#if CS_ENABLE_STRDUP
-/*
- * Equivalent of standard `strdup()`, defined if only `CS_ENABLE_STRDUP` is 1.
- */
-char *strdup(const char *src);
-#endif
-
-#if CS_ENABLE_TO64
-#include <stdint.h>
-/*
- * Simple string -> int64 conversion routine.
- */
-int64_t cs_to64(const char *s);
-#endif
-
-/*
- * Cross-platform version of `strncasecmp()`.
- */
-int mg_ncasecmp(const char *s1, const char *s2, size_t len);
-
-/*
- * Cross-platform version of `strcasecmp()`.
- */
-int mg_casecmp(const char *s1, const char *s2);
-
-/*
- * Prints message to the buffer. If the buffer is large enough to hold the
- * message, it returns buffer. If buffer is to small, it allocates a large
- * enough buffer on heap and returns allocated buffer.
- * This is a supposed use case:
- *
- * ```c
- *    char buf[5], *p = buf;
- *    mg_avprintf(&p, sizeof(buf), "%s", "hi there");
- *    use_p_somehow(p);
- *    if (p != buf) {
- *      free(p);
- *    }
- * ```
- *
- * The purpose of this is to avoid malloc-ing if generated strings are small.
- */
-int mg_asprintf(char **buf, size_t size, const char *fmt, ...)
-    PRINTF_LIKE(3, 4);
-
-/* Same as mg_asprintf, but takes varargs list. */
-int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap);
-
-/*
- * A helper function for traversing a comma separated list of values.
- * It returns a list pointer shifted to the next value or NULL if the end
- * of the list found.
- * The value is stored in a val vector. If the value has a form "x=y", then
- * eq_val vector is initialised to point to the "y" part, and val vector length
- * is adjusted to point only to "x".
- * If the list is just a comma separated list of entries, like "aa,bb,cc" then
- * `eq_val` will contain zero-length string.
- *
- * The purpose of this function is to parse comma separated string without
- * any copying/memory allocation.
- */
-const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
-                                     struct mg_str *eq_val);
-
-/*
- * Like `mg_next_comma_list_entry()`, but takes `list` as `struct mg_str`.
- * NB: Test return value's .p, not .len. On last itreation that yields result
- * .len will be 0 but .p will not. When finished, .p will be NULL.
- */
-struct mg_str mg_next_comma_list_entry_n(struct mg_str list, struct mg_str *val,
-                                         struct mg_str *eq_val);
-
-/*
- * Matches 0-terminated string (mg_match_prefix) or string with given length
- * mg_match_prefix_n against a glob pattern. Glob syntax:
- * ```
- * - * matches zero or more characters until a slash character /
- * - ** matches zero or more characters
- * - ? Matches exactly one character which is not a slash /
- * - | or ,  divides alternative patterns
- * - any other character matches itself
- * ```
- * Match is case-insensitive. Return number of bytes matched.
- * Examples:
- * ```
- * mg_match_prefix("a*f", len, "abcdefgh") == 6
- * mg_match_prefix("a*f", len, "abcdexgh") == 0
- * mg_match_prefix("a*f|de*,xy", len, "defgh") == 5
- * mg_match_prefix("?*", len, "abc") == 3
- * mg_match_prefix("?*", len, "") == 0
- * ```
- */
-size_t mg_match_prefix(const char *pattern, int pattern_len, const char *str);
-
-/*
- * Like `mg_match_prefix()`, but takes `pattern` and `str` as `struct mg_str`.
- */
-size_t mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CS_COMMON_STR_UTIL_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/common/queue.h"
-#endif
-/* clang-format off */
-/*-
- * Copyright (c) 1991, 1993
- *	The Regents of the University of California.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- * 4. Neither the name of the University nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- *	@(#)queue.h	8.5 (Berkeley) 8/20/94
- * $FreeBSD$
- */
-
-#ifndef _SYS_QUEUE_H_
-#define	_SYS_QUEUE_H_
-
-/*
- * This file defines four types of data structures: singly-linked lists,
- * singly-linked tail queues, lists and tail queues.
- *
- * A singly-linked list is headed by a single forward pointer. The elements
- * are singly linked for minimum space and pointer manipulation overhead at
- * the expense of O(n) removal for arbitrary elements. New elements can be
- * added to the list after an existing element or at the head of the list.
- * Elements being removed from the head of the list should use the explicit
- * macro for this purpose for optimum efficiency. A singly-linked list may
- * only be traversed in the forward direction.  Singly-linked lists are ideal
- * for applications with large datasets and few or no removals or for
- * implementing a LIFO queue.
- *
- * A singly-linked tail queue is headed by a pair of pointers, one to the
- * head of the list and the other to the tail of the list. The elements are
- * singly linked for minimum space and pointer manipulation overhead at the
- * expense of O(n) removal for arbitrary elements. New elements can be added
- * to the list after an existing element, at the head of the list, or at the
- * end of the list. Elements being removed from the head of the tail queue
- * should use the explicit macro for this purpose for optimum efficiency.
- * A singly-linked tail queue may only be traversed in the forward direction.
- * Singly-linked tail queues are ideal for applications with large datasets
- * and few or no removals or for implementing a FIFO queue.
- *
- * A list is headed by a single forward pointer (or an array of forward
- * pointers for a hash table header). The elements are doubly linked
- * so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list before
- * or after an existing element or at the head of the list. A list
- * may be traversed in either direction.
- *
- * A tail queue is headed by a pair of pointers, one to the head of the
- * list and the other to the tail of the list. The elements are doubly
- * linked so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list before or
- * after an existing element, at the head of the list, or at the end of
- * the list. A tail queue may be traversed in either direction.
- *
- * For details on the use of these macros, see the queue(3) manual page.
- *
- *
- *				SLIST	LIST	STAILQ	TAILQ
- * _HEAD			+	+	+	+
- * _CLASS_HEAD			+	+	+	+
- * _HEAD_INITIALIZER		+	+	+	+
- * _ENTRY			+	+	+	+
- * _CLASS_ENTRY			+	+	+	+
- * _INIT			+	+	+	+
- * _EMPTY			+	+	+	+
- * _FIRST			+	+	+	+
- * _NEXT			+	+	+	+
- * _PREV			-	+	-	+
- * _LAST			-	-	+	+
- * _FOREACH			+	+	+	+
- * _FOREACH_FROM		+	+	+	+
- * _FOREACH_SAFE		+	+	+	+
- * _FOREACH_FROM_SAFE		+	+	+	+
- * _FOREACH_REVERSE		-	-	-	+
- * _FOREACH_REVERSE_FROM	-	-	-	+
- * _FOREACH_REVERSE_SAFE	-	-	-	+
- * _FOREACH_REVERSE_FROM_SAFE	-	-	-	+
- * _INSERT_HEAD			+	+	+	+
- * _INSERT_BEFORE		-	+	-	+
- * _INSERT_AFTER		+	+	+	+
- * _INSERT_TAIL			-	-	+	+
- * _CONCAT			-	-	+	+
- * _REMOVE_AFTER		+	-	+	-
- * _REMOVE_HEAD			+	-	+	-
- * _REMOVE			+	+	+	+
- * _SWAP			+	+	+	+
- *
- */
-#ifdef QUEUE_MACRO_DEBUG
-/* Store the last 2 places the queue element or head was altered */
-struct qm_trace {
-	unsigned long	 lastline;
-	unsigned long	 prevline;
-	const char	*lastfile;
-	const char	*prevfile;
-};
-
-#define	TRACEBUF	struct qm_trace trace;
-#define	TRACEBUF_INITIALIZER	{ __LINE__, 0, __FILE__, NULL } ,
-#define	TRASHIT(x)	do {(x) = (void *)-1;} while (0)
-#define	QMD_SAVELINK(name, link)	void **name = (void *)&(link)
-
-#define	QMD_TRACE_HEAD(head) do {					\
-	(head)->trace.prevline = (head)->trace.lastline;		\
-	(head)->trace.prevfile = (head)->trace.lastfile;		\
-	(head)->trace.lastline = __LINE__;				\
-	(head)->trace.lastfile = __FILE__;				\
-} while (0)
-
-#define	QMD_TRACE_ELEM(elem) do {					\
-	(elem)->trace.prevline = (elem)->trace.lastline;		\
-	(elem)->trace.prevfile = (elem)->trace.lastfile;		\
-	(elem)->trace.lastline = __LINE__;				\
-	(elem)->trace.lastfile = __FILE__;				\
-} while (0)
-
-#else
-#define	QMD_TRACE_ELEM(elem)
-#define	QMD_TRACE_HEAD(head)
-#define	QMD_SAVELINK(name, link)
-#define	TRACEBUF
-#define	TRACEBUF_INITIALIZER
-#define	TRASHIT(x)
-#endif	/* QUEUE_MACRO_DEBUG */
-
-#ifdef __cplusplus
-/*
- * In C++ there can be structure lists and class lists:
- */
-#define	QUEUE_TYPEOF(type) type
-#else
-#define	QUEUE_TYPEOF(type) struct type
-#endif
-
-/*
- * Singly-linked List declarations.
- */
-#define	SLIST_HEAD(name, type)						\
-struct name {								\
-	struct type *slh_first;	/* first element */			\
-}
-
-#define	SLIST_CLASS_HEAD(name, type)					\
-struct name {								\
-	class type *slh_first;	/* first element */			\
-}
-
-#define	SLIST_HEAD_INITIALIZER(head)					\
-	{ NULL }
-
-#define	SLIST_ENTRY(type)						\
-struct {								\
-	struct type *sle_next;	/* next element */			\
-}
-
-#define	SLIST_CLASS_ENTRY(type)						\
-struct {								\
-	class type *sle_next;		/* next element */		\
-}
-
-/*
- * Singly-linked List functions.
- */
-#define	SLIST_EMPTY(head)	((head)->slh_first == NULL)
-
-#define	SLIST_FIRST(head)	((head)->slh_first)
-
-#define	SLIST_FOREACH(var, head, field)					\
-	for ((var) = SLIST_FIRST((head));				\
-	    (var);							\
-	    (var) = SLIST_NEXT((var), field))
-
-#define	SLIST_FOREACH_FROM(var, head, field)				\
-	for ((var) = ((var) ? (var) : SLIST_FIRST((head)));		\
-	    (var);							\
-	    (var) = SLIST_NEXT((var), field))
-
-#define	SLIST_FOREACH_SAFE(var, head, field, tvar)			\
-	for ((var) = SLIST_FIRST((head));				\
-	    (var) && ((tvar) = SLIST_NEXT((var), field), 1);		\
-	    (var) = (tvar))
-
-#define	SLIST_FOREACH_FROM_SAFE(var, head, field, tvar)			\
-	for ((var) = ((var) ? (var) : SLIST_FIRST((head)));		\
-	    (var) && ((tvar) = SLIST_NEXT((var), field), 1);		\
-	    (var) = (tvar))
-
-#define	SLIST_FOREACH_PREVPTR(var, varp, head, field)			\
-	for ((varp) = &SLIST_FIRST((head));				\
-	    ((var) = *(varp)) != NULL;					\
-	    (varp) = &SLIST_NEXT((var), field))
-
-#define	SLIST_INIT(head) do {						\
-	SLIST_FIRST((head)) = NULL;					\
-} while (0)
-
-#define	SLIST_INSERT_AFTER(slistelm, elm, field) do {			\
-	SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field);	\
-	SLIST_NEXT((slistelm), field) = (elm);				\
-} while (0)
-
-#define	SLIST_INSERT_HEAD(head, elm, field) do {			\
-	SLIST_NEXT((elm), field) = SLIST_FIRST((head));			\
-	SLIST_FIRST((head)) = (elm);					\
-} while (0)
-
-#define	SLIST_NEXT(elm, field)	((elm)->field.sle_next)
-
-#define	SLIST_REMOVE(head, elm, type, field) do {			\
-	QMD_SAVELINK(oldnext, (elm)->field.sle_next);			\
-	if (SLIST_FIRST((head)) == (elm)) {				\
-		SLIST_REMOVE_HEAD((head), field);			\
-	}								\
-	else {								\
-		QUEUE_TYPEOF(type) *curelm = SLIST_FIRST(head);		\
-		while (SLIST_NEXT(curelm, field) != (elm))		\
-			curelm = SLIST_NEXT(curelm, field);		\
-		SLIST_REMOVE_AFTER(curelm, field);			\
-	}								\
-	TRASHIT(*oldnext);						\
-} while (0)
-
-#define SLIST_REMOVE_AFTER(elm, field) do {				\
-	SLIST_NEXT(elm, field) =					\
-	    SLIST_NEXT(SLIST_NEXT(elm, field), field);			\
-} while (0)
-
-#define	SLIST_REMOVE_HEAD(head, field) do {				\
-	SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field);	\
-} while (0)
-
-#define SLIST_SWAP(head1, head2, type) do {				\
-	QUEUE_TYPEOF(type) *swap_first = SLIST_FIRST(head1);		\
-	SLIST_FIRST(head1) = SLIST_FIRST(head2);			\
-	SLIST_FIRST(head2) = swap_first;				\
-} while (0)
-
-/*
- * Singly-linked Tail queue declarations.
- */
-#define	STAILQ_HEAD(name, type)						\
-struct name {								\
-	struct type *stqh_first;/* first element */			\
-	struct type **stqh_last;/* addr of last next element */		\
-}
-
-#define	STAILQ_CLASS_HEAD(name, type)					\
-struct name {								\
-	class type *stqh_first;	/* first element */			\
-	class type **stqh_last;	/* addr of last next element */		\
-}
-
-#define	STAILQ_HEAD_INITIALIZER(head)					\
-	{ NULL, &(head).stqh_first }
-
-#define	STAILQ_ENTRY(type)						\
-struct {								\
-	struct type *stqe_next;	/* next element */			\
-}
-
-#define	STAILQ_CLASS_ENTRY(type)					\
-struct {								\
-	class type *stqe_next;	/* next element */			\
-}
-
-/*
- * Singly-linked Tail queue functions.
- */
-#define	STAILQ_CONCAT(head1, head2) do {				\
-	if (!STAILQ_EMPTY((head2))) {					\
-		*(head1)->stqh_last = (head2)->stqh_first;		\
-		(head1)->stqh_last = (head2)->stqh_last;		\
-		STAILQ_INIT((head2));					\
-	}								\
-} while (0)
-
-#define	STAILQ_EMPTY(head)	((head)->stqh_first == NULL)
-
-#define	STAILQ_FIRST(head)	((head)->stqh_first)
-
-#define	STAILQ_FOREACH(var, head, field)				\
-	for((var) = STAILQ_FIRST((head));				\
-	   (var);							\
-	   (var) = STAILQ_NEXT((var), field))
-
-#define	STAILQ_FOREACH_FROM(var, head, field)				\
-	for ((var) = ((var) ? (var) : STAILQ_FIRST((head)));		\
-	   (var);							\
-	   (var) = STAILQ_NEXT((var), field))
-
-#define	STAILQ_FOREACH_SAFE(var, head, field, tvar)			\
-	for ((var) = STAILQ_FIRST((head));				\
-	    (var) && ((tvar) = STAILQ_NEXT((var), field), 1);		\
-	    (var) = (tvar))
-
-#define	STAILQ_FOREACH_FROM_SAFE(var, head, field, tvar)		\
-	for ((var) = ((var) ? (var) : STAILQ_FIRST((head)));		\
-	    (var) && ((tvar) = STAILQ_NEXT((var), field), 1);		\
-	    (var) = (tvar))
-
-#define	STAILQ_INIT(head) do {						\
-	STAILQ_FIRST((head)) = NULL;					\
-	(head)->stqh_last = &STAILQ_FIRST((head));			\
-} while (0)
-
-#define	STAILQ_INSERT_AFTER(head, tqelm, elm, field) do {		\
-	if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\
-		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
-	STAILQ_NEXT((tqelm), field) = (elm);				\
-} while (0)
-
-#define	STAILQ_INSERT_HEAD(head, elm, field) do {			\
-	if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL)	\
-		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
-	STAILQ_FIRST((head)) = (elm);					\
-} while (0)
-
-#define	STAILQ_INSERT_TAIL(head, elm, field) do {			\
-	STAILQ_NEXT((elm), field) = NULL;				\
-	*(head)->stqh_last = (elm);					\
-	(head)->stqh_last = &STAILQ_NEXT((elm), field);			\
-} while (0)
-
-#define	STAILQ_LAST(head, type, field)				\
-	(STAILQ_EMPTY((head)) ? NULL :				\
-	    __containerof((head)->stqh_last,			\
-	    QUEUE_TYPEOF(type), field.stqe_next))
-
-#define	STAILQ_NEXT(elm, field)	((elm)->field.stqe_next)
-
-#define	STAILQ_REMOVE(head, elm, type, field) do {			\
-	QMD_SAVELINK(oldnext, (elm)->field.stqe_next);			\
-	if (STAILQ_FIRST((head)) == (elm)) {				\
-		STAILQ_REMOVE_HEAD((head), field);			\
-	}								\
-	else {								\
-		QUEUE_TYPEOF(type) *curelm = STAILQ_FIRST(head);	\
-		while (STAILQ_NEXT(curelm, field) != (elm))		\
-			curelm = STAILQ_NEXT(curelm, field);		\
-		STAILQ_REMOVE_AFTER(head, curelm, field);		\
-	}								\
-	TRASHIT(*oldnext);						\
-} while (0)
-
-#define STAILQ_REMOVE_AFTER(head, elm, field) do {			\
-	if ((STAILQ_NEXT(elm, field) =					\
-	     STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL)	\
-		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
-} while (0)
-
-#define	STAILQ_REMOVE_HEAD(head, field) do {				\
-	if ((STAILQ_FIRST((head)) =					\
-	     STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL)		\
-		(head)->stqh_last = &STAILQ_FIRST((head));		\
-} while (0)
-
-#define STAILQ_SWAP(head1, head2, type) do {				\
-	QUEUE_TYPEOF(type) *swap_first = STAILQ_FIRST(head1);		\
-	QUEUE_TYPEOF(type) **swap_last = (head1)->stqh_last;		\
-	STAILQ_FIRST(head1) = STAILQ_FIRST(head2);			\
-	(head1)->stqh_last = (head2)->stqh_last;			\
-	STAILQ_FIRST(head2) = swap_first;				\
-	(head2)->stqh_last = swap_last;					\
-	if (STAILQ_EMPTY(head1))					\
-		(head1)->stqh_last = &STAILQ_FIRST(head1);		\
-	if (STAILQ_EMPTY(head2))					\
-		(head2)->stqh_last = &STAILQ_FIRST(head2);		\
-} while (0)
-
-
-/*
- * List declarations.
- */
-#define	LIST_HEAD(name, type)						\
-struct name {								\
-	struct type *lh_first;	/* first element */			\
-}
-
-#define	LIST_CLASS_HEAD(name, type)					\
-struct name {								\
-	class type *lh_first;	/* first element */			\
-}
-
-#define	LIST_HEAD_INITIALIZER(head)					\
-	{ NULL }
-
-#define	LIST_ENTRY(type)						\
-struct {								\
-	struct type *le_next;	/* next element */			\
-	struct type **le_prev;	/* address of previous next element */	\
-}
-
-#define	LIST_CLASS_ENTRY(type)						\
-struct {								\
-	class type *le_next;	/* next element */			\
-	class type **le_prev;	/* address of previous next element */	\
-}
-
-/*
- * List functions.
- */
-
-#if (defined(_KERNEL) && defined(INVARIANTS))
-#define	QMD_LIST_CHECK_HEAD(head, field) do {				\
-	if (LIST_FIRST((head)) != NULL &&				\
-	    LIST_FIRST((head))->field.le_prev !=			\
-	     &LIST_FIRST((head)))					\
-		panic("Bad list head %p first->prev != head", (head));	\
-} while (0)
-
-#define	QMD_LIST_CHECK_NEXT(elm, field) do {				\
-	if (LIST_NEXT((elm), field) != NULL &&				\
-	    LIST_NEXT((elm), field)->field.le_prev !=			\
-	     &((elm)->field.le_next))					\
-	     	panic("Bad link elm %p next->prev != elm", (elm));	\
-} while (0)
-
-#define	QMD_LIST_CHECK_PREV(elm, field) do {				\
-	if (*(elm)->field.le_prev != (elm))				\
-		panic("Bad link elm %p prev->next != elm", (elm));	\
-} while (0)
-#else
-#define	QMD_LIST_CHECK_HEAD(head, field)
-#define	QMD_LIST_CHECK_NEXT(elm, field)
-#define	QMD_LIST_CHECK_PREV(elm, field)
-#endif /* (_KERNEL && INVARIANTS) */
-
-#define	LIST_EMPTY(head)	((head)->lh_first == NULL)
-
-#define	LIST_FIRST(head)	((head)->lh_first)
-
-#define	LIST_FOREACH(var, head, field)					\
-	for ((var) = LIST_FIRST((head));				\
-	    (var);							\
-	    (var) = LIST_NEXT((var), field))
-
-#define	LIST_FOREACH_FROM(var, head, field)				\
-	for ((var) = ((var) ? (var) : LIST_FIRST((head)));		\
-	    (var);							\
-	    (var) = LIST_NEXT((var), field))
-
-#define	LIST_FOREACH_SAFE(var, head, field, tvar)			\
-	for ((var) = LIST_FIRST((head));				\
-	    (var) && ((tvar) = LIST_NEXT((var), field), 1);		\
-	    (var) = (tvar))
-
-#define	LIST_FOREACH_FROM_SAFE(var, head, field, tvar)			\
-	for ((var) = ((var) ? (var) : LIST_FIRST((head)));		\
-	    (var) && ((tvar) = LIST_NEXT((var), field), 1);		\
-	    (var) = (tvar))
-
-#define	LIST_INIT(head) do {						\
-	LIST_FIRST((head)) = NULL;					\
-} while (0)
-
-#define	LIST_INSERT_AFTER(listelm, elm, field) do {			\
-	QMD_LIST_CHECK_NEXT(listelm, field);				\
-	if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\
-		LIST_NEXT((listelm), field)->field.le_prev =		\
-		    &LIST_NEXT((elm), field);				\
-	LIST_NEXT((listelm), field) = (elm);				\
-	(elm)->field.le_prev = &LIST_NEXT((listelm), field);		\
-} while (0)
-
-#define	LIST_INSERT_BEFORE(listelm, elm, field) do {			\
-	QMD_LIST_CHECK_PREV(listelm, field);				\
-	(elm)->field.le_prev = (listelm)->field.le_prev;		\
-	LIST_NEXT((elm), field) = (listelm);				\
-	*(listelm)->field.le_prev = (elm);				\
-	(listelm)->field.le_prev = &LIST_NEXT((elm), field);		\
-} while (0)
-
-#define	LIST_INSERT_HEAD(head, elm, field) do {				\
-	QMD_LIST_CHECK_HEAD((head), field);				\
-	if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL)	\
-		LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\
-	LIST_FIRST((head)) = (elm);					\
-	(elm)->field.le_prev = &LIST_FIRST((head));			\
-} while (0)
-
-#define	LIST_NEXT(elm, field)	((elm)->field.le_next)
-
-#define	LIST_PREV(elm, head, type, field)			\
-	((elm)->field.le_prev == &LIST_FIRST((head)) ? NULL :	\
-	    __containerof((elm)->field.le_prev,			\
-	    QUEUE_TYPEOF(type), field.le_next))
-
-#define	LIST_REMOVE(elm, field) do {					\
-	QMD_SAVELINK(oldnext, (elm)->field.le_next);			\
-	QMD_SAVELINK(oldprev, (elm)->field.le_prev);			\
-	QMD_LIST_CHECK_NEXT(elm, field);				\
-	QMD_LIST_CHECK_PREV(elm, field);				\
-	if (LIST_NEXT((elm), field) != NULL)				\
-		LIST_NEXT((elm), field)->field.le_prev = 		\
-		    (elm)->field.le_prev;				\
-	*(elm)->field.le_prev = LIST_NEXT((elm), field);		\
-	TRASHIT(*oldnext);						\
-	TRASHIT(*oldprev);						\
-} while (0)
-
-#define LIST_SWAP(head1, head2, type, field) do {			\
-	QUEUE_TYPEOF(type) *swap_tmp = LIST_FIRST(head1);		\
-	LIST_FIRST((head1)) = LIST_FIRST((head2));			\
-	LIST_FIRST((head2)) = swap_tmp;					\
-	if ((swap_tmp = LIST_FIRST((head1))) != NULL)			\
-		swap_tmp->field.le_prev = &LIST_FIRST((head1));		\
-	if ((swap_tmp = LIST_FIRST((head2))) != NULL)			\
-		swap_tmp->field.le_prev = &LIST_FIRST((head2));		\
-} while (0)
-
-/*
- * Tail queue declarations.
- */
-#define	TAILQ_HEAD(name, type)						\
-struct name {								\
-	struct type *tqh_first;	/* first element */			\
-	struct type **tqh_last;	/* addr of last next element */		\
-	TRACEBUF							\
-}
-
-#define	TAILQ_CLASS_HEAD(name, type)					\
-struct name {								\
-	class type *tqh_first;	/* first element */			\
-	class type **tqh_last;	/* addr of last next element */		\
-	TRACEBUF							\
-}
-
-#define	TAILQ_HEAD_INITIALIZER(head)					\
-	{ NULL, &(head).tqh_first, TRACEBUF_INITIALIZER }
-
-#define	TAILQ_ENTRY(type)						\
-struct {								\
-	struct type *tqe_next;	/* next element */			\
-	struct type **tqe_prev;	/* address of previous next element */	\
-	TRACEBUF							\
-}
-
-#define	TAILQ_CLASS_ENTRY(type)						\
-struct {								\
-	class type *tqe_next;	/* next element */			\
-	class type **tqe_prev;	/* address of previous next element */	\
-	TRACEBUF							\
-}
-
-/*
- * Tail queue functions.
- */
-#if (defined(_KERNEL) && defined(INVARIANTS))
-#define	QMD_TAILQ_CHECK_HEAD(head, field) do {				\
-	if (!TAILQ_EMPTY(head) &&					\
-	    TAILQ_FIRST((head))->field.tqe_prev !=			\
-	     &TAILQ_FIRST((head)))					\
-		panic("Bad tailq head %p first->prev != head", (head));	\
-} while (0)
-
-#define	QMD_TAILQ_CHECK_TAIL(head, field) do {				\
-	if (*(head)->tqh_last != NULL)					\
-	    	panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head)); 	\
-} while (0)
-
-#define	QMD_TAILQ_CHECK_NEXT(elm, field) do {				\
-	if (TAILQ_NEXT((elm), field) != NULL &&				\
-	    TAILQ_NEXT((elm), field)->field.tqe_prev !=			\
-	     &((elm)->field.tqe_next))					\
-		panic("Bad link elm %p next->prev != elm", (elm));	\
-} while (0)
-
-#define	QMD_TAILQ_CHECK_PREV(elm, field) do {				\
-	if (*(elm)->field.tqe_prev != (elm))				\
-		panic("Bad link elm %p prev->next != elm", (elm));	\
-} while (0)
-#else
-#define	QMD_TAILQ_CHECK_HEAD(head, field)
-#define	QMD_TAILQ_CHECK_TAIL(head, headname)
-#define	QMD_TAILQ_CHECK_NEXT(elm, field)
-#define	QMD_TAILQ_CHECK_PREV(elm, field)
-#endif /* (_KERNEL && INVARIANTS) */
-
-#define	TAILQ_CONCAT(head1, head2, field) do {				\
-	if (!TAILQ_EMPTY(head2)) {					\
-		*(head1)->tqh_last = (head2)->tqh_first;		\
-		(head2)->tqh_first->field.tqe_prev = (head1)->tqh_last;	\
-		(head1)->tqh_last = (head2)->tqh_last;			\
-		TAILQ_INIT((head2));					\
-		QMD_TRACE_HEAD(head1);					\
-		QMD_TRACE_HEAD(head2);					\
-	}								\
-} while (0)
-
-#define	TAILQ_EMPTY(head)	((head)->tqh_first == NULL)
-
-#define	TAILQ_FIRST(head)	((head)->tqh_first)
-
-#define	TAILQ_FOREACH(var, head, field)					\
-	for ((var) = TAILQ_FIRST((head));				\
-	    (var);							\
-	    (var) = TAILQ_NEXT((var), field))
-
-#define	TAILQ_FOREACH_FROM(var, head, field)				\
-	for ((var) = ((var) ? (var) : TAILQ_FIRST((head)));		\
-	    (var);							\
-	    (var) = TAILQ_NEXT((var), field))
-
-#define	TAILQ_FOREACH_SAFE(var, head, field, tvar)			\
-	for ((var) = TAILQ_FIRST((head));				\
-	    (var) && ((tvar) = TAILQ_NEXT((var), field), 1);		\
-	    (var) = (tvar))
-
-#define	TAILQ_FOREACH_FROM_SAFE(var, head, field, tvar)			\
-	for ((var) = ((var) ? (var) : TAILQ_FIRST((head)));		\
-	    (var) && ((tvar) = TAILQ_NEXT((var), field), 1);		\
-	    (var) = (tvar))
-
-#define	TAILQ_FOREACH_REVERSE(var, head, headname, field)		\
-	for ((var) = TAILQ_LAST((head), headname);			\
-	    (var);							\
-	    (var) = TAILQ_PREV((var), headname, field))
-
-#define	TAILQ_FOREACH_REVERSE_FROM(var, head, headname, field)		\
-	for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname));	\
-	    (var);							\
-	    (var) = TAILQ_PREV((var), headname, field))
-
-#define	TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar)	\
-	for ((var) = TAILQ_LAST((head), headname);			\
-	    (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1);	\
-	    (var) = (tvar))
-
-#define	TAILQ_FOREACH_REVERSE_FROM_SAFE(var, head, headname, field, tvar) \
-	for ((var) = ((var) ? (var) : TAILQ_LAST((head), headname));	\
-	    (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1);	\
-	    (var) = (tvar))
-
-#define	TAILQ_INIT(head) do {						\
-	TAILQ_FIRST((head)) = NULL;					\
-	(head)->tqh_last = &TAILQ_FIRST((head));			\
-	QMD_TRACE_HEAD(head);						\
-} while (0)
-
-#define	TAILQ_INSERT_AFTER(head, listelm, elm, field) do {		\
-	QMD_TAILQ_CHECK_NEXT(listelm, field);				\
-	if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\
-		TAILQ_NEXT((elm), field)->field.tqe_prev = 		\
-		    &TAILQ_NEXT((elm), field);				\
-	else {								\
-		(head)->tqh_last = &TAILQ_NEXT((elm), field);		\
-		QMD_TRACE_HEAD(head);					\
-	}								\
-	TAILQ_NEXT((listelm), field) = (elm);				\
-	(elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field);		\
-	QMD_TRACE_ELEM(&(elm)->field);					\
-	QMD_TRACE_ELEM(&(listelm)->field);				\
-} while (0)
-
-#define	TAILQ_INSERT_BEFORE(listelm, elm, field) do {			\
-	QMD_TAILQ_CHECK_PREV(listelm, field);				\
-	(elm)->field.tqe_prev = (listelm)->field.tqe_prev;		\
-	TAILQ_NEXT((elm), field) = (listelm);				\
-	*(listelm)->field.tqe_prev = (elm);				\
-	(listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field);		\
-	QMD_TRACE_ELEM(&(elm)->field);					\
-	QMD_TRACE_ELEM(&(listelm)->field);				\
-} while (0)
-
-#define	TAILQ_INSERT_HEAD(head, elm, field) do {			\
-	QMD_TAILQ_CHECK_HEAD(head, field);				\
-	if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL)	\
-		TAILQ_FIRST((head))->field.tqe_prev =			\
-		    &TAILQ_NEXT((elm), field);				\
-	else								\
-		(head)->tqh_last = &TAILQ_NEXT((elm), field);		\
-	TAILQ_FIRST((head)) = (elm);					\
-	(elm)->field.tqe_prev = &TAILQ_FIRST((head));			\
-	QMD_TRACE_HEAD(head);						\
-	QMD_TRACE_ELEM(&(elm)->field);					\
-} while (0)
-
-#define	TAILQ_INSERT_TAIL(head, elm, field) do {			\
-	QMD_TAILQ_CHECK_TAIL(head, field);				\
-	TAILQ_NEXT((elm), field) = NULL;				\
-	(elm)->field.tqe_prev = (head)->tqh_last;			\
-	*(head)->tqh_last = (elm);					\
-	(head)->tqh_last = &TAILQ_NEXT((elm), field);			\
-	QMD_TRACE_HEAD(head);						\
-	QMD_TRACE_ELEM(&(elm)->field);					\
-} while (0)
-
-#define	TAILQ_LAST(head, headname)					\
-	(*(((struct headname *)((head)->tqh_last))->tqh_last))
-
-#define	TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
-
-#define	TAILQ_PREV(elm, headname, field)				\
-	(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
-
-#define	TAILQ_REMOVE(head, elm, field) do {				\
-	QMD_SAVELINK(oldnext, (elm)->field.tqe_next);			\
-	QMD_SAVELINK(oldprev, (elm)->field.tqe_prev);			\
-	QMD_TAILQ_CHECK_NEXT(elm, field);				\
-	QMD_TAILQ_CHECK_PREV(elm, field);				\
-	if ((TAILQ_NEXT((elm), field)) != NULL)				\
-		TAILQ_NEXT((elm), field)->field.tqe_prev = 		\
-		    (elm)->field.tqe_prev;				\
-	else {								\
-		(head)->tqh_last = (elm)->field.tqe_prev;		\
-		QMD_TRACE_HEAD(head);					\
-	}								\
-	*(elm)->field.tqe_prev = TAILQ_NEXT((elm), field);		\
-	TRASHIT(*oldnext);						\
-	TRASHIT(*oldprev);						\
-	QMD_TRACE_ELEM(&(elm)->field);					\
-} while (0)
-
-#define TAILQ_SWAP(head1, head2, type, field) do {			\
-	QUEUE_TYPEOF(type) *swap_first = (head1)->tqh_first;		\
-	QUEUE_TYPEOF(type) **swap_last = (head1)->tqh_last;		\
-	(head1)->tqh_first = (head2)->tqh_first;			\
-	(head1)->tqh_last = (head2)->tqh_last;				\
-	(head2)->tqh_first = swap_first;				\
-	(head2)->tqh_last = swap_last;					\
-	if ((swap_first = (head1)->tqh_first) != NULL)			\
-		swap_first->field.tqe_prev = &(head1)->tqh_first;	\
-	else								\
-		(head1)->tqh_last = &(head1)->tqh_first;		\
-	if ((swap_first = (head2)->tqh_first) != NULL)			\
-		swap_first->field.tqe_prev = &(head2)->tqh_first;	\
-	else								\
-		(head2)->tqh_last = &(head2)->tqh_first;		\
-} while (0)
-
-#endif /* !_SYS_QUEUE_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_features.h"
-#endif
-
-#ifndef CS_MONGOOSE_SRC_FEATURES_H_
-#define CS_MONGOOSE_SRC_FEATURES_H_
-
-#ifndef MG_DISABLE_HTTP_DIGEST_AUTH
-#define MG_DISABLE_HTTP_DIGEST_AUTH 0
-#endif
-
-#ifndef MG_DISABLE_HTTP_KEEP_ALIVE
-#define MG_DISABLE_HTTP_KEEP_ALIVE 0
-#endif
-
-#ifndef MG_DISABLE_PFS
-#define MG_DISABLE_PFS 0
-#endif
-
-#ifndef MG_DISABLE_WS_RANDOM_MASK
-#define MG_DISABLE_WS_RANDOM_MASK 0
-#endif
-
-#ifndef MG_ENABLE_ASYNC_RESOLVER
-#define MG_ENABLE_ASYNC_RESOLVER 1
-#endif
-
-#ifndef MG_ENABLE_BROADCAST
-#define MG_ENABLE_BROADCAST 0
-#endif
-
-#ifndef MG_ENABLE_COAP
-#define MG_ENABLE_COAP 0
-#endif
-
-#ifndef MG_ENABLE_DEBUG
-#define MG_ENABLE_DEBUG 0
-#endif
-
-#ifndef MG_ENABLE_DIRECTORY_LISTING
-#define MG_ENABLE_DIRECTORY_LISTING 0
-#endif
-
-#ifndef MG_ENABLE_DNS
-#define MG_ENABLE_DNS 1
-#endif
-
-#ifndef MG_ENABLE_DNS_SERVER
-#define MG_ENABLE_DNS_SERVER 0
-#endif
-
-#ifndef MG_ENABLE_FAKE_DAVLOCK
-#define MG_ENABLE_FAKE_DAVLOCK 0
-#endif
-
-#ifndef MG_ENABLE_FILESYSTEM
-#define MG_ENABLE_FILESYSTEM 0
-#endif
-
-#ifndef MG_ENABLE_GETADDRINFO
-#define MG_ENABLE_GETADDRINFO 0
-#endif
-
-#ifndef MG_ENABLE_HEXDUMP
-#define MG_ENABLE_HEXDUMP CS_ENABLE_STDIO
-#endif
-
-#ifndef MG_ENABLE_HTTP
-#define MG_ENABLE_HTTP 1
-#endif
-
-#ifndef MG_ENABLE_HTTP_CGI
-#define MG_ENABLE_HTTP_CGI 0
-#endif
-
-#ifndef MG_ENABLE_HTTP_SSI
-#define MG_ENABLE_HTTP_SSI MG_ENABLE_FILESYSTEM
-#endif
-
-#ifndef MG_ENABLE_HTTP_SSI_EXEC
-#define MG_ENABLE_HTTP_SSI_EXEC 0
-#endif
-
-#ifndef MG_ENABLE_HTTP_STREAMING_MULTIPART
-#define MG_ENABLE_HTTP_STREAMING_MULTIPART 0
-#endif
-
-#ifndef MG_ENABLE_HTTP_WEBDAV
-#define MG_ENABLE_HTTP_WEBDAV 0
-#endif
-
-#ifndef MG_ENABLE_HTTP_WEBSOCKET
-#define MG_ENABLE_HTTP_WEBSOCKET MG_ENABLE_HTTP
-#endif
-
-#ifndef MG_ENABLE_IPV6
-#define MG_ENABLE_IPV6 0
-#endif
-
-#ifndef MG_ENABLE_MQTT
-#define MG_ENABLE_MQTT 1
-#endif
-
-#ifndef MG_ENABLE_SOCKS
-#define MG_ENABLE_SOCKS 0
-#endif
-
-#ifndef MG_ENABLE_MQTT_BROKER
-#define MG_ENABLE_MQTT_BROKER 0
-#endif
-
-#ifndef MG_ENABLE_SSL
-#define MG_ENABLE_SSL 0
-#endif
-
-#ifndef MG_ENABLE_SYNC_RESOLVER
-#define MG_ENABLE_SYNC_RESOLVER 0
-#endif
-
-#ifndef MG_ENABLE_STDIO
-#define MG_ENABLE_STDIO CS_ENABLE_STDIO
-#endif
-
-#ifndef MG_NET_IF
-#define MG_NET_IF MG_NET_IF_SOCKET
-#endif
-
-#ifndef MG_SSL_IF
-#define MG_SSL_IF MG_SSL_IF_OPENSSL
-#endif
-
-#ifndef MG_ENABLE_THREADS /* ifdef-ok */
-#ifdef _WIN32
-#define MG_ENABLE_THREADS 1
-#else
-#define MG_ENABLE_THREADS 0
-#endif
-#endif
-
-#if MG_ENABLE_DEBUG && !defined(CS_ENABLE_DEBUG)
-#define CS_ENABLE_DEBUG 1
-#endif
-
-/* MQTT broker requires MQTT */
-#if MG_ENABLE_MQTT_BROKER && !MG_ENABLE_MQTT
-#undef MG_ENABLE_MQTT
-#define MG_ENABLE_MQTT 1
-#endif
-
-#ifndef MG_ENABLE_HTTP_URL_REWRITES
-#define MG_ENABLE_HTTP_URL_REWRITES \
-  (CS_PLATFORM == CS_P_WINDOWS || CS_PLATFORM == CS_P_UNIX)
-#endif
-
-#ifndef MG_ENABLE_SNTP
-#define MG_ENABLE_SNTP 0
-#endif
-
-#ifndef MG_ENABLE_EXTRA_ERRORS_DESC
-#define MG_ENABLE_EXTRA_ERRORS_DESC 0
-#endif
-
-#ifndef MG_ENABLE_CALLBACK_USERDATA
-#define MG_ENABLE_CALLBACK_USERDATA 0
-#endif
-
-#if MG_ENABLE_CALLBACK_USERDATA
-#define MG_UD_ARG(ud) , ud
-#define MG_CB(cb, ud) cb, ud
-#else
-#define MG_UD_ARG(ud)
-#define MG_CB(cb, ud) cb
-#endif
-
-#endif /* CS_MONGOOSE_SRC_FEATURES_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_net_if.h"
-#endif
-
-#ifndef CS_MONGOOSE_SRC_NET_IF_H_
-#define CS_MONGOOSE_SRC_NET_IF_H_
-
-/* Amalgamated: #include "common/platform.h" */
-
-/*
- * Internal async networking core interface.
- * Consists of calls made by the core, which should not block,
- * and callbacks back into the core ("..._cb").
- * Callbacks may (will) cause methods to be invoked from within,
- * but methods are not allowed to invoke callbacks inline.
- *
- * Implementation must ensure that only one callback is invoked at any time.
- */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#define MG_MAIN_IFACE 0
-
-struct mg_mgr;
-struct mg_connection;
-union socket_address;
-
-struct mg_iface_vtable;
-
-struct mg_iface {
-  struct mg_mgr *mgr;
-  void *data; /* Implementation-specific data */
-  const struct mg_iface_vtable *vtable;
-};
-
-struct mg_iface_vtable {
-  void (*init)(struct mg_iface *iface);
-  void (*free)(struct mg_iface *iface);
-  void (*add_conn)(struct mg_connection *nc);
-  void (*remove_conn)(struct mg_connection *nc);
-  time_t (*poll)(struct mg_iface *iface, int timeout_ms);
-
-  /* Set up a listening TCP socket on a given address. rv = 0 -> ok. */
-  int (*listen_tcp)(struct mg_connection *nc, union socket_address *sa);
-  /* Request that a "listening" UDP socket be created. */
-  int (*listen_udp)(struct mg_connection *nc, union socket_address *sa);
-
-  /* Request that a TCP connection is made to the specified address. */
-  void (*connect_tcp)(struct mg_connection *nc, const union socket_address *sa);
-  /* Open a UDP socket. Doesn't actually connect anything. */
-  void (*connect_udp)(struct mg_connection *nc);
-
-  /* Send functions for TCP and UDP. Sent data is copied before return. */
-  int (*tcp_send)(struct mg_connection *nc, const void *buf, size_t len);
-  int (*udp_send)(struct mg_connection *nc, const void *buf, size_t len);
-
-  int (*tcp_recv)(struct mg_connection *nc, void *buf, size_t len);
-  int (*udp_recv)(struct mg_connection *nc, void *buf, size_t len,
-                  union socket_address *sa, size_t *sa_len);
-
-  /* Perform interface-related connection initialization. Return 1 on ok. */
-  int (*create_conn)(struct mg_connection *nc);
-  /* Perform interface-related cleanup on connection before destruction. */
-  void (*destroy_conn)(struct mg_connection *nc);
-
-  /* Associate a socket to a connection. */
-  void (*sock_set)(struct mg_connection *nc, sock_t sock);
-
-  /* Put connection's address into *sa, local (remote = 0) or remote. */
-  void (*get_conn_addr)(struct mg_connection *nc, int remote,
-                        union socket_address *sa);
-};
-
-extern const struct mg_iface_vtable *mg_ifaces[];
-extern int mg_num_ifaces;
-
-/* Creates a new interface instance. */
-struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable,
-                                    struct mg_mgr *mgr);
-
-/*
- * Find an interface with a given implementation. The search is started from
- * interface `from`, exclusive. Returns NULL if none is found.
- */
-struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
-                               const struct mg_iface_vtable *vtable,
-                               struct mg_iface *from);
-/*
- * Deliver a new TCP connection. Returns NULL in case on error (unable to
- * create connection, in which case interface state should be discarded.
- * This is phase 1 of the two-phase process - MG_EV_ACCEPT will be delivered
- * when mg_if_accept_tcp_cb is invoked.
- */
-struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc);
-void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
-                         size_t sa_len);
-
-/* Callback invoked by connect methods. err = 0 -> ok, != 0 -> error. */
-void mg_if_connect_cb(struct mg_connection *nc, int err);
-/*
- * Callback that tells the core that data can be received.
- * Core will use tcp/udp_recv to retrieve the data.
- */
-void mg_if_can_recv_cb(struct mg_connection *nc);
-void mg_if_can_send_cb(struct mg_connection *nc);
-/*
- * Receive callback.
- * buf must be heap-allocated and ownership is transferred to the core.
- */
-void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
-                       union socket_address *sa, size_t sa_len);
-
-/* void mg_if_close_conn(struct mg_connection *nc); */
-
-/* Deliver a POLL event to the connection. */
-int mg_if_poll(struct mg_connection *nc, double now);
-
-/*
- * Return minimal timer value amoung connections in the manager.
- * Returns 0 if there aren't any timers.
- */
-double mg_mgr_min_timer(const struct mg_mgr *mgr);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_MONGOOSE_SRC_NET_IF_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_ssl_if.h"
-#endif
-
-#ifndef CS_MONGOOSE_SRC_SSL_IF_H_
-#define CS_MONGOOSE_SRC_SSL_IF_H_
-
-#if MG_ENABLE_SSL
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-struct mg_ssl_if_ctx;
-struct mg_connection;
-
-void mg_ssl_if_init(void);
-
-enum mg_ssl_if_result {
-  MG_SSL_OK = 0,
-  MG_SSL_WANT_READ = -1,
-  MG_SSL_WANT_WRITE = -2,
-  MG_SSL_ERROR = -3,
-};
-
-struct mg_ssl_if_conn_params {
-  const char *cert;
-  const char *key;
-  const char *ca_cert;
-  const char *server_name;
-  const char *cipher_suites;
-  const char *psk_identity;
-  const char *psk_key;
-};
-
-enum mg_ssl_if_result mg_ssl_if_conn_init(
-    struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
-    const char **err_msg);
-enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
-                                            struct mg_connection *lc);
-void mg_ssl_if_conn_close_notify(struct mg_connection *nc);
-void mg_ssl_if_conn_free(struct mg_connection *nc);
-
-enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc);
-int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size);
-int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* MG_ENABLE_SSL */
-
-#endif /* CS_MONGOOSE_SRC_SSL_IF_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_net.h"
-#endif
-
-/*
- * === Core API: TCP/UDP/SSL
- *
- * NOTE: Mongoose manager is single threaded. It does not protect
- * its data structures by mutexes, therefore all functions that are dealing
- * with a particular event manager should be called from the same thread,
- * with exception of the `mg_broadcast()` function. It is fine to have different
- * event managers handled by different threads.
- */
-
-#ifndef CS_MONGOOSE_SRC_NET_H_
-#define CS_MONGOOSE_SRC_NET_H_
-
-/* Amalgamated: #include "mg_common.h" */
-/* Amalgamated: #include "mg_net_if.h" */
-/* Amalgamated: #include "common/mbuf.h" */
-
-#ifndef MG_VPRINTF_BUFFER_SIZE
-#define MG_VPRINTF_BUFFER_SIZE 100
-#endif
-
-#ifdef MG_USE_READ_WRITE
-#define MG_RECV_FUNC(s, b, l, f) read(s, b, l)
-#define MG_SEND_FUNC(s, b, l, f) write(s, b, l)
-#else
-#define MG_RECV_FUNC(s, b, l, f) recv(s, b, l, f)
-#define MG_SEND_FUNC(s, b, l, f) send(s, b, l, f)
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-union socket_address {
-  struct sockaddr sa;
-  struct sockaddr_in sin;
-#if MG_ENABLE_IPV6
-  struct sockaddr_in6 sin6;
-#else
-  struct sockaddr sin6;
-#endif
-};
-
-struct mg_connection;
-
-/*
- * Callback function (event handler) prototype. Must be defined by the user.
- * Mongoose calls the event handler, passing the events defined below.
- */
-typedef void (*mg_event_handler_t)(struct mg_connection *nc, int ev,
-                                   void *ev_data MG_UD_ARG(void *user_data));
-
-/* Events. Meaning of event parameter (evp) is given in the comment. */
-#define MG_EV_POLL 0    /* Sent to each connection on each mg_mgr_poll() call */
-#define MG_EV_ACCEPT 1  /* New connection accepted. union socket_address * */
-#define MG_EV_CONNECT 2 /* connect() succeeded or failed. int *  */
-#define MG_EV_RECV 3    /* Data has been received. int *num_bytes */
-#define MG_EV_SEND 4    /* Data has been written to a socket. int *num_bytes */
-#define MG_EV_CLOSE 5   /* Connection is closed. NULL */
-#define MG_EV_TIMER 6   /* now >= conn->ev_timer_time. double * */
-
-/*
- * Mongoose event manager.
- */
-struct mg_mgr {
-  struct mg_connection *active_connections;
-#if MG_ENABLE_HEXDUMP
-  const char *hexdump_file; /* Debug hexdump file path */
-#endif
-#if MG_ENABLE_BROADCAST
-  sock_t ctl[2]; /* Socketpair for mg_broadcast() */
-#endif
-  void *user_data; /* User data */
-  int num_ifaces;
-  int num_calls;
-  struct mg_iface **ifaces; /* network interfaces */
-  const char *nameserver;   /* DNS server to use */
-};
-
-/*
- * Mongoose connection.
- */
-struct mg_connection {
-  struct mg_connection *next, *prev; /* mg_mgr::active_connections linkage */
-  struct mg_connection *listener;    /* Set only for accept()-ed connections */
-  struct mg_mgr *mgr;                /* Pointer to containing manager */
-
-  sock_t sock; /* Socket to the remote peer */
-  int err;
-  union socket_address sa; /* Remote peer address */
-  size_t recv_mbuf_limit;  /* Max size of recv buffer */
-  struct mbuf recv_mbuf;   /* Received data */
-  struct mbuf send_mbuf;   /* Data scheduled for sending */
-  time_t last_io_time;     /* Timestamp of the last socket IO */
-  double ev_timer_time;    /* Timestamp of the future MG_EV_TIMER */
-  mg_event_handler_t proto_handler; /* Protocol-specific event handler */
-  void *proto_data;                 /* Protocol-specific data */
-  void (*proto_data_destructor)(void *proto_data);
-  mg_event_handler_t handler; /* Event handler function */
-  void *user_data;            /* User-specific data */
-  union {
-    void *v;
-    /*
-     * the C standard is fussy about fitting function pointers into
-     * void pointers, since some archs might have fat pointers for functions.
-     */
-    mg_event_handler_t f;
-  } priv_1;
-  void *priv_2;
-  void *mgr_data; /* Implementation-specific event manager's data. */
-  struct mg_iface *iface;
-  unsigned long flags;
-/* Flags set by Mongoose */
-#define MG_F_LISTENING (1 << 0)          /* This connection is listening */
-#define MG_F_UDP (1 << 1)                /* This connection is UDP */
-#define MG_F_RESOLVING (1 << 2)          /* Waiting for async resolver */
-#define MG_F_CONNECTING (1 << 3)         /* connect() call in progress */
-#define MG_F_SSL (1 << 4)                /* SSL is enabled on the connection */
-#define MG_F_SSL_HANDSHAKE_DONE (1 << 5) /* SSL hanshake has completed */
-#define MG_F_WANT_READ (1 << 6)          /* SSL specific */
-#define MG_F_WANT_WRITE (1 << 7)         /* SSL specific */
-#define MG_F_IS_WEBSOCKET (1 << 8)       /* Websocket specific */
-#define MG_F_RECV_AND_CLOSE (1 << 9) /* Drain rx and close the connection. */
-
-/* Flags that are settable by user */
-#define MG_F_SEND_AND_CLOSE (1 << 10)      /* Push remaining data and close  */
-#define MG_F_CLOSE_IMMEDIATELY (1 << 11)   /* Disconnect */
-
-/* Flags for protocol handlers */
-#define MG_F_PROTO_1 (1 << 12)
-#define MG_F_PROTO_2 (1 << 13)
-#define MG_F_ENABLE_BROADCAST (1 << 14)    /* Allow broadcast address usage */
-
-/* Flags left for application */
-#define MG_F_USER_1 (1 << 20)
-#define MG_F_USER_2 (1 << 21)
-#define MG_F_USER_3 (1 << 22)
-#define MG_F_USER_4 (1 << 23)
-#define MG_F_USER_5 (1 << 24)
-#define MG_F_USER_6 (1 << 25)
-
-#if MG_ENABLE_SSL
-  void *ssl_if_data; /* SSL library data. */
-#else
-  void *unused_ssl_if_data; /* To keep the size of the structure the same. */
-#endif
-};
-
-/*
- * Initialise Mongoose manager. Side effect: ignores SIGPIPE signal.
- * `mgr->user_data` field will be initialised with a `user_data` parameter.
- * That is an arbitrary pointer, where the user code can associate some data
- * with the particular Mongoose manager. For example, a C++ wrapper class
- * could be written in which case `user_data` can hold a pointer to the
- * class instance.
- */
-void mg_mgr_init(struct mg_mgr *mgr, void *user_data);
-
-/*
- * Optional parameters to `mg_mgr_init_opt()`.
- *
- * If `main_iface` is not NULL, it will be used as the main interface in the
- * default interface set. The pointer will be free'd by `mg_mgr_free`.
- * Otherwise, the main interface will be autodetected based on the current
- * platform.
- *
- * If `num_ifaces` is 0 and `ifaces` is NULL, the default interface set will be
- * used.
- * This is an advanced option, as it requires you to construct a full interface
- * set, including special networking interfaces required by some optional
- * features such as TCP tunneling. Memory backing `ifaces` and each of the
- * `num_ifaces` pointers it contains will be reclaimed by `mg_mgr_free`.
- */
-struct mg_mgr_init_opts {
-  const struct mg_iface_vtable *main_iface;
-  int num_ifaces;
-  const struct mg_iface_vtable **ifaces;
-  const char *nameserver;
-};
-
-/*
- * Like `mg_mgr_init` but with more options.
- *
- * Notably, this allows you to create a manger and choose
- * dynamically which networking interface implementation to use.
- */
-void mg_mgr_init_opt(struct mg_mgr *mgr, void *user_data,
-                     struct mg_mgr_init_opts opts);
-
-/*
- * De-initialises Mongoose manager.
- *
- * Closes and deallocates all active connections.
- */
-void mg_mgr_free(struct mg_mgr *mgr);
-
-/*
- * This function performs the actual IO and must be called in a loop
- * (an event loop). It returns number of user events generated (except POLLs).
- * `milli` is the maximum number of milliseconds to sleep.
- * `mg_mgr_poll()` checks all connections for IO readiness. If at least one
- * of the connections is IO-ready, `mg_mgr_poll()` triggers the respective
- * event handlers and returns.
- */
-int mg_mgr_poll(struct mg_mgr *mgr, int milli);
-
-#if MG_ENABLE_BROADCAST
-/*
- * Passes a message of a given length to all connections.
- *
- * Must be called from a thread that does NOT call `mg_mgr_poll()`.
- * Note that `mg_broadcast()` is the only function
- * that can be, and must be, called from a different (non-IO) thread.
- *
- * `func` callback function will be called by the IO thread for each
- * connection. When called, the event will be `MG_EV_POLL`, and a message will
- * be passed as the `ev_data` pointer. Maximum message size is capped
- * by `MG_CTL_MSG_MESSAGE_SIZE` which is set to 8192 bytes by default.
- */
-void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
-                  size_t len);
-#endif
-
-/*
- * Iterates over all active connections.
- *
- * Returns the next connection from the list
- * of active connections or `NULL` if there are no more connections. Below
- * is the iteration idiom:
- *
- * ```c
- * for (c = mg_next(srv, NULL); c != NULL; c = mg_next(srv, c)) {
- *   // Do something with connection `c`
- * }
- * ```
- */
-struct mg_connection *mg_next(struct mg_mgr *mgr, struct mg_connection *c);
-
-/*
- * Optional parameters to `mg_add_sock_opt()`.
- *
- * `flags` is an initial `struct mg_connection::flags` bitmask to set,
- * see `MG_F_*` flags definitions.
- */
-struct mg_add_sock_opts {
-  void *user_data;           /* Initial value for connection's user_data */
-  unsigned int flags;        /* Initial connection flags */
-  const char **error_string; /* Placeholder for the error string */
-  struct mg_iface *iface;    /* Interface instance */
-};
-
-/*
- * Creates a connection, associates it with the given socket and event handler
- * and adds it to the manager.
- *
- * For more options see the `mg_add_sock_opt` variant.
- */
-struct mg_connection *mg_add_sock(struct mg_mgr *mgr, sock_t sock,
-                                  MG_CB(mg_event_handler_t handler,
-                                        void *user_data));
-
-/*
- * Creates a connection, associates it with the given socket and event handler
- * and adds to the manager.
- *
- * See the `mg_add_sock_opts` structure for a description of the options.
- */
-struct mg_connection *mg_add_sock_opt(struct mg_mgr *mgr, sock_t sock,
-                                      MG_CB(mg_event_handler_t handler,
-                                            void *user_data),
-                                      struct mg_add_sock_opts opts);
-
-/*
- * Optional parameters to `mg_bind_opt()`.
- *
- * `flags` is an initial `struct mg_connection::flags` bitmask to set,
- * see `MG_F_*` flags definitions.
- */
-struct mg_bind_opts {
-  void *user_data;           /* Initial value for connection's user_data */
-  unsigned int flags;        /* Extra connection flags */
-  const char **error_string; /* Placeholder for the error string */
-  struct mg_iface *iface;    /* Interface instance */
-#if MG_ENABLE_SSL
-  /*
-   * SSL settings.
-   *
-   * Server certificate to present to clients or client certificate to
-   * present to tunnel dispatcher (for tunneled connections).
-   */
-  const char *ssl_cert;
-  /* Private key corresponding to the certificate. If ssl_cert is set but
-   * ssl_key is not, ssl_cert is used. */
-  const char *ssl_key;
-  /* CA bundle used to verify client certificates or tunnel dispatchers. */
-  const char *ssl_ca_cert;
-  /* Colon-delimited list of acceptable cipher suites.
-   * Names depend on the library used, for example:
-   *
-   * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL)
-   * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256
-   *   (mbedTLS)
-   *
-   * For OpenSSL the list can be obtained by running "openssl ciphers".
-   * For mbedTLS, names can be found in library/ssl_ciphersuites.c
-   * If NULL, a reasonable default is used.
-   */
-  const char *ssl_cipher_suites;
-#endif
-};
-
-/*
- * Creates a listening connection.
- *
- * See `mg_bind_opt` for full documentation.
- */
-struct mg_connection *mg_bind(struct mg_mgr *mgr, const char *address,
-                              MG_CB(mg_event_handler_t handler,
-                                    void *user_data));
-/*
- * Creates a listening connection.
- *
- * The `address` parameter specifies which address to bind to. It's format is
- * the same as for the `mg_connect()` call, where `HOST` part is optional.
- * `address` can be just a port number, e.g. `:8000`. To bind to a specific
- * interface, an IP address can be specified, e.g. `1.2.3.4:8000`. By default,
- * a TCP connection is created. To create UDP connection, prepend `udp://`
- * prefix, e.g. `udp://:8000`. To summarize, `address` parameter has following
- * format: `[PROTO://][IP_ADDRESS]:PORT`, where `PROTO` could be `tcp` or
- * `udp`.
- *
- * See the `mg_bind_opts` structure for a description of the optional
- * parameters.
- *
- * Returns a new listening connection or `NULL` on error.
- * NOTE: The connection remains owned by the manager, do not free().
- */
-struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
-                                  MG_CB(mg_event_handler_t handler,
-                                        void *user_data),
-                                  struct mg_bind_opts opts);
-
-/* Optional parameters to `mg_connect_opt()` */
-struct mg_connect_opts {
-  void *user_data;           /* Initial value for connection's user_data */
-  unsigned int flags;        /* Extra connection flags */
-  const char **error_string; /* Placeholder for the error string */
-  struct mg_iface *iface;    /* Interface instance */
-  const char *nameserver;    /* DNS server to use, NULL for default */
-#if MG_ENABLE_SSL
-  /*
-   * SSL settings.
-   * Client certificate to present to the server.
-   */
-  const char *ssl_cert;
-  /*
-   * Private key corresponding to the certificate.
-   * If ssl_cert is set but ssl_key is not, ssl_cert is used.
-   */
-  const char *ssl_key;
-  /*
-   * Verify server certificate using this CA bundle. If set to "*", then SSL
-   * is enabled but no cert verification is performed.
-   */
-  const char *ssl_ca_cert;
-  /* Colon-delimited list of acceptable cipher suites.
-   * Names depend on the library used, for example:
-   *
-   * ECDH-ECDSA-AES128-GCM-SHA256:DHE-RSA-AES128-SHA256 (OpenSSL)
-   * TLS-ECDH-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-128-GCM-SHA256
-   *   (mbedTLS)
-   *
-   * For OpenSSL the list can be obtained by running "openssl ciphers".
-   * For mbedTLS, names can be found in library/ssl_ciphersuites.c
-   * If NULL, a reasonable default is used.
-   */
-  const char *ssl_cipher_suites;
-  /*
-   * Server name verification. If ssl_ca_cert is set and the certificate has
-   * passed verification, its subject will be verified against this string.
-   * By default (if ssl_server_name is NULL) hostname part of the address will
-   * be used. Wildcard matching is supported. A special value of "*" disables
-   * name verification.
-   */
-  const char *ssl_server_name;
-  /*
-   * PSK identity and key. Identity is a NUL-terminated string and key is a hex
-   * string. Key must be either 16 or 32 bytes (32 or 64 hex digits) for AES-128
-   * or AES-256 respectively.
-   * Note: Default list of cipher suites does not include PSK suites, if you
-   * want to use PSK you will need to set ssl_cipher_suites as well.
-   */
-  const char *ssl_psk_identity;
-  const char *ssl_psk_key;
-#endif
-};
-
-/*
- * Connects to a remote host.
- *
- * See `mg_connect_opt()` for full documentation.
- */
-struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
-                                 MG_CB(mg_event_handler_t handler,
-                                       void *user_data));
-
-/*
- * Connects to a remote host.
- *
- * The `address` format is `[PROTO://]HOST:PORT`. `PROTO` could be `tcp` or
- * `udp`. `HOST` could be an IP address,
- * IPv6 address (if Mongoose is compiled with `-DMG_ENABLE_IPV6`) or a host
- * name. If `HOST` is a name, Mongoose will resolve it asynchronously. Examples
- * of valid addresses: `google.com:80`, `udp://1.2.3.4:53`, `10.0.0.1:443`,
- * `[::1]:80`
- *
- * See the `mg_connect_opts` structure for a description of the optional
- * parameters.
- *
- * Returns a new outbound connection or `NULL` on error.
- *
- * NOTE: The connection remains owned by the manager, do not free().
- *
- * NOTE: To enable IPv6 addresses `-DMG_ENABLE_IPV6` should be specified
- * in the compilation flags.
- *
- * NOTE: The new connection will receive `MG_EV_CONNECT` as its first event
- * which will report the connect success status.
- * If the asynchronous resolution fails or the `connect()` syscall fails for
- * whatever reason (e.g. with `ECONNREFUSED` or `ENETUNREACH`), then
- * `MG_EV_CONNECT` event will report failure. Code example below:
- *
- * ```c
- * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
- *   int connect_status;
- *
- *   switch (ev) {
- *     case MG_EV_CONNECT:
- *       connect_status = * (int *) ev_data;
- *       if (connect_status == 0) {
- *         // Success
- *       } else  {
- *         // Error
- *         printf("connect() error: %s\n", strerror(connect_status));
- *       }
- *       break;
- *     ...
- *   }
- * }
- *
- *   ...
- *   mg_connect(mgr, "my_site.com:80", ev_handler);
- * ```
- */
-struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
-                                     MG_CB(mg_event_handler_t handler,
-                                           void *user_data),
-                                     struct mg_connect_opts opts);
-
-#if MG_ENABLE_SSL && MG_NET_IF != MG_NET_IF_SIMPLELINK
-/*
- * Note: This function is deprecated. Please, use SSL options in
- * mg_connect_opt.
- *
- * Enables SSL for a given connection.
- * `cert` is a server certificate file name for a listening connection
- * or a client certificate file name for an outgoing connection.
- * The certificate files must be in PEM format. The server certificate file
- * must contain a certificate, concatenated with a private key, optionally
- * concatenated with DH parameters.
- * `ca_cert` is a CA certificate or NULL if peer verification is not
- * required.
- * Return: NULL on success or error message on error.
- */
-const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
-                       const char *ca_cert);
-#endif
-
-/*
- * Sends data to the connection.
- *
- * Note that sending functions do not actually push data to the socket.
- * They just append data to the output buffer. MG_EV_SEND will be delivered when
- * the data has actually been pushed out.
- */
-void mg_send(struct mg_connection *, const void *buf, int len);
-
-/* Enables format string warnings for mg_printf */
-#if defined(__GNUC__)
-__attribute__((format(printf, 2, 3)))
-#endif
-/* don't separate from mg_printf declaration */
-
-/*
- * Sends `printf`-style formatted data to the connection.
- *
- * See `mg_send` for more details on send semantics.
- */
-int mg_printf(struct mg_connection *, const char *fmt, ...);
-
-/* Same as `mg_printf()`, but takes `va_list ap` as an argument. */
-int mg_vprintf(struct mg_connection *, const char *fmt, va_list ap);
-
-/*
- * Creates a socket pair.
- * `sock_type` can be either `SOCK_STREAM` or `SOCK_DGRAM`.
- * Returns 0 on failure and 1 on success.
- */
-int mg_socketpair(sock_t[2], int sock_type);
-
-#if MG_ENABLE_SYNC_RESOLVER
-/*
- * Convert domain name into IP address.
- *
- * This is a utility function. If compilation flags have
- * `-DMG_ENABLE_GETADDRINFO`, then `getaddrinfo()` call is used for name
- * resolution. Otherwise, `gethostbyname()` is used.
- *
- * CAUTION: this function can block.
- * Return 1 on success, 0 on failure.
- */
-int mg_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len);
-#endif
-
-/*
- * Verify given IP address against the ACL.
- *
- * `remote_ip` - an IPv4 address to check, in host byte order
- * `acl` - a comma separated list of IP subnets: `x.x.x.x/x` or `x.x.x.x`.
- * Each subnet is
- * prepended by either a - or a + sign. A plus sign means allow, where a
- * minus sign means deny. If a subnet mask is omitted, such as `-1.2.3.4`,
- * it means that only that single IP address is denied.
- * Subnet masks may vary from 0 to 32, inclusive. The default setting
- * is to allow all access. On each request the full list is traversed,
- * and the last match wins. Example:
- *
- * `-0.0.0.0/0,+192.168/16` - deny all accesses, only allow 192.168/16 subnet
- *
- * To learn more about subnet masks, see this
- * link:https://en.wikipedia.org/wiki/Subnetwork[Wikipedia page on Subnetwork].
- *
- * Returns -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
- */
-int mg_check_ip_acl(const char *acl, uint32_t remote_ip);
-
-/*
- * Schedules an MG_EV_TIMER event to be delivered at `timestamp` time.
- * `timestamp` is UNIX time (the number of seconds since Epoch). It is
- * `double` instead of `time_t` to allow for sub-second precision.
- * Returns the old timer value.
- *
- * Example: set the connect timeout to 1.5 seconds:
- *
- * ```
- *  c = mg_connect(&mgr, "cesanta.com", ev_handler);
- *  mg_set_timer(c, mg_time() + 1.5);
- *  ...
- *
- *  void ev_handler(struct mg_connection *c, int ev, void *ev_data) {
- *  switch (ev) {
- *    case MG_EV_CONNECT:
- *      mg_set_timer(c, 0);  // Clear connect timer
- *      break;
- *    case MG_EV_TIMER:
- *      log("Connect timeout");
- *      c->flags |= MG_F_CLOSE_IMMEDIATELY;
- *      break;
- * ```
- */
-double mg_set_timer(struct mg_connection *c, double timestamp);
-
-/*
- * A sub-second precision version of time().
- */
-double mg_time(void);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_MONGOOSE_SRC_NET_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_uri.h"
-#endif
-
-/*
- * === URI
- */
-
-#ifndef CS_MONGOOSE_SRC_URI_H_
-#define CS_MONGOOSE_SRC_URI_H_
-
-/* Amalgamated: #include "mg_net.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-/*
- * Parses an URI and fills string chunks with locations of the respective
- * uri components within the input uri string. NULL pointers will be
- * ignored.
- *
- * General syntax:
- *
- *     [scheme://[user_info@]]host[:port][/path][?query][#fragment]
- *
- * Example:
- *
- *     foo.com:80
- *     tcp://foo.com:1234
- *     http://foo.com:80/bar?baz=1
- *     https://user:pw@foo.com:443/blah
- *
- * `path` will include the leading slash. `query` won't include the leading `?`.
- * `host` can contain embedded colons if surrounded by square brackets in order
- * to support IPv6 literal addresses.
- *
- *
- * Returns 0 on success, -1 on error.
- */
-int mg_parse_uri(const struct mg_str uri, struct mg_str *scheme,
-                 struct mg_str *user_info, struct mg_str *host,
-                 unsigned int *port, struct mg_str *path, struct mg_str *query,
-                 struct mg_str *fragment);
-
-/*
- * Assemble URI from parts. Any of the inputs can be NULL or zero-length mg_str.
- *
- * If normalize_path is true, path is normalized by resolving relative refs.
- *
- * Result is a heap-allocated string (uri->p must be free()d after use).
- *
- * Returns 0 on success, -1 on error.
- */
-int mg_assemble_uri(const struct mg_str *scheme, const struct mg_str *user_info,
-                    const struct mg_str *host, unsigned int port,
-                    const struct mg_str *path, const struct mg_str *query,
-                    const struct mg_str *fragment, int normalize_path,
-                    struct mg_str *uri);
-
-int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-#endif /* CS_MONGOOSE_SRC_URI_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_util.h"
-#endif
-
-/*
- * === Utility API
- */
-
-#ifndef CS_MONGOOSE_SRC_UTIL_H_
-#define CS_MONGOOSE_SRC_UTIL_H_
-
-#include <stdio.h>
-
-/* Amalgamated: #include "mg_common.h" */
-/* Amalgamated: #include "mg_net_if.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#ifndef MG_MAX_PATH
-#ifdef PATH_MAX
-#define MG_MAX_PATH PATH_MAX
-#else
-#define MG_MAX_PATH 256
-#endif
-#endif
-
-/*
- * Fetches substring from input string `s`, `end` into `v`.
- * Skips initial delimiter characters. Records first non-delimiter character
- * at the beginning of substring `v`. Then scans the rest of the string
- * until a delimiter character or end-of-string is found.
- * `delimiters` is a 0-terminated string containing delimiter characters.
- * Either one of `delimiters` or `end_string` terminates the search.
- * Returns an `s` pointer, advanced forward where parsing has stopped.
- */
-const char *mg_skip(const char *s, const char *end_string,
-                    const char *delimiters, struct mg_str *v);
-
-/*
- * Decodes base64-encoded string `s`, `len` into the destination `dst`.
- * The destination has to have enough space to hold the decoded buffer.
- * Decoding stops either when all strings have been decoded or invalid an
- * character appeared.
- * Destination is '\0'-terminated.
- * Returns the number of decoded characters. On success, that should be equal
- * to `len`. On error (invalid character) the return value is smaller then
- * `len`.
- */
-int mg_base64_decode(const unsigned char *s, int len, char *dst);
-
-/*
- * Base64-encode chunk of memory `src`, `src_len` into the destination `dst`.
- * Destination has to have enough space to hold encoded buffer.
- * Destination is '\0'-terminated.
- */
-void mg_base64_encode(const unsigned char *src, int src_len, char *dst);
-
-#if MG_ENABLE_FILESYSTEM
-/*
- * Performs a 64-bit `stat()` call against a given file.
- *
- * `path` should be UTF8 encoded.
- *
- * Return value is the same as for `stat()` syscall.
- */
-int mg_stat(const char *path, cs_stat_t *st);
-
-/*
- * Opens the given file and returns a file stream.
- *
- * `path` and `mode` should be UTF8 encoded.
- *
- * Return value is the same as for the `fopen()` call.
- */
-FILE *mg_fopen(const char *path, const char *mode);
-
-/*
- * Opens the given file and returns a file stream.
- *
- * `path` should be UTF8 encoded.
- *
- * Return value is the same as for the `open()` syscall.
- */
-int mg_open(const char *path, int flag, int mode);
-
-/*
- * Reads data from the given file stream.
- *
- * Return value is a number of bytes readen.
- */
-size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f);
-
-/*
- * Writes data to the given file stream.
- *
- * Return value is a number of bytes wtitten.
- */
-size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f);
-
-#endif /* MG_ENABLE_FILESYSTEM */
-
-#if MG_ENABLE_THREADS
-/*
- * Starts a new detached thread.
- * Arguments and semantics are the same as pthead's `pthread_create()`.
- * `thread_func` is a thread function, `thread_func_param` is a parameter
- * that is passed to the thread function.
- */
-void *mg_start_thread(void *(*thread_func)(void *), void *thread_func_param);
-#endif
-
-void mg_set_close_on_exec(sock_t);
-
-#define MG_SOCK_STRINGIFY_IP 1
-#define MG_SOCK_STRINGIFY_PORT 2
-#define MG_SOCK_STRINGIFY_REMOTE 4
-/*
- * Converts a connection's local or remote address into string.
- *
- * The `flags` parameter is a bit mask that controls the behaviour,
- * see `MG_SOCK_STRINGIFY_*` definitions.
- *
- * - MG_SOCK_STRINGIFY_IP - print IP address
- * - MG_SOCK_STRINGIFY_PORT - print port number
- * - MG_SOCK_STRINGIFY_REMOTE - print remote peer's IP/port, not local address
- *
- * If both port number and IP address are printed, they are separated by `:`.
- * If compiled with `-DMG_ENABLE_IPV6`, IPv6 addresses are supported.
- * Return length of the stringified address.
- */
-int mg_conn_addr_to_str(struct mg_connection *c, char *buf, size_t len,
-                        int flags);
-#if MG_NET_IF == MG_NET_IF_SOCKET
-/* Legacy interface. */
-void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
-#endif
-
-/*
- * Convert the socket's address into string.
- *
- * `flags` is MG_SOCK_STRINGIFY_IP and/or MG_SOCK_STRINGIFY_PORT.
- */
-int mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
-                        int flags);
-
-#if MG_ENABLE_HEXDUMP
-/*
- * Generates a human-readable hexdump of memory chunk.
- *
- * Takes a memory buffer `buf` of length `len` and creates a hex dump of that
- * buffer in `dst`. The generated output is a-la hexdump(1).
- * Returns the length of generated string, excluding terminating `\0`. If
- * returned length is bigger than `dst_len`, the overflow bytes are discarded.
- */
-int mg_hexdump(const void *buf, int len, char *dst, int dst_len);
-
-/* Same as mg_hexdump, but with output going to file instead of a buffer. */
-void mg_hexdumpf(FILE *fp, const void *buf, int len);
-
-/*
- * Generates human-readable hexdump of the data sent or received by the
- * connection. `path` is a file name where hexdump should be written.
- * `num_bytes` is a number of bytes sent/received. `ev` is one of the `MG_*`
- * events sent to an event handler. This function is supposed to be called from
- * the event handler.
- */
-void mg_hexdump_connection(struct mg_connection *nc, const char *path,
-                           const void *buf, int num_bytes, int ev);
-#endif
-
-/*
- * Returns true if target platform is big endian.
- */
-int mg_is_big_endian(void);
-
-/*
- * Use with cs_base64_init/update/finish in order to write out base64 in chunks.
- */
-void mg_mbuf_append_base64_putc(char ch, void *user_data);
-
-/*
- * Encode `len` bytes starting at `data` as base64 and append them to an mbuf.
- */
-void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len);
-
-/*
- * Generate a Basic Auth header and appends it to buf.
- * If pass is NULL, then user is expected to contain the credentials pair
- * already encoded as `user:pass`.
- */
-void mg_basic_auth_header(const struct mg_str user, const struct mg_str pass,
-                          struct mbuf *buf);
-
-/*
- * URL-escape the specified string.
- * All characters acept letters, numbers and characters listed in
- * `safe` are escaped. If `hex_upper`is true, `A-F` are used for hex digits.
- * Input need not be NUL-terminated, but the returned string is.
- * Returned string is heap-allocated and must be free()'d.
- */
-#define MG_URL_ENCODE_F_SPACE_AS_PLUS (1 << 0)
-#define MG_URL_ENCODE_F_UPPERCASE_HEX (1 << 1)
-struct mg_str mg_url_encode_opt(const struct mg_str src,
-                                const struct mg_str safe, unsigned int flags);
-
-/* Same as `mg_url_encode_opt(src, "._-$,;~()/", 0)`. */
-struct mg_str mg_url_encode(const struct mg_str src);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-#endif /* CS_MONGOOSE_SRC_UTIL_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_http.h"
-#endif
-
-/*
- * === Common API reference
- */
-
-#ifndef CS_MONGOOSE_SRC_HTTP_H_
-#define CS_MONGOOSE_SRC_HTTP_H_
-
-#if MG_ENABLE_HTTP
-
-/* Amalgamated: #include "common/mg_str.h" */
-/* Amalgamated: #include "mg_net.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#ifndef MG_MAX_HTTP_HEADERS
-#define MG_MAX_HTTP_HEADERS 20
-#endif
-
-#ifndef MG_MAX_HTTP_REQUEST_SIZE
-#define MG_MAX_HTTP_REQUEST_SIZE 1024
-#endif
-
-#ifndef MG_MAX_HTTP_SEND_MBUF
-#define MG_MAX_HTTP_SEND_MBUF 1024
-#endif
-
-#ifndef MG_CGI_ENVIRONMENT_SIZE
-#define MG_CGI_ENVIRONMENT_SIZE 8192
-#endif
-
-/* HTTP message */
-struct http_message {
-  struct mg_str message; /* Whole message: request line + headers + body */
-  struct mg_str body;    /* Message body. 0-length for requests with no body */
-
-  /* HTTP Request line (or HTTP response line) */
-  struct mg_str method; /* "GET" */
-  struct mg_str uri;    /* "/my_file.html" */
-  struct mg_str proto;  /* "HTTP/1.1" -- for both request and response */
-
-  /* For responses, code and response status message are set */
-  int resp_code;
-  struct mg_str resp_status_msg;
-
-  /*
-   * Query-string part of the URI. For example, for HTTP request
-   *    GET /foo/bar?param1=val1&param2=val2
-   *    |    uri    |     query_string     |
-   *
-   * Note that question mark character doesn't belong neither to the uri,
-   * nor to the query_string
-   */
-  struct mg_str query_string;
-
-  /* Headers */
-  struct mg_str header_names[MG_MAX_HTTP_HEADERS];
-  struct mg_str header_values[MG_MAX_HTTP_HEADERS];
-
-  /*
-   * Value of the Content-Length header if present,
-   * otherwise MG_HTTP_CONTENT_LENGTH_UNKNOWN.
-   */
-  size_t content_length;
-};
-
-#define MG_HTTP_CONTENT_LENGTH_UNKNOWN ((size_t) -1)
-
-#if MG_ENABLE_HTTP_WEBSOCKET
-/* WebSocket message */
-struct websocket_message {
-  unsigned char *data;
-  size_t size;
-  unsigned char flags;
-};
-#endif
-
-/* HTTP multipart part */
-struct mg_http_multipart_part {
-  const char *file_name;
-  const char *var_name;
-  struct mg_str data;
-  int status; /* <0 on error */
-  void *user_data;
-  /*
-   * User handler can indicate how much of the data was consumed
-   * by setting this variable. By default, it is assumed that all
-   * data has been consumed by the handler.
-   * If not all data was consumed, user's handler will be invoked again later
-   * with the remainder.
-   */
-  size_t num_data_consumed;
-};
-
-/* SSI call context */
-struct mg_ssi_call_ctx {
-  struct http_message *req; /* The request being processed. */
-  struct mg_str file;       /* Filesystem path of the file being processed. */
-  struct mg_str arg; /* The argument passed to the tag: <!-- call arg -->. */
-};
-
-/* HTTP and websocket events. void *ev_data is described in a comment. */
-#define MG_EV_HTTP_REQUEST 100 /* struct http_message * */
-#define MG_EV_HTTP_REPLY 101   /* struct http_message * */
-#define MG_EV_HTTP_CHUNK 102   /* struct http_message * */
-#define MG_EV_SSI_CALL 105     /* char * */
-#define MG_EV_SSI_CALL_CTX 106 /* struct mg_ssi_call_ctx * */
-
-#if MG_ENABLE_HTTP_WEBSOCKET
-#define MG_EV_WEBSOCKET_HANDSHAKE_REQUEST 111 /* struct http_message * */
-#define MG_EV_WEBSOCKET_HANDSHAKE_DONE 112    /* struct http_message * */
-#define MG_EV_WEBSOCKET_FRAME 113             /* struct websocket_message * */
-#define MG_EV_WEBSOCKET_CONTROL_FRAME 114     /* struct websocket_message * */
-#endif
-
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-#define MG_EV_HTTP_MULTIPART_REQUEST 121 /* struct http_message */
-#define MG_EV_HTTP_PART_BEGIN 122        /* struct mg_http_multipart_part */
-#define MG_EV_HTTP_PART_DATA 123         /* struct mg_http_multipart_part */
-#define MG_EV_HTTP_PART_END 124          /* struct mg_http_multipart_part */
-/* struct mg_http_multipart_part */
-#define MG_EV_HTTP_MULTIPART_REQUEST_END 125
-#endif
-
-#define MG_F_WEBSOCKET_NO_DEFRAG MG_F_PROTO_1
-#define MG_F_DELETE_CHUNK MG_F_PROTO_2
-
-/*
- * Attaches a built-in HTTP event handler to the given connection.
- * The user-defined event handler will receive following extra events:
- *
- * - MG_EV_HTTP_REQUEST: HTTP request has arrived. Parsed HTTP request
- *  is passed as
- *   `struct http_message` through the handler's `void *ev_data` pointer.
- * - MG_EV_HTTP_REPLY: The HTTP reply has arrived. The parsed HTTP reply is
- *   passed as `struct http_message` through the handler's `void *ev_data`
- *   pointer.
- * - MG_EV_HTTP_CHUNK: The HTTP chunked-encoding chunk has arrived.
- *   The parsed HTTP reply is passed as `struct http_message` through the
- *   handler's `void *ev_data` pointer. `http_message::body` would contain
- *   incomplete, reassembled HTTP body.
- *   It will grow with every new chunk that arrives, and it can
- *   potentially consume a lot of memory. An event handler may process
- *   the body as chunks are coming, and signal Mongoose to delete processed
- *   body by setting `MG_F_DELETE_CHUNK` in `mg_connection::flags`. When
- *   the last zero chunk is received,
- *   Mongoose sends `MG_EV_HTTP_REPLY` event with
- *   full reassembled body (if handler did not signal to delete chunks) or
- *   with empty body (if handler did signal to delete chunks).
- * - MG_EV_WEBSOCKET_HANDSHAKE_REQUEST: server has received the WebSocket
- *   handshake request. `ev_data` contains parsed HTTP request.
- * - MG_EV_WEBSOCKET_HANDSHAKE_DONE: server has completed the WebSocket
- *   handshake. `ev_data` is a `struct http_message` containing the
- *   client's request (server mode) or server's response (client).
- *   In client mode handler can examine `resp_code`, which should be 101.
- * - MG_EV_WEBSOCKET_FRAME: new WebSocket frame has arrived. `ev_data` is
- *   `struct websocket_message *`
- *
- * When compiled with MG_ENABLE_HTTP_STREAMING_MULTIPART, Mongoose parses
- * multipart requests and splits them into separate events:
- * - MG_EV_HTTP_MULTIPART_REQUEST: Start of the request.
- *   This event is sent before body is parsed. After this, the user
- *   should expect a sequence of PART_BEGIN/DATA/END requests.
- *   This is also the last time when headers and other request fields are
- *   accessible.
- * - MG_EV_HTTP_PART_BEGIN: Start of a part of a multipart message.
- *   Argument: mg_http_multipart_part with var_name and file_name set
- *   (if present). No data is passed in this message.
- * - MG_EV_HTTP_PART_DATA: new portion of data from the multipart message.
- *   Argument: mg_http_multipart_part. var_name and file_name are preserved,
- *   data is available in mg_http_multipart_part.data.
- * - MG_EV_HTTP_PART_END: End of the current part. var_name, file_name are
- *   the same, no data in the message. If status is 0, then the part is
- *   properly terminated with a boundary, status < 0 means that connection
- *   was terminated.
- * - MG_EV_HTTP_MULTIPART_REQUEST_END: End of the multipart request.
- *   Argument: mg_http_multipart_part, var_name and file_name are NULL,
- *   status = 0 means request was properly closed, < 0 means connection
- *   was terminated (note: in this case both PART_END and REQUEST_END are
- *   delivered).
- */
-void mg_set_protocol_http_websocket(struct mg_connection *nc);
-
-#if MG_ENABLE_HTTP_WEBSOCKET
-/*
- * Send websocket handshake to the server.
- *
- * `nc` must be a valid connection, connected to a server. `uri` is an URI
- * to fetch, extra_headers` is extra HTTP headers to send or `NULL`.
- *
- * This function is intended to be used by websocket client.
- *
- * Note that the Host header is mandatory in HTTP/1.1 and must be
- * included in `extra_headers`. `mg_send_websocket_handshake2` offers
- * a better API for that.
- *
- * Deprecated in favour of `mg_send_websocket_handshake2`
- */
-void mg_send_websocket_handshake(struct mg_connection *nc, const char *uri,
-                                 const char *extra_headers);
-
-/*
- * Send websocket handshake to the server.
- *
- * `nc` must be a valid connection, connected to a server. `uri` is an URI
- * to fetch, `host` goes into the `Host` header, `protocol` goes into the
- * `Sec-WebSocket-Proto` header (NULL to omit), extra_headers` is extra HTTP
- * headers to send or `NULL`.
- *
- * This function is intended to be used by websocket client.
- */
-void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
-                                  const char *host, const char *protocol,
-                                  const char *extra_headers);
-
-/* Like mg_send_websocket_handshake2 but also passes basic auth header */
-void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
-                                  const char *host, const char *protocol,
-                                  const char *extra_headers, const char *user,
-                                  const char *pass);
-
-/* Same as mg_send_websocket_handshake3 but with strings not necessarily
- * NUL-temrinated */
-void mg_send_websocket_handshake3v(struct mg_connection *nc,
-                                   const struct mg_str path,
-                                   const struct mg_str host,
-                                   const struct mg_str protocol,
-                                   const struct mg_str extra_headers,
-                                   const struct mg_str user,
-                                   const struct mg_str pass);
-
-/*
- * Helper function that creates an outbound WebSocket connection.
- *
- * `url` is a URL to connect to. It must be properly URL-encoded, e.g. have
- * no spaces, etc. By default, `mg_connect_ws()` sends Connection and
- * Host headers. `extra_headers` is an extra HTTP header to send, e.g.
- * `"User-Agent: my-app\r\n"`.
- * If `protocol` is not NULL, then a `Sec-WebSocket-Protocol` header is sent.
- *
- * Examples:
- *
- * ```c
- *   nc1 = mg_connect_ws(mgr, ev_handler_1, "ws://echo.websocket.org", NULL,
- *                       NULL);
- *   nc2 = mg_connect_ws(mgr, ev_handler_1, "wss://echo.websocket.org", NULL,
- *                       NULL);
- *   nc3 = mg_connect_ws(mgr, ev_handler_1, "ws://api.cesanta.com",
- *                       "clubby.cesanta.com", NULL);
- * ```
- */
-struct mg_connection *mg_connect_ws(struct mg_mgr *mgr,
-                                    MG_CB(mg_event_handler_t event_handler,
-                                          void *user_data),
-                                    const char *url, const char *protocol,
-                                    const char *extra_headers);
-
-/*
- * Helper function that creates an outbound WebSocket connection
- *
- * Mostly identical to `mg_connect_ws`, but allows to provide extra parameters
- * (for example, SSL parameters)
- */
-struct mg_connection *mg_connect_ws_opt(
-    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
-    struct mg_connect_opts opts, const char *url, const char *protocol,
-    const char *extra_headers);
-
-/*
- * Send WebSocket frame to the remote end.
- *
- * `op_and_flags` specifies the frame's type. It's one of:
- *
- * - WEBSOCKET_OP_CONTINUE
- * - WEBSOCKET_OP_TEXT
- * - WEBSOCKET_OP_BINARY
- * - WEBSOCKET_OP_CLOSE
- * - WEBSOCKET_OP_PING
- * - WEBSOCKET_OP_PONG
- *
- * Orred with one of the flags:
- *
- * - WEBSOCKET_DONT_FIN: Don't set the FIN flag on the frame to be sent.
- *
- * `data` and `data_len` contain frame data.
- */
-void mg_send_websocket_frame(struct mg_connection *nc, int op_and_flags,
-                             const void *data, size_t data_len);
-
-/*
- * Like `mg_send_websocket_frame()`, but composes a single frame from multiple
- * buffers.
- */
-void mg_send_websocket_framev(struct mg_connection *nc, int op_and_flags,
-                              const struct mg_str *strings, int num_strings);
-
-/*
- * Sends WebSocket frame to the remote end.
- *
- * Like `mg_send_websocket_frame()`, but allows to create formatted messages
- * with `printf()`-like semantics.
- */
-void mg_printf_websocket_frame(struct mg_connection *nc, int op_and_flags,
-                               const char *fmt, ...);
-
-/* Websocket opcodes, from http://tools.ietf.org/html/rfc6455 */
-#define WEBSOCKET_OP_CONTINUE 0
-#define WEBSOCKET_OP_TEXT 1
-#define WEBSOCKET_OP_BINARY 2
-#define WEBSOCKET_OP_CLOSE 8
-#define WEBSOCKET_OP_PING 9
-#define WEBSOCKET_OP_PONG 10
-
-/*
- * If set causes the FIN flag to not be set on outbound
- * frames. This enables sending multiple fragments of a single
- * logical message.
- *
- * The WebSocket protocol mandates that if the FIN flag of a data
- * frame is not set, the next frame must be a WEBSOCKET_OP_CONTINUE.
- * The last frame must have the FIN bit set.
- *
- * Note that mongoose will automatically defragment incoming messages,
- * so this flag is used only on outbound messages.
- */
-#define WEBSOCKET_DONT_FIN 0x100
-
-#endif /* MG_ENABLE_HTTP_WEBSOCKET */
-
-/*
- * Decodes a URL-encoded string.
- *
- * Source string is specified by (`src`, `src_len`), and destination is
- * (`dst`, `dst_len`). If `is_form_url_encoded` is non-zero, then
- * `+` character is decoded as a blank space character. This function
- * guarantees to NUL-terminate the destination. If destination is too small,
- * then the source string is partially decoded and `-1` is returned.
- *Otherwise,
- * a length of the decoded string is returned, not counting final NUL.
- */
-int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
-                  int is_form_url_encoded);
-
-extern void mg_hash_md5_v(size_t num_msgs, const uint8_t *msgs[],
-                          const size_t *msg_lens, uint8_t *digest);
-extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
-                           const size_t *msg_lens, uint8_t *digest);
-
-/*
- * Flags for `mg_http_is_authorized()`.
- */
-#define MG_AUTH_FLAG_IS_DIRECTORY (1 << 0)
-#define MG_AUTH_FLAG_IS_GLOBAL_PASS_FILE (1 << 1)
-#define MG_AUTH_FLAG_ALLOW_MISSING_FILE (1 << 2)
-
-/*
- * Checks whether an http request is authorized. `domain` is the authentication
- * realm, `passwords_file` is a htdigest file (can be created e.g. with
- * `htdigest` utility). If either `domain` or `passwords_file` is NULL, this
- * function always returns 1; otherwise checks the authentication in the
- * http request and returns 1 only if there is a match; 0 otherwise.
- */
-int mg_http_is_authorized(struct http_message *hm, struct mg_str path,
-                          const char *domain, const char *passwords_file,
-                          int flags);
-
-/*
- * Sends 401 Unauthorized response.
- */
-void mg_http_send_digest_auth_request(struct mg_connection *c,
-                                      const char *domain);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* MG_ENABLE_HTTP */
-
-#endif /* CS_MONGOOSE_SRC_HTTP_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_http_server.h"
-#endif
-/*
- * === Server API reference
- */
-
-#ifndef CS_MONGOOSE_SRC_HTTP_SERVER_H_
-#define CS_MONGOOSE_SRC_HTTP_SERVER_H_
-
-#if MG_ENABLE_HTTP
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-/*
- * Parses a HTTP message.
- *
- * `is_req` should be set to 1 if parsing a request, 0 if reply.
- *
- * Returns the number of bytes parsed. If HTTP message is
- * incomplete `0` is returned. On parse error, a negative number is returned.
- */
-int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req);
-
-/*
- * Searches and returns the header `name` in parsed HTTP message `hm`.
- * If header is not found, NULL is returned. Example:
- *
- *     struct mg_str *host_hdr = mg_get_http_header(hm, "Host");
- */
-struct mg_str *mg_get_http_header(struct http_message *hm, const char *name);
-
-/*
- * Parses the HTTP header `hdr`. Finds variable `var_name` and stores its value
- * in the buffer `*buf`, `buf_size`. If the buffer size is not enough,
- * allocates a buffer of required size and writes it to `*buf`, similar to
- * asprintf(). The caller should always check whether the buffer was updated,
- * and free it if so.
- *
- * This function is supposed to parse cookies, authentication headers, etc.
- * Example (error handling omitted):
- *
- *     char user_buf[20];
- *     char *user = user_buf;
- *     struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
- *     mg_http_parse_header2(hdr, "username", &user, sizeof(user_buf));
- *     // ... do something useful with user
- *     if (user != user_buf) {
- *       free(user);
- *     }
- *
- * Returns the length of the variable's value. If variable is not found, 0 is
- * returned.
- */
-int mg_http_parse_header2(struct mg_str *hdr, const char *var_name, char **buf,
-                          size_t buf_size);
-
-/*
- * DEPRECATED: use mg_http_parse_header2() instead.
- *
- * Same as mg_http_parse_header2(), but takes buffer as a `char *` (instead of
- * `char **`), and thus it cannot allocate a new buffer if the provided one
- * is not enough, and just returns 0 in that case.
- */
-int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
-                         size_t buf_size)
-#ifdef __GNUC__
-    __attribute__((deprecated))
-#endif
-    ;
-
-/*
- * Gets and parses the Authorization: Basic header
- * Returns -1 if no Authorization header is found, or if
- * mg_parse_http_basic_auth
- * fails parsing the resulting header.
- */
-int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
-                           char *pass, size_t pass_len);
-
-/*
- * Parses the Authorization: Basic header
- * Returns -1 iif the authorization type is not "Basic" or any other error such
- * as incorrectly encoded base64 user password pair.
- */
-int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
-                             char *pass, size_t pass_len);
-
-/*
- * Parses the buffer `buf`, `buf_len` that contains multipart form data chunks.
- * Stores the chunk name in a `var_name`, `var_name_len` buffer.
- * If a chunk is an uploaded file, then `file_name`, `file_name_len` is
- * filled with an uploaded file name. `chunk`, `chunk_len`
- * points to the chunk data.
- *
- * Return: number of bytes to skip to the next chunk or 0 if there are
- *         no more chunks.
- *
- * Usage example:
- *
- * ```c
- *    static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
- *      switch(ev) {
- *        case MG_EV_HTTP_REQUEST: {
- *          struct http_message *hm = (struct http_message *) ev_data;
- *          char var_name[100], file_name[100];
- *          const char *chunk;
- *          size_t chunk_len, n1, n2;
- *
- *          n1 = n2 = 0;
- *          while ((n2 = mg_parse_multipart(hm->body.p + n1,
- *                                          hm->body.len - n1,
- *                                          var_name, sizeof(var_name),
- *                                          file_name, sizeof(file_name),
- *                                          &chunk, &chunk_len)) > 0) {
- *            printf("var: %s, file_name: %s, size: %d, chunk: [%.*s]\n",
- *                   var_name, file_name, (int) chunk_len,
- *                   (int) chunk_len, chunk);
- *            n1 += n2;
- *          }
- *        }
- *        break;
- * ```
- */
-size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
-                          size_t var_name_len, char *file_name,
-                          size_t file_name_len, const char **chunk,
-                          size_t *chunk_len);
-
-/*
- * Fetches a HTTP form variable.
- *
- * Fetches a variable `name` from a `buf` into a buffer specified by `dst`,
- * `dst_len`. The destination is always zero-terminated. Returns the length of
- * a fetched variable. If not found, 0 is returned. `buf` must be valid
- * url-encoded buffer. If destination is too small or an error occured,
- * negative number is returned.
- */
-int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
-                    size_t dst_len);
-
-#if MG_ENABLE_FILESYSTEM
-/*
- * This structure defines how `mg_serve_http()` works.
- * Best practice is to set only required settings, and leave the rest as NULL.
- */
-struct mg_serve_http_opts {
-  /* Path to web root directory */
-  const char *document_root;
-
-  /* List of index files. Default is "" */
-  const char *index_files;
-
-  /*
-   * Leave as NULL to disable authentication.
-   * To enable directory protection with authentication, set this to ".htpasswd"
-   * Then, creating ".htpasswd" file in any directory automatically protects
-   * it with digest authentication.
-   * Use `mongoose` web server binary, or `htdigest` Apache utility to
-   * create/manipulate passwords file.
-   * Make sure `auth_domain` is set to a valid domain name.
-   */
-  const char *per_directory_auth_file;
-
-  /* Authorization domain (domain name of this web server) */
-  const char *auth_domain;
-
-  /*
-   * Leave as NULL to disable authentication.
-   * Normally, only selected directories in the document root are protected.
-   * If absolutely every access to the web server needs to be authenticated,
-   * regardless of the URI, set this option to the path to the passwords file.
-   * Format of that file is the same as ".htpasswd" file. Make sure that file
-   * is located outside document root to prevent people fetching it.
-   */
-  const char *global_auth_file;
-
-  /* Set to "no" to disable directory listing. Enabled by default. */
-  const char *enable_directory_listing;
-
-  /*
-   * SSI files pattern. If not set, "**.shtml$|**.shtm$" is used.
-   *
-   * All files that match ssi_pattern are treated as SSI.
-   *
-   * Server Side Includes (SSI) is a simple interpreted server-side scripting
-   * language which is most commonly used to include the contents of a file
-   * into a web page. It can be useful when it is desirable to include a common
-   * piece of code throughout a website, for example, headers and footers.
-   *
-   * In order for a webpage to recognize an SSI-enabled HTML file, the
-   * filename should end with a special extension, by default the extension
-   * should be either .shtml or .shtm
-   *
-   * Unknown SSI directives are silently ignored by Mongoose. Currently,
-   * the following SSI directives are supported:
-   *    &lt;!--#include FILE_TO_INCLUDE --&gt;
-   *    &lt;!--#exec "COMMAND_TO_EXECUTE" --&gt;
-   *    &lt;!--#call COMMAND --&gt;
-   *
-   * Note that &lt;!--#include ...> directive supports three path
-   *specifications:
-   *
-   * &lt;!--#include virtual="path" --&gt;  Path is relative to web server root
-   * &lt;!--#include abspath="path" --&gt;  Path is absolute or relative to the
-   *                                  web server working dir
-   * &lt;!--#include file="path" --&gt;,    Path is relative to current document
-   * &lt;!--#include "path" --&gt;
-   *
-   * The include directive may be used to include the contents of a file or
-   * the result of running a CGI script.
-   *
-   * The exec directive is used to execute
-   * a command on a server, and show command's output. Example:
-   *
-   * &lt;!--#exec "ls -l" --&gt;
-   *
-   * The call directive is a way to invoke a C handler from the HTML page.
-   * On each occurence of &lt;!--#call COMMAND OPTIONAL_PARAMS> directive,
-   * Mongoose calls a registered event handler with MG_EV_SSI_CALL event,
-   * and event parameter will point to the COMMAND OPTIONAL_PARAMS string.
-   * An event handler can output any text, for example by calling
-   * `mg_printf()`. This is a flexible way of generating a web page on
-   * server side by calling a C event handler. Example:
-   *
-   * &lt;!--#call foo --&gt; ... &lt;!--#call bar --&gt;
-   *
-   * In the event handler:
-   *    case MG_EV_SSI_CALL: {
-   *      const char *param = (const char *) ev_data;
-   *      if (strcmp(param, "foo") == 0) {
-   *        mg_printf(c, "hello from foo");
-   *      } else if (strcmp(param, "bar") == 0) {
-   *        mg_printf(c, "hello from bar");
-   *      }
-   *      break;
-   *    }
-   */
-  const char *ssi_pattern;
-
-  /* IP ACL. By default, NULL, meaning all IPs are allowed to connect */
-  const char *ip_acl;
-
-#if MG_ENABLE_HTTP_URL_REWRITES
-  /* URL rewrites.
-   *
-   * Comma-separated list of `uri_pattern=url_file_or_directory_path` rewrites.
-   * When HTTP request is received, Mongoose constructs a file name from the
-   * requested URI by combining `document_root` and the URI. However, if the
-   * rewrite option is used and `uri_pattern` matches requested URI, then
-   * `document_root` is ignored. Instead, `url_file_or_directory_path` is used,
-   * which should be a full path name or a path relative to the web server's
-   * current working directory. It can also be an URI (http:// or https://)
-   * in which case mongoose will behave as a reverse proxy for that destination.
-   *
-   * Note that `uri_pattern`, as all Mongoose patterns, is a prefix pattern.
-   *
-   * If uri_pattern starts with `@` symbol, then Mongoose compares it with the
-   * HOST header of the request. If they are equal, Mongoose sets document root
-   * to `file_or_directory_path`, implementing virtual hosts support.
-   * Example: `@foo.com=/document/root/for/foo.com`
-   *
-   * If `uri_pattern` starts with `%` symbol, then Mongoose compares it with
-   * the listening port. If they match, then Mongoose issues a 301 redirect.
-   * For example, to redirect all HTTP requests to the
-   * HTTPS port, do `%80=https://my.site.com`. Note that the request URI is
-   * automatically appended to the redirect location.
-   */
-  const char *url_rewrites;
-#endif
-
-  /* DAV document root. If NULL, DAV requests are going to fail. */
-  const char *dav_document_root;
-
-  /*
-   * DAV passwords file. If NULL, DAV requests are going to fail.
-   * If passwords file is set to "-", then DAV auth is disabled.
-   */
-  const char *dav_auth_file;
-
-  /* Glob pattern for the files to hide. */
-  const char *hidden_file_pattern;
-
-  /* Set to non-NULL to enable CGI, e.g. **.cgi$|**.php$" */
-  const char *cgi_file_pattern;
-
-  /* If not NULL, ignore CGI script hashbang and use this interpreter */
-  const char *cgi_interpreter;
-
-  /*
-   * Comma-separated list of Content-Type overrides for path suffixes, e.g.
-   * ".txt=text/plain; charset=utf-8,.c=text/plain"
-   */
-  const char *custom_mime_types;
-
-  /*
-   * Extra HTTP headers to add to each server response.
-   * Example: to enable CORS, set this to "Access-Control-Allow-Origin: *".
-   */
-  const char *extra_headers;
-};
-
-/*
- * Serves given HTTP request according to the `options`.
- *
- * Example code snippet:
- *
- * ```c
- * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
- *   struct http_message *hm = (struct http_message *) ev_data;
- *   struct mg_serve_http_opts opts = { .document_root = "/var/www" };  // C99
- *
- *   switch (ev) {
- *     case MG_EV_HTTP_REQUEST:
- *       mg_serve_http(nc, hm, opts);
- *       break;
- *     default:
- *       break;
- *   }
- * }
- * ```
- */
-void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
-                   struct mg_serve_http_opts opts);
-
-/*
- * Serves a specific file with a given MIME type and optional extra headers.
- *
- * Example code snippet:
- *
- * ```c
- * static void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
- *   switch (ev) {
- *     case MG_EV_HTTP_REQUEST: {
- *       struct http_message *hm = (struct http_message *) ev_data;
- *       mg_http_serve_file(nc, hm, "file.txt",
- *                          mg_mk_str("text/plain"), mg_mk_str(""));
- *       break;
- *     }
- *     ...
- *   }
- * }
- * ```
- */
-void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
-                        const char *path, const struct mg_str mime_type,
-                        const struct mg_str extra_headers);
-
-#if MG_ENABLE_HTTP_STREAMING_MULTIPART
-
-/* Callback prototype for `mg_file_upload_handler()`. */
-typedef struct mg_str (*mg_fu_fname_fn)(struct mg_connection *nc,
-                                        struct mg_str fname);
-
-/*
- * File upload handler.
- * This handler can be used to implement file uploads with minimum code.
- * This handler will process MG_EV_HTTP_PART_* events and store file data into
- * a local file.
- * `local_name_fn` will be invoked with whatever name was provided by the client
- * and will expect the name of the local file to open. A return value of NULL
- * will abort file upload (client will get a "403 Forbidden" response). If
- * non-null, the returned string must be heap-allocated and will be freed by
- * the caller.
- * Exception: it is ok to return the same string verbatim.
- *
- * Example:
- *
- * ```c
- * struct mg_str upload_fname(struct mg_connection *nc, struct mg_str fname) {
- *   // Just return the same filename. Do not actually do this except in test!
- *   // fname is user-controlled and needs to be sanitized.
- *   return fname;
- * }
- * void ev_handler(struct mg_connection *nc, int ev, void *ev_data) {
- *   switch (ev) {
- *     ...
- *     case MG_EV_HTTP_PART_BEGIN:
- *     case MG_EV_HTTP_PART_DATA:
- *     case MG_EV_HTTP_PART_END:
- *       mg_file_upload_handler(nc, ev, ev_data, upload_fname);
- *       break;
- *   }
- * }
- * ```
- */
-void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
-                            mg_fu_fname_fn local_name_fn
-                                MG_UD_ARG(void *user_data));
-#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
-#endif /* MG_ENABLE_FILESYSTEM */
-
-/*
- * Registers a callback for a specified http endpoint
- * Note: if callback is registered it is called instead of the
- * callback provided in mg_bind
- *
- * Example code snippet:
- *
- * ```c
- * static void handle_hello1(struct mg_connection *nc, int ev, void *ev_data) {
- *   (void) ev; (void) ev_data;
- *   mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello1]");
- *  nc->flags |= MG_F_SEND_AND_CLOSE;
- * }
- *
- * static void handle_hello2(struct mg_connection *nc, int ev, void *ev_data) {
- *  (void) ev; (void) ev_data;
- *   mg_printf(nc, "HTTP/1.0 200 OK\r\n\r\n[I am Hello2]");
- *  nc->flags |= MG_F_SEND_AND_CLOSE;
- * }
- *
- * void init() {
- *   nc = mg_bind(&mgr, local_addr, cb1);
- *   mg_register_http_endpoint(nc, "/hello1", handle_hello1);
- *   mg_register_http_endpoint(nc, "/hello1/hello2", handle_hello2);
- * }
- * ```
- */
-void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
-                               MG_CB(mg_event_handler_t handler,
-                                     void *user_data));
-
-struct mg_http_endpoint_opts {
-  void *user_data;
-  /* Authorization domain (realm) */
-  const char *auth_domain;
-  const char *auth_file;
-};
-
-void mg_register_http_endpoint_opt(struct mg_connection *nc,
-                                   const char *uri_path,
-                                   mg_event_handler_t handler,
-                                   struct mg_http_endpoint_opts opts);
-
-/*
- * Authenticates a HTTP request against an opened password file.
- * Returns 1 if authenticated, 0 otherwise.
- */
-int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
-                              FILE *fp);
-
-/*
- * Authenticates given response params against an opened password file.
- * Returns 1 if authenticated, 0 otherwise.
- *
- * It's used by mg_http_check_digest_auth().
- */
-int mg_check_digest_auth(struct mg_str method, struct mg_str uri,
-                         struct mg_str username, struct mg_str cnonce,
-                         struct mg_str response, struct mg_str qop,
-                         struct mg_str nc, struct mg_str nonce,
-                         struct mg_str auth_domain, FILE *fp);
-
-/*
- * Sends buffer `buf` of size `len` to the client using chunked HTTP encoding.
- * This function sends the buffer size as hex number + newline first, then
- * the buffer itself, then the newline. For example,
- * `mg_send_http_chunk(nc, "foo", 3)` will append the `3\r\nfoo\r\n` string
- * to the `nc->send_mbuf` output IO buffer.
- *
- * NOTE: The HTTP header "Transfer-Encoding: chunked" should be sent prior to
- * using this function.
- *
- * NOTE: do not forget to send an empty chunk at the end of the response,
- * to tell the client that everything was sent. Example:
- *
- * ```
- *   mg_printf_http_chunk(nc, "%s", "my response!");
- *   mg_send_http_chunk(nc, "", 0); // Tell the client we're finished
- * ```
- */
-void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len);
-
-/*
- * Sends a printf-formatted HTTP chunk.
- * Functionality is similar to `mg_send_http_chunk()`.
- */
-void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...);
-
-/*
- * Sends the response status line.
- * If `extra_headers` is not NULL, then `extra_headers` are also sent
- * after the response line. `extra_headers` must NOT end end with new line.
- * Example:
- *
- *      mg_send_response_line(nc, 200, "Access-Control-Allow-Origin: *");
- *
- * Will result in:
- *
- *      HTTP/1.1 200 OK\r\n
- *      Access-Control-Allow-Origin: *\r\n
- */
-void mg_send_response_line(struct mg_connection *nc, int status_code,
-                           const char *extra_headers);
-
-/*
- * Sends an error response. If reason is NULL, the message will be inferred
- * from the error code (if supported).
- */
-void mg_http_send_error(struct mg_connection *nc, int code, const char *reason);
-
-/*
- * Sends a redirect response.
- * `status_code` should be either 301 or 302 and `location` point to the
- * new location.
- * If `extra_headers` is not empty, then `extra_headers` are also sent
- * after the response line. `extra_headers` must NOT end end with new line.
- *
- * Example:
- *
- *      mg_http_send_redirect(nc, 302, mg_mk_str("/login"), mg_mk_str(NULL));
- */
-void mg_http_send_redirect(struct mg_connection *nc, int status_code,
-                           const struct mg_str location,
-                           const struct mg_str extra_headers);
-
-/*
- * Sends the response line and headers.
- * This function sends the response line with the `status_code`, and
- * automatically
- * sends one header: either "Content-Length" or "Transfer-Encoding".
- * If `content_length` is negative, then "Transfer-Encoding: chunked" header
- * is sent, otherwise, "Content-Length" header is sent.
- *
- * NOTE: If `Transfer-Encoding` is `chunked`, then message body must be sent
- * using `mg_send_http_chunk()` or `mg_printf_http_chunk()` functions.
- * Otherwise, `mg_send()` or `mg_printf()` must be used.
- * Extra headers could be set through `extra_headers`. Note `extra_headers`
- * must NOT be terminated by a new line.
- */
-void mg_send_head(struct mg_connection *n, int status_code,
-                  int64_t content_length, const char *extra_headers);
-
-/*
- * Sends a printf-formatted HTTP chunk, escaping HTML tags.
- */
-void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...);
-
-#if MG_ENABLE_HTTP_URL_REWRITES
-/*
- * Proxies a given request to a given upstream http server. The path prefix
- * in `mount` will be stripped of the path requested to the upstream server,
- * e.g. if mount is /api and upstream is http://localhost:8001/foo
- * then an incoming request to /api/bar will cause a request to
- * http://localhost:8001/foo/bar
- *
- * EXPERIMENTAL API. Please use http_serve_http + url_rewrites if a static
- * mapping is good enough.
- */
-void mg_http_reverse_proxy(struct mg_connection *nc,
-                           const struct http_message *hm, struct mg_str mount,
-                           struct mg_str upstream);
-#endif
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* MG_ENABLE_HTTP */
-
-#endif /* CS_MONGOOSE_SRC_HTTP_SERVER_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_http_client.h"
-#endif
-/*
- * === Client API reference
- */
-
-#ifndef CS_MONGOOSE_SRC_HTTP_CLIENT_H_
-#define CS_MONGOOSE_SRC_HTTP_CLIENT_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-/*
- * Helper function that creates an outbound HTTP connection.
- *
- * `url` is the URL to fetch. It must be properly URL-encoded, e.g. have
- * no spaces, etc. By default, `mg_connect_http()` sends the Connection and
- * Host headers. `extra_headers` is an extra HTTP header to send, e.g.
- * `"User-Agent: my-app\r\n"`.
- * If `post_data` is NULL, then a GET request is created. Otherwise, a POST
- * request is created with the specified POST data. Note that if the data being
- * posted is a form submission, the `Content-Type` header should be set
- * accordingly (see example below).
- *
- * Examples:
- *
- * ```c
- *   nc1 = mg_connect_http(mgr, ev_handler_1, "http://www.google.com", NULL,
- *                         NULL);
- *   nc2 = mg_connect_http(mgr, ev_handler_1, "https://github.com", NULL, NULL);
- *   nc3 = mg_connect_http(
- *       mgr, ev_handler_1, "my_server:8000/form_submit/",
- *       "Content-Type: application/x-www-form-urlencoded\r\n",
- *       "var_1=value_1&var_2=value_2");
- * ```
- */
-struct mg_connection *mg_connect_http(
-    struct mg_mgr *mgr,
-    MG_CB(mg_event_handler_t event_handler, void *user_data), const char *url,
-    const char *extra_headers, const char *post_data);
-
-/*
- * Helper function that creates an outbound HTTP connection.
- *
- * Mostly identical to mg_connect_http, but allows you to provide extra
- *parameters
- * (for example, SSL parameters)
- */
-struct mg_connection *mg_connect_http_opt(
-    struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
-    struct mg_connect_opts opts, const char *url, const char *extra_headers,
-    const char *post_data);
-
-/* Creates digest authentication header for a client request. */
-int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
-                                      const char *method, const char *uri,
-                                      const char *auth_domain, const char *user,
-                                      const char *passwd, const char *nonce);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-#endif /* CS_MONGOOSE_SRC_HTTP_CLIENT_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_mqtt.h"
-#endif
-
-/*
- * === MQTT API reference
- */
-
-#ifndef CS_MONGOOSE_SRC_MQTT_H_
-#define CS_MONGOOSE_SRC_MQTT_H_
-
-/* Amalgamated: #include "mg_net.h" */
-
-struct mg_mqtt_message {
-  int cmd;
-  int qos;
-  int len; /* message length in the IO buffer */
-  struct mg_str topic;
-  struct mg_str payload;
-
-  uint8_t connack_ret_code; /* connack */
-  uint16_t message_id;      /* puback */
-
-  /* connect */
-  uint8_t protocol_version;
-  uint8_t connect_flags;
-  uint16_t keep_alive_timer;
-  struct mg_str protocol_name;
-  struct mg_str client_id;
-  struct mg_str will_topic;
-  struct mg_str will_message;
-  struct mg_str user_name;
-  struct mg_str password;
-};
-
-struct mg_mqtt_topic_expression {
-  const char *topic;
-  uint8_t qos;
-};
-
-struct mg_send_mqtt_handshake_opts {
-  unsigned char flags; /* connection flags */
-  uint16_t keep_alive;
-  const char *will_topic;
-  const char *will_message;
-  const char *user_name;
-  const char *password;
-};
-
-/* mg_mqtt_proto_data should be in header to allow external access to it */
-struct mg_mqtt_proto_data {
-  uint16_t keep_alive;
-  double last_control_time;
-};
-
-/* Message types */
-#define MG_MQTT_CMD_CONNECT 1
-#define MG_MQTT_CMD_CONNACK 2
-#define MG_MQTT_CMD_PUBLISH 3
-#define MG_MQTT_CMD_PUBACK 4
-#define MG_MQTT_CMD_PUBREC 5
-#define MG_MQTT_CMD_PUBREL 6
-#define MG_MQTT_CMD_PUBCOMP 7
-#define MG_MQTT_CMD_SUBSCRIBE 8
-#define MG_MQTT_CMD_SUBACK 9
-#define MG_MQTT_CMD_UNSUBSCRIBE 10
-#define MG_MQTT_CMD_UNSUBACK 11
-#define MG_MQTT_CMD_PINGREQ 12
-#define MG_MQTT_CMD_PINGRESP 13
-#define MG_MQTT_CMD_DISCONNECT 14
-
-/* MQTT event types */
-#define MG_MQTT_EVENT_BASE 200
-#define MG_EV_MQTT_CONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNECT)
-#define MG_EV_MQTT_CONNACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_CONNACK)
-#define MG_EV_MQTT_PUBLISH (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBLISH)
-#define MG_EV_MQTT_PUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBACK)
-#define MG_EV_MQTT_PUBREC (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREC)
-#define MG_EV_MQTT_PUBREL (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBREL)
-#define MG_EV_MQTT_PUBCOMP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PUBCOMP)
-#define MG_EV_MQTT_SUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBSCRIBE)
-#define MG_EV_MQTT_SUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_SUBACK)
-#define MG_EV_MQTT_UNSUBSCRIBE (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBSCRIBE)
-#define MG_EV_MQTT_UNSUBACK (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_UNSUBACK)
-#define MG_EV_MQTT_PINGREQ (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGREQ)
-#define MG_EV_MQTT_PINGRESP (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_PINGRESP)
-#define MG_EV_MQTT_DISCONNECT (MG_MQTT_EVENT_BASE + MG_MQTT_CMD_DISCONNECT)
-
-/* Message flags */
-#define MG_MQTT_RETAIN 0x1
-#define MG_MQTT_QOS(qos) ((qos) << 1)
-#define MG_MQTT_GET_QOS(flags) (((flags) &0x6) >> 1)
-#define MG_MQTT_SET_QOS(flags, qos) (flags) = ((flags) & ~0x6) | ((qos) << 1)
-#define MG_MQTT_DUP 0x8
-
-/* Connection flags */
-#define MG_MQTT_CLEAN_SESSION 0x02
-#define MG_MQTT_HAS_WILL 0x04
-#define MG_MQTT_WILL_RETAIN 0x20
-#define MG_MQTT_HAS_PASSWORD 0x40
-#define MG_MQTT_HAS_USER_NAME 0x80
-#define MG_MQTT_GET_WILL_QOS(flags) (((flags) &0x18) >> 3)
-#define MG_MQTT_SET_WILL_QOS(flags, qos) \
-  (flags) = ((flags) & ~0x18) | ((qos) << 3)
-
-/* CONNACK return codes */
-#define MG_EV_MQTT_CONNACK_ACCEPTED 0
-#define MG_EV_MQTT_CONNACK_UNACCEPTABLE_VERSION 1
-#define MG_EV_MQTT_CONNACK_IDENTIFIER_REJECTED 2
-#define MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE 3
-#define MG_EV_MQTT_CONNACK_BAD_AUTH 4
-#define MG_EV_MQTT_CONNACK_NOT_AUTHORIZED 5
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-/*
- * Attaches a built-in MQTT event handler to the given connection.
- *
- * The user-defined event handler will receive following extra events:
- *
- * - MG_EV_MQTT_CONNACK
- * - MG_EV_MQTT_PUBLISH
- * - MG_EV_MQTT_PUBACK
- * - MG_EV_MQTT_PUBREC
- * - MG_EV_MQTT_PUBREL
- * - MG_EV_MQTT_PUBCOMP
- * - MG_EV_MQTT_SUBACK
- */
-void mg_set_protocol_mqtt(struct mg_connection *nc);
-
-/* Sends an MQTT handshake. */
-void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id);
-
-/* Sends an MQTT handshake with optional parameters. */
-void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
-                                struct mg_send_mqtt_handshake_opts);
-
-/* Publishes a message to a given topic. */
-void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
-                     uint16_t message_id, int flags, const void *data,
-                     size_t len);
-
-/* Subscribes to a bunch of topics. */
-void mg_mqtt_subscribe(struct mg_connection *nc,
-                       const struct mg_mqtt_topic_expression *topics,
-                       size_t topics_len, uint16_t message_id);
-
-/* Unsubscribes from a bunch of topics. */
-void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
-                         size_t topics_len, uint16_t message_id);
-
-/* Sends a DISCONNECT command. */
-void mg_mqtt_disconnect(struct mg_connection *nc);
-
-/* Sends a CONNACK command with a given `return_code`. */
-void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code);
-
-/* Sends a PUBACK command with a given `message_id`. */
-void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id);
-
-/* Sends a PUBREC command with a given `message_id`. */
-void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id);
-
-/* Sends a PUBREL command with a given `message_id`. */
-void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id);
-
-/* Sends a PUBCOMP command with a given `message_id`. */
-void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id);
-
-/*
- * Sends a SUBACK command with a given `message_id`
- * and a sequence of granted QoSs.
- */
-void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
-                    uint16_t message_id);
-
-/* Sends a UNSUBACK command with a given `message_id`. */
-void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id);
-
-/* Sends a PINGREQ command. */
-void mg_mqtt_ping(struct mg_connection *nc);
-
-/* Sends a PINGRESP command. */
-void mg_mqtt_pong(struct mg_connection *nc);
-
-/*
- * Extracts the next topic expression from a SUBSCRIBE command payload.
- *
- * The topic expression name will point to a string in the payload buffer.
- * Returns the pos of the next topic expression or -1 when the list
- * of topics is exhausted.
- */
-int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
-                                 struct mg_str *topic, uint8_t *qos, int pos);
-
-/*
- * Matches a topic against a topic expression
- *
- * Returns 1 if it matches; 0 otherwise.
- */
-int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic);
-
-/*
- * Same as `mg_mqtt_match_topic_expression()`, but takes `exp` as a
- * NULL-terminated string.
- */
-int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* CS_MONGOOSE_SRC_MQTT_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_mqtt_server.h"
-#endif
-
-/*
- * === MQTT Server API reference
- */
-
-#ifndef CS_MONGOOSE_SRC_MQTT_BROKER_H_
-#define CS_MONGOOSE_SRC_MQTT_BROKER_H_
-
-#if MG_ENABLE_MQTT_BROKER
-
-/* Amalgamated: #include "common/queue.h" */
-/* Amalgamated: #include "mg_mqtt.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#ifndef MG_MQTT_MAX_SESSION_SUBSCRIPTIONS
-#define MG_MQTT_MAX_SESSION_SUBSCRIPTIONS 512
-#endif
-
-struct mg_mqtt_broker;
-
-/* MQTT session (Broker side). */
-struct mg_mqtt_session {
-  struct mg_mqtt_broker *brk;       /* Broker */
-  LIST_ENTRY(mg_mqtt_session) link; /* mg_mqtt_broker::sessions linkage */
-  struct mg_connection *nc;         /* Connection with the client */
-  size_t num_subscriptions;         /* Size of `subscriptions` array */
-  void *user_data;                  /* User data */
-  struct mg_mqtt_topic_expression *subscriptions;
-};
-
-/* MQTT broker. */
-struct mg_mqtt_broker {
-  LIST_HEAD(_mg_sesshead, mg_mqtt_session) sessions; /* Session list */
-  void *user_data;                                   /* User data */
-};
-
-/* Initialises a MQTT broker. */
-void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data);
-
-/*
- * Processes a MQTT broker message.
- *
- * The listening connection expects a pointer to an initialised
- * `mg_mqtt_broker` structure in the `user_data` field.
- *
- * Basic usage:
- *
- * ```c
- * mg_mqtt_broker_init(&brk, NULL);
- *
- * if ((nc = mg_bind(&mgr, address, mg_mqtt_broker)) == NULL) {
- *   // fail;
- * }
- * nc->user_data = &brk;
- * ```
- *
- * New incoming connections will receive a `mg_mqtt_session` structure
- * in the connection `user_data`. The original `user_data` will be stored
- * in the `user_data` field of the session structure. This allows the user
- * handler to store user data before `mg_mqtt_broker` creates the session.
- *
- * Since only the MG_EV_ACCEPT message is processed by the listening socket,
- * for most events the `user_data` will thus point to a `mg_mqtt_session`.
- */
-void mg_mqtt_broker(struct mg_connection *brk, int ev, void *data);
-
-/*
- * Iterates over all MQTT session connections. Example:
- *
- * ```c
- * struct mg_mqtt_session *s;
- * for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
- *   // Do something
- * }
- * ```
- */
-struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
-                                     struct mg_mqtt_session *s);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* MG_ENABLE_MQTT_BROKER */
-#endif /* CS_MONGOOSE_SRC_MQTT_BROKER_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_dns.h"
-#endif
-
-/*
- * === DNS API reference
- */
-
-#ifndef CS_MONGOOSE_SRC_DNS_H_
-#define CS_MONGOOSE_SRC_DNS_H_
-
-/* Amalgamated: #include "mg_net.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#define MG_DNS_A_RECORD 0x01     /* Lookup IP address */
-#define MG_DNS_CNAME_RECORD 0x05 /* Lookup CNAME */
-#define MG_DNS_PTR_RECORD 0x0c   /* Lookup PTR */
-#define MG_DNS_TXT_RECORD 0x10   /* Lookup TXT */
-#define MG_DNS_AAAA_RECORD 0x1c  /* Lookup IPv6 address */
-#define MG_DNS_SRV_RECORD 0x21   /* Lookup SRV */
-#define MG_DNS_MX_RECORD 0x0f    /* Lookup mail server for domain */
-#define MG_DNS_ANY_RECORD 0xff
-#define MG_DNS_NSEC_RECORD 0x2f
-
-#define MG_MAX_DNS_QUESTIONS 32
-#define MG_MAX_DNS_ANSWERS 32
-
-#define MG_DNS_MESSAGE 100 /* High-level DNS message event */
-
-enum mg_dns_resource_record_kind {
-  MG_DNS_INVALID_RECORD = 0,
-  MG_DNS_QUESTION,
-  MG_DNS_ANSWER
-};
-
-/* DNS resource record. */
-struct mg_dns_resource_record {
-  struct mg_str name; /* buffer with compressed name */
-  int rtype;
-  int rclass;
-  int ttl;
-  enum mg_dns_resource_record_kind kind;
-  struct mg_str rdata; /* protocol data (can be a compressed name) */
-};
-
-/* DNS message (request and response). */
-struct mg_dns_message {
-  struct mg_str pkt; /* packet body */
-  uint16_t flags;
-  uint16_t transaction_id;
-  int num_questions;
-  int num_answers;
-  struct mg_dns_resource_record questions[MG_MAX_DNS_QUESTIONS];
-  struct mg_dns_resource_record answers[MG_MAX_DNS_ANSWERS];
-};
-
-struct mg_dns_resource_record *mg_dns_next_record(
-    struct mg_dns_message *msg, int query, struct mg_dns_resource_record *prev);
-
-/*
- * Parses the record data from a DNS resource record.
- *
- *  - A:     struct in_addr *ina
- *  - AAAA:  struct in6_addr *ina
- *  - CNAME: char buffer
- *
- * Returns -1 on error.
- *
- * TODO(mkm): MX
- */
-int mg_dns_parse_record_data(struct mg_dns_message *msg,
-                             struct mg_dns_resource_record *rr, void *data,
-                             size_t data_len);
-
-/*
- * Sends a DNS query to the remote end.
- */
-void mg_send_dns_query(struct mg_connection *nc, const char *name,
-                       int query_type);
-
-/*
- * Inserts a DNS header to an IO buffer.
- *
- * Returns the number of bytes inserted.
- */
-int mg_dns_insert_header(struct mbuf *io, size_t pos,
-                         struct mg_dns_message *msg);
-
-/*
- * Appends already encoded questions from an existing message.
- *
- * This is useful when generating a DNS reply message which includes
- * all question records.
- *
- * Returns the number of appended bytes.
- */
-int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg);
-
-/*
- * Encodes and appends a DNS resource record to an IO buffer.
- *
- * The record metadata is taken from the `rr` parameter, while the name and data
- * are taken from the parameters, encoded in the appropriate format depending on
- * record type and stored in the IO buffer. The encoded values might contain
- * offsets within the IO buffer. It's thus important that the IO buffer doesn't
- * get trimmed while a sequence of records are encoded while preparing a DNS
- * reply.
- *
- * This function doesn't update the `name` and `rdata` pointers in the `rr`
- * struct because they might be invalidated as soon as the IO buffer grows
- * again.
- *
- * Returns the number of bytes appended or -1 in case of error.
- */
-int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
-                         const char *name, size_t nlen, const void *rdata,
-                         size_t rlen);
-
-/*
- * Encodes a DNS name.
- */
-int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len);
-int mg_dns_encode_name_s(struct mbuf *io, struct mg_str name);
-
-/* Low-level: parses a DNS response. */
-int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg);
-
-/*
- * Uncompresses a DNS compressed name.
- *
- * The containing DNS message is required because of the compressed encoding
- * and reference suffixes present elsewhere in the packet.
- *
- * If the name is less than `dst_len` characters long, the remainder
- * of `dst` is terminated with `\0` characters. Otherwise, `dst` is not
- * terminated.
- *
- * If `dst_len` is 0 `dst` can be NULL.
- * Returns the uncompressed name length.
- */
-size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
-                              char *dst, int dst_len);
-
-/*
- * Attaches a built-in DNS event handler to the given listening connection.
- *
- * The DNS event handler parses the incoming UDP packets, treating them as DNS
- * requests. If an incoming packet gets successfully parsed by the DNS event
- * handler, a user event handler will receive an `MG_DNS_REQUEST` event, with
- * `ev_data` pointing to the parsed `struct mg_dns_message`.
- *
- * See
- * [captive_dns_server](https://github.com/cesanta/mongoose/tree/master/examples/captive_dns_server)
- * example on how to handle DNS request and send DNS reply.
- */
-void mg_set_protocol_dns(struct mg_connection *nc);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-#endif /* CS_MONGOOSE_SRC_DNS_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_dns_server.h"
-#endif
-
-/*
- * === DNS server API reference
- *
- * Disabled by default; enable with `-DMG_ENABLE_DNS_SERVER`.
- */
-
-#ifndef CS_MONGOOSE_SRC_DNS_SERVER_H_
-#define CS_MONGOOSE_SRC_DNS_SERVER_H_
-
-#if MG_ENABLE_DNS_SERVER
-
-/* Amalgamated: #include "mg_dns.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-#define MG_DNS_SERVER_DEFAULT_TTL 3600
-
-struct mg_dns_reply {
-  struct mg_dns_message *msg;
-  struct mbuf *io;
-  size_t start;
-};
-
-/*
- * Creates a DNS reply.
- *
- * The reply will be based on an existing query message `msg`.
- * The query body will be appended to the output buffer.
- * "reply + recursion allowed" will be added to the message flags and the
- * message's num_answers will be set to 0.
- *
- * Answer records can be appended with `mg_dns_send_reply` or by lower
- * level function defined in the DNS API.
- *
- * In order to send a reply use `mg_dns_send_reply`.
- * It's possible to use a connection's send buffer as reply buffer,
- * and it will work for both UDP and TCP connections.
- *
- * Example:
- *
- * ```c
- * reply = mg_dns_create_reply(&nc->send_mbuf, msg);
- * for (i = 0; i < msg->num_questions; i++) {
- *   rr = &msg->questions[i];
- *   if (rr->rtype == MG_DNS_A_RECORD) {
- *     mg_dns_reply_record(&reply, rr, 3600, &dummy_ip_addr, 4);
- *   }
- * }
- * mg_dns_send_reply(nc, &reply);
- * ```
- */
-struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
-                                        struct mg_dns_message *msg);
-
-/*
- * Appends a DNS reply record to the IO buffer and to the DNS message.
- *
- * The message's num_answers field will be incremented. It's the caller's duty
- * to ensure num_answers is properly initialised.
- *
- * Returns -1 on error.
- */
-int mg_dns_reply_record(struct mg_dns_reply *reply,
-                        struct mg_dns_resource_record *question,
-                        const char *name, int rtype, int ttl, const void *rdata,
-                        size_t rdata_len);
-
-/*
- * Sends a DNS reply through a connection.
- *
- * The DNS data is stored in an IO buffer pointed by reply structure in `r`.
- * This function mutates the content of that buffer in order to ensure that
- * the DNS header reflects the size and flags of the message, that might have
- * been updated either with `mg_dns_reply_record` or by direct manipulation of
- * `r->message`.
- *
- * Once sent, the IO buffer will be trimmed unless the reply IO buffer
- * is the connection's send buffer and the connection is not in UDP mode.
- */
-void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* MG_ENABLE_DNS_SERVER */
-#endif /* CS_MONGOOSE_SRC_DNS_SERVER_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_resolv.h"
-#endif
-
-/*
- * === API reference
- */
-
-#ifndef CS_MONGOOSE_SRC_RESOLV_H_
-#define CS_MONGOOSE_SRC_RESOLV_H_
-
-/* Amalgamated: #include "mg_dns.h" */
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-enum mg_resolve_err {
-  MG_RESOLVE_OK = 0,
-  MG_RESOLVE_NO_ANSWERS = 1,
-  MG_RESOLVE_EXCEEDED_RETRY_COUNT = 2,
-  MG_RESOLVE_TIMEOUT = 3
-};
-
-typedef void (*mg_resolve_callback_t)(struct mg_dns_message *dns_message,
-                                      void *user_data, enum mg_resolve_err);
-
-/* Options for `mg_resolve_async_opt`. */
-struct mg_resolve_async_opts {
-  const char *nameserver;
-  int max_retries;    /* defaults to 2 if zero */
-  int timeout;        /* in seconds; defaults to 5 if zero */
-  int accept_literal; /* pseudo-resolve literal ipv4 and ipv6 addrs */
-  int only_literal;   /* only resolves literal addrs; sync cb invocation */
-  struct mg_connection **dns_conn; /* return DNS connection */
-};
-
-/* See `mg_resolve_async_opt()` */
-int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
-                     mg_resolve_callback_t cb, void *data);
-
-/* Set default DNS server */
-void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver);
-
-/*
- * Resolved a DNS name asynchronously.
- *
- * Upon successful resolution, the user callback will be invoked
- * with the full DNS response message and a pointer to the user's
- * context `data`.
- *
- * In case of timeout while performing the resolution the callback
- * will receive a NULL `msg`.
- *
- * The DNS answers can be extracted with `mg_next_record` and
- * `mg_dns_parse_record_data`:
- *
- * [source,c]
- * ----
- * struct in_addr ina;
- * struct mg_dns_resource_record *rr = mg_next_record(msg, MG_DNS_A_RECORD,
- *   NULL);
- * mg_dns_parse_record_data(msg, rr, &ina, sizeof(ina));
- * ----
- */
-int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
-                         mg_resolve_callback_t cb, void *data,
-                         struct mg_resolve_async_opts opts);
-
-/*
- * Resolve a name from `/etc/hosts`.
- *
- * Returns 0 on success, -1 on failure.
- */
-int mg_resolve_from_hosts_file(const char *host, union socket_address *usa);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-#endif /* CS_MONGOOSE_SRC_RESOLV_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_coap.h"
-#endif
-
-/*
- * === CoAP API reference
- *
- * CoAP message format:
- *
- * ```
- * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
- * |Ver| T | TKL | Code | Message ID | Token (if any, TKL bytes) ...
- * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
- * | Options (if any) ...            |1 1 1 1 1 1 1 1| Payload (if any) ...
- * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
- * ```
- */
-
-#ifndef CS_MONGOOSE_SRC_COAP_H_
-#define CS_MONGOOSE_SRC_COAP_H_
-
-#if MG_ENABLE_COAP
-
-#define MG_COAP_MSG_TYPE_FIELD 0x2
-#define MG_COAP_CODE_CLASS_FIELD 0x4
-#define MG_COAP_CODE_DETAIL_FIELD 0x8
-#define MG_COAP_MSG_ID_FIELD 0x10
-#define MG_COAP_TOKEN_FIELD 0x20
-#define MG_COAP_OPTIOMG_FIELD 0x40
-#define MG_COAP_PAYLOAD_FIELD 0x80
-
-#define MG_COAP_ERROR 0x10000
-#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)
-#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)
-#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)
-#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)
-
-#define MG_COAP_MSG_CON 0
-#define MG_COAP_MSG_NOC 1
-#define MG_COAP_MSG_ACK 2
-#define MG_COAP_MSG_RST 3
-#define MG_COAP_MSG_MAX 3
-
-#define MG_COAP_CODECLASS_REQUEST 0
-#define MG_COAP_CODECLASS_RESP_OK 2
-#define MG_COAP_CODECLASS_CLIENT_ERR 4
-#define MG_COAP_CODECLASS_SRV_ERR 5
-
-#define MG_COAP_EVENT_BASE 300
-#define MG_EV_COAP_CON (MG_COAP_EVENT_BASE + MG_COAP_MSG_CON)
-#define MG_EV_COAP_NOC (MG_COAP_EVENT_BASE + MG_COAP_MSG_NOC)
-#define MG_EV_COAP_ACK (MG_COAP_EVENT_BASE + MG_COAP_MSG_ACK)
-#define MG_EV_COAP_RST (MG_COAP_EVENT_BASE + MG_COAP_MSG_RST)
-
-/*
- * CoAP options.
- * Use mg_coap_add_option and mg_coap_free_options
- * for creation and destruction.
- */
-struct mg_coap_option {
-  struct mg_coap_option *next;
-  uint32_t number;
-  struct mg_str value;
-};
-
-/* CoAP message. See RFC 7252 for details. */
-struct mg_coap_message {
-  uint32_t flags;
-  uint8_t msg_type;
-  uint8_t code_class;
-  uint8_t code_detail;
-  uint16_t msg_id;
-  struct mg_str token;
-  struct mg_coap_option *options;
-  struct mg_str payload;
-  struct mg_coap_option *optiomg_tail;
-};
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-/* Sets CoAP protocol handler - triggers CoAP specific events. */
-int mg_set_protocol_coap(struct mg_connection *nc);
-
-/*
- * Adds a new option to mg_coap_message structure.
- * Returns pointer to the newly created option.
- * Note: options must be freed by using mg_coap_free_options
- */
-struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
-                                          uint32_t number, char *value,
-                                          size_t len);
-
-/*
- * Frees the memory allocated for options.
- * If the cm parameter doesn't contain any option it does nothing.
- */
-void mg_coap_free_options(struct mg_coap_message *cm);
-
-/*
- * Composes a CoAP message from `mg_coap_message`
- * and sends it into `nc` connection.
- * Returns 0 on success. On error, it is a bitmask:
- *
- * - `#define MG_COAP_ERROR 0x10000`
- * - `#define MG_COAP_FORMAT_ERROR (MG_COAP_ERROR | 0x20000)`
- * - `#define MG_COAP_IGNORE (MG_COAP_ERROR | 0x40000)`
- * - `#define MG_COAP_NOT_ENOUGH_DATA (MG_COAP_ERROR | 0x80000)`
- * - `#define MG_COAP_NETWORK_ERROR (MG_COAP_ERROR | 0x100000)`
- */
-uint32_t mg_coap_send_message(struct mg_connection *nc,
-                              struct mg_coap_message *cm);
-
-/*
- * Composes CoAP acknowledgement from `mg_coap_message`
- * and sends it into `nc` connection.
- * Return value: see `mg_coap_send_message()`
- */
-uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id);
-
-/*
- * Parses CoAP message and fills mg_coap_message and returns cm->flags.
- * This is a helper function.
- *
- * NOTE: usually CoAP works over UDP, so lack of data means format error.
- * But, in theory, it is possible to use CoAP over TCP (according to RFC)
- *
- * The caller has to check results and treat COAP_NOT_ENOUGH_DATA according to
- * underlying protocol:
- *
- * - in case of UDP COAP_NOT_ENOUGH_DATA means COAP_FORMAT_ERROR,
- * - in case of TCP client can try to receive more data
- *
- * Return value: see `mg_coap_send_message()`
- */
-uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm);
-
-/*
- * Composes CoAP message from mg_coap_message structure.
- * This is a helper function.
- * Return value: see `mg_coap_send_message()`
- */
-uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif /* MG_ENABLE_COAP */
-
-#endif /* CS_MONGOOSE_SRC_COAP_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_sntp.h"
-#endif
-
-#ifndef CS_MONGOOSE_SRC_SNTP_H_
-#define CS_MONGOOSE_SRC_SNTP_H_
-
-#if MG_ENABLE_SNTP
-
-#define MG_SNTP_EVENT_BASE 500
-
-/*
- * Received reply from time server. Event handler parameter contains
- * pointer to mg_sntp_message structure
- */
-#define MG_SNTP_REPLY (MG_SNTP_EVENT_BASE + 1)
-
-/* Received malformed SNTP packet */
-#define MG_SNTP_MALFORMED_REPLY (MG_SNTP_EVENT_BASE + 2)
-
-/* Failed to get time from server (timeout etc) */
-#define MG_SNTP_FAILED (MG_SNTP_EVENT_BASE + 3)
-
-struct mg_sntp_message {
-  /* if server sends this flags, user should not send requests to it */
-  int kiss_of_death;
-  /* usual mg_time */
-  double time;
-};
-
-/* Establishes connection to given sntp server */
-struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
-                                      MG_CB(mg_event_handler_t event_handler,
-                                            void *user_data),
-                                      const char *sntp_server_name);
-
-/* Sends time request to given connection */
-void mg_sntp_send_request(struct mg_connection *c);
-
-/*
- * Helper function
- * Establishes connection to time server, tries to send request
- * repeats sending SNTP_ATTEMPTS times every SNTP_TIMEOUT sec
- * (if needed)
- * See sntp_client example
- */
-struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
-                                       mg_event_handler_t event_handler,
-                                       const char *sntp_server_name);
-
-#endif
-
-#endif /* CS_MONGOOSE_SRC_SNTP_H_ */
-#ifdef MG_MODULE_LINES
-#line 1 "src/mg_socks.h"
-#endif
-
-#ifndef CS_MONGOOSE_SRC_SOCKS_H_
-#define CS_MONGOOSE_SRC_SOCKS_H_
-
-#if MG_ENABLE_SOCKS
-
-#define MG_SOCKS_VERSION 5
-
-#define MG_SOCKS_HANDSHAKE_DONE MG_F_USER_1
-#define MG_SOCKS_CONNECT_DONE MG_F_USER_2
-
-/* SOCKS5 handshake methods */
-enum mg_socks_handshake_method {
-  MG_SOCKS_HANDSHAKE_NOAUTH = 0,     /* Handshake method - no authentication */
-  MG_SOCKS_HANDSHAKE_GSSAPI = 1,     /* Handshake method - GSSAPI auth */
-  MG_SOCKS_HANDSHAKE_USERPASS = 2,   /* Handshake method - user/password auth */
-  MG_SOCKS_HANDSHAKE_FAILURE = 0xff, /* Handshake method - failure */
-};
-
-/* SOCKS5 commands */
-enum mg_socks_command {
-  MG_SOCKS_CMD_CONNECT = 1,       /* Command: CONNECT */
-  MG_SOCKS_CMD_BIND = 2,          /* Command: BIND */
-  MG_SOCKS_CMD_UDP_ASSOCIATE = 3, /* Command: UDP ASSOCIATE */
-};
-
-/* SOCKS5 address types */
-enum mg_socks_address_type {
-  MG_SOCKS_ADDR_IPV4 = 1,   /* Address type: IPv4 */
-  MG_SOCKS_ADDR_DOMAIN = 3, /* Address type: Domain name */
-  MG_SOCKS_ADDR_IPV6 = 4,   /* Address type: IPv6 */
-};
-
-/* SOCKS5 response codes */
-enum mg_socks_response {
-  MG_SOCKS_SUCCESS = 0,            /* Response: success */
-  MG_SOCKS_FAILURE = 1,            /* Response: failure */
-  MG_SOCKS_NOT_ALLOWED = 2,        /* Response: connection not allowed */
-  MG_SOCKS_NET_UNREACHABLE = 3,    /* Response: network unreachable */
-  MG_SOCKS_HOST_UNREACHABLE = 4,   /* Response: network unreachable */
-  MG_SOCKS_CONN_REFUSED = 5,       /* Response: network unreachable */
-  MG_SOCKS_TTL_EXPIRED = 6,        /* Response: network unreachable */
-  MG_SOCKS_CMD_NOT_SUPPORTED = 7,  /* Response: network unreachable */
-  MG_SOCKS_ADDR_NOT_SUPPORTED = 8, /* Response: network unreachable */
-};
-
-#ifdef __cplusplus
-extern "C" {
-#endif /* __cplusplus */
-
-/* Turn the connection into the SOCKS server */
-void mg_set_protocol_socks(struct mg_connection *c);
-
-/* Create socks tunnel for the client connection */
-struct mg_iface *mg_socks_mk_iface(struct mg_mgr *, const char *proxy_addr);
-
-#ifdef __cplusplus
-}
-#endif /* __cplusplus */
-
-#endif
-#endif
diff --git a/vendor/mpack.c b/vendor/mpack.c
deleted file mode 100644
index 67e54e8..0000000
--- a/vendor/mpack.c
+++ /dev/null
@@ -1,6440 +0,0 @@
-/**
- * The MIT License (MIT)
- * 
- * Copyright (c) 2015-2018 Nicholas Fraser
- * 
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in all
- * copies or substantial portions of the Software.
- * 
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- * 
- */
-
-/*
- * This is the MPack 1.0 amalgamation package.
- *
- * http://github.com/ludocode/mpack
- */
-
-#define MPACK_INTERNAL 1
-#define MPACK_EMIT_INLINE_DEFS 1
-
-#include "mpack.h"
-
-
-/* mpack/mpack-platform.c.c */
-
-
-// We define MPACK_EMIT_INLINE_DEFS and include mpack.h to emit
-// standalone definitions of all (non-static) inline functions in MPack.
-
-#define MPACK_INTERNAL 1
-#define MPACK_EMIT_INLINE_DEFS 1
-
-/* #include "mpack-platform.h" */
-/* #include "mpack.h" */
-
-
-#if MPACK_DEBUG && MPACK_STDIO
-#include <stdarg.h>
-#endif
-
-
-
-#if MPACK_DEBUG
-
-#if MPACK_STDIO
-void mpack_assert_fail_format(const char* format, ...) {
-    char buffer[512];
-    va_list args;
-    va_start(args, format);
-    vsnprintf(buffer, sizeof(buffer), format, args);
-    va_end(args);
-    buffer[sizeof(buffer) - 1] = 0;
-    mpack_assert_fail_wrapper(buffer);
-}
-
-void mpack_break_hit_format(const char* format, ...) {
-    char buffer[512];
-    va_list args;
-    va_start(args, format);
-    vsnprintf(buffer, sizeof(buffer), format, args);
-    va_end(args);
-    buffer[sizeof(buffer) - 1] = 0;
-    mpack_break_hit(buffer);
-}
-#endif
-
-#if !MPACK_CUSTOM_ASSERT
-void mpack_assert_fail(const char* message) {
-    MPACK_UNUSED(message);
-
-    #if MPACK_STDIO
-    fprintf(stderr, "%s\n", message);
-    #endif
-}
-#endif
-
-// We split the assert failure from the wrapper so that a
-// custom assert function can return.
-void mpack_assert_fail_wrapper(const char* message) {
-
-    #ifdef MPACK_GCOV
-    // gcov marks even __builtin_unreachable() as an uncovered line. this
-    // silences it.
-    (mpack_assert_fail(message), __builtin_unreachable());
-
-    #else
-    mpack_assert_fail(message);
-
-    // mpack_assert_fail() is not supposed to return. in case it does, we
-    // abort.
-
-    #if !MPACK_NO_BUILTINS
-    #if defined(__GNUC__) || defined(__clang__)
-    __builtin_trap();
-    #elif defined(WIN32)
-    __debugbreak();
-    #endif
-    #endif
-
-    #if (defined(__GNUC__) || defined(__clang__)) && !MPACK_NO_BUILTINS
-    __builtin_abort();
-    #elif MPACK_STDLIB
-    abort();
-    #endif
-
-    MPACK_UNREACHABLE;
-    #endif
-}
-
-#if !MPACK_CUSTOM_BREAK
-
-// If we have a custom assert handler, break wraps it by default.
-// This allows users of MPack to only implement mpack_assert_fail() without
-// having to worry about the difference between assert and break.
-//
-// MPACK_CUSTOM_BREAK is available to define a separate break handler
-// (which is needed by the unit test suite), but this is not offered in
-// mpack-config.h for simplicity.
-
-#if MPACK_CUSTOM_ASSERT
-void mpack_break_hit(const char* message) {
-    mpack_assert_fail_wrapper(message);
-}
-#else
-void mpack_break_hit(const char* message) {
-    MPACK_UNUSED(message);
-
-    #if MPACK_STDIO
-    fprintf(stderr, "%s\n", message);
-    #endif
-
-    #if defined(__GNUC__) || defined(__clang__) && !MPACK_NO_BUILTINS
-    __builtin_trap();
-    #elif defined(WIN32) && !MPACK_NO_BUILTINS
-    __debugbreak();
-    #elif MPACK_STDLIB
-    abort();
-    #endif
-}
-#endif
-
-#endif
-
-#endif
-
-
-
-// The below are adapted from the C wikibook:
-//     https://en.wikibooks.org/wiki/C_Programming/Strings
-
-#ifndef mpack_memcmp
-int mpack_memcmp(const void* s1, const void* s2, size_t n) {
-     const unsigned char *us1 = (const unsigned char *) s1;
-     const unsigned char *us2 = (const unsigned char *) s2;
-     while (n-- != 0) {
-         if (*us1 != *us2)
-             return (*us1 < *us2) ? -1 : +1;
-         us1++;
-         us2++;
-     }
-     return 0;
-}
-#endif
-
-#ifndef mpack_memcpy
-void* mpack_memcpy(void* MPACK_RESTRICT s1, const void* MPACK_RESTRICT s2, size_t n) {
-    char* MPACK_RESTRICT dst = (char *)s1;
-    const char* MPACK_RESTRICT src = (const char *)s2;
-    while (n-- != 0)
-        *dst++ = *src++;
-    return s1;
-}
-#endif
-
-#ifndef mpack_memmove
-void* mpack_memmove(void* s1, const void* s2, size_t n) {
-    char *p1 = (char *)s1;
-    const char *p2 = (const char *)s2;
-    if (p2 < p1 && p1 < p2 + n) {
-        p2 += n;
-        p1 += n;
-        while (n-- != 0)
-            *--p1 = *--p2;
-    } else
-        while (n-- != 0)
-            *p1++ = *p2++;
-    return s1;
-}
-#endif
-
-#ifndef mpack_memset
-void* mpack_memset(void* s, int c, size_t n) {
-    unsigned char *us = (unsigned char *)s;
-    unsigned char uc = (unsigned char)c;
-    while (n-- != 0)
-        *us++ = uc;
-    return s;
-}
-#endif
-
-#ifndef mpack_strlen
-size_t mpack_strlen(const char* s) {
-    const char* p = s;
-    while (*p != '\0')
-        p++;
-    return (size_t)(p - s);
-}
-#endif
-
-
-
-#if defined(MPACK_MALLOC) && !defined(MPACK_REALLOC)
-void* mpack_realloc(void* old_ptr, size_t used_size, size_t new_size) {
-    if (new_size == 0) {
-        if (old_ptr)
-            MPACK_FREE(old_ptr);
-        return NULL;
-    }
-
-    void* new_ptr = MPACK_MALLOC(new_size);
-    if (new_ptr == NULL)
-        return NULL;
-
-    mpack_memcpy(new_ptr, old_ptr, used_size);
-    MPACK_FREE(old_ptr);
-    return new_ptr;
-}
-#endif
-
-/* mpack/mpack-common.c.c */
-
-#define MPACK_INTERNAL 1
-
-/* #include "mpack-common.h" */
-
-#if MPACK_DEBUG && MPACK_STDIO
-#include <stdarg.h>
-#endif
-
-const char* mpack_error_to_string(mpack_error_t error) {
-    #if MPACK_STRINGS
-    switch (error) {
-        #define MPACK_ERROR_STRING_CASE(e) case e: return #e
-        MPACK_ERROR_STRING_CASE(mpack_ok);
-        MPACK_ERROR_STRING_CASE(mpack_error_io);
-        MPACK_ERROR_STRING_CASE(mpack_error_invalid);
-        MPACK_ERROR_STRING_CASE(mpack_error_unsupported);
-        MPACK_ERROR_STRING_CASE(mpack_error_type);
-        MPACK_ERROR_STRING_CASE(mpack_error_too_big);
-        MPACK_ERROR_STRING_CASE(mpack_error_memory);
-        MPACK_ERROR_STRING_CASE(mpack_error_bug);
-        MPACK_ERROR_STRING_CASE(mpack_error_data);
-        MPACK_ERROR_STRING_CASE(mpack_error_eof);
-        #undef MPACK_ERROR_STRING_CASE
-    }
-    mpack_assert(0, "unrecognized error %i", (int)error);
-    return "(unknown mpack_error_t)";
-    #else
-    MPACK_UNUSED(error);
-    return "";
-    #endif
-}
-
-const char* mpack_type_to_string(mpack_type_t type) {
-    #if MPACK_STRINGS
-    switch (type) {
-        #define MPACK_TYPE_STRING_CASE(e) case e: return #e
-        MPACK_TYPE_STRING_CASE(mpack_type_missing);
-        MPACK_TYPE_STRING_CASE(mpack_type_nil);
-        MPACK_TYPE_STRING_CASE(mpack_type_bool);
-        MPACK_TYPE_STRING_CASE(mpack_type_float);
-        MPACK_TYPE_STRING_CASE(mpack_type_double);
-        MPACK_TYPE_STRING_CASE(mpack_type_int);
-        MPACK_TYPE_STRING_CASE(mpack_type_uint);
-        MPACK_TYPE_STRING_CASE(mpack_type_str);
-        MPACK_TYPE_STRING_CASE(mpack_type_bin);
-        MPACK_TYPE_STRING_CASE(mpack_type_array);
-        MPACK_TYPE_STRING_CASE(mpack_type_map);
-        #if MPACK_EXTENSIONS
-        MPACK_TYPE_STRING_CASE(mpack_type_ext);
-        #endif
-        #undef MPACK_TYPE_STRING_CASE
-    }
-    mpack_assert(0, "unrecognized type %i", (int)type);
-    return "(unknown mpack_type_t)";
-    #else
-    MPACK_UNUSED(type);
-    return "";
-    #endif
-}
-
-int mpack_tag_cmp(mpack_tag_t left, mpack_tag_t right) {
-
-    // positive numbers may be stored as int; convert to uint
-    if (left.type == mpack_type_int && left.v.i >= 0) {
-        left.type = mpack_type_uint;
-        left.v.u = (uint64_t)left.v.i;
-    }
-    if (right.type == mpack_type_int && right.v.i >= 0) {
-        right.type = mpack_type_uint;
-        right.v.u = (uint64_t)right.v.i;
-    }
-
-    if (left.type != right.type)
-        return ((int)left.type < (int)right.type) ? -1 : 1;
-
-    switch (left.type) {
-        case mpack_type_missing: // fallthrough
-        case mpack_type_nil:
-            return 0;
-
-        case mpack_type_bool:
-            return (int)left.v.b - (int)right.v.b;
-
-        case mpack_type_int:
-            if (left.v.i == right.v.i)
-                return 0;
-            return (left.v.i < right.v.i) ? -1 : 1;
-
-        case mpack_type_uint:
-            if (left.v.u == right.v.u)
-                return 0;
-            return (left.v.u < right.v.u) ? -1 : 1;
-
-        case mpack_type_array:
-        case mpack_type_map:
-            if (left.v.n == right.v.n)
-                return 0;
-            return (left.v.n < right.v.n) ? -1 : 1;
-
-        case mpack_type_str:
-        case mpack_type_bin:
-            if (left.v.l == right.v.l)
-                return 0;
-            return (left.v.l < right.v.l) ? -1 : 1;
-
-        #if MPACK_EXTENSIONS
-        case mpack_type_ext:
-            if (left.exttype == right.exttype) {
-                if (left.v.l == right.v.l)
-                    return 0;
-                return (left.v.l < right.v.l) ? -1 : 1;
-            }
-            return (int)left.exttype - (int)right.exttype;
-        #endif
-
-        // floats should not normally be compared for equality. we compare
-        // with memcmp() to silence compiler warnings, but this will return
-        // equal if both are NaNs with the same representation (though we may
-        // want this, for instance if you are for some bizarre reason using
-        // floats as map keys.) i'm not sure what the right thing to
-        // do is here. check for NaN first? always return false if the type
-        // is float? use operator== and pragmas to silence compiler warning?
-        // please send me your suggestions.
-        // note also that we don't convert floats to doubles, so when this is
-        // used for ordering purposes, all floats are ordered before all
-        // doubles.
-        case mpack_type_float:
-            return mpack_memcmp(&left.v.f, &right.v.f, sizeof(left.v.f));
-        case mpack_type_double:
-            return mpack_memcmp(&left.v.d, &right.v.d, sizeof(left.v.d));
-    }
-
-    mpack_assert(0, "unrecognized type %i", (int)left.type);
-    return false;
-}
-
-#if MPACK_DEBUG && MPACK_STDIO
-static char mpack_hex_char(uint8_t hex_value) {
-    return (hex_value < 10) ? (char)('0' + hex_value) : (char)('a' + (hex_value - 10));
-}
-
-static void mpack_tag_debug_complete_bin_ext(mpack_tag_t tag, size_t string_length, char* buffer, size_t buffer_size,
-        const char* prefix, size_t prefix_size)
-{
-    // If at any point in this function we run out of space in the buffer, we
-    // bail out. The outer tag print wrapper will make sure we have a
-    // null-terminator.
-
-    if (string_length == 0 || string_length >= buffer_size)
-        return;
-    buffer += string_length;
-    buffer_size -= string_length;
-
-    size_t total = mpack_tag_bytes(&tag);
-    if (total == 0) {
-        strncpy(buffer, ">", buffer_size);
-        return;
-    }
-
-    strncpy(buffer, ": ", buffer_size);
-    if (buffer_size < 2)
-        return;
-    buffer += 2;
-    buffer_size -= 2;
-
-    size_t hex_bytes = 0;
-    for (size_t i = 0; i < MPACK_PRINT_BYTE_COUNT && i < prefix_size && buffer_size > 2; ++i) {
-        uint8_t byte = (uint8_t)prefix[i];
-        buffer[0] = mpack_hex_char((uint8_t)(byte >> 4));
-        buffer[1] = mpack_hex_char((uint8_t)(byte & 0xfu));
-        buffer += 2;
-        buffer_size -= 2;
-        ++hex_bytes;
-    }
-
-    if (buffer_size != 0)
-        mpack_snprintf(buffer, buffer_size, "%s>", (total > hex_bytes) ? "..." : "");
-}
-
-static void mpack_tag_debug_pseudo_json_bin(mpack_tag_t tag, char* buffer, size_t buffer_size,
-        const char* prefix, size_t prefix_size)
-{
-    mpack_assert(mpack_tag_type(&tag) == mpack_type_bin);
-    size_t length = (size_t)mpack_snprintf(buffer, buffer_size, "<binary data of length %u", tag.v.l);
-    mpack_tag_debug_complete_bin_ext(tag, length, buffer, buffer_size, prefix, prefix_size);
-}
-
-#if MPACK_EXTENSIONS
-static void mpack_tag_debug_pseudo_json_ext(mpack_tag_t tag, char* buffer, size_t buffer_size,
-        const char* prefix, size_t prefix_size)
-{
-    mpack_assert(mpack_tag_type(&tag) == mpack_type_ext);
-    size_t length = (size_t)mpack_snprintf(buffer, buffer_size, "<ext data of type %i and length %u",
-            mpack_tag_ext_exttype(&tag), mpack_tag_ext_length(&tag));
-    mpack_tag_debug_complete_bin_ext(tag, length, buffer, buffer_size, prefix, prefix_size);
-}
-#endif
-
-static void mpack_tag_debug_pseudo_json_impl(mpack_tag_t tag, char* buffer, size_t buffer_size,
-        const char* prefix, size_t prefix_size)
-{
-    switch (tag.type) {
-        case mpack_type_missing:
-            mpack_snprintf(buffer, buffer_size, "<missing!>");
-            return;
-        case mpack_type_nil:
-            mpack_snprintf(buffer, buffer_size, "null");
-            return;
-        case mpack_type_bool:
-            mpack_snprintf(buffer, buffer_size, tag.v.b ? "true" : "false");
-            return;
-        case mpack_type_int:
-            mpack_snprintf(buffer, buffer_size, "%" PRIi64, tag.v.i);
-            return;
-        case mpack_type_uint:
-            mpack_snprintf(buffer, buffer_size, "%" PRIu64, tag.v.u);
-            return;
-        case mpack_type_float:
-            mpack_snprintf(buffer, buffer_size, "%f", tag.v.f);
-            return;
-        case mpack_type_double:
-            mpack_snprintf(buffer, buffer_size, "%f", tag.v.d);
-            return;
-
-        case mpack_type_str:
-            mpack_snprintf(buffer, buffer_size, "<string of %u bytes>", tag.v.l);
-            return;
-        case mpack_type_bin:
-            mpack_tag_debug_pseudo_json_bin(tag, buffer, buffer_size, prefix, prefix_size);
-            return;
-        #if MPACK_EXTENSIONS
-        case mpack_type_ext:
-            mpack_tag_debug_pseudo_json_ext(tag, buffer, buffer_size, prefix, prefix_size);
-            return;
-        #endif
-
-        case mpack_type_array:
-            mpack_snprintf(buffer, buffer_size, "<array of %u elements>", tag.v.n);
-            return;
-        case mpack_type_map:
-            mpack_snprintf(buffer, buffer_size, "<map of %u key-value pairs>", tag.v.n);
-            return;
-    }
-
-    mpack_snprintf(buffer, buffer_size, "<unknown!>");
-}
-
-void mpack_tag_debug_pseudo_json(mpack_tag_t tag, char* buffer, size_t buffer_size,
-        const char* prefix, size_t prefix_size)
-{
-    mpack_assert(buffer_size > 0, "buffer size cannot be zero!");
-    buffer[0] = 0;
-
-    mpack_tag_debug_pseudo_json_impl(tag, buffer, buffer_size, prefix, prefix_size);
-
-    // We always null-terminate the buffer manually just in case the snprintf()
-    // function doesn't null-terminate when the string doesn't fit.
-    buffer[buffer_size - 1] = 0;
-}
-
-static void mpack_tag_debug_describe_impl(mpack_tag_t tag, char* buffer, size_t buffer_size) {
-    switch (tag.type) {
-        case mpack_type_missing:
-            mpack_snprintf(buffer, buffer_size, "missing");
-            return;
-        case mpack_type_nil:
-            mpack_snprintf(buffer, buffer_size, "nil");
-            return;
-        case mpack_type_bool:
-            mpack_snprintf(buffer, buffer_size, tag.v.b ? "true" : "false");
-            return;
-        case mpack_type_int:
-            mpack_snprintf(buffer, buffer_size, "int %" PRIi64, tag.v.i);
-            return;
-        case mpack_type_uint:
-            mpack_snprintf(buffer, buffer_size, "uint %" PRIu64, tag.v.u);
-            return;
-        case mpack_type_float:
-            mpack_snprintf(buffer, buffer_size, "float %f", tag.v.f);
-            return;
-        case mpack_type_double:
-            mpack_snprintf(buffer, buffer_size, "double %f", tag.v.d);
-            return;
-        case mpack_type_str:
-            mpack_snprintf(buffer, buffer_size, "str of %u bytes", tag.v.l);
-            return;
-        case mpack_type_bin:
-            mpack_snprintf(buffer, buffer_size, "bin of %u bytes", tag.v.l);
-            return;
-        #if MPACK_EXTENSIONS
-        case mpack_type_ext:
-            mpack_snprintf(buffer, buffer_size, "ext of type %i, %u bytes",
-                    mpack_tag_ext_exttype(&tag), mpack_tag_ext_length(&tag));
-            return;
-        #endif
-        case mpack_type_array:
-            mpack_snprintf(buffer, buffer_size, "array of %u elements", tag.v.n);
-            return;
-        case mpack_type_map:
-            mpack_snprintf(buffer, buffer_size, "map of %u key-value pairs", tag.v.n);
-            return;
-    }
-
-    mpack_snprintf(buffer, buffer_size, "unknown!");
-}
-
-void mpack_tag_debug_describe(mpack_tag_t tag, char* buffer, size_t buffer_size) {
-    mpack_assert(buffer_size > 0, "buffer size cannot be zero!");
-    buffer[0] = 0;
-
-    mpack_tag_debug_describe_impl(tag, buffer, buffer_size);
-
-    // We always null-terminate the buffer manually just in case the snprintf()
-    // function doesn't null-terminate when the string doesn't fit.
-    buffer[buffer_size - 1] = 0;
-}
-#endif
-
-
-
-#if MPACK_READ_TRACKING || MPACK_WRITE_TRACKING
-
-#ifndef MPACK_TRACKING_INITIAL_CAPACITY
-// seems like a reasonable number. we grow by doubling, and it only
-// needs to be as long as the maximum depth of the message.
-#define MPACK_TRACKING_INITIAL_CAPACITY 8
-#endif
-
-mpack_error_t mpack_track_init(mpack_track_t* track) {
-    track->count = 0;
-    track->capacity = MPACK_TRACKING_INITIAL_CAPACITY;
-    track->elements = (mpack_track_element_t*)MPACK_MALLOC(sizeof(mpack_track_element_t) * track->capacity);
-    if (track->elements == NULL)
-        return mpack_error_memory;
-    return mpack_ok;
-}
-
-mpack_error_t mpack_track_grow(mpack_track_t* track) {
-    mpack_assert(track->elements, "null track elements!");
-    mpack_assert(track->count == track->capacity, "incorrect growing?");
-
-    size_t new_capacity = track->capacity * 2;
-
-    mpack_track_element_t* new_elements = (mpack_track_element_t*)mpack_realloc(track->elements,
-            sizeof(mpack_track_element_t) * track->count, sizeof(mpack_track_element_t) * new_capacity);
-    if (new_elements == NULL)
-        return mpack_error_memory;
-
-    track->elements = new_elements;
-    track->capacity = new_capacity;
-    return mpack_ok;
-}
-
-mpack_error_t mpack_track_push(mpack_track_t* track, mpack_type_t type, uint64_t count) {
-    mpack_assert(track->elements, "null track elements!");
-    mpack_log("track pushing %s count %i\n", mpack_type_to_string(type), (int)count);
-
-    // maps have twice the number of elements (key/value pairs)
-    if (type == mpack_type_map)
-        count *= 2;
-
-    // grow if needed
-    if (track->count == track->capacity) {
-        mpack_error_t error = mpack_track_grow(track);
-        if (error != mpack_ok)
-            return error;
-    }
-
-    // insert new track
-    track->elements[track->count].type = type;
-    track->elements[track->count].left = count;
-    ++track->count;
-    return mpack_ok;
-}
-
-mpack_error_t mpack_track_pop(mpack_track_t* track, mpack_type_t type) {
-    mpack_assert(track->elements, "null track elements!");
-    mpack_log("track popping %s\n", mpack_type_to_string(type));
-
-    if (track->count == 0) {
-        mpack_break("attempting to close a %s but nothing was opened!", mpack_type_to_string(type));
-        return mpack_error_bug;
-    }
-
-    mpack_track_element_t* element = &track->elements[track->count - 1];
-
-    if (element->type != type) {
-        mpack_break("attempting to close a %s but the open element is a %s!",
-                mpack_type_to_string(type), mpack_type_to_string(element->type));
-        return mpack_error_bug;
-    }
-
-    if (element->left != 0) {
-        mpack_break("attempting to close a %s but there are %" PRIu64 " %s left",
-                mpack_type_to_string(type), element->left,
-                (type == mpack_type_map || type == mpack_type_array) ? "elements" : "bytes");
-        return mpack_error_bug;
-    }
-
-    --track->count;
-    return mpack_ok;
-}
-
-mpack_error_t mpack_track_peek_element(mpack_track_t* track, bool read) {
-    MPACK_UNUSED(read);
-    mpack_assert(track->elements, "null track elements!");
-
-    // if there are no open elements, that's fine, we can read/write elements at will
-    if (track->count == 0)
-        return mpack_ok;
-
-    mpack_track_element_t* element = &track->elements[track->count - 1];
-
-    if (element->type != mpack_type_map && element->type != mpack_type_array) {
-        mpack_break("elements cannot be %s within an %s", read ? "read" : "written",
-                mpack_type_to_string(element->type));
-        return mpack_error_bug;
-    }
-
-    if (element->left == 0) {
-        mpack_break("too many elements %s for %s", read ? "read" : "written",
-                mpack_type_to_string(element->type));
-        return mpack_error_bug;
-    }
-
-    return mpack_ok;
-}
-
-mpack_error_t mpack_track_element(mpack_track_t* track, bool read) {
-    mpack_error_t error = mpack_track_peek_element(track, read);
-    if (track->count > 0 && error == mpack_ok)
-        --track->elements[track->count - 1].left;
-    return error;
-}
-
-mpack_error_t mpack_track_bytes(mpack_track_t* track, bool read, uint64_t count) {
-    MPACK_UNUSED(read);
-    mpack_assert(track->elements, "null track elements!");
-
-    if (track->count == 0) {
-        mpack_break("bytes cannot be %s with no open bin, str or ext", read ? "read" : "written");
-        return mpack_error_bug;
-    }
-
-    mpack_track_element_t* element = &track->elements[track->count - 1];
-
-    if (element->type == mpack_type_map || element->type == mpack_type_array) {
-        mpack_break("bytes cannot be %s within an %s", read ? "read" : "written",
-                mpack_type_to_string(element->type));
-        return mpack_error_bug;
-    }
-
-    if (element->left < count) {
-        mpack_break("too many bytes %s for %s", read ? "read" : "written",
-                mpack_type_to_string(element->type));
-        return mpack_error_bug;
-    }
-
-    element->left -= count;
-    return mpack_ok;
-}
-
-mpack_error_t mpack_track_str_bytes_all(mpack_track_t* track, bool read, uint64_t count) {
-    mpack_error_t error = mpack_track_bytes(track, read, count);
-    if (error != mpack_ok)
-        return error;
-
-    mpack_track_element_t* element = &track->elements[track->count - 1];
-
-    if (element->type != mpack_type_str) {
-        mpack_break("the open type must be a string, not a %s", mpack_type_to_string(element->type));
-        return mpack_error_bug;
-    }
-
-    if (element->left != 0) {
-        mpack_break("not all bytes were read; the wrong byte count was requested for a string read.");
-        return mpack_error_bug;
-    }
-
-    return mpack_ok;
-}
-
-mpack_error_t mpack_track_check_empty(mpack_track_t* track) {
-    if (track->count != 0) {
-        mpack_break("unclosed %s", mpack_type_to_string(track->elements[0].type));
-        return mpack_error_bug;
-    }
-    return mpack_ok;
-}
-
-mpack_error_t mpack_track_destroy(mpack_track_t* track, bool cancel) {
-    mpack_error_t error = cancel ? mpack_ok : mpack_track_check_empty(track);
-    if (track->elements) {
-        MPACK_FREE(track->elements);
-        track->elements = NULL;
-    }
-    return error;
-}
-#endif
-
-
-
-static bool mpack_utf8_check_impl(const uint8_t* str, size_t count, bool allow_null) {
-    while (count > 0) {
-        uint8_t lead = str[0];
-
-        // NUL
-        if (!allow_null && lead == '\0') // we don't allow NUL bytes in MPack C-strings
-            return false;
-
-        // ASCII
-        if (lead <= 0x7F) {
-            ++str;
-            --count;
-
-        // 2-byte sequence
-        } else if ((lead & 0xE0) == 0xC0) {
-            if (count < 2) // truncated sequence
-                return false;
-
-            uint8_t cont = str[1];
-            if ((cont & 0xC0) != 0x80) // not a continuation byte
-                return false;
-
-            str += 2;
-            count -= 2;
-
-            uint32_t z = ((uint32_t)(lead & ~0xE0) << 6) |
-                          (uint32_t)(cont & ~0xC0);
-
-            if (z < 0x80) // overlong sequence
-                return false;
-
-        // 3-byte sequence
-        } else if ((lead & 0xF0) == 0xE0) {
-            if (count < 3) // truncated sequence
-                return false;
-
-            uint8_t cont1 = str[1];
-            if ((cont1 & 0xC0) != 0x80) // not a continuation byte
-                return false;
-            uint8_t cont2 = str[2];
-            if ((cont2 & 0xC0) != 0x80) // not a continuation byte
-                return false;
-
-            str += 3;
-            count -= 3;
-
-            uint32_t z = ((uint32_t)(lead  & ~0xF0) << 12) |
-                         ((uint32_t)(cont1 & ~0xC0) <<  6) |
-                          (uint32_t)(cont2 & ~0xC0);
-
-            if (z < 0x800) // overlong sequence
-                return false;
-            if (z >= 0xD800 && z <= 0xDFFF) // surrogate
-                return false;
-
-        // 4-byte sequence
-        } else if ((lead & 0xF8) == 0xF0) {
-            if (count < 4) // truncated sequence
-                return false;
-
-            uint8_t cont1 = str[1];
-            if ((cont1 & 0xC0) != 0x80) // not a continuation byte
-                return false;
-            uint8_t cont2 = str[2];
-            if ((cont2 & 0xC0) != 0x80) // not a continuation byte
-                return false;
-            uint8_t cont3 = str[3];
-            if ((cont3 & 0xC0) != 0x80) // not a continuation byte
-                return false;
-
-            str += 4;
-            count -= 4;
-
-            uint32_t z = ((uint32_t)(lead  & ~0xF8) << 18) |
-                         ((uint32_t)(cont1 & ~0xC0) << 12) |
-                         ((uint32_t)(cont2 & ~0xC0) <<  6) |
-                          (uint32_t)(cont3 & ~0xC0);
-
-            if (z < 0x10000) // overlong sequence
-                return false;
-            if (z > 0x10FFFF) // codepoint limit
-                return false;
-
-        } else {
-            return false; // continuation byte without a lead, or lead for a 5-byte sequence or longer
-        }
-    }
-    return true;
-}
-
-bool mpack_utf8_check(const char* str, size_t bytes) {
-    return mpack_utf8_check_impl((const uint8_t*)str, bytes, true);
-}
-
-bool mpack_utf8_check_no_null(const char* str, size_t bytes) {
-    return mpack_utf8_check_impl((const uint8_t*)str, bytes, false);
-}
-
-bool mpack_str_check_no_null(const char* str, size_t bytes) {
-    for (size_t i = 0; i < bytes; ++i)
-        if (str[i] == '\0')
-            return false;
-    return true;
-}
-
-#if MPACK_DEBUG && MPACK_STDIO
-void mpack_print_append(mpack_print_t* print, const char* data, size_t count) {
-
-    // copy whatever fits into the buffer
-    size_t copy = print->size - print->count;
-    if (copy > count)
-        copy = count;
-    mpack_memcpy(print->buffer + print->count, data, copy);
-    print->count += copy;
-    data += copy;
-    count -= copy;
-
-    // if we don't need to flush or can't flush there's nothing else to do
-    if (count == 0 || print->callback == NULL)
-        return;
-
-    // flush the buffer
-    print->callback(print->context, print->buffer, print->count);
-
-    if (count > print->size / 2) {
-        // flush the rest of the data
-        print->count = 0;
-        print->callback(print->context, data, count);
-    } else {
-        // copy the rest of the data into the buffer
-        mpack_memcpy(print->buffer, data, count);
-        print->count = count;
-    }
-
-}
-
-void mpack_print_flush(mpack_print_t* print) {
-    if (print->count > 0 && print->callback != NULL) {
-        print->callback(print->context, print->buffer, print->count);
-        print->count = 0;
-    }
-}
-
-void mpack_print_file_callback(void* context, const char* data, size_t count) {
-    FILE* file = (FILE*)context;
-    fwrite(data, 1, count, file);
-}
-#endif
-
-/* mpack/mpack-writer.c.c */
-
-#define MPACK_INTERNAL 1
-
-/* #include "mpack-writer.h" */
-
-#if MPACK_WRITER
-
-#if MPACK_WRITE_TRACKING
-static void mpack_writer_flag_if_error(mpack_writer_t* writer, mpack_error_t error) {
-    if (error != mpack_ok)
-        mpack_writer_flag_error(writer, error);
-}
-
-void mpack_writer_track_push(mpack_writer_t* writer, mpack_type_t type, uint64_t count) {
-    if (writer->error == mpack_ok)
-        mpack_writer_flag_if_error(writer, mpack_track_push(&writer->track, type, count));
-}
-
-void mpack_writer_track_pop(mpack_writer_t* writer, mpack_type_t type) {
-    if (writer->error == mpack_ok)
-        mpack_writer_flag_if_error(writer, mpack_track_pop(&writer->track, type));
-}
-
-void mpack_writer_track_element(mpack_writer_t* writer) {
-    if (writer->error == mpack_ok)
-        mpack_writer_flag_if_error(writer, mpack_track_element(&writer->track, false));
-}
-
-void mpack_writer_track_bytes(mpack_writer_t* writer, size_t count) {
-    if (writer->error == mpack_ok)
-        mpack_writer_flag_if_error(writer, mpack_track_bytes(&writer->track, false, count));
-}
-#endif
-
-static void mpack_writer_clear(mpack_writer_t* writer) {
-    #if MPACK_COMPATIBILITY
-    writer->version = mpack_version_current;
-    #endif
-    writer->flush = NULL;
-    writer->error_fn = NULL;
-    writer->teardown = NULL;
-    writer->context = NULL;
-
-    writer->buffer = NULL;
-    writer->current = NULL;
-    writer->end = NULL;
-    writer->error = mpack_ok;
-
-    #if MPACK_WRITE_TRACKING
-    mpack_memset(&writer->track, 0, sizeof(writer->track));
-    #endif
-}
-
-void mpack_writer_init(mpack_writer_t* writer, char* buffer, size_t size) {
-    mpack_assert(buffer != NULL, "cannot initialize writer with empty buffer");
-    mpack_writer_clear(writer);
-    writer->buffer = buffer;
-    writer->current = buffer;
-    writer->end = writer->buffer + size;
-
-    #if MPACK_WRITE_TRACKING
-    mpack_writer_flag_if_error(writer, mpack_track_init(&writer->track));
-    #endif
-
-    mpack_log("===========================\n");
-    mpack_log("initializing writer with buffer size %i\n", (int)size);
-}
-
-void mpack_writer_init_error(mpack_writer_t* writer, mpack_error_t error) {
-    mpack_writer_clear(writer);
-    writer->error = error;
-
-    mpack_log("===========================\n");
-    mpack_log("initializing writer in error state %i\n", (int)error);
-}
-
-void mpack_writer_set_flush(mpack_writer_t* writer, mpack_writer_flush_t flush) {
-    MPACK_STATIC_ASSERT(MPACK_WRITER_MINIMUM_BUFFER_SIZE >= MPACK_MAXIMUM_TAG_SIZE,
-            "minimum buffer size must fit any tag!");
-    MPACK_STATIC_ASSERT(31 + MPACK_TAG_SIZE_FIXSTR >= MPACK_WRITER_MINIMUM_BUFFER_SIZE,
-            "minimum buffer size must fit the largest possible fixstr!");
-
-    if (mpack_writer_buffer_size(writer) < MPACK_WRITER_MINIMUM_BUFFER_SIZE) {
-        mpack_break("buffer size is %i, but minimum buffer size for flush is %i",
-                (int)mpack_writer_buffer_size(writer), MPACK_WRITER_MINIMUM_BUFFER_SIZE);
-        mpack_writer_flag_error(writer, mpack_error_bug);
-        return;
-    }
-
-    writer->flush = flush;
-}
-
-#ifdef MPACK_MALLOC
-typedef struct mpack_growable_writer_t {
-    char** target_data;
-    size_t* target_size;
-} mpack_growable_writer_t;
-
-static char* mpack_writer_get_reserved(mpack_writer_t* writer) {
-    // This is in a separate function in order to avoid false strict aliasing
-    // warnings. We aren't actually violating strict aliasing (the reserved
-    // space is only ever dereferenced as an mpack_growable_writer_t.)
-    return (char*)writer->reserved;
-}
-
-static void mpack_growable_writer_flush(mpack_writer_t* writer, const char* data, size_t count) {
-
-    // This is an intrusive flush function which modifies the writer's buffer
-    // in response to a flush instead of emptying it in order to add more
-    // capacity for data. This removes the need to copy data from a fixed buffer
-    // into a growable one, improving performance.
-    //
-    // There are three ways flush can be called:
-    //   - flushing the buffer during writing (used is zero, count is all data, data is buffer)
-    //   - flushing extra data during writing (used is all flushed data, count is extra data, data is not buffer)
-    //   - flushing during teardown (used and count are both all flushed data, data is buffer)
-    //
-    // In the first two cases, we grow the buffer by at least double, enough
-    // to ensure that new data will fit. We ignore the teardown flush.
-
-    if (data == writer->buffer) {
-
-        // teardown, do nothing
-        if (mpack_writer_buffer_used(writer) == count)
-            return;
-
-        // otherwise leave the data in the buffer and just grow
-        writer->current = writer->buffer + count;
-        count = 0;
-    }
-
-    size_t used = mpack_writer_buffer_used(writer);
-    size_t size = mpack_writer_buffer_size(writer);
-
-    mpack_log("flush size %i used %i data %p buffer %p\n",
-            (int)count, (int)used, data, writer->buffer);
-
-    mpack_assert(data == writer->buffer || used + count > size,
-            "extra flush for %i but there is %i space left in the buffer! (%i/%i)",
-            (int)count, (int)mpack_writer_buffer_left(writer), (int)used, (int)size);
-
-    // grow to fit the data
-    // TODO: this really needs to correctly test for overflow
-    size_t new_size = size * 2;
-    while (new_size < used + count)
-        new_size *= 2;
-
-    mpack_log("flush growing buffer size from %i to %i\n", (int)size, (int)new_size);
-
-    // grow the buffer
-    char* new_buffer = (char*)mpack_realloc(writer->buffer, used, new_size);
-    if (new_buffer == NULL) {
-        mpack_writer_flag_error(writer, mpack_error_memory);
-        return;
-    }
-    writer->current = new_buffer + used;
-    writer->buffer = new_buffer;
-    writer->end = writer->buffer + new_size;
-
-    // append the extra data
-    if (count > 0) {
-        mpack_memcpy(writer->current, data, count);
-        writer->current += count;
-    }
-
-    mpack_log("new buffer %p, used %i\n", new_buffer, (int)mpack_writer_buffer_used(writer));
-}
-
-static void mpack_growable_writer_teardown(mpack_writer_t* writer) {
-    mpack_growable_writer_t* growable_writer = (mpack_growable_writer_t*)mpack_writer_get_reserved(writer);
-
-    if (mpack_writer_error(writer) == mpack_ok) {
-
-        // shrink the buffer to an appropriate size if the data is
-        // much smaller than the buffer
-        if (mpack_writer_buffer_used(writer) < mpack_writer_buffer_size(writer) / 2) {
-            size_t used = mpack_writer_buffer_used(writer);
-
-            // We always return a non-null pointer that must be freed, even if
-            // nothing was written. malloc() and realloc() do not necessarily
-            // do this so we enforce it ourselves.
-            size_t size = (used != 0) ? used : 1;
-
-            char* buffer = (char*)mpack_realloc(writer->buffer, used, size);
-            if (!buffer) {
-                MPACK_FREE(writer->buffer);
-                mpack_writer_flag_error(writer, mpack_error_memory);
-                return;
-            }
-            writer->buffer = buffer;
-            writer->end = (writer->current = writer->buffer + used);
-        }
-
-        *growable_writer->target_data = writer->buffer;
-        *growable_writer->target_size = mpack_writer_buffer_used(writer);
-        writer->buffer = NULL;
-
-    } else if (writer->buffer) {
-        MPACK_FREE(writer->buffer);
-        writer->buffer = NULL;
-    }
-
-    writer->context = NULL;
-}
-
-void mpack_writer_init_growable(mpack_writer_t* writer, char** target_data, size_t* target_size) {
-    mpack_assert(target_data != NULL, "cannot initialize writer without a destination for the data");
-    mpack_assert(target_size != NULL, "cannot initialize writer without a destination for the size");
-
-    *target_data = NULL;
-    *target_size = 0;
-
-    MPACK_STATIC_ASSERT(sizeof(mpack_growable_writer_t) <= sizeof(writer->reserved),
-            "not enough reserved space for growable writer!");
-    mpack_growable_writer_t* growable_writer = (mpack_growable_writer_t*)mpack_writer_get_reserved(writer);
-
-    growable_writer->target_data = target_data;
-    growable_writer->target_size = target_size;
-
-    size_t capacity = MPACK_BUFFER_SIZE;
-    char* buffer = (char*)MPACK_MALLOC(capacity);
-    if (buffer == NULL) {
-        mpack_writer_init_error(writer, mpack_error_memory);
-        return;
-    }
-
-    mpack_writer_init(writer, buffer, capacity);
-    mpack_writer_set_flush(writer, mpack_growable_writer_flush);
-    mpack_writer_set_teardown(writer, mpack_growable_writer_teardown);
-}
-#endif
-
-#if MPACK_STDIO
-static void mpack_file_writer_flush(mpack_writer_t* writer, const char* buffer, size_t count) {
-    FILE* file = (FILE*)writer->context;
-    size_t written = fwrite((const void*)buffer, 1, count, file);
-    if (written != count)
-        mpack_writer_flag_error(writer, mpack_error_io);
-}
-
-static void mpack_file_writer_teardown(mpack_writer_t* writer) {
-    MPACK_FREE(writer->buffer);
-    writer->buffer = NULL;
-    writer->context = NULL;
-}
-
-static void mpack_file_writer_teardown_close(mpack_writer_t* writer) {
-    FILE* file = (FILE*)writer->context;
-
-    if (file) {
-        int ret = fclose(file);
-        if (ret != 0)
-            mpack_writer_flag_error(writer, mpack_error_io);
-    }
-
-    mpack_file_writer_teardown(writer);
-}
-
-void mpack_writer_init_stdfile(mpack_writer_t* writer, FILE* file, bool close_when_done) {
-    mpack_assert(file != NULL, "file is NULL");
-
-    size_t capacity = MPACK_BUFFER_SIZE;
-    char* buffer = (char*)MPACK_MALLOC(capacity);
-    if (buffer == NULL) {
-        mpack_writer_init_error(writer, mpack_error_memory);
-        if (close_when_done) {
-            fclose(file);
-        }
-        return;
-    }
-
-    mpack_writer_init(writer, buffer, capacity);
-    mpack_writer_set_context(writer, file);
-    mpack_writer_set_flush(writer, mpack_file_writer_flush);
-    mpack_writer_set_teardown(writer, close_when_done ?
-            mpack_file_writer_teardown_close :
-            mpack_file_writer_teardown);
-}
-
-void mpack_writer_init_filename(mpack_writer_t* writer, const char* filename) {
-    mpack_assert(filename != NULL, "filename is NULL");
-
-    FILE* file = fopen(filename, "wb");
-    if (file == NULL) {
-        mpack_writer_init_error(writer, mpack_error_io);
-        return;
-    }
-
-    mpack_writer_init_stdfile(writer, file, true);
-}
-#endif
-
-void mpack_writer_flag_error(mpack_writer_t* writer, mpack_error_t error) {
-    mpack_log("writer %p setting error %i: %s\n", writer, (int)error, mpack_error_to_string(error));
-
-    if (writer->error == mpack_ok) {
-        writer->error = error;
-        if (writer->error_fn)
-            writer->error_fn(writer, writer->error);
-    }
-}
-
-MPACK_STATIC_INLINE void mpack_writer_flush_unchecked(mpack_writer_t* writer) {
-    // This is a bit ugly; we reset used before calling flush so that
-    // a flush function can distinguish between flushing the buffer
-    // versus flushing external data. see mpack_growable_writer_flush()
-    size_t used = mpack_writer_buffer_used(writer);
-    writer->current = writer->buffer;
-    writer->flush(writer, writer->buffer, used);
-}
-
-void mpack_writer_flush_message(mpack_writer_t* writer) {
-    if (writer->error != mpack_ok)
-        return;
-
-    #if MPACK_WRITE_TRACKING
-    mpack_writer_flag_if_error(writer, mpack_track_check_empty(&writer->track));
-    if (writer->error != mpack_ok)
-        return;
-    #endif
-
-    if (writer->flush == NULL) {
-        mpack_break("cannot call mpack_writer_flush_message() without a flush function!");
-        mpack_writer_flag_error(writer, mpack_error_bug);
-        return;
-    }
-
-    if (mpack_writer_buffer_used(writer) > 0)
-        mpack_writer_flush_unchecked(writer);
-}
-
-// Ensures there are at least count bytes free in the buffer. This
-// will flag an error if the flush function fails to make enough
-// room in the buffer.
-MPACK_NOINLINE static bool mpack_writer_ensure(mpack_writer_t* writer, size_t count) {
-    mpack_assert(count != 0, "cannot ensure zero bytes!");
-    mpack_assert(count <= MPACK_WRITER_MINIMUM_BUFFER_SIZE,
-            "cannot ensure %i bytes, this is more than the minimum buffer size %i!",
-            (int)count, (int)MPACK_WRITER_MINIMUM_BUFFER_SIZE);
-    mpack_assert(count > mpack_writer_buffer_left(writer),
-            "request to ensure %i bytes but there are already %i left in the buffer!",
-            (int)count, (int)mpack_writer_buffer_left(writer));
-
-    mpack_log("ensuring %i bytes, %i left\n", (int)count, (int)mpack_writer_buffer_left(writer));
-
-    if (mpack_writer_error(writer) != mpack_ok)
-        return false;
-
-    if (writer->flush == NULL) {
-        mpack_writer_flag_error(writer, mpack_error_too_big);
-        return false;
-    }
-
-    mpack_writer_flush_unchecked(writer);
-    if (mpack_writer_error(writer) != mpack_ok)
-        return false;
-
-    if (mpack_writer_buffer_left(writer) >= count)
-        return true;
-
-    mpack_writer_flag_error(writer, mpack_error_io);
-    return false;
-}
-
-// Writes encoded bytes to the buffer when we already know the data
-// does not fit in the buffer (i.e. it straddles the edge of the
-// buffer.) If there is a flush function, it is guaranteed to be
-// called; otherwise mpack_error_too_big is raised.
-MPACK_NOINLINE static void mpack_write_native_straddle(mpack_writer_t* writer, const char* p, size_t count) {
-    mpack_assert(count == 0 || p != NULL, "data pointer for %i bytes is NULL", (int)count);
-
-    if (mpack_writer_error(writer) != mpack_ok)
-        return;
-    mpack_log("big write for %i bytes from %p, %i space left in buffer\n",
-            (int)count, p, (int)mpack_writer_buffer_left(writer));
-    mpack_assert(count > mpack_writer_buffer_left(writer),
-            "big write requested for %i bytes, but there is %i available "
-            "space in buffer. should have called mpack_write_native() instead",
-            (int)count, (int)(mpack_writer_buffer_left(writer)));
-
-    // we'll need a flush function
-    if (!writer->flush) {
-        mpack_writer_flag_error(writer, mpack_error_too_big);
-        return;
-    }
-
-    // flush the buffer
-    mpack_writer_flush_unchecked(writer);
-    if (mpack_writer_error(writer) != mpack_ok)
-        return;
-
-    // note that an intrusive flush function (such as mpack_growable_writer_flush())
-    // may have changed size and/or reset used to a non-zero value. we treat both as
-    // though they may have changed, and there may still be data in the buffer.
-
-    // flush the extra data directly if it doesn't fit in the buffer
-    if (count > mpack_writer_buffer_left(writer)) {
-        writer->flush(writer, p, count);
-        if (mpack_writer_error(writer) != mpack_ok)
-            return;
-    } else {
-        mpack_memcpy(writer->current, p, count);
-        writer->current += count;
-    }
-}
-
-// Writes encoded bytes to the buffer, flushing if necessary.
-MPACK_STATIC_INLINE void mpack_write_native(mpack_writer_t* writer, const char* p, size_t count) {
-    mpack_assert(count == 0 || p != NULL, "data pointer for %i bytes is NULL", (int)count);
-
-    if (mpack_writer_buffer_left(writer) < count) {
-        mpack_write_native_straddle(writer, p, count);
-    } else {
-        mpack_memcpy(writer->current, p, count);
-        writer->current += count;
-    }
-}
-
-mpack_error_t mpack_writer_destroy(mpack_writer_t* writer) {
-
-    // clean up tracking, asserting if we're not already in an error state
-    #if MPACK_WRITE_TRACKING
-    mpack_track_destroy(&writer->track, writer->error != mpack_ok);
-    #endif
-
-    // flush any outstanding data
-    if (mpack_writer_error(writer) == mpack_ok && mpack_writer_buffer_used(writer) != 0 && writer->flush != NULL) {
-        writer->flush(writer, writer->buffer, mpack_writer_buffer_used(writer));
-        writer->flush = NULL;
-    }
-
-    if (writer->teardown) {
-        writer->teardown(writer);
-        writer->teardown = NULL;
-    }
-
-    return writer->error;
-}
-
-void mpack_write_tag(mpack_writer_t* writer, mpack_tag_t value) {
-    switch (value.type) {
-        case mpack_type_missing:
-            mpack_break("cannot write a missing value!");
-            mpack_writer_flag_error(writer, mpack_error_bug);
-            return;
-
-        case mpack_type_nil:    mpack_write_nil   (writer);            return;
-        case mpack_type_bool:   mpack_write_bool  (writer, value.v.b); return;
-        case mpack_type_float:  mpack_write_float (writer, value.v.f); return;
-        case mpack_type_double: mpack_write_double(writer, value.v.d); return;
-        case mpack_type_int:    mpack_write_int   (writer, value.v.i); return;
-        case mpack_type_uint:   mpack_write_uint  (writer, value.v.u); return;
-
-        case mpack_type_str: mpack_start_str(writer, value.v.l); return;
-        case mpack_type_bin: mpack_start_bin(writer, value.v.l); return;
-
-        #if MPACK_EXTENSIONS
-        case mpack_type_ext:
-            mpack_start_ext(writer, mpack_tag_ext_exttype(&value), mpack_tag_ext_length(&value));
-            return;
-        #endif
-
-        case mpack_type_array: mpack_start_array(writer, value.v.n); return;
-        case mpack_type_map:   mpack_start_map(writer, value.v.n);   return;
-    }
-
-    mpack_break("unrecognized type %i", (int)value.type);
-    mpack_writer_flag_error(writer, mpack_error_bug);
-}
-
-MPACK_STATIC_INLINE void mpack_write_byte_element(mpack_writer_t* writer, char value) {
-    mpack_writer_track_element(writer);
-    if (MPACK_LIKELY(mpack_writer_buffer_left(writer) >= 1) || mpack_writer_ensure(writer, 1))
-        *(writer->current++) = value;
-}
-
-void mpack_write_nil(mpack_writer_t* writer) {
-    mpack_write_byte_element(writer, (char)0xc0);
-}
-
-void mpack_write_bool(mpack_writer_t* writer, bool value) {
-    mpack_write_byte_element(writer, (char)(0xc2 | (value ? 1 : 0)));
-}
-
-void mpack_write_true(mpack_writer_t* writer) {
-    mpack_write_byte_element(writer, (char)0xc3);
-}
-
-void mpack_write_false(mpack_writer_t* writer) {
-    mpack_write_byte_element(writer, (char)0xc2);
-}
-
-void mpack_write_object_bytes(mpack_writer_t* writer, const char* data, size_t bytes) {
-    mpack_writer_track_element(writer);
-    mpack_write_native(writer, data, bytes);
-}
-
-/*
- * Encode functions
- */
-
-MPACK_STATIC_INLINE void mpack_encode_fixuint(char* p, uint8_t value) {
-    mpack_assert(value <= 127);
-    mpack_store_u8(p, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_u8(char* p, uint8_t value) {
-    mpack_assert(value > 127);
-    mpack_store_u8(p, 0xcc);
-    mpack_store_u8(p + 1, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_u16(char* p, uint16_t value) {
-    mpack_assert(value > UINT8_MAX);
-    mpack_store_u8(p, 0xcd);
-    mpack_store_u16(p + 1, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_u32(char* p, uint32_t value) {
-    mpack_assert(value > UINT16_MAX);
-    mpack_store_u8(p, 0xce);
-    mpack_store_u32(p + 1, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_u64(char* p, uint64_t value) {
-    mpack_assert(value > UINT32_MAX);
-    mpack_store_u8(p, 0xcf);
-    mpack_store_u64(p + 1, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_fixint(char* p, int8_t value) {
-    // this can encode positive or negative fixints
-    mpack_assert(value >= -32);
-    mpack_store_i8(p, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_i8(char* p, int8_t value) {
-    mpack_assert(value < -32);
-    mpack_store_u8(p, 0xd0);
-    mpack_store_i8(p + 1, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_i16(char* p, int16_t value) {
-    mpack_assert(value < INT8_MIN);
-    mpack_store_u8(p, 0xd1);
-    mpack_store_i16(p + 1, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_i32(char* p, int32_t value) {
-    mpack_assert(value < INT16_MIN);
-    mpack_store_u8(p, 0xd2);
-    mpack_store_i32(p + 1, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_i64(char* p, int64_t value) {
-    mpack_assert(value < INT32_MIN);
-    mpack_store_u8(p, 0xd3);
-    mpack_store_i64(p + 1, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_float(char* p, float value) {
-    mpack_store_u8(p, 0xca);
-    mpack_store_float(p + 1, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_double(char* p, double value) {
-    mpack_store_u8(p, 0xcb);
-    mpack_store_double(p + 1, value);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_fixarray(char* p, uint8_t count) {
-    mpack_assert(count <= 15);
-    mpack_store_u8(p, (uint8_t)(0x90 | count));
-}
-
-MPACK_STATIC_INLINE void mpack_encode_array16(char* p, uint16_t count) {
-    mpack_assert(count > 15);
-    mpack_store_u8(p, 0xdc);
-    mpack_store_u16(p + 1, count);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_array32(char* p, uint32_t count) {
-    mpack_assert(count > UINT16_MAX);
-    mpack_store_u8(p, 0xdd);
-    mpack_store_u32(p + 1, count);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_fixmap(char* p, uint8_t count) {
-    mpack_assert(count <= 15);
-    mpack_store_u8(p, (uint8_t)(0x80 | count));
-}
-
-MPACK_STATIC_INLINE void mpack_encode_map16(char* p, uint16_t count) {
-    mpack_assert(count > 15);
-    mpack_store_u8(p, 0xde);
-    mpack_store_u16(p + 1, count);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_map32(char* p, uint32_t count) {
-    mpack_assert(count > UINT16_MAX);
-    mpack_store_u8(p, 0xdf);
-    mpack_store_u32(p + 1, count);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_fixstr(char* p, uint8_t count) {
-    mpack_assert(count <= 31);
-    mpack_store_u8(p, (uint8_t)(0xa0 | count));
-}
-
-MPACK_STATIC_INLINE void mpack_encode_str8(char* p, uint8_t count) {
-    mpack_assert(count > 31);
-    mpack_store_u8(p, 0xd9);
-    mpack_store_u8(p + 1, count);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_str16(char* p, uint16_t count) {
-    // we might be encoding a raw in compatibility mode, so we
-    // allow count to be in the range [32, UINT8_MAX].
-    mpack_assert(count > 31);
-    mpack_store_u8(p, 0xda);
-    mpack_store_u16(p + 1, count);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_str32(char* p, uint32_t count) {
-    mpack_assert(count > UINT16_MAX);
-    mpack_store_u8(p, 0xdb);
-    mpack_store_u32(p + 1, count);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_bin8(char* p, uint8_t count) {
-    mpack_store_u8(p, 0xc4);
-    mpack_store_u8(p + 1, count);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_bin16(char* p, uint16_t count) {
-    mpack_assert(count > UINT8_MAX);
-    mpack_store_u8(p, 0xc5);
-    mpack_store_u16(p + 1, count);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_bin32(char* p, uint32_t count) {
-    mpack_assert(count > UINT16_MAX);
-    mpack_store_u8(p, 0xc6);
-    mpack_store_u32(p + 1, count);
-}
-
-#if MPACK_EXTENSIONS
-MPACK_STATIC_INLINE void mpack_encode_fixext1(char* p, int8_t exttype) {
-    mpack_store_u8(p, 0xd4);
-    mpack_store_i8(p + 1, exttype);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_fixext2(char* p, int8_t exttype) {
-    mpack_store_u8(p, 0xd5);
-    mpack_store_i8(p + 1, exttype);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_fixext4(char* p, int8_t exttype) {
-    mpack_store_u8(p, 0xd6);
-    mpack_store_i8(p + 1, exttype);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_fixext8(char* p, int8_t exttype) {
-    mpack_store_u8(p, 0xd7);
-    mpack_store_i8(p + 1, exttype);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_fixext16(char* p, int8_t exttype) {
-    mpack_store_u8(p, 0xd8);
-    mpack_store_i8(p + 1, exttype);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_ext8(char* p, int8_t exttype, uint8_t count) {
-    mpack_assert(count != 1 && count != 2 && count != 4 && count != 8 && count != 16);
-    mpack_store_u8(p, 0xc7);
-    mpack_store_u8(p + 1, count);
-    mpack_store_i8(p + 2, exttype);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_ext16(char* p, int8_t exttype, uint16_t count) {
-    mpack_assert(count > UINT8_MAX);
-    mpack_store_u8(p, 0xc8);
-    mpack_store_u16(p + 1, count);
-    mpack_store_i8(p + 3, exttype);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_ext32(char* p, int8_t exttype, uint32_t count) {
-    mpack_assert(count > UINT16_MAX);
-    mpack_store_u8(p, 0xc9);
-    mpack_store_u32(p + 1, count);
-    mpack_store_i8(p + 5, exttype);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_timestamp_4(char* p, uint32_t seconds) {
-    mpack_encode_fixext4(p, MPACK_EXTTYPE_TIMESTAMP);
-    mpack_store_u32(p + MPACK_TAG_SIZE_FIXEXT4, seconds);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_timestamp_8(char* p, int64_t seconds, uint32_t nanoseconds) {
-    mpack_assert(nanoseconds <= MPACK_TIMESTAMP_NANOSECONDS_MAX);
-    mpack_encode_fixext8(p, MPACK_EXTTYPE_TIMESTAMP);
-    uint64_t encoded = ((uint64_t)nanoseconds << 34) | (uint64_t)seconds;
-    mpack_store_u64(p + MPACK_TAG_SIZE_FIXEXT8, encoded);
-}
-
-MPACK_STATIC_INLINE void mpack_encode_timestamp_12(char* p, int64_t seconds, uint32_t nanoseconds) {
-    mpack_assert(nanoseconds <= MPACK_TIMESTAMP_NANOSECONDS_MAX);
-    mpack_encode_ext8(p, MPACK_EXTTYPE_TIMESTAMP, 12);
-    mpack_store_u32(p + MPACK_TAG_SIZE_EXT8, nanoseconds);
-    mpack_store_i64(p + MPACK_TAG_SIZE_EXT8 + 4, seconds);
-}
-#endif
-
-
-
-/*
- * Write functions
- */
-
-// This is a macro wrapper to the encode functions to encode
-// directly into the buffer. If mpack_writer_ensure() fails
-// it will flag an error so we don't have to do anything.
-#define MPACK_WRITE_ENCODED(encode_fn, size, ...) do {                                                 \
-    if (MPACK_LIKELY(mpack_writer_buffer_left(writer) >= size) || mpack_writer_ensure(writer, size)) { \
-        MPACK_EXPAND(encode_fn(writer->current, __VA_ARGS__));                                         \
-        writer->current += size;                                                                       \
-    }                                                                                                  \
-} while (0)
-
-void mpack_write_u8(mpack_writer_t* writer, uint8_t value) {
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    mpack_write_u64(writer, value);
-    #else
-    mpack_writer_track_element(writer);
-    if (value <= 127) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixuint, MPACK_TAG_SIZE_FIXUINT, value);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_u8, MPACK_TAG_SIZE_U8, value);
-    }
-    #endif
-}
-
-void mpack_write_u16(mpack_writer_t* writer, uint16_t value) {
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    mpack_write_u64(writer, value);
-    #else
-    mpack_writer_track_element(writer);
-    if (value <= 127) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixuint, MPACK_TAG_SIZE_FIXUINT, (uint8_t)value);
-    } else if (value <= UINT8_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_u8, MPACK_TAG_SIZE_U8, (uint8_t)value);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_u16, MPACK_TAG_SIZE_U16, value);
-    }
-    #endif
-}
-
-void mpack_write_u32(mpack_writer_t* writer, uint32_t value) {
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    mpack_write_u64(writer, value);
-    #else
-    mpack_writer_track_element(writer);
-    if (value <= 127) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixuint, MPACK_TAG_SIZE_FIXUINT, (uint8_t)value);
-    } else if (value <= UINT8_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_u8, MPACK_TAG_SIZE_U8, (uint8_t)value);
-    } else if (value <= UINT16_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_u16, MPACK_TAG_SIZE_U16, (uint16_t)value);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_u32, MPACK_TAG_SIZE_U32, value);
-    }
-    #endif
-}
-
-void mpack_write_u64(mpack_writer_t* writer, uint64_t value) {
-    mpack_writer_track_element(writer);
-
-    if (value <= 127) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixuint, MPACK_TAG_SIZE_FIXUINT, (uint8_t)value);
-    } else if (value <= UINT8_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_u8, MPACK_TAG_SIZE_U8, (uint8_t)value);
-    } else if (value <= UINT16_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_u16, MPACK_TAG_SIZE_U16, (uint16_t)value);
-    } else if (value <= UINT32_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_u32, MPACK_TAG_SIZE_U32, (uint32_t)value);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_u64, MPACK_TAG_SIZE_U64, value);
-    }
-}
-
-void mpack_write_i8(mpack_writer_t* writer, int8_t value) {
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    mpack_write_i64(writer, value);
-    #else
-    mpack_writer_track_element(writer);
-    if (value >= -32) {
-        // we encode positive and negative fixints together
-        MPACK_WRITE_ENCODED(mpack_encode_fixint, MPACK_TAG_SIZE_FIXINT, (int8_t)value);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_i8, MPACK_TAG_SIZE_I8, (int8_t)value);
-    }
-    #endif
-}
-
-void mpack_write_i16(mpack_writer_t* writer, int16_t value) {
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    mpack_write_i64(writer, value);
-    #else
-    mpack_writer_track_element(writer);
-    if (value >= -32) {
-        if (value <= 127) {
-            // we encode positive and negative fixints together
-            MPACK_WRITE_ENCODED(mpack_encode_fixint, MPACK_TAG_SIZE_FIXINT, (int8_t)value);
-        } else if (value <= UINT8_MAX) {
-            MPACK_WRITE_ENCODED(mpack_encode_u8, MPACK_TAG_SIZE_U8, (uint8_t)value);
-        } else {
-            MPACK_WRITE_ENCODED(mpack_encode_u16, MPACK_TAG_SIZE_U16, (uint16_t)value);
-        }
-    } else if (value >= INT8_MIN) {
-        MPACK_WRITE_ENCODED(mpack_encode_i8, MPACK_TAG_SIZE_I8, (int8_t)value);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_i16, MPACK_TAG_SIZE_I16, (int16_t)value);
-    }
-    #endif
-}
-
-void mpack_write_i32(mpack_writer_t* writer, int32_t value) {
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    mpack_write_i64(writer, value);
-    #else
-    mpack_writer_track_element(writer);
-    if (value >= -32) {
-        if (value <= 127) {
-            // we encode positive and negative fixints together
-            MPACK_WRITE_ENCODED(mpack_encode_fixint, MPACK_TAG_SIZE_FIXINT, (int8_t)value);
-        } else if (value <= UINT8_MAX) {
-            MPACK_WRITE_ENCODED(mpack_encode_u8, MPACK_TAG_SIZE_U8, (uint8_t)value);
-        } else if (value <= UINT16_MAX) {
-            MPACK_WRITE_ENCODED(mpack_encode_u16, MPACK_TAG_SIZE_U16, (uint16_t)value);
-        } else {
-            MPACK_WRITE_ENCODED(mpack_encode_u32, MPACK_TAG_SIZE_U32, (uint32_t)value);
-        }
-    } else if (value >= INT8_MIN) {
-        MPACK_WRITE_ENCODED(mpack_encode_i8, MPACK_TAG_SIZE_I8, (int8_t)value);
-    } else if (value >= INT16_MIN) {
-        MPACK_WRITE_ENCODED(mpack_encode_i16, MPACK_TAG_SIZE_I16, (int16_t)value);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_i32, MPACK_TAG_SIZE_I32, value);
-    }
-    #endif
-}
-
-void mpack_write_i64(mpack_writer_t* writer, int64_t value) {
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    if (value > 127) {
-        // for non-fix positive ints we call the u64 writer to save space
-        mpack_write_u64(writer, (uint64_t)value);
-        return;
-    }
-    #endif
-
-    mpack_writer_track_element(writer);
-    if (value >= -32) {
-        #if MPACK_OPTIMIZE_FOR_SIZE
-        MPACK_WRITE_ENCODED(mpack_encode_fixint, MPACK_TAG_SIZE_FIXINT, (int8_t)value);
-        #else
-        if (value <= 127) {
-            MPACK_WRITE_ENCODED(mpack_encode_fixint, MPACK_TAG_SIZE_FIXINT, (int8_t)value);
-        } else if (value <= UINT8_MAX) {
-            MPACK_WRITE_ENCODED(mpack_encode_u8, MPACK_TAG_SIZE_U8, (uint8_t)value);
-        } else if (value <= UINT16_MAX) {
-            MPACK_WRITE_ENCODED(mpack_encode_u16, MPACK_TAG_SIZE_U16, (uint16_t)value);
-        } else if (value <= UINT32_MAX) {
-            MPACK_WRITE_ENCODED(mpack_encode_u32, MPACK_TAG_SIZE_U32, (uint32_t)value);
-        } else {
-            MPACK_WRITE_ENCODED(mpack_encode_u64, MPACK_TAG_SIZE_U64, (uint64_t)value);
-        }
-        #endif
-    } else if (value >= INT8_MIN) {
-        MPACK_WRITE_ENCODED(mpack_encode_i8, MPACK_TAG_SIZE_I8, (int8_t)value);
-    } else if (value >= INT16_MIN) {
-        MPACK_WRITE_ENCODED(mpack_encode_i16, MPACK_TAG_SIZE_I16, (int16_t)value);
-    } else if (value >= INT32_MIN) {
-        MPACK_WRITE_ENCODED(mpack_encode_i32, MPACK_TAG_SIZE_I32, (int32_t)value);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_i64, MPACK_TAG_SIZE_I64, value);
-    }
-}
-
-void mpack_write_float(mpack_writer_t* writer, float value) {
-    mpack_writer_track_element(writer);
-    MPACK_WRITE_ENCODED(mpack_encode_float, MPACK_TAG_SIZE_FLOAT, value);
-}
-
-void mpack_write_double(mpack_writer_t* writer, double value) {
-    mpack_writer_track_element(writer);
-    MPACK_WRITE_ENCODED(mpack_encode_double, MPACK_TAG_SIZE_DOUBLE, value);
-}
-
-#if MPACK_EXTENSIONS
-void mpack_write_timestamp(mpack_writer_t* writer, int64_t seconds, uint32_t nanoseconds) {
-    #if MPACK_COMPATIBILITY
-    if (writer->version <= mpack_version_v4) {
-        mpack_break("Timestamps require spec version v5 or later. This writer is in v%i mode.", (int)writer->version);
-        mpack_writer_flag_error(writer, mpack_error_bug);
-        return;
-    }
-    #endif
-
-    if (nanoseconds > MPACK_TIMESTAMP_NANOSECONDS_MAX) {
-        mpack_break("timestamp nanoseconds out of bounds: %u", nanoseconds);
-        mpack_writer_flag_error(writer, mpack_error_bug);
-        return;
-    }
-
-    mpack_writer_track_element(writer);
-
-    if (seconds < 0 || seconds >= (INT64_C(1) << 34)) {
-        MPACK_WRITE_ENCODED(mpack_encode_timestamp_12, MPACK_EXT_SIZE_TIMESTAMP12, seconds, nanoseconds);
-    } else if (seconds > UINT32_MAX || nanoseconds > 0) {
-        MPACK_WRITE_ENCODED(mpack_encode_timestamp_8, MPACK_EXT_SIZE_TIMESTAMP8, seconds, nanoseconds);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_timestamp_4, MPACK_EXT_SIZE_TIMESTAMP4, (uint32_t)seconds);
-    }
-}
-#endif
-
-void mpack_start_array(mpack_writer_t* writer, uint32_t count) {
-    mpack_writer_track_element(writer);
-
-    if (count <= 15) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixarray, MPACK_TAG_SIZE_FIXARRAY, (uint8_t)count);
-    } else if (count <= UINT16_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_array16, MPACK_TAG_SIZE_ARRAY16, (uint16_t)count);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_array32, MPACK_TAG_SIZE_ARRAY32, (uint32_t)count);
-    }
-
-    mpack_writer_track_push(writer, mpack_type_array, count);
-}
-
-void mpack_start_map(mpack_writer_t* writer, uint32_t count) {
-    mpack_writer_track_element(writer);
-
-    if (count <= 15) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixmap, MPACK_TAG_SIZE_FIXMAP, (uint8_t)count);
-    } else if (count <= UINT16_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_map16, MPACK_TAG_SIZE_MAP16, (uint16_t)count);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_map32, MPACK_TAG_SIZE_MAP32, (uint32_t)count);
-    }
-
-    mpack_writer_track_push(writer, mpack_type_map, count);
-}
-
-static void mpack_start_str_notrack(mpack_writer_t* writer, uint32_t count) {
-    if (count <= 31) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixstr, MPACK_TAG_SIZE_FIXSTR, (uint8_t)count);
-
-    // str8 is only supported in v5 or later.
-    } else if (count <= UINT8_MAX
-            #if MPACK_COMPATIBILITY
-            && writer->version >= mpack_version_v5
-            #endif
-            ) {
-        MPACK_WRITE_ENCODED(mpack_encode_str8, MPACK_TAG_SIZE_STR8, (uint8_t)count);
-
-    } else if (count <= UINT16_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_str16, MPACK_TAG_SIZE_STR16, (uint16_t)count);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_str32, MPACK_TAG_SIZE_STR32, (uint32_t)count);
-    }
-}
-
-static void mpack_start_bin_notrack(mpack_writer_t* writer, uint32_t count) {
-    #if MPACK_COMPATIBILITY
-    // In the v4 spec, there was only the raw type for any kind of
-    // variable-length data. In v4 mode, we support the bin functions,
-    // but we produce an old-style raw.
-    if (writer->version <= mpack_version_v4) {
-        mpack_start_str_notrack(writer, count);
-        return;
-    }
-    #endif
-
-    if (count <= UINT8_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_bin8, MPACK_TAG_SIZE_BIN8, (uint8_t)count);
-    } else if (count <= UINT16_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_bin16, MPACK_TAG_SIZE_BIN16, (uint16_t)count);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_bin32, MPACK_TAG_SIZE_BIN32, (uint32_t)count);
-    }
-}
-
-void mpack_start_str(mpack_writer_t* writer, uint32_t count) {
-    mpack_writer_track_element(writer);
-    mpack_start_str_notrack(writer, count);
-    mpack_writer_track_push(writer, mpack_type_str, count);
-}
-
-void mpack_start_bin(mpack_writer_t* writer, uint32_t count) {
-    mpack_writer_track_element(writer);
-    mpack_start_bin_notrack(writer, count);
-    mpack_writer_track_push(writer, mpack_type_bin, count);
-}
-
-#if MPACK_EXTENSIONS
-void mpack_start_ext(mpack_writer_t* writer, int8_t exttype, uint32_t count) {
-    #if MPACK_COMPATIBILITY
-    if (writer->version <= mpack_version_v4) {
-        mpack_break("Ext types require spec version v5 or later. This writer is in v%i mode.", (int)writer->version);
-        mpack_writer_flag_error(writer, mpack_error_bug);
-        return;
-    }
-    #endif
-
-    mpack_writer_track_element(writer);
-
-    if (count == 1) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixext1, MPACK_TAG_SIZE_FIXEXT1, exttype);
-    } else if (count == 2) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixext2, MPACK_TAG_SIZE_FIXEXT2, exttype);
-    } else if (count == 4) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixext4, MPACK_TAG_SIZE_FIXEXT4, exttype);
-    } else if (count == 8) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixext8, MPACK_TAG_SIZE_FIXEXT8, exttype);
-    } else if (count == 16) {
-        MPACK_WRITE_ENCODED(mpack_encode_fixext16, MPACK_TAG_SIZE_FIXEXT16, exttype);
-    } else if (count <= UINT8_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_ext8, MPACK_TAG_SIZE_EXT8, exttype, (uint8_t)count);
-    } else if (count <= UINT16_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_ext16, MPACK_TAG_SIZE_EXT16, exttype, (uint16_t)count);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_ext32, MPACK_TAG_SIZE_EXT32, exttype, (uint32_t)count);
-    }
-
-    mpack_writer_track_push(writer, mpack_type_ext, count);
-}
-#endif
-
-
-
-/*
- * Compound helpers and other functions
- */
-
-void mpack_write_str(mpack_writer_t* writer, const char* data, uint32_t count) {
-    mpack_assert(data != NULL, "data for string of length %i is NULL", (int)count);
-
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    mpack_writer_track_element(writer);
-    mpack_start_str_notrack(writer, count);
-    mpack_write_native(writer, data, count);
-    #else
-
-    mpack_writer_track_element(writer);
-
-    if (count <= 31) {
-        // The minimum buffer size when using a flush function is guaranteed to
-        // fit the largest possible fixstr.
-        size_t size = count + MPACK_TAG_SIZE_FIXSTR;
-        if (MPACK_LIKELY(mpack_writer_buffer_left(writer) >= size) || mpack_writer_ensure(writer, size)) {
-            char* MPACK_RESTRICT p = writer->current;
-            mpack_encode_fixstr(p, (uint8_t)count);
-            mpack_memcpy(p + MPACK_TAG_SIZE_FIXSTR, data, count);
-            writer->current += count + MPACK_TAG_SIZE_FIXSTR;
-        }
-        return;
-    }
-
-    if (count <= UINT8_MAX
-            #if MPACK_COMPATIBILITY
-            && writer->version >= mpack_version_v5
-            #endif
-            ) {
-        if (count + MPACK_TAG_SIZE_STR8 <= mpack_writer_buffer_left(writer)) {
-            char* MPACK_RESTRICT p = writer->current;
-            mpack_encode_str8(p, (uint8_t)count);
-            mpack_memcpy(p + MPACK_TAG_SIZE_STR8, data, count);
-            writer->current += count + MPACK_TAG_SIZE_STR8;
-        } else {
-            MPACK_WRITE_ENCODED(mpack_encode_str8, MPACK_TAG_SIZE_STR8, (uint8_t)count);
-            mpack_write_native(writer, data, count);
-        }
-        return;
-    }
-
-    // str16 and str32 are likely to be a significant fraction of the buffer
-    // size, so we don't bother with a combined space check in order to
-    // minimize code size.
-    if (count <= UINT16_MAX) {
-        MPACK_WRITE_ENCODED(mpack_encode_str16, MPACK_TAG_SIZE_STR16, (uint16_t)count);
-        mpack_write_native(writer, data, count);
-    } else {
-        MPACK_WRITE_ENCODED(mpack_encode_str32, MPACK_TAG_SIZE_STR32, (uint32_t)count);
-        mpack_write_native(writer, data, count);
-    }
-
-    #endif
-}
-
-void mpack_write_bin(mpack_writer_t* writer, const char* data, uint32_t count) {
-    mpack_assert(data != NULL, "data pointer for bin of %i bytes is NULL", (int)count);
-    mpack_start_bin(writer, count);
-    mpack_write_bytes(writer, data, count);
-    mpack_finish_bin(writer);
-}
-
-#if MPACK_EXTENSIONS
-void mpack_write_ext(mpack_writer_t* writer, int8_t exttype, const char* data, uint32_t count) {
-    mpack_assert(data != NULL, "data pointer for ext of type %i and %i bytes is NULL", exttype, (int)count);
-    mpack_start_ext(writer, exttype, count);
-    mpack_write_bytes(writer, data, count);
-    mpack_finish_ext(writer);
-}
-#endif
-
-void mpack_write_bytes(mpack_writer_t* writer, const char* data, size_t count) {
-    mpack_assert(data != NULL, "data pointer for %i bytes is NULL", (int)count);
-    mpack_writer_track_bytes(writer, count);
-    mpack_write_native(writer, data, count);
-}
-
-void mpack_write_cstr(mpack_writer_t* writer, const char* cstr) {
-    mpack_assert(cstr != NULL, "cstr pointer is NULL");
-    size_t length = mpack_strlen(cstr);
-    if (length > UINT32_MAX)
-        mpack_writer_flag_error(writer, mpack_error_invalid);
-    mpack_write_str(writer, cstr, (uint32_t)length);
-}
-
-void mpack_write_cstr_or_nil(mpack_writer_t* writer, const char* cstr) {
-    if (cstr)
-        mpack_write_cstr(writer, cstr);
-    else
-        mpack_write_nil(writer);
-}
-
-void mpack_write_utf8(mpack_writer_t* writer, const char* str, uint32_t length) {
-    mpack_assert(str != NULL, "data for string of length %i is NULL", (int)length);
-    if (!mpack_utf8_check(str, length)) {
-        mpack_writer_flag_error(writer, mpack_error_invalid);
-        return;
-    }
-    mpack_write_str(writer, str, length);
-}
-
-void mpack_write_utf8_cstr(mpack_writer_t* writer, const char* cstr) {
-    mpack_assert(cstr != NULL, "cstr pointer is NULL");
-    size_t length = mpack_strlen(cstr);
-    if (length > UINT32_MAX) {
-        mpack_writer_flag_error(writer, mpack_error_invalid);
-        return;
-    }
-    mpack_write_utf8(writer, cstr, (uint32_t)length);
-}
-
-void mpack_write_utf8_cstr_or_nil(mpack_writer_t* writer, const char* cstr) {
-    if (cstr)
-        mpack_write_utf8_cstr(writer, cstr);
-    else
-        mpack_write_nil(writer);
-}
-
-#endif
-
-
-/* mpack/mpack-reader.c.c */
-
-#define MPACK_INTERNAL 1
-
-/* #include "mpack-reader.h" */
-
-#if MPACK_READER
-
-static void mpack_reader_skip_using_fill(mpack_reader_t* reader, size_t count);
-
-void mpack_reader_init(mpack_reader_t* reader, char* buffer, size_t size, size_t count) {
-    mpack_assert(buffer != NULL, "buffer is NULL");
-
-    mpack_memset(reader, 0, sizeof(*reader));
-    reader->buffer = buffer;
-    reader->size = size;
-    reader->data = buffer;
-    reader->end = buffer + count;
-
-    #if MPACK_READ_TRACKING
-    mpack_reader_flag_if_error(reader, mpack_track_init(&reader->track));
-    #endif
-
-    mpack_log("===========================\n");
-    mpack_log("initializing reader with buffer size %i\n", (int)size);
-}
-
-void mpack_reader_init_error(mpack_reader_t* reader, mpack_error_t error) {
-    mpack_memset(reader, 0, sizeof(*reader));
-    reader->error = error;
-
-    mpack_log("===========================\n");
-    mpack_log("initializing reader error state %i\n", (int)error);
-}
-
-void mpack_reader_init_data(mpack_reader_t* reader, const char* data, size_t count) {
-    mpack_assert(data != NULL, "data is NULL");
-
-    mpack_memset(reader, 0, sizeof(*reader));
-    reader->data = data;
-    reader->end = data + count;
-
-    #if MPACK_READ_TRACKING
-    mpack_reader_flag_if_error(reader, mpack_track_init(&reader->track));
-    #endif
-
-    mpack_log("===========================\n");
-    mpack_log("initializing reader with data size %i\n", (int)count);
-}
-
-void mpack_reader_set_fill(mpack_reader_t* reader, mpack_reader_fill_t fill) {
-    MPACK_STATIC_ASSERT(MPACK_READER_MINIMUM_BUFFER_SIZE >= MPACK_MAXIMUM_TAG_SIZE,
-            "minimum buffer size must fit any tag!");
-
-    if (reader->size == 0) {
-        mpack_break("cannot use fill function without a writeable buffer!");
-        mpack_reader_flag_error(reader, mpack_error_bug);
-        return;
-    }
-
-    if (reader->size < MPACK_READER_MINIMUM_BUFFER_SIZE) {
-        mpack_break("buffer size is %i, but minimum buffer size for fill is %i",
-                (int)reader->size, MPACK_READER_MINIMUM_BUFFER_SIZE);
-        mpack_reader_flag_error(reader, mpack_error_bug);
-        return;
-    }
-
-    reader->fill = fill;
-}
-
-void mpack_reader_set_skip(mpack_reader_t* reader, mpack_reader_skip_t skip) {
-    mpack_assert(reader->size != 0, "cannot use skip function without a writeable buffer!");
-    reader->skip = skip;
-}
-
-#if MPACK_STDIO
-static size_t mpack_file_reader_fill(mpack_reader_t* reader, char* buffer, size_t count) {
-    if (feof((FILE *)reader->context)) {
-       mpack_reader_flag_error(reader, mpack_error_eof);
-       return 0;
-    }
-    return fread((void*)buffer, 1, count, (FILE*)reader->context);
-}
-
-static void mpack_file_reader_skip(mpack_reader_t* reader, size_t count) {
-    if (mpack_reader_error(reader) != mpack_ok)
-        return;
-    FILE* file = (FILE*)reader->context;
-
-    // We call ftell() to test whether the stream is seekable
-    // without causing a file error.
-    if (ftell(file) >= 0) {
-        mpack_log("seeking forward %i bytes\n", (int)count);
-        if (fseek(file, (long int)count, SEEK_CUR) == 0)
-            return;
-        mpack_log("fseek() didn't return zero!\n");
-        if (ferror(file)) {
-            mpack_reader_flag_error(reader, mpack_error_io);
-            return;
-        }
-    }
-
-    // If the stream is not seekable, fall back to the fill function.
-    mpack_reader_skip_using_fill(reader, count);
-}
-
-static void mpack_file_reader_teardown(mpack_reader_t* reader) {
-    MPACK_FREE(reader->buffer);
-    reader->buffer = NULL;
-    reader->context = NULL;
-    reader->size = 0;
-    reader->fill = NULL;
-    reader->skip = NULL;
-    reader->teardown = NULL;
-}
-
-static void mpack_file_reader_teardown_close(mpack_reader_t* reader) {
-    FILE* file = (FILE*)reader->context;
-
-    if (file) {
-        int ret = fclose(file);
-        if (ret != 0)
-            mpack_reader_flag_error(reader, mpack_error_io);
-    }
-
-    mpack_file_reader_teardown(reader);
-}
-
-void mpack_reader_init_stdfile(mpack_reader_t* reader, FILE* file, bool close_when_done) {
-    mpack_assert(file != NULL, "file is NULL");
-
-    size_t capacity = MPACK_BUFFER_SIZE;
-    char* buffer = (char*)MPACK_MALLOC(capacity);
-    if (buffer == NULL) {
-        mpack_reader_init_error(reader, mpack_error_memory);
-        if (close_when_done) {
-            fclose(file);
-        }
-        return;
-    }
-
-    mpack_reader_init(reader, buffer, capacity, 0);
-    mpack_reader_set_context(reader, file);
-    mpack_reader_set_fill(reader, mpack_file_reader_fill);
-    mpack_reader_set_skip(reader, mpack_file_reader_skip);
-    mpack_reader_set_teardown(reader, close_when_done ?
-            mpack_file_reader_teardown_close :
-            mpack_file_reader_teardown);
-}
-
-void mpack_reader_init_filename(mpack_reader_t* reader, const char* filename) {
-    mpack_assert(filename != NULL, "filename is NULL");
-
-    FILE* file = fopen(filename, "rb");
-    if (file == NULL) {
-        mpack_reader_init_error(reader, mpack_error_io);
-        return;
-    }
-
-    mpack_reader_init_stdfile(reader, file, true);
-}
-#endif
-
-mpack_error_t mpack_reader_destroy(mpack_reader_t* reader) {
-
-    // clean up tracking, asserting if we're not already in an error state
-    #if MPACK_READ_TRACKING
-    mpack_reader_flag_if_error(reader, mpack_track_destroy(&reader->track, mpack_reader_error(reader) != mpack_ok));
-    #endif
-
-    if (reader->teardown)
-        reader->teardown(reader);
-    reader->teardown = NULL;
-
-    return reader->error;
-}
-
-size_t mpack_reader_remaining(mpack_reader_t* reader, const char** data) {
-    if (mpack_reader_error(reader) != mpack_ok)
-        return 0;
-
-    #if MPACK_READ_TRACKING
-    if (mpack_reader_flag_if_error(reader, mpack_track_check_empty(&reader->track)) != mpack_ok)
-        return 0;
-    #endif
-
-    if (data)
-        *data = reader->data;
-    return (size_t)(reader->end - reader->data);
-}
-
-void mpack_reader_flag_error(mpack_reader_t* reader, mpack_error_t error) {
-    mpack_log("reader %p setting error %i: %s\n", reader, (int)error, mpack_error_to_string(error));
-
-    if (reader->error == mpack_ok) {
-        reader->error = error;
-        reader->end = reader->data;
-        if (reader->error_fn)
-            reader->error_fn(reader, error);
-    }
-}
-
-// Loops on the fill function, reading between the minimum and
-// maximum number of bytes and flagging an error if it fails.
-MPACK_NOINLINE static size_t mpack_fill_range(mpack_reader_t* reader, char* p, size_t min_bytes, size_t max_bytes) {
-    mpack_assert(reader->fill != NULL, "mpack_fill_range() called with no fill function?");
-    mpack_assert(min_bytes > 0, "cannot fill zero bytes!");
-    mpack_assert(max_bytes >= min_bytes, "min_bytes %i cannot be larger than max_bytes %i!",
-            (int)min_bytes, (int)max_bytes);
-
-    size_t count = 0;
-    while (count < min_bytes) {
-        size_t read = reader->fill(reader, p + count, max_bytes - count);
-
-        // Reader fill functions can flag an error or return 0 on failure. We
-        // also guard against functions that -1 just in case.
-        if (mpack_reader_error(reader) != mpack_ok)
-            return 0;
-        if (read == 0 || read == ((size_t)(-1))) {
-            mpack_reader_flag_error(reader, mpack_error_io);
-            return 0;
-        }
-
-        count += read;
-    }
-    return count;
-}
-
-MPACK_NOINLINE bool mpack_reader_ensure_straddle(mpack_reader_t* reader, size_t count) {
-    mpack_assert(count != 0, "cannot ensure zero bytes!");
-    mpack_assert(reader->error == mpack_ok, "reader cannot be in an error state!");
-
-    mpack_assert(count > (size_t)(reader->end - reader->data),
-            "straddling ensure requested for %i bytes, but there are %i bytes "
-            "left in buffer. call mpack_reader_ensure() instead",
-            (int)count, (int)(reader->end - reader->data));
-
-    // we'll need a fill function to get more data. if there's no
-    // fill function, the buffer should contain an entire MessagePack
-    // object, so we raise mpack_error_invalid instead of mpack_error_io
-    // on truncated data.
-    if (reader->fill == NULL) {
-        mpack_reader_flag_error(reader, mpack_error_invalid);
-        return false;
-    }
-
-    // we need enough space in the buffer. if the buffer is not
-    // big enough, we return mpack_error_too_big (since this is
-    // for an in-place read larger than the buffer size.)
-    if (count > reader->size) {
-        mpack_reader_flag_error(reader, mpack_error_too_big);
-        return false;
-    }
-
-    // move the existing data to the start of the buffer
-    size_t left = (size_t)(reader->end - reader->data);
-    mpack_memmove(reader->buffer, reader->data, left);
-    reader->end -= reader->data - reader->buffer;
-    reader->data = reader->buffer;
-
-    // read at least the necessary number of bytes, accepting up to the
-    // buffer size
-    size_t read = mpack_fill_range(reader, reader->buffer + left,
-            count - left, reader->size - left);
-    if (mpack_reader_error(reader) != mpack_ok)
-        return false;
-    reader->end += read;
-    return true;
-}
-
-// Reads count bytes into p. Used when there are not enough bytes
-// left in the buffer to satisfy a read.
-MPACK_NOINLINE void mpack_read_native_straddle(mpack_reader_t* reader, char* p, size_t count) {
-    mpack_assert(count == 0 || p != NULL, "data pointer for %i bytes is NULL", (int)count);
-
-    if (mpack_reader_error(reader) != mpack_ok) {
-        mpack_memset(p, 0, count);
-        return;
-    }
-
-    size_t left = (size_t)(reader->end - reader->data);
-    mpack_log("big read for %i bytes into %p, %i left in buffer, buffer size %i\n",
-            (int)count, p, (int)left, (int)reader->size);
-
-    if (count <= left) {
-        mpack_assert(0,
-                "big read requested for %i bytes, but there are %i bytes "
-                "left in buffer. call mpack_read_native() instead",
-                (int)count, (int)left);
-        mpack_reader_flag_error(reader, mpack_error_bug);
-        mpack_memset(p, 0, count);
-        return;
-    }
-
-    // we'll need a fill function to get more data. if there's no
-    // fill function, the buffer should contain an entire MessagePack
-    // object, so we raise mpack_error_invalid instead of mpack_error_io
-    // on truncated data.
-    if (reader->fill == NULL) {
-        mpack_reader_flag_error(reader, mpack_error_invalid);
-        mpack_memset(p, 0, count);
-        return;
-    }
-
-    if (reader->size == 0) {
-        // somewhat debatable what error should be returned here. when
-        // initializing a reader with an in-memory buffer it's not
-        // necessarily a bug if the data is blank; it might just have
-        // been truncated to zero. for this reason we return the same
-        // error as if the data was truncated.
-        mpack_reader_flag_error(reader, mpack_error_io);
-        mpack_memset(p, 0, count);
-        return;
-    }
-
-    // flush what's left of the buffer
-    if (left > 0) {
-        mpack_log("flushing %i bytes remaining in buffer\n", (int)left);
-        mpack_memcpy(p, reader->data, left);
-        count -= left;
-        p += left;
-        reader->data += left;
-    }
-
-    // if the remaining data needed is some small fraction of the
-    // buffer size, we'll try to fill the buffer as much as possible
-    // and copy the needed data out.
-    if (count <= reader->size / MPACK_READER_SMALL_FRACTION_DENOMINATOR) {
-        size_t read = mpack_fill_range(reader, reader->buffer, count, reader->size);
-        if (mpack_reader_error(reader) != mpack_ok)
-            return;
-        mpack_memcpy(p, reader->buffer, count);
-        reader->data = reader->buffer + count;
-        reader->end = reader->buffer + read;
-
-    // otherwise we read the remaining data directly into the target.
-    } else {
-        mpack_log("reading %i additional bytes\n", (int)count);
-        mpack_fill_range(reader, p, count, count);
-    }
-}
-
-MPACK_NOINLINE static void mpack_skip_bytes_straddle(mpack_reader_t* reader, size_t count) {
-
-    // we'll need at least a fill function to skip more data. if there's
-    // no fill function, the buffer should contain an entire MessagePack
-    // object, so we raise mpack_error_invalid instead of mpack_error_io
-    // on truncated data. (see mpack_read_native_straddle())
-    if (reader->fill == NULL) {
-        mpack_log("reader has no fill function!\n");
-        mpack_reader_flag_error(reader, mpack_error_invalid);
-        return;
-    }
-
-    // discard whatever's left in the buffer
-    size_t left = (size_t)(reader->end - reader->data);
-    mpack_log("discarding %i bytes still in buffer\n", (int)left);
-    count -= left;
-    reader->data = reader->end;
-
-    // use the skip function if we've got one, and if we're trying
-    // to skip a lot of data. if we only need to skip some tiny
-    // fraction of the buffer size, it's probably better to just
-    // fill the buffer and skip from it instead of trying to seek.
-    if (reader->skip && count > reader->size / 16) {
-        mpack_log("calling skip function for %i bytes\n", (int)count);
-        reader->skip(reader, count);
-        return;
-    }
-
-    mpack_reader_skip_using_fill(reader, count);
-}
-
-void mpack_skip_bytes(mpack_reader_t* reader, size_t count) {
-    if (mpack_reader_error(reader) != mpack_ok)
-        return;
-    mpack_log("skip requested for %i bytes\n", (int)count);
-    mpack_reader_track_bytes(reader, count);
-
-    // check if we have enough in the buffer already
-    size_t left = (size_t)(reader->end - reader->data);
-    if (left >= count) {
-        mpack_log("skipping %i bytes still in buffer\n", (int)count);
-        reader->data += count;
-        return;
-    }
-
-    mpack_skip_bytes_straddle(reader, count);
-}
-
-MPACK_NOINLINE static void mpack_reader_skip_using_fill(mpack_reader_t* reader, size_t count) {
-    mpack_assert(reader->fill != NULL, "missing fill function!");
-    mpack_assert(reader->data == reader->end, "there are bytes left in the buffer!");
-    mpack_assert(reader->error == mpack_ok, "should not have called this in an error state (%i)", reader->error);
-    mpack_log("skip using fill for %i bytes\n", (int)count);
-
-    // fill and discard multiples of the buffer size
-    while (count > reader->size) {
-        mpack_log("filling and discarding buffer of %i bytes\n", (int)reader->size);
-        if (mpack_fill_range(reader, reader->buffer, reader->size, reader->size) < reader->size) {
-            mpack_reader_flag_error(reader, mpack_error_io);
-            return;
-        }
-        count -= reader->size;
-    }
-
-    // fill the buffer as much as possible
-    reader->data = reader->buffer;
-    size_t read = mpack_fill_range(reader, reader->buffer, count, reader->size);
-    if (read < count) {
-        mpack_reader_flag_error(reader, mpack_error_io);
-        return;
-    }
-    reader->end = reader->data + read;
-    mpack_log("filled %i bytes into buffer; discarding %i bytes\n", (int)read, (int)count);
-    reader->data += count;
-}
-
-void mpack_read_bytes(mpack_reader_t* reader, char* p, size_t count) {
-    mpack_assert(p != NULL, "destination for read of %i bytes is NULL", (int)count);
-    mpack_reader_track_bytes(reader, count);
-    mpack_read_native(reader, p, count);
-}
-
-void mpack_read_utf8(mpack_reader_t* reader, char* p, size_t byte_count) {
-    mpack_assert(p != NULL, "destination for read of %i bytes is NULL", (int)byte_count);
-    mpack_reader_track_str_bytes_all(reader, byte_count);
-    mpack_read_native(reader, p, byte_count);
-
-    if (mpack_reader_error(reader) == mpack_ok && !mpack_utf8_check(p, byte_count))
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-static void mpack_read_cstr_unchecked(mpack_reader_t* reader, char* buf, size_t buffer_size, size_t byte_count) {
-    mpack_assert(buf != NULL, "destination for read of %i bytes is NULL", (int)byte_count);
-    mpack_assert(buffer_size >= 1, "buffer size is zero; you must have room for at least a null-terminator");
-
-    if (mpack_reader_error(reader)) {
-        buf[0] = 0;
-        return;
-    }
-
-    if (byte_count > buffer_size - 1) {
-        mpack_reader_flag_error(reader, mpack_error_too_big);
-        buf[0] = 0;
-        return;
-    }
-
-    mpack_reader_track_str_bytes_all(reader, byte_count);
-    mpack_read_native(reader, buf, byte_count);
-    buf[byte_count] = 0;
-}
-
-void mpack_read_cstr(mpack_reader_t* reader, char* buf, size_t buffer_size, size_t byte_count) {
-    mpack_read_cstr_unchecked(reader, buf, buffer_size, byte_count);
-
-    // check for null bytes
-    if (mpack_reader_error(reader) == mpack_ok && !mpack_str_check_no_null(buf, byte_count)) {
-        buf[0] = 0;
-        mpack_reader_flag_error(reader, mpack_error_type);
-    }
-}
-
-void mpack_read_utf8_cstr(mpack_reader_t* reader, char* buf, size_t buffer_size, size_t byte_count) {
-    mpack_read_cstr_unchecked(reader, buf, buffer_size, byte_count);
-
-    // check encoding
-    if (mpack_reader_error(reader) == mpack_ok && !mpack_utf8_check_no_null(buf, byte_count)) {
-        buf[0] = 0;
-        mpack_reader_flag_error(reader, mpack_error_type);
-    }
-}
-
-#ifdef MPACK_MALLOC
-// Reads native bytes with error callback disabled. This allows MPack reader functions
-// to hold an allocated buffer and read native data into it without leaking it in
-// case of a non-local jump (longjmp, throw) out of an error handler.
-static void mpack_read_native_noerrorfn(mpack_reader_t* reader, char* p, size_t count) {
-    mpack_assert(reader->error == mpack_ok, "cannot call if an error is already flagged!");
-    mpack_reader_error_t error_fn = reader->error_fn;
-    reader->error_fn = NULL;
-    mpack_read_native(reader, p, count);
-    reader->error_fn = error_fn;
-}
-
-char* mpack_read_bytes_alloc_impl(mpack_reader_t* reader, size_t count, bool null_terminated) {
-
-    // track the bytes first in case it jumps
-    mpack_reader_track_bytes(reader, count);
-    if (mpack_reader_error(reader) != mpack_ok)
-        return NULL;
-
-    // cannot allocate zero bytes. this is not an error.
-    if (count == 0 && null_terminated == false)
-        return NULL;
-
-    // allocate data
-    char* data = (char*)MPACK_MALLOC(count + (null_terminated ? 1 : 0)); // TODO: can this overflow?
-    if (data == NULL) {
-        mpack_reader_flag_error(reader, mpack_error_memory);
-        return NULL;
-    }
-
-    // read with error callback disabled so we don't leak our buffer
-    mpack_read_native_noerrorfn(reader, data, count);
-
-    // report flagged errors
-    if (mpack_reader_error(reader) != mpack_ok) {
-        MPACK_FREE(data);
-        if (reader->error_fn)
-            reader->error_fn(reader, mpack_reader_error(reader));
-        return NULL;
-    }
-
-    if (null_terminated)
-        data[count] = '\0';
-    return data;
-}
-#endif
-
-// read inplace without tracking (since there are different
-// tracking modes for different inplace readers)
-static const char* mpack_read_bytes_inplace_notrack(mpack_reader_t* reader, size_t count) {
-    if (mpack_reader_error(reader) != mpack_ok)
-        return NULL;
-
-    // if we have enough bytes already in the buffer, we can return it directly.
-    if ((size_t)(reader->end - reader->data) >= count) {
-        const char* bytes = reader->data;
-        reader->data += count;
-        return bytes;
-    }
-
-    if (!mpack_reader_ensure(reader, count))
-        return NULL;
-
-    const char* bytes = reader->data;
-    reader->data += count;
-    return bytes;
-}
-
-const char* mpack_read_bytes_inplace(mpack_reader_t* reader, size_t count) {
-    mpack_reader_track_bytes(reader, count);
-    return mpack_read_bytes_inplace_notrack(reader, count);
-}
-
-const char* mpack_read_utf8_inplace(mpack_reader_t* reader, size_t count) {
-    mpack_reader_track_str_bytes_all(reader, count);
-    const char* str = mpack_read_bytes_inplace_notrack(reader, count);
-
-    if (mpack_reader_error(reader) == mpack_ok && !mpack_utf8_check(str, count)) {
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return NULL;
-    }
-
-    return str;
-}
-
-static size_t mpack_parse_tag(mpack_reader_t* reader, mpack_tag_t* tag) {
-    mpack_assert(reader->error == mpack_ok, "reader cannot be in an error state!");
-
-    if (!mpack_reader_ensure(reader, 1))
-        return 0;
-    uint8_t type = mpack_load_u8(reader->data);
-
-    // unfortunately, by far the fastest way to parse a tag is to switch
-    // on the first byte, and to explicitly list every possible byte. so for
-    // infix types, the list of cases is quite large.
-    //
-    // in size-optimized builds, we switch on the top four bits first to
-    // handle most infix types with a smaller jump table to save space.
-
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    switch (type >> 4) {
-
-        // positive fixnum
-        case 0x0: case 0x1: case 0x2: case 0x3:
-        case 0x4: case 0x5: case 0x6: case 0x7:
-            *tag = mpack_tag_make_uint(type);
-            return 1;
-
-        // negative fixnum
-        case 0xe: case 0xf:
-            *tag = mpack_tag_make_int((int8_t)type);
-            return 1;
-
-        // fixmap
-        case 0x8:
-            *tag = mpack_tag_make_map(type & ~0xf0u);
-            return 1;
-
-        // fixarray
-        case 0x9:
-            *tag = mpack_tag_make_array(type & ~0xf0u);
-            return 1;
-
-        // fixstr
-        case 0xa: case 0xb:
-            *tag = mpack_tag_make_str(type & ~0xe0u);
-            return 1;
-
-        // not one of the common infix types
-        default:
-            break;
-
-    }
-    #endif
-
-    // handle individual type tags
-    switch (type) {
-
-        #if !MPACK_OPTIMIZE_FOR_SIZE
-        // positive fixnum
-        case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07:
-        case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f:
-        case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
-        case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
-        case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
-        case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f:
-        case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
-        case 0x38: case 0x39: case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: case 0x3f:
-        case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47:
-        case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f:
-        case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57:
-        case 0x58: case 0x59: case 0x5a: case 0x5b: case 0x5c: case 0x5d: case 0x5e: case 0x5f:
-        case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67:
-        case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f:
-        case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77:
-        case 0x78: case 0x79: case 0x7a: case 0x7b: case 0x7c: case 0x7d: case 0x7e: case 0x7f:
-            *tag = mpack_tag_make_uint(type);
-            return 1;
-
-        // negative fixnum
-        case 0xe0: case 0xe1: case 0xe2: case 0xe3: case 0xe4: case 0xe5: case 0xe6: case 0xe7:
-        case 0xe8: case 0xe9: case 0xea: case 0xeb: case 0xec: case 0xed: case 0xee: case 0xef:
-        case 0xf0: case 0xf1: case 0xf2: case 0xf3: case 0xf4: case 0xf5: case 0xf6: case 0xf7:
-        case 0xf8: case 0xf9: case 0xfa: case 0xfb: case 0xfc: case 0xfd: case 0xfe: case 0xff:
-            *tag = mpack_tag_make_int((int8_t)type);
-            return 1;
-
-        // fixmap
-        case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87:
-        case 0x88: case 0x89: case 0x8a: case 0x8b: case 0x8c: case 0x8d: case 0x8e: case 0x8f:
-            *tag = mpack_tag_make_map(type & ~0xf0u);
-            return 1;
-
-        // fixarray
-        case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97:
-        case 0x98: case 0x99: case 0x9a: case 0x9b: case 0x9c: case 0x9d: case 0x9e: case 0x9f:
-            *tag = mpack_tag_make_array(type & ~0xf0u);
-            return 1;
-
-        // fixstr
-        case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7:
-        case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf:
-        case 0xb0: case 0xb1: case 0xb2: case 0xb3: case 0xb4: case 0xb5: case 0xb6: case 0xb7:
-        case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbc: case 0xbd: case 0xbe: case 0xbf:
-            *tag = mpack_tag_make_str(type & ~0xe0u);
-            return 1;
-        #endif
-
-        // nil
-        case 0xc0:
-            *tag = mpack_tag_make_nil();
-            return 1;
-
-        // bool
-        case 0xc2: case 0xc3:
-            *tag = mpack_tag_make_bool((bool)(type & 1));
-            return 1;
-
-        // bin8
-        case 0xc4:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_BIN8))
-                return 0;
-            *tag = mpack_tag_make_bin(mpack_load_u8(reader->data + 1));
-            return MPACK_TAG_SIZE_BIN8;
-
-        // bin16
-        case 0xc5:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_BIN16))
-                return 0;
-            *tag = mpack_tag_make_bin(mpack_load_u16(reader->data + 1));
-            return MPACK_TAG_SIZE_BIN16;
-
-        // bin32
-        case 0xc6:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_BIN32))
-                return 0;
-            *tag = mpack_tag_make_bin(mpack_load_u32(reader->data + 1));
-            return MPACK_TAG_SIZE_BIN32;
-
-        #if MPACK_EXTENSIONS
-        // ext8
-        case 0xc7:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_EXT8))
-                return 0;
-            *tag = mpack_tag_make_ext(mpack_load_i8(reader->data + 2), mpack_load_u8(reader->data + 1));
-            return MPACK_TAG_SIZE_EXT8;
-
-        // ext16
-        case 0xc8:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_EXT16))
-                return 0;
-            *tag = mpack_tag_make_ext(mpack_load_i8(reader->data + 3), mpack_load_u16(reader->data + 1));
-            return MPACK_TAG_SIZE_EXT16;
-
-        // ext32
-        case 0xc9:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_EXT32))
-                return 0;
-            *tag = mpack_tag_make_ext(mpack_load_i8(reader->data + 5), mpack_load_u32(reader->data + 1));
-            return MPACK_TAG_SIZE_EXT32;
-        #endif
-
-        // float
-        case 0xca:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_FLOAT))
-                return 0;
-            *tag = mpack_tag_make_float(mpack_load_float(reader->data + 1));
-            return MPACK_TAG_SIZE_FLOAT;
-
-        // double
-        case 0xcb:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_DOUBLE))
-                return 0;
-            *tag = mpack_tag_make_double(mpack_load_double(reader->data + 1));
-            return MPACK_TAG_SIZE_DOUBLE;
-
-        // uint8
-        case 0xcc:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_U8))
-                return 0;
-            *tag = mpack_tag_make_uint(mpack_load_u8(reader->data + 1));
-            return MPACK_TAG_SIZE_U8;
-
-        // uint16
-        case 0xcd:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_U16))
-                return 0;
-            *tag = mpack_tag_make_uint(mpack_load_u16(reader->data + 1));
-            return MPACK_TAG_SIZE_U16;
-
-        // uint32
-        case 0xce:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_U32))
-                return 0;
-            *tag = mpack_tag_make_uint(mpack_load_u32(reader->data + 1));
-            return MPACK_TAG_SIZE_U32;
-
-        // uint64
-        case 0xcf:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_U64))
-                return 0;
-            *tag = mpack_tag_make_uint(mpack_load_u64(reader->data + 1));
-            return MPACK_TAG_SIZE_U64;
-
-        // int8
-        case 0xd0:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_I8))
-                return 0;
-            *tag = mpack_tag_make_int(mpack_load_i8(reader->data + 1));
-            return MPACK_TAG_SIZE_I8;
-
-        // int16
-        case 0xd1:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_I16))
-                return 0;
-            *tag = mpack_tag_make_int(mpack_load_i16(reader->data + 1));
-            return MPACK_TAG_SIZE_I16;
-
-        // int32
-        case 0xd2:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_I32))
-                return 0;
-            *tag = mpack_tag_make_int(mpack_load_i32(reader->data + 1));
-            return MPACK_TAG_SIZE_I32;
-
-        // int64
-        case 0xd3:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_I64))
-                return 0;
-            *tag = mpack_tag_make_int(mpack_load_i64(reader->data + 1));
-            return MPACK_TAG_SIZE_I64;
-
-        #if MPACK_EXTENSIONS
-        // fixext1
-        case 0xd4:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_FIXEXT1))
-                return 0;
-            *tag = mpack_tag_make_ext(mpack_load_i8(reader->data + 1), 1);
-            return MPACK_TAG_SIZE_FIXEXT1;
-
-        // fixext2
-        case 0xd5:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_FIXEXT2))
-                return 0;
-            *tag = mpack_tag_make_ext(mpack_load_i8(reader->data + 1), 2);
-            return MPACK_TAG_SIZE_FIXEXT2;
-
-        // fixext4
-        case 0xd6:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_FIXEXT4))
-                return 0;
-            *tag = mpack_tag_make_ext(mpack_load_i8(reader->data + 1), 4);
-            return 2;
-
-        // fixext8
-        case 0xd7:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_FIXEXT8))
-                return 0;
-            *tag = mpack_tag_make_ext(mpack_load_i8(reader->data + 1), 8);
-            return MPACK_TAG_SIZE_FIXEXT8;
-
-        // fixext16
-        case 0xd8:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_FIXEXT16))
-                return 0;
-            *tag = mpack_tag_make_ext(mpack_load_i8(reader->data + 1), 16);
-            return MPACK_TAG_SIZE_FIXEXT16;
-        #endif
-
-        // str8
-        case 0xd9:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_STR8))
-                return 0;
-            *tag = mpack_tag_make_str(mpack_load_u8(reader->data + 1));
-            return MPACK_TAG_SIZE_STR8;
-
-        // str16
-        case 0xda:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_STR16))
-                return 0;
-            *tag = mpack_tag_make_str(mpack_load_u16(reader->data + 1));
-            return MPACK_TAG_SIZE_STR16;
-
-        // str32
-        case 0xdb:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_STR32))
-                return 0;
-            *tag = mpack_tag_make_str(mpack_load_u32(reader->data + 1));
-            return MPACK_TAG_SIZE_STR32;
-
-        // array16
-        case 0xdc:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_ARRAY16))
-                return 0;
-            *tag = mpack_tag_make_array(mpack_load_u16(reader->data + 1));
-            return MPACK_TAG_SIZE_ARRAY16;
-
-        // array32
-        case 0xdd:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_ARRAY32))
-                return 0;
-            *tag = mpack_tag_make_array(mpack_load_u32(reader->data + 1));
-            return MPACK_TAG_SIZE_ARRAY32;
-
-        // map16
-        case 0xde:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_MAP16))
-                return 0;
-            *tag = mpack_tag_make_map(mpack_load_u16(reader->data + 1));
-            return MPACK_TAG_SIZE_MAP16;
-
-        // map32
-        case 0xdf:
-            if (!mpack_reader_ensure(reader, MPACK_TAG_SIZE_MAP32))
-                return 0;
-            *tag = mpack_tag_make_map(mpack_load_u32(reader->data + 1));
-            return MPACK_TAG_SIZE_MAP32;
-
-        // reserved
-        case 0xc1:
-            mpack_reader_flag_error(reader, mpack_error_invalid);
-            return 0;
-
-        #if !MPACK_EXTENSIONS
-        // ext
-        case 0xc7: // fallthrough
-        case 0xc8: // fallthrough
-        case 0xc9: // fallthrough
-        // fixext
-        case 0xd4: // fallthrough
-        case 0xd5: // fallthrough
-        case 0xd6: // fallthrough
-        case 0xd7: // fallthrough
-        case 0xd8:
-            mpack_reader_flag_error(reader, mpack_error_unsupported);
-            return 0;
-        #endif
-
-        #if MPACK_OPTIMIZE_FOR_SIZE
-        // any other bytes should have been handled by the infix switch
-        default:
-            break;
-        #endif
-    }
-
-    mpack_assert(0, "unreachable");
-    return 0;
-}
-
-mpack_tag_t mpack_read_tag(mpack_reader_t* reader) {
-    mpack_log("reading tag\n");
-
-    // make sure we can read a tag
-    if (mpack_reader_error(reader) != mpack_ok)
-        return mpack_tag_nil();
-    if (mpack_reader_track_element(reader) != mpack_ok)
-        return mpack_tag_nil();
-
-    mpack_tag_t tag = MPACK_TAG_ZERO;
-    size_t count = mpack_parse_tag(reader, &tag);
-    if (count == 0)
-        return mpack_tag_nil();
-
-    #if MPACK_READ_TRACKING
-    mpack_error_t track_error = mpack_ok;
-
-    switch (tag.type) {
-        case mpack_type_map:
-        case mpack_type_array:
-            track_error = mpack_track_push(&reader->track, tag.type, tag.v.n);
-            break;
-        #if MPACK_EXTENSIONS
-        case mpack_type_ext:
-        #endif
-        case mpack_type_str:
-        case mpack_type_bin:
-            track_error = mpack_track_push(&reader->track, tag.type, tag.v.l);
-            break;
-        default:
-            break;
-    }
-
-    if (track_error != mpack_ok) {
-        mpack_reader_flag_error(reader, track_error);
-        return mpack_tag_nil();
-    }
-    #endif
-
-    reader->data += count;
-    return tag;
-}
-
-mpack_tag_t mpack_peek_tag(mpack_reader_t* reader) {
-    mpack_log("peeking tag\n");
-
-    // make sure we can peek a tag
-    if (mpack_reader_error(reader) != mpack_ok)
-        return mpack_tag_nil();
-    if (mpack_reader_track_peek_element(reader) != mpack_ok)
-        return mpack_tag_nil();
-
-    mpack_tag_t tag = MPACK_TAG_ZERO;
-    if (mpack_parse_tag(reader, &tag) == 0)
-        return mpack_tag_nil();
-    return tag;
-}
-
-void mpack_discard(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (mpack_reader_error(reader))
-        return;
-    switch (var.type) {
-        case mpack_type_str:
-            mpack_skip_bytes(reader, var.v.l);
-            mpack_done_str(reader);
-            break;
-        case mpack_type_bin:
-            mpack_skip_bytes(reader, var.v.l);
-            mpack_done_bin(reader);
-            break;
-        #if MPACK_EXTENSIONS
-        case mpack_type_ext:
-            mpack_skip_bytes(reader, var.v.l);
-            mpack_done_ext(reader);
-            break;
-        #endif
-        case mpack_type_array: {
-            for (; var.v.n > 0; --var.v.n) {
-                mpack_discard(reader);
-                if (mpack_reader_error(reader))
-                    break;
-            }
-            mpack_done_array(reader);
-            break;
-        }
-        case mpack_type_map: {
-            for (; var.v.n > 0; --var.v.n) {
-                mpack_discard(reader);
-                mpack_discard(reader);
-                if (mpack_reader_error(reader))
-                    break;
-            }
-            mpack_done_map(reader);
-            break;
-        }
-        default:
-            break;
-    }
-}
-
-#if MPACK_EXTENSIONS
-mpack_timestamp_t mpack_read_timestamp(mpack_reader_t* reader, size_t size) {
-    mpack_timestamp_t timestamp = {0, 0};
-
-    if (size != 4 && size != 8 && size != 12) {
-        mpack_reader_flag_error(reader, mpack_error_invalid);
-        return timestamp;
-    }
-
-    char buf[12];
-    mpack_read_bytes(reader, buf, size);
-    mpack_done_ext(reader);
-    if (mpack_reader_error(reader) != mpack_ok)
-        return timestamp;
-
-    switch (size) {
-        case 4:
-            timestamp.seconds = (int64_t)(uint64_t)mpack_load_u32(buf);
-            break;
-
-        case 8: {
-            uint64_t packed = mpack_load_u64(buf);
-            timestamp.seconds = (int64_t)(packed & ((UINT64_C(1) << 34) - 1));
-            timestamp.nanoseconds = (uint32_t)(packed >> 34);
-            break;
-        }
-
-        case 12:
-            timestamp.nanoseconds = mpack_load_u32(buf);
-            timestamp.seconds = mpack_load_i64(buf + 4);
-            break;
-
-        default:
-            mpack_assert(false, "unreachable");
-            break;
-    }
-
-    if (timestamp.nanoseconds > MPACK_TIMESTAMP_NANOSECONDS_MAX) {
-        mpack_reader_flag_error(reader, mpack_error_invalid);
-        mpack_timestamp_t zero = {0, 0};
-        return zero;
-    }
-
-    return timestamp;
-}
-#endif
-
-#if MPACK_READ_TRACKING
-void mpack_done_type(mpack_reader_t* reader, mpack_type_t type) {
-    if (mpack_reader_error(reader) == mpack_ok)
-        mpack_reader_flag_if_error(reader, mpack_track_pop(&reader->track, type));
-}
-#endif
-
-#if MPACK_DEBUG && MPACK_STDIO
-static size_t mpack_print_read_prefix(mpack_reader_t* reader, size_t length, char* buffer, size_t buffer_size) {
-    if (length == 0)
-        return 0;
-
-    size_t read = (length < buffer_size) ? length : buffer_size;
-    mpack_read_bytes(reader, buffer, read);
-    if (mpack_reader_error(reader) != mpack_ok)
-        return 0;
-
-    mpack_skip_bytes(reader, length - read);
-    return read;
-}
-
-static void mpack_print_element(mpack_reader_t* reader, mpack_print_t* print, size_t depth) {
-    mpack_tag_t val = mpack_read_tag(reader);
-    if (mpack_reader_error(reader) != mpack_ok)
-        return;
-
-    // We read some bytes from bin and ext so we can print its prefix in hex.
-    char buffer[MPACK_PRINT_BYTE_COUNT];
-    size_t count = 0;
-
-    switch (val.type) {
-        case mpack_type_str:
-            mpack_print_append_cstr(print, "\"");
-            for (size_t i = 0; i < val.v.l; ++i) {
-                char c;
-                mpack_read_bytes(reader, &c, 1);
-                if (mpack_reader_error(reader) != mpack_ok)
-                    return;
-                switch (c) {
-                    case '\n': mpack_print_append_cstr(print, "\\n"); break;
-                    case '\\': mpack_print_append_cstr(print, "\\\\"); break;
-                    case '"': mpack_print_append_cstr(print, "\\\""); break;
-                    default: mpack_print_append(print, &c, 1); break;
-                }
-            }
-            mpack_print_append_cstr(print, "\"");
-            mpack_done_str(reader);
-            return;
-
-        case mpack_type_array:
-            mpack_print_append_cstr(print, "[\n");
-            for (size_t i = 0; i < val.v.n; ++i) {
-                for (size_t j = 0; j < depth + 1; ++j)
-                    mpack_print_append_cstr(print, "    ");
-                mpack_print_element(reader, print, depth + 1);
-                if (mpack_reader_error(reader) != mpack_ok)
-                    return;
-                if (i != val.v.n - 1)
-                    mpack_print_append_cstr(print, ",");
-                mpack_print_append_cstr(print, "\n");
-            }
-            for (size_t i = 0; i < depth; ++i)
-                mpack_print_append_cstr(print, "    ");
-            mpack_print_append_cstr(print, "]");
-            mpack_done_array(reader);
-            return;
-
-        case mpack_type_map:
-            mpack_print_append_cstr(print, "{\n");
-            for (size_t i = 0; i < val.v.n; ++i) {
-                for (size_t j = 0; j < depth + 1; ++j)
-                    mpack_print_append_cstr(print, "    ");
-                mpack_print_element(reader, print, depth + 1);
-                if (mpack_reader_error(reader) != mpack_ok)
-                    return;
-                mpack_print_append_cstr(print, ": ");
-                mpack_print_element(reader, print, depth + 1);
-                if (mpack_reader_error(reader) != mpack_ok)
-                    return;
-                if (i != val.v.n - 1)
-                    mpack_print_append_cstr(print, ",");
-                mpack_print_append_cstr(print, "\n");
-            }
-            for (size_t i = 0; i < depth; ++i)
-                mpack_print_append_cstr(print, "    ");
-            mpack_print_append_cstr(print, "}");
-            mpack_done_map(reader);
-            return;
-
-        // The above cases return so as not to print a pseudo-json value. The
-        // below cases break and print pseudo-json.
-
-        case mpack_type_bin:
-            count = mpack_print_read_prefix(reader, mpack_tag_bin_length(&val), buffer, sizeof(buffer));
-            mpack_done_bin(reader);
-            break;
-
-        #if MPACK_EXTENSIONS
-        case mpack_type_ext:
-            count = mpack_print_read_prefix(reader, mpack_tag_ext_length(&val), buffer, sizeof(buffer));
-            mpack_done_ext(reader);
-            break;
-        #endif
-
-        default:
-            break;
-    }
-
-    char buf[256];
-    mpack_tag_debug_pseudo_json(val, buf, sizeof(buf), buffer, count);
-    mpack_print_append_cstr(print, buf);
-}
-
-static void mpack_print_and_destroy(mpack_reader_t* reader, mpack_print_t* print, size_t depth) {
-    for (size_t i = 0; i < depth; ++i)
-        mpack_print_append_cstr(print, "    ");
-    mpack_print_element(reader, print, depth);
-
-    size_t remaining = mpack_reader_remaining(reader, NULL);
-
-    char buf[256];
-    if (mpack_reader_destroy(reader) != mpack_ok) {
-        mpack_snprintf(buf, sizeof(buf), "\n<mpack parsing error %s>", mpack_error_to_string(mpack_reader_error(reader)));
-        buf[sizeof(buf) - 1] = '\0';
-        mpack_print_append_cstr(print, buf);
-    } else if (remaining > 0) {
-        mpack_snprintf(buf, sizeof(buf), "\n<%i extra bytes at end of message>", (int)remaining);
-        buf[sizeof(buf) - 1] = '\0';
-        mpack_print_append_cstr(print, buf);
-    }
-}
-
-static void mpack_print_data(const char* data, size_t len, mpack_print_t* print, size_t depth) {
-    mpack_reader_t reader;
-    mpack_reader_init_data(&reader, data, len);
-    mpack_print_and_destroy(&reader, print, depth);
-}
-
-void mpack_print_data_to_buffer(const char* data, size_t data_size, char* buffer, size_t buffer_size) {
-    if (buffer_size == 0) {
-        mpack_assert(false, "buffer size is zero!");
-        return;
-    }
-
-    mpack_print_t print;
-    mpack_memset(&print, 0, sizeof(print));
-    print.buffer = buffer;
-    print.size = buffer_size;
-    mpack_print_data(data, data_size, &print, 0);
-    mpack_print_append(&print, "",  1); // null-terminator
-    mpack_print_flush(&print);
-
-    // we always make sure there's a null-terminator at the end of the buffer
-    // in case we ran out of space.
-    print.buffer[print.size - 1] = '\0';
-}
-
-void mpack_print_data_to_callback(const char* data, size_t size, mpack_print_callback_t callback, void* context) {
-    char buffer[1024];
-    mpack_print_t print;
-    mpack_memset(&print, 0, sizeof(print));
-    print.buffer = buffer;
-    print.size = sizeof(buffer);
-    print.callback = callback;
-    print.context = context;
-    mpack_print_data(data, size, &print, 0);
-    mpack_print_flush(&print);
-}
-
-void mpack_print_data_to_file(const char* data, size_t len, FILE* file) {
-    mpack_assert(data != NULL, "data is NULL");
-    mpack_assert(file != NULL, "file is NULL");
-
-    char buffer[1024];
-    mpack_print_t print;
-    mpack_memset(&print, 0, sizeof(print));
-    print.buffer = buffer;
-    print.size = sizeof(buffer);
-    print.callback = &mpack_print_file_callback;
-    print.context = file;
-
-    mpack_print_data(data, len, &print, 2);
-    mpack_print_append_cstr(&print, "\n");
-    mpack_print_flush(&print);
-}
-
-void mpack_print_stdfile_to_callback(FILE* file, mpack_print_callback_t callback, void* context) {
-    char buffer[1024];
-    mpack_print_t print;
-    mpack_memset(&print, 0, sizeof(print));
-    print.buffer = buffer;
-    print.size = sizeof(buffer);
-    print.callback = callback;
-    print.context = context;
-
-    mpack_reader_t reader;
-    mpack_reader_init_stdfile(&reader, file, false);
-    mpack_print_and_destroy(&reader, &print, 0);
-    mpack_print_flush(&print);
-}
-#endif
-
-#endif
-
-/* mpack/mpack-expect.c.c */
-
-#define MPACK_INTERNAL 1
-
-/* #include "mpack-expect.h" */
-
-#if MPACK_EXPECT
-
-
-// Helpers
-
-MPACK_STATIC_INLINE uint8_t mpack_expect_native_u8(mpack_reader_t* reader) {
-    if (mpack_reader_error(reader) != mpack_ok)
-        return 0;
-    uint8_t type;
-    if (!mpack_reader_ensure(reader, sizeof(type)))
-        return 0;
-    type = mpack_load_u8(reader->data);
-    reader->data += sizeof(type);
-    return type;
-}
-
-#if !MPACK_OPTIMIZE_FOR_SIZE
-MPACK_STATIC_INLINE uint16_t mpack_expect_native_u16(mpack_reader_t* reader) {
-    if (mpack_reader_error(reader) != mpack_ok)
-        return 0;
-    uint16_t type;
-    if (!mpack_reader_ensure(reader, sizeof(type)))
-        return 0;
-    type = mpack_load_u16(reader->data);
-    reader->data += sizeof(type);
-    return type;
-}
-
-MPACK_STATIC_INLINE uint32_t mpack_expect_native_u32(mpack_reader_t* reader) {
-    if (mpack_reader_error(reader) != mpack_ok)
-        return 0;
-    uint32_t type;
-    if (!mpack_reader_ensure(reader, sizeof(type)))
-        return 0;
-    type = mpack_load_u32(reader->data);
-    reader->data += sizeof(type);
-    return type;
-}
-#endif
-
-MPACK_STATIC_INLINE uint8_t mpack_expect_type_byte(mpack_reader_t* reader) {
-    mpack_reader_track_element(reader);
-    return mpack_expect_native_u8(reader);
-}
-
-
-// Basic Number Functions
-
-uint8_t mpack_expect_u8(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_uint) {
-        if (var.v.u <= UINT8_MAX)
-            return (uint8_t)var.v.u;
-    } else if (var.type == mpack_type_int) {
-        if (var.v.i >= 0 && var.v.i <= UINT8_MAX)
-            return (uint8_t)var.v.i;
-    }
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-uint16_t mpack_expect_u16(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_uint) {
-        if (var.v.u <= UINT16_MAX)
-            return (uint16_t)var.v.u;
-    } else if (var.type == mpack_type_int) {
-        if (var.v.i >= 0 && var.v.i <= UINT16_MAX)
-            return (uint16_t)var.v.i;
-    }
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-uint32_t mpack_expect_u32(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_uint) {
-        if (var.v.u <= UINT32_MAX)
-            return (uint32_t)var.v.u;
-    } else if (var.type == mpack_type_int) {
-        if (var.v.i >= 0 && var.v.i <= UINT32_MAX)
-            return (uint32_t)var.v.i;
-    }
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-uint64_t mpack_expect_u64(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_uint) {
-        return var.v.u;
-    } else if (var.type == mpack_type_int) {
-        if (var.v.i >= 0)
-            return (uint64_t)var.v.i;
-    }
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-int8_t mpack_expect_i8(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_uint) {
-        if (var.v.u <= INT8_MAX)
-            return (int8_t)var.v.u;
-    } else if (var.type == mpack_type_int) {
-        if (var.v.i >= INT8_MIN && var.v.i <= INT8_MAX)
-            return (int8_t)var.v.i;
-    }
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-int16_t mpack_expect_i16(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_uint) {
-        if (var.v.u <= INT16_MAX)
-            return (int16_t)var.v.u;
-    } else if (var.type == mpack_type_int) {
-        if (var.v.i >= INT16_MIN && var.v.i <= INT16_MAX)
-            return (int16_t)var.v.i;
-    }
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-int32_t mpack_expect_i32(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_uint) {
-        if (var.v.u <= INT32_MAX)
-            return (int32_t)var.v.u;
-    } else if (var.type == mpack_type_int) {
-        if (var.v.i >= INT32_MIN && var.v.i <= INT32_MAX)
-            return (int32_t)var.v.i;
-    }
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-int64_t mpack_expect_i64(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_uint) {
-        if (var.v.u <= INT64_MAX)
-            return (int64_t)var.v.u;
-    } else if (var.type == mpack_type_int) {
-        return var.v.i;
-    }
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-float mpack_expect_float(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_uint)
-        return (float)var.v.u;
-    else if (var.type == mpack_type_int)
-        return (float)var.v.i;
-    else if (var.type == mpack_type_float)
-        return var.v.f;
-    else if (var.type == mpack_type_double)
-        return (float)var.v.d;
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0.0f;
-}
-
-double mpack_expect_double(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_uint)
-        return (double)var.v.u;
-    else if (var.type == mpack_type_int)
-        return (double)var.v.i;
-    else if (var.type == mpack_type_float)
-        return (double)var.v.f;
-    else if (var.type == mpack_type_double)
-        return var.v.d;
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0.0;
-}
-
-float mpack_expect_float_strict(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_float)
-        return var.v.f;
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0.0f;
-}
-
-double mpack_expect_double_strict(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_float)
-        return (double)var.v.f;
-    else if (var.type == mpack_type_double)
-        return var.v.d;
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0.0;
-}
-
-
-// Ranged Number Functions
-//
-// All ranged functions are identical other than the type, so we
-// define their content with a macro. The prototypes are still written
-// out in full to support ctags/IDE tools.
-
-#define MPACK_EXPECT_RANGE_IMPL(name, type_t)                           \
-                                                                        \
-    /* make sure the range is sensible */                               \
-    mpack_assert(min_value <= max_value,                                \
-            "min_value %i must be less than or equal to max_value %i",  \
-            min_value, max_value);                                      \
-                                                                        \
-    /* read the value */                                                \
-    type_t val = mpack_expect_##name(reader);                           \
-    if (mpack_reader_error(reader) != mpack_ok)                         \
-        return min_value;                                               \
-                                                                        \
-    /* make sure it fits */                                             \
-    if (val < min_value || val > max_value) {                           \
-        mpack_reader_flag_error(reader, mpack_error_type);              \
-        return min_value;                                               \
-    }                                                                   \
-                                                                        \
-    return val;
-
-uint8_t mpack_expect_u8_range(mpack_reader_t* reader, uint8_t min_value, uint8_t max_value) {MPACK_EXPECT_RANGE_IMPL(u8, uint8_t)}
-uint16_t mpack_expect_u16_range(mpack_reader_t* reader, uint16_t min_value, uint16_t max_value) {MPACK_EXPECT_RANGE_IMPL(u16, uint16_t)}
-uint32_t mpack_expect_u32_range(mpack_reader_t* reader, uint32_t min_value, uint32_t max_value) {MPACK_EXPECT_RANGE_IMPL(u32, uint32_t)}
-uint64_t mpack_expect_u64_range(mpack_reader_t* reader, uint64_t min_value, uint64_t max_value) {MPACK_EXPECT_RANGE_IMPL(u64, uint64_t)}
-
-int8_t mpack_expect_i8_range(mpack_reader_t* reader, int8_t min_value, int8_t max_value) {MPACK_EXPECT_RANGE_IMPL(i8, int8_t)}
-int16_t mpack_expect_i16_range(mpack_reader_t* reader, int16_t min_value, int16_t max_value) {MPACK_EXPECT_RANGE_IMPL(i16, int16_t)}
-int32_t mpack_expect_i32_range(mpack_reader_t* reader, int32_t min_value, int32_t max_value) {MPACK_EXPECT_RANGE_IMPL(i32, int32_t)}
-int64_t mpack_expect_i64_range(mpack_reader_t* reader, int64_t min_value, int64_t max_value) {MPACK_EXPECT_RANGE_IMPL(i64, int64_t)}
-
-float mpack_expect_float_range(mpack_reader_t* reader, float min_value, float max_value) {MPACK_EXPECT_RANGE_IMPL(float, float)}
-double mpack_expect_double_range(mpack_reader_t* reader, double min_value, double max_value) {MPACK_EXPECT_RANGE_IMPL(double, double)}
-
-uint32_t mpack_expect_map_range(mpack_reader_t* reader, uint32_t min_value, uint32_t max_value) {MPACK_EXPECT_RANGE_IMPL(map, uint32_t)}
-uint32_t mpack_expect_array_range(mpack_reader_t* reader, uint32_t min_value, uint32_t max_value) {MPACK_EXPECT_RANGE_IMPL(array, uint32_t)}
-
-
-// Matching Number Functions
-
-void mpack_expect_uint_match(mpack_reader_t* reader, uint64_t value) {
-    if (mpack_expect_u64(reader) != value)
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-void mpack_expect_int_match(mpack_reader_t* reader, int64_t value) {
-    if (mpack_expect_i64(reader) != value)
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-
-// Other Basic Types
-
-void mpack_expect_nil(mpack_reader_t* reader) {
-    if (mpack_expect_type_byte(reader) != 0xc0)
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-bool mpack_expect_bool(mpack_reader_t* reader) {
-    uint8_t type = mpack_expect_type_byte(reader);
-    if ((type & ~1) != 0xc2)
-        mpack_reader_flag_error(reader, mpack_error_type);
-    return (bool)(type & 1);
-}
-
-void mpack_expect_true(mpack_reader_t* reader) {
-    if (mpack_expect_bool(reader) != true)
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-void mpack_expect_false(mpack_reader_t* reader) {
-    if (mpack_expect_bool(reader) != false)
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-#if MPACK_EXTENSIONS
-mpack_timestamp_t mpack_expect_timestamp(mpack_reader_t* reader) {
-    mpack_timestamp_t zero = {0, 0};
-
-    mpack_tag_t tag = mpack_read_tag(reader);
-    if (tag.type != mpack_type_ext) {
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return zero;
-    }
-    if (mpack_tag_ext_exttype(&tag) != MPACK_EXTTYPE_TIMESTAMP) {
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return zero;
-    }
-
-    return mpack_read_timestamp(reader, mpack_tag_ext_length(&tag));
-}
-
-int64_t mpack_expect_timestamp_truncate(mpack_reader_t* reader) {
-    return mpack_expect_timestamp(reader).seconds;
-}
-#endif
-
-
-// Compound Types
-
-uint32_t mpack_expect_map(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_map)
-        return var.v.n;
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-void mpack_expect_map_match(mpack_reader_t* reader, uint32_t count) {
-    if (mpack_expect_map(reader) != count)
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-bool mpack_expect_map_or_nil(mpack_reader_t* reader, uint32_t* count) {
-    mpack_assert(count != NULL, "count cannot be NULL");
-
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_nil) {
-        *count = 0;
-        return false;
-    }
-    if (var.type == mpack_type_map) {
-        *count = var.v.n;
-        return true;
-    }
-    mpack_reader_flag_error(reader, mpack_error_type);
-    *count = 0;
-    return false;
-}
-
-bool mpack_expect_map_max_or_nil(mpack_reader_t* reader, uint32_t max_count, uint32_t* count) {
-    mpack_assert(count != NULL, "count cannot be NULL");
-
-    bool has_map = mpack_expect_map_or_nil(reader, count);
-    if (has_map && *count > max_count) {
-        *count = 0;
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return false;
-    }
-    return has_map;
-}
-
-uint32_t mpack_expect_array(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_array)
-        return var.v.n;
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-void mpack_expect_array_match(mpack_reader_t* reader, uint32_t count) {
-    if (mpack_expect_array(reader) != count)
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-bool mpack_expect_array_or_nil(mpack_reader_t* reader, uint32_t* count) {
-    mpack_assert(count != NULL, "count cannot be NULL");
-
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_nil) {
-        *count = 0;
-        return false;
-    }
-    if (var.type == mpack_type_array) {
-        *count = var.v.n;
-        return true;
-    }
-    mpack_reader_flag_error(reader, mpack_error_type);
-    *count = 0;
-    return false;
-}
-
-bool mpack_expect_array_max_or_nil(mpack_reader_t* reader, uint32_t max_count, uint32_t* count) {
-    mpack_assert(count != NULL, "count cannot be NULL");
-
-    bool has_array = mpack_expect_array_or_nil(reader, count);
-    if (has_array && *count > max_count) {
-        *count = 0;
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return false;
-    }
-    return has_array;
-}
-
-#ifdef MPACK_MALLOC
-void* mpack_expect_array_alloc_impl(mpack_reader_t* reader, size_t element_size, uint32_t max_count, uint32_t* out_count, bool allow_nil) {
-    mpack_assert(out_count != NULL, "out_count cannot be NULL");
-    *out_count = 0;
-
-    uint32_t count;
-    bool has_array = true;
-    if (allow_nil)
-        has_array = mpack_expect_array_max_or_nil(reader, max_count, &count);
-    else
-        count = mpack_expect_array_max(reader, max_count);
-    if (mpack_reader_error(reader))
-        return NULL;
-
-    // size 0 is not an error; we return NULL for no elements.
-    if (count == 0) {
-        // we call mpack_done_array() automatically ONLY if we are using
-        // the _or_nil variant. this is the only way to allow nil and empty
-        // to work the same way.
-        if (allow_nil && has_array)
-            mpack_done_array(reader);
-        return NULL;
-    }
-
-    void* p = MPACK_MALLOC(element_size * count);
-    if (p == NULL) {
-        mpack_reader_flag_error(reader, mpack_error_memory);
-        return NULL;
-    }
-
-    *out_count = count;
-    return p;
-}
-#endif
-
-
-// Str, Bin and Ext Functions
-
-uint32_t mpack_expect_str(mpack_reader_t* reader) {
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_str)
-        return var.v.l;
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-    #else
-    uint8_t type = mpack_expect_type_byte(reader);
-    uint32_t count;
-
-    if ((type >> 5) == 5) {
-        count = type & (uint8_t)~0xe0;
-    } else if (type == 0xd9) {
-        count = mpack_expect_native_u8(reader);
-    } else if (type == 0xda) {
-        count = mpack_expect_native_u16(reader);
-    } else if (type == 0xdb) {
-        count = mpack_expect_native_u32(reader);
-    } else {
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return 0;
-    }
-
-    #if MPACK_READ_TRACKING
-    mpack_reader_flag_if_error(reader, mpack_track_push(&reader->track, mpack_type_str, count));
-    #endif
-    return count;
-    #endif
-}
-
-size_t mpack_expect_str_buf(mpack_reader_t* reader, char* buf, size_t bufsize) {
-    mpack_assert(buf != NULL, "buf cannot be NULL");
-
-    size_t length = mpack_expect_str(reader);
-    if (mpack_reader_error(reader))
-        return 0;
-
-    if (length > bufsize) {
-        mpack_reader_flag_error(reader, mpack_error_too_big);
-        return 0;
-    }
-
-    mpack_read_bytes(reader, buf, length);
-    if (mpack_reader_error(reader))
-        return 0;
-
-    mpack_done_str(reader);
-    return length;
-}
-
-size_t mpack_expect_utf8(mpack_reader_t* reader, char* buf, size_t size) {
-    mpack_assert(buf != NULL, "buf cannot be NULL");
-
-    size_t length = mpack_expect_str_buf(reader, buf, size);
-
-    if (!mpack_utf8_check(buf, length)) {
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return 0;
-    }
-
-    return length;
-}
-
-uint32_t mpack_expect_bin(mpack_reader_t* reader) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_bin)
-        return var.v.l;
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-size_t mpack_expect_bin_buf(mpack_reader_t* reader, char* buf, size_t bufsize) {
-    mpack_assert(buf != NULL, "buf cannot be NULL");
-
-    size_t binsize = mpack_expect_bin(reader);
-    if (mpack_reader_error(reader))
-        return 0;
-    if (binsize > bufsize) {
-        mpack_reader_flag_error(reader, mpack_error_too_big);
-        return 0;
-    }
-    mpack_read_bytes(reader, buf, binsize);
-    if (mpack_reader_error(reader))
-        return 0;
-    mpack_done_bin(reader);
-    return binsize;
-}
-
-#if MPACK_EXTENSIONS
-uint32_t mpack_expect_ext(mpack_reader_t* reader, int8_t* type) {
-    mpack_tag_t var = mpack_read_tag(reader);
-    if (var.type == mpack_type_ext) {
-        *type = mpack_tag_ext_exttype(&var);
-        return mpack_tag_ext_length(&var);
-    }
-    *type = 0;
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return 0;
-}
-
-size_t mpack_expect_ext_buf(mpack_reader_t* reader, int8_t* type, char* buf, size_t bufsize) {
-    mpack_assert(buf != NULL, "buf cannot be NULL");
-
-    size_t extsize = mpack_expect_ext(reader, type);
-    if (mpack_reader_error(reader))
-        return 0;
-    if (extsize > bufsize) {
-        *type = 0;
-        mpack_reader_flag_error(reader, mpack_error_too_big);
-        return 0;
-    }
-    mpack_read_bytes(reader, buf, extsize);
-    if (mpack_reader_error(reader)) {
-        *type = 0;
-        return 0;
-    }
-    mpack_done_ext(reader);
-    return extsize;
-}
-#endif
-
-void mpack_expect_cstr(mpack_reader_t* reader, char* buf, size_t bufsize) {
-    uint32_t length = mpack_expect_str(reader);
-    mpack_read_cstr(reader, buf, bufsize, length);
-    mpack_done_str(reader);
-}
-
-void mpack_expect_utf8_cstr(mpack_reader_t* reader, char* buf, size_t bufsize) {
-    uint32_t length = mpack_expect_str(reader);
-    mpack_read_utf8_cstr(reader, buf, bufsize, length);
-    mpack_done_str(reader);
-}
-
-#ifdef MPACK_MALLOC
-static char* mpack_expect_cstr_alloc_unchecked(mpack_reader_t* reader, size_t maxsize, size_t* out_length) {
-    mpack_assert(out_length != NULL, "out_length cannot be NULL");
-    *out_length = 0;
-
-    // make sure argument makes sense
-    if (maxsize < 1) {
-        mpack_break("maxsize is zero; you must have room for at least a null-terminator");
-        mpack_reader_flag_error(reader, mpack_error_bug);
-        return NULL;
-    }
-
-    if (maxsize > UINT32_MAX)
-        maxsize = UINT32_MAX;
-
-    size_t length = mpack_expect_str_max(reader, (uint32_t)maxsize - 1);
-    char* str = mpack_read_bytes_alloc_impl(reader, length, true);
-    mpack_done_str(reader);
-
-    if (str)
-        *out_length = length;
-    return str;
-}
-
-char* mpack_expect_cstr_alloc(mpack_reader_t* reader, size_t maxsize) {
-    size_t length;
-    char* str = mpack_expect_cstr_alloc_unchecked(reader, maxsize, &length);
-
-    if (str && !mpack_str_check_no_null(str, length)) {
-        MPACK_FREE(str);
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return NULL;
-    }
-
-    return str;
-}
-
-char* mpack_expect_utf8_cstr_alloc(mpack_reader_t* reader, size_t maxsize) {
-    size_t length;
-    char* str = mpack_expect_cstr_alloc_unchecked(reader, maxsize, &length);
-
-    if (str && !mpack_utf8_check_no_null(str, length)) {
-        MPACK_FREE(str);
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return NULL;
-    }
-
-    return str;
-}
-#endif
-
-void mpack_expect_str_match(mpack_reader_t* reader, const char* str, size_t len) {
-    mpack_assert(str != NULL, "str cannot be NULL");
-
-    // expect a str the correct length
-    if (len > UINT32_MAX)
-        mpack_reader_flag_error(reader, mpack_error_type);
-    mpack_expect_str_length(reader, (uint32_t)len);
-    if (mpack_reader_error(reader))
-        return;
-    mpack_reader_track_bytes(reader, len);
-
-    // check each byte one by one (matched strings are likely to be very small)
-    for (; len > 0; --len) {
-        if (mpack_expect_native_u8(reader) != *str++) {
-            mpack_reader_flag_error(reader, mpack_error_type);
-            return;
-        }
-    }
-
-    mpack_done_str(reader);
-}
-
-void mpack_expect_tag(mpack_reader_t* reader, mpack_tag_t expected) {
-    mpack_tag_t actual = mpack_read_tag(reader);
-    if (!mpack_tag_equal(actual, expected))
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-#ifdef MPACK_MALLOC
-char* mpack_expect_bin_alloc(mpack_reader_t* reader, size_t maxsize, size_t* size) {
-    mpack_assert(size != NULL, "size cannot be NULL");
-    *size = 0;
-
-    if (maxsize > UINT32_MAX)
-        maxsize = UINT32_MAX;
-
-    size_t length = mpack_expect_bin_max(reader, (uint32_t)maxsize);
-    if (mpack_reader_error(reader))
-        return NULL;
-
-    char* data = mpack_read_bytes_alloc(reader, length);
-    mpack_done_bin(reader);
-
-    if (data)
-        *size = length;
-    return data;
-}
-#endif
-
-#if MPACK_EXTENSIONS && defined(MPACK_MALLOC)
-char* mpack_expect_ext_alloc(mpack_reader_t* reader, int8_t* type, size_t maxsize, size_t* size) {
-    mpack_assert(size != NULL, "size cannot be NULL");
-    *size = 0;
-
-    if (maxsize > UINT32_MAX)
-        maxsize = UINT32_MAX;
-
-    size_t length = mpack_expect_ext_max(reader, type, (uint32_t)maxsize);
-    if (mpack_reader_error(reader))
-        return NULL;
-
-    char* data = mpack_read_bytes_alloc(reader, length);
-    mpack_done_ext(reader);
-
-    if (data) {
-        *size = length;
-    } else {
-        *type = 0;
-    }
-    return data;
-}
-#endif
-
-size_t mpack_expect_enum(mpack_reader_t* reader, const char* strings[], size_t count) {
-
-    // read the string in-place
-    size_t keylen = mpack_expect_str(reader);
-    const char* key = mpack_read_bytes_inplace(reader, keylen);
-    mpack_done_str(reader);
-    if (mpack_reader_error(reader) != mpack_ok)
-        return count;
-
-    // find what key it matches
-    for (size_t i = 0; i < count; ++i) {
-        const char* other = strings[i];
-        size_t otherlen = mpack_strlen(other);
-        if (keylen == otherlen && mpack_memcmp(key, other, keylen) == 0)
-            return i;
-    }
-
-    // no matches
-    mpack_reader_flag_error(reader, mpack_error_type);
-    return count;
-}
-
-size_t mpack_expect_enum_optional(mpack_reader_t* reader, const char* strings[], size_t count) {
-    if (mpack_reader_error(reader) != mpack_ok)
-        return count;
-
-    mpack_assert(count != 0, "count cannot be zero; no strings are valid!");
-    mpack_assert(strings != NULL, "strings cannot be NULL");
-
-    // the key is only recognized if it is a string
-    if (mpack_peek_tag(reader).type != mpack_type_str) {
-        mpack_discard(reader);
-        return count;
-    }
-
-    // read the string in-place
-    size_t keylen = mpack_expect_str(reader);
-    const char* key = mpack_read_bytes_inplace(reader, keylen);
-    mpack_done_str(reader);
-    if (mpack_reader_error(reader) != mpack_ok)
-        return count;
-
-    // find what key it matches
-    for (size_t i = 0; i < count; ++i) {
-        const char* other = strings[i];
-        size_t otherlen = mpack_strlen(other);
-        if (keylen == otherlen && mpack_memcmp(key, other, keylen) == 0)
-            return i;
-    }
-
-    // no matches
-    return count;
-}
-
-size_t mpack_expect_key_uint(mpack_reader_t* reader, bool found[], size_t count) {
-    if (mpack_reader_error(reader) != mpack_ok)
-        return count;
-
-    if (count == 0) {
-        mpack_break("count cannot be zero; no keys are valid!");
-        mpack_reader_flag_error(reader, mpack_error_bug);
-        return count;
-    }
-    mpack_assert(found != NULL, "found cannot be NULL");
-
-    // the key is only recognized if it is an unsigned int
-    if (mpack_peek_tag(reader).type != mpack_type_uint) {
-        mpack_discard(reader);
-        return count;
-    }
-
-    // read the key
-    uint64_t value = mpack_expect_u64(reader);
-    if (mpack_reader_error(reader) != mpack_ok)
-        return count;
-
-    // unrecognized keys are fine, we just return count
-    if (value >= count)
-        return count;
-
-    // check if this key is a duplicate
-    if (found[value]) {
-        mpack_reader_flag_error(reader, mpack_error_invalid);
-        return count;
-    }
-
-    found[value] = true;
-    return (size_t)value;
-}
-
-size_t mpack_expect_key_cstr(mpack_reader_t* reader, const char* keys[], bool found[], size_t count) {
-    size_t i = mpack_expect_enum_optional(reader, keys, count);
-
-    // unrecognized keys are fine, we just return count
-    if (i == count)
-        return count;
-
-    // check if this key is a duplicate
-    mpack_assert(found != NULL, "found cannot be NULL");
-    if (found[i]) {
-        mpack_reader_flag_error(reader, mpack_error_invalid);
-        return count;
-    }
-
-    found[i] = true;
-    return i;
-}
-
-#endif
-
-
-/* mpack/mpack-node.c.c */
-
-#define MPACK_INTERNAL 1
-
-/* #include "mpack-node.h" */
-
-#if MPACK_NODE
-
-MPACK_STATIC_INLINE const char* mpack_node_data_unchecked(mpack_node_t node) {
-    mpack_assert(mpack_node_error(node) == mpack_ok, "tree is in an error state!");
-
-    mpack_type_t type = node.data->type;
-    MPACK_UNUSED(type);
-    #if MPACK_EXTENSIONS
-    mpack_assert(type == mpack_type_str || type == mpack_type_bin || type == mpack_type_ext,
-            "node of type %i (%s) is not a data type!", type, mpack_type_to_string(type));
-    #else
-    mpack_assert(type == mpack_type_str || type == mpack_type_bin,
-            "node of type %i (%s) is not a data type!", type, mpack_type_to_string(type));
-    #endif
-
-    return node.tree->data + node.data->value.offset;
-}
-
-#if MPACK_EXTENSIONS
-MPACK_STATIC_INLINE int8_t mpack_node_exttype_unchecked(mpack_node_t node) {
-    mpack_assert(mpack_node_error(node) == mpack_ok, "tree is in an error state!");
-
-    mpack_type_t type = node.data->type;
-    MPACK_UNUSED(type);
-    mpack_assert(type == mpack_type_ext, "node of type %i (%s) is not an ext type!",
-            type, mpack_type_to_string(type));
-
-    // the exttype of an ext node is stored in the byte preceding the data
-    return mpack_load_i8(mpack_node_data_unchecked(node) - 1);
-}
-#endif
-
-
-
-/*
- * Tree Parsing
- */
-
-#ifdef MPACK_MALLOC
-
-// fix up the alloc size to make sure it exactly fits the
-// maximum number of nodes it can contain (the allocator will
-// waste it back anyway, but we round it down just in case)
-
-#define MPACK_NODES_PER_PAGE \
-    ((MPACK_NODE_PAGE_SIZE - sizeof(mpack_tree_page_t)) / sizeof(mpack_node_data_t) + 1)
-
-#define MPACK_PAGE_ALLOC_SIZE \
-    (sizeof(mpack_tree_page_t) + sizeof(mpack_node_data_t) * (MPACK_NODES_PER_PAGE - 1))
-
-#endif
-
-#ifdef MPACK_MALLOC
-/*
- * Fills the tree until we have at least enough bytes for the current node.
- */
-static bool mpack_tree_reserve_fill(mpack_tree_t* tree) {
-    mpack_assert(tree->parser.state == mpack_tree_parse_state_in_progress);
-
-    size_t bytes = tree->parser.current_node_reserved;
-    mpack_assert(bytes > tree->parser.possible_nodes_left,
-            "there are already enough bytes! call mpack_tree_ensure() instead.");
-    mpack_log("filling to reserve %i bytes\n", (int)bytes);
-
-    // if the necessary bytes would put us over the maximum tree
-    // size, fail right away.
-    // TODO: check for overflow?
-    if (tree->data_length + bytes > tree->max_size) {
-        mpack_tree_flag_error(tree, mpack_error_too_big);
-        return false;
-    }
-
-    // we'll need a read function to fetch more data. if there's
-    // no read function, the data should contain an entire message
-    // (or messages), so we flag it as invalid.
-    if (tree->read_fn == NULL) {
-        mpack_log("tree has no read function!\n");
-        mpack_tree_flag_error(tree, mpack_error_invalid);
-        return false;
-    }
-
-    // expand the buffer if needed
-    if (tree->data_length + bytes > tree->buffer_capacity) {
-
-        // TODO: check for overflow?
-        size_t new_capacity = (tree->buffer_capacity == 0) ? MPACK_BUFFER_SIZE : tree->buffer_capacity;
-        while (new_capacity < tree->data_length + bytes)
-            new_capacity *= 2;
-        if (new_capacity > tree->max_size)
-            new_capacity = tree->max_size;
-
-        mpack_log("expanding buffer from %i to %i\n", (int)tree->buffer_capacity, (int)new_capacity);
-
-        char* new_buffer;
-        if (tree->buffer == NULL)
-            new_buffer = (char*)MPACK_MALLOC(new_capacity);
-        else
-            new_buffer = (char*)mpack_realloc(tree->buffer, tree->data_length, new_capacity);
-
-        if (new_buffer == NULL) {
-            mpack_tree_flag_error(tree, mpack_error_memory);
-            return false;
-        }
-
-        tree->data = new_buffer;
-        tree->buffer = new_buffer;
-        tree->buffer_capacity = new_capacity;
-    }
-
-    // request as much data as possible, looping until we have
-    // all the data we need
-    do {
-        size_t read = tree->read_fn(tree, tree->buffer + tree->data_length, tree->buffer_capacity - tree->data_length);
-
-        // If the fill function encounters an error, it should flag an error on
-        // the tree.
-        if (mpack_tree_error(tree) != mpack_ok)
-            return false;
-
-        // We guard against fill functions that return -1 just in case.
-        if (read == (size_t)(-1)) {
-            mpack_tree_flag_error(tree, mpack_error_io);
-            return false;
-        }
-
-        // If the fill function returns 0, the data is not available yet. We
-        // return false to stop parsing the current node.
-        if (read == 0) {
-            mpack_log("not enough data.\n");
-            return false;
-        }
-
-        mpack_log("read %u more bytes\n", (uint32_t)read);
-        tree->data_length += read;
-        tree->parser.possible_nodes_left += read;
-    } while (tree->parser.possible_nodes_left < bytes);
-
-    return true;
-}
-#endif
-
-/*
- * Ensures there are enough additional bytes in the tree for the current node
- * (including reserved bytes for the children of this node, and in addition to
- * the reserved bytes for children of previous compound nodes), reading more
- * data if needed.
- *
- * extra_bytes is the number of additional bytes to reserve for the current
- * node beyond the type byte (since one byte is already reserved for each node
- * by its parent array or map.)
- *
- * This may reallocate the tree, which means the tree->data pointer may change!
- *
- * Returns false if not enough bytes could be read.
- */
-MPACK_STATIC_INLINE bool mpack_tree_reserve_bytes(mpack_tree_t* tree, size_t extra_bytes) {
-    mpack_assert(tree->parser.state == mpack_tree_parse_state_in_progress);
-
-    // We guard against overflow here. A compound type could declare more than
-    // UINT32_MAX contents which overflows SIZE_MAX on 32-bit platforms. We
-    // flag mpack_error_invalid instead of mpack_error_too_big since it's far
-    // more likely that the message is corrupt than that the data is valid but
-    // not parseable on this architecture (see test_read_node_possible() in
-    // test-node.c .)
-    if ((uint64_t)tree->parser.current_node_reserved + (uint64_t)extra_bytes > SIZE_MAX) {
-        mpack_tree_flag_error(tree, mpack_error_invalid);
-        return false;
-    }
-
-    tree->parser.current_node_reserved += extra_bytes;
-
-    // Note that possible_nodes_left already accounts for reserved bytes for
-    // children of previous compound nodes. So even if there are hundreds of
-    // bytes left in the buffer, we might need to read anyway.
-    if (tree->parser.current_node_reserved <= tree->parser.possible_nodes_left)
-        return true;
-
-    #ifdef MPACK_MALLOC
-    return mpack_tree_reserve_fill(tree);
-    #else
-    return false;
-    #endif
-}
-
-MPACK_STATIC_INLINE size_t mpack_tree_parser_stack_capacity(mpack_tree_t* tree) {
-    #ifdef MPACK_MALLOC
-    return tree->parser.stack_capacity;
-    #else
-    return sizeof(tree->parser.stack) / sizeof(tree->parser.stack[0]);
-    #endif
-}
-
-static bool mpack_tree_push_stack(mpack_tree_t* tree, mpack_node_data_t* first_child, size_t total) {
-    mpack_tree_parser_t* parser = &tree->parser;
-    mpack_assert(parser->state == mpack_tree_parse_state_in_progress);
-
-    // No need to push empty containers
-    if (total == 0)
-        return true;
-
-    // Make sure we have enough room in the stack
-    if (parser->level + 1 == mpack_tree_parser_stack_capacity(tree)) {
-        #ifdef MPACK_MALLOC
-        size_t new_capacity = parser->stack_capacity * 2;
-        mpack_log("growing parse stack to capacity %i\n", (int)new_capacity);
-
-        // Replace the stack-allocated parsing stack
-        if (!parser->stack_owned) {
-            mpack_level_t* new_stack = (mpack_level_t*)MPACK_MALLOC(sizeof(mpack_level_t) * new_capacity);
-            if (!new_stack) {
-                mpack_tree_flag_error(tree, mpack_error_memory);
-                return false;
-            }
-            mpack_memcpy(new_stack, parser->stack, sizeof(mpack_level_t) * parser->stack_capacity);
-            parser->stack = new_stack;
-            parser->stack_owned = true;
-
-        // Realloc the allocated parsing stack
-        } else {
-            mpack_level_t* new_stack = (mpack_level_t*)mpack_realloc(parser->stack,
-                    sizeof(mpack_level_t) * parser->stack_capacity, sizeof(mpack_level_t) * new_capacity);
-            if (!new_stack) {
-                mpack_tree_flag_error(tree, mpack_error_memory);
-                return false;
-            }
-            parser->stack = new_stack;
-        }
-        parser->stack_capacity = new_capacity;
-        #else
-        mpack_tree_flag_error(tree, mpack_error_too_big);
-        return false;
-        #endif
-    }
-
-    // Push the contents of this node onto the parsing stack
-    ++parser->level;
-    parser->stack[parser->level].child = first_child;
-    parser->stack[parser->level].left = total;
-    return true;
-}
-
-static bool mpack_tree_parse_children(mpack_tree_t* tree, mpack_node_data_t* node) {
-    mpack_tree_parser_t* parser = &tree->parser;
-    mpack_assert(parser->state == mpack_tree_parse_state_in_progress);
-
-    mpack_type_t type = node->type;
-    size_t total = node->len;
-
-    // Calculate total elements to read
-    if (type == mpack_type_map) {
-        if ((uint64_t)total * 2 > SIZE_MAX) {
-            mpack_tree_flag_error(tree, mpack_error_too_big);
-            return false;
-        }
-        total *= 2;
-    }
-
-    // Make sure we are under our total node limit (TODO can this overflow?)
-    tree->node_count += total;
-    if (tree->node_count > tree->max_nodes) {
-        mpack_tree_flag_error(tree, mpack_error_too_big);
-        return false;
-    }
-
-    // Each node is at least one byte. Count these bytes now to make
-    // sure there is enough data left.
-    if (!mpack_tree_reserve_bytes(tree, total))
-        return false;
-
-    // If there are enough nodes left in the current page, no need to grow
-    if (total <= parser->nodes_left) {
-        node->value.children = parser->nodes;
-        parser->nodes += total;
-        parser->nodes_left -= total;
-
-    } else {
-
-        #ifdef MPACK_MALLOC
-
-        // We can't grow if we're using a fixed pool (i.e. we didn't start with a page)
-        if (!tree->next) {
-            mpack_tree_flag_error(tree, mpack_error_too_big);
-            return false;
-        }
-
-        // Otherwise we need to grow, and the node's children need to be contiguous.
-        // This is a heuristic to decide whether we should waste the remaining space
-        // in the current page and start a new one, or give the children their
-        // own page. With a fraction of 1/8, this causes at most 12% additional
-        // waste. Note that reducing this too much causes less cache coherence and
-        // more malloc() overhead due to smaller allocations, so there's a tradeoff
-        // here. This heuristic could use some improvement, especially with custom
-        // page sizes.
-
-        mpack_tree_page_t* page;
-
-        if (total > MPACK_NODES_PER_PAGE || parser->nodes_left > MPACK_NODES_PER_PAGE / 8) {
-            // TODO: this should check for overflow
-            page = (mpack_tree_page_t*)MPACK_MALLOC(
-                    sizeof(mpack_tree_page_t) + sizeof(mpack_node_data_t) * (total - 1));
-            if (page == NULL) {
-                mpack_tree_flag_error(tree, mpack_error_memory);
-                return false;
-            }
-            mpack_log("allocated seperate page %p for %i children, %i left in page of %i total\n",
-                    page, (int)total, (int)parser->nodes_left, (int)MPACK_NODES_PER_PAGE);
-
-            node->value.children = page->nodes;
-
-        } else {
-            page = (mpack_tree_page_t*)MPACK_MALLOC(MPACK_PAGE_ALLOC_SIZE);
-            if (page == NULL) {
-                mpack_tree_flag_error(tree, mpack_error_memory);
-                return false;
-            }
-            mpack_log("allocated new page %p for %i children, wasting %i in page of %i total\n",
-                    page, (int)total, (int)parser->nodes_left, (int)MPACK_NODES_PER_PAGE);
-
-            node->value.children = page->nodes;
-            parser->nodes = page->nodes + total;
-            parser->nodes_left = MPACK_NODES_PER_PAGE - total;
-        }
-
-        page->next = tree->next;
-        tree->next = page;
-
-        #else
-        // We can't grow if we don't have an allocator
-        mpack_tree_flag_error(tree, mpack_error_too_big);
-        return false;
-        #endif
-    }
-
-    return mpack_tree_push_stack(tree, node->value.children, total);
-}
-
-static bool mpack_tree_parse_bytes(mpack_tree_t* tree, mpack_node_data_t* node) {
-    node->value.offset = tree->size + tree->parser.current_node_reserved + 1;
-    return mpack_tree_reserve_bytes(tree, node->len);
-}
-
-#if MPACK_EXTENSIONS
-static bool mpack_tree_parse_ext(mpack_tree_t* tree, mpack_node_data_t* node) {
-    // reserve space for exttype
-    tree->parser.current_node_reserved += sizeof(int8_t);
-    node->type = mpack_type_ext;
-    return mpack_tree_parse_bytes(tree, node);
-}
-#endif
-
-static bool mpack_tree_parse_node_contents(mpack_tree_t* tree, mpack_node_data_t* node) {
-    mpack_assert(tree->parser.state == mpack_tree_parse_state_in_progress);
-    mpack_assert(node != NULL, "null node?");
-
-    // read the type. we've already accounted for this byte in
-    // possible_nodes_left, so we already know it is in bounds, and we don't
-    // need to reserve it for this node.
-    mpack_assert(tree->data_length > tree->size);
-    uint8_t type = mpack_load_u8(tree->data + tree->size);
-    mpack_log("node type %x\n", type);
-    tree->parser.current_node_reserved = 0;
-
-    // as with mpack_read_tag(), the fastest way to parse a node is to switch
-    // on the first byte, and to explicitly list every possible byte. we switch
-    // on the first four bits in size-optimized builds.
-
-    #if MPACK_OPTIMIZE_FOR_SIZE
-    switch (type >> 4) {
-
-        // positive fixnum
-        case 0x0: case 0x1: case 0x2: case 0x3:
-        case 0x4: case 0x5: case 0x6: case 0x7:
-            node->type = mpack_type_uint;
-            node->value.u = type;
-            return true;
-
-        // negative fixnum
-        case 0xe: case 0xf:
-            node->type = mpack_type_int;
-            node->value.i = (int8_t)type;
-            return true;
-
-        // fixmap
-        case 0x8:
-            node->type = mpack_type_map;
-            node->len = (uint32_t)(type & ~0xf0);
-            return mpack_tree_parse_children(tree, node);
-
-        // fixarray
-        case 0x9:
-            node->type = mpack_type_array;
-            node->len = (uint32_t)(type & ~0xf0);
-            return mpack_tree_parse_children(tree, node);
-
-        // fixstr
-        case 0xa: case 0xb:
-            node->type = mpack_type_str;
-            node->len = (uint32_t)(type & ~0xe0);
-            return mpack_tree_parse_bytes(tree, node);
-
-        // not one of the common infix types
-        default:
-            break;
-    }
-    #endif
-
-    switch (type) {
-
-        #if !MPACK_OPTIMIZE_FOR_SIZE
-        // positive fixnum
-        case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07:
-        case 0x08: case 0x09: case 0x0a: case 0x0b: case 0x0c: case 0x0d: case 0x0e: case 0x0f:
-        case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17:
-        case 0x18: case 0x19: case 0x1a: case 0x1b: case 0x1c: case 0x1d: case 0x1e: case 0x1f:
-        case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27:
-        case 0x28: case 0x29: case 0x2a: case 0x2b: case 0x2c: case 0x2d: case 0x2e: case 0x2f:
-        case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37:
-        case 0x38: case 0x39: case 0x3a: case 0x3b: case 0x3c: case 0x3d: case 0x3e: case 0x3f:
-        case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47:
-        case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f:
-        case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57:
-        case 0x58: case 0x59: case 0x5a: case 0x5b: case 0x5c: case 0x5d: case 0x5e: case 0x5f:
-        case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67:
-        case 0x68: case 0x69: case 0x6a: case 0x6b: case 0x6c: case 0x6d: case 0x6e: case 0x6f:
-        case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77:
-        case 0x78: case 0x79: case 0x7a: case 0x7b: case 0x7c: case 0x7d: case 0x7e: case 0x7f:
-            node->type = mpack_type_uint;
-            node->value.u = type;
-            return true;
-
-        // negative fixnum
-        case 0xe0: case 0xe1: case 0xe2: case 0xe3: case 0xe4: case 0xe5: case 0xe6: case 0xe7:
-        case 0xe8: case 0xe9: case 0xea: case 0xeb: case 0xec: case 0xed: case 0xee: case 0xef:
-        case 0xf0: case 0xf1: case 0xf2: case 0xf3: case 0xf4: case 0xf5: case 0xf6: case 0xf7:
-        case 0xf8: case 0xf9: case 0xfa: case 0xfb: case 0xfc: case 0xfd: case 0xfe: case 0xff:
-            node->type = mpack_type_int;
-            node->value.i = (int8_t)type;
-            return true;
-
-        // fixmap
-        case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87:
-        case 0x88: case 0x89: case 0x8a: case 0x8b: case 0x8c: case 0x8d: case 0x8e: case 0x8f:
-            node->type = mpack_type_map;
-            node->len = (uint32_t)(type & ~0xf0);
-            return mpack_tree_parse_children(tree, node);
-
-        // fixarray
-        case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97:
-        case 0x98: case 0x99: case 0x9a: case 0x9b: case 0x9c: case 0x9d: case 0x9e: case 0x9f:
-            node->type = mpack_type_array;
-            node->len = (uint32_t)(type & ~0xf0);
-            return mpack_tree_parse_children(tree, node);
-
-        // fixstr
-        case 0xa0: case 0xa1: case 0xa2: case 0xa3: case 0xa4: case 0xa5: case 0xa6: case 0xa7:
-        case 0xa8: case 0xa9: case 0xaa: case 0xab: case 0xac: case 0xad: case 0xae: case 0xaf:
-        case 0xb0: case 0xb1: case 0xb2: case 0xb3: case 0xb4: case 0xb5: case 0xb6: case 0xb7:
-        case 0xb8: case 0xb9: case 0xba: case 0xbb: case 0xbc: case 0xbd: case 0xbe: case 0xbf:
-            node->type = mpack_type_str;
-            node->len = (uint32_t)(type & ~0xe0);
-            return mpack_tree_parse_bytes(tree, node);
-        #endif
-
-        // nil
-        case 0xc0:
-            node->type = mpack_type_nil;
-            return true;
-
-        // bool
-        case 0xc2: case 0xc3:
-            node->type = mpack_type_bool;
-            node->value.b = type & 1;
-            return true;
-
-        // bin8
-        case 0xc4:
-            node->type = mpack_type_bin;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint8_t)))
-                return false;
-            node->len = mpack_load_u8(tree->data + tree->size + 1);
-            return mpack_tree_parse_bytes(tree, node);
-
-        // bin16
-        case 0xc5:
-            node->type = mpack_type_bin;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint16_t)))
-                return false;
-            node->len = mpack_load_u16(tree->data + tree->size + 1);
-            return mpack_tree_parse_bytes(tree, node);
-
-        // bin32
-        case 0xc6:
-            node->type = mpack_type_bin;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint32_t)))
-                return false;
-            node->len = mpack_load_u32(tree->data + tree->size + 1);
-            return mpack_tree_parse_bytes(tree, node);
-
-        #if MPACK_EXTENSIONS
-        // ext8
-        case 0xc7:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint8_t)))
-                return false;
-            node->len = mpack_load_u8(tree->data + tree->size + 1);
-            return mpack_tree_parse_ext(tree, node);
-
-        // ext16
-        case 0xc8:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint16_t)))
-                return false;
-            node->len = mpack_load_u16(tree->data + tree->size + 1);
-            return mpack_tree_parse_ext(tree, node);
-
-        // ext32
-        case 0xc9:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint32_t)))
-                return false;
-            node->len = mpack_load_u32(tree->data + tree->size + 1);
-            return mpack_tree_parse_ext(tree, node);
-        #endif
-
-        // float
-        case 0xca:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(float)))
-                return false;
-            node->value.f = mpack_load_float(tree->data + tree->size + 1);
-            node->type = mpack_type_float;
-            return true;
-
-        // double
-        case 0xcb:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(double)))
-                return false;
-            node->value.d = mpack_load_double(tree->data + tree->size + 1);
-            node->type = mpack_type_double;
-            return true;
-
-        // uint8
-        case 0xcc:
-            node->type = mpack_type_uint;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint8_t)))
-                return false;
-            node->value.u = mpack_load_u8(tree->data + tree->size + 1);
-            return true;
-
-        // uint16
-        case 0xcd:
-            node->type = mpack_type_uint;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint16_t)))
-                return false;
-            node->value.u = mpack_load_u16(tree->data + tree->size + 1);
-            return true;
-
-        // uint32
-        case 0xce:
-            node->type = mpack_type_uint;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint32_t)))
-                return false;
-            node->value.u = mpack_load_u32(tree->data + tree->size + 1);
-            return true;
-
-        // uint64
-        case 0xcf:
-            node->type = mpack_type_uint;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint64_t)))
-                return false;
-            node->value.u = mpack_load_u64(tree->data + tree->size + 1);
-            return true;
-
-        // int8
-        case 0xd0:
-            node->type = mpack_type_int;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(int8_t)))
-                return false;
-            node->value.i = mpack_load_i8(tree->data + tree->size + 1);
-            return true;
-
-        // int16
-        case 0xd1:
-            node->type = mpack_type_int;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(int16_t)))
-                return false;
-            node->value.i = mpack_load_i16(tree->data + tree->size + 1);
-            return true;
-
-        // int32
-        case 0xd2:
-            node->type = mpack_type_int;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(int32_t)))
-                return false;
-            node->value.i = mpack_load_i32(tree->data + tree->size + 1);
-            return true;
-
-        // int64
-        case 0xd3:
-            node->type = mpack_type_int;
-            if (!mpack_tree_reserve_bytes(tree, sizeof(int64_t)))
-                return false;
-            node->value.i = mpack_load_i64(tree->data + tree->size + 1);
-            return true;
-
-        #if MPACK_EXTENSIONS
-        // fixext1
-        case 0xd4:
-            node->len = 1;
-            return mpack_tree_parse_ext(tree, node);
-
-        // fixext2
-        case 0xd5:
-            node->len = 2;
-            return mpack_tree_parse_ext(tree, node);
-
-        // fixext4
-        case 0xd6:
-            node->len = 4;
-            return mpack_tree_parse_ext(tree, node);
-
-        // fixext8
-        case 0xd7:
-            node->len = 8;
-            return mpack_tree_parse_ext(tree, node);
-
-        // fixext16
-        case 0xd8:
-            node->len = 16;
-            return mpack_tree_parse_ext(tree, node);
-        #endif
-
-        // str8
-        case 0xd9:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint8_t)))
-                return false;
-            node->len = mpack_load_u8(tree->data + tree->size + 1);
-            node->type = mpack_type_str;
-            return mpack_tree_parse_bytes(tree, node);
-
-        // str16
-        case 0xda:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint16_t)))
-                return false;
-            node->len = mpack_load_u16(tree->data + tree->size + 1);
-            node->type = mpack_type_str;
-            return mpack_tree_parse_bytes(tree, node);
-
-        // str32
-        case 0xdb:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint32_t)))
-                return false;
-            node->len = mpack_load_u32(tree->data + tree->size + 1);
-            node->type = mpack_type_str;
-            return mpack_tree_parse_bytes(tree, node);
-
-        // array16
-        case 0xdc:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint16_t)))
-                return false;
-            node->len = mpack_load_u16(tree->data + tree->size + 1);
-            node->type = mpack_type_array;
-            return mpack_tree_parse_children(tree, node);
-
-        // array32
-        case 0xdd:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint32_t)))
-                return false;
-            node->len = mpack_load_u32(tree->data + tree->size + 1);
-            node->type = mpack_type_array;
-            return mpack_tree_parse_children(tree, node);
-
-        // map16
-        case 0xde:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint16_t)))
-                return false;
-            node->len = mpack_load_u16(tree->data + tree->size + 1);
-            node->type = mpack_type_map;
-            return mpack_tree_parse_children(tree, node);
-
-        // map32
-        case 0xdf:
-            if (!mpack_tree_reserve_bytes(tree, sizeof(uint32_t)))
-                return false;
-            node->len = mpack_load_u32(tree->data + tree->size + 1);
-            node->type = mpack_type_map;
-            return mpack_tree_parse_children(tree, node);
-
-        // reserved
-        case 0xc1:
-            mpack_tree_flag_error(tree, mpack_error_invalid);
-            return false;
-
-        #if !MPACK_EXTENSIONS
-        // ext
-        case 0xc7: // fallthrough
-        case 0xc8: // fallthrough
-        case 0xc9: // fallthrough
-        // fixext
-        case 0xd4: // fallthrough
-        case 0xd5: // fallthrough
-        case 0xd6: // fallthrough
-        case 0xd7: // fallthrough
-        case 0xd8:
-            mpack_tree_flag_error(tree, mpack_error_unsupported);
-            return false;
-        #endif
-
-        #if MPACK_OPTIMIZE_FOR_SIZE
-        // any other bytes should have been handled by the infix switch
-        default:
-            break;
-        #endif
-    }
-
-    mpack_assert(0, "unreachable");
-    return false;
-}
-
-static bool mpack_tree_parse_node(mpack_tree_t* tree, mpack_node_data_t* node) {
-    mpack_log("parsing a node at position %i in level %i\n",
-            (int)tree->size, (int)tree->parser.level);
-
-    if (!mpack_tree_parse_node_contents(tree, node)) {
-        mpack_log("node parsing returned false\n");
-        return false;
-    }
-
-    tree->parser.possible_nodes_left -= tree->parser.current_node_reserved;
-
-    // The reserve for the current node does not include the initial byte
-    // previously reserved as part of its parent.
-    size_t node_size = tree->parser.current_node_reserved + 1;
-
-    // If the parsed type is a map or array, the reserve includes one byte for
-    // each child. We want to subtract these out of possible_nodes_left, but
-    // not out of the current size of the tree.
-    if (node->type == mpack_type_array)
-        node_size -= node->len;
-    else if (node->type == mpack_type_map)
-        node_size -= node->len * 2;
-    tree->size += node_size;
-
-    mpack_log("parsed a node of type %s of %i bytes and "
-            "%i additional bytes reserved for children.\n",
-            mpack_type_to_string(node->type), (int)node_size,
-            (int)tree->parser.current_node_reserved + 1 - (int)node_size);
-
-    return true;
-}
-
-/*
- * We read nodes in a loop instead of recursively for maximum performance. The
- * stack holds the amount of children left to read in each level of the tree.
- * Parsing can pause and resume when more data becomes available.
- */
-static bool mpack_tree_continue_parsing(mpack_tree_t* tree) {
-    if (mpack_tree_error(tree) != mpack_ok)
-        return false;
-
-    mpack_tree_parser_t* parser = &tree->parser;
-    mpack_assert(parser->state == mpack_tree_parse_state_in_progress);
-    mpack_log("parsing tree elements, %i bytes in buffer\n", (int)tree->data_length);
-
-    // we loop parsing nodes until the parse stack is empty. we break
-    // by returning out of the function.
-    while (true) {
-        mpack_node_data_t* node = parser->stack[parser->level].child;
-        size_t level = parser->level;
-        if (!mpack_tree_parse_node(tree, node))
-            return false;
-        --parser->stack[level].left;
-        ++parser->stack[level].child;
-
-        mpack_assert(mpack_tree_error(tree) == mpack_ok,
-                "mpack_tree_parse_node() should have returned false due to error!");
-
-        // pop empty stack levels, exiting the outer loop when the stack is empty.
-        // (we could tail-optimize containers by pre-emptively popping empty
-        // stack levels before reading the new element, this way we wouldn't
-        // have to loop. but we eventually want to use the parse stack to give
-        // better error messages that contain the location of the error, so
-        // it needs to be complete.)
-        while (parser->stack[parser->level].left == 0) {
-            if (parser->level == 0)
-                return true;
-            --parser->level;
-        }
-    }
-}
-
-static void mpack_tree_cleanup(mpack_tree_t* tree) {
-    MPACK_UNUSED(tree);
-
-    #ifdef MPACK_MALLOC
-    if (tree->parser.stack_owned) {
-        MPACK_FREE(tree->parser.stack);
-        tree->parser.stack = NULL;
-        tree->parser.stack_owned = false;
-    }
-
-    mpack_tree_page_t* page = tree->next;
-    while (page != NULL) {
-        mpack_tree_page_t* next = page->next;
-        mpack_log("freeing page %p\n", page);
-        MPACK_FREE(page);
-        page = next;
-    }
-    tree->next = NULL;
-    #endif
-}
-
-static bool mpack_tree_parse_start(mpack_tree_t* tree) {
-    if (mpack_tree_error(tree) != mpack_ok)
-        return false;
-
-    mpack_tree_parser_t* parser = &tree->parser;
-    mpack_assert(parser->state != mpack_tree_parse_state_in_progress,
-            "previous parsing was not finished!");
-
-    if (parser->state == mpack_tree_parse_state_parsed)
-        mpack_tree_cleanup(tree);
-
-    mpack_log("starting parse\n");
-    tree->parser.state = mpack_tree_parse_state_in_progress;
-    tree->parser.current_node_reserved = 0;
-
-    // check if we previously parsed a tree
-    if (tree->size > 0) {
-        #ifdef MPACK_MALLOC
-        // if we're buffered, move the remaining data back to the
-        // start of the buffer
-        // TODO: This is not ideal performance-wise. We should only move data
-        // when we need to call the fill function.
-        // TODO: We could consider shrinking the buffer here, especially if we
-        // determine that the fill function is providing less than a quarter of
-        // the buffer size or if messages take up less than a quarter of the
-        // buffer size. Maybe this should be configurable.
-        if (tree->buffer != NULL) {
-            mpack_memmove(tree->buffer, tree->buffer + tree->size, tree->data_length - tree->size);
-        }
-        else
-        #endif
-        // otherwise advance past the parsed data
-        {
-            tree->data += tree->size;
-        }
-        tree->data_length -= tree->size;
-        tree->size = 0;
-        tree->node_count = 0;
-    }
-
-    // make sure we have at least one byte available before allocating anything
-    parser->possible_nodes_left = tree->data_length;
-    if (!mpack_tree_reserve_bytes(tree, sizeof(uint8_t))) {
-        tree->parser.state = mpack_tree_parse_state_not_started;
-        return false;
-    }
-    mpack_log("parsing tree at %p starting with byte %x\n", tree->data, (uint8_t)tree->data[0]);
-    parser->possible_nodes_left -= 1;
-    tree->node_count = 1;
-
-    #ifdef MPACK_MALLOC
-    parser->stack = parser->stack_local;
-    parser->stack_owned = false;
-    parser->stack_capacity = sizeof(parser->stack_local) / sizeof(*parser->stack_local);
-
-    if (tree->pool == NULL) {
-
-        // allocate first page
-        mpack_tree_page_t* page = (mpack_tree_page_t*)MPACK_MALLOC(MPACK_PAGE_ALLOC_SIZE);
-        mpack_log("allocated initial page %p of size %i count %i\n",
-                page, (int)MPACK_PAGE_ALLOC_SIZE, (int)MPACK_NODES_PER_PAGE);
-        if (page == NULL) {
-            tree->error = mpack_error_memory;
-            return false;
-        }
-        page->next = NULL;
-        tree->next = page;
-
-        parser->nodes = page->nodes;
-        parser->nodes_left = MPACK_NODES_PER_PAGE;
-    }
-    else
-    #endif
-    {
-        // otherwise use the provided pool
-        mpack_assert(tree->pool != NULL, "no pool provided?");
-        parser->nodes = tree->pool;
-        parser->nodes_left = tree->pool_count;
-    }
-
-    tree->root = parser->nodes;
-    ++parser->nodes;
-    --parser->nodes_left;
-
-    parser->level = 0;
-    parser->stack[0].child = tree->root;
-    parser->stack[0].left = 1;
-
-    return true;
-}
-
-void mpack_tree_parse(mpack_tree_t* tree) {
-    if (mpack_tree_error(tree) != mpack_ok)
-        return;
-
-    if (tree->parser.state != mpack_tree_parse_state_in_progress) {
-        if (!mpack_tree_parse_start(tree)) {
-            mpack_tree_flag_error(tree, (tree->read_fn == NULL) ?
-                    mpack_error_invalid : mpack_error_io);
-            return;
-        }
-    }
-
-    if (!mpack_tree_continue_parsing(tree)) {
-        if (mpack_tree_error(tree) != mpack_ok)
-            return;
-
-        // We're parsing synchronously on a blocking fill function. If we
-        // didn't completely finish parsing the tree, it's an error.
-        mpack_log("tree parsing incomplete. flagging error.\n");
-        mpack_tree_flag_error(tree, (tree->read_fn == NULL) ?
-                mpack_error_invalid : mpack_error_io);
-        return;
-    }
-
-    mpack_assert(mpack_tree_error(tree) == mpack_ok);
-    mpack_assert(tree->parser.level == 0);
-    tree->parser.state = mpack_tree_parse_state_parsed;
-    mpack_log("parsed tree of %i bytes, %i bytes left\n", (int)tree->size, (int)tree->parser.possible_nodes_left);
-    mpack_log("%i nodes in final page\n", (int)tree->parser.nodes_left);
-}
-
-bool mpack_tree_try_parse(mpack_tree_t* tree) {
-    if (mpack_tree_error(tree) != mpack_ok)
-        return false;
-
-    if (tree->parser.state != mpack_tree_parse_state_in_progress)
-        if (!mpack_tree_parse_start(tree))
-            return false;
-
-    if (!mpack_tree_continue_parsing(tree))
-        return false;
-
-    mpack_assert(mpack_tree_error(tree) == mpack_ok);
-    mpack_assert(tree->parser.level == 0);
-    tree->parser.state = mpack_tree_parse_state_parsed;
-    return true;
-}
-
-
-
-/*
- * Tree functions
- */
-
-mpack_node_t mpack_tree_root(mpack_tree_t* tree) {
-    if (mpack_tree_error(tree) != mpack_ok)
-        return mpack_tree_nil_node(tree);
-
-    // We check that a tree was parsed successfully and assert if not. You must
-    // call mpack_tree_parse() (or mpack_tree_try_parse() with a success
-    // result) in order to access the root node.
-    if (tree->parser.state != mpack_tree_parse_state_parsed) {
-        mpack_break("Tree has not been parsed! "
-                "Did you call mpack_tree_parse() or mpack_tree_try_parse()?");
-        mpack_tree_flag_error(tree, mpack_error_bug);
-        return mpack_tree_nil_node(tree);
-    }
-
-    return mpack_node(tree, tree->root);
-}
-
-static void mpack_tree_init_clear(mpack_tree_t* tree) {
-    mpack_memset(tree, 0, sizeof(*tree));
-    tree->nil_node.type = mpack_type_nil;
-    tree->missing_node.type = mpack_type_missing;
-    tree->max_size = SIZE_MAX;
-    tree->max_nodes = SIZE_MAX;
-}
-
-#ifdef MPACK_MALLOC
-void mpack_tree_init_data(mpack_tree_t* tree, const char* data, size_t length) {
-    mpack_tree_init_clear(tree);
-
-    MPACK_STATIC_ASSERT(MPACK_NODE_PAGE_SIZE >= sizeof(mpack_tree_page_t),
-            "MPACK_NODE_PAGE_SIZE is too small");
-
-    MPACK_STATIC_ASSERT(MPACK_PAGE_ALLOC_SIZE <= MPACK_NODE_PAGE_SIZE,
-            "incorrect page rounding?");
-
-    tree->data = data;
-    tree->data_length = length;
-    tree->pool = NULL;
-    tree->pool_count = 0;
-    tree->next = NULL;
-
-    mpack_log("===========================\n");
-    mpack_log("initializing tree with data of size %i\n", (int)length);
-}
-#endif
-
-void mpack_tree_init_pool(mpack_tree_t* tree, const char* data, size_t length,
-        mpack_node_data_t* node_pool, size_t node_pool_count)
-{
-    mpack_tree_init_clear(tree);
-    #ifdef MPACK_MALLOC
-    tree->next = NULL;
-    #endif
-
-    if (node_pool_count == 0) {
-        mpack_break("initial page has no nodes!");
-        mpack_tree_flag_error(tree, mpack_error_bug);
-        return;
-    }
-
-    tree->data = data;
-    tree->data_length = length;
-    tree->pool = node_pool;
-    tree->pool_count = node_pool_count;
-
-    mpack_log("===========================\n");
-    mpack_log("initializing tree with data of size %i and pool of count %i\n",
-            (int)length, (int)node_pool_count);
-}
-
-void mpack_tree_init_error(mpack_tree_t* tree, mpack_error_t error) {
-    mpack_tree_init_clear(tree);
-    tree->error = error;
-
-    mpack_log("===========================\n");
-    mpack_log("initializing tree error state %i\n", (int)error);
-}
-
-#ifdef MPACK_MALLOC
-void mpack_tree_init_stream(mpack_tree_t* tree, mpack_tree_read_t read_fn, void* context,
-        size_t max_message_size, size_t max_message_nodes) {
-    mpack_tree_init_clear(tree);
-
-    tree->read_fn = read_fn;
-    tree->context = context;
-
-    mpack_tree_set_limits(tree, max_message_size, max_message_nodes);
-    tree->max_size = max_message_size;
-    tree->max_nodes = max_message_nodes;
-
-    mpack_log("===========================\n");
-    mpack_log("initializing tree with stream, max size %i max nodes %i\n",
-            (int)max_message_size, (int)max_message_nodes);
-}
-#endif
-
-void mpack_tree_set_limits(mpack_tree_t* tree, size_t max_message_size, size_t max_message_nodes) {
-    mpack_assert(max_message_size > 0);
-    mpack_assert(max_message_nodes > 0);
-    tree->max_size = max_message_size;
-    tree->max_nodes = max_message_nodes;
-}
-
-#if MPACK_STDIO
-typedef struct mpack_file_tree_t {
-    char* data;
-    size_t size;
-    char buffer[MPACK_BUFFER_SIZE];
-} mpack_file_tree_t;
-
-static void mpack_file_tree_teardown(mpack_tree_t* tree) {
-    mpack_file_tree_t* file_tree = (mpack_file_tree_t*)tree->context;
-    MPACK_FREE(file_tree->data);
-    MPACK_FREE(file_tree);
-}
-
-static bool mpack_file_tree_read(mpack_tree_t* tree, mpack_file_tree_t* file_tree, FILE* file, size_t max_bytes) {
-
-    // get the file size
-    errno = 0;
-    int error = 0;
-    fseek(file, 0, SEEK_END);
-    error |= errno;
-    long size = ftell(file);
-    error |= errno;
-    fseek(file, 0, SEEK_SET);
-    error |= errno;
-
-    // check for errors
-    if (error != 0 || size < 0) {
-        mpack_tree_init_error(tree, mpack_error_io);
-        return false;
-    }
-    if (size == 0) {
-        mpack_tree_init_error(tree, mpack_error_invalid);
-        return false;
-    }
-
-    // make sure the size is less than max_bytes
-    // (this mess exists to safely convert between long and size_t regardless of their widths)
-    if (max_bytes != 0 && (((uint64_t)LONG_MAX > (uint64_t)SIZE_MAX && size > (long)SIZE_MAX) || (size_t)size > max_bytes)) {
-        mpack_tree_init_error(tree, mpack_error_too_big);
-        return false;
-    }
-
-    // allocate data
-    file_tree->data = (char*)MPACK_MALLOC((size_t)size);
-    if (file_tree->data == NULL) {
-        mpack_tree_init_error(tree, mpack_error_memory);
-        return false;
-    }
-
-    // read the file
-    long total = 0;
-    while (total < size) {
-        size_t read = fread(file_tree->data + total, 1, (size_t)(size - total), file);
-        if (read <= 0) {
-            mpack_tree_init_error(tree, mpack_error_io);
-            MPACK_FREE(file_tree->data);
-            return false;
-        }
-        total += (long)read;
-    }
-
-    file_tree->size = (size_t)size;
-    return true;
-}
-
-static bool mpack_tree_file_check_max_bytes(mpack_tree_t* tree, size_t max_bytes) {
-
-    // the C STDIO family of file functions use long (e.g. ftell)
-    if (max_bytes > LONG_MAX) {
-        mpack_break("max_bytes of %" PRIu64 " is invalid, maximum is LONG_MAX", (uint64_t)max_bytes);
-        mpack_tree_init_error(tree, mpack_error_bug);
-        return false;
-    }
-
-    return true;
-}
-
-static void mpack_tree_init_stdfile_noclose(mpack_tree_t* tree, FILE* stdfile, size_t max_bytes) {
-
-    // allocate file tree
-    mpack_file_tree_t* file_tree = (mpack_file_tree_t*) MPACK_MALLOC(sizeof(mpack_file_tree_t));
-    if (file_tree == NULL) {
-        mpack_tree_init_error(tree, mpack_error_memory);
-        return;
-    }
-
-    // read all data
-    if (!mpack_file_tree_read(tree, file_tree, stdfile, max_bytes)) {
-        MPACK_FREE(file_tree);
-        return;
-    }
-
-    mpack_tree_init_data(tree, file_tree->data, file_tree->size);
-    mpack_tree_set_context(tree, file_tree);
-    mpack_tree_set_teardown(tree, mpack_file_tree_teardown);
-}
-
-void mpack_tree_init_stdfile(mpack_tree_t* tree, FILE* stdfile, size_t max_bytes, bool close_when_done) {
-    if (!mpack_tree_file_check_max_bytes(tree, max_bytes))
-        return;
-
-    mpack_tree_init_stdfile_noclose(tree, stdfile, max_bytes);
-
-    if (close_when_done)
-        fclose(stdfile);
-}
-
-void mpack_tree_init_filename(mpack_tree_t* tree, const char* filename, size_t max_bytes) {
-    if (!mpack_tree_file_check_max_bytes(tree, max_bytes))
-        return;
-
-    // open the file
-    FILE* file = fopen(filename, "rb");
-    if (!file) {
-        mpack_tree_init_error(tree, mpack_error_io);
-        return;
-    }
-
-    mpack_tree_init_stdfile(tree, file, max_bytes, true);
-}
-#endif
-
-mpack_error_t mpack_tree_destroy(mpack_tree_t* tree) {
-    mpack_tree_cleanup(tree);
-
-    #ifdef MPACK_MALLOC
-    if (tree->buffer)
-        MPACK_FREE(tree->buffer);
-    #endif
-
-    if (tree->teardown)
-        tree->teardown(tree);
-    tree->teardown = NULL;
-
-    return tree->error;
-}
-
-void mpack_tree_flag_error(mpack_tree_t* tree, mpack_error_t error) {
-    if (tree->error == mpack_ok) {
-        mpack_log("tree %p setting error %i: %s\n", tree, (int)error, mpack_error_to_string(error));
-        tree->error = error;
-        if (tree->error_fn)
-            tree->error_fn(tree, error);
-    }
-
-}
-
-
-
-/*
- * Node misc functions
- */
-
-void mpack_node_flag_error(mpack_node_t node, mpack_error_t error) {
-    mpack_tree_flag_error(node.tree, error);
-}
-
-mpack_tag_t mpack_node_tag(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return mpack_tag_nil();
-
-    mpack_tag_t tag = MPACK_TAG_ZERO;
-
-    tag.type = node.data->type;
-    switch (node.data->type) {
-        case mpack_type_missing:
-            // If a node is missing, I don't know if it makes sense to ask for
-            // a tag for it. We'll return a missing tag to match the missing
-            // node I guess, but attempting to use the tag for anything (like
-            // writing it for example) will flag mpack_error_bug.
-            break;
-        case mpack_type_nil:                                            break;
-        case mpack_type_bool:    tag.v.b = node.data->value.b;          break;
-        case mpack_type_float:   tag.v.f = node.data->value.f;          break;
-        case mpack_type_double:  tag.v.d = node.data->value.d;          break;
-        case mpack_type_int:     tag.v.i = node.data->value.i;          break;
-        case mpack_type_uint:    tag.v.u = node.data->value.u;          break;
-
-        case mpack_type_str:     tag.v.l = node.data->len;     break;
-        case mpack_type_bin:     tag.v.l = node.data->len;     break;
-
-        #if MPACK_EXTENSIONS
-        case mpack_type_ext:
-            tag.v.l = node.data->len;
-            tag.exttype = mpack_node_exttype_unchecked(node);
-            break;
-        #endif
-
-        case mpack_type_array:   tag.v.n = node.data->len;  break;
-        case mpack_type_map:     tag.v.n = node.data->len;  break;
-
-        default:
-            mpack_assert(0, "unrecognized type %i", (int)node.data->type);
-            break;
-    }
-    return tag;
-}
-
-#if MPACK_DEBUG && MPACK_STDIO
-static void mpack_node_print_element(mpack_node_t node, mpack_print_t* print, size_t depth) {
-    mpack_node_data_t* data = node.data;
-    switch (data->type) {
-        case mpack_type_str:
-            {
-                mpack_print_append_cstr(print, "\"");
-                const char* bytes = mpack_node_data_unchecked(node);
-                for (size_t i = 0; i < data->len; ++i) {
-                    char c = bytes[i];
-                    switch (c) {
-                        case '\n': mpack_print_append_cstr(print, "\\n"); break;
-                        case '\\': mpack_print_append_cstr(print, "\\\\"); break;
-                        case '"': mpack_print_append_cstr(print, "\\\""); break;
-                        default: mpack_print_append(print, &c, 1); break;
-                    }
-                }
-                mpack_print_append_cstr(print, "\"");
-            }
-            break;
-
-        case mpack_type_array:
-            mpack_print_append_cstr(print, "[\n");
-            for (size_t i = 0; i < data->len; ++i) {
-                for (size_t j = 0; j < depth + 1; ++j)
-                    mpack_print_append_cstr(print, "    ");
-                mpack_node_print_element(mpack_node_array_at(node, i), print, depth + 1);
-                if (i != data->len - 1)
-                    mpack_print_append_cstr(print, ",");
-                mpack_print_append_cstr(print, "\n");
-            }
-            for (size_t i = 0; i < depth; ++i)
-                mpack_print_append_cstr(print, "    ");
-            mpack_print_append_cstr(print, "]");
-            break;
-
-        case mpack_type_map:
-            mpack_print_append_cstr(print, "{\n");
-            for (size_t i = 0; i < data->len; ++i) {
-                for (size_t j = 0; j < depth + 1; ++j)
-                    mpack_print_append_cstr(print, "    ");
-                mpack_node_print_element(mpack_node_map_key_at(node, i), print, depth + 1);
-                mpack_print_append_cstr(print, ": ");
-                mpack_node_print_element(mpack_node_map_value_at(node, i), print, depth + 1);
-                if (i != data->len - 1)
-                    mpack_print_append_cstr(print, ",");
-                mpack_print_append_cstr(print, "\n");
-            }
-            for (size_t i = 0; i < depth; ++i)
-                mpack_print_append_cstr(print, "    ");
-            mpack_print_append_cstr(print, "}");
-            break;
-
-        default:
-            {
-                const char* prefix = NULL;
-                size_t prefix_length = 0;
-                if (mpack_node_type(node) == mpack_type_bin
-                        #if MPACK_EXTENSIONS
-                        || mpack_node_type(node) == mpack_type_ext
-                        #endif
-                ) {
-                    prefix = mpack_node_data(node);
-                    prefix_length = mpack_node_data_len(node);
-                }
-
-                char buf[256];
-                mpack_tag_t tag = mpack_node_tag(node);
-                mpack_tag_debug_pseudo_json(tag, buf, sizeof(buf), prefix, prefix_length);
-                mpack_print_append_cstr(print, buf);
-            }
-            break;
-    }
-}
-
-void mpack_node_print_to_buffer(mpack_node_t node, char* buffer, size_t buffer_size) {
-    if (buffer_size == 0) {
-        mpack_assert(false, "buffer size is zero!");
-        return;
-    }
-
-    mpack_print_t print;
-    mpack_memset(&print, 0, sizeof(print));
-    print.buffer = buffer;
-    print.size = buffer_size;
-    mpack_node_print_element(node, &print, 0);
-    mpack_print_append(&print, "",  1); // null-terminator
-    mpack_print_flush(&print);
-
-    // we always make sure there's a null-terminator at the end of the buffer
-    // in case we ran out of space.
-    print.buffer[print.size - 1] = '\0';
-}
-
-void mpack_node_print_to_callback(mpack_node_t node, mpack_print_callback_t callback, void* context) {
-    char buffer[1024];
-    mpack_print_t print;
-    mpack_memset(&print, 0, sizeof(print));
-    print.buffer = buffer;
-    print.size = sizeof(buffer);
-    print.callback = callback;
-    print.context = context;
-    mpack_node_print_element(node, &print, 0);
-    mpack_print_flush(&print);
-}
-
-void mpack_node_print_to_file(mpack_node_t node, FILE* file) {
-    mpack_assert(file != NULL, "file is NULL");
-
-    char buffer[1024];
-    mpack_print_t print;
-    mpack_memset(&print, 0, sizeof(print));
-    print.buffer = buffer;
-    print.size = sizeof(buffer);
-    print.callback = &mpack_print_file_callback;
-    print.context = file;
-
-    size_t depth = 2;
-    for (size_t i = 0; i < depth; ++i)
-        mpack_print_append_cstr(&print, "    ");
-    mpack_node_print_element(node, &print, depth);
-    mpack_print_append_cstr(&print, "\n");
-    mpack_print_flush(&print);
-}
-#endif
- 
-
- 
-/*
- * Node Value Functions
- */
-
-#if MPACK_EXTENSIONS
-mpack_timestamp_t mpack_node_timestamp(mpack_node_t node) {
-    mpack_timestamp_t timestamp = {0, 0};
-
-    // we'll let mpack_node_exttype() do most checks
-    if (mpack_node_exttype(node) != MPACK_EXTTYPE_TIMESTAMP) {
-        mpack_log("exttype %i\n", mpack_node_exttype(node));
-        mpack_node_flag_error(node, mpack_error_type);
-        return timestamp;
-    }
-
-    const char* p = mpack_node_data_unchecked(node);
-
-    switch (node.data->len) {
-        case 4:
-            timestamp.nanoseconds = 0;
-            timestamp.seconds = mpack_load_u32(p);
-            break;
-
-        case 8: {
-            uint64_t value = mpack_load_u64(p);
-            timestamp.nanoseconds = (uint32_t)(value >> 34);
-            timestamp.seconds = value & ((UINT64_C(1) << 34) - 1);
-            break;
-        }
-
-        case 12:
-            timestamp.nanoseconds = mpack_load_u32(p);
-            timestamp.seconds = mpack_load_i64(p + 4);
-            break;
-
-        default:
-            mpack_tree_flag_error(node.tree, mpack_error_invalid);
-            return timestamp;
-    }
-
-    if (timestamp.nanoseconds > MPACK_TIMESTAMP_NANOSECONDS_MAX) {
-        mpack_tree_flag_error(node.tree, mpack_error_invalid);
-        mpack_timestamp_t zero = {0, 0};
-        return zero;
-    }
-
-    return timestamp;
-}
-
-int64_t mpack_node_timestamp_seconds(mpack_node_t node) {
-    return mpack_node_timestamp(node).seconds;
-}
-
-uint32_t mpack_node_timestamp_nanoseconds(mpack_node_t node) {
-    return mpack_node_timestamp(node).nanoseconds;
-}
-#endif
-
-
-
-/*
- * Node Data Functions
- */
-
-void mpack_node_check_utf8(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return;
-    mpack_node_data_t* data = node.data;
-    if (data->type != mpack_type_str || !mpack_utf8_check(mpack_node_data_unchecked(node), data->len))
-        mpack_node_flag_error(node, mpack_error_type);
-}
-
-void mpack_node_check_utf8_cstr(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return;
-    mpack_node_data_t* data = node.data;
-    if (data->type != mpack_type_str || !mpack_utf8_check_no_null(mpack_node_data_unchecked(node), data->len))
-        mpack_node_flag_error(node, mpack_error_type);
-}
-
-size_t mpack_node_copy_data(mpack_node_t node, char* buffer, size_t bufsize) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    mpack_assert(bufsize == 0 || buffer != NULL, "buffer is NULL for maximum of %i bytes", (int)bufsize);
-
-    mpack_type_t type = node.data->type;
-    if (type != mpack_type_str && type != mpack_type_bin
-            #if MPACK_EXTENSIONS
-            && type != mpack_type_ext
-            #endif
-    ) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return 0;
-    }
-
-    if (node.data->len > bufsize) {
-        mpack_node_flag_error(node, mpack_error_too_big);
-        return 0;
-    }
-
-    mpack_memcpy(buffer, mpack_node_data_unchecked(node), node.data->len);
-    return (size_t)node.data->len;
-}
-
-size_t mpack_node_copy_utf8(mpack_node_t node, char* buffer, size_t bufsize) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    mpack_assert(bufsize == 0 || buffer != NULL, "buffer is NULL for maximum of %i bytes", (int)bufsize);
-
-    mpack_type_t type = node.data->type;
-    if (type != mpack_type_str) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return 0;
-    }
-
-    if (node.data->len > bufsize) {
-        mpack_node_flag_error(node, mpack_error_too_big);
-        return 0;
-    }
-
-    if (!mpack_utf8_check(mpack_node_data_unchecked(node), node.data->len)) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return 0;
-    }
-
-    mpack_memcpy(buffer, mpack_node_data_unchecked(node), node.data->len);
-    return (size_t)node.data->len;
-}
-
-void mpack_node_copy_cstr(mpack_node_t node, char* buffer, size_t bufsize) {
-
-    // we can't break here because the error isn't recoverable; we
-    // have to add a null-terminator.
-    mpack_assert(buffer != NULL, "buffer is NULL");
-    mpack_assert(bufsize >= 1, "buffer size is zero; you must have room for at least a null-terminator");
-
-    if (mpack_node_error(node) != mpack_ok) {
-        buffer[0] = '\0';
-        return;
-    }
-
-    if (node.data->type != mpack_type_str) {
-        buffer[0] = '\0';
-        mpack_node_flag_error(node, mpack_error_type);
-        return;
-    }
-
-    if (node.data->len > bufsize - 1) {
-        buffer[0] = '\0';
-        mpack_node_flag_error(node, mpack_error_too_big);
-        return;
-    }
-
-    if (!mpack_str_check_no_null(mpack_node_data_unchecked(node), node.data->len)) {
-        buffer[0] = '\0';
-        mpack_node_flag_error(node, mpack_error_type);
-        return;
-    }
-
-    mpack_memcpy(buffer, mpack_node_data_unchecked(node), node.data->len);
-    buffer[node.data->len] = '\0';
-}
-
-void mpack_node_copy_utf8_cstr(mpack_node_t node, char* buffer, size_t bufsize) {
-
-    // we can't break here because the error isn't recoverable; we
-    // have to add a null-terminator.
-    mpack_assert(buffer != NULL, "buffer is NULL");
-    mpack_assert(bufsize >= 1, "buffer size is zero; you must have room for at least a null-terminator");
-
-    if (mpack_node_error(node) != mpack_ok) {
-        buffer[0] = '\0';
-        return;
-    }
-
-    if (node.data->type != mpack_type_str) {
-        buffer[0] = '\0';
-        mpack_node_flag_error(node, mpack_error_type);
-        return;
-    }
-
-    if (node.data->len > bufsize - 1) {
-        buffer[0] = '\0';
-        mpack_node_flag_error(node, mpack_error_too_big);
-        return;
-    }
-
-    if (!mpack_utf8_check_no_null(mpack_node_data_unchecked(node), node.data->len)) {
-        buffer[0] = '\0';
-        mpack_node_flag_error(node, mpack_error_type);
-        return;
-    }
-
-    mpack_memcpy(buffer, mpack_node_data_unchecked(node), node.data->len);
-    buffer[node.data->len] = '\0';
-}
-
-#ifdef MPACK_MALLOC
-char* mpack_node_data_alloc(mpack_node_t node, size_t maxlen) {
-    if (mpack_node_error(node) != mpack_ok)
-        return NULL;
-
-    // make sure this is a valid data type
-    mpack_type_t type = node.data->type;
-    if (type != mpack_type_str && type != mpack_type_bin
-            #if MPACK_EXTENSIONS
-            && type != mpack_type_ext
-            #endif
-    ) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return NULL;
-    }
-
-    if (node.data->len > maxlen) {
-        mpack_node_flag_error(node, mpack_error_too_big);
-        return NULL;
-    }
-
-    char* ret = (char*) MPACK_MALLOC((size_t)node.data->len);
-    if (ret == NULL) {
-        mpack_node_flag_error(node, mpack_error_memory);
-        return NULL;
-    }
-
-    mpack_memcpy(ret, mpack_node_data_unchecked(node), node.data->len);
-    return ret;
-}
-
-char* mpack_node_cstr_alloc(mpack_node_t node, size_t maxlen) {
-    if (mpack_node_error(node) != mpack_ok)
-        return NULL;
-
-    // make sure maxlen makes sense
-    if (maxlen < 1) {
-        mpack_break("maxlen is zero; you must have room for at least a null-terminator");
-        mpack_node_flag_error(node, mpack_error_bug);
-        return NULL;
-    }
-
-    if (node.data->type != mpack_type_str) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return NULL;
-    }
-
-    if (node.data->len > maxlen - 1) {
-        mpack_node_flag_error(node, mpack_error_too_big);
-        return NULL;
-    }
-
-    if (!mpack_str_check_no_null(mpack_node_data_unchecked(node), node.data->len)) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return NULL;
-    }
-
-    char* ret = (char*) MPACK_MALLOC((size_t)(node.data->len + 1));
-    if (ret == NULL) {
-        mpack_node_flag_error(node, mpack_error_memory);
-        return NULL;
-    }
-
-    mpack_memcpy(ret, mpack_node_data_unchecked(node), node.data->len);
-    ret[node.data->len] = '\0';
-    return ret;
-}
-
-char* mpack_node_utf8_cstr_alloc(mpack_node_t node, size_t maxlen) {
-    if (mpack_node_error(node) != mpack_ok)
-        return NULL;
-
-    // make sure maxlen makes sense
-    if (maxlen < 1) {
-        mpack_break("maxlen is zero; you must have room for at least a null-terminator");
-        mpack_node_flag_error(node, mpack_error_bug);
-        return NULL;
-    }
-
-    if (node.data->type != mpack_type_str) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return NULL;
-    }
-
-    if (node.data->len > maxlen - 1) {
-        mpack_node_flag_error(node, mpack_error_too_big);
-        return NULL;
-    }
-
-    if (!mpack_utf8_check_no_null(mpack_node_data_unchecked(node), node.data->len)) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return NULL;
-    }
-
-    char* ret = (char*) MPACK_MALLOC((size_t)(node.data->len + 1));
-    if (ret == NULL) {
-        mpack_node_flag_error(node, mpack_error_memory);
-        return NULL;
-    }
-
-    mpack_memcpy(ret, mpack_node_data_unchecked(node), node.data->len);
-    ret[node.data->len] = '\0';
-    return ret;
-}
-#endif
-
-
-/*
- * Compound Node Functions
- */
-
-static mpack_node_data_t* mpack_node_map_int_impl(mpack_node_t node, int64_t num) {
-    if (mpack_node_error(node) != mpack_ok)
-        return NULL;
-
-    if (node.data->type != mpack_type_map) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return NULL;
-    }
-
-    mpack_node_data_t* found = NULL;
-
-    for (size_t i = 0; i < node.data->len; ++i) {
-        mpack_node_data_t* key = mpack_node_child(node, i * 2);
-
-        if ((key->type == mpack_type_int && key->value.i == num) ||
-            (key->type == mpack_type_uint && num >= 0 && key->value.u == (uint64_t)num))
-        {
-            if (found) {
-                mpack_node_flag_error(node, mpack_error_data);
-                return NULL;
-            }
-            found = mpack_node_child(node, i * 2 + 1);
-        }
-    }
-
-    if (found)
-        return found;
-
-    return NULL;
-}
-
-static mpack_node_data_t* mpack_node_map_uint_impl(mpack_node_t node, uint64_t num) {
-    if (mpack_node_error(node) != mpack_ok)
-        return NULL;
-
-    if (node.data->type != mpack_type_map) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return NULL;
-    }
-
-    mpack_node_data_t* found = NULL;
-
-    for (size_t i = 0; i < node.data->len; ++i) {
-        mpack_node_data_t* key = mpack_node_child(node, i * 2);
-
-        if ((key->type == mpack_type_uint && key->value.u == num) ||
-            (key->type == mpack_type_int && key->value.i >= 0 && (uint64_t)key->value.i == num))
-        {
-            if (found) {
-                mpack_node_flag_error(node, mpack_error_data);
-                return NULL;
-            }
-            found = mpack_node_child(node, i * 2 + 1);
-        }
-    }
-
-    if (found)
-        return found;
-
-    return NULL;
-}
-
-static mpack_node_data_t* mpack_node_map_str_impl(mpack_node_t node, const char* str, size_t length) {
-    if (mpack_node_error(node) != mpack_ok)
-        return NULL;
-
-    mpack_assert(length == 0 || str != NULL, "str of length %i is NULL", (int)length);
-
-    if (node.data->type != mpack_type_map) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return NULL;
-    }
-
-    mpack_tree_t* tree = node.tree;
-    mpack_node_data_t* found = NULL;
-
-    for (size_t i = 0; i < node.data->len; ++i) {
-        mpack_node_data_t* key = mpack_node_child(node, i * 2);
-
-        if (key->type == mpack_type_str && key->len == length &&
-                mpack_memcmp(str, mpack_node_data_unchecked(mpack_node(tree, key)), length) == 0) {
-            if (found) {
-                mpack_node_flag_error(node, mpack_error_data);
-                return NULL;
-            }
-            found = mpack_node_child(node, i * 2 + 1);
-        }
-    }
-
-    if (found)
-        return found;
-
-    return NULL;
-}
-
-static mpack_node_t mpack_node_wrap_lookup(mpack_tree_t* tree, mpack_node_data_t* data) {
-    if (!data) {
-        if (tree->error == mpack_ok)
-            mpack_tree_flag_error(tree, mpack_error_data);
-        return mpack_tree_nil_node(tree);
-    }
-    return mpack_node(tree, data);
-}
-
-static mpack_node_t mpack_node_wrap_lookup_optional(mpack_tree_t* tree, mpack_node_data_t* data) {
-    if (!data) {
-        if (tree->error == mpack_ok)
-            return mpack_tree_missing_node(tree);
-        return mpack_tree_nil_node(tree);
-    }
-    return mpack_node(tree, data);
-}
-
-mpack_node_t mpack_node_map_int(mpack_node_t node, int64_t num) {
-    return mpack_node_wrap_lookup(node.tree, mpack_node_map_int_impl(node, num));
-}
-
-mpack_node_t mpack_node_map_int_optional(mpack_node_t node, int64_t num) {
-    return mpack_node_wrap_lookup_optional(node.tree, mpack_node_map_int_impl(node, num));
-}
-
-mpack_node_t mpack_node_map_uint(mpack_node_t node, uint64_t num) {
-    return mpack_node_wrap_lookup(node.tree, mpack_node_map_uint_impl(node, num));
-}
-
-mpack_node_t mpack_node_map_uint_optional(mpack_node_t node, uint64_t num) {
-    return mpack_node_wrap_lookup_optional(node.tree, mpack_node_map_uint_impl(node, num));
-}
-
-mpack_node_t mpack_node_map_str(mpack_node_t node, const char* str, size_t length) {
-    return mpack_node_wrap_lookup(node.tree, mpack_node_map_str_impl(node, str, length));
-}
-
-mpack_node_t mpack_node_map_str_optional(mpack_node_t node, const char* str, size_t length) {
-    return mpack_node_wrap_lookup_optional(node.tree, mpack_node_map_str_impl(node, str, length));
-}
-
-mpack_node_t mpack_node_map_cstr(mpack_node_t node, const char* cstr) {
-    mpack_assert(cstr != NULL, "cstr is NULL");
-    return mpack_node_map_str(node, cstr, mpack_strlen(cstr));
-}
-
-mpack_node_t mpack_node_map_cstr_optional(mpack_node_t node, const char* cstr) {
-    mpack_assert(cstr != NULL, "cstr is NULL");
-    return mpack_node_map_str_optional(node, cstr, mpack_strlen(cstr));
-}
-
-bool mpack_node_map_contains_int(mpack_node_t node, int64_t num) {
-    return mpack_node_map_int_impl(node, num) != NULL;
-}
-
-bool mpack_node_map_contains_uint(mpack_node_t node, uint64_t num) {
-    return mpack_node_map_uint_impl(node, num) != NULL;
-}
-
-bool mpack_node_map_contains_str(mpack_node_t node, const char* str, size_t length) {
-    return mpack_node_map_str_impl(node, str, length) != NULL;
-}
-
-bool mpack_node_map_contains_cstr(mpack_node_t node, const char* cstr) {
-    mpack_assert(cstr != NULL, "cstr is NULL");
-    return mpack_node_map_contains_str(node, cstr, mpack_strlen(cstr));
-}
-
-size_t mpack_node_enum_optional(mpack_node_t node, const char* strings[], size_t count) {
-    if (mpack_node_error(node) != mpack_ok)
-        return count;
-
-    // the value is only recognized if it is a string
-    if (mpack_node_type(node) != mpack_type_str)
-        return count;
-
-    // fetch the string
-    const char* key = mpack_node_str(node);
-    size_t keylen = mpack_node_strlen(node);
-    mpack_assert(mpack_node_error(node) == mpack_ok, "these should not fail");
-
-    // find what key it matches
-    for (size_t i = 0; i < count; ++i) {
-        const char* other = strings[i];
-        size_t otherlen = mpack_strlen(other);
-        if (keylen == otherlen && mpack_memcmp(key, other, keylen) == 0)
-            return i;
-    }
-
-    // no matches
-    return count;
-}
-
-size_t mpack_node_enum(mpack_node_t node, const char* strings[], size_t count) {
-    size_t value = mpack_node_enum_optional(node, strings, count);
-    if (value == count)
-        mpack_node_flag_error(node, mpack_error_type);
-    return value;
-}
-
-mpack_type_t mpack_node_type(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return mpack_type_nil;
-    return node.data->type;
-}
-
-bool mpack_node_is_nil(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok) {
-        // All nodes are treated as nil nodes when we are in error.
-        return true;
-    }
-    return node.data->type == mpack_type_nil;
-}
-
-bool mpack_node_is_missing(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok) {
-        // errors still return nil nodes, not missing nodes.
-        return false;
-    }
-    return node.data->type == mpack_type_missing;
-}
-
-void mpack_node_nil(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return;
-    if (node.data->type != mpack_type_nil)
-        mpack_node_flag_error(node, mpack_error_type);
-}
-
-void mpack_node_missing(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return;
-    if (node.data->type != mpack_type_missing)
-        mpack_node_flag_error(node, mpack_error_type);
-}
-
-bool mpack_node_bool(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return false;
-
-    if (node.data->type == mpack_type_bool)
-        return node.data->value.b;
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return false;
-}
-
-void mpack_node_true(mpack_node_t node) {
-    if (mpack_node_bool(node) != true)
-        mpack_node_flag_error(node, mpack_error_type);
-}
-
-void mpack_node_false(mpack_node_t node) {
-    if (mpack_node_bool(node) != false)
-        mpack_node_flag_error(node, mpack_error_type);
-}
-
-uint8_t mpack_node_u8(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_uint) {
-        if (node.data->value.u <= UINT8_MAX)
-            return (uint8_t)node.data->value.u;
-    } else if (node.data->type == mpack_type_int) {
-        if (node.data->value.i >= 0 && node.data->value.i <= UINT8_MAX)
-            return (uint8_t)node.data->value.i;
-    }
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-int8_t mpack_node_i8(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_uint) {
-        if (node.data->value.u <= INT8_MAX)
-            return (int8_t)node.data->value.u;
-    } else if (node.data->type == mpack_type_int) {
-        if (node.data->value.i >= INT8_MIN && node.data->value.i <= INT8_MAX)
-            return (int8_t)node.data->value.i;
-    }
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-uint16_t mpack_node_u16(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_uint) {
-        if (node.data->value.u <= UINT16_MAX)
-            return (uint16_t)node.data->value.u;
-    } else if (node.data->type == mpack_type_int) {
-        if (node.data->value.i >= 0 && node.data->value.i <= UINT16_MAX)
-            return (uint16_t)node.data->value.i;
-    }
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-int16_t mpack_node_i16(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_uint) {
-        if (node.data->value.u <= INT16_MAX)
-            return (int16_t)node.data->value.u;
-    } else if (node.data->type == mpack_type_int) {
-        if (node.data->value.i >= INT16_MIN && node.data->value.i <= INT16_MAX)
-            return (int16_t)node.data->value.i;
-    }
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-uint32_t mpack_node_u32(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_uint) {
-        if (node.data->value.u <= UINT32_MAX)
-            return (uint32_t)node.data->value.u;
-    } else if (node.data->type == mpack_type_int) {
-        if (node.data->value.i >= 0 && node.data->value.i <= UINT32_MAX)
-            return (uint32_t)node.data->value.i;
-    }
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-int32_t mpack_node_i32(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_uint) {
-        if (node.data->value.u <= INT32_MAX)
-            return (int32_t)node.data->value.u;
-    } else if (node.data->type == mpack_type_int) {
-        if (node.data->value.i >= INT32_MIN && node.data->value.i <= INT32_MAX)
-            return (int32_t)node.data->value.i;
-    }
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-uint64_t mpack_node_u64(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_uint) {
-        return node.data->value.u;
-    } else if (node.data->type == mpack_type_int) {
-        if (node.data->value.i >= 0)
-            return (uint64_t)node.data->value.i;
-    }
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-int64_t mpack_node_i64(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_uint) {
-        if (node.data->value.u <= (uint64_t)INT64_MAX)
-            return (int64_t)node.data->value.u;
-    } else if (node.data->type == mpack_type_int) {
-        return node.data->value.i;
-    }
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-unsigned int mpack_node_uint(mpack_node_t node) {
-
-    // This should be true at compile-time, so this just wraps the 32-bit function.
-    if (sizeof(unsigned int) == 4)
-        return (unsigned int)mpack_node_u32(node);
-
-    // Otherwise we use u64 and check the range.
-    uint64_t val = mpack_node_u64(node);
-    if (val <= UINT_MAX)
-        return (unsigned int)val;
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-int mpack_node_int(mpack_node_t node) {
-
-    // This should be true at compile-time, so this just wraps the 32-bit function.
-    if (sizeof(int) == 4)
-        return (int)mpack_node_i32(node);
-
-    // Otherwise we use i64 and check the range.
-    int64_t val = mpack_node_i64(node);
-    if (val >= INT_MIN && val <= INT_MAX)
-        return (int)val;
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-float mpack_node_float(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0.0f;
-
-    if (node.data->type == mpack_type_uint)
-        return (float)node.data->value.u;
-    else if (node.data->type == mpack_type_int)
-        return (float)node.data->value.i;
-    else if (node.data->type == mpack_type_float)
-        return node.data->value.f;
-    else if (node.data->type == mpack_type_double)
-        return (float)node.data->value.d;
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0.0f;
-}
-
-double mpack_node_double(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0.0;
-
-    if (node.data->type == mpack_type_uint)
-        return (double)node.data->value.u;
-    else if (node.data->type == mpack_type_int)
-        return (double)node.data->value.i;
-    else if (node.data->type == mpack_type_float)
-        return (double)node.data->value.f;
-    else if (node.data->type == mpack_type_double)
-        return node.data->value.d;
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0.0;
-}
-
-float mpack_node_float_strict(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0.0f;
-
-    if (node.data->type == mpack_type_float)
-        return node.data->value.f;
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0.0f;
-}
-
-double mpack_node_double_strict(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0.0;
-
-    if (node.data->type == mpack_type_float)
-        return (double)node.data->value.f;
-    else if (node.data->type == mpack_type_double)
-        return node.data->value.d;
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0.0;
-}
-
-#if MPACK_EXTENSIONS
-int8_t mpack_node_exttype(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_ext)
-        return mpack_node_exttype_unchecked(node);
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-#endif
-
-uint32_t mpack_node_data_len(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    mpack_type_t type = node.data->type;
-    if (type == mpack_type_str || type == mpack_type_bin
-            #if MPACK_EXTENSIONS
-            || type == mpack_type_ext
-            #endif
-            )
-        return (uint32_t)node.data->len;
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-size_t mpack_node_strlen(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_str)
-        return (size_t)node.data->len;
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-const char* mpack_node_str(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return NULL;
-
-    mpack_type_t type = node.data->type;
-    if (type == mpack_type_str)
-        return mpack_node_data_unchecked(node);
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return NULL;
-}
-
-const char* mpack_node_data(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return NULL;
-
-    mpack_type_t type = node.data->type;
-    if (type == mpack_type_str || type == mpack_type_bin
-            #if MPACK_EXTENSIONS
-            || type == mpack_type_ext
-            #endif
-            )
-        return mpack_node_data_unchecked(node);
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return NULL;
-}
-
-const char* mpack_node_bin_data(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return NULL;
-
-    if (node.data->type == mpack_type_bin)
-        return mpack_node_data_unchecked(node);
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return NULL;
-}
-
-size_t mpack_node_bin_size(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type == mpack_type_bin)
-        return (size_t)node.data->len;
-
-    mpack_node_flag_error(node, mpack_error_type);
-    return 0;
-}
-
-size_t mpack_node_array_length(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type != mpack_type_array) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return 0;
-    }
-
-    return (size_t)node.data->len;
-}
-
-mpack_node_t mpack_node_array_at(mpack_node_t node, size_t index) {
-    if (mpack_node_error(node) != mpack_ok)
-        return mpack_tree_nil_node(node.tree);
-
-    if (node.data->type != mpack_type_array) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return mpack_tree_nil_node(node.tree);
-    }
-
-    if (index >= node.data->len) {
-        mpack_node_flag_error(node, mpack_error_data);
-        return mpack_tree_nil_node(node.tree);
-    }
-
-    return mpack_node(node.tree, mpack_node_child(node, index));
-}
-
-size_t mpack_node_map_count(mpack_node_t node) {
-    if (mpack_node_error(node) != mpack_ok)
-        return 0;
-
-    if (node.data->type != mpack_type_map) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return 0;
-    }
-
-    return node.data->len;
-}
-
-// internal node map lookup
-static mpack_node_t mpack_node_map_at(mpack_node_t node, size_t index, size_t offset) {
-    if (mpack_node_error(node) != mpack_ok)
-        return mpack_tree_nil_node(node.tree);
-
-    if (node.data->type != mpack_type_map) {
-        mpack_node_flag_error(node, mpack_error_type);
-        return mpack_tree_nil_node(node.tree);
-    }
-
-    if (index >= node.data->len) {
-        mpack_node_flag_error(node, mpack_error_data);
-        return mpack_tree_nil_node(node.tree);
-    }
-
-    return mpack_node(node.tree, mpack_node_child(node, index * 2 + offset));
-}
-
-mpack_node_t mpack_node_map_key_at(mpack_node_t node, size_t index) {
-    return mpack_node_map_at(node, index, 0);
-}
-
-mpack_node_t mpack_node_map_value_at(mpack_node_t node, size_t index) {
-    return mpack_node_map_at(node, index, 1);
-}
-
-#endif
diff --git a/vendor/mpack.h b/vendor/mpack.h
deleted file mode 100644
index ee989d8..0000000
--- a/vendor/mpack.h
+++ /dev/null
@@ -1,7151 +0,0 @@
-/**
- * The MIT License (MIT)
- * 
- * Copyright (c) 2015-2018 Nicholas Fraser
- * 
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- * 
- * The above copyright notice and this permission notice shall be included in all
- * copies or substantial portions of the Software.
- * 
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
- * SOFTWARE.
- * 
- */
-
-/*
- * This is the MPack 1.0 amalgamation package.
- *
- * http://github.com/ludocode/mpack
- */
-
-#ifndef MPACK_H
-#define MPACK_H 1
-
-#define MPACK_AMALGAMATED 1
-#define MPACK_RELEASE_VERSION 1
-
-#if defined(MPACK_HAS_CONFIG) && MPACK_HAS_CONFIG
-#include "mpack-config.h"
-#endif
-
-
-/* mpack/mpack-defaults.h.h */
-
-
-/**
- * @name Features
- * @{
- */
-
-/**
- * @def MPACK_READER
- *
- * Enables compilation of the base Tag Reader.
- */
-#ifndef MPACK_READER
-#define MPACK_READER 1
-#endif
-
-/**
- * @def MPACK_EXPECT
- *
- * Enables compilation of the static Expect API.
- */
-#ifndef MPACK_EXPECT
-#define MPACK_EXPECT 1
-#endif
-
-/**
- * @def MPACK_NODE
- *
- * Enables compilation of the dynamic Node API.
- */
-#ifndef MPACK_NODE
-#define MPACK_NODE 1
-#endif
-
-/**
- * @def MPACK_WRITER
- *
- * Enables compilation of the Writer.
- */
-#ifndef MPACK_WRITER
-#define MPACK_WRITER 1
-#endif
-
-/**
- * @def MPACK_COMPATIBILITY
- *
- * Enables compatibility features for reading and writing older
- * versions of MessagePack.
- *
- * This is disabled by default. When disabled, the behaviour is equivalent to
- * using the default version, @ref mpack_version_current.
- *
- * Enable this if you need to interoperate with applications or data that do
- * not support the new (v5) MessagePack spec. See the section on v4
- * compatibility in @ref docs/protocol.md for more information.
- */
-#ifndef MPACK_COMPATIBILITY
-#define MPACK_COMPATIBILITY 0
-#endif
-
-/**
- * @def MPACK_EXTENSIONS
- *
- * Enables the use of extension types.
- *
- * This is disabled by default. Define it to 1 to enable it. If disabled,
- * functions to read and write extensions will not exist, and any occurrence of
- * extension types in parsed messages will flag @ref mpack_error_invalid.
- *
- * MPack discourages the use of extension types. See the section on extension
- * types in @ref docs/protocol.md for more information.
- */
-#ifndef MPACK_EXTENSIONS
-#define MPACK_EXTENSIONS 0
-#endif
-
-
-/**
- * @}
- */
-
-
-/**
- * @name Dependencies
- * @{
- */
-
-/**
- * @def MPACK_HAS_CONFIG
- *
- * Enables the use of an @c mpack-config.h configuration file for MPack.
- * This file must be in the same folder as @c mpack.h, or it must be
- * available from your project's include paths.
- */
-// This goes in your project settings.
-
-/**
- * @def MPACK_STDLIB
- *
- * Enables the use of C stdlib. This allows the library to use malloc
- * for debugging and in allocation helpers.
- */
-#ifndef MPACK_STDLIB
-#define MPACK_STDLIB 1
-#endif
-
-/**
- * @def MPACK_STDIO
- *
- * Enables the use of C stdio. This adds helpers for easily
- * reading/writing C files and makes debugging easier.
- */
-#ifndef MPACK_STDIO
-#define MPACK_STDIO 1
-#endif
-
-/**
- * @}
- */
-
-
-/**
- * @name System Functions
- * @{
- */
-
-/**
- * @def MPACK_MALLOC
- *
- * Defines the memory allocation function used by MPack. This is used by
- * helpers for automatically allocating data the correct size, and for
- * debugging functions. If this macro is undefined, the allocation helpers
- * will not be compiled.
- *
- * The default is @c malloc() if @ref MPACK_STDLIB is enabled.
- */
-/**
- * @def MPACK_FREE
- *
- * Defines the memory free function used by MPack. This is used by helpers
- * for automatically allocating data the correct size. If this macro is
- * undefined, the allocation helpers will not be compiled.
- *
- * The default is @c free() if @ref MPACK_MALLOC has not been customized and
- * @ref MPACK_STDLIB is enabled.
- */
-/**
- * @def MPACK_REALLOC
- *
- * Defines the realloc function used by MPack. It is used by growable
- * buffers to resize more efficiently.
- *
- * The default is @c realloc() if @ref MPACK_MALLOC has not been customized and
- * @ref MPACK_STDLIB is enabled.
- *
- * This is optional, even when @ref MPACK_MALLOC is used. If @ref MPACK_MALLOC is
- * set and @ref MPACK_REALLOC is not, @ref MPACK_MALLOC is used with a simple copy
- * to grow buffers.
- */
-#if defined(MPACK_STDLIB) && MPACK_STDLIB && !defined(MPACK_MALLOC)
-#define MPACK_MALLOC malloc
-#define MPACK_REALLOC realloc
-#define MPACK_FREE free
-#endif
-
-/**
- * @}
- */
-
-
-/**
- * @name Debugging Options
- */
-
-/**
- * @def MPACK_DEBUG
- *
- * Enables debug features. You may want to wrap this around your
- * own debug preprocs. By default, this is enabled if @c DEBUG or @c _DEBUG
- * are defined. (@c NDEBUG is not used since it is allowed to have
- * different values in different translation units.)
- */
-#if !defined(MPACK_DEBUG) && (defined(DEBUG) || defined(_DEBUG))
-#define MPACK_DEBUG 1
-#endif
-
-/**
- * @def MPACK_STRINGS
- *
- * Enables descriptive error and type strings.
- *
- * This can be turned off (by defining it to 0) to maximize space savings
- * on embedded devices. If this is disabled, string functions such as
- * mpack_error_to_string() and mpack_type_to_string() return an empty string.
- */
-#ifndef MPACK_STRINGS
-#define MPACK_STRINGS 1
-#endif
-
-/**
- * Set this to 1 to implement a custom @ref mpack_assert_fail() function.
- * See the documentation on @ref mpack_assert_fail() for details.
- *
- * Asserts are only used when @ref MPACK_DEBUG is enabled, and can be
- * triggered by bugs in MPack or bugs due to incorrect usage of MPack.
- */
-#ifndef MPACK_CUSTOM_ASSERT
-#define MPACK_CUSTOM_ASSERT 0
-#endif
-
-/**
- * @def MPACK_READ_TRACKING
- *
- * Enables compound type size tracking for readers. This ensures that the
- * correct number of elements or bytes are read from a compound type.
- *
- * This is enabled by default in debug builds (provided a @c malloc() is
- * available.)
- */
-#if !defined(MPACK_READ_TRACKING) && \
-        defined(MPACK_DEBUG) && MPACK_DEBUG && \
-        defined(MPACK_READER) && MPACK_READER && \
-        defined(MPACK_MALLOC)
-#define MPACK_READ_TRACKING 1
-#endif
-
-/**
- * @def MPACK_WRITE_TRACKING
- *
- * Enables compound type size tracking for writers. This ensures that the
- * correct number of elements or bytes are written in a compound type.
- *
- * Note that without write tracking enabled, it is possible for buggy code
- * to emit invalid MessagePack without flagging an error by writing the wrong
- * number of elements or bytes in a compound type. With tracking enabled,
- * MPack will catch such errors and break on the offending line of code.
- *
- * This is enabled by default in debug builds (provided a @c malloc() is
- * available.)
- */
-#if !defined(MPACK_WRITE_TRACKING) && \
-        defined(MPACK_DEBUG) && MPACK_DEBUG && \
-        defined(MPACK_WRITER) && MPACK_WRITER && \
-        defined(MPACK_MALLOC)
-#define MPACK_WRITE_TRACKING 1
-#endif
-
-/**
- * @}
- */
-
-
-/**
- * @name Miscellaneous Options
- * @{
- */
-
-/**
- * Whether to optimize for size or speed.
- *
- * Optimizing for size simplifies some parsing and encoding algorithms
- * at the expense of speed, and saves a few kilobytes of space in the
- * resulting executable.
- *
- * This automatically detects -Os with GCC/Clang. Unfortunately there
- * doesn't seem to be a macro defined for /Os under MSVC.
- */
-#ifndef MPACK_OPTIMIZE_FOR_SIZE
-#ifdef __OPTIMIZE_SIZE__
-#define MPACK_OPTIMIZE_FOR_SIZE 1
-#else
-#define MPACK_OPTIMIZE_FOR_SIZE 0
-#endif
-#endif
-
-/**
- * Stack space in bytes to use when initializing a reader or writer
- * with a stack-allocated buffer.
- */
-#ifndef MPACK_STACK_SIZE
-#define MPACK_STACK_SIZE 4096
-#endif
-
-/**
- * Buffer size to use for allocated buffers (such as for a file writer.)
- *
- * Starting with a single page and growing as needed seems to
- * provide the best performance with minimal memory waste.
- * Increasing this does not improve performance even when writing
- * huge messages.
- */
-#ifndef MPACK_BUFFER_SIZE
-#define MPACK_BUFFER_SIZE 4096
-#endif
-
-/**
- * Minimum size of an allocated node page in bytes.
- *
- * The children for a given compound element must be contiguous, so
- * larger pages than this may be allocated as needed. (Safety checks
- * exist to prevent malicious data from causing too large allocations.)
- *
- * See @ref mpack_node_data_t for the size of nodes.
- *
- * Using as many nodes fit in one memory page seems to provide the
- * best performance, and has very little waste when parsing small
- * messages.
- */
-#ifndef MPACK_NODE_PAGE_SIZE
-#define MPACK_NODE_PAGE_SIZE 4096
-#endif
-
-/**
- * The initial depth for the node parser. When MPACK_MALLOC is available,
- * the node parser has no practical depth limit, and it is not recursive
- * so there is no risk of overflowing the call stack.
- */
-#ifndef MPACK_NODE_INITIAL_DEPTH
-#define MPACK_NODE_INITIAL_DEPTH 8
-#endif
-
-/**
- * The maximum depth for the node parser if @ref MPACK_MALLOC is not available.
- */
-#ifndef MPACK_NODE_MAX_DEPTH_WITHOUT_MALLOC
-#define MPACK_NODE_MAX_DEPTH_WITHOUT_MALLOC 32
-#endif
-
-/**
- * @}
- */
-
-
-/**
- * @}
- */
-
-
-/* mpack/mpack-platform.h.h */
-
-/**
- * @file
- *
- * Abstracts all platform-specific code from MPack. This contains
- * implementations of standard C functions when libc is not available,
- * as well as wrappers to library functions.
- */
-
-#ifndef MPACK_PLATFORM_H
-#define MPACK_PLATFORM_H 1
-
-
-
-/* Pre-include checks */
-
-#if defined(_MSC_VER) && _MSC_VER < 1800 && !defined(__cplusplus)
-#error "In Visual Studio 2012 and earlier, MPack must be compiled as C++. Enable the /Tp compiler flag."
-#endif
-
-#if defined(WIN32) && defined(MPACK_INTERNAL) && MPACK_INTERNAL
-#define _CRT_SECURE_NO_WARNINGS 1
-#endif
-
-
-
-/* Doxygen preprocs */
-#if defined(MPACK_DOXYGEN) && MPACK_DOXYGEN
-#define MPACK_HAS_CONFIG 0
-// We give these their default values of 0 here even though they are defined to
-// 1 in the doxyfile. Doxygen will show this as the value in the docs, even
-// though it ignores it when parsing the rest of the source. This is what we
-// want, since we want the documentation to show these defaults but still
-// generate documentation for the functions they add when they're on.
-#define MPACK_COMPATIBILITY 0
-#define MPACK_EXTENSIONS 0
-#endif
-
-
-
-/* Include the custom config file if enabled */
-
-#if defined(MPACK_HAS_CONFIG) && MPACK_HAS_CONFIG
-/* #include "mpack-config.h" */
-#endif
-
-/*
- * Now that the optional config is included, we define the defaults
- * for any of the configuration options and other switches that aren't
- * yet defined.
- */
-#if defined(MPACK_DOXYGEN) && MPACK_DOXYGEN
-/* #include "mpack-defaults-doxygen.h" */
-#else
-/* #include "mpack-defaults.h" */
-#endif
-
-/*
- * All remaining configuration options that have not yet been set must
- * be defined here in order to support -Wundef.
- */
-#ifndef MPACK_DEBUG
-#define MPACK_DEBUG 0
-#endif
-#ifndef MPACK_CUSTOM_BREAK
-#define MPACK_CUSTOM_BREAK 0
-#endif
-#ifndef MPACK_READ_TRACKING
-#define MPACK_READ_TRACKING 0
-#endif
-#ifndef MPACK_WRITE_TRACKING
-#define MPACK_WRITE_TRACKING 0
-#endif
-#ifndef MPACK_EMIT_INLINE_DEFS
-#define MPACK_EMIT_INLINE_DEFS 0
-#endif
-#ifndef MPACK_AMALGAMATED
-#define MPACK_AMALGAMATED 0
-#endif
-#ifndef MPACK_RELEASE_VERSION
-#define MPACK_RELEASE_VERSION 0
-#endif
-#ifndef MPACK_INTERNAL
-#define MPACK_INTERNAL 0
-#endif
-#ifndef MPACK_NO_BUILTINS
-#define MPACK_NO_BUILTINS 0
-#endif
-
-
-
-/* System headers (based on configuration) */
-
-#ifndef __STDC_LIMIT_MACROS
-#define __STDC_LIMIT_MACROS 1
-#endif
-#ifndef __STDC_FORMAT_MACROS
-#define __STDC_FORMAT_MACROS 1
-#endif
-#ifndef __STDC_CONSTANT_MACROS
-#define __STDC_CONSTANT_MACROS 1
-#endif
-
-#include <stddef.h>
-#include <stdint.h>
-#include <stdbool.h>
-#include <inttypes.h>
-#include <limits.h>
-
-#if MPACK_STDLIB
-#include <string.h>
-#include <stdlib.h>
-#endif
-
-#if MPACK_STDIO
-#include <stdio.h>
-#include <errno.h>
-#endif
-
-
-
-/*
- * Header configuration
- */
-
-#ifdef __cplusplus
-    #define MPACK_EXTERN_C_START extern "C" {
-    #define MPACK_EXTERN_C_END   }
-#else
-    #define MPACK_EXTERN_C_START /* nothing */
-    #define MPACK_EXTERN_C_END   /* nothing */
-#endif
-
-/* GCC versions from 4.6 to before 5.1 warn about defining a C99
- * non-static inline function before declaring it (see issue #20) */
-#ifdef __GNUC__
-    #if (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
-        #ifdef __cplusplus
-            #define MPACK_DECLARED_INLINE_WARNING_START \
-                _Pragma ("GCC diagnostic push") \
-                _Pragma ("GCC diagnostic ignored \"-Wmissing-declarations\"")
-        #else
-            #define MPACK_DECLARED_INLINE_WARNING_START \
-                _Pragma ("GCC diagnostic push") \
-                _Pragma ("GCC diagnostic ignored \"-Wmissing-prototypes\"")
-        #endif
-        #define MPACK_DECLARED_INLINE_WARNING_END \
-            _Pragma ("GCC diagnostic pop")
-    #endif
-#endif
-#ifndef MPACK_DECLARED_INLINE_WARNING_START
-    #define MPACK_DECLARED_INLINE_WARNING_START /* nothing */
-    #define MPACK_DECLARED_INLINE_WARNING_END /* nothing */
-#endif
-
-/* GCC versions before 4.8 warn about shadowing a function with a
- * variable that isn't a function or function pointer (like "index") */
-#ifdef __GNUC__
-    #if (__GNUC__ < 4) || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
-        #define MPACK_WSHADOW_WARNING_START \
-            _Pragma ("GCC diagnostic push") \
-            _Pragma ("GCC diagnostic ignored \"-Wshadow\"")
-        #define MPACK_WSHADOW_WARNING_END \
-            _Pragma ("GCC diagnostic pop")
-    #endif
-#endif
-#ifndef MPACK_WSHADOW_WARNING_START
-    #define MPACK_WSHADOW_WARNING_START /* nothing */
-    #define MPACK_WSHADOW_WARNING_END /* nothing */
-#endif
-
-#define MPACK_HEADER_START \
-    MPACK_EXTERN_C_START \
-    MPACK_WSHADOW_WARNING_START \
-    MPACK_DECLARED_INLINE_WARNING_START
-
-#define MPACK_HEADER_END \
-    MPACK_DECLARED_INLINE_WARNING_END \
-    MPACK_WSHADOW_WARNING_END \
-    MPACK_EXTERN_C_END
-
-MPACK_HEADER_START
-
-
-
-/* Miscellaneous helper macros */
-
-#define MPACK_UNUSED(var) ((void)(var))
-
-#define MPACK_STRINGIFY_IMPL(arg) #arg
-#define MPACK_STRINGIFY(arg) MPACK_STRINGIFY_IMPL(arg)
-
-// This is a workaround for MSVC's incorrect expansion of __VA_ARGS__. It
-// treats __VA_ARGS__ as a single preprocessor token when passed in the
-// argument list of another macro unless we use an outer wrapper to expand it
-// lexically first. (For safety/consistency we use this in all variadic macros
-// that don't ignore the variadic arguments regardless of whether __VA_ARGS__
-// is passed to another macro.)
-//     https://stackoverflow.com/a/32400131
-#define MPACK_EXPAND(x) x
-
-// Extracts the first argument of a variadic macro list, where there might only
-// be one argument.
-#define MPACK_EXTRACT_ARG0_IMPL(first, ...) first
-#define MPACK_EXTRACT_ARG0(...) MPACK_EXPAND(MPACK_EXTRACT_ARG0_IMPL( __VA_ARGS__ , ignored))
-
-// Stringifies the first argument of a variadic macro list, where there might
-// only be one argument.
-#define MPACK_STRINGIFY_ARG0_impl(first, ...) #first
-#define MPACK_STRINGIFY_ARG0(...) MPACK_EXPAND(MPACK_STRINGIFY_ARG0_impl( __VA_ARGS__ , ignored))
-
-
-
-/*
- * Definition of inline macros.
- *
- * MPack does not use static inline in header files; only one non-inline definition
- * of each function should exist in the final build. This can reduce the binary size
- * in cases where the compiler cannot or chooses not to inline a function.
- * The addresses of functions should also compare equal across translation units
- * regardless of whether they are declared inline.
- *
- * The above requirements mean that the declaration and definition of non-trivial
- * inline functions must be separated so that the definitions will only
- * appear when necessary. In addition, three different linkage models need
- * to be supported:
- *
- *  - The C99 model, where a standalone function is emitted only if there is any
- *    `extern inline` or non-`inline` declaration (including the definition itself)
- *
- *  - The GNU model, where an `inline` definition emits a standalone function and an
- *    `extern inline` definition does not, regardless of other declarations
- *
- *  - The C++ model, where `inline` emits a standalone function with special
- *    (COMDAT) linkage
- *
- * The macros below wrap up everything above. All inline functions defined in header
- * files have a single non-inline definition emitted in the compilation of
- * mpack-platform.c. All inline declarations and definitions use the same MPACK_INLINE
- * specification to simplify the rules on when standalone functions are emitted.
- * Inline functions in source files are defined MPACK_STATIC_INLINE.
- *
- * Additional reading:
- *     http://www.greenend.org.uk/rjk/tech/inline.html
- */
-
-#if defined(__cplusplus)
-    // C++ rules
-    // The linker will need COMDAT support to link C++ object files,
-    // so we don't need to worry about emitting definitions from C++
-    // translation units. If mpack-platform.c (or the amalgamation)
-    // is compiled as C, its definition will be used, otherwise a
-    // C++ definition will be used, and no other C files will emit
-    // a defition.
-    #define MPACK_INLINE inline
-
-#elif defined(_MSC_VER)
-    // MSVC 2013 always uses COMDAT linkage, but it doesn't treat 'inline' as a
-    // keyword in C99 mode. (This appears to be fixed in a later version of
-    // MSVC but we don't bother detecting it.)
-    #define MPACK_INLINE __inline
-    #define MPACK_STATIC_INLINE static __inline
-
-#elif defined(__GNUC__) && (defined(__GNUC_GNU_INLINE__) || \
-        !defined(__GNUC_STDC_INLINE__) && !defined(__GNUC_GNU_INLINE__))
-    // GNU rules
-    #if MPACK_EMIT_INLINE_DEFS
-        #define MPACK_INLINE inline
-    #else
-        #define MPACK_INLINE extern inline
-    #endif
-
-#else
-    // C99 rules
-    #if MPACK_EMIT_INLINE_DEFS
-        #define MPACK_INLINE extern inline
-    #else
-        #define MPACK_INLINE inline
-    #endif
-#endif
-
-#ifndef MPACK_STATIC_INLINE
-#define MPACK_STATIC_INLINE static inline
-#endif
-
-#ifdef MPACK_OPTIMIZE_FOR_SPEED
-    #error "You should define MPACK_OPTIMIZE_FOR_SIZE, not MPACK_OPTIMIZE_FOR_SPEED."
-#endif
-
-
-
-/*
- * Prevent inlining
- *
- * When a function is only used once, it is almost always inlined
- * automatically. This can cause poor instruction cache usage because a
- * function that should rarely be called (such as buffer exhaustion handling)
- * will get inlined into the middle of a hot code path.
- */
-
-#if !MPACK_NO_BUILTINS
-    #if defined(_MSC_VER)
-        #define MPACK_NOINLINE __declspec(noinline)
-    #elif defined(__GNUC__) || defined(__clang__)
-        #define MPACK_NOINLINE __attribute__((noinline))
-    #endif
-#endif
-#ifndef MPACK_NOINLINE
-    #define MPACK_NOINLINE /* nothing */
-#endif
-
-
-
-/* Some compiler-specific keywords and builtins */
-
-#if !MPACK_NO_BUILTINS
-    #if defined(__GNUC__) || defined(__clang__)
-        #define MPACK_UNREACHABLE __builtin_unreachable()
-        #define MPACK_NORETURN(fn) fn __attribute__((noreturn))
-        #define MPACK_RESTRICT __restrict__
-    #elif defined(_MSC_VER)
-        #define MPACK_UNREACHABLE __assume(0)
-        #define MPACK_NORETURN(fn) __declspec(noreturn) fn
-        #define MPACK_RESTRICT __restrict
-    #endif
-#endif
-
-#ifndef MPACK_RESTRICT
-#ifdef __cplusplus
-#define MPACK_RESTRICT /* nothing, unavailable in C++ */
-#else
-#define MPACK_RESTRICT restrict /* required in C99 */
-#endif
-#endif
-
-#ifndef MPACK_UNREACHABLE
-#define MPACK_UNREACHABLE ((void)0)
-#endif
-#ifndef MPACK_NORETURN
-#define MPACK_NORETURN(fn) fn
-#endif
-
-
-
-/*
- * Likely/unlikely
- *
- * These should only really be used when a branch is taken (or not taken) less
- * than 1/1000th of the time. Buffer flush checks when writing very small
- * elements are a good example.
- */
-
-#if !MPACK_NO_BUILTINS
-    #if defined(__GNUC__) || defined(__clang__)
-        #ifndef MPACK_LIKELY
-            #define MPACK_LIKELY(x) __builtin_expect((x),1)
-        #endif
-        #ifndef MPACK_UNLIKELY
-            #define MPACK_UNLIKELY(x) __builtin_expect((x),0)
-        #endif
-    #endif
-#endif
-
-#ifndef MPACK_LIKELY
-    #define MPACK_LIKELY(x) (x)
-#endif
-#ifndef MPACK_UNLIKELY
-    #define MPACK_UNLIKELY(x) (x)
-#endif
-
-
-
-/* Static assert */
-
-#ifndef MPACK_STATIC_ASSERT
-    #if defined(__cplusplus)
-        #if __cplusplus >= 201103L
-            #define MPACK_STATIC_ASSERT static_assert
-        #endif
-    #elif defined(__STDC_VERSION__)
-        #if __STDC_VERSION__ >= 201112L
-            #define MPACK_STATIC_ASSERT _Static_assert
-        #endif
-    #endif
-#endif
-
-#if !MPACK_NO_BUILTINS
-    #ifndef MPACK_STATIC_ASSERT
-        #if defined(__has_feature)
-            #if __has_feature(cxx_static_assert)
-                #define MPACK_STATIC_ASSERT static_assert
-            #elif __has_feature(c_static_assert)
-                #define MPACK_STATIC_ASSERT _Static_assert
-            #endif
-        #endif
-    #endif
-
-    #ifndef MPACK_STATIC_ASSERT
-        #if defined(__GNUC__)
-            #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)
-                #ifndef __cplusplus
-                    #if __GNUC__ >= 5
-                    #define MPACK_IGNORE_PEDANTIC "GCC diagnostic ignored \"-Wpedantic\""
-                    #else
-                    #define MPACK_IGNORE_PEDANTIC "GCC diagnostic ignored \"-pedantic\""
-                    #endif
-                    #define MPACK_STATIC_ASSERT(expr, str) do { \
-                        _Pragma ("GCC diagnostic push") \
-                        _Pragma (MPACK_IGNORE_PEDANTIC) \
-                        _Pragma ("GCC diagnostic ignored \"-Wc++-compat\"") \
-                        _Static_assert(expr, str); \
-                        _Pragma ("GCC diagnostic pop") \
-                    } while (0)
-                #endif
-            #endif
-        #endif
-    #endif
-
-    #ifndef MPACK_STATIC_ASSERT
-        #ifdef _MSC_VER
-            #if _MSC_VER >= 1600
-                #define MPACK_STATIC_ASSERT static_assert
-            #endif
-        #endif
-    #endif
-#endif
-
-#ifndef MPACK_STATIC_ASSERT
-    #define MPACK_STATIC_ASSERT(expr, str) (MPACK_UNUSED(sizeof(char[1 - 2*!(expr)])))
-#endif
-
-
-
-/* _Generic */
-
-#ifndef MPACK_HAS_GENERIC
-    #if defined(__clang__) && defined(__has_feature)
-        // With Clang we can test for _Generic support directly
-        // and ignore C/C++ version
-        #if __has_feature(c_generic_selections)
-            #define MPACK_HAS_GENERIC 1
-        #else
-            #define MPACK_HAS_GENERIC 0
-        #endif
-    #endif
-#endif
-
-#ifndef MPACK_HAS_GENERIC
-    #if defined(__STDC_VERSION__)
-        #if __STDC_VERSION__ >= 201112L
-            #if defined(__GNUC__) && !defined(__clang__)
-                // GCC does not have full C11 support in GCC 4.7 and 4.8
-                #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)
-                    #define MPACK_HAS_GENERIC 1
-                #endif
-            #else
-                // We hope other compilers aren't lying about C11/_Generic support
-                #define MPACK_HAS_GENERIC 1
-            #endif
-        #endif
-    #endif
-#endif
-
-#ifndef MPACK_HAS_GENERIC
-    #define MPACK_HAS_GENERIC 0
-#endif
-
-
-
-/*
- * Finite Math
- *
- * -ffinite-math-only, included in -ffast-math, breaks functions that
- * that check for non-finite real values such as isnan() and isinf().
- *
- * We should use this to trap errors when reading data that contains
- * non-finite reals. This isn't currently implemented.
- */
-
-#ifndef MPACK_FINITE_MATH
-#if defined(__FINITE_MATH_ONLY__) && __FINITE_MATH_ONLY__
-#define MPACK_FINITE_MATH 1
-#endif
-#endif
-
-#ifndef MPACK_FINITE_MATH
-#define MPACK_FINITE_MATH 0
-#endif
-
-
-
-/*
- * Endianness checks
- *
- * These define MPACK_NHSWAP*() which swap network<->host byte
- * order when needed.
- *
- * We leave them undefined if we can't determine the endianness
- * at compile-time, in which case we fall back to bit-shifts.
- *
- * See the notes in mpack-common.h.
- */
-
-#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && defined(__ORDER_BIG_ENDIAN__)
-    #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
-        #define MPACK_NHSWAP16(x) (x)
-        #define MPACK_NHSWAP32(x) (x)
-        #define MPACK_NHSWAP64(x) (x)
-    #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
-
-        #if !MPACK_NO_BUILTINS
-            #if defined(__clang__)
-                #ifdef __has_builtin
-                    // Unlike the GCC builtins, the bswap builtins in Clang
-                    // significantly improve ARM performance.
-                    #if __has_builtin(__builtin_bswap16)
-                        #define MPACK_NHSWAP16(x) __builtin_bswap16(x)
-                    #endif
-                    #if __has_builtin(__builtin_bswap32)
-                        #define MPACK_NHSWAP32(x) __builtin_bswap32(x)
-                    #endif
-                    #if __has_builtin(__builtin_bswap64)
-                        #define MPACK_NHSWAP64(x) __builtin_bswap64(x)
-                    #endif
-                #endif
-
-            #elif defined(__GNUC__)
-
-                // The GCC bswap builtins are apparently poorly optimized on older
-                // versions of GCC, so we set a minimum version here just in case.
-                //     http://hardwarebug.org/2010/01/14/beware-the-builtins/
-
-                #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
-                    #define MPACK_NHSWAP64(x) __builtin_bswap64(x)
-                #endif
-
-                // __builtin_bswap16() was not implemented on all platforms
-                // until GCC 4.8.0:
-                //     https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52624
-                //
-                // The 16- and 32-bit versions in GCC significantly reduce performance
-                // on ARM with little effect on code size so we don't use them.
-
-            #endif
-        #endif
-    #endif
-
-#elif defined(_MSC_VER) && defined(_WIN32) && !MPACK_NO_BUILTINS
-
-    // On Windows, we assume x86 and x86_64 are always little-endian.
-    // We make no assumptions about ARM even though all current
-    // Windows Phone devices are little-endian in case Microsoft's
-    // compiler is ever used with a big-endian ARM device.
-
-    #if defined(_M_IX86) || defined(_M_X64) || defined(_M_AMD64)
-        #define MPACK_NHSWAP16(x) _byteswap_ushort(x)
-        #define MPACK_NHSWAP32(x) _byteswap_ulong(x)
-        #define MPACK_NHSWAP64(x) _byteswap_uint64(x)
-    #endif
-
-#endif
-
-#if defined(__FLOAT_WORD_ORDER__) && defined(__BYTE_ORDER__)
-
-    // We check where possible that the float byte order matches the
-    // integer byte order. This is extremely unlikely to fail, but
-    // we check anyway just in case.
-    //
-    // (The static assert is placed in float/double encoders instead
-    // of here because our static assert fallback doesn't work at
-    // file scope)
-
-    #define MPACK_CHECK_FLOAT_ORDER() \
-        MPACK_STATIC_ASSERT(__FLOAT_WORD_ORDER__ == __BYTE_ORDER__, \
-            "float byte order does not match int byte order! float/double " \
-            "encoding is not properly implemented on this platform.")
-
-#endif
-
-#ifndef MPACK_CHECK_FLOAT_ORDER
-    #define MPACK_CHECK_FLOAT_ORDER() /* nothing */
-#endif
-
-
-/*
- * Here we define mpack_assert() and mpack_break(). They both work like a normal
- * assertion function in debug mode, causing a trap or abort. However, on some platforms
- * you can safely resume execution from mpack_break(), whereas mpack_assert() is
- * always fatal.
- *
- * In release mode, mpack_assert() is converted to an assurance to the compiler
- * that the expression cannot be false (via e.g. __assume() or __builtin_unreachable())
- * to improve optimization where supported. There is thus no point in "safely" handling
- * the case of this being false. Writing mpack_assert(0) rarely makes sense (except
- * possibly as a default handler in a switch) since the compiler will throw away any
- * code after it. If at any time an mpack_assert() is not true, the behaviour is
- * undefined. This also means the expression is evaluated even in release.
- *
- * mpack_break() on the other hand is compiled to nothing in release. It is
- * used in situations where we want to highlight a programming error as early as
- * possible (in the debugger), but we still handle the situation safely if it
- * happens in release to avoid producing incorrect results (such as in
- * MPACK_WRITE_TRACKING.) It does not take an expression to test because it
- * belongs in a safe-handling block after its failing condition has been tested.
- *
- * If stdio is available, we can add a format string describing the error, and
- * on some compilers we can declare it noreturn to get correct results from static
- * analysis tools. Note that the format string and arguments are not evaluated unless
- * the assertion is hit.
- *
- * Note that any arguments to mpack_assert() beyond the first are only evaluated
- * if the expression is false (and are never evaluated in release.)
- *
- * mpack_assert_fail() and mpack_break_hit() are defined separately
- * because assert is noreturn and break isn't. This distinction is very
- * important for static analysis tools to give correct results.
- */
-
-#if MPACK_DEBUG
-
-    /**
-     * @addtogroup config
-     * @{
-     */
-    /**
-     * @name Debug Functions
-     */
-    /**
-     * Implement this and define @ref MPACK_CUSTOM_ASSERT to use a custom
-     * assertion function.
-     *
-     * This function should not return. If it does, MPack will @c abort().
-     *
-     * If you use C++, make sure you include @c mpack.h where you define
-     * this to get the correct linkage (or define it <code>extern "C"</code>.)
-     *
-     * Asserts are only used when @ref MPACK_DEBUG is enabled, and can be
-     * triggered by bugs in MPack or bugs due to incorrect usage of MPack.
-     */
-    void mpack_assert_fail(const char* message);
-    /**
-     * @}
-     */
-    /**
-     * @}
-     */
-
-    MPACK_NORETURN(void mpack_assert_fail_wrapper(const char* message));
-    #if MPACK_STDIO
-        MPACK_NORETURN(void mpack_assert_fail_format(const char* format, ...));
-        #define mpack_assert_fail_at(line, file, exprstr, format, ...) \
-                MPACK_EXPAND(mpack_assert_fail_format("mpack assertion failed at " file ":" #line "\n%s\n" format, exprstr, __VA_ARGS__))
-    #else
-        #define mpack_assert_fail_at(line, file, exprstr, format, ...) \
-                mpack_assert_fail_wrapper("mpack assertion failed at " file ":" #line "\n" exprstr "\n")
-    #endif
-
-    #define mpack_assert_fail_pos(line, file, exprstr, expr, ...) \
-            MPACK_EXPAND(mpack_assert_fail_at(line, file, exprstr, __VA_ARGS__))
-
-    // This contains a workaround to the pedantic C99 requirement of having at
-    // least one argument to a variadic macro. The first argument is the
-    // boolean expression, the optional second argument (if provided) must be a
-    // literal format string, and any additional arguments are the format
-    // argument list.
-    //
-    // Unfortunately this means macros are expanded in the expression before it
-    // gets stringified. I haven't found a workaround to this.
-    //
-    // This adds two unused arguments to the format argument list when a
-    // format string is provided, so this would complicate the use of
-    // -Wformat and __attribute__((format)) on mpack_assert_fail_format() if we
-    // ever bothered to implement it.
-    #define mpack_assert(...) \
-            MPACK_EXPAND(((!(MPACK_EXTRACT_ARG0(__VA_ARGS__))) ? \
-                mpack_assert_fail_pos(__LINE__, __FILE__, MPACK_STRINGIFY_ARG0(__VA_ARGS__) , __VA_ARGS__ , "", NULL) : \
-                (void)0))
-
-    void mpack_break_hit(const char* message);
-    #if MPACK_STDIO
-        void mpack_break_hit_format(const char* format, ...);
-        #define mpack_break_hit_at(line, file, ...) \
-                MPACK_EXPAND(mpack_break_hit_format("mpack breakpoint hit at " file ":" #line "\n" __VA_ARGS__))
-    #else
-        #define mpack_break_hit_at(line, file, ...) \
-                mpack_break_hit("mpack breakpoint hit at " file ":" #line )
-    #endif
-    #define mpack_break_hit_pos(line, file, ...) MPACK_EXPAND(mpack_break_hit_at(line, file, __VA_ARGS__))
-    #define mpack_break(...) MPACK_EXPAND(mpack_break_hit_pos(__LINE__, __FILE__, __VA_ARGS__))
-#else
-    #define mpack_assert(...) \
-            (MPACK_EXPAND((!(MPACK_EXTRACT_ARG0(__VA_ARGS__))) ? \
-                (MPACK_UNREACHABLE, (void)0) : \
-                (void)0))
-    #define mpack_break(...) ((void)0)
-#endif
-
-
-
-/* Wrap some needed libc functions */
-
-#if MPACK_STDLIB
-    #define mpack_memcmp memcmp
-    #define mpack_memcpy memcpy
-    #define mpack_memmove memmove
-    #define mpack_memset memset
-    #ifndef mpack_strlen
-        #define mpack_strlen strlen
-    #endif
-
-    #if defined(MPACK_UNIT_TESTS) && MPACK_INTERNAL && defined(__GNUC__)
-        // make sure we don't use the stdlib directly during development
-        #undef memcmp
-        #undef memcpy
-        #undef memmove
-        #undef memset
-        #undef strlen
-        #undef malloc
-        #undef free
-        #pragma GCC poison memcmp
-        #pragma GCC poison memcpy
-        #pragma GCC poison memmove
-        #pragma GCC poison memset
-        #pragma GCC poison strlen
-        #pragma GCC poison malloc
-        #pragma GCC poison free
-    #endif
-
-#elif defined(__GNUC__) && !MPACK_NO_BUILTINS
-    // there's not always a builtin memmove for GCC,
-    // and we don't have a way to test for it
-    #define mpack_memcmp __builtin_memcmp
-    #define mpack_memcpy __builtin_memcpy
-    #define mpack_memset __builtin_memset
-    #define mpack_strlen __builtin_strlen
-
-#elif defined(__clang__) && defined(__has_builtin) && !MPACK_NO_BUILTINS
-    #if __has_builtin(__builtin_memcmp)
-    #define mpack_memcmp __builtin_memcmp
-    #endif
-    #if __has_builtin(__builtin_memcpy)
-    #define mpack_memcpy __builtin_memcpy
-    #endif
-    #if __has_builtin(__builtin_memmove)
-    #define mpack_memmove __builtin_memmove
-    #endif
-    #if __has_builtin(__builtin_memset)
-    #define mpack_memset __builtin_memset
-    #endif
-    #if __has_builtin(__builtin_strlen)
-    #define mpack_strlen __builtin_strlen
-    #endif
-#endif
-
-#ifndef mpack_memcmp
-int mpack_memcmp(const void* s1, const void* s2, size_t n);
-#endif
-#ifndef mpack_memcpy
-void* mpack_memcpy(void* MPACK_RESTRICT s1, const void* MPACK_RESTRICT s2, size_t n);
-#endif
-#ifndef mpack_memmove
-void* mpack_memmove(void* s1, const void* s2, size_t n);
-#endif
-#ifndef mpack_memset
-void* mpack_memset(void* s, int c, size_t n);
-#endif
-#ifndef mpack_strlen
-size_t mpack_strlen(const char* s);
-#endif
-
-#if MPACK_STDIO
-    #if defined(WIN32)
-        #define mpack_snprintf _snprintf
-    #else
-        #define mpack_snprintf snprintf
-    #endif
-#endif
-
-
-
-/* Debug logging */
-#if 0
-    #include <stdio.h>
-    #define mpack_log(...) (MPACK_EXPAND(printf(__VA_ARGS__), fflush(stdout)))
-#else
-    #define mpack_log(...) ((void)0)
-#endif
-
-
-
-/* Make sure our configuration makes sense */
-#if defined(MPACK_MALLOC) && !defined(MPACK_FREE)
-    #error "MPACK_MALLOC requires MPACK_FREE."
-#endif
-#if !defined(MPACK_MALLOC) && defined(MPACK_FREE)
-    #error "MPACK_FREE requires MPACK_MALLOC."
-#endif
-#if MPACK_READ_TRACKING && !defined(MPACK_READER)
-    #error "MPACK_READ_TRACKING requires MPACK_READER."
-#endif
-#if MPACK_WRITE_TRACKING && !defined(MPACK_WRITER)
-    #error "MPACK_WRITE_TRACKING requires MPACK_WRITER."
-#endif
-#ifndef MPACK_MALLOC
-    #if MPACK_STDIO
-        #error "MPACK_STDIO requires preprocessor definitions for MPACK_MALLOC and MPACK_FREE."
-    #endif
-    #if MPACK_READ_TRACKING
-        #error "MPACK_READ_TRACKING requires preprocessor definitions for MPACK_MALLOC and MPACK_FREE."
-    #endif
-    #if MPACK_WRITE_TRACKING
-        #error "MPACK_WRITE_TRACKING requires preprocessor definitions for MPACK_MALLOC and MPACK_FREE."
-    #endif
-#endif
-
-
-
-/* Implement realloc if unavailable */
-#ifdef MPACK_MALLOC
-    #ifdef MPACK_REALLOC
-        MPACK_INLINE void* mpack_realloc(void* old_ptr, size_t used_size, size_t new_size) {
-            MPACK_UNUSED(used_size);
-            return MPACK_REALLOC(old_ptr, new_size);
-        }
-    #else
-        void* mpack_realloc(void* old_ptr, size_t used_size, size_t new_size);
-    #endif
-#endif
-
-
-
-/**
- * @}
- */
-
-MPACK_HEADER_END
-
-#endif
-
-
-/* mpack/mpack-common.h.h */
-
-/**
- * @file
- *
- * Defines types and functions shared by the MPack reader and writer.
- */
-
-#ifndef MPACK_COMMON_H
-#define MPACK_COMMON_H 1
-
-/* #include "mpack-platform.h" */
-
-#ifndef MPACK_PRINT_BYTE_COUNT
-#define MPACK_PRINT_BYTE_COUNT 12
-#endif
-
-MPACK_HEADER_START
-
-
-
-/**
- * @defgroup common Tags and Common Elements
- *
- * Contains types, constants and functions shared by both the encoding
- * and decoding portions of MPack.
- *
- * @{
- */
-
-/* Version information */
-
-#define MPACK_VERSION_MAJOR 1  /**< The major version number of MPack. */
-#define MPACK_VERSION_MINOR 0  /**< The minor version number of MPack. */
-#define MPACK_VERSION_PATCH 0  /**< The patch version number of MPack. */
-
-/** A number containing the version number of MPack for comparison purposes. */
-#define MPACK_VERSION ((MPACK_VERSION_MAJOR * 10000) + \
-        (MPACK_VERSION_MINOR * 100) + MPACK_VERSION_PATCH)
-
-/** A macro to test for a minimum version of MPack. */
-#define MPACK_VERSION_AT_LEAST(major, minor, patch) \
-        (MPACK_VERSION >= (((major) * 10000) + ((minor) * 100) + (patch)))
-
-/** @cond */
-#if (MPACK_VERSION_PATCH > 0)
-#define MPACK_VERSION_STRING_BASE \
-        MPACK_STRINGIFY(MPACK_VERSION_MAJOR) "." \
-        MPACK_STRINGIFY(MPACK_VERSION_MINOR) "." \
-        MPACK_STRINGIFY(MPACK_VERSION_PATCH)
-#else
-#define MPACK_VERSION_STRING_BASE \
-        MPACK_STRINGIFY(MPACK_VERSION_MAJOR) "." \
-        MPACK_STRINGIFY(MPACK_VERSION_MINOR)
-#endif
-/** @endcond */
-
-/**
- * @def MPACK_VERSION_STRING
- * @hideinitializer
- *
- * A string containing the MPack version.
- */
-#if MPACK_RELEASE_VERSION
-#define MPACK_VERSION_STRING MPACK_VERSION_STRING_BASE
-#else
-#define MPACK_VERSION_STRING MPACK_VERSION_STRING_BASE "dev"
-#endif
-
-/**
- * @def MPACK_LIBRARY_STRING
- * @hideinitializer
- *
- * A string describing MPack, containing the library name, version and debug mode.
- */
-#if MPACK_DEBUG
-#define MPACK_LIBRARY_STRING "MPack " MPACK_VERSION_STRING "-debug"
-#else
-#define MPACK_LIBRARY_STRING "MPack " MPACK_VERSION_STRING
-#endif
-
-/** @cond */
-/**
- * @def MPACK_MAXIMUM_TAG_SIZE
- *
- * The maximum encoded size of a tag in bytes.
- */
-#define MPACK_MAXIMUM_TAG_SIZE 9
-/** @endcond */
-
-#if MPACK_EXTENSIONS
-/**
- * @def MPACK_TIMESTAMP_NANOSECONDS_MAX
- *
- * The maximum value of nanoseconds for a timestamp.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-#define MPACK_TIMESTAMP_NANOSECONDS_MAX 999999999
-#endif
-
-
-
-#if MPACK_COMPATIBILITY
-/**
- * Versions of the MessagePack format.
- *
- * A reader, writer, or tree can be configured to serialize in an older
- * version of the MessagePack spec. This is necessary to interface with
- * older MessagePack libraries that do not support new MessagePack features.
- *
- * @note This requires @ref MPACK_COMPATIBILITY.
- */
-typedef enum mpack_version_t {
-
-    /**
-     * Version 1.0/v4, supporting only the @c raw type without @c str8.
-     */
-    mpack_version_v4 = 4,
-
-    /**
-     * Version 2.0/v5, supporting the @c str8, @c bin and @c ext types.
-     */
-    mpack_version_v5 = 5,
-
-    /**
-     * The most recent supported version of MessagePack. This is the default.
-     */
-    mpack_version_current = mpack_version_v5,
-
-} mpack_version_t;
-#endif
-
-/**
- * Error states for MPack objects.
- *
- * When a reader, writer, or tree is in an error state, all subsequent calls
- * are ignored and their return values are nil/zero. You should check whether
- * the source is in an error state before using such values.
- */
-typedef enum mpack_error_t {
-    mpack_ok = 0,        /**< No error. */
-    mpack_error_io = 2,  /**< The reader or writer failed to fill or flush, or some other file or socket error occurred. */
-    mpack_error_invalid, /**< The data read is not valid MessagePack. */
-    mpack_error_unsupported, /**< The data read is not supported by this configuration of MPack. (See @ref MPACK_EXTENSIONS.) */
-    mpack_error_type,    /**< The type or value range did not match what was expected by the caller. */
-    mpack_error_too_big, /**< A read or write was bigger than the maximum size allowed for that operation. */
-    mpack_error_memory,  /**< An allocation failure occurred. */
-    mpack_error_bug,     /**< The MPack API was used incorrectly. (This will always assert in debug mode.) */
-    mpack_error_data,    /**< The contained data is not valid. */
-    mpack_error_eof,     /**< The reader failed to read because of file or socket EOF */
-} mpack_error_t;
-
-/**
- * Converts an MPack error to a string. This function returns an empty
- * string when MPACK_DEBUG is not set.
- */
-const char* mpack_error_to_string(mpack_error_t error);
-
-/**
- * Defines the type of a MessagePack tag.
- *
- * Note that extension types, both user defined and built-in, are represented
- * in tags as @ref mpack_type_ext. The value for an extension type is stored
- * separately.
- */
-typedef enum mpack_type_t {
-    mpack_type_missing = 0, /**< Special type indicating a missing optional value. */
-    mpack_type_nil,         /**< A null value. */
-    mpack_type_bool,        /**< A boolean (true or false.) */
-    mpack_type_int,         /**< A 64-bit signed integer. */
-    mpack_type_uint,        /**< A 64-bit unsigned integer. */
-    mpack_type_float,       /**< A 32-bit IEEE 754 floating point number. */
-    mpack_type_double,      /**< A 64-bit IEEE 754 floating point number. */
-    mpack_type_str,         /**< A string. */
-    mpack_type_bin,         /**< A chunk of binary data. */
-    mpack_type_array,       /**< An array of MessagePack objects. */
-    mpack_type_map,         /**< An ordered map of key/value pairs of MessagePack objects. */
-
-    #if MPACK_EXTENSIONS
-    /**
-     * A typed MessagePack extension object containing a chunk of binary data.
-     *
-     * @note This requires @ref MPACK_EXTENSIONS.
-     */
-    mpack_type_ext,
-    #endif
-} mpack_type_t;
-
-/**
- * Converts an MPack type to a string. This function returns an empty
- * string when MPACK_DEBUG is not set.
- */
-const char* mpack_type_to_string(mpack_type_t type);
-
-#if MPACK_EXTENSIONS
-/**
- * A timestamp.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-typedef struct mpack_timestamp_t {
-    int64_t seconds; /*< The number of seconds (signed) since 1970-01-01T00:00:00Z. */
-    uint32_t nanoseconds; /*< The number of additional nanoseconds, between 0 and 999,999,999. */
-} mpack_timestamp_t;
-#endif
-
-/**
- * An MPack tag is a MessagePack object header. It is a variant type
- * representing any kind of object, and includes the length of compound types
- * (e.g. map, array, string) or the value of non-compound types (e.g. boolean,
- * integer, float.)
- *
- * If the type is compound (str, bin, ext, array or map), the contained
- * elements or bytes are stored separately.
- *
- * This structure is opaque; its fields should not be accessed outside
- * of MPack.
- */
-typedef struct mpack_tag_t mpack_tag_t;
-
-/* Hide internals from documentation */
-/** @cond */
-struct mpack_tag_t {
-    mpack_type_t type; /*< The type of value. */
-
-    #if MPACK_EXTENSIONS
-    int8_t exttype; /*< The extension type if the type is @ref mpack_type_ext. */
-    #endif
-
-    /* The value for non-compound types. */
-    union {
-        uint64_t u; /*< The value if the type is unsigned int. */
-        int64_t  i; /*< The value if the type is signed int. */
-        double   d; /*< The value if the type is double. */
-        float    f; /*< The value if the type is float. */
-        bool     b; /*< The value if the type is bool. */
-
-        /* The number of bytes if the type is str, bin or ext. */
-        uint32_t l;
-
-        /* The element count if the type is an array, or the number of
-            key/value pairs if the type is map. */
-        uint32_t n;
-    } v;
-};
-/** @endcond */
-
-/**
- * @name Tag Generators
- * @{
- */
-
-/**
- * @def MPACK_TAG_ZERO
- *
- * An @ref mpack_tag_t initializer that zeroes the given tag.
- *
- * @warning This does not make the tag nil! The tag's type is invalid when
- * initialized this way. Use @ref mpack_tag_make_nil() to generate a nil tag.
- */
-#if MPACK_EXTENSIONS
-#define MPACK_TAG_ZERO {(mpack_type_t)0, 0, {0}}
-#else
-#define MPACK_TAG_ZERO {(mpack_type_t)0, {0}}
-#endif
-
-/** Generates a nil tag. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_nil(void) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_nil;
-    return ret;
-}
-
-/** Generates a bool tag. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_bool(bool value) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_bool;
-    ret.v.b = value;
-    return ret;
-}
-
-/** Generates a bool tag with value true. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_true(void) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_bool;
-    ret.v.b = true;
-    return ret;
-}
-
-/** Generates a bool tag with value false. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_false(void) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_bool;
-    ret.v.b = false;
-    return ret;
-}
-
-/** Generates a signed int tag. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_int(int64_t value) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_int;
-    ret.v.i = value;
-    return ret;
-}
-
-/** Generates an unsigned int tag. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_uint(uint64_t value) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_uint;
-    ret.v.u = value;
-    return ret;
-}
-
-/** Generates a float tag. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_float(float value) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_float;
-    ret.v.f = value;
-    return ret;
-}
-
-/** Generates a double tag. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_double(double value) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_double;
-    ret.v.d = value;
-    return ret;
-}
-
-/** Generates an array tag. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_array(uint32_t count) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_array;
-    ret.v.n = count;
-    return ret;
-}
-
-/** Generates a map tag. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_map(uint32_t count) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_map;
-    ret.v.n = count;
-    return ret;
-}
-
-/** Generates a str tag. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_str(uint32_t length) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_str;
-    ret.v.l = length;
-    return ret;
-}
-
-/** Generates a bin tag. */
-MPACK_INLINE mpack_tag_t mpack_tag_make_bin(uint32_t length) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_bin;
-    ret.v.l = length;
-    return ret;
-}
-
-#if MPACK_EXTENSIONS
-/**
- * Generates an ext tag.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-MPACK_INLINE mpack_tag_t mpack_tag_make_ext(int8_t exttype, uint32_t length) {
-    mpack_tag_t ret = MPACK_TAG_ZERO;
-    ret.type = mpack_type_ext;
-    ret.exttype = exttype;
-    ret.v.l = length;
-    return ret;
-}
-#endif
-
-/**
- * @}
- */
-
-/**
- * @name Tag Querying Functions
- * @{
- */
-
-/**
- * Gets the type of a tag.
- */
-MPACK_INLINE mpack_type_t mpack_tag_type(mpack_tag_t* tag) {
-    return tag->type;
-}
-
-/**
- * Gets the boolean value of a bool-type tag. The tag must be of type @ref
- * mpack_type_bool.
- *
- * This asserts that the type in the tag is @ref mpack_type_bool. (No check is
- * performed if MPACK_DEBUG is not set.)
- */
-MPACK_INLINE bool mpack_tag_bool_value(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_bool, "tag is not a bool!");
-    return tag->v.b;
-}
-
-/**
- * Gets the signed integer value of an int-type tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_int. (No check is
- * performed if MPACK_DEBUG is not set.)
- *
- * @warning This does not convert between signed and unsigned tags! A positive
- * integer may be stored in a tag as either @ref mpack_type_int or @ref
- * mpack_type_uint. You must check the type first; this can only be used if the
- * type is @ref mpack_type_int.
- *
- * @see mpack_type_int
- */
-MPACK_INLINE int64_t mpack_tag_int_value(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_int, "tag is not an int!");
-    return tag->v.i;
-}
-
-/**
- * Gets the unsigned integer value of a uint-type tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_uint. (No check is
- * performed if MPACK_DEBUG is not set.)
- *
- * @warning This does not convert between signed and unsigned tags! A positive
- * integer may be stored in a tag as either @ref mpack_type_int or @ref
- * mpack_type_uint. You must check the type first; this can only be used if the
- * type is @ref mpack_type_uint.
- *
- * @see mpack_type_uint
- */
-MPACK_INLINE uint64_t mpack_tag_uint_value(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_uint, "tag is not a uint!");
-    return tag->v.u;
-}
-
-/**
- * Gets the float value of a float-type tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_float. (No check is
- * performed if MPACK_DEBUG is not set.)
- *
- * @warning This does not convert between float and double tags! This can only
- * be used if the type is @ref mpack_type_float.
- *
- * @see mpack_type_float
- */
-MPACK_INLINE float mpack_tag_float_value(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_float, "tag is not a float!");
-    return tag->v.f;
-}
-
-/**
- * Gets the double value of a double-type tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_double. (No check
- * is performed if MPACK_DEBUG is not set.)
- *
- * @warning This does not convert between float and double tags! This can only
- * be used if the type is @ref mpack_type_double.
- *
- * @see mpack_type_double
- */
-MPACK_INLINE double mpack_tag_double_value(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_double, "tag is not a double!");
-    return tag->v.d;
-}
-
-/**
- * Gets the number of elements in an array tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_array. (No check is
- * performed if MPACK_DEBUG is not set.)
- *
- * @see mpack_type_array
- */
-MPACK_INLINE uint32_t mpack_tag_array_count(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_array, "tag is not an array!");
-    return tag->v.n;
-}
-
-/**
- * Gets the number of key-value pairs in a map tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_map. (No check is
- * performed if MPACK_DEBUG is not set.)
- *
- * @see mpack_type_map
- */
-MPACK_INLINE uint32_t mpack_tag_map_count(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_map, "tag is not a map!");
-    return tag->v.n;
-}
-
-/**
- * Gets the length in bytes of a str-type tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_str. (No check is
- * performed if MPACK_DEBUG is not set.)
- *
- * @see mpack_type_str
- */
-MPACK_INLINE uint32_t mpack_tag_str_length(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_str, "tag is not a str!");
-    return tag->v.l;
-}
-
-/**
- * Gets the length in bytes of a bin-type tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_bin. (No check is
- * performed if MPACK_DEBUG is not set.)
- *
- * @see mpack_type_bin
- */
-MPACK_INLINE uint32_t mpack_tag_bin_length(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_bin, "tag is not a bin!");
-    return tag->v.l;
-}
-
-#if MPACK_EXTENSIONS
-/**
- * Gets the length in bytes of an ext-type tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_ext. (No check is
- * performed if MPACK_DEBUG is not set.)
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @see mpack_type_ext
- */
-MPACK_INLINE uint32_t mpack_tag_ext_length(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_ext, "tag is not an ext!");
-    return tag->v.l;
-}
-
-/**
- * Gets the extension type (exttype) of an ext-type tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_ext. (No check is
- * performed if MPACK_DEBUG is not set.)
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @see mpack_type_ext
- */
-MPACK_INLINE int8_t mpack_tag_ext_exttype(mpack_tag_t* tag) {
-    mpack_assert(tag->type == mpack_type_ext, "tag is not an ext!");
-    return tag->exttype;
-}
-#endif
-
-/**
- * Gets the length in bytes of a str-, bin- or ext-type tag.
- *
- * This asserts that the type in the tag is @ref mpack_type_str, @ref
- * mpack_type_bin or @ref mpack_type_ext. (No check is performed if MPACK_DEBUG
- * is not set.)
- *
- * @see mpack_type_str
- * @see mpack_type_bin
- * @see mpack_type_ext
- */
-MPACK_INLINE uint32_t mpack_tag_bytes(mpack_tag_t* tag) {
-    #if MPACK_EXTENSIONS
-    mpack_assert(tag->type == mpack_type_str || tag->type == mpack_type_bin
-            || tag->type == mpack_type_ext, "tag is not a str, bin or ext!");
-    #else
-    mpack_assert(tag->type == mpack_type_str || tag->type == mpack_type_bin,
-            "tag is not a str or bin!");
-    #endif
-    return tag->v.l;
-}
-
-/**
- * @}
- */
-
-/**
- * @name Other tag functions
- * @{
- */
-
-#if MPACK_EXTENSIONS
-/**
- * The extension type for a timestamp.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-#define MPACK_EXTTYPE_TIMESTAMP ((int8_t)(-1))
-#endif
-
-/**
- * Compares two tags with an arbitrary fixed ordering. Returns 0 if the tags are
- * equal, a negative integer if left comes before right, or a positive integer
- * otherwise.
- *
- * \warning The ordering is not guaranteed to be preserved across MPack versions; do
- * not rely on it in persistent data.
- *
- * \warning Floating point numbers are compared bit-for-bit, not using the language's
- * operator==. This means that NaNs with matching representation will compare equal.
- * This behaviour is up for debate; see comments in the definition of mpack_tag_cmp().
- *
- * See mpack_tag_equal() for more information on when tags are considered equal.
- */
-int mpack_tag_cmp(mpack_tag_t left, mpack_tag_t right);
-
-/**
- * Compares two tags for equality. Tags are considered equal if the types are compatible
- * and the values (for non-compound types) are equal.
- *
- * The field width of variable-width fields is ignored (and in fact is not stored
- * in a tag), and positive numbers in signed integers are considered equal to their
- * unsigned counterparts. So for example the value 1 stored as a positive fixint
- * is equal to the value 1 stored in a 64-bit unsigned integer field.
- *
- * The "extension type" of an extension object is considered part of the value
- * and must match exactly.
- *
- * \warning Floating point numbers are compared bit-for-bit, not using the language's
- * operator==. This means that NaNs with matching representation will compare equal.
- * This behaviour is up for debate; see comments in the definition of mpack_tag_cmp().
- */
-MPACK_INLINE bool mpack_tag_equal(mpack_tag_t left, mpack_tag_t right) {
-    return mpack_tag_cmp(left, right) == 0;
-}
-
-#if MPACK_DEBUG && MPACK_STDIO
-/**
- * Generates a json-like debug description of the given tag into the given buffer.
- *
- * This is only available in debug mode, and only if stdio is available (since
- * it uses snprintf().) It's strictly for debugging purposes.
- *
- * The prefix is used to print the first few hexadecimal bytes of a bin or ext
- * type. Pass NULL if not a bin or ext.
- */
-void mpack_tag_debug_pseudo_json(mpack_tag_t tag, char* buffer, size_t buffer_size,
-        const char* prefix, size_t prefix_size);
-
-/**
- * Generates a debug string description of the given tag into the given buffer.
- *
- * This is only available in debug mode, and only if stdio is available (since
- * it uses snprintf().) It's strictly for debugging purposes.
- */
-void mpack_tag_debug_describe(mpack_tag_t tag, char* buffer, size_t buffer_size);
-
-/** @cond */
-
-/*
- * A callback function for printing pseudo-JSON for debugging purposes.
- *
- * @see mpack_node_print_callback
- */
-typedef void (*mpack_print_callback_t)(void* context, const char* data, size_t count);
-
-// helpers for printing debug output
-// i feel a bit like i'm re-implementing a buffered writer again...
-typedef struct mpack_print_t {
-    char* buffer;
-    size_t size;
-    size_t count;
-    mpack_print_callback_t callback;
-    void* context;
-} mpack_print_t;
-
-void mpack_print_append(mpack_print_t* print, const char* data, size_t count);
-
-MPACK_INLINE void mpack_print_append_cstr(mpack_print_t* print, const char* cstr) {
-    mpack_print_append(print, cstr, mpack_strlen(cstr));
-}
-
-void mpack_print_flush(mpack_print_t* print);
-
-void mpack_print_file_callback(void* context, const char* data, size_t count);
-
-/** @endcond */
-
-#endif
-
-/**
- * @}
- */
-
-/**
- * @name Deprecated Tag Generators
- * @{
- */
-
-/*
- * "make" has been added to their names to disambiguate them from the
- * value-fetching functions (e.g. mpack_tag_make_bool() vs
- * mpack_tag_bool_value().)
- *
- * The length and count for all compound types was the wrong sign (int32_t
- * instead of uint32_t.) These preserve the old behaviour; the new "make"
- * functions have the correct sign.
- */
-
-/** \deprecated Renamed to mpack_tag_make_nil(). */
-MPACK_INLINE mpack_tag_t mpack_tag_nil(void) {
-    return mpack_tag_make_nil();
-}
-
-/** \deprecated Renamed to mpack_tag_make_bool(). */
-MPACK_INLINE mpack_tag_t mpack_tag_bool(bool value) {
-    return mpack_tag_make_bool(value);
-}
-
-/** \deprecated Renamed to mpack_tag_make_true(). */
-MPACK_INLINE mpack_tag_t mpack_tag_true(void) {
-    return mpack_tag_make_true();
-}
-
-/** \deprecated Renamed to mpack_tag_make_false(). */
-MPACK_INLINE mpack_tag_t mpack_tag_false(void) {
-    return mpack_tag_make_false();
-}
-
-/** \deprecated Renamed to mpack_tag_make_int(). */
-MPACK_INLINE mpack_tag_t mpack_tag_int(int64_t value) {
-    return mpack_tag_make_int(value);
-}
-
-/** \deprecated Renamed to mpack_tag_make_uint(). */
-MPACK_INLINE mpack_tag_t mpack_tag_uint(uint64_t value) {
-    return mpack_tag_make_uint(value);
-}
-
-/** \deprecated Renamed to mpack_tag_make_float(). */
-MPACK_INLINE mpack_tag_t mpack_tag_float(float value) {
-    return mpack_tag_make_float(value);
-}
-
-/** \deprecated Renamed to mpack_tag_make_double(). */
-MPACK_INLINE mpack_tag_t mpack_tag_double(double value) {
-    return mpack_tag_make_double(value);
-}
-
-/** \deprecated Renamed to mpack_tag_make_array(). */
-MPACK_INLINE mpack_tag_t mpack_tag_array(int32_t count) {
-    return mpack_tag_make_array((uint32_t)count);
-}
-
-/** \deprecated Renamed to mpack_tag_make_map(). */
-MPACK_INLINE mpack_tag_t mpack_tag_map(int32_t count) {
-    return mpack_tag_make_map((uint32_t)count);
-}
-
-/** \deprecated Renamed to mpack_tag_make_str(). */
-MPACK_INLINE mpack_tag_t mpack_tag_str(int32_t length) {
-    return mpack_tag_make_str((uint32_t)length);
-}
-
-/** \deprecated Renamed to mpack_tag_make_bin(). */
-MPACK_INLINE mpack_tag_t mpack_tag_bin(int32_t length) {
-    return mpack_tag_make_bin((uint32_t)length);
-}
-
-#if MPACK_EXTENSIONS
-/** \deprecated Renamed to mpack_tag_make_ext(). */
-MPACK_INLINE mpack_tag_t mpack_tag_ext(int8_t exttype, int32_t length) {
-    return mpack_tag_make_ext(exttype, (uint32_t)length);
-}
-#endif
-
-/**
- * @}
- */
-
-/** @cond */
-
-/*
- * Helpers to perform unaligned network-endian loads and stores
- * at arbitrary addresses. Byte-swapping builtins are used if they
- * are available and if they improve performance.
- *
- * These will remain available in the public API so feel free to
- * use them for other purposes, but they are undocumented.
- */
-
-MPACK_INLINE uint8_t mpack_load_u8(const char* p) {
-    return (uint8_t)p[0];
-}
-
-MPACK_INLINE uint16_t mpack_load_u16(const char* p) {
-    #ifdef MPACK_NHSWAP16
-    uint16_t val;
-    mpack_memcpy(&val, p, sizeof(val));
-    return MPACK_NHSWAP16(val);
-    #else
-    return (uint16_t)((((uint16_t)(uint8_t)p[0]) << 8) |
-           ((uint16_t)(uint8_t)p[1]));
-    #endif
-}
-
-MPACK_INLINE uint32_t mpack_load_u32(const char* p) {
-    #ifdef MPACK_NHSWAP32
-    uint32_t val;
-    mpack_memcpy(&val, p, sizeof(val));
-    return MPACK_NHSWAP32(val);
-    #else
-    return (((uint32_t)(uint8_t)p[0]) << 24) |
-           (((uint32_t)(uint8_t)p[1]) << 16) |
-           (((uint32_t)(uint8_t)p[2]) <<  8) |
-            ((uint32_t)(uint8_t)p[3]);
-    #endif
-}
-
-MPACK_INLINE uint64_t mpack_load_u64(const char* p) {
-    #ifdef MPACK_NHSWAP64
-    uint64_t val;
-    mpack_memcpy(&val, p, sizeof(val));
-    return MPACK_NHSWAP64(val);
-    #else
-    return (((uint64_t)(uint8_t)p[0]) << 56) |
-           (((uint64_t)(uint8_t)p[1]) << 48) |
-           (((uint64_t)(uint8_t)p[2]) << 40) |
-           (((uint64_t)(uint8_t)p[3]) << 32) |
-           (((uint64_t)(uint8_t)p[4]) << 24) |
-           (((uint64_t)(uint8_t)p[5]) << 16) |
-           (((uint64_t)(uint8_t)p[6]) <<  8) |
-            ((uint64_t)(uint8_t)p[7]);
-    #endif
-}
-
-MPACK_INLINE void mpack_store_u8(char* p, uint8_t val) {
-    uint8_t* u = (uint8_t*)p;
-    u[0] = val;
-}
-
-MPACK_INLINE void mpack_store_u16(char* p, uint16_t val) {
-    #ifdef MPACK_NHSWAP16
-    val = MPACK_NHSWAP16(val);
-    mpack_memcpy(p, &val, sizeof(val));
-    #else
-    uint8_t* u = (uint8_t*)p;
-    u[0] = (uint8_t)((val >> 8) & 0xFF);
-    u[1] = (uint8_t)( val       & 0xFF);
-    #endif
-}
-
-MPACK_INLINE void mpack_store_u32(char* p, uint32_t val) {
-    #ifdef MPACK_NHSWAP32
-    val = MPACK_NHSWAP32(val);
-    mpack_memcpy(p, &val, sizeof(val));
-    #else
-    uint8_t* u = (uint8_t*)p;
-    u[0] = (uint8_t)((val >> 24) & 0xFF);
-    u[1] = (uint8_t)((val >> 16) & 0xFF);
-    u[2] = (uint8_t)((val >>  8) & 0xFF);
-    u[3] = (uint8_t)( val        & 0xFF);
-    #endif
-}
-
-MPACK_INLINE void mpack_store_u64(char* p, uint64_t val) {
-    #ifdef MPACK_NHSWAP64
-    val = MPACK_NHSWAP64(val);
-    mpack_memcpy(p, &val, sizeof(val));
-    #else
-    uint8_t* u = (uint8_t*)p;
-    u[0] = (uint8_t)((val >> 56) & 0xFF);
-    u[1] = (uint8_t)((val >> 48) & 0xFF);
-    u[2] = (uint8_t)((val >> 40) & 0xFF);
-    u[3] = (uint8_t)((val >> 32) & 0xFF);
-    u[4] = (uint8_t)((val >> 24) & 0xFF);
-    u[5] = (uint8_t)((val >> 16) & 0xFF);
-    u[6] = (uint8_t)((val >>  8) & 0xFF);
-    u[7] = (uint8_t)( val        & 0xFF);
-    #endif
-}
-
-MPACK_INLINE int8_t  mpack_load_i8 (const char* p) {return (int8_t) mpack_load_u8 (p);}
-MPACK_INLINE int16_t mpack_load_i16(const char* p) {return (int16_t)mpack_load_u16(p);}
-MPACK_INLINE int32_t mpack_load_i32(const char* p) {return (int32_t)mpack_load_u32(p);}
-MPACK_INLINE int64_t mpack_load_i64(const char* p) {return (int64_t)mpack_load_u64(p);}
-MPACK_INLINE void mpack_store_i8 (char* p, int8_t  val) {mpack_store_u8 (p, (uint8_t) val);}
-MPACK_INLINE void mpack_store_i16(char* p, int16_t val) {mpack_store_u16(p, (uint16_t)val);}
-MPACK_INLINE void mpack_store_i32(char* p, int32_t val) {mpack_store_u32(p, (uint32_t)val);}
-MPACK_INLINE void mpack_store_i64(char* p, int64_t val) {mpack_store_u64(p, (uint64_t)val);}
-
-MPACK_INLINE float mpack_load_float(const char* p) {
-    MPACK_CHECK_FLOAT_ORDER();
-    MPACK_STATIC_ASSERT(sizeof(float) == sizeof(uint32_t), "float is wrong size??");
-    union {
-        float f;
-        uint32_t u;
-    } v;
-    v.u = mpack_load_u32(p);
-    return v.f;
-}
-
-MPACK_INLINE double mpack_load_double(const char* p) {
-    MPACK_CHECK_FLOAT_ORDER();
-    MPACK_STATIC_ASSERT(sizeof(double) == sizeof(uint64_t), "double is wrong size??");
-    union {
-        double d;
-        uint64_t u;
-    } v;
-    v.u = mpack_load_u64(p);
-    return v.d;
-}
-
-MPACK_INLINE void mpack_store_float(char* p, float value) {
-    MPACK_CHECK_FLOAT_ORDER();
-    union {
-        float f;
-        uint32_t u;
-    } v;
-    v.f = value;
-    mpack_store_u32(p, v.u);
-}
-
-MPACK_INLINE void mpack_store_double(char* p, double value) {
-    MPACK_CHECK_FLOAT_ORDER();
-    union {
-        double d;
-        uint64_t u;
-    } v;
-    v.d = value;
-    mpack_store_u64(p, v.u);
-}
-
-/** @endcond */
-
-
-
-/** @cond */
-
-// Sizes in bytes for the various possible tags
-#define MPACK_TAG_SIZE_FIXUINT  1
-#define MPACK_TAG_SIZE_U8       2
-#define MPACK_TAG_SIZE_U16      3
-#define MPACK_TAG_SIZE_U32      5
-#define MPACK_TAG_SIZE_U64      9
-#define MPACK_TAG_SIZE_FIXINT   1
-#define MPACK_TAG_SIZE_I8       2
-#define MPACK_TAG_SIZE_I16      3
-#define MPACK_TAG_SIZE_I32      5
-#define MPACK_TAG_SIZE_I64      9
-#define MPACK_TAG_SIZE_FLOAT    5
-#define MPACK_TAG_SIZE_DOUBLE   9
-#define MPACK_TAG_SIZE_FIXARRAY 1
-#define MPACK_TAG_SIZE_ARRAY16  3
-#define MPACK_TAG_SIZE_ARRAY32  5
-#define MPACK_TAG_SIZE_FIXMAP   1
-#define MPACK_TAG_SIZE_MAP16    3
-#define MPACK_TAG_SIZE_MAP32    5
-#define MPACK_TAG_SIZE_FIXSTR   1
-#define MPACK_TAG_SIZE_STR8     2
-#define MPACK_TAG_SIZE_STR16    3
-#define MPACK_TAG_SIZE_STR32    5
-#define MPACK_TAG_SIZE_BIN8     2
-#define MPACK_TAG_SIZE_BIN16    3
-#define MPACK_TAG_SIZE_BIN32    5
-#define MPACK_TAG_SIZE_FIXEXT1  2
-#define MPACK_TAG_SIZE_FIXEXT2  2
-#define MPACK_TAG_SIZE_FIXEXT4  2
-#define MPACK_TAG_SIZE_FIXEXT8  2
-#define MPACK_TAG_SIZE_FIXEXT16 2
-#define MPACK_TAG_SIZE_EXT8     3
-#define MPACK_TAG_SIZE_EXT16    4
-#define MPACK_TAG_SIZE_EXT32    6
-
-// size in bytes for complete ext types
-#define MPACK_EXT_SIZE_TIMESTAMP4 (MPACK_TAG_SIZE_FIXEXT4 + 4)
-#define MPACK_EXT_SIZE_TIMESTAMP8 (MPACK_TAG_SIZE_FIXEXT8 + 8)
-#define MPACK_EXT_SIZE_TIMESTAMP12 (MPACK_TAG_SIZE_EXT8 + 12)
-
-/** @endcond */
-
-
-
-#if MPACK_READ_TRACKING || MPACK_WRITE_TRACKING
-/* Tracks the write state of compound elements (maps, arrays, */
-/* strings, binary blobs and extension types) */
-/** @cond */
-
-typedef struct mpack_track_element_t {
-    mpack_type_t type;
-    uint64_t left; // we need 64-bit because (2 * INT32_MAX) elements can be stored in a map
-} mpack_track_element_t;
-
-typedef struct mpack_track_t {
-    size_t count;
-    size_t capacity;
-    mpack_track_element_t* elements;
-} mpack_track_t;
-
-#if MPACK_INTERNAL
-mpack_error_t mpack_track_init(mpack_track_t* track);
-mpack_error_t mpack_track_grow(mpack_track_t* track);
-mpack_error_t mpack_track_push(mpack_track_t* track, mpack_type_t type, uint64_t count);
-mpack_error_t mpack_track_pop(mpack_track_t* track, mpack_type_t type);
-mpack_error_t mpack_track_element(mpack_track_t* track, bool read);
-mpack_error_t mpack_track_peek_element(mpack_track_t* track, bool read);
-mpack_error_t mpack_track_bytes(mpack_track_t* track, bool read, uint64_t count);
-mpack_error_t mpack_track_str_bytes_all(mpack_track_t* track, bool read, uint64_t count);
-mpack_error_t mpack_track_check_empty(mpack_track_t* track);
-mpack_error_t mpack_track_destroy(mpack_track_t* track, bool cancel);
-#endif
-
-/** @endcond */
-#endif
-
-
-
-#if MPACK_INTERNAL
-/** @cond */
-
-
-
-/* Miscellaneous string functions */
-
-/**
- * Returns true if the given UTF-8 string is valid.
- */
-bool mpack_utf8_check(const char* str, size_t bytes);
-
-/**
- * Returns true if the given UTF-8 string is valid and contains no null characters.
- */
-bool mpack_utf8_check_no_null(const char* str, size_t bytes);
-
-/**
- * Returns true if the given string has no null bytes.
- */
-bool mpack_str_check_no_null(const char* str, size_t bytes);
-
-
-
-/** @endcond */
-#endif
-
-
-
-/**
- * @}
- */
-
-/**
- * @}
- */
-
-MPACK_HEADER_END
-
-#endif
-
-
-/* mpack/mpack-writer.h.h */
-
-/**
- * @file
- *
- * Declares the MPack Writer.
- */
-
-#ifndef MPACK_WRITER_H
-#define MPACK_WRITER_H 1
-
-/* #include "mpack-common.h" */
-
-MPACK_HEADER_START
-
-#if MPACK_WRITER
-
-#if MPACK_WRITE_TRACKING
-struct mpack_track_t;
-#endif
-
-/**
- * @defgroup writer Write API
- *
- * The MPack Write API encodes structured data of a fixed (hardcoded) schema to MessagePack.
- *
- * @{
- */
-
-/**
- * @def MPACK_WRITER_MINIMUM_BUFFER_SIZE
- *
- * The minimum buffer size for a writer with a flush function.
- */
-#define MPACK_WRITER_MINIMUM_BUFFER_SIZE 32
-
-/**
- * A buffered MessagePack encoder.
- *
- * The encoder wraps an existing buffer and, optionally, a flush function.
- * This allows efficiently encoding to an in-memory buffer or to a stream.
- *
- * All write operations are synchronous; they will block until the
- * data is fully written, or an error occurs.
- */
-typedef struct mpack_writer_t mpack_writer_t;
-
-/**
- * The MPack writer's flush function to flush the buffer to the output stream.
- * It should flag an appropriate error on the writer if flushing fails (usually
- * mpack_error_io or mpack_error_memory.)
- *
- * The specified context for callbacks is at writer->context.
- */
-typedef void (*mpack_writer_flush_t)(mpack_writer_t* writer, const char* buffer, size_t count);
-
-/**
- * An error handler function to be called when an error is flagged on
- * the writer.
- *
- * The error handler will only be called once on the first error flagged;
- * any subsequent writes and errors are ignored, and the writer is
- * permanently in that error state.
- *
- * MPack is safe against non-local jumps out of error handler callbacks.
- * This means you are allowed to longjmp or throw an exception (in C++,
- * Objective-C, or with SEH) out of this callback.
- *
- * Bear in mind when using longjmp that local non-volatile variables that
- * have changed are undefined when setjmp() returns, so you can't put the
- * writer on the stack in the same activation frame as the setjmp without
- * declaring it volatile.
- *
- * You must still eventually destroy the writer. It is not destroyed
- * automatically when an error is flagged. It is safe to destroy the
- * writer within this error callback, but you will either need to perform
- * a non-local jump, or store something in your context to identify
- * that the writer is destroyed since any future accesses to it cause
- * undefined behavior.
- */
-typedef void (*mpack_writer_error_t)(mpack_writer_t* writer, mpack_error_t error);
-
-/**
- * A teardown function to be called when the writer is destroyed.
- */
-typedef void (*mpack_writer_teardown_t)(mpack_writer_t* writer);
-
-/* Hide internals from documentation */
-/** @cond */
-
-struct mpack_writer_t {
-    #if MPACK_COMPATIBILITY
-    mpack_version_t version;          /* Version of the MessagePack spec to write */
-    #endif
-    mpack_writer_flush_t flush;       /* Function to write bytes to the output stream */
-    mpack_writer_error_t error_fn;    /* Function to call on error */
-    mpack_writer_teardown_t teardown; /* Function to teardown the context on destroy */
-    void* context;                    /* Context for writer callbacks */
-
-    char* buffer;         /* Byte buffer */
-    char* current;        /* Current position within the buffer */
-    char* end;            /* The end of the buffer */
-    mpack_error_t error;  /* Error state */
-
-    #if MPACK_WRITE_TRACKING
-    mpack_track_t track; /* Stack of map/array/str/bin/ext writes */
-    #endif
-
-    #ifdef MPACK_MALLOC
-    /* Reserved. You can use this space to allocate a custom
-     * context in order to reduce heap allocations. */
-    void* reserved[2];
-    #endif
-};
-
-#if MPACK_WRITE_TRACKING
-void mpack_writer_track_push(mpack_writer_t* writer, mpack_type_t type, uint64_t count);
-void mpack_writer_track_pop(mpack_writer_t* writer, mpack_type_t type);
-void mpack_writer_track_element(mpack_writer_t* writer);
-void mpack_writer_track_bytes(mpack_writer_t* writer, size_t count);
-#else
-MPACK_INLINE void mpack_writer_track_push(mpack_writer_t* writer, mpack_type_t type, uint64_t count) {
-    MPACK_UNUSED(writer);
-    MPACK_UNUSED(type);
-    MPACK_UNUSED(count);
-}
-MPACK_INLINE void mpack_writer_track_pop(mpack_writer_t* writer, mpack_type_t type) {
-    MPACK_UNUSED(writer);
-    MPACK_UNUSED(type);
-}
-MPACK_INLINE void mpack_writer_track_element(mpack_writer_t* writer) {
-    MPACK_UNUSED(writer);
-}
-MPACK_INLINE void mpack_writer_track_bytes(mpack_writer_t* writer, size_t count) {
-    MPACK_UNUSED(writer);
-    MPACK_UNUSED(count);
-}
-#endif
-
-/** @endcond */
-
-/**
- * @name Lifecycle Functions
- * @{
- */
-
-/**
- * Initializes an MPack writer with the given buffer. The writer
- * does not assume ownership of the buffer.
- *
- * Trying to write past the end of the buffer will result in mpack_error_too_big
- * unless a flush function is set with mpack_writer_set_flush(). To use the data
- * without flushing, call mpack_writer_buffer_used() to determine the number of
- * bytes written.
- *
- * @param writer The MPack writer.
- * @param buffer The buffer into which to write MessagePack data.
- * @param size The size of the buffer.
- */
-void mpack_writer_init(mpack_writer_t* writer, char* buffer, size_t size);
-
-#ifdef MPACK_MALLOC
-/**
- * Initializes an MPack writer using a growable buffer.
- *
- * The data is placed in the given data pointer if and when the writer
- * is destroyed without error. The data pointer is NULL during writing,
- * and will remain NULL if an error occurs.
- *
- * The allocated data must be freed with MPACK_FREE() (or simply free()
- * if MPack's allocator hasn't been customized.)
- *
- * @throws mpack_error_memory if the buffer fails to grow when
- * flushing.
- *
- * @param writer The MPack writer.
- * @param data Where to place the allocated data.
- * @param size Where to write the size of the data.
- */
-void mpack_writer_init_growable(mpack_writer_t* writer, char** data, size_t* size);
-#endif
-
-/**
- * Initializes an MPack writer directly into an error state. Use this if you
- * are writing a wrapper to mpack_writer_init() which can fail its setup.
- */
-void mpack_writer_init_error(mpack_writer_t* writer, mpack_error_t error);
-
-#if MPACK_STDIO
-/**
- * Initializes an MPack writer that writes to a file.
- *
- * @throws mpack_error_memory if allocation fails
- * @throws mpack_error_io if the file cannot be opened
- */
-void mpack_writer_init_filename(mpack_writer_t* writer, const char* filename);
-
-/**
- * Deprecated.
- *
- * \deprecated Renamed to mpack_writer_init_filename().
- */
-MPACK_INLINE void mpack_writer_init_file(mpack_writer_t* writer, const char* filename) {
-    mpack_writer_init_filename(writer, filename);
-}
-
-/**
- * Initializes an MPack writer that writes to a libc FILE. This can be used to
- * write to stdout or stderr, or to a file opened separately.
- *
- * @param writer The MPack writer.
- * @param stdfile The FILE.
- * @param close_when_done If true, fclose() will be called on the FILE when it
- *         is no longer needed. If false, the file will not be flushed or
- *         closed when writing is done.
- *
- * @note The writer is buffered. If you want to write other data to the FILE in
- *         between messages, you must flush it first.
- *
- * @see mpack_writer_flush_message
- */
-void mpack_writer_init_stdfile(mpack_writer_t* writer, FILE* stdfile, bool close_when_done);
-#endif
-
-/** @cond */
-
-#define mpack_writer_init_stack_line_ex(line, writer) \
-    char mpack_buf_##line[MPACK_STACK_SIZE]; \
-    mpack_writer_init(writer, mpack_buf_##line, sizeof(mpack_buf_##line))
-
-#define mpack_writer_init_stack_line(line, writer) \
-    mpack_writer_init_stack_line_ex(line, writer)
-
-/*
- * Initializes an MPack writer using stack space as a buffer. A flush function
- * should be added to the writer to flush the buffer.
- *
- * This is currently undocumented since it's not entirely useful on its own.
- */
-
-#define mpack_writer_init_stack(writer) \
-    mpack_writer_init_stack_line(__LINE__, (writer))
-
-/** @endcond */
-
-/**
- * Cleans up the MPack writer, flushing and closing the underlying stream,
- * if any. Returns the final error state of the writer.
- *
- * No flushing is performed if the writer is in an error state. The attached
- * teardown function is called whether or not the writer is in an error state.
- *
- * This will assert in tracking mode if the writer is not in an error
- * state and has any unclosed compound types. If you want to cancel
- * writing in the middle of a document, you need to flag an error on
- * the writer before destroying it (such as mpack_error_data).
- *
- * Note that a writer may raise an error and call your error handler during
- * the final flush. It is safe to longjmp or throw out of this error handler,
- * but if you do, the writer will not be destroyed, and the teardown function
- * will not be called. You can still get the writer's error state, and you
- * must call @ref mpack_writer_destroy() again. (The second call is guaranteed
- * not to call your error handler again since the writer is already in an error
- * state.)
- *
- * @see mpack_writer_set_error_handler
- * @see mpack_writer_set_flush
- * @see mpack_writer_set_teardown
- * @see mpack_writer_flag_error
- * @see mpack_error_data
- */
-mpack_error_t mpack_writer_destroy(mpack_writer_t* writer);
-
-/**
- * @}
- */
-
-/**
- * @name Configuration
- * @{
- */
-
-#if MPACK_COMPATIBILITY
-/**
- * Sets the version of the MessagePack spec that will be generated.
- *
- * This can be used to interface with older libraries that do not support
- * the newest MessagePack features (such as the @c str8 type.)
- *
- * @note This requires @ref MPACK_COMPATIBILITY.
- */
-MPACK_INLINE void mpack_writer_set_version(mpack_writer_t* writer, mpack_version_t version) {
-    writer->version = version;
-}
-#endif
-
-/**
- * Sets the custom pointer to pass to the writer callbacks, such as flush
- * or teardown.
- *
- * @param writer The MPack writer.
- * @param context User data to pass to the writer callbacks.
- *
- * @see mpack_writer_context()
- */
-MPACK_INLINE void mpack_writer_set_context(mpack_writer_t* writer, void* context) {
-    writer->context = context;
-}
-
-/**
- * Returns the custom context for writer callbacks.
- *
- * @see mpack_writer_set_context
- * @see mpack_writer_set_flush
- */
-MPACK_INLINE void* mpack_writer_context(mpack_writer_t* writer) {
-    return writer->context;
-}
-
-/**
- * Sets the flush function to write out the data when the buffer is full.
- *
- * If no flush function is used, trying to write past the end of the
- * buffer will result in mpack_error_too_big.
- *
- * This should normally be used with mpack_writer_set_context() to register
- * a custom pointer to pass to the flush function.
- *
- * @param writer The MPack writer.
- * @param flush The function to write out data from the buffer.
- *
- * @see mpack_writer_context()
- */
-void mpack_writer_set_flush(mpack_writer_t* writer, mpack_writer_flush_t flush);
-
-/**
- * Sets the error function to call when an error is flagged on the writer.
- *
- * This should normally be used with mpack_writer_set_context() to register
- * a custom pointer to pass to the error function.
- *
- * See the definition of mpack_writer_error_t for more information about
- * what you can do from an error callback.
- *
- * @see mpack_writer_error_t
- * @param writer The MPack writer.
- * @param error_fn The function to call when an error is flagged on the writer.
- */
-MPACK_INLINE void mpack_writer_set_error_handler(mpack_writer_t* writer, mpack_writer_error_t error_fn) {
-    writer->error_fn = error_fn;
-}
-
-/**
- * Sets the teardown function to call when the writer is destroyed.
- *
- * This should normally be used with mpack_writer_set_context() to register
- * a custom pointer to pass to the teardown function.
- *
- * @param writer The MPack writer.
- * @param teardown The function to call when the writer is destroyed.
- */
-MPACK_INLINE void mpack_writer_set_teardown(mpack_writer_t* writer, mpack_writer_teardown_t teardown) {
-    writer->teardown = teardown;
-}
-
-/**
- * @}
- */
-
-/**
- * @name Core Writer Functions
- * @{
- */
-
-/**
- * Flushes any buffered data to the underlying stream.
- *
- * If write tracking is enabled, this will break and flag @ref
- * mpack_error_bug if the writer has any open compound types, ensuring
- * that no compound types are still open. This prevents a "missing
- * finish" bug from causing a never-ending message.
- *
- * If the writer is connected to a socket and you are keeping it open,
- * you will want to call this after writing a message (or set of
- * messages) so that the data is actually sent.
- *
- * It is not necessary to call this if you are not keeping the writer
- * open afterwards. You can just call `mpack_writer_destroy()`, and it
- * will flush before cleaning up.
- *
- * This will assert if no flush function is assigned to the writer.
- */
-void mpack_writer_flush_message(mpack_writer_t* writer);
-
-/**
- * Returns the number of bytes currently stored in the buffer. This
- * may be less than the total number of bytes written if bytes have
- * been flushed to an underlying stream.
- */
-MPACK_INLINE size_t mpack_writer_buffer_used(mpack_writer_t* writer) {
-    return (size_t)(writer->current - writer->buffer);
-}
-
-/**
- * Returns the amount of space left in the buffer. This may be reset
- * after a write if bytes are flushed to an underlying stream.
- */
-MPACK_INLINE size_t mpack_writer_buffer_left(mpack_writer_t* writer) {
-    return (size_t)(writer->end - writer->current);
-}
-
-/**
- * Returns the (current) size of the buffer. This may change after a write if
- * the flush callback changes the buffer.
- */
-MPACK_INLINE size_t mpack_writer_buffer_size(mpack_writer_t* writer) {
-    return (size_t)(writer->end - writer->buffer);
-}
-
-/**
- * Places the writer in the given error state, calling the error callback if one
- * is set.
- *
- * This allows you to externally flag errors, for example if you are validating
- * data as you write it, or if you want to cancel writing in the middle of a
- * document. (The writer will assert if you try to destroy it without error and
- * with unclosed compound types. In this case you should flag mpack_error_data
- * before destroying it.)
- *
- * If the writer is already in an error state, this call is ignored and no
- * error callback is called.
- *
- * @see mpack_writer_destroy
- * @see mpack_error_data
- */
-void mpack_writer_flag_error(mpack_writer_t* writer, mpack_error_t error);
-
-/**
- * Queries the error state of the MPack writer.
- *
- * If a writer is in an error state, you should discard all data since the
- * last time the error flag was checked. The error flag cannot be cleared.
- */
-MPACK_INLINE mpack_error_t mpack_writer_error(mpack_writer_t* writer) {
-    return writer->error;
-}
-
-/**
- * Writes a MessagePack object header (an MPack Tag.)
- *
- * If the value is a map, array, string, binary or extension type, the
- * containing elements or bytes must be written separately and the
- * appropriate finish function must be called (as though one of the
- * mpack_start_*() functions was called.)
- *
- * @see mpack_write_bytes()
- * @see mpack_finish_map()
- * @see mpack_finish_array()
- * @see mpack_finish_str()
- * @see mpack_finish_bin()
- * @see mpack_finish_ext()
- * @see mpack_finish_type()
- */
-void mpack_write_tag(mpack_writer_t* writer, mpack_tag_t tag);
-
-/**
- * @}
- */
-
-/**
- * @name Integers
- * @{
- */
-
-/** Writes an 8-bit integer in the most efficient packing available. */
-void mpack_write_i8(mpack_writer_t* writer, int8_t value);
-
-/** Writes a 16-bit integer in the most efficient packing available. */
-void mpack_write_i16(mpack_writer_t* writer, int16_t value);
-
-/** Writes a 32-bit integer in the most efficient packing available. */
-void mpack_write_i32(mpack_writer_t* writer, int32_t value);
-
-/** Writes a 64-bit integer in the most efficient packing available. */
-void mpack_write_i64(mpack_writer_t* writer, int64_t value);
-
-/** Writes an integer in the most efficient packing available. */
-MPACK_INLINE void mpack_write_int(mpack_writer_t* writer, int64_t value) {
-    mpack_write_i64(writer, value);
-}
-
-/** Writes an 8-bit unsigned integer in the most efficient packing available. */
-void mpack_write_u8(mpack_writer_t* writer, uint8_t value);
-
-/** Writes an 16-bit unsigned integer in the most efficient packing available. */
-void mpack_write_u16(mpack_writer_t* writer, uint16_t value);
-
-/** Writes an 32-bit unsigned integer in the most efficient packing available. */
-void mpack_write_u32(mpack_writer_t* writer, uint32_t value);
-
-/** Writes an 64-bit unsigned integer in the most efficient packing available. */
-void mpack_write_u64(mpack_writer_t* writer, uint64_t value);
-
-/** Writes an unsigned integer in the most efficient packing available. */
-MPACK_INLINE void mpack_write_uint(mpack_writer_t* writer, uint64_t value) {
-    mpack_write_u64(writer, value);
-}
-
-/**
- * @}
- */
-
-/**
- * @name Other Basic Types
- * @{
- */
-
-/** Writes a float. */
-void mpack_write_float(mpack_writer_t* writer, float value);
-
-/** Writes a double. */
-void mpack_write_double(mpack_writer_t* writer, double value);
-
-/** Writes a boolean. */
-void mpack_write_bool(mpack_writer_t* writer, bool value);
-
-/** Writes a boolean with value true. */
-void mpack_write_true(mpack_writer_t* writer);
-
-/** Writes a boolean with value false. */
-void mpack_write_false(mpack_writer_t* writer);
-
-/** Writes a nil. */
-void mpack_write_nil(mpack_writer_t* writer);
-
-/** Write a pre-encoded messagepack object */
-void mpack_write_object_bytes(mpack_writer_t* writer, const char* data, size_t bytes);
-
-#if MPACK_EXTENSIONS
-/**
- * Writes a timestamp.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @param writer The writer
- * @param seconds The (signed) number of seconds since 1970-01-01T00:00:00Z.
- * @param nanoseconds The additional number of nanoseconds from 0 to 999,999,999 inclusive.
- */
-void mpack_write_timestamp(mpack_writer_t* writer, int64_t seconds, uint32_t nanoseconds);
-
-/**
- * Writes a timestamp with the given number of seconds (and zero nanoseconds).
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @param writer The writer
- * @param seconds The (signed) number of seconds since 1970-01-01T00:00:00Z.
- */
-MPACK_INLINE void mpack_write_timestamp_seconds(mpack_writer_t* writer, int64_t seconds) {
-    mpack_write_timestamp(writer, seconds, 0);
-}
-
-/**
- * Writes a timestamp.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-MPACK_INLINE void mpack_write_timestamp_struct(mpack_writer_t* writer, mpack_timestamp_t timestamp) {
-    mpack_write_timestamp(writer, timestamp.seconds, timestamp.nanoseconds);
-}
-#endif
-
-/**
- * @}
- */
-
-/**
- * @name Map and Array Functions
- * @{
- */
-
-/**
- * Opens an array.
- *
- * `count` elements must follow, and mpack_finish_array() must be called
- * when done.
- *
- * @see mpack_finish_array()
- */
-void mpack_start_array(mpack_writer_t* writer, uint32_t count);
-
-/**
- * Opens a map.
- *
- * `count * 2` elements must follow, and mpack_finish_map() must be called
- * when done.
- *
- * Remember that while map elements in MessagePack are implicitly ordered,
- * they are not ordered in JSON. If you need elements to be read back
- * in the order they are written, consider use an array instead.
- *
- * @see mpack_finish_map()
- */
-void mpack_start_map(mpack_writer_t* writer, uint32_t count);
-
-/**
- * Finishes writing an array.
- *
- * This should be called only after a corresponding call to mpack_start_array()
- * and after the array contents are written.
- *
- * This will track writes to ensure that the correct number of elements are written.
- *
- * @see mpack_start_array()
- */
-MPACK_INLINE void mpack_finish_array(mpack_writer_t* writer) {
-    mpack_writer_track_pop(writer, mpack_type_array);
-}
-
-/**
- * Finishes writing a map.
- *
- * This should be called only after a corresponding call to mpack_start_map()
- * and after the map contents are written.
- *
- * This will track writes to ensure that the correct number of elements are written.
- *
- * @see mpack_start_map()
- */
-MPACK_INLINE void mpack_finish_map(mpack_writer_t* writer) {
-    mpack_writer_track_pop(writer, mpack_type_map);
-}
-
-/**
- * @}
- */
-
-/**
- * @name Data Helpers
- * @{
- */
-
-/**
- * Writes a string.
- *
- * To stream a string in chunks, use mpack_start_str() instead.
- *
- * MPack does not care about the underlying encoding, but UTF-8 is highly
- * recommended, especially for compatibility with JSON. You should consider
- * calling mpack_write_utf8() instead, especially if you will be reading
- * it back as UTF-8.
- *
- * You should not call mpack_finish_str() after calling this; this
- * performs both start and finish.
- */
-void mpack_write_str(mpack_writer_t* writer, const char* str, uint32_t length);
-
-/**
- * Writes a string, ensuring that it is valid UTF-8.
- *
- * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
- * WTF-8. Only pure UTF-8 is allowed.
- *
- * You should not call mpack_finish_str() after calling this; this
- * performs both start and finish.
- *
- * @throws mpack_error_invalid if the string is not valid UTF-8
- */
-void mpack_write_utf8(mpack_writer_t* writer, const char* str, uint32_t length);
-
-/**
- * Writes a null-terminated string. (The null-terminator is not written.)
- *
- * MPack does not care about the underlying encoding, but UTF-8 is highly
- * recommended, especially for compatibility with JSON. You should consider
- * calling mpack_write_utf8_cstr() instead, especially if you will be reading
- * it back as UTF-8.
- *
- * You should not call mpack_finish_str() after calling this; this
- * performs both start and finish.
- */
-void mpack_write_cstr(mpack_writer_t* writer, const char* cstr);
-
-/**
- * Writes a null-terminated string, or a nil node if the given cstr pointer
- * is NULL. (The null-terminator is not written.)
- *
- * MPack does not care about the underlying encoding, but UTF-8 is highly
- * recommended, especially for compatibility with JSON. You should consider
- * calling mpack_write_utf8_cstr_or_nil() instead, especially if you will
- * be reading it back as UTF-8.
- *
- * You should not call mpack_finish_str() after calling this; this
- * performs both start and finish.
- */
-void mpack_write_cstr_or_nil(mpack_writer_t* writer, const char* cstr);
-
-/**
- * Writes a null-terminated string, ensuring that it is valid UTF-8. (The
- * null-terminator is not written.)
- *
- * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
- * WTF-8. Only pure UTF-8 is allowed.
- *
- * You should not call mpack_finish_str() after calling this; this
- * performs both start and finish.
- *
- * @throws mpack_error_invalid if the string is not valid UTF-8
- */
-void mpack_write_utf8_cstr(mpack_writer_t* writer, const char* cstr);
-
-/**
- * Writes a null-terminated string ensuring that it is valid UTF-8, or
- * writes nil if the given cstr pointer is NULL. (The null-terminator
- * is not written.)
- *
- * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
- * WTF-8. Only pure UTF-8 is allowed.
- *
- * You should not call mpack_finish_str() after calling this; this
- * performs both start and finish.
- *
- * @throws mpack_error_invalid if the string is not valid UTF-8
- */
-void mpack_write_utf8_cstr_or_nil(mpack_writer_t* writer, const char* cstr);
-
-/**
- * Writes a binary blob.
- *
- * To stream a binary blob in chunks, use mpack_start_bin() instead.
- *
- * You should not call mpack_finish_bin() after calling this; this
- * performs both start and finish.
- */
-void mpack_write_bin(mpack_writer_t* writer, const char* data, uint32_t count);
-
-#if MPACK_EXTENSIONS
-/**
- * Writes an extension type.
- *
- * To stream an extension blob in chunks, use mpack_start_ext() instead.
- *
- * Extension types [0, 127] are available for application-specific types. Extension
- * types [-128, -1] are reserved for future extensions of MessagePack.
- *
- * You should not call mpack_finish_ext() after calling this; this
- * performs both start and finish.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-void mpack_write_ext(mpack_writer_t* writer, int8_t exttype, const char* data, uint32_t count);
-#endif
-
-/**
- * @}
- */
-
-/**
- * @name Chunked Data Functions
- * @{
- */
-
-/**
- * Opens a string. `count` bytes should be written with calls to
- * mpack_write_bytes(), and mpack_finish_str() should be called
- * when done.
- *
- * To write an entire string at once, use mpack_write_str() or
- * mpack_write_cstr() instead.
- *
- * MPack does not care about the underlying encoding, but UTF-8 is highly
- * recommended, especially for compatibility with JSON.
- */
-void mpack_start_str(mpack_writer_t* writer, uint32_t count);
-
-/**
- * Opens a binary blob. `count` bytes should be written with calls to
- * mpack_write_bytes(), and mpack_finish_bin() should be called
- * when done.
- */
-void mpack_start_bin(mpack_writer_t* writer, uint32_t count);
-
-#if MPACK_EXTENSIONS
-/**
- * Opens an extension type. `count` bytes should be written with calls
- * to mpack_write_bytes(), and mpack_finish_ext() should be called
- * when done.
- *
- * Extension types [0, 127] are available for application-specific types. Extension
- * types [-128, -1] are reserved for future extensions of MessagePack.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-void mpack_start_ext(mpack_writer_t* writer, int8_t exttype, uint32_t count);
-#endif
-
-/**
- * Writes a portion of bytes for a string, binary blob or extension type which
- * was opened by mpack_write_tag() or one of the mpack_start_*() functions.
- *
- * This can be called multiple times to write the data in chunks, as long as
- * the total amount of bytes written matches the count given when the compound
- * type was started.
- *
- * The corresponding mpack_finish_*() function must be called when done.
- *
- * To write an entire string, binary blob or extension type at
- * once, use one of the mpack_write_*() functions instead.
- *
- * @see mpack_write_tag()
- * @see mpack_start_str()
- * @see mpack_start_bin()
- * @see mpack_start_ext()
- * @see mpack_finish_str()
- * @see mpack_finish_bin()
- * @see mpack_finish_ext()
- * @see mpack_finish_type()
- */
-void mpack_write_bytes(mpack_writer_t* writer, const char* data, size_t count);
-
-/**
- * Finishes writing a string.
- *
- * This should be called only after a corresponding call to mpack_start_str()
- * and after the string bytes are written with mpack_write_bytes().
- *
- * This will track writes to ensure that the correct number of elements are written.
- *
- * @see mpack_start_str()
- * @see mpack_write_bytes()
- */
-MPACK_INLINE void mpack_finish_str(mpack_writer_t* writer) {
-    mpack_writer_track_pop(writer, mpack_type_str);
-}
-
-/**
- * Finishes writing a binary blob.
- *
- * This should be called only after a corresponding call to mpack_start_bin()
- * and after the binary bytes are written with mpack_write_bytes().
- *
- * This will track writes to ensure that the correct number of bytes are written.
- *
- * @see mpack_start_bin()
- * @see mpack_write_bytes()
- */
-MPACK_INLINE void mpack_finish_bin(mpack_writer_t* writer) {
-    mpack_writer_track_pop(writer, mpack_type_bin);
-}
-
-#if MPACK_EXTENSIONS
-/**
- * Finishes writing an extended type binary data blob.
- *
- * This should be called only after a corresponding call to mpack_start_bin()
- * and after the binary bytes are written with mpack_write_bytes().
- *
- * This will track writes to ensure that the correct number of bytes are written.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @see mpack_start_ext()
- * @see mpack_write_bytes()
- */
-MPACK_INLINE void mpack_finish_ext(mpack_writer_t* writer) {
-    mpack_writer_track_pop(writer, mpack_type_ext);
-}
-#endif
-
-/**
- * Finishes writing the given compound type.
- *
- * This will track writes to ensure that the correct number of elements
- * or bytes are written.
- *
- * This can be called with the appropriate type instead the corresponding
- * mpack_finish_*() function if you want to finish a dynamic type.
- */
-MPACK_INLINE void mpack_finish_type(mpack_writer_t* writer, mpack_type_t type) {
-    mpack_writer_track_pop(writer, type);
-}
-
-/**
- * @}
- */
-
-#if MPACK_WRITER && MPACK_HAS_GENERIC && !defined(__cplusplus)
-
-/**
- * @name Type-Generic Writers
- * @{
- */
-
-/**
- * @def mpack_write(writer, value)
- *
- * Type-generic writer for primitive types.
- *
- * The compiler will dispatch to an appropriate write function based
- * on the type of the @a value parameter.
- *
- * @note This requires C11 `_Generic` support. (A set of inline overloads
- * are used in C++ to provide the same functionality.)
- *
- * @warning In C11, the indentifiers `true`, `false` and `NULL` are
- * all of type `int`, not `bool` or `void*`! They will emit unexpected
- * types when passed uncast, so be careful when using them.
- */
-#define mpack_write(writer, value) \
-    _Generic(((void)0, value),                      \
-              int8_t: mpack_write_i8,               \
-             int16_t: mpack_write_i16,              \
-             int32_t: mpack_write_i32,              \
-             int64_t: mpack_write_i64,              \
-             uint8_t: mpack_write_u8,               \
-            uint16_t: mpack_write_u16,              \
-            uint32_t: mpack_write_u32,              \
-            uint64_t: mpack_write_u64,              \
-                bool: mpack_write_bool,             \
-               float: mpack_write_float,            \
-              double: mpack_write_double,           \
-              char *: mpack_write_cstr_or_nil,      \
-        const char *: mpack_write_cstr_or_nil       \
-    )(writer, value)
-
-/**
- * @def mpack_write_kv(writer, key, value)
- *
- * Type-generic writer for key-value pairs of null-terminated string
- * keys and primitive values.
- *
- * @warning @a writer may be evaluated multiple times.
- *
- * @warning In C11, the indentifiers `true`, `false` and `NULL` are
- * all of type `int`, not `bool` or `void*`! They will emit unexpected
- * types when passed uncast, so be careful when using them.
- *
- * @param writer The writer.
- * @param key A null-terminated C string.
- * @param value A primitive type supported by mpack_write().
- */
-#define mpack_write_kv(writer, key, value) do {     \
-    mpack_write_cstr(writer, key);                  \
-    mpack_write(writer, value);                     \
-} while (0)
-
-/**
- * @}
- */
-
-#endif
-
-/**
- * @}
- */
-
-#endif
-
-MPACK_HEADER_END
-
-#if defined(__cplusplus) || defined(MPACK_DOXYGEN)
-
-/*
- * C++ generic writers for primitive values
- *
- * These currently sit outside of MPACK_HEADER_END because it defines
- * extern "C". They'll be moved to a C++-specific header soon.
- */
-
-#ifdef MPACK_DOXYGEN
-#undef mpack_write
-#undef mpack_write_kv
-#endif
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, int8_t value) {
-    mpack_write_i8(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, int16_t value) {
-    mpack_write_i16(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, int32_t value) {
-    mpack_write_i32(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, int64_t value) {
-    mpack_write_i64(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint8_t value) {
-    mpack_write_u8(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint16_t value) {
-    mpack_write_u16(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint32_t value) {
-    mpack_write_u32(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, uint64_t value) {
-    mpack_write_u64(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, bool value) {
-    mpack_write_bool(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, float value) {
-    mpack_write_float(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, double value) {
-    mpack_write_double(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, char *value) {
-    mpack_write_cstr_or_nil(writer, value);
-}
-
-MPACK_INLINE void mpack_write(mpack_writer_t* writer, const char *value) {
-    mpack_write_cstr_or_nil(writer, value);
-}
-
-/* C++ generic write for key-value pairs */
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int8_t value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_i8(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int16_t value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_i16(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int32_t value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_i32(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, int64_t value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_i64(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint8_t value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_u8(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint16_t value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_u16(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint32_t value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_u32(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, uint64_t value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_u64(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, bool value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_bool(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, float value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_float(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, double value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_double(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, char *value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_cstr_or_nil(writer, value);
-}
-
-MPACK_INLINE void mpack_write_kv(mpack_writer_t* writer, const char *key, const char *value) {
-    mpack_write_cstr(writer, key);
-    mpack_write_cstr_or_nil(writer, value);
-}
-#endif /* __cplusplus */
-
-#endif
-
-/* mpack/mpack-reader.h.h */
-
-/**
- * @file
- *
- * Declares the core MPack Tag Reader.
- */
-
-#ifndef MPACK_READER_H
-#define MPACK_READER_H 1
-
-/* #include "mpack-common.h" */
-
-MPACK_HEADER_START
-
-#if MPACK_READER
-
-#if MPACK_READ_TRACKING
-struct mpack_track_t;
-#endif
-
-// The denominator to determine whether a read is a small
-// fraction of the buffer size.
-#define MPACK_READER_SMALL_FRACTION_DENOMINATOR 32
-
-/**
- * @defgroup reader Reader API
- *
- * The MPack Reader API contains functions for imperatively reading dynamically
- * typed data from a MessagePack stream.
- *
- * See @ref docs/reader.md for examples.
- *
- * @note If you are not writing code for an embedded device (or otherwise do
- * not need maximum performance with minimal memory usage), you should not use
- * this. You probably want to use the @link node Node API@endlink instead.
- *
- * This forms the basis of the @link expect Expect API@endlink, which can be
- * used to interpret the stream of elements in expected types and value ranges.
- *
- * @{
- */
-
-/**
- * @def MPACK_READER_MINIMUM_BUFFER_SIZE
- *
- * The minimum buffer size for a reader with a fill function.
- */
-#define MPACK_READER_MINIMUM_BUFFER_SIZE 32
-
-/**
- * A buffered MessagePack decoder.
- *
- * The decoder wraps an existing buffer and, optionally, a fill function.
- * This allows efficiently decoding data from existing memory buffers, files,
- * streams, etc.
- *
- * All read operations are synchronous; they will block until the
- * requested data is fully read, or an error occurs.
- *
- * This structure is opaque; its fields should not be accessed outside
- * of MPack.
- */
-typedef struct mpack_reader_t mpack_reader_t;
-
-/**
- * The MPack reader's fill function. It should fill the buffer with at
- * least one byte and at most the given @c count, returning the number
- * of bytes written to the buffer.
- *
- * In case of error, it should flag an appropriate error on the reader
- * (usually @ref mpack_error_io), or simply return zero. If zero is
- * returned, mpack_error_io is raised.
- *
- * @note When reading from a stream, you should only copy and return
- * the bytes that are immediately available. It is always safe to return
- * less than the requested count as long as some non-zero number of bytes
- * are read; if more bytes are needed, the read function will simply be
- * called again.
- *
- * @see mpack_reader_context()
- */
-typedef size_t (*mpack_reader_fill_t)(mpack_reader_t* reader, char* buffer, size_t count);
-
-/**
- * The MPack reader's skip function. It should discard the given number
- * of bytes from the source (for example by seeking forward.)
- *
- * In case of error, it should flag an appropriate error on the reader.
- *
- * @see mpack_reader_context()
- */
-typedef void (*mpack_reader_skip_t)(mpack_reader_t* reader, size_t count);
-
-/**
- * An error handler function to be called when an error is flagged on
- * the reader.
- *
- * The error handler will only be called once on the first error flagged;
- * any subsequent reads and errors are ignored, and the reader is
- * permanently in that error state.
- *
- * MPack is safe against non-local jumps out of error handler callbacks.
- * This means you are allowed to longjmp or throw an exception (in C++,
- * Objective-C, or with SEH) out of this callback.
- *
- * Bear in mind when using longjmp that local non-volatile variables that
- * have changed are undefined when setjmp() returns, so you can't put the
- * reader on the stack in the same activation frame as the setjmp without
- * declaring it volatile.
- *
- * You must still eventually destroy the reader. It is not destroyed
- * automatically when an error is flagged. It is safe to destroy the
- * reader within this error callback, but you will either need to perform
- * a non-local jump, or store something in your context to identify
- * that the reader is destroyed since any future accesses to it cause
- * undefined behavior.
- */
-typedef void (*mpack_reader_error_t)(mpack_reader_t* reader, mpack_error_t error);
-
-/**
- * A teardown function to be called when the reader is destroyed.
- */
-typedef void (*mpack_reader_teardown_t)(mpack_reader_t* reader);
-
-/* Hide internals from documentation */
-/** @cond */
-
-struct mpack_reader_t {
-    void* context;                    /* Context for reader callbacks */
-    mpack_reader_fill_t fill;         /* Function to read bytes into the buffer */
-    mpack_reader_error_t error_fn;    /* Function to call on error */
-    mpack_reader_teardown_t teardown; /* Function to teardown the context on destroy */
-    mpack_reader_skip_t skip;         /* Function to skip bytes from the source */
-
-    char* buffer;       /* Writeable byte buffer */
-    size_t size;        /* Size of the buffer */
-
-    const char* data;   /* Current data pointer (in the buffer, if it is used) */
-    const char* end;    /* The end of available data (in the buffer, if it is used) */
-
-    mpack_error_t error;  /* Error state */
-
-    #if MPACK_READ_TRACKING
-    mpack_track_t track; /* Stack of map/array/str/bin/ext reads */
-    #endif
-};
-
-/** @endcond */
-
-/**
- * @name Lifecycle Functions
- * @{
- */
-
-/**
- * Initializes an MPack reader with the given buffer. The reader does
- * not assume ownership of the buffer, but the buffer must be writeable
- * if a fill function will be used to refill it.
- *
- * @param reader The MPack reader.
- * @param buffer The buffer with which to read MessagePack data.
- * @param size The size of the buffer.
- * @param count The number of bytes already in the buffer.
- */
-void mpack_reader_init(mpack_reader_t* reader, char* buffer, size_t size, size_t count);
-
-/**
- * Initializes an MPack reader directly into an error state. Use this if you
- * are writing a wrapper to mpack_reader_init() which can fail its setup.
- */
-void mpack_reader_init_error(mpack_reader_t* reader, mpack_error_t error);
-
-/**
- * Initializes an MPack reader to parse a pre-loaded contiguous chunk of data. The
- * reader does not assume ownership of the data.
- *
- * @param reader The MPack reader.
- * @param data The data to parse.
- * @param count The number of bytes pointed to by data.
- */
-void mpack_reader_init_data(mpack_reader_t* reader, const char* data, size_t count);
-
-#if MPACK_STDIO
-/**
- * Initializes an MPack reader that reads from a file.
- *
- * The file will be automatically opened and closed by the reader.
- */
-void mpack_reader_init_filename(mpack_reader_t* reader, const char* filename);
-
-/**
- * Deprecated.
- *
- * \deprecated Renamed to mpack_reader_init_filename().
- */
-MPACK_INLINE void mpack_reader_init_file(mpack_reader_t* reader, const char* filename) {
-    mpack_reader_init_filename(reader, filename);
-}
-
-/**
- * Initializes an MPack reader that reads from a libc FILE. This can be used to
- * read from stdin, or from a file opened separately.
- *
- * @param reader The MPack reader.
- * @param stdfile The FILE.
- * @param close_when_done If true, fclose() will be called on the FILE when it
- *         is no longer needed. If false, the file will not be closed when
- *         reading is done.
- *
- * @warning The reader is buffered. It will read data in advance of parsing it,
- * and it may read more data than it parsed. See mpack_reader_remaining() to
- * access the extra data.
- */
-void mpack_reader_init_stdfile(mpack_reader_t* reader, FILE* stdfile, bool close_when_done);
-#endif
-
-/**
- * @def mpack_reader_init_stack(reader)
- * @hideinitializer
- *
- * Initializes an MPack reader using stack space as a buffer. A fill function
- * should be added to the reader to fill the buffer.
- *
- * @see mpack_reader_set_fill
- */
-
-/** @cond */
-#define mpack_reader_init_stack_line_ex(line, reader) \
-    char mpack_buf_##line[MPACK_STACK_SIZE]; \
-    mpack_reader_init((reader), mpack_buf_##line, sizeof(mpack_buf_##line), 0)
-
-#define mpack_reader_init_stack_line(line, reader) \
-    mpack_reader_init_stack_line_ex(line, reader)
-/** @endcond */
-
-#define mpack_reader_init_stack(reader) \
-    mpack_reader_init_stack_line(__LINE__, (reader))
-
-/**
- * Cleans up the MPack reader, ensuring that all compound elements
- * have been completely read. Returns the final error state of the
- * reader.
- *
- * This will assert in tracking mode if the reader is not in an error
- * state and has any incomplete reads. If you want to cancel reading
- * in the middle of a document, you need to flag an error on the reader
- * before destroying it (such as mpack_error_data).
- *
- * @see mpack_read_tag()
- * @see mpack_reader_flag_error()
- * @see mpack_error_data
- */
-mpack_error_t mpack_reader_destroy(mpack_reader_t* reader);
-
-/**
- * @}
- */
-
-/**
- * @name Callbacks
- * @{
- */
-
-/**
- * Sets the custom pointer to pass to the reader callbacks, such as fill
- * or teardown.
- *
- * @param reader The MPack reader.
- * @param context User data to pass to the reader callbacks.
- *
- * @see mpack_reader_context()
- */
-MPACK_INLINE void mpack_reader_set_context(mpack_reader_t* reader, void* context) {
-    reader->context = context;
-}
-
-/**
- * Returns the custom context for reader callbacks.
- *
- * @see mpack_reader_set_context
- * @see mpack_reader_set_fill
- * @see mpack_reader_set_skip
- */
-MPACK_INLINE void* mpack_reader_context(mpack_reader_t* reader) {
-    return reader->context;
-}
-
-/**
- * Sets the fill function to refill the data buffer when it runs out of data.
- *
- * If no fill function is used, truncated MessagePack data results in
- * mpack_error_invalid (since the buffer is assumed to contain a
- * complete MessagePack object.)
- *
- * If a fill function is used, truncated MessagePack data usually
- * results in mpack_error_io (since the fill function fails to get
- * the missing data.)
- *
- * This should normally be used with mpack_reader_set_context() to register
- * a custom pointer to pass to the fill function.
- *
- * @param reader The MPack reader.
- * @param fill The function to fetch additional data into the buffer.
- */
-void mpack_reader_set_fill(mpack_reader_t* reader, mpack_reader_fill_t fill);
-
-/**
- * Sets the skip function to discard bytes from the source stream.
- *
- * It's not necessary to implement this function. If the stream is not
- * seekable, don't set a skip callback. The reader will fall back to
- * using the fill function instead.
- *
- * This should normally be used with mpack_reader_set_context() to register
- * a custom pointer to pass to the skip function.
- *
- * The skip function is ignored in size-optimized builds to reduce code
- * size. Data will be skipped with the fill function when necessary.
- *
- * @param reader The MPack reader.
- * @param skip The function to discard bytes from the source stream.
- */
-void mpack_reader_set_skip(mpack_reader_t* reader, mpack_reader_skip_t skip);
-
-/**
- * Sets the error function to call when an error is flagged on the reader.
- *
- * This should normally be used with mpack_reader_set_context() to register
- * a custom pointer to pass to the error function.
- *
- * See the definition of mpack_reader_error_t for more information about
- * what you can do from an error callback.
- *
- * @see mpack_reader_error_t
- * @param reader The MPack reader.
- * @param error_fn The function to call when an error is flagged on the reader.
- */
-MPACK_INLINE void mpack_reader_set_error_handler(mpack_reader_t* reader, mpack_reader_error_t error_fn) {
-    reader->error_fn = error_fn;
-}
-
-/**
- * Sets the teardown function to call when the reader is destroyed.
- *
- * This should normally be used with mpack_reader_set_context() to register
- * a custom pointer to pass to the teardown function.
- *
- * @param reader The MPack reader.
- * @param teardown The function to call when the reader is destroyed.
- */
-MPACK_INLINE void mpack_reader_set_teardown(mpack_reader_t* reader, mpack_reader_teardown_t teardown) {
-    reader->teardown = teardown;
-}
-
-/**
- * @}
- */
-
-/**
- * @name Core Reader Functions
- * @{
- */
-
-/**
- * Queries the error state of the MPack reader.
- *
- * If a reader is in an error state, you should discard all data since the
- * last time the error flag was checked. The error flag cannot be cleared.
- */
-MPACK_INLINE mpack_error_t mpack_reader_error(mpack_reader_t* reader) {
-    return reader->error;
-}
-
-/**
- * Places the reader in the given error state, calling the error callback if one
- * is set.
- *
- * This allows you to externally flag errors, for example if you are validating
- * data as you read it.
- *
- * If the reader is already in an error state, this call is ignored and no
- * error callback is called.
- */
-void mpack_reader_flag_error(mpack_reader_t* reader, mpack_error_t error);
-
-/**
- * Places the reader in the given error state if the given error is not mpack_ok,
- * returning the resulting error state of the reader.
- *
- * This allows you to externally flag errors, for example if you are validating
- * data as you read it.
- *
- * If the given error is mpack_ok or if the reader is already in an error state,
- * this call is ignored and the actual error state of the reader is returned.
- */
-MPACK_INLINE mpack_error_t mpack_reader_flag_if_error(mpack_reader_t* reader, mpack_error_t error) {
-    if (error != mpack_ok)
-        mpack_reader_flag_error(reader, error);
-    return mpack_reader_error(reader);
-}
-
-/**
- * Returns bytes left in the reader's buffer.
- *
- * If you are done reading MessagePack data but there is other interesting data
- * following it, the reader may have buffered too much data. The number of bytes
- * remaining in the buffer and a pointer to the position of those bytes can be
- * queried here.
- *
- * If you know the length of the MPack chunk beforehand, it's better to instead
- * have your fill function limit the data it reads so that the reader does not
- * have extra data. In this case you can simply check that this returns zero.
- *
- * Returns 0 if the reader is in an error state.
- *
- * @param reader The MPack reader from which to query remaining data.
- * @param data [out] A pointer to the remaining data, or NULL.
- * @return The number of bytes remaining in the buffer.
- */
-size_t mpack_reader_remaining(mpack_reader_t* reader, const char** data);
-
-/**
- * Reads a MessagePack object header (an MPack tag.)
- *
- * If an error occurs, the reader is placed in an error state and a
- * nil tag is returned. If the reader is already in an error state,
- * a nil tag is returned.
- *
- * If the type is compound (i.e. is a map, array, string, binary or
- * extension type), additional reads are required to get the contained
- * data, and the corresponding done function must be called when done.
- *
- * @note Maps in JSON are unordered, so it is recommended not to expect
- * a specific ordering for your map values in case your data is converted
- * to/from JSON.
- * 
- * @see mpack_read_bytes()
- * @see mpack_done_array()
- * @see mpack_done_map()
- * @see mpack_done_str()
- * @see mpack_done_bin()
- * @see mpack_done_ext()
- */
-mpack_tag_t mpack_read_tag(mpack_reader_t* reader);
-
-/**
- * Parses the next MessagePack object header (an MPack tag) without
- * advancing the reader.
- *
- * If an error occurs, the reader is placed in an error state and a
- * nil tag is returned. If the reader is already in an error state,
- * a nil tag is returned.
- *
- * @note Maps in JSON are unordered, so it is recommended not to expect
- * a specific ordering for your map values in case your data is converted
- * to/from JSON.
- *
- * @see mpack_read_tag()
- * @see mpack_discard()
- */
-mpack_tag_t mpack_peek_tag(mpack_reader_t* reader);
-
-/**
- * @}
- */
-
-/**
- * @name String and Data Functions
- * @{
- */
-
-/**
- * Skips bytes from the underlying stream. This is used only to
- * skip the contents of a string, binary blob or extension object.
- */
-void mpack_skip_bytes(mpack_reader_t* reader, size_t count);
-
-/**
- * Reads bytes from a string, binary blob or extension object, copying
- * them into the given buffer.
- *
- * A str, bin or ext must have been opened by a call to mpack_read_tag()
- * which yielded one of these types, or by a call to an expect function
- * such as mpack_expect_str() or mpack_expect_bin().
- *
- * If an error occurs, the buffer contents are undefined.
- *
- * This can be called multiple times for a single str, bin or ext
- * to read the data in chunks. The total data read must add up
- * to the size of the object.
- *
- * @param reader The MPack reader
- * @param p The buffer in which to copy the bytes
- * @param count The number of bytes to read
- */
-void mpack_read_bytes(mpack_reader_t* reader, char* p, size_t count);
-
-/**
- * Reads bytes from a string, ensures that the string is valid UTF-8,
- * and copies the bytes into the given buffer.
- *
- * A string must have been opened by a call to mpack_read_tag() which
- * yielded a string, or by a call to an expect function such as
- * mpack_expect_str().
- *
- * The given byte count must match the complete size of the string as
- * returned by the tag or expect function. You must ensure that the
- * buffer fits the data.
- *
- * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
- * WTF-8. Only pure UTF-8 is allowed.
- *
- * If an error occurs, the buffer contents are undefined.
- *
- * Unlike mpack_read_bytes(), this cannot be used to read the data in
- * chunks (since this might split a character's UTF-8 bytes, and the
- * reader does not keep track of the UTF-8 decoding state between reads.)
- *
- * @throws mpack_error_type if the string contains invalid UTF-8.
- */
-void mpack_read_utf8(mpack_reader_t* reader, char* p, size_t byte_count);
-
-/**
- * Reads bytes from a string, ensures that the string contains no NUL
- * bytes, copies the bytes into the given buffer and adds a null-terminator.
- *
- * A string must have been opened by a call to mpack_read_tag() which
- * yielded a string, or by a call to an expect function such as
- * mpack_expect_str().
- *
- * The given byte count must match the size of the string as returned
- * by the tag or expect function. The string will only be copied if
- * the buffer is large enough to store it.
- *
- * If an error occurs, the buffer will contain an empty string.
- *
- * @note If you know the object will be a string before reading it,
- * it is highly recommended to use mpack_expect_cstr() instead.
- * Alternatively you could use mpack_peek_tag() and call
- * mpack_expect_cstr() if it's a string.
- *
- * @throws mpack_error_too_big if the string plus null-terminator is larger than the given buffer size
- * @throws mpack_error_type if the string contains a null byte.
- *
- * @see mpack_peek_tag()
- * @see mpack_expect_cstr()
- * @see mpack_expect_utf8_cstr()
- */
-void mpack_read_cstr(mpack_reader_t* reader, char* buf, size_t buffer_size, size_t byte_count);
-
-/**
- * Reads bytes from a string, ensures that the string is valid UTF-8
- * with no NUL bytes, copies the bytes into the given buffer and adds a
- * null-terminator.
- *
- * A string must have been opened by a call to mpack_read_tag() which
- * yielded a string, or by a call to an expect function such as
- * mpack_expect_str().
- *
- * The given byte count must match the size of the string as returned
- * by the tag or expect function. The string will only be copied if
- * the buffer is large enough to store it.
- *
- * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
- * WTF-8. Only pure UTF-8 is allowed, but without the NUL character, since
- * it cannot be represented in a null-terminated string.
- *
- * If an error occurs, the buffer will contain an empty string.
- *
- * @note If you know the object will be a string before reading it,
- * it is highly recommended to use mpack_expect_utf8_cstr() instead.
- * Alternatively you could use mpack_peek_tag() and call
- * mpack_expect_utf8_cstr() if it's a string.
- *
- * @throws mpack_error_too_big if the string plus null-terminator is larger than the given buffer size
- * @throws mpack_error_type if the string contains invalid UTF-8 or a null byte.
- *
- * @see mpack_peek_tag()
- * @see mpack_expect_utf8_cstr()
- */
-void mpack_read_utf8_cstr(mpack_reader_t* reader, char* buf, size_t buffer_size, size_t byte_count);
-
-#ifdef MPACK_MALLOC
-/** @cond */
-// This can optionally add a null-terminator, but it does not check
-// whether the data contains null bytes. This must be done separately
-// in a cstring read function (possibly as part of a UTF-8 check.)
-char* mpack_read_bytes_alloc_impl(mpack_reader_t* reader, size_t count, bool null_terminated);
-/** @endcond */
-
-/**
- * Reads bytes from a string, binary blob or extension object, allocating
- * storage for them and returning the allocated pointer.
- *
- * The allocated string must be freed with MPACK_FREE() (or simply free()
- * if MPack's allocator hasn't been customized.)
- *
- * Returns NULL if any error occurs, or if count is zero.
- */
-MPACK_INLINE char* mpack_read_bytes_alloc(mpack_reader_t* reader, size_t count) {
-    return mpack_read_bytes_alloc_impl(reader, count, false);
-}
-#endif
-
-/**
- * Reads bytes from a string, binary blob or extension object in-place in
- * the buffer. This can be used to avoid copying the data.
- *
- * A str, bin or ext must have been opened by a call to mpack_read_tag()
- * which yielded one of these types, or by a call to an expect function
- * such as mpack_expect_str() or mpack_expect_bin().
- *
- * If the bytes are from a string, the string is not null-terminated! Use
- * mpack_read_cstr() to copy the string into a buffer and add a null-terminator.
- *
- * The returned pointer is invalidated on the next read, or when the buffer
- * is destroyed.
- *
- * The reader will move data around in the buffer if needed to ensure that
- * the pointer can always be returned, so this should only be used if
- * count is very small compared to the buffer size. If you need to check
- * whether a small size is reasonable (for example you intend to handle small and
- * large sizes differently), you can call mpack_should_read_bytes_inplace().
- *
- * This can be called multiple times for a single str, bin or ext
- * to read the data in chunks. The total data read must add up
- * to the size of the object.
- *
- * NULL is returned if the reader is in an error state.
- *
- * @throws mpack_error_too_big if the requested size is larger than the buffer size
- *
- * @see mpack_should_read_bytes_inplace()
- */
-const char* mpack_read_bytes_inplace(mpack_reader_t* reader, size_t count);
-
-/**
- * Reads bytes from a string in-place in the buffer and ensures they are
- * valid UTF-8. This can be used to avoid copying the data.
- *
- * A string must have been opened by a call to mpack_read_tag() which
- * yielded a string, or by a call to an expect function such as
- * mpack_expect_str().
- *
- * The string is not null-terminated! Use mpack_read_utf8_cstr() to
- * copy the string into a buffer and add a null-terminator.
- *
- * The returned pointer is invalidated on the next read, or when the buffer
- * is destroyed.
- *
- * The reader will move data around in the buffer if needed to ensure that
- * the pointer can always be returned, so this should only be used if
- * count is very small compared to the buffer size. If you need to check
- * whether a small size is reasonable (for example you intend to handle small and
- * large sizes differently), you can call mpack_should_read_bytes_inplace().
- *
- * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
- * WTF-8. Only pure UTF-8 is allowed.
- *
- * Unlike mpack_read_bytes_inplace(), this cannot be used to read the data in
- * chunks (since this might split a character's UTF-8 bytes, and the
- * reader does not keep track of the UTF-8 decoding state between reads.)
- *
- * NULL is returned if the reader is in an error state.
- *
- * @throws mpack_error_type if the string contains invalid UTF-8
- * @throws mpack_error_too_big if the requested size is larger than the buffer size
- *
- * @see mpack_should_read_bytes_inplace()
- */
-const char* mpack_read_utf8_inplace(mpack_reader_t* reader, size_t count);
-
-/**
- * Returns true if it's a good idea to read the given number of bytes
- * in-place.
- *
- * If the read will be larger than some small fraction of the buffer size,
- * this will return false to avoid shuffling too much data back and forth
- * in the buffer.
- *
- * Use this if you're expecting arbitrary size data, and you want to read
- * in-place for the best performance when possible but will fall back to
- * a normal read if the data is too large.
- *
- * @see mpack_read_bytes_inplace()
- */
-MPACK_INLINE bool mpack_should_read_bytes_inplace(mpack_reader_t* reader, size_t count) {
-    return (reader->size == 0 || count <= reader->size / MPACK_READER_SMALL_FRACTION_DENOMINATOR);
-}
-
-#if MPACK_EXTENSIONS
-/**
- * Reads a timestamp contained in an ext object of the given size, closing the
- * ext type.
- *
- * An ext object of exttype @ref MPACK_EXTTYPE_TIMESTAMP must have been opened
- * by a call to e.g. mpack_read_tag() or mpack_expect_ext().
- *
- * You must NOT call mpack_done_ext() after calling this. A timestamp ext
- * object can only contain a single timestamp value, so this calls
- * mpack_done_ext() automatically.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @throws mpack_error_invalid if the size is not one of the supported
- * timestamp sizes, or if the nanoseconds are out of range.
- */
-mpack_timestamp_t mpack_read_timestamp(mpack_reader_t* reader, size_t size);
-#endif
-
-/**
- * @}
- */
-
-/**
- * @name Core Reader Functions
- * @{
- */
-
-#if MPACK_READ_TRACKING
-/**
- * Finishes reading the given type.
- *
- * This will track reads to ensure that the correct number of elements
- * or bytes are read.
- */
-void mpack_done_type(mpack_reader_t* reader, mpack_type_t type);
-#else
-MPACK_INLINE void mpack_done_type(mpack_reader_t* reader, mpack_type_t type) {
-    MPACK_UNUSED(reader);
-    MPACK_UNUSED(type);
-}
-#endif
-
-/**
- * Finishes reading an array.
- *
- * This will track reads to ensure that the correct number of elements are read.
- */
-MPACK_INLINE void mpack_done_array(mpack_reader_t* reader) {
-    mpack_done_type(reader, mpack_type_array);
-}
-
-/**
- * @fn mpack_done_map(mpack_reader_t* reader)
- *
- * Finishes reading a map.
- *
- * This will track reads to ensure that the correct number of elements are read.
- */
-MPACK_INLINE void mpack_done_map(mpack_reader_t* reader) {
-    mpack_done_type(reader, mpack_type_map);
-}
-
-/**
- * @fn mpack_done_str(mpack_reader_t* reader)
- *
- * Finishes reading a string.
- *
- * This will track reads to ensure that the correct number of bytes are read.
- */
-MPACK_INLINE void mpack_done_str(mpack_reader_t* reader) {
-    mpack_done_type(reader, mpack_type_str);
-}
-
-/**
- * @fn mpack_done_bin(mpack_reader_t* reader)
- *
- * Finishes reading a binary data blob.
- *
- * This will track reads to ensure that the correct number of bytes are read.
- */
-MPACK_INLINE void mpack_done_bin(mpack_reader_t* reader) {
-    mpack_done_type(reader, mpack_type_bin);
-}
-
-#if MPACK_EXTENSIONS
-/**
- * @fn mpack_done_ext(mpack_reader_t* reader)
- *
- * Finishes reading an extended type binary data blob.
- *
- * This will track reads to ensure that the correct number of bytes are read.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-MPACK_INLINE void mpack_done_ext(mpack_reader_t* reader) {
-    mpack_done_type(reader, mpack_type_ext);
-}
-#endif
-
-/**
- * Reads and discards the next object. This will read and discard all
- * contained data as well if it is a compound type.
- */
-void mpack_discard(mpack_reader_t* reader);
-
-/**
- * @}
- */
-
-/** @cond */
-
-#if MPACK_DEBUG && MPACK_STDIO
-/**
- * @name Debugging Functions
- * @{
- */
-/*
- * Converts a blob of MessagePack to a pseudo-JSON string for debugging
- * purposes, placing the result in the given buffer with a null-terminator.
- *
- * If the buffer does not have enough space, the result will be truncated (but
- * it is guaranteed to be null-terminated.)
- *
- * This is only available in debug mode, and only if stdio is available (since
- * it uses snprintf().) It's strictly for debugging purposes.
- */
-void mpack_print_data_to_buffer(const char* data, size_t data_size, char* buffer, size_t buffer_size);
-
-/*
- * Converts a node to pseudo-JSON for debugging purposes, calling the given
- * callback as many times as is necessary to output the character data.
- *
- * No null-terminator or trailing newline will be written.
- *
- * This is only available in debug mode, and only if stdio is available (since
- * it uses snprintf().) It's strictly for debugging purposes.
- */
-void mpack_print_data_to_callback(const char* data, size_t size, mpack_print_callback_t callback, void* context);
-
-/*
- * Converts a blob of MessagePack to pseudo-JSON for debugging purposes
- * and pretty-prints it to the given file.
- */
-void mpack_print_data_to_file(const char* data, size_t len, FILE* file);
-
-/*
- * Converts a blob of MessagePack to pseudo-JSON for debugging purposes
- * and pretty-prints it to stdout.
- */
-MPACK_INLINE void mpack_print_data_to_stdout(const char* data, size_t len) {
-    mpack_print_data_to_file(data, len, stdout);
-}
-
-/*
- * Converts the MessagePack contained in the given `FILE*` to pseudo-JSON for
- * debugging purposes, calling the given callback as many times as is necessary
- * to output the character data.
- */
-void mpack_print_stdfile_to_callback(FILE* file, mpack_print_callback_t callback, void* context);
-
-/*
- * Deprecated.
- *
- * \deprecated Renamed to mpack_print_data_to_stdout().
- */
-MPACK_INLINE void mpack_print(const char* data, size_t len) {
-    mpack_print_data_to_stdout(data, len);
-}
-
-/**
- * @}
- */
-#endif
-
-/** @endcond */
-
-/**
- * @}
- */
-
-
-
-#if MPACK_INTERNAL
-
-bool mpack_reader_ensure_straddle(mpack_reader_t* reader, size_t count);
-
-/*
- * Ensures there are at least @c count bytes left in the
- * data, raising an error and returning false if more
- * data cannot be made available.
- */
-MPACK_INLINE bool mpack_reader_ensure(mpack_reader_t* reader, size_t count) {
-    mpack_assert(count != 0, "cannot ensure zero bytes!");
-    mpack_assert(reader->error == mpack_ok, "reader cannot be in an error state!");
-
-    if (count <= (size_t)(reader->end - reader->data))
-        return true;
-    return mpack_reader_ensure_straddle(reader, count);
-}
-
-void mpack_read_native_straddle(mpack_reader_t* reader, char* p, size_t count);
-
-// Reads count bytes into p, deferring to mpack_read_native_straddle() if more
-// bytes are needed than are available in the buffer.
-MPACK_INLINE void mpack_read_native(mpack_reader_t* reader, char* p, size_t count) {
-    mpack_assert(count == 0 || p != NULL, "data pointer for %i bytes is NULL", (int)count);
-
-    if (count > (size_t)(reader->end - reader->data)) {
-        mpack_read_native_straddle(reader, p, count);
-    } else {
-        mpack_memcpy(p, reader->data, count);
-        reader->data += count;
-    }
-}
-
-#if MPACK_READ_TRACKING
-#define MPACK_READER_TRACK(reader, error_expr) \
-    (((reader)->error == mpack_ok) ? mpack_reader_flag_if_error((reader), (error_expr)) : (reader)->error)
-#else
-#define MPACK_READER_TRACK(reader, error_expr) (MPACK_UNUSED(reader), mpack_ok)
-#endif
-
-MPACK_INLINE mpack_error_t mpack_reader_track_element(mpack_reader_t* reader) {
-    return MPACK_READER_TRACK(reader, mpack_track_element(&reader->track, true));
-}
-
-MPACK_INLINE mpack_error_t mpack_reader_track_peek_element(mpack_reader_t* reader) {
-    return MPACK_READER_TRACK(reader, mpack_track_peek_element(&reader->track, true));
-}
-
-MPACK_INLINE mpack_error_t mpack_reader_track_bytes(mpack_reader_t* reader, uint64_t count) {
-    MPACK_UNUSED(count);
-    return MPACK_READER_TRACK(reader, mpack_track_bytes(&reader->track, true, count));
-}
-
-MPACK_INLINE mpack_error_t mpack_reader_track_str_bytes_all(mpack_reader_t* reader, uint64_t count) {
-    MPACK_UNUSED(count);
-    return MPACK_READER_TRACK(reader, mpack_track_str_bytes_all(&reader->track, true, count));
-}
-
-#endif
-
-
-
-#endif
-
-MPACK_HEADER_END
-
-#endif
-
-
-/* mpack/mpack-expect.h.h */
-
-/**
- * @file
- *
- * Declares the MPack static Expect API.
- */
-
-#ifndef MPACK_EXPECT_H
-#define MPACK_EXPECT_H 1
-
-/* #include "mpack-reader.h" */
-
-MPACK_HEADER_START
-
-#if MPACK_EXPECT
-
-#if !MPACK_READER
-#error "MPACK_EXPECT requires MPACK_READER."
-#endif
-
-/**
- * @defgroup expect Expect API
- *
- * The MPack Expect API allows you to easily read MessagePack data when you
- * expect it to follow a predefined schema.
- *
- * @note If you are not writing code for an embedded device (or otherwise do
- * not need maximum performance with minimal memory usage), you should not use
- * this. You probably want to use the @link node Node API@endlink instead.
- *
- * See @ref docs/expect.md for examples.
- *
- * The main purpose of the Expect API is convenience, so the API is lax. It
- * automatically converts between similar types where there is no loss of
- * precision.
- *
- * When using any of the expect functions, if the type or value of what was
- * read does not match what is expected, @ref mpack_error_type is raised.
- *
- * @{
- */
-
-/**
- * @name Basic Number Functions
- * @{
- */
-
-/**
- * Reads an 8-bit unsigned integer.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in an 8-bit unsigned int.
- *
- * Returns zero if an error occurs.
- */
-uint8_t mpack_expect_u8(mpack_reader_t* reader);
-
-/**
- * Reads a 16-bit unsigned integer.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 16-bit unsigned int.
- *
- * Returns zero if an error occurs.
- */
-uint16_t mpack_expect_u16(mpack_reader_t* reader);
-
-/**
- * Reads a 32-bit unsigned integer.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 32-bit unsigned int.
- *
- * Returns zero if an error occurs.
- */
-uint32_t mpack_expect_u32(mpack_reader_t* reader);
-
-/**
- * Reads a 64-bit unsigned integer.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 64-bit unsigned int.
- *
- * Returns zero if an error occurs.
- */
-uint64_t mpack_expect_u64(mpack_reader_t* reader);
-
-/**
- * Reads an 8-bit signed integer.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in an 8-bit signed int.
- *
- * Returns zero if an error occurs.
- */
-int8_t mpack_expect_i8(mpack_reader_t* reader);
-
-/**
- * Reads a 16-bit signed integer.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 16-bit signed int.
- *
- * Returns zero if an error occurs.
- */
-int16_t mpack_expect_i16(mpack_reader_t* reader);
-
-/**
- * Reads a 32-bit signed integer.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 32-bit signed int.
- *
- * Returns zero if an error occurs.
- */
-int32_t mpack_expect_i32(mpack_reader_t* reader);
-
-/**
- * Reads a 64-bit signed integer.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 64-bit signed int.
- *
- * Returns zero if an error occurs.
- */
-int64_t mpack_expect_i64(mpack_reader_t* reader);
-
-/**
- * Reads a number, returning the value as a float. The underlying value can be an
- * integer, float or double; the value is converted to a float.
- *
- * @note Reading a double or a large integer with this function can incur a
- * loss of precision.
- *
- * @throws mpack_error_type if the underlying value is not a float, double or integer.
- */
-float mpack_expect_float(mpack_reader_t* reader);
-
-/**
- * Reads a number, returning the value as a double. The underlying value can be an
- * integer, float or double; the value is converted to a double.
- *
- * @note Reading a very large integer with this function can incur a
- * loss of precision.
- *
- * @throws mpack_error_type if the underlying value is not a float, double or integer.
- */
-double mpack_expect_double(mpack_reader_t* reader);
-
-/**
- * Reads a float. The underlying value must be a float, not a double or an integer.
- * This ensures no loss of precision can occur.
- *
- * @throws mpack_error_type if the underlying value is not a float.
- */
-float mpack_expect_float_strict(mpack_reader_t* reader);
-
-/**
- * Reads a double. The underlying value must be a float or double, not an integer.
- * This ensures no loss of precision can occur.
- *
- * @throws mpack_error_type if the underlying value is not a float or double.
- */
-double mpack_expect_double_strict(mpack_reader_t* reader);
-
-/**
- * @}
- */
-
-/**
- * @name Ranged Number Functions
- * @{
- */
-
-/**
- * Reads an 8-bit unsigned integer, ensuring that it falls within the given range.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in an 8-bit unsigned int.
- *
- * Returns min_value if an error occurs.
- */
-uint8_t mpack_expect_u8_range(mpack_reader_t* reader, uint8_t min_value, uint8_t max_value);
-
-/**
- * Reads a 16-bit unsigned integer, ensuring that it falls within the given range.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 16-bit unsigned int.
- *
- * Returns min_value if an error occurs.
- */
-uint16_t mpack_expect_u16_range(mpack_reader_t* reader, uint16_t min_value, uint16_t max_value);
-
-/**
- * Reads a 32-bit unsigned integer, ensuring that it falls within the given range.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 32-bit unsigned int.
- *
- * Returns min_value if an error occurs.
- */
-uint32_t mpack_expect_u32_range(mpack_reader_t* reader, uint32_t min_value, uint32_t max_value);
-
-/**
- * Reads a 64-bit unsigned integer, ensuring that it falls within the given range.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 64-bit unsigned int.
- *
- * Returns min_value if an error occurs.
- */
-uint64_t mpack_expect_u64_range(mpack_reader_t* reader, uint64_t min_value, uint64_t max_value);
-
-/**
- * Reads an unsigned integer, ensuring that it falls within the given range.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in an unsigned int.
- *
- * Returns min_value if an error occurs.
- */
-MPACK_INLINE unsigned int mpack_expect_uint_range(mpack_reader_t* reader, unsigned int min_value, unsigned int max_value) {
-    // This should be true at compile-time, so this just wraps the 32-bit
-    // function. We fallback to 64-bit if for some reason sizeof(int) isn't 4.
-    if (sizeof(unsigned int) == 4)
-        return (unsigned int)mpack_expect_u32_range(reader, (uint32_t)min_value, (uint32_t)max_value);
-    return (unsigned int)mpack_expect_u64_range(reader, min_value, max_value);
-}
-
-/**
- * Reads an 8-bit unsigned integer, ensuring that it is at most @a max_value.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in an 8-bit unsigned int.
- *
- * Returns 0 if an error occurs.
- */
-MPACK_INLINE uint8_t mpack_expect_u8_max(mpack_reader_t* reader, uint8_t max_value) {
-    return mpack_expect_u8_range(reader, 0, max_value);
-}
-
-/**
- * Reads a 16-bit unsigned integer, ensuring that it is at most @a max_value.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 16-bit unsigned int.
- *
- * Returns 0 if an error occurs.
- */
-MPACK_INLINE uint16_t mpack_expect_u16_max(mpack_reader_t* reader, uint16_t max_value) {
-    return mpack_expect_u16_range(reader, 0, max_value);
-}
-
-/**
- * Reads a 32-bit unsigned integer, ensuring that it is at most @a max_value.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 32-bit unsigned int.
- *
- * Returns 0 if an error occurs.
- */
-MPACK_INLINE uint32_t mpack_expect_u32_max(mpack_reader_t* reader, uint32_t max_value) {
-    return mpack_expect_u32_range(reader, 0, max_value);
-}
-
-/**
- * Reads a 64-bit unsigned integer, ensuring that it is at most @a max_value.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 64-bit unsigned int.
- *
- * Returns 0 if an error occurs.
- */
-MPACK_INLINE uint64_t mpack_expect_u64_max(mpack_reader_t* reader, uint64_t max_value) {
-    return mpack_expect_u64_range(reader, 0, max_value);
-}
-
-/**
- * Reads an unsigned integer, ensuring that it is at most @a max_value.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in an unsigned int.
- *
- * Returns 0 if an error occurs.
- */
-MPACK_INLINE unsigned int mpack_expect_uint_max(mpack_reader_t* reader, unsigned int max_value) {
-    return mpack_expect_uint_range(reader, 0, max_value);
-}
-
-/**
- * Reads an 8-bit signed integer, ensuring that it falls within the given range.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in an 8-bit signed int.
- *
- * Returns min_value if an error occurs.
- */
-int8_t mpack_expect_i8_range(mpack_reader_t* reader, int8_t min_value, int8_t max_value);
-
-/**
- * Reads a 16-bit signed integer, ensuring that it falls within the given range.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 16-bit signed int.
- *
- * Returns min_value if an error occurs.
- */
-int16_t mpack_expect_i16_range(mpack_reader_t* reader, int16_t min_value, int16_t max_value);
-
-/**
- * Reads a 32-bit signed integer, ensuring that it falls within the given range.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 32-bit signed int.
- *
- * Returns min_value if an error occurs.
- */
-int32_t mpack_expect_i32_range(mpack_reader_t* reader, int32_t min_value, int32_t max_value);
-
-/**
- * Reads a 64-bit signed integer, ensuring that it falls within the given range.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 64-bit signed int.
- *
- * Returns min_value if an error occurs.
- */
-int64_t mpack_expect_i64_range(mpack_reader_t* reader, int64_t min_value, int64_t max_value);
-
-/**
- * Reads a signed integer, ensuring that it falls within the given range.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a signed int.
- *
- * Returns min_value if an error occurs.
- */
-MPACK_INLINE int mpack_expect_int_range(mpack_reader_t* reader, int min_value, int max_value) {
-    // This should be true at compile-time, so this just wraps the 32-bit
-    // function. We fallback to 64-bit if for some reason sizeof(int) isn't 4.
-    if (sizeof(int) == 4)
-        return (int)mpack_expect_i32_range(reader, (int32_t)min_value, (int32_t)max_value);
-    return (int)mpack_expect_i64_range(reader, min_value, max_value);
-}
-
-/**
- * Reads an 8-bit signed integer, ensuring that it is at least zero and at
- * most @a max_value.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in an 8-bit signed int.
- *
- * Returns 0 if an error occurs.
- */
-MPACK_INLINE int8_t mpack_expect_i8_max(mpack_reader_t* reader, int8_t max_value) {
-    return mpack_expect_i8_range(reader, 0, max_value);
-}
-
-/**
- * Reads a 16-bit signed integer, ensuring that it is at least zero and at
- * most @a max_value.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 16-bit signed int.
- *
- * Returns 0 if an error occurs.
- */
-MPACK_INLINE int16_t mpack_expect_i16_max(mpack_reader_t* reader, int16_t max_value) {
-    return mpack_expect_i16_range(reader, 0, max_value);
-}
-
-/**
- * Reads a 32-bit signed integer, ensuring that it is at least zero and at
- * most @a max_value.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 32-bit signed int.
- *
- * Returns 0 if an error occurs.
- */
-MPACK_INLINE int32_t mpack_expect_i32_max(mpack_reader_t* reader, int32_t max_value) {
-    return mpack_expect_i32_range(reader, 0, max_value);
-}
-
-/**
- * Reads a 64-bit signed integer, ensuring that it is at least zero and at
- * most @a max_value.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a 64-bit signed int.
- *
- * Returns 0 if an error occurs.
- */
-MPACK_INLINE int64_t mpack_expect_i64_max(mpack_reader_t* reader, int64_t max_value) {
-    return mpack_expect_i64_range(reader, 0, max_value);
-}
-
-/**
- * Reads an int, ensuring that it is at least zero and at most @a max_value.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a signed int.
- *
- * Returns 0 if an error occurs.
- */
-MPACK_INLINE int mpack_expect_int_max(mpack_reader_t* reader, int max_value) {
-    return mpack_expect_int_range(reader, 0, max_value);
-}
-
-/**
- * Reads a number, ensuring that it falls within the given range and returning
- * the value as a float. The underlying value can be an integer, float or
- * double; the value is converted to a float.
- *
- * @note Reading a double or a large integer with this function can incur a
- * loss of precision.
- *
- * @throws mpack_error_type if the underlying value is not a float, double or integer.
- */
-float mpack_expect_float_range(mpack_reader_t* reader, float min_value, float max_value);
-
-/**
- * Reads a number, ensuring that it falls within the given range and returning
- * the value as a double. The underlying value can be an integer, float or
- * double; the value is converted to a double.
- *
- * @note Reading a very large integer with this function can incur a
- * loss of precision.
- *
- * @throws mpack_error_type if the underlying value is not a float, double or integer.
- */
-double mpack_expect_double_range(mpack_reader_t* reader, double min_value, double max_value);
-
-/**
- * @}
- */
-
-
-
-// These are additional Basic Number functions that wrap inline range functions.
-
-/**
- * @name Basic Number Functions
- * @{
- */
-
-/**
- * Reads an unsigned int.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in an unsigned int.
- *
- * Returns zero if an error occurs.
- */
-MPACK_INLINE unsigned int mpack_expect_uint(mpack_reader_t* reader) {
-
-    // This should be true at compile-time, so this just wraps the 32-bit function.
-    if (sizeof(unsigned int) == 4)
-        return (unsigned int)mpack_expect_u32(reader);
-
-    // Otherwise we wrap the max function to ensure it fits.
-    return (unsigned int)mpack_expect_u64_max(reader, UINT_MAX);
-
-}
-
-/**
- * Reads a signed int.
- *
- * The underlying type may be an integer type of any size and signedness,
- * as long as the value can be represented in a signed int.
- *
- * Returns zero if an error occurs.
- */
-MPACK_INLINE int mpack_expect_int(mpack_reader_t* reader) {
-
-    // This should be true at compile-time, so this just wraps the 32-bit function.
-    if (sizeof(int) == 4)
-        return (int)mpack_expect_i32(reader);
-
-    // Otherwise we wrap the range function to ensure it fits.
-    return (int)mpack_expect_i64_range(reader, INT_MIN, INT_MAX);
-
-}
-
-/**
- * @}
- */
-
-
-
-/**
- * @name Matching Number Functions
- * @{
- */
-
-/**
- * Reads an unsigned integer, ensuring that it exactly matches the given value.
- *
- * mpack_error_type is raised if the value is not representable as an unsigned
- * integer or if it does not exactly match the given value.
- */
-void mpack_expect_uint_match(mpack_reader_t* reader, uint64_t value);
-
-/**
- * Reads a signed integer, ensuring that it exactly matches the given value.
- *
- * mpack_error_type is raised if the value is not representable as a signed
- * integer or if it does not exactly match the given value.
- */
-void mpack_expect_int_match(mpack_reader_t* reader, int64_t value);
-
-/**
- * @name Other Basic Types
- * @{
- */
-
-/**
- * Reads a nil, raising @ref mpack_error_type if the value is not nil.
- */
-void mpack_expect_nil(mpack_reader_t* reader);
-
-/**
- * Reads a boolean.
- *
- * @note Integers will raise mpack_error_type; the value must be strictly a boolean.
- */
-bool mpack_expect_bool(mpack_reader_t* reader);
-
-/**
- * Reads a boolean, raising @ref mpack_error_type if its value is not @c true.
- */
-void mpack_expect_true(mpack_reader_t* reader);
-
-/**
- * Reads a boolean, raising @ref mpack_error_type if its value is not @c false.
- */
-void mpack_expect_false(mpack_reader_t* reader);
-
-/**
- * @}
- */
-
-/**
- * @name Extension Functions
- * @{
- */
-
-#if MPACK_EXTENSIONS
-/**
- * Reads a timestamp.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-mpack_timestamp_t mpack_expect_timestamp(mpack_reader_t* reader);
-
-/**
- * Reads a timestamp in seconds, truncating the nanoseconds (if any).
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-int64_t mpack_expect_timestamp_truncate(mpack_reader_t* reader);
-#endif
-
-/**
- * @}
- */
-
-/**
- * @name Compound Types
- * @{
- */
-
-/**
- * Reads the start of a map, returning its element count.
- *
- * A number of values follow equal to twice the element count of the map,
- * alternating between keys and values. @ref mpack_done_map() must be called
- * once all elements have been read.
- *
- * @note Maps in JSON are unordered, so it is recommended not to expect
- * a specific ordering for your map values in case your data is converted
- * to/from JSON.
- *
- * @warning This call is dangerous! It does not have a size limit, and it
- * does not have any way of checking whether there is enough data in the
- * message (since the data could be coming from a stream.) When looping
- * through the map's contents, you must check for errors on each iteration
- * of the loop. Otherwise an attacker could craft a message declaring a map
- * of a billion elements which would throw your parsing code into an
- * infinite loop! You should strongly consider using mpack_expect_map_max()
- * with a safe maximum size instead.
- *
- * @throws mpack_error_type if the value is not a map.
- */
-uint32_t mpack_expect_map(mpack_reader_t* reader);
-
-/**
- * Reads the start of a map with a number of elements in the given range, returning
- * its element count.
- *
- * A number of values follow equal to twice the element count of the map,
- * alternating between keys and values. @ref mpack_done_map() must be called
- * once all elements have been read.
- *
- * @note Maps in JSON are unordered, so it is recommended not to expect
- * a specific ordering for your map values in case your data is converted
- * to/from JSON.
- *
- * min_count is returned if an error occurs.
- *
- * @throws mpack_error_type if the value is not a map or if its size does
- * not fall within the given range.
- */
-uint32_t mpack_expect_map_range(mpack_reader_t* reader, uint32_t min_count, uint32_t max_count);
-
-/**
- * Reads the start of a map with a number of elements at most @a max_count,
- * returning its element count.
- *
- * A number of values follow equal to twice the element count of the map,
- * alternating between keys and values. @ref mpack_done_map() must be called
- * once all elements have been read.
- *
- * @note Maps in JSON are unordered, so it is recommended not to expect
- * a specific ordering for your map values in case your data is converted
- * to/from JSON.
- *
- * Zero is returned if an error occurs.
- *
- * @throws mpack_error_type if the value is not a map or if its size is
- * greater than max_count.
- */
-MPACK_INLINE uint32_t mpack_expect_map_max(mpack_reader_t* reader, uint32_t max_count) {
-    return mpack_expect_map_range(reader, 0, max_count);
-}
-
-/**
- * Reads the start of a map of the exact size given.
- *
- * A number of values follow equal to twice the element count of the map,
- * alternating between keys and values. @ref mpack_done_map() must be called
- * once all elements have been read.
- *
- * @note Maps in JSON are unordered, so it is recommended not to expect
- * a specific ordering for your map values in case your data is converted
- * to/from JSON.
- *
- * @throws mpack_error_type if the value is not a map or if its size
- * does not match the given count.
- */
-void mpack_expect_map_match(mpack_reader_t* reader, uint32_t count);
-
-/**
- * Reads a nil node or the start of a map, returning whether a map was
- * read and placing its number of key/value pairs in count.
- *
- * If a map was read, a number of values follow equal to twice the element count
- * of the map, alternating between keys and values. @ref mpack_done_map() should
- * also be called once all elements have been read (only if a map was read.)
- *
- * @note Maps in JSON are unordered, so it is recommended not to expect
- * a specific ordering for your map values in case your data is converted
- * to/from JSON.
- *
- * @warning This call is dangerous! It does not have a size limit, and it
- * does not have any way of checking whether there is enough data in the
- * message (since the data could be coming from a stream.) When looping
- * through the map's contents, you must check for errors on each iteration
- * of the loop. Otherwise an attacker could craft a message declaring a map
- * of a billion elements which would throw your parsing code into an
- * infinite loop! You should strongly consider using mpack_expect_map_max_or_nil()
- * with a safe maximum size instead.
- *
- * @returns @c true if a map was read successfully; @c false if nil was read
- *     or an error occured.
- * @throws mpack_error_type if the value is not a nil or map.
- */
-bool mpack_expect_map_or_nil(mpack_reader_t* reader, uint32_t* count);
-
-/**
- * Reads a nil node or the start of a map with a number of elements at most
- * max_count, returning whether a map was read and placing its number of
- * key/value pairs in count.
- *
- * If a map was read, a number of values follow equal to twice the element count
- * of the map, alternating between keys and values. @ref mpack_done_map() should
- * anlso be called once all elements have been read (only if a map was read.)
- *
- * @note Maps in JSON are unordered, so it is recommended not to expect
- * a specific ordering for your map values in case your data is converted
- * to/from JSON. Consider using mpack_expect_key_cstr() or mpack_expect_key_uint()
- * to switch on the key; see @ref docs/expect.md for examples.
- *
- * @returns @c true if a map was read successfully; @c false if nil was read
- *     or an error occured.
- * @throws mpack_error_type if the value is not a nil or map.
- */
-bool mpack_expect_map_max_or_nil(mpack_reader_t* reader, uint32_t max_count, uint32_t* count);
-
-/**
- * Reads the start of an array, returning its element count.
- *
- * A number of values follow equal to the element count of the array.
- * @ref mpack_done_array() must be called once all elements have been read.
- *
- * @warning This call is dangerous! It does not have a size limit, and it
- * does not have any way of checking whether there is enough data in the
- * message (since the data could be coming from a stream.) When looping
- * through the array's contents, you must check for errors on each iteration
- * of the loop. Otherwise an attacker could craft a message declaring an array
- * of a billion elements which would throw your parsing code into an
- * infinite loop! You should strongly consider using mpack_expect_array_max()
- * with a safe maximum size instead.
- */
-uint32_t mpack_expect_array(mpack_reader_t* reader);
-
-/**
- * Reads the start of an array with a number of elements in the given range,
- * returning its element count.
- *
- * A number of values follow equal to the element count of the array.
- * @ref mpack_done_array() must be called once all elements have been read.
- *
- * min_count is returned if an error occurs.
- *
- * @throws mpack_error_type if the value is not an array or if its size does
- * not fall within the given range.
- */
-uint32_t mpack_expect_array_range(mpack_reader_t* reader, uint32_t min_count, uint32_t max_count);
-
-/**
- * Reads the start of an array with a number of elements at most @a max_count,
- * returning its element count.
- *
- * A number of values follow equal to the element count of the array.
- * @ref mpack_done_array() must be called once all elements have been read.
- *
- * Zero is returned if an error occurs.
- *
- * @throws mpack_error_type if the value is not an array or if its size is
- * greater than max_count.
- */
-MPACK_INLINE uint32_t mpack_expect_array_max(mpack_reader_t* reader, uint32_t max_count) {
-    return mpack_expect_array_range(reader, 0, max_count);
-}
-
-/**
- * Reads the start of an array of the exact size given.
- *
- * A number of values follow equal to the element count of the array.
- * @ref mpack_done_array() must be called once all elements have been read.
- *
- * @throws mpack_error_type if the value is not an array or if its size does
- * not match the given count.
- */
-void mpack_expect_array_match(mpack_reader_t* reader, uint32_t count);
-
-/**
- * Reads a nil node or the start of an array, returning whether an array was
- * read and placing its number of elements in count.
- *
- * If an array was read, a number of values follow equal to the element count
- * of the array. @ref mpack_done_array() should also be called once all elements
- * have been read (only if an array was read.)
- *
- * @warning This call is dangerous! It does not have a size limit, and it
- * does not have any way of checking whether there is enough data in the
- * message (since the data could be coming from a stream.) When looping
- * through the array's contents, you must check for errors on each iteration
- * of the loop. Otherwise an attacker could craft a message declaring an array
- * of a billion elements which would throw your parsing code into an
- * infinite loop! You should strongly consider using mpack_expect_array_max_or_nil()
- * with a safe maximum size instead.
- *
- * @returns @c true if an array was read successfully; @c false if nil was read
- *     or an error occured.
- * @throws mpack_error_type if the value is not a nil or array.
- */
-bool mpack_expect_array_or_nil(mpack_reader_t* reader, uint32_t* count);
-
-/**
- * Reads a nil node or the start of an array with a number of elements at most
- * max_count, returning whether an array was read and placing its number of
- * key/value pairs in count.
- *
- * If an array was read, a number of values follow equal to the element count
- * of the array. @ref mpack_done_array() should also be called once all elements
- * have been read (only if an array was read.)
- *
- * @returns @c true if an array was read successfully; @c false if nil was read
- *     or an error occured.
- * @throws mpack_error_type if the value is not a nil or array.
- */
-bool mpack_expect_array_max_or_nil(mpack_reader_t* reader, uint32_t max_count, uint32_t* count);
-
-#ifdef MPACK_MALLOC
-/**
- * @hideinitializer
- *
- * Reads the start of an array and allocates storage for it, placing its
- * size in out_count. A number of objects follow equal to the element count
- * of the array. You must call @ref mpack_done_array() when done (even
- * if the element count is zero.)
- *
- * If an error occurs, NULL is returned and the reader is placed in an
- * error state.
- *
- * If the count is zero, NULL is returned. This does not indicate error.
- * You should not check the return value for NULL to check for errors; only
- * check the reader's error state.
- *
- * The allocated array must be freed with MPACK_FREE() (or simply free()
- * if MPack's allocator hasn't been customized.)
- *
- * @throws mpack_error_type if the value is not an array or if its size is
- * greater than max_count.
- */
-#define mpack_expect_array_alloc(reader, Type, max_count, out_count) \
-    ((Type*)mpack_expect_array_alloc_impl(reader, sizeof(Type), max_count, out_count, false))
-
-/**
- * @hideinitializer
- *
- * Reads a nil node or the start of an array and allocates storage for it,
- * placing its size in out_count. A number of objects follow equal to the element
- * count of the array if a non-empty array was read.
- *
- * If an error occurs, NULL is returned and the reader is placed in an
- * error state.
- *
- * If a nil node was read, NULL is returned. If an empty array was read,
- * mpack_done_array() is called automatically and NULL is returned. These
- * do not indicate error. You should not check the return value for NULL
- * to check for errors; only check the reader's error state.
- *
- * The allocated array must be freed with MPACK_FREE() (or simply free()
- * if MPack's allocator hasn't been customized.)
- *
- * @warning You must call @ref mpack_done_array() if and only if a non-zero
- * element count is read. This function does not differentiate between nil
- * and an empty array.
- *
- * @throws mpack_error_type if the value is not an array or if its size is
- * greater than max_count.
- */
-#define mpack_expect_array_or_nil_alloc(reader, Type, max_count, out_count) \
-    ((Type*)mpack_expect_array_alloc_impl(reader, sizeof(Type), max_count, out_count, true))
-#endif
-
-/**
- * @}
- */
-
-/** @cond */
-#ifdef MPACK_MALLOC
-void* mpack_expect_array_alloc_impl(mpack_reader_t* reader,
-        size_t element_size, uint32_t max_count, uint32_t* out_count, bool allow_nil);
-#endif
-/** @endcond */
-
-
-/**
- * @name String Functions
- * @{
- */
-
-/**
- * Reads the start of a string, returning its size in bytes.
- *
- * The bytes follow and must be read separately with mpack_read_bytes()
- * or mpack_read_bytes_inplace(). mpack_done_str() must be called
- * once all bytes have been read.
- *
- * NUL bytes are allowed in the string, and no encoding checks are done.
- *
- * mpack_error_type is raised if the value is not a string.
- */
-uint32_t mpack_expect_str(mpack_reader_t* reader);
-
-/**
- * Reads a string of at most the given size, writing it into the
- * given buffer and returning its size in bytes.
- *
- * This does not add a null-terminator! Use mpack_expect_cstr() to
- * add a null-terminator.
- *
- * NUL bytes are allowed in the string, and no encoding checks are done.
- */
-size_t mpack_expect_str_buf(mpack_reader_t* reader, char* buf, size_t bufsize);
-
-/**
- * Reads a string into the given buffer, ensuring it is a valid UTF-8 string
- * and returning its size in bytes.
- *
- * This does not add a null-terminator! Use mpack_expect_utf8_cstr() to
- * add a null-terminator.
- *
- * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
- * WTF-8. Only pure UTF-8 is allowed.
- *
- * NUL bytes are allowed in the string (as they are in UTF-8.)
- *
- * Raises mpack_error_too_big if there is not enough room for the string.
- * Raises mpack_error_type if the value is not a string or is not a valid UTF-8 string.
- */
-size_t mpack_expect_utf8(mpack_reader_t* reader, char* buf, size_t bufsize);
-
-/**
- * Reads the start of a string, raising an error if its length is not
- * at most the given number of bytes (not including any null-terminator.)
- *
- * The bytes follow and must be read separately with mpack_read_bytes()
- * or mpack_read_bytes_inplace(). @ref mpack_done_str() must be called
- * once all bytes have been read.
- *
- * @throws mpack_error_type If the value is not a string.
- * @throws mpack_error_too_big If the string's length in bytes is larger than the given maximum size.
- */
-MPACK_INLINE uint32_t mpack_expect_str_max(mpack_reader_t* reader, uint32_t maxsize) {
-    uint32_t length = mpack_expect_str(reader);
-    if (length > maxsize) {
-        mpack_reader_flag_error(reader, mpack_error_too_big);
-        return 0;
-    }
-    return length;
-}
-
-/**
- * Reads the start of a string, raising an error if its length is not
- * exactly the given number of bytes (not including any null-terminator.)
- *
- * The bytes follow and must be read separately with mpack_read_bytes()
- * or mpack_read_bytes_inplace(). @ref mpack_done_str() must be called
- * once all bytes have been read.
- *
- * mpack_error_type is raised if the value is not a string or if its
- * length does not match.
- */
-MPACK_INLINE void mpack_expect_str_length(mpack_reader_t* reader, uint32_t count) {
-    if (mpack_expect_str(reader) != count)
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-/**
- * Reads a string, ensuring it exactly matches the given string.
- *
- * Remember that maps are unordered in JSON. Don't use this for map keys
- * unless the map has only a single key!
- */
-void mpack_expect_str_match(mpack_reader_t* reader, const char* str, size_t length);
-
-/**
- * Reads a string into the given buffer, ensures it has no null bytes,
- * and adds a null-terminator at the end.
- *
- * Raises mpack_error_too_big if there is not enough room for the string and null-terminator.
- * Raises mpack_error_type if the value is not a string or contains a null byte.
- */
-void mpack_expect_cstr(mpack_reader_t* reader, char* buf, size_t size);
-
-/**
- * Reads a string into the given buffer, ensures it is a valid UTF-8 string
- * without NUL characters, and adds a null-terminator at the end.
- *
- * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
- * WTF-8. Only pure UTF-8 is allowed, but without the NUL character, since
- * it cannot be represented in a null-terminated string.
- *
- * Raises mpack_error_too_big if there is not enough room for the string and null-terminator.
- * Raises mpack_error_type if the value is not a string or is not a valid UTF-8 string.
- */
-void mpack_expect_utf8_cstr(mpack_reader_t* reader, char* buf, size_t size);
-
-#ifdef MPACK_MALLOC
-/**
- * Reads a string with the given total maximum size (including space for a
- * null-terminator), allocates storage for it, ensures it has no null-bytes,
- * and adds a null-terminator at the end. You assume ownership of the
- * returned pointer if reading succeeds.
- *
- * The allocated string must be freed with MPACK_FREE() (or simply free()
- * if MPack's allocator hasn't been customized.)
- *
- * @throws mpack_error_too_big If the string plus null-terminator is larger than the given maxsize.
- * @throws mpack_error_type If the value is not a string or contains a null byte.
- */
-char* mpack_expect_cstr_alloc(mpack_reader_t* reader, size_t maxsize);
-
-/**
- * Reads a string with the given total maximum size (including space for a
- * null-terminator), allocates storage for it, ensures it is valid UTF-8
- * with no null-bytes, and adds a null-terminator at the end. You assume
- * ownership of the returned pointer if reading succeeds.
- *
- * The length in bytes of the string, not including the null-terminator,
- * will be written to size.
- *
- * This does not accept any UTF-8 variant such as Modified UTF-8, CESU-8 or
- * WTF-8. Only pure UTF-8 is allowed, but without the NUL character, since
- * it cannot be represented in a null-terminated string.
- *
- * The allocated string must be freed with MPACK_FREE() (or simply free()
- * if MPack's allocator hasn't been customized.)
- * if you want a null-terminator.
- *
- * @throws mpack_error_too_big If the string plus null-terminator is larger
- *     than the given maxsize.
- * @throws mpack_error_type If the value is not a string or contains
- *     invalid UTF-8 or a null byte.
- */
-char* mpack_expect_utf8_cstr_alloc(mpack_reader_t* reader, size_t maxsize);
-#endif
-
-/**
- * Reads a string, ensuring it exactly matches the given null-terminated
- * string.
- *
- * Remember that maps are unordered in JSON. Don't use this for map keys
- * unless the map has only a single key!
- */
-MPACK_INLINE void mpack_expect_cstr_match(mpack_reader_t* reader, const char* cstr) {
-    mpack_assert(cstr != NULL, "cstr pointer is NULL");
-    mpack_expect_str_match(reader, cstr, mpack_strlen(cstr));
-}
-
-/**
- * @}
- */
-
-/**
- * @name Binary Data
- * @{
- */
-
-/**
- * Reads the start of a binary blob, returning its size in bytes.
- *
- * The bytes follow and must be read separately with mpack_read_bytes()
- * or mpack_read_bytes_inplace(). @ref mpack_done_bin() must be called
- * once all bytes have been read.
- *
- * mpack_error_type is raised if the value is not a binary blob.
- */
-uint32_t mpack_expect_bin(mpack_reader_t* reader);
-
-/**
- * Reads the start of a binary blob, raising an error if its length is not
- * at most the given number of bytes.
- *
- * The bytes follow and must be read separately with mpack_read_bytes()
- * or mpack_read_bytes_inplace(). @ref mpack_done_bin() must be called
- * once all bytes have been read.
- *
- * mpack_error_type is raised if the value is not a binary blob or if its
- * length does not match.
- */
-MPACK_INLINE uint32_t mpack_expect_bin_max(mpack_reader_t* reader, uint32_t maxsize) {
-    uint32_t length = mpack_expect_bin(reader);
-    if (length > maxsize) {
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return 0;
-    }
-    return length;
-}
-
-/**
- * Reads the start of a binary blob, raising an error if its length is not
- * exactly the given number of bytes.
- *
- * The bytes follow and must be read separately with mpack_read_bytes()
- * or mpack_read_bytes_inplace(). @ref mpack_done_bin() must be called
- * once all bytes have been read.
- *
- * mpack_error_type is raised if the value is not a binary blob or if its
- * length does not match.
- */
-MPACK_INLINE void mpack_expect_bin_size(mpack_reader_t* reader, uint32_t count) {
-    if (mpack_expect_bin(reader) != count)
-        mpack_reader_flag_error(reader, mpack_error_type);
-}
-
-/**
- * Reads a binary blob into the given buffer, returning its size in bytes.
- *
- * For compatibility, this will accept if the underlying type is string or
- * binary (since in MessagePack 1.0, strings and binary data were combined
- * under the "raw" type which became string in 1.1.)
- */
-size_t mpack_expect_bin_buf(mpack_reader_t* reader, char* buf, size_t size);
-
-/**
- * Reads a binary blob with the given total maximum size, allocating storage for it.
- */
-char* mpack_expect_bin_alloc(mpack_reader_t* reader, size_t maxsize, size_t* size);
-
-/**
- * @}
- */
-
-/**
- * @name Extension Functions
- * @{
- */
-
-#if MPACK_EXTENSIONS
-/**
- * Reads the start of an extension blob, returning its size in bytes and
- * placing the type into @p type.
- *
- * The bytes follow and must be read separately with mpack_read_bytes()
- * or mpack_read_bytes_inplace(). @ref mpack_done_ext() must be called
- * once all bytes have been read.
- *
- * @p type will be a user-defined type in the range [0,127] or a reserved type
- * in the range [-128,-2].
- *
- * mpack_error_type is raised if the value is not an extension blob. The @p
- * type value is zero if an error occurs.
- *
- * @note This cannot be used to match a timestamp. @ref mpack_error_type will
- * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
- * mpack_expect_timestamp_truncate() instead.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @warning Be careful when using reserved types. They may no longer be ext
- * types in the future, and previously valid data containing reserved types may
- * become invalid in the future.
- */
-uint32_t mpack_expect_ext(mpack_reader_t* reader, int8_t* type);
-
-/**
- * Reads the start of an extension blob, raising an error if its length is not
- * at most the given number of bytes and placing the type into @p type.
- *
- * The bytes follow and must be read separately with mpack_read_bytes()
- * or mpack_read_bytes_inplace(). @ref mpack_done_ext() must be called
- * once all bytes have been read.
- *
- * mpack_error_type is raised if the value is not an extension blob or if its
- * length does not match. The @p type value is zero if an error is raised.
- *
- * @p type will be a user-defined type in the range [0,127] or a reserved type
- * in the range [-128,-2].
- *
- * @note This cannot be used to match a timestamp. @ref mpack_error_type will
- * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
- * mpack_expect_timestamp_truncate() instead.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @warning Be careful when using reserved types. They may no longer be ext
- * types in the future, and previously valid data containing reserved types may
- * become invalid in the future.
- *
- * @see mpack_expect_ext()
- */
-MPACK_INLINE uint32_t mpack_expect_ext_max(mpack_reader_t* reader, int8_t* type, uint32_t maxsize) {
-    uint32_t length = mpack_expect_ext(reader, type);
-    if (length > maxsize) {
-        mpack_reader_flag_error(reader, mpack_error_type);
-        return 0;
-    }
-    return length;
-}
-
-/**
- * Reads the start of an extension blob, raising an error if its length is not
- * exactly the given number of bytes and placing the type into @p type.
- *
- * The bytes follow and must be read separately with mpack_read_bytes()
- * or mpack_read_bytes_inplace(). @ref mpack_done_ext() must be called
- * once all bytes have been read.
- *
- * mpack_error_type is raised if the value is not an extension blob or if its
- * length does not match. The @p type value is zero if an error is raised.
- *
- * @p type will be a user-defined type in the range [0,127] or a reserved type
- * in the range [-128,-2].
- *
- * @note This cannot be used to match a timestamp. @ref mpack_error_type will
- * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
- * mpack_expect_timestamp_truncate() instead.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @warning Be careful when using reserved types. They may no longer be ext
- * types in the future, and previously valid data containing reserved types may
- * become invalid in the future.
- *
- * @see mpack_expect_ext()
- */
-MPACK_INLINE void mpack_expect_ext_size(mpack_reader_t* reader, int8_t* type, uint32_t count) {
-    if (mpack_expect_ext(reader, type) != count) {
-        *type = 0;
-        mpack_reader_flag_error(reader, mpack_error_type);
-    }
-}
-
-/**
- * Reads an extension blob into the given buffer, returning its size in bytes
- * and placing the type into @p type.
- *
- * mpack_error_type is raised if the value is not an extension blob or if its
- * length does not match. The @p type value is zero if an error is raised.
- *
- * @p type will be a user-defined type in the range [0,127] or a reserved type
- * in the range [-128,-2].
- *
- * @note This cannot be used to match a timestamp. @ref mpack_error_type will
- * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
- * mpack_expect_timestamp_truncate() instead.
- *
- * @warning Be careful when using reserved types. They may no longer be ext
- * types in the future, and previously valid data containing reserved types may
- * become invalid in the future.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @see mpack_expect_ext()
- */
-size_t mpack_expect_ext_buf(mpack_reader_t* reader, int8_t* type, char* buf, size_t size);
-#endif
-
-#if MPACK_EXTENSIONS && defined(MPACK_MALLOC)
-/**
- * Reads an extension blob with the given total maximum size, allocating
- * storage for it, and placing the type into @p type.
- *
- * mpack_error_type is raised if the value is not an extension blob or if its
- * length does not match. The @p type value is zero if an error is raised.
- *
- * @p type will be a user-defined type in the range [0,127] or a reserved type
- * in the range [-128,-2].
- *
- * @note This cannot be used to match a timestamp. @ref mpack_error_type will
- * be flagged if the value is a timestamp. Use mpack_expect_timestamp() or
- * mpack_expect_timestamp_truncate() instead.
- *
- * @warning Be careful when using reserved types. They may no longer be ext
- * types in the future, and previously valid data containing reserved types may
- * become invalid in the future.
- *
- * @note This requires @ref MPACK_EXTENSIONS and @ref MPACK_MALLOC.
- *
- * @see mpack_expect_ext()
- */
-char* mpack_expect_ext_alloc(mpack_reader_t* reader, int8_t* type, size_t maxsize, size_t* size);
-#endif
-
-/**
- * @}
- */
-
-/**
- * @name Special Functions
- * @{
- */
-
-/**
- * Reads a MessagePack object header (an MPack tag), expecting it to exactly
- * match the given tag.
- *
- * If the type is compound (i.e. is a map, array, string, binary or
- * extension type), additional reads are required to get the contained
- * data, and the corresponding done function must be called when done.
- *
- * @throws mpack_error_type if the tag does not match
- *
- * @see mpack_read_bytes()
- * @see mpack_done_array()
- * @see mpack_done_map()
- * @see mpack_done_str()
- * @see mpack_done_bin()
- * @see mpack_done_ext()
- */
-void mpack_expect_tag(mpack_reader_t* reader, mpack_tag_t tag);
-
-/**
- * Expects a string matching one of the strings in the given array,
- * returning its array index.
- *
- * If the value does not match any of the given strings,
- * @ref mpack_error_type is flagged. Use mpack_expect_enum_optional()
- * if you want to allow other values than the given strings.
- *
- * If any error occurs or the reader is in an error state, @a count
- * is returned.
- *
- * This can be used to quickly parse a string into an enum when the
- * enum values range from 0 to @a count-1. If the last value in the
- * enum is a special "count" value, it can be passed as the count,
- * and the return value can be cast directly to the enum type.
- *
- * @code{.c}
- * typedef enum           { APPLE ,  BANANA ,  ORANGE , COUNT} fruit_t;
- * const char* fruits[] = {"apple", "banana", "orange"};
- *
- * fruit_t fruit = (fruit_t)mpack_expect_enum(reader, fruits, COUNT);
- * @endcode
- *
- * See @ref docs/expect.md for more examples.
- *
- * The maximum string length is the size of the buffer (strings are read in-place.)
- *
- * @param reader The reader
- * @param strings An array of expected strings of length count
- * @param count The number of strings
- * @return The index of the matched string, or @a count in case of error
- */
-size_t mpack_expect_enum(mpack_reader_t* reader, const char* strings[], size_t count);
-
-/**
- * Expects a string matching one of the strings in the given array
- * returning its array index, or @a count if no strings match.
- *
- * If the value is not a string, or it does not match any of the
- * given strings, @a count is returned and no error is flagged.
- *
- * If any error occurs or the reader is in an error state, @a count
- * is returned.
- *
- * This can be used to quickly parse a string into an enum when the
- * enum values range from 0 to @a count-1. If the last value in the
- * enum is a special "count" value, it can be passed as the count,
- * and the return value can be cast directly to the enum type.
- *
- * @code{.c}
- * typedef enum           { APPLE ,  BANANA ,  ORANGE , COUNT} fruit_t;
- * const char* fruits[] = {"apple", "banana", "orange"};
- *
- * fruit_t fruit = (fruit_t)mpack_expect_enum_optional(reader, fruits, COUNT);
- * @endcode
- *
- * See @ref docs/expect.md for more examples.
- *
- * The maximum string length is the size of the buffer (strings are read in-place.)
- *
- * @param reader The reader
- * @param strings An array of expected strings of length count
- * @param count The number of strings
- *
- * @return The index of the matched string, or @a count if it does not
- * match or an error occurs
- */
-size_t mpack_expect_enum_optional(mpack_reader_t* reader, const char* strings[], size_t count);
-
-/**
- * Expects an unsigned integer map key between 0 and count-1, marking it
- * as found in the given bool array and returning it.
- *
- * This is a helper for switching among int keys in a map. It is
- * typically used with an enum to define the key values. It should
- * be called in the expression of a switch() statement. See @ref
- * docs/expect.md for an example.
- *
- * The found array must be cleared before expecting the first key. If the
- * flag for a given key is already set when found (i.e. the map contains a
- * duplicate key), mpack_error_invalid is flagged.
- *
- * If the key is not a non-negative integer, or if the key is @a count or
- * larger, @a count is returned and no error is flagged. If you want an error
- * on unrecognized keys, flag an error in the default case in your switch;
- * otherwise you must call mpack_discard() to discard its content.
- *
- * @param reader The reader
- * @param found An array of bool flags of length count
- * @param count The number of values in the found array, and one more than the
- *              maximum allowed key
- *
- * @see @ref docs/expect.md
- */
-size_t mpack_expect_key_uint(mpack_reader_t* reader, bool found[], size_t count);
-
-/**
- * Expects a string map key matching one of the strings in the given key list,
- * marking it as found in the given bool array and returning its index.
- *
- * This is a helper for switching among string keys in a map. It is
- * typically used with an enum with names matching the strings in the
- * array to define the key indices. It should be called in the expression
- * of a switch() statement. See @ref docs/expect.md for an example.
- *
- * The found array must be cleared before expecting the first key. If the
- * flag for a given key is already set when found (i.e. the map contains a
- * duplicate key), mpack_error_invalid is flagged.
- *
- * If the key is unrecognized, count is returned and no error is flagged. If
- * you want an error on unrecognized keys, flag an error in the default case
- * in your switch; otherwise you must call mpack_discard() to discard its content.
- *
- * The maximum key length is the size of the buffer (keys are read in-place.)
- *
- * @param reader The reader
- * @param keys An array of expected string keys of length count
- * @param found An array of bool flags of length count
- * @param count The number of values in the keys and found arrays
- *
- * @see @ref docs/expect.md
- */
-size_t mpack_expect_key_cstr(mpack_reader_t* reader, const char* keys[],
-        bool found[], size_t count);
-
-/**
- * @}
- */
-
-/**
- * @}
- */
-
-#endif
-
-MPACK_HEADER_END
-
-#endif
-
-
-
-/* mpack/mpack-node.h.h */
-
-/**
- * @file
- *
- * Declares the MPack dynamic Node API.
- */
-
-#ifndef MPACK_NODE_H
-#define MPACK_NODE_H 1
-
-/* #include "mpack-reader.h" */
-
-MPACK_HEADER_START
-
-#if MPACK_NODE
-
-/**
- * @defgroup node Node API
- *
- * The MPack Node API allows you to parse a chunk of MessagePack into a
- * dynamically typed data structure, providing random access to the parsed
- * data.
- *
- * See @ref docs/node.md for examples.
- *
- * @{
- */
-
-/**
- * A handle to node data in a parsed MPack tree.
- *
- * Nodes represent either primitive values or compound types. If a
- * node is a compound type, it contains a pointer to its child nodes,
- * or a pointer to its underlying data.
- *
- * Nodes are immutable.
- *
- * @note @ref mpack_node_t is an opaque reference to the node data, not the
- * node data itself. (It contains pointers to both the node data and the tree.)
- * It is passed by value in the Node API.
- */
-typedef struct mpack_node_t mpack_node_t;
-
-/**
- * The storage for nodes in an MPack tree.
- *
- * You only need to use this if you intend to provide your own storage
- * for nodes instead of letting the tree allocate it.
- *
- * @ref mpack_node_data_t is 16 bytes on most common architectures (32-bit
- * and 64-bit.)
- */
-typedef struct mpack_node_data_t mpack_node_data_t;
-
-/**
- * An MPack tree parser to parse a blob or stream of MessagePack.
- *
- * When a message is parsed, the tree contains a single root node which
- * contains all parsed data. The tree and its nodes are immutable.
- */
-typedef struct mpack_tree_t mpack_tree_t;
-
-/**
- * An error handler function to be called when an error is flagged on
- * the tree.
- *
- * The error handler will only be called once on the first error flagged;
- * any subsequent node reads and errors are ignored, and the tree is
- * permanently in that error state.
- *
- * MPack is safe against non-local jumps out of error handler callbacks.
- * This means you are allowed to longjmp or throw an exception (in C++,
- * Objective-C, or with SEH) out of this callback.
- *
- * Bear in mind when using longjmp that local non-volatile variables that
- * have changed are undefined when setjmp() returns, so you can't put the
- * tree on the stack in the same activation frame as the setjmp without
- * declaring it volatile.
- *
- * You must still eventually destroy the tree. It is not destroyed
- * automatically when an error is flagged. It is safe to destroy the
- * tree within this error callback, but you will either need to perform
- * a non-local jump, or store something in your context to identify
- * that the tree is destroyed since any future accesses to it cause
- * undefined behavior.
- */
-typedef void (*mpack_tree_error_t)(mpack_tree_t* tree, mpack_error_t error);
-
-/**
- * The MPack tree's read function. It should fill the buffer with as many bytes
- * as are immediately available up to the given @c count, returning the number
- * of bytes written to the buffer.
- *
- * In case of error, it should flag an appropriate error on the reader
- * (usually @ref mpack_error_io.)
- *
- * The blocking or non-blocking behaviour of the read should match whether you
- * are using mpack_tree_parse() or mpack_tree_try_parse().
- *
- * If you are using mpack_tree_parse(), the read should block until at least
- * one byte is read. If you return 0, mpack_tree_parse() will raise @ref
- * mpack_error_io.
- *
- * If you are using mpack_tree_try_parse(), the read function can always
- * return 0, and must never block waiting for data (otherwise
- * mpack_tree_try_parse() would be equivalent to mpack_tree_parse().)
- * When you return 0, mpack_tree_try_parse() will return false without flagging
- * an error.
- */
-typedef size_t (*mpack_tree_read_t)(mpack_tree_t* tree, char* buffer, size_t count);
-
-/**
- * A teardown function to be called when the tree is destroyed.
- */
-typedef void (*mpack_tree_teardown_t)(mpack_tree_t* tree);
-
-
-
-/* Hide internals from documentation */
-/** @cond */
-
-struct mpack_node_t {
-    mpack_node_data_t* data;
-    mpack_tree_t* tree;
-};
-
-struct mpack_node_data_t {
-    mpack_type_t type;
-
-    /*
-     * The element count if the type is an array;
-     * the number of key/value pairs if the type is map;
-     * or the number of bytes if the type is str, bin or ext.
-     */
-    uint32_t len;
-
-    union
-    {
-        bool     b; /* The value if the type is bool. */
-        float    f; /* The value if the type is float. */
-        double   d; /* The value if the type is double. */
-        int64_t  i; /* The value if the type is signed int. */
-        uint64_t u; /* The value if the type is unsigned int. */
-        size_t offset; /* The byte offset for str, bin and ext */
-        mpack_node_data_t* children; /* The children for map or array */
-    } value;
-};
-
-typedef struct mpack_tree_page_t {
-    struct mpack_tree_page_t* next;
-    mpack_node_data_t nodes[1]; // variable size
-} mpack_tree_page_t;
-
-typedef enum mpack_tree_parse_state_t {
-    mpack_tree_parse_state_not_started,
-    mpack_tree_parse_state_in_progress,
-    mpack_tree_parse_state_parsed,
-} mpack_tree_parse_state_t;
-
-typedef struct mpack_level_t {
-    mpack_node_data_t* child;
-    size_t left; // children left in level
-} mpack_level_t;
-
-typedef struct mpack_tree_parser_t {
-    mpack_tree_parse_state_t state;
-
-    // We keep track of the number of "possible nodes" left in the data rather
-    // than the number of bytes.
-    //
-    // When a map or array is parsed, we ensure at least one byte for each child
-    // exists and subtract them right away. This ensures that if ever a map or
-    // array declares more elements than could possibly be contained in the data,
-    // we will error out immediately rather than allocating storage for them.
-    //
-    // For example malicious data that repeats 0xDE 0xFF 0xFF (start of a map
-    // with 65536 key-value pairs) would otherwise cause us to run out of
-    // memory. With this, the parser can allocate at most as many nodes as
-    // there are bytes in the data (plus the paging overhead, 12%.) An error
-    // will be flagged immediately if and when there isn't enough data left to
-    // fully read all children of all open compound types on the parsing stack.
-    //
-    // Once an entire message has been parsed (and there are no nodes left to
-    // parse whose bytes have been subtracted), this matches the number of left
-    // over bytes in the data.
-    size_t possible_nodes_left;
-
-    mpack_node_data_t* nodes; // next node in current page/pool
-    size_t nodes_left; // nodes left in current page/pool
-
-    size_t current_node_reserved;
-    size_t level;
-
-    #ifdef MPACK_MALLOC
-    // It's much faster to allocate the initial parsing stack inline within the
-    // parser. We replace it with a heap allocation if we need to grow it.
-    mpack_level_t* stack;
-    size_t stack_capacity;
-    bool stack_owned;
-    mpack_level_t stack_local[MPACK_NODE_INITIAL_DEPTH];
-    #else
-    // Without malloc(), we have to reserve a parsing stack the maximum allowed
-    // parsing depth.
-    mpack_level_t stack[MPACK_NODE_MAX_DEPTH_WITHOUT_MALLOC];
-    #endif
-} mpack_tree_parser_t;
-
-struct mpack_tree_t {
-    mpack_tree_error_t error_fn;    /* Function to call on error */
-    mpack_tree_read_t read_fn;      /* Function to call to read more data */
-    mpack_tree_teardown_t teardown; /* Function to teardown the context on destroy */
-    void* context;                  /* Context for tree callbacks */
-
-    mpack_node_data_t nil_node;     /* a nil node to be returned in case of error */
-    mpack_node_data_t missing_node; /* a missing node to be returned in optional lookups */
-    mpack_error_t error;
-
-    #ifdef MPACK_MALLOC
-    char* buffer;
-    size_t buffer_capacity;
-    #endif
-
-    const char* data;
-    size_t data_length; // length of data (and content of buffer, if used)
-
-    size_t size; // size in bytes of tree (usually matches data_length, but not if tree has trailing data)
-    size_t node_count; // total number of nodes in tree (across all pages)
-
-    size_t max_size;  // maximum message size
-    size_t max_nodes; // maximum nodes in a message
-
-    mpack_tree_parser_t parser;
-    mpack_node_data_t* root;
-
-    mpack_node_data_t* pool; // pool, or NULL if no pool provided
-    size_t pool_count;
-
-    #ifdef MPACK_MALLOC
-    mpack_tree_page_t* next;
-    #endif
-};
-
-// internal functions
-
-MPACK_INLINE mpack_node_t mpack_node(mpack_tree_t* tree, mpack_node_data_t* data) {
-    mpack_node_t node;
-    node.data = data;
-    node.tree = tree;
-    return node;
-}
-
-MPACK_INLINE mpack_node_data_t* mpack_node_child(mpack_node_t node, size_t child) {
-    return node.data->value.children + child;
-}
-
-MPACK_INLINE mpack_node_t mpack_tree_nil_node(mpack_tree_t* tree) {
-    return mpack_node(tree, &tree->nil_node);
-}
-
-MPACK_INLINE mpack_node_t mpack_tree_missing_node(mpack_tree_t* tree) {
-    return mpack_node(tree, &tree->missing_node);
-}
-
-/** @endcond */
-
-
-
-/**
- * @name Tree Initialization
- * @{
- */
-
-#ifdef MPACK_MALLOC
-/**
- * Initializes a tree parser with the given data.
- *
- * Configure the tree if desired, then call mpack_tree_parse() to parse it. The
- * tree will allocate pages of nodes as needed and will free them when
- * destroyed.
- *
- * The tree must be destroyed with mpack_tree_destroy().
- *
- * Any string or blob data types reference the original data, so the given data
- * pointer must remain valid until after the tree is destroyed.
- */
-void mpack_tree_init_data(mpack_tree_t* tree, const char* data, size_t length);
-
-/**
- * Deprecated.
- *
- * \deprecated Renamed to mpack_tree_init_data().
- */
-MPACK_INLINE void mpack_tree_init(mpack_tree_t* tree, const char* data, size_t length) {
-    mpack_tree_init_data(tree, data, length);
-}
-
-/**
- * Initializes a tree parser from an unbounded stream, or a stream of
- * unknown length.
- *
- * The parser can be used to read a single message from a stream of unknown
- * length, or multiple messages from an unbounded stream, allowing it to
- * be used for RPC communication. Call @ref mpack_tree_parse() to parse
- * a message from a blocking stream, or @ref mpack_tree_try_parse() for a
- * non-blocking stream.
- *
- * The stream will use a growable internal buffer to store the most recent
- * message, as well as allocated pages of nodes for the parse tree.
- *
- * Maximum allowances for message size and node count must be specified in this
- * function (since the stream is unbounded.) They can be changed later with
- * @ref mpack_tree_set_limits().
- *
- * @param tree The tree parser
- * @param read_fn The read function
- * @param context The context for the read function
- * @param max_message_size The maximum size of a message in bytes
- * @param max_message_nodes The maximum number of nodes per message. See
- *        @ref mpack_node_data_t for the size of nodes.
- *
- * @see mpack_tree_read_t
- * @see mpack_reader_context()
- */
-void mpack_tree_init_stream(mpack_tree_t* tree, mpack_tree_read_t read_fn, void* context,
-        size_t max_message_size, size_t max_message_nodes);
-#endif
-
-/**
- * Initializes a tree parser with the given data, using the given node data
- * pool to store the results.
- *
- * Configure the tree if desired, then call mpack_tree_parse() to parse it.
- *
- * If the data does not fit in the pool, @ref mpack_error_too_big will be flagged
- * on the tree.
- *
- * The tree must be destroyed with mpack_tree_destroy(), even if parsing fails.
- */
-void mpack_tree_init_pool(mpack_tree_t* tree, const char* data, size_t length,
-        mpack_node_data_t* node_pool, size_t node_pool_count);
-
-/**
- * Initializes an MPack tree directly into an error state. Use this if you
- * are writing a wrapper to another <tt>mpack_tree_init*()</tt> function which
- * can fail its setup.
- */
-void mpack_tree_init_error(mpack_tree_t* tree, mpack_error_t error);
-
-#if MPACK_STDIO
-/**
- * Initializes a tree to parse the given file. The tree must be destroyed with
- * mpack_tree_destroy(), even if parsing fails.
- *
- * The file is opened, loaded fully into memory, and closed before this call
- * returns.
- *
- * @param tree The tree to initialize
- * @param filename The filename passed to fopen() to read the file
- * @param max_bytes The maximum size of file to load, or 0 for unlimited size.
- */
-void mpack_tree_init_filename(mpack_tree_t* tree, const char* filename, size_t max_bytes);
-
-/**
- * Deprecated.
- *
- * \deprecated Renamed to mpack_tree_init_filename().
- */
-MPACK_INLINE void mpack_tree_init_file(mpack_tree_t* tree, const char* filename, size_t max_bytes) {
-    mpack_tree_init_filename(tree, filename, max_bytes);
-}
-
-/**
- * Initializes a tree to parse the given libc FILE. This can be used to
- * read from stdin, or from a file opened separately.
- *
- * The tree must be destroyed with mpack_tree_destroy(), even if parsing fails.
- *
- * The FILE is fully loaded fully into memory (and closed if requested) before
- * this call returns.
- *
- * @param tree The tree to initialize.
- * @param stdfile The FILE.
- * @param max_bytes The maximum size of file to load, or 0 for unlimited size.
- * @param close_when_done If true, fclose() will be called on the FILE when it
- *         is no longer needed. If false, the file will not be closed when
- *         reading is done.
- *
- * @warning The tree will read all data in the FILE before parsing it. If this
- *          is used on stdin, the parser will block until it is closed, even if
- *          a complete message has been written to it!
- */
-void mpack_tree_init_stdfile(mpack_tree_t* tree, FILE* stdfile, size_t max_bytes, bool close_when_done);
-#endif
-
-/**
- * @}
- */
-
-/**
- * @name Tree Functions
- * @{
- */
-
-/**
- * Sets the maximum byte size and maximum number of nodes allowed per message.
- *
- * The default is SIZE_MAX (no limit) unless @ref mpack_tree_init_stream() is
- * called (where maximums are required.)
- *
- * If a pool of nodes is used, the node limit is the lesser of this limit and
- * the pool size.
- *
- * @param tree The tree parser
- * @param max_message_size The maximum size of a message in bytes
- * @param max_message_nodes The maximum number of nodes per message. See
- *        @ref mpack_node_data_t for the size of nodes.
- */
-void mpack_tree_set_limits(mpack_tree_t* tree, size_t max_message_size,
-        size_t max_message_nodes);
-
-/**
- * Parses a MessagePack message into a tree of immutable nodes.
- *
- * If successful, the root node will be available under @ref mpack_tree_root().
- * If not, an appropriate error will be flagged.
- *
- * This can be called repeatedly to parse a series of messages from a data
- * source. When this is called, all previous nodes from this tree and their
- * contents (including the root node) are invalidated.
- *
- * If this is called with a stream (see @ref mpack_tree_init_stream()), the
- * stream must block until data is available. (Otherwise, if this is called on
- * a non-blocking stream, parsing will fail with @ref mpack_error_io when the
- * fill function returns 0.)
- *
- * There is no way to recover a tree in an error state. It must be destroyed.
- */
-void mpack_tree_parse(mpack_tree_t* tree);
-
-/**
- * Attempts to parse a MessagePack message from a non-blocking stream into a
- * tree of immutable nodes.
- *
- * A non-blocking read function must have been passed to the tree in
- * mpack_tree_init_stream().
- *
- * If this returns true, a message is available under
- * @ref mpack_tree_root(). The tree nodes and data will be valid until
- * the next time a parse is started.
- *
- * If this returns false, no message is available, because either not enough
- * data is available yet or an error has occurred. You must check the tree for
- * errors whenever this returns false. If there is no error, you should try
- * again later when more data is available. (You will want to select()/poll()
- * on the underlying socket or use some other asynchronous mechanism to
- * determine when it has data.)
- *
- * There is no way to recover a tree in an error state. It must be destroyed.
- *
- * @see mpack_tree_init_stream()
- */
-bool mpack_tree_try_parse(mpack_tree_t* tree);
-
-/**
- * Returns the root node of the tree, if the tree is not in an error state.
- * Returns a nil node otherwise.
- *
- * @warning You must call mpack_tree_parse() before calling this. If
- * @ref mpack_tree_parse() was never called, the tree will assert.
- */
-mpack_node_t mpack_tree_root(mpack_tree_t* tree);
-
-/**
- * Returns the error state of the tree.
- */
-MPACK_INLINE mpack_error_t mpack_tree_error(mpack_tree_t* tree) {
-    return tree->error;
-}
-
-/**
- * Returns the size in bytes of the current parsed message.
- *
- * If there is something in the buffer after the MessagePack object, this can
- * be used to find it.
- *
- * This is zero if an error occurred during tree parsing (since the
- * portion of the data that the first complete object occupies cannot
- * be determined if the data is invalid or corrupted.)
- */
-MPACK_INLINE size_t mpack_tree_size(mpack_tree_t* tree) {
-    return tree->size;
-}
-
-/**
- * Destroys the tree.
- */
-mpack_error_t mpack_tree_destroy(mpack_tree_t* tree);
-
-/**
- * Sets the custom pointer to pass to the tree callbacks, such as teardown.
- *
- * @param tree The MPack tree.
- * @param context User data to pass to the tree callbacks.
- *
- * @see mpack_reader_context()
- */
-MPACK_INLINE void mpack_tree_set_context(mpack_tree_t* tree, void* context) {
-    tree->context = context;
-}
-
-/**
- * Returns the custom context for tree callbacks.
- *
- * @see mpack_tree_set_context
- * @see mpack_tree_init_stream
- */
-MPACK_INLINE void* mpack_tree_context(mpack_tree_t* tree) {
-    return tree->context;
-}
-
-/**
- * Sets the error function to call when an error is flagged on the tree.
- *
- * This should normally be used with mpack_tree_set_context() to register
- * a custom pointer to pass to the error function.
- *
- * See the definition of mpack_tree_error_t for more information about
- * what you can do from an error callback.
- *
- * @see mpack_tree_error_t
- * @param tree The MPack tree.
- * @param error_fn The function to call when an error is flagged on the tree.
- */
-MPACK_INLINE void mpack_tree_set_error_handler(mpack_tree_t* tree, mpack_tree_error_t error_fn) {
-    tree->error_fn = error_fn;
-}
-
-/**
- * Sets the teardown function to call when the tree is destroyed.
- *
- * This should normally be used with mpack_tree_set_context() to register
- * a custom pointer to pass to the teardown function.
- *
- * @param tree The MPack tree.
- * @param teardown The function to call when the tree is destroyed.
- */
-MPACK_INLINE void mpack_tree_set_teardown(mpack_tree_t* tree, mpack_tree_teardown_t teardown) {
-    tree->teardown = teardown;
-}
-
-/**
- * Places the tree in the given error state, calling the error callback if one
- * is set.
- *
- * This allows you to externally flag errors, for example if you are validating
- * data as you read it.
- *
- * If the tree is already in an error state, this call is ignored and no
- * error callback is called.
- */
-void mpack_tree_flag_error(mpack_tree_t* tree, mpack_error_t error);
-
-/**
- * @}
- */
-
-/**
- * @name Node Core Functions
- * @{
- */
-
-/**
- * Places the node's tree in the given error state, calling the error callback
- * if one is set.
- *
- * This allows you to externally flag errors, for example if you are validating
- * data as you read it.
- *
- * If the tree is already in an error state, this call is ignored and no
- * error callback is called.
- */
-void mpack_node_flag_error(mpack_node_t node, mpack_error_t error);
-
-/**
- * Returns the error state of the node's tree.
- */
-MPACK_INLINE mpack_error_t mpack_node_error(mpack_node_t node) {
-    return mpack_tree_error(node.tree);
-}
-
-/**
- * Returns a tag describing the given node, or a nil tag if the
- * tree is in an error state.
- */
-mpack_tag_t mpack_node_tag(mpack_node_t node);
-
-/** @cond */
-
-#if MPACK_DEBUG && MPACK_STDIO
-/*
- * Converts a node to a pseudo-JSON string for debugging purposes, placing the
- * result in the given buffer with a null-terminator.
- *
- * If the buffer does not have enough space, the result will be truncated (but
- * it is guaranteed to be null-terminated.)
- *
- * This is only available in debug mode, and only if stdio is available (since
- * it uses snprintf().) It's strictly for debugging purposes.
- */
-void mpack_node_print_to_buffer(mpack_node_t node, char* buffer, size_t buffer_size);
-
-/*
- * Converts a node to pseudo-JSON for debugging purposes, calling the given
- * callback as many times as is necessary to output the character data.
- *
- * No null-terminator or trailing newline will be written.
- *
- * This is only available in debug mode, and only if stdio is available (since
- * it uses snprintf().) It's strictly for debugging purposes.
- */
-void mpack_node_print_to_callback(mpack_node_t node, mpack_print_callback_t callback, void* context);
-
-/*
- * Converts a node to pseudo-JSON for debugging purposes
- * and pretty-prints it to the given file.
- *
- * This is only available in debug mode, and only if stdio is available (since
- * it uses snprintf().) It's strictly for debugging purposes.
- */
-void mpack_node_print_to_file(mpack_node_t node, FILE* file);
-
-/*
- * Converts a node to pseudo-JSON for debugging purposes
- * and pretty-prints it to stdout.
- *
- * This is only available in debug mode, and only if stdio is available (since
- * it uses snprintf().) It's strictly for debugging purposes.
- */
-MPACK_INLINE void mpack_node_print_to_stdout(mpack_node_t node) {
-    mpack_node_print_to_file(node, stdout);
-}
-
-/*
- * Deprecated.
- *
- * \deprecated Renamed to mpack_node_print_to_stdout().
- */
-MPACK_INLINE void mpack_node_print(mpack_node_t node) {
-    mpack_node_print_to_stdout(node);
-}
-#endif
-
-/** @endcond */
-
-/**
- * @}
- */
-
-/**
- * @name Node Primitive Value Functions
- * @{
- */
-
-/**
- * Returns the type of the node.
- */
-mpack_type_t mpack_node_type(mpack_node_t node);
-
-/**
- * Returns true if the given node is a nil node; false otherwise.
- *
- * To ensure that a node is nil and flag an error otherwise, use
- * mpack_node_nil().
- */
-bool mpack_node_is_nil(mpack_node_t node);
-
-/**
- * Returns true if the given node handle indicates a missing node; false otherwise.
- *
- * To ensure that a node is missing and flag an error otherwise, use
- * mpack_node_missing().
- */
-bool mpack_node_is_missing(mpack_node_t node);
-
-/**
- * Checks that the given node is of nil type, raising @ref mpack_error_type
- * otherwise.
- *
- * Use mpack_node_is_nil() to return whether the node is nil.
- */
-void mpack_node_nil(mpack_node_t node);
-
-/**
- * Checks that the given node indicates a missing node, raising @ref
- * mpack_error_type otherwise.
- *
- * Use mpack_node_is_missing() to return whether the node is missing.
- */
-void mpack_node_missing(mpack_node_t node);
-
-/**
- * Returns the bool value of the node. If this node is not of the correct
- * type, false is returned and mpack_error_type is raised.
- */
-bool mpack_node_bool(mpack_node_t node);
-
-/**
- * Checks if the given node is of bool type with value true, raising
- * mpack_error_type otherwise.
- */
-void mpack_node_true(mpack_node_t node);
-
-/**
- * Checks if the given node is of bool type with value false, raising
- * mpack_error_type otherwise.
- */
-void mpack_node_false(mpack_node_t node);
-
-/**
- * Returns the 8-bit unsigned value of the node. If this node is not
- * of a compatible type, @ref mpack_error_type is raised and zero is returned.
- */
-uint8_t mpack_node_u8(mpack_node_t node);
-
-/**
- * Returns the 8-bit signed value of the node. If this node is not
- * of a compatible type, @ref mpack_error_type is raised and zero is returned.
- */
-int8_t mpack_node_i8(mpack_node_t node);
-
-/**
- * Returns the 16-bit unsigned value of the node. If this node is not
- * of a compatible type, @ref mpack_error_type is raised and zero is returned.
- */
-uint16_t mpack_node_u16(mpack_node_t node);
-
-/**
- * Returns the 16-bit signed value of the node. If this node is not
- * of a compatible type, @ref mpack_error_type is raised and zero is returned.
- */
-int16_t mpack_node_i16(mpack_node_t node);
-
-/**
- * Returns the 32-bit unsigned value of the node. If this node is not
- * of a compatible type, @ref mpack_error_type is raised and zero is returned.
- */
-uint32_t mpack_node_u32(mpack_node_t node);
-
-/**
- * Returns the 32-bit signed value of the node. If this node is not
- * of a compatible type, @ref mpack_error_type is raised and zero is returned.
- */
-int32_t mpack_node_i32(mpack_node_t node);
-
-/**
- * Returns the 64-bit unsigned value of the node. If this node is not
- * of a compatible type, @ref mpack_error_type is raised, and zero is returned.
- */
-uint64_t mpack_node_u64(mpack_node_t node);
-
-/**
- * Returns the 64-bit signed value of the node. If this node is not
- * of a compatible type, @ref mpack_error_type is raised and zero is returned.
- */
-int64_t mpack_node_i64(mpack_node_t node);
-
-/**
- * Returns the unsigned int value of the node.
- *
- * Returns zero if an error occurs.
- *
- * @throws mpack_error_type If the node is not an integer type or does not fit in the range of an unsigned int
- */
-unsigned int mpack_node_uint(mpack_node_t node);
-
-/**
- * Returns the int value of the node.
- *
- * Returns zero if an error occurs.
- *
- * @throws mpack_error_type If the node is not an integer type or does not fit in the range of an int
- */
-int mpack_node_int(mpack_node_t node);
-
-/**
- * Returns the float value of the node. The underlying value can be an
- * integer, float or double; the value is converted to a float.
- *
- * @note Reading a double or a large integer with this function can incur a
- * loss of precision.
- *
- * @throws mpack_error_type if the underlying value is not a float, double or integer.
- */
-float mpack_node_float(mpack_node_t node);
-
-/**
- * Returns the double value of the node. The underlying value can be an
- * integer, float or double; the value is converted to a double.
- *
- * @note Reading a very large integer with this function can incur a
- * loss of precision.
- *
- * @throws mpack_error_type if the underlying value is not a float, double or integer.
- */
-double mpack_node_double(mpack_node_t node);
-
-/**
- * Returns the float value of the node. The underlying value must be a float,
- * not a double or an integer. This ensures no loss of precision can occur.
- *
- * @throws mpack_error_type if the underlying value is not a float.
- */
-float mpack_node_float_strict(mpack_node_t node);
-
-/**
- * Returns the double value of the node. The underlying value must be a float
- * or double, not an integer. This ensures no loss of precision can occur.
- *
- * @throws mpack_error_type if the underlying value is not a float or double.
- */
-double mpack_node_double_strict(mpack_node_t node);
-
-#if MPACK_EXTENSIONS
-/**
- * Returns a timestamp.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @throws mpack_error_type if the underlying value is not a timestamp.
- */
-mpack_timestamp_t mpack_node_timestamp(mpack_node_t node);
-
-/**
- * Returns a timestamp's (signed) seconds since 1970-01-01T00:00:00Z.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @throws mpack_error_type if the underlying value is not a timestamp.
- */
-int64_t mpack_node_timestamp_seconds(mpack_node_t node);
-
-/**
- * Returns a timestamp's additional nanoseconds.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- *
- * @return A nanosecond count between 0 and 999,999,999 inclusive.
- * @throws mpack_error_type if the underlying value is not a timestamp.
- */
-uint32_t mpack_node_timestamp_nanoseconds(mpack_node_t node);
-#endif
-
-/**
- * @}
- */
-
-/**
- * @name Node String and Data Functions
- * @{
- */
-
-/**
- * Checks that the given node contains a valid UTF-8 string.
- *
- * If the string is invalid, this flags an error, which would cause subsequent calls
- * to mpack_node_str() to return NULL and mpack_node_strlen() to return zero. So you
- * can check the node for error immediately after calling this, or you can call those
- * functions to use the data anyway and check for errors later.
- *
- * @throws mpack_error_type If this node is not a string or does not contain valid UTF-8.
- *
- * @param node The string node to test
- *
- * @see mpack_node_str()
- * @see mpack_node_strlen()
- */
-void mpack_node_check_utf8(mpack_node_t node);
-
-/**
- * Checks that the given node contains a valid UTF-8 string with no NUL bytes.
- *
- * This does not check that the string has a null-terminator! It only checks whether
- * the string could safely be represented as a C-string by appending a null-terminator.
- * (If the string does already contain a null-terminator, this will flag an error.)
- *
- * This is performed automatically by other UTF-8 cstr helper functions. Only
- * call this if you will do something else with the data directly, but you still
- * want to ensure it will be valid as a UTF-8 C-string.
- *
- * @throws mpack_error_type If this node is not a string, does not contain valid UTF-8,
- *     or contains a NUL byte.
- *
- * @param node The string node to test
- *
- * @see mpack_node_str()
- * @see mpack_node_strlen()
- * @see mpack_node_copy_utf8_cstr()
- * @see mpack_node_utf8_cstr_alloc()
- */
-void mpack_node_check_utf8_cstr(mpack_node_t node);
-
-#if MPACK_EXTENSIONS
-/**
- * Returns the extension type of the given ext node.
- *
- * This returns zero if the tree is in an error state.
- *
- * @note This requires @ref MPACK_EXTENSIONS.
- */
-int8_t mpack_node_exttype(mpack_node_t node);
-#endif
-
-/**
- * Returns the number of bytes in the given bin node.
- *
- * This returns zero if the tree is in an error state.
- *
- * If this node is not a bin, @ref mpack_error_type is raised and zero is returned.
- */
-size_t mpack_node_bin_size(mpack_node_t node);
-
-/**
- * Returns the length of the given str, bin or ext node.
- *
- * This returns zero if the tree is in an error state.
- *
- * If this node is not a str, bin or map, @ref mpack_error_type is raised and zero
- * is returned.
- */
-uint32_t mpack_node_data_len(mpack_node_t node);
-
-/**
- * Returns the length in bytes of the given string node. This does not
- * include any null-terminator.
- *
- * This returns zero if the tree is in an error state.
- *
- * If this node is not a str, @ref mpack_error_type is raised and zero is returned.
- */
-size_t mpack_node_strlen(mpack_node_t node);
-
-/**
- * Returns a pointer to the data contained by this node, ensuring the node is a
- * string.
- *
- * @warning Strings are not null-terminated! Use one of the cstr functions
- * to get a null-terminated string.
- *
- * The pointer is valid as long as the data backing the tree is valid.
- *
- * If this node is not a string, @ref mpack_error_type is raised and @c NULL is returned.
- *
- * @see mpack_node_copy_cstr()
- * @see mpack_node_cstr_alloc()
- * @see mpack_node_utf8_cstr_alloc()
- */
-const char* mpack_node_str(mpack_node_t node);
-
-/**
- * Returns a pointer to the data contained by this node.
- *
- * @note Strings are not null-terminated! Use one of the cstr functions
- * to get a null-terminated string.
- *
- * The pointer is valid as long as the data backing the tree is valid.
- *
- * If this node is not of a str, bin or map, @ref mpack_error_type is raised, and
- * @c NULL is returned.
- *
- * @see mpack_node_copy_cstr()
- * @see mpack_node_cstr_alloc()
- * @see mpack_node_utf8_cstr_alloc()
- */
-const char* mpack_node_data(mpack_node_t node);
-
-/**
- * Returns a pointer to the data contained by this bin node.
- *
- * The pointer is valid as long as the data backing the tree is valid.
- *
- * If this node is not a bin, @ref mpack_error_type is raised and @c NULL is
- * returned.
- */
-const char* mpack_node_bin_data(mpack_node_t node);
-
-/**
- * Copies the bytes contained by this node into the given buffer, returning the
- * number of bytes in the node.
- *
- * @throws mpack_error_type If this node is not a str, bin or ext type
- * @throws mpack_error_too_big If the string does not fit in the given buffer
- *
- * @param node The string node from which to copy data
- * @param buffer A buffer in which to copy the node's bytes
- * @param bufsize The size of the given buffer
- *
- * @return The number of bytes in the node, or zero if an error occurs.
- */
-size_t mpack_node_copy_data(mpack_node_t node, char* buffer, size_t bufsize);
-
-/**
- * Checks that the given node contains a valid UTF-8 string and copies the
- * string into the given buffer, returning the number of bytes in the string.
- *
- * @throws mpack_error_type If this node is not a string
- * @throws mpack_error_too_big If the string does not fit in the given buffer
- *
- * @param node The string node from which to copy data
- * @param buffer A buffer in which to copy the node's bytes
- * @param bufsize The size of the given buffer
- *
- * @return The number of bytes in the node, or zero if an error occurs.
- */
-size_t mpack_node_copy_utf8(mpack_node_t node, char* buffer, size_t bufsize);
-
-/**
- * Checks that the given node contains a string with no NUL bytes, copies the string
- * into the given buffer, and adds a null terminator.
- *
- * If this node is not of a string type, @ref mpack_error_type is raised. If the string
- * does not fit, @ref mpack_error_data is raised.
- *
- * If any error occurs, the buffer will contain an empty null-terminated string.
- *
- * @param node The string node from which to copy data
- * @param buffer A buffer in which to copy the node's string
- * @param size The size of the given buffer
- */
-void mpack_node_copy_cstr(mpack_node_t node, char* buffer, size_t size);
-
-/**
- * Checks that the given node contains a valid UTF-8 string with no NUL bytes,
- * copies the string into the given buffer, and adds a null terminator.
- *
- * If this node is not of a string type, @ref mpack_error_type is raised. If the string
- * does not fit, @ref mpack_error_data is raised.
- *
- * If any error occurs, the buffer will contain an empty null-terminated string.
- *
- * @param node The string node from which to copy data
- * @param buffer A buffer in which to copy the node's string
- * @param size The size of the given buffer
- */
-void mpack_node_copy_utf8_cstr(mpack_node_t node, char* buffer, size_t size);
-
-#ifdef MPACK_MALLOC
-/**
- * Allocates a new chunk of data using MPACK_MALLOC() with the bytes
- * contained by this node.
- *
- * The allocated data must be freed with MPACK_FREE() (or simply free()
- * if MPack's allocator hasn't been customized.)
- *
- * @throws mpack_error_type If this node is not a str, bin or ext type
- * @throws mpack_error_too_big If the size of the data is larger than the
- *     given maximum size
- * @throws mpack_error_memory If an allocation failure occurs
- *
- * @param node The node from which to allocate and copy data
- * @param maxsize The maximum size to allocate
- *
- * @return The allocated data, or NULL if any error occurs.
- */
-char* mpack_node_data_alloc(mpack_node_t node, size_t maxsize);
-
-/**
- * Allocates a new null-terminated string using MPACK_MALLOC() with the string
- * contained by this node.
- *
- * The allocated string must be freed with MPACK_FREE() (or simply free()
- * if MPack's allocator hasn't been customized.)
- *
- * @throws mpack_error_type If this node is not a string or contains NUL bytes
- * @throws mpack_error_too_big If the size of the string plus null-terminator
- *     is larger than the given maximum size
- * @throws mpack_error_memory If an allocation failure occurs
- *
- * @param node The node from which to allocate and copy string data
- * @param maxsize The maximum size to allocate, including the null-terminator
- *
- * @return The allocated string, or NULL if any error occurs.
- */
-char* mpack_node_cstr_alloc(mpack_node_t node, size_t maxsize);
-
-/**
- * Allocates a new null-terminated string using MPACK_MALLOC() with the UTF-8
- * string contained by this node.
- *
- * The allocated string must be freed with MPACK_FREE() (or simply free()
- * if MPack's allocator hasn't been customized.)
- *
- * @throws mpack_error_type If this node is not a string, is not valid UTF-8,
- *     or contains NUL bytes
- * @throws mpack_error_too_big If the size of the string plus null-terminator
- *     is larger than the given maximum size
- * @throws mpack_error_memory If an allocation failure occurs
- *
- * @param node The node from which to allocate and copy string data
- * @param maxsize The maximum size to allocate, including the null-terminator
- *
- * @return The allocated string, or NULL if any error occurs.
- */
-char* mpack_node_utf8_cstr_alloc(mpack_node_t node, size_t maxsize);
-#endif
-
-/**
- * Searches the given string array for a string matching the given
- * node and returns its index.
- *
- * If the node does not match any of the given strings,
- * @ref mpack_error_type is flagged. Use mpack_node_enum_optional()
- * if you want to allow values other than the given strings.
- *
- * If any error occurs or if the tree is in an error state, @a count
- * is returned.
- *
- * This can be used to quickly parse a string into an enum when the
- * enum values range from 0 to @a count-1. If the last value in the
- * enum is a special "count" value, it can be passed as the count,
- * and the return value can be cast directly to the enum type.
- *
- * @code{.c}
- * typedef enum           { APPLE ,  BANANA ,  ORANGE , COUNT} fruit_t;
- * const char* fruits[] = {"apple", "banana", "orange"};
- *
- * fruit_t fruit = (fruit_t)mpack_node_enum(node, fruits, COUNT);
- * @endcode
- *
- * @param node The node
- * @param strings An array of expected strings of length count
- * @param count The number of strings
- * @return The index of the matched string, or @a count in case of error
- */
-size_t mpack_node_enum(mpack_node_t node, const char* strings[], size_t count);
-
-/**
- * Searches the given string array for a string matching the given node,
- * returning its index or @a count if no strings match.
- *
- * If the value is not a string, or it does not match any of the
- * given strings, @a count is returned and no error is flagged.
- *
- * If any error occurs or if the tree is in an error state, @a count
- * is returned.
- *
- * This can be used to quickly parse a string into an enum when the
- * enum values range from 0 to @a count-1. If the last value in the
- * enum is a special "count" value, it can be passed as the count,
- * and the return value can be cast directly to the enum type.
- *
- * @code{.c}
- * typedef enum           { APPLE ,  BANANA ,  ORANGE , COUNT} fruit_t;
- * const char* fruits[] = {"apple", "banana", "orange"};
- *
- * fruit_t fruit = (fruit_t)mpack_node_enum_optional(node, fruits, COUNT);
- * @endcode
- *
- * @param node The node
- * @param strings An array of expected strings of length count
- * @param count The number of strings
- * @return The index of the matched string, or @a count in case of error
- */
-size_t mpack_node_enum_optional(mpack_node_t node, const char* strings[], size_t count);
-
-/**
- * @}
- */
-
-/**
- * @name Compound Node Functions
- * @{
- */
-
-/**
- * Returns the length of the given array node. Raises mpack_error_type
- * and returns 0 if the given node is not an array.
- */
-size_t mpack_node_array_length(mpack_node_t node);
-
-/**
- * Returns the node in the given array at the given index. If the node
- * is not an array, @ref mpack_error_type is raised and a nil node is returned.
- * If the given index is out of bounds, @ref mpack_error_data is raised and
- * a nil node is returned.
- */
-mpack_node_t mpack_node_array_at(mpack_node_t node, size_t index);
-
-/**
- * Returns the number of key/value pairs in the given map node. Raises
- * mpack_error_type and returns 0 if the given node is not a map.
- */
-size_t mpack_node_map_count(mpack_node_t node);
-
-/**
- * Returns the key node in the given map at the given index.
- *
- * A nil node is returned in case of error.
- *
- * @throws mpack_error_type if the node is not a map
- * @throws mpack_error_data if the given index is out of bounds
- */
-mpack_node_t mpack_node_map_key_at(mpack_node_t node, size_t index);
-
-/**
- * Returns the value node in the given map at the given index.
- *
- * A nil node is returned in case of error.
- *
- * @throws mpack_error_type if the node is not a map
- * @throws mpack_error_data if the given index is out of bounds
- */
-mpack_node_t mpack_node_map_value_at(mpack_node_t node, size_t index);
-
-/**
- * Returns the value node in the given map for the given integer key.
- *
- * The key must exist within the map. Use mpack_node_map_int_optional() to
- * check for optional keys.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node does not contain exactly one entry with the given key
- *
- * @return The value node for the given key, or a nil node in case of error
- */
-mpack_node_t mpack_node_map_int(mpack_node_t node, int64_t num);
-
-/**
- * Returns the value node in the given map for the given integer key, or a
- * missing node if the map does not contain the given key.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node contains more than one entry with the given key
- *
- * @return The value node for the given key, or a missing node if the key does
- *         not exist, or a nil node in case of error
- *
- * @see mpack_node_is_missing()
- */
-mpack_node_t mpack_node_map_int_optional(mpack_node_t node, int64_t num);
-
-/**
- * Returns the value node in the given map for the given unsigned integer key.
- *
- * The key must exist within the map. Use mpack_node_map_uint_optional() to
- * check for optional keys.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node does not contain exactly one entry with the given key
- *
- * @return The value node for the given key, or a nil node in case of error
- */
-mpack_node_t mpack_node_map_uint(mpack_node_t node, uint64_t num);
-
-/**
- * Returns the value node in the given map for the given unsigned integer
- * key, or a nil node if the map does not contain the given key.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node contains more than one entry with the given key
- *
- * @return The value node for the given key, or a missing node if the key does
- *         not exist, or a nil node in case of error
- *
- * @see mpack_node_is_missing()
- */
-mpack_node_t mpack_node_map_uint_optional(mpack_node_t node, uint64_t num);
-
-/**
- * Returns the value node in the given map for the given string key.
- *
- * The key must exist within the map. Use mpack_node_map_str_optional() to
- * check for optional keys.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node does not contain exactly one entry with the given key
- *
- * @return The value node for the given key, or a nil node in case of error
- */
-mpack_node_t mpack_node_map_str(mpack_node_t node, const char* str, size_t length);
-
-/**
- * Returns the value node in the given map for the given string key, or a nil
- * node if the map does not contain the given key.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node contains more than one entry with the given key
- *
- * @return The value node for the given key, or a missing node if the key does
- *         not exist, or a nil node in case of error
- *
- * @see mpack_node_is_missing()
- */
-mpack_node_t mpack_node_map_str_optional(mpack_node_t node, const char* str, size_t length);
-
-/**
- * Returns the value node in the given map for the given null-terminated
- * string key.
- *
- * The key must exist within the map. Use mpack_node_map_cstr_optional() to
- * check for optional keys.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node does not contain exactly one entry with the given key
- *
- * @return The value node for the given key, or a nil node in case of error
- */
-mpack_node_t mpack_node_map_cstr(mpack_node_t node, const char* cstr);
-
-/**
- * Returns the value node in the given map for the given null-terminated
- * string key, or a nil node if the map does not contain the given key.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node contains more than one entry with the given key
- *
- * @return The value node for the given key, or a missing node if the key does
- *         not exist, or a nil node in case of error
- *
- * @see mpack_node_is_missing()
- */
-mpack_node_t mpack_node_map_cstr_optional(mpack_node_t node, const char* cstr);
-
-/**
- * Returns true if the given node map contains exactly one entry with the
- * given integer key.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node contains more than one entry with the given key
- */
-bool mpack_node_map_contains_int(mpack_node_t node, int64_t num);
-
-/**
- * Returns true if the given node map contains exactly one entry with the
- * given unsigned integer key.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node contains more than one entry with the given key
- */
-bool mpack_node_map_contains_uint(mpack_node_t node, uint64_t num);
-
-/**
- * Returns true if the given node map contains exactly one entry with the
- * given string key.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node contains more than one entry with the given key
- */
-bool mpack_node_map_contains_str(mpack_node_t node, const char* str, size_t length);
-
-/**
- * Returns true if the given node map contains exactly one entry with the
- * given null-terminated string key.
- *
- * The key must be unique. An error is flagged if the node has multiple
- * entries with the given key.
- *
- * @throws mpack_error_type If the node is not a map
- * @throws mpack_error_data If the node contains more than one entry with the given key
- */
-bool mpack_node_map_contains_cstr(mpack_node_t node, const char* cstr);
-
-/**
- * @}
- */
-
-/**
- * @}
- */
-
-#endif
-
-MPACK_HEADER_END
-
-#endif
-
-
-#endif
-
diff --git a/version.h.in b/version.h.in
deleted file mode 100644
index 252b6fb..0000000
--- a/version.h.in
+++ /dev/null
@@ -1 +0,0 @@
-#define EMGAUWA_CONTROLLER_VERSION "@CMAKE_PROJECT_VERSION@"