+
+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:
+ 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", ctx, (int) (strlen(str) - 1), str));
+ (void) file;
+ (void) line;
+}
+
+struct mg_ssl_if_ctx {
+ mbedtls_ssl_config *conf;
+ mbedtls_ssl_context *ssl;
+ mbedtls_x509_crt *cert;
+ mbedtls_pk_context *key;
+ mbedtls_x509_crt *ca_cert;
+ struct mbuf cipher_suites;
+};
+
+/* 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() {
+}
+
+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 = 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);
+
+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", 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 = 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;
+ }
+
+ if (!(nc->flags & MG_F_LISTENING)) {
+ ctx->ssl = 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;
+ }
+ }
+
+ nc->flags |= MG_F_SSL;
+
+ return MG_SSL_OK;
+}
+
+#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
+int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len);
+int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len);
+#else
+static int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) {
+ struct mg_connection *nc = (struct mg_connection *) ctx;
+ int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0);
+ DBG(("%p %d -> %d", nc, (int) len, n));
+ if (n >= 0) return n;
+ n = mg_get_errno();
+ return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_WRITE : -1);
+}
+
+static int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) {
+ struct mg_connection *nc = (struct mg_connection *) ctx;
+ int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0);
+ DBG(("%p %d <- %d", nc, (int) len, n));
+ if (n >= 0) return n;
+ n = mg_get_errno();
+ return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_READ : -1);
+}
+#endif
+
+static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc,
+ int ret) {
+ if (ret == MBEDTLS_ERR_SSL_WANT_READ) return MG_SSL_WANT_READ;
+ if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) return MG_SSL_WANT_WRITE;
+ if (ret !=
+ MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { /* CLOSE_NOTIFY = Normal shutdown */
+ LOG(LL_ERROR, ("%p SSL error: %d", nc, ret));
+ }
+ nc->err = ret;
+ nc->flags |= MG_F_CLOSE_IMMEDIATELY;
+ return MG_SSL_ERROR;
+}
+
+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;
+ }
+ 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;
+ }
+}
+
+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, ssl_socket_send, ssl_socket_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 buf_size) {
+ struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
+ int n = mbedtls_ssl_read(ctx->ssl, buf, buf_size);
+ DBG(("%p %d -> %d", nc, (int) buf_size, 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 *data, size_t len) {
+ struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
+ int n = mbedtls_ssl_write(ctx->ssl, data, len);
+ DBG(("%p %d -> %d", nc, (int) len, n));
+ if (n < 0) return mg_ssl_if_mbed_err(nc, n);
+ return n;
+}
+
+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);
+ }
+ mg_ssl_if_mbed_free_certs_and_keys(ctx);
+ if (ctx->conf != NULL) {
+ mbedtls_ssl_config_free(ctx->conf);
+ MG_FREE(ctx->conf);
+ }
+ 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) {
+ return MG_SSL_OK;
+ }
+ ctx->ca_cert = 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);
+ 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 = MG_CALLOC(1, sizeof(*ctx->cert));
+ mbedtls_x509_crt_init(ctx->cert);
+ ctx->key = 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[] = {
+ MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
+ MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_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, 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;
+ char *e, 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));
+ 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;
+}
+
+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(¶ms, 0, sizeof(params));
+ params.cert = cert;
+ params.ca_cert = ca_cert;
+ if (mg_ssl_if_conn_init(nc, ¶ms, &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 "mongoose/src/multithreading.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/util.h" */
+
+#if MG_ENABLE_THREADS
+
+static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p);
+
+/*
+ * This thread function executes user event handler.
+ * It runs an event manager that has only one connection, until that
+ * connection is alive.
+ */
+static void *per_connection_thread_function(void *param) {
+ struct mg_connection *c = (struct mg_connection *) param;
+ struct mg_mgr m;
+ /* mgr_data can be used subsequently, store its value */
+ int poll_timeout = (intptr_t) c->mgr_data;
+
+ mg_mgr_init(&m, NULL);
+ mg_add_conn(&m, c);
+ mg_call(c, NULL, MG_EV_ACCEPT, &c->sa);
+
+ while (m.active_connections != NULL) {
+ mg_mgr_poll(&m, poll_timeout ? poll_timeout : 1000);
+ }
+ mg_mgr_free(&m);
+
+ return param;
+}
+
+static void link_conns(struct mg_connection *c1, struct mg_connection *c2) {
+ c1->priv_2 = c2;
+ c2->priv_2 = c1;
+}
+
+static void unlink_conns(struct mg_connection *c) {
+ struct mg_connection *peer = (struct mg_connection *) c->priv_2;
+ if (peer != NULL) {
+ peer->flags |= MG_F_SEND_AND_CLOSE;
+ peer->priv_2 = NULL;
+ }
+ c->priv_2 = NULL;
+}
+
+static void forwarder_ev_handler(struct mg_connection *c, int ev, void *p) {
+ (void) p;
+ if (ev == MG_EV_RECV && c->priv_2) {
+ mg_forward(c, (struct mg_connection *) c->priv_2);
+ } else if (ev == MG_EV_CLOSE) {
+ unlink_conns(c);
+ }
+}
+
+static void spawn_handling_thread(struct mg_connection *nc) {
+ struct mg_mgr dummy;
+ sock_t sp[2];
+ struct mg_connection *c[2];
+ int poll_timeout;
+ /*
+ * Create a socket pair, and wrap each socket into the connection with
+ * dummy event manager.
+ * c[0] stays in this thread, c[1] goes to another thread.
+ */
+ mg_mgr_init(&dummy, NULL);
+ mg_socketpair(sp, SOCK_STREAM);
+
+ c[0] = mg_add_sock(&dummy, sp[0], forwarder_ev_handler);
+ c[1] = mg_add_sock(&dummy, sp[1], nc->listener->priv_1.f);
+
+ /* link_conns replaces priv_2, storing its value */
+ poll_timeout = (intptr_t) nc->priv_2;
+
+ /* Interlink client connection with c[0] */
+ link_conns(c[0], nc);
+
+ /*
+ * Switch c[0] manager from the dummy one to the real one. c[1] manager
+ * will be set in another thread, allocated on stack of that thread.
+ */
+ mg_add_conn(nc->mgr, c[0]);
+
+ /*
+ * Dress c[1] as nc.
+ * TODO(lsm): code in accept_conn() looks similar. Refactor.
+ */
+ c[1]->listener = nc->listener;
+ c[1]->proto_handler = nc->proto_handler;
+ c[1]->user_data = nc->user_data;
+ c[1]->sa = nc->sa;
+ c[1]->flags = nc->flags;
+
+ /* priv_2 is used, so, put timeout to mgr_data */
+ c[1]->mgr_data = (void *) (intptr_t) poll_timeout;
+
+ mg_start_thread(per_connection_thread_function, c[1]);
+}
+
+static void multithreaded_ev_handler(struct mg_connection *c, int ev, void *p) {
+ (void) p;
+ if (ev == MG_EV_ACCEPT) {
+ spawn_handling_thread(c);
+ c->handler = forwarder_ev_handler;
+ }
+}
+
+void mg_enable_multithreading_opt(struct mg_connection *nc,
+ struct mg_multithreading_opts opts) {
+ /* Wrap user event handler into our multithreaded_ev_handler */
+ nc->priv_1.f = nc->handler;
+ /*
+ * We put timeout to `priv_2` member of the main
+ * (listening) connection, mt is not enabled yet,
+ * and this member is not used
+ */
+ nc->priv_2 = (void *) (intptr_t) opts.poll_timeout;
+ nc->handler = multithreaded_ev_handler;
+}
+
+void mg_enable_multithreading(struct mg_connection *nc) {
+ struct mg_multithreading_opts opts;
+ memset(&opts, 0, sizeof(opts));
+ mg_enable_multithreading_opt(nc, opts);
+}
+
+#endif
+#ifdef MG_MODULE_LINES
+#line 1 "mongoose/src/uri.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/uri.h" */
+
+/*
+ * scan string until `sep`, 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, char sep,
+ struct mg_str *res) {
+ res->p = *p;
+ for (; *p < end; (*p)++) {
+ if (**p == sep) {
+ break;
+ }
+ }
+ res->len = (*p) - res->p;
+ if (*p < end) (*p)++;
+}
+
+int mg_parse_uri(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`
+ * - `xxxx/path`
+ */
+ 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 += 2; /* point to last separator char */
+ } else {
+ rhost.p = uri.p;
+ rhost.len = p - uri.p;
+ state = P_PORT;
+ }
+ break;
+ case P_USER_INFO:
+ p++;
+ ruser_info.p = p;
+ for (; p < end; p++) {
+ if (*p == '@') {
+ state = P_HOST;
+ break;
+ } else if (*p == '/') {
+ break;
+ }
+ }
+ if (p == end || *p == '/') {
+ /* backtrack and parse as host */
+ state = P_HOST;
+ p = ruser_info.p;
+ }
+ ruser_info.len = p - ruser_info.p;
+ break;
+ case P_HOST:
+ if (*p == '@') p++;
+ rhost.p = p;
+ for (; p < end; p++) {
+ if (*p == ':') {
+ state = P_PORT;
+ break;
+ } else if (*p == '/') {
+ state = P_REST;
+ break;
+ }
+ }
+ rhost.len = p - rhost.p;
+ 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);
+ parse_uri_component(&p, end, '#', &rquery);
+ parse_uri_component(&p, end, '\0', &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;
+}
+#ifdef MG_MODULE_LINES
+#line 1 "mongoose/src/http.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if MG_ENABLE_HTTP
+
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/util.h" */
+/* Amalgamated: #include "common/sha1.h" */
+/* Amalgamated: #include "common/md5.h" */
+
+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;
+ const char *name;
+ size_t name_len;
+ mg_event_handler_t handler;
+};
+
+enum mg_http_multipart_stream_state {
+ MPS_BEGIN,
+ MPS_WAITING_FOR_BOUNDARY,
+ MPS_WAITING_FOR_CHUNK,
+ MPS_GOT_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;
+ int prev_io_len;
+ enum mg_http_multipart_stream_state state;
+ int processing_part;
+};
+
+struct mg_reverse_proxy_data {
+ struct mg_connection *linked_conn;
+};
+
+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
+ 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;
+};
+
+static void mg_http_conn_destructor(void *proto_data);
+struct mg_connection *mg_connect_http_base(
+ struct mg_mgr *mgr, mg_event_handler_t ev_handler,
+ struct mg_connect_opts opts, const char *schema, const char *schema_ssl,
+ const char *url, const char **path, char **user, char **pass, char **addr);
+
+static struct mg_http_proto_data *mg_http_get_proto_data(
+ struct mg_connection *c) {
+ if (c->proto_data == NULL) {
+ c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
+ c->proto_data_destructor = mg_http_conn_destructor;
+ }
+
+ 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) {
+ free((void *) mp->boundary);
+ free((void *) mp->var_name);
+ 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;
+ free((void *) current->name);
+ 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_conn_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);
+ 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_type(const char *path, const char *dflt,
+ const struct mg_serve_http_opts *opts) {
+ const char *ext, *overrides;
+ size_t i, path_len;
+ struct mg_str r, k, v;
+
+ path_len = strlen(path);
+
+ overrides = opts->custom_mime_types;
+ while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
+ ext = path + (path_len - k.len);
+ if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
+ return v;
+ }
+ }
+
+ for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
+ ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len);
+ if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
+ mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) {
+ r.p = mg_static_builtin_mime_types[i].mime_type;
+ r.len = strlen(r.p);
+ return r;
+ }
+ }
+
+ r.p = dflt;
+ r.len = strlen(r.p);
+ return r;
+}
+#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;
+ 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)) {
+ req->body.len = (size_t) to64(v->p);
+ req->message.len = len + 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[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 < sizeof(buf)) {
+ to_read = sizeof(buf) - io->len;
+ }
+
+ if (left > 0 && to_read > left) {
+ to_read = left;
+ }
+
+ if (to_read == 0) {
+ /* Rate limiting. send_mbuf is too full, wait until it's drained. */
+ } else if (pd->file.sent < pd->file.cl &&
+ (n = fread(buf, 1, to_read, pd->file.fp)) > 0) {
+ mg_send(nc, buf, n);
+ pd->file.sent += n;
+ } else {
+ if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
+ mg_http_free_proto_data_file(&pd->file);
+ }
+ } 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 = 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);
+ }
+ }
+#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++;
+ }
+
+ /* 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, 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) {
+ hm->message.len = (size_t) pd->chunk.body_len + blen - i;
+ }
+ }
+
+ return body_len;
+}
+
+static mg_event_handler_t mg_http_get_endpoint_handler(
+ struct mg_connection *nc, struct mg_str *uri_path) {
+ struct mg_http_proto_data *pd;
+ mg_event_handler_t ret = NULL;
+ int matched, matched_max = 0;
+ struct mg_http_endpoint *ep;
+
+ if (nc == NULL) {
+ return NULL;
+ }
+
+ pd = mg_http_get_proto_data(nc);
+
+ ep = pd->endpoints;
+ while (ep != NULL) {
+ const struct mg_str name_s = {ep->name, ep->name_len};
+ if ((matched = mg_match_prefix_n(name_s, *uri_path)) != -1) {
+ if (matched > matched_max) {
+ /* Looking for the longest suitable handler */
+ ret = ep->handler;
+ matched_max = matched;
+ }
+ }
+
+ ep = ep->next;
+ }
+
+ return ret;
+}
+
+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);
+
+ if (pd->endpoint_handler == NULL || ev == MG_EV_HTTP_REQUEST) {
+ pd->endpoint_handler =
+ ev == MG_EV_HTTP_REQUEST
+ ? mg_http_get_endpoint_handler(nc->listener, &hm->uri)
+ : NULL;
+ }
+ mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler, ev,
+ hm);
+}
+
+#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
+
+/*
+ * 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,
+ struct http_message *hm) __attribute__((noinline));
+
+void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data) {
+ struct http_message hm;
+ mg_http_handler2(nc, ev, ev_data, &hm);
+}
+
+static void mg_http_handler2(struct mg_connection *nc, int ev, void *ev_data,
+ struct http_message *hm) {
+#else /* !__XTENSA__ */
+void mg_http_handler(struct mg_connection *nc, int ev, void *ev_data) {
+ struct http_message shm;
+ struct http_message *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_STREAMING_MULTIPART
+ if (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.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),
+ 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),
+ MG_EV_HTTP_MULTIPART_REQUEST_END, &mp);
+ } else
+#endif
+ if (io->len > 0 && 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;
+ mg_http_call_endpoint_handler(nc, ev2, hm);
+ }
+ }
+
+#if MG_ENABLE_FILESYSTEM
+ if (pd->file.fp != NULL) {
+ mg_http_transfer_file_data(nc);
+ }
+#endif
+
+ mg_call(nc, nc->handler, ev, ev_data);
+
+ if (ev == MG_EV_RECV) {
+ struct mg_str *s;
+
+#if MG_ENABLE_HTTP_STREAMING_MULTIPART
+ if (pd->mp_stream.boundary != NULL) {
+ mg_http_multipart_continue(nc);
+ return;
+ }
+#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
+
+ req_len = mg_parse_http(io->buf, io->len, hm, is_req);
+
+ 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 &&
+ mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
+ /* We're websocket client, got handshake response from server. */
+ /* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
+ mbuf_remove(io, req_len);
+ nc->proto_handler = mg_ws_handler;
+ nc->flags |= MG_F_IS_WEBSOCKET;
+ mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
+ mg_ws_handler(nc, MG_EV_RECV, ev_data);
+ } else if (nc->listener != NULL &&
+ (vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
+ mg_event_handler_t handler;
+
+ /* 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.
+ */
+ handler = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
+ if (handler != NULL) {
+ nc->handler = handler;
+ }
+
+ /* Send handshake */
+ mg_call(nc, nc->handler, 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);
+ }
+ mg_call(nc, nc->handler, MG_EV_WEBSOCKET_HANDSHAKE_DONE, NULL);
+ mg_ws_handler(nc, MG_EV_RECV, ev_data);
+ }
+ }
+#endif /* MG_ENABLE_HTTP_WEBSOCKET */
+ else if (hm->message.len <= io->len) {
+ int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
+
+/* Whole HTTP message is fully buffered, call event handler */
+
+#if MG_ENABLE_JAVASCRIPT
+ v7_val_t v1, v2, headers, req, args, res;
+ struct v7 *v7 = nc->mgr->v7;
+ const char *ev_name = trigger_ev == MG_EV_HTTP_REPLY ? "onsnd" : "onrcv";
+ int i, js_callback_handled_request = 0;
+
+ if (v7 != NULL) {
+ /* Lookup JS callback */
+ v1 = v7_get(v7, v7_get_global(v7), "Http", ~0);
+ v2 = v7_get(v7, v1, ev_name, ~0);
+
+ /* Create callback params. TODO(lsm): own/disown those */
+ args = v7_mk_array(v7);
+ req = v7_mk_object(v7);
+ headers = v7_mk_object(v7);
+
+ /* Populate request object */
+ v7_set(v7, req, "method", ~0,
+ v7_mk_string(v7, hm->method.p, hm->method.len, 1));
+ v7_set(v7, req, "uri", ~0, v7_mk_string(v7, hm->uri.p, hm->uri.len, 1));
+ v7_set(v7, req, "body", ~0,
+ v7_mk_string(v7, hm->body.p, hm->body.len, 1));
+ v7_set(v7, req, "headers", ~0, headers);
+ for (i = 0; hm->header_names[i].len > 0; i++) {
+ const struct mg_str *name = &hm->header_names[i];
+ const struct mg_str *value = &hm->header_values[i];
+ v7_set(v7, headers, name->p, name->len,
+ v7_mk_string(v7, value->p, value->len, 1));
+ }
+
+ /* Invoke callback. TODO(lsm): report errors */
+ v7_array_push(v7, args, v7_mk_foreign(v7, nc));
+ v7_array_push(v7, args, req);
+ if (v7_apply(v7, v2, V7_UNDEFINED, args, &res) == V7_OK &&
+ v7_is_truthy(v7, res)) {
+ js_callback_handled_request++;
+ }
+ }
+
+ /* If JS callback returns true, stop request processing */
+ if (js_callback_handled_request) {
+ nc->flags |= MG_F_SEND_AND_CLOSE;
+ } else {
+ mg_http_call_endpoint_handler(nc, trigger_ev, hm);
+ }
+#else
+ mg_http_call_endpoint_handler(nc, trigger_ev, hm);
+#endif
+ mbuf_remove(io, hm->message.len);
+ }
+ }
+ (void) pd;
+}
+
+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[100];
+ int boundary_len;
+
+ if (nc->listener == NULL) {
+ /* No streaming for replies now */
+ goto exit_mp;
+ }
+
+ 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_header(ct, "boundary", boundary, sizeof(boundary));
+ 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 {
+ 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 = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
+ if (pd->endpoint_handler == NULL) {
+ pd->endpoint_handler = nc->handler;
+ }
+
+ mg_call(nc, pd->endpoint_handler, MG_EV_HTTP_MULTIPART_REQUEST, hm);
+
+ mbuf_remove(io, req_len);
+ }
+exit_mp:
+ ;
+}
+
+#define CONTENT_DISPOSITION "Content-Disposition: "
+
+static void 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;
+ mg_call(c, pd->endpoint_handler, ev, &mp);
+ pd->mp_stream.user_data = mp.user_data;
+}
+
+static int mg_http_multipart_got_chunk(struct mg_connection *c) {
+ struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
+ struct mbuf *io = &c->recv_mbuf;
+
+ mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf,
+ pd->mp_stream.prev_io_len);
+ mbuf_remove(io, pd->mp_stream.prev_io_len);
+ pd->mp_stream.prev_io_len = 0;
+ pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
+
+ return 0;
+}
+
+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);
+ free((void *) pd->mp_stream.file_name);
+ pd->mp_stream.file_name = NULL;
+ 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 ((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 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);
+ char file_name[100], var_name[100];
+ 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);
+
+ 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;
+ mg_http_parse_header(&header, "name", var_name, sizeof(var_name) - 2);
+ mg_http_parse_header(&header, "filename", file_name,
+ sizeof(file_name) - 2);
+ 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);
+ }
+
+ free((void *) pd->mp_stream.file_name);
+ pd->mp_stream.file_name = strdup(file_name);
+ free((void *) pd->mp_stream.var_name);
+ pd->mp_stream.var_name = strdup(var_name);
+
+ 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;
+
+ 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 && pd->mp_stream.prev_io_len == 0) {
+ pd->mp_stream.prev_io_len = io->len;
+ return 0;
+ } else if (boundary == NULL &&
+ (int) io->len >
+ pd->mp_stream.prev_io_len + pd->mp_stream.boundary_len + 4) {
+ pd->mp_stream.state = MPS_GOT_CHUNK;
+ return 1;
+ } else if (boundary != NULL) {
+ int data_size = (boundary - io->buf - 4);
+ mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf, data_size);
+ mbuf_remove(io, (boundary - io->buf));
+ pd->mp_stream.prev_io_len = 0;
+ pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
+ return 1;
+ } 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_GOT_CHUNK: {
+ if (mg_http_multipart_got_chunk(c) == 0) {
+ return;
+ }
+ break;
+ }
+ case MPS_FINALIZE: {
+ if (mg_http_multipart_finalize(c) == 0) {
+ return;
+ }
+ break;
+ }
+ case MPS_FINISHED: {
+ mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
+ 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\nServer: %s\r\n", status_code,
+ mg_status_message(status_code), mg_version_header);
+ 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),
+ "Moved here.\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", 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(struct mg_connection *nc, struct http_message *hm,
+ const char *path, const struct mg_str mime_type,
+ const 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", nc, path, (int) mime_type.len, mime_type.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);
+ /*
+ * Content length casted to size_t because:
+ * 1) that's the maximum buffer size anyway
+ * 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
+ * position
+ * TODO(mkm): fix ESP8266 RTOS SDK
+ */
+ 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"
+ "%sEtag: %s\r\n\r\n",
+ current_time, last_modified, (int) mime_type.len, mime_type.p,
+ (pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range,
+ etag);
+
+ pd->file.cl = cl;
+ pd->file.type = DATA_FILE;
+ mg_http_transfer_file_data(nc);
+ }
+}
+
+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
+ mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts),
+ 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;
+
+ 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 = -1;
+ 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);
+ if (len == -1) {
+ len = -2;
+ }
+ 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] == '<' ? "<" : ">", 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 */
+}
+
+int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
+ size_t buf_size) {
+ int ch = ' ', ch1 = ',', len = 0, n = strlen(var_name);
+ const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
+
+ if (buf != NULL && buf_size > 0) buf[0] = '\0';
+ if (hdr == NULL) return 0;
+
+ /* 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[n] == '=' &&
+ !strncmp(s, var_name, n))
+ break;
+ }
+
+ if (s != NULL && &s[n + 1] < end) {
+ s += n + 1;
+ if (*s == '"' || *s == '\'') {
+ ch = ch1 = *s++;
+ }
+ p = s;
+ while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) {
+ if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
+ buf[len++] = *p++;
+ }
+ if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
+ len = 0;
+ } else {
+ if (len > 0 && s[len - 1] == ',') len--;
+ if (len > 0 && s[len - 1] == ';') len--;
+ buf[len] = '\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) == (int) strlen(p1)) ||
+ (p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
+}
+
+#if !MG_DISABLE_HTTP_DIGEST_AUTH
+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) {
+ static const char colon[] = ":", qop[] = "auth";
+ static const size_t one = 1;
+ char ha1[33], resp[33], cnonce[40];
+
+ snprintf(cnonce, sizeof(cnonce), "%x", (unsigned int) 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,
+ cnonce, strlen(cnonce), "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, cnonce, 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 < 3600;
+}
+
+int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
+ FILE *fp) {
+ struct mg_str *hdr;
+ char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
+ char user[50], cnonce[33], response[40], uri[200], qop[20], nc[20], nonce[30];
+ char expected_response[33];
+
+ /* Parse "Authorization:" header, fail fast on parse error */
+ if (hm == NULL || fp == NULL ||
+ (hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
+ mg_http_parse_header(hdr, "username", user, sizeof(user)) == 0 ||
+ mg_http_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce)) == 0 ||
+ mg_http_parse_header(hdr, "response", response, sizeof(response)) == 0 ||
+ mg_http_parse_header(hdr, "uri", uri, sizeof(uri)) == 0 ||
+ mg_http_parse_header(hdr, "qop", qop, sizeof(qop)) == 0 ||
+ mg_http_parse_header(hdr, "nc", nc, sizeof(nc)) == 0 ||
+ mg_http_parse_header(hdr, "nonce", nonce, sizeof(nonce)) == 0 ||
+ mg_check_nonce(nonce) == 0) {
+ return 0;
+ }
+
+ /*
+ * 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 &&
+ strcmp(user, f_user) == 0 &&
+ /* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
+ strcmp(auth_domain, f_domain) == 0) {
+ /* User and domain matched, check the password */
+ mg_mkmd5resp(
+ hm->method.p, hm->method.len, hm->uri.p,
+ hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0),
+ f_ha1, strlen(f_ha1), nonce, strlen(nonce), nc, strlen(nc), cnonce,
+ strlen(cnonce), qop, strlen(qop), expected_response);
+ return mg_casecmp(response, expected_response) == 0;
+ }
+ }
+
+ /* None of the entries in the passwords file matched - return failure */
+ return 0;
+}
+
+static int mg_is_authorized(struct http_message *hm, const char *path,
+ int is_directory, const char *domain,
+ const char *passwords_file,
+ int is_global_pass_file) {
+ char buf[MG_MAX_PATH];
+ const char *p;
+ FILE *fp;
+ int authorized = 1;
+
+ if (domain != NULL && passwords_file != NULL) {
+ if (is_global_pass_file) {
+ fp = mg_fopen(passwords_file, "r");
+ } else if (is_directory) {
+ snprintf(buf, sizeof(buf), "%s%c%s", path, DIRSEP, passwords_file);
+ fp = mg_fopen(buf, "r");
+ } else {
+ p = strrchr(path, DIRSEP);
+ if (p == NULL) p = path;
+ snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path), path, DIRSEP,
+ passwords_file);
+ fp = mg_fopen(buf, "r");
+ }
+
+ if (fp != NULL) {
+ authorized = mg_http_check_digest_auth(hm, domain, fp);
+ fclose(fp);
+ }
+ }
+
+ LOG(LL_DEBUG, ("%s '%s' %d %d", path, passwords_file ? passwords_file : "",
+ is_global_pass_file, authorized));
+ return authorized;
+}
+#else
+static int mg_is_authorized(struct http_message *hm, const char *path,
+ int is_directory, const char *domain,
+ const char *passwords_file,
+ int is_global_pass_file) {
+ (void) hm;
+ (void) path;
+ (void) is_directory;
+ (void) domain;
+ (void) passwords_file;
+ (void) is_global_pass_file;
+ return 1;
+}
+#endif
+
+#if MG_ENABLE_DIRECTORY_LISTING
+static size_t mg_url_encode(const char *src, size_t s_len, char *dst,
+ size_t dst_len) {
+ static const char *dont_escape = "._-$,;~()/";
+ static const char *hex = "0123456789abcdef";
+ size_t i = 0, j = 0;
+
+ for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
+ if (isalnum(*(const unsigned char *) (src + i)) ||
+ strchr(dont_escape, *(const unsigned char *) (src + i)) != NULL) {
+ dst[j] = src[i];
+ } else if (j + 3 < dst_len) {
+ dst[j] = '%';
+ dst[j + 1] = hex[(*(const unsigned char *) (src + i)) >> 4];
+ dst[j + 2] = hex[(*(const unsigned char *) (src + i)) & 0xf];
+ j += 2;
+ }
+ }
+
+ dst[j] = '\0';
+ return j;
+}
+
+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", "<");
+ } 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], href[MAX_PATH_SIZE * 3], path[MAX_PATH_SIZE];
+ int64_t fsize = stp->st_size;
+ int is_dir = S_ISDIR(stp->st_mode);
+ const char *slash = is_dir ? "/" : "";
+
+ 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));
+ mg_url_encode(file_name, strlen(file_name), href, sizeof(href));
+ mg_printf_http_chunk(nc,
+ "
%s%s | "
+ "%s | %s |
\n",
+ href, slash, path, slash, mod, is_dir ? -1 : fsize,
+ size);
+}
+
+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[MAX_PATH_SIZE];
+ cs_stat_t st;
+ struct dirent *dp;
+ DIR *dirp;
+
+ LOG(LL_DEBUG, ("%p [%s]", 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", 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 =
+ "";
+
+ 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,
+ "Index of %.*s%s%s"
+ "\n"
+ "Index of %.*s
\n"
+ "Name | "
+ "Modified"
+ " | Size |
"
+ "
|
\n"
+ "\n"
+ "",
+ (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,
+ "
|
\n"
+ "
\n"
+ "%s\n"
+ "",
+ 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) {
+ 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", 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;
+ }
+}
+
+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;
+ char *addr = NULL;
+ const char *path = NULL;
+ int i;
+ const char *error;
+ struct mg_connect_opts opts;
+ 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_reverse_proxy_handler, opts, "http://",
+ "https://", purl, &path, NULL /* user */,
+ NULL /* pass */, &addr);
+ 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,
+ path);
+
+ mg_printf(be, "Host: %s\r\n", addr);
+ 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_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 */
+ int 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;
+ }
+}
+
+static 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=\"%lu\"\r\n"
+ "Content-Length: 0\r\n\r\n",
+ domain, (unsigned long) mg_time());
+}
+
+static void mg_http_send_options(struct mg_connection *nc) {
+ mg_printf(nc, "%s",
+ "HTTP/1.1 200 OK\r\nAllow: 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", 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_is_authorized(hm, path, is_directory, opts->auth_domain,
+ opts->global_auth_file, 1) ||
+ !mg_is_authorized(hm, path, is_directory, opts->auth_domain,
+ opts->per_directory_auth_file, 0)) {
+ 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_is_authorized(hm, path, is_directory, opts->auth_domain,
+ opts->dav_auth_file, 1)))) {
+ 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);
+ } 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)) {
+ mg_http_send_error(nc, 304, "Not Modified");
+ } 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) {
+ 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 file_upload_state *) calloc(1, sizeof(*fus));
+ mp->user_data = NULL;
+
+ struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
+ if (lfn.p == NULL || lfn.len == 0) {
+ LOG(LL_ERROR, ("%p Not allowed to upload %s", 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->lfn = (char *) malloc(lfn.len + 1);
+ memcpy(fus->lfn, lfn.p, lfn.len);
+ fus->lfn[lfn.len] = '\0';
+ if (lfn.p != mp->file_name) free((char *) lfn.p);
+ LOG(LL_DEBUG,
+ ("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn));
+ fus->fp = mg_fopen(fus->lfn, "w");
+ 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 (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", 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", nc, mp->file_name,
+ fus->lfn, (int) fus->num_recd));
+ mg_printf(nc,
+ "HTTP/1.1 200 OK\r\n"
+ "Content-Type: text/plain\r\n"
+ "Connection: close\r\n\r\n"
+ "Ok, %s - %d bytes.\r\n",
+ mp->file_name, (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);
+ free(fus->lfn);
+ free(fus);
+ mp->user_data = NULL;
+ nc->flags |= MG_F_SEND_AND_CLOSE;
+ break;
+ }
+ }
+}
+
+#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
+#endif /* MG_ENABLE_FILESYSTEM */
+
+/* returns 0 on success, -1 on error */
+MG_INTERNAL int mg_http_common_url_parse(const char *url, const char *schema,
+ const char *schema_tls, int *use_ssl,
+ char **user, char **pass, char **addr,
+ int *port_i, const char **path) {
+ int addr_len = 0;
+ int auth_sep_pos = -1;
+ int user_sep_pos = -1;
+ int port_pos = -1;
+ (void) user;
+ (void) pass;
+
+ if (strncmp(url, schema, strlen(schema)) == 0) {
+ url += strlen(schema);
+ } else if (strncmp(url, schema_tls, strlen(schema_tls)) == 0) {
+ url += strlen(schema_tls);
+ *use_ssl = 1;
+#if !MG_ENABLE_SSL
+ return -1; /* SSL is not enabled, cannot do HTTPS URLs */
+#endif
+ }
+
+ while (*url != '\0') {
+ *addr = (char *) MG_REALLOC(*addr, addr_len + 6 /* space for port too. */);
+ if (*addr == NULL) {
+ DBG(("OOM"));
+ return -1;
+ }
+ if (*url == '/') {
+ break;
+ }
+ if (*url == '@') {
+ auth_sep_pos = addr_len;
+ user_sep_pos = port_pos;
+ port_pos = -1;
+ }
+ if (*url == ':') port_pos = addr_len;
+ (*addr)[addr_len++] = *url;
+ (*addr)[addr_len] = '\0';
+ url++;
+ }
+
+ if (addr_len == 0) goto cleanup;
+ if (port_pos < 0) {
+ *port_i = addr_len;
+ addr_len += sprintf(*addr + addr_len, ":%d", *use_ssl ? 443 : 80);
+ } else {
+ *port_i = -1;
+ }
+
+ if (*path == NULL) *path = url;
+
+ if (**path == '\0') *path = "/";
+
+ if (user != NULL && pass != NULL) {
+ if (auth_sep_pos == -1) {
+ *user = NULL;
+ *pass = NULL;
+ } else {
+ /* user is from 0 to user_sep_pos */
+ *user = (char *) MG_MALLOC(user_sep_pos + 1);
+ memcpy(*user, *addr, user_sep_pos);
+ (*user)[user_sep_pos] = '\0';
+ /* pass is from user_sep_pos + 1 to auth_sep_pos */
+ *pass = (char *) MG_MALLOC(auth_sep_pos - user_sep_pos - 1 + 1);
+ memcpy(*pass, *addr + user_sep_pos + 1, auth_sep_pos - user_sep_pos - 1);
+ (*pass)[auth_sep_pos - user_sep_pos - 1] = '\0';
+
+ /* move address proper to the front */
+ memmove(*addr, *addr + auth_sep_pos + 1, addr_len - auth_sep_pos);
+ }
+ }
+
+ DBG(("%s %s", *addr, *path));
+
+ return 0;
+
+cleanup:
+ MG_FREE(*addr);
+ return -1;
+}
+
+struct mg_connection *mg_connect_http_base(
+ struct mg_mgr *mgr, mg_event_handler_t ev_handler,
+ struct mg_connect_opts opts, const char *schema, const char *schema_ssl,
+ const char *url, const char **path, char **user, char **pass, char **addr) {
+ struct mg_connection *nc = NULL;
+ int port_i = -1;
+ int use_ssl = 0;
+
+ if (mg_http_common_url_parse(url, schema, schema_ssl, &use_ssl, user, pass,
+ addr, &port_i, path) < 0) {
+ MG_SET_PTRPTR(opts.error_string, "cannot parse url");
+ return NULL;
+ }
+
+ LOG(LL_DEBUG, ("%s use_ssl? %d", url, use_ssl));
+ 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");
+ if (user != NULL) MG_FREE(*user);
+ if (pass != NULL) MG_FREE(*pass);
+ MG_FREE(*addr);
+ return NULL;
+#endif
+ }
+
+ if ((nc = mg_connect_opt(mgr, *addr, ev_handler, opts)) != NULL) {
+ mg_set_protocol_http_websocket(nc);
+ /* If the port was addred by us, restore the original host. */
+ if (port_i >= 0) (*addr)[port_i] = '\0';
+ }
+
+ return nc;
+}
+
+struct mg_connection *mg_connect_http_opt(struct mg_mgr *mgr,
+ mg_event_handler_t ev_handler,
+ struct mg_connect_opts opts,
+ const char *url,
+ const char *extra_headers,
+ const char *post_data) {
+ char *user = NULL, *pass = NULL, *addr = NULL;
+ const char *path = NULL;
+ struct mbuf auth;
+ struct mg_connection *nc =
+ mg_connect_http_base(mgr, ev_handler, opts, "http://", "https://", url,
+ &path, &user, &pass, &addr);
+
+ if (nc == NULL) {
+ return NULL;
+ }
+
+ mbuf_init(&auth, 0);
+ if (user != NULL) {
+ mg_basic_auth_header(user, pass, &auth);
+ }
+
+ 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 == NULL ? "GET" : "POST", path, addr,
+ post_data == NULL ? 0 : strlen(post_data), (int) auth.len,
+ (auth.buf == NULL ? "" : auth.buf),
+ extra_headers == NULL ? "" : extra_headers,
+ post_data == NULL ? "" : post_data);
+
+ mbuf_free(&auth);
+ MG_FREE(user);
+ MG_FREE(pass);
+ MG_FREE(addr);
+ return nc;
+}
+
+struct mg_connection *mg_connect_http(struct mg_mgr *mgr,
+ mg_event_handler_t ev_handler,
+ 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, ev_handler, 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;
+
+ if (buf == NULL || buf_len <= 0) return 0;
+ if ((hl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
+ 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);
+ mg_http_parse_header(&header, "name", var_name, var_name_len);
+ mg_http_parse_header(&header, "filename", file_name, file_name_len);
+ }
+ }
+
+ /* 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(struct mg_connection *nc, const char *uri_path,
+ mg_event_handler_t handler) {
+ struct mg_http_proto_data *pd = NULL;
+ struct mg_http_endpoint *new_ep = NULL;
+
+ if (nc == NULL) return;
+ new_ep = (struct mg_http_endpoint *) calloc(1, sizeof(*new_ep));
+ if (new_ep == NULL) return;
+
+ pd = mg_http_get_proto_data(nc);
+ new_ep->name = strdup(uri_path);
+ new_ep->name_len = strlen(new_ep->name);
+ new_ep->handler = handler;
+ new_ep->next = pd->endpoints;
+ pd->endpoints = new_ep;
+}
+
+#endif /* MG_ENABLE_HTTP */
+#ifdef MG_MODULE_LINES
+#line 1 "mongoose/src/http_cgi.c"
+#endif
+/*
+ * Copyright (c) 2014-2016 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#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
+
+/*
+ * 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[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
+ 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[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
+ char buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
+ buf4[MAX_PATH_SIZE], cmdline[MAX_PATH_SIZE];
+ DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
+ FILE *fp;
+
+ memset(&si, 0, sizeof(si));
+ memset(&pi, 0, sizeof(pi));
+
+ si.cb = sizeof(si);
+ si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
+ si.wShowWindow = SW_HIDE;
+ si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
+
+ CreatePipe(&a[0], &a[1], NULL, 0);
+ CreatePipe(&b[0], &b[1], NULL, 0);
+ DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
+ DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
+
+ if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
+ buf[0] = buf[1] = '\0';
+ fgets(buf, sizeof(buf), fp);
+ buf[sizeof(buf) - 1] = '\0';
+ if (buf[0] == '#' && buf[1] == '!') {
+ interp = buf + 2;
+ /* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
+ while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
+ interp++;
+ }
+ }
+ fclose(fp);
+ }
+
+ snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
+ mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
+
+ mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
+ to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
+
+ if (interp != NULL) {
+ mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
+ snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
+ } else {
+ snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
+ }
+ to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
+
+ if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
+ (void *) env, full_dir, &si, &pi) != 0) {
+ mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
+ mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
+
+ CloseHandle(si.hStdOutput);
+ CloseHandle(si.hStdInput);
+
+ CloseHandle(pi.hThread);
+ CloseHandle(pi.hProcess);
+ } else {
+ CloseHandle(a[1]);
+ CloseHandle(b[0]);
+ closesocket(sock);
+ }
+ DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
+
+ /* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
+ (void) envp;
+ return (pi.hProcess != NULL);
+}
+#else
+static int mg_start_process(const char *interp, const char *cmd,
+ const char *env, const char *envp[],
+ const char *dir, sock_t sock) {
+ char buf[500];
+ pid_t pid = fork();
+ (void) env;
+
+ if (pid == 0) {
+ /*
+ * In Linux `chdir` declared with `warn_unused_result` attribute
+ * To shutup compiler we have yo use result in some way
+ */
+ int tmp = chdir(dir);
+ (void) tmp;
+ (void) dup2(sock, 0);
+ (void) dup2(sock, 1);
+ closesocket(sock);
+
+ /*
+ * After exec, all signal handlers are restored to their default values,
+ * with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
+ * implementation, SIGCHLD's handler will leave unchanged after exec
+ * if it was set to be ignored. Restore it to default action.
+ */
+ signal(SIGCHLD, SIG_DFL);
+
+ if (interp == NULL) {
+ execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
+ } else {
+ execle(interp, interp, cmd, (char *) 0, envp);
+ }
+ snprintf(buf, sizeof(buf),
+ "Status: 500\r\n\r\n"
+ "500 Server Error: %s%s%s: %s",
+ interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
+ strerror(errno));
+ send(1, buf, strlen(buf), 0);
+ exit(EXIT_FAILURE); /* exec call failed */
+ }
+
+ return (pid != 0);
+}
+#endif /* _WIN32 */
+
+/*
+ * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
+ * pointer into the vars array.
+ */
+static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
+ int n, space;
+ char *added = block->buf + block->len;
+ va_list ap;
+
+ /* Calculate how much space is left in the buffer */
+ space = sizeof(block->buf) - (block->len + 2);
+ if (space > 0) {
+ /* Copy VARIABLE=VALUE\0 string into the free space */
+ va_start(ap, fmt);
+ n = vsnprintf(added, (size_t) space, fmt, ap);
+ va_end(ap);
+
+ /* Make sure we do not overflow buffer and the envp array */
+ if (n > 0 && n + 1 < space &&
+ block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
+ /* Append a pointer to the added string into the envp array */
+ block->vars[block->nvars++] = added;
+ /* Bump up used length counter. Include \0 terminator */
+ block->len += n + 1;
+ }
+ }
+
+ return added;
+}
+
+static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
+ const char *s;
+ if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
+}
+
+static void mg_prepare_cgi_environment(struct mg_connection *nc,
+ const char *prog,
+ const struct mg_str *path_info,
+ const struct http_message *hm,
+ const struct mg_serve_http_opts *opts,
+ struct mg_cgi_env_block *blk) {
+ const char *s;
+ struct mg_str *h;
+ char *p;
+ size_t i;
+ char buf[100];
+
+ 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) {
+ struct mg_connection *nc = (struct mg_connection *) cgi_nc->user_data;
+ (void) ev_data;
+
+ if (nc == NULL) 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_USER_1) {
+ 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_USER_1;
+ }
+ if (!(nc->flags & MG_F_USER_1)) {
+ mg_forward(cgi_nc, nc);
+ }
+ break;
+ case MG_EV_CLOSE:
+ mg_http_free_proto_data_cgi(&mg_http_get_proto_data(cgi_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[MAX_PATH_SIZE];
+ const char *p;
+ sock_t fds[2];
+
+ DBG(("%p [%s]", nc, prog));
+ mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
+ /*
+ * CGI must be executed in its own directory. 'dir' must point to the
+ * directory containing executable program, 'p' must point to the
+ * executable program name relative to 'dir'.
+ */
+ if ((p = strrchr(prog, DIRSEP)) == NULL) {
+ snprintf(dir, sizeof(dir), "%s", ".");
+ } else {
+ snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
+ prog = p + 1;
+ }
+
+ /*
+ * Try to create socketpair in a loop until success. mg_socketpair()
+ * can be interrupted by a signal and fail.
+ * TODO(lsm): use sigaction to restart interrupted syscall
+ */
+ do {
+ mg_socketpair(fds, SOCK_STREAM);
+ } while (fds[0] == INVALID_SOCKET);
+
+ if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
+ fds[1]) != 0) {
+ size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len);
+ struct mg_connection *cgi_nc =
+ mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler);
+ struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(cgi_nc);
+ cgi_pd->cgi.cgi_nc = cgi_nc;
+ cgi_pd->cgi.cgi_nc->user_data = nc;
+ nc->flags |= MG_F_USER_1;
+ /* Push POST data to the CGI */
+ if (n > 0 && n < nc->recv_mbuf.len) {
+ mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, n);
+ }
+ 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) {
+ if (d->cgi_nc != NULL) d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
+ memset(d, 0, sizeof(struct mg_http_proto_data_cgi));
+ }
+}
+
+#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
+#ifdef MG_MODULE_LINES
+#line 1 "mongoose/src/http_ssi.c"
+#endif
+/*
+ * Copyright (c) 2014-2016 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#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 = 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[BUFSIZ], path[MAX_PATH_SIZE], *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 */
+ snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
+ } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
+ /*
+ * File name is relative to the webserver working directory
+ * or it is absolute system path
+ */
+ snprintf(path, sizeof(path), "%s", file_name);
+ } 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:
+ *
+ */
+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(" */
+ 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, MG_EV_SSI_CALL,
+ (void *) cctx.arg.p); /* NUL added above */
+ mg_call(nc, NULL, 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;
+ DBG(("%p %s", nc, path));
+
+ if ((fp = mg_fopen(path, "rb")) == NULL) {
+ mg_http_send_error(nc, 404, NULL);
+ } else {
+ mg_set_close_on_exec((sock_t) fileno(fp));
+
+ mime_type = mg_get_mime_type(path, "text/plain", opts);
+ mg_send_response_line(nc, 200, opts->extra_headers);
+ mg_printf(nc,
+ "Content-Type: %.*s\r\n"
+ "Connection: close\r\n\r\n",
+ (int) mime_type.len, mime_type.p);
+ 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 "mongoose/src/http_webdav.c"
+#endif
+/*
+ * Copyright (c) 2014-2016 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#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], buf[MAX_PATH_SIZE * 3];
+ time_t t = stp->st_mtime; /* store in local variable for NDK compile */
+ mg_gmt_time_string(mtime, sizeof(mtime), &t);
+ mg_url_encode(name, strlen(name), buf, sizeof(buf));
+ mg_printf(nc,
+ ""
+ "%s"
+ ""
+ ""
+ "%s"
+ "%" INT64_FMT
+ ""
+ "%s"
+ ""
+ "HTTP/1.1 200 OK"
+ ""
+ "\n",
+ buf, S_ISDIR(stp->st_mode) ? "" : "",
+ (int64_t) stp->st_size, mtime);
+}
+
+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"
+ ""
+ "\n";
+ static const char footer[] = "\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[MAX_PATH_SIZE];
+ 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"
+ ""
+ "\n"
+ "\n"
+ "\n"
+ "\n"
+ "\n"
+ "opaquelocktoken:%s%u"
+ ""
+ ""
+ "\n"
+ ""
+ "\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[MAX_PATH_SIZE];
+ 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[MAX_PATH_SIZE];
+ 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[MAX_PATH_SIZE];
+ 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 "mongoose/src/http_websocket.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
+
+#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
+#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
+#endif
+
+#define MG_WS_NO_HOST_HEADER_MAGIC ((char *) 0x1)
+
+static int mg_is_ws_fragment(unsigned char flags) {
+ return (flags & 0x80) == 0 || (flags & 0x0f) == 0;
+}
+
+static int mg_is_ws_first_fragment(unsigned char flags) {
+ return (flags & 0x80) == 0 && (flags & 0x0f) != 0;
+}
+
+static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
+ struct websocket_message *wsm) {
+ if (wsm->flags & 0x8) {
+ mg_call(nc, nc->handler, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
+ } else {
+ mg_call(nc, nc->handler, MG_EV_WEBSOCKET_FRAME, wsm);
+ }
+}
+
+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, buf_len = nc->recv_mbuf.len, len,
+ mask_len = 0, header_len = 0;
+ unsigned char *p = (unsigned char *) nc->recv_mbuf.buf, *buf = p,
+ *e = p + buf_len;
+ unsigned *sizep = (unsigned *) &p[1]; /* Size ptr for defragmented frames */
+ int ok, reass = buf_len > 0 && mg_is_ws_fragment(p[0]) &&
+ !(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
+
+ /* If that's a continuation frame that must be reassembled, handle it */
+ if (reass && !mg_is_ws_first_fragment(p[0]) &&
+ buf_len >= 1 + sizeof(*sizep) && buf_len >= 1 + sizeof(*sizep) + *sizep) {
+ buf += 1 + sizeof(*sizep) + *sizep;
+ buf_len -= 1 + sizeof(*sizep) + *sizep;
+ }
+
+ if (buf_len >= 2) {
+ len = buf[1] & 127;
+ mask_len = buf[1] & 128 ? 4 : 0;
+ if (len < 126 && buf_len >= mask_len) {
+ data_len = len;
+ header_len = 2 + mask_len;
+ } else if (len == 126 && buf_len >= 4 + mask_len) {
+ header_len = 4 + mask_len;
+ data_len = ntohs(*(uint16_t *) &buf[2]);
+ } else if (buf_len >= 10 + mask_len) {
+ header_len = 10 + mask_len;
+ data_len = (((uint64_t) ntohl(*(uint32_t *) &buf[2])) << 32) +
+ ntohl(*(uint32_t *) &buf[6]);
+ }
+ }
+
+ frame_len = header_len + data_len;
+ ok = frame_len > 0 && frame_len <= buf_len;
+
+ if (ok) {
+ struct websocket_message wsm;
+
+ wsm.size = (size_t) data_len;
+ wsm.data = buf + header_len;
+ wsm.flags = buf[0];
+
+ /* Apply mask if necessary */
+ if (mask_len > 0) {
+ for (i = 0; i < data_len; i++) {
+ buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
+ }
+ }
+
+ if (reass) {
+ /* On first fragmented frame, nullify size */
+ if (mg_is_ws_first_fragment(wsm.flags)) {
+ mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.size + sizeof(*sizep));
+ p[0] &= ~0x0f; /* Next frames will be treated as continuation */
+ buf = p + 1 + sizeof(*sizep);
+ *sizep = 0; /* TODO(lsm): fix. this can stomp over frame data */
+ }
+
+ /* Append this frame to the reassembled buffer */
+ memmove(buf, wsm.data, e - wsm.data);
+ (*sizep) += wsm.size;
+ nc->recv_mbuf.len -= wsm.data - buf;
+
+ /* On last fragmented frame - call user handler and remove data */
+ if (wsm.flags & 0x80) {
+ wsm.data = p + 1 + sizeof(*sizep);
+ wsm.size = *sizep;
+ mg_handle_incoming_websocket_frame(nc, &wsm);
+ mbuf_remove(&nc->recv_mbuf, 1 + sizeof(*sizep) + *sizep);
+ }
+ } else {
+ /* TODO(lsm): properly handle OOB control frames during defragmentation */
+ mg_handle_incoming_websocket_frame(nc, &wsm);
+ mbuf_remove(&nc->recv_mbuf, (size_t) frame_len); /* Cleanup frame */
+ }
+
+ /* If client closes, close too */
+ if ((buf[0] & 0x0f) == WEBSOCKET_OP_CLOSE) {
+ nc->flags |= MG_F_SEND_AND_CLOSE;
+ }
+ }
+
+ 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 : 0x80) + (op & 0x0f);
+ if (len < 126) {
+ header[1] = (unsigned char) len;
+ header_len = 2;
+ } else if (len < 65535) {
+ uint16_t tmp = htons((uint16_t) len);
+ header[1] = 126;
+ memcpy(&header[2], &tmp, sizeof(tmp));
+ header_len = 4;
+ } else {
+ uint32_t tmp;
+ header[1] = 127;
+ tmp = htonl((uint32_t)((uint64_t) len >> 32));
+ memcpy(&header[2], &tmp, sizeof(tmp));
+ tmp = htonl((uint32_t)(len & 0xffffffff));
+ memcpy(&header[6], &tmp, sizeof(tmp));
+ header_len = 10;
+ }
+
+ /* client connections enable masking */
+ if (nc->listener == NULL) {
+ header[1] |= 1 << 7; /* set masking flag */
+ mg_send(nc, header, header_len);
+ ctx->mask = mg_ws_random_mask();
+ mg_send(nc, &ctx->mask, sizeof(ctx->mask));
+ ctx->pos = nc->send_mbuf.len;
+ } else {
+ mg_send(nc, header, header_len);
+ ctx->pos = 0;
+ }
+}
+
+static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
+ size_t i;
+ if (ctx->pos == 0) return;
+ for (i = 0; i < (mbuf->len - ctx->pos); i++) {
+ mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
+ }
+}
+
+void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
+ size_t len) {
+ struct ws_mask_ctx ctx;
+ DBG(("%p %d %d", nc, op, (int) len));
+ mg_send_ws_header(nc, op, len, &ctx);
+ mg_send(nc, data, len);
+
+ mg_ws_mask_frame(&nc->send_mbuf, &ctx);
+
+ if (op == WEBSOCKET_OP_CLOSE) {
+ nc->flags |= MG_F_SEND_AND_CLOSE;
+ }
+}
+
+void mg_send_websocket_framev(struct mg_connection *nc, int op,
+ const struct mg_str *strv, int strvcnt) {
+ struct ws_mask_ctx ctx;
+ int i;
+ int len = 0;
+ for (i = 0; i < strvcnt; i++) {
+ len += strv[i].len;
+ }
+
+ mg_send_ws_header(nc, op, len, &ctx);
+
+ for (i = 0; i < strvcnt; i++) {
+ mg_send(nc, strv[i].p, strv[i].len);
+ }
+
+ mg_ws_mask_frame(&nc->send_mbuf, &ctx);
+
+ if (op == WEBSOCKET_OP_CLOSE) {
+ nc->flags |= MG_F_SEND_AND_CLOSE;
+ }
+}
+
+void mg_printf_websocket_frame(struct mg_connection *nc, int op,
+ const char *fmt, ...) {
+ char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
+ va_list ap;
+ int len;
+
+ va_start(ap, fmt);
+ if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
+ mg_send_websocket_frame(nc, op, buf, len);
+ }
+ va_end(ap);
+
+ if (buf != mem && buf != NULL) {
+ MG_FREE(buf);
+ }
+}
+
+MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
+ void *ev_data) {
+ mg_call(nc, nc->handler, 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;
+ }
+}
+
+#ifndef MG_EXT_SHA1
+static 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) {
+ 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];
+
+ mg_hash_sha1_v(2, msgs, msg_lens, sha);
+ mg_base64_encode(sha, sizeof(sha), b64_sha);
+ mg_printf(nc, "%s%s%s",
+ "HTTP/1.1 101 Switching Protocols\r\n"
+ "Upgrade: websocket\r\n"
+ "Connection: Upgrade\r\n"
+ "Sec-WebSocket-Accept: ",
+ b64_sha, "\r\n\r\n");
+ DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
+}
+
+void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
+ const char *host, const char *protocol,
+ const char *extra_headers) {
+ mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
+ NULL);
+}
+
+void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
+ const char *host, const char *protocol,
+ const char *extra_headers, const char *user,
+ const char *pass) {
+ 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 != NULL) {
+ 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",
+ path, (int) auth.len, (auth.buf == NULL ? "" : auth.buf), key);
+
+ /* TODO(mkm): take default hostname from http proto data if host == NULL */
+ if (host != MG_WS_NO_HOST_HEADER_MAGIC) {
+ mg_printf(nc, "Host: %s\r\n", host);
+ }
+ if (protocol != NULL) {
+ mg_printf(nc, "Sec-WebSocket-Protocol: %s\r\n", protocol);
+ }
+ if (extra_headers != NULL) {
+ mg_printf(nc, "%s", extra_headers);
+ }
+ mg_printf(nc, "\r\n");
+
+ mbuf_free(&auth);
+}
+
+void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
+ const char *extra_headers) {
+ mg_send_websocket_handshake2(nc, path, MG_WS_NO_HOST_HEADER_MAGIC, NULL,
+ extra_headers);
+}
+
+struct mg_connection *mg_connect_ws_opt(struct mg_mgr *mgr,
+ mg_event_handler_t ev_handler,
+ struct mg_connect_opts opts,
+ const char *url, const char *protocol,
+ const char *extra_headers) {
+ char *user = NULL, *pass = NULL, *addr = NULL;
+ const char *path = NULL;
+ struct mg_connection *nc =
+ mg_connect_http_base(mgr, ev_handler, opts, "ws://", "wss://", url, &path,
+ &user, &pass, &addr);
+
+ if (nc != NULL) {
+ mg_send_websocket_handshake3(nc, path, addr, protocol, extra_headers, user,
+ pass);
+ }
+
+ MG_FREE(addr);
+ MG_FREE(user);
+ MG_FREE(pass);
+ return nc;
+}
+
+struct mg_connection *mg_connect_ws(struct mg_mgr *mgr,
+ mg_event_handler_t ev_handler,
+ 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, ev_handler, opts, url, protocol, extra_headers);
+}
+#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
+#ifdef MG_MODULE_LINES
+#line 1 "mongoose/src/util.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/* Amalgamated: #include "common/base64.h" */
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/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;
+}
+
+static int lowercase(const char *s) {
+ return tolower(*(const unsigned char *) s);
+}
+
+#if MG_ENABLE_FILESYSTEM
+int mg_stat(const char *path, cs_stat_t *st) {
+#ifdef _WIN32
+ wchar_t wpath[MAX_PATH_SIZE];
+ 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[MAX_PATH_SIZE], 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[MAX_PATH_SIZE];
+ to_wchar(path, wpath, ARRAY_SIZE(wpath));
+ return _wopen(wpath, flag, mode);
+#else
+ return open(path, flag, mode); /* LCOV_EXCL_LINE */
+#endif
+}
+#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
+}
+
+void 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;
+ buf[0] = '\0';
+#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) {
+ *buf = '\0';
+ }
+#elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
+ /* Only Windoze Vista (and newer) have inet_ntop() */
+ strncpy(buf, inet_ntoa(sa->sin.sin_addr), len);
+#else
+ inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len);
+#endif
+ }
+ if (flags & MG_SOCK_STRINGIFY_PORT) {
+ int port = ntohs(sa->sin.sin_port);
+ if (flags & MG_SOCK_STRINGIFY_IP) {
+ snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s:%d",
+ (is_v6 ? "]" : ""), port);
+ } else {
+ snprintf(buf, len, "%d", port);
+ }
+ }
+}
+
+void 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);
+ mg_sock_addr_to_str(&sa, buf, len, flags);
+}
+
+#if MG_ENABLE_HEXDUMP
+int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
+ 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);
+ }
+ 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\n", ascii);
+
+ return n;
+}
+
+void mg_hexdump_connection(struct mg_connection *nc, const char *path,
+ const void *buf, int num_bytes, int ev) {
+ FILE *fp = NULL;
+ char *hexbuf, src[60], dst[60];
+ int buf_size = num_bytes * 5 + 100;
+
+ 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,
+ ev == MG_EV_RECV ? "<-" : ev == MG_EV_SEND
+ ? "->"
+ : ev == MG_EV_ACCEPT
+ ? "" : "XX",
+ dst, num_bytes);
+ if (num_bytes > 0 && (hexbuf = (char *) MG_MALLOC(buf_size)) != NULL) {
+ mg_hexdump(buf, num_bytes, hexbuf, buf_size);
+ fprintf(fp, "%s", hexbuf);
+ MG_FREE(hexbuf);
+ }
+ if (fp != stdin && fp != stdout) 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;
+}
+
+const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
+ struct mg_str *eq_val) {
+ if (list == NULL || *list == '\0') {
+ /* End of the list */
+ list = NULL;
+ } else {
+ val->p = list;
+ if ((list = strchr(val->p, ',')) != NULL) {
+ /* Comma found. Store length and shift the list ptr */
+ val->len = list - val->p;
+ list++;
+ } else {
+ /* This value is the last one */
+ list = val->p + strlen(val->p);
+ val->len = list - val->p;
+ }
+
+ 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;
+}
+
+int mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
+ const char *or_str;
+ size_t len, i = 0, j = 0;
+ int res;
+
+ if ((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; i++, j++) {
+ if (pattern.p[i] == '?' && j != str.len) {
+ continue;
+ } else if (pattern.p[i] == '$') {
+ return j == str.len ? (int) j : -1;
+ } else if (pattern.p[i] == '*') {
+ i++;
+ if (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) {
+ 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 == -1 && len-- > 0);
+ return res == -1 ? -1 : (int) (j + res + len);
+ } else if (lowercase(&pattern.p[i]) != lowercase(&str.p[j])) {
+ return -1;
+ }
+ }
+ return j;
+}
+
+int mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
+ const struct mg_str pstr = {pattern, (size_t) pattern_len};
+ return mg_match_prefix_n(pstr, mg_mk_str(str));
+}
+
+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 char *user, const char *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, strlen(user));
+ if (pass != NULL) {
+ cs_base64_update(&ctx, ":", 1);
+ cs_base64_update(&ctx, pass, strlen(pass));
+ }
+ cs_base64_finish(&ctx);
+ mbuf_append(buf, header_suffix, strlen(header_suffix));
+}
+#ifdef MG_MODULE_LINES
+#line 1 "mongoose/src/mqtt.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if MG_ENABLE_MQTT
+
+#include
+
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/mqtt.h" */
+
+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;
+ size_t len = 0;
+ int cmd;
+ const char *p = &io->buf[1], *end;
+
+ if (io->len < 2) return -1;
+ header = io->buf[0];
+ cmd = header >> 4;
+
+ /* decode mqtt variable length */
+ do {
+ len += (*p & 127) << 7 * (p - &io->buf[1]);
+ } while ((*p++ & 128) != 0 && ((size_t)(p - io->buf) <= io->len));
+
+ end = p + len;
+ if (end > io->buf + io->len + 1) {
+ return -1;
+ }
+
+ mm->cmd = cmd;
+ mm->qos = MG_MQTT_GET_QOS(header);
+
+ switch (cmd) {
+ case MG_MQTT_CMD_CONNECT: {
+ p = scanto(p, &mm->protocol_name);
+ mm->protocol_version = *(uint8_t *) p++;
+ mm->connect_flags = *(uint8_t *) p++;
+ mm->keep_alive_timer = getu16(p);
+ p += 2;
+ if (p < end) p = scanto(p, &mm->client_id);
+ if (p < end && (mm->connect_flags & MG_MQTT_HAS_WILL))
+ p = scanto(p, &mm->will_topic);
+ if (p < end && (mm->connect_flags & MG_MQTT_HAS_WILL))
+ p = scanto(p, &mm->will_message);
+ if (p < end && (mm->connect_flags & MG_MQTT_HAS_USER_NAME))
+ p = scanto(p, &mm->user_name);
+ if (p < end && (mm->connect_flags & MG_MQTT_HAS_PASSWORD))
+ p = scanto(p, &mm->password);
+
+ LOG(LL_DEBUG,
+ ("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
+ "will_msg [%.*s] user_name [%.*s] password [%.*s]",
+ 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:
+ 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:
+ mm->message_id = getu16(p);
+ break;
+ case MG_MQTT_CMD_PUBLISH: {
+ if (MG_MQTT_GET_QOS(header) > 0) {
+ mm->message_id = getu16(p);
+ p += 2;
+ }
+ p = scanto(p, &mm->topic);
+
+ mm->payload.p = p;
+ mm->payload.len = end - p;
+ break;
+ }
+ case MG_MQTT_CMD_SUBSCRIBE:
+ 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;
+ }
+
+ return end - io->buf;
+}
+
+static void mqtt_handler(struct mg_connection *nc, int ev, void *ev_data) {
+ int len;
+ struct mbuf *io = &nc->recv_mbuf;
+ struct mg_mqtt_message mm;
+ memset(&mm, 0, sizeof(mm));
+
+ nc->handler(nc, ev, ev_data);
+
+ switch (ev) {
+ case MG_EV_RECV:
+ len = parse_mqtt(io, &mm);
+ if (len == -1) break; /* not fully buffered */
+ nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm);
+ mbuf_remove(io, len);
+ break;
+ }
+}
+
+static void mg_mqtt_proto_data_destructor(void *proto_data) {
+ MG_FREE(proto_data);
+}
+
+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;
+}
+
+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) {
+ uint8_t header = MG_MQTT_CMD_CONNECT << 4;
+ uint8_t rem_len;
+ uint16_t keep_alive;
+ uint16_t len;
+ struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
+
+ /*
+ * 9: version_header(len, magic_string, version_number), 1: flags, 2:
+ * keep-alive timer,
+ * 2: client_identifier_len, n: client_id
+ */
+ rem_len = 9 + 1 + 2 + 2 + (uint8_t) strlen(client_id);
+
+ if (opts.user_name != NULL) {
+ opts.flags |= MG_MQTT_HAS_USER_NAME;
+ rem_len += (uint8_t) strlen(opts.user_name) + 2;
+ }
+ if (opts.password != NULL) {
+ opts.flags |= MG_MQTT_HAS_PASSWORD;
+ rem_len += (uint8_t) strlen(opts.password) + 2;
+ }
+ if (opts.will_topic != NULL && opts.will_message != NULL) {
+ opts.flags |= MG_MQTT_HAS_WILL;
+ rem_len += (uint8_t) strlen(opts.will_topic) + 2;
+ rem_len += (uint8_t) strlen(opts.will_message) + 2;
+ }
+
+ mg_send(nc, &header, 1);
+ mg_send(nc, &rem_len, 1);
+ mg_send(nc, "\00\06MQIsdp\03", 9);
+ mg_send(nc, &opts.flags, 1);
+
+ if (opts.keep_alive == 0) {
+ opts.keep_alive = 60;
+ }
+
+ keep_alive = htons(opts.keep_alive);
+ mg_send(nc, &keep_alive, 2);
+
+ len = htons((uint16_t) strlen(client_id));
+ mg_send(nc, &len, 2);
+ mg_send(nc, client_id, strlen(client_id));
+
+ if (opts.flags & MG_MQTT_HAS_WILL) {
+ len = htons((uint16_t) strlen(opts.will_topic));
+ mg_send(nc, &len, 2);
+ mg_send(nc, opts.will_topic, strlen(opts.will_topic));
+
+ len = htons((uint16_t) strlen(opts.will_message));
+ mg_send(nc, &len, 2);
+ mg_send(nc, opts.will_message, strlen(opts.will_message));
+ }
+
+ if (opts.flags & MG_MQTT_HAS_USER_NAME) {
+ len = htons((uint16_t) strlen(opts.user_name));
+ mg_send(nc, &len, 2);
+ mg_send(nc, opts.user_name, strlen(opts.user_name));
+ }
+ if (opts.flags & MG_MQTT_HAS_PASSWORD) {
+ len = htons((uint16_t) strlen(opts.password));
+ mg_send(nc, &len, 2);
+ mg_send(nc, opts.password, strlen(opts.password));
+ }
+
+ if (pd != NULL) {
+ pd->keep_alive = opts.keep_alive;
+ }
+}
+
+static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd,
+ uint8_t flags, size_t len) {
+ size_t off = nc->send_mbuf.len - len;
+ uint8_t header = cmd << 4 | (uint8_t) flags;
+
+ uint8_t buf[1 + sizeof(size_t)];
+ uint8_t *vlen = &buf[1];
+
+ assert(nc->send_mbuf.len >= len);
+
+ buf[0] = header;
+
+ /* mqtt variable length encoding */
+ do {
+ *vlen = len % 0x80;
+ len /= 0x80;
+ if (len > 0) *vlen |= 0x80;
+ vlen++;
+ } while (len > 0);
+
+ mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf);
+}
+
+void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
+ uint16_t message_id, int flags, const void *data,
+ size_t len) {
+ size_t old_len = nc->send_mbuf.len;
+
+ uint16_t topic_len = htons((uint16_t) strlen(topic));
+ uint16_t message_id_net = htons(message_id);
+
+ mg_send(nc, &topic_len, 2);
+ mg_send(nc, topic, strlen(topic));
+ if (MG_MQTT_GET_QOS(flags) > 0) {
+ mg_send(nc, &message_id_net, 2);
+ }
+ mg_send(nc, data, len);
+
+ mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags,
+ nc->send_mbuf.len - old_len);
+}
+
+void mg_mqtt_subscribe(struct mg_connection *nc,
+ const struct mg_mqtt_topic_expression *topics,
+ size_t topics_len, uint16_t message_id) {
+ size_t old_len = nc->send_mbuf.len;
+
+ uint16_t message_id_n = htons(message_id);
+ size_t i;
+
+ mg_send(nc, (char *) &message_id_n, 2);
+ for (i = 0; i < topics_len; i++) {
+ uint16_t topic_len_n = htons((uint16_t) strlen(topics[i].topic));
+ mg_send(nc, &topic_len_n, 2);
+ mg_send(nc, topics[i].topic, strlen(topics[i].topic));
+ mg_send(nc, &topics[i].qos, 1);
+ }
+
+ mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1),
+ nc->send_mbuf.len - old_len);
+}
+
+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;
+
+ if ((size_t) pos >= msg->payload.len) {
+ return -1;
+ }
+
+ topic->len = buf[0] << 8 | buf[1];
+ topic->p = (char *) buf + 2;
+ *qos = buf[2 + topic->len];
+ return pos + 2 + topic->len + 1;
+}
+
+void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
+ size_t topics_len, uint16_t message_id) {
+ size_t old_len = nc->send_mbuf.len;
+
+ uint16_t message_id_n = htons(message_id);
+ size_t i;
+
+ mg_send(nc, (char *) &message_id_n, 2);
+ for (i = 0; i < topics_len; i++) {
+ uint16_t topic_len_n = htons((uint16_t) strlen(topics[i]));
+ mg_send(nc, &topic_len_n, 2);
+ mg_send(nc, topics[i], strlen(topics[i]));
+ }
+
+ mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1),
+ nc->send_mbuf.len - old_len);
+}
+
+void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
+ uint8_t unused = 0;
+ mg_send(nc, &unused, 1);
+ mg_send(nc, &return_code, 1);
+ mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
+}
+
+/*
+ * 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 message_id_net = htons(message_id);
+ mg_send(nc, &message_id_net, 2);
+ mg_mqtt_prepend_header(nc, cmd, MG_MQTT_QOS(1), 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 message_id_net = htons(message_id);
+ mg_send(nc, &message_id_net, 2);
+ for (i = 0; i < qoss_len; i++) {
+ mg_send(nc, &qoss[i], 1);
+ }
+ mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
+}
+
+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_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
+}
+
+void mg_mqtt_pong(struct mg_connection *nc) {
+ mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
+}
+
+void mg_mqtt_disconnect(struct mg_connection *nc) {
+ mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
+}
+
+#endif /* MG_ENABLE_MQTT */
+#ifdef MG_MODULE_LINES
+#line 1 "mongoose/src/mqtt_server.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/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 *) 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);
+ s->user_data = nc->user_data;
+ nc->user_data = 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->user_data;
+ uint8_t qoss[512];
+ size_t qoss_len = 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;) {
+ qoss[qoss_len++] = qos;
+ }
+
+ ss->subscriptions = (struct mg_mqtt_topic_expression *) realloc(
+ ss->subscriptions, sizeof(*ss->subscriptions) * qoss_len);
+ for (pos = 0;
+ (pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
+ ss->num_subscriptions++) {
+ te = &ss->subscriptions[ss->num_subscriptions];
+ te->topic = (char *) malloc(topic.len + 1);
+ te->qos = qos;
+ strncpy((char *) te->topic, topic.p, topic.len + 1);
+ }
+
+ mg_mqtt_suback(nc, qoss, qoss_len, msg->message_id);
+}
+
+/*
+ * Matches a topic against a topic expression
+ *
+ * See http://goo.gl/iWk21X
+ *
+ * Returns 1 if it matches; 0 otherwise.
+ */
+static int mg_mqtt_match_topic_expression(const char *exp,
+ const struct mg_str *topic) {
+ /* TODO(mkm): implement real matching */
+ size_t len = strlen(exp);
+ if (strchr(exp, '#')) {
+ len -= 2;
+ if (topic->len < len) {
+ len = topic->len;
+ }
+ }
+ return strncmp(topic->p, exp, len) == 0;
+}
+
+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_match_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->user_data;
+ } else {
+ brk = (struct mg_mqtt_broker *) nc->user_data;
+ }
+
+ switch (ev) {
+ case MG_EV_ACCEPT:
+ mg_set_protocol_mqtt(nc);
+ nc->user_data = NULL; /* Clear up the inherited pointer to broker */
+ break;
+ case MG_EV_MQTT_CONNECT:
+ mg_mqtt_broker_handle_connect(brk, nc);
+ break;
+ case MG_EV_MQTT_SUBSCRIBE:
+ mg_mqtt_broker_handle_subscribe(nc, msg);
+ break;
+ case MG_EV_MQTT_PUBLISH:
+ mg_mqtt_broker_handle_publish(brk, msg);
+ break;
+ case MG_EV_CLOSE:
+ if (nc->listener && nc->user_data != NULL) {
+ mg_mqtt_close_session((struct mg_mqtt_session *) nc->user_data);
+ }
+ 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 "mongoose/src/dns.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if MG_ENABLE_DNS
+
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/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(struct mbuf *io, const char *name, size_t len) {
+ const char *s;
+ unsigned char n;
+ size_t pos = io->len;
+
+ do {
+ if ((s = strchr(name, '.')) == NULL) {
+ s = name + len;
+ }
+
+ if (s - name > 127) {
+ return -1; /* TODO(mkm) cover */
+ }
+ n = s - name; /* chunk length */
+ mbuf_append(io, &n, 1); /* send length */
+ mbuf_append(io, name, n);
+
+ if (*s == '.') {
+ n++;
+ }
+
+ name += n;
+ len -= n;
+ } while (*s != '\0');
+ mbuf_append(io, "\0", 1); /* Mark end of host name */
+
+ return io->len - pos;
+}
+
+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;
+ 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) {
+ uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
+ if (off >= msg->pkt.len) {
+ return 0;
+ }
+ data = (unsigned char *) msg->pkt.p + off;
+ continue;
+ }
+ 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) {
+ 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);
+
+ 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);
+ }
+ 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 "mongoose/src/dns_server.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if MG_ENABLE_DNS_SERVER
+
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/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 "mongoose/src/resolv.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if MG_ENABLE_ASYNC_RESOLVER
+
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/resolv.h" */
+
+#ifndef MG_DEFAULT_NAMESERVER
+#define MG_DEFAULT_NAMESERVER "8.8.8.8"
+#endif
+
+static const char *mg_default_dns_server = "udp://" MG_DEFAULT_NAMESERVER ":53";
+
+MG_INTERNAL char mg_dns_server[256];
+
+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 ||
+ RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value,
+ &len) == ERROR_SUCCESS)) {
+ /*
+ * 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 (value[0] == '\0') {
+ continue;
+ }
+ if (comma != NULL) {
+ *comma = '\0';
+ }
+ snprintf(name, name_len, "udp://%S:53", value);
+ ret = 0;
+ RegCloseKey(hSub);
+ break;
+ }
+ }
+ RegCloseKey(hKey);
+ }
+#elif MG_ENABLE_FILESYSTEM
+ FILE *fp;
+ char line[512];
+
+ if ((fp = mg_fopen("/etc/resolv.conf", "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, "udp://%u.%u.%u.%u:53", a, b, c, d);
+ ret = 0;
+ break;
+ }
+ }
+ (void) fclose(fp);
+ }
+#else
+ snprintf(name, name_len, "%s", mg_default_dns_server);
+#endif /* _WIN32 */
+
+ return ret;
+}
+
+int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
+#if MG_ENABLE_FILESYSTEM
+ /* 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("/etc/hosts", "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) {
+ time_t now = (time_t) mg_time();
+ struct mg_resolve_async_request *req;
+ struct mg_dns_message *msg;
+ int first = 0;
+
+ DBG(("ev=%d user_data=%p", ev, nc->user_data));
+
+ req = (struct mg_resolve_async_request *) nc->user_data;
+
+ if (req == NULL) {
+ return;
+ }
+
+ switch (ev) {
+ case MG_EV_CONNECT:
+ /* don't depend on timer not being at epoch for sending out first req */
+ first = 1;
+ /* fallthrough */
+ 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 (first || 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) {
+ 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_url;
+
+ DBG(("%s %d %p", name, query, 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->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 && mg_dns_server[0] == '\0' &&
+ mg_get_ip_address_of_nameserver(mg_dns_server, sizeof(mg_dns_server)) ==
+ -1) {
+ strncpy(mg_dns_server, mg_default_dns_server, sizeof(mg_dns_server));
+ }
+
+ if (nameserver == NULL) {
+ nameserver = mg_dns_server;
+ }
+
+ dns_nc = mg_connect(mgr, nameserver, mg_resolve_async_eh);
+ if (dns_nc == NULL) {
+ free(req);
+ return -1;
+ }
+ dns_nc->user_data = req;
+ if (opts.dns_conn != NULL) {
+ *opts.dns_conn = dns_nc;
+ }
+
+ return 0;
+}
+
+#endif /* MG_ENABLE_ASYNC_RESOLVER */
+#ifdef MG_MODULE_LINES
+#line 1 "mongoose/src/coap.c"
+#endif
+/*
+ * Copyright (c) 2015 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 .
+ *
+ * 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 .
+ */
+
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/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;
+ mbuf_append(io, NULL, packet_size);
+ 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) {
+ 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);
+
+ 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_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 "mongoose/src/tun.c"
+#endif
+/*
+ * Copyright (c) 2014 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if MG_ENABLE_TUN
+
+/* Amalgamated: #include "common/cs_dbg.h" */
+/* Amalgamated: #include "mongoose/src/http.h" */
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/net.h" */
+/* Amalgamated: #include "mongoose/src/net_if_tun.h" */
+/* Amalgamated: #include "mongoose/src/tun.h" */
+/* Amalgamated: #include "mongoose/src/util.h" */
+
+static void mg_tun_reconnect(struct mg_tun_client *client, int timeout);
+
+static void mg_tun_init_client(struct mg_tun_client *client, struct mg_mgr *mgr,
+ struct mg_iface *iface, const char *dispatcher,
+ struct mg_tun_ssl_opts ssl) {
+ client->mgr = mgr;
+ client->iface = iface;
+ client->disp_url = dispatcher;
+ client->last_stream_id = 0;
+ client->ssl = ssl;
+
+ client->disp = NULL; /* will be set by mg_tun_reconnect */
+ client->listener = NULL; /* will be set by mg_do_bind */
+ client->reconnect = NULL; /* will be set by mg_tun_reconnect */
+}
+
+void mg_tun_log_frame(struct mg_tun_frame *frame) {
+ LOG(LL_DEBUG, ("Got TUN frame: type=0x%x, flags=0x%x stream_id=0x%lx, "
+ "len=%zu",
+ frame->type, frame->flags, frame->stream_id, frame->body.len));
+#if MG_ENABLE_HEXDUMP
+ {
+ char hex[512];
+ mg_hexdump(frame->body.p, frame->body.len, hex, sizeof(hex) - 1);
+ hex[sizeof(hex) - 1] = '\0';
+ LOG(LL_DEBUG, ("body:\n%s", hex));
+ }
+#else
+ LOG(LL_DEBUG, ("body: '%.*s'", (int) frame->body.len, frame->body.p));
+#endif
+}
+
+static void mg_tun_close_all(struct mg_tun_client *client) {
+ struct mg_connection *nc;
+ for (nc = client->mgr->active_connections; nc != NULL; nc = nc->next) {
+ if (nc->iface == client->iface && !(nc->flags & MG_F_LISTENING)) {
+ LOG(LL_DEBUG, ("Closing tunneled connection %p", nc));
+ nc->flags |= MG_F_CLOSE_IMMEDIATELY;
+ /* mg_close_conn(nc); */
+ }
+ }
+}
+
+static void mg_tun_client_handler(struct mg_connection *nc, int ev,
+ void *ev_data) {
+ struct mg_tun_client *client = (struct mg_tun_client *) nc->user_data;
+
+ switch (ev) {
+ case MG_EV_CONNECT: {
+ int err = *(int *) ev_data;
+
+ if (err) {
+ LOG(LL_ERROR, ("Cannot connect to the tunnel dispatcher: %d", err));
+ } else {
+ LOG(LL_INFO, ("Connected to the tunnel dispatcher"));
+ }
+ break;
+ }
+ case MG_EV_HTTP_REPLY: {
+ struct http_message *hm = (struct http_message *) ev_data;
+
+ if (hm->resp_code != 200) {
+ LOG(LL_ERROR,
+ ("Tunnel dispatcher reply non-OK status code %d", hm->resp_code));
+ }
+ break;
+ }
+ case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {
+ LOG(LL_INFO, ("Tunnel dispatcher handshake done"));
+ break;
+ }
+ case MG_EV_WEBSOCKET_FRAME: {
+ struct websocket_message *wm = (struct websocket_message *) ev_data;
+ struct mg_connection *tc;
+ struct mg_tun_frame frame;
+
+ if (mg_tun_parse_frame(wm->data, wm->size, &frame) == -1) {
+ LOG(LL_ERROR, ("Got invalid tun frame dropping", wm->size));
+ break;
+ }
+
+ mg_tun_log_frame(&frame);
+
+ tc = mg_tun_if_find_conn(client, frame.stream_id);
+ if (tc == NULL) {
+ if (frame.body.len > 0) {
+ LOG(LL_DEBUG, ("Got frame after receiving end has been closed"));
+ }
+ break;
+ }
+ if (frame.body.len > 0) {
+ mg_if_recv_tcp_cb(tc, (void *) frame.body.p, frame.body.len,
+ 0 /* own */);
+ }
+ if (frame.flags & MG_TUN_F_END_STREAM) {
+ LOG(LL_DEBUG, ("Closing tunneled connection because got end of stream "
+ "from other end"));
+ tc->flags |= MG_F_CLOSE_IMMEDIATELY;
+ mg_close_conn(tc);
+ }
+ break;
+ }
+ case MG_EV_CLOSE: {
+ LOG(LL_DEBUG, ("Closing all tunneled connections"));
+ /*
+ * The client might have been already freed when the listening socket is
+ * closed.
+ */
+ if (client != NULL) {
+ mg_tun_close_all(client);
+ client->disp = NULL;
+ LOG(LL_INFO, ("Dispatcher connection is no more, reconnecting"));
+ /* TODO(mkm): implement exp back off */
+ mg_tun_reconnect(client, MG_TUN_RECONNECT_INTERVAL);
+ }
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+static void mg_tun_do_reconnect(struct mg_tun_client *client) {
+ struct mg_connection *dc;
+ struct mg_connect_opts opts;
+ memset(&opts, 0, sizeof(opts));
+#if MG_ENABLE_SSL
+ opts.ssl_cert = client->ssl.ssl_cert;
+ opts.ssl_key = client->ssl.ssl_key;
+ opts.ssl_ca_cert = client->ssl.ssl_ca_cert;
+#endif
+ /* HTTP/Websocket listener */
+ if ((dc = mg_connect_ws_opt(client->mgr, mg_tun_client_handler, opts,
+ client->disp_url, MG_TUN_PROTO_NAME, NULL)) ==
+ NULL) {
+ LOG(LL_ERROR,
+ ("Cannot connect to WS server on addr [%s]\n", client->disp_url));
+ return;
+ }
+
+ client->disp = dc;
+ dc->user_data = client;
+}
+
+void mg_tun_reconnect_ev_handler(struct mg_connection *nc, int ev,
+ void *ev_data) {
+ struct mg_tun_client *client = (struct mg_tun_client *) nc->user_data;
+ (void) ev_data;
+
+ switch (ev) {
+ case MG_EV_TIMER:
+ if (!(client->listener->flags & MG_F_TUN_DO_NOT_RECONNECT)) {
+ mg_tun_do_reconnect(client);
+ } else {
+ /* Reconnecting is suppressed, we'll check again at the next poll */
+ mg_tun_reconnect(client, 0);
+ }
+ break;
+ }
+}
+
+static void mg_tun_reconnect(struct mg_tun_client *client, int timeout) {
+ if (client->reconnect == NULL) {
+ client->reconnect =
+ mg_add_sock(client->mgr, INVALID_SOCKET, mg_tun_reconnect_ev_handler);
+ client->reconnect->user_data = client;
+ }
+ client->reconnect->ev_timer_time = mg_time() + timeout;
+}
+
+static struct mg_tun_client *mg_tun_create_client(struct mg_mgr *mgr,
+ const char *dispatcher,
+ struct mg_tun_ssl_opts ssl) {
+ struct mg_tun_client *client = NULL;
+ struct mg_iface *iface = mg_find_iface(mgr, &mg_tun_iface_vtable, NULL);
+ if (iface == NULL) {
+ LOG(LL_ERROR, ("The tun feature requires the manager to have a tun "
+ "interface enabled"));
+ return NULL;
+ }
+
+ client = (struct mg_tun_client *) MG_MALLOC(sizeof(*client));
+ mg_tun_init_client(client, mgr, iface, dispatcher, ssl);
+ iface->data = client;
+
+ /*
+ * We need to give application a chance to set MG_F_TUN_DO_NOT_RECONNECT on a
+ * listening connection right after mg_tun_bind_opt() returned it, so we
+ * should use mg_tun_reconnect() here, instead of mg_tun_do_reconnect()
+ */
+ mg_tun_reconnect(client, 0);
+ return client;
+}
+
+void mg_tun_destroy_client(struct mg_tun_client *client) {
+ /*
+ * NOTE:
+ * `client` is NULL in case of OOM
+ * `client->disp` is NULL if connection failed
+ * `client->iface is NULL is `mg_find_iface` failed
+ */
+
+ if (client != NULL && client->disp != NULL) {
+ /* the dispatcher connection handler will in turn close all tunnels */
+ client->disp->flags |= MG_F_CLOSE_IMMEDIATELY;
+ /* this is used as a signal to other tun handlers that the party is over */
+ client->disp->user_data = NULL;
+ }
+
+ if (client != NULL && client->reconnect != NULL) {
+ client->reconnect->flags |= MG_F_CLOSE_IMMEDIATELY;
+ }
+
+ if (client != NULL && client->iface != NULL) {
+ client->iface->data = NULL;
+ }
+
+ MG_FREE(client);
+}
+
+static struct mg_connection *mg_tun_do_bind(struct mg_tun_client *client,
+ mg_event_handler_t handler,
+ struct mg_bind_opts opts) {
+ struct mg_connection *lc;
+ opts.iface = client->iface;
+ lc = mg_bind_opt(client->mgr, ":1234" /* dummy port */, handler, opts);
+ client->listener = lc;
+ return lc;
+}
+
+struct mg_connection *mg_tun_bind_opt(struct mg_mgr *mgr,
+ const char *dispatcher,
+ mg_event_handler_t handler,
+ struct mg_bind_opts opts) {
+#if MG_ENABLE_SSL
+ struct mg_tun_ssl_opts ssl = {opts.ssl_cert, opts.ssl_key, opts.ssl_ca_cert};
+#else
+ struct mg_tun_ssl_opts ssl = {0};
+#endif
+ struct mg_tun_client *client = mg_tun_create_client(mgr, dispatcher, ssl);
+ if (client == NULL) {
+ return NULL;
+ }
+#if MG_ENABLE_SSL
+ /* these options don't make sense in the local mouth of the tunnel */
+ opts.ssl_cert = NULL;
+ opts.ssl_key = NULL;
+ opts.ssl_ca_cert = NULL;
+#endif
+ return mg_tun_do_bind(client, handler, opts);
+}
+
+int mg_tun_parse_frame(void *data, size_t len, struct mg_tun_frame *frame) {
+ const size_t header_size = sizeof(uint32_t) + sizeof(uint8_t) * 2;
+ if (len < header_size) {
+ return -1;
+ }
+
+ frame->type = *(uint8_t *) (data);
+ frame->flags = *(uint8_t *) ((char *) data + 1);
+ memcpy(&frame->stream_id, (char *) data + 2, sizeof(uint32_t));
+ frame->stream_id = ntohl(frame->stream_id);
+ frame->body.p = (char *) data + header_size;
+ frame->body.len = len - header_size;
+ return 0;
+}
+
+void mg_tun_send_frame(struct mg_connection *ws, uint32_t stream_id,
+ uint8_t type, uint8_t flags, struct mg_str msg) {
+ stream_id = htonl(stream_id);
+ {
+ struct mg_str parts[] = {
+ {(char *) &type, sizeof(type)},
+ {(char *) &flags, sizeof(flags)},
+ {(char *) &stream_id, sizeof(stream_id)},
+ {msg.p, msg.len} /* vc6 doesn't like just `msg` here */};
+ mg_send_websocket_framev(ws, WEBSOCKET_OP_BINARY, parts,
+ sizeof(parts) / sizeof(parts[0]));
+ }
+}
+
+#endif /* MG_ENABLE_TUN */
+#ifdef MG_MODULE_LINES
+#line 1 "mongoose/src/sntp.c"
+#endif
+/*
+ * Copyright (c) 2016 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/* Amalgamated: #include "mongoose/src/internal.h" */
+/* Amalgamated: #include "mongoose/src/sntp.h" */
+/* Amalgamated: #include "mongoose/src/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) {
+ char 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_SNMP_NO_DELAY_CORRECTION
+ uint32_t sec;
+ sec = htonl(mg_time() + SNTP_TIME_OFFSET);
+ memcpy(&buf[40], &sec, sizeof(sec));
+#endif
+
+ mg_send(c, buf, sizeof(buf));
+}
+
+#ifndef MG_SNMP_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 orig_ts_T1, recv_ts_T2, trsm_ts_T3, delay = 0;
+ int mode;
+ struct timeval tv;
+
+ (void) orig_ts_T1;
+ (void) recv_ts_T2;
+ 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_SNMP_NO_DELAY_CORRECTION
+ 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) {
+ struct mbuf *io = &c->recv_mbuf;
+ struct mg_sntp_message msg;
+
+ c->handler(c, ev, ev_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);
+ } else {
+ c->handler(c, MG_SNTP_REPLY, (void *) &msg);
+ }
+
+ 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_event_handler_t event_handler,
+ 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);
+
+ 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) {
+ struct sntp_data *sd = (struct sntp_data *) c->user_data;
+
+ switch (ev) {
+ case MG_EV_CONNECT:
+ if (*(int *) ev_data != 0) {
+ mg_call(c, sd->hander, 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, MG_SNTP_FAILED, NULL);
+ c->flags |= MG_F_CLOSE_IMMEDIATELY;
+ }
+ break;
+ case MG_SNTP_MALFORMED_REPLY:
+ mg_call(c, sd->hander, MG_SNTP_FAILED, NULL);
+ c->flags |= MG_F_CLOSE_IMMEDIATELY;
+ break;
+ case MG_SNTP_REPLY:
+ mg_call(c, sd->hander, MG_SNTP_REPLY, ev_data);
+ c->flags |= MG_F_CLOSE_IMMEDIATELY;
+ break;
+ case MG_EV_CLOSE:
+ MG_FREE(c->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_sntp_util_ev_handler, sntp_server_name);
+ if (c == NULL) {
+ MG_FREE(sd);
+ return NULL;
+ }
+
+ sd->hander = event_handler;
+ c->user_data = sd;
+
+ return c;
+}
+
+#endif /* MG_ENABLE_SNTP */
+#ifdef MG_MODULE_LINES
+#line 1 "common/platforms/cc3200/cc3200_libc.c"
+#endif
+/*
+ * Copyright (c) 2014-2016 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if CS_PLATFORM == CS_P_CC3200
+
+#include
+#include
+
+#ifndef __TI_COMPILER_VERSION__
+#include
+#include
+#include
+#include
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#define CONSOLE_UART UARTA0_BASE
+
+#ifdef __TI_COMPILER_VERSION__
+int asprintf(char **strp, const char *fmt, ...) {
+ va_list ap;
+ int len;
+
+ *strp = malloc(BUFSIZ);
+ if (*strp == NULL) return -1;
+
+ va_start(ap, fmt);
+ len = vsnprintf(*strp, BUFSIZ, fmt, ap);
+ va_end(ap);
+
+ if (len > 0) {
+ *strp = 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__ */
+
+#ifndef __TI_COMPILER_VERSION__
+int _gettimeofday_r(struct _reent *r, struct timeval *tp, void *tzp) {
+#else
+int gettimeofday(struct timeval *tp, void *tzp) {
+#endif
+ unsigned long long r1 = 0, r2;
+ /* Achieve two consecutive reads of the same value. */
+ do {
+ r2 = r1;
+ r1 = PRCMSlowClkCtrFastGet();
+ } while (r1 != r2);
+ /* This is a 32768 Hz counter. */
+ tp->tv_sec = (r1 >> 15);
+ /* 1/32768-th of a second is 30.517578125 microseconds, approx. 31,
+ * but we round down so it doesn't overflow at 32767 */
+ tp->tv_usec = (r1 & 0x7FFF) * 30;
+ return 0;
+}
+
+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 "common/platforms/msp432/msp432_libc.c"
+#endif
+/*
+ * Copyright (c) 2014-2016 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#if CS_PLATFORM == CS_P_MSP432
+
+#include
+#include
+
+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 "common/platforms/nrf5/nrf5_libc.c"
+#endif
+/*
+ * Copyright (c) 2014-2016 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#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 "common/platforms/simplelink/sl_fs_slfs.h"
+#endif
+/*
+ * Copyright (c) 2014-2016 Cesanta Software Limited
+ * All rights reserved
+ */
+
+#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
+#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
+
+#if defined(MG_FS_SLFS)
+
+#include
+#ifndef __TI_COMPILER_VERSION__
+#include
+#include
+#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_new_file_size(const char *name, size_t size);
+
+#endif /* defined(MG_FS_SLFS) */
+
+#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
+#ifdef MG_MODULE_LINES
+#line 1 "common/platforms/simplelink/sl_fs_slfs.c"
+#endif
+/*
+ * Copyright (c) 2014-2016 Cesanta Software Limited
+ * All rights reserved
+ */
+
+/* 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
+
+#if CS_PLATFORM == CS_P_CC3200
+#include
+#endif
+#include
+#include